declare namespace console {
    export function log(...args: any[]): void;
    export function trace(...args: any[]): void;
    export function debug(...args: any[]): void;
    export function info(...args: any[]): void;
    export function warn(...args: any[]): void;
    export function error(...args: any[]): void;
    export function assert(condition: boolean, message?: string, ...args: any[]): void;
    export function count(label?: any): void;
    export function countReset(label?: any): void;
    export function time(label?: any): void;
    export function timeLog(label?: any): void;
    export function timeEnd(label?: any): void;
    export function group(...args: any[]): void;
    export function groupCollapsed(...args: any[]): void;
    export function groupEnd(): void;
}

declare const crypto: Crypto;

declare const window: {
    crypto: Crypto;
};

declare namespace performance {
    export function now(): number;
}

declare function btoa(text: string): string;
declare function atob(text: string): string;
declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): number;
declare function clearTimeout(timeoutId: number): void;
declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): number;
declare function clearInterval(intervalId: number): void;
declare function fetch<T = any>(url: string, options?: RequestInit): Promise<Response<T>>;

declare class ServiceError extends Error {
    public name: string;
    public errorCode?: number;
    public service?: string;

    constructor(errorCode?: number, message?: string, service?: string);

    public set(errorCode: number, message: string): void;
    public setService(service: string): void;
}

interface Crypto {
    getRandomValues<T extends Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray>(array: T): T;
    subtle: CryptoSubtle;
}

interface CryptoSubtle {
    generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKeyPair>;
    generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
    generateKey(algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKeyPair | CryptoKey>;
    exportKey(format: "jwk", key: CryptoKey): Promise<JsonWebKey>;
    exportKey(format: "raw" | "pkcs8" | "spki", key: CryptoKey): Promise<ArrayBuffer>;
    importKey(format: "jwk", keyData: JsonWebKey, algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
    importKey(format: "raw" | "pkcs8" | "spki", keyData: ArrayBufferView | ArrayBuffer, algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
    sign(algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, key: CryptoKey, data: ArrayBufferView | ArrayBuffer): Promise<ArrayBuffer>;
    verify(algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, key: CryptoKey, signature: ArrayBufferView | ArrayBuffer, data: ArrayBufferView | ArrayBuffer): Promise<boolean>;
}

declare class Body<T = any> {
    body: Blob | ArrayBuffer | FormData | string | null;
    bodyUsed: boolean;

    constructor(body?: Blob | ArrayBuffer | FormData | string | null);
    arrayBuffer(): Promise<ArrayBuffer>;
    blob(): Promise<Blob>;
    formData(): Promise<FormData>;
    text(): Promise<string>;
    json<J = T>(): Promise<J>;
}

interface RequestOptions {
    body?: Blob | ArrayBuffer | FormData | string | null;
    headers?: Headers;
    method?: string;
}

declare class Request<T = any> extends Body<T> {
    headers: Headers;
    method: string;
    url: string;

    constructor(input: Request | string, options?: RequestOptions)

    clone(): Request<T>;
}

interface ResponseOptions {
    status?: number;
    statusText?: string;
    headers?: Headers | Record<string, string>;
}

declare class Response<T = any> extends Body<T> {
    headers: Headers;
    ok: boolean;
    redirected: boolean;
    status: number;
    statusText: string;
    type: string;
    url: string;

    constructor(body?: Blob | ArrayBuffer | FormData | string | null, options?: ResponseOptions);

    clone(): Response<T>;
}

interface RequestInit {
    method?: string;
    headers?: FetchHeadersInit;
    body?: FetchBodyInit;
    agent?: FetchAgentInit;
}

interface FetchError {
    message: string;
}

interface BlobOptions {
    type: string;
    endings: string;
}

declare class Headers implements Iterable<[string, string]> {
    constructor(init?: FetchHeadersInit);
    forEach(callback: (value: string, name: string) => void): void;
    append(name: string, value: string): void;
    delete(name: string): void;
    get(name: string): string | null;
    getAll(name: string): string[];
    has(name: string): boolean;
    raw(): { [k: string]: string[]; };
    set(name: string, value: string): void;

    entries(): Iterator<[string, string]>;
    keys(): Iterator<string>;
    values(): Iterator<string>;
    [Symbol.iterator](): Iterator<[string, string]>;
}

declare class Blob {
    constructor(chunks: Array<string | ArrayBuffer | ArrayBufferView | Blob>, options?: BlobOptions);
    arrayBuffer(): Promise<ArrayBuffer>;
    arrayBufferSync(): ArrayBuffer;
    text(): Promise<string>;
    textSync(): string;
    slice(start: number, end: number, type: string): Blob;
}

declare class FormData {
    append(name: string, value: string | Blob, filename?: string): void;
    delete(name: string): void;
    entries(): Iterator<any[]>;
    getBlob(): Blob;
    get(name: string): string | Blob; // Per spec it should return File instead of Blob, but currently we don't have a polyfill for File
    getAll(): Array<string | Blob>; // Same where with the Blob
    has(name: string): boolean;
    keys(): Iterator<string>;
    set(name: string, value: string | Blob, filename?: string): void;
    values(): Iterator<string | Blob>;
}

declare class URL {
    constructor(input: string | URL, base?: string | URL);
    hash: string;
    host: string;
    hostname: string;
    href: string;
    readonly origin: string;
    password: string;
    pathname: string;
    port: string;
    protocol: string;
    search: string;
    readonly searchParams: URLSearchParams;
    username: string;
    toString(): string;
    toJSON(): string;
    static canParse(url: string | URL, base?: string): boolean;
}

declare class URLSearchParams implements Iterable<[string, string]> {
    constructor(init?: URLSearchParams | string | { [key: string]: string | string[] | undefined; } | Iterable<[string, string]> | Array<[string, string]>);
    append(name: string, value: string): void;
    delete(name: string): void;
    entries(): IterableIterator<[string, string]>;
    forEach(callback: (value: string, name: string, searchParams: this) => void): void;
    get(name: string): string | null;
    getAll(name: string): string[];
    has(name: string): boolean;
    keys(): IterableIterator<string>;
    set(name: string, value: string): void;
    sort(): void;
    toString(): string;
    values(): IterableIterator<string>;
    [Symbol.iterator](): IterableIterator<[string, string]>;
}

type FetchHeadersInit = Headers | string[][] | { [key: string]: string; };
type FetchBodyInit = FormData | ArrayBuffer | ArrayBufferView | string; // TODO: add URLSearchParams
type FetchAgentInit = {
    /**
     * If true the server will reject any connection which is not
     * authorized with the list of supplied CAs.
     */
    rejectUnauthorized?: boolean;
    /**
     * Private keys in PEM format. PEM allows the option of private keys
     * being encrypted. Encrypted keys will be decrypted with passphrase.
     */
    key?: string | ArrayBuffer | (string | ArrayBuffer)[];
    /**
     *  Cert chains in PEM format. One cert chain should be provided per
     *  private key. Each cert chain should consist of the PEM formatted
     *  certificate for a provided private key, followed by the PEM
     *  formatted intermediate certificates (if any), in order, and not
     *  including the root CA (the root CA must be pre-known to the peer,
     *  see ca). When providing multiple cert chains, they do not have to
     *  be in the same order as their private keys in key. If the
     *  intermediate certificates are not provided, the peer will not be
     *  able to validate the certificate, and the handshake will fail.
     */
    cert?: string | ArrayBuffer | (string | ArrayBuffer)[];
    /**
     * Optionally override the trusted CA certificates. Default is to trust
     * the well-known CAs curated by Mozilla. Mozilla's CAs are completely
     * replaced when CAs are explicitly specified using this option.
     */
    ca?: string | ArrayBuffer | (string | ArrayBuffer)[];
    /**
     * Shared passphrase used for a single private key.
     */
    passphrase?: string;
};

interface Context<EV = any> {
    /**
     * Start time in UNIX time (milliseconds) indicating when the invocation started.
     */
    readonly startTime: number;

    /**
     * Timeout in milliseconds for how long the invocation can run.
     */
    readonly timeout: number;

    /**
     * Memory in MBs that is available for the invocation.
     */
    readonly availableMemory: number;

    /**
     * Unique identifier of the invocation.
     */
    readonly invocationId: string;

    /**
     * * Environment information where the invocation is running.
     */
    readonly environment: {
        /**
         * Environment unique ID.
         */
        readonly uid: string;
        /**
         * Environment name.
         */
        readonly name: string;
        /**
         * Environment variables.
         */
        readonly vars: EV;
    };

    /**
     * Deployment version and label of the invocation.
     */
    readonly deployment?: {
        /**
         * Deployment unique ID.
         */
        readonly uid: string;

        /**
         * Deployment version.
         */
        readonly version: string;

        /**
         * Deployment label, if available.
         */
        readonly label?: string;
    };

    /**
     * How the original invocation was triggered. Original invocation in this context means if the script was programmatically triggered, then this property indicates the trigger type of the original invocation. 
     * If the script was not programmatically triggered then this value remains the same as the `triggerType` property.
     * 
     * * EXTERNAL - Script was triggered via Event Listener in a response to external event.
     * * MANUAL - Script was triggered manually.
     * * SCHEDULED - Script was triggered via Scheduled Trigger.
     * * MANUAL_EVENT_LISTENER - Script was triggered manually via Event Listener with a test payload.
     */
    readonly rootTriggerType: 'EXTERNAL' | 'MANUAL' | 'SCHEDULED' | 'MANUAL_EVENT_LISTENER';

    /**
     * How the script was triggered:
     * 
     * * EXTERNAL - Script was triggered via Event Listener as a response to external event being emitted.
     * * MANUAL - Script was triggered manually.
     * * SCHEDULED - Script was triggered via Scheduled Trigger.
     * * MANUAL_EVENT_LISTENER - Script was triggered manually via Event Listener with a test payload.
     * * CHAINED - Script was triggered programmatically from another script, to figure out the original trigger type, read the `rootTriggerType` property.
     */
    readonly triggerType: 'EXTERNAL' | 'MANUAL' | 'SCHEDULED' | 'MANUAL_EVENT_LISTENER' | 'CHAINED';
}

interface TextEncoderOptions {
    stream?: boolean;
}

interface TextDecoderOptions {
    stream?: boolean;
}

declare class TextEncoder {
    encode(input: string, options?: TextEncoderOptions): Uint8Array;
}

declare class TextDecoder {
    decode(input: Uint8Array, options?: TextDecoderOptions): string;
}

interface Algorithm {
    name: string;
}

type AlgorithmIdentifier = string | Algorithm;
type BigInteger = Uint8Array;
type HashAlgorithmIdentifier = AlgorithmIdentifier;
type NamedCurve = string;
type KeyUsage = "decrypt" | "deriveBits" | "deriveKey" | "encrypt" | "sign" | "unwrapKey" | "verify" | "wrapKey";
type KeyType = "private" | "public" | "secret";

interface RsaKeyGenParams extends Algorithm {
    modulusLength: number;
    publicExponent: BigInteger;
}

interface RsaHashedKeyGenParams extends RsaKeyGenParams {
    hash: HashAlgorithmIdentifier;
}

interface EcKeyGenParams extends Algorithm {
    namedCurve: NamedCurve;
}

interface DhKeyGenParams extends Algorithm {
    generator: Uint8Array;
    prime: Uint8Array;
}

interface KeyAlgorithm {
    name: string;
}

interface AesKeyGenParams extends Algorithm {
    length: number;
}

interface HmacKeyGenParams extends Algorithm {
    hash: HashAlgorithmIdentifier;
    length?: number;
}

interface Pbkdf2Params extends Algorithm {
    hash: HashAlgorithmIdentifier;
    iterations: number;
    salt: ArrayBufferView | ArrayBuffer;
}

interface JsonWebKey {
    alg?: string;
    crv?: string;
    d?: string;
    dp?: string;
    dq?: string;
    e?: string;
    ext?: boolean;
    k?: string;
    key_ops?: string[];
    kty?: string;
    n?: string;
    oth?: RsaOtherPrimesInfo[];
    p?: string;
    q?: string;
    qi?: string;
    use?: string;
    x?: string;
    y?: string;
}

interface RsaOtherPrimesInfo {
    d?: string;
    r?: string;
    t?: string;
}

interface RsaHashedImportParams extends Algorithm {
    hash: HashAlgorithmIdentifier;
}

interface HmacImportParams extends Algorithm {
    hash: HashAlgorithmIdentifier;
    length?: number;
}

interface EcKeyImportParams extends Algorithm {
    namedCurve: NamedCurve;
}

interface AesKeyAlgorithm extends KeyAlgorithm {
    length: number;
}

interface RsaPssParams extends Algorithm {
    saltLength: number;
}

interface EcdsaParams extends Algorithm {
    hash: HashAlgorithmIdentifier;
}

interface Ed448Params extends Algorithm {
    context?: ArrayBufferView | ArrayBuffer;
}

declare class CryptoKey {
    readonly algorithm: KeyAlgorithm;
    readonly extractable: boolean;
    readonly type: KeyType;
    readonly usages: KeyUsage[];
}

declare class CryptoKeyPair {
    privateKey: CryptoKey;
    publicKey: CryptoKey;
}