1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-26 16:09:27 -05:00
denoland-deno/cli/dts/lib.deno.shared_globals.d.ts

1535 lines
46 KiB
TypeScript
Raw Normal View History

// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, no-var */
/// <reference no-default-lib="true" />
/// <reference lib="esnext" />
/// <reference lib="deno.web" />
declare namespace WebAssembly {
interface CompileError {
}
var CompileError: {
prototype: CompileError;
new(): CompileError;
};
interface Global {
value: any;
valueOf(): any;
}
var Global: {
prototype: Global;
new(descriptor: GlobalDescriptor, v?: any): Global;
};
interface Instance {
readonly exports: Exports;
}
var Instance: {
prototype: Instance;
new(module: Module, importObject?: Imports): Instance;
};
interface LinkError {
}
var LinkError: {
prototype: LinkError;
new(): LinkError;
};
interface Memory {
readonly buffer: ArrayBuffer;
grow(delta: number): number;
}
var Memory: {
prototype: Memory;
new(descriptor: MemoryDescriptor): Memory;
};
interface Module {
}
var Module: {
prototype: Module;
new(bytes: BufferSource): Module;
customSections(moduleObject: Module, sectionName: string): ArrayBuffer[];
exports(moduleObject: Module): ModuleExportDescriptor[];
imports(moduleObject: Module): ModuleImportDescriptor[];
};
interface RuntimeError {
}
var RuntimeError: {
prototype: RuntimeError;
new(): RuntimeError;
};
interface Table {
readonly length: number;
get(index: number): Function | null;
grow(delta: number): number;
set(index: number, value: Function | null): void;
}
var Table: {
prototype: Table;
new(descriptor: TableDescriptor): Table;
};
interface GlobalDescriptor {
mutable?: boolean;
value: ValueType;
}
interface MemoryDescriptor {
initial: number;
maximum?: number;
}
interface ModuleExportDescriptor {
kind: ImportExportKind;
name: string;
}
interface ModuleImportDescriptor {
kind: ImportExportKind;
module: string;
name: string;
}
interface TableDescriptor {
element: TableKind;
initial: number;
maximum?: number;
}
interface WebAssemblyInstantiatedSource {
instance: Instance;
module: Module;
}
type ImportExportKind = "function" | "global" | "memory" | "table";
type TableKind = "anyfunc";
type ValueType = "f32" | "f64" | "i32" | "i64";
type ExportValue = Function | Global | Memory | Table;
type Exports = Record<string, ExportValue>;
type ImportValue = ExportValue | number;
type ModuleImports = Record<string, ImportValue>;
type Imports = Record<string, ModuleImports>;
function compile(bytes: BufferSource): Promise<Module>;
function compileStreaming(source: Response | Promise<Response>): Promise<Module>;
function instantiate(bytes: BufferSource, importObject?: Imports): Promise<WebAssemblyInstantiatedSource>;
function instantiate(moduleObject: Module, importObject?: Imports): Promise<Instance>;
function instantiateStreaming(response: Response | PromiseLike<Response>, importObject?: Imports): Promise<WebAssemblyInstantiatedSource>;
function validate(bytes: BufferSource): boolean;
}
/** Sets a timer which executes a function once after the timer expires. Returns
* an id which may be used to cancel the timeout.
*
* setTimeout(() => { console.log('hello'); }, 500);
*/
2020-04-07 11:12:31 -04:00
declare function setTimeout(
/** callback function to execute when timer expires */
cb: (...args: any[]) => void,
/** delay in ms */
2020-04-07 11:12:31 -04:00
delay?: number,
/** arguments passed to callback function */
...args: any[]
2020-04-07 11:12:31 -04:00
): number;
/** Repeatedly calls a function , with a fixed time delay between each call.
*
* // Outputs 'hello' to the console every 500ms
* setInterval(() => { console.log('hello'); }, 500);
*/
2020-04-07 11:12:31 -04:00
declare function setInterval(
/** callback function to execute when timer expires */
cb: (...args: any[]) => void,
/** delay in ms */
2020-04-07 11:12:31 -04:00
delay?: number,
/** arguments passed to callback function */
...args: any[]
2020-04-07 11:12:31 -04:00
): number;
/** Cancels a timed, repeating action which was previously started by a call
* to `setInterval()`
*
* const id = setInterval(()= > {console.log('hello');}, 500);
* ...
* clearInterval(id);
*/
2020-04-07 11:12:31 -04:00
declare function clearInterval(id?: number): void;
/** Cancels a scheduled action initiated by `setTimeout()`
*
* const id = setTimeout(()= > {console.log('hello');}, 500);
* ...
* clearTimeout(id);
*/
declare function clearTimeout(id?: number): void;
interface VoidFunction {
(): void;
}
/** A microtask is a short function which is executed after the function or
* module which created it exits and only if the JavaScript execution stack is
* empty, but before returning control to the event loop being used to drive the
* script's execution environment. This event loop may be either the main event
* loop or the event loop driving a web worker.
*
* queueMicrotask(() => { console.log('This event loop stack is complete'); });
*/
declare function queueMicrotask(func: VoidFunction): void;
declare var console: Console;
declare var crypto: Crypto;
/** Registers an event listener in the global scope, which will be called
* synchronously whenever the event `type` is dispatched.
*
* addEventListener('unload', () => { console.log('All finished!'); });
* ...
* dispatchEvent(new Event('unload'));
*/
declare function addEventListener(
type: string,
callback: EventListenerOrEventListenerObject | null,
options?: boolean | AddEventListenerOptions | undefined,
): void;
/** Dispatches an event in the global scope, synchronously invoking any
* registered event listeners for this event in the appropriate order. Returns
* false if event is cancelable and at least one of the event handlers which
* handled this event called Event.preventDefault(). Otherwise it returns true.
*
* dispatchEvent(new Event('unload'));
*/
declare function dispatchEvent(event: Event): boolean;
/** Remove a previously registered event listener from the global scope
*
* const lstnr = () => { console.log('hello'); };
* addEventListener('load', lstnr);
* removeEventListener('load', lstnr);
*/
declare function removeEventListener(
type: string,
callback: EventListenerOrEventListenerObject | null,
options?: boolean | EventListenerOptions | undefined,
): void;
2020-04-10 14:24:42 -04:00
interface DomIterable<K, V> {
keys(): IterableIterator<K>;
values(): IterableIterator<V>;
entries(): IterableIterator<[K, V]>;
[Symbol.iterator](): IterableIterator<[K, V]>;
forEach(
callback: (value: V, key: K, parent: this) => void,
thisArg?: any,
2020-04-10 14:24:42 -04:00
): void;
}
2020-04-10 14:24:42 -04:00
interface ReadableStreamReadDoneResult<T> {
done: true;
value?: T;
}
2020-04-10 14:24:42 -04:00
interface ReadableStreamReadValueResult<T> {
done: false;
value: T;
}
2020-04-10 14:24:42 -04:00
type ReadableStreamReadResult<T> =
| ReadableStreamReadValueResult<T>
| ReadableStreamReadDoneResult<T>;
2020-04-10 14:24:42 -04:00
interface ReadableStreamDefaultReader<R = any> {
readonly closed: Promise<void>;
cancel(reason?: any): Promise<void>;
read(): Promise<ReadableStreamReadResult<R>>;
releaseLock(): void;
}
2020-04-22 10:06:51 -04:00
interface ReadableStreamReader<R = any> {
cancel(): Promise<void>;
read(): Promise<ReadableStreamReadResult<R>>;
releaseLock(): void;
}
interface ReadableByteStreamControllerCallback {
(controller: ReadableByteStreamController): void | PromiseLike<void>;
}
interface UnderlyingByteSource {
autoAllocateChunkSize?: number;
cancel?: ReadableStreamErrorCallback;
pull?: ReadableByteStreamControllerCallback;
start?: ReadableByteStreamControllerCallback;
type: "bytes";
}
2020-04-10 14:24:42 -04:00
interface UnderlyingSource<R = any> {
cancel?: ReadableStreamErrorCallback;
pull?: ReadableStreamDefaultControllerCallback<R>;
start?: ReadableStreamDefaultControllerCallback<R>;
type?: undefined;
}
interface ReadableStreamErrorCallback {
(reason: any): void | PromiseLike<void>;
}
interface ReadableStreamDefaultControllerCallback<R> {
(controller: ReadableStreamDefaultController<R>): void | PromiseLike<void>;
}
2020-04-22 10:06:51 -04:00
interface ReadableStreamDefaultController<R = any> {
readonly desiredSize: number | null;
close(): void;
enqueue(chunk: R): void;
error(error?: any): void;
}
interface ReadableByteStreamController {
readonly byobRequest: undefined;
readonly desiredSize: number | null;
2020-04-10 14:24:42 -04:00
close(): void;
2020-04-22 10:06:51 -04:00
enqueue(chunk: ArrayBufferView): void;
error(error?: any): void;
}
interface PipeOptions {
preventAbort?: boolean;
preventCancel?: boolean;
preventClose?: boolean;
signal?: AbortSignal;
}
interface QueuingStrategySizeCallback<T = any> {
(chunk: T): number;
}
interface QueuingStrategy<T = any> {
highWaterMark?: number;
size?: QueuingStrategySizeCallback<T>;
2020-04-10 14:24:42 -04:00
}
/** This Streams API interface provides a built-in byte length queuing strategy
* that can be used when constructing streams. */
declare class CountQueuingStrategy implements QueuingStrategy {
constructor(options: { highWaterMark: number });
highWaterMark: number;
size(chunk: any): 1;
}
declare class ByteLengthQueuingStrategy
implements QueuingStrategy<ArrayBufferView> {
constructor(options: { highWaterMark: number });
highWaterMark: number;
size(chunk: ArrayBufferView): number;
}
2020-04-10 14:24:42 -04:00
/** This Streams API interface 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. */
interface ReadableStream<R = any> {
readonly locked: boolean;
cancel(reason?: any): Promise<void>;
2020-04-22 10:06:51 -04:00
getIterator(options?: { preventCancel?: boolean }): AsyncIterableIterator<R>;
2020-04-10 14:24:42 -04:00
// getReader(options: { mode: "byob" }): ReadableStreamBYOBReader;
getReader(): ReadableStreamDefaultReader<R>;
2020-04-22 10:06:51 -04:00
pipeThrough<T>(
{
writable,
readable,
}: {
writable: WritableStream<R>;
readable: ReadableStream<T>;
},
options?: PipeOptions,
2020-04-22 10:06:51 -04:00
): ReadableStream<T>;
pipeTo(dest: WritableStream<R>, options?: PipeOptions): Promise<void>;
2020-04-10 14:24:42 -04:00
tee(): [ReadableStream<R>, ReadableStream<R>];
2020-04-22 10:06:51 -04:00
[Symbol.asyncIterator](options?: {
preventCancel?: boolean;
}): AsyncIterableIterator<R>;
2020-04-10 14:24:42 -04:00
}
2020-04-22 10:06:51 -04:00
declare var ReadableStream: {
2020-04-10 14:24:42 -04:00
prototype: ReadableStream;
2020-04-22 10:06:51 -04:00
new (
underlyingSource: UnderlyingByteSource,
strategy?: { highWaterMark?: number; size?: undefined },
2020-04-22 10:06:51 -04:00
): ReadableStream<Uint8Array>;
new <R = any>(
underlyingSource?: UnderlyingSource<R>,
strategy?: QueuingStrategy<R>,
2020-04-22 10:06:51 -04:00
): ReadableStream<R>;
2020-04-10 14:24:42 -04:00
};
interface WritableStreamDefaultControllerCloseCallback {
(): void | PromiseLike<void>;
}
interface WritableStreamDefaultControllerStartCallback {
(controller: WritableStreamDefaultController): void | PromiseLike<void>;
}
interface WritableStreamDefaultControllerWriteCallback<W> {
(chunk: W, controller: WritableStreamDefaultController):
| void
| PromiseLike<
void
>;
}
interface WritableStreamErrorCallback {
(reason: any): void | PromiseLike<void>;
}
interface UnderlyingSink<W = any> {
abort?: WritableStreamErrorCallback;
close?: WritableStreamDefaultControllerCloseCallback;
start?: WritableStreamDefaultControllerStartCallback;
type?: undefined;
write?: WritableStreamDefaultControllerWriteCallback<W>;
}
/** This Streams API interface provides a standard abstraction for writing
* streaming data to a destination, known as a sink. This object comes with
* built-in backpressure and queuing. */
declare class WritableStream<W = any> {
constructor(
underlyingSink?: UnderlyingSink<W>,
strategy?: QueuingStrategy<W>,
);
2020-04-10 14:24:42 -04:00
readonly locked: boolean;
abort(reason?: any): Promise<void>;
close(): Promise<void>;
2020-04-10 14:24:42 -04:00
getWriter(): WritableStreamDefaultWriter<W>;
}
/** This Streams API interface 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. */
interface WritableStreamDefaultController {
error(error?: any): void;
}
/** This Streams API interface 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. */
2020-04-10 14:24:42 -04:00
interface WritableStreamDefaultWriter<W = any> {
readonly closed: Promise<void>;
readonly desiredSize: number | null;
readonly ready: Promise<void>;
abort(reason?: any): Promise<void>;
close(): Promise<void>;
releaseLock(): void;
write(chunk: W): Promise<void>;
}
declare class TransformStream<I = any, O = any> {
constructor(
transformer?: Transformer<I, O>,
writableStrategy?: QueuingStrategy<I>,
readableStrategy?: QueuingStrategy<O>,
);
readonly readable: ReadableStream<O>;
readonly writable: WritableStream<I>;
}
interface TransformStreamDefaultController<O = any> {
readonly desiredSize: number | null;
enqueue(chunk: O): void;
error(reason?: any): void;
terminate(): void;
}
interface Transformer<I = any, O = any> {
flush?: TransformStreamDefaultControllerCallback<O>;
readableType?: undefined;
start?: TransformStreamDefaultControllerCallback<O>;
transform?: TransformStreamDefaultControllerTransformCallback<I, O>;
writableType?: undefined;
}
interface TransformStreamDefaultControllerCallback<O> {
(controller: TransformStreamDefaultController<O>): void | PromiseLike<void>;
}
interface TransformStreamDefaultControllerTransformCallback<I, O> {
(
chunk: I,
controller: TransformStreamDefaultController<O>,
): void | PromiseLike<void>;
}
2020-04-10 14:24:42 -04:00
interface DOMStringList {
/** Returns the number of strings in strings. */
readonly length: number;
/** Returns true if strings contains string, and false otherwise. */
contains(string: string): boolean;
/** Returns the string with index index from strings. */
item(index: number): string | null;
[index: number]: string;
}
type BufferSource = ArrayBufferView | ArrayBuffer;
type BlobPart = BufferSource | Blob | string;
interface BlobPropertyBag {
type?: string;
ending?: "transparent" | "native";
}
/** A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. */
interface Blob {
readonly size: number;
readonly type: string;
arrayBuffer(): Promise<ArrayBuffer>;
slice(start?: number, end?: number, contentType?: string): Blob;
stream(): ReadableStream;
text(): Promise<string>;
}
declare const Blob: {
prototype: Blob;
new (blobParts?: BlobPart[], options?: BlobPropertyBag): Blob;
};
interface FilePropertyBag extends BlobPropertyBag {
lastModified?: number;
}
/** Provides information about files and allows JavaScript in a web page to
* access their content. */
interface File extends Blob {
readonly lastModified: number;
readonly name: string;
}
declare const File: {
prototype: File;
new (fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File;
};
2020-08-11 08:00:53 -04:00
interface FileReaderEventMap {
"abort": ProgressEvent<FileReader>;
"error": ProgressEvent<FileReader>;
"load": ProgressEvent<FileReader>;
"loadend": ProgressEvent<FileReader>;
"loadstart": ProgressEvent<FileReader>;
"progress": ProgressEvent<FileReader>;
}
/** Lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read. */
interface FileReader extends EventTarget {
readonly error: DOMException | null;
onabort: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null;
onerror: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null;
onload: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null;
onloadend: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null;
onloadstart: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null;
onprogress: ((this: FileReader, ev: ProgressEvent<FileReader>) => any) | null;
readonly readyState: number;
readonly result: string | ArrayBuffer | null;
abort(): void;
readAsArrayBuffer(blob: Blob): void;
readAsBinaryString(blob: Blob): void;
readAsDataURL(blob: Blob): void;
readAsText(blob: Blob, encoding?: string): void;
readonly DONE: number;
readonly EMPTY: number;
readonly LOADING: number;
addEventListener<K extends keyof FileReaderEventMap>(type: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
removeEventListener<K extends keyof FileReaderEventMap>(type: K, listener: (this: FileReader, ev: FileReaderEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
}
declare var FileReader: {
prototype: FileReader;
new(): FileReader;
readonly DONE: number;
readonly EMPTY: number;
readonly LOADING: number;
};
declare const isConsoleInstance: unique symbol;
declare class Console {
indentLevel: number;
[isConsoleInstance]: boolean;
/** Writes the arguments to stdout */
log: (...args: unknown[]) => void;
/** Writes the arguments to stdout */
debug: (...args: unknown[]) => void;
/** Writes the arguments to stdout */
info: (...args: unknown[]) => void;
/** Writes the properties of the supplied `obj` to stdout */
dir: (
obj: unknown,
options?: Partial<{
depth: number;
indentLevel: number;
}>,
) => void;
/** 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.
*
* Since we write to stdout, we can't display anything interactive
* we just fall back to `console.dir`.
2020-09-05 10:39:25 -04:00
*
* > [Console.dirxml](https://developer.mozilla.org/en-US/docs/Web/API/Console/dirxml)
* > by Mozilla Contributors is licensed under CC-BY-SA 2.5.
*/
dirxml: (
obj: unknown,
options?: Partial<{
showHidden: boolean;
depth: number;
colors: boolean;
indentLevel: number;
}>,
) => void;
/** Writes the arguments to stdout */
warn: (...args: unknown[]) => void;
/** Writes the arguments to stdout */
error: (...args: unknown[]) => void;
/** Writes an error message to stdout if the assertion is `false`. If the
* assertion is `true`, nothing happens.
*
* ref: https://console.spec.whatwg.org/#assert
*/
assert: (condition?: boolean, ...args: unknown[]) => void;
count: (label?: string) => void;
countReset: (label?: string) => void;
table: (data: unknown, properties?: string[] | undefined) => void;
time: (label?: string) => void;
timeLog: (label?: string, ...args: unknown[]) => void;
timeEnd: (label?: string) => void;
group: (...label: unknown[]) => void;
groupCollapsed: (...label: unknown[]) => void;
groupEnd: () => void;
clear: () => void;
trace: (...args: unknown[]) => void;
static [Symbol.hasInstance](instance: Console): boolean;
}
declare interface Crypto {
readonly subtle: null;
getRandomValues<
T extends
| Int8Array
| Int16Array
| Int32Array
| Uint8Array
| Uint16Array
| Uint32Array
| Uint8ClampedArray
| Float32Array
| Float64Array
| DataView
| null,
>(
array: T,
): T;
}
type FormDataEntryValue = File | string;
/** Provides a way to easily construct a set of key/value pairs representing
* form fields and their values, which can then be easily sent using the
* XMLHttpRequest.send() method. It uses the same format a form would use if the
* encoding type were set to "multipart/form-data". */
2020-04-10 14:24:42 -04:00
interface FormData extends DomIterable<string, FormDataEntryValue> {
append(name: string, value: string | Blob, fileName?: string): void;
delete(name: string): void;
get(name: string): FormDataEntryValue | null;
getAll(name: string): FormDataEntryValue[];
has(name: string): boolean;
set(name: string, value: string | Blob, fileName?: string): void;
}
declare const FormData: {
prototype: FormData;
// TODO(ry) FormData constructor is non-standard.
// new(form?: HTMLFormElement): FormData;
new (): FormData;
};
interface Body {
/** A simple getter used to expose a `ReadableStream` of the body contents. */
readonly body: ReadableStream<Uint8Array> | null;
/** Stores a `Boolean` that declares whether the body has been used in a
* response yet.
*/
readonly bodyUsed: boolean;
/** Takes a `Response` stream and reads it to completion. It returns a promise
* that resolves with an `ArrayBuffer`.
*/
arrayBuffer(): Promise<ArrayBuffer>;
/** Takes a `Response` stream and reads it to completion. It returns a promise
* that resolves with a `Blob`.
*/
blob(): Promise<Blob>;
/** Takes a `Response` stream and reads it to completion. It returns a promise
* that resolves with a `FormData` object.
*/
formData(): Promise<FormData>;
/** Takes a `Response` stream and reads it to completion. It returns a promise
* that resolves with the result of parsing the body text as JSON.
*/
json(): Promise<any>;
/** Takes a `Response` stream and reads it to completion. It returns a promise
* that resolves with a `USVString` (text).
*/
text(): Promise<string>;
}
type HeadersInit = Headers | string[][] | Record<string, string>;
/** This Fetch API interface allows you to perform various actions on HTTP
* request and response headers. These actions include retrieving, setting,
* adding to, and removing. A Headers object has an associated header list,
* which is initially empty and consists of zero or more name and value pairs.
*  You can add to this using methods like append() (see Examples.) In all
* methods of this interface, header names are matched by case-insensitive byte
* sequence. */
interface Headers {
append(name: string, value: string): void;
delete(name: string): void;
get(name: string): string | null;
has(name: string): boolean;
set(name: string, value: string): void;
forEach(
callbackfn: (value: string, key: string, parent: Headers) => void,
thisArg?: any,
): void;
}
2020-04-10 14:24:42 -04:00
interface Headers extends DomIterable<string, string> {
/** Appends a new value onto an existing header inside a `Headers` object, or
* adds the header if it does not already exist.
*/
append(name: string, value: string): void;
/** Deletes a header from a `Headers` object. */
delete(name: string): void;
/** Returns an iterator allowing to go through all key/value pairs
* contained in this Headers object. The both the key and value of each pairs
* are ByteString objects.
*/
entries(): IterableIterator<[string, string]>;
/** Returns a `ByteString` sequence of all the values of a header within a
* `Headers` object with a given name.
*/
get(name: string): string | null;
/** Returns a boolean stating whether a `Headers` object contains a certain
* header.
*/
has(name: string): boolean;
/** Returns an iterator allowing to go through all keys contained in
* this Headers object. The keys are ByteString objects.
*/
keys(): IterableIterator<string>;
/** Sets a new value for an existing header inside a Headers object, or adds
* the header if it does not already exist.
*/
set(name: string, value: string): void;
/** Returns an iterator allowing to go through all values contained in
* this Headers object. The values are ByteString objects.
*/
values(): IterableIterator<string>;
forEach(
callbackfn: (value: string, key: string, parent: this) => void,
thisArg?: any,
): void;
/** The Symbol.iterator well-known symbol specifies the default
* iterator for this Headers object
*/
[Symbol.iterator](): IterableIterator<[string, string]>;
}
declare const Headers: {
prototype: Headers;
new (init?: HeadersInit): Headers;
};
type RequestInfo = Request | string;
type RequestCache =
| "default"
| "force-cache"
| "no-cache"
| "no-store"
| "only-if-cached"
| "reload";
type RequestCredentials = "include" | "omit" | "same-origin";
type RequestMode = "cors" | "navigate" | "no-cors" | "same-origin";
type RequestRedirect = "error" | "follow" | "manual";
type ReferrerPolicy =
| ""
| "no-referrer"
| "no-referrer-when-downgrade"
| "origin"
| "origin-when-cross-origin"
| "same-origin"
| "strict-origin"
| "strict-origin-when-cross-origin"
| "unsafe-url";
type BodyInit =
| Blob
| BufferSource
| FormData
| URLSearchParams
| ReadableStream<Uint8Array>
| string;
type RequestDestination =
| ""
| "audio"
| "audioworklet"
| "document"
| "embed"
| "font"
| "image"
| "manifest"
| "object"
| "paintworklet"
| "report"
| "script"
| "sharedworker"
| "style"
| "track"
| "video"
| "worker"
| "xslt";
interface RequestInit {
/**
* A BodyInit object or null to set request's body.
*/
body?: BodyInit | null;
/**
* A string indicating how the request will interact with the browser's cache
* to set request's cache.
*/
cache?: RequestCache;
/**
* A string indicating whether credentials will be sent with the request
* always, never, or only when sent to a same-origin URL. Sets request's
* credentials.
*/
credentials?: RequestCredentials;
/**
* A Headers object, an object literal, or an array of two-item arrays to set
* request's headers.
*/
headers?: HeadersInit;
/**
* A cryptographic hash of the resource to be fetched by request. Sets
* request's integrity.
*/
integrity?: string;
/**
* A boolean to set request's keepalive.
*/
keepalive?: boolean;
/**
* A string to set request's method.
*/
method?: string;
/**
* A string to indicate whether the request will use CORS, or will be
* restricted to same-origin URLs. Sets request's mode.
*/
mode?: RequestMode;
/**
* 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.
*/
redirect?: RequestRedirect;
/**
* A string whose value is a same-origin URL, "about:client", or the empty
* string, to set request's referrer.
*/
referrer?: string;
/**
* A referrer policy to set request's referrerPolicy.
*/
referrerPolicy?: ReferrerPolicy;
/**
* An AbortSignal to set request's signal.
*/
signal?: AbortSignal | null;
/**
* Can only be null. Used to disassociate request from any Window.
*/
window?: any;
}
/** This Fetch API interface represents a resource request. */
interface Request extends Body {
/**
* Returns the cache mode associated with request, which is a string
* indicating how the request will interact with the browser's cache when
* fetching.
*/
readonly cache: RequestCache;
/**
* Returns the credentials mode associated with request, which is a string
* indicating whether credentials will be sent with the request always, never,
* or only when sent to a same-origin URL.
*/
readonly credentials: RequestCredentials;
/**
* Returns the kind of resource requested by request, e.g., "document" or "script".
*/
readonly destination: RequestDestination;
/**
* Returns a Headers object consisting of the headers associated with request.
* Note that headers added in the network layer by the user agent will not be
* accounted for in this object, e.g., the "Host" header.
*/
readonly headers: Headers;
/**
* Returns request's subresource integrity metadata, which is a cryptographic
* hash of the resource being fetched. Its value consists of multiple hashes
* separated by whitespace. [SRI]
*/
readonly integrity: string;
/**
* Returns a boolean indicating whether or not request is for a history
2020-05-14 02:58:48 -04:00
* navigation (a.k.a. back-forward navigation).
*/
readonly isHistoryNavigation: boolean;
/**
* Returns a boolean indicating whether or not request is for a reload
* navigation.
*/
readonly isReloadNavigation: boolean;
/**
* Returns a boolean indicating whether or not request can outlive the global
* in which it was created.
*/
readonly keepalive: boolean;
/**
* Returns request's HTTP method, which is "GET" by default.
*/
readonly method: string;
/**
* Returns the mode associated with request, which is a string indicating
* whether the request will use CORS, or will be restricted to same-origin
* URLs.
*/
readonly mode: RequestMode;
/**
* Returns the redirect mode associated with request, which is a string
* indicating how redirects for the request will be handled during fetching. A
* request will follow redirects by default.
*/
readonly redirect: RequestRedirect;
/**
* Returns the referrer of request. Its value can be a same-origin URL if
* explicitly set in init, the empty string to indicate no referrer, and
* "about:client" when defaulting to the global's default. This is used during
* fetching to determine the value of the `Referer` header of the request
* being made.
*/
readonly referrer: string;
/**
* Returns the referrer policy associated with request. This is used during
* fetching to compute the value of the request's referrer.
*/
readonly referrerPolicy: ReferrerPolicy;
/**
* Returns the signal associated with request, which is an AbortSignal object
* indicating whether or not request has been aborted, and its abort event
* handler.
*/
readonly signal: AbortSignal;
/**
* Returns the URL of request as a string.
*/
readonly url: string;
clone(): Request;
}
declare const Request: {
prototype: Request;
new (input: RequestInfo, init?: RequestInit): Request;
};
interface ResponseInit {
headers?: HeadersInit;
status?: number;
statusText?: string;
}
type ResponseType =
| "basic"
| "cors"
| "default"
| "error"
| "opaque"
| "opaqueredirect";
/** This Fetch API interface represents the response to a request. */
interface Response extends Body {
readonly headers: Headers;
readonly ok: boolean;
readonly redirected: boolean;
readonly status: number;
readonly statusText: string;
readonly trailer: Promise<Headers>;
readonly type: ResponseType;
readonly url: string;
clone(): Response;
}
declare const Response: {
prototype: Response;
new (body?: BodyInit | null, init?: ResponseInit): Response;
error(): Response;
redirect(url: string, status?: number): Response;
};
/** Fetch a resource from the network. It returns a Promise that resolves to the
* Response to that request, whether it is successful or not.
*
* const response = await fetch("http://my.json.host/data.json");
* console.log(response.status); // e.g. 200
* console.log(response.statusText); // e.g. "OK"
* const jsonData = await response.json();
*/
declare function fetch(
input: Request | URL | string,
init?: RequestInit,
): Promise<Response>;
2020-04-07 17:11:38 -04:00
interface URLSearchParams {
/** Appends a specified key/value pair as a new search parameter.
*
* ```ts
* let searchParams = new URLSearchParams();
* searchParams.append('name', 'first');
* searchParams.append('name', 'second');
* ```
2020-04-07 17:11:38 -04:00
*/
append(name: string, value: string): void;
2020-04-07 17:11:38 -04:00
/** Deletes the given search parameter and its associated value,
* from the list of all search parameters.
*
* ```ts
* let searchParams = new URLSearchParams([['name', 'value']]);
* searchParams.delete('name');
* ```
2020-04-07 17:11:38 -04:00
*/
delete(name: string): void;
2020-04-07 17:11:38 -04:00
/** Returns all the values associated with a given search parameter
* as an array.
*
* ```ts
* searchParams.getAll('name');
* ```
2020-04-07 17:11:38 -04:00
*/
getAll(name: string): string[];
2020-04-07 17:11:38 -04:00
/** Returns the first value associated to the given search parameter.
*
* ```ts
* searchParams.get('name');
* ```
2020-04-07 17:11:38 -04:00
*/
get(name: string): string | null;
2020-04-07 17:11:38 -04:00
/** Returns a Boolean that indicates whether a parameter with the
* specified name exists.
*
* ```ts
* searchParams.has('name');
* ```
2020-04-07 17:11:38 -04:00
*/
has(name: string): boolean;
2020-04-07 17:11:38 -04:00
/** 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.
*
* ```ts
* searchParams.set('name', 'value');
* ```
2020-04-07 17:11:38 -04:00
*/
set(name: string, value: string): void;
2020-04-07 17:11:38 -04:00
/** Sort all key/value pairs contained in this object in place and
* return undefined. The sort order is according to Unicode code
* points of the keys.
*
* ```ts
* searchParams.sort();
* ```
2020-04-07 17:11:38 -04:00
*/
sort(): void;
2020-04-07 17:11:38 -04:00
/** Calls a function for each element contained in this object in
* place and return undefined. Optionally accepts an object to use
* as this when executing callback as second argument.
*
* ```ts
* const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
* params.forEach((value, key, parent) => {
* console.log(value, key, parent);
* });
* ```
2020-04-07 17:11:38 -04:00
*
*/
forEach(
callbackfn: (value: string, key: string, parent: this) => void,
thisArg?: any,
2020-04-07 17:11:38 -04:00
): void;
2020-04-07 17:11:38 -04:00
/** Returns an iterator allowing to go through all keys contained
* in this object.
*
* ```ts
* const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
* for (const key of params.keys()) {
* console.log(key);
* }
* ```
2020-04-07 17:11:38 -04:00
*/
keys(): IterableIterator<string>;
2020-04-07 17:11:38 -04:00
/** Returns an iterator allowing to go through all values contained
* in this object.
*
* ```ts
* const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
* for (const value of params.values()) {
* console.log(value);
* }
* ```
2020-04-07 17:11:38 -04:00
*/
values(): IterableIterator<string>;
2020-04-07 17:11:38 -04:00
/** Returns an iterator allowing to go through all key/value
* pairs contained in this object.
*
* ```ts
* const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
* for (const [key, value] of params.entries()) {
* console.log(key, value);
* }
* ```
2020-04-07 17:11:38 -04:00
*/
entries(): IterableIterator<[string, string]>;
2020-04-07 17:11:38 -04:00
/** Returns an iterator allowing to go through all key/value
* pairs contained in this object.
*
* ```ts
* const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
* for (const [key, value] of params) {
* console.log(key, value);
* }
* ```
2020-04-07 17:11:38 -04:00
*/
[Symbol.iterator](): IterableIterator<[string, string]>;
2020-04-07 17:11:38 -04:00
/** Returns a query string suitable for use in a URL.
*
* ```ts
* searchParams.toString();
* ```
2020-04-07 17:11:38 -04:00
*/
toString(): string;
}
2020-04-07 17:11:38 -04:00
declare const URLSearchParams: {
prototype: URLSearchParams;
new (
init?: string[][] | Record<string, string> | string | URLSearchParams,
2020-04-07 17:11:38 -04:00
): URLSearchParams;
toString(): string;
};
/** The URL interface represents an object providing static methods used for creating object URLs. */
interface URL {
hash: string;
host: string;
hostname: string;
href: string;
toString(): string;
readonly origin: string;
password: string;
pathname: string;
port: string;
protocol: string;
search: string;
readonly searchParams: URLSearchParams;
username: string;
toJSON(): string;
}
2020-04-07 17:11:38 -04:00
declare const URL: {
prototype: URL;
new (url: string, base?: string | URL): URL;
2020-04-07 17:11:38 -04:00
createObjectURL(object: any): string;
revokeObjectURL(url: string): void;
};
interface MessageEventInit extends EventInit {
data?: any;
origin?: string;
lastEventId?: string;
}
declare class MessageEvent extends Event {
readonly data: any;
readonly origin: string;
readonly lastEventId: string;
constructor(type: string, eventInitDict?: MessageEventInit);
}
interface ErrorEventInit extends EventInit {
message?: string;
filename?: string;
lineno?: number;
colno?: number;
error?: any;
}
declare class ErrorEvent extends Event {
readonly message: string;
readonly filename: string;
readonly lineno: number;
readonly colno: number;
readonly error: any;
constructor(type: string, eventInitDict?: ErrorEventInit);
}
interface PostMessageOptions {
transfer?: any[];
}
2020-08-11 08:00:53 -04:00
interface ProgressEventInit extends EventInit {
lengthComputable?: boolean;
loaded?: number;
total?: number;
}
declare class Worker extends EventTarget {
onerror?: (e: ErrorEvent) => void;
onmessage?: (e: MessageEvent) => void;
onmessageerror?: (e: MessageEvent) => void;
2020-04-07 15:03:14 -04:00
constructor(
specifier: string,
options?: {
type?: "classic" | "module";
name?: string;
/** UNSTABLE: New API. Expect many changes; most likely this
* field will be made into an object for more granular
* configuration of worker thread (permissions, import map, etc.).
*
* Set to `true` to make `Deno` namespace and all of its methods
* available to worker thread.
*
* Currently worker inherits permissions from main thread (permissions
* given using `--allow-*` flags).
* Configurable permissions are on the roadmap to be implemented.
*
* Example:
*
* ```ts
* // mod.ts
* const worker = new Worker(
* new URL("deno_worker.ts", import.meta.url).href,
* { type: "module", deno: true }
* );
* worker.postMessage({ cmd: "readFile", fileName: "./log.txt" });
*
* // deno_worker.ts
*
*
* self.onmessage = async function (e) {
* const { cmd, fileName } = e.data;
* if (cmd !== "readFile") {
* throw new Error("Invalid command");
* }
* const buf = await Deno.readFile(fileName);
* const fileContents = new TextDecoder().decode(buf);
* console.log(fileContents);
* }
* ```
*
* // log.txt
* hello world
* hello world 2
*
* // run program
* $ deno run --allow-read mod.ts
* hello world
* hello world2
*
*/
deno?: boolean;
},
2020-04-07 15:03:14 -04:00
);
postMessage(message: any, transfer: ArrayBuffer[]): void;
postMessage(message: any, options?: PostMessageOptions): void;
2020-04-07 15:03:14 -04:00
terminate(): void;
}
declare type PerformanceEntryList = PerformanceEntry[];
declare interface Performance {
/** Removes the stored timestamp with the associated name. */
clearMarks(markName?: string): void;
/** Removes stored timestamp with the associated name. */
clearMeasures(measureName?: string): void;
getEntries(): PerformanceEntryList;
getEntriesByName(name: string, type?: string): PerformanceEntryList;
getEntriesByType(type: string): PerformanceEntryList;
/** Stores a timestamp with the associated name (a "mark"). */
mark(markName: string, options?: PerformanceMarkOptions): PerformanceMark;
/** Stores the `DOMHighResTimeStamp` duration between two marks along with the
* associated name (a "measure"). */
measure(
measureName: string,
options?: PerformanceMeasureOptions,
): PerformanceMeasure;
/** Stores the `DOMHighResTimeStamp` duration between two marks along with the
* associated name (a "measure"). */
measure(
measureName: string,
startMark?: string,
endMark?: string,
): PerformanceMeasure;
/** Returns a current time from Deno's start in milliseconds.
*
* Use the permission flag `--allow-hrtime` return a precise value.
*
* ```ts
* const t = performance.now();
* console.log(`${t} ms since start!`);
* ```
*/
now(): number;
}
declare const Performance: {
prototype: Performance;
new (): Performance;
};
declare const performance: Performance;
declare interface PerformanceMarkOptions {
/** Metadata to be included in the mark. */
detail?: any;
/** Timestamp to be used as the mark time. */
startTime?: number;
}
declare interface PerformanceMeasureOptions {
/** Metadata to be included in the measure. */
detail?: any;
/** Timestamp to be used as the start time or string to be used as start
* mark.*/
start?: string | number;
/** Duration between the start and end times. */
duration?: number;
/** Timestamp to be used as the end time or string to be used as end mark. */
end?: string | number;
}
/** Encapsulates a single performance metric that is part of the performance
* timeline. A performance entry can be directly created by making a performance
* mark or measure (for example by calling the `.mark()` method) at an explicit
* point in an application. */
declare class PerformanceEntry {
readonly duration: number;
readonly entryType: string;
readonly name: string;
readonly startTime: number;
toJSON(): any;
}
/** `PerformanceMark` is an abstract interface for `PerformanceEntry` objects
* with an entryType of `"mark"`. Entries of this type are created by calling
* `performance.mark()` to add a named `DOMHighResTimeStamp` (the mark) to the
* performance timeline. */
declare class PerformanceMark extends PerformanceEntry {
readonly detail: any;
readonly entryType: "mark";
constructor(name: string, options?: PerformanceMarkOptions);
}
/** `PerformanceMeasure` is an abstract interface for `PerformanceEntry` objects
* with an entryType of `"measure"`. Entries of this type are created by calling
* `performance.measure()` to add a named `DOMHighResTimeStamp` (the measure)
* between two marks to the performance timeline. */
declare class PerformanceMeasure extends PerformanceEntry {
readonly detail: any;
readonly entryType: "measure";
}
/** Events measuring progress of an underlying process, like an HTTP request
* (for an XMLHttpRequest, or the loading of the underlying resource of an
* <img>, <audio>, <video>, <style> or <link>). */
interface ProgressEvent<T extends EventTarget = EventTarget> extends Event {
readonly lengthComputable: boolean;
readonly loaded: number;
readonly target: T | null;
readonly total: number;
}
2020-08-11 08:00:53 -04:00
declare var ProgressEvent: {
prototype: ProgressEvent;
new(type:string, eventInitDict?: ProgressEventInit): ProgressEvent;
};
interface CustomEventInit<T = any> extends EventInit {
detail?: T;
}
declare class CustomEvent<T = any> extends Event {
constructor(typeArg: string, eventInitDict?: CustomEventInit<T>);
/** Returns any custom data event was created with. Typically used for
* synthetic events. */
readonly detail: T;
}
interface ErrorConstructor {
/** See https://v8.dev/docs/stack-trace-api#stack-trace-collection-for-custom-exceptions. */
// eslint-disable-next-line @typescript-eslint/ban-types
captureStackTrace(error: Object, constructor?: Function): void;
// TODO(nayeemrmn): Support `Error.prepareStackTrace()`. We currently use this
// internally in a way that makes it unavailable for users.
}
2020-09-05 10:39:25 -04:00
interface CloseEventInit extends EventInit {
code?: number;
reason?: string;
wasClean?: boolean;
}
interface CloseEvent extends Event {
/**
* Returns the WebSocket connection close code provided by the server.
*/
readonly code: number;
/**
* Returns the WebSocket connection close reason provided by the server.
*/
readonly reason: string;
/**
* Returns true if the connection closed cleanly; false otherwise.
*/
readonly wasClean: boolean;
}
declare var CloseEvent: {
prototype: CloseEvent;
new(type: string, eventInitDict?: CloseEventInit): CloseEvent;
};
interface WebSocketEventMap {
"close": CloseEvent;
"error": Event;
"message": MessageEvent;
"open": Event;
}
/** Provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. */
interface WebSocket extends EventTarget {
/**
* Returns a string that indicates how binary data from the WebSocket object is exposed to scripts:
*
* Can be set, to change how binary data is returned. The default is "blob".
*/
binaryType: BinaryType;
/**
* Returns the number of bytes of application data (UTF-8 text and binary data) that have been queued using send() but not yet been transmitted to the network.
*
* If the WebSocket connection is closed, this attribute's value will only increase with each call to the send() method. (The number does not reset to zero once the connection closes.)
*/
readonly bufferedAmount: number;
/**
* Returns the extensions selected by the server, if any.
*/
readonly extensions: string;
onclose: ((this: WebSocket, ev: CloseEvent) => any) | null;
onerror: ((this: WebSocket, ev: Event) => any) | null;
onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null;
onopen: ((this: WebSocket, ev: Event) => any) | null;
/**
* Returns the subprotocol selected by the server, if any. It can be used in conjunction with the array form of the constructor's second argument to perform subprotocol negotiation.
*/
readonly protocol: string;
/**
* Returns the state of the WebSocket object's connection. It can have the values described below.
*/
readonly readyState: number;
/**
* Returns the URL that was used to establish the WebSocket connection.
*/
readonly url: string;
/**
* Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason.
*/
close(code?: number, reason?: string): void;
/**
* Transmits data using the WebSocket connection. data can be a string, a Blob, an ArrayBuffer, or an ArrayBufferView.
*/
send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void;
readonly CLOSED: number;
readonly CLOSING: number;
readonly CONNECTING: number;
readonly OPEN: number;
addEventListener<K extends keyof WebSocketEventMap>(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void;
removeEventListener<K extends keyof WebSocketEventMap>(type: K, listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, options?: boolean | EventListenerOptions): void;
removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void;
}
declare var WebSocket: {
prototype: WebSocket;
new(url: string, protocols?: string | string[]): WebSocket;
readonly CLOSED: number;
readonly CLOSING: number;
readonly CONNECTING: number;
readonly OPEN: number;
};
type BinaryType = "arraybuffer" | "blob";