UNPKG

162 kBTypeScriptView Raw
1// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
2
3/// <reference no-default-lib="true" />
4/// <reference lib="esnext" />
5
6declare namespace Deno {
7 /** A set of error constructors that are raised by Deno APIs. */
8 export const errors: {
9 NotFound: ErrorConstructor;
10 PermissionDenied: ErrorConstructor;
11 ConnectionRefused: ErrorConstructor;
12 ConnectionReset: ErrorConstructor;
13 ConnectionAborted: ErrorConstructor;
14 NotConnected: ErrorConstructor;
15 AddrInUse: ErrorConstructor;
16 AddrNotAvailable: ErrorConstructor;
17 BrokenPipe: ErrorConstructor;
18 AlreadyExists: ErrorConstructor;
19 InvalidData: ErrorConstructor;
20 TimedOut: ErrorConstructor;
21 Interrupted: ErrorConstructor;
22 WriteZero: ErrorConstructor;
23 UnexpectedEof: ErrorConstructor;
24 BadResource: ErrorConstructor;
25 Http: ErrorConstructor;
26 Busy: ErrorConstructor;
27 };
28
29 /** The current process id of the runtime. */
30 export const pid: number;
31
32 /** Reflects the `NO_COLOR` environment variable.
33 *
34 * See: https://no-color.org/ */
35 export const noColor: boolean;
36
37 export interface TestDefinition {
38 fn: () => void | Promise<void>;
39 name: string;
40 ignore?: boolean;
41 /** Check that the number of async completed ops after the test is the same
42 * as number of dispatched ops. Defaults to true.*/
43 sanitizeOps?: boolean;
44 /** Ensure the test case does not "leak" resources - ie. the resource table
45 * after the test has exactly the same contents as before the test. Defaults
46 * to true. */
47 sanitizeResources?: boolean;
48 }
49
50 /** Register a test which will be run when `deno test` is used on the command
51 * line and the containing module looks like a test module.
52 * `fn` can be async if required.
53 * ```ts
54 * import {assert, fail, assertEquals} from "https://deno.land/std/testing/asserts.ts";
55 *
56 * Deno.test({
57 * name: "example test",
58 * fn(): void {
59 * assertEquals("world", "world");
60 * },
61 * });
62 *
63 * Deno.test({
64 * name: "example ignored test",
65 * ignore: Deno.build.os === "windows"
66 * fn(): void {
67 * // This test is ignored only on Windows machines
68 * },
69 * });
70 *
71 * Deno.test({
72 * name: "example async test",
73 * async fn() {
74 * const decoder = new TextDecoder("utf-8");
75 * const data = await Deno.readFile("hello_world.txt");
76 * assertEquals(decoder.decode(data), "Hello world")
77 * }
78 * });
79 * ```
80 */
81 export function test(t: TestDefinition): void;
82
83 /** Register a test which will be run when `deno test` is used on the command
84 * line and the containing module looks like a test module.
85 * `fn` can be async if required.
86 *
87 * ```ts
88 * import {assert, fail, assertEquals} from "https://deno.land/std/testing/asserts.ts";
89 *
90 * Deno.test("My test description", ():void => {
91 * assertEquals("hello", "hello");
92 * });
93 *
94 * Deno.test("My async test description", async ():Promise<void> => {
95 * const decoder = new TextDecoder("utf-8");
96 * const data = await Deno.readFile("hello_world.txt");
97 * assertEquals(decoder.decode(data), "Hello world")
98 * });
99 * ```
100 * */
101 export function test(name: string, fn: () => void | Promise<void>): void;
102
103 /** Exit the Deno process with optional exit code. If no exit code is supplied
104 * then Deno will exit with return code of 0.
105 *
106 * ```ts
107 * Deno.exit(5);
108 * ```
109 */
110 export function exit(code?: number): never;
111
112 export const env: {
113 /** Retrieve the value of an environment variable. Returns undefined if that
114 * key doesn't exist.
115 *
116 * ```ts
117 * console.log(Deno.env.get("HOME")); // e.g. outputs "/home/alice"
118 * console.log(Deno.env.get("MADE_UP_VAR")); // outputs "Undefined"
119 * ```
120 * Requires `allow-env` permission. */
121 get(key: string): string | undefined;
122
123 /** Set the value of an environment variable.
124 *
125 * ```ts
126 * Deno.env.set("SOME_VAR", "Value"));
127 * Deno.env.get("SOME_VAR"); // outputs "Value"
128 * ```
129 *
130 * Requires `allow-env` permission. */
131 set(key: string, value: string): void;
132
133 /** Returns a snapshot of the environment variables at invocation.
134 *
135 * ```ts
136 * Deno.env.set("TEST_VAR", "A");
137 * const myEnv = Deno.env.toObject();
138 * console.log(myEnv.SHELL);
139 * Deno.env.set("TEST_VAR", "B");
140 * console.log(myEnv.TEST_VAR); // outputs "A"
141 * ```
142 *
143 * Requires `allow-env` permission. */
144 toObject(): { [index: string]: string };
145 };
146
147 /**
148 * Returns the path to the current deno executable.
149 *
150 * ```ts
151 * console.log(Deno.execPath()); // e.g. "/home/alice/.local/bin/deno"
152 * ```
153 *
154 * Requires `allow-read` permission.
155 */
156 export function execPath(): string;
157
158 /**
159 * Change the current working directory to the specified path.
160 *
161 * ```ts
162 * Deno.chdir("/home/userA");
163 * Deno.chdir("../userB");
164 * Deno.chdir("C:\\Program Files (x86)\\Java");
165 * ```
166 *
167 * Throws `Deno.errors.NotFound` if directory not found.
168 * Throws `Deno.errors.PermissionDenied` if the user does not have access
169 * rights
170 *
171 * Requires --allow-read.
172 */
173 export function chdir(directory: string): void;
174
175 /**
176 * Return a string representing the current working directory.
177 *
178 * If the current directory can be reached via multiple paths (due to symbolic
179 * links), `cwd()` may return any one of them.
180 *
181 * ```ts
182 * const currentWorkingDirectory = Deno.cwd();
183 * ```
184 *
185 * Throws `Deno.errors.NotFound` if directory not available.
186 *
187 * Requires --allow-read
188 */
189 export function cwd(): string;
190
191 export enum SeekMode {
192 Start = 0,
193 Current = 1,
194 End = 2,
195 }
196
197 export interface Reader {
198 /** Reads up to `p.byteLength` bytes into `p`. It resolves to the number of
199 * bytes read (`0` < `n` <= `p.byteLength`) and rejects if any error
200 * encountered. Even if `read()` resolves to `n` < `p.byteLength`, it may
201 * use all of `p` as scratch space during the call. If some data is
202 * available but not `p.byteLength` bytes, `read()` conventionally resolves
203 * to what is available instead of waiting for more.
204 *
205 * When `read()` encounters end-of-file condition, it resolves to EOF
206 * (`null`).
207 *
208 * When `read()` encounters an error, it rejects with an error.
209 *
210 * Callers should always process the `n` > `0` bytes returned before
211 * considering the EOF (`null`). Doing so correctly handles I/O errors that
212 * happen after reading some bytes and also both of the allowed EOF
213 * behaviors.
214 *
215 * Implementations should not retain a reference to `p`.
216 *
217 * Use Deno.iter() to turn a Reader into an AsyncIterator.
218 */
219 read(p: Uint8Array): Promise<number | null>;
220 }
221
222 export interface ReaderSync {
223 /** Reads up to `p.byteLength` bytes into `p`. It resolves to the number
224 * of bytes read (`0` < `n` <= `p.byteLength`) and rejects if any error
225 * encountered. Even if `read()` returns `n` < `p.byteLength`, it may use
226 * all of `p` as scratch space during the call. If some data is available
227 * but not `p.byteLength` bytes, `read()` conventionally returns what is
228 * available instead of waiting for more.
229 *
230 * When `readSync()` encounters end-of-file condition, it returns EOF
231 * (`null`).
232 *
233 * When `readSync()` encounters an error, it throws with an error.
234 *
235 * Callers should always process the `n` > `0` bytes returned before
236 * considering the EOF (`null`). Doing so correctly handles I/O errors that happen
237 * after reading some bytes and also both of the allowed EOF behaviors.
238 *
239 * Implementations should not retain a reference to `p`.
240 *
241 * Use Deno.iterSync() to turn a ReaderSync into an Iterator.
242 */
243 readSync(p: Uint8Array): number | null;
244 }
245
246 export interface Writer {
247 /** Writes `p.byteLength` bytes from `p` to the underlying data stream. It
248 * resolves to the number of bytes written from `p` (`0` <= `n` <=
249 * `p.byteLength`) or reject with the error encountered that caused the
250 * write to stop early. `write()` must reject with a non-null error if
251 * would resolve to `n` < `p.byteLength`. `write()` must not modify the
252 * slice data, even temporarily.
253 *
254 * Implementations should not retain a reference to `p`.
255 */
256 write(p: Uint8Array): Promise<number>;
257 }
258
259 export interface WriterSync {
260 /** Writes `p.byteLength` bytes from `p` to the underlying data
261 * stream. It returns the number of bytes written from `p` (`0` <= `n`
262 * <= `p.byteLength`) and any error encountered that caused the write to
263 * stop early. `writeSync()` must throw a non-null error if it returns `n` <
264 * `p.byteLength`. `writeSync()` must not modify the slice data, even
265 * temporarily.
266 *
267 * Implementations should not retain a reference to `p`.
268 */
269 writeSync(p: Uint8Array): number;
270 }
271
272 export interface Closer {
273 close(): void;
274 }
275
276 export interface Seeker {
277 /** Seek sets the offset for the next `read()` or `write()` to offset,
278 * interpreted according to `whence`: `Start` means relative to the
279 * start of the file, `Current` means relative to the current offset,
280 * and `End` means relative to the end. Seek resolves to the new offset
281 * relative to the start of the file.
282 *
283 * Seeking to an offset before the start of the file is an error. Seeking to
284 * any positive offset is legal, but the behavior of subsequent I/O
285 * operations on the underlying object is implementation-dependent.
286 * It returns the number of cursor position.
287 */
288 seek(offset: number, whence: SeekMode): Promise<number>;
289 }
290
291 export interface SeekerSync {
292 /** Seek sets the offset for the next `readSync()` or `writeSync()` to
293 * offset, interpreted according to `whence`: `Start` means relative
294 * to the start of the file, `Current` means relative to the current
295 * offset, and `End` means relative to the end.
296 *
297 * Seeking to an offset before the start of the file is an error. Seeking to
298 * any positive offset is legal, but the behavior of subsequent I/O
299 * operations on the underlying object is implementation-dependent.
300 */
301 seekSync(offset: number, whence: SeekMode): number;
302 }
303
304 /** Copies from `src` to `dst` until either EOF (`null`) is read from `src` or
305 * an error occurs. It resolves to the number of bytes copied or rejects with
306 * the first error encountered while copying.
307 *
308 * ```ts
309 * const source = await Deno.open("my_file.txt");
310 * const buffer = new Deno.Buffer()
311 * const bytesCopied1 = await Deno.copy(source, Deno.stdout);
312 * const bytesCopied2 = await Deno.copy(source, buffer);
313 * ```
314 *
315 * @param src The source to copy from
316 * @param dst The destination to copy to
317 * @param options Can be used to tune size of the buffer. Default size is 32kB
318 */
319 export function copy(
320 src: Reader,
321 dst: Writer,
322 options?: {
323 bufSize?: number;
324 }
325 ): Promise<number>;
326
327 /** Turns a Reader, `r`, into an async iterator.
328 *
329 * ```ts
330 * let f = await Deno.open("/etc/passwd");
331 * for await (const chunk of Deno.iter(f)) {
332 * console.log(chunk);
333 * }
334 * f.close();
335 * ```
336 *
337 * Second argument can be used to tune size of a buffer.
338 * Default size of the buffer is 32kB.
339 *
340 * ```ts
341 * let f = await Deno.open("/etc/passwd");
342 * const iter = Deno.iter(f, {
343 * bufSize: 1024 * 1024
344 * });
345 * for await (const chunk of iter) {
346 * console.log(chunk);
347 * }
348 * f.close();
349 * ```
350 *
351 * Iterator uses an internal buffer of fixed size for efficiency; it returns
352 * a view on that buffer on each iteration. It is therefore caller's
353 * responsibility to copy contents of the buffer if needed; otherwise the
354 * next iteration will overwrite contents of previously returned chunk.
355 */
356 export function iter(
357 r: Reader,
358 options?: {
359 bufSize?: number;
360 }
361 ): AsyncIterableIterator<Uint8Array>;
362
363 /** Turns a ReaderSync, `r`, into an iterator.
364 *
365 * ```ts
366 * let f = Deno.openSync("/etc/passwd");
367 * for (const chunk of Deno.iterSync(reader)) {
368 * console.log(chunk);
369 * }
370 * f.close();
371 * ```
372 *
373 * Second argument can be used to tune size of a buffer.
374 * Default size of the buffer is 32kB.
375 *
376 * ```ts
377 * let f = await Deno.open("/etc/passwd");
378 * const iter = Deno.iterSync(f, {
379 * bufSize: 1024 * 1024
380 * });
381 * for (const chunk of iter) {
382 * console.log(chunk);
383 * }
384 * f.close();
385 * ```
386 *
387 * Iterator uses an internal buffer of fixed size for efficiency; it returns
388 * a view on that buffer on each iteration. It is therefore caller's
389 * responsibility to copy contents of the buffer if needed; otherwise the
390 * next iteration will overwrite contents of previously returned chunk.
391 */
392 export function iterSync(
393 r: ReaderSync,
394 options?: {
395 bufSize?: number;
396 }
397 ): IterableIterator<Uint8Array>;
398
399 /** Synchronously open a file and return an instance of `Deno.File`. The
400 * file does not need to previously exist if using the `create` or `createNew`
401 * open options. It is the callers responsibility to close the file when finished
402 * with it.
403 *
404 * ```ts
405 * const file = Deno.openSync("/foo/bar.txt", { read: true, write: true });
406 * // Do work with file
407 * Deno.close(file.rid);
408 * ```
409 *
410 * Requires `allow-read` and/or `allow-write` permissions depending on options.
411 */
412 export function openSync(path: string, options?: OpenOptions): File;
413
414 /** Open a file and resolve to an instance of `Deno.File`. The
415 * file does not need to previously exist if using the `create` or `createNew`
416 * open options. It is the callers responsibility to close the file when finished
417 * with it.
418 *
419 * ```ts
420 * const file = await Deno.open("/foo/bar.txt", { read: true, write: true });
421 * // Do work with file
422 * Deno.close(file.rid);
423 * ```
424 *
425 * Requires `allow-read` and/or `allow-write` permissions depending on options.
426 */
427 export function open(path: string, options?: OpenOptions): Promise<File>;
428
429 /** Creates a file if none exists or truncates an existing file and returns
430 * an instance of `Deno.File`.
431 *
432 * ```ts
433 * const file = Deno.createSync("/foo/bar.txt");
434 * ```
435 *
436 * Requires `allow-read` and `allow-write` permissions.
437 */
438 export function createSync(path: string): File;
439
440 /** Creates a file if none exists or truncates an existing file and resolves to
441 * an instance of `Deno.File`.
442 *
443 * ```ts
444 * const file = await Deno.create("/foo/bar.txt");
445 * ```
446 *
447 * Requires `allow-read` and `allow-write` permissions.
448 */
449 export function create(path: string): Promise<File>;
450
451 /** Synchronously read from a resource ID (`rid`) into an array buffer (`buffer`).
452 *
453 * Returns either the number of bytes read during the operation or EOF
454 * (`null`) if there was nothing more to read.
455 *
456 * It is possible for a read to successfully return with `0` bytes. This does
457 * not indicate EOF.
458 *
459 * This function is one of the lowest level APIs and most users should not
460 * work with this directly, but rather use Deno.readAllSync() instead.
461 *
462 * **It is not guaranteed that the full buffer will be read in a single call.**
463 *
464 * ```ts
465 * // if "/foo/bar.txt" contains the text "hello world":
466 * const file = Deno.openSync("/foo/bar.txt");
467 * const buf = new Uint8Array(100);
468 * const numberOfBytesRead = Deno.readSync(file.rid, buf); // 11 bytes
469 * const text = new TextDecoder().decode(buf); // "hello world"
470 * Deno.close(file.rid);
471 * ```
472 */
473 export function readSync(rid: number, buffer: Uint8Array): number | null;
474
475 /** Read from a resource ID (`rid`) into an array buffer (`buffer`).
476 *
477 * Resolves to either the number of bytes read during the operation or EOF
478 * (`null`) if there was nothing more to read.
479 *
480 * It is possible for a read to successfully return with `0` bytes. This does
481 * not indicate EOF.
482 *
483 * This function is one of the lowest level APIs and most users should not
484 * work with this directly, but rather use Deno.readAll() instead.
485 *
486 * **It is not guaranteed that the full buffer will be read in a single call.**
487 *
488 * ```ts
489 * // if "/foo/bar.txt" contains the text "hello world":
490 * const file = await Deno.open("/foo/bar.txt");
491 * const buf = new Uint8Array(100);
492 * const numberOfBytesRead = await Deno.read(file.rid, buf); // 11 bytes
493 * const text = new TextDecoder().decode(buf); // "hello world"
494 * Deno.close(file.rid);
495 * ```
496 */
497 export function read(rid: number, buffer: Uint8Array): Promise<number | null>;
498
499 /** Synchronously write to the resource ID (`rid`) the contents of the array
500 * buffer (`data`).
501 *
502 * Returns the number of bytes written. This function is one of the lowest
503 * level APIs and most users should not work with this directly, but rather use
504 * Deno.writeAllSync() instead.
505 *
506 * **It is not guaranteed that the full buffer will be written in a single
507 * call.**
508 *
509 * ```ts
510 * const encoder = new TextEncoder();
511 * const data = encoder.encode("Hello world");
512 * const file = Deno.openSync("/foo/bar.txt");
513 * const bytesWritten = Deno.writeSync(file.rid, data); // 11
514 * Deno.close(file.rid);
515 * ```
516 */
517 export function writeSync(rid: number, data: Uint8Array): number;
518
519 /** Write to the resource ID (`rid`) the contents of the array buffer (`data`).
520 *
521 * Resolves to the number of bytes written. This function is one of the lowest
522 * level APIs and most users should not work with this directly, but rather use
523 * Deno.writeAll() instead.
524 *
525 * **It is not guaranteed that the full buffer will be written in a single
526 * call.**
527 *
528 * ```ts
529 * const encoder = new TextEncoder();
530 * const data = encoder.encode("Hello world");
531 * const file = await Deno.open("/foo/bar.txt");
532 * const bytesWritten = await Deno.write(file.rid, data); // 11
533 * Deno.close(file.rid);
534 * ```
535 */
536 export function write(rid: number, data: Uint8Array): Promise<number>;
537
538 /** Synchronously seek a resource ID (`rid`) to the given `offset` under mode
539 * given by `whence`. The new position within the resource (bytes from the
540 * start) is returned.
541 *
542 * ```ts
543 * const file = Deno.openSync('hello.txt', {read: true, write: true, truncate: true, create: true});
544 * Deno.writeSync(file.rid, new TextEncoder().encode("Hello world"));
545 * // advance cursor 6 bytes
546 * const cursorPosition = Deno.seekSync(file.rid, 6, Deno.SeekMode.Start);
547 * console.log(cursorPosition); // 6
548 * const buf = new Uint8Array(100);
549 * file.readSync(buf);
550 * console.log(new TextDecoder().decode(buf)); // "world"
551 * ```
552 *
553 * The seek modes work as follows:
554 *
555 * ```ts
556 * // Given file.rid pointing to file with "Hello world", which is 11 bytes long:
557 * // Seek 6 bytes from the start of the file
558 * console.log(Deno.seekSync(file.rid, 6, Deno.SeekMode.Start)); // "6"
559 * // Seek 2 more bytes from the current position
560 * console.log(Deno.seekSync(file.rid, 2, Deno.SeekMode.Current)); // "8"
561 * // Seek backwards 2 bytes from the end of the file
562 * console.log(Deno.seekSync(file.rid, -2, Deno.SeekMode.End)); // "9" (e.g. 11-2)
563 * ```
564 */
565 export function seekSync(
566 rid: number,
567 offset: number,
568 whence: SeekMode
569 ): number;
570
571 /** Seek a resource ID (`rid`) to the given `offset` under mode given by `whence`.
572 * The call resolves to the new position within the resource (bytes from the start).
573 *
574 * ```ts
575 * const file = await Deno.open('hello.txt', {read: true, write: true, truncate: true, create: true});
576 * await Deno.write(file.rid, new TextEncoder().encode("Hello world"));
577 * // advance cursor 6 bytes
578 * const cursorPosition = await Deno.seek(file.rid, 6, Deno.SeekMode.Start);
579 * console.log(cursorPosition); // 6
580 * const buf = new Uint8Array(100);
581 * await file.read(buf);
582 * console.log(new TextDecoder().decode(buf)); // "world"
583 * ```
584 *
585 * The seek modes work as follows:
586 *
587 * ```ts
588 * // Given file.rid pointing to file with "Hello world", which is 11 bytes long:
589 * // Seek 6 bytes from the start of the file
590 * console.log(await Deno.seek(file.rid, 6, Deno.SeekMode.Start)); // "6"
591 * // Seek 2 more bytes from the current position
592 * console.log(await Deno.seek(file.rid, 2, Deno.SeekMode.Current)); // "8"
593 * // Seek backwards 2 bytes from the end of the file
594 * console.log(await Deno.seek(file.rid, -2, Deno.SeekMode.End)); // "9" (e.g. 11-2)
595 * ```
596 */
597 export function seek(
598 rid: number,
599 offset: number,
600 whence: SeekMode
601 ): Promise<number>;
602
603 /** Close the given resource ID (rid) which has been previously opened, such
604 * as via opening or creating a file. Closing a file when you are finished
605 * with it is important to avoid leaking resources.
606 *
607 * ```ts
608 * const file = await Deno.open("my_file.txt");
609 * // do work with "file" object
610 * Deno.close(file.rid);
611 * ````
612 */
613 export function close(rid: number): void;
614
615 /** The Deno abstraction for reading and writing files. */
616 export class File
617 implements
618 Reader,
619 ReaderSync,
620 Writer,
621 WriterSync,
622 Seeker,
623 SeekerSync,
624 Closer {
625 readonly rid: number;
626 constructor(rid: number);
627 write(p: Uint8Array): Promise<number>;
628 writeSync(p: Uint8Array): number;
629 read(p: Uint8Array): Promise<number | null>;
630 readSync(p: Uint8Array): number | null;
631 seek(offset: number, whence: SeekMode): Promise<number>;
632 seekSync(offset: number, whence: SeekMode): number;
633 close(): void;
634 }
635
636 /** A handle for `stdin`. */
637 export const stdin: Reader & ReaderSync & Closer & { rid: number };
638 /** A handle for `stdout`. */
639 export const stdout: Writer & WriterSync & Closer & { rid: number };
640 /** A handle for `stderr`. */
641 export const stderr: Writer & WriterSync & Closer & { rid: number };
642
643 export interface OpenOptions {
644 /** Sets the option for read access. This option, when `true`, means that the
645 * file should be read-able if opened. */
646 read?: boolean;
647 /** Sets the option for write access. This option, when `true`, means that
648 * the file should be write-able if opened. If the file already exists,
649 * any write calls on it will overwrite its contents, by default without
650 * truncating it. */
651 write?: boolean;
652 /**Sets the option for the append mode. This option, when `true`, means that
653 * writes will append to a file instead of overwriting previous contents.
654 * Note that setting `{ write: true, append: true }` has the same effect as
655 * setting only `{ append: true }`. */
656 append?: boolean;
657 /** Sets the option for truncating a previous file. If a file is
658 * successfully opened with this option set it will truncate the file to `0`
659 * size if it already exists. The file must be opened with write access
660 * for truncate to work. */
661 truncate?: boolean;
662 /** Sets the option to allow creating a new file, if one doesn't already
663 * exist at the specified path. Requires write or append access to be
664 * used. */
665 create?: boolean;
666 /** Defaults to `false`. If set to `true`, no file, directory, or symlink is
667 * allowed to exist at the target location. Requires write or append
668 * access to be used. When createNew is set to `true`, create and truncate
669 * are ignored. */
670 createNew?: boolean;
671 /** Permissions to use if creating the file (defaults to `0o666`, before
672 * the process's umask).
673 * Ignored on Windows. */
674 mode?: number;
675 }
676
677 /**
678 *
679 * Check if a given resource id (`rid`) is a TTY.
680 *
681 * ```ts
682 * // This example is system and context specific
683 * const nonTTYRid = Deno.openSync("my_file.txt").rid;
684 * const ttyRid = Deno.openSync("/dev/tty6").rid;
685 * console.log(Deno.isatty(nonTTYRid)); // false
686 * console.log(Deno.isatty(ttyRid)); // true
687 * Deno.close(nonTTYRid);
688 * Deno.close(ttyRid);
689 * ```
690 */
691 export function isatty(rid: number): boolean;
692
693 /** A variable-sized buffer of bytes with `read()` and `write()` methods.
694 *
695 * Deno.Buffer is almost always used with some I/O like files and sockets. It
696 * allows one to buffer up a download from a socket. Buffer grows and shrinks
697 * as necessary.
698 *
699 * Deno.Buffer is NOT the same thing as Node's Buffer. Node's Buffer was
700 * created in 2009 before JavaScript had the concept of ArrayBuffers. It's
701 * simply a non-standard ArrayBuffer.
702 *
703 * ArrayBuffer is a fixed memory allocation. Deno.Buffer is implemented on top
704 * of ArrayBuffer.
705 *
706 * Based on [Go Buffer](https://golang.org/pkg/bytes/#Buffer). */
707 export class Buffer implements Reader, ReaderSync, Writer, WriterSync {
708 constructor(ab?: ArrayBuffer);
709 /** Returns a slice holding the unread portion of the buffer.
710 *
711 * The slice is valid for use only until the next buffer modification (that
712 * is, only until the next call to a method like `read()`, `write()`,
713 * `reset()`, or `truncate()`). The slice aliases the buffer content at
714 * least until the next buffer modification, so immediate changes to the
715 * slice will affect the result of future reads. */
716 bytes(): Uint8Array;
717 /** Returns whether the unread portion of the buffer is empty. */
718 empty(): boolean;
719 /** A read only number of bytes of the unread portion of the buffer. */
720 readonly length: number;
721 /** The read only capacity of the buffer's underlying byte slice, that is,
722 * the total space allocated for the buffer's data. */
723 readonly capacity: number;
724 /** Discards all but the first `n` unread bytes from the buffer but
725 * continues to use the same allocated storage. It throws if `n` is
726 * negative or greater than the length of the buffer. */
727 truncate(n: number): void;
728 /** Resets the buffer to be empty, but it retains the underlying storage for
729 * use by future writes. `.reset()` is the same as `.truncate(0)`. */
730 reset(): void;
731 /** Reads the next `p.length` bytes from the buffer or until the buffer is
732 * drained. Returns the number of bytes read. If the buffer has no data to
733 * return, the return is EOF (`null`). */
734 readSync(p: Uint8Array): number | null;
735 /** Reads the next `p.length` bytes from the buffer or until the buffer is
736 * drained. Resolves to the number of bytes read. If the buffer has no
737 * data to return, resolves to EOF (`null`).
738 *
739 * NOTE: This methods reads bytes sychronously; it's provided for
740 * compatibility with `Reader` interfaces.
741 */
742 read(p: Uint8Array): Promise<number | null>;
743 writeSync(p: Uint8Array): number;
744 /** NOTE: This methods writes bytes sychronously; it's provided for
745 * compatibility with `Writer` interface. */
746 write(p: Uint8Array): Promise<number>;
747 /** Grows the buffer's capacity, if necessary, to guarantee space for
748 * another `n` bytes. After `.grow(n)`, at least `n` bytes can be written to
749 * the buffer without another allocation. If `n` is negative, `.grow()` will
750 * throw. If the buffer can't grow it will throw an error.
751 *
752 * Based on Go Lang's
753 * [Buffer.Grow](https://golang.org/pkg/bytes/#Buffer.Grow). */
754 grow(n: number): void;
755 /** Reads data from `r` until EOF (`null`) and appends it to the buffer,
756 * growing the buffer as needed. It resolves to the number of bytes read.
757 * If the buffer becomes too large, `.readFrom()` will reject with an error.
758 *
759 * Based on Go Lang's
760 * [Buffer.ReadFrom](https://golang.org/pkg/bytes/#Buffer.ReadFrom). */
761 readFrom(r: Reader): Promise<number>;
762 /** Reads data from `r` until EOF (`null`) and appends it to the buffer,
763 * growing the buffer as needed. It returns the number of bytes read. If the
764 * buffer becomes too large, `.readFromSync()` will throw an error.
765 *
766 * Based on Go Lang's
767 * [Buffer.ReadFrom](https://golang.org/pkg/bytes/#Buffer.ReadFrom). */
768 readFromSync(r: ReaderSync): number;
769 }
770
771 /** Read Reader `r` until EOF (`null`) and resolve to the content as
772 * Uint8Array`.
773 *
774 * ```ts
775 * // Example from stdin
776 * const stdinContent = await Deno.readAll(Deno.stdin);
777 *
778 * // Example from file
779 * const file = await Deno.open("my_file.txt", {read: true});
780 * const myFileContent = await Deno.readAll(file);
781 * Deno.close(file.rid);
782 *
783 * // Example from buffer
784 * const myData = new Uint8Array(100);
785 * // ... fill myData array with data
786 * const reader = new Deno.Buffer(myData.buffer as ArrayBuffer);
787 * const bufferContent = await Deno.readAll(reader);
788 * ```
789 */
790 export function readAll(r: Reader): Promise<Uint8Array>;
791
792 /** Synchronously reads Reader `r` until EOF (`null`) and returns the content
793 * as `Uint8Array`.
794 *
795 * ```ts
796 * // Example from stdin
797 * const stdinContent = Deno.readAllSync(Deno.stdin);
798 *
799 * // Example from file
800 * const file = Deno.openSync("my_file.txt", {read: true});
801 * const myFileContent = Deno.readAllSync(file);
802 * Deno.close(file.rid);
803 *
804 * // Example from buffer
805 * const myData = new Uint8Array(100);
806 * // ... fill myData array with data
807 * const reader = new Deno.Buffer(myData.buffer as ArrayBuffer);
808 * const bufferContent = Deno.readAllSync(reader);
809 * ```
810 */
811 export function readAllSync(r: ReaderSync): Uint8Array;
812
813 /** Write all the content of the array buffer (`arr`) to the writer (`w`).
814 *
815 * ```ts
816 * // Example writing to stdout
817 * const contentBytes = new TextEncoder().encode("Hello World");
818 * await Deno.writeAll(Deno.stdout, contentBytes);
819 *
820 * // Example writing to file
821 * const contentBytes = new TextEncoder().encode("Hello World");
822 * const file = await Deno.open('test.file', {write: true});
823 * await Deno.writeAll(file, contentBytes);
824 * Deno.close(file.rid);
825 *
826 * // Example writing to buffer
827 * const contentBytes = new TextEncoder().encode("Hello World");
828 * const writer = new Deno.Buffer();
829 * await Deno.writeAll(writer, contentBytes);
830 * console.log(writer.bytes().length); // 11
831 * ```
832 */
833 export function writeAll(w: Writer, arr: Uint8Array): Promise<void>;
834
835 /** Synchronously write all the content of the array buffer (`arr`) to the
836 * writer (`w`).
837 *
838 * ```ts
839 * // Example writing to stdout
840 * const contentBytes = new TextEncoder().encode("Hello World");
841 * Deno.writeAllSync(Deno.stdout, contentBytes);
842 *
843 * // Example writing to file
844 * const contentBytes = new TextEncoder().encode("Hello World");
845 * const file = Deno.openSync('test.file', {write: true});
846 * Deno.writeAllSync(file, contentBytes);
847 * Deno.close(file.rid);
848 *
849 * // Example writing to buffer
850 * const contentBytes = new TextEncoder().encode("Hello World");
851 * const writer = new Deno.Buffer();
852 * Deno.writeAllSync(writer, contentBytes);
853 * console.log(writer.bytes().length); // 11
854 * ```
855 */
856 export function writeAllSync(w: WriterSync, arr: Uint8Array): void;
857
858 export interface MkdirOptions {
859 /** Defaults to `false`. If set to `true`, means that any intermediate
860 * directories will also be created (as with the shell command `mkdir -p`).
861 * Intermediate directories are created with the same permissions.
862 * When recursive is set to `true`, succeeds silently (without changing any
863 * permissions) if a directory already exists at the path, or if the path
864 * is a symlink to an existing directory. */
865 recursive?: boolean;
866 /** Permissions to use when creating the directory (defaults to `0o777`,
867 * before the process's umask).
868 * Ignored on Windows. */
869 mode?: number;
870 }
871
872 /** Synchronously creates a new directory with the specified path.
873 *
874 * ```ts
875 * Deno.mkdirSync("new_dir");
876 * Deno.mkdirSync("nested/directories", { recursive: true });
877 * Deno.mkdirSync("restricted_access_dir", { mode: 0o700 });
878 * ```
879 *
880 * Defaults to throwing error if the directory already exists.
881 *
882 * Requires `allow-write` permission. */
883 export function mkdirSync(path: string, options?: MkdirOptions): void;
884
885 /** Creates a new directory with the specified path.
886 *
887 * ```ts
888 * await Deno.mkdir("new_dir");
889 * await Deno.mkdir("nested/directories", { recursive: true });
890 * await Deno.mkdir("restricted_access_dir", { mode: 0o700 });
891 * ```
892 *
893 * Defaults to throwing error if the directory already exists.
894 *
895 * Requires `allow-write` permission. */
896 export function mkdir(path: string, options?: MkdirOptions): Promise<void>;
897
898 export interface MakeTempOptions {
899 /** Directory where the temporary directory should be created (defaults to
900 * the env variable TMPDIR, or the system's default, usually /tmp). */
901 dir?: string;
902 /** String that should precede the random portion of the temporary
903 * directory's name. */
904 prefix?: string;
905 /** String that should follow the random portion of the temporary
906 * directory's name. */
907 suffix?: string;
908 }
909
910 /** Synchronously creates a new temporary directory in the default directory
911 * for temporary files (see also `Deno.dir("temp")`), unless `dir` is specified.
912 * Other optional options include prefixing and suffixing the directory name
913 * with `prefix` and `suffix` respectively.
914 *
915 * The full path to the newly created directory is returned.
916 *
917 * Multiple programs calling this function simultaneously will create different
918 * directories. It is the caller's responsibility to remove the directory when
919 * no longer needed.
920 *
921 * ```ts
922 * const tempDirName0 = Deno.makeTempDirSync(); // e.g. /tmp/2894ea76
923 * const tempDirName1 = Deno.makeTempDirSync({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d
924 * ```
925 *
926 * Requires `allow-write` permission. */
927 // TODO(ry) Doesn't check permissions.
928 export function makeTempDirSync(options?: MakeTempOptions): string;
929
930 /** Creates a new temporary directory in the default directory for temporary
931 * files (see also `Deno.dir("temp")`), unless `dir` is specified. Other
932 * optional options include prefixing and suffixing the directory name with
933 * `prefix` and `suffix` respectively.
934 *
935 * This call resolves to the full path to the newly created directory.
936 *
937 * Multiple programs calling this function simultaneously will create different
938 * directories. It is the caller's responsibility to remove the directory when
939 * no longer needed.
940 *
941 * ```ts
942 * const tempDirName0 = await Deno.makeTempDir(); // e.g. /tmp/2894ea76
943 * const tempDirName1 = await Deno.makeTempDir({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d
944 * ```
945 *
946 * Requires `allow-write` permission. */
947 // TODO(ry) Doesn't check permissions.
948 export function makeTempDir(options?: MakeTempOptions): Promise<string>;
949
950 /** Synchronously creates a new temporary file in the default directory for
951 * temporary files (see also `Deno.dir("temp")`), unless `dir` is specified.
952 * Other optional options include prefixing and suffixing the directory name
953 * with `prefix` and `suffix` respectively.
954 *
955 * The full path to the newly created file is returned.
956 *
957 * Multiple programs calling this function simultaneously will create different
958 * files. It is the caller's responsibility to remove the file when no longer
959 * needed.
960 *
961 * ```ts
962 * const tempFileName0 = Deno.makeTempFileSync(); // e.g. /tmp/419e0bf2
963 * const tempFileName1 = Deno.makeTempFileSync({ prefix: 'my_temp' }); // e.g. /tmp/my_temp754d3098
964 * ```
965 *
966 * Requires `allow-write` permission. */
967 export function makeTempFileSync(options?: MakeTempOptions): string;
968
969 /** Creates a new temporary file in the default directory for temporary
970 * files (see also `Deno.dir("temp")`), unless `dir` is specified. Other
971 * optional options include prefixing and suffixing the directory name with
972 * `prefix` and `suffix` respectively.
973 *
974 * This call resolves to the full path to the newly created file.
975 *
976 * Multiple programs calling this function simultaneously will create different
977 * files. It is the caller's responsibility to remove the file when no longer
978 * needed.
979 *
980 * ```ts
981 * const tmpFileName0 = await Deno.makeTempFile(); // e.g. /tmp/419e0bf2
982 * const tmpFileName1 = await Deno.makeTempFile({ prefix: 'my_temp' }); // e.g. /tmp/my_temp754d3098
983 * ```
984 *
985 * Requires `allow-write` permission. */
986 export function makeTempFile(options?: MakeTempOptions): Promise<string>;
987
988 /** Synchronously changes the permission of a specific file/directory of
989 * specified path. Ignores the process's umask.
990 *
991 * ```ts
992 * Deno.chmodSync("/path/to/file", 0o666);
993 * ```
994 *
995 * For a full description, see [chmod](#chmod)
996 *
997 * NOTE: This API currently throws on Windows
998 *
999 * Requires `allow-write` permission. */
1000 export function chmodSync(path: string, mode: number): void;
1001
1002 /** Changes the permission of a specific file/directory of specified path.
1003 * Ignores the process's umask.
1004 *
1005 * ```ts
1006 * await Deno.chmod("/path/to/file", 0o666);
1007 * ```
1008 *
1009 * The mode is a sequence of 3 octal numbers. The first/left-most number
1010 * specifies the permissions for the owner. The second number specifies the
1011 * permissions for the group. The last/right-most number specifies the
1012 * permissions for others. For example, with a mode of 0o764, the owner (7) can
1013 * read/write/execute, the group (6) can read/write and everyone else (4) can
1014 * read only.
1015 *
1016 * | Number | Description |
1017 * | ------ | ----------- |
1018 * | 7 | read, write, and execute |
1019 * | 6 | read and write |
1020 * | 5 | read and execute |
1021 * | 4 | read only |
1022 * | 3 | write and execute |
1023 * | 2 | write only |
1024 * | 1 | execute only |
1025 * | 0 | no permission |
1026 *
1027 * NOTE: This API currently throws on Windows
1028 *
1029 * Requires `allow-write` permission. */
1030 export function chmod(path: string, mode: number): Promise<void>;
1031
1032 /** Synchronously change owner of a regular file or directory. This functionality
1033 * is not available on Windows.
1034 *
1035 * ```ts
1036 * Deno.chownSync("myFile.txt", 1000, 1002);
1037 * ```
1038 *
1039 * Requires `allow-write` permission.
1040 *
1041 * Throws Error (not implemented) if executed on Windows
1042 *
1043 * @param path path to the file
1044 * @param uid user id (UID) of the new owner
1045 * @param gid group id (GID) of the new owner
1046 */
1047 export function chownSync(path: string, uid: number, gid: number): void;
1048
1049 /** Change owner of a regular file or directory. This functionality
1050 * is not available on Windows.
1051 *
1052 * ```ts
1053 * await Deno.chown("myFile.txt", 1000, 1002);
1054 * ```
1055 *
1056 * Requires `allow-write` permission.
1057 *
1058 * Throws Error (not implemented) if executed on Windows
1059 *
1060 * @param path path to the file
1061 * @param uid user id (UID) of the new owner
1062 * @param gid group id (GID) of the new owner
1063 */
1064 export function chown(path: string, uid: number, gid: number): Promise<void>;
1065
1066 export interface RemoveOptions {
1067 /** Defaults to `false`. If set to `true`, path will be removed even if
1068 * it's a non-empty directory. */
1069 recursive?: boolean;
1070 }
1071
1072 /** Synchronously removes the named file or directory.
1073 *
1074 * ```ts
1075 * Deno.removeSync("/path/to/empty_dir/or/file");
1076 * Deno.removeSync("/path/to/populated_dir/or/file", { recursive: true });
1077 * ```
1078 *
1079 * Throws error if permission denied, path not found, or path is a non-empty
1080 * directory and the `recursive` option isn't set to `true`.
1081 *
1082 * Requires `allow-write` permission. */
1083 export function removeSync(path: string, options?: RemoveOptions): void;
1084
1085 /** Removes the named file or directory.
1086 *
1087 * ```ts
1088 * await Deno.remove("/path/to/empty_dir/or/file");
1089 * await Deno.remove("/path/to/populated_dir/or/file", { recursive: true });
1090 * ```
1091 *
1092 * Throws error if permission denied, path not found, or path is a non-empty
1093 * directory and the `recursive` option isn't set to `true`.
1094 *
1095 * Requires `allow-write` permission. */
1096 export function remove(path: string, options?: RemoveOptions): Promise<void>;
1097
1098 /** Synchronously renames (moves) `oldpath` to `newpath`. Paths may be files or
1099 * directories. If `newpath` already exists and is not a directory,
1100 * `renameSync()` replaces it. OS-specific restrictions may apply when
1101 * `oldpath` and `newpath` are in different directories.
1102 *
1103 * ```ts
1104 * Deno.renameSync("old/path", "new/path");
1105 * ```
1106 *
1107 * On Unix, this operation does not follow symlinks at either path.
1108 *
1109 * It varies between platforms when the operation throws errors, and if so what
1110 * they are. It's always an error to rename anything to a non-empty directory.
1111 *
1112 * Requires `allow-read` and `allow-write` permissions. */
1113 export function renameSync(oldpath: string, newpath: string): void;
1114
1115 /** Renames (moves) `oldpath` to `newpath`. Paths may be files or directories.
1116 * If `newpath` already exists and is not a directory, `rename()` replaces it.
1117 * OS-specific restrictions may apply when `oldpath` and `newpath` are in
1118 * different directories.
1119 *
1120 * ```ts
1121 * await Deno.rename("old/path", "new/path");
1122 * ```
1123 *
1124 * On Unix, this operation does not follow symlinks at either path.
1125 *
1126 * It varies between platforms when the operation throws errors, and if so what
1127 * they are. It's always an error to rename anything to a non-empty directory.
1128 *
1129 * Requires `allow-read` and `allow-write` permission. */
1130 export function rename(oldpath: string, newpath: string): Promise<void>;
1131
1132 /** Synchronously reads and returns the entire contents of a file as utf8 encoded string
1133 * encoded string. Reading a directory returns an empty string.
1134 *
1135 * ```ts
1136 * const data = Deno.readTextFileSync("hello.txt");
1137 * console.log(data);
1138 * ```
1139 *
1140 * Requires `allow-read` permission. */
1141 export function readTextFileSync(path: string): string;
1142
1143 /** Asynchronously reads and returns the entire contents of a file as a utf8
1144 * encoded string. Reading a directory returns an empty data array.
1145 *
1146 * ```ts
1147 * const data = await Deno.readTextFile("hello.txt");
1148 * console.log(data);
1149 * ```
1150 *
1151 * Requires `allow-read` permission. */
1152 export function readTextFile(path: string): Promise<string>;
1153
1154 /** Synchronously reads and returns the entire contents of a file as an array
1155 * of bytes. `TextDecoder` can be used to transform the bytes to string if
1156 * required. Reading a directory returns an empty data array.
1157 *
1158 * ```ts
1159 * const decoder = new TextDecoder("utf-8");
1160 * const data = Deno.readFileSync("hello.txt");
1161 * console.log(decoder.decode(data));
1162 * ```
1163 *
1164 * Requires `allow-read` permission. */
1165 export function readFileSync(path: string): Uint8Array;
1166
1167 /** Reads and resolves to the entire contents of a file as an array of bytes.
1168 * `TextDecoder` can be used to transform the bytes to string if required.
1169 * Reading a directory returns an empty data array.
1170 *
1171 * ```ts
1172 * const decoder = new TextDecoder("utf-8");
1173 * const data = await Deno.readFile("hello.txt");
1174 * console.log(decoder.decode(data));
1175 * ```
1176 *
1177 * Requires `allow-read` permission. */
1178 export function readFile(path: string): Promise<Uint8Array>;
1179
1180 /** A FileInfo describes a file and is returned by `stat`, `lstat`,
1181 * `statSync`, `lstatSync`. */
1182 export interface FileInfo {
1183 /** True if this is info for a regular file. Mutually exclusive to
1184 * `FileInfo.isDirectory` and `FileInfo.isSymlink`. */
1185 isFile: boolean;
1186 /** True if this is info for a regular directory. Mutually exclusive to
1187 * `FileInfo.isFile` and `FileInfo.isSymlink`. */
1188 isDirectory: boolean;
1189 /** True if this is info for a symlink. Mutually exclusive to
1190 * `FileInfo.isFile` and `FileInfo.isDirectory`. */
1191 isSymlink: boolean;
1192 /** The size of the file, in bytes. */
1193 size: number;
1194 /** The last modification time of the file. This corresponds to the `mtime`
1195 * field from `stat` on Linux/Mac OS and `ftLastWriteTime` on Windows. This
1196 * may not be available on all platforms. */
1197 mtime: Date | null;
1198 /** The last access time of the file. This corresponds to the `atime`
1199 * field from `stat` on Unix and `ftLastAccessTime` on Windows. This may not
1200 * be available on all platforms. */
1201 atime: Date | null;
1202 /** The creation time of the file. This corresponds to the `birthtime`
1203 * field from `stat` on Mac/BSD and `ftCreationTime` on Windows. This may
1204 * not be available on all platforms. */
1205 birthtime: Date | null;
1206 /** ID of the device containing the file.
1207 *
1208 * _Linux/Mac OS only._ */
1209 dev: number | null;
1210 /** Inode number.
1211 *
1212 * _Linux/Mac OS only._ */
1213 ino: number | null;
1214 /** **UNSTABLE**: Match behavior with Go on Windows for `mode`.
1215 *
1216 * The underlying raw `st_mode` bits that contain the standard Unix
1217 * permissions for this file/directory. */
1218 mode: number | null;
1219 /** Number of hard links pointing to this file.
1220 *
1221 * _Linux/Mac OS only._ */
1222 nlink: number | null;
1223 /** User ID of the owner of this file.
1224 *
1225 * _Linux/Mac OS only._ */
1226 uid: number | null;
1227 /** Group ID of the owner of this file.
1228 *
1229 * _Linux/Mac OS only._ */
1230 gid: number | null;
1231 /** Device ID of this file.
1232 *
1233 * _Linux/Mac OS only._ */
1234 rdev: number | null;
1235 /** Blocksize for filesystem I/O.
1236 *
1237 * _Linux/Mac OS only._ */
1238 blksize: number | null;
1239 /** Number of blocks allocated to the file, in 512-byte units.
1240 *
1241 * _Linux/Mac OS only._ */
1242 blocks: number | null;
1243 }
1244
1245 /** Returns absolute normalized path, with symbolic links resolved.
1246 *
1247 * ```ts
1248 * // e.g. given /home/alice/file.txt and current directory /home/alice
1249 * Deno.symlinkSync("file.txt", "symlink_file.txt");
1250 * const realPath = Deno.realPathSync("./file.txt");
1251 * const realSymLinkPath = Deno.realPathSync("./symlink_file.txt");
1252 * console.log(realPath); // outputs "/home/alice/file.txt"
1253 * console.log(realSymLinkPath); // outputs "/home/alice/file.txt"
1254 * ```
1255 *
1256 * Requires `allow-read` permission. */
1257 export function realPathSync(path: string): string;
1258
1259 /** Resolves to the absolute normalized path, with symbolic links resolved.
1260 *
1261 * ```ts
1262 * // e.g. given /home/alice/file.txt and current directory /home/alice
1263 * await Deno.symlink("file.txt", "symlink_file.txt");
1264 * const realPath = await Deno.realPath("./file.txt");
1265 * const realSymLinkPath = await Deno.realPath("./symlink_file.txt");
1266 * console.log(realPath); // outputs "/home/alice/file.txt"
1267 * console.log(realSymLinkPath); // outputs "/home/alice/file.txt"
1268 * ```
1269 *
1270 * Requires `allow-read` permission. */
1271 export function realPath(path: string): Promise<string>;
1272
1273 export interface DirEntry {
1274 name: string;
1275 isFile: boolean;
1276 isDirectory: boolean;
1277 isSymlink: boolean;
1278 }
1279
1280 /** Synchronously reads the directory given by `path` and returns an iterable
1281 * of `Deno.DirEntry`.
1282 *
1283 * ```ts
1284 * for (const dirEntry of Deno.readDirSync("/")) {
1285 * console.log(dirEntry.name);
1286 * }
1287 * ```
1288 *
1289 * Throws error if `path` is not a directory.
1290 *
1291 * Requires `allow-read` permission. */
1292 export function readDirSync(path: string): Iterable<DirEntry>;
1293
1294 /** Reads the directory given by `path` and returns an async iterable of
1295 * `Deno.DirEntry`.
1296 *
1297 * ```ts
1298 * for await (const dirEntry of Deno.readDir("/")) {
1299 * console.log(dirEntry.name);
1300 * }
1301 * ```
1302 *
1303 * Throws error if `path` is not a directory.
1304 *
1305 * Requires `allow-read` permission. */
1306 export function readDir(path: string): AsyncIterable<DirEntry>;
1307
1308 /** Synchronously copies the contents and permissions of one file to another
1309 * specified path, by default creating a new file if needed, else overwriting.
1310 * Fails if target path is a directory or is unwritable.
1311 *
1312 * ```ts
1313 * Deno.copyFileSync("from.txt", "to.txt");
1314 * ```
1315 *
1316 * Requires `allow-read` permission on fromPath.
1317 * Requires `allow-write` permission on toPath. */
1318 export function copyFileSync(fromPath: string, toPath: string): void;
1319
1320 /** Copies the contents and permissions of one file to another specified path,
1321 * by default creating a new file if needed, else overwriting. Fails if target
1322 * path is a directory or is unwritable.
1323 *
1324 * ```ts
1325 * await Deno.copyFile("from.txt", "to.txt");
1326 * ```
1327 *
1328 * Requires `allow-read` permission on fromPath.
1329 * Requires `allow-write` permission on toPath. */
1330 export function copyFile(fromPath: string, toPath: string): Promise<void>;
1331
1332 /** Returns the full path destination of the named symbolic link.
1333 *
1334 * ```ts
1335 * Deno.symlinkSync("./test.txt", "./test_link.txt");
1336 * const target = Deno.readLinkSync("./test_link.txt"); // full path of ./test.txt
1337 * ```
1338 *
1339 * Throws TypeError if called with a hard link
1340 *
1341 * Requires `allow-read` permission. */
1342 export function readLinkSync(path: string): string;
1343
1344 /** Resolves to the full path destination of the named symbolic link.
1345 *
1346 * ```ts
1347 * await Deno.symlink("./test.txt", "./test_link.txt");
1348 * const target = await Deno.readLink("./test_link.txt"); // full path of ./test.txt
1349 * ```
1350 *
1351 * Throws TypeError if called with a hard link
1352 *
1353 * Requires `allow-read` permission. */
1354 export function readLink(path: string): Promise<string>;
1355
1356 /** Resolves to a `Deno.FileInfo` for the specified `path`. If `path` is a
1357 * symlink, information for the symlink will be returned instead of what it
1358 * points to.
1359 *
1360 * ```ts
1361 * const fileInfo = await Deno.lstat("hello.txt");
1362 * assert(fileInfo.isFile);
1363 * ```
1364 *
1365 * Requires `allow-read` permission. */
1366 export function lstat(path: string): Promise<FileInfo>;
1367
1368 /** Synchronously returns a `Deno.FileInfo` for the specified `path`. If
1369 * `path` is a symlink, information for the symlink will be returned instead of
1370 * what it points to..
1371 *
1372 * ```ts
1373 * const fileInfo = Deno.lstatSync("hello.txt");
1374 * assert(fileInfo.isFile);
1375 * ```
1376 *
1377 * Requires `allow-read` permission. */
1378 export function lstatSync(path: string): FileInfo;
1379
1380 /** Resolves to a `Deno.FileInfo` for the specified `path`. Will always
1381 * follow symlinks.
1382 *
1383 * ```ts
1384 * const fileInfo = await Deno.stat("hello.txt");
1385 * assert(fileInfo.isFile);
1386 * ```
1387 *
1388 * Requires `allow-read` permission. */
1389 export function stat(path: string): Promise<FileInfo>;
1390
1391 /** Synchronously returns a `Deno.FileInfo` for the specified `path`. Will
1392 * always follow symlinks.
1393 *
1394 * ```ts
1395 * const fileInfo = Deno.statSync("hello.txt");
1396 * assert(fileInfo.isFile);
1397 * ```
1398 *
1399 * Requires `allow-read` permission. */
1400 export function statSync(path: string): FileInfo;
1401
1402 /** Options for writing to a file. */
1403 export interface WriteFileOptions {
1404 /** Defaults to `false`. If set to `true`, will append to a file instead of
1405 * overwriting previous contents. */
1406 append?: boolean;
1407 /** Sets the option to allow creating a new file, if one doesn't already
1408 * exist at the specified path (defaults to `true`). */
1409 create?: boolean;
1410 /** Permissions always applied to file. */
1411 mode?: number;
1412 }
1413
1414 /** Synchronously write `data` to the given `path`, by default creating a new
1415 * file if needed, else overwriting.
1416 *
1417 * ```ts
1418 * const encoder = new TextEncoder();
1419 * const data = encoder.encode("Hello world\n");
1420 * Deno.writeFileSync("hello1.txt", data); // overwrite "hello1.txt" or create it
1421 * Deno.writeFileSync("hello2.txt", data, {create: false}); // only works if "hello2.txt" exists
1422 * Deno.writeFileSync("hello3.txt", data, {mode: 0o777}); // set permissions on new file
1423 * Deno.writeFileSync("hello4.txt", data, {append: true}); // add data to the end of the file
1424 * ```
1425 *
1426 * Requires `allow-write` permission, and `allow-read` if `options.create` is
1427 * `false`.
1428 */
1429 export function writeFileSync(
1430 path: string,
1431 data: Uint8Array,
1432 options?: WriteFileOptions
1433 ): void;
1434
1435 /** Write `data` to the given `path`, by default creating a new file if needed,
1436 * else overwriting.
1437 *
1438 * ```ts
1439 * const encoder = new TextEncoder();
1440 * const data = encoder.encode("Hello world\n");
1441 * await Deno.writeFile("hello1.txt", data); // overwrite "hello1.txt" or create it
1442 * await Deno.writeFile("hello2.txt", data, {create: false}); // only works if "hello2.txt" exists
1443 * await Deno.writeFile("hello3.txt", data, {mode: 0o777}); // set permissions on new file
1444 * await Deno.writeFile("hello4.txt", data, {append: true}); // add data to the end of the file
1445 * ```
1446 *
1447 * Requires `allow-write` permission, and `allow-read` if `options.create` is `false`.
1448 */
1449 export function writeFile(
1450 path: string,
1451 data: Uint8Array,
1452 options?: WriteFileOptions
1453 ): Promise<void>;
1454
1455 /** Synchronously write string `data` to the given `path`, by default creating a new file if needed,
1456 * else overwriting.
1457 *
1458 * ```ts
1459 * await Deno.writeTextFileSync("hello1.txt", "Hello world\n"); // overwrite "hello1.txt" or create it
1460 * ```
1461 *
1462 * Requires `allow-write` permission, and `allow-read` if `options.create` is `false`.
1463 */
1464 export function writeTextFileSync(path: string, data: string): void;
1465
1466 /** Asynchronously write string `data` to the given `path`, by default creating a new file if needed,
1467 * else overwriting.
1468 *
1469 * ```ts
1470 * await Deno.writeTextFile("hello1.txt", "Hello world\n"); // overwrite "hello1.txt" or create it
1471 * ```
1472 *
1473 * Requires `allow-write` permission, and `allow-read` if `options.create` is `false`.
1474 */
1475 export function writeTextFile(path: string, data: string): Promise<void>;
1476
1477 /** Synchronously truncates or extends the specified file, to reach the
1478 * specified `len`. If `len` is not specified then the entire file contents
1479 * are truncated.
1480 *
1481 * ```ts
1482 * // truncate the entire file
1483 * Deno.truncateSync("my_file.txt");
1484 *
1485 * // truncate part of the file
1486 * const file = Deno.makeTempFileSync();
1487 * Deno.writeFileSync(file, new TextEncoder().encode("Hello World"));
1488 * Deno.truncateSync(file, 7);
1489 * const data = Deno.readFileSync(file);
1490 * console.log(new TextDecoder().decode(data));
1491 * ```
1492 *
1493 * Requires `allow-write` permission. */
1494 export function truncateSync(name: string, len?: number): void;
1495
1496 /** Truncates or extends the specified file, to reach the specified `len`. If
1497 * `len` is not specified then the entire file contents are truncated.
1498 *
1499 * ```ts
1500 * // truncate the entire file
1501 * await Deno.truncate("my_file.txt");
1502 *
1503 * // truncate part of the file
1504 * const file = await Deno.makeTempFile();
1505 * await Deno.writeFile(file, new TextEncoder().encode("Hello World"));
1506 * await Deno.truncate(file, 7);
1507 * const data = await Deno.readFile(file);
1508 * console.log(new TextDecoder().decode(data)); // "Hello W"
1509 * ```
1510 *
1511 * Requires `allow-write` permission. */
1512 export function truncate(name: string, len?: number): Promise<void>;
1513
1514 export interface NetAddr {
1515 transport: "tcp" | "udp";
1516 hostname: string;
1517 port: number;
1518 }
1519
1520 export interface UnixAddr {
1521 transport: "unix" | "unixpacket";
1522 path: string;
1523 }
1524
1525 export type Addr = NetAddr | UnixAddr;
1526
1527 /** A generic network listener for stream-oriented protocols. */
1528 export interface Listener extends AsyncIterable<Conn> {
1529 /** Waits for and resolves to the next connection to the `Listener`. */
1530 accept(): Promise<Conn>;
1531 /** Close closes the listener. Any pending accept promises will be rejected
1532 * with errors. */
1533 close(): void;
1534 /** Return the address of the `Listener`. */
1535 readonly addr: Addr;
1536
1537 [Symbol.asyncIterator](): AsyncIterableIterator<Conn>;
1538 }
1539
1540 export interface Conn extends Reader, Writer, Closer {
1541 /** The local address of the connection. */
1542 readonly localAddr: Addr;
1543 /** The remote address of the connection. */
1544 readonly remoteAddr: Addr;
1545 /** The resource ID of the connection. */
1546 readonly rid: number;
1547 /** Shuts down (`shutdown(2)`) the writing side of the TCP connection. Most
1548 * callers should just use `close()`.
1549 *
1550 * **Unstable** because of lack of testing and because Deno.shutdown is also
1551 * unstable.
1552 * */
1553 closeWrite(): void;
1554 }
1555
1556 export interface ListenOptions {
1557 /** The port to listen on. */
1558 port: number;
1559 /** A literal IP address or host name that can be resolved to an IP address.
1560 * If not specified, defaults to `0.0.0.0`. */
1561 hostname?: string;
1562 }
1563
1564 /** Listen announces on the local transport address.
1565 *
1566 * ```ts
1567 * const listener1 = Deno.listen({ port: 80 })
1568 * const listener2 = Deno.listen({ hostname: "192.0.2.1", port: 80 })
1569 * const listener3 = Deno.listen({ hostname: "[2001:db8::1]", port: 80 });
1570 * const listener4 = Deno.listen({ hostname: "golang.org", port: 80, transport: "tcp" });
1571 * ```
1572 *
1573 * Requires `allow-net` permission. */
1574 export function listen(
1575 options: ListenOptions & { transport?: "tcp" }
1576 ): Listener;
1577
1578 export interface ListenTlsOptions extends ListenOptions {
1579 /** Server certificate file. */
1580 certFile: string;
1581 /** Server public key file. */
1582 keyFile: string;
1583
1584 transport?: "tcp";
1585 }
1586
1587 /** Listen announces on the local transport address over TLS (transport layer
1588 * security).
1589 *
1590 * ```ts
1591 * const lstnr = Deno.listenTls({ port: 443, certFile: "./server.crt", keyFile: "./server.key" });
1592 * ```
1593 *
1594 * Requires `allow-net` permission. */
1595 export function listenTls(options: ListenTlsOptions): Listener;
1596
1597 export interface ConnectOptions {
1598 /** The port to connect to. */
1599 port: number;
1600 /** A literal IP address or host name that can be resolved to an IP address.
1601 * If not specified, defaults to `127.0.0.1`. */
1602 hostname?: string;
1603 transport?: "tcp";
1604 }
1605
1606 /**
1607 * Connects to the hostname (default is "127.0.0.1") and port on the named
1608 * transport (default is "tcp"), and resolves to the connection (`Conn`).
1609 *
1610 * ```ts
1611 * const conn1 = await Deno.connect({ port: 80 });
1612 * const conn2 = await Deno.connect({ hostname: "192.0.2.1", port: 80 });
1613 * const conn3 = await Deno.connect({ hostname: "[2001:db8::1]", port: 80 });
1614 * const conn4 = await Deno.connect({ hostname: "golang.org", port: 80, transport: "tcp" });
1615 * const conn5 = await Deno.connect({ path: "/foo/bar.sock", transport: "unix" });
1616 * ```
1617 *
1618 * Requires `allow-net` permission for "tcp" and `allow-read` for unix. */
1619 export function connect(options: ConnectOptions): Promise<Conn>;
1620
1621 export interface ConnectTlsOptions {
1622 /** The port to connect to. */
1623 port: number;
1624 /** A literal IP address or host name that can be resolved to an IP address.
1625 * If not specified, defaults to `127.0.0.1`. */
1626 hostname?: string;
1627 /** Server certificate file. */
1628 certFile?: string;
1629 }
1630
1631 /** Establishes a secure connection over TLS (transport layer security) using
1632 * an optional cert file, hostname (default is "127.0.0.1") and port. The
1633 * cert file is optional and if not included Mozilla's root certificates will
1634 * be used (see also https://github.com/ctz/webpki-roots for specifics)
1635 *
1636 * ```ts
1637 * const conn1 = await Deno.connectTls({ port: 80 });
1638 * const conn2 = await Deno.connectTls({ certFile: "./certs/my_custom_root_CA.pem", hostname: "192.0.2.1", port: 80 });
1639 * const conn3 = await Deno.connectTls({ hostname: "[2001:db8::1]", port: 80 });
1640 * const conn4 = await Deno.connectTls({ certFile: "./certs/my_custom_root_CA.pem", hostname: "golang.org", port: 80});
1641 * ```
1642 *
1643 * Requires `allow-net` permission.
1644 */
1645 export function connectTls(options: ConnectTlsOptions): Promise<Conn>;
1646
1647 export interface Metrics {
1648 opsDispatched: number;
1649 opsDispatchedSync: number;
1650 opsDispatchedAsync: number;
1651 opsDispatchedAsyncUnref: number;
1652 opsCompleted: number;
1653 opsCompletedSync: number;
1654 opsCompletedAsync: number;
1655 opsCompletedAsyncUnref: number;
1656 bytesSentControl: number;
1657 bytesSentData: number;
1658 bytesReceived: number;
1659 }
1660
1661 /** Receive metrics from the privileged side of Deno. This is primarily used
1662 * in the development of Deno. 'Ops', also called 'bindings', are the go-between
1663 * between Deno JavaScript and Deno Rust.
1664 *
1665 * > console.table(Deno.metrics())
1666 * ┌─────────────────────────┬────────┐
1667 * │ (index) │ Values │
1668 * ├─────────────────────────┼────────┤
1669 * │ opsDispatched │ 3 │
1670 * │ opsDispatchedSync │ 2 │
1671 * │ opsDispatchedAsync │ 1 │
1672 * │ opsDispatchedAsyncUnref │ 0 │
1673 * │ opsCompleted │ 3 │
1674 * │ opsCompletedSync │ 2 │
1675 * │ opsCompletedAsync │ 1 │
1676 * │ opsCompletedAsyncUnref │ 0 │
1677 * │ bytesSentControl │ 73 │
1678 * │ bytesSentData │ 0 │
1679 * │ bytesReceived │ 375 │
1680 * └─────────────────────────┴────────┘
1681 */
1682 export function metrics(): Metrics;
1683
1684 interface ResourceMap {
1685 // eslint-disable-next-line @typescript-eslint/no-explicit-any
1686 [rid: number]: any;
1687 }
1688
1689 /** Returns a map of open resource ids (rid) along with their string
1690 * representations. This is an internal API and as such resource
1691 * representation has `any` type; that means it can change any time.
1692 *
1693 * ```ts
1694 * console.log(Deno.resources());
1695 * // { 0: "stdin", 1: "stdout", 2: "stderr" }
1696 * Deno.openSync('../test.file');
1697 * console.log(Deno.resources());
1698 * // { 0: "stdin", 1: "stdout", 2: "stderr", 3: "fsFile" }
1699 * ```
1700 */
1701 export function resources(): ResourceMap;
1702
1703 export interface FsEvent {
1704 kind: "any" | "access" | "create" | "modify" | "remove";
1705 paths: string[];
1706 }
1707
1708 /** Watch for file system events against one or more `paths`, which can be files
1709 * or directories. These paths must exist already. One user action (e.g.
1710 * `touch test.file`) can generate multiple file system events. Likewise,
1711 * one user action can result in multiple file paths in one event (e.g. `mv
1712 * old_name.txt new_name.txt`). Recursive option is `true` by default and,
1713 * for directories, will watch the specified directory and all sub directories.
1714 * Note that the exact ordering of the events can vary between operating systems.
1715 *
1716 * ```ts
1717 * const watcher = Deno.watchFs("/");
1718 * for await (const event of watcher) {
1719 * console.log(">>>> event", event);
1720 * // { kind: "create", paths: [ "/foo.txt" ] }
1721 * }
1722 *```
1723 *
1724 * Requires `allow-read` permission.
1725 */
1726 export function watchFs(
1727 paths: string | string[],
1728 options?: { recursive: boolean }
1729 ): AsyncIterableIterator<FsEvent>;
1730
1731 export class Process {
1732 readonly rid: number;
1733 readonly pid: number;
1734 readonly stdin?: Writer & Closer;
1735 readonly stdout?: Reader & Closer;
1736 readonly stderr?: Reader & Closer;
1737 /** Resolves to the current status of the process. */
1738 status(): Promise<ProcessStatus>;
1739 /** Buffer the stdout until EOF and return it as `Uint8Array`.
1740 *
1741 * You must set stdout to `"piped"` when creating the process.
1742 *
1743 * This calls `close()` on stdout after its done. */
1744 output(): Promise<Uint8Array>;
1745 /** Buffer the stderr until EOF and return it as `Uint8Array`.
1746 *
1747 * You must set stderr to `"piped"` when creating the process.
1748 *
1749 * This calls `close()` on stderr after its done. */
1750 stderrOutput(): Promise<Uint8Array>;
1751 close(): void;
1752
1753 /** **UNSTABLE**: The `signo` argument may change to require the Deno.Signal
1754 * enum.
1755 *
1756 * Send a signal to process. This functionality currently only works on
1757 * Linux and Mac OS.
1758 */
1759 kill(signo: number): void;
1760 }
1761
1762 export type ProcessStatus =
1763 | {
1764 success: true;
1765 code: 0;
1766 signal?: undefined;
1767 }
1768 | {
1769 success: false;
1770 code: number;
1771 signal?: number;
1772 };
1773
1774 export interface RunOptions {
1775 /** Arguments to pass. Note, the first element needs to be a path to the
1776 * binary */
1777 cmd: string[];
1778 cwd?: string;
1779 env?: {
1780 [key: string]: string;
1781 };
1782 stdout?: "inherit" | "piped" | "null" | number;
1783 stderr?: "inherit" | "piped" | "null" | number;
1784 stdin?: "inherit" | "piped" | "null" | number;
1785 }
1786
1787 /** Spawns new subprocess. RunOptions must contain at a minimum the `opt.cmd`,
1788 * an array of program arguments, the first of which is the binary.
1789 *
1790 * ```ts
1791 * const p = Deno.run({
1792 * cmd: ["echo", "hello"],
1793 * });
1794 * ```
1795 *
1796 * Subprocess uses same working directory as parent process unless `opt.cwd`
1797 * is specified.
1798 *
1799 * Environmental variables for subprocess can be specified using `opt.env`
1800 * mapping.
1801 *
1802 * By default subprocess inherits stdio of parent process. To change that
1803 * `opt.stdout`, `opt.stderr` and `opt.stdin` can be specified independently -
1804 * they can be set to either an rid of open file or set to "inherit" "piped"
1805 * or "null":
1806 *
1807 * `"inherit"` The default if unspecified. The child inherits from the
1808 * corresponding parent descriptor.
1809 *
1810 * `"piped"` A new pipe should be arranged to connect the parent and child
1811 * sub-processes.
1812 *
1813 * `"null"` This stream will be ignored. This is the equivalent of attaching
1814 * the stream to `/dev/null`.
1815 *
1816 * Details of the spawned process are returned.
1817 *
1818 * Requires `allow-run` permission. */
1819 export function run(opt: RunOptions): Process;
1820
1821 interface InspectOptions {
1822 depth?: number;
1823 }
1824
1825 /** Converts the input into a string that has the same format as printed by
1826 * `console.log()`.
1827 *
1828 * ```ts
1829 * const obj = {};
1830 * obj.propA = 10;
1831 * obj.propB = "hello"
1832 * const objAsString = Deno.inspect(obj); // { propA: 10, propB: "hello" }
1833 * console.log(obj); // prints same value as objAsString, e.g. { propA: 10, propB: "hello" }
1834 * ```
1835 *
1836 * You can also register custom inspect functions, via the `customInspect` Deno
1837 * symbol on objects, to control and customize the output.
1838 *
1839 * ```ts
1840 * class A {
1841 * x = 10;
1842 * y = "hello";
1843 * [Deno.customInspect](): string {
1844 * return "x=" + this.x + ", y=" + this.y;
1845 * }
1846 * }
1847 * ```
1848 *
1849 * const inStringFormat = Deno.inspect(new A()); // "x=10, y=hello"
1850 * console.log(inStringFormat); // prints "x=10, y=hello"
1851 *
1852 * Finally, a number of output options are also available.
1853 *
1854 * const out = Deno.inspect(obj, {showHidden: true, depth: 4, colors: true, indentLevel: 2});
1855 *
1856 */
1857 export function inspect(value: unknown, options?: InspectOptions): string;
1858
1859 /** Build related information. */
1860 export const build: {
1861 /** The LLVM target triple */
1862 target: string;
1863 /** Instruction set architecture */
1864 arch: "x86_64";
1865 /** Operating system */
1866 os: "darwin" | "linux" | "windows";
1867 /** Computer vendor */
1868 vendor: string;
1869 /** Optional environment */
1870 env?: string;
1871 };
1872
1873 interface Version {
1874 deno: string;
1875 v8: string;
1876 typescript: string;
1877 }
1878 /** Version related information. */
1879 export const version: Version;
1880
1881 /** Returns the script arguments to the program. If for example we run a
1882 * program:
1883 *
1884 * deno run --allow-read https://deno.land/std/examples/cat.ts /etc/passwd
1885 *
1886 * Then `Deno.args` will contain:
1887 *
1888 * [ "/etc/passwd" ]
1889 */
1890 export const args: string[];
1891
1892 /** A symbol which can be used as a key for a custom method which will be
1893 * called when `Deno.inspect()` is called, or when the object is logged to
1894 * the console. */
1895 export const customInspect: unique symbol;
1896}
1897
1898// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
1899
1900/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, no-var */
1901
1902/// <reference no-default-lib="true" />
1903/// <reference lib="esnext" />
1904
1905// This follows the WebIDL at: https://webassembly.github.io/spec/js-api/
1906// and: https://webassembly.github.io/spec/web-api/
1907declare namespace WebAssembly {
1908 interface WebAssemblyInstantiatedSource {
1909 module: Module;
1910 instance: Instance;
1911 }
1912
1913 /** Compiles a `WebAssembly.Module` from WebAssembly binary code. This
1914 * function is useful if it is necessary to a compile a module before it can
1915 * be instantiated (otherwise, the `WebAssembly.instantiate()` function
1916 * should be used). */
1917 function compile(bufferSource: BufferSource): Promise<Module>;
1918
1919 /** Compiles a `WebAssembly.Module` directly from a streamed underlying
1920 * source. This function is useful if it is necessary to a compile a module
1921 * before it can be instantiated (otherwise, the
1922 * `WebAssembly.instantiateStreaming()` function should be used). */
1923 function compileStreaming(source: Promise<Response>): Promise<Module>;
1924
1925 /** Takes the WebAssembly binary code, in the form of a typed array or
1926 * `ArrayBuffer`, and performs both compilation and instantiation in one step.
1927 * The returned `Promise` resolves to both a compiled `WebAssembly.Module` and
1928 * its first `WebAssembly.Instance`. */
1929 function instantiate(
1930 bufferSource: BufferSource,
1931 importObject?: object
1932 ): Promise<WebAssemblyInstantiatedSource>;
1933
1934 /** Takes an already-compiled `WebAssembly.Module` and returns a `Promise`
1935 * that resolves to an `Instance` of that `Module`. This overload is useful if
1936 * the `Module` has already been compiled. */
1937 function instantiate(
1938 module: Module,
1939 importObject?: object
1940 ): Promise<Instance>;
1941
1942 /** Compiles and instantiates a WebAssembly module directly from a streamed
1943 * underlying source. This is the most efficient, optimized way to load wasm
1944 * code. */
1945 function instantiateStreaming(
1946 source: Promise<Response>,
1947 importObject?: object
1948 ): Promise<WebAssemblyInstantiatedSource>;
1949
1950 /** Validates a given typed array of WebAssembly binary code, returning
1951 * whether the bytes form a valid wasm module (`true`) or not (`false`). */
1952 function validate(bufferSource: BufferSource): boolean;
1953
1954 type ImportExportKind = "function" | "table" | "memory" | "global";
1955
1956 interface ModuleExportDescriptor {
1957 name: string;
1958 kind: ImportExportKind;
1959 }
1960 interface ModuleImportDescriptor {
1961 module: string;
1962 name: string;
1963 kind: ImportExportKind;
1964 }
1965
1966 class Module {
1967 constructor(bufferSource: BufferSource);
1968
1969 /** Given a `Module` and string, returns a copy of the contents of all
1970 * custom sections in the module with the given string name. */
1971 static customSections(
1972 moduleObject: Module,
1973 sectionName: string
1974 ): ArrayBuffer;
1975
1976 /** Given a `Module`, returns an array containing descriptions of all the
1977 * declared exports. */
1978 static exports(moduleObject: Module): ModuleExportDescriptor[];
1979
1980 /** Given a `Module`, returns an array containing descriptions of all the
1981 * declared imports. */
1982 static imports(moduleObject: Module): ModuleImportDescriptor[];
1983 }
1984
1985 class Instance<T extends object = { [key: string]: any }> {
1986 constructor(module: Module, importObject?: object);
1987
1988 /** An object containing as its members all the functions exported from the
1989 * WebAssembly module instance, to allow them to be accessed and used by
1990 * JavaScript. */
1991 readonly exports: T;
1992 }
1993
1994 interface MemoryDescriptor {
1995 initial: number;
1996 maximum?: number;
1997 }
1998
1999 class Memory {
2000 constructor(descriptor: MemoryDescriptor);
2001
2002 /** An accessor property that returns the buffer contained in the memory. */
2003 readonly buffer: ArrayBuffer;
2004
2005 /** Increases the size of the memory instance by a specified number of
2006 * WebAssembly pages (each one is 64KB in size). */
2007 grow(delta: number): number;
2008 }
2009
2010 type TableKind = "anyfunc";
2011
2012 interface TableDescriptor {
2013 element: TableKind;
2014 initial: number;
2015 maximum?: number;
2016 }
2017
2018 class Table {
2019 constructor(descriptor: TableDescriptor);
2020
2021 /** Returns the length of the table, i.e. the number of elements. */
2022 readonly length: number;
2023
2024 /** Accessor function — gets the element stored at a given index. */
2025 get(index: number): (...args: any[]) => any;
2026
2027 /** Increases the size of the Table instance by a specified number of
2028 * elements. */
2029 grow(delta: number): number;
2030
2031 /** Sets an element stored at a given index to a given value. */
2032 set(index: number, value: (...args: any[]) => any): void;
2033 }
2034
2035 type ValueType = "i32" | "i64" | "f32" | "f64";
2036
2037 interface GlobalDescriptor {
2038 value: ValueType;
2039 mutable?: boolean;
2040 }
2041
2042 /** Represents a global variable instance, accessible from both JavaScript and
2043 * importable/exportable across one or more `WebAssembly.Module` instances.
2044 * This allows dynamic linking of multiple modules. */
2045 class Global {
2046 constructor(descriptor: GlobalDescriptor, value?: any);
2047
2048 /** Old-style method that returns the value contained inside the global
2049 * variable. */
2050 valueOf(): any;
2051
2052 /** The value contained inside the global variable — this can be used to
2053 * directly set and get the global's value. */
2054 value: any;
2055 }
2056
2057 /** Indicates an error during WebAssembly decoding or validation */
2058 class CompileError extends Error {
2059 constructor(message: string, fileName?: string, lineNumber?: string);
2060 }
2061
2062 /** Indicates an error during module instantiation (besides traps from the
2063 * start function). */
2064 class LinkError extends Error {
2065 constructor(message: string, fileName?: string, lineNumber?: string);
2066 }
2067
2068 /** Is thrown whenever WebAssembly specifies a trap. */
2069 class RuntimeError extends Error {
2070 constructor(message: string, fileName?: string, lineNumber?: string);
2071 }
2072}
2073
2074/** Sets a timer which executes a function once after the timer expires. */
2075declare function setTimeout(
2076 cb: (...args: any[]) => void,
2077 delay?: number,
2078 ...args: any[]
2079): number;
2080
2081/** Repeatedly calls a function , with a fixed time delay between each call. */
2082declare function setInterval(
2083 cb: (...args: any[]) => void,
2084 delay?: number,
2085 ...args: any[]
2086): number;
2087declare function clearTimeout(id?: number): void;
2088declare function clearInterval(id?: number): void;
2089declare function queueMicrotask(func: Function): void;
2090
2091declare var console: Console;
2092declare var crypto: Crypto;
2093
2094declare function addEventListener(
2095 type: string,
2096 callback: EventListenerOrEventListenerObject | null,
2097 options?: boolean | AddEventListenerOptions | undefined
2098): void;
2099
2100declare function dispatchEvent(event: Event): boolean;
2101
2102declare function removeEventListener(
2103 type: string,
2104 callback: EventListenerOrEventListenerObject | null,
2105 options?: boolean | EventListenerOptions | undefined
2106): void;
2107
2108declare interface ImportMeta {
2109 url: string;
2110 main: boolean;
2111}
2112
2113interface DomIterable<K, V> {
2114 keys(): IterableIterator<K>;
2115 values(): IterableIterator<V>;
2116 entries(): IterableIterator<[K, V]>;
2117 [Symbol.iterator](): IterableIterator<[K, V]>;
2118 forEach(
2119 callback: (value: V, key: K, parent: this) => void,
2120 thisArg?: any
2121 ): void;
2122}
2123
2124interface ReadableStreamReadDoneResult<T> {
2125 done: true;
2126 value?: T;
2127}
2128
2129interface ReadableStreamReadValueResult<T> {
2130 done: false;
2131 value: T;
2132}
2133
2134type ReadableStreamReadResult<T> =
2135 | ReadableStreamReadValueResult<T>
2136 | ReadableStreamReadDoneResult<T>;
2137
2138interface ReadableStreamDefaultReader<R = any> {
2139 readonly closed: Promise<void>;
2140 cancel(reason?: any): Promise<void>;
2141 read(): Promise<ReadableStreamReadResult<R>>;
2142 releaseLock(): void;
2143}
2144
2145interface ReadableStreamReader<R = any> {
2146 cancel(): Promise<void>;
2147 read(): Promise<ReadableStreamReadResult<R>>;
2148 releaseLock(): void;
2149}
2150
2151interface ReadableByteStreamControllerCallback {
2152 (controller: ReadableByteStreamController): void | PromiseLike<void>;
2153}
2154
2155interface UnderlyingByteSource {
2156 autoAllocateChunkSize?: number;
2157 cancel?: ReadableStreamErrorCallback;
2158 pull?: ReadableByteStreamControllerCallback;
2159 start?: ReadableByteStreamControllerCallback;
2160 type: "bytes";
2161}
2162
2163interface UnderlyingSource<R = any> {
2164 cancel?: ReadableStreamErrorCallback;
2165 pull?: ReadableStreamDefaultControllerCallback<R>;
2166 start?: ReadableStreamDefaultControllerCallback<R>;
2167 type?: undefined;
2168}
2169
2170interface ReadableStreamErrorCallback {
2171 (reason: any): void | PromiseLike<void>;
2172}
2173
2174interface ReadableStreamDefaultControllerCallback<R> {
2175 (controller: ReadableStreamDefaultController<R>): void | PromiseLike<void>;
2176}
2177
2178interface ReadableStreamDefaultController<R = any> {
2179 readonly desiredSize: number | null;
2180 close(): void;
2181 enqueue(chunk: R): void;
2182 error(error?: any): void;
2183}
2184
2185interface ReadableByteStreamController {
2186 readonly byobRequest: undefined;
2187 readonly desiredSize: number | null;
2188 close(): void;
2189 enqueue(chunk: ArrayBufferView): void;
2190 error(error?: any): void;
2191}
2192
2193interface PipeOptions {
2194 preventAbort?: boolean;
2195 preventCancel?: boolean;
2196 preventClose?: boolean;
2197 signal?: AbortSignal;
2198}
2199
2200interface QueuingStrategySizeCallback<T = any> {
2201 (chunk: T): number;
2202}
2203
2204interface QueuingStrategy<T = any> {
2205 highWaterMark?: number;
2206 size?: QueuingStrategySizeCallback<T>;
2207}
2208
2209/** This Streams API interface provides a built-in byte length queuing strategy
2210 * that can be used when constructing streams. */
2211declare class CountQueuingStrategy implements QueuingStrategy {
2212 constructor(options: { highWaterMark: number });
2213 highWaterMark: number;
2214 size(chunk: any): 1;
2215}
2216
2217declare class ByteLengthQueuingStrategy
2218 implements QueuingStrategy<ArrayBufferView> {
2219 constructor(options: { highWaterMark: number });
2220 highWaterMark: number;
2221 size(chunk: ArrayBufferView): number;
2222}
2223
2224/** This Streams API interface represents a readable stream of byte data. The
2225 * Fetch API offers a concrete instance of a ReadableStream through the body
2226 * property of a Response object. */
2227interface ReadableStream<R = any> {
2228 readonly locked: boolean;
2229 cancel(reason?: any): Promise<void>;
2230 getIterator(options?: { preventCancel?: boolean }): AsyncIterableIterator<R>;
2231 // getReader(options: { mode: "byob" }): ReadableStreamBYOBReader;
2232 getReader(): ReadableStreamDefaultReader<R>;
2233 pipeThrough<T>(
2234 {
2235 writable,
2236 readable,
2237 }: {
2238 writable: WritableStream<R>;
2239 readable: ReadableStream<T>;
2240 },
2241 options?: PipeOptions
2242 ): ReadableStream<T>;
2243 pipeTo(dest: WritableStream<R>, options?: PipeOptions): Promise<void>;
2244 tee(): [ReadableStream<R>, ReadableStream<R>];
2245 [Symbol.asyncIterator](options?: {
2246 preventCancel?: boolean;
2247 }): AsyncIterableIterator<R>;
2248}
2249
2250declare var ReadableStream: {
2251 prototype: ReadableStream;
2252 new (
2253 underlyingSource: UnderlyingByteSource,
2254 strategy?: { highWaterMark?: number; size?: undefined }
2255 ): ReadableStream<Uint8Array>;
2256 new <R = any>(
2257 underlyingSource?: UnderlyingSource<R>,
2258 strategy?: QueuingStrategy<R>
2259 ): ReadableStream<R>;
2260};
2261
2262interface WritableStreamDefaultControllerCloseCallback {
2263 (): void | PromiseLike<void>;
2264}
2265
2266interface WritableStreamDefaultControllerStartCallback {
2267 (controller: WritableStreamDefaultController): void | PromiseLike<void>;
2268}
2269
2270interface WritableStreamDefaultControllerWriteCallback<W> {
2271 (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike<
2272 void
2273 >;
2274}
2275
2276interface WritableStreamErrorCallback {
2277 (reason: any): void | PromiseLike<void>;
2278}
2279
2280interface UnderlyingSink<W = any> {
2281 abort?: WritableStreamErrorCallback;
2282 close?: WritableStreamDefaultControllerCloseCallback;
2283 start?: WritableStreamDefaultControllerStartCallback;
2284 type?: undefined;
2285 write?: WritableStreamDefaultControllerWriteCallback<W>;
2286}
2287
2288/** This Streams API interface provides a standard abstraction for writing
2289 * streaming data to a destination, known as a sink. This object comes with
2290 * built-in backpressure and queuing. */
2291declare class WritableStream<W = any> {
2292 constructor(
2293 underlyingSink?: UnderlyingSink<W>,
2294 strategy?: QueuingStrategy<W>
2295 );
2296 readonly locked: boolean;
2297 abort(reason?: any): Promise<void>;
2298 close(): Promise<void>;
2299 getWriter(): WritableStreamDefaultWriter<W>;
2300}
2301
2302/** This Streams API interface represents a controller allowing control of a
2303 * WritableStream's state. When constructing a WritableStream, the underlying
2304 * sink is given a corresponding WritableStreamDefaultController instance to
2305 * manipulate. */
2306interface WritableStreamDefaultController {
2307 error(error?: any): void;
2308}
2309
2310/** This Streams API interface is the object returned by
2311 * WritableStream.getWriter() and once created locks the < writer to the
2312 * WritableStream ensuring that no other streams can write to the underlying
2313 * sink. */
2314interface WritableStreamDefaultWriter<W = any> {
2315 readonly closed: Promise<void>;
2316 readonly desiredSize: number | null;
2317 readonly ready: Promise<void>;
2318 abort(reason?: any): Promise<void>;
2319 close(): Promise<void>;
2320 releaseLock(): void;
2321 write(chunk: W): Promise<void>;
2322}
2323
2324declare class TransformStream<I = any, O = any> {
2325 constructor(
2326 transformer?: Transformer<I, O>,
2327 writableStrategy?: QueuingStrategy<I>,
2328 readableStrategy?: QueuingStrategy<O>
2329 );
2330 readonly readable: ReadableStream<O>;
2331 readonly writable: WritableStream<I>;
2332}
2333
2334interface TransformStreamDefaultController<O = any> {
2335 readonly desiredSize: number | null;
2336 enqueue(chunk: O): void;
2337 error(reason?: any): void;
2338 terminate(): void;
2339}
2340
2341interface Transformer<I = any, O = any> {
2342 flush?: TransformStreamDefaultControllerCallback<O>;
2343 readableType?: undefined;
2344 start?: TransformStreamDefaultControllerCallback<O>;
2345 transform?: TransformStreamDefaultControllerTransformCallback<I, O>;
2346 writableType?: undefined;
2347}
2348
2349interface TransformStreamDefaultControllerCallback<O> {
2350 (controller: TransformStreamDefaultController<O>): void | PromiseLike<void>;
2351}
2352
2353interface TransformStreamDefaultControllerTransformCallback<I, O> {
2354 (
2355 chunk: I,
2356 controller: TransformStreamDefaultController<O>
2357 ): void | PromiseLike<void>;
2358}
2359
2360interface DOMStringList {
2361 /** Returns the number of strings in strings. */
2362 readonly length: number;
2363 /** Returns true if strings contains string, and false otherwise. */
2364 contains(string: string): boolean;
2365 /** Returns the string with index index from strings. */
2366 item(index: number): string | null;
2367 [index: number]: string;
2368}
2369
2370declare class DOMException extends Error {
2371 constructor(message?: string, name?: string);
2372 readonly name: string;
2373 readonly message: string;
2374}
2375
2376type BufferSource = ArrayBufferView | ArrayBuffer;
2377type BlobPart = BufferSource | Blob | string;
2378
2379interface BlobPropertyBag {
2380 type?: string;
2381 ending?: "transparent" | "native";
2382}
2383
2384/** 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. */
2385interface Blob {
2386 readonly size: number;
2387 readonly type: string;
2388 arrayBuffer(): Promise<ArrayBuffer>;
2389 slice(start?: number, end?: number, contentType?: string): Blob;
2390 stream(): ReadableStream;
2391 text(): Promise<string>;
2392}
2393
2394declare const Blob: {
2395 prototype: Blob;
2396 new (blobParts?: BlobPart[], options?: BlobPropertyBag): Blob;
2397};
2398
2399interface FilePropertyBag extends BlobPropertyBag {
2400 lastModified?: number;
2401}
2402
2403/** Provides information about files and allows JavaScript in a web page to
2404 * access their content. */
2405interface File extends Blob {
2406 readonly lastModified: number;
2407 readonly name: string;
2408}
2409
2410declare const File: {
2411 prototype: File;
2412 new (fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File;
2413};
2414
2415declare const isConsoleInstance: unique symbol;
2416
2417declare class Console {
2418 indentLevel: number;
2419 [isConsoleInstance]: boolean;
2420 /** Writes the arguments to stdout */
2421 log: (...args: unknown[]) => void;
2422 /** Writes the arguments to stdout */
2423 debug: (...args: unknown[]) => void;
2424 /** Writes the arguments to stdout */
2425 info: (...args: unknown[]) => void;
2426 /** Writes the properties of the supplied `obj` to stdout */
2427 dir: (
2428 obj: unknown,
2429 options?: Partial<{
2430 depth: number;
2431 indentLevel: number;
2432 }>
2433 ) => void;
2434
2435 /** From MDN:
2436 * Displays an interactive tree of the descendant elements of
2437 * the specified XML/HTML element. If it is not possible to display
2438 * as an element the JavaScript Object view is shown instead.
2439 * The output is presented as a hierarchical listing of expandable
2440 * nodes that let you see the contents of child nodes.
2441 *
2442 * Since we write to stdout, we can't display anything interactive
2443 * we just fall back to `console.dir`.
2444 */
2445 dirxml: (
2446 obj: unknown,
2447 options?: Partial<{
2448 showHidden: boolean;
2449 depth: number;
2450 colors: boolean;
2451 indentLevel: number;
2452 }>
2453 ) => void;
2454
2455 /** Writes the arguments to stdout */
2456 warn: (...args: unknown[]) => void;
2457 /** Writes the arguments to stdout */
2458 error: (...args: unknown[]) => void;
2459 /** Writes an error message to stdout if the assertion is `false`. If the
2460 * assertion is `true`, nothing happens.
2461 *
2462 * ref: https://console.spec.whatwg.org/#assert
2463 */
2464 assert: (condition?: boolean, ...args: unknown[]) => void;
2465 count: (label?: string) => void;
2466 countReset: (label?: string) => void;
2467 table: (data: unknown, properties?: string[] | undefined) => void;
2468 time: (label?: string) => void;
2469 timeLog: (label?: string, ...args: unknown[]) => void;
2470 timeEnd: (label?: string) => void;
2471 group: (...label: unknown[]) => void;
2472 groupCollapsed: (...label: unknown[]) => void;
2473 groupEnd: () => void;
2474 clear: () => void;
2475 trace: (...args: unknown[]) => void;
2476 static [Symbol.hasInstance](instance: Console): boolean;
2477}
2478
2479declare interface Crypto {
2480 readonly subtle: null;
2481 getRandomValues<
2482 T extends
2483 | Int8Array
2484 | Int16Array
2485 | Int32Array
2486 | Uint8Array
2487 | Uint16Array
2488 | Uint32Array
2489 | Uint8ClampedArray
2490 | Float32Array
2491 | Float64Array
2492 | DataView
2493 | null
2494 >(
2495 array: T
2496 ): T;
2497}
2498
2499type FormDataEntryValue = File | string;
2500
2501/** Provides a way to easily construct a set of key/value pairs representing
2502 * form fields and their values, which can then be easily sent using the
2503 * XMLHttpRequest.send() method. It uses the same format a form would use if the
2504 * encoding type were set to "multipart/form-data". */
2505interface FormData extends DomIterable<string, FormDataEntryValue> {
2506 append(name: string, value: string | Blob, fileName?: string): void;
2507 delete(name: string): void;
2508 get(name: string): FormDataEntryValue | null;
2509 getAll(name: string): FormDataEntryValue[];
2510 has(name: string): boolean;
2511 set(name: string, value: string | Blob, fileName?: string): void;
2512}
2513
2514declare const FormData: {
2515 prototype: FormData;
2516 // TODO(ry) FormData constructor is non-standard.
2517 // new(form?: HTMLFormElement): FormData;
2518 new (): FormData;
2519};
2520
2521interface Body {
2522 /** A simple getter used to expose a `ReadableStream` of the body contents. */
2523 readonly body: ReadableStream<Uint8Array> | null;
2524 /** Stores a `Boolean` that declares whether the body has been used in a
2525 * response yet.
2526 */
2527 readonly bodyUsed: boolean;
2528 /** Takes a `Response` stream and reads it to completion. It returns a promise
2529 * that resolves with an `ArrayBuffer`.
2530 */
2531 arrayBuffer(): Promise<ArrayBuffer>;
2532 /** Takes a `Response` stream and reads it to completion. It returns a promise
2533 * that resolves with a `Blob`.
2534 */
2535 blob(): Promise<Blob>;
2536 /** Takes a `Response` stream and reads it to completion. It returns a promise
2537 * that resolves with a `FormData` object.
2538 */
2539 formData(): Promise<FormData>;
2540 /** Takes a `Response` stream and reads it to completion. It returns a promise
2541 * that resolves with the result of parsing the body text as JSON.
2542 */
2543 json(): Promise<any>;
2544 /** Takes a `Response` stream and reads it to completion. It returns a promise
2545 * that resolves with a `USVString` (text).
2546 */
2547 text(): Promise<string>;
2548}
2549
2550type HeadersInit = Headers | string[][] | Record<string, string>;
2551
2552/** This Fetch API interface allows you to perform various actions on HTTP
2553 * request and response headers. These actions include retrieving, setting,
2554 * adding to, and removing. A Headers object has an associated header list,
2555 * which is initially empty and consists of zero or more name and value pairs.
2556 *  You can add to this using methods like append() (see Examples.) In all
2557 * methods of this interface, header names are matched by case-insensitive byte
2558 * sequence. */
2559interface Headers {
2560 append(name: string, value: string): void;
2561 delete(name: string): void;
2562 get(name: string): string | null;
2563 has(name: string): boolean;
2564 set(name: string, value: string): void;
2565 forEach(
2566 callbackfn: (value: string, key: string, parent: Headers) => void,
2567 thisArg?: any
2568 ): void;
2569}
2570
2571interface Headers extends DomIterable<string, string> {
2572 /** Appends a new value onto an existing header inside a `Headers` object, or
2573 * adds the header if it does not already exist.
2574 */
2575 append(name: string, value: string): void;
2576 /** Deletes a header from a `Headers` object. */
2577 delete(name: string): void;
2578 /** Returns an iterator allowing to go through all key/value pairs
2579 * contained in this Headers object. The both the key and value of each pairs
2580 * are ByteString objects.
2581 */
2582 entries(): IterableIterator<[string, string]>;
2583 /** Returns a `ByteString` sequence of all the values of a header within a
2584 * `Headers` object with a given name.
2585 */
2586 get(name: string): string | null;
2587 /** Returns a boolean stating whether a `Headers` object contains a certain
2588 * header.
2589 */
2590 has(name: string): boolean;
2591 /** Returns an iterator allowing to go through all keys contained in
2592 * this Headers object. The keys are ByteString objects.
2593 */
2594 keys(): IterableIterator<string>;
2595 /** Sets a new value for an existing header inside a Headers object, or adds
2596 * the header if it does not already exist.
2597 */
2598 set(name: string, value: string): void;
2599 /** Returns an iterator allowing to go through all values contained in
2600 * this Headers object. The values are ByteString objects.
2601 */
2602 values(): IterableIterator<string>;
2603 forEach(
2604 callbackfn: (value: string, key: string, parent: this) => void,
2605 thisArg?: any
2606 ): void;
2607 /** The Symbol.iterator well-known symbol specifies the default
2608 * iterator for this Headers object
2609 */
2610 [Symbol.iterator](): IterableIterator<[string, string]>;
2611}
2612
2613declare const Headers: {
2614 prototype: Headers;
2615 new (init?: HeadersInit): Headers;
2616};
2617
2618type RequestInfo = Request | string;
2619type RequestCache =
2620 | "default"
2621 | "force-cache"
2622 | "no-cache"
2623 | "no-store"
2624 | "only-if-cached"
2625 | "reload";
2626type RequestCredentials = "include" | "omit" | "same-origin";
2627type RequestMode = "cors" | "navigate" | "no-cors" | "same-origin";
2628type RequestRedirect = "error" | "follow" | "manual";
2629type ReferrerPolicy =
2630 | ""
2631 | "no-referrer"
2632 | "no-referrer-when-downgrade"
2633 | "origin"
2634 | "origin-when-cross-origin"
2635 | "same-origin"
2636 | "strict-origin"
2637 | "strict-origin-when-cross-origin"
2638 | "unsafe-url";
2639type BodyInit =
2640 | Blob
2641 | BufferSource
2642 | FormData
2643 | URLSearchParams
2644 | ReadableStream<Uint8Array>
2645 | string;
2646type RequestDestination =
2647 | ""
2648 | "audio"
2649 | "audioworklet"
2650 | "document"
2651 | "embed"
2652 | "font"
2653 | "image"
2654 | "manifest"
2655 | "object"
2656 | "paintworklet"
2657 | "report"
2658 | "script"
2659 | "sharedworker"
2660 | "style"
2661 | "track"
2662 | "video"
2663 | "worker"
2664 | "xslt";
2665
2666interface RequestInit {
2667 /**
2668 * A BodyInit object or null to set request's body.
2669 */
2670 body?: BodyInit | null;
2671 /**
2672 * A string indicating how the request will interact with the browser's cache
2673 * to set request's cache.
2674 */
2675 cache?: RequestCache;
2676 /**
2677 * A string indicating whether credentials will be sent with the request
2678 * always, never, or only when sent to a same-origin URL. Sets request's
2679 * credentials.
2680 */
2681 credentials?: RequestCredentials;
2682 /**
2683 * A Headers object, an object literal, or an array of two-item arrays to set
2684 * request's headers.
2685 */
2686 headers?: HeadersInit;
2687 /**
2688 * A cryptographic hash of the resource to be fetched by request. Sets
2689 * request's integrity.
2690 */
2691 integrity?: string;
2692 /**
2693 * A boolean to set request's keepalive.
2694 */
2695 keepalive?: boolean;
2696 /**
2697 * A string to set request's method.
2698 */
2699 method?: string;
2700 /**
2701 * A string to indicate whether the request will use CORS, or will be
2702 * restricted to same-origin URLs. Sets request's mode.
2703 */
2704 mode?: RequestMode;
2705 /**
2706 * A string indicating whether request follows redirects, results in an error
2707 * upon encountering a redirect, or returns the redirect (in an opaque
2708 * fashion). Sets request's redirect.
2709 */
2710 redirect?: RequestRedirect;
2711 /**
2712 * A string whose value is a same-origin URL, "about:client", or the empty
2713 * string, to set request's referrer.
2714 */
2715 referrer?: string;
2716 /**
2717 * A referrer policy to set request's referrerPolicy.
2718 */
2719 referrerPolicy?: ReferrerPolicy;
2720 /**
2721 * An AbortSignal to set request's signal.
2722 */
2723 signal?: AbortSignal | null;
2724 /**
2725 * Can only be null. Used to disassociate request from any Window.
2726 */
2727 window?: any;
2728}
2729
2730/** This Fetch API interface represents a resource request. */
2731interface Request extends Body {
2732 /**
2733 * Returns the cache mode associated with request, which is a string
2734 * indicating how the request will interact with the browser's cache when
2735 * fetching.
2736 */
2737 readonly cache: RequestCache;
2738 /**
2739 * Returns the credentials mode associated with request, which is a string
2740 * indicating whether credentials will be sent with the request always, never,
2741 * or only when sent to a same-origin URL.
2742 */
2743 readonly credentials: RequestCredentials;
2744 /**
2745 * Returns the kind of resource requested by request, e.g., "document" or "script".
2746 */
2747 readonly destination: RequestDestination;
2748 /**
2749 * Returns a Headers object consisting of the headers associated with request.
2750 * Note that headers added in the network layer by the user agent will not be
2751 * accounted for in this object, e.g., the "Host" header.
2752 */
2753 readonly headers: Headers;
2754 /**
2755 * Returns request's subresource integrity metadata, which is a cryptographic
2756 * hash of the resource being fetched. Its value consists of multiple hashes
2757 * separated by whitespace. [SRI]
2758 */
2759 readonly integrity: string;
2760 /**
2761 * Returns a boolean indicating whether or not request is for a history
2762 * navigation (a.k.a. back-forward navigation).
2763 */
2764 readonly isHistoryNavigation: boolean;
2765 /**
2766 * Returns a boolean indicating whether or not request is for a reload
2767 * navigation.
2768 */
2769 readonly isReloadNavigation: boolean;
2770 /**
2771 * Returns a boolean indicating whether or not request can outlive the global
2772 * in which it was created.
2773 */
2774 readonly keepalive: boolean;
2775 /**
2776 * Returns request's HTTP method, which is "GET" by default.
2777 */
2778 readonly method: string;
2779 /**
2780 * Returns the mode associated with request, which is a string indicating
2781 * whether the request will use CORS, or will be restricted to same-origin
2782 * URLs.
2783 */
2784 readonly mode: RequestMode;
2785 /**
2786 * Returns the redirect mode associated with request, which is a string
2787 * indicating how redirects for the request will be handled during fetching. A
2788 * request will follow redirects by default.
2789 */
2790 readonly redirect: RequestRedirect;
2791 /**
2792 * Returns the referrer of request. Its value can be a same-origin URL if
2793 * explicitly set in init, the empty string to indicate no referrer, and
2794 * "about:client" when defaulting to the global's default. This is used during
2795 * fetching to determine the value of the `Referer` header of the request
2796 * being made.
2797 */
2798 readonly referrer: string;
2799 /**
2800 * Returns the referrer policy associated with request. This is used during
2801 * fetching to compute the value of the request's referrer.
2802 */
2803 readonly referrerPolicy: ReferrerPolicy;
2804 /**
2805 * Returns the signal associated with request, which is an AbortSignal object
2806 * indicating whether or not request has been aborted, and its abort event
2807 * handler.
2808 */
2809 readonly signal: AbortSignal;
2810 /**
2811 * Returns the URL of request as a string.
2812 */
2813 readonly url: string;
2814 clone(): Request;
2815}
2816
2817declare const Request: {
2818 prototype: Request;
2819 new (input: RequestInfo, init?: RequestInit): Request;
2820};
2821
2822type ResponseType =
2823 | "basic"
2824 | "cors"
2825 | "default"
2826 | "error"
2827 | "opaque"
2828 | "opaqueredirect";
2829
2830/** This Fetch API interface represents the response to a request. */
2831interface Response extends Body {
2832 readonly headers: Headers;
2833 readonly ok: boolean;
2834 readonly redirected: boolean;
2835 readonly status: number;
2836 readonly statusText: string;
2837 readonly trailer: Promise<Headers>;
2838 readonly type: ResponseType;
2839 readonly url: string;
2840 clone(): Response;
2841}
2842
2843declare const Response: {
2844 prototype: Response;
2845
2846 // TODO(#4667) Response constructor is non-standard.
2847 // new(body?: BodyInit | null, init?: ResponseInit): Response;
2848 new (
2849 url: string,
2850 status: number,
2851 statusText: string,
2852 headersList: Array<[string, string]>,
2853 rid: number,
2854 redirected_: boolean,
2855 type_?: null | ResponseType,
2856 body_?: null | Body
2857 ): Response;
2858
2859 error(): Response;
2860 redirect(url: string, status?: number): Response;
2861};
2862
2863/** Fetch a resource from the network. */
2864declare function fetch(
2865 input: Request | URL | string,
2866 init?: RequestInit
2867): Promise<Response>;
2868
2869declare function atob(s: string): string;
2870
2871/** Creates a base-64 ASCII string from the input string. */
2872declare function btoa(s: string): string;
2873
2874declare class TextDecoder {
2875 /** Returns encoding's name, lowercased. */
2876 readonly encoding: string;
2877 /** Returns `true` if error mode is "fatal", and `false` otherwise. */
2878 readonly fatal: boolean;
2879 /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */
2880 readonly ignoreBOM = false;
2881 constructor(
2882 label?: string,
2883 options?: { fatal?: boolean; ignoreBOM?: boolean }
2884 );
2885 /** Returns the result of running encoding's decoder. */
2886 decode(input?: BufferSource, options?: { stream?: false }): string;
2887 readonly [Symbol.toStringTag]: string;
2888}
2889
2890declare class TextEncoder {
2891 /** Returns "utf-8". */
2892 readonly encoding = "utf-8";
2893 /** Returns the result of running UTF-8's encoder. */
2894 encode(input?: string): Uint8Array;
2895 encodeInto(
2896 input: string,
2897 dest: Uint8Array
2898 ): { read: number; written: number };
2899 readonly [Symbol.toStringTag]: string;
2900}
2901
2902interface URLSearchParams {
2903 /** Appends a specified key/value pair as a new search parameter.
2904 *
2905 * ```ts
2906 * let searchParams = new URLSearchParams();
2907 * searchParams.append('name', 'first');
2908 * searchParams.append('name', 'second');
2909 * ```
2910 */
2911 append(name: string, value: string): void;
2912
2913 /** Deletes the given search parameter and its associated value,
2914 * from the list of all search parameters.
2915 *
2916 * ```ts
2917 * let searchParams = new URLSearchParams([['name', 'value']]);
2918 * searchParams.delete('name');
2919 * ```
2920 */
2921 delete(name: string): void;
2922
2923 /** Returns all the values associated with a given search parameter
2924 * as an array.
2925 *
2926 * ```ts
2927 * searchParams.getAll('name');
2928 * ```
2929 */
2930 getAll(name: string): string[];
2931
2932 /** Returns the first value associated to the given search parameter.
2933 *
2934 * ```ts
2935 * searchParams.get('name');
2936 * ```
2937 */
2938 get(name: string): string | null;
2939
2940 /** Returns a Boolean that indicates whether a parameter with the
2941 * specified name exists.
2942 *
2943 * ```ts
2944 * searchParams.has('name');
2945 * ```
2946 */
2947 has(name: string): boolean;
2948
2949 /** Sets the value associated with a given search parameter to the
2950 * given value. If there were several matching values, this method
2951 * deletes the others. If the search parameter doesn't exist, this
2952 * method creates it.
2953 *
2954 * ```ts
2955 * searchParams.set('name', 'value');
2956 * ```
2957 */
2958 set(name: string, value: string): void;
2959
2960 /** Sort all key/value pairs contained in this object in place and
2961 * return undefined. The sort order is according to Unicode code
2962 * points of the keys.
2963 *
2964 * ```ts
2965 * searchParams.sort();
2966 * ```
2967 */
2968 sort(): void;
2969
2970 /** Calls a function for each element contained in this object in
2971 * place and return undefined. Optionally accepts an object to use
2972 * as this when executing callback as second argument.
2973 *
2974 * ```ts
2975 * const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
2976 * params.forEach((value, key, parent) => {
2977 * console.log(value, key, parent);
2978 * });
2979 * ```
2980 *
2981 */
2982 forEach(
2983 callbackfn: (value: string, key: string, parent: this) => void,
2984 thisArg?: any
2985 ): void;
2986
2987 /** Returns an iterator allowing to go through all keys contained
2988 * in this object.
2989 *
2990 * ```ts
2991 * const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
2992 * for (const key of params.keys()) {
2993 * console.log(key);
2994 * }
2995 * ```
2996 */
2997 keys(): IterableIterator<string>;
2998
2999 /** Returns an iterator allowing to go through all values contained
3000 * in this object.
3001 *
3002 * ```ts
3003 * const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
3004 * for (const value of params.values()) {
3005 * console.log(value);
3006 * }
3007 * ```
3008 */
3009 values(): IterableIterator<string>;
3010
3011 /** Returns an iterator allowing to go through all key/value
3012 * pairs contained in this object.
3013 *
3014 * ```ts
3015 * const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
3016 * for (const [key, value] of params.entries()) {
3017 * console.log(key, value);
3018 * }
3019 * ```
3020 */
3021 entries(): IterableIterator<[string, string]>;
3022
3023 /** Returns an iterator allowing to go through all key/value
3024 * pairs contained in this object.
3025 *
3026 * ```ts
3027 * const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
3028 * for (const [key, value] of params) {
3029 * console.log(key, value);
3030 * }
3031 * ```
3032 */
3033 [Symbol.iterator](): IterableIterator<[string, string]>;
3034
3035 /** Returns a query string suitable for use in a URL.
3036 *
3037 * ```ts
3038 * searchParams.toString();
3039 * ```
3040 */
3041 toString(): string;
3042}
3043
3044declare const URLSearchParams: {
3045 prototype: URLSearchParams;
3046 new (
3047 init?: string[][] | Record<string, string> | string | URLSearchParams
3048 ): URLSearchParams;
3049 toString(): string;
3050};
3051
3052/** The URL interface represents an object providing static methods used for creating object URLs. */
3053interface URL {
3054 hash: string;
3055 host: string;
3056 hostname: string;
3057 href: string;
3058 toString(): string;
3059 readonly origin: string;
3060 password: string;
3061 pathname: string;
3062 port: string;
3063 protocol: string;
3064 search: string;
3065 readonly searchParams: URLSearchParams;
3066 username: string;
3067 toJSON(): string;
3068}
3069
3070declare const URL: {
3071 prototype: URL;
3072 new (url: string | URL, base?: string | URL): URL;
3073 createObjectURL(object: any): string;
3074 revokeObjectURL(url: string): void;
3075};
3076
3077interface MessageEventInit extends EventInit {
3078 data?: any;
3079 origin?: string;
3080 lastEventId?: string;
3081}
3082
3083declare class MessageEvent extends Event {
3084 readonly data: any;
3085 readonly origin: string;
3086 readonly lastEventId: string;
3087 constructor(type: string, eventInitDict?: MessageEventInit);
3088}
3089
3090interface ErrorEventInit extends EventInit {
3091 message?: string;
3092 filename?: string;
3093 lineno?: number;
3094 colno?: number;
3095 error?: any;
3096}
3097
3098declare class ErrorEvent extends Event {
3099 readonly message: string;
3100 readonly filename: string;
3101 readonly lineno: number;
3102 readonly colno: number;
3103 readonly error: any;
3104 constructor(type: string, eventInitDict?: ErrorEventInit);
3105}
3106
3107interface PostMessageOptions {
3108 transfer?: any[];
3109}
3110
3111declare class Worker extends EventTarget {
3112 onerror?: (e: ErrorEvent) => void;
3113 onmessage?: (e: MessageEvent) => void;
3114 onmessageerror?: (e: MessageEvent) => void;
3115 constructor(
3116 specifier: string,
3117 options?: {
3118 type?: "classic" | "module";
3119 name?: string;
3120 /** UNSTABLE: New API. Expect many changes; most likely this
3121 * field will be made into an object for more granular
3122 * configuration of worker thread (permissions, import map, etc.).
3123 *
3124 * Set to `true` to make `Deno` namespace and all of its methods
3125 * available to worker thread.
3126 *
3127 * Currently worker inherits permissions from main thread (permissions
3128 * given using `--allow-*` flags).
3129 * Configurable permissions are on the roadmap to be implemented.
3130 *
3131 * Example:
3132 *
3133 * ```ts
3134 * // mod.ts
3135 * const worker = new Worker("./deno_worker.ts", { type: "module", deno: true });
3136 * worker.postMessage({ cmd: "readFile", fileName: "./log.txt" });
3137 *
3138 * // deno_worker.ts
3139 *
3140 *
3141 * self.onmessage = async function (e) {
3142 * const { cmd, fileName } = e.data;
3143 * if (cmd !== "readFile") {
3144 * throw new Error("Invalid command");
3145 * }
3146 * const buf = await Deno.readFile(fileName);
3147 * const fileContents = new TextDecoder().decode(buf);
3148 * console.log(fileContents);
3149 * }
3150 * ```
3151 *
3152 * // log.txt
3153 * hello world
3154 * hello world 2
3155 *
3156 * // run program
3157 * $ deno run --allow-read mod.ts
3158 * hello world
3159 * hello world2
3160 *
3161 */
3162 deno?: boolean;
3163 }
3164 );
3165 postMessage(message: any, transfer: ArrayBuffer[]): void;
3166 postMessage(message: any, options?: PostMessageOptions): void;
3167 terminate(): void;
3168}
3169
3170declare namespace performance {
3171 /** Returns a current time from Deno's start in milliseconds.
3172 *
3173 * Use the flag --allow-hrtime return a precise value.
3174 *
3175 * ```ts
3176 * const t = performance.now();
3177 * console.log(`${t} ms since start!`);
3178 * ```
3179 */
3180 export function now(): number;
3181}
3182
3183interface EventInit {
3184 bubbles?: boolean;
3185 cancelable?: boolean;
3186 composed?: boolean;
3187}
3188
3189/** An event which takes place in the DOM. */
3190declare class Event {
3191 constructor(type: string, eventInitDict?: EventInit);
3192 /** Returns true or false depending on how event was initialized. True if
3193 * event goes through its target's ancestors in reverse tree order, and
3194 * false otherwise. */
3195 readonly bubbles: boolean;
3196 cancelBubble: boolean;
3197 /** Returns true or false depending on how event was initialized. Its return
3198 * value does not always carry meaning, but true can indicate that part of the
3199 * operation during which event was dispatched, can be canceled by invoking
3200 * the preventDefault() method. */
3201 readonly cancelable: boolean;
3202 /** Returns true or false depending on how event was initialized. True if
3203 * event invokes listeners past a ShadowRoot node that is the root of its
3204 * target, and false otherwise. */
3205 readonly composed: boolean;
3206 /** Returns the object whose event listener's callback is currently being
3207 * invoked. */
3208 readonly currentTarget: EventTarget | null;
3209 /** Returns true if preventDefault() was invoked successfully to indicate
3210 * cancellation, and false otherwise. */
3211 readonly defaultPrevented: boolean;
3212 /** Returns the event's phase, which is one of NONE, CAPTURING_PHASE,
3213 * AT_TARGET, and BUBBLING_PHASE. */
3214 readonly eventPhase: number;
3215 /** Returns true if event was dispatched by the user agent, and false
3216 * otherwise. */
3217 readonly isTrusted: boolean;
3218 /** Returns the object to which event is dispatched (its target). */
3219 readonly target: EventTarget | null;
3220 /** Returns the event's timestamp as the number of milliseconds measured
3221 * relative to the time origin. */
3222 readonly timeStamp: number;
3223 /** Returns the type of event, e.g. "click", "hashchange", or "submit". */
3224 readonly type: string;
3225 /** Returns the invocation target objects of event's path (objects on which
3226 * listeners will be invoked), except for any nodes in shadow trees of which
3227 * the shadow root's mode is "closed" that are not reachable from event's
3228 * currentTarget. */
3229 composedPath(): EventTarget[];
3230 /** If invoked when the cancelable attribute value is true, and while
3231 * executing a listener for the event with passive set to false, signals to
3232 * the operation that caused event to be dispatched that it needs to be
3233 * canceled. */
3234 preventDefault(): void;
3235 /** Invoking this method prevents event from reaching any registered event
3236 * listeners after the current one finishes running and, when dispatched in a
3237 * tree, also prevents event from reaching any other objects. */
3238 stopImmediatePropagation(): void;
3239 /** When dispatched in a tree, invoking this method prevents event from
3240 * reaching any objects other than the current object. */
3241 stopPropagation(): void;
3242 readonly AT_TARGET: number;
3243 readonly BUBBLING_PHASE: number;
3244 readonly CAPTURING_PHASE: number;
3245 readonly NONE: number;
3246 static readonly AT_TARGET: number;
3247 static readonly BUBBLING_PHASE: number;
3248 static readonly CAPTURING_PHASE: number;
3249 static readonly NONE: number;
3250}
3251
3252/**
3253 * EventTarget is a DOM interface implemented by objects that can receive events
3254 * and may have listeners for them.
3255 */
3256declare class EventTarget {
3257 /** Appends an event listener for events whose type attribute value is type.
3258 * The callback argument sets the callback that will be invoked when the event
3259 * is dispatched.
3260 *
3261 * The options argument sets listener-specific options. For compatibility this
3262 * can be a boolean, in which case the method behaves exactly as if the value
3263 * was specified as options's capture.
3264 *
3265 * When set to true, options's capture prevents callback from being invoked
3266 * when the event's eventPhase attribute value is BUBBLING_PHASE. When false
3267 * (or not present), callback will not be invoked when event's eventPhase
3268 * attribute value is CAPTURING_PHASE. Either way, callback will be invoked if
3269 * event's eventPhase attribute value is AT_TARGET.
3270 *
3271 * When set to true, options's passive indicates that the callback will not
3272 * cancel the event by invoking preventDefault(). This is used to enable
3273 * performance optimizations described in § 2.8 Observing event listeners.
3274 *
3275 * When set to true, options's once indicates that the callback will only be
3276 * invoked once after which the event listener will be removed.
3277 *
3278 * The event listener is appended to target's event listener list and is not
3279 * appended if it has the same type, callback, and capture. */
3280 addEventListener(
3281 type: string,
3282 listener: EventListenerOrEventListenerObject | null,
3283 options?: boolean | AddEventListenerOptions
3284 ): void;
3285 /** Dispatches a synthetic event event to target and returns true if either
3286 * event's cancelable attribute value is false or its preventDefault() method
3287 * was not invoked, and false otherwise. */
3288 dispatchEvent(event: Event): boolean;
3289 /** Removes the event listener in target's event listener list with the same
3290 * type, callback, and options. */
3291 removeEventListener(
3292 type: string,
3293 callback: EventListenerOrEventListenerObject | null,
3294 options?: EventListenerOptions | boolean
3295 ): void;
3296 [Symbol.toStringTag]: string;
3297}
3298
3299interface EventListener {
3300 (evt: Event): void | Promise<void>;
3301}
3302
3303interface EventListenerObject {
3304 handleEvent(evt: Event): void | Promise<void>;
3305}
3306
3307declare type EventListenerOrEventListenerObject =
3308 | EventListener
3309 | EventListenerObject;
3310
3311interface AddEventListenerOptions extends EventListenerOptions {
3312 once?: boolean;
3313 passive?: boolean;
3314}
3315
3316interface EventListenerOptions {
3317 capture?: boolean;
3318}
3319
3320/** Events measuring progress of an underlying process, like an HTTP request
3321 * (for an XMLHttpRequest, or the loading of the underlying resource of an
3322 * <img>, <audio>, <video>, <style> or <link>). */
3323interface ProgressEvent<T extends EventTarget = EventTarget> extends Event {
3324 readonly lengthComputable: boolean;
3325 readonly loaded: number;
3326 readonly target: T | null;
3327 readonly total: number;
3328}
3329
3330interface CustomEventInit<T = any> extends EventInit {
3331 detail?: T;
3332}
3333
3334declare class CustomEvent<T = any> extends Event {
3335 constructor(typeArg: string, eventInitDict?: CustomEventInit<T>);
3336 /** Returns any custom data event was created with. Typically used for
3337 * synthetic events. */
3338 readonly detail: T;
3339}
3340
3341/** A controller object that allows you to abort one or more DOM requests as and
3342 * when desired. */
3343declare class AbortController {
3344 /** Returns the AbortSignal object associated with this object. */
3345 readonly signal: AbortSignal;
3346 /** Invoking this method will set this object's AbortSignal's aborted flag and
3347 * signal to any observers that the associated activity is to be aborted. */
3348 abort(): void;
3349}
3350
3351interface AbortSignalEventMap {
3352 abort: Event;
3353}
3354
3355/** A signal object that allows you to communicate with a DOM request (such as a
3356 * Fetch) and abort it if required via an AbortController object. */
3357interface AbortSignal extends EventTarget {
3358 /** Returns true if this AbortSignal's AbortController has signaled to abort,
3359 * and false otherwise. */
3360 readonly aborted: boolean;
3361 onabort: ((this: AbortSignal, ev: Event) => any) | null;
3362 addEventListener<K extends keyof AbortSignalEventMap>(
3363 type: K,
3364 listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any,
3365 options?: boolean | AddEventListenerOptions
3366 ): void;
3367 addEventListener(
3368 type: string,
3369 listener: EventListenerOrEventListenerObject,
3370 options?: boolean | AddEventListenerOptions
3371 ): void;
3372 removeEventListener<K extends keyof AbortSignalEventMap>(
3373 type: K,
3374 listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any,
3375 options?: boolean | EventListenerOptions
3376 ): void;
3377 removeEventListener(
3378 type: string,
3379 listener: EventListenerOrEventListenerObject,
3380 options?: boolean | EventListenerOptions
3381 ): void;
3382}
3383
3384declare const AbortSignal: {
3385 prototype: AbortSignal;
3386 new (): AbortSignal;
3387};
3388
3389// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
3390
3391/* eslint-disable @typescript-eslint/no-explicit-any */
3392
3393/// <reference no-default-lib="true" />
3394/// <reference lib="deno.ns" />
3395/// <reference lib="deno.shared_globals" />
3396/// <reference lib="esnext" />
3397
3398declare interface Window extends EventTarget {
3399 readonly window: Window & typeof globalThis;
3400 readonly self: Window & typeof globalThis;
3401 onload: ((this: Window, ev: Event) => any) | null;
3402 onunload: ((this: Window, ev: Event) => any) | null;
3403 close: () => void;
3404 readonly closed: boolean;
3405 Deno: typeof Deno;
3406}
3407
3408declare const window: Window & typeof globalThis;
3409declare const self: Window & typeof globalThis;
3410declare const onload: ((this: Window, ev: Event) => any) | null;
3411declare const onunload: ((this: Window, ev: Event) => any) | null;
3412
3413/* eslint-enable @typescript-eslint/no-explicit-any */
3414
3415// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
3416
3417/// <reference no-default-lib="true" />
3418/// <reference lib="deno.ns" />
3419
3420declare namespace Deno {
3421 /**
3422 * **UNSTABLE**: New API, yet to be vetted. This API is under consideration to
3423 * determine if permissions are required to call it.
3424 *
3425 * Retrieve the process umask. If `mask` is provided, sets the process umask.
3426 * This call always returns what the umask was before the call.
3427 *
3428 * ```ts
3429 * console.log(Deno.umask()); // e.g. 18 (0o022)
3430 * const prevUmaskValue = Deno.umask(0o077); // e.g. 18 (0o022)
3431 * console.log(Deno.umask()); // e.g. 63 (0o077)
3432 * ```
3433 *
3434 * NOTE: This API is not implemented on Windows
3435 */
3436 export function umask(mask?: number): number;
3437
3438 /** Synchronously creates `newpath` as a hard link to `oldpath`.
3439 *
3440 * ```ts
3441 * Deno.linkSync("old/name", "new/name");
3442 * ```
3443 *
3444 * Requires `allow-read` and `allow-write` permissions. */
3445 export function linkSync(oldpath: string, newpath: string): void;
3446
3447 /** Creates `newpath` as a hard link to `oldpath`.
3448 *
3449 * **UNSTABLE**: needs security review.
3450 *
3451 * ```ts
3452 * await Deno.link("old/name", "new/name");
3453 * ```
3454 *
3455 * Requires `allow-read` and `allow-write` permissions. */
3456 export function link(oldpath: string, newpath: string): Promise<void>;
3457
3458 export type SymlinkOptions = {
3459 type: "file" | "dir";
3460 };
3461
3462 /** **UNSTABLE**: needs security review.
3463 *
3464 * Creates `newpath` as a symbolic link to `oldpath`.
3465 *
3466 * The options.type parameter can be set to `file` or `dir`. This argument is only
3467 * available on Windows and ignored on other platforms.
3468 *
3469 * ```ts
3470 * Deno.symlinkSync("old/name", "new/name");
3471 * ```
3472 *
3473 * Requires `allow-write` permission. */
3474 export function symlinkSync(
3475 oldpath: string,
3476 newpath: string,
3477 options?: SymlinkOptions
3478 ): void;
3479
3480 /** **UNSTABLE**: needs security review.
3481 *
3482 * Creates `newpath` as a symbolic link to `oldpath`.
3483 *
3484 * The options.type parameter can be set to `file` or `dir`. This argument is only
3485 * available on Windows and ignored on other platforms.
3486 *
3487 * ```ts
3488 * await Deno.symlink("old/name", "new/name");
3489 * ```
3490 *
3491 * Requires `allow-write` permission. */
3492 export function symlink(
3493 oldpath: string,
3494 newpath: string,
3495 options?: SymlinkOptions
3496 ): Promise<void>;
3497
3498 /** **UNSTABLE** */
3499 export type DirKind =
3500 | "home"
3501 | "cache"
3502 | "config"
3503 | "executable"
3504 | "data"
3505 | "data_local"
3506 | "audio"
3507 | "desktop"
3508 | "document"
3509 | "download"
3510 | "font"
3511 | "picture"
3512 | "public"
3513 | "template"
3514 | "tmp"
3515 | "video";
3516
3517 /**
3518 * **UNSTABLE**: Currently under evaluation to decide if method name `dir` and
3519 * parameter type alias name `DirKind` should be renamed.
3520 *
3521 * Returns the user and platform specific directories.
3522 *
3523 * ```ts
3524 * const homeDirectory = Deno.dir("home");
3525 * ```
3526 *
3527 * Requires `allow-env` permission.
3528 *
3529 * Returns `null` if there is no applicable directory or if any other error
3530 * occurs.
3531 *
3532 * Argument values: `"home"`, `"cache"`, `"config"`, `"executable"`, `"data"`,
3533 * `"data_local"`, `"audio"`, `"desktop"`, `"document"`, `"download"`,
3534 * `"font"`, `"picture"`, `"public"`, `"template"`, `"tmp"`, `"video"`
3535 *
3536 * `"home"`
3537 *
3538 * |Platform | Value | Example |
3539 * | ------- | -----------------------------------------| -----------------------|
3540 * | Linux | `$HOME` | /home/alice |
3541 * | macOS | `$HOME` | /Users/alice |
3542 * | Windows | `{FOLDERID_Profile}` | C:\Users\Alice |
3543 *
3544 * `"cache"`
3545 *
3546 * |Platform | Value | Example |
3547 * | ------- | ----------------------------------- | ---------------------------- |
3548 * | Linux | `$XDG_CACHE_HOME` or `$HOME`/.cache | /home/alice/.cache |
3549 * | macOS | `$HOME`/Library/Caches | /Users/Alice/Library/Caches |
3550 * | Windows | `{FOLDERID_LocalAppData}` | C:\Users\Alice\AppData\Local |
3551 *
3552 * `"config"`
3553 *
3554 * |Platform | Value | Example |
3555 * | ------- | ------------------------------------- | -------------------------------- |
3556 * | Linux | `$XDG_CONFIG_HOME` or `$HOME`/.config | /home/alice/.config |
3557 * | macOS | `$HOME`/Library/Preferences | /Users/Alice/Library/Preferences |
3558 * | Windows | `{FOLDERID_RoamingAppData}` | C:\Users\Alice\AppData\Roaming |
3559 *
3560 * `"executable"`
3561 *
3562 * |Platform | Value | Example |
3563 * | ------- | --------------------------------------------------------------- | -----------------------|
3564 * | Linux | `XDG_BIN_HOME` or `$XDG_DATA_HOME`/../bin or `$HOME`/.local/bin | /home/alice/.local/bin |
3565 * | macOS | - | - |
3566 * | Windows | - | - |
3567 *
3568 * `"data"`
3569 *
3570 * |Platform | Value | Example |
3571 * | ------- | ---------------------------------------- | ---------------------------------------- |
3572 * | Linux | `$XDG_DATA_HOME` or `$HOME`/.local/share | /home/alice/.local/share |
3573 * | macOS | `$HOME`/Library/Application Support | /Users/Alice/Library/Application Support |
3574 * | Windows | `{FOLDERID_RoamingAppData}` | C:\Users\Alice\AppData\Roaming |
3575 *
3576 * `"data_local"`
3577 *
3578 * |Platform | Value | Example |
3579 * | ------- | ---------------------------------------- | ---------------------------------------- |
3580 * | Linux | `$XDG_DATA_HOME` or `$HOME`/.local/share | /home/alice/.local/share |
3581 * | macOS | `$HOME`/Library/Application Support | /Users/Alice/Library/Application Support |
3582 * | Windows | `{FOLDERID_LocalAppData}` | C:\Users\Alice\AppData\Local |
3583 *
3584 * `"audio"`
3585 *
3586 * |Platform | Value | Example |
3587 * | ------- | ------------------ | -------------------- |
3588 * | Linux | `XDG_MUSIC_DIR` | /home/alice/Music |
3589 * | macOS | `$HOME`/Music | /Users/Alice/Music |
3590 * | Windows | `{FOLDERID_Music}` | C:\Users\Alice\Music |
3591 *
3592 * `"desktop"`
3593 *
3594 * |Platform | Value | Example |
3595 * | ------- | -------------------- | ---------------------- |
3596 * | Linux | `XDG_DESKTOP_DIR` | /home/alice/Desktop |
3597 * | macOS | `$HOME`/Desktop | /Users/Alice/Desktop |
3598 * | Windows | `{FOLDERID_Desktop}` | C:\Users\Alice\Desktop |
3599 *
3600 * `"document"`
3601 *
3602 * |Platform | Value | Example |
3603 * | ------- | ---------------------- | ------------------------ |
3604 * | Linux | `XDG_DOCUMENTS_DIR` | /home/alice/Documents |
3605 * | macOS | `$HOME`/Documents | /Users/Alice/Documents |
3606 * | Windows | `{FOLDERID_Documents}` | C:\Users\Alice\Documents |
3607 *
3608 * `"download"`
3609 *
3610 * |Platform | Value | Example |
3611 * | ------- | ---------------------- | ------------------------ |
3612 * | Linux | `XDG_DOWNLOAD_DIR` | /home/alice/Downloads |
3613 * | macOS | `$HOME`/Downloads | /Users/Alice/Downloads |
3614 * | Windows | `{FOLDERID_Downloads}` | C:\Users\Alice\Downloads |
3615 *
3616 * `"font"`
3617 *
3618 * |Platform | Value | Example |
3619 * | ------- | ---------------------------------------------------- | ------------------------------ |
3620 * | Linux | `$XDG_DATA_HOME`/fonts or `$HOME`/.local/share/fonts | /home/alice/.local/share/fonts |
3621 * | macOS | `$HOME/Library/Fonts` | /Users/Alice/Library/Fonts |
3622 * | Windows | – | – |
3623 *
3624 * `"picture"`
3625 *
3626 * |Platform | Value | Example |
3627 * | ------- | --------------------- | ----------------------- |
3628 * | Linux | `XDG_PICTURES_DIR` | /home/alice/Pictures |
3629 * | macOS | `$HOME`/Pictures | /Users/Alice/Pictures |
3630 * | Windows | `{FOLDERID_Pictures}` | C:\Users\Alice\Pictures |
3631 *
3632 * `"public"`
3633 *
3634 * |Platform | Value | Example |
3635 * | ------- | --------------------- | ------------------- |
3636 * | Linux | `XDG_PUBLICSHARE_DIR` | /home/alice/Public |
3637 * | macOS | `$HOME`/Public | /Users/Alice/Public |
3638 * | Windows | `{FOLDERID_Public}` | C:\Users\Public |
3639 *
3640 * `"template"`
3641 *
3642 * |Platform | Value | Example |
3643 * | ------- | ---------------------- | ---------------------------------------------------------- |
3644 * | Linux | `XDG_TEMPLATES_DIR` | /home/alice/Templates |
3645 * | macOS | – | – |
3646 * | Windows | `{FOLDERID_Templates}` | C:\Users\Alice\AppData\Roaming\Microsoft\Windows\Templates |
3647 *
3648 * `"tmp"`
3649 *
3650 * |Platform | Value | Example |
3651 * | ------- | ---------------------- | ---------------------------------------------------------- |
3652 * | Linux | `TMPDIR` | /tmp |
3653 * | macOS | `TMPDIR` | /tmp |
3654 * | Windows | `{TMP}` | C:\Users\Alice\AppData\Local\Temp |
3655 *
3656 * `"video"`
3657 *
3658 * |Platform | Value | Example |
3659 * | ------- | ------------------- | --------------------- |
3660 * | Linux | `XDG_VIDEOS_DIR` | /home/alice/Videos |
3661 * | macOS | `$HOME`/Movies | /Users/Alice/Movies |
3662 * | Windows | `{FOLDERID_Videos}` | C:\Users\Alice\Videos |
3663 *
3664 */
3665 export function dir(kind: DirKind): string | null;
3666
3667 /** Returns an array containing the 1, 5, and 15 minute load averages. The
3668 * load average is a measure of CPU and IO utilization of the last one, five,
3669 * and 15 minute periods expressed as a fractional number. Zero means there
3670 * is no load. On Windows, the three values are always the same and represent
3671 * the current load, not the 1, 5 and 15 minute load averages.
3672 *
3673 * ```ts
3674 * console.log(Deno.loadavg()); // e.g. [ 0.71, 0.44, 0.44 ]
3675 * ```
3676 *
3677 * Requires `allow-env` permission.
3678 *
3679 * **Unstable** There are questions around which permission this needs. And
3680 * maybe should be renamed (loadAverage?)
3681 */
3682 export function loadavg(): number[];
3683
3684 /** Returns the release version of the Operating System.
3685 *
3686 * ```ts
3687 * console.log(Deno.osRelease());
3688 * ```
3689 *
3690 * Requires `allow-env` permission.
3691 *
3692 * **Unstable** new API maybe move to Deno.build or Deno.versions? Depends on
3693 * sys-info, which we don't necessarally want to depend on.
3694 */
3695 export function osRelease(): string;
3696
3697 /** **UNSTABLE**: new API, yet to be vetted.
3698 *
3699 * Open and initialize a plugin.
3700 *
3701 * ```ts
3702 * const rid = Deno.openPlugin("./path/to/some/plugin.so");
3703 * const opId = Deno.core.ops()["some_op"];
3704 * const response = Deno.core.dispatch(opId, new Uint8Array([1,2,3,4]));
3705 * console.log(`Response from plugin ${response}`);
3706 * ```
3707 *
3708 * Requires `allow-plugin` permission.
3709 *
3710 * The plugin system is not stable and will change in the future, hence the
3711 * lack of docs. For now take a look at the example
3712 * https://github.com/denoland/deno/tree/master/test_plugin
3713 */
3714 export function openPlugin(filename: string): number;
3715
3716 /** The log category for a diagnostic message. */
3717 export enum DiagnosticCategory {
3718 Log = 0,
3719 Debug = 1,
3720 Info = 2,
3721 Error = 3,
3722 Warning = 4,
3723 Suggestion = 5,
3724 }
3725
3726 export interface DiagnosticMessageChain {
3727 message: string;
3728 category: DiagnosticCategory;
3729 code: number;
3730 next?: DiagnosticMessageChain[];
3731 }
3732
3733 export interface DiagnosticItem {
3734 /** A string message summarizing the diagnostic. */
3735 message: string;
3736 /** An ordered array of further diagnostics. */
3737 messageChain?: DiagnosticMessageChain;
3738 /** Information related to the diagnostic. This is present when there is a
3739 * suggestion or other additional diagnostic information */
3740 relatedInformation?: DiagnosticItem[];
3741 /** The text of the source line related to the diagnostic. */
3742 sourceLine?: string;
3743 /** The line number that is related to the diagnostic. */
3744 lineNumber?: number;
3745 /** The name of the script resource related to the diagnostic. */
3746 scriptResourceName?: string;
3747 /** The start position related to the diagnostic. */
3748 startPosition?: number;
3749 /** The end position related to the diagnostic. */
3750 endPosition?: number;
3751 /** The category of the diagnostic. */
3752 category: DiagnosticCategory;
3753 /** A number identifier. */
3754 code: number;
3755 /** The the start column of the sourceLine related to the diagnostic. */
3756 startColumn?: number;
3757 /** The end column of the sourceLine related to the diagnostic. */
3758 endColumn?: number;
3759 }
3760
3761 export interface Diagnostic {
3762 /** An array of diagnostic items. */
3763 items: DiagnosticItem[];
3764 }
3765
3766 /** **UNSTABLE**: new API, yet to be vetted.
3767 *
3768 * Format an array of diagnostic items and return them as a single string in a
3769 * user friendly format.
3770 *
3771 * ```ts
3772 * const [diagnostics, result] = Deno.compile("file_with_compile_issues.ts");
3773 * console.table(diagnostics); // Prints raw diagnostic data
3774 * console.log(Deno.formatDiagnostics(diagnostics)); // User friendly output of diagnostics
3775 * ```
3776 *
3777 * @param items An array of diagnostic items to format
3778 */
3779 export function formatDiagnostics(items: DiagnosticItem[]): string;
3780
3781 /** **UNSTABLE**: new API, yet to be vetted.
3782 *
3783 * A specific subset TypeScript compiler options that can be supported by the
3784 * Deno TypeScript compiler. */
3785 export interface CompilerOptions {
3786 /** Allow JavaScript files to be compiled. Defaults to `true`. */
3787 allowJs?: boolean;
3788 /** Allow default imports from modules with no default export. This does not
3789 * affect code emit, just typechecking. Defaults to `false`. */
3790 allowSyntheticDefaultImports?: boolean;
3791 /** Allow accessing UMD globals from modules. Defaults to `false`. */
3792 allowUmdGlobalAccess?: boolean;
3793 /** Do not report errors on unreachable code. Defaults to `false`. */
3794 allowUnreachableCode?: boolean;
3795 /** Do not report errors on unused labels. Defaults to `false` */
3796 allowUnusedLabels?: boolean;
3797 /** Parse in strict mode and emit `"use strict"` for each source file.
3798 * Defaults to `true`. */
3799 alwaysStrict?: boolean;
3800 /** Base directory to resolve non-relative module names. Defaults to
3801 * `undefined`. */
3802 baseUrl?: string;
3803 /** Report errors in `.js` files. Use in conjunction with `allowJs`. Defaults
3804 * to `false`. */
3805 checkJs?: boolean;
3806 /** Generates corresponding `.d.ts` file. Defaults to `false`. */
3807 declaration?: boolean;
3808 /** Output directory for generated declaration files. */
3809 declarationDir?: string;
3810 /** Generates a source map for each corresponding `.d.ts` file. Defaults to
3811 * `false`. */
3812 declarationMap?: boolean;
3813 /** Provide full support for iterables in `for..of`, spread and
3814 * destructuring when targeting ES5 or ES3. Defaults to `false`. */
3815 downlevelIteration?: boolean;
3816 /** Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files.
3817 * Defaults to `false`. */
3818 emitBOM?: boolean;
3819 /** Only emit `.d.ts` declaration files. Defaults to `false`. */
3820 emitDeclarationOnly?: boolean;
3821 /** Emit design-type metadata for decorated declarations in source. See issue
3822 * [microsoft/TypeScript#2577](https://github.com/Microsoft/TypeScript/issues/2577)
3823 * for details. Defaults to `false`. */
3824 emitDecoratorMetadata?: boolean;
3825 /** Emit `__importStar` and `__importDefault` helpers for runtime babel
3826 * ecosystem compatibility and enable `allowSyntheticDefaultImports` for type
3827 * system compatibility. Defaults to `true`. */
3828 esModuleInterop?: boolean;
3829 /** Enables experimental support for ES decorators. Defaults to `false`. */
3830 experimentalDecorators?: boolean;
3831 /** Emit a single file with source maps instead of having a separate file.
3832 * Defaults to `false`. */
3833 inlineSourceMap?: boolean;
3834 /** Emit the source alongside the source maps within a single file; requires
3835 * `inlineSourceMap` or `sourceMap` to be set. Defaults to `false`. */
3836 inlineSources?: boolean;
3837 /** Perform additional checks to ensure that transpile only would be safe.
3838 * Defaults to `false`. */
3839 isolatedModules?: boolean;
3840 /** Support JSX in `.tsx` files: `"react"`, `"preserve"`, `"react-native"`.
3841 * Defaults to `"react"`. */
3842 jsx?: "react" | "preserve" | "react-native";
3843 /** Specify the JSX factory function to use when targeting react JSX emit,
3844 * e.g. `React.createElement` or `h`. Defaults to `React.createElement`. */
3845 jsxFactory?: string;
3846 /** Resolve keyof to string valued property names only (no numbers or
3847 * symbols). Defaults to `false`. */
3848 keyofStringsOnly?: string;
3849 /** Emit class fields with ECMAScript-standard semantics. Defaults to `false`.
3850 * Does not apply to `"esnext"` target. */
3851 useDefineForClassFields?: boolean;
3852 /** List of library files to be included in the compilation. If omitted,
3853 * then the Deno main runtime libs are used. */
3854 lib?: string[];
3855 /** The locale to use to show error messages. */
3856 locale?: string;
3857 /** Specifies the location where debugger should locate map files instead of
3858 * generated locations. Use this flag if the `.map` files will be located at
3859 * run-time in a different location than the `.js` files. The location
3860 * specified will be embedded in the source map to direct the debugger where
3861 * the map files will be located. Defaults to `undefined`. */
3862 mapRoot?: string;
3863 /** Specify the module format for the emitted code. Defaults to
3864 * `"esnext"`. */
3865 module?:
3866 | "none"
3867 | "commonjs"
3868 | "amd"
3869 | "system"
3870 | "umd"
3871 | "es6"
3872 | "es2015"
3873 | "esnext";
3874 /** Do not generate custom helper functions like `__extends` in compiled
3875 * output. Defaults to `false`. */
3876 noEmitHelpers?: boolean;
3877 /** Report errors for fallthrough cases in switch statement. Defaults to
3878 * `false`. */
3879 noFallthroughCasesInSwitch?: boolean;
3880 /** Raise error on expressions and declarations with an implied any type.
3881 * Defaults to `true`. */
3882 noImplicitAny?: boolean;
3883 /** Report an error when not all code paths in function return a value.
3884 * Defaults to `false`. */
3885 noImplicitReturns?: boolean;
3886 /** Raise error on `this` expressions with an implied `any` type. Defaults to
3887 * `true`. */
3888 noImplicitThis?: boolean;
3889 /** Do not emit `"use strict"` directives in module output. Defaults to
3890 * `false`. */
3891 noImplicitUseStrict?: boolean;
3892 /** Do not add triple-slash references or module import targets to the list of
3893 * compiled files. Defaults to `false`. */
3894 noResolve?: boolean;
3895 /** Disable strict checking of generic signatures in function types. Defaults
3896 * to `false`. */
3897 noStrictGenericChecks?: boolean;
3898 /** Report errors on unused locals. Defaults to `false`. */
3899 noUnusedLocals?: boolean;
3900 /** Report errors on unused parameters. Defaults to `false`. */
3901 noUnusedParameters?: boolean;
3902 /** Redirect output structure to the directory. This only impacts
3903 * `Deno.compile` and only changes the emitted file names. Defaults to
3904 * `undefined`. */
3905 outDir?: string;
3906 /** List of path mapping entries for module names to locations relative to the
3907 * `baseUrl`. Defaults to `undefined`. */
3908 paths?: Record<string, string[]>;
3909 /** Do not erase const enum declarations in generated code. Defaults to
3910 * `false`. */
3911 preserveConstEnums?: boolean;
3912 /** Remove all comments except copy-right header comments beginning with
3913 * `/*!`. Defaults to `true`. */
3914 removeComments?: boolean;
3915 /** Include modules imported with `.json` extension. Defaults to `true`. */
3916 resolveJsonModule?: boolean;
3917 /** Specifies the root directory of input files. Only use to control the
3918 * output directory structure with `outDir`. Defaults to `undefined`. */
3919 rootDir?: string;
3920 /** List of _root_ folders whose combined content represent the structure of
3921 * the project at runtime. Defaults to `undefined`. */
3922 rootDirs?: string[];
3923 /** Generates corresponding `.map` file. Defaults to `false`. */
3924 sourceMap?: boolean;
3925 /** Specifies the location where debugger should locate TypeScript files
3926 * instead of source locations. Use this flag if the sources will be located
3927 * at run-time in a different location than that at design-time. The location
3928 * specified will be embedded in the sourceMap to direct the debugger where
3929 * the source files will be located. Defaults to `undefined`. */
3930 sourceRoot?: string;
3931 /** Enable all strict type checking options. Enabling `strict` enables
3932 * `noImplicitAny`, `noImplicitThis`, `alwaysStrict`, `strictBindCallApply`,
3933 * `strictNullChecks`, `strictFunctionTypes` and
3934 * `strictPropertyInitialization`. Defaults to `true`. */
3935 strict?: boolean;
3936 /** Enable stricter checking of the `bind`, `call`, and `apply` methods on
3937 * functions. Defaults to `true`. */
3938 strictBindCallApply?: boolean;
3939 /** Disable bivariant parameter checking for function types. Defaults to
3940 * `true`. */
3941 strictFunctionTypes?: boolean;
3942 /** Ensure non-undefined class properties are initialized in the constructor.
3943 * This option requires `strictNullChecks` be enabled in order to take effect.
3944 * Defaults to `true`. */
3945 strictPropertyInitialization?: boolean;
3946 /** In strict null checking mode, the `null` and `undefined` values are not in
3947 * the domain of every type and are only assignable to themselves and `any`
3948 * (the one exception being that `undefined` is also assignable to `void`). */
3949 strictNullChecks?: boolean;
3950 /** Suppress excess property checks for object literals. Defaults to
3951 * `false`. */
3952 suppressExcessPropertyErrors?: boolean;
3953 /** Suppress `noImplicitAny` errors for indexing objects lacking index
3954 * signatures. */
3955 suppressImplicitAnyIndexErrors?: boolean;
3956 /** Specify ECMAScript target version. Defaults to `esnext`. */
3957 target?:
3958 | "es3"
3959 | "es5"
3960 | "es6"
3961 | "es2015"
3962 | "es2016"
3963 | "es2017"
3964 | "es2018"
3965 | "es2019"
3966 | "es2020"
3967 | "esnext";
3968 /** List of names of type definitions to include. Defaults to `undefined`.
3969 *
3970 * The type definitions are resolved according to the normal Deno resolution
3971 * irrespective of if sources are provided on the call. Like other Deno
3972 * modules, there is no "magical" resolution. For example:
3973 *
3974 * ```ts
3975 * Deno.compile(
3976 * "./foo.js",
3977 * undefined,
3978 * {
3979 * types: [ "./foo.d.ts", "https://deno.land/x/example/types.d.ts" ]
3980 * }
3981 * );
3982 * ```
3983 */
3984 types?: string[];
3985 }
3986
3987 /** **UNSTABLE**: new API, yet to be vetted.
3988 *
3989 * The results of a transpile only command, where the `source` contains the
3990 * emitted source, and `map` optionally contains the source map. */
3991 export interface TranspileOnlyResult {
3992 source: string;
3993 map?: string;
3994 }
3995
3996 /** **UNSTABLE**: new API, yet to be vetted.
3997 *
3998 * Takes a set of TypeScript sources and resolves to a map where the key was
3999 * the original file name provided in sources and the result contains the
4000 * `source` and optionally the `map` from the transpile operation. This does no
4001 * type checking and validation, it effectively "strips" the types from the
4002 * file.
4003 *
4004 * ```ts
4005 * const results = await Deno.transpileOnly({
4006 * "foo.ts": `const foo: string = "foo";`
4007 * });
4008 * ```
4009 *
4010 * @param sources A map where the key is the filename and the value is the text
4011 * to transpile. The filename is only used in the transpile and
4012 * not resolved, for example to fill in the source name in the
4013 * source map.
4014 * @param options An option object of options to send to the compiler. This is
4015 * a subset of ts.CompilerOptions which can be supported by Deno.
4016 * Many of the options related to type checking and emitting
4017 * type declaration files will have no impact on the output.
4018 */
4019 export function transpileOnly(
4020 sources: Record<string, string>,
4021 options?: CompilerOptions
4022 ): Promise<Record<string, TranspileOnlyResult>>;
4023
4024 /** **UNSTABLE**: new API, yet to be vetted.
4025 *
4026 * Takes a root module name, and optionally a record set of sources. Resolves
4027 * with a compiled set of modules and possibly diagnostics if the compiler
4028 * encountered any issues. If just a root name is provided, the modules
4029 * will be resolved as if the root module had been passed on the command line.
4030 *
4031 * If sources are passed, all modules will be resolved out of this object, where
4032 * the key is the module name and the value is the content. The extension of
4033 * the module name will be used to determine the media type of the module.
4034 *
4035 * ```ts
4036 * const [ maybeDiagnostics1, output1 ] = await Deno.compile("foo.ts");
4037 *
4038 * const [ maybeDiagnostics2, output2 ] = await Deno.compile("/foo.ts", {
4039 * "/foo.ts": `export * from "./bar.ts";`,
4040 * "/bar.ts": `export const bar = "bar";`
4041 * });
4042 * ```
4043 *
4044 * @param rootName The root name of the module which will be used as the
4045 * "starting point". If no `sources` is specified, Deno will
4046 * resolve the module externally as if the `rootName` had been
4047 * specified on the command line.
4048 * @param sources An optional key/value map of sources to be used when resolving
4049 * modules, where the key is the module name, and the value is
4050 * the source content. The extension of the key will determine
4051 * the media type of the file when processing. If supplied,
4052 * Deno will not attempt to resolve any modules externally.
4053 * @param options An optional object of options to send to the compiler. This is
4054 * a subset of ts.CompilerOptions which can be supported by Deno.
4055 */
4056 export function compile(
4057 rootName: string,
4058 sources?: Record<string, string>,
4059 options?: CompilerOptions
4060 ): Promise<[DiagnosticItem[] | undefined, Record<string, string>]>;
4061
4062 /** **UNSTABLE**: new API, yet to be vetted.
4063 *
4064 * `bundle()` is part the compiler API. A full description of this functionality
4065 * can be found in the [manual](https://deno.land/manual/runtime/compiler_apis#denobundle).
4066 *
4067 * Takes a root module name, and optionally a record set of sources. Resolves
4068 * with a single JavaScript string (and bundle diagnostics if issues arise with
4069 * the bundling) that is like the output of a `deno bundle` command. If just
4070 * a root name is provided, the modules will be resolved as if the root module
4071 * had been passed on the command line.
4072 *
4073 * If sources are passed, all modules will be resolved out of this object, where
4074 * the key is the module name and the value is the content. The extension of the
4075 * module name will be used to determine the media type of the module.
4076 *
4077 * ```ts
4078 * // equivalent to "deno bundle foo.ts" from the command line
4079 * const [ maybeDiagnostics1, output1 ] = await Deno.bundle("foo.ts");
4080 *
4081 * const [ maybeDiagnostics2, output2 ] = await Deno.bundle("/foo.ts", {
4082 * "/foo.ts": `export * from "./bar.ts";`,
4083 * "/bar.ts": `export const bar = "bar";`
4084 * });
4085 * ```
4086 *
4087 * @param rootName The root name of the module which will be used as the
4088 * "starting point". If no `sources` is specified, Deno will
4089 * resolve the module externally as if the `rootName` had been
4090 * specified on the command line.
4091 * @param sources An optional key/value map of sources to be used when resolving
4092 * modules, where the key is the module name, and the value is
4093 * the source content. The extension of the key will determine
4094 * the media type of the file when processing. If supplied,
4095 * Deno will not attempt to resolve any modules externally.
4096 * @param options An optional object of options to send to the compiler. This is
4097 * a subset of ts.CompilerOptions which can be supported by Deno.
4098 */
4099 export function bundle(
4100 rootName: string,
4101 sources?: Record<string, string>,
4102 options?: CompilerOptions
4103 ): Promise<[DiagnosticItem[] | undefined, string]>;
4104
4105 /** **UNSTABLE**: Should not have same name as `window.location` type. */
4106 interface Location {
4107 /** The full url for the module, e.g. `file://some/file.ts` or
4108 * `https://some/file.ts`. */
4109 fileName: string;
4110 /** The line number in the file. It is assumed to be 1-indexed. */
4111 lineNumber: number;
4112 /** The column number in the file. It is assumed to be 1-indexed. */
4113 columnNumber: number;
4114 }
4115
4116 /** UNSTABLE: new API, yet to be vetted.
4117 *
4118 * Given a current location in a module, lookup the source location and return
4119 * it.
4120 *
4121 * When Deno transpiles code, it keep source maps of the transpiled code. This
4122 * function can be used to lookup the original location. This is
4123 * automatically done when accessing the `.stack` of an error, or when an
4124 * uncaught error is logged. This function can be used to perform the lookup
4125 * for creating better error handling.
4126 *
4127 * **Note:** `line` and `column` are 1 indexed, which matches display
4128 * expectations, but is not typical of most index numbers in Deno.
4129 *
4130 * An example:
4131 *
4132 * ```ts
4133 * const orig = Deno.applySourceMap({
4134 * fileName: "file://my/module.ts",
4135 * lineNumber: 5,
4136 * columnNumber: 15
4137 * });
4138 * console.log(`${orig.filename}:${orig.line}:${orig.column}`);
4139 * ```
4140 */
4141 export function applySourceMap(location: Location): Location;
4142
4143 enum LinuxSignal {
4144 SIGHUP = 1,
4145 SIGINT = 2,
4146 SIGQUIT = 3,
4147 SIGILL = 4,
4148 SIGTRAP = 5,
4149 SIGABRT = 6,
4150 SIGBUS = 7,
4151 SIGFPE = 8,
4152 SIGKILL = 9,
4153 SIGUSR1 = 10,
4154 SIGSEGV = 11,
4155 SIGUSR2 = 12,
4156 SIGPIPE = 13,
4157 SIGALRM = 14,
4158 SIGTERM = 15,
4159 SIGSTKFLT = 16,
4160 SIGCHLD = 17,
4161 SIGCONT = 18,
4162 SIGSTOP = 19,
4163 SIGTSTP = 20,
4164 SIGTTIN = 21,
4165 SIGTTOU = 22,
4166 SIGURG = 23,
4167 SIGXCPU = 24,
4168 SIGXFSZ = 25,
4169 SIGVTALRM = 26,
4170 SIGPROF = 27,
4171 SIGWINCH = 28,
4172 SIGIO = 29,
4173 SIGPWR = 30,
4174 SIGSYS = 31,
4175 }
4176 enum MacOSSignal {
4177 SIGHUP = 1,
4178 SIGINT = 2,
4179 SIGQUIT = 3,
4180 SIGILL = 4,
4181 SIGTRAP = 5,
4182 SIGABRT = 6,
4183 SIGEMT = 7,
4184 SIGFPE = 8,
4185 SIGKILL = 9,
4186 SIGBUS = 10,
4187 SIGSEGV = 11,
4188 SIGSYS = 12,
4189 SIGPIPE = 13,
4190 SIGALRM = 14,
4191 SIGTERM = 15,
4192 SIGURG = 16,
4193 SIGSTOP = 17,
4194 SIGTSTP = 18,
4195 SIGCONT = 19,
4196 SIGCHLD = 20,
4197 SIGTTIN = 21,
4198 SIGTTOU = 22,
4199 SIGIO = 23,
4200 SIGXCPU = 24,
4201 SIGXFSZ = 25,
4202 SIGVTALRM = 26,
4203 SIGPROF = 27,
4204 SIGWINCH = 28,
4205 SIGINFO = 29,
4206 SIGUSR1 = 30,
4207 SIGUSR2 = 31,
4208 }
4209
4210 /** **UNSTABLE**: make platform independent.
4211 *
4212 * Signals numbers. This is platform dependent. */
4213 export const Signal: typeof MacOSSignal | typeof LinuxSignal;
4214
4215 /** **UNSTABLE**: new API, yet to be vetted.
4216 *
4217 * Represents the stream of signals, implements both `AsyncIterator` and
4218 * `PromiseLike`. */
4219 export class SignalStream
4220 implements AsyncIterableIterator<void>, PromiseLike<void> {
4221 constructor(signal: typeof Deno.Signal);
4222 then<T, S>(
4223 f: (v: void) => T | Promise<T>,
4224 g?: (v: void) => S | Promise<S>
4225 ): Promise<T | S>;
4226 next(): Promise<IteratorResult<void>>;
4227 [Symbol.asyncIterator](): AsyncIterableIterator<void>;
4228 dispose(): void;
4229 }
4230
4231 /** **UNSTABLE**: new API, yet to be vetted.
4232 *
4233 * Returns the stream of the given signal number. You can use it as an async
4234 * iterator.
4235 *
4236 * ```ts
4237 * for await (const _ of Deno.signal(Deno.Signal.SIGTERM)) {
4238 * console.log("got SIGTERM!");
4239 * }
4240 * ```
4241 *
4242 * You can also use it as a promise. In this case you can only receive the
4243 * first one.
4244 *
4245 * ```ts
4246 * await Deno.signal(Deno.Signal.SIGTERM);
4247 * console.log("SIGTERM received!")
4248 * ```
4249 *
4250 * If you want to stop receiving the signals, you can use `.dispose()` method
4251 * of the signal stream object.
4252 *
4253 * ```ts
4254 * const sig = Deno.signal(Deno.Signal.SIGTERM);
4255 * setTimeout(() => { sig.dispose(); }, 5000);
4256 * for await (const _ of sig) {
4257 * console.log("SIGTERM!")
4258 * }
4259 * ```
4260 *
4261 * The above for-await loop exits after 5 seconds when `sig.dispose()` is
4262 * called.
4263 *
4264 * NOTE: This functionality is not yet implemented on Windows.
4265 */
4266 export function signal(signo: number): SignalStream;
4267
4268 /** **UNSTABLE**: new API, yet to be vetted. */
4269 export const signals: {
4270 /** Returns the stream of SIGALRM signals.
4271 *
4272 * This method is the shorthand for `Deno.signal(Deno.Signal.SIGALRM)`. */
4273 alarm: () => SignalStream;
4274 /** Returns the stream of SIGCHLD signals.
4275 *
4276 * This method is the shorthand for `Deno.signal(Deno.Signal.SIGCHLD)`. */
4277 child: () => SignalStream;
4278 /** Returns the stream of SIGHUP signals.
4279 *
4280 * This method is the shorthand for `Deno.signal(Deno.Signal.SIGHUP)`. */
4281 hungup: () => SignalStream;
4282 /** Returns the stream of SIGINT signals.
4283 *
4284 * This method is the shorthand for `Deno.signal(Deno.Signal.SIGINT)`. */
4285 interrupt: () => SignalStream;
4286 /** Returns the stream of SIGIO signals.
4287 *
4288 * This method is the shorthand for `Deno.signal(Deno.Signal.SIGIO)`. */
4289 io: () => SignalStream;
4290 /** Returns the stream of SIGPIPE signals.
4291 *
4292 * This method is the shorthand for `Deno.signal(Deno.Signal.SIGPIPE)`. */
4293 pipe: () => SignalStream;
4294 /** Returns the stream of SIGQUIT signals.
4295 *
4296 * This method is the shorthand for `Deno.signal(Deno.Signal.SIGQUIT)`. */
4297 quit: () => SignalStream;
4298 /** Returns the stream of SIGTERM signals.
4299 *
4300 * This method is the shorthand for `Deno.signal(Deno.Signal.SIGTERM)`. */
4301 terminate: () => SignalStream;
4302 /** Returns the stream of SIGUSR1 signals.
4303 *
4304 * This method is the shorthand for `Deno.signal(Deno.Signal.SIGUSR1)`. */
4305 userDefined1: () => SignalStream;
4306 /** Returns the stream of SIGUSR2 signals.
4307 *
4308 * This method is the shorthand for `Deno.signal(Deno.Signal.SIGUSR2)`. */
4309 userDefined2: () => SignalStream;
4310 /** Returns the stream of SIGWINCH signals.
4311 *
4312 * This method is the shorthand for `Deno.signal(Deno.Signal.SIGWINCH)`. */
4313 windowChange: () => SignalStream;
4314 };
4315
4316 /** **UNSTABLE**: new API, yet to be vetted
4317 *
4318 * Set TTY to be under raw mode or not. In raw mode, characters are read and
4319 * returned as is, without being processed. All special processing of
4320 * characters by the terminal is disabled, including echoing input characters.
4321 * Reading from a TTY device in raw mode is faster than reading from a TTY
4322 * device in canonical mode.
4323 *
4324 * ```ts
4325 * Deno.setRaw(myTTY.rid, true);
4326 * ```
4327 */
4328 export function setRaw(rid: number, mode: boolean): void;
4329
4330 /** **UNSTABLE**: needs investigation into high precision time.
4331 *
4332 * Synchronously changes the access (`atime`) and modification (`mtime`) times
4333 * of a file system object referenced by `path`. Given times are either in
4334 * seconds (UNIX epoch time) or as `Date` objects.
4335 *
4336 * ```ts
4337 * Deno.utimeSync("myfile.txt", 1556495550, new Date());
4338 * ```
4339 *
4340 * Requires `allow-write` permission. */
4341 export function utimeSync(
4342 path: string,
4343 atime: number | Date,
4344 mtime: number | Date
4345 ): void;
4346
4347 /** **UNSTABLE**: needs investigation into high precision time.
4348 *
4349 * Changes the access (`atime`) and modification (`mtime`) times of a file
4350 * system object referenced by `path`. Given times are either in seconds
4351 * (UNIX epoch time) or as `Date` objects.
4352 *
4353 * ```ts
4354 * await Deno.utime("myfile.txt", 1556495550, new Date());
4355 * ```
4356 *
4357 * Requires `allow-write` permission. */
4358 export function utime(
4359 path: string,
4360 atime: number | Date,
4361 mtime: number | Date
4362 ): Promise<void>;
4363
4364 /** **UNSTABLE**: Maybe remove `ShutdownMode` entirely.
4365 *
4366 * Corresponds to `SHUT_RD`, `SHUT_WR`, `SHUT_RDWR` on POSIX-like systems.
4367 *
4368 * See: http://man7.org/linux/man-pages/man2/shutdown.2.html */
4369 export enum ShutdownMode {
4370 Read = 0,
4371 Write,
4372 ReadWrite, // TODO(ry) panics on ReadWrite.
4373 }
4374
4375 /** **UNSTABLE**: Both the `how` parameter and `ShutdownMode` enum are under
4376 * consideration for removal.
4377 *
4378 * Shutdown socket send and receive operations.
4379 *
4380 * Matches behavior of POSIX shutdown(3).
4381 *
4382 * ```ts
4383 * const listener = Deno.listen({ port: 80 });
4384 * const conn = await listener.accept();
4385 * Deno.shutdown(conn.rid, Deno.ShutdownMode.Write);
4386 * ```
4387 */
4388 export function shutdown(rid: number, how: ShutdownMode): Promise<void>;
4389
4390 /** **UNSTABLE**:: new API, yet to be vetted.
4391 *
4392 * A generic transport listener for message-oriented protocols. */
4393 export interface DatagramConn extends AsyncIterable<[Uint8Array, Addr]> {
4394 /** **UNSTABLE**: new API, yet to be vetted.
4395 *
4396 * Waits for and resolves to the next message to the `UDPConn`. */
4397 receive(p?: Uint8Array): Promise<[Uint8Array, Addr]>;
4398 /** UNSTABLE: new API, yet to be vetted.
4399 *
4400 * Sends a message to the target. */
4401 send(p: Uint8Array, addr: Addr): Promise<void>;
4402 /** UNSTABLE: new API, yet to be vetted.
4403 *
4404 * Close closes the socket. Any pending message promises will be rejected
4405 * with errors. */
4406 close(): void;
4407 /** Return the address of the `UDPConn`. */
4408 readonly addr: Addr;
4409 [Symbol.asyncIterator](): AsyncIterableIterator<[Uint8Array, Addr]>;
4410 }
4411
4412 export interface UnixListenOptions {
4413 /** A Path to the Unix Socket. */
4414 path: string;
4415 }
4416
4417 /** **UNSTABLE**: new API, yet to be vetted.
4418 *
4419 * Listen announces on the local transport address.
4420 *
4421 * ```ts
4422 * const listener = Deno.listen({ path: "/foo/bar.sock", transport: "unix" })
4423 * ```
4424 *
4425 * Requires `allow-read` and `allow-write` permission. */
4426 export function listen(
4427 options: UnixListenOptions & { transport: "unix" }
4428 ): Listener;
4429
4430 /** **UNSTABLE**: new API
4431 *
4432 * Listen announces on the local transport address.
4433 *
4434 * ```ts
4435 * const listener1 = Deno.listenDatagram({
4436 * port: 80,
4437 * transport: "udp"
4438 * });
4439 * const listener2 = Deno.listenDatagram({
4440 * hostname: "golang.org",
4441 * port: 80,
4442 * transport: "udp"
4443 * });
4444 * ```
4445 *
4446 * Requires `allow-net` permission. */
4447 export function listenDatagram(
4448 options: ListenOptions & { transport: "udp" }
4449 ): DatagramConn;
4450
4451 /** **UNSTABLE**: new API
4452 *
4453 * Listen announces on the local transport address.
4454 *
4455 * ```ts
4456 * const listener = Deno.listenDatagram({
4457 * address: "/foo/bar.sock",
4458 * transport: "unixpacket"
4459 * });
4460 * ```
4461 *
4462 * Requires `allow-read` and `allow-write` permission. */
4463 export function listenDatagram(
4464 options: UnixListenOptions & { transport: "unixpacket" }
4465 ): DatagramConn;
4466
4467 export interface UnixConnectOptions {
4468 transport: "unix";
4469 path: string;
4470 }
4471
4472 /**
4473 * Connects to the hostname (default is "127.0.0.1") and port on the named
4474 * transport (default is "tcp"), and resolves to the connection (`Conn`).
4475 *
4476 * ```ts
4477 * const conn1 = await Deno.connect({ port: 80 });
4478 * const conn2 = await Deno.connect({ hostname: "192.0.2.1", port: 80 });
4479 * const conn3 = await Deno.connect({ hostname: "[2001:db8::1]", port: 80 });
4480 * const conn4 = await Deno.connect({ hostname: "golang.org", port: 80, transport: "tcp" });
4481 * const conn5 = await Deno.connect({ path: "/foo/bar.sock", transport: "unix" });
4482 * ```
4483 *
4484 * Requires `allow-net` permission for "tcp" and `allow-read` for unix. */
4485 export function connect(
4486 options: ConnectOptions | UnixConnectOptions
4487 ): Promise<Conn>;
4488
4489 export interface StartTlsOptions {
4490 /** A literal IP address or host name that can be resolved to an IP address.
4491 * If not specified, defaults to `127.0.0.1`. */
4492 hostname?: string;
4493 /** Server certificate file. */
4494 certFile?: string;
4495 }
4496
4497 /** **UNSTABLE**: new API, yet to be vetted.
4498 *
4499 * Start TLS handshake from an existing connection using
4500 * an optional cert file, hostname (default is "127.0.0.1"). The
4501 * cert file is optional and if not included Mozilla's root certificates will
4502 * be used (see also https://github.com/ctz/webpki-roots for specifics)
4503 * Using this function requires that the other end of the connection is
4504 * prepared for TLS handshake.
4505 *
4506 * ```ts
4507 * const conn = await Deno.connect({ port: 80, hostname: "127.0.0.1" });
4508 * const tlsConn = await Deno.startTls(conn, { certFile: "./certs/my_custom_root_CA.pem", hostname: "127.0.0.1", port: 80 });
4509 * ```
4510 *
4511 * Requires `allow-net` permission.
4512 */
4513 export function startTls(
4514 conn: Conn,
4515 options?: StartTlsOptions
4516 ): Promise<Conn>;
4517
4518 /** **UNSTABLE**: The `signo` argument may change to require the Deno.Signal
4519 * enum.
4520 *
4521 * Send a signal to process under given `pid`. This functionality currently
4522 * only works on Linux and Mac OS.
4523 *
4524 * If `pid` is negative, the signal will be sent to the process group
4525 * identified by `pid`.
4526 *
4527 * const p = Deno.run({
4528 * cmd: ["python", "-c", "from time import sleep; sleep(10000)"]
4529 * });
4530 *
4531 * Deno.kill(p.pid, Deno.Signal.SIGINT);
4532 *
4533 * Requires `allow-run` permission. */
4534 export function kill(pid: number, signo: number): void;
4535
4536 /** The name of a "powerful feature" which needs permission.
4537 *
4538 * See: https://w3c.github.io/permissions/#permission-registry
4539 *
4540 * Note that the definition of `PermissionName` in the above spec is swapped
4541 * out for a set of Deno permissions which are not web-compatible. */
4542 export type PermissionName =
4543 | "run"
4544 | "read"
4545 | "write"
4546 | "net"
4547 | "env"
4548 | "plugin"
4549 | "hrtime";
4550
4551 /** The current status of the permission.
4552 *
4553 * See: https://w3c.github.io/permissions/#status-of-a-permission */
4554 export type PermissionState = "granted" | "denied" | "prompt";
4555
4556 export interface RunPermissionDescriptor {
4557 name: "run";
4558 }
4559
4560 export interface ReadPermissionDescriptor {
4561 name: "read";
4562 path?: string;
4563 }
4564
4565 export interface WritePermissionDescriptor {
4566 name: "write";
4567 path?: string;
4568 }
4569
4570 export interface NetPermissionDescriptor {
4571 name: "net";
4572 url?: string;
4573 }
4574
4575 export interface EnvPermissionDescriptor {
4576 name: "env";
4577 }
4578
4579 export interface PluginPermissionDescriptor {
4580 name: "plugin";
4581 }
4582
4583 export interface HrtimePermissionDescriptor {
4584 name: "hrtime";
4585 }
4586
4587 /** Permission descriptors which define a permission and can be queried,
4588 * requested, or revoked.
4589 *
4590 * See: https://w3c.github.io/permissions/#permission-descriptor */
4591 export type PermissionDescriptor =
4592 | RunPermissionDescriptor
4593 | ReadPermissionDescriptor
4594 | WritePermissionDescriptor
4595 | NetPermissionDescriptor
4596 | EnvPermissionDescriptor
4597 | PluginPermissionDescriptor
4598 | HrtimePermissionDescriptor;
4599
4600 export class Permissions {
4601 /** Resolves to the current status of a permission.
4602 *
4603 * ```ts
4604 * const status = await Deno.permissions.query({ name: "read", path: "/etc" });
4605 * if (status.state === "granted") {
4606 * data = await Deno.readFile("/etc/passwd");
4607 * }
4608 * ```
4609 */
4610 query(desc: PermissionDescriptor): Promise<PermissionStatus>;
4611
4612 /** Revokes a permission, and resolves to the state of the permission.
4613 *
4614 * const status = await Deno.permissions.revoke({ name: "run" });
4615 * assert(status.state !== "granted")
4616 */
4617 revoke(desc: PermissionDescriptor): Promise<PermissionStatus>;
4618
4619 /** Requests the permission, and resolves to the state of the permission.
4620 *
4621 * ```ts
4622 * const status = await Deno.permissions.request({ name: "env" });
4623 * if (status.state === "granted") {
4624 * console.log(Deno.dir("home");
4625 * } else {
4626 * console.log("'env' permission is denied.");
4627 * }
4628 * ```
4629 */
4630 request(desc: PermissionDescriptor): Promise<PermissionStatus>;
4631 }
4632
4633 /** **UNSTABLE**: maybe move to `navigator.permissions` to match web API. It
4634 * could look like `navigator.permissions.query({ name: Deno.symbols.read })`.
4635 */
4636 export const permissions: Permissions;
4637
4638 /** see: https://w3c.github.io/permissions/#permissionstatus */
4639 export class PermissionStatus {
4640 state: PermissionState;
4641 constructor(state: PermissionState);
4642 }
4643
4644 /** Get the `hostname` of the machine the Deno process is running on.
4645 *
4646 * ```ts
4647 * console.log(Deno.hostname());
4648 * ```
4649 *
4650 * Requires `allow-env` permission.
4651 */
4652 export function hostname(): string;
4653}
4654
\No newline at end of file