Skip to content
refs
History
16213 lines · 609.3 KBRaw
1/* eslint-disable */
2// Generated by Wrangler by running `wrangler types` (hash: bcb80e0e11a7e77deeda38f65edfd23b)
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 POSTHOG_ENABLED: "false";
17 POSTHOG_PROJECT_TOKEN: "phc_oZkCWi9oE6HHRws4mWbKouSaeu2N4xoxVnkARLYofmxu";
18 POSTHOG_HOST: "https://us.i.posthog.com";
19 USER_HUB: DurableObjectNamespace<import("./workers/main").UserHub>;
20 REPO_HUB: DurableObjectNamespace<import("./workers/main").RepoHub>;
21 RUN_HUB: DurableObjectNamespace<import("./workers/main").RunHub>;
22 JOB_RUNNER: DurableObjectNamespace<import("./workers/main").JobRunner>;
23 JOB_SLOTS: DurableObjectNamespace<import("./workers/main").JobSlots>;
24 RUNS: Workflow<Parameters<import("./workers/main").RunPipeline['run']>[0]['payload']>;
25}
26declare namespace Cloudflare {
27 interface GlobalProps {
28 mainModule: typeof import("./workers/main");
29 durableNamespaces: "UserHub" | "RepoHub" | "RunHub" | "JobRunner" | "JobSlots";
30 }
31 interface Env extends __BaseEnv_Env {}
32}
33interface Env extends __BaseEnv_Env {}
34type StringifyValues<EnvType extends Record<string, unknown>> = {
35 [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string;
36};
37declare namespace NodeJS {
38 interface ProcessEnv extends StringifyValues<Pick<Cloudflare.Env, "ADMIN_EMAILS" | "EMAIL_FROM" | "PUBLIC_ORIGIN" | "POSTHOG_ENABLED" | "POSTHOG_PROJECT_TOKEN" | "POSTHOG_HOST">> {}
39}
40
41// Begin runtime types
42/*! *****************************************************************************
43Copyright (c) Cloudflare. All rights reserved.
44Copyright (c) Microsoft Corporation. All rights reserved.
45
46Licensed under the Apache License, Version 2.0 (the "License"); you may not use
47this file except in compliance with the License. You may obtain a copy of the
48License at http://www.apache.org/licenses/LICENSE-2.0
49THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
50KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
51WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
52MERCHANTABLITY OR NON-INFRINGEMENT.
53See the Apache Version 2.0 License for specific language governing permissions
54and limitations under the License.
55***************************************************************************** */
56/* eslint-disable */
57// noinspection JSUnusedGlobalSymbols
58declare var onmessage: never;
59/**
60 * 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.
61 *
62 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException)
63 */
64declare class DOMException extends Error {
65 constructor(message?: string, name?: string);
66 /**
67 * The **`message`** read-only property of the DOMException interface returns a string representing a message or description associated with the given error name.
68 *
69 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message)
70 */
71 readonly message: string;
72 /**
73 * The **`name`** read-only property of the DOMException interface returns a string that contains one of the strings associated with an error name.
74 *
75 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name)
76 */
77 readonly name: string;
78 /**
79 * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or 0 if none match.
80 * @deprecated
81 *
82 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code)
83 */
84 readonly code: number;
85 static readonly INDEX_SIZE_ERR: number;
86 static readonly DOMSTRING_SIZE_ERR: number;
87 static readonly HIERARCHY_REQUEST_ERR: number;
88 static readonly WRONG_DOCUMENT_ERR: number;
89 static readonly INVALID_CHARACTER_ERR: number;
90 static readonly NO_DATA_ALLOWED_ERR: number;
91 static readonly NO_MODIFICATION_ALLOWED_ERR: number;
92 static readonly NOT_FOUND_ERR: number;
93 static readonly NOT_SUPPORTED_ERR: number;
94 static readonly INUSE_ATTRIBUTE_ERR: number;
95 static readonly INVALID_STATE_ERR: number;
96 static readonly SYNTAX_ERR: number;
97 static readonly INVALID_MODIFICATION_ERR: number;
98 static readonly NAMESPACE_ERR: number;
99 static readonly INVALID_ACCESS_ERR: number;
100 static readonly VALIDATION_ERR: number;
101 static readonly TYPE_MISMATCH_ERR: number;
102 static readonly SECURITY_ERR: number;
103 static readonly NETWORK_ERR: number;
104 static readonly ABORT_ERR: number;
105 static readonly URL_MISMATCH_ERR: number;
106 static readonly QUOTA_EXCEEDED_ERR: number;
107 static readonly TIMEOUT_ERR: number;
108 static readonly INVALID_NODE_TYPE_ERR: number;
109 static readonly DATA_CLONE_ERR: number;
110 get stack(): any;
111 set stack(value: any);
112}
113type WorkerGlobalScopeEventMap = {
114 fetch: FetchEvent;
115 scheduled: ScheduledEvent;
116 queue: QueueEvent;
117 unhandledrejection: PromiseRejectionEvent;
118 rejectionhandled: PromiseRejectionEvent;
119};
120declare abstract class WorkerGlobalScope extends EventTarget<WorkerGlobalScopeEventMap> {
121 EventTarget: typeof EventTarget;
122}
123/* The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). *
124 * The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox).
125 *
126 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console)
127 */
128interface Console {
129 "assert"(condition?: boolean, ...data: any[]): void;
130 /**
131 * The **`console.clear()`** static method clears the console if possible.
132 *
133 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static)
134 */
135 clear(): void;
136 /**
137 * The **`console.count()`** static method logs the number of times that this particular call to count() has been called.
138 *
139 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static)
140 */
141 count(label?: string): void;
142 /**
143 * The **`console.countReset()`** static method resets counter used with console.count().
144 *
145 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static)
146 */
147 countReset(label?: string): void;
148 /**
149 * 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.
150 *
151 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static)
152 */
153 debug(...data: any[]): void;
154 /**
155 * 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.
156 *
157 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static)
158 */
159 dir(item?: any, options?: any): void;
160 /**
161 * 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.
162 *
163 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static)
164 */
165 dirxml(...data: any[]): void;
166 /**
167 * 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.
168 *
169 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static)
170 */
171 error(...data: any[]): void;
172 /**
173 * 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.
174 *
175 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static)
176 */
177 group(...data: any[]): void;
178 /**
179 * 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.
180 *
181 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static)
182 */
183 groupCollapsed(...data: any[]): void;
184 /**
185 * 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.
186 *
187 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static)
188 */
189 groupEnd(): void;
190 /**
191 * 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.
192 *
193 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static)
194 */
195 info(...data: any[]): void;
196 /**
197 * The **`console.log()`** static method outputs a message to the console.
198 *
199 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
200 */
201 log(...data: any[]): void;
202 /**
203 * The **`console.table()`** static method displays tabular data as a table.
204 *
205 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static)
206 */
207 table(tabularData?: any, properties?: string[]): void;
208 /**
209 * 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.
210 *
211 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static)
212 */
213 time(label?: string): void;
214 /**
215 * The **`console.timeEnd()`** static method stops a timer that was previously started by calling console.time().
216 *
217 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static)
218 */
219 timeEnd(label?: string): void;
220 /**
221 * The **`console.timeLog()`** static method logs the current value of a timer that was previously started by calling console.time().
222 *
223 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static)
224 */
225 timeLog(label?: string, ...data: any[]): void;
226 /* 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. */
227 timeStamp(label?: string): void;
228 /**
229 * The **`console.trace()`** static method outputs a stack trace to the console.
230 *
231 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static)
232 */
233 trace(...data: any[]): void;
234 /**
235 * 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.
236 *
237 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static)
238 */
239 warn(...data: any[]): void;
240}
241declare const console: Console;
242type BufferSource = ArrayBufferView | ArrayBuffer;
243type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array;
244declare namespace WebAssembly {
245 class CompileError extends Error {
246 constructor(message?: string);
247 }
248 class RuntimeError extends Error {
249 constructor(message?: string);
250 }
251 type ValueType = "anyfunc" | "externref" | "f32" | "f64" | "i32" | "i64" | "v128";
252 interface GlobalDescriptor {
253 value: ValueType;
254 mutable?: boolean;
255 }
256 class Global {
257 constructor(descriptor: GlobalDescriptor, value?: any);
258 value: any;
259 valueOf(): any;
260 }
261 type ImportValue = ExportValue | number;
262 type ModuleImports = Record<string, ImportValue>;
263 type Imports = Record<string, ModuleImports>;
264 type ExportValue = Function | Global | Memory | Table;
265 type Exports = Record<string, ExportValue>;
266 class Instance {
267 constructor(module: Module, imports?: Imports);
268 readonly exports: Exports;
269 }
270 interface MemoryDescriptor {
271 initial: number;
272 maximum?: number;
273 shared?: boolean;
274 }
275 class Memory {
276 constructor(descriptor: MemoryDescriptor);
277 readonly buffer: ArrayBuffer;
278 grow(delta: number): number;
279 }
280 type ImportExportKind = "function" | "global" | "memory" | "table";
281 interface ModuleExportDescriptor {
282 kind: ImportExportKind;
283 name: string;
284 }
285 interface ModuleImportDescriptor {
286 kind: ImportExportKind;
287 module: string;
288 name: string;
289 }
290 abstract class Module {
291 static customSections(module: Module, sectionName: string): ArrayBuffer[];
292 static exports(module: Module): ModuleExportDescriptor[];
293 static imports(module: Module): ModuleImportDescriptor[];
294 }
295 type TableKind = "anyfunc" | "externref";
296 interface TableDescriptor {
297 element: TableKind;
298 initial: number;
299 maximum?: number;
300 }
301 class Table {
302 constructor(descriptor: TableDescriptor, value?: any);
303 readonly length: number;
304 get(index: number): any;
305 grow(delta: number, value?: any): number;
306 set(index: number, value?: any): void;
307 }
308 function instantiate(module: Module, imports?: Imports): Promise<Instance>;
309 function validate(bytes: BufferSource): boolean;
310}
311/**
312 * The **`ServiceWorkerGlobalScope`** interface of the Service Worker API represents the global execution context of a service worker.
313 * Available only in secure contexts.
314 *
315 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope)
316 */
317interface ServiceWorkerGlobalScope extends WorkerGlobalScope {
318 DOMException: typeof DOMException;
319 WorkerGlobalScope: typeof WorkerGlobalScope;
320 btoa(data: string): string;
321 atob(data: string): string;
322 setTimeout(callback: (...args: any[]) => void, msDelay?: number): number;
323 setTimeout<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;
324 clearTimeout(timeoutId: number | null): void;
325 setInterval(callback: (...args: any[]) => void, msDelay?: number): number;
326 setInterval<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;
327 clearInterval(timeoutId: number | null): void;
328 queueMicrotask(task: Function): void;
329 structuredClone<T>(value: T, options?: StructuredSerializeOptions): T;
330 reportError(error: any): void;
331 fetch(input: RequestInfo | URL, init?: RequestInit<RequestInitCfProperties>): Promise<Response>;
332 self: ServiceWorkerGlobalScope;
333 crypto: Crypto;
334 caches: CacheStorage;
335 scheduler: Scheduler;
336 performance: Performance;
337 Cloudflare: Cloudflare;
338 readonly origin: string;
339 Event: typeof Event;
340 ExtendableEvent: typeof ExtendableEvent;
341 CustomEvent: typeof CustomEvent;
342 PromiseRejectionEvent: typeof PromiseRejectionEvent;
343 FetchEvent: typeof FetchEvent;
344 TailEvent: typeof TailEvent;
345 TraceEvent: typeof TailEvent;
346 ScheduledEvent: typeof ScheduledEvent;
347 MessageEvent: typeof MessageEvent;
348 CloseEvent: typeof CloseEvent;
349 ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader;
350 ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader;
351 ReadableStream: typeof ReadableStream;
352 WritableStream: typeof WritableStream;
353 WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter;
354 TransformStream: typeof TransformStream;
355 ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy;
356 CountQueuingStrategy: typeof CountQueuingStrategy;
357 ErrorEvent: typeof ErrorEvent;
358 MessageChannel: typeof MessageChannel;
359 MessagePort: typeof MessagePort;
360 EventSource: typeof EventSource;
361 ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest;
362 ReadableStreamDefaultController: typeof ReadableStreamDefaultController;
363 ReadableByteStreamController: typeof ReadableByteStreamController;
364 WritableStreamDefaultController: typeof WritableStreamDefaultController;
365 TransformStreamDefaultController: typeof TransformStreamDefaultController;
366 CompressionStream: typeof CompressionStream;
367 DecompressionStream: typeof DecompressionStream;
368 TextEncoderStream: typeof TextEncoderStream;
369 TextDecoderStream: typeof TextDecoderStream;
370 Headers: typeof Headers;
371 Body: typeof Body;
372 Request: typeof Request;
373 Response: typeof Response;
374 WebSocket: typeof WebSocket;
375 WebSocketPair: typeof WebSocketPair;
376 WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair;
377 AbortController: typeof AbortController;
378 AbortSignal: typeof AbortSignal;
379 TextDecoder: typeof TextDecoder;
380 TextEncoder: typeof TextEncoder;
381 navigator: Navigator;
382 Navigator: typeof Navigator;
383 URL: typeof URL;
384 URLSearchParams: typeof URLSearchParams;
385 URLPattern: typeof URLPattern;
386 Blob: typeof Blob;
387 File: typeof File;
388 FormData: typeof FormData;
389 Crypto: typeof Crypto;
390 SubtleCrypto: typeof SubtleCrypto;
391 CryptoKey: typeof CryptoKey;
392 CacheStorage: typeof CacheStorage;
393 Cache: typeof Cache;
394 FixedLengthStream: typeof FixedLengthStream;
395 IdentityTransformStream: typeof IdentityTransformStream;
396 HTMLRewriter: typeof HTMLRewriter;
397}
398declare function addEventListener<Type extends keyof WorkerGlobalScopeEventMap>(type: Type, handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, options?: EventTargetAddEventListenerOptions | boolean): void;
399declare function removeEventListener<Type extends keyof WorkerGlobalScopeEventMap>(type: Type, handler: EventListenerOrEventListenerObject<WorkerGlobalScopeEventMap[Type]>, options?: EventTargetEventListenerOptions | boolean): void;
400/**
401 * 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().
402 *
403 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent)
404 */
405declare function dispatchEvent(event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap]): boolean;
406/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */
407declare function btoa(data: string): string;
408/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */
409declare function atob(data: string): string;
410/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */
411declare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number;
412/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */
413declare function setTimeout<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;
414/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout) */
415declare function clearTimeout(timeoutId: number | null): void;
416/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */
417declare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number;
418/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */
419declare function setInterval<Args extends any[]>(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number;
420/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval) */
421declare function clearInterval(timeoutId: number | null): void;
422/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */
423declare function queueMicrotask(task: Function): void;
424/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */
425declare function structuredClone<T>(value: T, options?: StructuredSerializeOptions): T;
426/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */
427declare function reportError(error: any): void;
428/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */
429declare function fetch(input: RequestInfo | URL, init?: RequestInit<RequestInitCfProperties>): Promise<Response>;
430declare const self: ServiceWorkerGlobalScope;
431/**
432* The Web Crypto API provides a set of low-level functions for common cryptographic tasks.
433* The Workers runtime implements the full surface of this API, but with some differences in
434* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms)
435* compared to those implemented in most browsers.
436*
437* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/)
438*/
439declare const crypto: Crypto;
440/**
441* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.
442*
443* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)
444*/
445declare const caches: CacheStorage;
446/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/scheduler) */
447declare const scheduler: Scheduler;
448/**
449* The Workers runtime supports a subset of the Performance API, used to measure timing and performance,
450* as well as timing of subrequests and other operations.
451*
452* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/)
453*/
454declare const performance: Performance;
455declare const Cloudflare: Cloudflare;
456declare const origin: string;
457declare const navigator: Navigator;
458interface TestController {
459}
460interface ExecutionContext<Props = unknown> {
461 waitUntil(promise: Promise<any>): void;
462 passThroughOnException(): void;
463 readonly exports: Cloudflare.Exports;
464 readonly props: Props;
465 cache?: CacheContext;
466 readonly access?: CloudflareAccessContext;
467 tracing: Tracing;
468 abort(reason?: any): void;
469}
470type ExportedHandlerFetchHandler<Env = unknown, CfHostMetadata = unknown, Props = unknown> = (request: Request<CfHostMetadata, IncomingRequestCfProperties<CfHostMetadata>>, env: Env, ctx: ExecutionContext<Props>) => Response | Promise<Response>;
471type ExportedHandlerConnectHandler<Env = unknown, Props = unknown> = (socket: Socket, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
472type ExportedHandlerTailHandler<Env = unknown, Props = unknown> = (events: TraceItem[], env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
473type ExportedHandlerTraceHandler<Env = unknown, Props = unknown> = (traces: TraceItem[], env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
474type ExportedHandlerTailStreamHandler<Env = unknown, Props = unknown> = (event: TailStream.TailEvent<TailStream.Onset>, env: Env, ctx: ExecutionContext<Props>) => TailStream.TailEventHandlerType | undefined | Promise<TailStream.TailEventHandlerType | undefined>;
475type ExportedHandlerScheduledHandler<Env = unknown, Props = unknown> = (controller: ScheduledController, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
476type ExportedHandlerQueueHandler<Env = unknown, Message = unknown, Props = unknown> = (batch: MessageBatch<Message>, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
477type ExportedHandlerTestHandler<Env = unknown, Props = unknown> = (controller: TestController, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
478interface ExportedHandler<Env = unknown, QueueHandlerMessage = unknown, CfHostMetadata = unknown, Props = unknown> {
479 fetch?: ExportedHandlerFetchHandler<Env, CfHostMetadata, Props>;
480 connect?: ExportedHandlerConnectHandler<Env, Props>;
481 tail?: ExportedHandlerTailHandler<Env, Props>;
482 trace?: ExportedHandlerTraceHandler<Env, Props>;
483 tailStream?: ExportedHandlerTailStreamHandler<Env, Props>;
484 scheduled?: ExportedHandlerScheduledHandler<Env, Props>;
485 test?: ExportedHandlerTestHandler<Env, Props>;
486 email?: EmailExportedHandler<Env, Props>;
487 queue?: ExportedHandlerQueueHandler<Env, QueueHandlerMessage, Props>;
488}
489interface StructuredSerializeOptions {
490 transfer?: any[];
491}
492declare abstract class Navigator {
493 sendBeacon(url: string, body?: BodyInit): boolean;
494 readonly userAgent: string;
495 readonly hardwareConcurrency: number;
496 readonly platform: string;
497 readonly language: string;
498 readonly languages: string[];
499}
500interface AlarmInvocationInfo {
501 readonly isRetry: boolean;
502 readonly retryCount: number;
503 readonly scheduledTime: number;
504}
505interface Cloudflare {
506 readonly compatibilityFlags: Record<string, boolean>;
507}
508interface CachePurgeError {
509 code: number;
510 message: string;
511}
512interface CachePurgeResult {
513 success: boolean;
514 errors: CachePurgeError[];
515}
516interface CachePurgeOptions {
517 tags?: string[];
518 pathPrefixes?: string[];
519 purgeEverything?: boolean;
520}
521interface CacheContext {
522 purge(options: CachePurgeOptions): Promise<CachePurgeResult>;
523}
524interface CloudflareAccessContext {
525 readonly aud: string;
526 getIdentity(): Promise<CloudflareAccessIdentity | undefined>;
527}
528declare abstract class ColoLocalActorNamespace {
529 get(actorId: string): Fetcher;
530}
531interface DurableObject {
532 fetch(request: Request): Response | Promise<Response>;
533 connect?(socket: Socket): void | Promise<void>;
534 alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise<void>;
535 webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise<void>;
536 webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise<void>;
537 webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>;
538}
539type DurableObjectStub<T extends Rpc.DurableObjectBranded | undefined = undefined> = Fetcher<T, "alarm" | "connect" | "webSocketMessage" | "webSocketClose" | "webSocketError"> & {
540 readonly id: DurableObjectId;
541 readonly name?: string;
542};
543interface DurableObjectId {
544 toString(): string;
545 equals(other: DurableObjectId): boolean;
546 readonly name?: string;
547 readonly jurisdiction?: string;
548}
549declare abstract class DurableObjectNamespace<T extends Rpc.DurableObjectBranded | undefined = undefined> {
550 newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId;
551 idFromName(name: string): DurableObjectId;
552 idFromString(id: string): DurableObjectId;
553 get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub<T>;
554 getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub<T>;
555 jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace<T>;
556}
557type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high" | "us";
558interface DurableObjectNamespaceNewUniqueIdOptions {
559 jurisdiction?: DurableObjectJurisdiction;
560}
561type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "apac-ne" | "apac-se" | "oc" | "afr" | "me";
562type DurableObjectRoutingMode = "primary-only";
563interface DurableObjectNamespaceGetDurableObjectOptions {
564 locationHint?: DurableObjectLocationHint;
565 routingMode?: DurableObjectRoutingMode;
566}
567interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> {
568}
569interface DurableObjectState<Props = unknown> {
570 waitUntil(promise: Promise<any>): void;
571 readonly exports: Cloudflare.Exports;
572 readonly props: Props;
573 readonly id: DurableObjectId;
574 readonly storage: DurableObjectStorage;
575 container?: Container;
576 facets: DurableObjectFacets;
577 blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>;
578 acceptWebSocket(ws: WebSocket, tags?: string[]): void;
579 getWebSockets(tag?: string): WebSocket[];
580 setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void;
581 getWebSocketAutoResponse(): WebSocketRequestResponsePair | null;
582 getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null;
583 setHibernatableWebSocketEventTimeout(timeoutMs?: number): void;
584 getHibernatableWebSocketEventTimeout(): number | null;
585 getTags(ws: WebSocket): string[];
586 abort(reason?: string, options?: DurableObjectAbortOptions): void;
587}
588interface DurableObjectTransaction {
589 get<T = unknown>(key: string, options?: DurableObjectGetOptions): Promise<T | undefined>;
590 get<T = unknown>(keys: string[], options?: DurableObjectGetOptions): Promise<Map<string, T>>;
591 list<T = unknown>(options?: DurableObjectListOptions): Promise<Map<string, T>>;
592 put<T>(key: string, value: T, options?: DurableObjectPutOptions): Promise<void>;
593 put<T>(entries: Record<string, T>, options?: DurableObjectPutOptions): Promise<void>;
594 delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>;
595 delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>;
596 rollback(): void;
597 getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>;
598 setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise<void>;
599 deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>;
600}
601interface DurableObjectStorage {
602 get<T = unknown>(key: string, options?: DurableObjectGetOptions): Promise<T | undefined>;
603 get<T = unknown>(keys: string[], options?: DurableObjectGetOptions): Promise<Map<string, T>>;
604 list<T = unknown>(options?: DurableObjectListOptions): Promise<Map<string, T>>;
605 put<T>(key: string, value: T, options?: DurableObjectPutOptions): Promise<void>;
606 put<T>(entries: Record<string, T>, options?: DurableObjectPutOptions): Promise<void>;
607 delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>;
608 delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>;
609 deleteAll(options?: DurableObjectPutOptions): Promise<void>;
610 transaction<T>(closure: (txn: DurableObjectTransaction) => Promise<T>): Promise<T>;
611 getAlarm(options?: DurableObjectGetAlarmOptions): Promise<number | null>;
612 setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise<void>;
613 deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise<void>;
614 sync(): Promise<void>;
615 sql: SqlStorage;
616 kv: SyncKvStorage;
617 transactionSync<T>(closure: () => T): T;
618 getCurrentBookmark(): Promise<string>;
619 getBookmarkForTime(timestamp: number | Date): Promise<string>;
620 onNextSessionRestoreBookmark(bookmark: string): Promise<string>;
621}
622interface DurableObjectAbortOptions {
623 retryAlarm?: boolean;
624}
625interface DurableObjectListOptions {
626 start?: string;
627 startAfter?: string;
628 end?: string;
629 prefix?: string;
630 reverse?: boolean;
631 limit?: number;
632 allowConcurrency?: boolean;
633 noCache?: boolean;
634}
635interface DurableObjectGetOptions {
636 allowConcurrency?: boolean;
637 noCache?: boolean;
638}
639interface DurableObjectGetAlarmOptions {
640 allowConcurrency?: boolean;
641}
642interface DurableObjectPutOptions {
643 allowConcurrency?: boolean;
644 allowUnconfirmed?: boolean;
645 noCache?: boolean;
646}
647interface DurableObjectSetAlarmOptions {
648 allowConcurrency?: boolean;
649 allowUnconfirmed?: boolean;
650}
651declare class WebSocketRequestResponsePair {
652 constructor(request: string, response: string);
653 get request(): string;
654 get response(): string;
655}
656interface DurableObjectFacets {
657 get<T extends Rpc.DurableObjectBranded | undefined = undefined>(name: string, getStartupOptions: () => FacetStartupOptions<T> | Promise<FacetStartupOptions<T>>): Fetcher<T>;
658 abort(name: string, reason: any): void;
659 delete(name: string): void;
660 clone(src: string, dst: string): void;
661}
662interface FacetStartupOptions<T extends Rpc.DurableObjectBranded | undefined = undefined> {
663 id?: DurableObjectId | string;
664 class: DurableObjectClass<T>;
665}
666interface AnalyticsEngineDataset {
667 writeDataPoint(event?: AnalyticsEngineDataPoint): void;
668}
669interface AnalyticsEngineDataPoint {
670 indexes?: ((ArrayBuffer | string) | null)[];
671 doubles?: number[];
672 blobs?: ((ArrayBuffer | string) | null)[];
673}
674/**
675 * The **`Event`** interface represents an event which takes place on an EventTarget.
676 *
677 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event)
678 */
679declare class Event {
680 constructor(type: string, init?: EventInit);
681 /**
682 * 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.
683 *
684 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type)
685 */
686 get type(): string;
687 /**
688 * The **`eventPhase`** read-only property of the Event interface indicates which phase of the event flow is currently being evaluated.
689 *
690 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase)
691 */
692 get eventPhase(): number;
693 /**
694 * 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.
695 *
696 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed)
697 */
698 get composed(): boolean;
699 /**
700 * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not.
701 *
702 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles)
703 */
704 get bubbles(): boolean;
705 /**
706 * 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.
707 *
708 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable)
709 */
710 get cancelable(): boolean;
711 /**
712 * 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.
713 *
714 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented)
715 */
716 get defaultPrevented(): boolean;
717 /**
718 * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not.
719 * @deprecated
720 *
721 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue)
722 */
723 get returnValue(): boolean;
724 /**
725 * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached.
726 *
727 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget)
728 */
729 get currentTarget(): EventTarget | undefined;
730 /**
731 * 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.
732 *
733 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target)
734 */
735 get target(): EventTarget | undefined;
736 /**
737 * The deprecated **`Event.srcElement`** is an alias for the Event.target property. Use Event.target instead.
738 * @deprecated
739 *
740 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement)
741 */
742 get srcElement(): EventTarget | undefined;
743 /**
744 * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created.
745 *
746 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp)
747 */
748 get timeStamp(): number;
749 /**
750 * 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.
751 *
752 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted)
753 */
754 get isTrusted(): boolean;
755 /**
756 * 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.
757 * @deprecated
758 *
759 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble)
760 */
761 get cancelBubble(): boolean;
762 /**
763 * 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.
764 * @deprecated
765 *
766 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble)
767 */
768 set cancelBubble(value: boolean);
769 /**
770 * The **`stopImmediatePropagation()`** method of the Event interface prevents other listeners of the same event from being called.
771 *
772 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation)
773 */
774 stopImmediatePropagation(): void;
775 /**
776 * 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.
777 *
778 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault)
779 */
780 preventDefault(): void;
781 /**
782 * 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().
783 *
784 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation)
785 */
786 stopPropagation(): void;
787 /**
788 * 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.
789 *
790 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath)
791 */
792 composedPath(): EventTarget[];
793 static readonly NONE: number;
794 static readonly CAPTURING_PHASE: number;
795 static readonly AT_TARGET: number;
796 static readonly BUBBLING_PHASE: number;
797}
798interface EventInit {
799 bubbles?: boolean;
800 cancelable?: boolean;
801 composed?: boolean;
802}
803type EventListener<EventType extends Event = Event> = (event: EventType) => void;
804interface EventListenerObject<EventType extends Event = Event> {
805 handleEvent(event: EventType): void;
806}
807type EventListenerOrEventListenerObject<EventType extends Event = Event> = EventListener<EventType> | EventListenerObject<EventType>;
808/**
809 * 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.
810 *
811 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget)
812 */
813declare class EventTarget<EventMap extends Record<string, Event> = Record<string, Event>> {
814 constructor();
815 /**
816 * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target.
817 *
818 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener)
819 */
820 addEventListener<Type extends keyof EventMap>(type: Type, handler: EventListenerOrEventListenerObject<EventMap[Type]>, options?: EventTargetAddEventListenerOptions | boolean): void;
821 /**
822 * 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.
823 *
824 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener)
825 */
826 removeEventListener<Type extends keyof EventMap>(type: Type, handler: EventListenerOrEventListenerObject<EventMap[Type]>, options?: EventTargetEventListenerOptions | boolean): void;
827 /**
828 * 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().
829 *
830 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent)
831 */
832 dispatchEvent(event: EventMap[keyof EventMap]): boolean;
833}
834interface EventTargetEventListenerOptions {
835 capture?: boolean;
836}
837interface EventTargetAddEventListenerOptions {
838 capture?: boolean;
839 passive?: boolean;
840 once?: boolean;
841 signal?: AbortSignal;
842}
843interface EventTargetHandlerObject {
844 handleEvent: (event: Event) => any | undefined;
845}
846/**
847 * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired.
848 *
849 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController)
850 */
851declare class AbortController {
852 constructor();
853 /**
854 * 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.
855 *
856 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal)
857 */
858 get signal(): AbortSignal;
859 /**
860 * 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.
861 *
862 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort)
863 */
864 abort(reason?: any): void;
865}
866/**
867 * 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.
868 *
869 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal)
870 */
871declare abstract class AbortSignal extends EventTarget {
872 /**
873 * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an abort event).
874 *
875 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static)
876 */
877 static abort(reason?: any): AbortSignal;
878 /**
879 * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time.
880 *
881 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static)
882 */
883 static timeout(delay: number): AbortSignal;
884 /**
885 * 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.
886 *
887 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static)
888 */
889 static any(signals: AbortSignal[]): AbortSignal;
890 /**
891 * 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).
892 *
893 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted)
894 */
895 get aborted(): boolean;
896 /**
897 * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason.
898 *
899 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason)
900 */
901 get reason(): any;
902 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */
903 get onabort(): any | null;
904 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */
905 set onabort(value: any | null);
906 /**
907 * The **`throwIfAborted()`** method throws the signal's abort reason if the signal has been aborted; otherwise it does nothing.
908 *
909 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted)
910 */
911 throwIfAborted(): void;
912}
913/**
914 * The **`Scheduler`** interface of the Prioritized Task Scheduling API provides methods for scheduling prioritized tasks.
915 *
916 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Scheduler)
917 */
918interface Scheduler {
919 wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise<void>;
920}
921interface SchedulerWaitOptions {
922 signal?: AbortSignal;
923}
924/**
925 * 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.
926 *
927 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent)
928 */
929declare abstract class ExtendableEvent extends Event {
930 /**
931 * 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.
932 *
933 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil)
934 */
935 waitUntil(promise: Promise<any>): void;
936}
937/**
938 * The **`CustomEvent`** interface can be used to attach custom data to an event generated by an application.
939 *
940 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent)
941 */
942declare class CustomEvent<T = any> extends Event {
943 constructor(type: string, init?: CustomEventCustomEventInit);
944 /**
945 * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event.
946 *
947 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail)
948 */
949 get detail(): T;
950}
951interface CustomEventCustomEventInit {
952 bubbles?: boolean;
953 cancelable?: boolean;
954 composed?: boolean;
955 detail?: any;
956}
957/**
958 * 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.
959 *
960 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob)
961 */
962declare class Blob {
963 constructor(bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions);
964 /**
965 * The **`size`** read-only property of the Blob interface returns the size of the Blob or File in bytes.
966 *
967 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size)
968 */
969 get size(): number;
970 /**
971 * The **`type`** read-only property of the Blob interface returns the MIME type of the file.
972 *
973 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type)
974 */
975 get type(): string;
976 /**
977 * 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.
978 *
979 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice)
980 */
981 slice(start?: number, end?: number, type?: string): Blob;
982 /**
983 * 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.
984 *
985 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer)
986 */
987 arrayBuffer(): Promise<ArrayBuffer>;
988 /**
989 * 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.
990 *
991 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes)
992 */
993 bytes(): Promise<Uint8Array>;
994 /**
995 * 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.
996 *
997 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text)
998 */
999 text(): Promise<string>;
1000 /**
1001 * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the Blob.
1002 *
1003 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream)
1004 */
1005 stream(): ReadableStream;
1006}
1007interface BlobOptions {
1008 type?: string;
1009}
1010/**
1011 * The **`File`** interface provides information about files and allows JavaScript in a web page to access their content.
1012 *
1013 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File)
1014 */
1015declare class File extends Blob {
1016 constructor(bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions);
1017 /**
1018 * 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.
1019 *
1020 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name)
1021 */
1022 get name(): string;
1023 /**
1024 * 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.
1025 *
1026 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified)
1027 */
1028 get lastModified(): number;
1029}
1030interface FileOptions {
1031 type?: string;
1032 lastModified?: number;
1033}
1034/**
1035* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.
1036*
1037* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)
1038*/
1039declare abstract class CacheStorage {
1040 /**
1041 * The **`open()`** method of the CacheStorage interface returns a Promise that resolves to the Cache object matching the cacheName.
1042 *
1043 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open)
1044 */
1045 open(cacheName: string): Promise<Cache>;
1046 readonly default: Cache;
1047}
1048/**
1049* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache.
1050*
1051* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/)
1052*/
1053declare abstract class Cache {
1054 /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */
1055 delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<boolean>;
1056 /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */
1057 match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise<Response | undefined>;
1058 /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */
1059 put(request: RequestInfo | URL, response: Response): Promise<void>;
1060}
1061interface CacheQueryOptions {
1062 ignoreMethod?: boolean;
1063}
1064/**
1065* The Web Crypto API provides a set of low-level functions for common cryptographic tasks.
1066* The Workers runtime implements the full surface of this API, but with some differences in
1067* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms)
1068* compared to those implemented in most browsers.
1069*
1070* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/)
1071*/
1072declare abstract class Crypto {
1073 /**
1074 * The **`Crypto.subtle`** read-only property returns a SubtleCrypto which can then be used to perform low-level cryptographic operations.
1075 * Available only in secure contexts.
1076 *
1077 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle)
1078 */
1079 get subtle(): SubtleCrypto;
1080 /**
1081 * 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).
1082 *
1083 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues)
1084 */
1085 getRandomValues<T extends Int8Array | Uint8Array | Int16Array | Uint16Array | Int32Array | Uint32Array | BigInt64Array | BigUint64Array>(buffer: T): T;
1086 /**
1087 * The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator.
1088 * Available only in secure contexts.
1089 *
1090 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID)
1091 */
1092 randomUUID(): string;
1093 DigestStream: typeof DigestStream;
1094}
1095/**
1096 * The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions.
1097 * Available only in secure contexts.
1098 *
1099 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto)
1100 */
1101declare abstract class SubtleCrypto {
1102 /**
1103 * The **`encrypt()`** method of the SubtleCrypto interface encrypts data.
1104 *
1105 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt)
1106 */
1107 encrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;
1108 /**
1109 * 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").
1110 *
1111 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt)
1112 */
1113 decrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;
1114 /**
1115 * The **`sign()`** method of the SubtleCrypto interface generates a digital signature.
1116 *
1117 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign)
1118 */
1119 sign(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, data: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;
1120 /**
1121 * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature.
1122 *
1123 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify)
1124 */
1125 verify(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView): Promise<boolean>;
1126 /**
1127 * 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.
1128 *
1129 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest)
1130 */
1131 digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise<ArrayBuffer>;
1132 /**
1133 * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms).
1134 *
1135 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey)
1136 */
1137 generateKey(algorithm: string | SubtleCryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey | CryptoKeyPair>;
1138 /**
1139 * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key.
1140 *
1141 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey)
1142 */
1143 deriveKey(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;
1144 /**
1145 * The **`deriveBits()`** method of the SubtleCrypto interface can be used to derive an array of bits from a base key.
1146 *
1147 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits)
1148 */
1149 deriveBits(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null): Promise<ArrayBuffer>;
1150 /**
1151 * 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.
1152 *
1153 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey)
1154 */
1155 importKey(format: string, keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, algorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;
1156 /**
1157 * 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.
1158 *
1159 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey)
1160 */
1161 exportKey(format: string, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey>;
1162 /**
1163 * 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.
1164 *
1165 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey)
1166 */
1167 wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise<ArrayBuffer>;
1168 /**
1169 * 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.
1170 *
1171 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey)
1172 */
1173 unwrapKey(format: string, wrappedKey: ArrayBuffer | ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise<CryptoKey>;
1174 timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean;
1175}
1176/**
1177 * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods generateKey(), deriveKey(), importKey(), or unwrapKey().
1178 * Available only in secure contexts.
1179 *
1180 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey)
1181 */
1182declare abstract class CryptoKey {
1183 /**
1184 * 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:
1185 *
1186 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type)
1187 */
1188 readonly type: string;
1189 /**
1190 * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using SubtleCrypto.exportKey() or SubtleCrypto.wrapKey().
1191 *
1192 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable)
1193 */
1194 readonly extractable: boolean;
1195 /**
1196 * 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.
1197 *
1198 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm)
1199 */
1200 readonly algorithm: CryptoKeyKeyAlgorithm | CryptoKeyAesKeyAlgorithm | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm;
1201 /**
1202 * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key.
1203 *
1204 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages)
1205 */
1206 readonly usages: string[];
1207}
1208interface CryptoKeyPair {
1209 publicKey: CryptoKey;
1210 privateKey: CryptoKey;
1211}
1212interface JsonWebKey {
1213 kty: string;
1214 use?: string;
1215 key_ops?: string[];
1216 alg?: string;
1217 ext?: boolean;
1218 crv?: string;
1219 x?: string;
1220 y?: string;
1221 d?: string;
1222 n?: string;
1223 e?: string;
1224 p?: string;
1225 q?: string;
1226 dp?: string;
1227 dq?: string;
1228 qi?: string;
1229 oth?: RsaOtherPrimesInfo[];
1230 k?: string;
1231 pub?: string;
1232 priv?: string;
1233}
1234interface RsaOtherPrimesInfo {
1235 r?: string;
1236 d?: string;
1237 t?: string;
1238}
1239interface SubtleCryptoDeriveKeyAlgorithm {
1240 name: string;
1241 salt?: (ArrayBuffer | ArrayBufferView);
1242 iterations?: number;
1243 hash?: (string | SubtleCryptoHashAlgorithm);
1244 $public?: CryptoKey;
1245 info?: (ArrayBuffer | ArrayBufferView);
1246}
1247interface SubtleCryptoEncryptAlgorithm {
1248 name: string;
1249 iv?: (ArrayBuffer | ArrayBufferView);
1250 additionalData?: (ArrayBuffer | ArrayBufferView);
1251 tagLength?: number;
1252 counter?: (ArrayBuffer | ArrayBufferView);
1253 length?: number;
1254 label?: (ArrayBuffer | ArrayBufferView);
1255}
1256interface SubtleCryptoGenerateKeyAlgorithm {
1257 name: string;
1258 hash?: (string | SubtleCryptoHashAlgorithm);
1259 modulusLength?: number;
1260 publicExponent?: (ArrayBuffer | ArrayBufferView);
1261 length?: number;
1262 namedCurve?: string;
1263}
1264interface SubtleCryptoHashAlgorithm {
1265 name: string;
1266}
1267interface SubtleCryptoImportKeyAlgorithm {
1268 name: string;
1269 hash?: (string | SubtleCryptoHashAlgorithm);
1270 length?: number;
1271 namedCurve?: string;
1272 compressed?: boolean;
1273}
1274interface SubtleCryptoSignAlgorithm {
1275 name: string;
1276 hash?: (string | SubtleCryptoHashAlgorithm);
1277 dataLength?: number;
1278 saltLength?: number;
1279 context?: ArrayBuffer | ArrayBufferView;
1280}
1281interface CryptoKeyKeyAlgorithm {
1282 name: string;
1283}
1284interface CryptoKeyAesKeyAlgorithm {
1285 name: string;
1286 length: number;
1287}
1288interface CryptoKeyHmacKeyAlgorithm {
1289 name: string;
1290 hash: CryptoKeyKeyAlgorithm;
1291 length: number;
1292}
1293interface CryptoKeyRsaKeyAlgorithm {
1294 name: string;
1295 modulusLength: number;
1296 publicExponent: ArrayBuffer | ArrayBufferView;
1297 hash?: CryptoKeyKeyAlgorithm;
1298}
1299interface CryptoKeyEllipticKeyAlgorithm {
1300 name: string;
1301 namedCurve: string;
1302}
1303interface CryptoKeyArbitraryKeyAlgorithm {
1304 name: string;
1305 hash?: CryptoKeyKeyAlgorithm;
1306 namedCurve?: string;
1307 length?: number;
1308}
1309declare class DigestStream extends WritableStream<ArrayBuffer | ArrayBufferView> {
1310 constructor(algorithm: string | SubtleCryptoHashAlgorithm, options?: DigestStreamOptions);
1311 readonly digest: Promise<ArrayBuffer>;
1312 get bytesWritten(): number | bigint;
1313}
1314interface DigestStreamOptions {
1315 toWellFormed?: boolean;
1316}
1317/**
1318 * 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.
1319 *
1320 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder)
1321 */
1322declare class TextDecoder {
1323 constructor(label?: string, options?: TextDecoderConstructorOptions);
1324 /**
1325 * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter.
1326 *
1327 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode)
1328 */
1329 decode(input?: (ArrayBuffer | ArrayBufferView), options?: TextDecoderDecodeOptions): string;
1330 get encoding(): string;
1331 get fatal(): boolean;
1332 get ignoreBOM(): boolean;
1333}
1334/**
1335 * The **`TextEncoder`** interface enables you to encode a JavaScript string using UTF-8.
1336 *
1337 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder)
1338 */
1339declare class TextEncoder {
1340 constructor();
1341 /**
1342 * The **`TextEncoder.encode()`** method takes a string as input, and returns a Uint8Array containing the string encoded using UTF-8.
1343 *
1344 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode)
1345 */
1346 encode(input?: string): Uint8Array;
1347 /**
1348 * 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.
1349 *
1350 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto)
1351 */
1352 encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult;
1353 get encoding(): string;
1354}
1355interface TextDecoderConstructorOptions {
1356 fatal: boolean;
1357 ignoreBOM: boolean;
1358}
1359interface TextDecoderDecodeOptions {
1360 stream: boolean;
1361}
1362interface TextEncoderEncodeIntoResult {
1363 read: number;
1364 written: number;
1365}
1366/**
1367 * The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files.
1368 *
1369 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent)
1370 */
1371declare class ErrorEvent extends Event {
1372 constructor(type: string, init?: ErrorEventErrorEventInit);
1373 /**
1374 * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred.
1375 *
1376 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename)
1377 */
1378 get filename(): string;
1379 /**
1380 * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem.
1381 *
1382 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message)
1383 */
1384 get message(): string;
1385 /**
1386 * 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.
1387 *
1388 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno)
1389 */
1390 get lineno(): number;
1391 /**
1392 * 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.
1393 *
1394 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno)
1395 */
1396 get colno(): number;
1397 /**
1398 * 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.
1399 *
1400 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error)
1401 */
1402 get error(): any;
1403}
1404interface ErrorEventErrorEventInit {
1405 bubbles?: boolean;
1406 cancelable?: boolean;
1407 composed?: boolean;
1408 message?: string;
1409 filename?: string;
1410 lineno?: number;
1411 colno?: number;
1412 error?: any;
1413}
1414/**
1415 * The **`MessageEvent`** interface represents a message received by a target object.
1416 *
1417 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent)
1418 */
1419declare class MessageEvent extends Event {
1420 constructor(type: string, initializer?: MessageEventInit);
1421 /**
1422 * The **`data`** read-only property of the MessageEvent interface represents the data sent by the message emitter.
1423 *
1424 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data)
1425 */
1426 readonly data: any;
1427 /**
1428 * The **`origin`** read-only property of the MessageEvent interface is a string representing the origin of the message emitter.
1429 *
1430 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin)
1431 */
1432 readonly origin: string | null;
1433 /**
1434 * The **`lastEventId`** read-only property of the MessageEvent interface is a string representing a unique ID for the event.
1435 *
1436 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId)
1437 */
1438 readonly lastEventId: string;
1439 /**
1440 * 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.
1441 *
1442 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source)
1443 */
1444 readonly source: MessagePort | null;
1445 /**
1446 * 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.
1447 *
1448 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports)
1449 */
1450 readonly ports: MessagePort[];
1451}
1452interface MessageEventInit {
1453 bubbles?: boolean;
1454 cancelable?: boolean;
1455 composed?: boolean;
1456 data?: any;
1457 origin?: string;
1458 lastEventId?: string;
1459 source?: (MessagePort | null);
1460 ports?: MessagePort[];
1461}
1462/**
1463 * 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.
1464 *
1465 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent)
1466 */
1467declare abstract class PromiseRejectionEvent extends Event {
1468 /**
1469 * 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.
1470 *
1471 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise)
1472 */
1473 readonly promise: Promise<any>;
1474 /**
1475 * 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.
1476 *
1477 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason)
1478 */
1479 readonly reason: any;
1480}
1481/**
1482 * 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".
1483 *
1484 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData)
1485 */
1486declare class FormData {
1487 constructor();
1488 /**
1489 * 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.
1490 *
1491 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append)
1492 */
1493 append(name: string, value: string | Blob): void;
1494 /**
1495 * 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.
1496 *
1497 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append)
1498 */
1499 append(name: string, value: string): void;
1500 /**
1501 * 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.
1502 *
1503 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append)
1504 */
1505 append(name: string, value: Blob, filename?: string): void;
1506 /**
1507 * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a FormData object.
1508 *
1509 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete)
1510 */
1511 delete(name: string): void;
1512 /**
1513 * 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.
1514 *
1515 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get)
1516 */
1517 get(name: string): (File | string) | null;
1518 /**
1519 * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a FormData object.
1520 *
1521 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll)
1522 */
1523 getAll(name: string): (File | string)[];
1524 /**
1525 * The **`has()`** method of the FormData interface returns whether a FormData object contains a certain key.
1526 *
1527 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has)
1528 */
1529 has(name: string): boolean;
1530 /**
1531 * 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.
1532 *
1533 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set)
1534 */
1535 set(name: string, value: string | Blob): void;
1536 /**
1537 * 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.
1538 *
1539 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set)
1540 */
1541 set(name: string, value: string): void;
1542 /**
1543 * 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.
1544 *
1545 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set)
1546 */
1547 set(name: string, value: Blob, filename?: string): void;
1548 entries(): IterableIterator<[
1549 key: string,
1550 value: File | string
1551 ]>;
1552 keys(): IterableIterator<string>;
1553 values(): IterableIterator<(File | string)>;
1554 forEach<This = unknown>(callback: (this: This, value: File | string, key: string, parent: FormData) => void, thisArg?: This): void;
1555 [Symbol.iterator](): IterableIterator<[
1556 key: string,
1557 value: File | string
1558 ]>;
1559}
1560interface ContentOptions {
1561 html?: boolean;
1562}
1563declare class HTMLRewriter {
1564 constructor();
1565 on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter;
1566 onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter;
1567 transform(response: Response): Response;
1568}
1569interface HTMLRewriterElementContentHandlers {
1570 element?(element: Element): void | Promise<void>;
1571 comments?(comment: Comment): void | Promise<void>;
1572 text?(element: Text): void | Promise<void>;
1573}
1574interface HTMLRewriterDocumentContentHandlers {
1575 doctype?(doctype: Doctype): void | Promise<void>;
1576 comments?(comment: Comment): void | Promise<void>;
1577 text?(text: Text): void | Promise<void>;
1578 end?(end: DocumentEnd): void | Promise<void>;
1579}
1580interface Doctype {
1581 readonly name: string | null;
1582 readonly publicId: string | null;
1583 readonly systemId: string | null;
1584}
1585interface Element {
1586 tagName: string;
1587 readonly attributes: IterableIterator<string[]>;
1588 readonly removed: boolean;
1589 readonly namespaceURI: string;
1590 getAttribute(name: string): string | null;
1591 hasAttribute(name: string): boolean;
1592 setAttribute(name: string, value: string): Element;
1593 removeAttribute(name: string): Element;
1594 before(content: string | ReadableStream | Response, options?: ContentOptions): Element;
1595 after(content: string | ReadableStream | Response, options?: ContentOptions): Element;
1596 prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element;
1597 append(content: string | ReadableStream | Response, options?: ContentOptions): Element;
1598 replace(content: string | ReadableStream | Response, options?: ContentOptions): Element;
1599 remove(): Element;
1600 removeAndKeepContent(): Element;
1601 setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element;
1602 onEndTag(handler: (tag: EndTag) => void | Promise<void>): void;
1603}
1604interface EndTag {
1605 name: string;
1606 before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag;
1607 after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag;
1608 remove(): EndTag;
1609}
1610interface Comment {
1611 text: string;
1612 readonly removed: boolean;
1613 before(content: string, options?: ContentOptions): Comment;
1614 after(content: string, options?: ContentOptions): Comment;
1615 replace(content: string, options?: ContentOptions): Comment;
1616 remove(): Comment;
1617}
1618interface Text {
1619 readonly text: string;
1620 readonly lastInTextNode: boolean;
1621 readonly removed: boolean;
1622 before(content: string | ReadableStream | Response, options?: ContentOptions): Text;
1623 after(content: string | ReadableStream | Response, options?: ContentOptions): Text;
1624 replace(content: string | ReadableStream | Response, options?: ContentOptions): Text;
1625 remove(): Text;
1626}
1627interface DocumentEnd {
1628 append(content: string, options?: ContentOptions): DocumentEnd;
1629}
1630/**
1631 * 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.
1632 *
1633 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent)
1634 */
1635declare abstract class FetchEvent extends ExtendableEvent {
1636 /**
1637 * The **`request`** read-only property of the FetchEvent interface returns the Request that triggered the event handler.
1638 *
1639 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request)
1640 */
1641 readonly request: Request;
1642 /**
1643 * The **`respondWith()`** method of FetchEvent prevents the browser's default fetch handling, and allows you to provide a promise for a Response yourself.
1644 *
1645 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith)
1646 */
1647 respondWith(promise: Response | Promise<Response>): void;
1648 passThroughOnException(): void;
1649}
1650type HeadersInit = Headers | Iterable<Iterable<string>> | Record<string, string>;
1651/**
1652 * 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.
1653 *
1654 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers)
1655 */
1656declare class Headers {
1657 constructor(init?: HeadersInit);
1658 /**
1659 * 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.
1660 *
1661 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get)
1662 */
1663 get(name: string): string | null;
1664 getAll(name: string): string[];
1665 /**
1666 * 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.
1667 *
1668 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie)
1669 */
1670 getSetCookie(): string[];
1671 /**
1672 * The **`has()`** method of the Headers interface returns a boolean stating whether a Headers object contains a certain header.
1673 *
1674 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has)
1675 */
1676 has(name: string): boolean;
1677 /**
1678 * 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.
1679 *
1680 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set)
1681 */
1682 set(name: string, value: string): void;
1683 /**
1684 * 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.
1685 *
1686 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append)
1687 */
1688 append(name: string, value: string): void;
1689 /**
1690 * The **`delete()`** method of the Headers interface deletes a header from the current Headers object.
1691 *
1692 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete)
1693 */
1694 delete(name: string): void;
1695 forEach<This = unknown>(callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This): void;
1696 entries(): IterableIterator<[
1697 key: string,
1698 value: string
1699 ]>;
1700 keys(): IterableIterator<string>;
1701 values(): IterableIterator<string>;
1702 [Symbol.iterator](): IterableIterator<[
1703 key: string,
1704 value: string
1705 ]>;
1706}
1707type BodyInit = ReadableStream<Uint8Array> | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData | Iterable<ArrayBuffer | ArrayBufferView> | AsyncIterable<ArrayBuffer | ArrayBufferView>;
1708declare abstract class Body {
1709 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */
1710 get body(): ReadableStream | null;
1711 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */
1712 get bodyUsed(): boolean;
1713 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */
1714 arrayBuffer(): Promise<ArrayBuffer>;
1715 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */
1716 bytes(): Promise<Uint8Array>;
1717 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */
1718 text(): Promise<string>;
1719 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */
1720 json<T>(): Promise<T>;
1721 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */
1722 formData(): Promise<FormData>;
1723 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */
1724 blob(): Promise<Blob>;
1725}
1726/**
1727 * The **`Response`** interface of the Fetch API represents the response to a request.
1728 *
1729 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)
1730 */
1731declare var Response: {
1732 prototype: Response;
1733 new (body?: BodyInit | null, init?: ResponseInit): Response;
1734 error(): Response;
1735 redirect(url: string, status?: number): Response;
1736 json(any: any, maybeInit?: (ResponseInit | Response)): Response;
1737};
1738/**
1739 * The **`Response`** interface of the Fetch API represents the response to a request.
1740 *
1741 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response)
1742 */
1743interface Response extends Body {
1744 /**
1745 * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable.
1746 *
1747 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone)
1748 */
1749 clone(): Response;
1750 /**
1751 * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response.
1752 *
1753 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status)
1754 */
1755 status: number;
1756 /**
1757 * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status.
1758 *
1759 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText)
1760 */
1761 statusText: string;
1762 /**
1763 * The **`headers`** read-only property of the Response interface contains the Headers object associated with the response.
1764 *
1765 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers)
1766 */
1767 headers: Headers;
1768 /**
1769 * 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.
1770 *
1771 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok)
1772 */
1773 ok: boolean;
1774 /**
1775 * 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.
1776 *
1777 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected)
1778 */
1779 redirected: boolean;
1780 /**
1781 * 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.
1782 *
1783 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url)
1784 */
1785 url: string;
1786 webSocket: WebSocket | null;
1787 cf: any | undefined;
1788 /**
1789 * 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.
1790 *
1791 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type)
1792 */
1793 type: "default" | "error";
1794}
1795interface ResponseInit {
1796 status?: number;
1797 statusText?: string;
1798 headers?: HeadersInit;
1799 cf?: any;
1800 webSocket?: (WebSocket | null);
1801 encodeBody?: "automatic" | "manual";
1802}
1803type RequestInfo<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>> = Request<CfHostMetadata, Cf> | string;
1804/**
1805 * The **`Request`** interface of the Fetch API represents a resource request.
1806 *
1807 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request)
1808 */
1809declare var Request: {
1810 prototype: Request;
1811 new <CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>>(input: RequestInfo<CfProperties> | URL, init?: RequestInit<Cf>): Request<CfHostMetadata, Cf>;
1812};
1813/**
1814 * The **`Request`** interface of the Fetch API represents a resource request.
1815 *
1816 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request)
1817 */
1818interface Request<CfHostMetadata = unknown, Cf = CfProperties<CfHostMetadata>> extends Body {
1819 /**
1820 * The **`clone()`** method of the Request interface creates a copy of the current Request object.
1821 *
1822 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone)
1823 */
1824 clone(): Request<CfHostMetadata, Cf>;
1825 /**
1826 * The **`method`** read-only property of the Request interface contains the request's method (GET, POST, etc.)
1827 *
1828 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method)
1829 */
1830 method: string;
1831 /**
1832 * The **`url`** read-only property of the Request interface contains the URL of the request.
1833 *
1834 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url)
1835 */
1836 url: string;
1837 /**
1838 * The **`headers`** read-only property of the Request interface contains the Headers object associated with the request.
1839 *
1840 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers)
1841 */
1842 headers: Headers;
1843 /**
1844 * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled.
1845 *
1846 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect)
1847 */
1848 redirect: string;
1849 fetcher: Fetcher | null;
1850 /**
1851 * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request.
1852 *
1853 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal)
1854 */
1855 signal: AbortSignal;
1856 cf?: Cf;
1857 /**
1858 * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request.
1859 *
1860 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity)
1861 */
1862 integrity: string;
1863 /**
1864 * 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.
1865 *
1866 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive)
1867 */
1868 keepalive: boolean;
1869 /**
1870 * 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.
1871 *
1872 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache)
1873 */
1874 cache?: "no-store" | "no-cache";
1875}
1876interface RequestInit<Cf = CfProperties> {
1877 /* A string to set request's method. */
1878 method?: string;
1879 /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */
1880 headers?: HeadersInit;
1881 /* A BodyInit object or null to set request's body. */
1882 body?: BodyInit | null;
1883 /* 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. */
1884 redirect?: string;
1885 fetcher?: (Fetcher | null);
1886 cf?: Cf;
1887 /* A string indicating how the request will interact with the browser's cache to set request's cache. */
1888 cache?: "no-store" | "no-cache";
1889 /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */
1890 integrity?: string;
1891 /* An AbortSignal to set request's signal. */
1892 signal?: (AbortSignal | null);
1893 encodeResponseBody?: "automatic" | "manual";
1894}
1895type 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>;
1896type Fetcher<T extends Rpc.EntrypointBranded | undefined = undefined, Reserved extends string = never> = (T extends Rpc.EntrypointBranded ? Rpc.Provider<T, Reserved | "fetch" | "connect"> : unknown) & {
1897 fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
1898 connect(address: SocketAddress | string, options?: SocketOptions): Socket;
1899};
1900interface KVNamespaceListKey<Metadata, Key extends string = string> {
1901 name: Key;
1902 expiration?: number;
1903 metadata?: Metadata;
1904}
1905type KVNamespaceListResult<Metadata, Key extends string = string> = {
1906 list_complete: false;
1907 keys: KVNamespaceListKey<Metadata, Key>[];
1908 cursor: string;
1909 cacheStatus: string | null;
1910} | {
1911 list_complete: true;
1912 keys: KVNamespaceListKey<Metadata, Key>[];
1913 cacheStatus: string | null;
1914};
1915interface KVNamespace<Key extends string = string> {
1916 get(key: Key, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<string | null>;
1917 get(key: Key, type: "text"): Promise<string | null>;
1918 get<ExpectedValue = unknown>(key: Key, type: "json"): Promise<ExpectedValue | null>;
1919 get(key: Key, type: "arrayBuffer"): Promise<ArrayBuffer | null>;
1920 get(key: Key, type: "stream"): Promise<ReadableStream | null>;
1921 get(key: Key, options?: KVNamespaceGetOptions<"text">): Promise<string | null>;
1922 get<ExpectedValue = unknown>(key: Key, options?: KVNamespaceGetOptions<"json">): Promise<ExpectedValue | null>;
1923 get(key: Key, options?: KVNamespaceGetOptions<"arrayBuffer">): Promise<ArrayBuffer | null>;
1924 get(key: Key, options?: KVNamespaceGetOptions<"stream">): Promise<ReadableStream | null>;
1925 get(key: Array<Key>, type: "text"): Promise<Map<string, string | null>>;
1926 get<ExpectedValue = unknown>(key: Array<Key>, type: "json"): Promise<Map<string, ExpectedValue | null>>;
1927 get(key: Array<Key>, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<Map<string, string | null>>;
1928 get(key: Array<Key>, options?: KVNamespaceGetOptions<"text">): Promise<Map<string, string | null>>;
1929 get<ExpectedValue = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<"json">): Promise<Map<string, ExpectedValue | null>>;
1930 list<Metadata = unknown>(options?: KVNamespaceListOptions): Promise<KVNamespaceListResult<Metadata, Key>>;
1931 put(key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise<void>;
1932 getWithMetadata<Metadata = unknown>(key: Key, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;
1933 getWithMetadata<Metadata = unknown>(key: Key, type: "text"): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;
1934 getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Key, type: "json"): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>;
1935 getWithMetadata<Metadata = unknown>(key: Key, type: "arrayBuffer"): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>;
1936 getWithMetadata<Metadata = unknown>(key: Key, type: "stream"): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>;
1937 getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<"text">): Promise<KVNamespaceGetWithMetadataResult<string, Metadata>>;
1938 getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<"json">): Promise<KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>;
1939 getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<"arrayBuffer">): Promise<KVNamespaceGetWithMetadataResult<ArrayBuffer, Metadata>>;
1940 getWithMetadata<Metadata = unknown>(key: Key, options: KVNamespaceGetOptions<"stream">): Promise<KVNamespaceGetWithMetadataResult<ReadableStream, Metadata>>;
1941 getWithMetadata<Metadata = unknown>(key: Array<Key>, type: "text"): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;
1942 getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Array<Key>, type: "json"): Promise<Map<string, KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>>;
1943 getWithMetadata<Metadata = unknown>(key: Array<Key>, options?: Partial<KVNamespaceGetOptions<undefined>>): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;
1944 getWithMetadata<Metadata = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<"text">): Promise<Map<string, KVNamespaceGetWithMetadataResult<string, Metadata>>>;
1945 getWithMetadata<ExpectedValue = unknown, Metadata = unknown>(key: Array<Key>, options?: KVNamespaceGetOptions<"json">): Promise<Map<string, KVNamespaceGetWithMetadataResult<ExpectedValue, Metadata>>>;
1946 delete(key: Key): Promise<void>;
1947}
1948interface KVNamespaceListOptions {
1949 limit?: number;
1950 prefix?: (string | null);
1951 cursor?: (string | null);
1952}
1953interface KVNamespaceGetOptions<Type> {
1954 type: Type;
1955 cacheTtl?: number;
1956}
1957interface KVNamespacePutOptions {
1958 expiration?: number;
1959 expirationTtl?: number;
1960 metadata?: (any | null);
1961}
1962interface KVNamespaceGetWithMetadataResult<Value, Metadata> {
1963 value: Value | null;
1964 metadata: Metadata | null;
1965 cacheStatus: string | null;
1966}
1967type QueueContentType = "text" | "bytes" | "json" | "v8";
1968interface Queue<Body = unknown> {
1969 metrics(): Promise<QueueMetrics>;
1970 send(message: Body, options?: QueueSendOptions): Promise<QueueSendResponse>;
1971 sendBatch(messages: Iterable<MessageSendRequest<Body>>, options?: QueueSendBatchOptions): Promise<QueueSendBatchResponse>;
1972}
1973interface QueueSendMetrics {
1974 backlogCount: number;
1975 backlogBytes: number;
1976 oldestMessageTimestamp?: Date;
1977}
1978interface QueueSendMetadata {
1979 metrics: QueueSendMetrics;
1980}
1981interface QueueSendResponse {
1982 metadata: QueueSendMetadata;
1983}
1984interface QueueSendBatchMetrics {
1985 backlogCount: number;
1986 backlogBytes: number;
1987 oldestMessageTimestamp?: Date;
1988}
1989interface QueueSendBatchMetadata {
1990 metrics: QueueSendBatchMetrics;
1991}
1992interface QueueSendBatchResponse {
1993 metadata: QueueSendBatchMetadata;
1994}
1995interface QueueSendOptions {
1996 contentType?: QueueContentType;
1997 delaySeconds?: number;
1998}
1999interface QueueSendBatchOptions {
2000 delaySeconds?: number;
2001}
2002interface MessageSendRequest<Body = unknown> {
2003 body: Body;
2004 contentType?: QueueContentType;
2005 delaySeconds?: number;
2006}
2007interface QueueMetrics {
2008 backlogCount: number;
2009 backlogBytes: number;
2010 oldestMessageTimestamp?: Date;
2011}
2012interface MessageBatchMetrics {
2013 backlogCount: number;
2014 backlogBytes: number;
2015 oldestMessageTimestamp?: Date;
2016}
2017interface MessageBatchMetadata {
2018 metrics: MessageBatchMetrics;
2019}
2020interface QueueRetryOptions {
2021 delaySeconds?: number;
2022}
2023interface Message<Body = unknown> {
2024 readonly id: string;
2025 readonly timestamp: Date;
2026 readonly body: Body;
2027 readonly attempts: number;
2028 retry(options?: QueueRetryOptions): void;
2029 ack(): void;
2030}
2031interface QueueEvent<Body = unknown> extends ExtendableEvent {
2032 readonly messages: readonly Message<Body>[];
2033 readonly queue: string;
2034 readonly metadata: MessageBatchMetadata;
2035 retryAll(options?: QueueRetryOptions): void;
2036 ackAll(): void;
2037}
2038interface MessageBatch<Body = unknown> {
2039 readonly messages: readonly Message<Body>[];
2040 readonly queue: string;
2041 readonly metadata: MessageBatchMetadata;
2042 retryAll(options?: QueueRetryOptions): void;
2043 ackAll(): void;
2044}
2045interface R2Error extends Error {
2046 readonly name: string;
2047 readonly code: number;
2048 readonly message: string;
2049 readonly action: string;
2050 readonly stack: any;
2051}
2052interface R2ListOptions {
2053 limit?: number;
2054 prefix?: string;
2055 cursor?: string;
2056 delimiter?: string;
2057 startAfter?: string;
2058 include?: ("httpMetadata" | "customMetadata")[];
2059}
2060interface R2Bucket {
2061 head(key: string): Promise<R2Object | null>;
2062 get(key: string, options: R2GetOptions & {
2063 onlyIf: R2Conditional | Headers;
2064 }): Promise<R2ObjectBody | R2Object | null>;
2065 get(key: string, options?: R2GetOptions): Promise<R2ObjectBody | null>;
2066 put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & {
2067 onlyIf: R2Conditional | Headers;
2068 }): Promise<R2Object | null>;
2069 put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise<R2Object>;
2070 createMultipartUpload(key: string, options?: R2MultipartOptions): Promise<R2MultipartUpload>;
2071 resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload;
2072 delete(keys: string | string[]): Promise<void>;
2073 list(options?: R2ListOptions): Promise<R2Objects>;
2074}
2075interface R2MultipartUpload {
2076 readonly key: string;
2077 readonly uploadId: string;
2078 uploadPart(partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions): Promise<R2UploadedPart>;
2079 abort(): Promise<void>;
2080 complete(uploadedParts: R2UploadedPart[]): Promise<R2Object>;
2081}
2082interface R2UploadedPart {
2083 partNumber: number;
2084 etag: string;
2085}
2086declare abstract class R2Object {
2087 readonly key: string;
2088 readonly version: string;
2089 readonly size: number;
2090 readonly etag: string;
2091 readonly httpEtag: string;
2092 readonly checksums: R2Checksums;
2093 readonly uploaded: Date;
2094 readonly httpMetadata?: R2HTTPMetadata;
2095 readonly customMetadata?: Record<string, string>;
2096 readonly range?: R2Range;
2097 readonly storageClass: string;
2098 readonly ssecKeyMd5?: string;
2099 writeHttpMetadata(headers: Headers): void;
2100}
2101interface R2ObjectBody extends R2Object {
2102 get body(): ReadableStream;
2103 get bodyUsed(): boolean;
2104 arrayBuffer(): Promise<ArrayBuffer>;
2105 bytes(): Promise<Uint8Array>;
2106 text(): Promise<string>;
2107 json<T>(): Promise<T>;
2108 blob(): Promise<Blob>;
2109}
2110type R2Range = {
2111 offset: number;
2112 length?: number;
2113} | {
2114 offset?: number;
2115 length: number;
2116} | {
2117 suffix: number;
2118};
2119interface R2Conditional {
2120 etagMatches?: string;
2121 etagDoesNotMatch?: string;
2122 uploadedBefore?: Date;
2123 uploadedAfter?: Date;
2124 secondsGranularity?: boolean;
2125}
2126interface R2GetOptions {
2127 onlyIf?: (R2Conditional | Headers);
2128 range?: (R2Range | Headers);
2129 ssecKey?: (ArrayBuffer | string);
2130}
2131interface R2PutOptions {
2132 onlyIf?: (R2Conditional | Headers);
2133 httpMetadata?: (R2HTTPMetadata | Headers);
2134 customMetadata?: Record<string, string>;
2135 md5?: ((ArrayBuffer | ArrayBufferView) | string);
2136 sha1?: ((ArrayBuffer | ArrayBufferView) | string);
2137 sha256?: ((ArrayBuffer | ArrayBufferView) | string);
2138 sha384?: ((ArrayBuffer | ArrayBufferView) | string);
2139 sha512?: ((ArrayBuffer | ArrayBufferView) | string);
2140 storageClass?: string;
2141 ssecKey?: (ArrayBuffer | string);
2142}
2143interface R2MultipartOptions {
2144 httpMetadata?: (R2HTTPMetadata | Headers);
2145 customMetadata?: Record<string, string>;
2146 storageClass?: string;
2147 ssecKey?: (ArrayBuffer | string);
2148}
2149interface R2Checksums {
2150 readonly md5?: ArrayBuffer;
2151 readonly sha1?: ArrayBuffer;
2152 readonly sha256?: ArrayBuffer;
2153 readonly sha384?: ArrayBuffer;
2154 readonly sha512?: ArrayBuffer;
2155 toJSON(): R2StringChecksums;
2156}
2157interface R2StringChecksums {
2158 md5?: string;
2159 sha1?: string;
2160 sha256?: string;
2161 sha384?: string;
2162 sha512?: string;
2163}
2164interface R2HTTPMetadata {
2165 contentType?: string;
2166 contentLanguage?: string;
2167 contentDisposition?: string;
2168 contentEncoding?: string;
2169 cacheControl?: string;
2170 cacheExpiry?: Date;
2171}
2172type R2Objects = {
2173 objects: R2Object[];
2174 delimitedPrefixes: string[];
2175} & ({
2176 truncated: true;
2177 cursor: string;
2178} | {
2179 truncated: false;
2180});
2181interface R2UploadPartOptions {
2182 ssecKey?: (ArrayBuffer | string);
2183}
2184declare abstract class ScheduledEvent extends ExtendableEvent {
2185 readonly scheduledTime: number;
2186 readonly cron: string;
2187 noRetry(): void;
2188}
2189interface ScheduledController {
2190 readonly scheduledTime: number;
2191 readonly cron: string;
2192 noRetry(): void;
2193}
2194interface QueuingStrategy<T = any> {
2195 highWaterMark?: (number | bigint);
2196 size?: (chunk: T) => number | bigint;
2197}
2198interface UnderlyingSink<W = any> {
2199 type?: string;
2200 start?: (controller: WritableStreamDefaultController) => void | Promise<void>;
2201 write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise<void>;
2202 abort?: (reason: any) => void | Promise<void>;
2203 close?: () => void | Promise<void>;
2204}
2205interface UnderlyingByteSource {
2206 type: "bytes";
2207 autoAllocateChunkSize?: number;
2208 start?: (controller: ReadableByteStreamController) => void | Promise<void>;
2209 pull?: (controller: ReadableByteStreamController) => void | Promise<void>;
2210 cancel?: (reason: any) => void | Promise<void>;
2211}
2212interface UnderlyingSource<R = any> {
2213 type?: "" | undefined;
2214 start?: (controller: ReadableStreamDefaultController<R>) => void | Promise<void>;
2215 pull?: (controller: ReadableStreamDefaultController<R>) => void | Promise<void>;
2216 cancel?: (reason: any) => void | Promise<void>;
2217 expectedLength?: (number | bigint);
2218}
2219interface Transformer<I = any, O = any> {
2220 readableType?: string;
2221 writableType?: string;
2222 start?: (controller: TransformStreamDefaultController<O>) => void | Promise<void>;
2223 transform?: (chunk: I, controller: TransformStreamDefaultController<O>) => void | Promise<void>;
2224 flush?: (controller: TransformStreamDefaultController<O>) => void | Promise<void>;
2225 cancel?: (reason: any) => void | Promise<void>;
2226 expectedLength?: number;
2227}
2228interface StreamPipeOptions {
2229 preventAbort?: boolean;
2230 preventCancel?: boolean;
2231 /**
2232 * 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.
2233 *
2234 * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
2235 *
2236 * Errors and closures of the source and destination streams propagate as follows:
2237 *
2238 * 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.
2239 *
2240 * 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.
2241 *
2242 * 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.
2243 *
2244 * 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.
2245 *
2246 * 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.
2247 */
2248 preventClose?: boolean;
2249 signal?: AbortSignal;
2250}
2251type ReadableStreamReadResult<R = any> = {
2252 done: false;
2253 value: R;
2254} | {
2255 done: true;
2256 value?: undefined;
2257};
2258/**
2259 * 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.
2260 *
2261 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream)
2262 */
2263interface ReadableStream<R = any> {
2264 /**
2265 * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader.
2266 *
2267 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked)
2268 */
2269 get locked(): boolean;
2270 /**
2271 * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled.
2272 *
2273 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel)
2274 */
2275 cancel(reason?: any): Promise<void>;
2276 /**
2277 * 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.
2278 *
2279 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader)
2280 */
2281 getReader(): ReadableStreamDefaultReader<R>;
2282 /**
2283 * 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.
2284 *
2285 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader)
2286 */
2287 getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader;
2288 /**
2289 * 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.
2290 *
2291 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough)
2292 */
2293 pipeThrough<T>(transform: ReadableWritablePair<T, R>, options?: StreamPipeOptions): ReadableStream<T>;
2294 /**
2295 * 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.
2296 *
2297 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo)
2298 */
2299 pipeTo(destination: WritableStream<R>, options?: StreamPipeOptions): Promise<void>;
2300 /**
2301 * 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.
2302 *
2303 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee)
2304 */
2305 tee(): [
2306 ReadableStream<R>,
2307 ReadableStream<R>
2308 ];
2309 values(options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>;
2310 [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator<R>;
2311}
2312/**
2313 * 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.
2314 *
2315 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream)
2316 */
2317declare const ReadableStream: {
2318 prototype: ReadableStream;
2319 new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy<Uint8Array>): ReadableStream<Uint8Array>;
2320 new <R = any>(underlyingSource?: UnderlyingSource<R>, strategy?: QueuingStrategy<R>): ReadableStream<R>;
2321};
2322/**
2323 * 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).
2324 *
2325 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader)
2326 */
2327declare class ReadableStreamDefaultReader<R = any> {
2328 constructor(stream: ReadableStream);
2329 get closed(): Promise<void>;
2330 cancel(reason?: any): Promise<void>;
2331 /**
2332 * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue.
2333 *
2334 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read)
2335 */
2336 read(): Promise<ReadableStreamReadResult<R>>;
2337 /**
2338 * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream.
2339 *
2340 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock)
2341 */
2342 releaseLock(): void;
2343}
2344/**
2345 * 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.
2346 *
2347 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader)
2348 */
2349declare class ReadableStreamBYOBReader {
2350 constructor(stream: ReadableStream);
2351 get closed(): Promise<void>;
2352 cancel(reason?: any): Promise<void>;
2353 /**
2354 * 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.
2355 *
2356 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read)
2357 */
2358 read<T extends ArrayBufferView>(view: T): Promise<ReadableStreamReadResult<T>>;
2359 /**
2360 * 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.
2361 *
2362 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock)
2363 */
2364 releaseLock(): void;
2365 readAtLeast<T extends ArrayBufferView>(minElements: number, view: T): Promise<ReadableStreamReadResult<T>>;
2366}
2367interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions {
2368 min?: number;
2369}
2370interface ReadableStreamGetReaderOptions {
2371 /**
2372 * Creates a ReadableStreamBYOBReader and locks the stream to the new reader.
2373 *
2374 * 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.
2375 */
2376 mode: "byob";
2377}
2378/**
2379 * 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).
2380 *
2381 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest)
2382 */
2383declare abstract class ReadableStreamBYOBRequest {
2384 /**
2385 * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view.
2386 *
2387 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view)
2388 */
2389 get view(): Uint8Array | null;
2390 /**
2391 * 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.
2392 *
2393 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond)
2394 */
2395 respond(bytesWritten: number): void;
2396 /**
2397 * 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.
2398 *
2399 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView)
2400 */
2401 respondWithNewView(view: ArrayBuffer | ArrayBufferView): void;
2402 get atLeast(): number | null;
2403}
2404/**
2405 * 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.
2406 *
2407 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController)
2408 */
2409declare abstract class ReadableStreamDefaultController<R = any> {
2410 /**
2411 * The **`desiredSize`** read-only property of the ReadableStreamDefaultController interface returns the desired size required to fill the stream's internal queue.
2412 *
2413 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize)
2414 */
2415 get desiredSize(): number | null;
2416 /**
2417 * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream.
2418 *
2419 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close)
2420 */
2421 close(): void;
2422 /**
2423 * The **`enqueue()`** method of the ReadableStreamDefaultController interface enqueues a given chunk in the associated stream.
2424 *
2425 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue)
2426 */
2427 enqueue(chunk?: R): void;
2428 /**
2429 * The **`error()`** method of the ReadableStreamDefaultController interface causes any future interactions with the associated stream to error.
2430 *
2431 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error)
2432 */
2433 error(reason: any): void;
2434}
2435/**
2436 * 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.
2437 *
2438 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController)
2439 */
2440declare abstract class ReadableByteStreamController {
2441 /**
2442 * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or null if there are no pending requests.
2443 *
2444 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest)
2445 */
2446 get byobRequest(): ReadableStreamBYOBRequest | null;
2447 /**
2448 * 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".
2449 *
2450 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize)
2451 */
2452 get desiredSize(): number | null;
2453 /**
2454 * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream.
2455 *
2456 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close)
2457 */
2458 close(): void;
2459 /**
2460 * 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).
2461 *
2462 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue)
2463 */
2464 enqueue(chunk: ArrayBuffer | ArrayBufferView): void;
2465 /**
2466 * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason.
2467 *
2468 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error)
2469 */
2470 error(reason: any): void;
2471}
2472/**
2473 * 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.
2474 *
2475 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController)
2476 */
2477declare abstract class WritableStreamDefaultController {
2478 /**
2479 * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller.
2480 *
2481 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal)
2482 */
2483 get signal(): AbortSignal;
2484 /**
2485 * The **`error()`** method of the WritableStreamDefaultController interface causes any future interactions with the associated stream to error.
2486 *
2487 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error)
2488 */
2489 error(reason?: any): void;
2490}
2491/**
2492 * The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated ReadableStream and WritableStream.
2493 *
2494 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController)
2495 */
2496declare abstract class TransformStreamDefaultController<O = any> {
2497 /**
2498 * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream.
2499 *
2500 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize)
2501 */
2502 get desiredSize(): number | null;
2503 /**
2504 * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream.
2505 *
2506 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue)
2507 */
2508 enqueue(chunk?: O): void;
2509 /**
2510 * 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.
2511 *
2512 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error)
2513 */
2514 error(reason: any): void;
2515 /**
2516 * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream.
2517 *
2518 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate)
2519 */
2520 terminate(): void;
2521}
2522interface ReadableWritablePair<R = any, W = any> {
2523 readable: ReadableStream<R>;
2524 /**
2525 * 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.
2526 *
2527 * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader.
2528 */
2529 writable: WritableStream<W>;
2530}
2531/**
2532 * 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.
2533 *
2534 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream)
2535 */
2536declare class WritableStream<W = any> {
2537 constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy);
2538 /**
2539 * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the WritableStream is locked to a writer.
2540 *
2541 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked)
2542 */
2543 get locked(): boolean;
2544 /**
2545 * 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.
2546 *
2547 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort)
2548 */
2549 abort(reason?: any): Promise<void>;
2550 /**
2551 * 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.
2552 *
2553 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close)
2554 */
2555 close(): Promise<void>;
2556 /**
2557 * 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.
2558 *
2559 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter)
2560 */
2561 getWriter(): WritableStreamDefaultWriter<W>;
2562}
2563/**
2564 * 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.
2565 *
2566 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter)
2567 */
2568declare class WritableStreamDefaultWriter<W = any> {
2569 constructor(stream: WritableStream);
2570 /**
2571 * 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.
2572 *
2573 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed)
2574 */
2575 get closed(): Promise<void>;
2576 /**
2577 * 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.
2578 *
2579 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready)
2580 */
2581 get ready(): Promise<void>;
2582 /**
2583 * The **`desiredSize`** read-only property of the WritableStreamDefaultWriter interface returns the desired size required to fill the stream's internal queue.
2584 *
2585 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize)
2586 */
2587 get desiredSize(): number | null;
2588 /**
2589 * 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.
2590 *
2591 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort)
2592 */
2593 abort(reason?: any): Promise<void>;
2594 /**
2595 * The **`close()`** method of the WritableStreamDefaultWriter interface closes the associated writable stream.
2596 *
2597 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close)
2598 */
2599 close(): Promise<void>;
2600 /**
2601 * 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.
2602 *
2603 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write)
2604 */
2605 write(chunk?: W): Promise<void>;
2606 /**
2607 * 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.
2608 *
2609 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock)
2610 */
2611 releaseLock(): void;
2612}
2613/**
2614 * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain transform stream concept.
2615 *
2616 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream)
2617 */
2618declare class TransformStream<I = any, O = any> {
2619 constructor(transformer?: Transformer<I, O>, writableStrategy?: QueuingStrategy<I>, readableStrategy?: QueuingStrategy<O>);
2620 /**
2621 * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this TransformStream. This stream emits the transformed output data.
2622 *
2623 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable)
2624 */
2625 get readable(): ReadableStream<O>;
2626 /**
2627 * 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.
2628 *
2629 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable)
2630 */
2631 get writable(): WritableStream<I>;
2632}
2633declare class FixedLengthStream extends IdentityTransformStream {
2634 constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy);
2635}
2636declare class IdentityTransformStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {
2637 constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy);
2638}
2639interface IdentityTransformStreamQueuingStrategy {
2640 highWaterMark?: (number | bigint);
2641}
2642interface ReadableStreamValuesOptions {
2643 preventCancel?: boolean;
2644}
2645/**
2646 * 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.
2647 *
2648 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream)
2649 */
2650declare class CompressionStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {
2651 constructor(format: "gzip" | "deflate" | "deflate-raw");
2652}
2653/**
2654 * 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.
2655 *
2656 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream)
2657 */
2658declare class DecompressionStream extends TransformStream<ArrayBuffer | ArrayBufferView, Uint8Array> {
2659 constructor(format: "gzip" | "deflate" | "deflate-raw");
2660}
2661/**
2662 * 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.
2663 *
2664 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream)
2665 */
2666declare class TextEncoderStream extends TransformStream<string, Uint8Array> {
2667 constructor();
2668 get encoding(): string;
2669}
2670/**
2671 * 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.
2672 *
2673 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream)
2674 */
2675declare class TextDecoderStream extends TransformStream<ArrayBuffer | ArrayBufferView, string> {
2676 constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit);
2677 get encoding(): string;
2678 get fatal(): boolean;
2679 get ignoreBOM(): boolean;
2680}
2681interface TextDecoderStreamTextDecoderStreamInit {
2682 fatal?: boolean;
2683 ignoreBOM?: boolean;
2684}
2685/**
2686 * The **`ByteLengthQueuingStrategy`** interface of the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams.
2687 *
2688 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy)
2689 */
2690declare class ByteLengthQueuingStrategy implements QueuingStrategy<ArrayBufferView> {
2691 constructor(init: QueuingStrategyInit);
2692 /**
2693 * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied.
2694 *
2695 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark)
2696 */
2697 get highWaterMark(): number;
2698 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */
2699 get size(): (chunk?: any) => number;
2700}
2701/**
2702 * The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams.
2703 *
2704 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy)
2705 */
2706declare class CountQueuingStrategy implements QueuingStrategy {
2707 constructor(init: QueuingStrategyInit);
2708 /**
2709 * The read-only **`CountQueuingStrategy.highWaterMark`** property returns the total number of chunks that can be contained in the internal queue before backpressure is applied.
2710 *
2711 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark)
2712 */
2713 get highWaterMark(): number;
2714 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */
2715 get size(): (chunk?: any) => number;
2716}
2717interface QueuingStrategyInit {
2718 /**
2719 * Creates a new ByteLengthQueuingStrategy with the provided high water mark.
2720 *
2721 * 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.
2722 */
2723 highWaterMark: number;
2724}
2725interface TracePreviewInfo {
2726 id: string;
2727 slug: string;
2728 name: string;
2729}
2730interface ScriptVersion {
2731 id?: string;
2732 tag?: string;
2733 message?: string;
2734}
2735declare abstract class TailEvent extends ExtendableEvent {
2736 readonly events: TraceItem[];
2737 readonly traces: TraceItem[];
2738}
2739interface TraceItem {
2740 readonly event: (TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemConnectEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo) | null;
2741 readonly eventTimestamp: number | null;
2742 readonly logs: TraceLog[];
2743 readonly exceptions: TraceException[];
2744 readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[];
2745 readonly scriptName: string | null;
2746 readonly entrypoint?: string;
2747 readonly scriptVersion?: ScriptVersion;
2748 readonly dispatchNamespace?: string;
2749 readonly scriptTags?: string[];
2750 readonly tailAttributes?: Record<string, boolean | number | string>;
2751 readonly preview?: TracePreviewInfo;
2752 readonly durableObjectId?: string;
2753 readonly outcome: string;
2754 readonly executionModel: string;
2755 readonly truncated: boolean;
2756 readonly cpuTime: number;
2757 readonly wallTime: number;
2758}
2759interface TraceItemAlarmEventInfo {
2760 readonly scheduledTime: Date;
2761}
2762interface TraceItemConnectEventInfo {
2763}
2764interface TraceItemCustomEventInfo {
2765}
2766interface TraceItemScheduledEventInfo {
2767 readonly scheduledTime: number;
2768 readonly cron: string;
2769}
2770interface TraceItemQueueEventInfo {
2771 readonly queue: string;
2772 readonly batchSize: number;
2773}
2774interface TraceItemEmailEventInfo {
2775 readonly mailFrom: string;
2776 readonly rcptTo: string;
2777 readonly rawSize: number;
2778}
2779interface TraceItemTailEventInfo {
2780 readonly consumedEvents: TraceItemTailEventInfoTailItem[];
2781}
2782interface TraceItemTailEventInfoTailItem {
2783 readonly scriptName: string | null;
2784}
2785interface TraceItemFetchEventInfo {
2786 readonly response?: TraceItemFetchEventInfoResponse;
2787 readonly request: TraceItemFetchEventInfoRequest;
2788}
2789interface TraceItemFetchEventInfoRequest {
2790 readonly cf?: any;
2791 readonly headers: Record<string, string>;
2792 readonly method: string;
2793 readonly url: string;
2794 getUnredacted(): TraceItemFetchEventInfoRequest;
2795}
2796interface TraceItemFetchEventInfoResponse {
2797 readonly status: number;
2798}
2799interface TraceItemJsRpcEventInfo {
2800 readonly rpcMethod: string;
2801}
2802interface TraceItemHibernatableWebSocketEventInfo {
2803 readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError;
2804}
2805interface TraceItemHibernatableWebSocketEventInfoMessage {
2806 readonly webSocketEventType: string;
2807}
2808interface TraceItemHibernatableWebSocketEventInfoClose {
2809 readonly webSocketEventType: string;
2810 readonly code: number;
2811 readonly wasClean: boolean;
2812}
2813interface TraceItemHibernatableWebSocketEventInfoError {
2814 readonly webSocketEventType: string;
2815}
2816interface TraceLog {
2817 readonly timestamp: number;
2818 readonly level: string;
2819 readonly message: any;
2820 readonly errorInfo?: (TraceLogErrorInfo | null)[];
2821}
2822interface TraceLogErrorInfo {
2823 name: string;
2824 message: string;
2825 stack?: string;
2826}
2827interface TraceException {
2828 readonly timestamp: number;
2829 readonly message: string;
2830 readonly name: string;
2831 readonly stack?: string;
2832}
2833interface TraceDiagnosticChannelEvent {
2834 readonly timestamp: number;
2835 readonly channel: string;
2836 readonly message: any;
2837}
2838interface TraceMetrics {
2839 readonly cpuTime: number;
2840 readonly wallTime: number;
2841}
2842interface UnsafeTraceMetrics {
2843 fromTrace(item: TraceItem): TraceMetrics;
2844}
2845/**
2846 * 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.
2847 *
2848 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL)
2849 */
2850declare class URL {
2851 constructor(url: string | URL, base?: string | URL);
2852 /**
2853 * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL.
2854 *
2855 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin)
2856 */
2857 get origin(): string;
2858 /**
2859 * The **`href`** property of the URL interface is a string containing the whole URL.
2860 *
2861 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href)
2862 */
2863 get href(): string;
2864 /**
2865 * The **`href`** property of the URL interface is a string containing the whole URL.
2866 *
2867 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href)
2868 */
2869 set href(value: string);
2870 /**
2871 * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final ":".
2872 *
2873 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol)
2874 */
2875 get protocol(): string;
2876 /**
2877 * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final ":".
2878 *
2879 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol)
2880 */
2881 set protocol(value: string);
2882 /**
2883 * 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, "".
2884 *
2885 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username)
2886 */
2887 get username(): string;
2888 /**
2889 * 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, "".
2890 *
2891 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username)
2892 */
2893 set username(value: string);
2894 /**
2895 * 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, "".
2896 *
2897 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password)
2898 */
2899 get password(): string;
2900 /**
2901 * 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, "".
2902 *
2903 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password)
2904 */
2905 set password(value: string);
2906 /**
2907 * 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, "".
2908 *
2909 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host)
2910 */
2911 get host(): string;
2912 /**
2913 * 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, "".
2914 *
2915 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host)
2916 */
2917 set host(value: string);
2918 /**
2919 * 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.
2920 *
2921 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname)
2922 */
2923 get hostname(): string;
2924 /**
2925 * 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.
2926 *
2927 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname)
2928 */
2929 set hostname(value: string);
2930 /**
2931 * 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, "".
2932 *
2933 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port)
2934 */
2935 get port(): string;
2936 /**
2937 * 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, "".
2938 *
2939 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port)
2940 */
2941 set port(value: string);
2942 /**
2943 * 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.
2944 *
2945 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname)
2946 */
2947 get pathname(): string;
2948 /**
2949 * 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.
2950 *
2951 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname)
2952 */
2953 set pathname(value: string);
2954 /**
2955 * 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, "".
2956 *
2957 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search)
2958 */
2959 get search(): string;
2960 /**
2961 * 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, "".
2962 *
2963 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search)
2964 */
2965 set search(value: string);
2966 /**
2967 * 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, "".
2968 *
2969 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash)
2970 */
2971 get hash(): string;
2972 /**
2973 * 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, "".
2974 *
2975 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash)
2976 */
2977 set hash(value: string);
2978 /**
2979 * 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.
2980 *
2981 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams)
2982 */
2983 get searchParams(): URLSearchParams;
2984 /**
2985 * 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().
2986 *
2987 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON)
2988 */
2989 toJSON(): string;
2990 /*function toString() { [native code] }*/
2991 toString(): string;
2992 /**
2993 * 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.
2994 *
2995 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static)
2996 */
2997 static canParse(url: string, base?: string): boolean;
2998 /**
2999 * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters.
3000 *
3001 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static)
3002 */
3003 static parse(url: string, base?: string): URL | null;
3004 /**
3005 * The **`createObjectURL()`** static method of the URL interface creates a string containing a blob URL pointing to the object given in the parameter.
3006 *
3007 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static)
3008 */
3009 static createObjectURL(object: File | Blob): string;
3010 /**
3011 * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling URL.createObjectURL().
3012 *
3013 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static)
3014 */
3015 static revokeObjectURL(object_url: string): void;
3016}
3017/**
3018 * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL.
3019 *
3020 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams)
3021 */
3022declare class URLSearchParams {
3023 constructor(init?: (Iterable<Iterable<string>> | Record<string, string> | string));
3024 /**
3025 * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries.
3026 *
3027 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size)
3028 */
3029 get size(): number;
3030 /**
3031 * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter.
3032 *
3033 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append)
3034 */
3035 append(name: string, value: string): void;
3036 /**
3037 * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters.
3038 *
3039 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete)
3040 */
3041 delete(name: string, value?: string): void;
3042 /**
3043 * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter.
3044 *
3045 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get)
3046 */
3047 get(name: string): string | null;
3048 /**
3049 * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array.
3050 *
3051 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll)
3052 */
3053 getAll(name: string): string[];
3054 /**
3055 * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters.
3056 *
3057 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has)
3058 */
3059 has(name: string, value?: string): boolean;
3060 /**
3061 * 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.
3062 *
3063 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set)
3064 */
3065 set(name: string, value: string): void;
3066 /**
3067 * 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).
3068 *
3069 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort)
3070 */
3071 sort(): void;
3072 entries(): IterableIterator<[
3073 key: string,
3074 value: string
3075 ]>;
3076 keys(): IterableIterator<string>;
3077 values(): IterableIterator<string>;
3078 forEach<This = unknown>(callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, thisArg?: This): void;
3079 /*function toString() { [native code] }*/
3080 toString(): string;
3081 [Symbol.iterator](): IterableIterator<[
3082 key: string,
3083 value: string
3084 ]>;
3085}
3086/**
3087 * 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.
3088 *
3089 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern)
3090 */
3091declare class URLPattern {
3092 constructor(input?: (string | URLPatternInit), baseURL?: (string | URLPatternOptions), patternOptions?: URLPatternOptions);
3093 /**
3094 * The **`protocol`** read-only property of the URLPattern interface is a string containing the pattern used to match the protocol part of a URL.
3095 *
3096 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/protocol)
3097 */
3098 get protocol(): string;
3099 /**
3100 * The **`username`** read-only property of the URLPattern interface is a string containing the pattern used to match the username part of a URL.
3101 *
3102 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/username)
3103 */
3104 get username(): string;
3105 /**
3106 * The **`password`** read-only property of the URLPattern interface is a string containing the pattern used to match the password part of a URL.
3107 *
3108 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/password)
3109 */
3110 get password(): string;
3111 /**
3112 * The **`hostname`** read-only property of the URLPattern interface is a string containing the pattern used to match the hostname part of a URL.
3113 *
3114 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hostname)
3115 */
3116 get hostname(): string;
3117 /**
3118 * The **`port`** read-only property of the URLPattern interface is a string containing the pattern used to match the port part of a URL.
3119 *
3120 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/port)
3121 */
3122 get port(): string;
3123 /**
3124 * The **`pathname`** read-only property of the URLPattern interface is a string containing the pattern used to match the pathname part of a URL.
3125 *
3126 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/pathname)
3127 */
3128 get pathname(): string;
3129 /**
3130 * The **`search`** read-only property of the URLPattern interface is a string containing the pattern used to match the search part of a URL.
3131 *
3132 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/search)
3133 */
3134 get search(): string;
3135 /**
3136 * The **`hash`** read-only property of the URLPattern interface is a string containing the pattern used to match the fragment part of a URL.
3137 *
3138 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hash)
3139 */
3140 get hash(): string;
3141 /**
3142 * 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.
3143 *
3144 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/hasRegExpGroups)
3145 */
3146 get hasRegExpGroups(): boolean;
3147 /**
3148 * 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.
3149 *
3150 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/test)
3151 */
3152 test(input?: (string | URLPatternInit), baseURL?: string): boolean;
3153 /**
3154 * 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.
3155 *
3156 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLPattern/exec)
3157 */
3158 exec(input?: (string | URLPatternInit), baseURL?: string): URLPatternResult | null;
3159}
3160interface URLPatternInit {
3161 protocol?: string;
3162 username?: string;
3163 password?: string;
3164 hostname?: string;
3165 port?: string;
3166 pathname?: string;
3167 search?: string;
3168 hash?: string;
3169 baseURL?: string;
3170}
3171interface URLPatternComponentResult {
3172 input: string;
3173 groups: Record<string, string>;
3174}
3175interface URLPatternResult {
3176 inputs: (string | URLPatternInit)[];
3177 protocol: URLPatternComponentResult;
3178 username: URLPatternComponentResult;
3179 password: URLPatternComponentResult;
3180 hostname: URLPatternComponentResult;
3181 port: URLPatternComponentResult;
3182 pathname: URLPatternComponentResult;
3183 search: URLPatternComponentResult;
3184 hash: URLPatternComponentResult;
3185}
3186interface URLPatternOptions {
3187 ignoreCase?: boolean;
3188}
3189/**
3190 * 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.
3191 *
3192 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent)
3193 */
3194declare class CloseEvent extends Event {
3195 constructor(type: string, initializer?: CloseEventInit);
3196 /**
3197 * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed.
3198 *
3199 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code)
3200 */
3201 readonly code: number;
3202 /**
3203 * 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.
3204 *
3205 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason)
3206 */
3207 readonly reason: string;
3208 /**
3209 * The **`wasClean`** read-only property of the CloseEvent interface returns true if the connection closed cleanly.
3210 *
3211 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean)
3212 */
3213 readonly wasClean: boolean;
3214}
3215interface CloseEventInit {
3216 bubbles?: boolean;
3217 cancelable?: boolean;
3218 composed?: boolean;
3219 code?: number;
3220 reason?: string;
3221 wasClean?: boolean;
3222}
3223type WebSocketEventMap = {
3224 close: CloseEvent;
3225 message: MessageEvent;
3226 open: Event;
3227 error: ErrorEvent;
3228};
3229/**
3230 * 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.
3231 *
3232 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket)
3233 */
3234declare var WebSocket: {
3235 prototype: WebSocket;
3236 new (url: string, protocols?: (string[] | string)): WebSocket;
3237 readonly READY_STATE_CONNECTING: number;
3238 readonly CONNECTING: number;
3239 readonly READY_STATE_OPEN: number;
3240 readonly OPEN: number;
3241 readonly READY_STATE_CLOSING: number;
3242 readonly CLOSING: number;
3243 readonly READY_STATE_CLOSED: number;
3244 readonly CLOSED: number;
3245};
3246/**
3247 * 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.
3248 *
3249 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket)
3250 */
3251interface WebSocket extends EventTarget<WebSocketEventMap> {
3252 accept(options?: WebSocketAcceptOptions): void;
3253 /**
3254 * 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.
3255 *
3256 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send)
3257 */
3258 send(message: (ArrayBuffer | ArrayBufferView) | string): void;
3259 /**
3260 * The **`WebSocket.close()`** method closes the WebSocket connection or connection attempt, if any. If the connection is already CLOSED, this method does nothing.
3261 *
3262 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close)
3263 */
3264 close(code?: number, reason?: string): void;
3265 serializeAttachment(attachment: any): void;
3266 deserializeAttachment(): any | null;
3267 /**
3268 * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection.
3269 *
3270 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState)
3271 */
3272 readyState: number;
3273 /**
3274 * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor.
3275 *
3276 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url)
3277 */
3278 url: string | null;
3279 /**
3280 * 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.
3281 *
3282 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol)
3283 */
3284 protocol: string | null;
3285 /**
3286 * 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.
3287 *
3288 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions)
3289 */
3290 extensions: string | null;
3291 /**
3292 * The **`WebSocket.binaryType`** property controls the type of binary data being received over the WebSocket connection.
3293 *
3294 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType)
3295 */
3296 binaryType: "blob" | "arraybuffer";
3297}
3298interface WebSocketAcceptOptions {
3299 /**
3300 * When set to `true`, receiving a server-initiated WebSocket Close frame will not
3301 * automatically send a reciprocal Close frame, leaving the connection in a half-open
3302 * state. This is useful for proxying scenarios where you need to coordinate closing
3303 * both sides independently. Defaults to `false` when the
3304 * `no_web_socket_half_open_by_default` compatibility flag is enabled.
3305 */
3306 allowHalfOpen?: boolean;
3307}
3308declare const WebSocketPair: {
3309 new (): {
3310 0: WebSocket;
3311 1: WebSocket;
3312 };
3313};
3314interface SqlStorage {
3315 exec<T extends Record<string, SqlStorageValue>>(query: string, ...bindings: any[]): SqlStorageCursor<T>;
3316 get databaseSize(): number;
3317 Cursor: typeof SqlStorageCursor;
3318 Statement: typeof SqlStorageStatement;
3319}
3320declare abstract class SqlStorageStatement {
3321}
3322type SqlStorageValue = ArrayBuffer | string | number | null;
3323declare abstract class SqlStorageCursor<T extends Record<string, SqlStorageValue>> {
3324 next(): {
3325 done?: false;
3326 value: T;
3327 } | {
3328 done: true;
3329 value?: never;
3330 };
3331 toArray(): T[];
3332 one(): T;
3333 raw<U extends SqlStorageValue[]>(): IterableIterator<U>;
3334 columnNames: string[];
3335 get rowsRead(): number;
3336 get rowsWritten(): number;
3337 [Symbol.iterator](): IterableIterator<T>;
3338}
3339interface Socket {
3340 get readable(): ReadableStream;
3341 get writable(): WritableStream;
3342 get closed(): Promise<void>;
3343 get opened(): Promise<SocketInfo>;
3344 get upgraded(): boolean;
3345 get secureTransport(): "on" | "off" | "starttls";
3346 close(): Promise<void>;
3347 startTls(options?: TlsOptions): Socket;
3348}
3349interface SocketOptions {
3350 secureTransport?: string;
3351 allowHalfOpen: boolean;
3352 highWaterMark?: (number | bigint);
3353}
3354interface SocketAddress {
3355 hostname: string;
3356 port: number;
3357}
3358interface TlsOptions {
3359 expectedServerHostname?: string;
3360}
3361interface SocketInfo {
3362 remoteAddress?: string;
3363 localAddress?: string;
3364}
3365/**
3366 * The **`EventSource`** interface is web content's interface to server-sent events.
3367 *
3368 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource)
3369 */
3370declare class EventSource extends EventTarget {
3371 constructor(url: string, init?: EventSourceEventSourceInit);
3372 /**
3373 * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the EventSource.readyState attribute to 2 (closed).
3374 *
3375 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
3376 */
3377 close(): void;
3378 /**
3379 * The **`url`** read-only property of the EventSource interface returns a string representing the URL of the source.
3380 *
3381 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
3382 */
3383 get url(): string;
3384 /**
3385 * The **`withCredentials`** read-only property of the EventSource interface returns a boolean value indicating whether the EventSource object was instantiated with CORS credentials set.
3386 *
3387 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
3388 */
3389 get withCredentials(): boolean;
3390 /**
3391 * The **`readyState`** read-only property of the EventSource interface returns a number representing the state of the connection.
3392 *
3393 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
3394 */
3395 get readyState(): number;
3396 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
3397 get onopen(): any | null;
3398 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
3399 set onopen(value: any | null);
3400 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
3401 get onmessage(): any | null;
3402 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
3403 set onmessage(value: any | null);
3404 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
3405 get onerror(): any | null;
3406 /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
3407 set onerror(value: any | null);
3408 static readonly CONNECTING: number;
3409 static readonly OPEN: number;
3410 static readonly CLOSED: number;
3411 static from(stream: ReadableStream): EventSource;
3412}
3413interface EventSourceEventSourceInit {
3414 withCredentials?: boolean;
3415 fetcher?: Fetcher;
3416}
3417interface ExecOutput {
3418 readonly stdout: ArrayBuffer;
3419 readonly stderr: ArrayBuffer;
3420 readonly exitCode: number;
3421}
3422interface ContainerExecOptions {
3423 cwd?: string;
3424 env?: Record<string, string>;
3425 user?: string;
3426 signal?: AbortSignal;
3427 pty?: boolean | ContainerExecPtyOptions;
3428 stdin?: ReadableStream | "pipe";
3429 stdout?: "pipe" | "ignore";
3430 stderr?: "pipe" | "ignore" | "combined";
3431}
3432interface ContainerExecPtyOptions {
3433 cols?: number;
3434 rows?: number;
3435}
3436interface ExecProcess {
3437 readonly stdin: WritableStream | null;
3438 readonly stdout: ReadableStream | null;
3439 readonly stderr: ReadableStream | null;
3440 readonly pid: number;
3441 readonly isPty: boolean;
3442 readonly exitCode: Promise<number>;
3443 output(): Promise<ExecOutput>;
3444 kill(signal?: number): void;
3445 resize(cols: number, rows: number): void;
3446}
3447interface Container {
3448 get running(): boolean;
3449 get images(): Record<string, string>;
3450 start(options?: ContainerStartupOptions): void;
3451 monitor(): Promise<void>;
3452 destroy(error?: any): Promise<void>;
3453 signal(signo: number): void;
3454 getTcpPort(port: number): Fetcher;
3455 setInactivityTimeout(durationMs: number | bigint): Promise<void>;
3456 interceptOutboundHttp(addr: string, binding: Fetcher): Promise<void>;
3457 interceptAllOutboundHttp(binding: Fetcher): Promise<void>;
3458 snapshotContainer(options?: ContainerSnapshotOptions): Promise<ContainerSnapshot>;
3459 interceptOutboundHttps(addr: string, binding: Fetcher): Promise<void>;
3460 exec(cmd: string[], options?: ContainerExecOptions): Promise<ExecProcess>;
3461 inspect(): Promise<ContainerInfo | null>;
3462}
3463interface ContainerDirectorySnapshot {
3464 id: string;
3465 size: number;
3466 dir: string;
3467 name?: string;
3468}
3469type ContainerDirectorySnapshotRestoreParams = {
3470 snapshot: ContainerDirectorySnapshot;
3471 mountPoint?: string;
3472} | {
3473 snapshot?: undefined;
3474 mountPoint: string;
3475};
3476interface ContainerSnapshot {
3477 id: string;
3478 size: number;
3479 name?: string;
3480}
3481interface ContainerSnapshotRestoreParams {
3482 id: string;
3483}
3484interface ContainerSnapshotOptions {
3485 name?: string;
3486}
3487type ContainerStartupOptions = {
3488 entrypoint?: string[];
3489 enableInternet: boolean;
3490 env?: Record<string, string>;
3491 instance?: "lite" | "standard-1" | "standard-2" | "standard-3" | "standard-4" | ContainerStartResources;
3492 labels?: Record<string, string>;
3493 directorySnapshots?: ContainerDirectorySnapshotRestoreParams[];
3494} & ({
3495 image: string;
3496 containerSnapshot?: never;
3497} | {
3498 image?: never;
3499 containerSnapshot?: ContainerSnapshotRestoreParams;
3500});
3501interface ContainerInfo {
3502 labels: Record<string, string>;
3503 image: string;
3504}
3505interface ContainerStartResources {
3506 vcpu: number;
3507 memoryMib: number;
3508 diskMb: number;
3509}
3510/**
3511 * 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.
3512 *
3513 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort)
3514 */
3515declare abstract class MessagePort extends EventTarget {
3516 /**
3517 * The **`postMessage()`** method of the MessagePort interface sends a message from the port, and optionally, transfers ownership of objects to other browsing contexts.
3518 *
3519 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage)
3520 */
3521 postMessage(data?: any, options?: (any[] | MessagePortPostMessageOptions)): void;
3522 /**
3523 * 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.
3524 *
3525 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close)
3526 */
3527 close(): void;
3528 /**
3529 * 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.
3530 *
3531 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start)
3532 */
3533 start(): void;
3534 get onmessage(): any | null;
3535 set onmessage(value: any | null);
3536}
3537/**
3538 * 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.
3539 *
3540 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel)
3541 */
3542declare class MessageChannel {
3543 constructor();
3544 /**
3545 * 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.
3546 *
3547 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1)
3548 */
3549 readonly port1: MessagePort;
3550 /**
3551 * 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.
3552 *
3553 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2)
3554 */
3555 readonly port2: MessagePort;
3556}
3557interface MessagePortPostMessageOptions {
3558 transfer?: any[];
3559}
3560type 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;
3561type LoopbackServiceStub<T extends Rpc.WorkerEntrypointBranded | undefined = undefined> = Fetcher<T> & (T extends CloudflareWorkersModule.WorkerEntrypoint<any, infer Props> ? (opts: {
3562 props?: Props;
3563}) => Fetcher<T> : (opts: {
3564 props?: any;
3565}) => Fetcher<T>);
3566type LoopbackDurableObjectClass<T extends Rpc.DurableObjectBranded | undefined = undefined> = DurableObjectClass<T> & (T extends CloudflareWorkersModule.DurableObject<any, infer Props> ? (opts: {
3567 props?: Props;
3568}) => DurableObjectClass<T> : (opts: {
3569 props?: any;
3570}) => DurableObjectClass<T>);
3571interface LoopbackDurableObjectNamespace extends DurableObjectNamespace {
3572}
3573interface LoopbackColoLocalActorNamespace extends ColoLocalActorNamespace {
3574}
3575interface SyncKvStorage {
3576 get<T = unknown>(key: string): T | undefined;
3577 list<T = unknown>(options?: SyncKvListOptions): Iterable<[
3578 string,
3579 T
3580 ]>;
3581 put<T>(key: string, value: T): void;
3582 delete(key: string): boolean;
3583}
3584interface SyncKvListOptions {
3585 start?: string;
3586 startAfter?: string;
3587 end?: string;
3588 prefix?: string;
3589 reverse?: boolean;
3590 limit?: number;
3591}
3592interface WorkerStub {
3593 getEntrypoint<T extends Rpc.WorkerEntrypointBranded | undefined>(name?: string, options?: WorkerStubEntrypointOptions): Fetcher<T>;
3594 getDurableObjectClass<T extends Rpc.DurableObjectBranded | undefined>(name?: string, options?: WorkerStubEntrypointOptions): DurableObjectClass<T>;
3595}
3596interface WorkerStubEntrypointOptions {
3597 props?: any;
3598 limits?: workerdResourceLimits;
3599}
3600interface WorkerLoader {
3601 get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise<WorkerLoaderWorkerCode>): WorkerStub;
3602 load(code: WorkerLoaderWorkerCode): WorkerStub;
3603}
3604interface WorkerLoaderModule {
3605 js?: string;
3606 cjs?: string;
3607 text?: string;
3608 data?: ArrayBuffer;
3609 json?: any;
3610 py?: string;
3611 wasm?: ArrayBuffer | ArrayBufferView | WebAssembly.Module;
3612}
3613interface WorkerLoaderWorkerCode {
3614 compatibilityDate: string;
3615 compatibilityFlags?: string[];
3616 allowExperimental?: boolean;
3617 limits?: workerdResourceLimits;
3618 mainModule: string;
3619 modules: Record<string, string | WebAssembly.Module | WorkerLoaderModule>;
3620 env?: any;
3621 globalOutbound?: (Fetcher | null);
3622 tails?: Fetcher[];
3623 streamingTails?: Fetcher[];
3624}
3625interface workerdResourceLimits {
3626 cpuMs?: number;
3627 subRequests?: number;
3628}
3629/**
3630* The Workers runtime supports a subset of the Performance API, used to measure timing and performance,
3631* as well as timing of subrequests and other operations.
3632*
3633* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/)
3634*/
3635declare abstract class Performance {
3636 /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */
3637 get timeOrigin(): number;
3638 /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */
3639 now(): number;
3640 /**
3641 * The **`toJSON()`** method of the Performance interface is a serializer; it returns a JSON representation of the Performance object.
3642 *
3643 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/toJSON)
3644 */
3645 toJSON(): object;
3646}
3647interface Tracing {
3648 enterSpan<T, A extends unknown[]>(name: string, callback: (span: Span, ...args: A) => T, ...args: A): T;
3649 startActiveSpan<T, A extends unknown[]>(name: string, callback: (span: Span, ...args: A) => T, ...args: A): T;
3650 startSpan(name: string): Span;
3651 getActiveSpan(): Span | undefined;
3652 Span: typeof Span;
3653}
3654declare abstract class Span {
3655 get isTraced(): boolean;
3656 setAttribute(key: string, value: boolean | number | string): this;
3657 setAttributes(attributes: Record<string, boolean | number | string | undefined>): this;
3658 recordException(exception: string | {
3659 code: string | number;
3660 name?: string;
3661 message?: string;
3662 stack?: string;
3663 } | {
3664 code?: string | number;
3665 name: string;
3666 message?: string;
3667 stack?: string;
3668 } | {
3669 code?: string | number;
3670 name?: string;
3671 message: string;
3672 stack?: string;
3673 }): void;
3674 updateName(name: string): this;
3675 setStatus(status: TracingSpanStatus): this;
3676 end(): void;
3677}
3678type TracingSpanStatusCode = "unset" | "ok" | "error";
3679interface TracingSpanStatus {
3680 code: TracingSpanStatusCode;
3681 message?: string;
3682}
3683/**
3684 * Represents the identity of a user authenticated via Cloudflare Access.
3685 * This matches the result of calling /cdn-cgi/access/get-identity.
3686 *
3687 * The exact structure of the returned object depends on the identity provider
3688 * configuration for the Access application. The fields below represent commonly
3689 * available properties, but additional provider-specific fields may be present.
3690 */
3691interface CloudflareAccessIdentity extends Record<string, unknown> {
3692 /** The user's email address, if available from the identity provider. */
3693 email?: string;
3694 /** The user's display name. */
3695 name?: string;
3696 /** The user's unique identifier. */
3697 user_uuid?: string;
3698 /** The Cloudflare account ID. */
3699 account_id?: string;
3700 /** Login timestamp (Unix epoch seconds). */
3701 iat?: number;
3702 /** The user's IP address at authentication time. */
3703 ip?: string;
3704 /** Authentication methods used (e.g., "pwd"). */
3705 amr?: string[];
3706 /** Identity provider information. */
3707 idp?: {
3708 id: string;
3709 type: string;
3710 };
3711 /** Geographic information about where the user authenticated. */
3712 geo?: {
3713 country: string;
3714 };
3715 /** Group memberships from the identity provider. */
3716 groups?: Array<{
3717 id: string;
3718 name: string;
3719 email?: string;
3720 }>;
3721 /** Device posture check results, keyed by check ID. */
3722 devicePosture?: Record<string, unknown>;
3723 /** True if the user connected via Cloudflare WARP. */
3724 is_warp?: boolean;
3725 /** True if the user is authenticated via Cloudflare Gateway. */
3726 is_gateway?: boolean;
3727}
3728// ============================================================================
3729// Agent Memory
3730//
3731// Public type surface for user Workers binding to an Agent Memory namespace.
3732// ============================================================================
3733/** Memory type — every memory is classified into exactly one. */
3734type AgentMemoryMemoryType = "fact" | "event" | "instruction" | "task";
3735/** Search intensity for recall. */
3736type AgentMemoryThinkingLevel = "low" | "medium" | "high";
3737/** Response verbosity for recall. */
3738type AgentMemoryResponseLength = "short" | "medium" | "long";
3739/** A conversation message passed to ingest(). */
3740interface AgentMemoryMessage {
3741 role: "system" | "user" | "assistant";
3742 content: string;
3743 /** Optional message timestamp. */
3744 timestamp?: Date;
3745}
3746/** Raw memory content passed to remember(). */
3747interface AgentMemoryIncomingMemory {
3748 /** Raw memory content. The service classifies and summarizes automatically. */
3749 content: string;
3750 /** Optional session identifier to associate with this memory. */
3751 sessionId?: string | null | undefined;
3752}
3753/** A stored memory returned from remember(), get(), and delete(). */
3754interface AgentMemoryMemory {
3755 /** Memory ID. */
3756 id: string;
3757 /** Memory type. */
3758 type: AgentMemoryMemoryType;
3759 /** Text summary. */
3760 summary: string;
3761 /** Memory text. */
3762 content: string;
3763 /** Session that created this memory. */
3764 sessionId: string | null;
3765 /** Memory creation time. */
3766 createdAt: Date;
3767 /** Memory last-update time. */
3768 updatedAt: Date;
3769}
3770/** Single entry in a list() response. Same shape as Memory minus full content. */
3771type AgentMemoryMemoryListEntry = Omit<AgentMemoryMemory, "content">;
3772/** A scored memory candidate in a recall result. */
3773interface AgentMemoryScoredCandidate {
3774 /** Candidate ID. */
3775 id: string;
3776 /** Text summary. */
3777 summary: string;
3778 /** Session that created this candidate, when known. */
3779 sessionId: string | null;
3780 /** Relevance score (higher is better). Comparable only within a single query. */
3781 score: number;
3782}
3783/** Options for the ingest() method. */
3784interface AgentMemoryIngestOptions {
3785 /** Session identifier to associate with memories created during ingestion. */
3786 sessionId?: string | null | undefined;
3787}
3788/** Options for the getSummary() method. */
3789interface AgentMemoryGetSummaryOptions {
3790 /** Session identifier to retrieve session summary for. */
3791 sessionId?: string | null | undefined;
3792}
3793/** Response from the getSummary() method. */
3794interface AgentMemoryGetSummaryResponse {
3795 /** Markdown summary. */
3796 summary: string;
3797}
3798/**
3799 * Options for the recall() method.
3800 *
3801 * `referenceDate` accepts a Date object, an ISO-8601 date string
3802 * (YYYY-MM-DD), or a full ISO-8601 datetime string. When provided, this
3803 * date is used as "today" for resolving relative time references
3804 * ("how many days ago", "last week") instead of the server's wall-clock time.
3805 */
3806interface AgentMemoryRecallOptions {
3807 /** Recall intensity: "low" (default), "medium", or "high". */
3808 thinkingLevel?: AgentMemoryThinkingLevel;
3809 /** Response verbosity: "short", "medium" (default), or "long". */
3810 responseLength?: AgentMemoryResponseLength;
3811 /** Temporal anchor for date arithmetic. */
3812 referenceDate?: Date | string;
3813}
3814/** Response from the recall() method. */
3815interface AgentMemoryRecallResult {
3816 /** Number of memories retrieved. */
3817 count: number;
3818 /** LLM-generated answer synthesizing the matching memories. */
3819 answer: string;
3820 /** Matching memories ranked by relevance. */
3821 candidates: AgentMemoryScoredCandidate[];
3822}
3823/**
3824 * Options for the list() method.
3825 *
3826 * `cursor` is the opaque continuation token returned by the previous page;
3827 * pass it back unchanged to fetch the next page. `sessionId` and `type`
3828 * are exact-match filters; combining them is allowed.
3829 */
3830interface AgentMemoryListMemoriesOptions {
3831 /** Maximum number of memories to return. Default 20, max 500. */
3832 limit?: number;
3833 /** Opaque cursor from a previous page. */
3834 cursor?: string;
3835 /** Exact-match session filter. */
3836 sessionId?: string;
3837 /** Exact-match memory-type filter. */
3838 type?: AgentMemoryMemoryType;
3839}
3840/** Response from the list() method. */
3841interface AgentMemoryListMemoriesResult {
3842 memories: AgentMemoryMemoryListEntry[];
3843 /** Continuation cursor; absent when this page exhausted the result set. */
3844 cursor?: string;
3845}
3846/**
3847 * A single Agent Memory profile, scoped to a profile name.
3848 *
3849 * Returned by {@link AgentMemoryNamespace.getProfile}.
3850 */
3851declare abstract class AgentMemoryProfile {
3852 /**
3853 * Retrieve a memory by ID.
3854 *
3855 * @param memoryId - ULID of the memory to retrieve.
3856 * @throws if the memory does not exist.
3857 */
3858 get(memoryId: string): Promise<AgentMemoryMemory>;
3859 /**
3860 * Delete a memory by ID.
3861 *
3862 * Removes the memory and any source messages linked by the memory's
3863 * source message IDs.
3864 *
3865 * @param memoryId - ULID of the memory to delete.
3866 * @throws if the memory does not exist.
3867 */
3868 delete(memoryId: string): Promise<AgentMemoryMemory>;
3869 /**
3870 * Store a memory in this profile. The content is automatically classified,
3871 * summarized, and indexed.
3872 *
3873 * @param memory - Raw memory content to persist.
3874 */
3875 remember(memory: AgentMemoryIncomingMemory): Promise<AgentMemoryMemory>;
3876 /**
3877 * Extract memories from a conversation.
3878 *
3879 * @param messages - Conversation messages to extract memories from.
3880 * @param options - Optional ingest options.
3881 */
3882 ingest(messages: Iterable<AgentMemoryMessage>, options?: AgentMemoryIngestOptions): Promise<void>;
3883 /**
3884 * Get a profile summary.
3885 *
3886 * @param options - Optional getSummary options.
3887 */
3888 getSummary(options?: AgentMemoryGetSummaryOptions): Promise<AgentMemoryGetSummaryResponse>;
3889 /**
3890 * Recall memories in this profile.
3891 *
3892 * @param query - Recall query matched against memory content and keywords.
3893 * @param options - Optional recall parameters.
3894 * @returns Matching memories with relevance scores and a synthesized answer.
3895 */
3896 recall(query: string, options?: AgentMemoryRecallOptions): Promise<AgentMemoryRecallResult>;
3897 /**
3898 * List active memories in this profile.
3899 *
3900 * Returns a paginated, filterable view of stored memories. Superseded
3901 * versions are excluded. Use the returned `cursor` (when present) to
3902 * fetch the next page.
3903 *
3904 * @param options - Optional pagination and filter options.
3905 */
3906 list(options?: AgentMemoryListMemoriesOptions): Promise<AgentMemoryListMemoriesResult>;
3907 /**
3908 * Soft-delete every memory and message in this profile that is tagged
3909 * with `sessionId`.
3910 *
3911 * Idempotent: deleting a sessionId that has no rows is a no-op.
3912 *
3913 * @param sessionId - Session to delete.
3914 */
3915 deleteSession(sessionId: string): Promise<void>;
3916}
3917/**
3918 * Namespace-level Agent Memory binding.
3919 *
3920 * Used as the type of an `env.MEMORY`-style binding backed by the Agent
3921 * Memory product.
3922 *
3923 * @example
3924 * ```ts
3925 * export default {
3926 * async fetch(_request: Request, env: Env): Promise<Response> {
3927 * const profile = await env.MEMORY.getProfile("wrangler-e2e");
3928 * const summary = await profile.getSummary();
3929 * return Response.json(summary);
3930 * },
3931 * };
3932 * ```
3933 */
3934declare abstract class AgentMemoryNamespace {
3935 /**
3936 * Get a memory profile by name. Profiles are isolated by namespace and
3937 * addressed by a compound key (namespaceId:profileName).
3938 *
3939 * @param profileName - Profile name (validated against naming rules).
3940 * @returns RPC target for interacting with the profile.
3941 */
3942 getProfile(profileName: string): Promise<AgentMemoryProfile>;
3943 /**
3944 * Soft-delete a profile and schedule deferred purge. Marks all
3945 * memories and messages as deleted.
3946 *
3947 * @param profileName - Name of the profile to delete.
3948 */
3949 deleteProfile(profileName: string): Promise<void>;
3950}
3951// ============ AI Search Error Interfaces ============
3952interface AiSearchInternalError extends Error {
3953}
3954interface AiSearchNotFoundError extends Error {
3955}
3956// ============ AI Search Common Types ============
3957/** A single message in a conversation-style search or chat request. */
3958type AiSearchMessage = {
3959 role: 'system' | 'developer' | 'user' | 'assistant' | 'tool';
3960 content: string | null;
3961};
3962/**
3963 * Common shape for `ai_search_options` used by both single-instance and multi-instance requests.
3964 * Contains retrieval, query rewrite, reranking, and cache sub-options.
3965 */
3966type AiSearchOptions = {
3967 retrieval?: {
3968 /** Which retrieval backend to use. Defaults to the instance's configured index_method. */
3969 retrieval_type?: 'vector' | 'keyword' | 'hybrid';
3970 /** Fusion method for combining vector + keyword results. */
3971 fusion_method?: 'max' | 'rrf';
3972 /** How keyword terms are combined: "and" = all terms must match, "or" = any term matches. */
3973 keyword_match_mode?: 'and' | 'or';
3974 /** Minimum similarity score (0-1) for a result to be included. Default 0.4. */
3975 match_threshold?: number;
3976 /** Maximum number of results to return (1-50). Default 10. */
3977 max_num_results?: number;
3978 /** Vectorize metadata filters applied to the search. */
3979 filters?: VectorizeVectorMetadataFilter;
3980 /** Number of surrounding chunks to include for context (0-3). Default 0. */
3981 context_expansion?: number;
3982 /** If true, return only item metadata without chunk text. */
3983 metadata_only?: boolean;
3984 /** If true (default), return empty results on retrieval failure instead of throwing. */
3985 return_on_failure?: boolean;
3986 /** Boost results by metadata field values. Max 3 entries. */
3987 boost_by?: Array<{
3988 field: string;
3989 direction?: 'asc' | 'desc' | 'exists' | 'not_exists';
3990 }>;
3991 [key: string]: unknown;
3992 };
3993 query_rewrite?: {
3994 enabled?: boolean;
3995 model?: string;
3996 rewrite_prompt?: string;
3997 [key: string]: unknown;
3998 };
3999 reranking?: {
4000 enabled?: boolean;
4001 model?: string;
4002 /** Match threshold (0-1, default 0.4) */
4003 match_threshold?: number;
4004 [key: string]: unknown;
4005 };
4006 cache?: {
4007 enabled?: boolean;
4008 cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes';
4009 };
4010 [key: string]: unknown;
4011};
4012// ============ AI Search Request Types ============
4013/**
4014 * Request body for single-instance search.
4015 * Exactly one of `query` or `messages` must be provided.
4016 */
4017type AiSearchSearchRequest = {
4018 /** Simple query string. */
4019 query: string;
4020 messages?: never;
4021 ai_search_options?: AiSearchOptions;
4022} | {
4023 query?: never;
4024 /** Conversation-style input. At least one user message with non-empty content is required. */
4025 messages: AiSearchMessage[];
4026 ai_search_options?: AiSearchOptions;
4027};
4028type AiSearchChatCompletionsRequest = {
4029 messages: AiSearchMessage[];
4030 model?: string;
4031 stream?: boolean;
4032 ai_search_options?: AiSearchOptions;
4033 [key: string]: unknown;
4034};
4035// ============ AI Search Multi-Instance Types (Namespace-Scoped) ============
4036/** `ai_search_options` shape for multi-instance requests — requires `instance_ids`. */
4037type AiSearchMultiSearchOptions = AiSearchOptions & {
4038 /** Instance IDs to search across (1-10). */
4039 instance_ids: string[];
4040};
4041/**
4042 * Request for searching across multiple instances within a namespace.
4043 * `ai_search_options` is required and must include `instance_ids`.
4044 * Exactly one of `query` or `messages` must be provided.
4045 */
4046type AiSearchMultiSearchRequest = {
4047 /** Simple query string. */
4048 query: string;
4049 messages?: never;
4050 ai_search_options: AiSearchMultiSearchOptions;
4051} | {
4052 query?: never;
4053 /** Conversation-style input. */
4054 messages: AiSearchMessage[];
4055 ai_search_options: AiSearchMultiSearchOptions;
4056};
4057/** A search result chunk tagged with the instance it originated from. */
4058type AiSearchMultiSearchChunk = AiSearchSearchResponse['chunks'][number] & {
4059 instance_id: string;
4060};
4061/** Describes a per-instance error during a multi-instance operation. */
4062type AiSearchMultiSearchError = {
4063 instance_id: string;
4064 message: string;
4065};
4066/** Response from a multi-instance search, with chunks tagged by instance and optional partial-failure errors. */
4067type AiSearchMultiSearchResponse = {
4068 search_query: string;
4069 chunks: AiSearchMultiSearchChunk[];
4070 errors?: AiSearchMultiSearchError[];
4071};
4072/** Request for chat completions across multiple instances within a namespace. `ai_search_options` is required and must include `instance_ids`. */
4073type AiSearchMultiChatCompletionsRequest = Omit<AiSearchChatCompletionsRequest, 'ai_search_options'> & {
4074 ai_search_options: AiSearchMultiSearchOptions;
4075};
4076/** Response from multi-instance chat completions, with chunks tagged by instance and optional partial-failure errors. */
4077type AiSearchMultiChatCompletionsResponse = Omit<AiSearchChatCompletionsResponse, 'chunks'> & {
4078 chunks: AiSearchMultiSearchChunk[];
4079 errors?: AiSearchMultiSearchError[];
4080};
4081// ============ AI Search Response Types ============
4082type AiSearchSearchResponse = {
4083 search_query: string;
4084 chunks: Array<{
4085 id: string;
4086 type: string;
4087 /** Match score (0-1) */
4088 score: number;
4089 text: string;
4090 item: {
4091 timestamp?: number;
4092 key: string;
4093 metadata?: Record<string, unknown>;
4094 };
4095 scoring_details?: {
4096 /** Keyword match score (0-1) */
4097 keyword_score?: number;
4098 /** Vector similarity score (0-1) */
4099 vector_score?: number;
4100 /** Keyword rank position */
4101 keyword_rank?: number;
4102 /** Vector rank position */
4103 vector_rank?: number;
4104 /** Reranking model score */
4105 reranking_score?: number;
4106 /** Fusion method used to combine results */
4107 fusion_method?: 'rrf' | 'max';
4108 [key: string]: unknown;
4109 };
4110 }>;
4111};
4112type AiSearchChatCompletionsResponse = {
4113 id?: string;
4114 object?: string;
4115 model?: string;
4116 choices: Array<{
4117 index?: number;
4118 message: {
4119 role: 'system' | 'developer' | 'user' | 'assistant' | 'tool';
4120 content: string | null;
4121 [key: string]: unknown;
4122 };
4123 [key: string]: unknown;
4124 }>;
4125 chunks: AiSearchSearchResponse['chunks'];
4126 [key: string]: unknown;
4127};
4128type AiSearchStatsResponse = {
4129 queued?: number;
4130 running?: number;
4131 completed?: number;
4132 error?: number;
4133 skipped?: number;
4134 outdated?: number;
4135 last_activity?: string;
4136 /** Storage engine statistics. */
4137 engine?: {
4138 vectorize?: {
4139 vectorsCount: number;
4140 dimensions: number;
4141 };
4142 r2?: {
4143 payloadSizeBytes: number;
4144 metadataSizeBytes: number;
4145 objectCount: number;
4146 };
4147 };
4148};
4149// ============ AI Search Instance Info Types ============
4150type AiSearchInstanceInfo = {
4151 id: string;
4152 type?: 'r2' | 'web-crawler' | string;
4153 source?: string;
4154 source_params?: unknown;
4155 paused?: boolean;
4156 status?: string;
4157 namespace?: string;
4158 created_at?: string;
4159 modified_at?: string;
4160 token_id?: string;
4161 ai_gateway_id?: string;
4162 rewrite_query?: boolean;
4163 reranking?: boolean;
4164 embedding_model?: string;
4165 ai_search_model?: string;
4166 rewrite_model?: string;
4167 reranking_model?: string;
4168 /** @deprecated Use index_method instead. */
4169 hybrid_search_enabled?: boolean;
4170 /** Controls which storage backends are active. */
4171 index_method?: {
4172 vector?: boolean;
4173 keyword?: boolean;
4174 };
4175 /** Fusion method for combining vector and keyword results. */
4176 fusion_method?: 'max' | 'rrf';
4177 indexing_options?: {
4178 keyword_tokenizer?: 'porter' | 'trigram';
4179 } | null;
4180 retrieval_options?: {
4181 keyword_match_mode?: 'and' | 'or';
4182 boost_by?: Array<{
4183 field: string;
4184 direction?: 'asc' | 'desc' | 'exists' | 'not_exists';
4185 }>;
4186 } | null;
4187 chunk?: boolean;
4188 chunk_size?: number;
4189 chunk_overlap?: number;
4190 score_threshold?: number;
4191 max_num_results?: number;
4192 cache?: boolean;
4193 cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes';
4194 custom_metadata?: Array<{
4195 field_name: string;
4196 data_type: 'text' | 'number' | 'boolean' | 'datetime';
4197 }>;
4198 /** Sync interval in seconds. */
4199 sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400;
4200 metadata?: Record<string, unknown>;
4201 [key: string]: unknown;
4202};
4203/** Pagination, search, and ordering parameters for listing instances within a namespace. */
4204type AiSearchListInstancesParams = {
4205 page?: number;
4206 per_page?: number;
4207 /** Search instances by ID. */
4208 search?: string;
4209 /** Field to sort by. */
4210 order_by?: 'created_at';
4211 /** Sort direction. */
4212 order_by_direction?: 'asc' | 'desc';
4213};
4214type AiSearchListResponse = {
4215 result: AiSearchInstanceInfo[];
4216 result_info?: {
4217 count: number;
4218 page: number;
4219 per_page: number;
4220 total_count: number;
4221 };
4222};
4223// ============ AI Search Config Types ============
4224type AiSearchConfig = {
4225 /** Instance ID (1-32 chars, pattern: ^[a-z0-9_]+(?:-[a-z0-9_]+)*$) */
4226 id: string;
4227 /** Instance type. Omit to create with built-in storage. */
4228 type?: 'r2' | 'web-crawler' | string;
4229 /** Source URL (required for web-crawler type). */
4230 source?: string;
4231 source_params?: unknown;
4232 /** Token ID (UUID format) */
4233 token_id?: string;
4234 ai_gateway_id?: string;
4235 /** Enable query rewriting (default false) */
4236 rewrite_query?: boolean;
4237 /** Enable reranking (default false) */
4238 reranking?: boolean;
4239 embedding_model?: string;
4240 ai_search_model?: string;
4241 rewrite_model?: string;
4242 reranking_model?: string;
4243 /** @deprecated Use index_method instead. */
4244 hybrid_search_enabled?: boolean;
4245 /** Controls which storage backends are used during indexing. Defaults to vector-only. */
4246 index_method?: {
4247 vector?: boolean;
4248 keyword?: boolean;
4249 };
4250 /** Fusion method for combining vector and keyword results. "rrf" = reciprocal rank fusion (default), "max" = maximum score. */
4251 fusion_method?: 'max' | 'rrf';
4252 indexing_options?: {
4253 keyword_tokenizer?: 'porter' | 'trigram';
4254 } | null;
4255 retrieval_options?: {
4256 keyword_match_mode?: 'and' | 'or';
4257 boost_by?: Array<{
4258 field: string;
4259 direction?: 'asc' | 'desc' | 'exists' | 'not_exists';
4260 }>;
4261 } | null;
4262 chunk?: boolean;
4263 chunk_size?: number;
4264 chunk_overlap?: number;
4265 /** Minimum similarity score (0-1) for a result to be included. */
4266 score_threshold?: number;
4267 max_num_results?: number;
4268 cache?: boolean;
4269 /** Similarity threshold for cache hits. Stricter = fewer cache hits but higher relevance. */
4270 cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes';
4271 custom_metadata?: Array<{
4272 field_name: string;
4273 data_type: 'text' | 'number' | 'boolean' | 'datetime';
4274 }>;
4275 namespace?: string;
4276 /** Sync interval in seconds. 3600=1h, 7200=2h, 14400=4h, 21600=6h, 43200=12h, 86400=24h. */
4277 sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400;
4278 metadata?: Record<string, unknown>;
4279 [key: string]: unknown;
4280};
4281// ============ AI Search Item Types ============
4282type AiSearchItemInfo = {
4283 id: string;
4284 key: string;
4285 status: 'completed' | 'error' | 'skipped' | 'queued' | 'running' | 'outdated';
4286 next_action?: 'INDEX' | 'DELETE' | null;
4287 error?: string;
4288 checksum?: string;
4289 namespace?: string;
4290 chunks_count?: number | null;
4291 file_size?: number | null;
4292 source_id?: string | null;
4293 last_seen_at?: string;
4294 created_at?: string;
4295 metadata?: Record<string, unknown>;
4296 [key: string]: unknown;
4297};
4298type AiSearchItemContentResult = {
4299 body: ReadableStream;
4300 contentType: string;
4301 filename: string;
4302 size: number;
4303};
4304type AiSearchUploadItemOptions = {
4305 metadata?: Record<string, unknown>;
4306};
4307type AiSearchListItemsParams = {
4308 page?: number;
4309 per_page?: number;
4310 /** Search items by key name. */
4311 search?: string;
4312 /** Sort order for results. */
4313 sort_by?: 'status' | 'modified_at';
4314 /** Filter items by processing status. */
4315 status?: 'queued' | 'running' | 'completed' | 'error' | 'skipped' | 'outdated';
4316 /** Filter items by source (e.g. "builtin" or "web-crawler:https://example.com"). */
4317 source?: string;
4318 /** JSON-encoded Vectorize filter for metadata filtering. */
4319 metadata_filter?: string;
4320 /** Filter items by their unique ID. Returns at most one item. */
4321 item_id?: string;
4322 /**
4323 * Filter items by their exact key (object key / filename). Keys are unique
4324 * per source, so combine with `source` to disambiguate across data sources.
4325 */
4326 key?: string;
4327};
4328type AiSearchListItemsResponse = {
4329 result: AiSearchItemInfo[];
4330 result_info?: {
4331 count: number;
4332 page: number;
4333 per_page: number;
4334 total_count: number;
4335 };
4336};
4337// ============ AI Search Item Logs Types ============
4338type AiSearchItemLogsParams = {
4339 /** Maximum number of log entries to return (1-100, default 50). */
4340 limit?: number;
4341 /** Opaque cursor for pagination. Pass the `cursor` value from a previous response. */
4342 cursor?: string;
4343};
4344type AiSearchItemLog = {
4345 timestamp: string;
4346 action: string;
4347 message: string;
4348 fileKey?: string;
4349 chunkCount?: number;
4350 processingTimeMs?: number;
4351 errorType?: string;
4352};
4353/** Paginated response for item processing logs (cursor-based). */
4354type AiSearchItemLogsResponse = {
4355 result: AiSearchItemLog[];
4356 result_info: {
4357 count: number;
4358 per_page: number;
4359 cursor: string | null;
4360 truncated: boolean;
4361 };
4362};
4363// ============ AI Search Item Chunks Types ============
4364type AiSearchItemChunksParams = {
4365 /** Maximum number of chunks to return (1-100, default 20). */
4366 limit?: number;
4367 /** Offset into the chunks list (default 0). */
4368 offset?: number;
4369};
4370/** A single indexed chunk belonging to an item, including its text content and byte range. */
4371type AiSearchItemChunk = {
4372 id: string;
4373 text: string;
4374 start_byte: number;
4375 end_byte: number;
4376 item?: {
4377 timestamp?: number;
4378 key: string;
4379 metadata?: Record<string, unknown>;
4380 };
4381};
4382/** Paginated response for item chunks (offset-based). */
4383type AiSearchItemChunksResponse = {
4384 result: AiSearchItemChunk[];
4385 result_info: {
4386 count: number;
4387 total: number;
4388 limit: number;
4389 offset: number;
4390 };
4391};
4392// ============ AI Search Job Types ============
4393type AiSearchJobInfo = {
4394 id: string;
4395 source: 'user' | 'schedule';
4396 description?: string;
4397 last_seen_at?: string;
4398 started_at?: string;
4399 ended_at?: string;
4400 end_reason?: string;
4401};
4402type AiSearchJobLog = {
4403 id: number;
4404 message: string;
4405 message_type: number;
4406 created_at: number;
4407};
4408type AiSearchCreateJobParams = {
4409 description?: string;
4410};
4411type AiSearchListJobsParams = {
4412 page?: number;
4413 per_page?: number;
4414};
4415type AiSearchListJobsResponse = {
4416 result: AiSearchJobInfo[];
4417 result_info?: {
4418 count: number;
4419 page: number;
4420 per_page: number;
4421 total_count: number;
4422 };
4423};
4424type AiSearchJobLogsParams = {
4425 page?: number;
4426 per_page?: number;
4427};
4428type AiSearchJobLogsResponse = {
4429 result: AiSearchJobLog[];
4430 result_info?: {
4431 count: number;
4432 page: number;
4433 per_page: number;
4434 total_count: number;
4435 };
4436};
4437// ============ AI Search Sub-Service Classes ============
4438/**
4439 * Single item service for an AI Search instance.
4440 * Provides info, download, sync, logs, and chunks operations on a specific item.
4441 */
4442declare abstract class AiSearchItem {
4443 /** Get metadata about this item. */
4444 info(): Promise<AiSearchItemInfo>;
4445 /**
4446 * Download the item's content.
4447 * @returns Object with body stream, content type, filename, and size.
4448 */
4449 download(): Promise<AiSearchItemContentResult>;
4450 /**
4451 * Trigger re-indexing of this item.
4452 * @returns The updated item info.
4453 */
4454 sync(): Promise<AiSearchItemInfo>;
4455 /**
4456 * Retrieve processing logs for this item (cursor-based pagination).
4457 * @param params Optional pagination parameters (limit, cursor).
4458 * @returns Paginated log entries for this item.
4459 */
4460 logs(params?: AiSearchItemLogsParams): Promise<AiSearchItemLogsResponse>;
4461 /**
4462 * List indexed chunks for this item (offset-based pagination).
4463 * @param params Optional pagination parameters (limit, offset).
4464 * @returns Paginated chunk entries for this item.
4465 */
4466 chunks(params?: AiSearchItemChunksParams): Promise<AiSearchItemChunksResponse>;
4467}
4468/**
4469 * Items collection service for an AI Search instance.
4470 * Provides list, upload, and access to individual items.
4471 */
4472declare abstract class AiSearchItems {
4473 /** List items in this instance. */
4474 list(params?: AiSearchListItemsParams): Promise<AiSearchListItemsResponse>;
4475 /**
4476 * Upload a file as an item. Behaves as an upsert: if an item with the same
4477 * filename already exists, it is overwritten and re-indexed.
4478 * @param name Filename for the uploaded item.
4479 * @param content File content as a ReadableStream, Blob, or string.
4480 * @param options Optional metadata to attach to the item.
4481 * @returns The created item info.
4482 */
4483 upload(name: string, content: ReadableStream | Blob | string, options?: AiSearchUploadItemOptions): Promise<AiSearchItemInfo>;
4484 /**
4485 * Upload a file and poll until processing completes.
4486 * Behaves as an upsert: if an item with the same filename already exists,
4487 * it is overwritten and re-indexed.
4488 * @param name Filename for the uploaded item.
4489 * @param content File content as a ReadableStream, Blob, or string.
4490 * @param options Optional metadata and polling configuration.
4491 * @returns The item info after processing completes (or timeout).
4492 */
4493 uploadAndPoll(name: string, content: ReadableStream | Blob | string, options?: AiSearchUploadItemOptions & {
4494 /** Polling interval in milliseconds (default 1000). */
4495 pollIntervalMs?: number;
4496 /** Maximum time to wait in milliseconds (default 30000). */
4497 timeoutMs?: number;
4498 }): Promise<AiSearchItemInfo>;
4499 /**
4500 * Get an item by ID.
4501 * @param itemId The item identifier.
4502 * @returns Item service for info, download, sync, logs, and chunks operations.
4503 */
4504 get(itemId: string): AiSearchItem;
4505 /**
4506 * Delete an item from the instance.
4507 * @param itemId The item identifier.
4508 */
4509 delete(itemId: string): Promise<void>;
4510}
4511/**
4512 * Single job service for an AI Search instance.
4513 * Provides info, logs, and cancel operations for a specific job.
4514 */
4515declare abstract class AiSearchJob {
4516 /** Get metadata about this job. */
4517 info(): Promise<AiSearchJobInfo>;
4518 /** Get logs for this job. */
4519 logs(params?: AiSearchJobLogsParams): Promise<AiSearchJobLogsResponse>;
4520 /**
4521 * Cancel a running job.
4522 * @returns The updated job info.
4523 * @throws AiSearchNotFoundError if the job does not exist.
4524 */
4525 cancel(): Promise<AiSearchJobInfo>;
4526}
4527/**
4528 * Jobs collection service for an AI Search instance.
4529 * Provides list, create, and access to individual jobs.
4530 */
4531declare abstract class AiSearchJobs {
4532 /** List jobs for this instance. */
4533 list(params?: AiSearchListJobsParams): Promise<AiSearchListJobsResponse>;
4534 /**
4535 * Create a new indexing job.
4536 * @param params Optional job parameters.
4537 * @returns The created job info.
4538 */
4539 create(params?: AiSearchCreateJobParams): Promise<AiSearchJobInfo>;
4540 /**
4541 * Get a job by ID.
4542 * @param jobId The job identifier.
4543 * @returns Job service for info, logs, and cancel operations.
4544 */
4545 get(jobId: string): AiSearchJob;
4546}
4547// ============ AI Search Binding Classes ============
4548/**
4549 * Instance-level AI Search service.
4550 *
4551 * Used as:
4552 * - The return type of `AiSearchNamespace.get(name)` (namespace binding)
4553 * - The type of `env.BLOG_SEARCH` (single instance binding via `ai_search`)
4554 *
4555 * Provides search, chat, update, stats, items, and jobs operations.
4556 *
4557 * @example
4558 * ```ts
4559 * // Via namespace binding
4560 * const instance = env.AI_SEARCH.get("blog");
4561 * const results = await instance.search({
4562 * query: "How does caching work?",
4563 * });
4564 *
4565 * // Via single instance binding
4566 * const results = await env.BLOG_SEARCH.search({
4567 * messages: [{ role: "user", content: "How does caching work?" }],
4568 * });
4569 * ```
4570 */
4571declare abstract class AiSearchInstance {
4572 /**
4573 * Search the AI Search instance for relevant chunks.
4574 * @param params Search request with query or messages and optional AI search options.
4575 * @returns Search response with matching chunks and search query.
4576 */
4577 search(params: AiSearchSearchRequest): Promise<AiSearchSearchResponse>;
4578 /**
4579 * Generate chat completions with AI Search context (streaming).
4580 * @param params Chat completions request with stream: true.
4581 * @returns ReadableStream of server-sent events.
4582 */
4583 chatCompletions(params: AiSearchChatCompletionsRequest & {
4584 stream: true;
4585 }): Promise<ReadableStream>;
4586 /**
4587 * Generate chat completions with AI Search context.
4588 * @param params Chat completions request.
4589 * @returns Chat completion response with choices and RAG chunks.
4590 */
4591 chatCompletions(params: AiSearchChatCompletionsRequest): Promise<AiSearchChatCompletionsResponse>;
4592 /**
4593 * Update the instance configuration.
4594 * @param config Partial configuration to update.
4595 * @returns Updated instance info.
4596 */
4597 update(config: Partial<AiSearchConfig>): Promise<AiSearchInstanceInfo>;
4598 /** Get metadata about this instance. */
4599 info(): Promise<AiSearchInstanceInfo>;
4600 /**
4601 * Get instance statistics (item count, indexing status, etc.).
4602 * @returns Statistics with counts per status, last activity time, and engine details.
4603 */
4604 stats(): Promise<AiSearchStatsResponse>;
4605 /** Items collection — list, upload, and manage items in this instance. */
4606 get items(): AiSearchItems;
4607 /** Jobs collection — list, create, and inspect indexing jobs. */
4608 get jobs(): AiSearchJobs;
4609}
4610/**
4611 * Namespace-level AI Search service.
4612 *
4613 * Used as the type of `env.AI_SEARCH` (namespace binding via `ai_search_namespaces`).
4614 * Scoped to a single namespace. Provides dynamic instance access, creation, deletion,
4615 * and multi-instance search/chat operations.
4616 *
4617 * @example
4618 * ```ts
4619 * // Access an instance within the namespace
4620 * const blog = env.AI_SEARCH.get("blog");
4621 * const results = await blog.search({ query: "How does caching work?" });
4622 *
4623 * // List all instances in the namespace
4624 * const instances = await env.AI_SEARCH.list();
4625 *
4626 * // Create a new instance with built-in storage
4627 * const tenant = await env.AI_SEARCH.create({ id: "tenant-123" });
4628 *
4629 * // Upload items into the instance
4630 * await tenant.items.upload("doc.pdf", fileContent);
4631 *
4632 * // Search across multiple instances
4633 * const multi = await env.AI_SEARCH.search({
4634 * query: "caching",
4635 * ai_search_options: { instance_ids: ["blog", "docs"] },
4636 * });
4637 *
4638 * // Delete an instance
4639 * await env.AI_SEARCH.delete("tenant-123");
4640 * ```
4641 */
4642declare abstract class AiSearchNamespace {
4643 /**
4644 * Get an instance by name within the bound namespace.
4645 * @param name Instance name.
4646 * @returns Instance service for search, chat, update, stats, items, and jobs.
4647 */
4648 get(name: string): AiSearchInstance;
4649 /**
4650 * List instances in the bound namespace.
4651 * @param params Optional pagination, search, and ordering parameters.
4652 * @returns Array of instance metadata with pagination info.
4653 */
4654 list(params?: AiSearchListInstancesParams): Promise<AiSearchListResponse>;
4655 /**
4656 * Create a new instance within the bound namespace.
4657 * @param config Instance configuration. Only `id` is required — omit `type` and `source` to create with built-in storage.
4658 * @returns Instance service for the newly created instance.
4659 *
4660 * @example
4661 * ```ts
4662 * // Create with built-in storage (upload items manually)
4663 * const instance = await env.AI_SEARCH.create({ id: "my-search" });
4664 *
4665 * // Create with web crawler source
4666 * const instance = await env.AI_SEARCH.create({
4667 * id: "docs-search",
4668 * type: "web-crawler",
4669 * source: "https://developers.cloudflare.com",
4670 * });
4671 * ```
4672 */
4673 create(config: AiSearchConfig): Promise<AiSearchInstance>;
4674 /**
4675 * Delete an instance from the bound namespace.
4676 * @param name Instance name to delete.
4677 */
4678 delete(name: string): Promise<void>;
4679 /**
4680 * Search across multiple instances within the bound namespace.
4681 * Fans out to the specified instance_ids and merges results.
4682 * @param params Search request with required `ai_search_options.instance_ids`.
4683 * @returns Search response with chunks tagged by instance_id and optional partial-failure errors.
4684 */
4685 search(params: AiSearchMultiSearchRequest): Promise<AiSearchMultiSearchResponse>;
4686 /**
4687 * Generate chat completions across multiple instances within the bound namespace (streaming).
4688 * Fans out to the specified instance_ids, merges context, and generates a response.
4689 * @param params Chat completions request with stream: true and required `ai_search_options.instance_ids`.
4690 * @returns ReadableStream of server-sent events.
4691 */
4692 chatCompletions(params: AiSearchMultiChatCompletionsRequest & {
4693 stream: true;
4694 }): Promise<ReadableStream>;
4695 /**
4696 * Generate chat completions across multiple instances within the bound namespace.
4697 * Fans out to the specified instance_ids, merges context, and generates a response.
4698 * @param params Chat completions request with required `ai_search_options.instance_ids`.
4699 * @returns Chat completion response with choices, chunks tagged by instance_id, and optional partial-failure errors.
4700 */
4701 chatCompletions(params: AiSearchMultiChatCompletionsRequest): Promise<AiSearchMultiChatCompletionsResponse>;
4702}
4703type AiImageClassificationInput = {
4704 image: number[];
4705};
4706type AiImageClassificationOutput = {
4707 score?: number;
4708 label?: string;
4709}[];
4710declare abstract class BaseAiImageClassification {
4711 inputs: AiImageClassificationInput;
4712 postProcessedOutputs: AiImageClassificationOutput;
4713}
4714type AiImageToTextInput = {
4715 image: number[];
4716 prompt?: string;
4717 max_tokens?: number;
4718 temperature?: number;
4719 top_p?: number;
4720 top_k?: number;
4721 seed?: number;
4722 repetition_penalty?: number;
4723 frequency_penalty?: number;
4724 presence_penalty?: number;
4725 raw?: boolean;
4726 messages?: RoleScopedChatInput[];
4727};
4728type AiImageToTextOutput = {
4729 description: string;
4730};
4731declare abstract class BaseAiImageToText {
4732 inputs: AiImageToTextInput;
4733 postProcessedOutputs: AiImageToTextOutput;
4734}
4735type AiImageTextToTextInput = {
4736 image: string;
4737 prompt?: string;
4738 max_tokens?: number;
4739 temperature?: number;
4740 ignore_eos?: boolean;
4741 top_p?: number;
4742 top_k?: number;
4743 seed?: number;
4744 repetition_penalty?: number;
4745 frequency_penalty?: number;
4746 presence_penalty?: number;
4747 raw?: boolean;
4748 messages?: RoleScopedChatInput[];
4749};
4750type AiImageTextToTextOutput = {
4751 description: string;
4752};
4753declare abstract class BaseAiImageTextToText {
4754 inputs: AiImageTextToTextInput;
4755 postProcessedOutputs: AiImageTextToTextOutput;
4756}
4757type AiMultimodalEmbeddingsInput = {
4758 image: string;
4759 text: string[];
4760};
4761type AiIMultimodalEmbeddingsOutput = {
4762 data: number[][];
4763 shape: number[];
4764};
4765declare abstract class BaseAiMultimodalEmbeddings {
4766 inputs: AiImageTextToTextInput;
4767 postProcessedOutputs: AiImageTextToTextOutput;
4768}
4769type AiObjectDetectionInput = {
4770 image: number[];
4771};
4772type AiObjectDetectionOutput = {
4773 score?: number;
4774 label?: string;
4775}[];
4776declare abstract class BaseAiObjectDetection {
4777 inputs: AiObjectDetectionInput;
4778 postProcessedOutputs: AiObjectDetectionOutput;
4779}
4780type AiSentenceSimilarityInput = {
4781 source: string;
4782 sentences: string[];
4783};
4784type AiSentenceSimilarityOutput = number[];
4785declare abstract class BaseAiSentenceSimilarity {
4786 inputs: AiSentenceSimilarityInput;
4787 postProcessedOutputs: AiSentenceSimilarityOutput;
4788}
4789type AiAutomaticSpeechRecognitionInput = {
4790 audio: number[];
4791};
4792type AiAutomaticSpeechRecognitionOutput = {
4793 text?: string;
4794 words?: {
4795 word: string;
4796 start: number;
4797 end: number;
4798 }[];
4799 vtt?: string;
4800};
4801declare abstract class BaseAiAutomaticSpeechRecognition {
4802 inputs: AiAutomaticSpeechRecognitionInput;
4803 postProcessedOutputs: AiAutomaticSpeechRecognitionOutput;
4804}
4805type AiSummarizationInput = {
4806 input_text: string;
4807 max_length?: number;
4808};
4809type AiSummarizationOutput = {
4810 summary: string;
4811};
4812declare abstract class BaseAiSummarization {
4813 inputs: AiSummarizationInput;
4814 postProcessedOutputs: AiSummarizationOutput;
4815}
4816type AiTextClassificationInput = {
4817 text: string;
4818};
4819type AiTextClassificationOutput = {
4820 score?: number;
4821 label?: string;
4822}[];
4823declare abstract class BaseAiTextClassification {
4824 inputs: AiTextClassificationInput;
4825 postProcessedOutputs: AiTextClassificationOutput;
4826}
4827type AiTextEmbeddingsInput = {
4828 text: string | string[];
4829};
4830type AiTextEmbeddingsOutput = {
4831 shape: number[];
4832 data: number[][];
4833};
4834declare abstract class BaseAiTextEmbeddings {
4835 inputs: AiTextEmbeddingsInput;
4836 postProcessedOutputs: AiTextEmbeddingsOutput;
4837}
4838type RoleScopedChatInput = {
4839 role: "user" | "assistant" | "system" | "tool" | (string & NonNullable<unknown>);
4840 content: string;
4841 name?: string;
4842};
4843type AiTextGenerationToolLegacyInput = {
4844 name: string;
4845 description: string;
4846 parameters?: {
4847 type: "object" | (string & NonNullable<unknown>);
4848 properties: {
4849 [key: string]: {
4850 type: string;
4851 description?: string;
4852 };
4853 };
4854 required: string[];
4855 };
4856};
4857type AiTextGenerationToolInput = {
4858 type: "function" | (string & NonNullable<unknown>);
4859 function: {
4860 name: string;
4861 description: string;
4862 parameters?: {
4863 type: "object" | (string & NonNullable<unknown>);
4864 properties: {
4865 [key: string]: {
4866 type: string;
4867 description?: string;
4868 };
4869 };
4870 required: string[];
4871 };
4872 };
4873};
4874type AiTextGenerationFunctionsInput = {
4875 name: string;
4876 code: string;
4877};
4878type AiTextGenerationResponseFormat = {
4879 type: string;
4880 json_schema?: any;
4881};
4882type AiTextGenerationInput = {
4883 prompt?: string;
4884 raw?: boolean;
4885 stream?: boolean;
4886 max_tokens?: number;
4887 temperature?: number;
4888 top_p?: number;
4889 top_k?: number;
4890 seed?: number;
4891 repetition_penalty?: number;
4892 frequency_penalty?: number;
4893 presence_penalty?: number;
4894 messages?: RoleScopedChatInput[];
4895 response_format?: AiTextGenerationResponseFormat;
4896 tools?: AiTextGenerationToolInput[] | AiTextGenerationToolLegacyInput[] | (object & NonNullable<unknown>);
4897 functions?: AiTextGenerationFunctionsInput[];
4898};
4899type AiTextGenerationToolLegacyOutput = {
4900 name: string;
4901 arguments: unknown;
4902};
4903type AiTextGenerationToolOutput = {
4904 id: string;
4905 type: "function";
4906 function: {
4907 name: string;
4908 arguments: string;
4909 };
4910};
4911type UsageTags = {
4912 prompt_tokens: number;
4913 completion_tokens: number;
4914 total_tokens: number;
4915};
4916type AiTextGenerationOutput = {
4917 response?: string;
4918 tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[];
4919 usage?: UsageTags;
4920};
4921declare abstract class BaseAiTextGeneration {
4922 inputs: AiTextGenerationInput;
4923 postProcessedOutputs: AiTextGenerationOutput;
4924}
4925type AiTextToSpeechInput = {
4926 prompt: string;
4927 lang?: string;
4928};
4929type AiTextToSpeechOutput = Uint8Array | {
4930 audio: string;
4931};
4932declare abstract class BaseAiTextToSpeech {
4933 inputs: AiTextToSpeechInput;
4934 postProcessedOutputs: AiTextToSpeechOutput;
4935}
4936type AiTextToImageInput = {
4937 prompt: string;
4938 negative_prompt?: string;
4939 height?: number;
4940 width?: number;
4941 image?: number[];
4942 image_b64?: string;
4943 mask?: number[];
4944 num_steps?: number;
4945 strength?: number;
4946 guidance?: number;
4947 seed?: number;
4948};
4949type AiTextToImageOutput = ReadableStream<Uint8Array>;
4950declare abstract class BaseAiTextToImage {
4951 inputs: AiTextToImageInput;
4952 postProcessedOutputs: AiTextToImageOutput;
4953}
4954type AiTranslationInput = {
4955 text: string;
4956 target_lang: string;
4957 source_lang?: string;
4958};
4959type AiTranslationOutput = {
4960 translated_text?: string;
4961};
4962declare abstract class BaseAiTranslation {
4963 inputs: AiTranslationInput;
4964 postProcessedOutputs: AiTranslationOutput;
4965}
4966/**
4967 * Workers AI support for OpenAI's Chat Completions API
4968 */
4969type ChatCompletionContentPartText = {
4970 type: "text";
4971 text: string;
4972};
4973type ChatCompletionContentPartImage = {
4974 type: "image_url";
4975 image_url: {
4976 url: string;
4977 detail?: "auto" | "low" | "high";
4978 };
4979};
4980type ChatCompletionContentPartInputAudio = {
4981 type: "input_audio";
4982 input_audio: {
4983 /** Base64 encoded audio data. */
4984 data: string;
4985 format: "wav" | "mp3";
4986 };
4987};
4988type ChatCompletionContentPartFile = {
4989 type: "file";
4990 file: {
4991 /** Base64 encoded file data. */
4992 file_data?: string;
4993 /** The ID of an uploaded file. */
4994 file_id?: string;
4995 filename?: string;
4996 };
4997};
4998type ChatCompletionContentPartRefusal = {
4999 type: "refusal";
5000 refusal: string;
5001};
5002type ChatCompletionContentPart = ChatCompletionContentPartText | ChatCompletionContentPartImage | ChatCompletionContentPartInputAudio | ChatCompletionContentPartFile;
5003type FunctionDefinition = {
5004 name: string;
5005 description?: string;
5006 parameters?: Record<string, unknown>;
5007 strict?: boolean | null;
5008};
5009type ChatCompletionFunctionTool = {
5010 type: "function";
5011 function: FunctionDefinition;
5012};
5013type ChatCompletionCustomToolGrammarFormat = {
5014 type: "grammar";
5015 grammar: {
5016 definition: string;
5017 syntax: "lark" | "regex";
5018 };
5019};
5020type ChatCompletionCustomToolTextFormat = {
5021 type: "text";
5022};
5023type ChatCompletionCustomToolFormat = ChatCompletionCustomToolTextFormat | ChatCompletionCustomToolGrammarFormat;
5024type ChatCompletionCustomTool = {
5025 type: "custom";
5026 custom: {
5027 name: string;
5028 description?: string;
5029 format?: ChatCompletionCustomToolFormat;
5030 };
5031};
5032type ChatCompletionTool = ChatCompletionFunctionTool | ChatCompletionCustomTool;
5033type ChatCompletionMessageFunctionToolCall = {
5034 id: string;
5035 type: "function";
5036 function: {
5037 name: string;
5038 /** JSON-encoded arguments string. */
5039 arguments: string;
5040 };
5041};
5042type ChatCompletionMessageCustomToolCall = {
5043 id: string;
5044 type: "custom";
5045 custom: {
5046 name: string;
5047 input: string;
5048 };
5049};
5050type ChatCompletionMessageToolCall = ChatCompletionMessageFunctionToolCall | ChatCompletionMessageCustomToolCall;
5051type ChatCompletionToolChoiceFunction = {
5052 type: "function";
5053 function: {
5054 name: string;
5055 };
5056};
5057type ChatCompletionToolChoiceCustom = {
5058 type: "custom";
5059 custom: {
5060 name: string;
5061 };
5062};
5063type ChatCompletionToolChoiceAllowedTools = {
5064 type: "allowed_tools";
5065 allowed_tools: {
5066 mode: "auto" | "required";
5067 tools: Array<Record<string, unknown>>;
5068 };
5069};
5070type ChatCompletionToolChoiceOption = "none" | "auto" | "required" | ChatCompletionToolChoiceFunction | ChatCompletionToolChoiceCustom | ChatCompletionToolChoiceAllowedTools;
5071type DeveloperMessage = {
5072 role: "developer";
5073 content: string | Array<{
5074 type: "text";
5075 text: string;
5076 }>;
5077 name?: string;
5078};
5079type SystemMessage = {
5080 role: "system";
5081 content: string | Array<{
5082 type: "text";
5083 text: string;
5084 }>;
5085 name?: string;
5086};
5087/**
5088 * Permissive merged content part used inside UserMessage arrays.
5089 *
5090 * Cabidela has a limitation where anyOf/oneOf with enum-based discrimination
5091 * inside nested array items does not correctly match different branches for
5092 * different array elements, so the schema uses a single merged object.
5093 */
5094type UserMessageContentPart = {
5095 type: "text" | "image_url" | "input_audio" | "file";
5096 text?: string;
5097 image_url?: {
5098 url?: string;
5099 detail?: "auto" | "low" | "high";
5100 };
5101 input_audio?: {
5102 data?: string;
5103 format?: "wav" | "mp3";
5104 };
5105 file?: {
5106 file_data?: string;
5107 file_id?: string;
5108 filename?: string;
5109 };
5110};
5111type UserMessage = {
5112 role: "user";
5113 content: string | Array<UserMessageContentPart>;
5114 name?: string;
5115};
5116type AssistantMessageContentPart = {
5117 type: "text" | "refusal";
5118 text?: string;
5119 refusal?: string;
5120};
5121type AssistantMessage = {
5122 role: "assistant";
5123 content?: string | null | Array<AssistantMessageContentPart>;
5124 refusal?: string | null;
5125 name?: string;
5126 audio?: {
5127 id: string;
5128 };
5129 tool_calls?: Array<ChatCompletionMessageToolCall>;
5130 function_call?: {
5131 name: string;
5132 arguments: string;
5133 };
5134};
5135type ToolMessage = {
5136 role: "tool";
5137 content: string | Array<{
5138 type: "text";
5139 text: string;
5140 }>;
5141 tool_call_id: string;
5142};
5143type FunctionMessage = {
5144 role: "function";
5145 content: string;
5146 name: string;
5147};
5148type ChatCompletionMessageParam = DeveloperMessage | SystemMessage | UserMessage | AssistantMessage | ToolMessage | FunctionMessage;
5149type ChatCompletionsResponseFormatText = {
5150 type: "text";
5151};
5152type ChatCompletionsResponseFormatJSONObject = {
5153 type: "json_object";
5154};
5155type ResponseFormatJSONSchema = {
5156 type: "json_schema";
5157 json_schema: {
5158 name: string;
5159 description?: string;
5160 schema?: Record<string, unknown>;
5161 strict?: boolean | null;
5162 };
5163};
5164type ResponseFormat = ChatCompletionsResponseFormatText | ChatCompletionsResponseFormatJSONObject | ResponseFormatJSONSchema;
5165type ChatCompletionsStreamOptions = {
5166 include_usage?: boolean;
5167 include_obfuscation?: boolean;
5168};
5169type PredictionContent = {
5170 type: "content";
5171 content: string | Array<{
5172 type: "text";
5173 text: string;
5174 }>;
5175};
5176type AudioParams = {
5177 voice: string | {
5178 id: string;
5179 };
5180 format: "wav" | "aac" | "mp3" | "flac" | "opus" | "pcm16";
5181};
5182type WebSearchUserLocation = {
5183 type: "approximate";
5184 approximate: {
5185 city?: string;
5186 country?: string;
5187 region?: string;
5188 timezone?: string;
5189 };
5190};
5191type WebSearchOptions = {
5192 search_context_size?: "low" | "medium" | "high";
5193 user_location?: WebSearchUserLocation;
5194};
5195// Source of truth for per-model reasoning types: each model's `reasoning_effort` metadata
5196// in Workers AI ConfigAPI (supported efforts, aliases, defaults, and whether reasoning can
5197// be turned off). The Workers AI SDK type generator (cloudflare/ai/sdk,
5198// apps/worker-constellation-entry/scripts/build-types) turns it into the per-model
5199// `inputs` types below; the developer docs model schemas come from the same metadata.
5200type ChatTemplateKwargs = {
5201 /** Whether to enable reasoning. Support and defaults depend on the model. */
5202 enable_thinking?: boolean;
5203 /** If false, preserves reasoning context between turns. */
5204 clear_thinking?: boolean;
5205};
5206/** Shared optional properties used by both Prompt and Messages input branches. */
5207type ChatCompletionsCommonOptions = {
5208 model?: string;
5209 audio?: AudioParams;
5210 frequency_penalty?: number | null;
5211 logit_bias?: Record<string, unknown> | null;
5212 logprobs?: boolean | null;
5213 top_logprobs?: number | null;
5214 max_tokens?: number | null;
5215 max_completion_tokens?: number | null;
5216 metadata?: Record<string, unknown> | null;
5217 modalities?: Array<"text" | "audio"> | null;
5218 n?: number | null;
5219 parallel_tool_calls?: boolean;
5220 prediction?: PredictionContent;
5221 presence_penalty?: number | null;
5222 /** Reasoning effort. Supported levels depend on the model. */
5223 reasoning_effort?: "low" | "medium" | "high" | null;
5224 chat_template_kwargs?: ChatTemplateKwargs;
5225 response_format?: ResponseFormat;
5226 seed?: number | null;
5227 service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null;
5228 stop?: string | Array<string> | null;
5229 store?: boolean | null;
5230 stream?: boolean | null;
5231 stream_options?: ChatCompletionsStreamOptions;
5232 temperature?: number | null;
5233 tool_choice?: ChatCompletionToolChoiceOption;
5234 tools?: Array<ChatCompletionTool>;
5235 top_p?: number | null;
5236 user?: string;
5237 web_search_options?: WebSearchOptions;
5238 function_call?: "none" | "auto" | {
5239 name: string;
5240 };
5241 functions?: Array<FunctionDefinition>;
5242};
5243type PromptTokensDetails = {
5244 cached_tokens?: number;
5245 audio_tokens?: number;
5246};
5247type CompletionTokensDetails = {
5248 reasoning_tokens?: number;
5249 audio_tokens?: number;
5250 accepted_prediction_tokens?: number;
5251 rejected_prediction_tokens?: number;
5252};
5253type CompletionUsage = {
5254 prompt_tokens: number;
5255 completion_tokens: number;
5256 total_tokens: number;
5257 prompt_tokens_details?: PromptTokensDetails;
5258 completion_tokens_details?: CompletionTokensDetails;
5259};
5260type ChatCompletionTopLogprob = {
5261 token: string;
5262 logprob: number;
5263 bytes: Array<number> | null;
5264};
5265type ChatCompletionTokenLogprob = {
5266 token: string;
5267 logprob: number;
5268 bytes: Array<number> | null;
5269 top_logprobs: Array<ChatCompletionTopLogprob>;
5270};
5271type ChatCompletionAudio = {
5272 id: string;
5273 /** Base64 encoded audio bytes. */
5274 data: string;
5275 expires_at: number;
5276 transcript: string;
5277};
5278type ChatCompletionUrlCitation = {
5279 type: "url_citation";
5280 url_citation: {
5281 url: string;
5282 title: string;
5283 start_index: number;
5284 end_index: number;
5285 };
5286};
5287type ChatCompletionResponseMessage = {
5288 role: "assistant";
5289 content: string | null;
5290 refusal: string | null;
5291 annotations?: Array<ChatCompletionUrlCitation>;
5292 audio?: ChatCompletionAudio;
5293 tool_calls?: Array<ChatCompletionMessageToolCall>;
5294 function_call?: {
5295 name: string;
5296 arguments: string;
5297 } | null;
5298};
5299type ChatCompletionLogprobs = {
5300 content: Array<ChatCompletionTokenLogprob> | null;
5301 refusal?: Array<ChatCompletionTokenLogprob> | null;
5302};
5303type ChatCompletionChoice = {
5304 index: number;
5305 message: ChatCompletionResponseMessage;
5306 finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | "function_call";
5307 logprobs: ChatCompletionLogprobs | null;
5308};
5309type ChatCompletionsMessagesInput = {
5310 messages: Array<ChatCompletionMessageParam>;
5311} & ChatCompletionsCommonOptions;
5312type ChatCompletionsOutput = {
5313 id: string;
5314 object: string;
5315 created: number;
5316 model: string;
5317 choices: Array<ChatCompletionChoice>;
5318 usage?: CompletionUsage;
5319 system_fingerprint?: string | null;
5320 service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null;
5321};
5322/**
5323 * Workers AI support for OpenAI's Responses API
5324 * Reference: https://github.com/openai/openai-node/blob/master/src/resources/responses/responses.ts
5325 *
5326 * It's a stripped down version from its source.
5327 * It currently supports basic function calling, json mode and accepts images as input.
5328 *
5329 * It does not include types for WebSearch, CodeInterpreter, FileInputs, MCP, CustomTools.
5330 * We plan to add those incrementally as model + platform capabilities evolve.
5331 */
5332type ResponsesInput = {
5333 background?: boolean | null;
5334 conversation?: string | ResponseConversationParam | null;
5335 include?: Array<ResponseIncludable> | null;
5336 input?: string | ResponseInput;
5337 instructions?: string | null;
5338 max_output_tokens?: number | null;
5339 parallel_tool_calls?: boolean | null;
5340 previous_response_id?: string | null;
5341 prompt_cache_key?: string;
5342 reasoning?: Reasoning | null;
5343 safety_identifier?: string;
5344 service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null;
5345 stream?: boolean | null;
5346 stream_options?: StreamOptions | null;
5347 temperature?: number | null;
5348 text?: ResponseTextConfig;
5349 tool_choice?: ToolChoiceOptions | ToolChoiceFunction;
5350 tools?: Array<Tool>;
5351 top_p?: number | null;
5352 truncation?: "auto" | "disabled" | null;
5353};
5354type ResponsesOutput = {
5355 id?: string;
5356 created_at?: number;
5357 output_text?: string;
5358 error?: ResponseError | null;
5359 incomplete_details?: ResponseIncompleteDetails | null;
5360 instructions?: string | Array<ResponseInputItem> | null;
5361 object?: "response";
5362 output?: Array<ResponseOutputItem>;
5363 parallel_tool_calls?: boolean;
5364 temperature?: number | null;
5365 tool_choice?: ToolChoiceOptions | ToolChoiceFunction;
5366 tools?: Array<Tool>;
5367 top_p?: number | null;
5368 max_output_tokens?: number | null;
5369 previous_response_id?: string | null;
5370 prompt?: ResponsePrompt | null;
5371 reasoning?: Reasoning | null;
5372 safety_identifier?: string;
5373 service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null;
5374 status?: ResponseStatus;
5375 text?: ResponseTextConfig;
5376 truncation?: "auto" | "disabled" | null;
5377 usage?: ResponseUsage;
5378};
5379type EasyInputMessage = {
5380 content: string | ResponseInputMessageContentList;
5381 role: "user" | "assistant" | "system" | "developer";
5382 type?: "message";
5383};
5384type ResponsesFunctionTool = {
5385 name: string;
5386 parameters: {
5387 [key: string]: unknown;
5388 } | null;
5389 strict: boolean | null;
5390 type: "function";
5391 description?: string | null;
5392};
5393type ResponseIncompleteDetails = {
5394 reason?: "max_output_tokens" | "content_filter";
5395};
5396type ResponsePrompt = {
5397 id: string;
5398 variables?: {
5399 [key: string]: string | ResponseInputText | ResponseInputImage;
5400 } | null;
5401 version?: string | null;
5402};
5403type Reasoning = {
5404 effort?: ReasoningEffort | null;
5405 generate_summary?: "auto" | "concise" | "detailed" | null;
5406 summary?: "auto" | "concise" | "detailed" | null;
5407};
5408type ResponseContent = ResponseInputText | ResponseInputImage | ResponseOutputText | ResponseOutputRefusal | ResponseContentReasoningText;
5409type ResponseContentReasoningText = {
5410 text: string;
5411 type: "reasoning_text";
5412};
5413type ResponseConversationParam = {
5414 id: string;
5415};
5416type ResponseCreatedEvent = {
5417 response: Response;
5418 sequence_number: number;
5419 type: "response.created";
5420};
5421type ResponseCustomToolCallOutput = {
5422 call_id: string;
5423 output: string | Array<ResponseInputText | ResponseInputImage>;
5424 type: "custom_tool_call_output";
5425 id?: string;
5426};
5427type ResponseError = {
5428 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";
5429 message: string;
5430};
5431type ResponseErrorEvent = {
5432 code: string | null;
5433 message: string;
5434 param: string | null;
5435 sequence_number: number;
5436 type: "error";
5437};
5438type ResponseFailedEvent = {
5439 response: Response;
5440 sequence_number: number;
5441 type: "response.failed";
5442};
5443type ResponseFormatText = {
5444 type: "text";
5445};
5446type ResponseFormatJSONObject = {
5447 type: "json_object";
5448};
5449type ResponseFormatTextConfig = ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject;
5450type ResponseFormatTextJSONSchemaConfig = {
5451 name: string;
5452 schema: {
5453 [key: string]: unknown;
5454 };
5455 type: "json_schema";
5456 description?: string;
5457 strict?: boolean | null;
5458};
5459type ResponseFunctionCallArgumentsDeltaEvent = {
5460 delta: string;
5461 item_id: string;
5462 output_index: number;
5463 sequence_number: number;
5464 type: "response.function_call_arguments.delta";
5465};
5466type ResponseFunctionCallArgumentsDoneEvent = {
5467 arguments: string;
5468 item_id: string;
5469 name: string;
5470 output_index: number;
5471 sequence_number: number;
5472 type: "response.function_call_arguments.done";
5473};
5474type ResponseFunctionCallOutputItem = ResponseInputTextContent | ResponseInputImageContent;
5475type ResponseFunctionCallOutputItemList = Array<ResponseFunctionCallOutputItem>;
5476type ResponseFunctionToolCall = {
5477 arguments: string;
5478 call_id: string;
5479 name: string;
5480 type: "function_call";
5481 id?: string;
5482 status?: "in_progress" | "completed" | "incomplete";
5483};
5484interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall {
5485 id: string;
5486}
5487type ResponseFunctionToolCallOutputItem = {
5488 id: string;
5489 call_id: string;
5490 output: string | Array<ResponseInputText | ResponseInputImage>;
5491 type: "function_call_output";
5492 status?: "in_progress" | "completed" | "incomplete";
5493};
5494type ResponseIncludable = "message.input_image.image_url" | "message.output_text.logprobs";
5495type ResponseIncompleteEvent = {
5496 response: Response;
5497 sequence_number: number;
5498 type: "response.incomplete";
5499};
5500type ResponseInput = Array<ResponseInputItem>;
5501type ResponseInputContent = ResponseInputText | ResponseInputImage;
5502type ResponseInputImage = {
5503 detail: "low" | "high" | "auto";
5504 type: "input_image";
5505 /**
5506 * Base64 encoded image
5507 */
5508 image_url?: string | null;
5509};
5510type ResponseInputImageContent = {
5511 type: "input_image";
5512 detail?: "low" | "high" | "auto" | null;
5513 /**
5514 * Base64 encoded image
5515 */
5516 image_url?: string | null;
5517};
5518type ResponseInputItem = EasyInputMessage | ResponseInputItemMessage | ResponseOutputMessage | ResponseFunctionToolCall | ResponseInputItemFunctionCallOutput | ResponseReasoningItem;
5519type ResponseInputItemFunctionCallOutput = {
5520 call_id: string;
5521 output: string | ResponseFunctionCallOutputItemList;
5522 type: "function_call_output";
5523 id?: string | null;
5524 status?: "in_progress" | "completed" | "incomplete" | null;
5525};
5526type ResponseInputItemMessage = {
5527 content: ResponseInputMessageContentList;
5528 role: "user" | "system" | "developer";
5529 status?: "in_progress" | "completed" | "incomplete";
5530 type?: "message";
5531};
5532type ResponseInputMessageContentList = Array<ResponseInputContent>;
5533type ResponseInputMessageItem = {
5534 id: string;
5535 content: ResponseInputMessageContentList;
5536 role: "user" | "system" | "developer";
5537 status?: "in_progress" | "completed" | "incomplete";
5538 type?: "message";
5539};
5540type ResponseInputText = {
5541 text: string;
5542 type: "input_text";
5543};
5544type ResponseInputTextContent = {
5545 text: string;
5546 type: "input_text";
5547};
5548type ResponseItem = ResponseInputMessageItem | ResponseOutputMessage | ResponseFunctionToolCallItem | ResponseFunctionToolCallOutputItem;
5549type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem;
5550type ResponseOutputItemAddedEvent = {
5551 item: ResponseOutputItem;
5552 output_index: number;
5553 sequence_number: number;
5554 type: "response.output_item.added";
5555};
5556type ResponseOutputItemDoneEvent = {
5557 item: ResponseOutputItem;
5558 output_index: number;
5559 sequence_number: number;
5560 type: "response.output_item.done";
5561};
5562type ResponseOutputMessage = {
5563 id: string;
5564 content: Array<ResponseOutputText | ResponseOutputRefusal>;
5565 role: "assistant";
5566 status: "in_progress" | "completed" | "incomplete";
5567 type: "message";
5568};
5569type ResponseOutputRefusal = {
5570 refusal: string;
5571 type: "refusal";
5572};
5573type ResponseOutputText = {
5574 text: string;
5575 type: "output_text";
5576 logprobs?: Array<Logprob>;
5577};
5578type ResponseReasoningItem = {
5579 id: string;
5580 summary: Array<ResponseReasoningSummaryItem>;
5581 type: "reasoning";
5582 content?: Array<ResponseReasoningContentItem>;
5583 encrypted_content?: string | null;
5584 status?: "in_progress" | "completed" | "incomplete";
5585};
5586type ResponseReasoningSummaryItem = {
5587 text: string;
5588 type: "summary_text";
5589};
5590type ResponseReasoningContentItem = {
5591 text: string;
5592 type: "reasoning_text";
5593};
5594type ResponseReasoningTextDeltaEvent = {
5595 content_index: number;
5596 delta: string;
5597 item_id: string;
5598 output_index: number;
5599 sequence_number: number;
5600 type: "response.reasoning_text.delta";
5601};
5602type ResponseReasoningTextDoneEvent = {
5603 content_index: number;
5604 item_id: string;
5605 output_index: number;
5606 sequence_number: number;
5607 text: string;
5608 type: "response.reasoning_text.done";
5609};
5610type ResponseRefusalDeltaEvent = {
5611 content_index: number;
5612 delta: string;
5613 item_id: string;
5614 output_index: number;
5615 sequence_number: number;
5616 type: "response.refusal.delta";
5617};
5618type ResponseRefusalDoneEvent = {
5619 content_index: number;
5620 item_id: string;
5621 output_index: number;
5622 refusal: string;
5623 sequence_number: number;
5624 type: "response.refusal.done";
5625};
5626type ResponseStatus = "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete";
5627type ResponseStreamEvent = ResponseCompletedEvent | ResponseCreatedEvent | ResponseErrorEvent | ResponseFunctionCallArgumentsDeltaEvent | ResponseFunctionCallArgumentsDoneEvent | ResponseFailedEvent | ResponseIncompleteEvent | ResponseOutputItemAddedEvent | ResponseOutputItemDoneEvent | ResponseReasoningTextDeltaEvent | ResponseReasoningTextDoneEvent | ResponseRefusalDeltaEvent | ResponseRefusalDoneEvent | ResponseTextDeltaEvent | ResponseTextDoneEvent;
5628type ResponseCompletedEvent = {
5629 response: Response;
5630 sequence_number: number;
5631 type: "response.completed";
5632};
5633type ResponseTextConfig = {
5634 format?: ResponseFormatTextConfig;
5635 verbosity?: "low" | "medium" | "high" | null;
5636};
5637type ResponseTextDeltaEvent = {
5638 content_index: number;
5639 delta: string;
5640 item_id: string;
5641 logprobs: Array<Logprob>;
5642 output_index: number;
5643 sequence_number: number;
5644 type: "response.output_text.delta";
5645};
5646type ResponseTextDoneEvent = {
5647 content_index: number;
5648 item_id: string;
5649 logprobs: Array<Logprob>;
5650 output_index: number;
5651 sequence_number: number;
5652 text: string;
5653 type: "response.output_text.done";
5654};
5655type Logprob = {
5656 token: string;
5657 logprob: number;
5658 top_logprobs?: Array<TopLogprob>;
5659};
5660type TopLogprob = {
5661 token?: string;
5662 logprob?: number;
5663};
5664type ResponseUsage = {
5665 input_tokens: number;
5666 output_tokens: number;
5667 total_tokens: number;
5668};
5669type Tool = ResponsesFunctionTool;
5670type ToolChoiceFunction = {
5671 name: string;
5672 type: "function";
5673};
5674type ToolChoiceOptions = "none";
5675type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null;
5676type StreamOptions = {
5677 include_obfuscation?: boolean;
5678};
5679/** Marks keys from T that aren't in U as optional never */
5680type Without<T, U> = {
5681 [P in Exclude<keyof T, keyof U>]?: never;
5682};
5683/** Either T or U, but not both (mutually exclusive) */
5684type XOR<T, U> = (T & Without<U, T>) | (U & Without<T, U>);
5685type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = {
5686 text: string | string[];
5687 /**
5688 * 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.
5689 */
5690 pooling?: "mean" | "cls";
5691} | {
5692 /**
5693 * Batch of the embeddings requests to run using async-queue
5694 */
5695 requests: {
5696 text: string | string[];
5697 /**
5698 * 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.
5699 */
5700 pooling?: "mean" | "cls";
5701 }[];
5702};
5703type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = {
5704 shape?: number[];
5705 /**
5706 * Embeddings of the requested text values
5707 */
5708 data?: number[][];
5709 /**
5710 * The pooling method used in the embedding process.
5711 */
5712 pooling?: "mean" | "cls";
5713} | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse;
5714interface Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse {
5715 /**
5716 * The async request id that can be used to obtain the results.
5717 */
5718 request_id?: string;
5719}
5720declare abstract class Base_Ai_Cf_Baai_Bge_Base_En_V1_5 {
5721 inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input;
5722 postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output;
5723}
5724type Ai_Cf_Openai_Whisper_Input = string | {
5725 /**
5726 * An array of integers that represent the audio data constrained to 8-bit unsigned integer values
5727 */
5728 audio: number[];
5729};
5730interface Ai_Cf_Openai_Whisper_Output {
5731 /**
5732 * The transcription
5733 */
5734 text: string;
5735 word_count?: number;
5736 words?: {
5737 word?: string;
5738 /**
5739 * The second this word begins in the recording
5740 */
5741 start?: number;
5742 /**
5743 * The ending second when the word completes
5744 */
5745 end?: number;
5746 }[];
5747 vtt?: string;
5748}
5749declare abstract class Base_Ai_Cf_Openai_Whisper {
5750 inputs: Ai_Cf_Openai_Whisper_Input;
5751 postProcessedOutputs: Ai_Cf_Openai_Whisper_Output;
5752}
5753type Ai_Cf_Meta_M2M100_1_2B_Input = {
5754 /**
5755 * The text to be translated
5756 */
5757 text: string;
5758 /**
5759 * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified
5760 */
5761 source_lang?: string;
5762 /**
5763 * The language code to translate the text into (e.g., 'es' for Spanish)
5764 */
5765 target_lang: string;
5766} | {
5767 /**
5768 * Batch of the embeddings requests to run using async-queue
5769 */
5770 requests: {
5771 /**
5772 * The text to be translated
5773 */
5774 text: string;
5775 /**
5776 * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified
5777 */
5778 source_lang?: string;
5779 /**
5780 * The language code to translate the text into (e.g., 'es' for Spanish)
5781 */
5782 target_lang: string;
5783 }[];
5784};
5785type Ai_Cf_Meta_M2M100_1_2B_Output = {
5786 /**
5787 * The translated text in the target language
5788 */
5789 translated_text?: string;
5790} | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse;
5791interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse {
5792 /**
5793 * The async request id that can be used to obtain the results.
5794 */
5795 request_id?: string;
5796}
5797declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B {
5798 inputs: Ai_Cf_Meta_M2M100_1_2B_Input;
5799 postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output;
5800}
5801type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = {
5802 text: string | string[];
5803 /**
5804 * 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.
5805 */
5806 pooling?: "mean" | "cls";
5807} | {
5808 /**
5809 * Batch of the embeddings requests to run using async-queue
5810 */
5811 requests: {
5812 text: string | string[];
5813 /**
5814 * 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.
5815 */
5816 pooling?: "mean" | "cls";
5817 }[];
5818};
5819type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = {
5820 shape?: number[];
5821 /**
5822 * Embeddings of the requested text values
5823 */
5824 data?: number[][];
5825 /**
5826 * The pooling method used in the embedding process.
5827 */
5828 pooling?: "mean" | "cls";
5829} | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse;
5830interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse {
5831 /**
5832 * The async request id that can be used to obtain the results.
5833 */
5834 request_id?: string;
5835}
5836declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 {
5837 inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input;
5838 postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output;
5839}
5840type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = {
5841 text: string | string[];
5842 /**
5843 * 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.
5844 */
5845 pooling?: "mean" | "cls";
5846} | {
5847 /**
5848 * Batch of the embeddings requests to run using async-queue
5849 */
5850 requests: {
5851 text: string | string[];
5852 /**
5853 * 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.
5854 */
5855 pooling?: "mean" | "cls";
5856 }[];
5857};
5858type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = {
5859 shape?: number[];
5860 /**
5861 * Embeddings of the requested text values
5862 */
5863 data?: number[][];
5864 /**
5865 * The pooling method used in the embedding process.
5866 */
5867 pooling?: "mean" | "cls";
5868} | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse;
5869interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse {
5870 /**
5871 * The async request id that can be used to obtain the results.
5872 */
5873 request_id?: string;
5874}
5875declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 {
5876 inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input;
5877 postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output;
5878}
5879type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = string | {
5880 /**
5881 * The input text prompt for the model to generate a response.
5882 */
5883 prompt?: string;
5884 /**
5885 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
5886 */
5887 raw?: boolean;
5888 /**
5889 * 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.
5890 */
5891 top_p?: number;
5892 /**
5893 * 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.
5894 */
5895 top_k?: number;
5896 /**
5897 * Random seed for reproducibility of the generation.
5898 */
5899 seed?: number;
5900 /**
5901 * Penalty for repeated tokens; higher values discourage repetition.
5902 */
5903 repetition_penalty?: number;
5904 /**
5905 * Decreases the likelihood of the model repeating the same lines verbatim.
5906 */
5907 frequency_penalty?: number;
5908 /**
5909 * Increases the likelihood of the model introducing new topics.
5910 */
5911 presence_penalty?: number;
5912 image: number[] | (string & NonNullable<unknown>);
5913 /**
5914 * The maximum number of tokens to generate in the response.
5915 */
5916 max_tokens?: number;
5917};
5918interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output {
5919 description?: string;
5920}
5921declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M {
5922 inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input;
5923 postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output;
5924}
5925type Ai_Cf_Openai_Whisper_Tiny_En_Input = string | {
5926 /**
5927 * An array of integers that represent the audio data constrained to 8-bit unsigned integer values
5928 */
5929 audio: number[];
5930};
5931interface Ai_Cf_Openai_Whisper_Tiny_En_Output {
5932 /**
5933 * The transcription
5934 */
5935 text: string;
5936 word_count?: number;
5937 words?: {
5938 word?: string;
5939 /**
5940 * The second this word begins in the recording
5941 */
5942 start?: number;
5943 /**
5944 * The ending second when the word completes
5945 */
5946 end?: number;
5947 }[];
5948 vtt?: string;
5949}
5950declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En {
5951 inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input;
5952 postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output;
5953}
5954interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input {
5955 audio: string | {
5956 body?: object;
5957 contentType?: string;
5958 };
5959 /**
5960 * Supported tasks are 'translate' or 'transcribe'.
5961 */
5962 task?: string;
5963 /**
5964 * The language of the audio being transcribed or translated.
5965 */
5966 language?: string;
5967 /**
5968 * Preprocess the audio with a voice activity detection model.
5969 */
5970 vad_filter?: boolean;
5971 /**
5972 * A text prompt to help provide context to the model on the contents of the audio.
5973 */
5974 initial_prompt?: string;
5975 /**
5976 * The prefix appended to the beginning of the output of the transcription and can guide the transcription result.
5977 */
5978 prefix?: string;
5979 /**
5980 * The number of beams to use in beam search decoding. Higher values may improve accuracy at the cost of speed.
5981 */
5982 beam_size?: number;
5983 /**
5984 * Whether to condition on previous text during transcription. Setting to false may help prevent hallucination loops.
5985 */
5986 condition_on_previous_text?: boolean;
5987 /**
5988 * Threshold for detecting no-speech segments. Segments with no-speech probability above this value are skipped.
5989 */
5990 no_speech_threshold?: number;
5991 /**
5992 * Threshold for filtering out segments with high compression ratio, which often indicate repetitive or hallucinated text.
5993 */
5994 compression_ratio_threshold?: number;
5995 /**
5996 * Threshold for filtering out segments with low average log probability, indicating low confidence.
5997 */
5998 log_prob_threshold?: number;
5999 /**
6000 * Optional threshold (in seconds) to skip silent periods that may cause hallucinations.
6001 */
6002 hallucination_silence_threshold?: number;
6003}
6004interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output {
6005 transcription_info?: {
6006 /**
6007 * The language of the audio being transcribed or translated.
6008 */
6009 language?: string;
6010 /**
6011 * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1.
6012 */
6013 language_probability?: number;
6014 /**
6015 * The total duration of the original audio file, in seconds.
6016 */
6017 duration?: number;
6018 /**
6019 * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds.
6020 */
6021 duration_after_vad?: number;
6022 };
6023 /**
6024 * The complete transcription of the audio.
6025 */
6026 text: string;
6027 /**
6028 * The total number of words in the transcription.
6029 */
6030 word_count?: number;
6031 segments?: {
6032 /**
6033 * The starting time of the segment within the audio, in seconds.
6034 */
6035 start?: number;
6036 /**
6037 * The ending time of the segment within the audio, in seconds.
6038 */
6039 end?: number;
6040 /**
6041 * The transcription of the segment.
6042 */
6043 text?: string;
6044 /**
6045 * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs.
6046 */
6047 temperature?: number;
6048 /**
6049 * The average log probability of the predictions for the words in this segment, indicating overall confidence.
6050 */
6051 avg_logprob?: number;
6052 /**
6053 * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process.
6054 */
6055 compression_ratio?: number;
6056 /**
6057 * The probability that the segment contains no speech, represented as a decimal between 0 and 1.
6058 */
6059 no_speech_prob?: number;
6060 words?: {
6061 /**
6062 * The individual word transcribed from the audio.
6063 */
6064 word?: string;
6065 /**
6066 * The starting time of the word within the audio, in seconds.
6067 */
6068 start?: number;
6069 /**
6070 * The ending time of the word within the audio, in seconds.
6071 */
6072 end?: number;
6073 }[];
6074 }[];
6075 /**
6076 * The transcription in WebVTT format, which includes timing and text information for use in subtitles.
6077 */
6078 vtt?: string;
6079}
6080declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo {
6081 inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input;
6082 postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output;
6083}
6084type Ai_Cf_Baai_Bge_M3_Input = Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts | Ai_Cf_Baai_Bge_M3_Input_Embedding | {
6085 /**
6086 * Batch of the embeddings requests to run using async-queue
6087 */
6088 requests: (Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 | Ai_Cf_Baai_Bge_M3_Input_Embedding_1)[];
6089};
6090interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts {
6091 /**
6092 * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts
6093 */
6094 query?: string;
6095 /**
6096 * List of provided contexts. Note that the index in this array is important, as the response will refer to it.
6097 */
6098 contexts: {
6099 /**
6100 * One of the provided context content
6101 */
6102 text?: string;
6103 }[];
6104 /**
6105 * When provided with too long context should the model error out or truncate the context to fit?
6106 */
6107 truncate_inputs?: boolean;
6108}
6109interface Ai_Cf_Baai_Bge_M3_Input_Embedding {
6110 text: string | string[];
6111 /**
6112 * When provided with too long context should the model error out or truncate the context to fit?
6113 */
6114 truncate_inputs?: boolean;
6115}
6116interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 {
6117 /**
6118 * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts
6119 */
6120 query?: string;
6121 /**
6122 * List of provided contexts. Note that the index in this array is important, as the response will refer to it.
6123 */
6124 contexts: {
6125 /**
6126 * One of the provided context content
6127 */
6128 text?: string;
6129 }[];
6130 /**
6131 * When provided with too long context should the model error out or truncate the context to fit?
6132 */
6133 truncate_inputs?: boolean;
6134}
6135interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 {
6136 text: string | string[];
6137 /**
6138 * When provided with too long context should the model error out or truncate the context to fit?
6139 */
6140 truncate_inputs?: boolean;
6141}
6142type 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;
6143interface Ai_Cf_Baai_Bge_M3_Output_Query {
6144 response?: {
6145 /**
6146 * Index of the context in the request
6147 */
6148 id?: number;
6149 /**
6150 * Score of the context under the index.
6151 */
6152 score?: number;
6153 }[];
6154}
6155interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts {
6156 response?: number[][];
6157 shape?: number[];
6158 /**
6159 * The pooling method used in the embedding process.
6160 */
6161 pooling?: "mean" | "cls";
6162}
6163interface Ai_Cf_Baai_Bge_M3_Output_Embedding {
6164 shape?: number[];
6165 /**
6166 * Embeddings of the requested text values
6167 */
6168 data?: number[][];
6169 /**
6170 * The pooling method used in the embedding process.
6171 */
6172 pooling?: "mean" | "cls";
6173}
6174interface Ai_Cf_Baai_Bge_M3_AsyncResponse {
6175 /**
6176 * The async request id that can be used to obtain the results.
6177 */
6178 request_id?: string;
6179}
6180declare abstract class Base_Ai_Cf_Baai_Bge_M3 {
6181 inputs: Ai_Cf_Baai_Bge_M3_Input;
6182 postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output;
6183}
6184interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input {
6185 /**
6186 * A text description of the image you want to generate.
6187 */
6188 prompt: string;
6189 /**
6190 * The number of diffusion steps; higher values can improve quality but take longer.
6191 */
6192 steps?: number;
6193}
6194interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output {
6195 /**
6196 * The generated image in Base64 format.
6197 */
6198 image?: string;
6199}
6200declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell {
6201 inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input;
6202 postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output;
6203}
6204type 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;
6205interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt {
6206 /**
6207 * The input text prompt for the model to generate a response.
6208 */
6209 prompt: string;
6210 image?: number[] | (string & NonNullable<unknown>);
6211 /**
6212 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
6213 */
6214 raw?: boolean;
6215 /**
6216 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
6217 */
6218 stream?: boolean;
6219 /**
6220 * The maximum number of tokens to generate in the response.
6221 */
6222 max_tokens?: number;
6223 /**
6224 * Controls the randomness of the output; higher values produce more random results.
6225 */
6226 temperature?: number;
6227 /**
6228 * 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.
6229 */
6230 top_p?: number;
6231 /**
6232 * 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.
6233 */
6234 top_k?: number;
6235 /**
6236 * Random seed for reproducibility of the generation.
6237 */
6238 seed?: number;
6239 /**
6240 * Penalty for repeated tokens; higher values discourage repetition.
6241 */
6242 repetition_penalty?: number;
6243 /**
6244 * Decreases the likelihood of the model repeating the same lines verbatim.
6245 */
6246 frequency_penalty?: number;
6247 /**
6248 * Increases the likelihood of the model introducing new topics.
6249 */
6250 presence_penalty?: number;
6251 /**
6252 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
6253 */
6254 lora?: string;
6255}
6256interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages {
6257 /**
6258 * An array of message objects representing the conversation history.
6259 */
6260 messages: {
6261 /**
6262 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
6263 */
6264 role?: string;
6265 /**
6266 * The tool call id. If you don't know what to put here you can fall back to 000000001
6267 */
6268 tool_call_id?: string;
6269 content?: string | {
6270 /**
6271 * Type of the content provided
6272 */
6273 type?: string;
6274 text?: string;
6275 image_url?: {
6276 /**
6277 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
6278 */
6279 url?: string;
6280 };
6281 }[] | {
6282 /**
6283 * Type of the content provided
6284 */
6285 type?: string;
6286 text?: string;
6287 image_url?: {
6288 /**
6289 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
6290 */
6291 url?: string;
6292 };
6293 };
6294 }[];
6295 image?: number[] | (string & NonNullable<unknown>);
6296 functions?: {
6297 name: string;
6298 code: string;
6299 }[];
6300 /**
6301 * A list of tools available for the assistant to use.
6302 */
6303 tools?: ({
6304 /**
6305 * The name of the tool. More descriptive the better.
6306 */
6307 name: string;
6308 /**
6309 * A brief description of what the tool does.
6310 */
6311 description: string;
6312 /**
6313 * Schema defining the parameters accepted by the tool.
6314 */
6315 parameters: {
6316 /**
6317 * The type of the parameters object (usually 'object').
6318 */
6319 type: string;
6320 /**
6321 * List of required parameter names.
6322 */
6323 required?: string[];
6324 /**
6325 * Definitions of each parameter.
6326 */
6327 properties: {
6328 [k: string]: {
6329 /**
6330 * The data type of the parameter.
6331 */
6332 type: string;
6333 /**
6334 * A description of the expected parameter.
6335 */
6336 description: string;
6337 };
6338 };
6339 };
6340 } | {
6341 /**
6342 * Specifies the type of tool (e.g., 'function').
6343 */
6344 type: string;
6345 /**
6346 * Details of the function tool.
6347 */
6348 function: {
6349 /**
6350 * The name of the function.
6351 */
6352 name: string;
6353 /**
6354 * A brief description of what the function does.
6355 */
6356 description: string;
6357 /**
6358 * Schema defining the parameters accepted by the function.
6359 */
6360 parameters: {
6361 /**
6362 * The type of the parameters object (usually 'object').
6363 */
6364 type: string;
6365 /**
6366 * List of required parameter names.
6367 */
6368 required?: string[];
6369 /**
6370 * Definitions of each parameter.
6371 */
6372 properties: {
6373 [k: string]: {
6374 /**
6375 * The data type of the parameter.
6376 */
6377 type: string;
6378 /**
6379 * A description of the expected parameter.
6380 */
6381 description: string;
6382 };
6383 };
6384 };
6385 };
6386 })[];
6387 /**
6388 * If true, the response will be streamed back incrementally.
6389 */
6390 stream?: boolean;
6391 /**
6392 * The maximum number of tokens to generate in the response.
6393 */
6394 max_tokens?: number;
6395 /**
6396 * Controls the randomness of the output; higher values produce more random results.
6397 */
6398 temperature?: number;
6399 /**
6400 * 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.
6401 */
6402 top_p?: number;
6403 /**
6404 * 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.
6405 */
6406 top_k?: number;
6407 /**
6408 * Random seed for reproducibility of the generation.
6409 */
6410 seed?: number;
6411 /**
6412 * Penalty for repeated tokens; higher values discourage repetition.
6413 */
6414 repetition_penalty?: number;
6415 /**
6416 * Decreases the likelihood of the model repeating the same lines verbatim.
6417 */
6418 frequency_penalty?: number;
6419 /**
6420 * Increases the likelihood of the model introducing new topics.
6421 */
6422 presence_penalty?: number;
6423}
6424type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = {
6425 /**
6426 * The generated text response from the model
6427 */
6428 response?: string;
6429 /**
6430 * An array of tool calls requests made during the response generation
6431 */
6432 tool_calls?: {
6433 /**
6434 * The arguments passed to be passed to the tool call request
6435 */
6436 arguments?: object;
6437 /**
6438 * The name of the tool to be called
6439 */
6440 name?: string;
6441 }[];
6442};
6443declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct {
6444 inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input;
6445 postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output;
6446}
6447type 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;
6448interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt {
6449 /**
6450 * The input text prompt for the model to generate a response.
6451 */
6452 prompt: string;
6453 /**
6454 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
6455 */
6456 lora?: string;
6457 response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode;
6458 /**
6459 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
6460 */
6461 raw?: boolean;
6462 /**
6463 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
6464 */
6465 stream?: boolean;
6466 /**
6467 * The maximum number of tokens to generate in the response.
6468 */
6469 max_tokens?: number;
6470 /**
6471 * Controls the randomness of the output; higher values produce more random results.
6472 */
6473 temperature?: number;
6474 /**
6475 * 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.
6476 */
6477 top_p?: number;
6478 /**
6479 * 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.
6480 */
6481 top_k?: number;
6482 /**
6483 * Random seed for reproducibility of the generation.
6484 */
6485 seed?: number;
6486 /**
6487 * Penalty for repeated tokens; higher values discourage repetition.
6488 */
6489 repetition_penalty?: number;
6490 /**
6491 * Decreases the likelihood of the model repeating the same lines verbatim.
6492 */
6493 frequency_penalty?: number;
6494 /**
6495 * Increases the likelihood of the model introducing new topics.
6496 */
6497 presence_penalty?: number;
6498}
6499interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode {
6500 type?: "json_object" | "json_schema";
6501 json_schema?: unknown;
6502}
6503interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages {
6504 /**
6505 * An array of message objects representing the conversation history.
6506 */
6507 messages: {
6508 /**
6509 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
6510 */
6511 role: string;
6512 content: string | {
6513 /**
6514 * Type of the content (text)
6515 */
6516 type?: string;
6517 /**
6518 * Text content
6519 */
6520 text?: string;
6521 }[];
6522 }[];
6523 functions?: {
6524 name: string;
6525 code: string;
6526 }[];
6527 /**
6528 * A list of tools available for the assistant to use.
6529 */
6530 tools?: ({
6531 /**
6532 * The name of the tool. More descriptive the better.
6533 */
6534 name: string;
6535 /**
6536 * A brief description of what the tool does.
6537 */
6538 description: string;
6539 /**
6540 * Schema defining the parameters accepted by the tool.
6541 */
6542 parameters: {
6543 /**
6544 * The type of the parameters object (usually 'object').
6545 */
6546 type: string;
6547 /**
6548 * List of required parameter names.
6549 */
6550 required?: string[];
6551 /**
6552 * Definitions of each parameter.
6553 */
6554 properties: {
6555 [k: string]: {
6556 /**
6557 * The data type of the parameter.
6558 */
6559 type: string;
6560 /**
6561 * A description of the expected parameter.
6562 */
6563 description: string;
6564 };
6565 };
6566 };
6567 } | {
6568 /**
6569 * Specifies the type of tool (e.g., 'function').
6570 */
6571 type: string;
6572 /**
6573 * Details of the function tool.
6574 */
6575 function: {
6576 /**
6577 * The name of the function.
6578 */
6579 name: string;
6580 /**
6581 * A brief description of what the function does.
6582 */
6583 description: string;
6584 /**
6585 * Schema defining the parameters accepted by the function.
6586 */
6587 parameters: {
6588 /**
6589 * The type of the parameters object (usually 'object').
6590 */
6591 type: string;
6592 /**
6593 * List of required parameter names.
6594 */
6595 required?: string[];
6596 /**
6597 * Definitions of each parameter.
6598 */
6599 properties: {
6600 [k: string]: {
6601 /**
6602 * The data type of the parameter.
6603 */
6604 type: string;
6605 /**
6606 * A description of the expected parameter.
6607 */
6608 description: string;
6609 };
6610 };
6611 };
6612 };
6613 })[];
6614 response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1;
6615 /**
6616 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
6617 */
6618 raw?: boolean;
6619 /**
6620 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
6621 */
6622 stream?: boolean;
6623 /**
6624 * The maximum number of tokens to generate in the response.
6625 */
6626 max_tokens?: number;
6627 /**
6628 * Controls the randomness of the output; higher values produce more random results.
6629 */
6630 temperature?: number;
6631 /**
6632 * 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.
6633 */
6634 top_p?: number;
6635 /**
6636 * 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.
6637 */
6638 top_k?: number;
6639 /**
6640 * Random seed for reproducibility of the generation.
6641 */
6642 seed?: number;
6643 /**
6644 * Penalty for repeated tokens; higher values discourage repetition.
6645 */
6646 repetition_penalty?: number;
6647 /**
6648 * Decreases the likelihood of the model repeating the same lines verbatim.
6649 */
6650 frequency_penalty?: number;
6651 /**
6652 * Increases the likelihood of the model introducing new topics.
6653 */
6654 presence_penalty?: number;
6655}
6656interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 {
6657 type?: "json_object" | "json_schema";
6658 json_schema?: unknown;
6659}
6660interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch {
6661 requests?: {
6662 /**
6663 * 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.
6664 */
6665 external_reference?: string;
6666 /**
6667 * Prompt for the text generation model
6668 */
6669 prompt?: string;
6670 /**
6671 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
6672 */
6673 stream?: boolean;
6674 /**
6675 * The maximum number of tokens to generate in the response.
6676 */
6677 max_tokens?: number;
6678 /**
6679 * Controls the randomness of the output; higher values produce more random results.
6680 */
6681 temperature?: number;
6682 /**
6683 * 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.
6684 */
6685 top_p?: number;
6686 /**
6687 * Random seed for reproducibility of the generation.
6688 */
6689 seed?: number;
6690 /**
6691 * Penalty for repeated tokens; higher values discourage repetition.
6692 */
6693 repetition_penalty?: number;
6694 /**
6695 * Decreases the likelihood of the model repeating the same lines verbatim.
6696 */
6697 frequency_penalty?: number;
6698 /**
6699 * Increases the likelihood of the model introducing new topics.
6700 */
6701 presence_penalty?: number;
6702 response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2;
6703 }[];
6704}
6705interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 {
6706 type?: "json_object" | "json_schema";
6707 json_schema?: unknown;
6708}
6709type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = {
6710 /**
6711 * The generated text response from the model
6712 */
6713 response: string;
6714 /**
6715 * Usage statistics for the inference request
6716 */
6717 usage?: {
6718 /**
6719 * Total number of tokens in input
6720 */
6721 prompt_tokens?: number;
6722 /**
6723 * Total number of tokens in output
6724 */
6725 completion_tokens?: number;
6726 /**
6727 * Total number of input and output tokens
6728 */
6729 total_tokens?: number;
6730 };
6731 /**
6732 * An array of tool calls requests made during the response generation
6733 */
6734 tool_calls?: {
6735 /**
6736 * The arguments passed to be passed to the tool call request
6737 */
6738 arguments?: object;
6739 /**
6740 * The name of the tool to be called
6741 */
6742 name?: string;
6743 }[];
6744} | string | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse;
6745interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse {
6746 /**
6747 * The async request id that can be used to obtain the results.
6748 */
6749 request_id?: string;
6750}
6751declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast {
6752 inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input;
6753 postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output;
6754}
6755interface Ai_Cf_Meta_Llama_Guard_3_8B_Input {
6756 /**
6757 * An array of message objects representing the conversation history.
6758 */
6759 messages: {
6760 /**
6761 * The role of the message sender must alternate between 'user' and 'assistant'.
6762 */
6763 role: "user" | "assistant";
6764 /**
6765 * The content of the message as a string.
6766 */
6767 content: string;
6768 }[];
6769 /**
6770 * The maximum number of tokens to generate in the response.
6771 */
6772 max_tokens?: number;
6773 /**
6774 * Controls the randomness of the output; higher values produce more random results.
6775 */
6776 temperature?: number;
6777 /**
6778 * Dictate the output format of the generated response.
6779 */
6780 response_format?: {
6781 /**
6782 * Set to json_object to process and output generated text as JSON.
6783 */
6784 type?: string;
6785 };
6786}
6787interface Ai_Cf_Meta_Llama_Guard_3_8B_Output {
6788 response?: string | {
6789 /**
6790 * Whether the conversation is safe or not.
6791 */
6792 safe?: boolean;
6793 /**
6794 * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe.
6795 */
6796 categories?: string[];
6797 };
6798 /**
6799 * Usage statistics for the inference request
6800 */
6801 usage?: {
6802 /**
6803 * Total number of tokens in input
6804 */
6805 prompt_tokens?: number;
6806 /**
6807 * Total number of tokens in output
6808 */
6809 completion_tokens?: number;
6810 /**
6811 * Total number of input and output tokens
6812 */
6813 total_tokens?: number;
6814 };
6815}
6816declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B {
6817 inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input;
6818 postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output;
6819}
6820interface Ai_Cf_Baai_Bge_Reranker_Base_Input {
6821 /**
6822 * A query you wish to perform against the provided contexts.
6823 */
6824 /**
6825 * Number of returned results starting with the best score.
6826 */
6827 top_k?: number;
6828 /**
6829 * List of provided contexts. Note that the index in this array is important, as the response will refer to it.
6830 */
6831 contexts: {
6832 /**
6833 * One of the provided context content
6834 */
6835 text?: string;
6836 }[];
6837}
6838interface Ai_Cf_Baai_Bge_Reranker_Base_Output {
6839 response?: {
6840 /**
6841 * Index of the context in the request
6842 */
6843 id?: number;
6844 /**
6845 * Score of the context under the index.
6846 */
6847 score?: number;
6848 }[];
6849}
6850declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base {
6851 inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input;
6852 postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output;
6853}
6854type 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;
6855interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt {
6856 /**
6857 * The input text prompt for the model to generate a response.
6858 */
6859 prompt: string;
6860 /**
6861 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
6862 */
6863 lora?: string;
6864 response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode;
6865 /**
6866 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
6867 */
6868 raw?: boolean;
6869 /**
6870 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
6871 */
6872 stream?: boolean;
6873 /**
6874 * The maximum number of tokens to generate in the response.
6875 */
6876 max_tokens?: number;
6877 /**
6878 * Controls the randomness of the output; higher values produce more random results.
6879 */
6880 temperature?: number;
6881 /**
6882 * 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.
6883 */
6884 top_p?: number;
6885 /**
6886 * 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.
6887 */
6888 top_k?: number;
6889 /**
6890 * Random seed for reproducibility of the generation.
6891 */
6892 seed?: number;
6893 /**
6894 * Penalty for repeated tokens; higher values discourage repetition.
6895 */
6896 repetition_penalty?: number;
6897 /**
6898 * Decreases the likelihood of the model repeating the same lines verbatim.
6899 */
6900 frequency_penalty?: number;
6901 /**
6902 * Increases the likelihood of the model introducing new topics.
6903 */
6904 presence_penalty?: number;
6905}
6906interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode {
6907 type?: "json_object" | "json_schema";
6908 json_schema?: unknown;
6909}
6910interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages {
6911 /**
6912 * An array of message objects representing the conversation history.
6913 */
6914 messages: {
6915 /**
6916 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
6917 */
6918 role: string;
6919 /**
6920 * The content of the message as a string.
6921 */
6922 content: string;
6923 }[];
6924 functions?: {
6925 name: string;
6926 code: string;
6927 }[];
6928 /**
6929 * A list of tools available for the assistant to use.
6930 */
6931 tools?: ({
6932 /**
6933 * The name of the tool. More descriptive the better.
6934 */
6935 name: string;
6936 /**
6937 * A brief description of what the tool does.
6938 */
6939 description: string;
6940 /**
6941 * Schema defining the parameters accepted by the tool.
6942 */
6943 parameters: {
6944 /**
6945 * The type of the parameters object (usually 'object').
6946 */
6947 type: string;
6948 /**
6949 * List of required parameter names.
6950 */
6951 required?: string[];
6952 /**
6953 * Definitions of each parameter.
6954 */
6955 properties: {
6956 [k: string]: {
6957 /**
6958 * The data type of the parameter.
6959 */
6960 type: string;
6961 /**
6962 * A description of the expected parameter.
6963 */
6964 description: string;
6965 };
6966 };
6967 };
6968 } | {
6969 /**
6970 * Specifies the type of tool (e.g., 'function').
6971 */
6972 type: string;
6973 /**
6974 * Details of the function tool.
6975 */
6976 function: {
6977 /**
6978 * The name of the function.
6979 */
6980 name: string;
6981 /**
6982 * A brief description of what the function does.
6983 */
6984 description: string;
6985 /**
6986 * Schema defining the parameters accepted by the function.
6987 */
6988 parameters: {
6989 /**
6990 * The type of the parameters object (usually 'object').
6991 */
6992 type: string;
6993 /**
6994 * List of required parameter names.
6995 */
6996 required?: string[];
6997 /**
6998 * Definitions of each parameter.
6999 */
7000 properties: {
7001 [k: string]: {
7002 /**
7003 * The data type of the parameter.
7004 */
7005 type: string;
7006 /**
7007 * A description of the expected parameter.
7008 */
7009 description: string;
7010 };
7011 };
7012 };
7013 };
7014 })[];
7015 response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1;
7016 /**
7017 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7018 */
7019 raw?: boolean;
7020 /**
7021 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7022 */
7023 stream?: boolean;
7024 /**
7025 * The maximum number of tokens to generate in the response.
7026 */
7027 max_tokens?: number;
7028 /**
7029 * Controls the randomness of the output; higher values produce more random results.
7030 */
7031 temperature?: number;
7032 /**
7033 * 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.
7034 */
7035 top_p?: number;
7036 /**
7037 * 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.
7038 */
7039 top_k?: number;
7040 /**
7041 * Random seed for reproducibility of the generation.
7042 */
7043 seed?: number;
7044 /**
7045 * Penalty for repeated tokens; higher values discourage repetition.
7046 */
7047 repetition_penalty?: number;
7048 /**
7049 * Decreases the likelihood of the model repeating the same lines verbatim.
7050 */
7051 frequency_penalty?: number;
7052 /**
7053 * Increases the likelihood of the model introducing new topics.
7054 */
7055 presence_penalty?: number;
7056}
7057interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 {
7058 type?: "json_object" | "json_schema";
7059 json_schema?: unknown;
7060}
7061type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = {
7062 /**
7063 * The generated text response from the model
7064 */
7065 response: string;
7066 /**
7067 * Usage statistics for the inference request
7068 */
7069 usage?: {
7070 /**
7071 * Total number of tokens in input
7072 */
7073 prompt_tokens?: number;
7074 /**
7075 * Total number of tokens in output
7076 */
7077 completion_tokens?: number;
7078 /**
7079 * Total number of input and output tokens
7080 */
7081 total_tokens?: number;
7082 };
7083 /**
7084 * An array of tool calls requests made during the response generation
7085 */
7086 tool_calls?: {
7087 /**
7088 * The arguments passed to be passed to the tool call request
7089 */
7090 arguments?: object;
7091 /**
7092 * The name of the tool to be called
7093 */
7094 name?: string;
7095 }[];
7096};
7097declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct {
7098 inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input;
7099 postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output;
7100}
7101type Ai_Cf_Qwen_Qwq_32B_Input = Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages;
7102interface Ai_Cf_Qwen_Qwq_32B_Prompt {
7103 /**
7104 * The input text prompt for the model to generate a response.
7105 */
7106 prompt: string;
7107 /**
7108 * JSON schema that should be fulfilled for the response.
7109 */
7110 guided_json?: object;
7111 /**
7112 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7113 */
7114 raw?: boolean;
7115 /**
7116 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7117 */
7118 stream?: boolean;
7119 /**
7120 * The maximum number of tokens to generate in the response.
7121 */
7122 max_tokens?: number;
7123 /**
7124 * Controls the randomness of the output; higher values produce more random results.
7125 */
7126 temperature?: number;
7127 /**
7128 * 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.
7129 */
7130 top_p?: number;
7131 /**
7132 * 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.
7133 */
7134 top_k?: number;
7135 /**
7136 * Random seed for reproducibility of the generation.
7137 */
7138 seed?: number;
7139 /**
7140 * Penalty for repeated tokens; higher values discourage repetition.
7141 */
7142 repetition_penalty?: number;
7143 /**
7144 * Decreases the likelihood of the model repeating the same lines verbatim.
7145 */
7146 frequency_penalty?: number;
7147 /**
7148 * Increases the likelihood of the model introducing new topics.
7149 */
7150 presence_penalty?: number;
7151}
7152interface Ai_Cf_Qwen_Qwq_32B_Messages {
7153 /**
7154 * An array of message objects representing the conversation history.
7155 */
7156 messages: {
7157 /**
7158 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
7159 */
7160 role?: string;
7161 /**
7162 * The tool call id. If you don't know what to put here you can fall back to 000000001
7163 */
7164 tool_call_id?: string;
7165 content?: string | {
7166 /**
7167 * Type of the content provided
7168 */
7169 type?: string;
7170 text?: string;
7171 image_url?: {
7172 /**
7173 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7174 */
7175 url?: string;
7176 };
7177 }[] | {
7178 /**
7179 * Type of the content provided
7180 */
7181 type?: string;
7182 text?: string;
7183 image_url?: {
7184 /**
7185 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7186 */
7187 url?: string;
7188 };
7189 };
7190 }[];
7191 functions?: {
7192 name: string;
7193 code: string;
7194 }[];
7195 /**
7196 * A list of tools available for the assistant to use.
7197 */
7198 tools?: ({
7199 /**
7200 * The name of the tool. More descriptive the better.
7201 */
7202 name: string;
7203 /**
7204 * A brief description of what the tool does.
7205 */
7206 description: string;
7207 /**
7208 * Schema defining the parameters accepted by the tool.
7209 */
7210 parameters: {
7211 /**
7212 * The type of the parameters object (usually 'object').
7213 */
7214 type: string;
7215 /**
7216 * List of required parameter names.
7217 */
7218 required?: string[];
7219 /**
7220 * Definitions of each parameter.
7221 */
7222 properties: {
7223 [k: string]: {
7224 /**
7225 * The data type of the parameter.
7226 */
7227 type: string;
7228 /**
7229 * A description of the expected parameter.
7230 */
7231 description: string;
7232 };
7233 };
7234 };
7235 } | {
7236 /**
7237 * Specifies the type of tool (e.g., 'function').
7238 */
7239 type: string;
7240 /**
7241 * Details of the function tool.
7242 */
7243 function: {
7244 /**
7245 * The name of the function.
7246 */
7247 name: string;
7248 /**
7249 * A brief description of what the function does.
7250 */
7251 description: string;
7252 /**
7253 * Schema defining the parameters accepted by the function.
7254 */
7255 parameters: {
7256 /**
7257 * The type of the parameters object (usually 'object').
7258 */
7259 type: string;
7260 /**
7261 * List of required parameter names.
7262 */
7263 required?: string[];
7264 /**
7265 * Definitions of each parameter.
7266 */
7267 properties: {
7268 [k: string]: {
7269 /**
7270 * The data type of the parameter.
7271 */
7272 type: string;
7273 /**
7274 * A description of the expected parameter.
7275 */
7276 description: string;
7277 };
7278 };
7279 };
7280 };
7281 })[];
7282 /**
7283 * JSON schema that should be fufilled for the response.
7284 */
7285 guided_json?: object;
7286 /**
7287 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7288 */
7289 raw?: boolean;
7290 /**
7291 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7292 */
7293 stream?: boolean;
7294 /**
7295 * The maximum number of tokens to generate in the response.
7296 */
7297 max_tokens?: number;
7298 /**
7299 * Controls the randomness of the output; higher values produce more random results.
7300 */
7301 temperature?: number;
7302 /**
7303 * 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.
7304 */
7305 top_p?: number;
7306 /**
7307 * 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.
7308 */
7309 top_k?: number;
7310 /**
7311 * Random seed for reproducibility of the generation.
7312 */
7313 seed?: number;
7314 /**
7315 * Penalty for repeated tokens; higher values discourage repetition.
7316 */
7317 repetition_penalty?: number;
7318 /**
7319 * Decreases the likelihood of the model repeating the same lines verbatim.
7320 */
7321 frequency_penalty?: number;
7322 /**
7323 * Increases the likelihood of the model introducing new topics.
7324 */
7325 presence_penalty?: number;
7326}
7327type Ai_Cf_Qwen_Qwq_32B_Output = {
7328 /**
7329 * The generated text response from the model
7330 */
7331 response: string;
7332 /**
7333 * Usage statistics for the inference request
7334 */
7335 usage?: {
7336 /**
7337 * Total number of tokens in input
7338 */
7339 prompt_tokens?: number;
7340 /**
7341 * Total number of tokens in output
7342 */
7343 completion_tokens?: number;
7344 /**
7345 * Total number of input and output tokens
7346 */
7347 total_tokens?: number;
7348 };
7349 /**
7350 * An array of tool calls requests made during the response generation
7351 */
7352 tool_calls?: {
7353 /**
7354 * The arguments passed to be passed to the tool call request
7355 */
7356 arguments?: object;
7357 /**
7358 * The name of the tool to be called
7359 */
7360 name?: string;
7361 }[];
7362};
7363declare abstract class Base_Ai_Cf_Qwen_Qwq_32B {
7364 inputs: Ai_Cf_Qwen_Qwq_32B_Input;
7365 postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output;
7366}
7367type 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;
7368interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt {
7369 /**
7370 * The input text prompt for the model to generate a response.
7371 */
7372 prompt: string;
7373 /**
7374 * JSON schema that should be fulfilled for the response.
7375 */
7376 guided_json?: object;
7377 /**
7378 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7379 */
7380 raw?: boolean;
7381 /**
7382 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7383 */
7384 stream?: boolean;
7385 /**
7386 * The maximum number of tokens to generate in the response.
7387 */
7388 max_tokens?: number;
7389 /**
7390 * Controls the randomness of the output; higher values produce more random results.
7391 */
7392 temperature?: number;
7393 /**
7394 * 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.
7395 */
7396 top_p?: number;
7397 /**
7398 * 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.
7399 */
7400 top_k?: number;
7401 /**
7402 * Random seed for reproducibility of the generation.
7403 */
7404 seed?: number;
7405 /**
7406 * Penalty for repeated tokens; higher values discourage repetition.
7407 */
7408 repetition_penalty?: number;
7409 /**
7410 * Decreases the likelihood of the model repeating the same lines verbatim.
7411 */
7412 frequency_penalty?: number;
7413 /**
7414 * Increases the likelihood of the model introducing new topics.
7415 */
7416 presence_penalty?: number;
7417}
7418interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages {
7419 /**
7420 * An array of message objects representing the conversation history.
7421 */
7422 messages: {
7423 /**
7424 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
7425 */
7426 role?: string;
7427 /**
7428 * 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
7429 */
7430 tool_call_id?: string;
7431 content?: string | {
7432 /**
7433 * Type of the content provided
7434 */
7435 type?: string;
7436 text?: string;
7437 image_url?: {
7438 /**
7439 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7440 */
7441 url?: string;
7442 };
7443 }[] | {
7444 /**
7445 * Type of the content provided
7446 */
7447 type?: string;
7448 text?: string;
7449 image_url?: {
7450 /**
7451 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7452 */
7453 url?: string;
7454 };
7455 };
7456 }[];
7457 functions?: {
7458 name: string;
7459 code: string;
7460 }[];
7461 /**
7462 * A list of tools available for the assistant to use.
7463 */
7464 tools?: ({
7465 /**
7466 * The name of the tool. More descriptive the better.
7467 */
7468 name: string;
7469 /**
7470 * A brief description of what the tool does.
7471 */
7472 description: string;
7473 /**
7474 * Schema defining the parameters accepted by the tool.
7475 */
7476 parameters: {
7477 /**
7478 * The type of the parameters object (usually 'object').
7479 */
7480 type: string;
7481 /**
7482 * List of required parameter names.
7483 */
7484 required?: string[];
7485 /**
7486 * Definitions of each parameter.
7487 */
7488 properties: {
7489 [k: string]: {
7490 /**
7491 * The data type of the parameter.
7492 */
7493 type: string;
7494 /**
7495 * A description of the expected parameter.
7496 */
7497 description: string;
7498 };
7499 };
7500 };
7501 } | {
7502 /**
7503 * Specifies the type of tool (e.g., 'function').
7504 */
7505 type: string;
7506 /**
7507 * Details of the function tool.
7508 */
7509 function: {
7510 /**
7511 * The name of the function.
7512 */
7513 name: string;
7514 /**
7515 * A brief description of what the function does.
7516 */
7517 description: string;
7518 /**
7519 * Schema defining the parameters accepted by the function.
7520 */
7521 parameters: {
7522 /**
7523 * The type of the parameters object (usually 'object').
7524 */
7525 type: string;
7526 /**
7527 * List of required parameter names.
7528 */
7529 required?: string[];
7530 /**
7531 * Definitions of each parameter.
7532 */
7533 properties: {
7534 [k: string]: {
7535 /**
7536 * The data type of the parameter.
7537 */
7538 type: string;
7539 /**
7540 * A description of the expected parameter.
7541 */
7542 description: string;
7543 };
7544 };
7545 };
7546 };
7547 })[];
7548 /**
7549 * JSON schema that should be fufilled for the response.
7550 */
7551 guided_json?: object;
7552 /**
7553 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7554 */
7555 raw?: boolean;
7556 /**
7557 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7558 */
7559 stream?: boolean;
7560 /**
7561 * The maximum number of tokens to generate in the response.
7562 */
7563 max_tokens?: number;
7564 /**
7565 * Controls the randomness of the output; higher values produce more random results.
7566 */
7567 temperature?: number;
7568 /**
7569 * 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.
7570 */
7571 top_p?: number;
7572 /**
7573 * 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.
7574 */
7575 top_k?: number;
7576 /**
7577 * Random seed for reproducibility of the generation.
7578 */
7579 seed?: number;
7580 /**
7581 * Penalty for repeated tokens; higher values discourage repetition.
7582 */
7583 repetition_penalty?: number;
7584 /**
7585 * Decreases the likelihood of the model repeating the same lines verbatim.
7586 */
7587 frequency_penalty?: number;
7588 /**
7589 * Increases the likelihood of the model introducing new topics.
7590 */
7591 presence_penalty?: number;
7592}
7593type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = {
7594 /**
7595 * The generated text response from the model
7596 */
7597 response: string;
7598 /**
7599 * Usage statistics for the inference request
7600 */
7601 usage?: {
7602 /**
7603 * Total number of tokens in input
7604 */
7605 prompt_tokens?: number;
7606 /**
7607 * Total number of tokens in output
7608 */
7609 completion_tokens?: number;
7610 /**
7611 * Total number of input and output tokens
7612 */
7613 total_tokens?: number;
7614 };
7615 /**
7616 * An array of tool calls requests made during the response generation
7617 */
7618 tool_calls?: {
7619 /**
7620 * The arguments passed to be passed to the tool call request
7621 */
7622 arguments?: object;
7623 /**
7624 * The name of the tool to be called
7625 */
7626 name?: string;
7627 }[];
7628};
7629declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct {
7630 inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input;
7631 postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output;
7632}
7633type Ai_Cf_Google_Gemma_3_12B_It_Input = Ai_Cf_Google_Gemma_3_12B_It_Prompt | Ai_Cf_Google_Gemma_3_12B_It_Messages;
7634interface Ai_Cf_Google_Gemma_3_12B_It_Prompt {
7635 /**
7636 * The input text prompt for the model to generate a response.
7637 */
7638 prompt: string;
7639 /**
7640 * JSON schema that should be fufilled for the response.
7641 */
7642 guided_json?: object;
7643 /**
7644 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7645 */
7646 raw?: boolean;
7647 /**
7648 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7649 */
7650 stream?: boolean;
7651 /**
7652 * The maximum number of tokens to generate in the response.
7653 */
7654 max_tokens?: number;
7655 /**
7656 * Controls the randomness of the output; higher values produce more random results.
7657 */
7658 temperature?: number;
7659 /**
7660 * 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.
7661 */
7662 top_p?: number;
7663 /**
7664 * 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.
7665 */
7666 top_k?: number;
7667 /**
7668 * Random seed for reproducibility of the generation.
7669 */
7670 seed?: number;
7671 /**
7672 * Penalty for repeated tokens; higher values discourage repetition.
7673 */
7674 repetition_penalty?: number;
7675 /**
7676 * Decreases the likelihood of the model repeating the same lines verbatim.
7677 */
7678 frequency_penalty?: number;
7679 /**
7680 * Increases the likelihood of the model introducing new topics.
7681 */
7682 presence_penalty?: number;
7683}
7684interface Ai_Cf_Google_Gemma_3_12B_It_Messages {
7685 /**
7686 * An array of message objects representing the conversation history.
7687 */
7688 messages: {
7689 /**
7690 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
7691 */
7692 role?: string;
7693 content?: string | {
7694 /**
7695 * Type of the content provided
7696 */
7697 type?: string;
7698 text?: string;
7699 image_url?: {
7700 /**
7701 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7702 */
7703 url?: string;
7704 };
7705 }[];
7706 }[];
7707 functions?: {
7708 name: string;
7709 code: string;
7710 }[];
7711 /**
7712 * A list of tools available for the assistant to use.
7713 */
7714 tools?: ({
7715 /**
7716 * The name of the tool. More descriptive the better.
7717 */
7718 name: string;
7719 /**
7720 * A brief description of what the tool does.
7721 */
7722 description: string;
7723 /**
7724 * Schema defining the parameters accepted by the tool.
7725 */
7726 parameters: {
7727 /**
7728 * The type of the parameters object (usually 'object').
7729 */
7730 type: string;
7731 /**
7732 * List of required parameter names.
7733 */
7734 required?: string[];
7735 /**
7736 * Definitions of each parameter.
7737 */
7738 properties: {
7739 [k: string]: {
7740 /**
7741 * The data type of the parameter.
7742 */
7743 type: string;
7744 /**
7745 * A description of the expected parameter.
7746 */
7747 description: string;
7748 };
7749 };
7750 };
7751 } | {
7752 /**
7753 * Specifies the type of tool (e.g., 'function').
7754 */
7755 type: string;
7756 /**
7757 * Details of the function tool.
7758 */
7759 function: {
7760 /**
7761 * The name of the function.
7762 */
7763 name: string;
7764 /**
7765 * A brief description of what the function does.
7766 */
7767 description: string;
7768 /**
7769 * Schema defining the parameters accepted by the function.
7770 */
7771 parameters: {
7772 /**
7773 * The type of the parameters object (usually 'object').
7774 */
7775 type: string;
7776 /**
7777 * List of required parameter names.
7778 */
7779 required?: string[];
7780 /**
7781 * Definitions of each parameter.
7782 */
7783 properties: {
7784 [k: string]: {
7785 /**
7786 * The data type of the parameter.
7787 */
7788 type: string;
7789 /**
7790 * A description of the expected parameter.
7791 */
7792 description: string;
7793 };
7794 };
7795 };
7796 };
7797 })[];
7798 /**
7799 * JSON schema that should be fufilled for the response.
7800 */
7801 guided_json?: object;
7802 /**
7803 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7804 */
7805 raw?: boolean;
7806 /**
7807 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7808 */
7809 stream?: boolean;
7810 /**
7811 * The maximum number of tokens to generate in the response.
7812 */
7813 max_tokens?: number;
7814 /**
7815 * Controls the randomness of the output; higher values produce more random results.
7816 */
7817 temperature?: number;
7818 /**
7819 * 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.
7820 */
7821 top_p?: number;
7822 /**
7823 * 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.
7824 */
7825 top_k?: number;
7826 /**
7827 * Random seed for reproducibility of the generation.
7828 */
7829 seed?: number;
7830 /**
7831 * Penalty for repeated tokens; higher values discourage repetition.
7832 */
7833 repetition_penalty?: number;
7834 /**
7835 * Decreases the likelihood of the model repeating the same lines verbatim.
7836 */
7837 frequency_penalty?: number;
7838 /**
7839 * Increases the likelihood of the model introducing new topics.
7840 */
7841 presence_penalty?: number;
7842}
7843type Ai_Cf_Google_Gemma_3_12B_It_Output = {
7844 /**
7845 * The generated text response from the model
7846 */
7847 response: string;
7848 /**
7849 * Usage statistics for the inference request
7850 */
7851 usage?: {
7852 /**
7853 * Total number of tokens in input
7854 */
7855 prompt_tokens?: number;
7856 /**
7857 * Total number of tokens in output
7858 */
7859 completion_tokens?: number;
7860 /**
7861 * Total number of input and output tokens
7862 */
7863 total_tokens?: number;
7864 };
7865 /**
7866 * An array of tool calls requests made during the response generation
7867 */
7868 tool_calls?: {
7869 /**
7870 * The arguments passed to be passed to the tool call request
7871 */
7872 arguments?: object;
7873 /**
7874 * The name of the tool to be called
7875 */
7876 name?: string;
7877 }[];
7878};
7879declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It {
7880 inputs: Ai_Cf_Google_Gemma_3_12B_It_Input;
7881 postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output;
7882}
7883type 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;
7884interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt {
7885 /**
7886 * The input text prompt for the model to generate a response.
7887 */
7888 prompt: string;
7889 /**
7890 * JSON schema that should be fulfilled for the response.
7891 */
7892 guided_json?: object;
7893 response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode;
7894 /**
7895 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
7896 */
7897 raw?: boolean;
7898 /**
7899 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
7900 */
7901 stream?: boolean;
7902 /**
7903 * The maximum number of tokens to generate in the response.
7904 */
7905 max_tokens?: number;
7906 /**
7907 * Controls the randomness of the output; higher values produce more random results.
7908 */
7909 temperature?: number;
7910 /**
7911 * 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.
7912 */
7913 top_p?: number;
7914 /**
7915 * 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.
7916 */
7917 top_k?: number;
7918 /**
7919 * Random seed for reproducibility of the generation.
7920 */
7921 seed?: number;
7922 /**
7923 * Penalty for repeated tokens; higher values discourage repetition.
7924 */
7925 repetition_penalty?: number;
7926 /**
7927 * Decreases the likelihood of the model repeating the same lines verbatim.
7928 */
7929 frequency_penalty?: number;
7930 /**
7931 * Increases the likelihood of the model introducing new topics.
7932 */
7933 presence_penalty?: number;
7934}
7935interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode {
7936 type?: "json_object" | "json_schema";
7937 json_schema?: unknown;
7938}
7939interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages {
7940 /**
7941 * An array of message objects representing the conversation history.
7942 */
7943 messages: {
7944 /**
7945 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
7946 */
7947 role?: string;
7948 /**
7949 * The tool call id. If you don't know what to put here you can fall back to 000000001
7950 */
7951 tool_call_id?: string;
7952 content?: string | {
7953 /**
7954 * Type of the content provided
7955 */
7956 type?: string;
7957 text?: string;
7958 image_url?: {
7959 /**
7960 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7961 */
7962 url?: string;
7963 };
7964 }[] | {
7965 /**
7966 * Type of the content provided
7967 */
7968 type?: string;
7969 text?: string;
7970 image_url?: {
7971 /**
7972 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
7973 */
7974 url?: string;
7975 };
7976 };
7977 }[];
7978 functions?: {
7979 name: string;
7980 code: string;
7981 }[];
7982 /**
7983 * A list of tools available for the assistant to use.
7984 */
7985 tools?: ({
7986 /**
7987 * The name of the tool. More descriptive the better.
7988 */
7989 name: string;
7990 /**
7991 * A brief description of what the tool does.
7992 */
7993 description: string;
7994 /**
7995 * Schema defining the parameters accepted by the tool.
7996 */
7997 parameters: {
7998 /**
7999 * The type of the parameters object (usually 'object').
8000 */
8001 type: string;
8002 /**
8003 * List of required parameter names.
8004 */
8005 required?: string[];
8006 /**
8007 * Definitions of each parameter.
8008 */
8009 properties: {
8010 [k: string]: {
8011 /**
8012 * The data type of the parameter.
8013 */
8014 type: string;
8015 /**
8016 * A description of the expected parameter.
8017 */
8018 description: string;
8019 };
8020 };
8021 };
8022 } | {
8023 /**
8024 * Specifies the type of tool (e.g., 'function').
8025 */
8026 type: string;
8027 /**
8028 * Details of the function tool.
8029 */
8030 function: {
8031 /**
8032 * The name of the function.
8033 */
8034 name: string;
8035 /**
8036 * A brief description of what the function does.
8037 */
8038 description: string;
8039 /**
8040 * Schema defining the parameters accepted by the function.
8041 */
8042 parameters: {
8043 /**
8044 * The type of the parameters object (usually 'object').
8045 */
8046 type: string;
8047 /**
8048 * List of required parameter names.
8049 */
8050 required?: string[];
8051 /**
8052 * Definitions of each parameter.
8053 */
8054 properties: {
8055 [k: string]: {
8056 /**
8057 * The data type of the parameter.
8058 */
8059 type: string;
8060 /**
8061 * A description of the expected parameter.
8062 */
8063 description: string;
8064 };
8065 };
8066 };
8067 };
8068 })[];
8069 response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode;
8070 /**
8071 * JSON schema that should be fufilled for the response.
8072 */
8073 guided_json?: object;
8074 /**
8075 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8076 */
8077 raw?: boolean;
8078 /**
8079 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8080 */
8081 stream?: boolean;
8082 /**
8083 * The maximum number of tokens to generate in the response.
8084 */
8085 max_tokens?: number;
8086 /**
8087 * Controls the randomness of the output; higher values produce more random results.
8088 */
8089 temperature?: number;
8090 /**
8091 * 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.
8092 */
8093 top_p?: number;
8094 /**
8095 * 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.
8096 */
8097 top_k?: number;
8098 /**
8099 * Random seed for reproducibility of the generation.
8100 */
8101 seed?: number;
8102 /**
8103 * Penalty for repeated tokens; higher values discourage repetition.
8104 */
8105 repetition_penalty?: number;
8106 /**
8107 * Decreases the likelihood of the model repeating the same lines verbatim.
8108 */
8109 frequency_penalty?: number;
8110 /**
8111 * Increases the likelihood of the model introducing new topics.
8112 */
8113 presence_penalty?: number;
8114}
8115interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch {
8116 requests: (Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner)[];
8117}
8118interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner {
8119 /**
8120 * The input text prompt for the model to generate a response.
8121 */
8122 prompt: string;
8123 /**
8124 * JSON schema that should be fulfilled for the response.
8125 */
8126 guided_json?: object;
8127 response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode;
8128 /**
8129 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8130 */
8131 raw?: boolean;
8132 /**
8133 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8134 */
8135 stream?: boolean;
8136 /**
8137 * The maximum number of tokens to generate in the response.
8138 */
8139 max_tokens?: number;
8140 /**
8141 * Controls the randomness of the output; higher values produce more random results.
8142 */
8143 temperature?: number;
8144 /**
8145 * 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.
8146 */
8147 top_p?: number;
8148 /**
8149 * 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.
8150 */
8151 top_k?: number;
8152 /**
8153 * Random seed for reproducibility of the generation.
8154 */
8155 seed?: number;
8156 /**
8157 * Penalty for repeated tokens; higher values discourage repetition.
8158 */
8159 repetition_penalty?: number;
8160 /**
8161 * Decreases the likelihood of the model repeating the same lines verbatim.
8162 */
8163 frequency_penalty?: number;
8164 /**
8165 * Increases the likelihood of the model introducing new topics.
8166 */
8167 presence_penalty?: number;
8168}
8169interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner {
8170 /**
8171 * An array of message objects representing the conversation history.
8172 */
8173 messages: {
8174 /**
8175 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
8176 */
8177 role?: string;
8178 /**
8179 * The tool call id. If you don't know what to put here you can fall back to 000000001
8180 */
8181 tool_call_id?: string;
8182 content?: string | {
8183 /**
8184 * Type of the content provided
8185 */
8186 type?: string;
8187 text?: string;
8188 image_url?: {
8189 /**
8190 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
8191 */
8192 url?: string;
8193 };
8194 }[] | {
8195 /**
8196 * Type of the content provided
8197 */
8198 type?: string;
8199 text?: string;
8200 image_url?: {
8201 /**
8202 * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted
8203 */
8204 url?: string;
8205 };
8206 };
8207 }[];
8208 functions?: {
8209 name: string;
8210 code: string;
8211 }[];
8212 /**
8213 * A list of tools available for the assistant to use.
8214 */
8215 tools?: ({
8216 /**
8217 * The name of the tool. More descriptive the better.
8218 */
8219 name: string;
8220 /**
8221 * A brief description of what the tool does.
8222 */
8223 description: string;
8224 /**
8225 * Schema defining the parameters accepted by the tool.
8226 */
8227 parameters: {
8228 /**
8229 * The type of the parameters object (usually 'object').
8230 */
8231 type: string;
8232 /**
8233 * List of required parameter names.
8234 */
8235 required?: string[];
8236 /**
8237 * Definitions of each parameter.
8238 */
8239 properties: {
8240 [k: string]: {
8241 /**
8242 * The data type of the parameter.
8243 */
8244 type: string;
8245 /**
8246 * A description of the expected parameter.
8247 */
8248 description: string;
8249 };
8250 };
8251 };
8252 } | {
8253 /**
8254 * Specifies the type of tool (e.g., 'function').
8255 */
8256 type: string;
8257 /**
8258 * Details of the function tool.
8259 */
8260 function: {
8261 /**
8262 * The name of the function.
8263 */
8264 name: string;
8265 /**
8266 * A brief description of what the function does.
8267 */
8268 description: string;
8269 /**
8270 * Schema defining the parameters accepted by the function.
8271 */
8272 parameters: {
8273 /**
8274 * The type of the parameters object (usually 'object').
8275 */
8276 type: string;
8277 /**
8278 * List of required parameter names.
8279 */
8280 required?: string[];
8281 /**
8282 * Definitions of each parameter.
8283 */
8284 properties: {
8285 [k: string]: {
8286 /**
8287 * The data type of the parameter.
8288 */
8289 type: string;
8290 /**
8291 * A description of the expected parameter.
8292 */
8293 description: string;
8294 };
8295 };
8296 };
8297 };
8298 })[];
8299 response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode;
8300 /**
8301 * JSON schema that should be fufilled for the response.
8302 */
8303 guided_json?: object;
8304 /**
8305 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8306 */
8307 raw?: boolean;
8308 /**
8309 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8310 */
8311 stream?: boolean;
8312 /**
8313 * The maximum number of tokens to generate in the response.
8314 */
8315 max_tokens?: number;
8316 /**
8317 * Controls the randomness of the output; higher values produce more random results.
8318 */
8319 temperature?: number;
8320 /**
8321 * 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.
8322 */
8323 top_p?: number;
8324 /**
8325 * 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.
8326 */
8327 top_k?: number;
8328 /**
8329 * Random seed for reproducibility of the generation.
8330 */
8331 seed?: number;
8332 /**
8333 * Penalty for repeated tokens; higher values discourage repetition.
8334 */
8335 repetition_penalty?: number;
8336 /**
8337 * Decreases the likelihood of the model repeating the same lines verbatim.
8338 */
8339 frequency_penalty?: number;
8340 /**
8341 * Increases the likelihood of the model introducing new topics.
8342 */
8343 presence_penalty?: number;
8344}
8345type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = {
8346 /**
8347 * The generated text response from the model
8348 */
8349 response: string;
8350 /**
8351 * Usage statistics for the inference request
8352 */
8353 usage?: {
8354 /**
8355 * Total number of tokens in input
8356 */
8357 prompt_tokens?: number;
8358 /**
8359 * Total number of tokens in output
8360 */
8361 completion_tokens?: number;
8362 /**
8363 * Total number of input and output tokens
8364 */
8365 total_tokens?: number;
8366 };
8367 /**
8368 * An array of tool calls requests made during the response generation
8369 */
8370 tool_calls?: {
8371 /**
8372 * The tool call id.
8373 */
8374 id?: string;
8375 /**
8376 * Specifies the type of tool (e.g., 'function').
8377 */
8378 type?: string;
8379 /**
8380 * Details of the function tool.
8381 */
8382 function?: {
8383 /**
8384 * The name of the tool to be called
8385 */
8386 name?: string;
8387 /**
8388 * The arguments passed to be passed to the tool call request
8389 */
8390 arguments?: object;
8391 };
8392 }[];
8393};
8394declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct {
8395 inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input;
8396 postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output;
8397}
8398type 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;
8399interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt {
8400 /**
8401 * The input text prompt for the model to generate a response.
8402 */
8403 prompt: string;
8404 /**
8405 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
8406 */
8407 lora?: string;
8408 response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode;
8409 /**
8410 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8411 */
8412 raw?: boolean;
8413 /**
8414 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8415 */
8416 stream?: boolean;
8417 /**
8418 * The maximum number of tokens to generate in the response.
8419 */
8420 max_tokens?: number;
8421 /**
8422 * Controls the randomness of the output; higher values produce more random results.
8423 */
8424 temperature?: number;
8425 /**
8426 * 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.
8427 */
8428 top_p?: number;
8429 /**
8430 * 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.
8431 */
8432 top_k?: number;
8433 /**
8434 * Random seed for reproducibility of the generation.
8435 */
8436 seed?: number;
8437 /**
8438 * Penalty for repeated tokens; higher values discourage repetition.
8439 */
8440 repetition_penalty?: number;
8441 /**
8442 * Decreases the likelihood of the model repeating the same lines verbatim.
8443 */
8444 frequency_penalty?: number;
8445 /**
8446 * Increases the likelihood of the model introducing new topics.
8447 */
8448 presence_penalty?: number;
8449}
8450interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode {
8451 type?: "json_object" | "json_schema";
8452 json_schema?: unknown;
8453}
8454interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages {
8455 /**
8456 * An array of message objects representing the conversation history.
8457 */
8458 messages: {
8459 /**
8460 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
8461 */
8462 role: string;
8463 content: string | {
8464 /**
8465 * Type of the content (text)
8466 */
8467 type?: string;
8468 /**
8469 * Text content
8470 */
8471 text?: string;
8472 }[];
8473 }[];
8474 functions?: {
8475 name: string;
8476 code: string;
8477 }[];
8478 /**
8479 * A list of tools available for the assistant to use.
8480 */
8481 tools?: ({
8482 /**
8483 * The name of the tool. More descriptive the better.
8484 */
8485 name: string;
8486 /**
8487 * A brief description of what the tool does.
8488 */
8489 description: string;
8490 /**
8491 * Schema defining the parameters accepted by the tool.
8492 */
8493 parameters: {
8494 /**
8495 * The type of the parameters object (usually 'object').
8496 */
8497 type: string;
8498 /**
8499 * List of required parameter names.
8500 */
8501 required?: string[];
8502 /**
8503 * Definitions of each parameter.
8504 */
8505 properties: {
8506 [k: string]: {
8507 /**
8508 * The data type of the parameter.
8509 */
8510 type: string;
8511 /**
8512 * A description of the expected parameter.
8513 */
8514 description: string;
8515 };
8516 };
8517 };
8518 } | {
8519 /**
8520 * Specifies the type of tool (e.g., 'function').
8521 */
8522 type: string;
8523 /**
8524 * Details of the function tool.
8525 */
8526 function: {
8527 /**
8528 * The name of the function.
8529 */
8530 name: string;
8531 /**
8532 * A brief description of what the function does.
8533 */
8534 description: string;
8535 /**
8536 * Schema defining the parameters accepted by the function.
8537 */
8538 parameters: {
8539 /**
8540 * The type of the parameters object (usually 'object').
8541 */
8542 type: string;
8543 /**
8544 * List of required parameter names.
8545 */
8546 required?: string[];
8547 /**
8548 * Definitions of each parameter.
8549 */
8550 properties: {
8551 [k: string]: {
8552 /**
8553 * The data type of the parameter.
8554 */
8555 type: string;
8556 /**
8557 * A description of the expected parameter.
8558 */
8559 description: string;
8560 };
8561 };
8562 };
8563 };
8564 })[];
8565 response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1;
8566 /**
8567 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8568 */
8569 raw?: boolean;
8570 /**
8571 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8572 */
8573 stream?: boolean;
8574 /**
8575 * The maximum number of tokens to generate in the response.
8576 */
8577 max_tokens?: number;
8578 /**
8579 * Controls the randomness of the output; higher values produce more random results.
8580 */
8581 temperature?: number;
8582 /**
8583 * 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.
8584 */
8585 top_p?: number;
8586 /**
8587 * 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.
8588 */
8589 top_k?: number;
8590 /**
8591 * Random seed for reproducibility of the generation.
8592 */
8593 seed?: number;
8594 /**
8595 * Penalty for repeated tokens; higher values discourage repetition.
8596 */
8597 repetition_penalty?: number;
8598 /**
8599 * Decreases the likelihood of the model repeating the same lines verbatim.
8600 */
8601 frequency_penalty?: number;
8602 /**
8603 * Increases the likelihood of the model introducing new topics.
8604 */
8605 presence_penalty?: number;
8606}
8607interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 {
8608 type?: "json_object" | "json_schema";
8609 json_schema?: unknown;
8610}
8611interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch {
8612 requests: (Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1)[];
8613}
8614interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 {
8615 /**
8616 * The input text prompt for the model to generate a response.
8617 */
8618 prompt: string;
8619 /**
8620 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
8621 */
8622 lora?: string;
8623 response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2;
8624 /**
8625 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8626 */
8627 raw?: boolean;
8628 /**
8629 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8630 */
8631 stream?: boolean;
8632 /**
8633 * The maximum number of tokens to generate in the response.
8634 */
8635 max_tokens?: number;
8636 /**
8637 * Controls the randomness of the output; higher values produce more random results.
8638 */
8639 temperature?: number;
8640 /**
8641 * 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.
8642 */
8643 top_p?: number;
8644 /**
8645 * 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.
8646 */
8647 top_k?: number;
8648 /**
8649 * Random seed for reproducibility of the generation.
8650 */
8651 seed?: number;
8652 /**
8653 * Penalty for repeated tokens; higher values discourage repetition.
8654 */
8655 repetition_penalty?: number;
8656 /**
8657 * Decreases the likelihood of the model repeating the same lines verbatim.
8658 */
8659 frequency_penalty?: number;
8660 /**
8661 * Increases the likelihood of the model introducing new topics.
8662 */
8663 presence_penalty?: number;
8664}
8665interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 {
8666 type?: "json_object" | "json_schema";
8667 json_schema?: unknown;
8668}
8669interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 {
8670 /**
8671 * An array of message objects representing the conversation history.
8672 */
8673 messages: {
8674 /**
8675 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
8676 */
8677 role: string;
8678 content: string | {
8679 /**
8680 * Type of the content (text)
8681 */
8682 type?: string;
8683 /**
8684 * Text content
8685 */
8686 text?: string;
8687 }[];
8688 }[];
8689 functions?: {
8690 name: string;
8691 code: string;
8692 }[];
8693 /**
8694 * A list of tools available for the assistant to use.
8695 */
8696 tools?: ({
8697 /**
8698 * The name of the tool. More descriptive the better.
8699 */
8700 name: string;
8701 /**
8702 * A brief description of what the tool does.
8703 */
8704 description: string;
8705 /**
8706 * Schema defining the parameters accepted by the tool.
8707 */
8708 parameters: {
8709 /**
8710 * The type of the parameters object (usually 'object').
8711 */
8712 type: string;
8713 /**
8714 * List of required parameter names.
8715 */
8716 required?: string[];
8717 /**
8718 * Definitions of each parameter.
8719 */
8720 properties: {
8721 [k: string]: {
8722 /**
8723 * The data type of the parameter.
8724 */
8725 type: string;
8726 /**
8727 * A description of the expected parameter.
8728 */
8729 description: string;
8730 };
8731 };
8732 };
8733 } | {
8734 /**
8735 * Specifies the type of tool (e.g., 'function').
8736 */
8737 type: string;
8738 /**
8739 * Details of the function tool.
8740 */
8741 function: {
8742 /**
8743 * The name of the function.
8744 */
8745 name: string;
8746 /**
8747 * A brief description of what the function does.
8748 */
8749 description: string;
8750 /**
8751 * Schema defining the parameters accepted by the function.
8752 */
8753 parameters: {
8754 /**
8755 * The type of the parameters object (usually 'object').
8756 */
8757 type: string;
8758 /**
8759 * List of required parameter names.
8760 */
8761 required?: string[];
8762 /**
8763 * Definitions of each parameter.
8764 */
8765 properties: {
8766 [k: string]: {
8767 /**
8768 * The data type of the parameter.
8769 */
8770 type: string;
8771 /**
8772 * A description of the expected parameter.
8773 */
8774 description: string;
8775 };
8776 };
8777 };
8778 };
8779 })[];
8780 response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3;
8781 /**
8782 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
8783 */
8784 raw?: boolean;
8785 /**
8786 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
8787 */
8788 stream?: boolean;
8789 /**
8790 * The maximum number of tokens to generate in the response.
8791 */
8792 max_tokens?: number;
8793 /**
8794 * Controls the randomness of the output; higher values produce more random results.
8795 */
8796 temperature?: number;
8797 /**
8798 * 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.
8799 */
8800 top_p?: number;
8801 /**
8802 * 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.
8803 */
8804 top_k?: number;
8805 /**
8806 * Random seed for reproducibility of the generation.
8807 */
8808 seed?: number;
8809 /**
8810 * Penalty for repeated tokens; higher values discourage repetition.
8811 */
8812 repetition_penalty?: number;
8813 /**
8814 * Decreases the likelihood of the model repeating the same lines verbatim.
8815 */
8816 frequency_penalty?: number;
8817 /**
8818 * Increases the likelihood of the model introducing new topics.
8819 */
8820 presence_penalty?: number;
8821}
8822interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 {
8823 type?: "json_object" | "json_schema";
8824 json_schema?: unknown;
8825}
8826type 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;
8827interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response {
8828 /**
8829 * Unique identifier for the completion
8830 */
8831 id?: string;
8832 /**
8833 * Object type identifier
8834 */
8835 object?: "chat.completion";
8836 /**
8837 * Unix timestamp of when the completion was created
8838 */
8839 created?: number;
8840 /**
8841 * Model used for the completion
8842 */
8843 model?: string;
8844 /**
8845 * List of completion choices
8846 */
8847 choices?: {
8848 /**
8849 * Index of the choice in the list
8850 */
8851 index?: number;
8852 /**
8853 * The message generated by the model
8854 */
8855 message?: {
8856 /**
8857 * Role of the message author
8858 */
8859 role: string;
8860 /**
8861 * The content of the message
8862 */
8863 content: string;
8864 /**
8865 * Internal reasoning content (if available)
8866 */
8867 reasoning_content?: string;
8868 /**
8869 * Tool calls made by the assistant
8870 */
8871 tool_calls?: {
8872 /**
8873 * Unique identifier for the tool call
8874 */
8875 id: string;
8876 /**
8877 * Type of tool call
8878 */
8879 type: "function";
8880 function: {
8881 /**
8882 * Name of the function to call
8883 */
8884 name: string;
8885 /**
8886 * JSON string of arguments for the function
8887 */
8888 arguments: string;
8889 };
8890 }[];
8891 };
8892 /**
8893 * Reason why the model stopped generating
8894 */
8895 finish_reason?: string;
8896 /**
8897 * Stop reason (may be null)
8898 */
8899 stop_reason?: string | null;
8900 /**
8901 * Log probabilities (if requested)
8902 */
8903 logprobs?: {} | null;
8904 }[];
8905 /**
8906 * Usage statistics for the inference request
8907 */
8908 usage?: {
8909 /**
8910 * Total number of tokens in input
8911 */
8912 prompt_tokens?: number;
8913 /**
8914 * Total number of tokens in output
8915 */
8916 completion_tokens?: number;
8917 /**
8918 * Total number of input and output tokens
8919 */
8920 total_tokens?: number;
8921 };
8922 /**
8923 * Log probabilities for the prompt (if requested)
8924 */
8925 prompt_logprobs?: {} | null;
8926}
8927interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response {
8928 /**
8929 * Unique identifier for the completion
8930 */
8931 id?: string;
8932 /**
8933 * Object type identifier
8934 */
8935 object?: "text_completion";
8936 /**
8937 * Unix timestamp of when the completion was created
8938 */
8939 created?: number;
8940 /**
8941 * Model used for the completion
8942 */
8943 model?: string;
8944 /**
8945 * List of completion choices
8946 */
8947 choices?: {
8948 /**
8949 * Index of the choice in the list
8950 */
8951 index: number;
8952 /**
8953 * The generated text completion
8954 */
8955 text: string;
8956 /**
8957 * Reason why the model stopped generating
8958 */
8959 finish_reason: string;
8960 /**
8961 * Stop reason (may be null)
8962 */
8963 stop_reason?: string | null;
8964 /**
8965 * Log probabilities (if requested)
8966 */
8967 logprobs?: {} | null;
8968 /**
8969 * Log probabilities for the prompt (if requested)
8970 */
8971 prompt_logprobs?: {} | null;
8972 }[];
8973 /**
8974 * Usage statistics for the inference request
8975 */
8976 usage?: {
8977 /**
8978 * Total number of tokens in input
8979 */
8980 prompt_tokens?: number;
8981 /**
8982 * Total number of tokens in output
8983 */
8984 completion_tokens?: number;
8985 /**
8986 * Total number of input and output tokens
8987 */
8988 total_tokens?: number;
8989 };
8990}
8991interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse {
8992 /**
8993 * The async request id that can be used to obtain the results.
8994 */
8995 request_id?: string;
8996}
8997declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 {
8998 inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input;
8999 postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output;
9000}
9001interface Ai_Cf_Deepgram_Nova_3_Input {
9002 audio: {
9003 body: object;
9004 contentType: string;
9005 };
9006 /**
9007 * 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.
9008 */
9009 custom_topic_mode?: "extended" | "strict";
9010 /**
9011 * Custom topics you want the model to detect within your input audio or text if present Submit up to 100
9012 */
9013 custom_topic?: string;
9014 /**
9015 * 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
9016 */
9017 custom_intent_mode?: "extended" | "strict";
9018 /**
9019 * Custom intents you want the model to detect within your input audio if present
9020 */
9021 custom_intent?: string;
9022 /**
9023 * Identifies and extracts key entities from content in submitted audio
9024 */
9025 detect_entities?: boolean;
9026 /**
9027 * Identifies the dominant language spoken in submitted audio
9028 */
9029 detect_language?: boolean;
9030 /**
9031 * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0
9032 */
9033 diarize?: boolean;
9034 /**
9035 * Identify and extract key entities from content in submitted audio
9036 */
9037 dictation?: boolean;
9038 /**
9039 * Specify the expected encoding of your submitted audio
9040 */
9041 encoding?: "linear16" | "flac" | "mulaw" | "amr-nb" | "amr-wb" | "opus" | "speex" | "g729";
9042 /**
9043 * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing
9044 */
9045 extra?: string;
9046 /**
9047 * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um'
9048 */
9049 filler_words?: boolean;
9050 /**
9051 * Key term prompting can boost or suppress specialized terminology and brands.
9052 */
9053 keyterm?: string;
9054 /**
9055 * Keywords can boost or suppress specialized terminology and brands.
9056 */
9057 keywords?: string;
9058 /**
9059 * 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.
9060 */
9061 language?: string;
9062 /**
9063 * Spoken measurements will be converted to their corresponding abbreviations.
9064 */
9065 measurements?: boolean;
9066 /**
9067 * 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.
9068 */
9069 mip_opt_out?: boolean;
9070 /**
9071 * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio
9072 */
9073 mode?: "general" | "medical" | "finance";
9074 /**
9075 * Transcribe each audio channel independently.
9076 */
9077 multichannel?: boolean;
9078 /**
9079 * Numerals converts numbers from written format to numerical format.
9080 */
9081 numerals?: boolean;
9082 /**
9083 * Splits audio into paragraphs to improve transcript readability.
9084 */
9085 paragraphs?: boolean;
9086 /**
9087 * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely.
9088 */
9089 profanity_filter?: boolean;
9090 /**
9091 * Add punctuation and capitalization to the transcript.
9092 */
9093 punctuate?: boolean;
9094 /**
9095 * Redaction removes sensitive information from your transcripts.
9096 */
9097 redact?: string;
9098 /**
9099 * Search for terms or phrases in submitted audio and replaces them.
9100 */
9101 replace?: string;
9102 /**
9103 * Search for terms or phrases in submitted audio.
9104 */
9105 search?: string;
9106 /**
9107 * Recognizes the sentiment throughout a transcript or text.
9108 */
9109 sentiment?: boolean;
9110 /**
9111 * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability.
9112 */
9113 smart_format?: boolean;
9114 /**
9115 * Detect topics throughout a transcript or text.
9116 */
9117 topics?: boolean;
9118 /**
9119 * Segments speech into meaningful semantic units.
9120 */
9121 utterances?: boolean;
9122 /**
9123 * Seconds to wait before detecting a pause between words in submitted audio.
9124 */
9125 utt_split?: number;
9126 /**
9127 * The number of channels in the submitted audio
9128 */
9129 channels?: number;
9130 /**
9131 * 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.
9132 */
9133 interim_results?: boolean;
9134 /**
9135 * 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
9136 */
9137 endpointing?: string;
9138 /**
9139 * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets.
9140 */
9141 vad_events?: boolean;
9142 /**
9143 * 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.
9144 */
9145 utterance_end_ms?: boolean;
9146}
9147interface Ai_Cf_Deepgram_Nova_3_Output {
9148 results?: {
9149 channels?: {
9150 alternatives?: {
9151 confidence?: number;
9152 transcript?: string;
9153 words?: {
9154 confidence?: number;
9155 end?: number;
9156 start?: number;
9157 word?: string;
9158 }[];
9159 }[];
9160 }[];
9161 summary?: {
9162 result?: string;
9163 short?: string;
9164 };
9165 sentiments?: {
9166 segments?: {
9167 text?: string;
9168 start_word?: number;
9169 end_word?: number;
9170 sentiment?: string;
9171 sentiment_score?: number;
9172 }[];
9173 average?: {
9174 sentiment?: string;
9175 sentiment_score?: number;
9176 };
9177 };
9178 };
9179}
9180declare abstract class Base_Ai_Cf_Deepgram_Nova_3 {
9181 inputs: Ai_Cf_Deepgram_Nova_3_Input;
9182 postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output;
9183}
9184interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input {
9185 queries?: string | string[];
9186 /**
9187 * Optional instruction for the task
9188 */
9189 instruction?: string;
9190 documents?: string | string[];
9191 text?: string | string[];
9192}
9193interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output {
9194 data?: number[][];
9195 shape?: number[];
9196}
9197declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B {
9198 inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input;
9199 postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output;
9200}
9201type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = {
9202 /**
9203 * readable stream with audio data and content-type specified for that data
9204 */
9205 audio: {
9206 body: object;
9207 contentType: string;
9208 };
9209 /**
9210 * type of data PCM data that's sent to the inference server as raw array
9211 */
9212 dtype?: "uint8" | "float32" | "float64";
9213} | {
9214 /**
9215 * base64 encoded audio data
9216 */
9217 audio: string;
9218 /**
9219 * type of data PCM data that's sent to the inference server as raw array
9220 */
9221 dtype?: "uint8" | "float32" | "float64";
9222};
9223interface Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output {
9224 /**
9225 * if true, end-of-turn was detected
9226 */
9227 is_complete?: boolean;
9228 /**
9229 * probability of the end-of-turn detection
9230 */
9231 probability?: number;
9232}
9233declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 {
9234 inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input;
9235 postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output;
9236}
9237declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B {
9238 inputs: XOR<Omit<ResponsesInput, "reasoning"> & {
9239 reasoning?: (Omit<Reasoning, "effort"> & {
9240 /**
9241 * Reasoning effort. Supported levels: low, medium, high. Reasoning cannot be disabled.
9242 *
9243 * @default "medium"
9244 */
9245 effort?: "low" | "medium" | "high" | null;
9246 }) | null;
9247 }, Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
9248 /**
9249 * Reasoning effort. Supported levels: low, medium, high. Reasoning cannot be disabled.
9250 *
9251 * @default "medium"
9252 */
9253 reasoning_effort?: "low" | "medium" | "high" | null;
9254 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
9255 /**
9256 * Reasoning is always enabled for this model and cannot be disabled.
9257 *
9258 * @default true
9259 */
9260 enable_thinking?: true;
9261 };
9262 }>;
9263 postProcessedOutputs: XOR<ResponsesOutput, ChatCompletionsOutput>;
9264}
9265declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B {
9266 inputs: XOR<Omit<ResponsesInput, "reasoning"> & {
9267 reasoning?: (Omit<Reasoning, "effort"> & {
9268 /**
9269 * Reasoning effort. Supported levels: low, medium, high. Reasoning cannot be disabled.
9270 *
9271 * @default "medium"
9272 */
9273 effort?: "low" | "medium" | "high" | null;
9274 }) | null;
9275 }, Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
9276 /**
9277 * Reasoning effort. Supported levels: low, medium, high. Reasoning cannot be disabled.
9278 *
9279 * @default "medium"
9280 */
9281 reasoning_effort?: "low" | "medium" | "high" | null;
9282 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
9283 /**
9284 * Reasoning is always enabled for this model and cannot be disabled.
9285 *
9286 * @default true
9287 */
9288 enable_thinking?: true;
9289 };
9290 }>;
9291 postProcessedOutputs: XOR<ResponsesOutput, ChatCompletionsOutput>;
9292}
9293interface Ai_Cf_Leonardo_Phoenix_1_0_Input {
9294 /**
9295 * A text description of the image you want to generate.
9296 */
9297 prompt: string;
9298 /**
9299 * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt
9300 */
9301 guidance?: number;
9302 /**
9303 * Random seed for reproducibility of the image generation
9304 */
9305 seed?: number;
9306 /**
9307 * The height of the generated image in pixels
9308 */
9309 height?: number;
9310 /**
9311 * The width of the generated image in pixels
9312 */
9313 width?: number;
9314 /**
9315 * The number of diffusion steps; higher values can improve quality but take longer
9316 */
9317 num_steps?: number;
9318 /**
9319 * Specify what to exclude from the generated images
9320 */
9321 negative_prompt?: string;
9322}
9323/**
9324 * The generated image in JPEG format
9325 */
9326type Ai_Cf_Leonardo_Phoenix_1_0_Output = string;
9327declare abstract class Base_Ai_Cf_Leonardo_Phoenix_1_0 {
9328 inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input;
9329 postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output;
9330}
9331interface Ai_Cf_Leonardo_Lucid_Origin_Input {
9332 /**
9333 * A text description of the image you want to generate.
9334 */
9335 prompt: string;
9336 /**
9337 * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt
9338 */
9339 guidance?: number;
9340 /**
9341 * Random seed for reproducibility of the image generation
9342 */
9343 seed?: number;
9344 /**
9345 * The height of the generated image in pixels
9346 */
9347 height?: number;
9348 /**
9349 * The width of the generated image in pixels
9350 */
9351 width?: number;
9352 /**
9353 * The number of diffusion steps; higher values can improve quality but take longer
9354 */
9355 num_steps?: number;
9356 /**
9357 * The number of diffusion steps; higher values can improve quality but take longer
9358 */
9359 steps?: number;
9360}
9361interface Ai_Cf_Leonardo_Lucid_Origin_Output {
9362 /**
9363 * The generated image in Base64 format.
9364 */
9365 image?: string;
9366}
9367declare abstract class Base_Ai_Cf_Leonardo_Lucid_Origin {
9368 inputs: Ai_Cf_Leonardo_Lucid_Origin_Input;
9369 postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output;
9370}
9371interface Ai_Cf_Deepgram_Aura_1_Input {
9372 /**
9373 * Speaker used to produce the audio.
9374 */
9375 speaker?: "angus" | "asteria" | "arcas" | "orion" | "orpheus" | "athena" | "luna" | "zeus" | "perseus" | "helios" | "hera" | "stella";
9376 /**
9377 * Encoding of the output audio.
9378 */
9379 encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac";
9380 /**
9381 * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type..
9382 */
9383 container?: "none" | "wav" | "ogg";
9384 /**
9385 * The text content to be converted to speech
9386 */
9387 text: string;
9388 /**
9389 * 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
9390 */
9391 sample_rate?: number;
9392 /**
9393 * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type.
9394 */
9395 bit_rate?: number;
9396}
9397/**
9398 * The generated audio in MP3 format
9399 */
9400type Ai_Cf_Deepgram_Aura_1_Output = string;
9401declare abstract class Base_Ai_Cf_Deepgram_Aura_1 {
9402 inputs: Ai_Cf_Deepgram_Aura_1_Input;
9403 postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output;
9404}
9405interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input {
9406 /**
9407 * Input text to translate. Can be a single string or a list of strings.
9408 */
9409 text: string | string[];
9410 /**
9411 * Target langauge to translate to
9412 */
9413 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";
9414}
9415interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output {
9416 /**
9417 * Translated texts
9418 */
9419 translations: string[];
9420}
9421declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B {
9422 inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input;
9423 postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output;
9424}
9425type 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;
9426interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt {
9427 /**
9428 * The input text prompt for the model to generate a response.
9429 */
9430 prompt: string;
9431 /**
9432 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
9433 */
9434 lora?: string;
9435 response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode;
9436 /**
9437 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
9438 */
9439 raw?: boolean;
9440 /**
9441 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
9442 */
9443 stream?: boolean;
9444 /**
9445 * The maximum number of tokens to generate in the response.
9446 */
9447 max_tokens?: number;
9448 /**
9449 * Controls the randomness of the output; higher values produce more random results.
9450 */
9451 temperature?: number;
9452 /**
9453 * 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.
9454 */
9455 top_p?: number;
9456 /**
9457 * 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.
9458 */
9459 top_k?: number;
9460 /**
9461 * Random seed for reproducibility of the generation.
9462 */
9463 seed?: number;
9464 /**
9465 * Penalty for repeated tokens; higher values discourage repetition.
9466 */
9467 repetition_penalty?: number;
9468 /**
9469 * Decreases the likelihood of the model repeating the same lines verbatim.
9470 */
9471 frequency_penalty?: number;
9472 /**
9473 * Increases the likelihood of the model introducing new topics.
9474 */
9475 presence_penalty?: number;
9476}
9477interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode {
9478 type?: "json_object" | "json_schema";
9479 json_schema?: unknown;
9480}
9481interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages {
9482 /**
9483 * An array of message objects representing the conversation history.
9484 */
9485 messages: {
9486 /**
9487 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
9488 */
9489 role: string;
9490 content: string | {
9491 /**
9492 * Type of the content (text)
9493 */
9494 type?: string;
9495 /**
9496 * Text content
9497 */
9498 text?: string;
9499 }[];
9500 }[];
9501 functions?: {
9502 name: string;
9503 code: string;
9504 }[];
9505 /**
9506 * A list of tools available for the assistant to use.
9507 */
9508 tools?: ({
9509 /**
9510 * The name of the tool. More descriptive the better.
9511 */
9512 name: string;
9513 /**
9514 * A brief description of what the tool does.
9515 */
9516 description: string;
9517 /**
9518 * Schema defining the parameters accepted by the tool.
9519 */
9520 parameters: {
9521 /**
9522 * The type of the parameters object (usually 'object').
9523 */
9524 type: string;
9525 /**
9526 * List of required parameter names.
9527 */
9528 required?: string[];
9529 /**
9530 * Definitions of each parameter.
9531 */
9532 properties: {
9533 [k: string]: {
9534 /**
9535 * The data type of the parameter.
9536 */
9537 type: string;
9538 /**
9539 * A description of the expected parameter.
9540 */
9541 description: string;
9542 };
9543 };
9544 };
9545 } | {
9546 /**
9547 * Specifies the type of tool (e.g., 'function').
9548 */
9549 type: string;
9550 /**
9551 * Details of the function tool.
9552 */
9553 function: {
9554 /**
9555 * The name of the function.
9556 */
9557 name: string;
9558 /**
9559 * A brief description of what the function does.
9560 */
9561 description: string;
9562 /**
9563 * Schema defining the parameters accepted by the function.
9564 */
9565 parameters: {
9566 /**
9567 * The type of the parameters object (usually 'object').
9568 */
9569 type: string;
9570 /**
9571 * List of required parameter names.
9572 */
9573 required?: string[];
9574 /**
9575 * Definitions of each parameter.
9576 */
9577 properties: {
9578 [k: string]: {
9579 /**
9580 * The data type of the parameter.
9581 */
9582 type: string;
9583 /**
9584 * A description of the expected parameter.
9585 */
9586 description: string;
9587 };
9588 };
9589 };
9590 };
9591 })[];
9592 response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1;
9593 /**
9594 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
9595 */
9596 raw?: boolean;
9597 /**
9598 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
9599 */
9600 stream?: boolean;
9601 /**
9602 * The maximum number of tokens to generate in the response.
9603 */
9604 max_tokens?: number;
9605 /**
9606 * Controls the randomness of the output; higher values produce more random results.
9607 */
9608 temperature?: number;
9609 /**
9610 * 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.
9611 */
9612 top_p?: number;
9613 /**
9614 * 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.
9615 */
9616 top_k?: number;
9617 /**
9618 * Random seed for reproducibility of the generation.
9619 */
9620 seed?: number;
9621 /**
9622 * Penalty for repeated tokens; higher values discourage repetition.
9623 */
9624 repetition_penalty?: number;
9625 /**
9626 * Decreases the likelihood of the model repeating the same lines verbatim.
9627 */
9628 frequency_penalty?: number;
9629 /**
9630 * Increases the likelihood of the model introducing new topics.
9631 */
9632 presence_penalty?: number;
9633}
9634interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 {
9635 type?: "json_object" | "json_schema";
9636 json_schema?: unknown;
9637}
9638interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch {
9639 requests: (Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1)[];
9640}
9641interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 {
9642 /**
9643 * The input text prompt for the model to generate a response.
9644 */
9645 prompt: string;
9646 /**
9647 * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model.
9648 */
9649 lora?: string;
9650 response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2;
9651 /**
9652 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
9653 */
9654 raw?: boolean;
9655 /**
9656 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
9657 */
9658 stream?: boolean;
9659 /**
9660 * The maximum number of tokens to generate in the response.
9661 */
9662 max_tokens?: number;
9663 /**
9664 * Controls the randomness of the output; higher values produce more random results.
9665 */
9666 temperature?: number;
9667 /**
9668 * 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.
9669 */
9670 top_p?: number;
9671 /**
9672 * 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.
9673 */
9674 top_k?: number;
9675 /**
9676 * Random seed for reproducibility of the generation.
9677 */
9678 seed?: number;
9679 /**
9680 * Penalty for repeated tokens; higher values discourage repetition.
9681 */
9682 repetition_penalty?: number;
9683 /**
9684 * Decreases the likelihood of the model repeating the same lines verbatim.
9685 */
9686 frequency_penalty?: number;
9687 /**
9688 * Increases the likelihood of the model introducing new topics.
9689 */
9690 presence_penalty?: number;
9691}
9692interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 {
9693 type?: "json_object" | "json_schema";
9694 json_schema?: unknown;
9695}
9696interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 {
9697 /**
9698 * An array of message objects representing the conversation history.
9699 */
9700 messages: {
9701 /**
9702 * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool').
9703 */
9704 role: string;
9705 content: string | {
9706 /**
9707 * Type of the content (text)
9708 */
9709 type?: string;
9710 /**
9711 * Text content
9712 */
9713 text?: string;
9714 }[];
9715 }[];
9716 functions?: {
9717 name: string;
9718 code: string;
9719 }[];
9720 /**
9721 * A list of tools available for the assistant to use.
9722 */
9723 tools?: ({
9724 /**
9725 * The name of the tool. More descriptive the better.
9726 */
9727 name: string;
9728 /**
9729 * A brief description of what the tool does.
9730 */
9731 description: string;
9732 /**
9733 * Schema defining the parameters accepted by the tool.
9734 */
9735 parameters: {
9736 /**
9737 * The type of the parameters object (usually 'object').
9738 */
9739 type: string;
9740 /**
9741 * List of required parameter names.
9742 */
9743 required?: string[];
9744 /**
9745 * Definitions of each parameter.
9746 */
9747 properties: {
9748 [k: string]: {
9749 /**
9750 * The data type of the parameter.
9751 */
9752 type: string;
9753 /**
9754 * A description of the expected parameter.
9755 */
9756 description: string;
9757 };
9758 };
9759 };
9760 } | {
9761 /**
9762 * Specifies the type of tool (e.g., 'function').
9763 */
9764 type: string;
9765 /**
9766 * Details of the function tool.
9767 */
9768 function: {
9769 /**
9770 * The name of the function.
9771 */
9772 name: string;
9773 /**
9774 * A brief description of what the function does.
9775 */
9776 description: string;
9777 /**
9778 * Schema defining the parameters accepted by the function.
9779 */
9780 parameters: {
9781 /**
9782 * The type of the parameters object (usually 'object').
9783 */
9784 type: string;
9785 /**
9786 * List of required parameter names.
9787 */
9788 required?: string[];
9789 /**
9790 * Definitions of each parameter.
9791 */
9792 properties: {
9793 [k: string]: {
9794 /**
9795 * The data type of the parameter.
9796 */
9797 type: string;
9798 /**
9799 * A description of the expected parameter.
9800 */
9801 description: string;
9802 };
9803 };
9804 };
9805 };
9806 })[];
9807 response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3;
9808 /**
9809 * If true, a chat template is not applied and you must adhere to the specific model's expected formatting.
9810 */
9811 raw?: boolean;
9812 /**
9813 * If true, the response will be streamed back incrementally using SSE, Server Sent Events.
9814 */
9815 stream?: boolean;
9816 /**
9817 * The maximum number of tokens to generate in the response.
9818 */
9819 max_tokens?: number;
9820 /**
9821 * Controls the randomness of the output; higher values produce more random results.
9822 */
9823 temperature?: number;
9824 /**
9825 * 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.
9826 */
9827 top_p?: number;
9828 /**
9829 * 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.
9830 */
9831 top_k?: number;
9832 /**
9833 * Random seed for reproducibility of the generation.
9834 */
9835 seed?: number;
9836 /**
9837 * Penalty for repeated tokens; higher values discourage repetition.
9838 */
9839 repetition_penalty?: number;
9840 /**
9841 * Decreases the likelihood of the model repeating the same lines verbatim.
9842 */
9843 frequency_penalty?: number;
9844 /**
9845 * Increases the likelihood of the model introducing new topics.
9846 */
9847 presence_penalty?: number;
9848}
9849interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 {
9850 type?: "json_object" | "json_schema";
9851 json_schema?: unknown;
9852}
9853type 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;
9854interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response {
9855 /**
9856 * Unique identifier for the completion
9857 */
9858 id?: string;
9859 /**
9860 * Object type identifier
9861 */
9862 object?: "chat.completion";
9863 /**
9864 * Unix timestamp of when the completion was created
9865 */
9866 created?: number;
9867 /**
9868 * Model used for the completion
9869 */
9870 model?: string;
9871 /**
9872 * List of completion choices
9873 */
9874 choices?: {
9875 /**
9876 * Index of the choice in the list
9877 */
9878 index?: number;
9879 /**
9880 * The message generated by the model
9881 */
9882 message?: {
9883 /**
9884 * Role of the message author
9885 */
9886 role: string;
9887 /**
9888 * The content of the message
9889 */
9890 content: string;
9891 /**
9892 * Internal reasoning content (if available)
9893 */
9894 reasoning_content?: string;
9895 /**
9896 * Tool calls made by the assistant
9897 */
9898 tool_calls?: {
9899 /**
9900 * Unique identifier for the tool call
9901 */
9902 id: string;
9903 /**
9904 * Type of tool call
9905 */
9906 type: "function";
9907 function: {
9908 /**
9909 * Name of the function to call
9910 */
9911 name: string;
9912 /**
9913 * JSON string of arguments for the function
9914 */
9915 arguments: string;
9916 };
9917 }[];
9918 };
9919 /**
9920 * Reason why the model stopped generating
9921 */
9922 finish_reason?: string;
9923 /**
9924 * Stop reason (may be null)
9925 */
9926 stop_reason?: string | null;
9927 /**
9928 * Log probabilities (if requested)
9929 */
9930 logprobs?: {} | null;
9931 }[];
9932 /**
9933 * Usage statistics for the inference request
9934 */
9935 usage?: {
9936 /**
9937 * Total number of tokens in input
9938 */
9939 prompt_tokens?: number;
9940 /**
9941 * Total number of tokens in output
9942 */
9943 completion_tokens?: number;
9944 /**
9945 * Total number of input and output tokens
9946 */
9947 total_tokens?: number;
9948 };
9949 /**
9950 * Log probabilities for the prompt (if requested)
9951 */
9952 prompt_logprobs?: {} | null;
9953}
9954interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response {
9955 /**
9956 * Unique identifier for the completion
9957 */
9958 id?: string;
9959 /**
9960 * Object type identifier
9961 */
9962 object?: "text_completion";
9963 /**
9964 * Unix timestamp of when the completion was created
9965 */
9966 created?: number;
9967 /**
9968 * Model used for the completion
9969 */
9970 model?: string;
9971 /**
9972 * List of completion choices
9973 */
9974 choices?: {
9975 /**
9976 * Index of the choice in the list
9977 */
9978 index: number;
9979 /**
9980 * The generated text completion
9981 */
9982 text: string;
9983 /**
9984 * Reason why the model stopped generating
9985 */
9986 finish_reason: string;
9987 /**
9988 * Stop reason (may be null)
9989 */
9990 stop_reason?: string | null;
9991 /**
9992 * Log probabilities (if requested)
9993 */
9994 logprobs?: {} | null;
9995 /**
9996 * Log probabilities for the prompt (if requested)
9997 */
9998 prompt_logprobs?: {} | null;
9999 }[];
10000 /**
10001 * Usage statistics for the inference request
10002 */
10003 usage?: {
10004 /**
10005 * Total number of tokens in input
10006 */
10007 prompt_tokens?: number;
10008 /**
10009 * Total number of tokens in output
10010 */
10011 completion_tokens?: number;
10012 /**
10013 * Total number of input and output tokens
10014 */
10015 total_tokens?: number;
10016 };
10017}
10018interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse {
10019 /**
10020 * The async request id that can be used to obtain the results.
10021 */
10022 request_id?: string;
10023}
10024declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It {
10025 inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input;
10026 postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output;
10027}
10028interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input {
10029 /**
10030 * Input text to embed. Can be a single string or a list of strings.
10031 */
10032 text: string | string[];
10033}
10034interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output {
10035 /**
10036 * Embedding vectors, where each vector is a list of floats.
10037 */
10038 data: number[][];
10039 /**
10040 * Shape of the embedding data as [number_of_embeddings, embedding_dimension].
10041 *
10042 * @minItems 2
10043 * @maxItems 2
10044 */
10045 shape: [
10046 number,
10047 number
10048 ];
10049}
10050declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B {
10051 inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input;
10052 postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output;
10053}
10054interface Ai_Cf_Deepgram_Flux_Input {
10055 /**
10056 * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM.
10057 */
10058 encoding: "linear16";
10059 /**
10060 * Sample rate of the audio stream in Hz.
10061 */
10062 sample_rate: string;
10063 /**
10064 * 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.
10065 */
10066 eager_eot_threshold?: string;
10067 /**
10068 * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9.
10069 */
10070 eot_threshold?: string;
10071 /**
10072 * A turn will be finished when this much time has passed after speech, regardless of EOT confidence.
10073 */
10074 eot_timeout_ms?: string;
10075 /**
10076 * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms.
10077 */
10078 keyterm?: string;
10079 /**
10080 * 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
10081 */
10082 mip_opt_out?: "true" | "false";
10083 /**
10084 * Label your requests for the purpose of identification during usage reporting
10085 */
10086 tag?: string;
10087}
10088/**
10089 * Output will be returned as websocket messages.
10090 */
10091interface Ai_Cf_Deepgram_Flux_Output {
10092 /**
10093 * The unique identifier of the request (uuid)
10094 */
10095 request_id?: string;
10096 /**
10097 * Starts at 0 and increments for each message the server sends to the client.
10098 */
10099 sequence_id?: number;
10100 /**
10101 * The type of event being reported.
10102 */
10103 event?: "Update" | "StartOfTurn" | "EagerEndOfTurn" | "TurnResumed" | "EndOfTurn";
10104 /**
10105 * The index of the current turn
10106 */
10107 turn_index?: number;
10108 /**
10109 * Start time in seconds of the audio range that was transcribed
10110 */
10111 audio_window_start?: number;
10112 /**
10113 * End time in seconds of the audio range that was transcribed
10114 */
10115 audio_window_end?: number;
10116 /**
10117 * Text that was said over the course of the current turn
10118 */
10119 transcript?: string;
10120 /**
10121 * The words in the transcript
10122 */
10123 words?: {
10124 /**
10125 * The individual punctuated, properly-cased word from the transcript
10126 */
10127 word: string;
10128 /**
10129 * Confidence that this word was transcribed correctly
10130 */
10131 confidence: number;
10132 }[];
10133 /**
10134 * Confidence that no more speech is coming in this turn
10135 */
10136 end_of_turn_confidence?: number;
10137}
10138declare abstract class Base_Ai_Cf_Deepgram_Flux {
10139 inputs: Ai_Cf_Deepgram_Flux_Input;
10140 postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output;
10141}
10142interface Ai_Cf_Deepgram_Aura_2_En_Input {
10143 /**
10144 * Speaker used to produce the audio.
10145 */
10146 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";
10147 /**
10148 * Encoding of the output audio.
10149 */
10150 encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac";
10151 /**
10152 * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type..
10153 */
10154 container?: "none" | "wav" | "ogg";
10155 /**
10156 * The text content to be converted to speech
10157 */
10158 text: string;
10159 /**
10160 * 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
10161 */
10162 sample_rate?: number;
10163 /**
10164 * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type.
10165 */
10166 bit_rate?: number;
10167}
10168/**
10169 * The generated audio in MP3 format
10170 */
10171type Ai_Cf_Deepgram_Aura_2_En_Output = string;
10172declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En {
10173 inputs: Ai_Cf_Deepgram_Aura_2_En_Input;
10174 postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output;
10175}
10176interface Ai_Cf_Deepgram_Aura_2_Es_Input {
10177 /**
10178 * Speaker used to produce the audio.
10179 */
10180 speaker?: "sirio" | "nestor" | "carina" | "celeste" | "alvaro" | "diana" | "aquila" | "selena" | "estrella" | "javier";
10181 /**
10182 * Encoding of the output audio.
10183 */
10184 encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac";
10185 /**
10186 * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type..
10187 */
10188 container?: "none" | "wav" | "ogg";
10189 /**
10190 * The text content to be converted to speech
10191 */
10192 text: string;
10193 /**
10194 * 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
10195 */
10196 sample_rate?: number;
10197 /**
10198 * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type.
10199 */
10200 bit_rate?: number;
10201}
10202/**
10203 * The generated audio in MP3 format
10204 */
10205type Ai_Cf_Deepgram_Aura_2_Es_Output = string;
10206declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es {
10207 inputs: Ai_Cf_Deepgram_Aura_2_Es_Input;
10208 postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output;
10209}
10210interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Input {
10211 multipart: {
10212 body?: object;
10213 contentType?: string;
10214 };
10215}
10216interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output {
10217 /**
10218 * Generated image as Base64 string.
10219 */
10220 image?: string;
10221}
10222declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Dev {
10223 inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Input;
10224 postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output;
10225}
10226interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Input {
10227 multipart: {
10228 body?: object;
10229 contentType?: string;
10230 };
10231}
10232interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output {
10233 /**
10234 * Generated image as Base64 string.
10235 */
10236 image?: string;
10237}
10238declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B {
10239 inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Input;
10240 postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output;
10241}
10242interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Input {
10243 multipart: {
10244 body?: object;
10245 contentType?: string;
10246 };
10247}
10248interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output {
10249 /**
10250 * Generated image as Base64 string.
10251 */
10252 image?: string;
10253}
10254declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B {
10255 inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Input;
10256 postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output;
10257}
10258declare abstract class Base_Ai_Cf_Zai_Org_Glm_4_7_Flash {
10259 inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
10260 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
10261 /**
10262 * Whether to enable reasoning for this model. This model has no reasoning effort levels.
10263 *
10264 * @default true
10265 */
10266 enable_thinking?: boolean;
10267 };
10268 };
10269 postProcessedOutputs: ChatCompletionsOutput;
10270}
10271declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_5 {
10272 inputs: ChatCompletionsInput;
10273 postProcessedOutputs: ChatCompletionsOutput;
10274}
10275declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_6 {
10276 inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
10277 /**
10278 * 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.
10279 *
10280 * @default "high"
10281 */
10282 reasoning_effort?: "high" | "none" | null;
10283 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
10284 /**
10285 * Whether to enable reasoning for this model.
10286 *
10287 * @default true
10288 */
10289 enable_thinking?: boolean;
10290 };
10291 };
10292 postProcessedOutputs: ChatCompletionsOutput;
10293}
10294type Ai_Cf_Nvidia_Nemotron_3_120B_A12B_Input = Omit<ChatCompletionsInput, "model" | "max_tokens" | "metadata" | "modalities" | "chat_template_kwargs" | "store" | "reasoning_effort"> & {
10295 /**
10296 * ID of the model to use (for example, '@cf/nvidia/nemotron-3-120b-a12b').
10297 */
10298 model?: ChatCompletionsInput["model"];
10299 /**
10300 * The maximum number of tokens to generate.
10301 */
10302 max_tokens?: ChatCompletionsInput["max_tokens"];
10303 /**
10304 * Set of key-value pairs that can be attached to the object.
10305 */
10306 metadata?: ChatCompletionsInput["metadata"];
10307 /**
10308 * Output types requested from the model.
10309 */
10310 modalities?: ChatCompletionsInput["modalities"];
10311 /**
10312 * Nemotron chat-template controls for normal reasoning, low-effort reasoning, and non-reasoning responses.
10313 */
10314 chat_template_kwargs?: {
10315 /**
10316 * Whether to enable reasoning. Reasoning is enabled by default.
10317 */
10318 enable_thinking?: boolean;
10319 /**
10320 * When reasoning is enabled, use Nemotron's low-effort reasoning mode, which uses significantly fewer reasoning tokens.
10321 */
10322 low_effort?: boolean;
10323 /**
10324 * For coding agent use, Nvidia suggests setting force_nonempty_content=true
10325 */
10326 force_nonempty_content?: boolean;
10327 };
10328 /**
10329 * Whether to store the output for model distillation or evaluation.
10330 *
10331 * @default false
10332 */
10333 store?: ChatCompletionsInput["store"];
10334};
10335declare abstract class Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B {
10336 inputs: Ai_Cf_Nvidia_Nemotron_3_120B_A12B_Input;
10337 postProcessedOutputs: ChatCompletionsOutput;
10338}
10339type Ai_Cf_Google_Gemma_4_26B_A4B_It_Input = Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
10340 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
10341 /**
10342 * Whether to enable reasoning for this model. This model has no reasoning effort levels.
10343 *
10344 * @default true
10345 */
10346 enable_thinking?: boolean;
10347 };
10348} & {
10349 /**
10350 * @default false
10351 */
10352 skip_special_tokens?: boolean;
10353};
10354declare abstract class Base_Ai_Cf_Google_Gemma_4_26B_A4B_It {
10355 inputs: Ai_Cf_Google_Gemma_4_26B_A4B_It_Input;
10356 postProcessedOutputs: ChatCompletionsOutput;
10357}
10358/** @deprecated Use Base_Ai_Cf_Google_Gemma_4_26B_A4B_It. */
10359declare abstract class Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT extends Base_Ai_Cf_Google_Gemma_4_26B_A4B_It {
10360}
10361type Ai_Cf_Nvidia_Nemotron_Speech_Streaming_En_0_6B_Input = {
10362 /**
10363 * readable stream with audio data and content-type specified for that data
10364 */
10365 audio: {
10366 body: object;
10367 contentType: string;
10368 };
10369} | {
10370 /**
10371 * base64 encoded audio data
10372 */
10373 audio: string;
10374 encoding?: "wav" | "flac" | "ogg" | "linear16";
10375 sample_rate?: number;
10376 channels?: number;
10377};
10378interface Ai_Cf_Nvidia_Nemotron_Speech_Streaming_En_0_6B_Output {
10379 text?: string;
10380 duration?: number;
10381}
10382declare abstract class Base_Ai_Cf_Nvidia_Nemotron_Speech_Streaming_En_0_6B {
10383 inputs: Ai_Cf_Nvidia_Nemotron_Speech_Streaming_En_0_6B_Input;
10384 postProcessedOutputs: Ai_Cf_Nvidia_Nemotron_Speech_Streaming_En_0_6B_Output;
10385}
10386declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_7_Code {
10387 inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
10388 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
10389 /**
10390 * Reasoning is always enabled for this model and cannot be disabled. This model has no reasoning effort levels.
10391 *
10392 * @default true
10393 */
10394 enable_thinking?: true;
10395 };
10396 };
10397 postProcessedOutputs: ChatCompletionsOutput;
10398}
10399declare abstract class Base_Ai_Cf_Zai_Org_Glm_5_2 {
10400 inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
10401 /**
10402 * 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.
10403 *
10404 * @default "max"
10405 */
10406 reasoning_effort?: "max" | "high" | "none" | null;
10407 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
10408 /**
10409 * Whether to enable reasoning for this model.
10410 *
10411 * @default true
10412 */
10413 enable_thinking?: boolean;
10414 };
10415 };
10416 postProcessedOutputs: ChatCompletionsOutput;
10417}
10418interface Ai_Cf_Moondream_Moondream3_1_9B_A2B_Input {
10419 /**
10420 * Which Moondream skill to run.
10421 */
10422 task?: "query" | "caption" | "point" | "detect";
10423 /**
10424 * Input image as a public HTTPS URL or base64 data URI. Optional for `query`; required for `caption`, `point`, and `detect`.
10425 */
10426 image?: string;
10427 /**
10428 * Question for the `query` task.
10429 */
10430 question?: string;
10431 /**
10432 * Caption length for the `caption` task.
10433 */
10434 caption_length?: "short" | "normal" | "long";
10435 /**
10436 * Object phrase to locate for `point` and `detect` tasks (e.g. 'person wearing a red shirt').
10437 */
10438 target?: string;
10439 /**
10440 * Enable reasoning trace for the `query` task.
10441 */
10442 reasoning?: boolean;
10443 /**
10444 * Sampling temperature.
10445 */
10446 temperature?: number;
10447 /**
10448 * Top-p (nucleus) sampling.
10449 */
10450 top_p?: number;
10451 /**
10452 * Max tokens to generate for `query` and `caption`.
10453 */
10454 max_tokens?: number;
10455 /**
10456 * Max objects to return for `point` and `detect`.
10457 */
10458 max_objects?: number;
10459 /**
10460 * Return incremental tokens for `query` and `caption`. `point` and `detect` do not support streaming.
10461 */
10462 stream?: boolean;
10463}
10464interface Ai_Cf_Moondream_Moondream3_1_9B_A2B_Output {
10465 /**
10466 * Reason the generation finished.
10467 */
10468 finish_reason: string;
10469 metrics: {
10470 /**
10471 * Number of input tokens consumed.
10472 */
10473 input_tokens: number;
10474 /**
10475 * Number of output tokens generated.
10476 */
10477 output_tokens: number;
10478 /**
10479 * Prefill time in milliseconds.
10480 */
10481 prefill_time_ms: number;
10482 /**
10483 * Decode time in milliseconds.
10484 */
10485 decode_time_ms: number;
10486 /**
10487 * Time to first token in milliseconds.
10488 */
10489 ttft_ms: number;
10490 };
10491 /**
10492 * Answer text for the `query` task. Null for other tasks.
10493 */
10494 answer?: string;
10495 /**
10496 * Caption text for the `caption` task. Null for other tasks.
10497 */
10498 caption?: string;
10499 /**
10500 * Located points for the `point` task. Null for other tasks.
10501 */
10502 points?: {
10503 /**
10504 * X coordinate.
10505 */
10506 x: number;
10507 /**
10508 * Y coordinate.
10509 */
10510 y: number;
10511 }[];
10512 /**
10513 * Detected bounding boxes for the `detect` task. Null for other tasks.
10514 */
10515 objects?: {
10516 /**
10517 * Minimum X coordinate.
10518 */
10519 x_min: number;
10520 /**
10521 * Minimum Y coordinate.
10522 */
10523 y_min: number;
10524 /**
10525 * Maximum X coordinate.
10526 */
10527 x_max: number;
10528 /**
10529 * Maximum Y coordinate.
10530 */
10531 y_max: number;
10532 }[];
10533 /**
10534 * Reasoning trace for the `query` task when reasoning=true. Null otherwise.
10535 */
10536 reasoning?: {
10537 /**
10538 * Reasoning text.
10539 */
10540 text: string;
10541 /**
10542 * Grounding information.
10543 */
10544 grounding?: {}[];
10545 };
10546}
10547declare abstract class Base_Ai_Cf_Moondream_Moondream3_1_9B_A2B {
10548 inputs: Ai_Cf_Moondream_Moondream3_1_9B_A2B_Input;
10549 postProcessedOutputs: Ai_Cf_Moondream_Moondream3_1_9B_A2B_Output;
10550}
10551declare abstract class Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Flash_0731 {
10552 inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
10553 /**
10554 * 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.
10555 *
10556 * @default "high"
10557 */
10558 reasoning_effort?: "max" | "high" | "low" | "none" | null;
10559 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
10560 /**
10561 * Whether to enable reasoning for this model.
10562 *
10563 * @default true
10564 */
10565 enable_thinking?: boolean;
10566 };
10567 };
10568 postProcessedOutputs: ChatCompletionsOutput;
10569}
10570declare abstract class Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Pro_0813 {
10571 inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
10572 /**
10573 * 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.
10574 *
10575 * @default "high"
10576 */
10577 reasoning_effort?: "max" | "high" | "low" | "none" | null;
10578 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
10579 /**
10580 * Whether to enable reasoning for this model.
10581 *
10582 * @default true
10583 */
10584 enable_thinking?: boolean;
10585 };
10586 };
10587 postProcessedOutputs: ChatCompletionsOutput;
10588}
10589declare abstract class Base_Ai_Cf_Qwen_Qwen3_8_27B {
10590 inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
10591 /**
10592 * Reasoning effort. Supported levels: low, medium, xhigh.
10593 *
10594 * @default "xhigh"
10595 */
10596 reasoning_effort?: "low" | "medium" | "xhigh" | null;
10597 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
10598 /**
10599 * Whether to enable reasoning for this model.
10600 *
10601 * @default true
10602 */
10603 enable_thinking?: boolean;
10604 };
10605 };
10606 postProcessedOutputs: ChatCompletionsOutput;
10607}
10608declare abstract class Base_Ai_Cf_Zai_Org_Glm_5_3 {
10609 inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
10610 /**
10611 * 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.
10612 *
10613 * @default "max"
10614 */
10615 reasoning_effort?: "max" | "high" | "low" | null;
10616 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
10617 /**
10618 * Reasoning is always enabled for this model and cannot be disabled.
10619 *
10620 * @default true
10621 */
10622 enable_thinking?: true;
10623 };
10624 };
10625 postProcessedOutputs: ChatCompletionsOutput;
10626}
10627declare abstract class Base_Ai_Cf_Zai_Org_Glm_5_3_Flash {
10628 inputs: Omit<ChatCompletionsInput, "reasoning_effort" | "chat_template_kwargs"> & {
10629 /**
10630 * 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.
10631 *
10632 * @default "max"
10633 */
10634 reasoning_effort?: "max" | "high" | "low" | null;
10635 chat_template_kwargs?: Omit<ChatTemplateKwargs, "enable_thinking"> & {
10636 /**
10637 * Reasoning is always enabled for this model and cannot be disabled.
10638 *
10639 * @default true
10640 */
10641 enable_thinking?: true;
10642 };
10643 };
10644 postProcessedOutputs: ChatCompletionsOutput;
10645}
10646interface AiModels {
10647 "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification;
10648 "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage;
10649 "@cf/runwayml/stable-diffusion-v1-5-inpainting": BaseAiTextToImage;
10650 "@cf/lykon/dreamshaper-8-lcm": BaseAiTextToImage;
10651 "@cf/bytedance/stable-diffusion-xl-lightning": BaseAiTextToImage;
10652 "@cf/myshell-ai/melotts": BaseAiTextToSpeech;
10653 "@cf/google/embeddinggemma-300m": BaseAiTextEmbeddings;
10654 "@cf/microsoft/resnet-50": BaseAiImageClassification;
10655 "@cf/meta/llama-2-7b-chat-int8": BaseAiTextGeneration;
10656 "@cf/mistral/mistral-7b-instruct-v0.1": BaseAiTextGeneration;
10657 "@cf/meta/llama-2-7b-chat-fp16": BaseAiTextGeneration;
10658 "@hf/thebloke/llama-2-13b-chat-awq": BaseAiTextGeneration;
10659 "@hf/thebloke/mistral-7b-instruct-v0.1-awq": BaseAiTextGeneration;
10660 "@hf/thebloke/zephyr-7b-beta-awq": BaseAiTextGeneration;
10661 "@hf/thebloke/openhermes-2.5-mistral-7b-awq": BaseAiTextGeneration;
10662 "@hf/thebloke/neural-chat-7b-v3-1-awq": BaseAiTextGeneration;
10663 "@hf/thebloke/deepseek-coder-6.7b-base-awq": BaseAiTextGeneration;
10664 "@hf/thebloke/deepseek-coder-6.7b-instruct-awq": BaseAiTextGeneration;
10665 "@cf/deepseek-ai/deepseek-math-7b-instruct": BaseAiTextGeneration;
10666 "@cf/defog/sqlcoder-7b-2": BaseAiTextGeneration;
10667 "@cf/openchat/openchat-3.5-0106": BaseAiTextGeneration;
10668 "@cf/tiiuae/falcon-7b-instruct": BaseAiTextGeneration;
10669 "@cf/thebloke/discolm-german-7b-v1-awq": BaseAiTextGeneration;
10670 "@cf/qwen/qwen1.5-0.5b-chat": BaseAiTextGeneration;
10671 "@cf/qwen/qwen1.5-7b-chat-awq": BaseAiTextGeneration;
10672 "@cf/qwen/qwen1.5-14b-chat-awq": BaseAiTextGeneration;
10673 "@cf/tinyllama/tinyllama-1.1b-chat-v1.0": BaseAiTextGeneration;
10674 "@cf/microsoft/phi-2": BaseAiTextGeneration;
10675 "@cf/qwen/qwen1.5-1.8b-chat": BaseAiTextGeneration;
10676 "@cf/mistral/mistral-7b-instruct-v0.2-lora": BaseAiTextGeneration;
10677 "@hf/nousresearch/hermes-2-pro-mistral-7b": BaseAiTextGeneration;
10678 "@hf/nexusflow/starling-lm-7b-beta": BaseAiTextGeneration;
10679 "@hf/google/gemma-7b-it": BaseAiTextGeneration;
10680 "@cf/meta-llama/llama-2-7b-chat-hf-lora": BaseAiTextGeneration;
10681 "@cf/google/gemma-2b-it-lora": BaseAiTextGeneration;
10682 "@cf/google/gemma-7b-it-lora": BaseAiTextGeneration;
10683 "@hf/mistral/mistral-7b-instruct-v0.2": BaseAiTextGeneration;
10684 "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration;
10685 "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration;
10686 "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration;
10687 "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration;
10688 "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration;
10689 "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration;
10690 "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration;
10691 "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration;
10692 "@cf/ibm-granite/granite-4.0-h-micro": BaseAiTextGeneration;
10693 "@cf/facebook/bart-large-cnn": BaseAiSummarization;
10694 "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText;
10695 "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5;
10696 "@cf/openai/whisper": Base_Ai_Cf_Openai_Whisper;
10697 "@cf/meta/m2m100-1.2b": Base_Ai_Cf_Meta_M2M100_1_2B;
10698 "@cf/baai/bge-small-en-v1.5": Base_Ai_Cf_Baai_Bge_Small_En_V1_5;
10699 "@cf/baai/bge-large-en-v1.5": Base_Ai_Cf_Baai_Bge_Large_En_V1_5;
10700 "@cf/unum/uform-gen2-qwen-500m": Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M;
10701 "@cf/openai/whisper-tiny-en": Base_Ai_Cf_Openai_Whisper_Tiny_En;
10702 "@cf/openai/whisper-large-v3-turbo": Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo;
10703 "@cf/baai/bge-m3": Base_Ai_Cf_Baai_Bge_M3;
10704 "@cf/black-forest-labs/flux-1-schnell": Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell;
10705 "@cf/meta/llama-3.2-11b-vision-instruct": Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct;
10706 "@cf/meta/llama-3.3-70b-instruct-fp8-fast": Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast;
10707 "@cf/meta/llama-guard-3-8b": Base_Ai_Cf_Meta_Llama_Guard_3_8B;
10708 "@cf/baai/bge-reranker-base": Base_Ai_Cf_Baai_Bge_Reranker_Base;
10709 "@cf/qwen/qwen2.5-coder-32b-instruct": Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct;
10710 "@cf/qwen/qwq-32b": Base_Ai_Cf_Qwen_Qwq_32B;
10711 "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct;
10712 "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It;
10713 "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct;
10714 "@cf/qwen/qwen3-30b-a3b-fp8": Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8;
10715 "@cf/deepgram/nova-3": Base_Ai_Cf_Deepgram_Nova_3;
10716 "@cf/qwen/qwen3-embedding-0.6b": Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B;
10717 "@cf/pipecat-ai/smart-turn-v2": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2;
10718 "@cf/openai/gpt-oss-120b": Base_Ai_Cf_Openai_Gpt_Oss_120B;
10719 "@cf/openai/gpt-oss-20b": Base_Ai_Cf_Openai_Gpt_Oss_20B;
10720 "@cf/leonardo/phoenix-1.0": Base_Ai_Cf_Leonardo_Phoenix_1_0;
10721 "@cf/leonardo/lucid-origin": Base_Ai_Cf_Leonardo_Lucid_Origin;
10722 "@cf/deepgram/aura-1": Base_Ai_Cf_Deepgram_Aura_1;
10723 "@cf/ai4bharat/indictrans2-en-indic-1B": Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B;
10724 "@cf/aisingapore/gemma-sea-lion-v4-27b-it": Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It;
10725 "@cf/pfnet/plamo-embedding-1b": Base_Ai_Cf_Pfnet_Plamo_Embedding_1B;
10726 "@cf/deepgram/flux": Base_Ai_Cf_Deepgram_Flux;
10727 "@cf/deepgram/aura-2-en": Base_Ai_Cf_Deepgram_Aura_2_En;
10728 "@cf/deepgram/aura-2-es": Base_Ai_Cf_Deepgram_Aura_2_Es;
10729 "@cf/black-forest-labs/flux-2-dev": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Dev;
10730 "@cf/black-forest-labs/flux-2-klein-4b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B;
10731 "@cf/black-forest-labs/flux-2-klein-9b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B;
10732 "@cf/zai-org/glm-4.7-flash": Base_Ai_Cf_Zai_Org_Glm_4_7_Flash;
10733 "@cf/moonshotai/kimi-k2.5": Base_Ai_Cf_Moonshotai_Kimi_K2_5;
10734 "@cf/moonshotai/kimi-k2.6": Base_Ai_Cf_Moonshotai_Kimi_K2_6;
10735 "@cf/nvidia/nemotron-3-120b-a12b": Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B;
10736 "@cf/google/gemma-4-26b-a4b-it": Base_Ai_Cf_Google_Gemma_4_26B_A4B_It;
10737 "@cf/nvidia/nemotron-speech-streaming-en-0.6b": Base_Ai_Cf_Nvidia_Nemotron_Speech_Streaming_En_0_6B;
10738 "@cf/moonshotai/kimi-k2.7-code": Base_Ai_Cf_Moonshotai_Kimi_K2_7_Code;
10739 "@cf/zai-org/glm-5.2": Base_Ai_Cf_Zai_Org_Glm_5_2;
10740 "@cf/moondream/moondream3.1-9B-A2B": Base_Ai_Cf_Moondream_Moondream3_1_9B_A2B;
10741 "@cf/deepseek-ai/deepseek-v4-flash-0731": Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Flash_0731;
10742 "@cf/deepseek-ai/deepseek-v4-pro-0813": Base_Ai_Cf_Deepseek_Ai_Deepseek_V4_Pro_0813;
10743 "@cf/qwen/qwen3.8-27b": Base_Ai_Cf_Qwen_Qwen3_8_27B;
10744 "@cf/zai-org/glm-5.3": Base_Ai_Cf_Zai_Org_Glm_5_3;
10745 "@cf/zai-org/glm-5.3-flash": Base_Ai_Cf_Zai_Org_Glm_5_3_Flash;
10746}
10747type AiOptions = {
10748 /**
10749 * Send requests as an asynchronous batch job, only works for supported models
10750 * https://developers.cloudflare.com/workers-ai/features/batch-api
10751 */
10752 queueRequest?: boolean;
10753 /**
10754 * Establish websocket connections, only works for supported models
10755 */
10756 websocket?: boolean;
10757 /**
10758 * Tag your requests to group and view them in Cloudflare dashboard.
10759 *
10760 * Rules:
10761 * Tags must only contain letters, numbers, and the symbols: : - . / @
10762 * Each tag can have maximum 50 characters.
10763 * Maximum 5 tags are allowed each request.
10764 * Duplicate tags will removed.
10765 */
10766 tags?: string[];
10767 gateway?: GatewayOptions;
10768 returnRawResponse?: boolean;
10769 prefix?: string;
10770 extraHeaders?: object;
10771 signal?: AbortSignal;
10772};
10773type AiModelsSearchParams = {
10774 author?: string;
10775 hide_experimental?: boolean;
10776 page?: number;
10777 per_page?: number;
10778 search?: string;
10779 source?: number;
10780 task?: string;
10781};
10782type AiModelsSearchObject = {
10783 id: string;
10784 source: number;
10785 name: string;
10786 description: string;
10787 task: {
10788 id: string;
10789 name: string;
10790 description: string;
10791 };
10792 tags: string[];
10793 properties: {
10794 property_id: string;
10795 value: string;
10796 }[];
10797};
10798type ChatCompletionsBase = ChatCompletionsMessagesInput;
10799type ChatCompletionsInput = ChatCompletionsMessagesInput;
10800interface InferenceUpstreamError extends Error {
10801}
10802interface AiInternalError extends Error {
10803}
10804type AiModelListType = Record<string, any>;
10805type AiAsyncBatchResponse = {
10806 request_id: string;
10807};
10808type AiWebSearchRequest = {
10809 /** AI Gateway configuration used for this request. */
10810 gatewayId: string;
10811 /** Search query. */
10812 query: string;
10813 /** Maximum number of results. Defaults to 10 and is capped at 20. */
10814 limit?: number;
10815 /** Optional BYOK web-search provider configured on the gateway. */
10816 provider?: string;
10817 /** Optional BYOK key alias. Defaults to `default`. */
10818 byokAlias?: string;
10819};
10820declare abstract class Ai<AiModelList extends AiModelListType = AiModels> {
10821 aiGatewayLogId: string | null;
10822 gateway(gatewayId: string): AiGateway;
10823 websearch(request: AiWebSearchRequest): Promise<Response>;
10824 /**
10825 * @deprecated Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead.
10826 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
10827 */
10828 aiSearch(): AiSearchNamespace;
10829 /**
10830 * @deprecated AutoRAG has been replaced by AI Search.
10831 * Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead.
10832 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
10833 *
10834 * @param autoragId Instance ID
10835 */
10836 autorag(autoragId: string): AutoRAG;
10837 // Batch request
10838 run<Name extends keyof AiModelList>(model: Name, inputs: {
10839 requests: AiModelList[Name]['inputs'][];
10840 }, options: AiOptions & {
10841 queueRequest: true;
10842 }): Promise<AiAsyncBatchResponse>;
10843 // Raw response
10844 run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & {
10845 returnRawResponse: true;
10846 }): Promise<Response>;
10847 // WebSocket
10848 run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & {
10849 websocket: true;
10850 }): Promise<Response>;
10851 // Streaming
10852 run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'] & {
10853 stream: true;
10854 }, options?: AiOptions): Promise<ReadableStream>;
10855 // Normal (default) - known model
10856 run<Name extends keyof AiModelList>(model: Name, inputs: AiModelList[Name]['inputs'], options?: AiOptions): Promise<AiModelList[Name]['postProcessedOutputs']>;
10857 // Unknown model (fallback).
10858 //
10859 // The `Exclude<..., keyof AiModelList>` constraint forces TypeScript to
10860 // route any model name that is a literal key of `AiModelList` to one of
10861 // the known-model overloads above (so input/output mismatches surface as
10862 // type errors rather than silently falling back to `Record<string, unknown>`).
10863 // Names that aren't in `AiModelList` — e.g. third-party gateway models
10864 // like `"google/nano-banana"` — still hit this overload.
10865 run<Model extends string>(model: Model extends keyof AiModelList ? never : Model, inputs: Record<string, unknown>, options?: AiOptions): Promise<Record<string, unknown>>;
10866 models(params?: AiModelsSearchParams): Promise<AiModelsSearchObject[]>;
10867 toMarkdown(): ToMarkdownService;
10868 toMarkdown(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise<ConversionResponse[]>;
10869 toMarkdown(files: MarkdownDocument, options?: ConversionRequestOptions): Promise<ConversionResponse>;
10870}
10871type GatewayRetries = {
10872 maxAttempts?: 1 | 2 | 3 | 4 | 5;
10873 retryDelayMs?: number;
10874 backoff?: 'constant' | 'linear' | 'exponential';
10875};
10876type GatewayOptions = {
10877 id: string;
10878 cacheKey?: string;
10879 cacheTtl?: number;
10880 skipCache?: boolean;
10881 metadata?: Record<string, number | string | boolean | null | bigint>;
10882 collectLog?: boolean;
10883 eventId?: string;
10884 requestTimeoutMs?: number;
10885 retries?: GatewayRetries;
10886};
10887type UniversalGatewayOptions = Exclude<GatewayOptions, 'id'> & {
10888 /**
10889 ** @deprecated
10890 */
10891 id?: string;
10892};
10893type AiGatewayPatchLog = {
10894 score?: number | null;
10895 feedback?: -1 | 1 | null;
10896 metadata?: Record<string, number | string | boolean | null | bigint> | null;
10897};
10898type AiGatewayLog = {
10899 id: string;
10900 provider: string;
10901 model: string;
10902 model_type?: string;
10903 path: string;
10904 duration: number;
10905 request_type?: string;
10906 request_content_type?: string;
10907 status_code: number;
10908 response_content_type?: string;
10909 success: boolean;
10910 cached: boolean;
10911 tokens_in?: number;
10912 tokens_out?: number;
10913 metadata?: Record<string, number | string | boolean | null | bigint>;
10914 step?: number;
10915 cost?: number;
10916 custom_cost?: boolean;
10917 request_size: number;
10918 request_head?: string;
10919 request_head_complete: boolean;
10920 response_size: number;
10921 response_head?: string;
10922 response_head_complete: boolean;
10923 created_at: Date;
10924};
10925type 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';
10926type AIGatewayHeaders = {
10927 'cf-aig-metadata': Record<string, number | string | boolean | null | bigint> | string;
10928 'cf-aig-custom-cost': {
10929 per_token_in?: number;
10930 per_token_out?: number;
10931 } | {
10932 total_cost?: number;
10933 } | string;
10934 'cf-aig-cache-ttl': number | string;
10935 'cf-aig-skip-cache': boolean | string;
10936 'cf-aig-cache-key': string;
10937 'cf-aig-event-id': string;
10938 'cf-aig-request-timeout': number | string;
10939 'cf-aig-max-attempts': number | string;
10940 'cf-aig-retry-delay': number | string;
10941 'cf-aig-backoff': string;
10942 'cf-aig-collect-log': boolean | string;
10943 Authorization: string;
10944 'Content-Type': string;
10945 [key: string]: string | number | boolean | object;
10946};
10947type AIGatewayUniversalRequest = {
10948 provider: AIGatewayProviders | string; // eslint-disable-line
10949 endpoint: string;
10950 headers: Partial<AIGatewayHeaders>;
10951 query: unknown;
10952};
10953interface AiGatewayInternalError extends Error {
10954}
10955interface AiGatewayLogNotFound extends Error {
10956}
10957declare abstract class AiGateway {
10958 patchLog(logId: string, data: AiGatewayPatchLog): Promise<void>;
10959 getLog(logId: string): Promise<AiGatewayLog>;
10960 run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: {
10961 gateway?: UniversalGatewayOptions;
10962 extraHeaders?: object;
10963 signal?: AbortSignal;
10964 }): Promise<Response>;
10965 getUrl(provider?: AIGatewayProviders | string): Promise<string>; // eslint-disable-line
10966}
10967/** A parameter accepted by an Analytics SQL query. */
10968type AnalyticsSQLParameter = string | number | boolean | null;
10969/** An Analytics SQL query and its optional positional or named parameters. */
10970interface AnalyticsSQLQuery {
10971 query: string;
10972 params?: readonly AnalyticsSQLParameter[] | Readonly<Record<string, AnalyticsSQLParameter>>;
10973}
10974/** Execution statistics returned by Analytics SQL. */
10975interface AnalyticsSQLStatistics {
10976 elapsed_ms: number;
10977 rows_read: number;
10978 bytes_read: number;
10979}
10980/** The rows and execution statistics returned by an Analytics SQL query. */
10981interface AnalyticsSQLResult<T extends Record<string, unknown> = Record<string, unknown>> {
10982 data: T[];
10983 rows: number;
10984 statistics: AnalyticsSQLStatistics;
10985}
10986/** An Analytics SQL binding. */
10987interface AnalyticsSQLBinding {
10988 query<T extends Record<string, unknown> = Record<string, unknown>>(request: AnalyticsSQLQuery): Promise<AnalyticsSQLResult<T>>;
10989}
10990// Copyright (c) 2022-2025 Cloudflare, Inc.
10991// Licensed under the Apache 2.0 license found in the LICENSE file or at:
10992// https://opensource.org/licenses/Apache-2.0
10993/**
10994 * Artifacts — Git-compatible file storage on Cloudflare Workers.
10995 *
10996 * Provides programmatic access to create, manage, and fork repositories,
10997 * and to issue and revoke scoped access tokens.
10998 */
10999/** Information about a repository. */
11000interface ArtifactsRepoInfo {
11001 /** Unique repository ID. */
11002 id: string;
11003 /** Repository name. */
11004 name: string;
11005 /** Repository description, or null if not set. */
11006 description: string | null;
11007 /** Default branch name (e.g. "main"). */
11008 defaultBranch: string;
11009 /** ISO 8601 creation timestamp. */
11010 createdAt: string;
11011 /** ISO 8601 last-updated timestamp. */
11012 updatedAt: string;
11013 /** ISO 8601 timestamp of the last push, or null if never pushed. */
11014 lastPushAt: string | null;
11015 /** Fork source (e.g. "github:owner/repo", "artifacts:namespace/repo"), or null if not a fork. */
11016 source: string | null;
11017 /** Whether the repository is read-only. */
11018 readOnly: boolean;
11019 /** HTTPS git remote URL. */
11020 remote: string;
11021}
11022/** Result of creating a repository — includes the initial access token. */
11023interface ArtifactsCreateRepoResult {
11024 /** Unique repository ID. */
11025 id: string;
11026 /** Repository name. */
11027 name: string;
11028 /** Repository description, or null if not set. */
11029 description: string | null;
11030 /** Default branch name. */
11031 defaultBranch: string;
11032 /** HTTPS git remote URL. */
11033 remote: string;
11034 /** Plaintext access token (only returned at creation time). */
11035 token: string;
11036}
11037/** Paginated list of repositories. */
11038interface ArtifactsRepoListResult {
11039 /** Repositories in this page (without the `remote` field). */
11040 repos: Omit<ArtifactsRepoInfo, 'remote'>[];
11041 /** Total number of repositories in the namespace. */
11042 total: number;
11043 /** Cursor for the next page, if there are more results. */
11044 cursor?: string;
11045}
11046/** Result of creating an access token. */
11047interface ArtifactsCreateTokenResult {
11048 /** Unique token ID. */
11049 id: string;
11050 /** Plaintext token (only returned at creation time). */
11051 plaintext: string;
11052 /** Token scope: "read" or "write". */
11053 scope: 'read' | 'write';
11054 /** ISO 8601 token expiry timestamp. */
11055 expiresAt: string;
11056}
11057/** Token metadata (no plaintext). */
11058interface ArtifactsTokenInfo {
11059 /** Unique token ID. */
11060 id: string;
11061 /** Token scope: "read" or "write". */
11062 scope: 'read' | 'write';
11063 /** Token state: "active", "expired", or "revoked". */
11064 state: 'active' | 'expired' | 'revoked';
11065 /** ISO 8601 creation timestamp. */
11066 createdAt: string;
11067 /** ISO 8601 expiry timestamp. */
11068 expiresAt: string;
11069}
11070/** Paginated list of tokens for a repository. */
11071interface ArtifactsTokenListResult {
11072 /** Tokens in this page. */
11073 tokens: ArtifactsTokenInfo[];
11074 /** Total number of tokens for the repository. */
11075 total: number;
11076}
11077/**
11078 * Classification of a Git tree entry derived from its mode.
11079 *
11080 * `tree` is a directory, `blob` is a regular file, `symlink` is a symbolic link,
11081 * `gitlink` is a submodule reference, and `exec` is an executable file.
11082 */
11083type ArtifactsTreeEntryType = 'tree' | 'blob' | 'symlink' | 'gitlink' | 'exec';
11084/** An immediate child of a Git tree returned by {@link ArtifactsRepo.readTree}. */
11085interface ArtifactsTreeEntry {
11086 /** Name relative to the tree being read. */
11087 name: string;
11088 /** Canonical Git mode, such as `100644` for a file or `40000` for a tree. */
11089 mode: string;
11090 /** Lowercase, 40-character SHA-1 object ID. */
11091 hash: string;
11092 /** Classification derived from `mode`. */
11093 type: ArtifactsTreeEntryType;
11094}
11095/** Decoded metadata returned by {@link ArtifactsRepo.readCommit} and {@link ArtifactsRepo.log}. */
11096interface ArtifactsCommitMetadata {
11097 /** Lowercase, 40-character SHA-1 commit ID. */
11098 hash: string;
11099 /** Lowercase, 40-character SHA-1 ID of the commit's root tree. */
11100 treeHash: string;
11101 /** Commit message with one trailing newline removed, if present. */
11102 message: string;
11103 /** Author identity from the commit. */
11104 author: {
11105 /** Author name. */
11106 name: string;
11107 /** Author email address. */
11108 email: string;
11109 };
11110 /** Committer identity from the commit. */
11111 committer: {
11112 /** Committer name. */
11113 name: string;
11114 /** Committer email address. */
11115 email: string;
11116 };
11117 /** Parent commit IDs in Git order; empty for a root commit. */
11118 parents: string[];
11119 /** Author timestamp in Unix seconds. */
11120 authoredAt: number;
11121 /** Committer timestamp in Unix seconds. */
11122 committedAt: number;
11123}
11124/**
11125 * Repository capability returned by {@link Artifacts.get}.
11126 *
11127 * Metadata is available through {@link info}, not as properties on the capability.
11128 * Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs.
11129 *
11130 * The capability is an RPC stub. Dispose of it when finished, for example with
11131 * `using repo = await env.ARTIFACTS.get(name);`, to release it before the request ends.
11132 */
11133interface ArtifactsRepo extends Disposable {
11134 /**
11135 * Create an access token for this repo.
11136 * @param scope Token scope: "write" (default) or "read".
11137 * @param ttl Time-to-live in seconds (default 86400, min 60, max 31536000).
11138 * @throws {ArtifactsError} with code `INVALID_TTL` if ttl is out of range.
11139 */
11140 createToken(scope?: 'write' | 'read', ttl?: number): Promise<ArtifactsCreateTokenResult>;
11141 /** List tokens for this repo (metadata only, no plaintext). */
11142 listTokens(): Promise<ArtifactsTokenListResult>;
11143 /**
11144 * Revoke a token by plaintext or ID.
11145 * @param tokenOrId Plaintext token or token ID.
11146 * @returns true if revoked, false if not found.
11147 * @throws {ArtifactsError} with code `INVALID_INPUT` if tokenOrId is empty.
11148 */
11149 revokeToken(tokenOrId: string): Promise<boolean>;
11150 /**
11151 * Retrieve current repository metadata. Each call performs a fresh lookup.
11152 * @returns Current public repository metadata.
11153 * @throws {ArtifactsError} `NOT_FOUND` if the repository was deleted, or `INTERNAL_ERROR` on
11154 * an unexpected lookup failure.
11155 */
11156 info(): Promise<ArtifactsRepoInfo>;
11157 /**
11158 * Read the raw bytes of a Git blob by object ID.
11159 * @param hash Lowercase, 40-character SHA-1 object ID.
11160 * @returns An untyped {@link Blob}, or `null` if the object is missing or is not a Git blob.
11161 * @throws {ArtifactsError} `INVALID_INPUT` for a malformed hash, `MEMORY_LIMIT` if the object
11162 * cannot be buffered safely, or `INTERNAL_ERROR` on an unexpected read failure.
11163 * @see {@link ArtifactsRepo.readFile} to resolve a file by ref and path.
11164 */
11165 readBlob(hash: string): Promise<Blob | null>;
11166 /**
11167 * Read the immediate children of a Git tree by object ID.
11168 * @param hash Lowercase, 40-character SHA-1 tree ID.
11169 * @returns Tree entries, or `null` if the object is missing.
11170 * @throws {ArtifactsError} `INVALID_INPUT` for a malformed hash, or `INTERNAL_ERROR` if the
11171 * object is not a valid tree or the read fails unexpectedly.
11172 * @see {@link ArtifactsTreeEntry}
11173 */
11174 readTree(hash: string): Promise<ArtifactsTreeEntry[] | null>;
11175 /**
11176 * Decode a Git commit by object ID.
11177 * @param hash Lowercase, 40-character SHA-1 commit ID.
11178 * @returns Commit metadata, or `null` if the object is missing.
11179 * @throws {ArtifactsError} `INVALID_INPUT` for a malformed hash, or `INTERNAL_ERROR` if the
11180 * object is not a valid commit or the read fails unexpectedly.
11181 * @see {@link ArtifactsCommitMetadata}
11182 */
11183 readCommit(hash: string): Promise<ArtifactsCommitMetadata | null>;
11184 /**
11185 * Resolve a file from a branch, tag, or commit ID and return its bytes with a browser-safe
11186 * content type in {@link Blob.type}.
11187 * @param args File lookup options.
11188 * @param args.ref Branch, tag, or commit ID to resolve.
11189 * @param args.path Non-empty repository-relative path.
11190 * @returns A MIME-typed {@link Blob}, or `null` if the ref or path cannot resolve to a file.
11191 * @throws {ArtifactsError} `INVALID_INPUT` if either argument is empty, `MEMORY_LIMIT` if the
11192 * file cannot be buffered safely, or `INTERNAL_ERROR` on an unexpected read failure.
11193 */
11194 readFile(args: {
11195 ref: string;
11196 path: string;
11197 }): Promise<Blob | null>;
11198 /**
11199 * List commits along the first-parent chain, newest first.
11200 * @param opts History options. All fields are optional.
11201 * @param opts.ref Branch, tag, or commit ID; defaults to `HEAD`.
11202 * @param opts.limit Maximum results; defaults to `50` and is capped at `1000`.
11203 * @param opts.offset Number of matching commits to skip; defaults to `0`.
11204 * @returns Commit metadata, or an empty array if the ref cannot be resolved.
11205 * @throws {ArtifactsError} `INTERNAL_ERROR` on an unexpected traversal failure.
11206 * @see {@link ArtifactsCommitMetadata}
11207 */
11208 log(opts?: {
11209 ref?: string;
11210 limit?: number;
11211 offset?: number;
11212 }): Promise<ArtifactsCommitMetadata[]>;
11213 // ── Fork ──
11214 /**
11215 * Fork this repo to a new repo.
11216 * @param name Target repository name.
11217 * @param opts Optional: description, readOnly flag, defaultBranchOnly (default true).
11218 * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid.
11219 * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the target repo already exists.
11220 * @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if a fork is already running.
11221 */
11222 fork(name: string, opts?: {
11223 description?: string;
11224 readOnly?: boolean;
11225 defaultBranchOnly?: boolean;
11226 }): Promise<ArtifactsCreateRepoResult>;
11227}
11228// ── Error types ──────────────────────────────────────────────────────────────
11229/**
11230 * Error codes returned by Artifacts binding operations.
11231 *
11232 * Each code maps to a numeric code available on `ArtifactsError.numericCode`.
11233 */
11234type 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';
11235/**
11236 * Error thrown by Artifacts binding operations.
11237 *
11238 * Uses a string `.code` discriminator following the Cloudflare platform
11239 * convention (StreamError, ImagesError, etc.). The `.numericCode` matches
11240 * the REST API `errors[].code` values.
11241 */
11242interface ArtifactsError extends Error {
11243 readonly name: 'ArtifactsError';
11244 /** String error code for programmatic matching. */
11245 readonly code: ArtifactsErrorCode;
11246 /** Numeric error code matching the REST API. */
11247 readonly numericCode: number;
11248}
11249// ── Binding ──────────────────────────────────────────────────────────────────
11250/**
11251 * Artifacts binding — namespace-level operations.
11252 *
11253 * Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs.
11254 */
11255interface Artifacts {
11256 /**
11257 * Create a new repository with an initial access token.
11258 * @param name Repository name (alphanumeric, dots, hyphens, underscores).
11259 * @param opts Optional: readOnly flag, description, default branch name.
11260 * @returns Repo metadata with initial token.
11261 * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid.
11262 * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the repo already exists.
11263 */
11264 create(name: string, opts?: {
11265 readOnly?: boolean;
11266 description?: string;
11267 setDefaultBranch?: string;
11268 }): Promise<ArtifactsCreateRepoResult>;
11269 /**
11270 * Get a handle to an existing repository.
11271 * @param name Repository name.
11272 * @returns Repo handle.
11273 * @throws {ArtifactsError} with code `NOT_FOUND` if the repo does not exist.
11274 * @throws {ArtifactsError} with code `CREATE_IN_PROGRESS` if the repo is still being created.
11275 * @throws {ArtifactsError} with code `IMPORT_IN_PROGRESS` if the repo is still importing.
11276 * @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if the repo is still forking.
11277 */
11278 get(name: string): Promise<ArtifactsRepo>;
11279 /**
11280 * Import a repository from an external git remote.
11281 * @param params Source URL and optional branch/depth, plus target name and options.
11282 * @returns Repo metadata with initial token.
11283 * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if the target name is invalid.
11284 * @throws {ArtifactsError} with code `INVALID_INPUT` if the source URL is not valid HTTPS.
11285 * @throws {ArtifactsError} with code `INVALID_URL` if the source URL does not point to a git repository.
11286 * @throws {ArtifactsError} with code `REMOTE_AUTH_REQUIRED` if the remote requires authentication.
11287 * @throws {ArtifactsError} with code `NOT_FOUND` if the remote repository does not exist.
11288 * @throws {ArtifactsError} with code `UPSTREAM_UNAVAILABLE` if the remote cannot be reached.
11289 * @throws {ArtifactsError} with code `MEMORY_LIMIT` if the import exceeds service memory limits.
11290 * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the target repo already exists.
11291 */
11292 import(params: {
11293 source: {
11294 url: string;
11295 branch?: string;
11296 depth?: number;
11297 };
11298 target: {
11299 name: string;
11300 opts?: {
11301 description?: string;
11302 readOnly?: boolean;
11303 };
11304 };
11305 }): Promise<ArtifactsCreateRepoResult>;
11306 /**
11307 * List repositories with cursor-based pagination.
11308 * @param opts Optional: limit (1–200, default 50), cursor for next page.
11309 */
11310 list(opts?: {
11311 limit?: number;
11312 cursor?: string;
11313 }): Promise<ArtifactsRepoListResult>;
11314 /**
11315 * Delete a repository and all associated tokens.
11316 * @param name Repository name.
11317 * @returns true if deleted, false if not found.
11318 * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid.
11319 */
11320 delete(name: string): Promise<boolean>;
11321}
11322/**
11323 * @deprecated Use the standalone AI Search Workers binding instead.
11324 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11325 */
11326interface AutoRAGInternalError extends Error {
11327}
11328/**
11329 * @deprecated Use the standalone AI Search Workers binding instead.
11330 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11331 */
11332interface AutoRAGNotFoundError extends Error {
11333}
11334/**
11335 * @deprecated Use the standalone AI Search Workers binding instead.
11336 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11337 */
11338interface AutoRAGUnauthorizedError extends Error {
11339}
11340/**
11341 * @deprecated Use the standalone AI Search Workers binding instead.
11342 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11343 */
11344interface AutoRAGNameNotSetError extends Error {
11345}
11346type ComparisonFilter = {
11347 key: string;
11348 type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte';
11349 value: string | number | boolean;
11350};
11351type CompoundFilter = {
11352 type: 'and' | 'or';
11353 filters: ComparisonFilter[];
11354};
11355/**
11356 * @deprecated Use the standalone AI Search Workers binding instead.
11357 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11358 */
11359type AutoRagSearchRequest = {
11360 query: string;
11361 filters?: CompoundFilter | ComparisonFilter;
11362 max_num_results?: number;
11363 ranking_options?: {
11364 ranker?: string;
11365 score_threshold?: number;
11366 };
11367 reranking?: {
11368 enabled?: boolean;
11369 model?: string;
11370 };
11371 rewrite_query?: boolean;
11372};
11373/**
11374 * @deprecated Use the standalone AI Search Workers binding instead.
11375 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11376 */
11377type AutoRagAiSearchRequest = AutoRagSearchRequest & {
11378 stream?: boolean;
11379 system_prompt?: string;
11380};
11381/**
11382 * @deprecated Use the standalone AI Search Workers binding instead.
11383 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11384 */
11385type AutoRagAiSearchRequestStreaming = Omit<AutoRagAiSearchRequest, 'stream'> & {
11386 stream: true;
11387};
11388/**
11389 * @deprecated Use the standalone AI Search Workers binding instead.
11390 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11391 */
11392type AutoRagSearchResponse = {
11393 object: 'vector_store.search_results.page';
11394 search_query: string;
11395 data: {
11396 file_id: string;
11397 filename: string;
11398 score: number;
11399 attributes: Record<string, string | number | boolean | null>;
11400 content: {
11401 type: 'text';
11402 text: string;
11403 }[];
11404 }[];
11405 has_more: boolean;
11406 next_page: string | null;
11407};
11408/**
11409 * @deprecated Use the standalone AI Search Workers binding instead.
11410 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11411 */
11412type AutoRagListResponse = {
11413 id: string;
11414 enable: boolean;
11415 type: string;
11416 source: string;
11417 vectorize_name: string;
11418 paused: boolean;
11419 status: string;
11420}[];
11421/**
11422 * @deprecated Use the standalone AI Search Workers binding instead.
11423 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11424 */
11425type AutoRagAiSearchResponse = AutoRagSearchResponse & {
11426 response: string;
11427};
11428/**
11429 * @deprecated Use the standalone AI Search Workers binding instead.
11430 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11431 */
11432declare abstract class AutoRAG {
11433 /**
11434 * @deprecated Use the standalone AI Search Workers binding instead.
11435 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11436 */
11437 list(): Promise<AutoRagListResponse>;
11438 /**
11439 * @deprecated Use the standalone AI Search Workers binding instead.
11440 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11441 */
11442 search(params: AutoRagSearchRequest): Promise<AutoRagSearchResponse>;
11443 /**
11444 * @deprecated Use the standalone AI Search Workers binding instead.
11445 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11446 */
11447 aiSearch(params: AutoRagAiSearchRequestStreaming): Promise<Response>;
11448 /**
11449 * @deprecated Use the standalone AI Search Workers binding instead.
11450 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11451 */
11452 aiSearch(params: AutoRagAiSearchRequest): Promise<AutoRagAiSearchResponse>;
11453 /**
11454 * @deprecated Use the standalone AI Search Workers binding instead.
11455 * See https://developers.cloudflare.com/ai-search/usage/workers-binding/
11456 */
11457 aiSearch(params: AutoRagAiSearchRequest): Promise<AutoRagAiSearchResponse | Response>;
11458}
11459type BrowserRunLifecycleEvent = 'load' | 'domcontentloaded' | 'networkidle0' | 'networkidle2';
11460type BrowserRunResourceType = 'document' | 'stylesheet' | 'image' | 'media' | 'font' | 'script' | 'texttrack' | 'xhr' | 'fetch' | 'prefetch' | 'eventsource' | 'websocket' | 'manifest' | 'signedexchange' | 'ping' | 'cspviolationreport' | 'preflight' | 'other';
11461/** Options fields shared by all quick actions. */
11462interface BrowserRunBaseOptions {
11463 /** Adds `<script>` tags into the page with the desired URL or content.
11464 * @see https://pptr.dev/api/puppeteer.frameaddscripttagoptions
11465 */
11466 addScriptTag?: Array<{
11467 content?: string;
11468 url?: string;
11469 type?: string;
11470 id?: string;
11471 }>;
11472 /** Adds `<link rel="stylesheet">` or `<style>` tags into the page.
11473 * @see https://pptr.dev/api/puppeteer.frameaddstyletagoptions
11474 */
11475 addStyleTag?: Array<{
11476 content?: string;
11477 url?: string;
11478 }>;
11479 /** Provide credentials for HTTP authentication. @see https://pptr.dev/api/puppeteer.credentials */
11480 authenticate?: {
11481 username: string;
11482 password: string;
11483 };
11484 /** Set cookies before navigating. @see https://pptr.dev/api/puppeteer.cookieparam */
11485 cookies?: Array<{
11486 name: string;
11487 value: string;
11488 url?: string;
11489 domain?: string;
11490 path?: string;
11491 secure?: boolean;
11492 httpOnly?: boolean;
11493 sameSite?: 'Strict' | 'Lax' | 'None';
11494 expires?: number;
11495 priority?: 'Low' | 'Medium' | 'High';
11496 sameParty?: boolean;
11497 sourceScheme?: 'Unset' | 'NonSecure' | 'Secure';
11498 sourcePort?: number;
11499 partitionKey?: string;
11500 }>;
11501 /** Emulate a specific CSS media type (e.g. `"screen"`, `"print"`). */
11502 emulateMediaType?: string;
11503 /** Navigation options. @see https://pptr.dev/api/puppeteer.gotooptions */
11504 gotoOptions?: {
11505 /** Navigation timeout in milliseconds (max 60 000). @default 30000 */
11506 timeout?: number;
11507 /** When to consider navigation complete. @default "domcontentloaded" */
11508 waitUntil?: BrowserRunLifecycleEvent | BrowserRunLifecycleEvent[];
11509 referer?: string;
11510 referrerPolicy?: string;
11511 };
11512 /** Block requests matching these regex patterns. Mutually exclusive with `allowRequestPattern`. */
11513 rejectRequestPattern?: string[];
11514 /** Only allow requests matching these regex patterns. Mutually exclusive with `rejectRequestPattern`. */
11515 allowRequestPattern?: string[];
11516 /** Block requests of these resource types. Mutually exclusive with `allowResourceTypes`. */
11517 rejectResourceTypes?: BrowserRunResourceType[];
11518 /** Only allow requests of these resource types. Mutually exclusive with `rejectResourceTypes`. */
11519 allowResourceTypes?: BrowserRunResourceType[];
11520 /** Additional HTTP headers sent with every request. */
11521 setExtraHTTPHeaders?: Record<string, string>;
11522 /** Whether JavaScript is enabled on the page. */
11523 setJavaScriptEnabled?: boolean;
11524 /** Override the default user agent string.
11525 * @default "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36"
11526 * */
11527 userAgent?: string;
11528 /** Set the browser viewport size.
11529 * @see https://pptr.dev/api/puppeteer.viewport
11530 * @default {width:1920,height:1080}
11531 * */
11532 viewport?: {
11533 width: number;
11534 height: number;
11535 deviceScaleFactor?: number;
11536 isMobile?: boolean;
11537 isLandscape?: boolean;
11538 hasTouch?: boolean;
11539 };
11540 /** Wait for a CSS selector to appear in the page before proceeding.
11541 * @see https://pptr.dev/api/puppeteer.waitforselectoroptions
11542 */
11543 waitForSelector?: {
11544 selector: string;
11545 hidden?: true;
11546 visible?: true;
11547 /** Timeout in milliseconds. Max 120000 */
11548 timeout?: number;
11549 };
11550 /** Wait for a fixed delay in milliseconds before proceeding. Max 120000 */
11551 waitForTimeout?: number;
11552 /** When true, continue on best-effort when awaited events fail or timeout. */
11553 bestAttempt?: boolean;
11554 /** Maximum duration in milliseconds for the browser action after page load. Max 120000 */
11555 actionTimeout?: number;
11556 /** Cache time to live in seconds (0-86400). Set to 0 to disable.
11557 * @default 5
11558 */
11559 cacheTTL?: number;
11560}
11561/**
11562 * Backend selection, mixed into the options of the quick actions that support it.
11563 * Deliberately not part of `BrowserRunBaseOptions`: `scrape`, `links` and `snapshot`
11564 * reject an alternate backend, so they must not accept the field.
11565 */
11566interface BrowserRunAlternateBackendOptions {
11567 /** Render with an alternate browser backend instead of the default one. */
11568 browser?: 'kitesurf';
11569}
11570/** Common options shared by all quick actions. Exactly one of `url` or `html` must be provided.*/
11571type BrowserRunCommonOptions = (BrowserRunBaseOptions & {
11572 /** URL to navigate to, e.g. `"https://example.com"`. */
11573 url: string;
11574}) | (BrowserRunBaseOptions & {
11575 /** Set the HTML content of the page directly. */
11576 html: string;
11577});
11578type BrowserRunPuppeteerScreenshotOptions = {
11579 /** @default "png" */
11580 type?: 'png' | 'jpeg' | 'webp';
11581 /** @default "binary" */
11582 encoding?: 'binary' | 'base64';
11583 quality?: number;
11584 fullPage?: boolean;
11585 clip?: {
11586 x: number;
11587 y: number;
11588 width: number;
11589 height: number;
11590 scale?: number;
11591 };
11592 omitBackground?: boolean;
11593 optimizeForSpeed?: boolean;
11594 captureBeyondViewport?: boolean;
11595 fromSurface?: boolean;
11596};
11597type BrowserRunScreenshotOptions = BrowserRunCommonOptions & {
11598 /** CSS selector of the element to screenshot. */
11599 selector?: string;
11600 /** When true, scroll the entire page before taking the screenshot. */
11601 scrollPage?: boolean;
11602 /** @see https://pptr.dev/api/puppeteer.screenshotoptions */
11603 screenshotOptions?: BrowserRunPuppeteerScreenshotOptions;
11604} & BrowserRunAlternateBackendOptions;
11605type BrowserRunPDFOptions = BrowserRunCommonOptions & {
11606 /** @see https://pptr.dev/api/puppeteer.pdfoptions */
11607 pdfOptions?: {
11608 /** @default 1 */
11609 scale?: number;
11610 /** @default false */
11611 displayHeaderFooter?: boolean;
11612 headerTemplate?: string;
11613 footerTemplate?: string;
11614 /** @default false */
11615 printBackground?: boolean;
11616 /** @default false */
11617 landscape?: boolean;
11618 pageRanges?: string;
11619 /** @default "letter" */
11620 format?: 'letter' | 'legal' | 'tabloid' | 'ledger' | 'a0' | 'a1' | 'a2' | 'a3' | 'a4' | 'a5' | 'a6';
11621 width?: string | number;
11622 height?: string | number;
11623 /** @default false */
11624 preferCSSPageSize?: boolean;
11625 margin?: {
11626 top?: string | number;
11627 right?: string | number;
11628 bottom?: string | number;
11629 left?: string | number;
11630 };
11631 /** @default false */
11632 omitBackground?: boolean;
11633 /** @default true */
11634 tagged?: boolean;
11635 /** @default false */
11636 outline?: boolean;
11637 /** @default 30000 */
11638 timeout?: number;
11639 };
11640} & BrowserRunAlternateBackendOptions;
11641type BrowserRunScrapeOptions = BrowserRunCommonOptions & {
11642 /** CSS selectors to scrape. At least one element is required. */
11643 elements: Array<{
11644 selector: string;
11645 }>;
11646};
11647type BrowserRunLinksOptions = BrowserRunCommonOptions & {
11648 /** When true, only return links that are visible on the page. @default false */
11649 visibleLinksOnly?: boolean;
11650 /** When true, exclude links pointing to external domains. @default false */
11651 excludeExternalLinks?: boolean;
11652};
11653type BrowserRunSnapshotFormat = 'content' | 'screenshot' | 'markdown' | 'accessibilityTree';
11654type BrowserRunSnapshotOptions = BrowserRunCommonOptions & {
11655 /** Which representations of the page to return. At least two distinct formats
11656 * are required; request a single format from its dedicated action instead.
11657 * @default ["content","screenshot"]
11658 */
11659 formats?: BrowserRunSnapshotFormat[];
11660 /** @see https://pptr.dev/api/puppeteer.screenshotoptions */
11661 screenshotOptions?: Omit<BrowserRunPuppeteerScreenshotOptions, 'encoding'>;
11662};
11663/** Options for the `accessibilityTree` quick action. */
11664type BrowserRunAccessibilityTreeOptions = BrowserRunCommonOptions & {
11665 /** When true, prune nodes that carry no semantic meaning, such as generic
11666 * containers. Defaults to true, or to false when `root` is set so that the
11667 * requested subtree is returned as-is.
11668 */
11669 interestingOnly?: boolean;
11670 /** CSS selector limiting the tree to the matching element's subtree.
11671 * A selector that matches nothing yields `accessibilityTree: null` with
11672 * HTTP 200; a malformed selector is an error.
11673 */
11674 root?: string;
11675} & BrowserRunAlternateBackendOptions;
11676interface BrowserRunJsonBaseOptions {
11677 /** Custom AI models to try in order. Max 3. Falls back to next on error. */
11678 custom_ai?: Array<{
11679 /** Model ID in `<provider>/<model_name>` format, e.g. `"workers-ai/@cf/meta/llama-3.3-70b-instruct-fp8-fast"`. */
11680 model: string;
11681 /** Bearer token. Not needed for workers-ai models. */
11682 authorization?: string;
11683 }>;
11684}
11685/**
11686 * Options for the `json` quick action.
11687 * At least one of `prompt` or `response_format` must be provided.
11688 */
11689type BrowserRunJsonOptions = BrowserRunCommonOptions & BrowserRunAlternateBackendOptions & BrowserRunJsonBaseOptions & ({
11690 /** Natural-language prompt describing what data to extract. */
11691 prompt: string;
11692 /** Structured output schema for the AI model. @see https://developers.cloudflare.com/workers-ai/json-mode/ */
11693 response_format?: AiTextGenerationResponseFormat;
11694} | {
11695 /** Natural-language prompt describing what data to extract. */
11696 prompt?: string;
11697 /** Structured output schema for the AI model. @see https://developers.cloudflare.com/workers-ai/json-mode/ */
11698 response_format: AiTextGenerationResponseFormat;
11699});
11700type BrowserRunContentOptions = BrowserRunCommonOptions & BrowserRunAlternateBackendOptions;
11701type BrowserRunMarkdownOptions = BrowserRunCommonOptions & BrowserRunAlternateBackendOptions;
11702type BrowserRunRedirectHop = {
11703 /** URL that returned the redirect. */
11704 url: string;
11705 /** HTTP status of the redirect. */
11706 status: number;
11707 /** Redirect response headers, including `location`. */
11708 headers: Record<string, string>;
11709};
11710type BrowserRunResponseMeta = {
11711 /** HTTP status code of the rendered page */
11712 status: number;
11713 /** Page title */
11714 title: string;
11715 /** Origin response headers, lowercased. Repeated headers are joined with a newline. Credential and transport-only headers that do not survive rendering are omitted. */
11716 headers?: Record<string, string>;
11717 /** URL that served the response, after any redirects the browser followed. */
11718 finalUrl?: string;
11719 /** 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. */
11720 redirectChain?: BrowserRunRedirectHop[];
11721};
11722/**
11723 * A node in the page's accessibility tree, as exposed to assistive technology.
11724 * `role` is the only field always present; the rest are populated when the
11725 * underlying element defines them.
11726 * @see https://pptr.dev/api/puppeteer.serializedaxnode
11727 */
11728interface BrowserRunSerializedAXNode {
11729 /** The ARIA role, e.g. `"button"`, `"heading"`, `"RootWebArea"`. */
11730 role: string;
11731 /** The `aria-autocomplete` value. */
11732 autocomplete?: string;
11733 /** Checked state of a checkbox, radio, or menu item. */
11734 checked?: boolean | 'mixed';
11735 /** Accessible description, typically from `aria-describedby` or `title`. */
11736 description?: string;
11737 disabled?: boolean;
11738 expanded?: boolean;
11739 /** Whether the element currently holds keyboard focus. */
11740 focused?: boolean;
11741 /** The kind of popup the element triggers, e.g. `"menu"`, `"dialog"`. */
11742 haspopup?: string;
11743 /** The `aria-invalid` value. */
11744 invalid?: string;
11745 /** Keyboard shortcuts bound to the element, from `aria-keyshortcuts`. */
11746 keyshortcuts?: string;
11747 /** Hierarchical level, e.g. the heading level of an `<h2>`. */
11748 level?: number;
11749 /** Whether the element is a modal dialog. */
11750 modal?: boolean;
11751 /** Whether a text input accepts multiple lines. */
11752 multiline?: boolean;
11753 /** Whether more than one option can be selected. */
11754 multiselectable?: boolean;
11755 /** Accessible name, e.g. a button's label or an image's alt text. */
11756 name?: string;
11757 orientation?: string;
11758 /** Pressed state of a toggle button. */
11759 pressed?: boolean | 'mixed';
11760 readonly?: boolean;
11761 required?: boolean;
11762 /** Author-supplied role description, from `aria-roledescription`. */
11763 roledescription?: string;
11764 selected?: boolean;
11765 /** Current value of an input or range element. */
11766 value?: string | number;
11767 valuemax?: number;
11768 valuemin?: number;
11769 /** Human-readable form of `value`, from `aria-valuetext`. */
11770 valuetext?: string;
11771 /** Child nodes. Absent for leaf nodes. */
11772 children?: BrowserRunSerializedAXNode[];
11773}
11774/** Success response for `content` action. */
11775type BrowserRunContentSuccessResponse = {
11776 success: true;
11777 /** Extracted HTML content */
11778 result: string;
11779 meta: BrowserRunResponseMeta;
11780};
11781/** Success response for `links` action. */
11782type BrowserRunLinksSuccessResponse = {
11783 success: true;
11784 /** Extracted links */
11785 result: string[];
11786 meta: BrowserRunResponseMeta;
11787};
11788/** Success response for `scrape` action. */
11789type BrowserRunScrapeSuccessResponse = {
11790 success: true;
11791 result: Array<{
11792 /** The CSS selector used to find elements. */
11793 selector: string;
11794 /** Array of elements matching the selector. */
11795 results: Array<{
11796 /** Outer HTML of the element. */
11797 html: string;
11798 /** Text content of the element. */
11799 text: string;
11800 /** Width of the element in pixels. */
11801 width: number;
11802 /** Height of the element in pixels. */
11803 height: number;
11804 /** Top position of the element relative to the viewport in pixels. */
11805 top: number;
11806 /** Left position of the element relative to the viewport in pixels. */
11807 left: number;
11808 /** Array of HTML attributes on the element. */
11809 attributes: Array<{
11810 /** Attribute name. */
11811 name: string;
11812 /** Attribute value. */
11813 value: string;
11814 }>;
11815 }>;
11816 }>;
11817 meta: BrowserRunResponseMeta;
11818};
11819/** Success response for `snapshot` action. Each field is present only when the
11820 * corresponding entry was requested in `formats`.
11821 */
11822type BrowserRunSnapshotSuccessResponse = {
11823 success: true;
11824 result: {
11825 /** HTML content of the page. */
11826 content?: string;
11827 /** Base64-encoded screenshot image. */
11828 screenshot?: string;
11829 /** Markdown content. Prefixed with YAML frontmatter (e.g. `title`) when the
11830 * page provides that metadata.
11831 */
11832 markdown?: string;
11833 /** Root of the page's accessibility tree. */
11834 accessibilityTree?: BrowserRunSerializedAXNode;
11835 };
11836 meta: BrowserRunResponseMeta;
11837};
11838/** Success response for `accessibilityTree` action. */
11839type BrowserRunAccessibilityTreeSuccessResponse = {
11840 success: true;
11841 result: {
11842 /** Root of the accessibility tree, or `null` when `root` matched no element. */
11843 accessibilityTree: BrowserRunSerializedAXNode | null;
11844 };
11845 meta: BrowserRunResponseMeta;
11846};
11847/** Success response for `json` action. */
11848type BrowserRunJsonSuccessResponse = {
11849 success: true;
11850 /** JSON data extracted from the page using an AI model */
11851 result: Record<string, unknown>;
11852 meta: BrowserRunResponseMeta;
11853};
11854/** Success response for `markdown` action. */
11855type BrowserRunMarkdownSuccessResponse = {
11856 success: true;
11857 /** Extracted markdown content */
11858 result: string;
11859 meta: BrowserRunResponseMeta;
11860};
11861/** Error response for BrowserRun actions. */
11862type BrowserRunErrorResponse = {
11863 success: false;
11864 errors: {
11865 message: string;
11866 code?: number;
11867 detail?: string;
11868 path?: string;
11869 }[];
11870};
11871/** Error response for BrowserRun `json` action. */
11872type BrowserRunJsonErrorResponse = BrowserRunErrorResponse & {
11873 /** Raw AI response text for debugging */
11874 rawAiResponse?: string;
11875};
11876/** Session-scoped guardrails applied when acquiring a browser session. */
11877type BrowserRunAcquireGuardrails = {
11878 /** Domains that the browser may access. An empty list denies all domains. */
11879 allowedDomains?: string[];
11880 /** Named domain sets that the browser may access. */
11881 allowedDomainSets?: string[];
11882};
11883/** Options for acquiring a new browser session. */
11884type BrowserRunAcquireOptions = {
11885 /** Idle session lifetime in milliseconds. */
11886 keepAlive?: number;
11887 /** Record the browser session. */
11888 recording?: boolean;
11889 /** Geoegress hint as an ISO-3166 alpha-2 country code. */
11890 location?: string;
11891 /** Map hostnames to caller-provided Workers that handle outbound requests. */
11892 outboundByHost?: Record<string, Fetcher>;
11893 /** Session-scoped network guardrails. */
11894 guardrails?: BrowserRunAcquireGuardrails;
11895 /** Include the session's DevTools targets in the result. */
11896 targets?: boolean;
11897 /** Lifetime of target live-view URLs in milliseconds. */
11898 liveViewUrlExpiresInMs?: number;
11899};
11900/** Metadata returned when a browser session is acquired. */
11901type BrowserRunAcquireResult = {
11902 sessionId: string;
11903 targets?: BrowserRunDevToolsTarget[];
11904};
11905/** Options for connecting to an already-acquired browser session. */
11906type BrowserRunConnectOptions = {
11907 /** Connect to a specific page target instead of the browser-level CDP endpoint. */
11908 targetId?: string;
11909};
11910/** Connection capability returned by `connectSession()` and `launch()`. */
11911type BrowserRunConnection = {
11912 sessionId: string;
11913 /** A session-pinned Fetcher. Use its `fetch()` method for a WebSocket upgrade. */
11914 webSocket: Fetcher;
11915 targets?: BrowserRunDevToolsTarget[];
11916};
11917/** The UI mode for a live-view link. */
11918type BrowserRunLiveViewMode = 'devtools' | 'tab' | 'full';
11919/** Connection-scoped guardrails applied to a live-view link. */
11920type BrowserRunConnectionGuardrails = {
11921 mode: 'readonly';
11922};
11923/** Options for minting a live-view link. */
11924type BrowserRunLiveViewOptions = {
11925 mode?: BrowserRunLiveViewMode;
11926 targetId?: string;
11927 expiresInMs?: number;
11928 guardrails?: BrowserRunConnectionGuardrails;
11929};
11930/** Live-view link metadata. */
11931type BrowserRunLiveView = {
11932 webSocketDebuggerUrl: string;
11933 devtoolsFrontendUrl: string;
11934 id: string;
11935 options: {
11936 mode: BrowserRunLiveViewMode;
11937 guardrails?: BrowserRunConnectionGuardrails;
11938 };
11939};
11940/** Options for listing active browser sessions. */
11941type BrowserRunListSessionsOptions = {
11942 limit?: number;
11943 offset?: number;
11944};
11945/** Options for listing session history. */
11946type BrowserRunHistoryOptions = {
11947 limit?: number;
11948 offset?: number;
11949};
11950/** A browser session returned by the session-management methods. */
11951type BrowserRunSession = {
11952 sessionId: string;
11953 startTime?: number;
11954 endTime?: number;
11955 closeReason?: number;
11956 closeReasonText?: string;
11957 connectionId?: string;
11958 connectionStartTime?: number;
11959 connectionEndTime?: number;
11960 lastUpdated?: number;
11961 webSocketDebuggerUrl?: string;
11962 devtoolsFrontendUrl?: string;
11963};
11964/** Account browser-session and browser-time limits. */
11965type BrowserRunLimits = {
11966 activeSessions: Array<{
11967 id: string;
11968 }>;
11969 maxConcurrentSessions: number;
11970 allowedBrowserAcquisitions: number;
11971 timeUntilNextAllowedBrowserAcquisition: number;
11972 usedBrowserTimeSeconds?: number;
11973};
11974/** A browser target returned by the DevTools JSON methods. */
11975type BrowserRunDevToolsTarget = {
11976 id: string;
11977 type: string;
11978 url: string;
11979 title?: string;
11980 description?: string;
11981 webSocketDebuggerUrl?: string;
11982 devtoolsFrontendUrl?: string;
11983};
11984/** Browser and protocol version metadata. */
11985type BrowserRunDevToolsVersion = {
11986 Browser: string;
11987 'Protocol-Version': string;
11988 'User-Agent': string;
11989 'V8-Version': string;
11990 'WebKit-Version': string;
11991 webSocketDebuggerUrl: string;
11992};
11993/** A DevTools protocol domain. Protocol definitions may gain additional fields over time. */
11994interface BrowserRunDevToolsProtocolDomain extends Record<string, unknown> {
11995 domain: string;
11996 experimental?: boolean;
11997 dependencies?: string[];
11998 types?: Array<Record<string, any>>;
11999 commands?: Array<Record<string, any>>;
12000 events?: Array<Record<string, any>>;
12001}
12002/** The DevTools protocol definition. Additional protocol fields may be returned by Chrome. */
12003interface BrowserRunDevToolsProtocol extends Record<string, any> {
12004 domains: BrowserRunDevToolsProtocolDomain[];
12005 version?: {
12006 major: string;
12007 minor: string;
12008 };
12009}
12010/** Options shared by DevTools target-listing and target-creation methods. */
12011type BrowserRunTargetOptions = {
12012 liveViewUrlExpiresInMs?: number;
12013};
12014/** Result returned by DevTools target activation and close methods. */
12015type BrowserRunTargetActionResult = {
12016 message: string;
12017};
12018/** Methods exposed by the nested `devtools` binding target. */
12019type BrowserRunDevtools = {
12020 getVersion(sessionId: string): Promise<BrowserRunDevToolsVersion>;
12021 getProtocol(sessionId: string): Promise<BrowserRunDevToolsProtocol>;
12022 listTargets(sessionId: string, options?: BrowserRunTargetOptions): Promise<BrowserRunDevToolsTarget[]>;
12023 getTarget(sessionId: string, targetId: string): Promise<BrowserRunDevToolsTarget>;
12024 newTarget(sessionId: string, url?: string, options?: BrowserRunTargetOptions): Promise<BrowserRunDevToolsTarget>;
12025 activateTarget(sessionId: string, targetId: string): Promise<BrowserRunTargetActionResult>;
12026 closeTarget(sessionId: string, targetId: string): Promise<BrowserRunTargetActionResult>;
12027};
12028/** Result returned when closing a browser session. */
12029type BrowserRunCloseSessionResult = {
12030 status: 'closing' | 'closed';
12031};
12032/**
12033 * Browser Run API binding for automating headless browsers.
12034 * @see https://developers.cloudflare.com/browser-run/
12035 */
12036declare abstract class BrowserRun {
12037 /**
12038 * Send a raw HTTP request to the Browser Run API.
12039 * Used by libraries like `@cloudflare/puppeteer` to acquire and connect to a browser instance.
12040 * @see https://developers.cloudflare.com/browser-run/
12041 */
12042 fetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
12043 /**
12044 * Take a screenshot of a web page.
12045 * @param action - Must be `'screenshot'`.
12046 * @param options - Screenshot options including viewport, selectors, and image format.
12047 * @returns A `Response` containing one of:
12048 *
12049 * **Success (HTTP 200):**
12050 * - Binary image data with `Content-Type: image/png`, `image/jpeg`, or `image/webp` (when `encoding: 'binary'`, the default)
12051 * - Data URI string with `Content-Type: text/plain` (when `encoding: 'base64'`)
12052 *
12053 * **Error:**
12054 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
12055 *
12056 * **Headers:**
12057 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
12058 */
12059 quickAction(action: 'screenshot', options: BrowserRunScreenshotOptions): Promise<Response>;
12060 /**
12061 * Generate a PDF of a web page.
12062 * @param action - Must be `'pdf'`.
12063 * @param options - PDF generation options including page size, margins, and headers/footers.
12064 * @returns A `Response` containing one of:
12065 *
12066 * **Success (HTTP 200):**
12067 * - Binary PDF data with `Content-Type: application/pdf`
12068 *
12069 * **Error:**
12070 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
12071 *
12072 * **Headers:**
12073 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
12074 */
12075 quickAction(action: 'pdf', options: BrowserRunPDFOptions): Promise<Response>;
12076 /**
12077 * Get the HTML content of a web page.
12078 * @param action - Must be `'content'`.
12079 * @param options - Navigation and page interaction options.
12080 * @returns A `Response` containing one of:
12081 *
12082 * **Success (HTTP 200):**
12083 * - `BrowserRunContentSuccessResponse` JSON with `Content-Type: application/json`
12084 *
12085 * **Error:**
12086 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
12087 *
12088 * **Headers:**
12089 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
12090 */
12091 quickAction(action: 'content', options: BrowserRunContentOptions): Promise<Response>;
12092 /**
12093 * Scrape elements from a web page by CSS selector.
12094 * @param action - Must be `'scrape'`.
12095 * @param options - Scrape options with CSS selectors for elements to extract.
12096 * @returns A `Response` containing one of:
12097 *
12098 * **Success (HTTP 200):**
12099 * - `BrowserRunScrapeSuccessResponse` JSON with `Content-Type: application/json`
12100 *
12101 * **Error:**
12102 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
12103 *
12104 * **Headers:**
12105 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
12106 */
12107 quickAction(action: 'scrape', options: BrowserRunScrapeOptions): Promise<Response>;
12108 /**
12109 * Extract all links from a web page.
12110 * @param action - Must be `'links'`.
12111 * @param options - Options to filter visible or internal links only.
12112 * @returns A `Response` containing one of:
12113 *
12114 * **Success (HTTP 200):**
12115 * - `BrowserRunLinksSuccessResponse` JSON with `Content-Type: application/json`
12116 *
12117 * **Error:**
12118 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
12119 *
12120 * **Headers:**
12121 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
12122 */
12123 quickAction(action: 'links', options: BrowserRunLinksOptions): Promise<Response>;
12124 /**
12125 * Get several representations of a web page in one request.
12126 * @param action - Must be `'snapshot'`.
12127 * @param options - Snapshot options including the `formats` to return and
12128 * screenshot settings (encoding is always base64).
12129 * @returns A `Response` containing one of:
12130 *
12131 * **Success (HTTP 200):**
12132 * - `BrowserRunSnapshotSuccessResponse` JSON with `Content-Type: application/json`
12133 *
12134 * **Error:**
12135 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
12136 *
12137 * **Headers:**
12138 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
12139 */
12140 quickAction(action: 'snapshot', options: BrowserRunSnapshotOptions): Promise<Response>;
12141 /**
12142 * Extract structured JSON data from a web page using AI.
12143 * @param action - Must be `'json'`.
12144 * @param options - JSON extraction options with prompt or response_format schema.
12145 * @returns A `Response` containing one of:
12146 *
12147 * **Success (HTTP 200):**
12148 * - `BrowserRunJsonSuccessResponse` JSON with `Content-Type: application/json`
12149 *
12150 * **Error:**
12151 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
12152 * - HTTP 422 with code `2012` for HTML-to-markdown conversion failures
12153 * - HTTP 422/500 for AI extraction failures (may include `rawAiResponse` field)
12154 *
12155 * **Headers:**
12156 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
12157 */
12158 quickAction(action: 'json', options: BrowserRunJsonOptions): Promise<Response>;
12159 /**
12160 * Convert a web page to Markdown.
12161 * @param action - Must be `'markdown'`.
12162 * @param options - Navigation and page interaction options.
12163 * @returns A `Response` containing one of:
12164 *
12165 * **Success (HTTP 200):**
12166 * - `BrowserRunMarkdownSuccessResponse` JSON with `Content-Type: application/json`
12167 *
12168 * **Error:**
12169 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
12170 * - HTTP 422 with code `2012` for HTML-to-markdown conversion failures
12171 *
12172 * **Headers:**
12173 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
12174 */
12175 quickAction(action: 'markdown', options: BrowserRunMarkdownOptions): Promise<Response>;
12176 /**
12177 * Get the accessibility tree of a web page.
12178 * @param action - Must be `'accessibilityTree'`.
12179 * @param options - Options to scope the tree to a subtree and to control
12180 * whether semantically uninteresting nodes are pruned.
12181 * @returns A `Response` containing one of:
12182 *
12183 * **Success (HTTP 200):**
12184 * - `BrowserRunAccessibilityTreeSuccessResponse` JSON with `Content-Type: application/json`
12185 * - `result.accessibilityTree` is `null` when `root` matched no element
12186 *
12187 * **Error:**
12188 * - `BrowserRunErrorResponse` JSON with appropriate HTTP status code (400, 422, 429, 500, 503)
12189 * - HTTP 422 for a malformed `root` selector
12190 * - HTTP 500 with code `2017` or `2018` when the tree could not be built
12191 *
12192 * **Headers:**
12193 * - `X-Browser-Ms-Used`: Browser time consumed in milliseconds (set when status < 500)
12194 */
12195 quickAction(action: 'accessibilityTree', options: BrowserRunAccessibilityTreeOptions): Promise<Response>;
12196 /** Acquire a new browser session and return its metadata. */
12197 acquire(options?: BrowserRunAcquireOptions): Promise<BrowserRunAcquireResult>;
12198 /** Acquire a browser session and return a session-pinned WebSocket capability. */
12199 launch(options?: BrowserRunAcquireOptions): Promise<BrowserRunConnection>;
12200 /** Return a session-pinned WebSocket capability for an existing session. */
12201 connectSession(sessionId: string, options?: BrowserRunConnectOptions): Promise<BrowserRunConnection>;
12202 /** Mint an authenticated live-view link for a browser session. */
12203 getLiveView(sessionId: string, options?: BrowserRunLiveViewOptions): Promise<BrowserRunLiveView>;
12204 /** List the caller's active browser sessions. */
12205 listSessions(options?: BrowserRunListSessionsOptions): Promise<BrowserRunSession[]>;
12206 /** List recent active and closed browser sessions. */
12207 history(options?: BrowserRunHistoryOptions): Promise<BrowserRunSession[]>;
12208 /** Return the caller's browser-session and browser-time limits. */
12209 limits(): Promise<BrowserRunLimits>;
12210 /** Return details for one browser session, or `null` when it does not exist. */
12211 getSession(sessionId: string): Promise<BrowserRunSession | null>;
12212 /** Close a browser session. */
12213 closeSession(sessionId: string): Promise<BrowserRunCloseSessionResult>;
12214 /** DevTools JSON methods exposed through one nested binding target. */
12215 get devtools(): BrowserRunDevtools;
12216}
12217/**
12218 * In addition to the properties you can set in the RequestInit dict
12219 * that you pass as an argument to the Request constructor, you can
12220 * set certain properties of a `cf` object to control how Cloudflare
12221 * features are applied to that new Request.
12222 *
12223 * Note: Currently, these properties cannot be tested in the
12224 * playground.
12225 */
12226interface RequestInitCfProperties extends Record<string, unknown> {
12227 cacheEverything?: boolean;
12228 /**
12229 * A request's cache key is what determines if two requests are
12230 * "the same" for caching purposes. If a request has the same cache key
12231 * as some previous request, then we can serve the same cached response for
12232 * both. (e.g. 'some-key')
12233 *
12234 * Only available for Enterprise customers.
12235 */
12236 cacheKey?: string;
12237 /**
12238 * This allows you to append additional Cache-Tag response headers
12239 * to the origin response without modifications to the origin server.
12240 * This will allow for greater control over the Purge by Cache Tag feature
12241 * utilizing changes only in the Workers process.
12242 *
12243 * Only available for Enterprise customers.
12244 */
12245 cacheTags?: string[];
12246 /**
12247 * Force response to be cached for a given number of seconds. (e.g. 300)
12248 */
12249 cacheTtl?: number;
12250 /**
12251 * Force response to be cached for a given number of seconds based on the Origin status code.
12252 * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 })
12253 */
12254 cacheTtlByStatus?: Record<string, number>;
12255 /**
12256 * Controls whether Cloudflare uses range requests when fetching the response
12257 * from the origin.
12258 *
12259 * - `"on"`: enable origin range requests for this request.
12260 * - `"off"`: disable origin range requests for this request.
12261 */
12262 originRangeRequests?: "on" | "off";
12263 /** Controls how responses with a `Vary` header are cached for this request. */
12264 vary?: RequestInitCfPropertiesVary;
12265 /**
12266 * Explicit Cache-Control header value to set on the response stored in cache.
12267 * This gives full control over cache directives (e.g. 'public, max-age=3600, s-maxage=86400').
12268 *
12269 * Cannot be used together with `cacheTtl` or the `cache` request option (`no-store`/`no-cache`),
12270 * as these are mutually exclusive cache control mechanisms. Setting both will throw a TypeError.
12271 *
12272 * Can be used together with `cacheTtlByStatus`.
12273 */
12274 cacheControl?: string;
12275 /**
12276 * Whether the response should be eligible for Cache Reserve storage.
12277 */
12278 cacheReserveEligible?: boolean;
12279 /**
12280 * Whether to respect strong ETags (as opposed to weak ETags) from the origin.
12281 */
12282 respectStrongEtag?: boolean;
12283 /**
12284 * Whether to strip ETag headers from the origin response before caching.
12285 */
12286 stripEtags?: boolean;
12287 /**
12288 * Whether to strip Last-Modified headers from the origin response before caching.
12289 */
12290 stripLastModified?: boolean;
12291 /**
12292 * Whether to enable Cache Deception Armor, which protects against web cache
12293 * deception attacks by verifying the Content-Type matches the URL extension.
12294 */
12295 cacheDeceptionArmor?: boolean;
12296 /**
12297 * Minimum file size in bytes for a response to be eligible for Cache Reserve storage.
12298 */
12299 cacheReserveMinimumFileSize?: number;
12300 scrapeShield?: boolean;
12301 apps?: boolean;
12302 /**
12303 * Controls whether an outbound gRPC-web subrequest from this Worker is
12304 * converted to gRPC at the Cloudflare edge.
12305 *
12306 * - `"passthrough"`: forward the subrequest unchanged as gRPC-web (default).
12307 * - `"convert"`: convert the gRPC-web subrequest to gRPC at the edge.
12308 *
12309 * Provides per-request control over the same edge conversion behavior
12310 * gated by the `auto_grpc_convert` compatibility flag.
12311 */
12312 grpcWeb?: "passthrough" | "convert";
12313 image?: RequestInitCfPropertiesImage;
12314 minify?: RequestInitCfPropertiesImageMinify;
12315 mirage?: boolean;
12316 polish?: "lossy" | "lossless" | "off";
12317 r2?: RequestInitCfPropertiesR2;
12318 /**
12319 * Redirects the request to an alternate origin server. You can use this,
12320 * for example, to implement load balancing across several origins.
12321 * (e.g.us-east.example.com)
12322 *
12323 * Note - For security reasons, the hostname set in resolveOverride must
12324 * be proxied on the same Cloudflare zone of the incoming request.
12325 * Otherwise, the setting is ignored. CNAME hosts are allowed, so to
12326 * resolve to a host under a different domain or a DNS only domain first
12327 * declare a CNAME record within your own zone’s DNS mapping to the
12328 * external hostname, set proxy on Cloudflare, then set resolveOverride
12329 * to point to that CNAME record.
12330 */
12331 resolveOverride?: string;
12332}
12333/**
12334 * Controls how Workers Standard Vary handles a request header listed by an
12335 * origin `Vary` response header:
12336 *
12337 * - `"normalize"`: normalize the request header value before it is used in the
12338 * cache variance key.
12339 * - `"passthrough"`: use the raw request header value in the cache variance
12340 * key.
12341 * - `"bypass"`: bypass cache when the header appears in the origin `Vary`
12342 * response header.
12343 */
12344type RequestInitCfPropertiesVaryAction = "normalize" | "passthrough" | "bypass";
12345/** Configuration for Workers Standard Vary support. */
12346interface RequestInitCfPropertiesVary {
12347 /** The fallback action for varied request headers not listed in `headers`. */
12348 default: RequestInitCfPropertiesVaryHeader;
12349 /**
12350 * Lowercase request header names and their Vary configuration.
12351 *
12352 * The `accept` header can include `media_types`, the `accept-language`
12353 * header can include `languages`, and other headers support only `action`.
12354 */
12355 headers?: RequestInitCfPropertiesVaryHeaders;
12356}
12357/** Common Vary behavior for a single request header. */
12358interface RequestInitCfPropertiesVaryHeader {
12359 /** How this request header contributes to cache variance. */
12360 action: RequestInitCfPropertiesVaryAction;
12361}
12362/** Vary behavior for the `accept` request header. */
12363interface RequestInitCfPropertiesVaryAcceptHeader extends RequestInitCfPropertiesVaryHeader {
12364 /**
12365 * Media types to keep when normalizing the `Accept` request header.
12366 *
12367 * Named `media_types` to match the serialized `cf.vary` configuration.
12368 */
12369 media_types?: string[];
12370}
12371/** Vary behavior for the `accept-language` request header. */
12372interface RequestInitCfPropertiesVaryAcceptLanguageHeader extends RequestInitCfPropertiesVaryHeader {
12373 /**
12374 * Language tags to keep when normalizing the `Accept-Language` request
12375 * header.
12376 */
12377 languages?: string[];
12378}
12379/**
12380 * Lowercase request header names and their Vary behavior.
12381 *
12382 * The index signature allows arbitrary custom request headers beyond the
12383 * well-known `accept` and `accept-language` specializations.
12384 */
12385interface RequestInitCfPropertiesVaryHeaders {
12386 accept?: RequestInitCfPropertiesVaryAcceptHeader;
12387 "accept-language"?: RequestInitCfPropertiesVaryAcceptLanguageHeader;
12388 [header: string]: RequestInitCfPropertiesVaryHeader | RequestInitCfPropertiesVaryAcceptHeader | RequestInitCfPropertiesVaryAcceptLanguageHeader | undefined;
12389}
12390interface BasicImageTransformations {
12391 /**
12392 * Maximum width in image pixels. The value must be an integer.
12393 */
12394 width?: number;
12395 /**
12396 * Maximum height in image pixels. The value must be an integer.
12397 */
12398 height?: number;
12399 /**
12400 * When cropping with fit: "cover", this defines the side or point that should
12401 * be left uncropped. The value is either a string
12402 * "left", "right", "top", "bottom", "auto", or "center" (the default),
12403 * or an object {x, y} containing focal point coordinates in the original
12404 * image expressed as fractions ranging from 0.0 (top or left) to 1.0
12405 * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will
12406 * crop bottom or left and right sides as necessary, but won’t crop anything
12407 * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to
12408 * preserve as much as possible around a point at 20% of the height of the
12409 * source image.
12410 */
12411 gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | BasicImageTransformationsGravityCoordinates;
12412 /**
12413 * Specifies how closely the image is cropped toward detected faces when combined
12414 * with the gravity=face option. Accepts a valid range between 0.0 (includes as much
12415 * of the background as possible) and 1.0 (crops the image as closely to the face as
12416 * possible). The default is 0.
12417 */
12418 zoom?: number;
12419 /**
12420 * Resizing mode as a string. It affects interpretation of width and height
12421 * options:
12422 * - scale-down: Similar to contain, but the image is never enlarged. If
12423 * the image is larger than given width or height, it will be resized.
12424 * Otherwise its original size will be kept.
12425 * - scale-up: Similar to contain, but the image is never shrunk. If the
12426 * image is smaller than the given width or height, it will be resized.
12427 * Otherwise its original size will be kept.
12428 * - contain: Resizes to maximum size that fits within the given width and
12429 * height. If only a single dimension is given (e.g. only width), the
12430 * image will be shrunk or enlarged to exactly match that dimension.
12431 * Aspect ratio is always preserved.
12432 * - cover: Resizes (shrinks or enlarges) to fill the entire area of width
12433 * and height. If the image has an aspect ratio different from the ratio
12434 * of width and height, it will be cropped to fit.
12435 * - crop: The image will be shrunk and cropped to fit within the area
12436 * specified by width and height. The image will not be enlarged. For images
12437 * smaller than the given dimensions it's the same as scale-down. For
12438 * images larger than the given dimensions, it's the same as cover.
12439 * See also trim.
12440 * - pad: Resizes to the maximum size that fits within the given width and
12441 * height, and then fills the remaining area with a background color
12442 * (white by default). Use of this mode is not recommended, as the same
12443 * effect can be more efficiently achieved with the contain mode and the
12444 * CSS object-fit: contain property.
12445 * - squeeze: Stretches and deforms to the width and height given, even if it
12446 * breaks aspect ratio
12447 */
12448 fit?: "scale-down" | "scale-up" | "contain" | "cover" | "crop" | "pad" | "squeeze";
12449 /**
12450 * Allows you to trim your image. Takes dpr into account and is performed before
12451 * resizing or rotation.
12452 *
12453 * It can be used as:
12454 * - left, top, right, bottom - it will specify the number of pixels to cut
12455 * off each side
12456 * - width, height - the width/height you'd like to end up with - can be used
12457 * in combination with the properties above
12458 * - border - this will automatically trim the surroundings of an image based on
12459 * it's color. It consists of three properties:
12460 * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit)
12461 * - tolerance: difference from color to treat as color
12462 * - keep: the number of pixels of border to keep
12463 */
12464 trim?: "border" | {
12465 top?: number;
12466 bottom?: number;
12467 left?: number;
12468 right?: number;
12469 width?: number;
12470 height?: number;
12471 border?: boolean | {
12472 color?: string;
12473 tolerance?: number;
12474 keep?: number;
12475 };
12476 };
12477 /**
12478 * Background color to add underneath the image. Applies only to images with
12479 * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…),
12480 * hsl(…), etc.)
12481 */
12482 background?: string;
12483 /**
12484 * Flips the images horizontally, vertically, or both. Flipping is applied before
12485 * rotation, so if you apply flip=h,rotate=90 then the image will be flipped
12486 * horizontally, then rotated by 90 degrees.
12487 */
12488 flip?: 'h' | 'v' | 'hv';
12489 /**
12490 * Number of degrees (90, 180, 270) to rotate the image by. width and height
12491 * options refer to axes after rotation.
12492 */
12493 rotate?: 0 | 90 | 180 | 270 | 360;
12494 /**
12495 * Strength of sharpening filter to apply to the image. Floating-point
12496 * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a
12497 * recommended value for downscaled images.
12498 */
12499 sharpen?: number;
12500 /**
12501 * Radius of a blur filter (approximate gaussian). Maximum supported radius
12502 * is 250.
12503 */
12504 blur?: number;
12505 /**
12506 * Increase contrast by a factor. A value of 1.0 equals no change, a value of
12507 * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is
12508 * ignored.
12509 */
12510 contrast?: number;
12511 /**
12512 * Increase brightness by a factor. A value of 1.0 equals no change, a value
12513 * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright.
12514 * 0 is ignored.
12515 */
12516 brightness?: number;
12517 /**
12518 * Increase exposure by a factor. A value of 1.0 equals no change, a value of
12519 * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored.
12520 */
12521 gamma?: number;
12522 /**
12523 * Increase contrast by a factor. A value of 1.0 equals no change, a value of
12524 * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is
12525 * ignored.
12526 */
12527 saturation?: number;
12528 /**
12529 * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it
12530 * easier to specify higher-DPI sizes in <img srcset>.
12531 */
12532 dpr?: number;
12533 /**
12534 * Adds a border around the image. The border is added after resizing. Border
12535 * width takes dpr into account, and can be specified either using a single
12536 * width property, or individually for each side.
12537 */
12538 border?: {
12539 color: string;
12540 width: number;
12541 } | {
12542 color: string;
12543 top: number;
12544 right: number;
12545 bottom: number;
12546 left: number;
12547 };
12548 /**
12549 * Image segmentation using artificial intelligence models. Sets pixels not
12550 * within selected segment area to transparent e.g "foreground" sets every
12551 * background pixel as transparent.
12552 */
12553 segment?: "foreground";
12554 /**
12555 * Controls the algorithm used when an image needs to be enlarged. This
12556 * parameter works with any fit mode that upscales, such as `contain`,
12557 * `cover`, and `scale-up`. It has no effect when `fit=scale-down` or when
12558 * the target dimensions are smaller than the source.
12559 * - interpolate: Uses bicubic interpolation, which may reduce image quality.
12560 * This is the default behavior when `upscale` is not specified.
12561 * - generate: Uses AI upscaling to produce sharper, more detailed results
12562 * when enlarging images.
12563 */
12564 upscale?: "interpolate" | "generate";
12565}
12566interface BasicImageTransformationsGravityCoordinates {
12567 x?: number;
12568 y?: number;
12569 mode?: 'remainder' | 'box-center';
12570}
12571interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations {
12572 /**
12573 * Absolute URL of the image file to use for the drawing. It can be any of
12574 * the supported file formats. For drawing of watermarks or non-rectangular
12575 * overlays we recommend using PNG or WebP images.
12576 */
12577 url: string;
12578 /**
12579 * Floating-point number between 0 (transparent) and 1 (opaque).
12580 * For example, opacity: 0.5 makes overlay semitransparent.
12581 */
12582 opacity?: number;
12583 /**
12584 * - If set to true, the overlay image will be tiled to cover the entire
12585 * area. This is useful for stock-photo-like watermarks.
12586 * - If set to "x", the overlay image will be tiled horizontally only
12587 * (form a line).
12588 * - If set to "y", the overlay image will be tiled vertically only
12589 * (form a line).
12590 */
12591 repeat?: true | "x" | "y";
12592 /**
12593 * How to combine the foreground and backdrop pixels to create the result
12594 */
12595 composite?:
12596 /** Foreground drawn on top of backdrop (default) */
12597 'over'
12598 /** Foreground shown only where backdrop is opaque */
12599 | 'in'
12600 /** Foreground drawn on top, but clipped to the backdrop's shape */
12601 | 'atop'
12602 /** Foreground shown only where backdrop is transparent */
12603 | 'out'
12604 /** Foreground and backdrop visible only where the other is not */
12605 | 'xor'
12606 /** Foreground and backdrop channels added (brightening) */
12607 | 'lighter';
12608 /**
12609 * Position of the overlay image relative to a given edge. Each property is
12610 * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10
12611 * positions left side of the overlay 10 pixels from the left edge of the
12612 * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom
12613 * of the background image.
12614 *
12615 * Setting both left & right, or both top & bottom is an error.
12616 *
12617 * If no position is specified, the image will be centered.
12618 */
12619 top?: number;
12620 left?: number;
12621 bottom?: number;
12622 right?: number;
12623}
12624interface RequestInitCfPropertiesImage extends BasicImageTransformations {
12625 /**
12626 * Quality setting from 1-100 (useful values are in 60-90 range). Lower values
12627 * make images look worse, but load faster. The default is 85. It applies only
12628 * to JPEG and WebP images. It doesn’t have any effect on PNG.
12629 */
12630 quality?: number | "low" | "medium-low" | "medium-high" | "high";
12631 /**
12632 * Output format to generate. It can be:
12633 * - avif: generate images in AVIF format.
12634 * - webp: generate images in Google WebP format. Set quality to 100 to get
12635 * the WebP-lossless format.
12636 * - json: instead of generating an image, outputs information about the
12637 * image, in JSON format. The JSON object will contain image size
12638 * (before and after resizing), source image’s MIME type, file size, etc.
12639 * - jpeg: generate images in JPEG format.
12640 * - png: generate images in PNG format.
12641 */
12642 format?: "avif" | "webp" | "json" | "jpeg" | "png" | "baseline-jpeg" | "png-force" | "svg";
12643 /**
12644 * Whether to preserve animation frames from input files. Default is true.
12645 * Setting it to false reduces animations to still images. This setting is
12646 * recommended when enlarging images or processing arbitrary user content,
12647 * because large GIF animations can weigh tens or even hundreds of megabytes.
12648 * It is also useful to set anim:false when using format:"json" to get the
12649 * response quicker without the number of frames.
12650 */
12651 anim?: boolean;
12652 /**
12653 * What EXIF data should be preserved in the output image. Note that EXIF
12654 * rotation and embedded color profiles are always applied ("baked in" into
12655 * the image), and aren't affected by this option. Note that if the Polish
12656 * feature is enabled, all metadata may have been removed already and this
12657 * option may have no effect.
12658 * - keep: Preserve most of EXIF metadata, including GPS location if there's
12659 * any.
12660 * - copyright: Only keep the copyright tag, and discard everything else.
12661 * This is the default behavior for JPEG files.
12662 * - none: Discard all invisible EXIF metadata. Currently WebP and PNG
12663 * output formats always discard metadata.
12664 */
12665 metadata?: "keep" | "copyright" | "none";
12666 /**
12667 * Overlays are drawn in the order they appear in the array (last array
12668 * entry is the topmost layer).
12669 */
12670 draw?: RequestInitCfPropertiesImageDraw[];
12671 /**
12672 * Fetching image from authenticated origin. Setting this property will
12673 * pass authentication headers (Authorization, Cookie, etc.) through to
12674 * the origin.
12675 */
12676 "origin-auth"?: "share-publicly";
12677 /**
12678 * Slightly reduces latency on a cache miss by selecting a
12679 * quickest-to-compress file format, at a cost of increased file size and
12680 * lower image quality. It will usually override the format option and choose
12681 * JPEG over WebP or AVIF. We do not recommend using this option, except in
12682 * unusual circumstances like resizing uncacheable dynamically-generated
12683 * images.
12684 */
12685 compression?: "fast";
12686}
12687interface RequestInitCfPropertiesImageMinify {
12688 javascript?: boolean;
12689 css?: boolean;
12690 html?: boolean;
12691}
12692interface RequestInitCfPropertiesR2 {
12693 /**
12694 * Colo id of bucket that an object is stored in
12695 */
12696 bucketColoId?: number;
12697}
12698/**
12699 * Request metadata provided by Cloudflare's edge.
12700 */
12701type IncomingRequestCfProperties<HostMetadata = unknown> = IncomingRequestCfPropertiesBase & IncomingRequestCfPropertiesBotManagementEnterprise & IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> & IncomingRequestCfPropertiesGeographicInformation & IncomingRequestCfPropertiesCloudflareAccessOrApiShield;
12702interface IncomingRequestCfPropertiesBase extends Record<string, unknown> {
12703 /**
12704 * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request.
12705 *
12706 * @example 395747
12707 */
12708 asn?: number;
12709 /**
12710 * The organization which owns the ASN of the incoming request.
12711 *
12712 * @example "Google Cloud"
12713 */
12714 asOrganization?: string;
12715 /**
12716 * The original value of the `Accept-Encoding` header if Cloudflare modified it.
12717 *
12718 * @example "gzip, deflate, br"
12719 */
12720 clientAcceptEncoding?: string;
12721 /**
12722 * The number of milliseconds it took for the request to reach your worker.
12723 *
12724 * @example 22
12725 */
12726 clientTcpRtt?: number;
12727 /**
12728 * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code)
12729 * airport code of the data center that the request hit.
12730 *
12731 * @example "DFW"
12732 */
12733 colo: string;
12734 /**
12735 * Represents the upstream's response to a
12736 * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html)
12737 * from cloudflare.
12738 *
12739 * For workers with no upstream, this will always be `1`.
12740 *
12741 * @example 3
12742 */
12743 edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus;
12744 /**
12745 * The HTTP Protocol the request used.
12746 *
12747 * @example "HTTP/2"
12748 */
12749 httpProtocol: string;
12750 /**
12751 * The browser-requested prioritization information in the request object.
12752 *
12753 * If no information was set, defaults to the empty string `""`
12754 *
12755 * @example "weight=192;exclusive=0;group=3;group-weight=127"
12756 * @default ""
12757 */
12758 requestPriority: string;
12759 /**
12760 * The TLS version of the connection to Cloudflare.
12761 * In requests served over plaintext (without TLS), this property is the empty string `""`.
12762 *
12763 * @example "TLSv1.3"
12764 */
12765 tlsVersion: string;
12766 /**
12767 * The cipher for the connection to Cloudflare.
12768 * In requests served over plaintext (without TLS), this property is the empty string `""`.
12769 *
12770 * @example "AEAD-AES128-GCM-SHA256"
12771 */
12772 tlsCipher: string;
12773 /**
12774 * 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.
12775 *
12776 * If the incoming request was served over plaintext (without TLS) this field is undefined.
12777 */
12778 tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata;
12779}
12780interface IncomingRequestCfPropertiesBotManagementBase {
12781 /**
12782 * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot,
12783 * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human).
12784 *
12785 * @example 54
12786 */
12787 score: number;
12788 /**
12789 * A boolean value that is true if the request comes from a good bot, like Google or Bing.
12790 * 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).
12791 */
12792 verifiedBot: boolean;
12793 /**
12794 * A boolean value that is true if the request originates from a
12795 * Cloudflare-verified proxy service.
12796 */
12797 corporateProxy: boolean;
12798 /**
12799 * 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.
12800 */
12801 staticResource: boolean;
12802 /**
12803 * 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).
12804 */
12805 detectionIds: number[];
12806}
12807interface IncomingRequestCfPropertiesBotManagement {
12808 /**
12809 * Results of Cloudflare's Bot Management analysis
12810 */
12811 botManagement: IncomingRequestCfPropertiesBotManagementBase;
12812 /**
12813 * Duplicate of `botManagement.score`.
12814 *
12815 * @deprecated
12816 */
12817 clientTrustScore: number;
12818}
12819interface IncomingRequestCfPropertiesBotManagementEnterprise extends IncomingRequestCfPropertiesBotManagement {
12820 /**
12821 * Results of Cloudflare's Bot Management analysis
12822 */
12823 botManagement: IncomingRequestCfPropertiesBotManagementBase & {
12824 /**
12825 * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients
12826 * across different destination IPs, Ports, and X509 certificates.
12827 */
12828 ja3Hash: string;
12829 };
12830}
12831interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise<HostMetadata> {
12832 /**
12833 * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/).
12834 *
12835 * This field is only present if you have Cloudflare for SaaS enabled on your account
12836 * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)).
12837 */
12838 hostMetadata?: HostMetadata;
12839}
12840interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield {
12841 /**
12842 * Information about the client certificate presented to Cloudflare.
12843 *
12844 * This is populated when the incoming request is served over TLS using
12845 * either Cloudflare Access or API Shield (mTLS)
12846 * and the presented SSL certificate has a valid
12847 * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number)
12848 * (i.e., not `null` or `""`).
12849 *
12850 * Otherwise, a set of placeholder values are used.
12851 *
12852 * The property `certPresented` will be set to `"1"` when
12853 * the object is populated (i.e. the above conditions were met).
12854 */
12855 tlsClientAuth: IncomingRequestCfPropertiesTLSClientAuth | IncomingRequestCfPropertiesTLSClientAuthPlaceholder;
12856}
12857/**
12858 * Metadata about the request's TLS handshake
12859 */
12860interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata {
12861 /**
12862 * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal
12863 *
12864 * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d"
12865 */
12866 clientHandshake: string;
12867 /**
12868 * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal
12869 *
12870 * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d"
12871 */
12872 serverHandshake: string;
12873 /**
12874 * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal
12875 *
12876 * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b"
12877 */
12878 clientFinished: string;
12879 /**
12880 * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal
12881 *
12882 * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b"
12883 */
12884 serverFinished: string;
12885}
12886/**
12887 * Geographic data about the request's origin.
12888 */
12889interface IncomingRequestCfPropertiesGeographicInformation {
12890 /**
12891 * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from.
12892 *
12893 * 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.
12894 *
12895 * If Cloudflare is unable to determine where the request originated this property is omitted.
12896 *
12897 * The country code `"T1"` is used for requests originating on TOR.
12898 *
12899 * @example "GB"
12900 */
12901 country?: Iso3166Alpha2Code | "T1";
12902 /**
12903 * If present, this property indicates that the request originated in the EU
12904 *
12905 * @example "1"
12906 */
12907 isEUCountry?: "1";
12908 /**
12909 * A two-letter code indicating the continent the request originated from.
12910 *
12911 * @example "AN"
12912 */
12913 continent?: ContinentCode;
12914 /**
12915 * The city the request originated from
12916 *
12917 * @example "Austin"
12918 */
12919 city?: string;
12920 /**
12921 * Postal code of the incoming request
12922 *
12923 * @example "78701"
12924 */
12925 postalCode?: string;
12926 /**
12927 * Latitude of the incoming request
12928 *
12929 * @example "30.27130"
12930 */
12931 latitude?: string;
12932 /**
12933 * Longitude of the incoming request
12934 *
12935 * @example "-97.74260"
12936 */
12937 longitude?: string;
12938 /**
12939 * Timezone of the incoming request
12940 *
12941 * @example "America/Chicago"
12942 */
12943 timezone?: string;
12944 /**
12945 * If known, the ISO 3166-2 name for the first level region associated with
12946 * the IP address of the incoming request
12947 *
12948 * @example "Texas"
12949 */
12950 region?: string;
12951 /**
12952 * If known, the ISO 3166-2 code for the first-level region associated with
12953 * the IP address of the incoming request
12954 *
12955 * @example "TX"
12956 */
12957 regionCode?: string;
12958 /**
12959 * Metro code (DMA) of the incoming request
12960 *
12961 * @example "635"
12962 */
12963 metroCode?: string;
12964}
12965/** Data about the incoming request's TLS certificate */
12966interface IncomingRequestCfPropertiesTLSClientAuth {
12967 /** Always `"1"`, indicating that the certificate was presented */
12968 certPresented: "1";
12969 /**
12970 * Result of certificate verification.
12971 *
12972 * @example "FAILED:self signed certificate"
12973 */
12974 certVerified: Exclude<CertVerificationStatus, "NONE">;
12975 /** The presented certificate's revokation status.
12976 *
12977 * - A value of `"1"` indicates the certificate has been revoked
12978 * - A value of `"0"` indicates the certificate has not been revoked
12979 */
12980 certRevoked: "1" | "0";
12981 /**
12982 * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html)
12983 *
12984 * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare"
12985 */
12986 certIssuerDN: string;
12987 /**
12988 * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html)
12989 *
12990 * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare"
12991 */
12992 certSubjectDN: string;
12993 /**
12994 * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted)
12995 *
12996 * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare"
12997 */
12998 certIssuerDNRFC2253: string;
12999 /**
13000 * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted)
13001 *
13002 * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare"
13003 */
13004 certSubjectDNRFC2253: string;
13005 /** The certificate issuer's distinguished name (legacy policies) */
13006 certIssuerDNLegacy: string;
13007 /** The certificate subject's distinguished name (legacy policies) */
13008 certSubjectDNLegacy: string;
13009 /**
13010 * The certificate's serial number
13011 *
13012 * @example "00936EACBE07F201DF"
13013 */
13014 certSerial: string;
13015 /**
13016 * The certificate issuer's serial number
13017 *
13018 * @example "2489002934BDFEA34"
13019 */
13020 certIssuerSerial: string;
13021 /**
13022 * The certificate's Subject Key Identifier
13023 *
13024 * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4"
13025 */
13026 certSKI: string;
13027 /**
13028 * The certificate issuer's Subject Key Identifier
13029 *
13030 * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4"
13031 */
13032 certIssuerSKI: string;
13033 /**
13034 * The certificate's SHA-1 fingerprint
13035 *
13036 * @example "6b9109f323999e52259cda7373ff0b4d26bd232e"
13037 */
13038 certFingerprintSHA1: string;
13039 /**
13040 * The certificate's SHA-256 fingerprint
13041 *
13042 * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea"
13043 */
13044 certFingerprintSHA256: string;
13045 /**
13046 * The effective starting date of the certificate
13047 *
13048 * @example "Dec 22 19:39:00 2018 GMT"
13049 */
13050 certNotBefore: string;
13051 /**
13052 * The effective expiration date of the certificate
13053 *
13054 * @example "Dec 22 19:39:00 2018 GMT"
13055 */
13056 certNotAfter: string;
13057 /**
13058 * The client leaf certificate in [RFC 9440](https://www.rfc-editor.org/rfc/rfc9440)
13059 * format (`:base64-DER:`). Empty if no client certificate was presented or if
13060 * the leaf certificate exceeded 10 KB (see {@link certRFC9440TooLarge}).
13061 *
13062 * Suitable for forwarding to an origin via the `Client-Cert` HTTP header.
13063 */
13064 certRFC9440: string;
13065 /**
13066 * `true` if the leaf certificate exceeded 10 KB and was omitted from
13067 * {@link certRFC9440}.
13068 */
13069 certRFC9440TooLarge: boolean;
13070 /**
13071 * The intermediate certificate chain in [RFC 9440](https://www.rfc-editor.org/rfc/rfc9440)
13072 * format as a comma-separated list. Empty if no intermediates were sent or
13073 * if the chain exceeded 16 KB (see {@link certChainRFC9440TooLarge}).
13074 *
13075 * Suitable for forwarding to an origin via the `Client-Cert-Chain` HTTP header.
13076 */
13077 certChainRFC9440: string;
13078 /**
13079 * `true` if the intermediate chain exceeded 16 KB and was omitted from
13080 * {@link certChainRFC9440}.
13081 */
13082 certChainRFC9440TooLarge: boolean;
13083}
13084/** Placeholder values for TLS Client Authorization */
13085interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder {
13086 certPresented: "0";
13087 certVerified: "NONE";
13088 certRevoked: "0";
13089 certIssuerDN: "";
13090 certSubjectDN: "";
13091 certIssuerDNRFC2253: "";
13092 certSubjectDNRFC2253: "";
13093 certIssuerDNLegacy: "";
13094 certSubjectDNLegacy: "";
13095 certSerial: "";
13096 certIssuerSerial: "";
13097 certSKI: "";
13098 certIssuerSKI: "";
13099 certFingerprintSHA1: "";
13100 certFingerprintSHA256: "";
13101 certNotBefore: "";
13102 certNotAfter: "";
13103 certRFC9440: "";
13104 certRFC9440TooLarge: false;
13105 certChainRFC9440: "";
13106 certChainRFC9440TooLarge: false;
13107}
13108/** Possible outcomes of TLS verification */
13109declare type CertVerificationStatus =
13110/** Authentication succeeded */
13111"SUCCESS"
13112/** No certificate was presented */
13113 | "NONE"
13114/** Failed because the certificate was self-signed */
13115 | "FAILED:self signed certificate"
13116/** Failed because the certificate failed a trust chain check */
13117 | "FAILED:unable to verify the first certificate"
13118/** Failed because the certificate not yet valid */
13119 | "FAILED:certificate is not yet valid"
13120/** Failed because the certificate is expired */
13121 | "FAILED:certificate has expired"
13122/** Failed for another unspecified reason */
13123 | "FAILED";
13124/**
13125 * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare.
13126 */
13127declare 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 */
13128/** ISO 3166-1 Alpha-2 codes */
13129declare 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";
13130/** The 2-letter continent codes Cloudflare uses */
13131declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA";
13132type CfProperties<HostMetadata = unknown> = IncomingRequestCfProperties<HostMetadata> | RequestInitCfProperties;
13133interface D1Meta {
13134 duration: number;
13135 size_after: number;
13136 rows_read: number;
13137 rows_written: number;
13138 last_row_id: number;
13139 changed_db: boolean;
13140 changes: number;
13141 /**
13142 * The region of the database instance that executed the query.
13143 */
13144 served_by_region?: string;
13145 /**
13146 * The three letters airport code of the colo that executed the query.
13147 */
13148 served_by_colo?: string;
13149 /**
13150 * True if-and-only-if the database instance that executed the query was the primary.
13151 */
13152 served_by_primary?: boolean;
13153 timings?: {
13154 /**
13155 * The duration of the SQL query execution by the database instance. It doesn't include any network time.
13156 */
13157 sql_duration_ms: number;
13158 };
13159 /**
13160 * Number of total attempts to execute the query, due to automatic retries.
13161 * Note: All other fields in the response like `timings` only apply to the last attempt.
13162 */
13163 total_attempts?: number;
13164}
13165interface D1Response {
13166 success: true;
13167 meta: D1Meta & Record<string, unknown>;
13168 error?: never;
13169}
13170type D1Result<T = unknown> = D1Response & {
13171 results: T[];
13172};
13173interface D1ExecResult {
13174 count: number;
13175 duration: number;
13176}
13177type D1SessionConstraint =
13178// Indicates that the first query should go to the primary, and the rest queries
13179// using the same D1DatabaseSession will go to any replica that is consistent with
13180// the bookmark maintained by the session (returned by the first query).
13181'first-primary'
13182// Indicates that the first query can go anywhere (primary or replica), and the rest queries
13183// using the same D1DatabaseSession will go to any replica that is consistent with
13184// the bookmark maintained by the session (returned by the first query).
13185 | 'first-unconstrained';
13186type D1SessionBookmark = string;
13187declare abstract class D1Database {
13188 prepare(query: string): D1PreparedStatement;
13189 batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;
13190 exec(query: string): Promise<D1ExecResult>;
13191 /**
13192 * Creates a new D1 Session anchored at the given constraint or the bookmark.
13193 * All queries executed using the created session will have sequential consistency,
13194 * meaning that all writes done through the session will be visible in subsequent reads.
13195 *
13196 * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session.
13197 */
13198 withSession(constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint): D1DatabaseSession;
13199 /**
13200 * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases.
13201 */
13202 dump(): Promise<ArrayBuffer>;
13203}
13204declare abstract class D1DatabaseSession {
13205 prepare(query: string): D1PreparedStatement;
13206 batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;
13207 /**
13208 * @returns The latest session bookmark across all executed queries on the session.
13209 * If no query has been executed yet, `null` is returned.
13210 */
13211 getBookmark(): D1SessionBookmark | null;
13212}
13213declare abstract class D1PreparedStatement {
13214 bind(...values: unknown[]): D1PreparedStatement;
13215 first<T = unknown>(colName: string): Promise<T | null>;
13216 first<T = Record<string, unknown>>(): Promise<T | null>;
13217 run<T = Record<string, unknown>>(): Promise<D1Result<T>>;
13218 all<T = Record<string, unknown>>(): Promise<D1Result<T>>;
13219 raw<T = unknown[]>(options: {
13220 columnNames: true;
13221 }): Promise<[
13222 string[],
13223 ...T[]
13224 ]>;
13225 raw<T = unknown[]>(options?: {
13226 columnNames?: false;
13227 }): Promise<T[]>;
13228}
13229// `Disposable` was added to TypeScript's standard lib types in version 5.2.
13230// To support older TypeScript versions, define an empty `Disposable` interface.
13231// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2,
13232// but this will ensure type checking on older versions still passes.
13233// TypeScript's interface merging will ensure our empty interface is effectively
13234// ignored when `Disposable` is included in the standard lib.
13235interface Disposable {
13236}
13237declare module 'cloudflare:durable-objects' {
13238 /**
13239 * Marks a Durable Object method as safe to run more than once. The runtime may then retry calls
13240 * to it after a disconnect that might have happened after the method started. It does not
13241 * enable retries or change how many are made.
13242 *
13243 * Each attempt creates its own return value, so if the method returns an `RpcTarget`, its
13244 * `[Symbol.dispose]()` may run once per attempt.
13245 *
13246 * Only public instance methods can be decorated. When composing decorators, apply `@retryable`
13247 * outermost (first in source order) so it marks the method that is finally installed.
13248 * Otherwise `@retryable` has no effect, and constructing the object logs a warning.
13249 * Requires standard (not `experimentalDecorators`) decorators and a bundler that transforms
13250 * them, such as Wrangler.
13251 */
13252 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;
13253}
13254/**
13255 * The returned data after sending an email
13256 */
13257interface EmailSendResult {
13258 /**
13259 * The Email Message ID
13260 */
13261 messageId: string;
13262}
13263/**
13264 * An email message that can be sent from a Worker.
13265 */
13266interface EmailMessage {
13267 /**
13268 * Envelope From attribute of the email message.
13269 */
13270 readonly from: string;
13271 /**
13272 * Envelope To attribute of the email message.
13273 */
13274 readonly to: string;
13275}
13276/**
13277 * An email message that is sent to a consumer Worker and can be rejected/forwarded.
13278 */
13279interface ForwardableEmailMessage extends EmailMessage {
13280 /**
13281 * Stream of the email message content.
13282 */
13283 readonly raw: ReadableStream<Uint8Array>;
13284 /**
13285 * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers).
13286 */
13287 readonly headers: Headers;
13288 /**
13289 * Size of the email message content.
13290 */
13291 readonly rawSize: number;
13292 /**
13293 * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason.
13294 * @param reason The reject reason.
13295 * @returns void
13296 */
13297 setReject(reason: string): void;
13298 /**
13299 * Forward this email message to a verified destination address of the account.
13300 * @param rcptTo Verified destination address.
13301 * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers).
13302 * @returns A promise that resolves when the email message is forwarded.
13303 */
13304 forward(rcptTo: string, headers?: Headers): Promise<EmailSendResult>;
13305 /**
13306 * Reply to the sender of this email message with a new EmailMessage object.
13307 * @param message The reply message.
13308 * @returns A promise that resolves when the email message is replied.
13309 */
13310 reply(message: EmailMessage): Promise<EmailSendResult>;
13311 /**
13312 * Reply to the sender of this email message with a message built from the given
13313 * fields. Threading headers (In-Reply-To/References) are set automatically.
13314 * @param builder The reply message contents.
13315 * @returns A promise that resolves when the email message is replied.
13316 */
13317 reply(builder: EmailReplyMessageBuilder): Promise<EmailSendResult>;
13318}
13319/** A file attachment for an email message */
13320type EmailAttachment = {
13321 disposition: 'inline';
13322 contentId: string;
13323 filename: string;
13324 type: string;
13325 content: string | ArrayBuffer | ArrayBufferView;
13326} | {
13327 disposition: 'attachment';
13328 contentId?: undefined;
13329 filename: string;
13330 type: string;
13331 content: string | ArrayBuffer | ArrayBufferView;
13332};
13333/** An Email Address */
13334interface EmailAddress {
13335 name: string;
13336 email: string;
13337}
13338/**
13339 * Recipient fields for `SendEmail.send()`. At least one of `to`, `cc`, or
13340 * `bcc` must be provided.
13341 */
13342type EmailDestinations = {
13343 to?: string | EmailAddress | (string | EmailAddress)[];
13344 cc?: string | EmailAddress | (string | EmailAddress)[];
13345 bcc?: string | EmailAddress | (string | EmailAddress)[];
13346} & ({
13347 to: string | EmailAddress | (string | EmailAddress)[];
13348} | {
13349 cc: string | EmailAddress | (string | EmailAddress)[];
13350} | {
13351 bcc: string | EmailAddress | (string | EmailAddress)[];
13352});
13353/**
13354 * Fields shared by all composed emails (no recipients). Used directly by
13355 * `ForwardableEmailMessage.reply()`, which always replies to the original
13356 * sender, and extended by `EmailMessageBuilder` for `SendEmail.send()`.
13357 */
13358interface EmailReplyMessageBuilder {
13359 from: string | EmailAddress;
13360 subject: string;
13361 replyTo?: string | EmailAddress;
13362 headers?: Record<string, string>;
13363 text?: string;
13364 html?: string;
13365 attachments?: EmailAttachment[];
13366}
13367/**
13368 * Fields for composing an email without constructing raw MIME, for
13369 * `SendEmail.send()`. Requires at least one of `to`, `cc`, or `bcc`.
13370 */
13371type EmailMessageBuilder = EmailReplyMessageBuilder & EmailDestinations;
13372/**
13373 * A binding that allows a Worker to send email messages.
13374 */
13375interface SendEmail {
13376 send(message: EmailMessage): Promise<EmailSendResult>;
13377 send(builder: EmailMessageBuilder): Promise<EmailSendResult>;
13378}
13379declare abstract class EmailEvent extends ExtendableEvent {
13380 readonly message: ForwardableEmailMessage;
13381}
13382declare type EmailExportedHandler<Env = unknown, Props = unknown> = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext<Props>) => void | Promise<void>;
13383declare module "cloudflare:email" {
13384 let _EmailMessage: {
13385 prototype: EmailMessage;
13386 new (from: string, to: string, raw: ReadableStream | string): EmailMessage;
13387 };
13388 export { _EmailMessage as EmailMessage };
13389}
13390/**
13391 * Evaluation context for targeting rules.
13392 * Keys are attribute names (e.g. "userId", "country"), values are the attribute values.
13393 */
13394type FlagshipEvaluationContext = Record<string, string | number | boolean>;
13395interface FlagshipEvaluationDetails<T> {
13396 flagKey: string;
13397 value: T;
13398 variant?: string | undefined;
13399 reason?: string | undefined;
13400 errorCode?: string | undefined;
13401 errorMessage?: string | undefined;
13402}
13403interface FlagshipEvaluationError extends Error {
13404}
13405/**
13406 * Feature flags binding for evaluating feature flags from a Cloudflare Workers script.
13407 *
13408 * @example
13409 * ```typescript
13410 * // Get a boolean flag value with a default
13411 * const enabled = await env.FLAGS.getBooleanValue('my-feature', false);
13412 *
13413 * // Get a flag value with evaluation context for targeting
13414 * const variant = await env.FLAGS.getStringValue('experiment', 'control', {
13415 * userId: 'user-123',
13416 * country: 'US',
13417 * });
13418 *
13419 * // Get full evaluation details including variant and reason
13420 * const details = await env.FLAGS.getBooleanDetails('my-feature', false);
13421 * console.log(details.variant, details.reason);
13422 * ```
13423 */
13424declare abstract class Flagship {
13425 /**
13426 * Get a flag value without type checking.
13427 * @param flagKey The key of the flag to evaluate.
13428 * @param defaultValue Optional default value returned when evaluation fails.
13429 * @param context Optional evaluation context for targeting rules.
13430 */
13431 get(flagKey: string, defaultValue?: unknown, context?: FlagshipEvaluationContext): Promise<unknown>;
13432 /**
13433 * Get a boolean flag value.
13434 * @param flagKey The key of the flag to evaluate.
13435 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
13436 * @param context Optional evaluation context for targeting rules.
13437 */
13438 getBooleanValue(flagKey: string, defaultValue: boolean, context?: FlagshipEvaluationContext): Promise<boolean>;
13439 /**
13440 * Get a string flag value.
13441 * @param flagKey The key of the flag to evaluate.
13442 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
13443 * @param context Optional evaluation context for targeting rules.
13444 */
13445 getStringValue(flagKey: string, defaultValue: string, context?: FlagshipEvaluationContext): Promise<string>;
13446 /**
13447 * Get a number flag value.
13448 * @param flagKey The key of the flag to evaluate.
13449 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
13450 * @param context Optional evaluation context for targeting rules.
13451 */
13452 getNumberValue(flagKey: string, defaultValue: number, context?: FlagshipEvaluationContext): Promise<number>;
13453 /**
13454 * Get an object flag value.
13455 * @param flagKey The key of the flag to evaluate.
13456 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
13457 * @param context Optional evaluation context for targeting rules.
13458 */
13459 getObjectValue<T extends object>(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise<T>;
13460 /**
13461 * Get a boolean flag value with full evaluation details.
13462 * @param flagKey The key of the flag to evaluate.
13463 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
13464 * @param context Optional evaluation context for targeting rules.
13465 */
13466 getBooleanDetails(flagKey: string, defaultValue: boolean, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<boolean>>;
13467 /**
13468 * Get a string flag value with full evaluation details.
13469 * @param flagKey The key of the flag to evaluate.
13470 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
13471 * @param context Optional evaluation context for targeting rules.
13472 */
13473 getStringDetails(flagKey: string, defaultValue: string, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<string>>;
13474 /**
13475 * Get a number flag value with full evaluation details.
13476 * @param flagKey The key of the flag to evaluate.
13477 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
13478 * @param context Optional evaluation context for targeting rules.
13479 */
13480 getNumberDetails(flagKey: string, defaultValue: number, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<number>>;
13481 /**
13482 * Get an object flag value with full evaluation details.
13483 * @param flagKey The key of the flag to evaluate.
13484 * @param defaultValue Default value returned when evaluation fails or the flag type does not match.
13485 * @param context Optional evaluation context for targeting rules.
13486 */
13487 getObjectDetails<T extends object>(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise<FlagshipEvaluationDetails<T>>;
13488}
13489/**
13490 * Hello World binding to serve as an explanatory example. DO NOT USE
13491 */
13492interface HelloWorldBinding {
13493 /**
13494 * Retrieve the current stored value
13495 */
13496 get(): Promise<{
13497 value: string;
13498 ms?: number;
13499 }>;
13500 /**
13501 * Set a new stored value
13502 */
13503 set(value: string): Promise<void>;
13504}
13505interface Hyperdrive {
13506 /**
13507 * Connect directly to Hyperdrive as if it's your database, returning a TCP socket.
13508 *
13509 * Calling this method returns an identical socket to if you call
13510 * `connect("host:port")` using the `host` and `port` fields from this object.
13511 * Pick whichever approach works better with your preferred DB client library.
13512 *
13513 * Note that this socket is not yet authenticated -- it's expected that your
13514 * code (or preferably, the client library of your choice) will authenticate
13515 * using the information in this class's readonly fields.
13516 */
13517 connect(): Socket;
13518 /**
13519 * A valid DB connection string that can be passed straight into the typical
13520 * client library/driver/ORM. This will typically be the easiest way to use
13521 * Hyperdrive.
13522 */
13523 readonly connectionString: string;
13524 /*
13525 * A randomly generated hostname that is only valid within the context of the
13526 * currently running Worker which, when passed into `connect()` function from
13527 * the "cloudflare:sockets" module, will connect to the Hyperdrive instance
13528 * for your database.
13529 */
13530 readonly host: string;
13531 /*
13532 * A synthetic IPv4 address (in the reserved 240.0.0.0/4 range) that, like the
13533 * host field, is only valid within the context of the currently running
13534 * Worker and, when passed into the `connect()` function from the
13535 * "cloudflare:sockets" module, will connect to the Hyperdrive instance for
13536 * your database. This is provided for database drivers that require the host
13537 * to be an IP literal rather than a hostname.
13538 */
13539 readonly ip: string;
13540 /*
13541 * The port that must be paired the the host field when connecting.
13542 */
13543 readonly port: number;
13544 /*
13545 * The username to use when authenticating to your database via Hyperdrive.
13546 * Unlike the host and password, this will be the same every time
13547 */
13548 readonly user: string;
13549 /*
13550 * The randomly generated password to use when authenticating to your
13551 * database via Hyperdrive. Like the host field, this password is only valid
13552 * within the context of the currently running Worker instance from which
13553 * it's read.
13554 */
13555 readonly password: string;
13556 /*
13557 * The name of the database to connect to.
13558 */
13559 readonly database: string;
13560}
13561/**
13562 * A handle to a dynamically-provisioned Hyperdrive connection, returned by
13563 * `HyperdriveApi.get()`.
13564 */
13565interface HyperdriveDynamic extends Disposable {
13566 /**
13567 * The database name to use when connecting through this Hyperdrive.
13568 */
13569 readonly database: Promise<string>;
13570 /*
13571 * The randomly generated user to use when authenticating to your
13572 * database via Hyperdrive.
13573 */
13574 readonly user: Promise<string>;
13575 /*
13576 * The randomly generated password to use when authenticating to your
13577 * database via Hyperdrive.
13578 */
13579 readonly password: Promise<string>;
13580 /**
13581 * Open a TCP socket to the target database through this Hyperdrive.
13582 *
13583 */
13584 connect(): Promise<Socket>;
13585}
13586/**
13587 * Binding that provisions Hyperdrive connections at request time, rather than
13588 * from static configuration.
13589 */
13590interface HyperdriveDynamicApi {
13591 /**
13592 * Provision a connection for the database described by `args`.
13593 *
13594 */
13595 get(args: HyperdriveDynamicConfig): Promise<HyperdriveDynamic>;
13596 /**
13597 * Get a pre-generated connection string used for connecting to dynamic Hyperdrive.
13598 */
13599 getHyperdriveConnectionString(connectionString: string): Promise<string>;
13600}
13601/**
13602 * Parameters identifying the database that a dynamically-provisioned
13603 * Hyperdrive connection should target.
13604 */
13605interface HyperdriveDynamicConfig {
13606 /**
13607 * Generated connection string to pass into the dynamic worker.
13608 *
13609 */
13610 dynamicHyperdriveConnectionString: string;
13611 /**
13612 * Connection string for the origin database Hyperdrive should connect to.
13613 * Contains credentials, so treat it as a secret.
13614 *
13615 * The scheme selects the database engine. PostgreSQL origins are supported.
13616 */
13617 connectionString: string;
13618 /**
13619 * Region in which to place the connection pool. See the Hyperdrive
13620 * documentation for the set of supported regions.
13621 */
13622 targetRegion: string;
13623 /**
13624 * Whether Hyperdrive should cache query results for this connection.
13625 */
13626 cachingEnabled?: boolean;
13627 /**
13628 * Maximum number of connections the pool may open to the origin database.
13629 * Defaults to 60.
13630 */
13631 maxConnections?: number;
13632}
13633// Copyright (c) 2024 Cloudflare, Inc.
13634// Licensed under the Apache 2.0 license found in the LICENSE file or at:
13635// https://opensource.org/licenses/Apache-2.0
13636type ImageInfoResponse = {
13637 format: 'image/svg+xml';
13638} | {
13639 format: string;
13640 fileSize: number;
13641 width: number;
13642 height: number;
13643};
13644/**
13645 * Parameters for rasterizing text into an image.
13646 */
13647type TextRasterize = {
13648 /** The text content to render */
13649 content: string;
13650 /** rasterization options for the text **/
13651 options: TextOptions;
13652};
13653type TextOptions = {
13654 /** Font configuration */
13655 font: {
13656 /** URL to a font file in TrueType (.ttf), OpenType (.otf), WOFF (.woff), or WOFF2 (.woff2) format */
13657 url: string;
13658 };
13659 /** Font size in points (pt) */
13660 size?: number;
13661 /** Text color in CSS format: hex (#RRGGBB or #RRGGBBAA), rgb(r,g,b), rgba(r,g,b,a), or named colors */
13662 color?: string;
13663};
13664type ImageSource = ReadableStream<Uint8Array> | TextRasterize;
13665type ImageTransform = {
13666 width?: number;
13667 height?: number;
13668 background?: string;
13669 blur?: number;
13670 border?: {
13671 color?: string;
13672 width?: number;
13673 } | {
13674 top?: number;
13675 bottom?: number;
13676 left?: number;
13677 right?: number;
13678 };
13679 brightness?: number;
13680 contrast?: number;
13681 fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop';
13682 flip?: 'h' | 'v' | 'hv';
13683 gamma?: number;
13684 segment?: 'foreground';
13685 gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | {
13686 x?: number;
13687 y?: number;
13688 mode: 'remainder' | 'box-center';
13689 };
13690 rotate?: 0 | 90 | 180 | 270;
13691 saturation?: number;
13692 sharpen?: number;
13693 trim?: 'border' | {
13694 top?: number;
13695 bottom?: number;
13696 left?: number;
13697 right?: number;
13698 width?: number;
13699 height?: number;
13700 border?: boolean | {
13701 color?: string;
13702 tolerance?: number;
13703 keep?: number;
13704 };
13705 };
13706};
13707type ImageDrawOptions = {
13708 opacity?: number;
13709 repeat?: boolean | string;
13710 composite?: ImageCompositeMode;
13711 top?: number;
13712 left?: number;
13713 bottom?: number;
13714 right?: number;
13715};
13716type ImageCompositeMode =
13717/** Foreground drawn on top of backdrop (default) */
13718'over'
13719/** Foreground shown only where backdrop is opaque */
13720 | 'in'
13721/** Foreground drawn on top, but clipped to the backdrop's shape */
13722 | 'atop'
13723/** Foreground shown only where backdrop is transparent */
13724 | 'out'
13725/** Foreground and backdrop visible only where the other is not */
13726 | 'xor'
13727/** Foreground and backdrop channels added (brightening) */
13728 | 'lighter';
13729type ImageInputOptions = {
13730 encoding?: 'base64';
13731};
13732type ImageOutputOptions = {
13733 format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba';
13734 quality?: number;
13735 background?: string;
13736 anim?: boolean;
13737};
13738interface ImageMetadata {
13739 id: string;
13740 filename?: string;
13741 uploaded?: string;
13742 requireSignedURLs: boolean;
13743 meta?: Record<string, unknown>;
13744 variants: string[];
13745 draft?: boolean;
13746 creator?: string;
13747}
13748interface ImageUploadOptions {
13749 id?: string;
13750 filename?: string;
13751 requireSignedURLs?: boolean;
13752 metadata?: Record<string, unknown>;
13753 creator?: string;
13754 /**
13755 * If 'base64', the input data will be decoded from base64 before processing
13756 */
13757 encoding?: 'base64';
13758}
13759interface ImageUpdateOptions {
13760 requireSignedURLs?: boolean;
13761 metadata?: Record<string, unknown>;
13762 creator?: string;
13763}
13764type ImageMetadataFilterOperators = {
13765 eq?: string | number | boolean;
13766 in?: string[] | number[];
13767 gt?: number;
13768 gte?: number;
13769 lt?: number;
13770 lte?: number;
13771};
13772type ImageMetadataFilterValue = string | number | boolean | ImageMetadataFilterOperators;
13773interface ImageListFilter {
13774 metadata?: Record<string, ImageMetadataFilterValue>;
13775}
13776interface ImageListOptions {
13777 limit?: number;
13778 cursor?: string;
13779 sortOrder?: 'asc' | 'desc';
13780 creator?: string;
13781 filter?: ImageListFilter;
13782}
13783interface ImageSignedUrlOptions {
13784 variant: string;
13785 expiresIn?: number;
13786 keyName?: string;
13787}
13788interface ImageDirectUploadOptions {
13789 id?: string;
13790 requireSignedURLs?: boolean;
13791 metadata?: Record<string, unknown>;
13792 creator?: string;
13793 expiresIn?: number;
13794}
13795interface ImageDirectUploadResult {
13796 id: string;
13797 uploadURL: string;
13798}
13799interface ImageList {
13800 images: ImageMetadata[];
13801 cursor?: string;
13802 listComplete: boolean;
13803}
13804interface ImageHandle {
13805 /**
13806 * Get metadata for a hosted image
13807 * @returns Image metadata, or null if not found
13808 */
13809 details(): Promise<ImageMetadata | null>;
13810 /**
13811 * Get the raw image data for a hosted image
13812 * @returns ReadableStream of image bytes, or null if not found
13813 */
13814 bytes(): Promise<ReadableStream<Uint8Array> | null>;
13815 /**
13816 * Generate a signed delivery URL for this hosted image.
13817 * @param options Signing configuration
13818 * @returns A signed image delivery URL
13819 * @throws {@link ImagesError} if signing fails
13820 */
13821 signedUrl(options: ImageSignedUrlOptions): Promise<string>;
13822 /**
13823 * Update hosted image metadata
13824 * @param options Properties to update
13825 * @returns Updated image metadata
13826 * @throws {@link ImagesError} if update fails
13827 */
13828 update(options: ImageUpdateOptions): Promise<ImageMetadata>;
13829 /**
13830 * Delete a hosted image
13831 * @returns True if deleted, false if not found
13832 */
13833 delete(): Promise<boolean>;
13834}
13835interface HostedImagesBinding {
13836 /**
13837 * Get a handle for a hosted image
13838 * @param imageId The ID of the image (UUID or custom ID)
13839 * @returns A handle for per-image operations
13840 */
13841 image(imageId: string): ImageHandle;
13842 /**
13843 * Upload a new hosted image
13844 * @param image The image file to upload
13845 * @param options Upload configuration
13846 * @returns Metadata for the uploaded image
13847 * @throws {@link ImagesError} if upload fails
13848 */
13849 upload(image: ReadableStream<Uint8Array> | ArrayBuffer, options?: ImageUploadOptions): Promise<ImageMetadata>;
13850 /**
13851 * List hosted images with pagination
13852 * @param options List configuration
13853 * @returns List of images with pagination info
13854 * @throws {@link ImagesError} if list fails
13855 */
13856 list(options?: ImageListOptions): Promise<ImageList>;
13857 /**
13858 * Create a Direct Creator Upload link, letting an end user upload an
13859 * image straight to Cloudflare without exposing an API token
13860 * @param options Upload link configuration
13861 * @returns The new image ID and the upload URL to hand to the end user
13862 * @throws {@link ImagesError} if creation fails
13863 */
13864 createDirectUpload(options?: ImageDirectUploadOptions): Promise<ImageDirectUploadResult>;
13865}
13866interface ImagesBinding {
13867 /**
13868 * Get image metadata (type, width and height)
13869 * @throws {@link ImagesError} with code 9412 if input is not an image
13870 * @param stream The image bytes
13871 */
13872 info(stream: ReadableStream<Uint8Array>, options?: ImageInputOptions): Promise<ImageInfoResponse>;
13873 /**
13874 * Begin applying a series of transformations to an image
13875 * @param stream The image bytes
13876 * @returns A transform handle
13877 */
13878 input(stream: ReadableStream<Uint8Array>, options?: ImageInputOptions): ImageTransformer;
13879 /**
13880 * Begin applying a series of transformations to text
13881 * @param content string to be rendered
13882 * @param options font, optional color and size to use in rendering text
13883 * @returns A transform handle
13884 */
13885 text(content: string, options: TextOptions): ImageTransformer;
13886 /**
13887 * Access hosted images CRUD operations
13888 */
13889 readonly hosted: HostedImagesBinding;
13890}
13891interface ImageTransformer {
13892 /**
13893 * Apply transform next, returning a transform handle.
13894 * You can then apply more transformations, draw, or retrieve the output.
13895 * @param transform
13896 */
13897 transform(transform: ImageTransform): ImageTransformer;
13898 /**
13899 * Draw an image on this transformer, returning a transform handle.
13900 * You can then apply more transformations, draw, or retrieve the output.
13901 * @param image The image (or transformer that will give the image) to draw
13902 * @param options The options configuring how to draw the image
13903 */
13904 draw(image: ReadableStream<Uint8Array> | ImageTransformer, options?: ImageDrawOptions): ImageTransformer;
13905 /**
13906 * Retrieve the image that results from applying the transforms to the
13907 * provided input
13908 * @param options Options that apply to the output e.g. output format
13909 */
13910 output(options: ImageOutputOptions): Promise<ImageTransformationResult>;
13911}
13912type ImageTransformationOutputOptions = {
13913 encoding?: 'base64';
13914};
13915type ImageTransformationResponseOptions = {
13916 headers?: HeadersInit;
13917};
13918interface ImageTransformationResult {
13919 /**
13920 * The image as a response, ready to store in cache or return to users
13921 * @param options Options that apply to the returned response, e.g. additional headers
13922 */
13923 response(options?: ImageTransformationResponseOptions): Response;
13924 /**
13925 * The content type of the returned image
13926 */
13927 contentType(): string;
13928 /**
13929 * The bytes of the response
13930 */
13931 image(options?: ImageTransformationOutputOptions): ReadableStream<Uint8Array>;
13932}
13933interface ImagesError extends Error {
13934 readonly code: number;
13935 readonly message: string;
13936 readonly stack?: string;
13937}
13938/**
13939 * Media binding for transforming media streams.
13940 * Provides the entry point for media transformation operations.
13941 */
13942interface MediaBinding {
13943 /**
13944 * Creates a media transformer from an input stream.
13945 * @param media - The input media bytes
13946 * @returns A MediaTransformer instance for applying transformations
13947 */
13948 input(media: ReadableStream<Uint8Array>): MediaTransformer;
13949}
13950/**
13951 * Media transformer for applying transformation operations to media content.
13952 * Handles sizing, fitting, and other input transformation parameters.
13953 */
13954interface MediaTransformer {
13955 /**
13956 * Applies transformation options to the media content.
13957 * @param transform - Configuration for how the media should be transformed
13958 * @returns A generator for producing the transformed media output
13959 */
13960 transform(transform?: MediaTransformationInputOptions): MediaTransformationGenerator;
13961 /**
13962 * Generates the final media output with specified options.
13963 * @param output - Configuration for the output format and parameters
13964 * @returns The final transformation result containing the transformed media
13965 */
13966 output(output?: MediaTransformationOutputOptions): MediaTransformationResult;
13967}
13968/**
13969 * Generator for producing media transformation results.
13970 * Configures the output format and parameters for the transformed media.
13971 */
13972interface MediaTransformationGenerator {
13973 /**
13974 * Generates the final media output with specified options.
13975 * @param output - Configuration for the output format and parameters
13976 * @returns The final transformation result containing the transformed media
13977 */
13978 output(output?: MediaTransformationOutputOptions): MediaTransformationResult;
13979}
13980/**
13981 * Result of a media transformation operation.
13982 * Provides multiple ways to access the transformed media content.
13983 */
13984interface MediaTransformationResult {
13985 /**
13986 * Returns the transformed media as a readable stream of bytes.
13987 * @returns A promise containing a readable stream with the transformed media
13988 */
13989 media(): Promise<ReadableStream<Uint8Array>>;
13990 /**
13991 * Returns the transformed media as an HTTP response object.
13992 * @returns The transformed media as a Promise<Response>, ready to store in cache or return to users
13993 */
13994 response(): Promise<Response>;
13995 /**
13996 * Returns the MIME type of the transformed media.
13997 * @returns A promise containing the content type string (e.g., 'image/jpeg', 'video/mp4')
13998 */
13999 contentType(): Promise<string>;
14000}
14001/**
14002 * Configuration options for transforming media input.
14003 * Controls how the media should be resized and fitted.
14004 */
14005type MediaTransformationInputOptions = {
14006 /** How the media should be resized to fit the specified dimensions */
14007 fit?: 'contain' | 'cover' | 'scale-down';
14008 /** Target width in pixels */
14009 width?: number;
14010 /** Target height in pixels */
14011 height?: number;
14012};
14013/**
14014 * Configuration options for Media Transformations output.
14015 * Controls the format, timing, and type of the generated output.
14016 */
14017type MediaTransformationOutputOptions = {
14018 /**
14019 * Output mode determining the type of media to generate
14020 */
14021 mode?: 'video' | 'spritesheet' | 'frame' | 'audio';
14022 /** Whether to include audio in the output */
14023 audio?: boolean;
14024 /**
14025 * Starting timestamp for frame extraction or start time for clips. (e.g. '2s').
14026 */
14027 time?: string;
14028 /**
14029 * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s').
14030 */
14031 duration?: string;
14032 /**
14033 * Number of frames in the spritesheet.
14034 */
14035 imageCount?: number;
14036 /**
14037 * Output format for the generated media.
14038 */
14039 format?: 'jpg' | 'png' | 'm4a';
14040};
14041/**
14042 * Error object for media transformation operations.
14043 * Extends the standard Error interface with additional media-specific information.
14044 */
14045interface MediaError extends Error {
14046 readonly code: number;
14047 readonly message: string;
14048 readonly stack?: string;
14049}
14050declare module 'cloudflare:node' {
14051 interface NodeStyleServer {
14052 listen(...args: unknown[]): this;
14053 address(): {
14054 port?: number | null | undefined;
14055 } | null;
14056 }
14057 export function httpServerHandler(port: number): ExportedHandler;
14058 export function httpServerHandler(options: {
14059 port: number;
14060 }): ExportedHandler;
14061 export function httpServerHandler(server: NodeStyleServer): ExportedHandler;
14062 /**
14063 * Dispatches a request to the `http.Server` listening on the given port and
14064 * resolves with its response. The direct form of `httpServerHandler()`.
14065 */
14066 export function handleAsNodeRequest(port: number | {
14067 port: number;
14068 }, request: Request, env?: unknown, ctx?: ExecutionContext): Promise<Response>;
14069 /**
14070 * Routes inbound sockets to the `net.Server` listening on the port each
14071 * socket arrived on.
14072 */
14073 export function connectHandler(): ExportedHandler;
14074 /**
14075 * Dispatches an inbound socket to the `net.Server` listening on the port it
14076 * arrived on, resolving when the connection has closed. The direct form of
14077 * `connectHandler()`, for use inside a `connect()` handler, such as a
14078 * Durable Object's.
14079 */
14080 export function handleAsNodeConnection(socket: Socket, env?: unknown, ctx?: ExecutionContext): Promise<void>;
14081}
14082type Params<P extends string = any> = Record<P, string | string[]>;
14083type EventContext<Env, P extends string, Data> = {
14084 request: Request<unknown, IncomingRequestCfProperties<unknown>>;
14085 functionPath: string;
14086 waitUntil: (promise: Promise<any>) => void;
14087 passThroughOnException: () => void;
14088 next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
14089 env: Env & {
14090 ASSETS: {
14091 fetch: typeof fetch;
14092 };
14093 };
14094 params: Params<P>;
14095 data: Data;
14096};
14097type PagesFunction<Env = unknown, Params extends string = any, Data extends Record<string, unknown> = Record<string, unknown>> = (context: EventContext<Env, Params, Data>) => Response | Promise<Response>;
14098type EventPluginContext<Env, P extends string, Data, PluginArgs> = {
14099 request: Request<unknown, IncomingRequestCfProperties<unknown>>;
14100 functionPath: string;
14101 waitUntil: (promise: Promise<any>) => void;
14102 passThroughOnException: () => void;
14103 next: (input?: Request | string, init?: RequestInit) => Promise<Response>;
14104 env: Env & {
14105 ASSETS: {
14106 fetch: typeof fetch;
14107 };
14108 };
14109 params: Params<P>;
14110 data: Data;
14111 pluginArgs: PluginArgs;
14112};
14113type 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>;
14114declare module "assets:*" {
14115 export const onRequest: PagesFunction;
14116}
14117// Copyright (c) 2022-2023 Cloudflare, Inc.
14118// Licensed under the Apache 2.0 license found in the LICENSE file or at:
14119// https://opensource.org/licenses/Apache-2.0
14120declare module "cloudflare:pipelines" {
14121 export abstract class PipelineTransformationEntrypoint<Env = unknown, I extends PipelineRecord = PipelineRecord, O extends PipelineRecord = PipelineRecord> {
14122 protected env: Env;
14123 protected ctx: ExecutionContext;
14124 constructor(ctx: ExecutionContext, env: Env);
14125 /**
14126 * run receives an array of PipelineRecord which can be
14127 * transformed and returned to the pipeline
14128 * @param records Incoming records from the pipeline to be transformed
14129 * @param metadata Information about the specific pipeline calling the transformation entrypoint
14130 * @returns A promise containing the transformed PipelineRecord array
14131 */
14132 public run(records: I[], metadata: PipelineBatchMetadata): Promise<O[]>;
14133 }
14134 export type PipelineRecord = Record<string, unknown>;
14135 export type PipelineBatchMetadata = {
14136 pipelineId: string;
14137 pipelineName: string;
14138 };
14139 export interface Pipeline<T extends PipelineRecord = PipelineRecord> {
14140 /**
14141 * The Pipeline interface represents the type of a binding to a Pipeline
14142 *
14143 * @param records The records to send to the pipeline
14144 */
14145 send(records: T[]): Promise<void>;
14146 }
14147}
14148// PubSubMessage represents an incoming PubSub message.
14149// The message includes metadata about the broker, the client, and the payload
14150// itself.
14151// https://developers.cloudflare.com/pub-sub/
14152interface PubSubMessage {
14153 // Message ID
14154 readonly mid: number;
14155 // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT
14156 readonly broker: string;
14157 // The MQTT topic the message was sent on.
14158 readonly topic: string;
14159 // The client ID of the client that published this message.
14160 readonly clientId: string;
14161 // The unique identifier (JWT ID) used by the client to authenticate, if token
14162 // auth was used.
14163 readonly jti?: string;
14164 // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker
14165 // received the message from the client.
14166 readonly receivedAt: number;
14167 // An (optional) string with the MIME type of the payload, if set by the
14168 // client.
14169 readonly contentType: string;
14170 // Set to 1 when the payload is a UTF-8 string
14171 // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063
14172 readonly payloadFormatIndicator: number;
14173 // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays.
14174 // You can use payloadFormatIndicator to inspect this before decoding.
14175 payload: string | Uint8Array;
14176}
14177// JsonWebKey extended by kid parameter
14178interface JsonWebKeyWithKid extends JsonWebKey {
14179 // Key Identifier of the JWK
14180 readonly kid: string;
14181}
14182interface RateLimitOptions {
14183 key: string;
14184}
14185interface RateLimitOutcome {
14186 success: boolean;
14187}
14188interface RateLimit {
14189 /**
14190 * Rate limit a request based on the provided options.
14191 * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/
14192 * @returns A promise that resolves with the outcome of the rate limit.
14193 */
14194 limit(options: RateLimitOptions): Promise<RateLimitOutcome>;
14195}
14196// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need
14197// to referenced by `Fetcher`. This is included in the "importable" version of the types which
14198// strips all `module` blocks.
14199declare namespace Rpc {
14200 // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s.
14201 // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`.
14202 // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to
14203 // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape)
14204 export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND';
14205 export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND';
14206 export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND';
14207 export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND';
14208 export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND';
14209 export interface RpcTargetBranded {
14210 [__RPC_TARGET_BRAND]: never;
14211 }
14212 export interface WorkerEntrypointBranded {
14213 [__WORKER_ENTRYPOINT_BRAND]: never;
14214 }
14215 export interface DurableObjectBranded {
14216 [__DURABLE_OBJECT_BRAND]: never;
14217 }
14218 export interface WorkflowEntrypointBranded {
14219 [__WORKFLOW_ENTRYPOINT_BRAND]: never;
14220 }
14221 export type EntrypointBranded = WorkerEntrypointBranded | DurableObjectBranded | WorkflowEntrypointBranded;
14222 // Types that can be used through `Stub`s
14223 export type Stubable = RpcTargetBranded | ((...args: any[]) => any);
14224 // Types that can be passed over RPC
14225 // The reason for using a generic type here is to build a serializable subset of structured
14226 // cloneable composite types. This allows types defined with the "interface" keyword to pass the
14227 // serializable check as well. Otherwise, only types defined with the "type" keyword would pass.
14228 type Serializable<T> =
14229 // Structured cloneables
14230 BaseType
14231 // Structured cloneable composites
14232 | 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> | {
14233 [K in keyof T]: K extends number | string ? Serializable<T[K]> : never;
14234 }
14235 // Special types
14236 | Stub<Stubable>
14237 // Serialized as stubs, see `Stubify`
14238 | Stubable;
14239 // Base type for all RPC stubs, including common memory management methods.
14240 // `T` is used as a marker type for unwrapping `Stub`s later.
14241 interface StubBase<T extends Stubable> extends Disposable {
14242 [__RPC_STUB_BRAND]: T;
14243 dup(): this;
14244 }
14245 export type Stub<T extends Stubable> = Provider<T> & StubBase<T>;
14246 // This represents all the types that can be sent as-is over an RPC boundary
14247 type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | ReadableStream<Uint8Array> | WritableStream<Uint8Array> | Request | Response | Headers;
14248 // Recursively rewrite all `Stubable` types with `Stub`s
14249 // prettier-ignore
14250 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 {
14251 [key: string | number]: any;
14252 } ? {
14253 [K in keyof T]: Stubify<T[K]>;
14254 } : T;
14255 // Recursively rewrite all `Stub<T>`s with the corresponding `T`s.
14256 // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies:
14257 // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`.
14258 // prettier-ignore
14259 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 {
14260 [key: string | number]: unknown;
14261 } ? {
14262 [K in keyof T]: Unstubify<T[K]>;
14263 } : T;
14264 type UnstubifyAll<A extends any[]> = {
14265 [I in keyof A]: Unstubify<A[I]>;
14266 };
14267 // Utility type for adding `Provider`/`Disposable`s to `object` types only.
14268 // Note `unknown & T` is equivalent to `T`.
14269 type MaybeProvider<T> = T extends object ? Provider<T> : unknown;
14270 type MaybeDisposable<T> = T extends object ? Disposable : unknown;
14271 // Type for method return or property on an RPC interface.
14272 // - Stubable types are replaced by stubs.
14273 // - Serializable types are passed by value, with stubable types replaced by stubs
14274 // and a top-level `Disposer`.
14275 // Everything else can't be passed over PRC.
14276 // Technically, we use custom thenables here, but they quack like `Promise`s.
14277 // Intersecting with `(Maybe)Provider` allows pipelining.
14278 // prettier-ignore
14279 type Result<R> = R extends Stubable ? Promise<Stub<R>> & Provider<R> : R extends Serializable<R> ? Promise<Stubify<R> & MaybeDisposable<R>> & MaybeProvider<R> : never;
14280 // Type for method or property on an RPC interface.
14281 // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
14282 // Unwrapping `Stub`s allows calling with `Stubable` arguments.
14283 // For properties, rewrite types to be `Result`s.
14284 // In each case, unwrap `Promise`s.
14285 type MethodOrProperty<V> = V extends (...args: infer P) => infer R ? (...args: UnstubifyAll<P>) => Result<Awaited<R>> : Result<Awaited<V>>;
14286 // Type for the callable part of an `Provider` if `T` is callable.
14287 // This is intersected with methods/properties.
14288 type MaybeCallableProvider<T> = T extends (...args: any[]) => any ? MethodOrProperty<T> : unknown;
14289 // Base type for all other types providing RPC-like interfaces.
14290 // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
14291 // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC.
14292 export type Provider<T extends object, Reserved extends string = never> = MaybeCallableProvider<T> & Pick<{
14293 [K in keyof T]: MethodOrProperty<T[K]>;
14294 }, Exclude<keyof T, Reserved | symbol | keyof StubBase<never>>>;
14295}
14296declare namespace Cloudflare {
14297 // Type of `env`.
14298 //
14299 // The specific project can extend `Env` by redeclaring it in project-specific files. Typescript
14300 // will merge all declarations.
14301 //
14302 // You can use `wrangler types` to generate the `Env` type automatically.
14303 interface Env {
14304 }
14305 // Project-specific parameters used to inform types.
14306 //
14307 // This interface is, again, intended to be declared in project-specific files, and then that
14308 // declaration will be merged with this one.
14309 //
14310 // A project should have a declaration like this:
14311 //
14312 // interface GlobalProps {
14313 // // Declares the main module's exports. Used to populate Cloudflare.Exports aka the type
14314 // // of `ctx.exports`.
14315 // mainModule: typeof import("my-main-module");
14316 //
14317 // // Declares which of the main module's exports are configured with durable storage, and
14318 // // thus should behave as Durable Object namsepace bindings.
14319 // durableNamespaces: "MyDurableObject" | "AnotherDurableObject";
14320 // }
14321 //
14322 // You can use `wrangler types` to generate `GlobalProps` automatically.
14323 interface GlobalProps {
14324 }
14325 // Evaluates to the type of a property in GlobalProps, defaulting to `Default` if it is not
14326 // present.
14327 type GlobalProp<K extends string, Default> = K extends keyof GlobalProps ? GlobalProps[K] : Default;
14328 // The type of the program's main module exports, if known. Requires `GlobalProps` to declare the
14329 // `mainModule` property.
14330 type MainModule = GlobalProp<"mainModule", {}>;
14331 // The type of ctx.exports, which contains loopback bindings for all top-level exports.
14332 type Exports = {
14333 [K in keyof MainModule]: LoopbackForExport<MainModule[K]>
14334 // If the export is listed in `durableNamespaces`, then it is also a
14335 // DurableObjectNamespace.
14336 & (K extends GlobalProp<"durableNamespaces", never> ? MainModule[K] extends new (...args: any[]) => infer DoInstance ? DoInstance extends Rpc.DurableObjectBranded ? DurableObjectNamespace<DoInstance> : DurableObjectNamespace<undefined> : DurableObjectNamespace<undefined> : {});
14337 };
14338}
14339declare namespace CloudflareWorkersModule {
14340 export type RpcStub<T extends Rpc.Stubable> = Rpc.Stub<T>;
14341 export const RpcStub: {
14342 new <T extends Rpc.Stubable>(value: T): Rpc.Stub<T>;
14343 };
14344 export abstract class RpcTarget implements Rpc.RpcTargetBranded {
14345 [Rpc.__RPC_TARGET_BRAND]: never;
14346 }
14347 // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC
14348 export abstract class WorkerEntrypoint<Env = Cloudflare.Env, Props = {}> implements Rpc.WorkerEntrypointBranded {
14349 [Rpc.__WORKER_ENTRYPOINT_BRAND]: never;
14350 protected ctx: ExecutionContext<Props>;
14351 protected env: Env;
14352 constructor(ctx: ExecutionContext, env: Env);
14353 email?(message: ForwardableEmailMessage): void | Promise<void>;
14354 fetch?(request: Request): Response | Promise<Response>;
14355 connect?(socket: Socket): void | Promise<void>;
14356 queue?(batch: MessageBatch): void | Promise<void>;
14357 scheduled?(controller: ScheduledController): void | Promise<void>;
14358 tail?(events: TraceItem[]): void | Promise<void>;
14359 tailStream?(event: TailStream.TailEvent<TailStream.Onset>): TailStream.TailEventHandlerType | undefined | Promise<TailStream.TailEventHandlerType | undefined>;
14360 test?(controller: TestController): void | Promise<void>;
14361 trace?(traces: TraceItem[]): void | Promise<void>;
14362 }
14363 export abstract class DurableObject<Env = Cloudflare.Env, Props = {}> implements Rpc.DurableObjectBranded {
14364 [Rpc.__DURABLE_OBJECT_BRAND]: never;
14365 protected ctx: DurableObjectState<Props>;
14366 protected env: Env;
14367 constructor(ctx: DurableObjectState, env: Env);
14368 alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise<void>;
14369 fetch?(request: Request): Response | Promise<Response>;
14370 connect?(socket: Socket): void | Promise<void>;
14371 webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise<void>;
14372 webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise<void>;
14373 webSocketError?(ws: WebSocket, error: unknown): void | Promise<void>;
14374 }
14375 export type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';
14376 export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number;
14377 export type WorkflowDelayDuration = WorkflowSleepDuration;
14378 export type WorkflowDynamicDelayContext = {
14379 ctx: WorkflowStepContext<WorkflowDelayFunction>;
14380 error: Error;
14381 };
14382 export type WorkflowDelayFunction = (input: WorkflowDynamicDelayContext) => WorkflowDelayDuration | Promise<WorkflowDelayDuration>;
14383 export type WorkflowTimeoutDuration = WorkflowSleepDuration;
14384 export type WorkflowRetentionDuration = WorkflowSleepDuration;
14385 export type WorkflowBackoff = 'constant' | 'linear' | 'exponential';
14386 export type WorkflowStepSensitivity = 'output';
14387 export type WorkflowStepConfig = {
14388 retries?: {
14389 limit: number;
14390 delay: WorkflowDelayDuration | number | WorkflowDelayFunction;
14391 backoff?: WorkflowBackoff;
14392 };
14393 timeout?: WorkflowTimeoutDuration | number;
14394 sensitive?: WorkflowStepSensitivity;
14395 };
14396 // Internal discriminators used only for `WorkflowStep.do` overload
14397 // resolution. They mirror `WorkflowStepConfig` but pin `retries.delay` to a
14398 // single kind so the callback context can be narrowed based on the shape of
14399 // the config argument (rather than on an inferred type parameter, which is
14400 // lost when the caller supplies an explicit return-type argument). Not
14401 // exported: they must not widen the public type surface.
14402 type WorkflowStepConfigWithStaticDelay = Omit<WorkflowStepConfig, 'retries'> & {
14403 retries?: {
14404 limit: number;
14405 delay: WorkflowDelayDuration | number;
14406 backoff?: WorkflowBackoff;
14407 };
14408 };
14409 type WorkflowStepConfigWithDelayFunction = Omit<WorkflowStepConfig, 'retries'> & {
14410 retries: {
14411 limit: number;
14412 delay: WorkflowDelayFunction;
14413 backoff?: WorkflowBackoff;
14414 };
14415 };
14416 export type WorkflowStepRollbackConfig = Pick<WorkflowStepConfig, 'retries' | 'timeout'>;
14417 export type WorkflowCronSchedule = {
14418 /** Cron expression that triggered this event. */
14419 cron: string;
14420 /** Timestamp of the scheduled trigger, in milliseconds since the Unix epoch. */
14421 scheduledTime: number;
14422 };
14423 export type WorkflowEvent<T> = {
14424 payload: Readonly<T>;
14425 timestamp: Date;
14426 instanceId: string;
14427 workflowName: string;
14428 schedule?: WorkflowCronSchedule;
14429 };
14430 export type WorkflowStepEvent<T> = {
14431 payload: Readonly<T>;
14432 timestamp: Date;
14433 type: string;
14434 sensitive?: WorkflowStepSensitivity;
14435 };
14436 export type WorkflowStepContext<Delay = WorkflowDelayDuration | number> = {
14437 step: {
14438 name: string;
14439 count: number;
14440 };
14441 attempt: number;
14442 config: {
14443 retries?: {
14444 limit: number;
14445 backoff?: WorkflowBackoff;
14446 } & (Delay extends WorkflowDelayFunction ? {} : {
14447 delay: WorkflowDelayDuration | number;
14448 });
14449 timeout?: WorkflowTimeoutDuration | number;
14450 sensitive?: WorkflowStepSensitivity;
14451 };
14452 };
14453 // The rollback handler receives the step context, so it mirrors the same
14454 // delay discriminant as the step callback: when the step was configured with
14455 // a dynamic delay function the resolved `config.retries.delay` is omitted,
14456 // otherwise it is present. `Delay` is threaded from the `WorkflowStep.do`
14457 // overload that matched the step config.
14458 export type WorkflowRollbackContext<T = unknown, Delay = WorkflowDelayDuration | number> = {
14459 ctx: WorkflowStepContext<Delay>;
14460 error: Error;
14461 output: T | undefined;
14462 /** @deprecated Use `ctx.step.name` and `ctx.step.count` instead. */
14463 stepName: string;
14464 };
14465 export type WorkflowRollbackHandler<T = unknown, Delay = WorkflowDelayDuration | number> = (ctx: WorkflowRollbackContext<T, Delay>) => Promise<void>;
14466 export type WorkflowStepRollbackOptions<T = unknown, Delay = WorkflowDelayDuration | number> = {
14467 rollback: WorkflowRollbackHandler<T, Delay>;
14468 rollbackConfig?: WorkflowStepRollbackConfig;
14469 };
14470 export abstract class WorkflowStep {
14471 do<T extends Rpc.Serializable<T>>(name: string, callback: (ctx: WorkflowStepContext) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T>): Promise<T>;
14472 // The config overloads discriminate on the shape of `config.retries.delay`
14473 // so the callback context reflects whether the resolved delay is present
14474 // (static delay) or omitted (dynamic delay function). Each has a single
14475 // type parameter, so an explicit return-type argument (`do<T>(...)`) still
14476 // resolves here. ORDERING IS LOAD-BEARING: the broad `WorkflowStepConfig`
14477 // fallback MUST remain last, otherwise it shadows the discriminating
14478 // overloads and narrowing is silently lost.
14479 do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfigWithDelayFunction, callback: (ctx: WorkflowStepContext<WorkflowDelayFunction>) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T, WorkflowDelayFunction>): Promise<T>;
14480 do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfigWithStaticDelay, callback: (ctx: WorkflowStepContext<WorkflowDelayDuration | number>) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T, WorkflowDelayDuration | number>): Promise<T>;
14481 do<T extends Rpc.Serializable<T>>(name: string, config: WorkflowStepConfig, callback: (ctx: WorkflowStepContext) => Promise<T>, rollbackOptions?: WorkflowStepRollbackOptions<T>): Promise<T>;
14482 sleep: (name: string, duration: WorkflowSleepDuration) => Promise<void>;
14483 sleepUntil: (name: string, timestamp: Date | number) => Promise<void>;
14484 waitForEvent<T extends Rpc.Serializable<T>>(name: string, options: {
14485 type: string;
14486 timeout?: WorkflowTimeoutDuration | number;
14487 }): Promise<WorkflowStepEvent<T>>;
14488 }
14489 export type WorkflowInstanceStatus = 'queued' | 'running' | 'paused' | 'errored' | 'terminated' | 'complete' | 'waiting' | 'waitingForPause' | 'unknown';
14490 export abstract class WorkflowEntrypoint<Env = unknown, T extends Rpc.Serializable<T> | unknown = unknown> implements Rpc.WorkflowEntrypointBranded {
14491 [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never;
14492 protected ctx: ExecutionContext;
14493 protected env: Env;
14494 constructor(ctx: ExecutionContext, env: Env);
14495 run(event: Readonly<WorkflowEvent<T>>, step: WorkflowStep): Promise<unknown>;
14496 }
14497 export function waitUntil(promise: Promise<unknown>): void;
14498 export function withEnv(newEnv: unknown, fn: () => unknown): unknown;
14499 export function withExports(newExports: unknown, fn: () => unknown): unknown;
14500 export function withEnvAndExports(newEnv: unknown, newExports: unknown, fn: () => unknown): unknown;
14501 export const env: Cloudflare.Env;
14502 export const exports: Cloudflare.Exports;
14503 export const cache: CacheContext;
14504 export const tracing: Tracing;
14505}
14506declare module 'cloudflare:workers' {
14507 export = CloudflareWorkersModule;
14508}
14509interface SecretsStoreSecret {
14510 /**
14511 * Get a secret from the Secrets Store, returning a string of the secret value
14512 * if it exists, or throws an error if it does not exist
14513 */
14514 get(): Promise<string>;
14515}
14516declare module "cloudflare:sockets" {
14517 function _connect(address: string | SocketAddress, options?: SocketOptions): Socket;
14518 export { _connect as connect };
14519}
14520/**
14521 * Binding entrypoint for Cloudflare Stream.
14522 *
14523 * Usage:
14524 * - Binding-level operations:
14525 * `await env.STREAM.videos.upload`
14526 * `await env.STREAM.videos.createDirectUpload`
14527 * `await env.STREAM.videos.*`
14528 * `await env.STREAM.watermarks.*`
14529 * - Per-video operations:
14530 * `await env.STREAM.video(id).downloads.*`
14531 * `await env.STREAM.video(id).captions.*`
14532 *
14533 * Example usage:
14534 * ```ts
14535 * await env.STREAM.video(id).downloads.generate();
14536 *
14537 * const video = env.STREAM.video(id)
14538 * const captions = video.captions.list();
14539 * const videoDetails = video.details()
14540 * ```
14541 */
14542interface StreamBinding {
14543 /**
14544 * Returns a handle scoped to a single video for per-video operations.
14545 * @param id The unique identifier for the video.
14546 * @returns A handle for per-video operations.
14547 */
14548 video(id: string): StreamVideoHandle;
14549 /**
14550 * Uploads a new video from a provided URL.
14551 * @param url The URL to upload from.
14552 * @param params Optional upload parameters.
14553 * @returns The uploaded video details.
14554 * @throws {BadRequestError} if the upload parameter is invalid or the URL is invalid
14555 * @throws {QuotaReachedError} if the account storage capacity is exceeded
14556 * @throws {MaxFileSizeError} if the file size is too large
14557 * @throws {RateLimitedError} if the server received too many requests
14558 * @throws {AlreadyUploadedError} if a video was already uploaded to this URL
14559 * @throws {InternalError} if an unexpected error occurs
14560 */
14561 upload(url: string, params?: StreamUrlUploadParams): Promise<StreamVideo>;
14562 /**
14563 * Creates a direct upload that allows video uploads without an API key.
14564 * @param params Parameters for the direct upload
14565 * @returns The direct upload details.
14566 * @throws {BadRequestError} if the parameters are invalid
14567 * @throws {RateLimitedError} if the server received too many requests
14568 * @throws {InternalError} if an unexpected error occurs
14569 */
14570 createDirectUpload(params: StreamDirectUploadCreateParams): Promise<StreamDirectUpload>;
14571 videos: StreamVideos;
14572 watermarks: StreamWatermarks;
14573}
14574/**
14575 * Handle for operations scoped to a single Stream video.
14576 */
14577interface StreamVideoHandle {
14578 /**
14579 * The unique identifier for the video.
14580 */
14581 id: string;
14582 /**
14583 * Get a full videos details
14584 * @returns The full video details.
14585 * @throws {NotFoundError} if the video is not found
14586 * @throws {InternalError} if an unexpected error occurs
14587 */
14588 details(): Promise<StreamVideo>;
14589 /**
14590 * Update details for a single video.
14591 * @param params The fields to update for the video.
14592 * @returns The updated video details.
14593 * @throws {NotFoundError} if the video is not found
14594 * @throws {BadRequestError} if the parameters are invalid
14595 * @throws {InternalError} if an unexpected error occurs
14596 */
14597 update(params: StreamUpdateVideoParams): Promise<StreamVideo>;
14598 /**
14599 * Deletes a video and its copies from Cloudflare Stream.
14600 * @returns A promise that resolves when deletion completes.
14601 * @throws {NotFoundError} if the video is not found
14602 * @throws {InternalError} if an unexpected error occurs
14603 */
14604 delete(): Promise<void>;
14605 /**
14606 * Creates a signed URL token for a video.
14607 * @returns The signed token that was created.
14608 * @throws {InternalError} if the signing key cannot be retrieved or the token cannot be signed
14609 */
14610 generateToken(): Promise<string>;
14611 downloads: StreamScopedDownloads;
14612 captions: StreamScopedCaptions;
14613}
14614interface StreamVideo {
14615 /**
14616 * The unique identifier for the video.
14617 */
14618 id: string;
14619 /**
14620 * A user-defined identifier for the media creator.
14621 */
14622 creator: string | null;
14623 /**
14624 * The thumbnail URL for the video.
14625 */
14626 thumbnail: string;
14627 /**
14628 * The thumbnail timestamp percentage.
14629 */
14630 thumbnailTimestampPct: number;
14631 /**
14632 * Indicates whether the video is ready to stream.
14633 */
14634 readyToStream: boolean;
14635 /**
14636 * The date and time the video became ready to stream.
14637 */
14638 readyToStreamAt: string | null;
14639 /**
14640 * Processing status information.
14641 */
14642 status: StreamVideoStatus;
14643 /**
14644 * A user modifiable key-value store.
14645 */
14646 meta: Record<string, string>;
14647 /**
14648 * The date and time the video was created.
14649 */
14650 created: string;
14651 /**
14652 * The date and time the video was last modified.
14653 */
14654 modified: string;
14655 /**
14656 * The date and time at which the video will be deleted.
14657 */
14658 scheduledDeletion: string | null;
14659 /**
14660 * The size of the video in bytes.
14661 */
14662 size: number;
14663 /**
14664 * The preview URL for the video.
14665 */
14666 preview?: string;
14667 /**
14668 * Origins allowed to display the video.
14669 */
14670 allowedOrigins: Array<string>;
14671 /**
14672 * Indicates whether signed URLs are required.
14673 */
14674 requireSignedURLs: boolean | null;
14675 /**
14676 * The date and time the video was uploaded.
14677 */
14678 uploaded: string | null;
14679 /**
14680 * The date and time when the upload URL expires.
14681 */
14682 uploadExpiry: string | null;
14683 /**
14684 * The maximum size in bytes for direct uploads.
14685 */
14686 maxSizeBytes: number | null;
14687 /**
14688 * The maximum duration in seconds for direct uploads.
14689 */
14690 maxDurationSeconds: number | null;
14691 /**
14692 * The video duration in seconds. -1 indicates unknown.
14693 */
14694 duration: number;
14695 /**
14696 * Input metadata for the original upload.
14697 */
14698 input: StreamVideoInput;
14699 /**
14700 * Playback URLs for the video.
14701 */
14702 hlsPlaybackUrl: string;
14703 dashPlaybackUrl: string;
14704 /**
14705 * The watermark applied to the video, if any.
14706 */
14707 watermark: StreamWatermark | null;
14708 /**
14709 * The live input id associated with the video, if any.
14710 */
14711 liveInputId?: string | null;
14712 /**
14713 * The source video id if this is a clip.
14714 */
14715 clippedFromId: string | null;
14716 /**
14717 * Public details associated with the video.
14718 */
14719 publicDetails: StreamPublicDetails | null;
14720}
14721type StreamVideoStatus = {
14722 /**
14723 * The current processing state.
14724 */
14725 state: string;
14726 /**
14727 * The current processing step.
14728 */
14729 step?: string;
14730 /**
14731 * The percent complete as a string.
14732 */
14733 pctComplete?: string;
14734 /**
14735 * An error reason code, if applicable.
14736 */
14737 errorReasonCode: string;
14738 /**
14739 * An error reason text, if applicable.
14740 */
14741 errorReasonText: string;
14742};
14743type StreamVideoInput = {
14744 /**
14745 * The input width in pixels.
14746 */
14747 width: number;
14748 /**
14749 * The input height in pixels.
14750 */
14751 height: number;
14752};
14753type StreamPublicDetails = {
14754 /**
14755 * The public title for the video.
14756 */
14757 title: string | null;
14758 /**
14759 * The public share link.
14760 */
14761 share_link: string | null;
14762 /**
14763 * The public channel link.
14764 */
14765 channel_link: string | null;
14766 /**
14767 * The public logo URL.
14768 */
14769 logo: string | null;
14770};
14771type StreamDirectUpload = {
14772 /**
14773 * The URL an unauthenticated upload can use for a single multipart request.
14774 */
14775 uploadURL: string;
14776 /**
14777 * A Cloudflare-generated unique identifier for a media item.
14778 */
14779 id: string;
14780 /**
14781 * The watermark profile applied to the upload.
14782 */
14783 watermark: StreamWatermark | null;
14784 /**
14785 * The scheduled deletion time, if any.
14786 */
14787 scheduledDeletion: string | null;
14788};
14789type StreamDirectUploadCreateParams = {
14790 /**
14791 * The maximum duration in seconds for a video upload.
14792 */
14793 maxDurationSeconds: number;
14794 /**
14795 * The date and time after upload when videos will not be accepted.
14796 */
14797 expiry?: string;
14798 /**
14799 * A user-defined identifier for the media creator.
14800 */
14801 creator?: string;
14802 /**
14803 * A user modifiable key-value store used to reference other systems of record for
14804 * managing videos.
14805 */
14806 meta?: Record<string, string>;
14807 /**
14808 * Lists the origins allowed to display the video.
14809 */
14810 allowedOrigins?: Array<string>;
14811 /**
14812 * Indicates whether the video can be accessed using the id. When set to `true`,
14813 * a signed token must be generated with a signing key to view the video.
14814 */
14815 requireSignedURLs?: boolean;
14816 /**
14817 * The thumbnail timestamp percentage.
14818 */
14819 thumbnailTimestampPct?: number;
14820 /**
14821 * The date and time at which the video will be deleted. Include `null` to remove
14822 * a scheduled deletion.
14823 */
14824 scheduledDeletion?: string | null;
14825 /**
14826 * The watermark profile to apply.
14827 */
14828 watermark?: StreamDirectUploadWatermark;
14829};
14830type StreamDirectUploadWatermark = {
14831 /**
14832 * The unique identifier for the watermark profile.
14833 */
14834 id: string;
14835};
14836type StreamUrlUploadParams = {
14837 /**
14838 * Lists the origins allowed to display the video. Enter allowed origin
14839 * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the
14840 * video to be viewed on any origin.
14841 */
14842 allowedOrigins?: Array<string>;
14843 /**
14844 * A user-defined identifier for the media creator.
14845 */
14846 creator?: string;
14847 /**
14848 * A user modifiable key-value store used to reference other systems of
14849 * record for managing videos.
14850 */
14851 meta?: Record<string, string>;
14852 /**
14853 * Indicates whether the video can be a accessed using the id. When
14854 * set to `true`, a signed token must be generated with a signing key to view the
14855 * video.
14856 */
14857 requireSignedURLs?: boolean;
14858 /**
14859 * Indicates the date and time at which the video will be deleted. Omit
14860 * the field to indicate no change, or include with a `null` value to remove an
14861 * existing scheduled deletion. If specified, must be at least 30 days from upload
14862 * time.
14863 */
14864 scheduledDeletion?: string | null;
14865 /**
14866 * The timestamp for a thumbnail image calculated as a percentage value
14867 * of the video's duration. To convert from a second-wise timestamp to a
14868 * percentage, divide the desired timestamp by the total duration of the video. If
14869 * this value is not set, the default thumbnail image is taken from 0s of the
14870 * video.
14871 */
14872 thumbnailTimestampPct?: number;
14873 /**
14874 * The identifier for the watermark profile
14875 */
14876 watermarkId?: string;
14877};
14878interface StreamScopedCaptions {
14879 /**
14880 * Uploads the caption or subtitle file to the endpoint for a specific BCP47 language.
14881 * One caption or subtitle file per language is allowed.
14882 * @param language The BCP 47 language tag for the caption or subtitle.
14883 * @param input The caption or subtitle stream to upload.
14884 * @returns The created caption entry.
14885 * @throws {NotFoundError} if the video is not found
14886 * @throws {BadRequestError} if the language or file is invalid
14887 * @throws {InternalError} if an unexpected error occurs
14888 */
14889 upload(language: string, input: ReadableStream): Promise<StreamCaption>;
14890 /**
14891 * Generate captions or subtitles for the provided language via AI.
14892 * @param language The BCP 47 language tag to generate.
14893 * @returns The generated caption entry.
14894 * @throws {NotFoundError} if the video is not found
14895 * @throws {BadRequestError} if the language is invalid
14896 * @throws {StreamError} if a generated caption already exists
14897 * @throws {StreamError} if the video duration is too long
14898 * @throws {StreamError} if the video is missing audio
14899 * @throws {StreamError} if the requested language is not supported
14900 * @throws {InternalError} if an unexpected error occurs
14901 */
14902 generate(language: string): Promise<StreamCaption>;
14903 /**
14904 * Lists the captions or subtitles.
14905 * Use the language parameter to filter by a specific language.
14906 * @param language The optional BCP 47 language tag to filter by.
14907 * @returns The list of captions or subtitles.
14908 * @throws {NotFoundError} if the video or caption is not found
14909 * @throws {InternalError} if an unexpected error occurs
14910 */
14911 list(language?: string): Promise<StreamCaption[]>;
14912 /**
14913 * Removes the captions or subtitles from a video.
14914 * @param language The BCP 47 language tag to remove.
14915 * @returns A promise that resolves when deletion completes.
14916 * @throws {NotFoundError} if the video or caption is not found
14917 * @throws {InternalError} if an unexpected error occurs
14918 */
14919 delete(language: string): Promise<void>;
14920}
14921interface StreamScopedDownloads {
14922 /**
14923 * Generates a download for a video when a video is ready to view. Available
14924 * types are `default` and `audio`. Defaults to `default` when omitted.
14925 * @param downloadType The download type to create.
14926 * @returns The current downloads for the video.
14927 * @throws {NotFoundError} if the video is not found
14928 * @throws {BadRequestError} if the download type is invalid
14929 * @throws {StreamError} if the video duration is too long to generate a download
14930 * @throws {StreamError} if the video is not ready to stream
14931 * @throws {InternalError} if an unexpected error occurs
14932 */
14933 generate(downloadType?: StreamDownloadType): Promise<StreamDownloadGetResponse>;
14934 /**
14935 * Lists the downloads created for a video.
14936 * @returns The current downloads for the video.
14937 * @throws {NotFoundError} if the video or downloads are not found
14938 * @throws {InternalError} if an unexpected error occurs
14939 */
14940 get(): Promise<StreamDownloadGetResponse>;
14941 /**
14942 * Delete the downloads for a video. Available types are `default` and `audio`.
14943 * Defaults to `default` when omitted.
14944 * @param downloadType The download type to delete.
14945 * @returns A promise that resolves when deletion completes.
14946 * @throws {NotFoundError} if the video or downloads are not found
14947 * @throws {InternalError} if an unexpected error occurs
14948 */
14949 delete(downloadType?: StreamDownloadType): Promise<void>;
14950}
14951interface StreamVideos {
14952 /**
14953 * Lists all videos in a users account.
14954 * @returns The list of videos.
14955 * @throws {BadRequestError} if the parameters are invalid
14956 * @throws {InternalError} if an unexpected error occurs
14957 */
14958 list(params?: StreamVideosListParams): Promise<StreamVideo[]>;
14959}
14960interface StreamWatermarks {
14961 /**
14962 * Generate a new watermark profile
14963 * @param input The image stream to upload
14964 * @param params The watermark creation parameters.
14965 * @returns The created watermark profile.
14966 * @throws {BadRequestError} if the parameters are invalid
14967 * @throws {InvalidURLError} if the URL is invalid
14968 * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached
14969 * @throws {InternalError} if an unexpected error occurs
14970 */
14971 generate(input: ReadableStream, params: StreamWatermarkCreateParams): Promise<StreamWatermark>;
14972 /**
14973 * Generate a new watermark profile
14974 * @param url The image url to upload
14975 * @param params The watermark creation parameters.
14976 * @returns The created watermark profile.
14977 * @throws {BadRequestError} if the parameters are invalid
14978 * @throws {InvalidURLError} if the URL is invalid
14979 * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached
14980 * @throws {InternalError} if an unexpected error occurs
14981 */
14982 generate(url: string, params: StreamWatermarkCreateParams): Promise<StreamWatermark>;
14983 /**
14984 * Lists all watermark profiles for an account.
14985 * @returns The list of watermark profiles.
14986 * @throws {InternalError} if an unexpected error occurs
14987 */
14988 list(): Promise<StreamWatermark[]>;
14989 /**
14990 * Retrieves details for a single watermark profile.
14991 * @param watermarkId The watermark profile identifier.
14992 * @returns The watermark profile details.
14993 * @throws {NotFoundError} if the watermark is not found
14994 * @throws {InternalError} if an unexpected error occurs
14995 */
14996 get(watermarkId: string): Promise<StreamWatermark>;
14997 /**
14998 * Deletes a watermark profile.
14999 * @param watermarkId The watermark profile identifier.
15000 * @returns A promise that resolves when deletion completes.
15001 * @throws {NotFoundError} if the watermark is not found
15002 * @throws {InternalError} if an unexpected error occurs
15003 */
15004 delete(watermarkId: string): Promise<void>;
15005}
15006type StreamUpdateVideoParams = {
15007 /**
15008 * Lists the origins allowed to display the video. Enter allowed origin
15009 * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the
15010 * video to be viewed on any origin.
15011 */
15012 allowedOrigins?: Array<string>;
15013 /**
15014 * A user-defined identifier for the media creator.
15015 */
15016 creator?: string;
15017 /**
15018 * The maximum duration in seconds for a video upload. Can be set for a
15019 * video that is not yet uploaded to limit its duration. Uploads that exceed the
15020 * specified duration will fail during processing. A value of `-1` means the value
15021 * is unknown.
15022 */
15023 maxDurationSeconds?: number;
15024 /**
15025 * A user modifiable key-value store used to reference other systems of
15026 * record for managing videos.
15027 */
15028 meta?: Record<string, string>;
15029 /**
15030 * Indicates whether the video can be a accessed using the id. When
15031 * set to `true`, a signed token must be generated with a signing key to view the
15032 * video.
15033 */
15034 requireSignedURLs?: boolean;
15035 /**
15036 * Indicates the date and time at which the video will be deleted. Omit
15037 * the field to indicate no change, or include with a `null` value to remove an
15038 * existing scheduled deletion. If specified, must be at least 30 days from upload
15039 * time.
15040 */
15041 scheduledDeletion?: string | null;
15042 /**
15043 * The timestamp for a thumbnail image calculated as a percentage value
15044 * of the video's duration. To convert from a second-wise timestamp to a
15045 * percentage, divide the desired timestamp by the total duration of the video. If
15046 * this value is not set, the default thumbnail image is taken from 0s of the
15047 * video.
15048 */
15049 thumbnailTimestampPct?: number;
15050};
15051type StreamCaption = {
15052 /**
15053 * Whether the caption was generated via AI.
15054 */
15055 generated?: boolean;
15056 /**
15057 * The language label displayed in the native language to users.
15058 */
15059 label: string;
15060 /**
15061 * The language tag in BCP 47 format.
15062 */
15063 language: string;
15064 /**
15065 * The status of a generated caption.
15066 */
15067 status?: 'ready' | 'inprogress' | 'error';
15068};
15069type StreamDownloadStatus = 'ready' | 'inprogress' | 'error';
15070type StreamDownloadType = 'default' | 'audio';
15071type StreamDownload = {
15072 /**
15073 * Indicates the progress as a percentage between 0 and 100.
15074 */
15075 percentComplete: number;
15076 /**
15077 * The status of a generated download.
15078 */
15079 status: StreamDownloadStatus;
15080 /**
15081 * The URL to access the generated download.
15082 */
15083 url?: string;
15084};
15085/**
15086 * An object with download type keys. Each key is optional and only present if that
15087 * download type has been created.
15088 */
15089type StreamDownloadGetResponse = {
15090 /**
15091 * The audio-only download. Only present if this download type has been created.
15092 */
15093 audio?: StreamDownload;
15094 /**
15095 * The default video download. Only present if this download type has been created.
15096 */
15097 default?: StreamDownload;
15098};
15099type StreamWatermarkPosition = 'upperRight' | 'upperLeft' | 'lowerLeft' | 'lowerRight' | 'center';
15100type StreamWatermark = {
15101 /**
15102 * The unique identifier for a watermark profile.
15103 */
15104 id: string;
15105 /**
15106 * The size of the image in bytes.
15107 */
15108 size: number;
15109 /**
15110 * The height of the image in pixels.
15111 */
15112 height: number;
15113 /**
15114 * The width of the image in pixels.
15115 */
15116 width: number;
15117 /**
15118 * The date and a time a watermark profile was created.
15119 */
15120 created: string;
15121 /**
15122 * The source URL for a downloaded image. If the watermark profile was created via
15123 * direct upload, this field is null.
15124 */
15125 downloadedFrom: string | null;
15126 /**
15127 * A short description of the watermark profile.
15128 */
15129 name: string;
15130 /**
15131 * The translucency of the image. A value of `0.0` makes the image completely
15132 * transparent, and `1.0` makes the image completely opaque. Note that if the image
15133 * is already semi-transparent, setting this to `1.0` will not make the image
15134 * completely opaque.
15135 */
15136 opacity: number;
15137 /**
15138 * The whitespace between the adjacent edges (determined by position) of the video
15139 * and the image. `0.0` indicates no padding, and `1.0` indicates a fully padded
15140 * video width or length, as determined by the algorithm.
15141 */
15142 padding: number;
15143 /**
15144 * The size of the image relative to the overall size of the video. This parameter
15145 * will adapt to horizontal and vertical videos automatically. `0.0` indicates no
15146 * scaling (use the size of the image as-is), and `1.0 `fills the entire video.
15147 */
15148 scale: number;
15149 /**
15150 * The location of the image. Valid positions are: `upperRight`, `upperLeft`,
15151 * `lowerLeft`, `lowerRight`, and `center`. Note that `center` ignores the
15152 * `padding` parameter.
15153 */
15154 position: StreamWatermarkPosition;
15155};
15156type StreamWatermarkCreateParams = {
15157 /**
15158 * A short description of the watermark profile.
15159 */
15160 name?: string;
15161 /**
15162 * The translucency of the image. A value of `0.0` makes the image completely
15163 * transparent, and `1.0` makes the image completely opaque. Note that if the
15164 * image is already semi-transparent, setting this to `1.0` will not make the
15165 * image completely opaque.
15166 */
15167 opacity?: number;
15168 /**
15169 * The whitespace between the adjacent edges (determined by position) of the
15170 * video and the image. `0.0` indicates no padding, and `1.0` indicates a fully
15171 * padded video width or length, as determined by the algorithm.
15172 */
15173 padding?: number;
15174 /**
15175 * The size of the image relative to the overall size of the video. This
15176 * parameter will adapt to horizontal and vertical videos automatically. `0.0`
15177 * indicates no scaling (use the size of the image as-is), and `1.0 `fills the
15178 * entire video.
15179 */
15180 scale?: number;
15181 /**
15182 * The location of the image.
15183 */
15184 position?: StreamWatermarkPosition;
15185};
15186type StreamVideosListParams = {
15187 /**
15188 * The maximum number of videos to return.
15189 */
15190 limit?: number;
15191 /**
15192 * Return videos created before this timestamp.
15193 * (RFC3339/RFC3339Nano)
15194 */
15195 before?: string;
15196 /**
15197 * Comparison operator for the `before` field.
15198 * @default 'lt'
15199 */
15200 beforeComp?: StreamPaginationComparison;
15201 /**
15202 * Return videos created after this timestamp.
15203 * (RFC3339/RFC3339Nano)
15204 */
15205 after?: string;
15206 /**
15207 * Comparison operator for the `after` field.
15208 * @default 'gte'
15209 */
15210 afterComp?: StreamPaginationComparison;
15211};
15212type StreamPaginationComparison = 'eq' | 'gt' | 'gte' | 'lt' | 'lte';
15213/**
15214 * Error object for Stream binding operations.
15215 */
15216interface StreamError extends Error {
15217 readonly code: number;
15218 readonly statusCode: number;
15219 readonly message: string;
15220 readonly stack?: string;
15221}
15222interface InternalError extends StreamError {
15223 name: 'InternalError';
15224}
15225interface BadRequestError extends StreamError {
15226 name: 'BadRequestError';
15227}
15228interface NotFoundError extends StreamError {
15229 name: 'NotFoundError';
15230}
15231interface ForbiddenError extends StreamError {
15232 name: 'ForbiddenError';
15233}
15234interface RateLimitedError extends StreamError {
15235 name: 'RateLimitedError';
15236}
15237interface QuotaReachedError extends StreamError {
15238 name: 'QuotaReachedError';
15239}
15240interface MaxFileSizeError extends StreamError {
15241 name: 'MaxFileSizeError';
15242}
15243interface InvalidURLError extends StreamError {
15244 name: 'InvalidURLError';
15245}
15246interface AlreadyUploadedError extends StreamError {
15247 name: 'AlreadyUploadedError';
15248}
15249interface TooManyWatermarksError extends StreamError {
15250 name: 'TooManyWatermarksError';
15251}
15252type MarkdownDocument = {
15253 name: string;
15254 blob: Blob;
15255};
15256type OutputFormat = 'markdown' | 'text';
15257type ConversionResponse = {
15258 id: string;
15259 name: string;
15260 mimeType: string;
15261 format: OutputFormat;
15262 tokens: number;
15263 data: string;
15264} | {
15265 id: string;
15266 name: string;
15267 mimeType: string;
15268 format: 'error';
15269 error: string;
15270};
15271type ImageConversionOptions = {
15272 descriptionLanguage?: 'en' | 'es' | 'fr' | 'it' | 'pt' | 'de';
15273};
15274type EmbeddedImageConversionOptions = ImageConversionOptions & {
15275 convert?: boolean;
15276 maxConvertedImages?: number;
15277};
15278type ConversionOutputOptions = {
15279 format?: OutputFormat;
15280};
15281type ConversionOptions = {
15282 output?: ConversionOutputOptions;
15283 html?: {
15284 images?: EmbeddedImageConversionOptions & {
15285 convertOGImage?: boolean;
15286 };
15287 hostname?: string;
15288 cssSelector?: string;
15289 };
15290 docx?: {
15291 images?: EmbeddedImageConversionOptions;
15292 };
15293 image?: ImageConversionOptions;
15294 pdf?: {
15295 images?: EmbeddedImageConversionOptions;
15296 metadata?: boolean;
15297 };
15298};
15299type ConversionRequestOptions = {
15300 gateway?: GatewayOptions;
15301 extraHeaders?: object;
15302 conversionOptions?: ConversionOptions;
15303};
15304type SupportedFileFormat = {
15305 mimeType: string;
15306 extension: string;
15307};
15308declare abstract class ToMarkdownService {
15309 transform(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise<ConversionResponse[]>;
15310 transform(files: MarkdownDocument, options?: ConversionRequestOptions): Promise<ConversionResponse>;
15311 supported(): Promise<SupportedFileFormat[]>;
15312}
15313declare namespace TailStream {
15314 interface Header {
15315 readonly name: string;
15316 readonly value: string;
15317 }
15318 interface FetchEventInfo {
15319 readonly type: "fetch";
15320 readonly method: string;
15321 readonly url: string;
15322 readonly cfJson?: object;
15323 readonly headers: Header[];
15324 }
15325 interface JsRpcEventInfo {
15326 readonly type: "jsrpc";
15327 }
15328 interface ScheduledEventInfo {
15329 readonly type: "scheduled";
15330 readonly scheduledTime: Date;
15331 readonly cron: string;
15332 }
15333 interface AlarmEventInfo {
15334 readonly type: "alarm";
15335 readonly scheduledTime: Date;
15336 }
15337 interface QueueEventInfo {
15338 readonly type: "queue";
15339 readonly queueName: string;
15340 readonly batchSize: number;
15341 }
15342 interface EmailEventInfo {
15343 readonly type: "email";
15344 readonly mailFrom: string;
15345 readonly rcptTo: string;
15346 readonly rawSize: number;
15347 }
15348 interface TraceEventInfo {
15349 readonly type: "trace";
15350 readonly traces: (string | null)[];
15351 }
15352 interface HibernatableWebSocketEventInfoMessage {
15353 readonly type: "message";
15354 }
15355 interface HibernatableWebSocketEventInfoError {
15356 readonly type: "error";
15357 }
15358 interface HibernatableWebSocketEventInfoClose {
15359 readonly type: "close";
15360 readonly code: number;
15361 readonly wasClean: boolean;
15362 }
15363 interface HibernatableWebSocketEventInfo {
15364 readonly type: "hibernatableWebSocket";
15365 readonly info: HibernatableWebSocketEventInfoClose | HibernatableWebSocketEventInfoError | HibernatableWebSocketEventInfoMessage;
15366 }
15367 interface CustomEventInfo {
15368 readonly type: "custom";
15369 }
15370 interface FetchResponseInfo {
15371 readonly type: "fetch";
15372 readonly statusCode: number;
15373 }
15374 interface ConnectEventInfo {
15375 readonly type: "connect";
15376 }
15377 type EventOutcome = "ok" | "canceled" | "exception" | "unknown" | "killSwitch" | "daemonDown" | "exceededCpu" | "exceededMemory" | "loadShed" | "responseStreamDisconnected" | "scriptNotFound" | "internalError" | "exceededWallTime" | "aborted";
15378 interface ScriptVersion {
15379 readonly id: string;
15380 readonly tag?: string;
15381 readonly message?: string;
15382 }
15383 interface TracePreviewInfo {
15384 readonly id: string;
15385 readonly slug: string;
15386 readonly name: string;
15387 }
15388 interface Onset {
15389 readonly type: "onset";
15390 readonly attributes: Attribute[];
15391 // id for the span being opened by this Onset event.
15392 readonly spanId: string;
15393 readonly dispatchNamespace?: string;
15394 readonly entrypoint?: string;
15395 readonly executionModel: string;
15396 readonly durableObjectId?: string;
15397 readonly scriptName?: string;
15398 readonly scriptTags?: string[];
15399 readonly scriptVersion?: ScriptVersion;
15400 readonly preview?: TracePreviewInfo;
15401 readonly info: FetchEventInfo | ConnectEventInfo | JsRpcEventInfo | ScheduledEventInfo | AlarmEventInfo | QueueEventInfo | EmailEventInfo | TraceEventInfo | HibernatableWebSocketEventInfo | CustomEventInfo;
15402 }
15403 interface Outcome {
15404 readonly type: "outcome";
15405 readonly outcome: EventOutcome;
15406 readonly cpuTime: number;
15407 readonly wallTime: number;
15408 }
15409 type SpanStatusCode = "unset" | "ok" | "error";
15410 interface SpanStatus {
15411 readonly code: SpanStatusCode;
15412 /** A developer-facing error message, present only when code is "error". */
15413 readonly message?: string;
15414 }
15415 interface SpanOpen {
15416 readonly type: "spanOpen";
15417 readonly name: string;
15418 // id for the span being opened by this SpanOpen event.
15419 readonly spanId: string;
15420 readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes;
15421 }
15422 interface SpanClose {
15423 readonly type: "spanClose";
15424 readonly outcome: EventOutcome;
15425 }
15426 type SpanUpdateInfo = {
15427 readonly type: "name";
15428 readonly name: string;
15429 } | {
15430 readonly type: "status";
15431 readonly status: SpanStatus;
15432 };
15433 interface SpanUpdate {
15434 readonly type: "spanUpdate";
15435 readonly info: SpanUpdateInfo;
15436 }
15437 interface DiagnosticChannelEvent {
15438 readonly type: "diagnosticChannel";
15439 readonly channel: string;
15440 readonly message: any;
15441 }
15442 interface Exception {
15443 readonly type: "exception";
15444 readonly code?: string | number;
15445 readonly name: string;
15446 readonly message: string;
15447 readonly stack?: string;
15448 }
15449 interface TailStreamErrorInfo {
15450 readonly name: string;
15451 readonly message: string;
15452 readonly stack?: string;
15453 }
15454 type Log = {
15455 readonly type: "log";
15456 readonly level: "debug" | "error" | "info" | "log" | "warn";
15457 readonly errorInfo?: readonly (TailStreamErrorInfo | null)[];
15458 } & ({
15459 readonly message: object;
15460 readonly truncated?: false;
15461 } | {
15462 readonly message: string;
15463 readonly truncated: true;
15464 });
15465 interface DroppedEventsDiagnostic {
15466 readonly diagnosticsType: "droppedEvents";
15467 readonly count: number;
15468 }
15469 interface StreamDiagnostic {
15470 readonly type: 'streamDiagnostic';
15471 // To add new diagnostic types, define a new interface and add it to this union type.
15472 readonly diagnostic: DroppedEventsDiagnostic;
15473 }
15474 // This marks the worker handler return information.
15475 // This is separate from Outcome because the worker invocation can live for a long time after
15476 // returning. For example - Websockets that return an http upgrade response but then continue
15477 // streaming information or SSE http connections.
15478 interface Return {
15479 readonly type: "return";
15480 readonly info?: FetchResponseInfo;
15481 }
15482 interface Attribute {
15483 readonly name: string;
15484 readonly value: string | string[] | boolean | boolean[] | number | number[] | bigint | bigint[];
15485 }
15486 interface Attributes {
15487 readonly type: "attributes";
15488 readonly info: Attribute[];
15489 }
15490 type EventType = Onset | Outcome | SpanOpen | SpanClose | SpanUpdate | DiagnosticChannelEvent | Exception | Log | StreamDiagnostic | Return | Attributes;
15491 // Context in which this trace event lives.
15492 interface SpanContext {
15493 // Single id for the entire top-level invocation
15494 // This should be a new traceId for the first worker stage invoked in the eyeball request and then
15495 // same-account service-bindings should reuse the same traceId but cross-account service-bindings
15496 // should use a new traceId.
15497 readonly traceId: string;
15498 // spanId in which this event is handled
15499 // for Onset and SpanOpen events this would be the parent span id
15500 // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events
15501 // For Hibernate and Mark this would be the span under which they were emitted.
15502 // spanId is not set ONLY if:
15503 // 1. This is an Onset event
15504 // 2. We are not inheriting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation)
15505 readonly spanId?: string;
15506 // W3C trace flags from an upstream traceparent. Absent when no upstream
15507 // sampling decision was made.
15508 readonly traceFlags?: number;
15509 }
15510 interface TailEvent<Event extends EventType> {
15511 // invocation id of the currently invoked worker stage.
15512 // invocation id will always be unique to every Onset event and will be the same until the Outcome event.
15513 readonly invocationId: string;
15514 // Inherited spanContext for this event.
15515 readonly spanContext: SpanContext;
15516 readonly timestamp: Date;
15517 readonly sequence: number;
15518 readonly event: Event;
15519 }
15520 type TailEventHandler<Event extends EventType = EventType> = (event: TailEvent<Event>) => void | Promise<void>;
15521 type TailEventHandlerObject = {
15522 outcome?: TailEventHandler<Outcome>;
15523 spanOpen?: TailEventHandler<SpanOpen>;
15524 spanClose?: TailEventHandler<SpanClose>;
15525 spanUpdate?: TailEventHandler<SpanUpdate>;
15526 diagnosticChannel?: TailEventHandler<DiagnosticChannelEvent>;
15527 exception?: TailEventHandler<Exception>;
15528 log?: TailEventHandler<Log>;
15529 return?: TailEventHandler<Return>;
15530 attributes?: TailEventHandler<Attributes>;
15531 };
15532 type TailEventHandlerType = TailEventHandler | TailEventHandlerObject;
15533}
15534// Copyright (c) 2022-2023 Cloudflare, Inc.
15535// Licensed under the Apache 2.0 license found in the LICENSE file or at:
15536// https://opensource.org/licenses/Apache-2.0
15537/**
15538 * Data types supported for holding vector metadata.
15539 */
15540type VectorizeVectorMetadataValue = string | number | boolean | string[];
15541/**
15542 * Additional information to associate with a vector.
15543 */
15544type VectorizeVectorMetadata = VectorizeVectorMetadataValue | Record<string, VectorizeVectorMetadataValue>;
15545type VectorFloatArray = Float32Array | Float64Array;
15546interface VectorizeError {
15547 code?: number;
15548 error: string;
15549}
15550/**
15551 * Comparison logic/operation to use for metadata filtering.
15552 *
15553 * This list is expected to grow as support for more operations are released.
15554 */
15555type VectorizeVectorMetadataFilterOp = '$eq' | '$ne' | '$lt' | '$lte' | '$gt' | '$gte';
15556type VectorizeVectorMetadataFilterCollectionOp = '$in' | '$nin';
15557/**
15558 * Filter criteria for vector metadata used to limit the retrieved query result set.
15559 */
15560type VectorizeVectorMetadataFilter = {
15561 [field: string]: Exclude<VectorizeVectorMetadataValue, string[]> | null | {
15562 [Op in VectorizeVectorMetadataFilterOp]?: Exclude<VectorizeVectorMetadataValue, string[]> | null;
15563 } | {
15564 [Op in VectorizeVectorMetadataFilterCollectionOp]?: Exclude<VectorizeVectorMetadataValue, string[]>[];
15565 };
15566};
15567/**
15568 * Supported distance metrics for an index.
15569 * Distance metrics determine how other "similar" vectors are determined.
15570 */
15571type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product";
15572/**
15573 * Metadata return levels for a Vectorize query.
15574 *
15575 * Default to "none".
15576 *
15577 * @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.
15578 * @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).
15579 * @property none No indexed metadata will be returned.
15580 */
15581type VectorizeMetadataRetrievalLevel = "all" | "indexed" | "none";
15582interface VectorizeQueryOptions {
15583 topK?: number;
15584 namespace?: string;
15585 returnValues?: boolean;
15586 returnMetadata?: boolean | VectorizeMetadataRetrievalLevel;
15587 filter?: VectorizeVectorMetadataFilter;
15588}
15589/**
15590 * Information about the configuration of an index.
15591 */
15592type VectorizeIndexConfig = {
15593 dimensions: number;
15594 metric: VectorizeDistanceMetric;
15595} | {
15596 preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity
15597};
15598/**
15599 * Metadata about an existing index.
15600 *
15601 * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.
15602 * See {@link VectorizeIndexInfo} for its post-beta equivalent.
15603 */
15604interface VectorizeIndexDetails {
15605 /** The unique ID of the index */
15606 readonly id: string;
15607 /** The name of the index. */
15608 name: string;
15609 /** (optional) A human readable description for the index. */
15610 description?: string;
15611 /** The index configuration, including the dimension size and distance metric. */
15612 config: VectorizeIndexConfig;
15613 /** The number of records containing vectors within the index. */
15614 vectorsCount: number;
15615}
15616/**
15617 * Metadata about an existing index.
15618 */
15619interface VectorizeIndexInfo {
15620 /** The number of records containing vectors within the index. */
15621 vectorCount: number;
15622 /** Number of dimensions the index has been configured for. */
15623 dimensions: number;
15624 /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */
15625 processedUpToDatetime: number;
15626 /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */
15627 processedUpToMutation: number;
15628}
15629/**
15630 * Represents a single vector value set along with its associated metadata.
15631 */
15632interface VectorizeVector {
15633 /** 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. */
15634 id: string;
15635 /** The vector values */
15636 values: VectorFloatArray | number[];
15637 /** The namespace this vector belongs to. */
15638 namespace?: string;
15639 /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */
15640 metadata?: Record<string, VectorizeVectorMetadata>;
15641}
15642/**
15643 * Represents a matched vector for a query along with its score and (if specified) the matching vector information.
15644 */
15645type VectorizeMatch = Pick<Partial<VectorizeVector>, "values"> & Omit<VectorizeVector, "values"> & {
15646 /** The score or rank for similarity, when returned as a result */
15647 score: number;
15648};
15649/**
15650 * A set of matching {@link VectorizeMatch} for a particular query.
15651 */
15652interface VectorizeMatches {
15653 matches: VectorizeMatch[];
15654 count: number;
15655}
15656/**
15657 * Results of an operation that performed a mutation on a set of vectors.
15658 * Here, `ids` is a list of vectors that were successfully processed.
15659 *
15660 * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.
15661 * See {@link VectorizeAsyncMutation} for its post-beta equivalent.
15662 */
15663interface VectorizeVectorMutation {
15664 /* List of ids of vectors that were successfully processed. */
15665 ids: string[];
15666 /* Total count of the number of processed vectors. */
15667 count: number;
15668}
15669/**
15670 * Result type indicating a mutation on the Vectorize Index.
15671 * Actual mutations are processed async where the `mutationId` is the unique identifier for the operation.
15672 */
15673interface VectorizeAsyncMutation {
15674 /** The unique identifier for the async mutation operation containing the changeset. */
15675 mutationId: string;
15676}
15677/**
15678 * A Vectorize Vector Search Index for querying vectors/embeddings.
15679 *
15680 * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released.
15681 * See {@link Vectorize} for its new implementation.
15682 */
15683declare abstract class VectorizeIndex {
15684 /**
15685 * Get information about the currently bound index.
15686 * @returns A promise that resolves with information about the current index.
15687 */
15688 public describe(): Promise<VectorizeIndexDetails>;
15689 /**
15690 * Use the provided vector to perform a similarity search across the index.
15691 * @param vector Input vector that will be used to drive the similarity search.
15692 * @param options Configuration options to massage the returned data.
15693 * @returns A promise that resolves with matched and scored vectors.
15694 */
15695 public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise<VectorizeMatches>;
15696 /**
15697 * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown.
15698 * @param vectors List of vectors that will be inserted.
15699 * @returns A promise that resolves with the ids & count of records that were successfully processed.
15700 */
15701 public insert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>;
15702 /**
15703 * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values.
15704 * @param vectors List of vectors that will be upserted.
15705 * @returns A promise that resolves with the ids & count of records that were successfully processed.
15706 */
15707 public upsert(vectors: VectorizeVector[]): Promise<VectorizeVectorMutation>;
15708 /**
15709 * Delete a list of vectors with a matching id.
15710 * @param ids List of vector ids that should be deleted.
15711 * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted).
15712 */
15713 public deleteByIds(ids: string[]): Promise<VectorizeVectorMutation>;
15714 /**
15715 * Get a list of vectors with a matching id.
15716 * @param ids List of vector ids that should be returned.
15717 * @returns A promise that resolves with the raw unscored vectors matching the id set.
15718 */
15719 public getByIds(ids: string[]): Promise<VectorizeVector[]>;
15720}
15721/**
15722 * A Vectorize Vector Search Index for querying vectors/embeddings.
15723 *
15724 * Mutations in this version are async, returning a mutation id.
15725 */
15726declare abstract class Vectorize {
15727 /**
15728 * Get information about the currently bound index.
15729 * @returns A promise that resolves with information about the current index.
15730 */
15731 public describe(): Promise<VectorizeIndexInfo>;
15732 /**
15733 * Use the provided vector to perform a similarity search across the index.
15734 * @param vector Input vector that will be used to drive the similarity search.
15735 * @param options Configuration options to massage the returned data.
15736 * @returns A promise that resolves with matched and scored vectors.
15737 */
15738 public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise<VectorizeMatches>;
15739 /**
15740 * Use the provided vector-id to perform a similarity search across the index.
15741 * @param vectorId Id for a vector in the index against which the index should be queried.
15742 * @param options Configuration options to massage the returned data.
15743 * @returns A promise that resolves with matched and scored vectors.
15744 */
15745 public queryById(vectorId: string, options?: VectorizeQueryOptions): Promise<VectorizeMatches>;
15746 /**
15747 * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown.
15748 * @param vectors List of vectors that will be inserted.
15749 * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset.
15750 */
15751 public insert(vectors: VectorizeVector[]): Promise<VectorizeAsyncMutation>;
15752 /**
15753 * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values.
15754 * @param vectors List of vectors that will be upserted.
15755 * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset.
15756 */
15757 public upsert(vectors: VectorizeVector[]): Promise<VectorizeAsyncMutation>;
15758 /**
15759 * Delete a list of vectors with a matching id.
15760 * @param ids List of vector ids that should be deleted.
15761 * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset.
15762 */
15763 public deleteByIds(ids: string[]): Promise<VectorizeAsyncMutation>;
15764 /**
15765 * Get a list of vectors with a matching id.
15766 * @param ids List of vector ids that should be returned.
15767 * @returns A promise that resolves with the raw unscored vectors matching the id set.
15768 */
15769 public getByIds(ids: string[]): Promise<VectorizeVector[]>;
15770}
15771/**
15772 * The interface for "version_metadata" binding
15773 * providing metadata about the Worker Version using this binding.
15774 */
15775type WorkerVersionMetadata = {
15776 /** The ID of the Worker Version using this binding */
15777 id: string;
15778 /** The tag of the Worker Version using this binding */
15779 tag: string;
15780 /** The timestamp of when the Worker Version was uploaded */
15781 timestamp: string;
15782};
15783// ============ Web Search Request Types ============
15784/**
15785 * Options for a Web Search query.
15786 */
15787type WebSearchSearchOptions = {
15788 /** The search query. */
15789 query: string;
15790 /**
15791 * Maximum number of results to return. Defaults to 10, capped at 20.
15792 * The actual count may be lower if fewer matches exist.
15793 */
15794 limit?: number;
15795};
15796// ============ Web Search Response Types ============
15797/**
15798 * A single Web Search result.
15799 *
15800 * Web Search is discovery-only -- results carry catalog metadata about a page
15801 * but never the page body. To read a result's content the caller invokes the
15802 * global `fetch()` API against the result's `url`, at which point the
15803 * destination's own access controls apply (including Cloudflare Pay-per-Crawl).
15804 */
15805type WebSearchResult = {
15806 /** Canonical URL. */
15807 url: string;
15808 /** Page title. */
15809 title: string;
15810 /** Page-level description. May be absent. */
15811 description?: string;
15812 /**
15813 * Last-modified date for the page, when known. Naive (no timezone)
15814 * ISO-8601 datetime, e.g. `"2025-11-30T04:39:48"`.
15815 */
15816 lastModifiedDate?: string;
15817 /**
15818 * Page meta image URL (typically the `og:image`). May be absent.
15819 */
15820 imageUrl?: string;
15821 /** Optional favicon URL for UI hints. */
15822 faviconUrl?: string;
15823};
15824/**
15825 * Per-response metadata for a Web Search query. Carries operational
15826 * fields useful for support and debugging.
15827 */
15828type WebSearchResponseMetadata = {
15829 /** The query that was executed. */
15830 query: string;
15831 /** Opaque request identifier used for support and debugging. */
15832 requestId: string;
15833 /** End-to-end latency for this search request, in milliseconds. */
15834 latencyMs: number;
15835};
15836/**
15837 * Response from a Web Search query.
15838 */
15839type WebSearchSearchResponse = {
15840 items: WebSearchResult[];
15841 metadata: WebSearchResponseMetadata;
15842};
15843// ============ Web Search Binding Class ============
15844/**
15845 * Cloudflare Web Search binding.
15846 *
15847 * Discovery-only primitive for agents and Workers. Returns URLs and catalog
15848 * metadata for a query; never returns page content or excerpts. To read a
15849 * result's body, fetch the URL with the global `fetch()` API.
15850 *
15851 * Declared in wrangler with a single object (there is exactly one corpus, the
15852 * public web, so there is no name, namespace, or instance to specify):
15853 *
15854 * ```jsonc
15855 * { "web_search": { "binding": "WEBSEARCH" } }
15856 * ```
15857 *
15858 * @example
15859 * ```ts
15860 * const { items, metadata } = await env.WEBSEARCH.search({
15861 * query: "Cloudflare Workers",
15862 * });
15863 *
15864 * const top = items[0];
15865 * console.log(top.url, top.title, metadata.latencyMs);
15866 *
15867 * // Read content yourself; pay-per-crawl and other publisher
15868 * // controls apply at the fetch site, not at search time.
15869 * const page = await fetch(top.url);
15870 * ```
15871 */
15872declare abstract class WebSearch {
15873 /**
15874 * Run a Web Search query.
15875 * @param options Search options. Only `query` is required.
15876 * @returns The matching results plus per-response metadata.
15877 */
15878 search(options: WebSearchSearchOptions): Promise<WebSearchSearchResponse>;
15879}
15880interface DynamicDispatchLimits {
15881 /**
15882 * Limit CPU time in milliseconds.
15883 */
15884 cpuMs?: number;
15885 /**
15886 * Limit number of subrequests.
15887 */
15888 subRequests?: number;
15889}
15890interface DynamicDispatchOptions {
15891 /**
15892 * Limit resources of invoked Worker script.
15893 */
15894 limits?: DynamicDispatchLimits;
15895 /**
15896 * Arguments for outbound Worker script, if configured.
15897 */
15898 outbound?: {
15899 [key: string]: any;
15900 };
15901}
15902interface DispatchNamespace {
15903 /**
15904 * @param name Name of the Worker script.
15905 * @param args Arguments to Worker script.
15906 * @param options Options for Dynamic Dispatch invocation.
15907 * @returns A Fetcher object that allows you to send requests to the Worker script.
15908 * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown.
15909 */
15910 get(name: string, args?: {
15911 [key: string]: any;
15912 }, options?: DynamicDispatchOptions): Fetcher;
15913}
15914declare module 'cloudflare:workflows' {
15915 /**
15916 * NonRetryableError allows for a user to throw a fatal error
15917 * that makes a Workflow instance fail immediately without triggering a retry
15918 */
15919 export class NonRetryableError extends Error {
15920 public constructor(message: string, name?: string);
15921 }
15922}
15923declare abstract class Workflow<PARAMS = unknown> {
15924 /**
15925 * Get a handle to an existing instance of the Workflow.
15926 * @param id Id for the instance of this Workflow
15927 * @returns A promise that resolves with a handle for the Instance
15928 */
15929 public get(id: string): Promise<WorkflowInstance>;
15930 /**
15931 * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown.
15932 * @param options Options when creating an instance including id and params
15933 * @returns A promise that resolves with a handle for the Instance
15934 */
15935 public create(options?: WorkflowInstanceCreateOptions<PARAMS>): Promise<WorkflowInstance>;
15936 /**
15937 * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown.
15938 * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached.
15939 * @param batch List of Options when creating an instance including name and params
15940 * @returns A promise that resolves with a list of handles for the created instances.
15941 */
15942 public createBatch(batch: WorkflowInstanceCreateOptions<PARAMS>[]): Promise<WorkflowInstance[]>;
15943 /**
15944 * Delete a batch of Workflow instances and their stored state.
15945 * `deleteBatch` is limited to 100 instances at a time. Duplicate IDs are deleted once.
15946 * The result contains one entry for each input position; IDs that do not exist are returned as per-instance errors.
15947 * @param instanceIds IDs of the Workflow instances to delete
15948 * @returns A promise that resolves with the successfully deleted instances and any per-instance errors.
15949 */
15950 public deleteBatch(instanceIds: string[]): Promise<WorkflowBatchDeleteResult>;
15951}
15952type WorkflowBatchDeleteResult = {
15953 deleted: {
15954 id: string;
15955 }[];
15956 errors: {
15957 id: string;
15958 code: number;
15959 message: string;
15960 }[];
15961};
15962type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year';
15963type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number;
15964type WorkflowRetentionDuration = WorkflowSleepDuration;
15965/** Geographic regions supported when creating a Workflow instance.
15966 * Location hints are best-effort placement preferences. */
15967type WorkflowInstanceLocationHint = 'wnam' | 'enam' | 'sam' | 'weur' | 'eeur' | 'apac' | 'apac-ne' | 'apac-se' | 'oc' | 'afr' | 'me';
15968interface WorkflowInstanceCreateOptions<PARAMS = unknown> {
15969 /**
15970 * An id for your Workflow instance. Must be unique within the Workflow.
15971 */
15972 id?: string;
15973 /**
15974 * The event payload the Workflow instance is triggered with
15975 */
15976 params?: PARAMS;
15977 /**
15978 * The retention policy for Workflow instance.
15979 * Defaults to the maximum retention period available for the owner's account.
15980 */
15981 retention?: {
15982 successRetention?: WorkflowRetentionDuration;
15983 errorRetention?: WorkflowRetentionDuration;
15984 };
15985 /** A best-effort geographic placement preference for the Workflow instance.
15986 * See `WorkflowInstanceLocationHint` for supported regions. */
15987 locationHint?: WorkflowInstanceLocationHint;
15988}
15989type InstanceStatus = {
15990 status: 'queued' // means that instance is waiting to be started (see concurrency limits)
15991 | 'running' | 'paused' | 'errored' | 'terminated' // user terminated the instance while it was running
15992 | 'complete' | 'waiting' // instance is hibernating and waiting for sleep or event to finish
15993 | 'waitingForPause' // instance is finishing the current work to pause
15994 | 'rollingBack' | 'unknown';
15995 error?: {
15996 name: string;
15997 message: string;
15998 };
15999 output?: unknown;
16000};
16001interface WorkflowError {
16002 code?: number;
16003 message: string;
16004}
16005interface WorkflowInstanceTerminateOptions {
16006 /**
16007 * If true, run registered rollback handlers before terminating the instance.
16008 * Only steps that registered rollback handlers are rolled back.
16009 */
16010 rollback?: boolean;
16011}
16012interface WorkflowInstanceRestartOptions {
16013 /**
16014 * Restart from a specific step. If omitted, the instance restarts from the beginning.
16015 * The step must exist in the instance's execution history.
16016 */
16017 from?: {
16018 /**
16019 * The step name as defined in your workflow code.
16020 */
16021 name: string;
16022 /**
16023 * 1-indexed occurrence of this step name. Use when the same step name appears multiple times (e.g. in a loop).
16024 * @default 1
16025 */
16026 count?: number;
16027 /**
16028 * Step type filter. Use when different step types share the same name.
16029 */
16030 type?: 'do' | 'sleep' | 'waitForEvent';
16031 };
16032}
16033/** An event emitted by a Workflow instance. */
16034type WorkflowInstanceEvent = {
16035 instanceId: string;
16036 eventId: number;
16037 timestamp: number;
16038} & ({
16039 type: 'workflow_queued';
16040} | {
16041 type: 'workflow_started';
16042 params?: unknown;
16043} | {
16044 type: 'workflow_running';
16045} | {
16046 type: 'workflow_paused';
16047} | {
16048 type: 'workflow_waiting_for_pause';
16049} | {
16050 type: 'workflow_waiting';
16051} | {
16052 type: 'workflow_completed';
16053 output?: unknown;
16054} | {
16055 type: 'workflow_errored';
16056 error: {
16057 name: string;
16058 message: string;
16059 };
16060} | {
16061 type: 'workflow_terminated';
16062} | {
16063 type: 'step_started';
16064 stepName: string;
16065 config?: {
16066 retries: {
16067 limit: number;
16068 delay: WorkflowSleepDuration | '[dynamic]';
16069 backoff?: 'constant' | 'linear' | 'exponential';
16070 };
16071 timeout: WorkflowSleepDuration;
16072 sensitive?: 'output';
16073 };
16074} | {
16075 type: 'step_completed';
16076 stepName: string;
16077 output?: unknown;
16078} | {
16079 type: 'step_errored';
16080 stepName: string;
16081} | {
16082 type: 'attempt_started';
16083 stepName: string;
16084 attempt: number;
16085} | {
16086 type: 'attempt_completed';
16087 stepName: string;
16088 attempt: number;
16089} | {
16090 type: 'attempt_errored';
16091 stepName: string;
16092 attempt: number;
16093 retryDelayMs?: number;
16094 error: {
16095 name: string;
16096 message: string;
16097 };
16098} | {
16099 type: 'sleep_started';
16100 stepName: string;
16101 durationMs: number;
16102} | {
16103 type: 'sleep_completed';
16104 stepName: string;
16105} | {
16106 type: 'wait_started';
16107 stepName: string;
16108 eventType: string;
16109} | {
16110 type: 'wait_completed';
16111 stepName: string;
16112} | {
16113 type: 'wait_timed_out';
16114 stepName: string;
16115} | {
16116 type: 'rollback_started';
16117} | {
16118 type: 'rollback_step_started';
16119 stepName: string;
16120 config?: {
16121 retries: {
16122 limit: number;
16123 delay: WorkflowSleepDuration | '[dynamic]';
16124 backoff?: 'constant' | 'linear' | 'exponential';
16125 };
16126 timeout: WorkflowSleepDuration;
16127 sensitive?: 'output';
16128 };
16129} | {
16130 type: 'rollback_step_completed';
16131 stepName: string;
16132} | {
16133 type: 'rollback_step_errored';
16134 stepName: string;
16135 error: {
16136 name: string;
16137 message: string;
16138 };
16139} | {
16140 type: 'rollback_attempt_started';
16141 stepName: string;
16142 attempt: number;
16143} | {
16144 type: 'rollback_attempt_completed';
16145 stepName: string;
16146 attempt: number;
16147} | {
16148 type: 'rollback_attempt_errored';
16149 stepName: string;
16150 attempt: number;
16151 retryDelayMs?: number;
16152 error: {
16153 name: string;
16154 message: string;
16155 };
16156} | {
16157 type: 'rollback_completed';
16158} | {
16159 type: 'rollback_errored';
16160});
16161type WorkflowInstanceEventType = WorkflowInstanceEvent['type'];
16162/** Options available for a Workflow instance subscription. */
16163type WorkflowInstanceSubscribeOptions = {
16164 /** The value from which to start the subscription. */
16165 cursor?: number;
16166 /** The event types to include in the subscription. */
16167 filter?: WorkflowInstanceEventType[];
16168};
16169/** A disposable subscription to a Workflow instance's events. */
16170interface WorkflowInstanceSubscription extends Disposable {
16171 next(): Promise<IteratorResult<WorkflowInstanceEvent, void>>;
16172}
16173declare abstract class WorkflowInstance {
16174 public id: string;
16175 /**
16176 * Pause the instance.
16177 */
16178 public pause(): Promise<void>;
16179 /**
16180 * Resume the instance. If it is already running, an error will be thrown.
16181 */
16182 public resume(): Promise<void>;
16183 /**
16184 * Terminate the instance. If it is errored, terminated or complete, an error will be thrown.
16185 * @param options Options for termination, including whether registered rollback handlers should run.
16186 */
16187 public terminate(options?: WorkflowInstanceTerminateOptions): Promise<void>;
16188 /**
16189 * Restart the instance. Optionally restart from a specific step, preserving
16190 * cached results for all steps before it.
16191 * @param options Options for the restart, including an optional step to restart from.
16192 */
16193 public restart(options?: WorkflowInstanceRestartOptions): Promise<void>;
16194 /**
16195 * Delete the instance and its stored state.
16196 */
16197 public delete(): Promise<void>;
16198 /**
16199 * Returns the current status of the instance.
16200 */
16201 public status(): Promise<InstanceStatus>;
16202 /**
16203 * Send an event to this instance.
16204 */
16205 public sendEvent({ type, payload, }: {
16206 type: string;
16207 payload: unknown;
16208 }): Promise<void>;
16209 /**
16210 * Subscribe to events emitted by this instance.
16211 */
16212 public subscribe(options?: WorkflowInstanceSubscribeOptions): Promise<WorkflowInstanceSubscription>;
16213}