diff --git a/.gitignore b/.gitignore index b47f73edb42..7c50504c14d 100644 --- a/.gitignore +++ b/.gitignore @@ -20,7 +20,6 @@ coverage/ /build/ /scripts/build/ -!/scripts/build/deno-cache dist/ # submodule packages diff --git a/bin/cli.ts b/bin/cli.ts deleted file mode 100644 index 2fc3b584fa0..00000000000 --- a/bin/cli.ts +++ /dev/null @@ -1,20 +0,0 @@ -// deno install -n stencil --allow-read --allow-write --allow-net -f ./bin/cli.ts - -import { run } from '../cli/index.js'; -import { createDenoLogger, createDenoSys } from '../sys/deno/index.js'; - -if (import.meta.main) { - try { - const denoLogger = createDenoLogger({ Deno }); - const denoSys = createDenoSys({ Deno }); - - await run({ - args: Deno.args, - logger: denoLogger, - sys: denoSys, - }); - } catch (e) { - console.error('uncaught error', e); - Deno.exit(1); - } -} diff --git a/docs/adr/0010-deno-vendoring.md b/docs/adr/0010-deno-vendoring.md index 744ff37be83..c005dc4a3ff 100644 --- a/docs/adr/0010-deno-vendoring.md +++ b/docs/adr/0010-deno-vendoring.md @@ -4,7 +4,7 @@ Date: 2021-08-24 ## Status -accepted +deprecated - see [0013-deno-removal.md](./0013-deno-removal.md) ## Context @@ -66,4 +66,5 @@ experimental feature, we accept that risk. ## Links +- Document that supersedes this one: [0013-deno-removal.md](./0013-deno-removal.md) - PR introducing this change: [fix(ci): vendor deno for builds #3020](https://github.com/ionic-team/stencil/pull/3020) diff --git a/docs/adr/0013-deno-removal.md b/docs/adr/0013-deno-removal.md new file mode 100644 index 00000000000..fc87719c63a --- /dev/null +++ b/docs/adr/0013-deno-removal.md @@ -0,0 +1,37 @@ +# 13. deno-removal + +Date: 2021.09.16 + +## Status + +accepted + +## Context + +Deno support in Stencil has always been marked as 'experimental'. Throughout the feature's lifespan, the current team +has run into some form of issue or another. For a concrete example of such an issue, see +[0010-deno-vendoring.md](./0010-deno-vendoring.md). + +The Stencil team revisited the capability and value associated with this functionality. The feature did not work in +the latest version of Stencil, and the team has not been able to get any positive signal that this functionality is +being used. + +## Decision + +Deno shall be removed from the Stencil codebase. However, the `sys` interface shall remain. + +Deno shall be removed from the Stencil site as a downloadable executable, and marked as having reached end of life. + +## Consequences + +The codebase may become easier to maintain. + +It is possible the PR in which Deno is removed may leave behind artifacts from the Deno implementation. This includes, +but is not limited to: +- Implementation details that are a result of the system handling both the node and Deno runtimes +- Subtle breakages in the codebase in the event of global entities being mutated at build/runtime + +## Links + +- [0010-deno-vendoring.md](./0010-deno-vendoring.md) +- [Deno End of Life PR](https://github.com/ionic-team/stencil-site/pull/764) \ No newline at end of file diff --git a/docs/adr/README.md b/docs/adr/README.md index 2c826c676d8..5e963142fdc 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -12,3 +12,4 @@ * [10. deno-vendoring](0010-deno-vendoring.md) * [11. karma-testing-constraints](0011-karma-testing-constraints.md) * [12. output-markdown-format](0012-output-markdown-format.md) +* [13. deno-removal](0013-deno-removal.md) diff --git a/scripts/build.ts b/scripts/build.ts index bfb983a4ec1..88627e15139 100644 --- a/scripts/build.ts +++ b/scripts/build.ts @@ -9,7 +9,6 @@ import { internal } from './bundles/internal'; import { mockDoc } from './bundles/mock-doc'; import { release } from './release'; import { screenshot } from './bundles/screenshot'; -import { sysDeno } from './bundles/sys-deno'; import { sysNode, sysNodeExternalBundles } from './bundles/sys-node'; import { testing } from './bundles/testing'; import { validateBuild } from './test/validate-build'; @@ -52,7 +51,6 @@ export async function createBuild(opts: BuildOptions): Promise> 4]; - dst[i * 2 + 1] = hextable[v & 0x0f]; - } - return dst; -} - -/** - * EncodeToString returns the hexadecimal encoding of `src`. - * @param src - */ -export function encodeToString(src: Uint8Array): string { - return new TextDecoder().decode(encode(src)); -} - -/** - * Decode decodes `src` into `decodedLen(src.length)` bytes - * If the input is malformed an error will be thrown - * the error. - * @param src - */ -export function decode(src: Uint8Array): Uint8Array { - const dst = new Uint8Array(decodedLen(src.length)); - for (let i = 0; i < dst.length; i++) { - const a = fromHexChar(src[i * 2]); - const b = fromHexChar(src[i * 2 + 1]); - dst[i] = (a << 4) | b; - } - - if (src.length % 2 == 1) { - // Check for invalid char before reporting bad length, - // since the invalid char (if present) is an earlier problem. - fromHexChar(src[dst.length * 2]); - throw errLength(); - } - - return dst; -} - -/** - * DecodedLen returns the length of decoding `x` source bytes. - * Specifically, it returns `x / 2`. - * @param x - */ -export function decodedLen(x: number): number { - return x >>> 1; -} - -/** - * DecodeString returns the bytes represented by the hexadecimal string `s`. - * DecodeString expects that src contains only hexadecimal characters and that - * src has even length. - * If the input is malformed, DecodeString will throw an error. - * @param s the `string` to decode to `Uint8Array` - */ -export function decodeString(s: string): Uint8Array { - return decode(new TextEncoder().encode(s)); -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_fmt_colors_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_fmt_colors_ts.ts deleted file mode 100644 index 7a12b28837e..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_fmt_colors_ts.ts +++ /dev/null @@ -1,255 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -/** A module to print ANSI terminal colors. Inspired by chalk, kleur, and colors - * on npm. - * - * ``` - * import { bgBlue, red, bold } from "https://deno.land/std/fmt/colors.ts"; - * console.log(bgBlue(red(bold("Hello world!")))); - * ``` - * - * This module supports `NO_COLOR` environmental variable disabling any coloring - * if `NO_COLOR` is set. - * - * This module is browser compatible. */ - -const noColor = globalThis.Deno?.noColor ?? true; - -interface Code { - open: string; - close: string; - regexp: RegExp; -} - -/** RGB 8-bits per channel. Each in range `0->255` or `0x00->0xff` */ -interface Rgb { - r: number; - g: number; - b: number; -} - -let enabled = !noColor; - -export function setColorEnabled(value: boolean): void { - if (noColor) { - return; - } - - enabled = value; -} - -export function getColorEnabled(): boolean { - return enabled; -} - -function code(open: number[], close: number): Code { - return { - open: `\x1b[${open.join(";")}m`, - close: `\x1b[${close}m`, - regexp: new RegExp(`\\x1b\\[${close}m`, "g"), - }; -} - -function run(str: string, code: Code): string { - return enabled - ? `${code.open}${str.replace(code.regexp, code.open)}${code.close}` - : str; -} - -export function reset(str: string): string { - return run(str, code([0], 0)); -} - -export function bold(str: string): string { - return run(str, code([1], 22)); -} - -export function dim(str: string): string { - return run(str, code([2], 22)); -} - -export function italic(str: string): string { - return run(str, code([3], 23)); -} - -export function underline(str: string): string { - return run(str, code([4], 24)); -} - -export function inverse(str: string): string { - return run(str, code([7], 27)); -} - -export function hidden(str: string): string { - return run(str, code([8], 28)); -} - -export function strikethrough(str: string): string { - return run(str, code([9], 29)); -} - -export function black(str: string): string { - return run(str, code([30], 39)); -} - -export function red(str: string): string { - return run(str, code([31], 39)); -} - -export function green(str: string): string { - return run(str, code([32], 39)); -} - -export function yellow(str: string): string { - return run(str, code([33], 39)); -} - -export function blue(str: string): string { - return run(str, code([34], 39)); -} - -export function magenta(str: string): string { - return run(str, code([35], 39)); -} - -export function cyan(str: string): string { - return run(str, code([36], 39)); -} - -export function white(str: string): string { - return run(str, code([37], 39)); -} - -export function gray(str: string): string { - return run(str, code([90], 39)); -} - -export function bgBlack(str: string): string { - return run(str, code([40], 49)); -} - -export function bgRed(str: string): string { - return run(str, code([41], 49)); -} - -export function bgGreen(str: string): string { - return run(str, code([42], 49)); -} - -export function bgYellow(str: string): string { - return run(str, code([43], 49)); -} - -export function bgBlue(str: string): string { - return run(str, code([44], 49)); -} - -export function bgMagenta(str: string): string { - return run(str, code([45], 49)); -} - -export function bgCyan(str: string): string { - return run(str, code([46], 49)); -} - -export function bgWhite(str: string): string { - return run(str, code([47], 49)); -} - -/* Special Color Sequences */ - -function clampAndTruncate(n: number, max = 255, min = 0): number { - return Math.trunc(Math.max(Math.min(n, max), min)); -} - -/** Set text color using paletted 8bit colors. - * https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit */ -export function rgb8(str: string, color: number): string { - return run(str, code([38, 5, clampAndTruncate(color)], 39)); -} - -/** Set background color using paletted 8bit colors. - * https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit */ -export function bgRgb8(str: string, color: number): string { - return run(str, code([48, 5, clampAndTruncate(color)], 49)); -} - -/** Set text color using 24bit rgb. - * `color` can be a number in range `0x000000` to `0xffffff` or - * an `Rgb`. - * - * To produce the color magenta: - * - * rgba24("foo", 0xff00ff); - * rgba24("foo", {r: 255, g: 0, b: 255}); - */ -export function rgb24(str: string, color: number | Rgb): string { - if (typeof color === "number") { - return run( - str, - code( - [38, 2, (color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff], - 39, - ), - ); - } - return run( - str, - code( - [ - 38, - 2, - clampAndTruncate(color.r), - clampAndTruncate(color.g), - clampAndTruncate(color.b), - ], - 39, - ), - ); -} - -/** Set background color using 24bit rgb. - * `color` can be a number in range `0x000000` to `0xffffff` or - * an `Rgb`. - * - * To produce the color magenta: - * - * bgRgba24("foo", 0xff00ff); - * bgRgba24("foo", {r: 255, g: 0, b: 255}); - */ -export function bgRgb24(str: string, color: number | Rgb): string { - if (typeof color === "number") { - return run( - str, - code( - [48, 2, (color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff], - 49, - ), - ); - } - return run( - str, - code( - [ - 48, - 2, - clampAndTruncate(color.r), - clampAndTruncate(color.g), - clampAndTruncate(color.b), - ], - 49, - ), - ); -} - -// https://github.com/chalk/ansi-regex/blob/2b56fb0c7a07108e5b54241e8faec160d393aedb/index.js -const ANSI_PATTERN = new RegExp( - [ - "[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)", - "(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))", - ].join("|"), - "g", -); - -export function stripColor(string: string): string { - return string.replace(ANSI_PATTERN, ""); -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_fs__util_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_fs__util_ts.ts deleted file mode 100644 index 6866526cdcc..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_fs__util_ts.ts +++ /dev/null @@ -1,38 +0,0 @@ -import * as path from "../path/mod.ts"; - -/** - * Test whether or not `dest` is a sub-directory of `src` - * @param src src file path - * @param dest dest file path - * @param sep path separator - */ -export function isSubdir( - src: string, - dest: string, - sep: string = path.sep, -): boolean { - if (src === dest) { - return false; - } - const srcArray = src.split(sep); - const destArray = dest.split(sep); - return srcArray.every((current, i) => destArray[i] === current); -} - -export type PathType = "file" | "dir" | "symlink"; - -/** - * Get a human readable file type string. - * - * @param fileInfo A FileInfo describes a file and is returned by `stat`, - * `lstat` - */ -export function getFileInfoType(fileInfo: Deno.FileInfo): PathType | undefined { - return fileInfo.isFile - ? "file" - : fileInfo.isDirectory - ? "dir" - : fileInfo.isSymlink - ? "symlink" - : undefined; -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_copy_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_fs_copy_ts.ts deleted file mode 100644 index b1b34035438..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_copy_ts.ts +++ /dev/null @@ -1,293 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import * as path from "../path/mod.ts"; -import { ensureDir, ensureDirSync } from "./ensure_dir.ts"; -import { isSubdir, getFileInfoType } from "./_util.ts"; -import { assert } from "../_util/assert.ts"; - -const isWindows = Deno.build.os === "windows"; - -export interface CopyOptions { - /** - * overwrite existing file or directory. Default is `false` - */ - overwrite?: boolean; - /** - * When `true`, will set last modification and access times to the ones of the - * original source files. - * When `false`, timestamp behavior is OS-dependent. - * Default is `false`. - */ - preserveTimestamps?: boolean; -} - -async function ensureValidCopy( - src: string, - dest: string, - options: CopyOptions, - isCopyFolder = false, -): Promise { - let destStat: Deno.FileInfo; - - try { - destStat = await Deno.lstat(dest); - } catch (err) { - if (err instanceof Deno.errors.NotFound) { - return; - } - throw err; - } - - if (isCopyFolder && !destStat.isDirectory) { - throw new Error( - `Cannot overwrite non-directory '${dest}' with directory '${src}'.`, - ); - } - if (!options.overwrite) { - throw new Error(`'${dest}' already exists.`); - } - - return destStat; -} - -function ensureValidCopySync( - src: string, - dest: string, - options: CopyOptions, - isCopyFolder = false, -): Deno.FileInfo | undefined { - let destStat: Deno.FileInfo; - try { - destStat = Deno.lstatSync(dest); - } catch (err) { - if (err instanceof Deno.errors.NotFound) { - return; - } - throw err; - } - - if (isCopyFolder && !destStat.isDirectory) { - throw new Error( - `Cannot overwrite non-directory '${dest}' with directory '${src}'.`, - ); - } - if (!options.overwrite) { - throw new Error(`'${dest}' already exists.`); - } - - return destStat; -} - -/* copy file to dest */ -async function copyFile( - src: string, - dest: string, - options: CopyOptions, -): Promise { - await ensureValidCopy(src, dest, options); - await Deno.copyFile(src, dest); - if (options.preserveTimestamps) { - const statInfo = await Deno.stat(src); - assert(statInfo.atime instanceof Date, `statInfo.atime is unavailable`); - assert(statInfo.mtime instanceof Date, `statInfo.mtime is unavailable`); - await Deno.utime(dest, statInfo.atime, statInfo.mtime); - } -} -/* copy file to dest synchronously */ -function copyFileSync(src: string, dest: string, options: CopyOptions): void { - ensureValidCopySync(src, dest, options); - Deno.copyFileSync(src, dest); - if (options.preserveTimestamps) { - const statInfo = Deno.statSync(src); - assert(statInfo.atime instanceof Date, `statInfo.atime is unavailable`); - assert(statInfo.mtime instanceof Date, `statInfo.mtime is unavailable`); - Deno.utimeSync(dest, statInfo.atime, statInfo.mtime); - } -} - -/* copy symlink to dest */ -async function copySymLink( - src: string, - dest: string, - options: CopyOptions, -): Promise { - await ensureValidCopy(src, dest, options); - const originSrcFilePath = await Deno.readLink(src); - const type = getFileInfoType(await Deno.lstat(src)); - if (isWindows) { - await Deno.symlink(originSrcFilePath, dest, { - type: type === "dir" ? "dir" : "file", - }); - } else { - await Deno.symlink(originSrcFilePath, dest); - } - if (options.preserveTimestamps) { - const statInfo = await Deno.lstat(src); - assert(statInfo.atime instanceof Date, `statInfo.atime is unavailable`); - assert(statInfo.mtime instanceof Date, `statInfo.mtime is unavailable`); - await Deno.utime(dest, statInfo.atime, statInfo.mtime); - } -} - -/* copy symlink to dest synchronously */ -function copySymlinkSync( - src: string, - dest: string, - options: CopyOptions, -): void { - ensureValidCopySync(src, dest, options); - const originSrcFilePath = Deno.readLinkSync(src); - const type = getFileInfoType(Deno.lstatSync(src)); - if (isWindows) { - Deno.symlinkSync(originSrcFilePath, dest, { - type: type === "dir" ? "dir" : "file", - }); - } else { - Deno.symlinkSync(originSrcFilePath, dest); - } - - if (options.preserveTimestamps) { - const statInfo = Deno.lstatSync(src); - assert(statInfo.atime instanceof Date, `statInfo.atime is unavailable`); - assert(statInfo.mtime instanceof Date, `statInfo.mtime is unavailable`); - Deno.utimeSync(dest, statInfo.atime, statInfo.mtime); - } -} - -/* copy folder from src to dest. */ -async function copyDir( - src: string, - dest: string, - options: CopyOptions, -): Promise { - const destStat = await ensureValidCopy(src, dest, options, true); - - if (!destStat) { - await ensureDir(dest); - } - - if (options.preserveTimestamps) { - const srcStatInfo = await Deno.stat(src); - assert(srcStatInfo.atime instanceof Date, `statInfo.atime is unavailable`); - assert(srcStatInfo.mtime instanceof Date, `statInfo.mtime is unavailable`); - await Deno.utime(dest, srcStatInfo.atime, srcStatInfo.mtime); - } - - for await (const entry of Deno.readDir(src)) { - const srcPath = path.join(src, entry.name); - const destPath = path.join(dest, path.basename(srcPath as string)); - if (entry.isSymlink) { - await copySymLink(srcPath, destPath, options); - } else if (entry.isDirectory) { - await copyDir(srcPath, destPath, options); - } else if (entry.isFile) { - await copyFile(srcPath, destPath, options); - } - } -} - -/* copy folder from src to dest synchronously */ -function copyDirSync(src: string, dest: string, options: CopyOptions): void { - const destStat = ensureValidCopySync(src, dest, options, true); - - if (!destStat) { - ensureDirSync(dest); - } - - if (options.preserveTimestamps) { - const srcStatInfo = Deno.statSync(src); - assert(srcStatInfo.atime instanceof Date, `statInfo.atime is unavailable`); - assert(srcStatInfo.mtime instanceof Date, `statInfo.mtime is unavailable`); - Deno.utimeSync(dest, srcStatInfo.atime, srcStatInfo.mtime); - } - - for (const entry of Deno.readDirSync(src)) { - assert(entry.name != null, "file.name must be set"); - const srcPath = path.join(src, entry.name); - const destPath = path.join(dest, path.basename(srcPath as string)); - if (entry.isSymlink) { - copySymlinkSync(srcPath, destPath, options); - } else if (entry.isDirectory) { - copyDirSync(srcPath, destPath, options); - } else if (entry.isFile) { - copyFileSync(srcPath, destPath, options); - } - } -} - -/** - * Copy a file or directory. The directory can have contents. Like `cp -r`. - * Requires the `--allow-read` and `--allow-write` flag. - * @param src the file/directory path. - * Note that if `src` is a directory it will copy everything inside - * of this directory, not the entire directory itself - * @param dest the destination path. Note that if `src` is a file, `dest` cannot - * be a directory - * @param options - */ -export async function copy( - src: string, - dest: string, - options: CopyOptions = {}, -): Promise { - src = path.resolve(src); - dest = path.resolve(dest); - - if (src === dest) { - throw new Error("Source and destination cannot be the same."); - } - - const srcStat = await Deno.lstat(src); - - if (srcStat.isDirectory && isSubdir(src, dest)) { - throw new Error( - `Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`, - ); - } - - if (srcStat.isSymlink) { - await copySymLink(src, dest, options); - } else if (srcStat.isDirectory) { - await copyDir(src, dest, options); - } else if (srcStat.isFile) { - await copyFile(src, dest, options); - } -} - -/** - * Copy a file or directory. The directory can have contents. Like `cp -r`. - * Requires the `--allow-read` and `--allow-write` flag. - * @param src the file/directory path. - * Note that if `src` is a directory it will copy everything inside - * of this directory, not the entire directory itself - * @param dest the destination path. Note that if `src` is a file, `dest` cannot - * be a directory - * @param options - */ -export function copySync( - src: string, - dest: string, - options: CopyOptions = {}, -): void { - src = path.resolve(src); - dest = path.resolve(dest); - - if (src === dest) { - throw new Error("Source and destination cannot be the same."); - } - - const srcStat = Deno.lstatSync(src); - - if (srcStat.isDirectory && isSubdir(src, dest)) { - throw new Error( - `Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`, - ); - } - - if (srcStat.isSymlink) { - copySymlinkSync(src, dest, options); - } else if (srcStat.isDirectory) { - copyDirSync(src, dest, options); - } else if (srcStat.isFile) { - copyFileSync(src, dest, options); - } -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_empty_dir_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_fs_empty_dir_ts.ts deleted file mode 100644 index dea09b5c07a..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_empty_dir_ts.ts +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { join } from "../path/mod.ts"; - -/** - * Ensures that a directory is empty. - * Deletes directory contents if the directory is not empty. - * If the directory does not exist, it is created. - * The directory itself is not deleted. - * Requires the `--allow-read` and `--allow-write` flag. - */ -export async function emptyDir(dir: string): Promise { - try { - const items = []; - for await (const dirEntry of Deno.readDir(dir)) { - items.push(dirEntry); - } - - while (items.length) { - const item = items.shift(); - if (item && item.name) { - const filepath = join(dir, item.name); - await Deno.remove(filepath, { recursive: true }); - } - } - } catch (err) { - if (!(err instanceof Deno.errors.NotFound)) { - throw err; - } - - // if not exist. then create it - await Deno.mkdir(dir, { recursive: true }); - } -} - -/** - * Ensures that a directory is empty. - * Deletes directory contents if the directory is not empty. - * If the directory does not exist, it is created. - * The directory itself is not deleted. - * Requires the `--allow-read` and `--allow-write` flag. - */ -export function emptyDirSync(dir: string): void { - try { - const items = [...Deno.readDirSync(dir)]; - - // If the directory exists, remove all entries inside it. - while (items.length) { - const item = items.shift(); - if (item && item.name) { - const filepath = join(dir, item.name); - Deno.removeSync(filepath, { recursive: true }); - } - } - } catch (err) { - if (!(err instanceof Deno.errors.NotFound)) { - throw err; - } - // if not exist. then create it - Deno.mkdirSync(dir, { recursive: true }); - return; - } -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_ensure_dir_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_fs_ensure_dir_ts.ts deleted file mode 100644 index f5b5cd30950..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_ensure_dir_ts.ts +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { getFileInfoType } from "./_util.ts"; - -/** - * Ensures that the directory exists. - * If the directory structure does not exist, it is created. Like mkdir -p. - * Requires the `--allow-read` and `--allow-write` flag. - */ -export async function ensureDir(dir: string): Promise { - try { - const fileInfo = await Deno.lstat(dir); - if (!fileInfo.isDirectory) { - throw new Error( - `Ensure path exists, expected 'dir', got '${ - getFileInfoType(fileInfo) - }'`, - ); - } - } catch (err) { - if (err instanceof Deno.errors.NotFound) { - // if dir not exists. then create it. - await Deno.mkdir(dir, { recursive: true }); - return; - } - throw err; - } -} - -/** - * Ensures that the directory exists. - * If the directory structure does not exist, it is created. Like mkdir -p. - * Requires the `--allow-read` and `--allow-write` flag. - */ -export function ensureDirSync(dir: string): void { - try { - const fileInfo = Deno.lstatSync(dir); - if (!fileInfo.isDirectory) { - throw new Error( - `Ensure path exists, expected 'dir', got '${ - getFileInfoType(fileInfo) - }'`, - ); - } - } catch (err) { - if (err instanceof Deno.errors.NotFound) { - // if dir not exists. then create it. - Deno.mkdirSync(dir, { recursive: true }); - return; - } - throw err; - } -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_ensure_file_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_fs_ensure_file_ts.ts deleted file mode 100644 index 41565795c5f..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_ensure_file_ts.ts +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import * as path from "../path/mod.ts"; -import { ensureDir, ensureDirSync } from "./ensure_dir.ts"; -import { getFileInfoType } from "./_util.ts"; - -/** - * Ensures that the file exists. - * If the file that is requested to be created is in directories that do not - * exist. - * these directories are created. If the file already exists, - * it is NOTMODIFIED. - * Requires the `--allow-read` and `--allow-write` flag. - */ -export async function ensureFile(filePath: string): Promise { - try { - // if file exists - const stat = await Deno.lstat(filePath); - if (!stat.isFile) { - throw new Error( - `Ensure path exists, expected 'file', got '${getFileInfoType(stat)}'`, - ); - } - } catch (err) { - // if file not exists - if (err instanceof Deno.errors.NotFound) { - // ensure dir exists - await ensureDir(path.dirname(filePath)); - // create file - await Deno.writeFile(filePath, new Uint8Array()); - return; - } - - throw err; - } -} - -/** - * Ensures that the file exists. - * If the file that is requested to be created is in directories that do not - * exist, - * these directories are created. If the file already exists, - * it is NOT MODIFIED. - * Requires the `--allow-read` and `--allow-write` flag. - */ -export function ensureFileSync(filePath: string): void { - try { - // if file exists - const stat = Deno.lstatSync(filePath); - if (!stat.isFile) { - throw new Error( - `Ensure path exists, expected 'file', got '${getFileInfoType(stat)}'`, - ); - } - } catch (err) { - // if file not exists - if (err instanceof Deno.errors.NotFound) { - // ensure dir exists - ensureDirSync(path.dirname(filePath)); - // create file - Deno.writeFileSync(filePath, new Uint8Array()); - return; - } - throw err; - } -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_ensure_link_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_fs_ensure_link_ts.ts deleted file mode 100644 index ea8501b0392..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_ensure_link_ts.ts +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import * as path from "../path/mod.ts"; -import { ensureDir, ensureDirSync } from "./ensure_dir.ts"; -import { exists, existsSync } from "./exists.ts"; -import { getFileInfoType } from "./_util.ts"; - -/** - * Ensures that the hard link exists. - * If the directory structure does not exist, it is created. - * - * @param src the source file path. Directory hard links are not allowed. - * @param dest the destination link path - */ -export async function ensureLink(src: string, dest: string): Promise { - if (await exists(dest)) { - const destStatInfo = await Deno.lstat(dest); - const destFilePathType = getFileInfoType(destStatInfo); - if (destFilePathType !== "file") { - throw new Error( - `Ensure path exists, expected 'file', got '${destFilePathType}'`, - ); - } - return; - } - - await ensureDir(path.dirname(dest)); - - await Deno.link(src, dest); -} - -/** - * Ensures that the hard link exists. - * If the directory structure does not exist, it is created. - * - * @param src the source file path. Directory hard links are not allowed. - * @param dest the destination link path - */ -export function ensureLinkSync(src: string, dest: string): void { - if (existsSync(dest)) { - const destStatInfo = Deno.lstatSync(dest); - const destFilePathType = getFileInfoType(destStatInfo); - if (destFilePathType !== "file") { - throw new Error( - `Ensure path exists, expected 'file', got '${destFilePathType}'`, - ); - } - return; - } - - ensureDirSync(path.dirname(dest)); - - Deno.linkSync(src, dest); -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_ensure_symlink_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_fs_ensure_symlink_ts.ts deleted file mode 100644 index 03a8db93040..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_ensure_symlink_ts.ts +++ /dev/null @@ -1,70 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import * as path from "../path/mod.ts"; -import { ensureDir, ensureDirSync } from "./ensure_dir.ts"; -import { exists, existsSync } from "./exists.ts"; -import { getFileInfoType } from "./_util.ts"; - -/** - * Ensures that the link exists. - * If the directory structure does not exist, it is created. - * - * @param src the source file path - * @param dest the destination link path - */ -export async function ensureSymlink(src: string, dest: string): Promise { - const srcStatInfo = await Deno.lstat(src); - const srcFilePathType = getFileInfoType(srcStatInfo); - - if (await exists(dest)) { - const destStatInfo = await Deno.lstat(dest); - const destFilePathType = getFileInfoType(destStatInfo); - if (destFilePathType !== "symlink") { - throw new Error( - `Ensure path exists, expected 'symlink', got '${destFilePathType}'`, - ); - } - return; - } - - await ensureDir(path.dirname(dest)); - - if (Deno.build.os === "windows") { - await Deno.symlink(src, dest, { - type: srcFilePathType === "dir" ? "dir" : "file", - }); - } else { - await Deno.symlink(src, dest); - } -} - -/** - * Ensures that the link exists. - * If the directory structure does not exist, it is created. - * - * @param src the source file path - * @param dest the destination link path - */ -export function ensureSymlinkSync(src: string, dest: string): void { - const srcStatInfo = Deno.lstatSync(src); - const srcFilePathType = getFileInfoType(srcStatInfo); - - if (existsSync(dest)) { - const destStatInfo = Deno.lstatSync(dest); - const destFilePathType = getFileInfoType(destStatInfo); - if (destFilePathType !== "symlink") { - throw new Error( - `Ensure path exists, expected 'symlink', got '${destFilePathType}'`, - ); - } - return; - } - - ensureDirSync(path.dirname(dest)); - if (Deno.build.os === "windows") { - Deno.symlinkSync(src, dest, { - type: srcFilePathType === "dir" ? "dir" : "file", - }); - } else { - Deno.symlinkSync(src, dest); - } -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_eol_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_fs_eol_ts.ts deleted file mode 100644 index 2f15be269e0..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_eol_ts.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. - -/** EndOfLine character enum */ -export enum EOL { - LF = "\n", - CRLF = "\r\n", -} - -const regDetect = /(?:\r?\n)/g; - -/** - * Detect the EOL character for string input. - * returns null if no newline - */ -export function detect(content: string): EOL | null { - const d = content.match(regDetect); - if (!d || d.length === 0) { - return null; - } - const crlf = d.filter((x: string): boolean => x === EOL.CRLF); - if (crlf.length > 0) { - return EOL.CRLF; - } else { - return EOL.LF; - } -} - -/** Format the file to the targeted EOL */ -export function format(content: string, eol: EOL): string { - return content.replace(regDetect, eol); -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_exists_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_fs_exists_ts.ts deleted file mode 100644 index a79455b2d82..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_exists_ts.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -/** - * Test whether or not the given path exists by checking with the file system - */ -export async function exists(filePath: string): Promise { - try { - await Deno.lstat(filePath); - return true; - } catch (err) { - if (err instanceof Deno.errors.NotFound) { - return false; - } - - throw err; - } -} - -/** - * Test whether or not the given path exists by checking with the file system - */ -export function existsSync(filePath: string): boolean { - try { - Deno.lstatSync(filePath); - return true; - } catch (err) { - if (err instanceof Deno.errors.NotFound) { - return false; - } - throw err; - } -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_expand_glob_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_fs_expand_glob_ts.ts deleted file mode 100644 index 6d1f883b560..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_expand_glob_ts.ts +++ /dev/null @@ -1,275 +0,0 @@ -import { - GlobOptions, - SEP_PATTERN, - globToRegExp, - isAbsolute, - isGlob, - joinGlobs, - normalize, -} from "../path/mod.ts"; -import { - WalkEntry, - createWalkEntry, - createWalkEntrySync, - walk, - walkSync, -} from "./walk.ts"; -import { assert } from "../_util/assert.ts"; - -const isWindows = Deno.build.os == "windows"; - -export interface ExpandGlobOptions extends GlobOptions { - root?: string; - exclude?: string[]; - includeDirs?: boolean; -} - -interface SplitPath { - segments: string[]; - isAbsolute: boolean; - hasTrailingSep: boolean; - // Defined for any absolute Windows path. - winRoot?: string; -} - -// TODO: Maybe make this public somewhere. -function split(path: string): SplitPath { - const s = SEP_PATTERN.source; - const segments = path - .replace(new RegExp(`^${s}|${s}$`, "g"), "") - .split(SEP_PATTERN); - const isAbsolute_ = isAbsolute(path); - return { - segments, - isAbsolute: isAbsolute_, - hasTrailingSep: !!path.match(new RegExp(`${s}$`)), - winRoot: isWindows && isAbsolute_ ? segments.shift() : undefined, - }; -} - -function throwUnlessNotFound(error: Error): void { - if (!(error instanceof Deno.errors.NotFound)) { - throw error; - } -} - -function comparePath(a: WalkEntry, b: WalkEntry): number { - if (a.path < b.path) return -1; - if (a.path > b.path) return 1; - return 0; -} - -/** - * Expand the glob string from the specified `root` directory and yield each - * result as a `WalkEntry` object. - * - * Examples: - * - * for await (const file of expandGlob("**\/*.ts")) { - * console.log(file); - * } - */ -export async function* expandGlob( - glob: string, - { - root = Deno.cwd(), - exclude = [], - includeDirs = true, - extended = false, - globstar = false, - }: ExpandGlobOptions = {}, -): AsyncIterableIterator { - const globOptions: GlobOptions = { extended, globstar }; - const absRoot = isAbsolute(root) - ? normalize(root) - : joinGlobs([Deno.cwd(), root], globOptions); - const resolveFromRoot = (path: string): string => - isAbsolute(path) - ? normalize(path) - : joinGlobs([absRoot, path], globOptions); - const excludePatterns = exclude - .map(resolveFromRoot) - .map((s: string): RegExp => globToRegExp(s, globOptions)); - const shouldInclude = (path: string): boolean => - !excludePatterns.some((p: RegExp): boolean => !!path.match(p)); - const { segments, hasTrailingSep, winRoot } = split(resolveFromRoot(glob)); - - let fixedRoot = winRoot != undefined ? winRoot : "/"; - while (segments.length > 0 && !isGlob(segments[0])) { - const seg = segments.shift(); - assert(seg != null); - fixedRoot = joinGlobs([fixedRoot, seg], globOptions); - } - - let fixedRootInfo: WalkEntry; - try { - fixedRootInfo = await createWalkEntry(fixedRoot); - } catch (error) { - return throwUnlessNotFound(error); - } - - async function* advanceMatch( - walkInfo: WalkEntry, - globSegment: string, - ): AsyncIterableIterator { - if (!walkInfo.isDirectory) { - return; - } else if (globSegment == "..") { - const parentPath = joinGlobs([walkInfo.path, ".."], globOptions); - try { - if (shouldInclude(parentPath)) { - return yield await createWalkEntry(parentPath); - } - } catch (error) { - throwUnlessNotFound(error); - } - return; - } else if (globSegment == "**") { - return yield* walk(walkInfo.path, { - includeFiles: false, - skip: excludePatterns, - }); - } - yield* walk(walkInfo.path, { - maxDepth: 1, - match: [ - globToRegExp( - joinGlobs([walkInfo.path, globSegment], globOptions), - globOptions, - ), - ], - skip: excludePatterns, - }); - } - - let currentMatches: WalkEntry[] = [fixedRootInfo]; - for (const segment of segments) { - // Advancing the list of current matches may introduce duplicates, so we - // pass everything through this Map. - const nextMatchMap: Map = new Map(); - for (const currentMatch of currentMatches) { - for await (const nextMatch of advanceMatch(currentMatch, segment)) { - nextMatchMap.set(nextMatch.path, nextMatch); - } - } - currentMatches = [...nextMatchMap.values()].sort(comparePath); - } - if (hasTrailingSep) { - currentMatches = currentMatches.filter( - (entry: WalkEntry): boolean => entry.isDirectory, - ); - } - if (!includeDirs) { - currentMatches = currentMatches.filter( - (entry: WalkEntry): boolean => !entry.isDirectory, - ); - } - yield* currentMatches; -} - -/** - * Synchronous version of `expandGlob()`. - * - * Examples: - * - * for (const file of expandGlobSync("**\/*.ts")) { - * console.log(file); - * } - */ -export function* expandGlobSync( - glob: string, - { - root = Deno.cwd(), - exclude = [], - includeDirs = true, - extended = false, - globstar = false, - }: ExpandGlobOptions = {}, -): IterableIterator { - const globOptions: GlobOptions = { extended, globstar }; - const absRoot = isAbsolute(root) - ? normalize(root) - : joinGlobs([Deno.cwd(), root], globOptions); - const resolveFromRoot = (path: string): string => - isAbsolute(path) - ? normalize(path) - : joinGlobs([absRoot, path], globOptions); - const excludePatterns = exclude - .map(resolveFromRoot) - .map((s: string): RegExp => globToRegExp(s, globOptions)); - const shouldInclude = (path: string): boolean => - !excludePatterns.some((p: RegExp): boolean => !!path.match(p)); - const { segments, hasTrailingSep, winRoot } = split(resolveFromRoot(glob)); - - let fixedRoot = winRoot != undefined ? winRoot : "/"; - while (segments.length > 0 && !isGlob(segments[0])) { - const seg = segments.shift(); - assert(seg != null); - fixedRoot = joinGlobs([fixedRoot, seg], globOptions); - } - - let fixedRootInfo: WalkEntry; - try { - fixedRootInfo = createWalkEntrySync(fixedRoot); - } catch (error) { - return throwUnlessNotFound(error); - } - - function* advanceMatch( - walkInfo: WalkEntry, - globSegment: string, - ): IterableIterator { - if (!walkInfo.isDirectory) { - return; - } else if (globSegment == "..") { - const parentPath = joinGlobs([walkInfo.path, ".."], globOptions); - try { - if (shouldInclude(parentPath)) { - return yield createWalkEntrySync(parentPath); - } - } catch (error) { - throwUnlessNotFound(error); - } - return; - } else if (globSegment == "**") { - return yield* walkSync(walkInfo.path, { - includeFiles: false, - skip: excludePatterns, - }); - } - yield* walkSync(walkInfo.path, { - maxDepth: 1, - match: [ - globToRegExp( - joinGlobs([walkInfo.path, globSegment], globOptions), - globOptions, - ), - ], - skip: excludePatterns, - }); - } - - let currentMatches: WalkEntry[] = [fixedRootInfo]; - for (const segment of segments) { - // Advancing the list of current matches may introduce duplicates, so we - // pass everything through this Map. - const nextMatchMap: Map = new Map(); - for (const currentMatch of currentMatches) { - for (const nextMatch of advanceMatch(currentMatch, segment)) { - nextMatchMap.set(nextMatch.path, nextMatch); - } - } - currentMatches = [...nextMatchMap.values()].sort(comparePath); - } - if (hasTrailingSep) { - currentMatches = currentMatches.filter( - (entry: WalkEntry): boolean => entry.isDirectory, - ); - } - if (!includeDirs) { - currentMatches = currentMatches.filter( - (entry: WalkEntry): boolean => !entry.isDirectory, - ); - } - yield* currentMatches; -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_mod_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_fs_mod_ts.ts deleted file mode 100644 index e49d24bac46..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_mod_ts.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -export * from "./empty_dir.ts"; -export * from "./ensure_dir.ts"; -export * from "./ensure_file.ts"; -export * from "./ensure_link.ts"; -export * from "./ensure_symlink.ts"; -export * from "./exists.ts"; -export * from "./expand_glob.ts"; -export * from "./move.ts"; -export * from "./copy.ts"; -export * from "./read_json.ts"; -export * from "./write_json.ts"; -export * from "./walk.ts"; -export * from "./eol.ts"; diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_move_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_fs_move_ts.ts deleted file mode 100644 index 421ca0771d5..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_move_ts.ts +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { exists, existsSync } from "./exists.ts"; -import { isSubdir } from "./_util.ts"; - -interface MoveOptions { - overwrite?: boolean; -} - -/** Moves a file or directory */ -export async function move( - src: string, - dest: string, - { overwrite = false }: MoveOptions = {}, -): Promise { - const srcStat = await Deno.stat(src); - - if (srcStat.isDirectory && isSubdir(src, dest)) { - throw new Error( - `Cannot move '${src}' to a subdirectory of itself, '${dest}'.`, - ); - } - - if (overwrite) { - if (await exists(dest)) { - await Deno.remove(dest, { recursive: true }); - } - await Deno.rename(src, dest); - } else { - if (await exists(dest)) { - throw new Error("dest already exists."); - } - await Deno.rename(src, dest); - } - - return; -} - -/** Moves a file or directory synchronously */ -export function moveSync( - src: string, - dest: string, - { overwrite = false }: MoveOptions = {}, -): void { - const srcStat = Deno.statSync(src); - - if (srcStat.isDirectory && isSubdir(src, dest)) { - throw new Error( - `Cannot move '${src}' to a subdirectory of itself, '${dest}'.`, - ); - } - - if (overwrite) { - if (existsSync(dest)) { - Deno.removeSync(dest, { recursive: true }); - } - Deno.renameSync(src, dest); - } else { - if (existsSync(dest)) { - throw new Error("dest already exists."); - } - Deno.renameSync(src, dest); - } -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_read_json_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_fs_read_json_ts.ts deleted file mode 100644 index aa7a0a47720..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_read_json_ts.ts +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. - -/** Reads a JSON file and then parses it into an object */ -export async function readJson(filePath: string): Promise { - const decoder = new TextDecoder("utf-8"); - - const content = decoder.decode(await Deno.readFile(filePath)); - - try { - return JSON.parse(content); - } catch (err) { - err.message = `${filePath}: ${err.message}`; - throw err; - } -} - -/** Reads a JSON file and then parses it into an object */ -export function readJsonSync(filePath: string): unknown { - const decoder = new TextDecoder("utf-8"); - - const content = decoder.decode(Deno.readFileSync(filePath)); - - try { - return JSON.parse(content); - } catch (err) { - err.message = `${filePath}: ${err.message}`; - throw err; - } -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_walk_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_fs_walk_ts.ts deleted file mode 100644 index 8f21968331b..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_walk_ts.ts +++ /dev/null @@ -1,186 +0,0 @@ -// Documentation and interface for walk were adapted from Go -// https://golang.org/pkg/path/filepath/#Walk -// Copyright 2009 The Go Authors. All rights reserved. BSD license. -import { assert } from "../_util/assert.ts"; -import { basename, join, normalize } from "../path/mod.ts"; - -export function createWalkEntrySync(path: string): WalkEntry { - path = normalize(path); - const name = basename(path); - const info = Deno.statSync(path); - return { - path, - name, - isFile: info.isFile, - isDirectory: info.isDirectory, - isSymlink: info.isSymlink, - }; -} - -export async function createWalkEntry(path: string): Promise { - path = normalize(path); - const name = basename(path); - const info = await Deno.stat(path); - return { - path, - name, - isFile: info.isFile, - isDirectory: info.isDirectory, - isSymlink: info.isSymlink, - }; -} - -export interface WalkOptions { - maxDepth?: number; - includeFiles?: boolean; - includeDirs?: boolean; - followSymlinks?: boolean; - exts?: string[]; - match?: RegExp[]; - skip?: RegExp[]; -} - -function include( - path: string, - exts?: string[], - match?: RegExp[], - skip?: RegExp[], -): boolean { - if (exts && !exts.some((ext): boolean => path.endsWith(ext))) { - return false; - } - if (match && !match.some((pattern): boolean => !!path.match(pattern))) { - return false; - } - if (skip && skip.some((pattern): boolean => !!path.match(pattern))) { - return false; - } - return true; -} - -export interface WalkEntry extends Deno.DirEntry { - path: string; -} - -/** Walks the file tree rooted at root, yielding each file or directory in the - * tree filtered according to the given options. The files are walked in lexical - * order, which makes the output deterministic but means that for very large - * directories walk() can be inefficient. - * - * Options: - * - maxDepth?: number = Infinity; - * - includeFiles?: boolean = true; - * - includeDirs?: boolean = true; - * - followSymlinks?: boolean = false; - * - exts?: string[]; - * - match?: RegExp[]; - * - skip?: RegExp[]; - * - * for await (const entry of walk(".")) { - * console.log(entry.path); - * assert(entry.isFile); - * }; - */ -export async function* walk( - root: string, - { - maxDepth = Infinity, - includeFiles = true, - includeDirs = true, - followSymlinks = false, - exts = undefined, - match = undefined, - skip = undefined, - }: WalkOptions = {}, -): AsyncIterableIterator { - if (maxDepth < 0) { - return; - } - if (includeDirs && include(root, exts, match, skip)) { - yield await createWalkEntry(root); - } - if (maxDepth < 1 || !include(root, undefined, undefined, skip)) { - return; - } - for await (const entry of Deno.readDir(root)) { - if (entry.isSymlink) { - if (followSymlinks) { - // TODO(ry) Re-enable followSymlinks. - throw new Error("unimplemented"); - } else { - continue; - } - } - - assert(entry.name != null); - const path = join(root, entry.name); - - if (entry.isFile) { - if (includeFiles && include(path, exts, match, skip)) { - yield { path, ...entry }; - } - } else { - yield* walk(path, { - maxDepth: maxDepth - 1, - includeFiles, - includeDirs, - followSymlinks, - exts, - match, - skip, - }); - } - } -} - -/** Same as walk() but uses synchronous ops */ -export function* walkSync( - root: string, - { - maxDepth = Infinity, - includeFiles = true, - includeDirs = true, - followSymlinks = false, - exts = undefined, - match = undefined, - skip = undefined, - }: WalkOptions = {}, -): IterableIterator { - if (maxDepth < 0) { - return; - } - if (includeDirs && include(root, exts, match, skip)) { - yield createWalkEntrySync(root); - } - if (maxDepth < 1 || !include(root, undefined, undefined, skip)) { - return; - } - for (const entry of Deno.readDirSync(root)) { - if (entry.isSymlink) { - if (followSymlinks) { - throw new Error("unimplemented"); - } else { - continue; - } - } - - assert(entry.name != null); - const path = join(root, entry.name); - - if (entry.isFile) { - if (includeFiles && include(path, exts, match, skip)) { - yield { path, ...entry }; - } - } else { - yield* walkSync(path, { - maxDepth: maxDepth - 1, - includeFiles, - includeDirs, - followSymlinks, - exts, - match, - skip, - }); - } - } -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_write_json_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_fs_write_json_ts.ts deleted file mode 100644 index 46c33572a7f..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_fs_write_json_ts.ts +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -// eslint-disable-next-line @typescript-eslint/no-explicit-any -type Replacer = (key: string, value: any) => any; - -export interface WriteJsonOptions extends Deno.WriteFileOptions { - replacer?: Array | Replacer; - spaces?: number | string; -} - -function serialize( - filePath: string, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - object: any, - options: WriteJsonOptions, -): string { - try { - const jsonString = JSON.stringify( - object, - options.replacer as string[], - options.spaces, - ); - return `${jsonString}\n`; - } catch (err) { - err.message = `${filePath}: ${err.message}`; - throw err; - } -} - -/* Writes an object to a JSON file. */ -export async function writeJson( - filePath: string, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - object: any, - options: WriteJsonOptions = {}, -): Promise { - const jsonString = serialize(filePath, object, options); - await Deno.writeTextFile(filePath, jsonString, { - append: options.append, - create: options.create, - mode: options.mode, - }); -} - -/* Writes an object to a JSON file. */ -export function writeJsonSync( - filePath: string, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - object: any, - options: WriteJsonOptions = {}, -): void { - const jsonString = serialize(filePath, object, options); - Deno.writeTextFileSync(filePath, jsonString, { - append: options.append, - create: options.create, - mode: options.mode, - }); -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_access_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_access_ts.ts deleted file mode 100644 index df84eac9c43..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_access_ts.ts +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. - -import type { CallbackWithError } from "./_fs_common.ts"; -import { notImplemented } from "../_utils.ts"; - -/** Revist once https://github.com/denoland/deno/issues/4017 lands */ - -//TODO - 'path' can also be a Buffer. Neither of these polyfills -//is available yet. See https://github.com/denoland/deno/issues/3403 -export function access( - path: string | URL, // eslint-disable-line @typescript-eslint/no-unused-vars - modeOrCallback: number | Function, // eslint-disable-line @typescript-eslint/no-unused-vars - callback?: CallbackWithError, // eslint-disable-line @typescript-eslint/no-unused-vars -): void { - notImplemented("Not yet available"); -} - -//TODO - 'path' can also be a Buffer. Neither of these polyfills -//is available yet. See https://github.com/denoland/deno/issues/3403 -// eslint-disable-next-line @typescript-eslint/no-unused-vars -export function accessSync(path: string | URL, mode?: number): void { - notImplemented("Not yet available"); -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_appendFile_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_appendFile_ts.ts deleted file mode 100644 index bc30de6098e..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_appendFile_ts.ts +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { - Encodings, - WriteFileOptions, - isFileOptions, - CallbackWithError, - getOpenOptions, -} from "./_fs_common.ts"; -import { notImplemented } from "../_utils.ts"; -import { fromFileUrl } from "../path.ts"; - -/** - * TODO: Also accept 'data' parameter as a Node polyfill Buffer type once these - * are implemented. See https://github.com/denoland/deno/issues/3403 - */ -export function appendFile( - pathOrRid: string | number | URL, - data: string, - optionsOrCallback: Encodings | WriteFileOptions | CallbackWithError, - callback?: CallbackWithError, -): void { - pathOrRid = pathOrRid instanceof URL ? fromFileUrl(pathOrRid) : pathOrRid; - const callbackFn: CallbackWithError | undefined = - optionsOrCallback instanceof Function ? optionsOrCallback : callback; - const options: Encodings | WriteFileOptions | undefined = - optionsOrCallback instanceof Function ? undefined : optionsOrCallback; - if (!callbackFn) { - throw new Error("No callback function supplied"); - } - - validateEncoding(options); - let rid = -1; - const buffer: Uint8Array = new TextEncoder().encode(data); - new Promise((resolve, reject) => { - if (typeof pathOrRid === "number") { - rid = pathOrRid; - Deno.write(rid, buffer).then(resolve).catch(reject); - } else { - const mode: number | undefined = isFileOptions(options) - ? options.mode - : undefined; - const flag: string | undefined = isFileOptions(options) - ? options.flag - : undefined; - - if (mode) { - //TODO rework once https://github.com/denoland/deno/issues/4017 completes - notImplemented("Deno does not yet support setting mode on create"); - } - Deno.open(pathOrRid as string, getOpenOptions(flag)) - .then(({ rid: openedFileRid }) => { - rid = openedFileRid; - return Deno.write(openedFileRid, buffer); - }) - .then(resolve) - .catch(reject); - } - }) - .then(() => { - closeRidIfNecessary(typeof pathOrRid === "string", rid); - callbackFn(); - }) - .catch((err) => { - closeRidIfNecessary(typeof pathOrRid === "string", rid); - callbackFn(err); - }); -} - -function closeRidIfNecessary(isPathString: boolean, rid: number): void { - if (isPathString && rid != -1) { - //Only close if a path was supplied and a rid allocated - Deno.close(rid); - } -} - -/** - * TODO: Also accept 'data' parameter as a Node polyfill Buffer type once these - * are implemented. See https://github.com/denoland/deno/issues/3403 - */ -export function appendFileSync( - pathOrRid: string | number | URL, - data: string, - options?: Encodings | WriteFileOptions, -): void { - let rid = -1; - - validateEncoding(options); - pathOrRid = pathOrRid instanceof URL ? fromFileUrl(pathOrRid) : pathOrRid; - - try { - if (typeof pathOrRid === "number") { - rid = pathOrRid; - } else { - const mode: number | undefined = isFileOptions(options) - ? options.mode - : undefined; - const flag: string | undefined = isFileOptions(options) - ? options.flag - : undefined; - - if (mode) { - // TODO rework once https://github.com/denoland/deno/issues/4017 completes - notImplemented("Deno does not yet support setting mode on create"); - } - - const file = Deno.openSync(pathOrRid, getOpenOptions(flag)); - rid = file.rid; - } - - const buffer: Uint8Array = new TextEncoder().encode(data); - - Deno.writeSync(rid, buffer); - } finally { - closeRidIfNecessary(typeof pathOrRid === "string", rid); - } -} - -function validateEncoding( - encodingOption: Encodings | WriteFileOptions | undefined, -): void { - if (!encodingOption) return; - - if (typeof encodingOption === "string") { - if (encodingOption !== "utf8") { - throw new Error("Only 'utf8' encoding is currently supported"); - } - } else if (encodingOption.encoding && encodingOption.encoding !== "utf8") { - throw new Error("Only 'utf8' encoding is currently supported"); - } -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_chmod_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_chmod_ts.ts deleted file mode 100644 index 9a8277b4539..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_chmod_ts.ts +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. - -import type { CallbackWithError } from "./_fs_common.ts"; -import { fromFileUrl } from "../path.ts"; - -const allowedModes = /^[0-7]{3}/; - -/** - * TODO: Also accept 'path' parameter as a Node polyfill Buffer type once these - * are implemented. See https://github.com/denoland/deno/issues/3403 - */ -export function chmod( - path: string | URL, - mode: string | number, - callback: CallbackWithError, -): void { - path = path instanceof URL ? fromFileUrl(path) : path; - - Deno.chmod(path, getResolvedMode(mode)) - .then(() => callback()) - .catch(callback); -} - -/** - * TODO: Also accept 'path' parameter as a Node polyfill Buffer type once these - * are implemented. See https://github.com/denoland/deno/issues/3403 - */ -export function chmodSync(path: string | URL, mode: string | number): void { - path = path instanceof URL ? fromFileUrl(path) : path; - Deno.chmodSync(path, getResolvedMode(mode)); -} - -function getResolvedMode(mode: string | number): number { - if (typeof mode === "number") { - return mode; - } - - if (typeof mode === "string" && !allowedModes.test(mode)) { - throw new Error("Unrecognized mode: " + mode); - } - - return parseInt(mode, 8); -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_chown_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_chown_ts.ts deleted file mode 100644 index ae3af01218f..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_chown_ts.ts +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. - -import type { CallbackWithError } from "./_fs_common.ts"; -import { fromFileUrl } from "../path.ts"; - -/** - * TODO: Also accept 'path' parameter as a Node polyfill Buffer type once these - * are implemented. See https://github.com/denoland/deno/issues/3403 - */ -export function chown( - path: string | URL, - uid: number, - gid: number, - callback: CallbackWithError, -): void { - path = path instanceof URL ? fromFileUrl(path) : path; - - Deno.chown(path, uid, gid) - .then(() => callback()) - .catch(callback); -} - -/** - * TODO: Also accept 'path' parameter as a Node polyfill Buffer type once these - * are implemented. See https://github.com/denoland/deno/issues/3403 - */ -export function chownSync(path: string | URL, uid: number, gid: number): void { - path = path instanceof URL ? fromFileUrl(path) : path; - - Deno.chownSync(path, uid, gid); -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_close_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_close_ts.ts deleted file mode 100644 index add6f6663ea..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_close_ts.ts +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. - -import type { CallbackWithError } from "./_fs_common.ts"; - -export function close(fd: number, callback: CallbackWithError): void { - queueMicrotask(() => { - try { - Deno.close(fd); - callback(null); - } catch (err) { - callback(err); - } - }); -} - -export function closeSync(fd: number): void { - Deno.close(fd); -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_common_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_common_ts.ts deleted file mode 100644 index 165b9aeca82..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_common_ts.ts +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. - -import { notImplemented } from "../_utils.ts"; - -export type CallbackWithError = (err?: Error | null) => void; - -export type TextEncodings = - | "ascii" - | "utf8" - | "utf-8" - | "utf16le" - | "ucs2" - | "ucs-2" - | "base64" - | "latin1" - | "hex"; -export type BinaryEncodings = "binary"; -export type Encodings = TextEncodings | BinaryEncodings; - -export interface FileOptions { - encoding?: Encodings; - flag?: string; -} - -export type TextOptionsArgument = - | TextEncodings - | ({ encoding: TextEncodings } & FileOptions); -export type BinaryOptionsArgument = - | BinaryEncodings - | ({ encoding: BinaryEncodings } & FileOptions); -export type FileOptionsArgument = Encodings | FileOptions; - -export interface WriteFileOptions extends FileOptions { - mode?: number; -} - -export function isFileOptions( - fileOptions: string | WriteFileOptions | undefined, -): fileOptions is FileOptions { - if (!fileOptions) return false; - - return ( - (fileOptions as FileOptions).encoding != undefined || - (fileOptions as FileOptions).flag != undefined || - (fileOptions as WriteFileOptions).mode != undefined - ); -} - -export function getEncoding( - optOrCallback?: FileOptions | WriteFileOptions | Function | Encodings | null, -): Encodings | null { - if (!optOrCallback || typeof optOrCallback === "function") { - return null; - } - - const encoding = typeof optOrCallback === "string" - ? optOrCallback - : optOrCallback.encoding; - if (!encoding) return null; - return encoding; -} - -export function checkEncoding(encoding: Encodings | null): Encodings | null { - if (!encoding) return null; - - encoding = encoding.toLowerCase() as Encodings; - if (["utf8", "hex", "base64"].includes(encoding)) return encoding; - - if (encoding === "utf-8") { - return "utf8"; - } - if (encoding === "binary") { - return "binary"; - // before this was buffer, however buffer is not used in Node - // node -e "require('fs').readFile('../world.txt', 'buffer', console.log)" - } - - const notImplementedEncodings = ["utf16le", "latin1", "ascii", "ucs2"]; - - if (notImplementedEncodings.includes(encoding as string)) { - notImplemented(`"${encoding}" encoding`); - } - - throw new Error(`The value "${encoding}" is invalid for option "encoding"`); -} - -export function getOpenOptions(flag: string | undefined): Deno.OpenOptions { - if (!flag) { - return { create: true, append: true }; - } - - let openOptions: Deno.OpenOptions; - switch (flag) { - case "a": { - // 'a': Open file for appending. The file is created if it does not exist. - openOptions = { create: true, append: true }; - break; - } - case "ax": { - // 'ax': Like 'a' but fails if the path exists. - openOptions = { createNew: true, write: true, append: true }; - break; - } - case "a+": { - // 'a+': Open file for reading and appending. The file is created if it does not exist. - openOptions = { read: true, create: true, append: true }; - break; - } - case "ax+": { - // 'ax+': Like 'a+' but fails if the path exists. - openOptions = { read: true, createNew: true, append: true }; - break; - } - case "r": { - // 'r': Open file for reading. An exception occurs if the file does not exist. - openOptions = { read: true }; - break; - } - case "r+": { - // 'r+': Open file for reading and writing. An exception occurs if the file does not exist. - openOptions = { read: true, write: true }; - break; - } - case "w": { - // 'w': Open file for writing. The file is created (if it does not exist) or truncated (if it exists). - openOptions = { create: true, write: true, truncate: true }; - break; - } - case "wx": { - // 'wx': Like 'w' but fails if the path exists. - openOptions = { createNew: true, write: true }; - break; - } - case "w+": { - // 'w+': Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists). - openOptions = { create: true, write: true, truncate: true, read: true }; - break; - } - case "wx+": { - // 'wx+': Like 'w+' but fails if the path exists. - openOptions = { createNew: true, write: true, read: true }; - break; - } - case "as": { - // 'as': Open file for appending in synchronous mode. The file is created if it does not exist. - openOptions = { create: true, append: true }; - } - case "as+": { - // 'as+': Open file for reading and appending in synchronous mode. The file is created if it does not exist. - openOptions = { create: true, read: true, append: true }; - } - case "rs+": { - // 'rs+': Open file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache. - openOptions = { create: true, read: true, write: true }; - } - default: { - throw new Error(`Unrecognized file system flag: ${flag}`); - } - } - - return openOptions; -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_constants_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_constants_ts.ts deleted file mode 100644 index 765e4af7904..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_constants_ts.ts +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. - -//File access constants -export const F_OK = 0; -export const R_OK = 4; -export const W_OK = 2; -export const X_OK = 1; - -//File mode constants -export const S_IRUSR = 0o400; //read by owner -export const S_IWUSR = 0o200; //write by owner -export const S_IXUSR = 0o100; //execute/search by owner -export const S_IRGRP = 0o40; //read by group -export const S_IWGRP = 0o20; //write by group -export const S_IXGRP = 0o10; //execute/search by group -export const S_IROTH = 0o4; //read by others -export const S_IWOTH = 0o2; //write by others -export const S_IXOTH = 0o1; //execute/search by others diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_copy_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_copy_ts.ts deleted file mode 100644 index ba530a85c93..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_copy_ts.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. - -import type { CallbackWithError } from "./_fs_common.ts"; -import { fromFileUrl } from "../path.ts"; - -export function copyFile( - source: string | URL, - destination: string, - callback: CallbackWithError, -): void { - source = source instanceof URL ? fromFileUrl(source) : source; - - Deno.copyFile(source, destination) - .then(() => callback()) - .catch(callback); -} - -export function copyFileSync(source: string | URL, destination: string): void { - source = source instanceof URL ? fromFileUrl(source) : source; - Deno.copyFileSync(source, destination); -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_exists_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_exists_ts.ts deleted file mode 100644 index e6e6e4f2e61..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_exists_ts.ts +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { fromFileUrl } from "../path.ts"; - -type ExitsCallback = (exists: boolean) => void; - -/** - * TODO: Also accept 'path' parameter as a Node polyfill Buffer type once these - * are implemented. See https://github.com/denoland/deno/issues/3403 - * Deprecated in node api - */ -export function exists(path: string | URL, callback: ExitsCallback): void { - path = path instanceof URL ? fromFileUrl(path) : path; - Deno.lstat(path) - .then(() => { - callback(true); - }) - .catch(() => callback(false)); -} - -/** - * TODO: Also accept 'path' parameter as a Node polyfill Buffer or URL type once these - * are implemented. See https://github.com/denoland/deno/issues/3403 - */ -export function existsSync(path: string | URL): boolean { - path = path instanceof URL ? fromFileUrl(path) : path; - try { - Deno.lstatSync(path); - return true; - } catch (err) { - if (err instanceof Deno.errors.NotFound) { - return false; - } - throw err; - } -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_mkdir_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_mkdir_ts.ts deleted file mode 100644 index 63aabd010d9..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_mkdir_ts.ts +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import type { CallbackWithError } from "./_fs_common.ts"; -import { fromFileUrl } from "../path.ts"; - -/** - * TODO: Also accept 'path' parameter as a Node polyfill Buffer type once these - * are implemented. See https://github.com/denoland/deno/issues/3403 - */ -type MkdirOptions = - | { recursive?: boolean; mode?: number | undefined } - | number - | boolean; - -export function mkdir( - path: string | URL, - options?: MkdirOptions | CallbackWithError, - callback?: CallbackWithError, -): void { - path = path instanceof URL ? fromFileUrl(path) : path; - - let mode = 0o777; - let recursive = false; - - if (typeof options == "function") { - callback = options; - } else if (typeof options === "number") { - mode = options; - } else if (typeof options === "boolean") { - recursive = options; - } else if (options) { - if (options.recursive !== undefined) recursive = options.recursive; - if (options.mode !== undefined) mode = options.mode; - } - if (typeof recursive !== "boolean") { - throw new Deno.errors.InvalidData( - "invalid recursive option , must be a boolean", - ); - } - Deno.mkdir(path, { recursive, mode }) - .then(() => { - if (typeof callback === "function") { - callback(); - } - }) - .catch((err) => { - if (typeof callback === "function") { - callback(err); - } - }); -} - -export function mkdirSync(path: string | URL, options?: MkdirOptions): void { - path = path instanceof URL ? fromFileUrl(path) : path; - let mode = 0o777; - let recursive = false; - - if (typeof options === "number") { - mode = options; - } else if (typeof options === "boolean") { - recursive = options; - } else if (options) { - if (options.recursive !== undefined) recursive = options.recursive; - if (options.mode !== undefined) mode = options.mode; - } - if (typeof recursive !== "boolean") { - throw new Deno.errors.InvalidData( - "invalid recursive option , must be a boolean", - ); - } - - Deno.mkdirSync(path, { recursive, mode }); -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_readFile_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_readFile_ts.ts deleted file mode 100644 index 2aef2829064..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_readFile_ts.ts +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { - Encodings, - getEncoding, - FileOptionsArgument, - TextOptionsArgument, - BinaryOptionsArgument, - TextEncodings, - BinaryEncodings, -} from "./_fs_common.ts"; -import { Buffer } from "../buffer.ts"; -import { fromFileUrl } from "../path.ts"; - -function maybeDecode(data: Uint8Array, encoding: TextEncodings): string; -function maybeDecode( - data: Uint8Array, - encoding: BinaryEncodings | null, -): Buffer; -function maybeDecode( - data: Uint8Array, - encoding: Encodings | null, -): string | Buffer { - const buffer = new Buffer(data.buffer, data.byteOffset, data.byteLength); - if (encoding && encoding !== "binary") return buffer.toString(encoding); - return buffer; -} - -type TextCallback = (err: Error | null, data?: string) => void; -type BinaryCallback = (err: Error | null, data?: Buffer) => void; -type GenericCallback = (err: Error | null, data?: string | Buffer) => void; -type Callback = TextCallback | BinaryCallback | GenericCallback; - -export function readFile( - path: string | URL, - options: TextOptionsArgument, - callback: TextCallback, -): void; -export function readFile( - path: string | URL, - options: BinaryOptionsArgument, - callback: BinaryCallback, -): void; -export function readFile( - path: string | URL, - options: null | undefined | FileOptionsArgument, - callback: BinaryCallback, -): void; -export function readFile(path: string | URL, callback: BinaryCallback): void; -export function readFile( - path: string | URL, - optOrCallback?: FileOptionsArgument | Callback | null | undefined, - callback?: Callback, -): void { - path = path instanceof URL ? fromFileUrl(path) : path; - let cb: Callback | undefined; - if (typeof optOrCallback === "function") { - cb = optOrCallback; - } else { - cb = callback; - } - - const encoding = getEncoding(optOrCallback); - - const p = Deno.readFile(path); - - if (cb) { - p.then((data: Uint8Array) => { - if (encoding && encoding !== "binary") { - const text = maybeDecode(data, encoding); - return (cb as TextCallback)(null, text); - } - const buffer = maybeDecode(data, encoding); - (cb as BinaryCallback)(null, buffer); - }).catch((err) => cb && cb(err)); - } -} - -export function readFileSync( - path: string | URL, - opt: TextOptionsArgument, -): string; -export function readFileSync( - path: string | URL, - opt?: BinaryOptionsArgument, -): Buffer; -export function readFileSync( - path: string | URL, - opt?: FileOptionsArgument, -): string | Buffer { - path = path instanceof URL ? fromFileUrl(path) : path; - const data = Deno.readFileSync(path); - const encoding = getEncoding(opt); - if (encoding && encoding !== "binary") { - const text = maybeDecode(data, encoding); - return text; - } - const buffer = maybeDecode(data, encoding); - return buffer; -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_readlink_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_readlink_ts.ts deleted file mode 100644 index 866ea187b32..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_readlink_ts.ts +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { - intoCallbackAPIWithIntercept, - MaybeEmpty, - notImplemented, -} from "../_utils.ts"; -import { fromFileUrl } from "../path.ts"; - -type ReadlinkCallback = ( - err: MaybeEmpty, - linkString: MaybeEmpty, -) => void; - -interface ReadlinkOptions { - encoding?: string | null; -} - -function maybeEncode( - data: string, - encoding: string | null, -): string | Uint8Array { - if (encoding === "buffer") { - return new TextEncoder().encode(data); - } - return data; -} - -function getEncoding( - optOrCallback?: ReadlinkOptions | ReadlinkCallback, -): string | null { - if (!optOrCallback || typeof optOrCallback === "function") { - return null; - } else { - if (optOrCallback.encoding) { - if ( - optOrCallback.encoding === "utf8" || - optOrCallback.encoding === "utf-8" - ) { - return "utf8"; - } else if (optOrCallback.encoding === "buffer") { - return "buffer"; - } else { - notImplemented(); - } - } - return null; - } -} - -export function readlink( - path: string | URL, - optOrCallback: ReadlinkCallback | ReadlinkOptions, - callback?: ReadlinkCallback, -): void { - path = path instanceof URL ? fromFileUrl(path) : path; - - let cb: ReadlinkCallback | undefined; - if (typeof optOrCallback === "function") { - cb = optOrCallback; - } else { - cb = callback; - } - - const encoding = getEncoding(optOrCallback); - - intoCallbackAPIWithIntercept( - Deno.readLink, - (data: string): string | Uint8Array => maybeEncode(data, encoding), - cb, - path, - ); -} - -export function readlinkSync( - path: string | URL, - opt?: ReadlinkOptions, -): string | Uint8Array { - path = path instanceof URL ? fromFileUrl(path) : path; - - return maybeEncode(Deno.readLinkSync(path), getEncoding(opt)); -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_writeFile_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_writeFile_ts.ts deleted file mode 100644 index a8ae1f58629..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs__fs_writeFile_ts.ts +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import { notImplemented } from "../_utils.ts"; -import { fromFileUrl } from "../path.ts"; -import { Buffer } from "../buffer.ts"; - -import { - Encodings, - WriteFileOptions, - CallbackWithError, - isFileOptions, - getEncoding, - checkEncoding, - getOpenOptions, -} from "./_fs_common.ts"; - -export function writeFile( - pathOrRid: string | number | URL, - data: string | Uint8Array, - optOrCallback: Encodings | CallbackWithError | WriteFileOptions | undefined, - callback?: CallbackWithError, -): void { - const callbackFn: CallbackWithError | undefined = - optOrCallback instanceof Function ? optOrCallback : callback; - const options: Encodings | WriteFileOptions | undefined = - optOrCallback instanceof Function ? undefined : optOrCallback; - - if (!callbackFn) { - throw new TypeError("Callback must be a function."); - } - - pathOrRid = pathOrRid instanceof URL ? fromFileUrl(pathOrRid) : pathOrRid; - - const flag: string | undefined = isFileOptions(options) - ? options.flag - : undefined; - - const mode: number | undefined = isFileOptions(options) - ? options.mode - : undefined; - - const encoding = checkEncoding(getEncoding(options)) || "utf8"; - const openOptions = getOpenOptions(flag || "w"); - - if (typeof data === "string") data = Buffer.from(data, encoding); - - const isRid = typeof pathOrRid === "number"; - let file; - - let error: Error | null = null; - (async (): Promise => { - try { - file = isRid - ? new Deno.File(pathOrRid as number) - : await Deno.open(pathOrRid as string, openOptions); - - if (!isRid && mode) { - if (Deno.build.os === "windows") notImplemented(`"mode" on Windows`); - await Deno.chmod(pathOrRid as string, mode); - } - - await Deno.writeAll(file, data as Uint8Array); - } catch (e) { - error = e; - } finally { - // Make sure to close resource - if (!isRid && file) file.close(); - callbackFn(error); - } - })(); -} - -export function writeFileSync( - pathOrRid: string | number | URL, - data: string | Uint8Array, - options?: Encodings | WriteFileOptions, -): void { - pathOrRid = pathOrRid instanceof URL ? fromFileUrl(pathOrRid) : pathOrRid; - - const flag: string | undefined = isFileOptions(options) - ? options.flag - : undefined; - - const mode: number | undefined = isFileOptions(options) - ? options.mode - : undefined; - - const encoding = checkEncoding(getEncoding(options)) || "utf8"; - const openOptions = getOpenOptions(flag || "w"); - - if (typeof data === "string") data = Buffer.from(data, encoding); - - const isRid = typeof pathOrRid === "number"; - let file; - - let error: Error | null = null; - try { - file = isRid - ? new Deno.File(pathOrRid as number) - : Deno.openSync(pathOrRid as string, openOptions); - - if (!isRid && mode) { - if (Deno.build.os === "windows") notImplemented(`"mode" on Windows`); - Deno.chmodSync(pathOrRid as string, mode); - } - - Deno.writeAllSync(file, data as Uint8Array); - } catch (e) { - error = e; - } finally { - // Make sure to close resource - if (!isRid && file) file.close(); - - if (error) throw error; - } -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs_promises__fs_readFile_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs_promises__fs_readFile_ts.ts deleted file mode 100644 index 446c4862572..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs_promises__fs_readFile_ts.ts +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import type { - FileOptionsArgument, - BinaryOptionsArgument, - TextOptionsArgument, -} from "../_fs_common.ts"; -import { readFile as readFileCallback } from "../_fs_readFile.ts"; - -export function readFile( - path: string | URL, - options: TextOptionsArgument, -): Promise; -export function readFile( - path: string | URL, - options?: BinaryOptionsArgument, -): Promise; -export function readFile( - path: string | URL, - options?: FileOptionsArgument, -): Promise { - return new Promise((resolve, reject) => { - readFileCallback(path, options, (err, data): void => { - if (err) return reject(err); - if (data == null) { - return reject(new Error("Invalid state: data missing, but no error")); - } - resolve(data); - }); - }); -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs_promises__fs_writeFile_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs_promises__fs_writeFile_ts.ts deleted file mode 100644 index 1c9ea503284..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs_promises__fs_writeFile_ts.ts +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -import type { Encodings, WriteFileOptions } from "../_fs_common.ts"; - -import { writeFile as writeFileCallback } from "../_fs_writeFile.ts"; - -export function writeFile( - pathOrRid: string | number | URL, - data: string | Uint8Array, - options?: Encodings | WriteFileOptions, -): Promise { - return new Promise((resolve, reject) => { - writeFileCallback(pathOrRid, data, options, (err?: Error | null) => { - if (err) return reject(err); - resolve(); - }); - }); -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs_promises_mod_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs_promises_mod_ts.ts deleted file mode 100644 index 4cc6462b9c3..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node__fs_promises_mod_ts.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { writeFile } from "./_fs_writeFile.ts"; -export { readFile } from "./_fs_readFile.ts"; diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node__util__util_callbackify_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node__util__util_callbackify_ts.ts deleted file mode 100644 index b37bf829a0e..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node__util__util_callbackify_ts.ts +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -// -// Adapted from Node.js. Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// These are simplified versions of the "real" errors in Node. -class NodeFalsyValueRejectionError extends Error { - public reason: unknown; - public code = "ERR_FALSY_VALUE_REJECTION"; - constructor(reason: unknown) { - super("Promise was rejected with falsy value"); - this.reason = reason; - } -} -class NodeInvalidArgTypeError extends TypeError { - public code = "ERR_INVALID_ARG_TYPE"; - constructor(argumentName: string) { - super(`The ${argumentName} argument must be of type function.`); - } -} - -type Callback = - | ((err: Error) => void) - | ((err: null, result: ResultT) => void); - -function callbackify( - fn: () => PromiseLike, -): (callback: Callback) => void; -function callbackify( - fn: (arg: ArgT) => PromiseLike, -): (arg: ArgT, callback: Callback) => void; -function callbackify( - fn: (arg1: Arg1T, arg2: Arg2T) => PromiseLike, -): (arg1: Arg1T, arg2: Arg2T, callback: Callback) => void; -function callbackify( - fn: (arg1: Arg1T, arg2: Arg2T, arg3: Arg3T) => PromiseLike, -): (arg1: Arg1T, arg2: Arg2T, arg3: Arg3T, callback: Callback) => void; -function callbackify( - fn: ( - arg1: Arg1T, - arg2: Arg2T, - arg3: Arg3T, - arg4: Arg4T, - ) => PromiseLike, -): ( - arg1: Arg1T, - arg2: Arg2T, - arg3: Arg3T, - arg4: Arg4T, - callback: Callback, -) => void; -function callbackify( - fn: ( - arg1: Arg1T, - arg2: Arg2T, - arg3: Arg3T, - arg4: Arg4T, - arg5: Arg5T, - ) => PromiseLike, -): ( - arg1: Arg1T, - arg2: Arg2T, - arg3: Arg3T, - arg4: Arg4T, - arg5: Arg5T, - callback: Callback, -) => void; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function callbackify(original: any): any { - if (typeof original !== "function") { - throw new NodeInvalidArgTypeError('"original"'); - } - - const callbackified = function (this: unknown, ...args: unknown[]): void { - const maybeCb = args.pop(); - if (typeof maybeCb !== "function") { - throw new NodeInvalidArgTypeError("last"); - } - const cb = (...args: unknown[]): void => { - maybeCb.apply(this, args); - }; - original.apply(this, args).then( - (ret: unknown) => { - queueMicrotask(cb.bind(this, null, ret)); - }, - (rej: unknown) => { - rej = rej || new NodeFalsyValueRejectionError(rej); - queueMicrotask(cb.bind(this, rej)); - }, - ); - }; - - const descriptors = Object.getOwnPropertyDescriptors(original); - // It is possible to manipulate a functions `length` or `name` property. This - // guards against the manipulation. - if (typeof descriptors.length.value === "number") { - descriptors.length.value++; - } - if (typeof descriptors.name.value === "string") { - descriptors.name.value += "Callbackified"; - } - Object.defineProperties(callbackified, descriptors); - return callbackified; -} - -export { callbackify }; diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node__util__util_promisify_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node__util__util_promisify_ts.ts deleted file mode 100644 index 4daba8b74b4..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node__util__util_promisify_ts.ts +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -// -// Adapted from Node.js. Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// Hack: work around the following TypeScript error: -// error: TS2345 [ERROR]: Argument of type 'typeof kCustomPromisifiedSymbol' -// is not assignable to parameter of type 'typeof kCustomPromisifiedSymbol'. -// assertStrictEquals(kCustomPromisifiedSymbol, promisify.custom); -// ~~~~~~~~~~~~~~~~ -declare const _CustomPromisifiedSymbol: unique symbol; -declare const _CustomPromisifyArgsSymbol: unique symbol; -declare let Symbol: SymbolConstructor; -interface SymbolConstructor { - for(key: "nodejs.util.promisify.custom"): typeof _CustomPromisifiedSymbol; - for( - key: "nodejs.util.promisify.customArgs", - ): typeof _CustomPromisifyArgsSymbol; -} -// End hack. - -// In addition to being accessible through util.promisify.custom, -// this symbol is registered globally and can be accessed in any environment as -// Symbol.for('nodejs.util.promisify.custom'). -const kCustomPromisifiedSymbol = Symbol.for("nodejs.util.promisify.custom"); -// This is an internal Node symbol used by functions returning multiple -// arguments, e.g. ['bytesRead', 'buffer'] for fs.read(). -const kCustomPromisifyArgsSymbol = Symbol.for( - "nodejs.util.promisify.customArgs", -); - -class NodeInvalidArgTypeError extends TypeError { - public code = "ERR_INVALID_ARG_TYPE"; - constructor(argumentName: string, type: string, received: unknown) { - super( - `The "${argumentName}" argument must be of type ${type}. Received ${typeof received}`, - ); - } -} - -export function promisify(original: Function): Function { - if (typeof original !== "function") { - throw new NodeInvalidArgTypeError("original", "Function", original); - } - - // @ts-expect-error TypeScript (as of 3.7) does not support indexing namespaces by symbol - if (original[kCustomPromisifiedSymbol]) { - // @ts-expect-error TypeScript (as of 3.7) does not support indexing namespaces by symbol - const fn = original[kCustomPromisifiedSymbol]; - if (typeof fn !== "function") { - throw new NodeInvalidArgTypeError( - "util.promisify.custom", - "Function", - fn, - ); - } - return Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, - enumerable: false, - writable: false, - configurable: true, - }); - } - - // Names to create an object from in case the callback receives multiple - // arguments, e.g. ['bytesRead', 'buffer'] for fs.read. - // @ts-expect-error TypeScript (as of 3.7) does not support indexing namespaces by symbol - const argumentNames = original[kCustomPromisifyArgsSymbol]; - - function fn(...args: unknown[]): Promise { - return new Promise((resolve, reject) => { - // @ts-expect-error: 'this' implicitly has type 'any' because it does not have a type annotation - original.call(this, ...args, (err: Error, ...values: unknown[]) => { - if (err) { - return reject(err); - } - if (argumentNames !== undefined && values.length > 1) { - const obj = {}; - for (let i = 0; i < argumentNames.length; i++) { - // @ts-expect-error TypeScript - obj[argumentNames[i]] = values[i]; - } - resolve(obj); - } else { - resolve(values[0]); - } - }); - }); - } - - Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); - - Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, - enumerable: false, - writable: false, - configurable: true, - }); - return Object.defineProperties( - fn, - Object.getOwnPropertyDescriptors(original), - ); -} - -promisify.custom = kCustomPromisifiedSymbol; diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node__util__util_types_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node__util__util_types_ts.ts deleted file mode 100644 index eaf955b3549..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node__util__util_types_ts.ts +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -// -// Adapted from Node.js. Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -const _toString = Object.prototype.toString; - -const _isObjectLike = (value: unknown): boolean => - value !== null && typeof value === "object"; - -const _isFunctionLike = (value: unknown): boolean => - value !== null && typeof value === "function"; - -export function isAnyArrayBuffer(value: unknown): boolean { - return ( - _isObjectLike(value) && - (_toString.call(value) === "[object ArrayBuffer]" || - _toString.call(value) === "[object SharedArrayBuffer]") - ); -} - -export function isArrayBufferView(value: unknown): boolean { - return ArrayBuffer.isView(value); -} - -export function isArgumentsObject(value: unknown): boolean { - return _isObjectLike(value) && _toString.call(value) === "[object Arguments]"; -} - -export function isArrayBuffer(value: unknown): boolean { - return ( - _isObjectLike(value) && _toString.call(value) === "[object ArrayBuffer]" - ); -} - -export function isAsyncFunction(value: unknown): boolean { - return ( - _isFunctionLike(value) && _toString.call(value) === "[object AsyncFunction]" - ); -} - -export function isBigInt64Array(value: unknown): boolean { - return ( - _isObjectLike(value) && _toString.call(value) === "[object BigInt64Array]" - ); -} - -export function isBigUint64Array(value: unknown): boolean { - return ( - _isObjectLike(value) && _toString.call(value) === "[object BigUint64Array]" - ); -} - -export function isBooleanObject(value: unknown): boolean { - return _isObjectLike(value) && _toString.call(value) === "[object Boolean]"; -} - -export function isBoxedPrimitive(value: unknown): boolean { - return ( - isBooleanObject(value) || - isStringObject(value) || - isNumberObject(value) || - isSymbolObject(value) || - isBigIntObject(value) - ); -} - -export function isDataView(value: unknown): boolean { - return _isObjectLike(value) && _toString.call(value) === "[object DataView]"; -} - -export function isDate(value: unknown): boolean { - return _isObjectLike(value) && _toString.call(value) === "[object Date]"; -} - -// isExternal: Not implemented - -export function isFloat32Array(value: unknown): boolean { - return ( - _isObjectLike(value) && _toString.call(value) === "[object Float32Array]" - ); -} - -export function isFloat64Array(value: unknown): boolean { - return ( - _isObjectLike(value) && _toString.call(value) === "[object Float64Array]" - ); -} - -export function isGeneratorFunction(value: unknown): boolean { - return ( - _isFunctionLike(value) && - _toString.call(value) === "[object GeneratorFunction]" - ); -} - -export function isGeneratorObject(value: unknown): boolean { - return _isObjectLike(value) && _toString.call(value) === "[object Generator]"; -} - -export function isInt8Array(value: unknown): boolean { - return _isObjectLike(value) && _toString.call(value) === "[object Int8Array]"; -} - -export function isInt16Array(value: unknown): boolean { - return ( - _isObjectLike(value) && _toString.call(value) === "[object Int16Array]" - ); -} - -export function isInt32Array(value: unknown): boolean { - return ( - _isObjectLike(value) && _toString.call(value) === "[object Int32Array]" - ); -} - -export function isMap(value: unknown): boolean { - return _isObjectLike(value) && _toString.call(value) === "[object Map]"; -} - -export function isMapIterator(value: unknown): boolean { - return ( - _isObjectLike(value) && _toString.call(value) === "[object Map Iterator]" - ); -} - -export function isModuleNamespaceObject(value: unknown): boolean { - return _isObjectLike(value) && _toString.call(value) === "[object Module]"; -} - -export function isNativeError(value: unknown): boolean { - return _isObjectLike(value) && _toString.call(value) === "[object Error]"; -} - -export function isNumberObject(value: unknown): boolean { - return _isObjectLike(value) && _toString.call(value) === "[object Number]"; -} - -export function isBigIntObject(value: unknown): boolean { - return _isObjectLike(value) && _toString.call(value) === "[object BigInt]"; -} - -export function isPromise(value: unknown): boolean { - return _isObjectLike(value) && _toString.call(value) === "[object Promise]"; -} - -export function isRegExp(value: unknown): boolean { - return _isObjectLike(value) && _toString.call(value) === "[object RegExp]"; -} - -export function isSet(value: unknown): boolean { - return _isObjectLike(value) && _toString.call(value) === "[object Set]"; -} - -export function isSetIterator(value: unknown): boolean { - return ( - _isObjectLike(value) && _toString.call(value) === "[object Set Iterator]" - ); -} - -export function isSharedArrayBuffer(value: unknown): boolean { - return ( - _isObjectLike(value) && - _toString.call(value) === "[object SharedArrayBuffer]" - ); -} - -export function isStringObject(value: unknown): boolean { - return _isObjectLike(value) && _toString.call(value) === "[object String]"; -} - -export function isSymbolObject(value: unknown): boolean { - return _isObjectLike(value) && _toString.call(value) === "[object Symbol]"; -} - -// Adapted from Lodash -export function isTypedArray(value: unknown): boolean { - /** Used to match `toStringTag` values of typed arrays. */ - const reTypedTag = - /^\[object (?:Float(?:32|64)|(?:Int|Uint)(?:8|16|32)|Uint8Clamped)Array\]$/; - return _isObjectLike(value) && reTypedTag.test(_toString.call(value)); -} - -export function isUint8Array(value: unknown): boolean { - return ( - _isObjectLike(value) && _toString.call(value) === "[object Uint8Array]" - ); -} - -export function isUint8ClampedArray(value: unknown): boolean { - return ( - _isObjectLike(value) && - _toString.call(value) === "[object Uint8ClampedArray]" - ); -} - -export function isUint16Array(value: unknown): boolean { - return ( - _isObjectLike(value) && _toString.call(value) === "[object Uint16Array]" - ); -} - -export function isUint32Array(value: unknown): boolean { - return ( - _isObjectLike(value) && _toString.call(value) === "[object Uint32Array]" - ); -} - -export function isWeakMap(value: unknown): boolean { - return _isObjectLike(value) && _toString.call(value) === "[object WeakMap]"; -} - -export function isWeakSet(value: unknown): boolean { - return _isObjectLike(value) && _toString.call(value) === "[object WeakSet]"; -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node__utils_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node__utils_ts.ts deleted file mode 100644 index 0e8b26fb549..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node__utils_ts.ts +++ /dev/null @@ -1,113 +0,0 @@ -export function notImplemented(msg?: string): never { - const message = msg ? `Not implemented: ${msg}` : "Not implemented"; - throw new Error(message); -} - -export type _TextDecoder = typeof TextDecoder.prototype; -export const _TextDecoder = TextDecoder; - -export type _TextEncoder = typeof TextEncoder.prototype; -export const _TextEncoder = TextEncoder; - -// API helpers - -export type MaybeNull = T | null; -export type MaybeDefined = T | undefined; -export type MaybeEmpty = T | null | undefined; - -export function intoCallbackAPI( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - func: (...args: any[]) => Promise, - cb: MaybeEmpty<(err: MaybeNull, value: MaybeEmpty) => void>, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ...args: any[] -): void { - func(...args) - .then((value) => cb && cb(null, value)) - .catch((err) => cb && cb(err, null)); -} - -export function intoCallbackAPIWithIntercept( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - func: (...args: any[]) => Promise, - interceptor: (v: T1) => T2, - cb: MaybeEmpty<(err: MaybeNull, value: MaybeEmpty) => void>, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ...args: any[] -): void { - func(...args) - .then((value) => cb && cb(null, interceptor(value))) - .catch((err) => cb && cb(err, null)); -} - -export function spliceOne(list: string[], index: number): void { - for (; index + 1 < list.length; index++) list[index] = list[index + 1]; - list.pop(); -} - -// Taken from: https://github.com/nodejs/node/blob/ba684805b6c0eded76e5cd89ee00328ac7a59365/lib/internal/util.js#L125 -// Return undefined if there is no match. -// Move the "slow cases" to a separate function to make sure this function gets -// inlined properly. That prioritizes the common case. -export function normalizeEncoding(enc: string | null): string | undefined { - if (enc == null || enc === "utf8" || enc === "utf-8") return "utf8"; - return slowCases(enc); -} - -// https://github.com/nodejs/node/blob/ba684805b6c0eded76e5cd89ee00328ac7a59365/lib/internal/util.js#L130 -function slowCases(enc: string): string | undefined { - switch (enc.length) { - case 4: - if (enc === "UTF8") return "utf8"; - if (enc === "ucs2" || enc === "UCS2") return "utf16le"; - enc = `${enc}`.toLowerCase(); - if (enc === "utf8") return "utf8"; - if (enc === "ucs2") return "utf16le"; - break; - case 3: - if (enc === "hex" || enc === "HEX" || `${enc}`.toLowerCase() === "hex") { - return "hex"; - } - break; - case 5: - if (enc === "ascii") return "ascii"; - if (enc === "ucs-2") return "utf16le"; - if (enc === "UTF-8") return "utf8"; - if (enc === "ASCII") return "ascii"; - if (enc === "UCS-2") return "utf16le"; - enc = `${enc}`.toLowerCase(); - if (enc === "utf-8") return "utf8"; - if (enc === "ascii") return "ascii"; - if (enc === "ucs-2") return "utf16le"; - break; - case 6: - if (enc === "base64") return "base64"; - if (enc === "latin1" || enc === "binary") return "latin1"; - if (enc === "BASE64") return "base64"; - if (enc === "LATIN1" || enc === "BINARY") return "latin1"; - enc = `${enc}`.toLowerCase(); - if (enc === "base64") return "base64"; - if (enc === "latin1" || enc === "binary") return "latin1"; - break; - case 7: - if ( - enc === "utf16le" || - enc === "UTF16LE" || - `${enc}`.toLowerCase() === "utf16le" - ) { - return "utf16le"; - } - break; - case 8: - if ( - enc === "utf-16le" || - enc === "UTF-16LE" || - `${enc}`.toLowerCase() === "utf-16le" - ) { - return "utf16le"; - } - break; - default: - if (enc === "") return "utf8"; - } -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node_buffer_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node_buffer_ts.ts deleted file mode 100644 index 7656803d957..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node_buffer_ts.ts +++ /dev/null @@ -1,594 +0,0 @@ -import * as hex from "../encoding/hex.ts"; -import * as base64 from "../encoding/base64.ts"; -import { notImplemented, normalizeEncoding } from "./_utils.ts"; - -const notImplementedEncodings = [ - "ascii", - "binary", - "latin1", - "ucs2", - "utf16le", -]; - -function checkEncoding(encoding = "utf8", strict = true): string { - if (typeof encoding !== "string" || (strict && encoding === "")) { - if (!strict) return "utf8"; - throw new TypeError(`Unkown encoding: ${encoding}`); - } - - const normalized = normalizeEncoding(encoding); - - if (normalized === undefined) { - throw new TypeError(`Unkown encoding: ${encoding}`); - } - - if (notImplementedEncodings.includes(encoding)) { - notImplemented(`"${encoding}" encoding`); - } - - return normalized; -} - -interface EncodingOp { - byteLength(string: string): number; -} - -// https://github.com/nodejs/node/blob/56dbe466fdbc598baea3bfce289bf52b97b8b8f7/lib/buffer.js#L598 -const encodingOps: { [key: string]: EncodingOp } = { - utf8: { - byteLength: (string: string): number => - new TextEncoder().encode(string).byteLength, - }, - ucs2: { - byteLength: (string: string): number => string.length * 2, - }, - utf16le: { - byteLength: (string: string): number => string.length * 2, - }, - latin1: { - byteLength: (string: string): number => string.length, - }, - ascii: { - byteLength: (string: string): number => string.length, - }, - base64: { - byteLength: (string: string): number => - base64ByteLength(string, string.length), - }, - hex: { - byteLength: (string: string): number => string.length >>> 1, - }, -}; - -function base64ByteLength(str: string, bytes: number): number { - // Handle padding - if (str.charCodeAt(bytes - 1) === 0x3d) bytes--; - if (bytes > 1 && str.charCodeAt(bytes - 1) === 0x3d) bytes--; - - // Base64 ratio: 3/4 - return (bytes * 3) >>> 2; -} - -/** - * See also https://nodejs.org/api/buffer.html - */ -export default class Buffer extends Uint8Array { - /** - * Allocates a new Buffer of size bytes. - */ - static alloc( - size: number, - fill?: number | string | Uint8Array | Buffer, - encoding = "utf8", - ): Buffer { - if (typeof size !== "number") { - throw new TypeError( - `The "size" argument must be of type number. Received type ${typeof size}`, - ); - } - - const buf = new Buffer(size); - if (size === 0) return buf; - - let bufFill; - if (typeof fill === "string") { - encoding = checkEncoding(encoding); - if ( - typeof fill === "string" && fill.length === 1 && encoding === "utf8" - ) { - buf.fill(fill.charCodeAt(0)); - } else bufFill = Buffer.from(fill, encoding); - } else if (typeof fill === "number") { - buf.fill(fill); - } else if (fill instanceof Uint8Array) { - if (fill.length === 0) { - throw new TypeError( - `The argument "value" is invalid. Received ${fill.constructor.name} []`, - ); - } - - bufFill = fill; - } - - if (bufFill) { - if (bufFill.length > buf.length) { - bufFill = bufFill.subarray(0, buf.length); - } - - let offset = 0; - while (offset < size) { - buf.set(bufFill, offset); - offset += bufFill.length; - if (offset + bufFill.length >= size) break; - } - if (offset !== size) { - buf.set(bufFill.subarray(0, size - offset), offset); - } - } - - return buf; - } - - static allocUnsafe(size: number): Buffer { - return new Buffer(size); - } - - /** - * Returns the byte length of a string when encoded. This is not the same as - * String.prototype.length, which does not account for the encoding that is - * used to convert the string into bytes. - */ - static byteLength( - string: string | Buffer | ArrayBufferView | ArrayBuffer | SharedArrayBuffer, - encoding = "utf8", - ): number { - if (typeof string != "string") return string.byteLength; - - encoding = normalizeEncoding(encoding) || "utf8"; - return encodingOps[encoding].byteLength(string); - } - - /** - * Returns a new Buffer which is the result of concatenating all the Buffer - * instances in the list together. - */ - static concat(list: Buffer[] | Uint8Array[], totalLength?: number): Buffer { - if (totalLength == undefined) { - totalLength = 0; - for (const buf of list) { - totalLength += buf.length; - } - } - - const buffer = new Buffer(totalLength); - let pos = 0; - for (const buf of list) { - buffer.set(buf, pos); - pos += buf.length; - } - - return buffer; - } - - /** - * Allocates a new Buffer using an array of bytes in the range 0 – 255. Array - * entries outside that range will be truncated to fit into it. - */ - static from(array: number[]): Buffer; - /** - * This creates a view of the ArrayBuffer without copying the underlying - * memory. For example, when passed a reference to the .buffer property of a - * TypedArray instance, the newly created Buffer will share the same allocated - * memory as the TypedArray. - */ - static from( - arrayBuffer: ArrayBuffer | SharedArrayBuffer, - byteOffset?: number, - length?: number, - ): Buffer; - /** - * Copies the passed buffer data onto a new Buffer instance. - */ - static from(buffer: Buffer | Uint8Array): Buffer; - /** - * Creates a new Buffer containing string. - */ - static from(string: string, encoding?: string): Buffer; - static from( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - value: any, - offsetOrEncoding?: number | string, - length?: number, - ): Buffer { - const offset = typeof offsetOrEncoding === "string" - ? undefined - : offsetOrEncoding; - let encoding = typeof offsetOrEncoding === "string" - ? offsetOrEncoding - : undefined; - - if (typeof value == "string") { - encoding = checkEncoding(encoding, false); - if (encoding === "hex") return new Buffer(hex.decodeString(value).buffer); - if (encoding === "base64") return new Buffer(base64.decode(value)); - return new Buffer(new TextEncoder().encode(value).buffer); - } - - // workaround for https://github.com/microsoft/TypeScript/issues/38446 - return new Buffer(value, offset!, length); - } - - /** - * Returns true if obj is a Buffer, false otherwise. - */ - static isBuffer(obj: object): obj is Buffer { - return obj instanceof Buffer; - } - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static isEncoding(encoding: any): boolean { - return ( - typeof encoding === "string" && - encoding.length !== 0 && - normalizeEncoding(encoding) !== undefined - ); - } - - /** - * Copies data from a region of buf to a region in target, even if the target - * memory region overlaps with buf. - */ - copy( - targetBuffer: Buffer | Uint8Array, - targetStart = 0, - sourceStart = 0, - sourceEnd = this.length, - ): number { - const sourceBuffer = this.subarray(sourceStart, sourceEnd); - targetBuffer.set(sourceBuffer, targetStart); - return sourceBuffer.length; - } - - /* - * Returns true if both buf and otherBuffer have exactly the same bytes, false otherwise. - */ - equals(otherBuffer: Uint8Array | Buffer): boolean { - if (!(otherBuffer instanceof Uint8Array)) { - throw new TypeError( - `The "otherBuffer" argument must be an instance of Buffer or Uint8Array. Received type ${typeof otherBuffer}`, - ); - } - - if (this === otherBuffer) return true; - if (this.byteLength !== otherBuffer.byteLength) return false; - - for (let i = 0; i < this.length; i++) { - if (this[i] !== otherBuffer[i]) return false; - } - - return true; - } - - readBigInt64BE(offset = 0): bigint { - return new DataView( - this.buffer, - this.byteOffset, - this.byteLength, - ).getBigInt64(offset); - } - readBigInt64LE(offset = 0): bigint { - return new DataView( - this.buffer, - this.byteOffset, - this.byteLength, - ).getBigInt64(offset, true); - } - - readBigUInt64BE(offset = 0): bigint { - return new DataView( - this.buffer, - this.byteOffset, - this.byteLength, - ).getBigUint64(offset); - } - readBigUInt64LE(offset = 0): bigint { - return new DataView( - this.buffer, - this.byteOffset, - this.byteLength, - ).getBigUint64(offset, true); - } - - readDoubleBE(offset = 0): number { - return new DataView( - this.buffer, - this.byteOffset, - this.byteLength, - ).getFloat64(offset); - } - readDoubleLE(offset = 0): number { - return new DataView( - this.buffer, - this.byteOffset, - this.byteLength, - ).getFloat64(offset, true); - } - - readFloatBE(offset = 0): number { - return new DataView( - this.buffer, - this.byteOffset, - this.byteLength, - ).getFloat32(offset); - } - readFloatLE(offset = 0): number { - return new DataView( - this.buffer, - this.byteOffset, - this.byteLength, - ).getFloat32(offset, true); - } - - readInt8(offset = 0): number { - return new DataView(this.buffer, this.byteOffset, this.byteLength).getInt8( - offset, - ); - } - - readInt16BE(offset = 0): number { - return new DataView(this.buffer, this.byteOffset, this.byteLength).getInt16( - offset, - ); - } - readInt16LE(offset = 0): number { - return new DataView(this.buffer, this.byteOffset, this.byteLength).getInt16( - offset, - true, - ); - } - - readInt32BE(offset = 0): number { - return new DataView(this.buffer, this.byteOffset, this.byteLength).getInt32( - offset, - ); - } - readInt32LE(offset = 0): number { - return new DataView(this.buffer, this.byteOffset, this.byteLength).getInt32( - offset, - true, - ); - } - - readUInt8(offset = 0): number { - return new DataView(this.buffer, this.byteOffset, this.byteLength).getUint8( - offset, - ); - } - - readUInt16BE(offset = 0): number { - return new DataView( - this.buffer, - this.byteOffset, - this.byteLength, - ).getUint16(offset); - } - readUInt16LE(offset = 0): number { - return new DataView( - this.buffer, - this.byteOffset, - this.byteLength, - ).getUint16(offset, true); - } - - readUInt32BE(offset = 0): number { - return new DataView( - this.buffer, - this.byteOffset, - this.byteLength, - ).getUint32(offset); - } - readUInt32LE(offset = 0): number { - return new DataView( - this.buffer, - this.byteOffset, - this.byteLength, - ).getUint32(offset, true); - } - - /** - * Returns a new Buffer that references the same memory as the original, but - * offset and cropped by the start and end indices. - */ - slice(begin = 0, end = this.length): Buffer { - // workaround for https://github.com/microsoft/TypeScript/issues/38665 - return this.subarray(begin, end) as Buffer; - } - - /** - * Returns a JSON representation of buf. JSON.stringify() implicitly calls - * this function when stringifying a Buffer instance. - */ - toJSON(): object { - return { type: "Buffer", data: Array.from(this) }; - } - - /** - * Decodes buf to a string according to the specified character encoding in - * encoding. start and end may be passed to decode only a subset of buf. - */ - toString(encoding = "utf8", start = 0, end = this.length): string { - encoding = checkEncoding(encoding); - - const b = this.subarray(start, end); - if (encoding === "hex") return hex.encodeToString(b); - if (encoding === "base64") return base64.encode(b.buffer); - - return new TextDecoder(encoding).decode(b); - } - - /** - * Writes string to buf at offset according to the character encoding in - * encoding. The length parameter is the number of bytes to write. If buf did - * not contain enough space to fit the entire string, only part of string will - * be written. However, partially encoded characters will not be written. - */ - write(string: string, offset = 0, length = this.length): number { - return new TextEncoder().encodeInto( - string, - this.subarray(offset, offset + length), - ).written; - } - - writeBigInt64BE(value: bigint, offset = 0): number { - new DataView(this.buffer, this.byteOffset, this.byteLength).setBigInt64( - offset, - value, - ); - return offset + 4; - } - writeBigInt64LE(value: bigint, offset = 0): number { - new DataView(this.buffer, this.byteOffset, this.byteLength).setBigInt64( - offset, - value, - true, - ); - return offset + 4; - } - - writeBigUInt64BE(value: bigint, offset = 0): number { - new DataView(this.buffer, this.byteOffset, this.byteLength).setBigUint64( - offset, - value, - ); - return offset + 4; - } - writeBigUInt64LE(value: bigint, offset = 0): number { - new DataView(this.buffer, this.byteOffset, this.byteLength).setBigUint64( - offset, - value, - true, - ); - return offset + 4; - } - - writeDoubleBE(value: number, offset = 0): number { - new DataView(this.buffer, this.byteOffset, this.byteLength).setFloat64( - offset, - value, - ); - return offset + 8; - } - writeDoubleLE(value: number, offset = 0): number { - new DataView(this.buffer, this.byteOffset, this.byteLength).setFloat64( - offset, - value, - true, - ); - return offset + 8; - } - - writeFloatBE(value: number, offset = 0): number { - new DataView(this.buffer, this.byteOffset, this.byteLength).setFloat32( - offset, - value, - ); - return offset + 4; - } - writeFloatLE(value: number, offset = 0): number { - new DataView(this.buffer, this.byteOffset, this.byteLength).setFloat32( - offset, - value, - true, - ); - return offset + 4; - } - - writeInt8(value: number, offset = 0): number { - new DataView(this.buffer, this.byteOffset, this.byteLength).setInt8( - offset, - value, - ); - return offset + 1; - } - - writeInt16BE(value: number, offset = 0): number { - new DataView(this.buffer, this.byteOffset, this.byteLength).setInt16( - offset, - value, - ); - return offset + 2; - } - writeInt16LE(value: number, offset = 0): number { - new DataView(this.buffer, this.byteOffset, this.byteLength).setInt16( - offset, - value, - true, - ); - return offset + 2; - } - - writeInt32BE(value: number, offset = 0): number { - new DataView(this.buffer, this.byteOffset, this.byteLength).setUint32( - offset, - value, - ); - return offset + 4; - } - writeInt32LE(value: number, offset = 0): number { - new DataView(this.buffer, this.byteOffset, this.byteLength).setInt32( - offset, - value, - true, - ); - return offset + 4; - } - - writeUInt8(value: number, offset = 0): number { - new DataView(this.buffer, this.byteOffset, this.byteLength).setUint8( - offset, - value, - ); - return offset + 1; - } - - writeUInt16BE(value: number, offset = 0): number { - new DataView(this.buffer, this.byteOffset, this.byteLength).setUint16( - offset, - value, - ); - return offset + 2; - } - writeUInt16LE(value: number, offset = 0): number { - new DataView(this.buffer, this.byteOffset, this.byteLength).setUint16( - offset, - value, - true, - ); - return offset + 2; - } - - writeUInt32BE(value: number, offset = 0): number { - new DataView(this.buffer, this.byteOffset, this.byteLength).setUint32( - offset, - value, - ); - return offset + 4; - } - writeUInt32LE(value: number, offset = 0): number { - new DataView(this.buffer, this.byteOffset, this.byteLength).setUint32( - offset, - value, - true, - ); - return offset + 4; - } -} - -export { Buffer }; - -Object.defineProperty(globalThis, "Buffer", { - value: Buffer, - enumerable: false, - writable: true, - configurable: true, -}); diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node_events_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node_events_ts.ts deleted file mode 100644 index b267852aa20..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node_events_ts.ts +++ /dev/null @@ -1,527 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -// Copyright (c) 2019 Denolibs authors. All rights reserved. MIT license. -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -import { validateIntegerRange } from "./util.ts"; -import { assert } from "../_util/assert.ts"; - -export interface WrappedFunction extends Function { - listener: Function; -} - -/** - * See also https://nodejs.org/api/events.html - */ -export default class EventEmitter { - public static defaultMaxListeners = 10; - public static errorMonitor = Symbol("events.errorMonitor"); - private maxListeners: number | undefined; - private _events: Map>; - - public constructor() { - this._events = new Map(); - } - - private _addListener( - eventName: string | symbol, - listener: Function | WrappedFunction, - prepend: boolean, - ): this { - this.emit("newListener", eventName, listener); - if (this._events.has(eventName)) { - const listeners = this._events.get(eventName) as Array< - Function | WrappedFunction - >; - if (prepend) { - listeners.unshift(listener); - } else { - listeners.push(listener); - } - } else { - this._events.set(eventName, [listener]); - } - const max = this.getMaxListeners(); - if (max > 0 && this.listenerCount(eventName) > max) { - const warning = new Error( - `Possible EventEmitter memory leak detected. - ${this.listenerCount(eventName)} ${eventName.toString()} listeners. - Use emitter.setMaxListeners() to increase limit`, - ); - warning.name = "MaxListenersExceededWarning"; - console.warn(warning); - } - - return this; - } - - /** Alias for emitter.on(eventName, listener). */ - public addListener( - eventName: string | symbol, - listener: Function | WrappedFunction, - ): this { - return this._addListener(eventName, listener, false); - } - - /** - * Synchronously calls each of the listeners registered for the event named - * eventName, in the order they were registered, passing the supplied - * arguments to each. - * @return true if the event had listeners, false otherwise - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - public emit(eventName: string | symbol, ...args: any[]): boolean { - if (this._events.has(eventName)) { - if ( - eventName === "error" && - this._events.get(EventEmitter.errorMonitor) - ) { - this.emit(EventEmitter.errorMonitor, ...args); - } - const listeners = (this._events.get(eventName) as Function[]).slice(); // We copy with slice() so array is not mutated during emit - for (const listener of listeners) { - try { - listener.apply(this, args); - } catch (err) { - this.emit("error", err); - } - } - return true; - } else if (eventName === "error") { - if (this._events.get(EventEmitter.errorMonitor)) { - this.emit(EventEmitter.errorMonitor, ...args); - } - const errMsg = args.length > 0 ? args[0] : Error("Unhandled error."); - throw errMsg; - } - return false; - } - - /** - * Returns an array listing the events for which the emitter has - * registered listeners. - */ - public eventNames(): [string | symbol] { - return Array.from(this._events.keys()) as [string | symbol]; - } - - /** - * Returns the current max listener value for the EventEmitter which is - * either set by emitter.setMaxListeners(n) or defaults to - * EventEmitter.defaultMaxListeners. - */ - public getMaxListeners(): number { - return this.maxListeners || EventEmitter.defaultMaxListeners; - } - - /** - * Returns the number of listeners listening to the event named - * eventName. - */ - public listenerCount(eventName: string | symbol): number { - if (this._events.has(eventName)) { - return (this._events.get(eventName) as Function[]).length; - } else { - return 0; - } - } - - private _listeners( - target: EventEmitter, - eventName: string | symbol, - unwrap: boolean, - ): Function[] { - if (!target._events.has(eventName)) { - return []; - } - const eventListeners: Function[] = target._events.get( - eventName, - ) as Function[]; - - return unwrap - ? this.unwrapListeners(eventListeners) - : eventListeners.slice(0); - } - - private unwrapListeners(arr: Function[]): Function[] { - const unwrappedListeners: Function[] = new Array(arr.length) as Function[]; - for (let i = 0; i < arr.length; i++) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - unwrappedListeners[i] = (arr[i] as any)["listener"] || arr[i]; - } - return unwrappedListeners; - } - - /** Returns a copy of the array of listeners for the event named eventName.*/ - public listeners(eventName: string | symbol): Function[] { - return this._listeners(this, eventName, true); - } - - /** - * Returns a copy of the array of listeners for the event named eventName, - * including any wrappers (such as those created by .once()). - */ - public rawListeners( - eventName: string | symbol, - ): Array { - return this._listeners(this, eventName, false); - } - - /** Alias for emitter.removeListener(). */ - public off(eventName: string | symbol, listener: Function): this { - return this.removeListener(eventName, listener); - } - - /** - * Adds the listener function to the end of the listeners array for the event - * named eventName. No checks are made to see if the listener has already - * been added. Multiple calls passing the same combination of eventName and - * listener will result in the listener being added, and called, multiple - * times. - */ - public on( - eventName: string | symbol, - listener: Function | WrappedFunction, - ): this { - return this.addListener(eventName, listener); - } - - /** - * Adds a one-time listener function for the event named eventName. The next - * time eventName is triggered, this listener is removed and then invoked. - */ - public once(eventName: string | symbol, listener: Function): this { - const wrapped: WrappedFunction = this.onceWrap(eventName, listener); - this.on(eventName, wrapped); - return this; - } - - // Wrapped function that calls EventEmitter.removeListener(eventName, self) on execution. - private onceWrap( - eventName: string | symbol, - listener: Function, - ): WrappedFunction { - const wrapper = function ( - this: { - eventName: string | symbol; - listener: Function; - rawListener: Function; - context: EventEmitter; - }, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ...args: any[] - ): void { - this.context.removeListener(this.eventName, this.rawListener); - this.listener.apply(this.context, args); - }; - const wrapperContext = { - eventName: eventName, - listener: listener, - rawListener: (wrapper as unknown) as WrappedFunction, - context: this, - }; - const wrapped = (wrapper.bind( - wrapperContext, - ) as unknown) as WrappedFunction; - wrapperContext.rawListener = wrapped; - wrapped.listener = listener; - return wrapped as WrappedFunction; - } - - /** - * Adds the listener function to the beginning of the listeners array for the - * event named eventName. No checks are made to see if the listener has - * already been added. Multiple calls passing the same combination of - * eventName and listener will result in the listener being added, and - * called, multiple times. - */ - public prependListener( - eventName: string | symbol, - listener: Function | WrappedFunction, - ): this { - return this._addListener(eventName, listener, true); - } - - /** - * Adds a one-time listener function for the event named eventName to the - * beginning of the listeners array. The next time eventName is triggered, - * this listener is removed, and then invoked. - */ - public prependOnceListener( - eventName: string | symbol, - listener: Function, - ): this { - const wrapped: WrappedFunction = this.onceWrap(eventName, listener); - this.prependListener(eventName, wrapped); - return this; - } - - /** Removes all listeners, or those of the specified eventName. */ - public removeAllListeners(eventName?: string | symbol): this { - if (this._events === undefined) { - return this; - } - - if (eventName) { - if (this._events.has(eventName)) { - const listeners = (this._events.get(eventName) as Array< - Function | WrappedFunction - >).slice(); // Create a copy; We use it AFTER it's deleted. - this._events.delete(eventName); - for (const listener of listeners) { - this.emit("removeListener", eventName, listener); - } - } - } else { - const eventList: [string | symbol] = this.eventNames(); - eventList.map((value: string | symbol) => { - this.removeAllListeners(value); - }); - } - - return this; - } - - /** - * Removes the specified listener from the listener array for the event - * named eventName. - */ - public removeListener(eventName: string | symbol, listener: Function): this { - if (this._events.has(eventName)) { - const arr: - | Array - | undefined = this._events.get(eventName); - - assert(arr); - - let listenerIndex = -1; - for (let i = arr.length - 1; i >= 0; i--) { - // arr[i]["listener"] is the reference to the listener inside a bound 'once' wrapper - if ( - arr[i] == listener || - (arr[i] && (arr[i] as WrappedFunction)["listener"] == listener) - ) { - listenerIndex = i; - break; - } - } - - if (listenerIndex >= 0) { - arr.splice(listenerIndex, 1); - this.emit("removeListener", eventName, listener); - if (arr.length === 0) { - this._events.delete(eventName); - } - } - } - return this; - } - - /** - * By default EventEmitters will print a warning if more than 10 listeners - * are added for a particular event. This is a useful default that helps - * finding memory leaks. Obviously, not all events should be limited to just - * 10 listeners. The emitter.setMaxListeners() method allows the limit to be - * modified for this specific EventEmitter instance. The value can be set to - * Infinity (or 0) to indicate an unlimited number of listeners. - */ - public setMaxListeners(n: number): this { - validateIntegerRange(n, "maxListeners", 0); - this.maxListeners = n; - return this; - } -} - -export { EventEmitter }; - -/** - * Creates a Promise that is fulfilled when the EventEmitter emits the given - * event or that is rejected when the EventEmitter emits 'error'. The Promise - * will resolve with an array of all the arguments emitted to the given event. - */ -export function once( - emitter: EventEmitter | EventTarget, - name: string, - // eslint-disable-next-line @typescript-eslint/no-explicit-any -): Promise { - return new Promise((resolve, reject) => { - if (emitter instanceof EventTarget) { - // EventTarget does not have `error` event semantics like Node - // EventEmitters, we do not listen to `error` events here. - emitter.addEventListener( - name, - (...args) => { - resolve(args); - }, - { once: true, passive: false, capture: false }, - ); - return; - } else if (emitter instanceof EventEmitter) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const eventListener = (...args: any[]): void => { - if (errorListener !== undefined) { - emitter.removeListener("error", errorListener); - } - resolve(args); - }; - let errorListener: Function; - - // Adding an error listener is not optional because - // if an error is thrown on an event emitter we cannot - // guarantee that the actual event we are waiting will - // be fired. The result could be a silent way to create - // memory or file descriptor leaks, which is something - // we should avoid. - if (name !== "error") { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - errorListener = (err: any): void => { - emitter.removeListener(name, eventListener); - reject(err); - }; - - emitter.once("error", errorListener); - } - - emitter.once(name, eventListener); - return; - } - }); -} - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function createIterResult(value: any, done: boolean): IteratorResult { - return { value, done }; -} - -interface AsyncInterable { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - next(): Promise>; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return(): Promise>; - throw(err: Error): void; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - [Symbol.asyncIterator](): any; -} - -/** - * Returns an AsyncIterator that iterates eventName events. It will throw if - * the EventEmitter emits 'error'. It removes all listeners when exiting the - * loop. The value returned by each iteration is an array composed of the - * emitted event arguments. - */ -export function on( - emitter: EventEmitter, - event: string | symbol, -): AsyncInterable { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const unconsumedEventValues: any[] = []; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const unconsumedPromises: any[] = []; - let error: Error | null = null; - let finished = false; - - const iterator = { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - next(): Promise> { - // First, we consume all unread events - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const value: any = unconsumedEventValues.shift(); - if (value) { - return Promise.resolve(createIterResult(value, false)); - } - - // Then we error, if an error happened - // This happens one time if at all, because after 'error' - // we stop listening - if (error) { - const p: Promise = Promise.reject(error); - // Only the first element errors - error = null; - return p; - } - - // If the iterator is finished, resolve to done - if (finished) { - return Promise.resolve(createIterResult(undefined, true)); - } - - // Wait until an event happens - return new Promise(function (resolve, reject) { - unconsumedPromises.push({ resolve, reject }); - }); - }, - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return(): Promise> { - emitter.removeListener(event, eventHandler); - emitter.removeListener("error", errorHandler); - finished = true; - - for (const promise of unconsumedPromises) { - promise.resolve(createIterResult(undefined, true)); - } - - return Promise.resolve(createIterResult(undefined, true)); - }, - - throw(err: Error): void { - error = err; - emitter.removeListener(event, eventHandler); - emitter.removeListener("error", errorHandler); - }, - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - [Symbol.asyncIterator](): any { - return this; - }, - }; - - emitter.on(event, eventHandler); - emitter.on("error", errorHandler); - - return iterator; - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - function eventHandler(...args: any[]): void { - const promise = unconsumedPromises.shift(); - if (promise) { - promise.resolve(createIterResult(args, false)); - } else { - unconsumedEventValues.push(args); - } - } - - // eslint-disable-next-line @typescript-eslint/no-explicit-any - function errorHandler(err: any): void { - finished = true; - - const toError = unconsumedPromises.shift(); - if (toError) { - toError.reject(err); - } else { - // The next time we call next() - error = err; - } - - iterator.return(); - } -} -export const captureRejectionSymbol = Symbol.for("nodejs.rejection"); diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node_fs_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node_fs_ts.ts deleted file mode 100644 index 4bb514c7a6f..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node_fs_ts.ts +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. - -import { access, accessSync } from "./_fs/_fs_access.ts"; -import { appendFile, appendFileSync } from "./_fs/_fs_appendFile.ts"; -import { chmod, chmodSync } from "./_fs/_fs_chmod.ts"; -import { chown, chownSync } from "./_fs/_fs_chown.ts"; -import { close, closeSync } from "./_fs/_fs_close.ts"; -import * as constants from "./_fs/_fs_constants.ts"; -import { readFile, readFileSync } from "./_fs/_fs_readFile.ts"; -import { readlink, readlinkSync } from "./_fs/_fs_readlink.ts"; -import { exists, existsSync } from "./_fs/_fs_exists.ts"; -import { mkdir, mkdirSync } from "./_fs/_fs_mkdir.ts"; -import { copyFile, copyFileSync } from "./_fs/_fs_copy.ts"; -import { writeFile, writeFileSync } from "./_fs/_fs_writeFile.ts"; -import * as promises from "./_fs/promises/mod.ts"; - -export { - access, - accessSync, - appendFile, - appendFileSync, - chmod, - chmodSync, - chown, - chownSync, - close, - closeSync, - constants, - copyFile, - copyFileSync, - exists, - existsSync, - readFile, - readFileSync, - readlink, - readlinkSync, - mkdir, - mkdirSync, - writeFile, - writeFileSync, - promises, -}; diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node_global_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node_global_ts.ts deleted file mode 100644 index 0cb6b8b06bf..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node_global_ts.ts +++ /dev/null @@ -1,9 +0,0 @@ -Object.defineProperty(globalThis, Symbol.toStringTag, { - value: "global", - writable: false, - enumerable: false, - configurable: true, -}); - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any)["global"] = globalThis; diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node_module_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node_module_ts.ts deleted file mode 100644 index 534fe88e4b4..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node_module_ts.ts +++ /dev/null @@ -1,1168 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -import "./global.ts"; - -import * as nodeBuffer from "./buffer.ts"; -import * as nodeEvents from "./events.ts"; -import * as nodeFS from "./fs.ts"; -import * as nodeOs from "./os.ts"; -import * as nodePath from "./path.ts"; -import * as nodeTimers from "./timers.ts"; -import * as nodeQueryString from "./querystring.ts"; -import * as nodeStringDecoder from "./string_decoder.ts"; -import * as nodeUtil from "./util.ts"; - -import * as path from "../path/mod.ts"; -import { assert } from "../_util/assert.ts"; -import { pathToFileURL, fileURLToPath } from "./url.ts"; - -const CHAR_FORWARD_SLASH = "/".charCodeAt(0); -const CHAR_BACKWARD_SLASH = "\\".charCodeAt(0); -const CHAR_COLON = ":".charCodeAt(0); - -const isWindows = Deno.build.os == "windows"; - -const relativeResolveCache = Object.create(null); - -let requireDepth = 0; -let statCache: Map | null = null; - -type StatResult = -1 | 0 | 1; -// Returns 0 if the path refers to -// a file, 1 when it's a directory or < 0 on error. -function stat(filename: string): StatResult { - filename = path.toNamespacedPath(filename); - if (statCache !== null) { - const result = statCache.get(filename); - if (result !== undefined) return result; - } - try { - const info = Deno.statSync(filename); - const result = info.isFile ? 0 : 1; - if (statCache !== null) statCache.set(filename, result); - return result; - } catch (e) { - if (e instanceof Deno.errors.PermissionDenied) { - throw new Error("CJS loader requires --allow-read."); - } - return -1; - } -} - -function updateChildren( - parent: Module | null, - child: Module, - scan: boolean, -): void { - const children = parent && parent.children; - if (children && !(scan && children.includes(child))) { - children.push(child); - } -} - -class Module { - id: string; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - exports: any; - parent: Module | null; - filename: string | null; - loaded: boolean; - children: Module[]; - paths: string[]; - path: string; - constructor(id = "", parent?: Module | null) { - this.id = id; - this.exports = {}; - this.parent = parent || null; - updateChildren(parent || null, this, false); - this.filename = null; - this.loaded = false; - this.children = []; - this.paths = []; - this.path = path.dirname(id); - } - static builtinModules: string[] = []; - static _extensions: { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - [key: string]: (module: Module, filename: string) => any; - } = Object.create(null); - static _cache: { [key: string]: Module } = Object.create(null); - static _pathCache = Object.create(null); - static globalPaths: string[] = []; - // Proxy related code removed. - static wrapper = [ - "(function (exports, require, module, __filename, __dirname) { ", - "\n});", - ]; - - // Loads a module at the given file path. Returns that module's - // `exports` property. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - require(id: string): any { - if (id === "") { - throw new Error(`id '${id}' must be a non-empty string`); - } - requireDepth++; - try { - return Module._load(id, this, /* isMain */ false); - } finally { - requireDepth--; - } - } - - // Given a file name, pass it to the proper extension handler. - load(filename: string): void { - assert(!this.loaded); - this.filename = filename; - this.paths = Module._nodeModulePaths(path.dirname(filename)); - - const extension = findLongestRegisteredExtension(filename); - // Removed ESM code - Module._extensions[extension](this, filename); - this.loaded = true; - // Removed ESM code - } - - // Run the file contents in the correct scope or sandbox. Expose - // the correct helper variables (require, module, exports) to - // the file. - // Returns exception, if any. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - _compile(content: string, filename: string): any { - // manifest code removed - const compiledWrapper = wrapSafe(filename, content); - // inspector code remove - const dirname = path.dirname(filename); - const require = makeRequireFunction(this); - const exports = this.exports; - const thisValue = exports; - if (requireDepth === 0) { - statCache = new Map(); - } - const result = compiledWrapper.call( - thisValue, - exports, - require, - this, - filename, - dirname, - ); - if (requireDepth === 0) { - statCache = null; - } - return result; - } - - /* - * Check for node modules paths. - * */ - static _resolveLookupPaths( - request: string, - parent: Module | null, - ): string[] | null { - if ( - request.charAt(0) !== "." || - (request.length > 1 && - request.charAt(1) !== "." && - request.charAt(1) !== "/" && - (!isWindows || request.charAt(1) !== "\\")) - ) { - let paths = modulePaths; - if (parent !== null && parent.paths && parent.paths.length) { - paths = parent.paths.concat(paths); - } - - return paths.length > 0 ? paths : null; - } - - // With --eval, parent.id is not set and parent.filename is null. - if (!parent || !parent.id || !parent.filename) { - // Make require('./path/to/foo') work - normally the path is taken - // from realpath(__filename) but with eval there is no filename - return ["."].concat(Module._nodeModulePaths("."), modulePaths); - } - // Returns the parent path of the file - return [path.dirname(parent.filename)]; - } - - static _resolveFilename( - request: string, - parent: Module, - isMain: boolean, - options?: { paths: string[] }, - ): string { - // Polyfills. - if (nativeModuleCanBeRequiredByUsers(request)) { - return request; - } - - let paths: string[]; - - if (typeof options === "object" && options !== null) { - if (Array.isArray(options.paths)) { - const isRelative = request.startsWith("./") || - request.startsWith("../") || - (isWindows && request.startsWith(".\\")) || - request.startsWith("..\\"); - - if (isRelative) { - paths = options.paths; - } else { - const fakeParent = new Module("", null); - - paths = []; - - for (let i = 0; i < options.paths.length; i++) { - const path = options.paths[i]; - fakeParent.paths = Module._nodeModulePaths(path); - const lookupPaths = Module._resolveLookupPaths(request, fakeParent); - - for (let j = 0; j < lookupPaths!.length; j++) { - if (!paths.includes(lookupPaths![j])) { - paths.push(lookupPaths![j]); - } - } - } - } - } else if (options.paths === undefined) { - paths = Module._resolveLookupPaths(request, parent)!; - } else { - throw new Error("options.paths is invalid"); - } - } else { - paths = Module._resolveLookupPaths(request, parent)!; - } - - // Look up the filename first, since that's the cache key. - const filename = Module._findPath(request, paths, isMain); - if (!filename) { - const requireStack = []; - for (let cursor: Module | null = parent; cursor; cursor = cursor.parent) { - requireStack.push(cursor.filename || cursor.id); - } - let message = `Cannot find module '${request}'`; - if (requireStack.length > 0) { - message = message + "\nRequire stack:\n- " + requireStack.join("\n- "); - } - const err = new Error(message) as Error & { - code: string; - requireStack: string[]; - }; - err.code = "MODULE_NOT_FOUND"; - err.requireStack = requireStack; - throw err; - } - return filename as string; - } - - static _findPath( - request: string, - paths: string[], - isMain: boolean, - ): string | boolean { - const absoluteRequest = path.isAbsolute(request); - if (absoluteRequest) { - paths = [""]; - } else if (!paths || paths.length === 0) { - return false; - } - - const cacheKey = request + "\x00" + - (paths.length === 1 ? paths[0] : paths.join("\x00")); - const entry = Module._pathCache[cacheKey]; - if (entry) { - return entry; - } - - let exts; - let trailingSlash = request.length > 0 && - request.charCodeAt(request.length - 1) === CHAR_FORWARD_SLASH; - if (!trailingSlash) { - trailingSlash = /(?:^|\/)\.?\.$/.test(request); - } - - // For each path - for (let i = 0; i < paths.length; i++) { - // Don't search further if path doesn't exist - const curPath = paths[i]; - - if (curPath && stat(curPath) < 1) continue; - const basePath = resolveExports(curPath, request, absoluteRequest); - let filename; - - const rc = stat(basePath); - if (!trailingSlash) { - if (rc === 0) { - // File. - // preserveSymlinks removed - filename = toRealPath(basePath); - } - - if (!filename) { - // Try it with each of the extensions - if (exts === undefined) exts = Object.keys(Module._extensions); - filename = tryExtensions(basePath, exts, isMain); - } - } - - if (!filename && rc === 1) { - // Directory. - // try it with each of the extensions at "index" - if (exts === undefined) exts = Object.keys(Module._extensions); - filename = tryPackage(basePath, exts, isMain, request); - } - - if (filename) { - Module._pathCache[cacheKey] = filename; - return filename; - } - } - // trySelf removed. - - return false; - } - - // Check the cache for the requested file. - // 1. If a module already exists in the cache: return its exports object. - // 2. If the module is native: call - // `NativeModule.prototype.compileForPublicLoader()` and return the exports. - // 3. Otherwise, create a new module for the file and save it to the cache. - // Then have it load the file contents before returning its exports - // object. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static _load(request: string, parent: Module, isMain: boolean): any { - let relResolveCacheIdentifier: string | undefined; - if (parent) { - // Fast path for (lazy loaded) modules in the same directory. The indirect - // caching is required to allow cache invalidation without changing the old - // cache key names. - relResolveCacheIdentifier = `${parent.path}\x00${request}`; - const filename = relativeResolveCache[relResolveCacheIdentifier]; - if (filename !== undefined) { - const cachedModule = Module._cache[filename]; - if (cachedModule !== undefined) { - updateChildren(parent, cachedModule, true); - if (!cachedModule.loaded) { - return getExportsForCircularRequire(cachedModule); - } - return cachedModule.exports; - } - delete relativeResolveCache[relResolveCacheIdentifier]; - } - } - - const filename = Module._resolveFilename(request, parent, isMain); - - const cachedModule = Module._cache[filename]; - if (cachedModule !== undefined) { - updateChildren(parent, cachedModule, true); - if (!cachedModule.loaded) { - return getExportsForCircularRequire(cachedModule); - } - return cachedModule.exports; - } - - // Native module polyfills - const mod = loadNativeModule(filename, request); - if (mod) return mod.exports; - - // Don't call updateChildren(), Module constructor already does. - const module = new Module(filename, parent); - - if (isMain) { - // TODO: set process info - // process.mainModule = module; - module.id = "."; - } - - Module._cache[filename] = module; - if (parent !== undefined) { - assert(relResolveCacheIdentifier); - relativeResolveCache[relResolveCacheIdentifier] = filename; - } - - let threw = true; - try { - // Source map code removed - module.load(filename); - threw = false; - } finally { - if (threw) { - delete Module._cache[filename]; - if (parent !== undefined) { - assert(relResolveCacheIdentifier); - delete relativeResolveCache[relResolveCacheIdentifier]; - } - } else if ( - module.exports && - Object.getPrototypeOf(module.exports) === - CircularRequirePrototypeWarningProxy - ) { - Object.setPrototypeOf(module.exports, PublicObjectPrototype); - } - } - - return module.exports; - } - - static wrap(script: string): string { - return `${Module.wrapper[0]}${script}${Module.wrapper[1]}`; - } - - static _nodeModulePaths(from: string): string[] { - if (isWindows) { - // Guarantee that 'from' is absolute. - from = path.resolve(from); - - // note: this approach *only* works when the path is guaranteed - // to be absolute. Doing a fully-edge-case-correct path.split - // that works on both Windows and Posix is non-trivial. - - // return root node_modules when path is 'D:\\'. - // path.resolve will make sure from.length >=3 in Windows. - if ( - from.charCodeAt(from.length - 1) === CHAR_BACKWARD_SLASH && - from.charCodeAt(from.length - 2) === CHAR_COLON - ) { - return [from + "node_modules"]; - } - - const paths = []; - for (let i = from.length - 1, p = 0, last = from.length; i >= 0; --i) { - const code = from.charCodeAt(i); - // The path segment separator check ('\' and '/') was used to get - // node_modules path for every path segment. - // Use colon as an extra condition since we can get node_modules - // path for drive root like 'C:\node_modules' and don't need to - // parse drive name. - if ( - code === CHAR_BACKWARD_SLASH || - code === CHAR_FORWARD_SLASH || - code === CHAR_COLON - ) { - if (p !== nmLen) paths.push(from.slice(0, last) + "\\node_modules"); - last = i; - p = 0; - } else if (p !== -1) { - if (nmChars[p] === code) { - ++p; - } else { - p = -1; - } - } - } - - return paths; - } else { - // posix - // Guarantee that 'from' is absolute. - from = path.resolve(from); - // Return early not only to avoid unnecessary work, but to *avoid* returning - // an array of two items for a root: [ '//node_modules', '/node_modules' ] - if (from === "/") return ["/node_modules"]; - - // note: this approach *only* works when the path is guaranteed - // to be absolute. Doing a fully-edge-case-correct path.split - // that works on both Windows and Posix is non-trivial. - const paths = []; - for (let i = from.length - 1, p = 0, last = from.length; i >= 0; --i) { - const code = from.charCodeAt(i); - if (code === CHAR_FORWARD_SLASH) { - if (p !== nmLen) paths.push(from.slice(0, last) + "/node_modules"); - last = i; - p = 0; - } else if (p !== -1) { - if (nmChars[p] === code) { - ++p; - } else { - p = -1; - } - } - } - - // Append /node_modules to handle root paths. - paths.push("/node_modules"); - - return paths; - } - } - - /** - * Create a `require` function that can be used to import CJS modules. - * Follows CommonJS resolution similar to that of Node.js, - * with `node_modules` lookup and `index.js` lookup support. - * Also injects available Node.js builtin module polyfills. - * - * const require = createRequire(import.meta.url); - * const fs = require("fs"); - * const leftPad = require("left-pad"); - * const cjsModule = require("./cjs_mod"); - * - * @param filename path or URL to current module - * @return Require function to import CJS modules - */ - static createRequire(filename: string | URL): RequireFunction { - let filepath: string; - if ( - filename instanceof URL || - (typeof filename === "string" && !path.isAbsolute(filename)) - ) { - filepath = fileURLToPath(filename); - } else if (typeof filename !== "string") { - throw new Error("filename should be a string"); - } else { - filepath = filename; - } - return createRequireFromPath(filepath); - } - - static _initPaths(): void { - const homeDir = Deno.env.get("HOME"); - const nodePath = Deno.env.get("NODE_PATH"); - - // Removed $PREFIX/bin/node case - - let paths = []; - - if (homeDir) { - paths.unshift(path.resolve(homeDir, ".node_libraries")); - paths.unshift(path.resolve(homeDir, ".node_modules")); - } - - if (nodePath) { - paths = nodePath - .split(path.delimiter) - .filter(function pathsFilterCB(path) { - return !!path; - }) - .concat(paths); - } - - modulePaths = paths; - - // Clone as a shallow copy, for introspection. - Module.globalPaths = modulePaths.slice(0); - } - - static _preloadModules(requests: string[]): void { - if (!Array.isArray(requests)) { - return; - } - - // Preloaded modules have a dummy parent module which is deemed to exist - // in the current working directory. This seeds the search path for - // preloaded modules. - const parent = new Module("internal/preload", null); - try { - parent.paths = Module._nodeModulePaths(Deno.cwd()); - } catch (e) { - if (e.code !== "ENOENT") { - throw e; - } - } - for (let n = 0; n < requests.length; n++) { - parent.require(requests[n]); - } - } -} - -// Polyfills. -const nativeModulePolyfill = new Map(); -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function createNativeModule(id: string, exports: any): Module { - const mod = new Module(id); - mod.exports = exports; - mod.loaded = true; - return mod; -} - -nativeModulePolyfill.set("buffer", createNativeModule("buffer", nodeBuffer)); -nativeModulePolyfill.set("events", createNativeModule("events", nodeEvents)); -nativeModulePolyfill.set("fs", createNativeModule("fs", nodeFS)); -nativeModulePolyfill.set("os", createNativeModule("os", nodeOs)); -nativeModulePolyfill.set("path", createNativeModule("path", nodePath)); -nativeModulePolyfill.set( - "querystring", - createNativeModule("querystring", nodeQueryString), -); -nativeModulePolyfill.set( - "string_decoder", - createNativeModule("string_decoder", nodeStringDecoder), -); -nativeModulePolyfill.set("timers", createNativeModule("timers", nodeTimers)); -nativeModulePolyfill.set("util", createNativeModule("util", nodeUtil)); - -function loadNativeModule( - _filename: string, - request: string, -): Module | undefined { - return nativeModulePolyfill.get(request); -} -function nativeModuleCanBeRequiredByUsers(request: string): boolean { - return nativeModulePolyfill.has(request); -} -// Populate with polyfill names -for (const id of nativeModulePolyfill.keys()) { - Module.builtinModules.push(id); -} - -let modulePaths: string[] = []; - -// Given a module name, and a list of paths to test, returns the first -// matching file in the following precedence. -// -// require("a.") -// -> a. -// -// require("a") -// -> a -// -> a. -// -> a/index. - -const packageJsonCache = new Map(); - -interface PackageInfo { - name?: string; - main?: string; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - exports?: any; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - type?: any; -} - -function readPackage(requestPath: string): PackageInfo | null { - const jsonPath = path.resolve(requestPath, "package.json"); - - const existing = packageJsonCache.get(jsonPath); - if (existing !== undefined) { - return existing; - } - - let json: string | undefined; - try { - json = new TextDecoder().decode( - Deno.readFileSync(path.toNamespacedPath(jsonPath)), - ); - } catch { - // pass - } - - if (json === undefined) { - packageJsonCache.set(jsonPath, null); - return null; - } - - try { - const parsed = JSON.parse(json); - const filtered = { - name: parsed.name, - main: parsed.main, - exports: parsed.exports, - type: parsed.type, - }; - packageJsonCache.set(jsonPath, filtered); - return filtered; - } catch (e) { - e.path = jsonPath; - e.message = "Error parsing " + jsonPath + ": " + e.message; - throw e; - } -} - -function readPackageScope( - checkPath: string, -): { path: string; data: PackageInfo } | false { - const rootSeparatorIndex = checkPath.indexOf(path.sep); - let separatorIndex; - while ( - (separatorIndex = checkPath.lastIndexOf(path.sep)) > rootSeparatorIndex - ) { - checkPath = checkPath.slice(0, separatorIndex); - if (checkPath.endsWith(path.sep + "node_modules")) return false; - const pjson = readPackage(checkPath); - if (pjson) { - return { - path: checkPath, - data: pjson, - }; - } - } - return false; -} - -function readPackageMain(requestPath: string): string | undefined { - const pkg = readPackage(requestPath); - return pkg ? pkg.main : undefined; -} - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function readPackageExports(requestPath: string): any | undefined { - const pkg = readPackage(requestPath); - return pkg ? pkg.exports : undefined; -} - -function tryPackage( - requestPath: string, - exts: string[], - isMain: boolean, - _originalPath: string, -): string | false { - const pkg = readPackageMain(requestPath); - - if (!pkg) { - return tryExtensions(path.resolve(requestPath, "index"), exts, isMain); - } - - const filename = path.resolve(requestPath, pkg); - let actual = tryFile(filename, isMain) || - tryExtensions(filename, exts, isMain) || - tryExtensions(path.resolve(filename, "index"), exts, isMain); - if (actual === false) { - actual = tryExtensions(path.resolve(requestPath, "index"), exts, isMain); - if (!actual) { - const err = new Error( - `Cannot find module '${filename}'. ` + - 'Please verify that the package.json has a valid "main" entry', - ) as Error & { code: string }; - err.code = "MODULE_NOT_FOUND"; - throw err; - } - } - return actual; -} - -// Check if the file exists and is not a directory -// if using --preserve-symlinks and isMain is false, -// keep symlinks intact, otherwise resolve to the -// absolute realpath. -function tryFile(requestPath: string, _isMain: boolean): string | false { - const rc = stat(requestPath); - return rc === 0 && toRealPath(requestPath); -} - -function toRealPath(requestPath: string): string { - // Deno does not have realpath implemented yet. - let fullPath = requestPath; - while (true) { - try { - fullPath = Deno.readLinkSync(fullPath); - } catch { - break; - } - } - return path.resolve(requestPath); -} - -// Given a path, check if the file exists with any of the set extensions -function tryExtensions( - p: string, - exts: string[], - isMain: boolean, -): string | false { - for (let i = 0; i < exts.length; i++) { - const filename = tryFile(p + exts[i], isMain); - - if (filename) { - return filename; - } - } - return false; -} - -// Find the longest (possibly multi-dot) extension registered in -// Module._extensions -function findLongestRegisteredExtension(filename: string): string { - const name = path.basename(filename); - let currentExtension; - let index; - let startIndex = 0; - while ((index = name.indexOf(".", startIndex)) !== -1) { - startIndex = index + 1; - if (index === 0) continue; // Skip dotfiles like .gitignore - currentExtension = name.slice(index); - if (Module._extensions[currentExtension]) return currentExtension; - } - return ".js"; -} - -// --experimental-resolve-self trySelf() support removed. - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function isConditionalDotExportSugar(exports: any, _basePath: string): boolean { - if (typeof exports === "string") return true; - if (Array.isArray(exports)) return true; - if (typeof exports !== "object") return false; - let isConditional = false; - let firstCheck = true; - for (const key of Object.keys(exports)) { - const curIsConditional = key[0] !== "."; - if (firstCheck) { - firstCheck = false; - isConditional = curIsConditional; - } else if (isConditional !== curIsConditional) { - throw new Error( - '"exports" cannot ' + - "contain some keys starting with '.' and some not. The exports " + - "object must either be an object of package subpath keys or an " + - "object of main entry condition name keys only.", - ); - } - } - return isConditional; -} - -function applyExports(basePath: string, expansion: string): string { - const mappingKey = `.${expansion}`; - - let pkgExports = readPackageExports(basePath); - if (pkgExports === undefined || pkgExports === null) { - return path.resolve(basePath, mappingKey); - } - - if (isConditionalDotExportSugar(pkgExports, basePath)) { - pkgExports = { ".": pkgExports }; - } - - if (typeof pkgExports === "object") { - if (Object.prototype.hasOwnProperty.call(pkgExports, mappingKey)) { - const mapping = pkgExports[mappingKey]; - return resolveExportsTarget( - pathToFileURL(basePath + "/"), - mapping, - "", - basePath, - mappingKey, - ); - } - - // Fallback to CJS main lookup when no main export is defined - if (mappingKey === ".") return basePath; - - let dirMatch = ""; - for (const candidateKey of Object.keys(pkgExports)) { - if (candidateKey[candidateKey.length - 1] !== "/") continue; - if ( - candidateKey.length > dirMatch.length && - mappingKey.startsWith(candidateKey) - ) { - dirMatch = candidateKey; - } - } - - if (dirMatch !== "") { - const mapping = pkgExports[dirMatch]; - const subpath = mappingKey.slice(dirMatch.length); - return resolveExportsTarget( - pathToFileURL(basePath + "/"), - mapping, - subpath, - basePath, - mappingKey, - ); - } - } - // Fallback to CJS main lookup when no main export is defined - if (mappingKey === ".") return basePath; - - const e = new Error( - `Package exports for '${basePath}' do not define ` + - `a '${mappingKey}' subpath`, - ) as Error & { code?: string }; - e.code = "MODULE_NOT_FOUND"; - throw e; -} - -// This only applies to requests of a specific form: -// 1. name/.* -// 2. @scope/name/.* -const EXPORTS_PATTERN = /^((?:@[^/\\%]+\/)?[^./\\%][^/\\%]*)(\/.*)?$/; -function resolveExports( - nmPath: string, - request: string, - absoluteRequest: boolean, -): string { - // The implementation's behavior is meant to mirror resolution in ESM. - if (!absoluteRequest) { - const [, name, expansion = ""] = request.match(EXPORTS_PATTERN) || []; - if (!name) { - return path.resolve(nmPath, request); - } - - const basePath = path.resolve(nmPath, name); - return applyExports(basePath, expansion); - } - - return path.resolve(nmPath, request); -} - -function resolveExportsTarget( - pkgPath: URL, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - target: any, - subpath: string, - basePath: string, - mappingKey: string, -): string { - if (typeof target === "string") { - if ( - target.startsWith("./") && - (subpath.length === 0 || target.endsWith("/")) - ) { - const resolvedTarget = new URL(target, pkgPath); - const pkgPathPath = pkgPath.pathname; - const resolvedTargetPath = resolvedTarget.pathname; - if ( - resolvedTargetPath.startsWith(pkgPathPath) && - resolvedTargetPath.indexOf("/node_modules/", pkgPathPath.length - 1) === - -1 - ) { - const resolved = new URL(subpath, resolvedTarget); - const resolvedPath = resolved.pathname; - if ( - resolvedPath.startsWith(resolvedTargetPath) && - resolvedPath.indexOf("/node_modules/", pkgPathPath.length - 1) === -1 - ) { - return fileURLToPath(resolved); - } - } - } - } else if (Array.isArray(target)) { - for (const targetValue of target) { - if (Array.isArray(targetValue)) continue; - try { - return resolveExportsTarget( - pkgPath, - targetValue, - subpath, - basePath, - mappingKey, - ); - } catch (e) { - if (e.code !== "MODULE_NOT_FOUND") throw e; - } - } - } else if (typeof target === "object" && target !== null) { - // removed experimentalConditionalExports - if (Object.prototype.hasOwnProperty.call(target, "default")) { - try { - return resolveExportsTarget( - pkgPath, - target.default, - subpath, - basePath, - mappingKey, - ); - } catch (e) { - if (e.code !== "MODULE_NOT_FOUND") throw e; - } - } - } - let e: Error & { code?: string }; - if (mappingKey !== ".") { - e = new Error( - `Package exports for '${basePath}' do not define a ` + - `valid '${mappingKey}' target${subpath ? " for " + subpath : ""}`, - ); - } else { - e = new Error(`No valid exports main found for '${basePath}'`); - } - e.code = "MODULE_NOT_FOUND"; - throw e; -} - -// 'node_modules' character codes reversed -const nmChars = [115, 101, 108, 117, 100, 111, 109, 95, 101, 100, 111, 110]; -const nmLen = nmChars.length; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function emitCircularRequireWarning(prop: any): void { - console.error( - `Accessing non-existent property '${ - String(prop) - }' of module exports inside circular dependency`, - ); -} - -// A Proxy that can be used as the prototype of a module.exports object and -// warns when non-existent properties are accessed. -const CircularRequirePrototypeWarningProxy = new Proxy( - {}, - { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - get(target: Record, prop: string): any { - if (prop in target) return target[prop]; - emitCircularRequireWarning(prop); - return undefined; - }, - - getOwnPropertyDescriptor(target, prop): PropertyDescriptor | undefined { - if (Object.prototype.hasOwnProperty.call(target, prop)) { - return Object.getOwnPropertyDescriptor(target, prop); - } - emitCircularRequireWarning(prop); - return undefined; - }, - }, -); - -// Object.prototype and ObjectProtoype refer to our 'primordials' versions -// and are not identical to the versions on the global object. -const PublicObjectPrototype = window.Object.prototype; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function getExportsForCircularRequire(module: Module): any { - if ( - module.exports && - Object.getPrototypeOf(module.exports) === PublicObjectPrototype && - // Exclude transpiled ES6 modules / TypeScript code because those may - // employ unusual patterns for accessing 'module.exports'. That should be - // okay because ES6 modules have a different approach to circular - // dependencies anyway. - !module.exports.__esModule - ) { - // This is later unset once the module is done loading. - Object.setPrototypeOf(module.exports, CircularRequirePrototypeWarningProxy); - } - - return module.exports; -} - -type RequireWrapper = ( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - exports: any, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - require: any, - module: Module, - __filename: string, - __dirname: string, -) => void; - -function wrapSafe(filename: string, content: string): RequireWrapper { - // TODO: fix this - const wrapper = Module.wrap(content); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const [f, err] = (Deno as any).core.evalContext(wrapper, filename); - if (err) { - throw err; - } - return f; - // ESM code removed. -} - -// Native extension for .js -Module._extensions[".js"] = (module: Module, filename: string): void => { - if (filename.endsWith(".js")) { - const pkg = readPackageScope(filename); - if (pkg !== false && pkg.data && pkg.data.type === "module") { - throw new Error("Importing ESM module"); - } - } - const content = new TextDecoder().decode(Deno.readFileSync(filename)); - module._compile(content, filename); -}; - -// Native extension for .json -Module._extensions[".json"] = (module: Module, filename: string): void => { - const content = new TextDecoder().decode(Deno.readFileSync(filename)); - // manifest code removed - try { - module.exports = JSON.parse(stripBOM(content)); - } catch (err) { - err.message = filename + ": " + err.message; - throw err; - } -}; - -// .node extension is not supported - -function createRequireFromPath(filename: string): RequireFunction { - // Allow a directory to be passed as the filename - const trailingSlash = filename.endsWith("/") || - (isWindows && filename.endsWith("\\")); - - const proxyPath = trailingSlash ? path.join(filename, "noop.js") : filename; - - const m = new Module(proxyPath); - m.filename = proxyPath; - - m.paths = Module._nodeModulePaths(m.path); - return makeRequireFunction(m); -} - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -type Require = (id: string) => any; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -type RequireResolve = (request: string, options: any) => string; -interface RequireResolveFunction extends RequireResolve { - paths: (request: string) => string[] | null; -} - -interface RequireFunction extends Require { - resolve: RequireResolveFunction; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - extensions: { [key: string]: (module: Module, filename: string) => any }; - cache: { [key: string]: Module }; -} - -function makeRequireFunction(mod: Module): RequireFunction { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const require = function require(path: string): any { - return mod.require(path); - }; - - function resolve(request: string, options?: { paths: string[] }): string { - return Module._resolveFilename(request, mod, false, options); - } - - require.resolve = resolve; - - function paths(request: string): string[] | null { - return Module._resolveLookupPaths(request, mod); - } - - resolve.paths = paths; - // TODO: set main - // require.main = process.mainModule; - - // Enable support to add extra extension types. - require.extensions = Module._extensions; - - require.cache = Module._cache; - - return require; -} - -/** - * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) - * because the buffer-to-string conversion in `fs.readFileSync()` - * translates it to FEFF, the UTF-16 BOM. - */ -function stripBOM(content: string): string { - if (content.charCodeAt(0) === 0xfeff) { - content = content.slice(1); - } - return content; -} - -export const builtinModules = Module.builtinModules; -export const createRequire = Module.createRequire; -export default Module; diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node_os_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node_os_ts.ts deleted file mode 100644 index c312ffe0c03..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node_os_ts.ts +++ /dev/null @@ -1,225 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -import { notImplemented } from "./_utils.ts"; -import { validateIntegerRange } from "./util.ts"; -import { EOL as fsEOL } from "../fs/eol.ts"; -import process from "./process.ts"; - -const SEE_GITHUB_ISSUE = "See https://github.com/denoland/deno/issues/3802"; - -interface CPUTimes { - /** The number of milliseconds the CPU has spent in user mode */ - user: number; - - /** The number of milliseconds the CPU has spent in nice mode */ - nice: number; - - /** The number of milliseconds the CPU has spent in sys mode */ - sys: number; - - /** The number of milliseconds the CPU has spent in idle mode */ - idle: number; - - /** The number of milliseconds the CPU has spent in irq mode */ - irq: number; -} - -interface CPUCoreInfo { - model: string; - - /** in MHz */ - speed: number; - - times: CPUTimes; -} - -interface NetworkAddress { - /** The assigned IPv4 or IPv6 address */ - address: string; - - /** The IPv4 or IPv6 network mask */ - netmask: string; - - family: "IPv4" | "IPv6"; - - /** The MAC address of the network interface */ - mac: string; - - /** true if the network interface is a loopback or similar interface that is not remotely accessible; otherwise false */ - internal: boolean; - - /** The numeric IPv6 scope ID (only specified when family is IPv6) */ - scopeid?: number; - - /** The assigned IPv4 or IPv6 address with the routing prefix in CIDR notation. If the netmask is invalid, this property is set to null. */ - cidr: string; -} - -interface NetworkInterfaces { - [key: string]: NetworkAddress[]; -} - -export interface UserInfoOptions { - encoding: string; -} - -interface UserInfo { - username: string; - uid: number; - gid: number; - shell: string; - homedir: string; -} - -arch[Symbol.toPrimitive] = (): string => arch(); -endianness[Symbol.toPrimitive] = (): string => endianness(); -freemem[Symbol.toPrimitive] = (): number => freemem(); -homedir[Symbol.toPrimitive] = (): string | null => homedir(); -hostname[Symbol.toPrimitive] = (): string | null => hostname(); -platform[Symbol.toPrimitive] = (): string => platform(); -release[Symbol.toPrimitive] = (): string => release(); -totalmem[Symbol.toPrimitive] = (): number => totalmem(); -type[Symbol.toPrimitive] = (): string => type(); -uptime[Symbol.toPrimitive] = (): number => uptime(); - -/** Returns the operating system CPU architecture for which the Deno binary was compiled */ -export function arch(): string { - return Deno.build.arch; -} - -/** Not yet implemented */ -export function cpus(): CPUCoreInfo[] { - notImplemented(SEE_GITHUB_ISSUE); -} - -/** - * Returns a string identifying the endianness of the CPU for which the Deno - * binary was compiled. Possible values are 'BE' for big endian and 'LE' for - * little endian. - **/ -export function endianness(): "BE" | "LE" { - // Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView#Endianness - const buffer = new ArrayBuffer(2); - new DataView(buffer).setInt16(0, 256, true /* littleEndian */); - // Int16Array uses the platform's endianness. - return new Int16Array(buffer)[0] === 256 ? "LE" : "BE"; -} - -/** Not yet implemented */ -export function freemem(): number { - notImplemented(SEE_GITHUB_ISSUE); -} - -/** Not yet implemented */ -export function getPriority(pid = 0): number { - validateIntegerRange(pid, "pid"); - notImplemented(SEE_GITHUB_ISSUE); -} - -/** Returns the string path of the current user's home directory. */ -export function homedir(): string | null { - notImplemented(SEE_GITHUB_ISSUE); -} - -/** Returns the host name of the operating system as a string. */ -export function hostname(): string { - notImplemented(SEE_GITHUB_ISSUE); -} - -/** Returns an array containing the 1, 5, and 15 minute load averages */ -export function loadavg(): number[] { - if (Deno.build.os === "windows") { - return [0, 0, 0]; - } - return Deno.loadavg(); -} - -/** Not yet implemented */ -export function networkInterfaces(): NetworkInterfaces { - notImplemented(SEE_GITHUB_ISSUE); -} -/** Returns the a string identifying the operating system platform. The value is set at compile time. Possible values are 'darwin', 'linux', and 'win32'. */ -export function platform(): string { - return process.platform; -} - -/** Returns the operating system as a string */ -export function release(): string { - return Deno.osRelease(); -} - -/** Not yet implemented */ -export function setPriority(pid: number, priority?: number): void { - /* The node API has the 'pid' as the first parameter and as optional. - This makes for a problematic implementation in Typescript. */ - if (priority === undefined) { - priority = pid; - pid = 0; - } - validateIntegerRange(pid, "pid"); - validateIntegerRange(priority, "priority", -20, 19); - - notImplemented(SEE_GITHUB_ISSUE); -} - -/** Returns the operating system's default directory for temporary files as a string. */ -export function tmpdir(): string | null { - notImplemented(SEE_GITHUB_ISSUE); -} - -/** Not yet implemented */ -export function totalmem(): number { - notImplemented(SEE_GITHUB_ISSUE); -} - -/** Not yet implemented */ -export function type(): string { - notImplemented(SEE_GITHUB_ISSUE); -} - -/** Not yet implemented */ -export function uptime(): number { - notImplemented(SEE_GITHUB_ISSUE); -} - -/** Not yet implemented */ -export function userInfo( - /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ - options: UserInfoOptions = { encoding: "utf-8" }, -): UserInfo { - notImplemented(SEE_GITHUB_ISSUE); -} - -export const constants = { - // UV_UDP_REUSEADDR: 4, //see https://nodejs.org/docs/latest-v12.x/api/os.html#os_libuv_constants - dlopen: { - // see https://nodejs.org/docs/latest-v12.x/api/os.html#os_dlopen_constants - }, - errno: { - // see https://nodejs.org/docs/latest-v12.x/api/os.html#os_error_constants - }, - signals: Deno.Signal, - priority: { - // see https://nodejs.org/docs/latest-v12.x/api/os.html#os_priority_constants - }, -}; - -export const EOL = Deno.build.os == "windows" ? fsEOL.CRLF : fsEOL.LF; diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node_path_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node_path_ts.ts deleted file mode 100644 index e8295281a19..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node_path_ts.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "../path/mod.ts"; diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node_process_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node_process_ts.ts deleted file mode 100644 index ce5f828c074..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node_process_ts.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { notImplemented } from "./_utils.ts"; - -/** https://nodejs.org/api/process.html#process_process_arch */ -export const arch = Deno.build.arch; - -/** https://nodejs.org/api/process.html#process_process_chdir_directory */ -export const chdir = Deno.chdir; - -/** https://nodejs.org/api/process.html#process_process_cwd */ -export const cwd = Deno.cwd; - -/** https://nodejs.org/api/process.html#process_process_exit_code */ -export const exit = Deno.exit; - -/** https://nodejs.org/api/process.html#process_process_pid */ -export const pid = Deno.pid; - -/** https://nodejs.org/api/process.html#process_process_platform */ -export const platform = Deno.build.os === "windows" ? "win32" : Deno.build.os; - -/** https://nodejs.org/api/process.html#process_process_version */ -export const version = `v${Deno.version.deno}`; - -/** https://nodejs.org/api/process.html#process_process_versions */ -export const versions = { - node: Deno.version.deno, - ...Deno.version, -}; - -/** https://nodejs.org/api/process.html#process_process */ -// @deprecated `import { process } from 'process'` for backwards compatibility with old deno versions -export const process = { - arch, - chdir, - cwd, - exit, - pid, - platform, - version, - versions, - - /** https://nodejs.org/api/process.html#process_process_events */ - // on is not exported by node, it is only available within process: - // node --input-type=module -e "import { on } from 'process'; console.log(on)" - on(_event: string, _callback: Function): void { - // TODO(rsp): to be implemented - notImplemented(); - }, - - /** https://nodejs.org/api/process.html#process_process_argv */ - get argv(): string[] { - // Getter delegates --allow-env and --allow-read until request - // Getter also allows the export Proxy instance to function as intended - return [Deno.execPath(), ...Deno.args]; - }, - - /** https://nodejs.org/api/process.html#process_process_env */ - get env(): { [index: string]: string } { - // Getter delegates --allow-env and --allow-read until request - // Getter also allows the export Proxy instance to function as intended - return Deno.env.toObject(); - }, -}; - -/** - * https://nodejs.org/api/process.html#process_process_argv - * @example `import { argv } from './std/node/process.ts'; console.log(argv)` - */ -// Proxy delegates --allow-env and --allow-read to request time, even for exports -export const argv = new Proxy(process.argv, {}); - -/** - * https://nodejs.org/api/process.html#process_process_env - * @example `import { env } from './std/node/process.ts'; console.log(env)` - */ -// Proxy delegates --allow-env and --allow-read to request time, even for exports -export const env = new Proxy(process.env, {}); - -// import process from './std/node/process.ts' -export default process; - -// Define the type for the global declration -type Process = typeof process; - -Object.defineProperty(process, Symbol.toStringTag, { - enumerable: false, - writable: true, - configurable: false, - value: "process", -}); - -Object.defineProperty(globalThis, "process", { - value: process, - enumerable: false, - writable: true, - configurable: true, -}); - -declare global { - const process: Process; -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node_querystring_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node_querystring_ts.ts deleted file mode 100644 index 4e3c728c12c..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node_querystring_ts.ts +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. - -interface ParseOptions { - decodeURIComponent?: (string: string) => string; - maxKeys?: number; -} -export const hexTable = new Array(256); -for (let i = 0; i < 256; ++i) { - hexTable[i] = "%" + ((i < 16 ? "0" : "") + i.toString(16)).toUpperCase(); -} - -export function parse( - str: string, - sep = "&", - eq = "=", - { decodeURIComponent = unescape, maxKeys = 1000 }: ParseOptions = {}, -): { [key: string]: string[] | string } { - const entries = str - .split(sep) - .map((entry) => entry.split(eq).map(decodeURIComponent)); - const final: { [key: string]: string[] | string } = {}; - - let i = 0; - while (true) { - if ((Object.keys(final).length === maxKeys && !!maxKeys) || !entries[i]) { - break; - } - - const [key, val] = entries[i]; - if (final[key]) { - if (Array.isArray(final[key])) { - (final[key] as string[]).push(val); - } else { - final[key] = [final[key] as string, val]; - } - } else { - final[key] = val; - } - - i++; - } - - return final; -} - -interface StringifyOptions { - encodeURIComponent?: (string: string) => string; -} - -export function encodeStr( - str: string, - noEscapeTable: number[], - hexTable: string[], -): string { - const len = str.length; - if (len === 0) return ""; - - let out = ""; - let lastPos = 0; - - for (let i = 0; i < len; i++) { - let c = str.charCodeAt(i); - // ASCII - if (c < 0x80) { - if (noEscapeTable[c] === 1) continue; - if (lastPos < i) out += str.slice(lastPos, i); - lastPos = i + 1; - out += hexTable[c]; - continue; - } - - if (lastPos < i) out += str.slice(lastPos, i); - - // Multi-byte characters ... - if (c < 0x800) { - lastPos = i + 1; - out += hexTable[0xc0 | (c >> 6)] + hexTable[0x80 | (c & 0x3f)]; - continue; - } - if (c < 0xd800 || c >= 0xe000) { - lastPos = i + 1; - out += hexTable[0xe0 | (c >> 12)] + - hexTable[0x80 | ((c >> 6) & 0x3f)] + - hexTable[0x80 | (c & 0x3f)]; - continue; - } - // Surrogate pair - ++i; - - // This branch should never happen because all URLSearchParams entries - // should already be converted to USVString. But, included for - // completion's sake anyway. - if (i >= len) throw new Deno.errors.InvalidData("invalid URI"); - - const c2 = str.charCodeAt(i) & 0x3ff; - - lastPos = i + 1; - c = 0x10000 + (((c & 0x3ff) << 10) | c2); - out += hexTable[0xf0 | (c >> 18)] + - hexTable[0x80 | ((c >> 12) & 0x3f)] + - hexTable[0x80 | ((c >> 6) & 0x3f)] + - hexTable[0x80 | (c & 0x3f)]; - } - if (lastPos === 0) return str; - if (lastPos < len) return out + str.slice(lastPos); - return out; -} - -export function stringify( - obj: object, - sep = "&", - eq = "=", - { encodeURIComponent = escape }: StringifyOptions = {}, -): string { - const final = []; - - for (const entry of Object.entries(obj)) { - if (Array.isArray(entry[1])) { - for (const val of entry[1]) { - final.push(encodeURIComponent(entry[0]) + eq + encodeURIComponent(val)); - } - } else if (typeof entry[1] !== "object" && entry[1] !== undefined) { - final.push(entry.map(encodeURIComponent).join(eq)); - } else { - final.push(encodeURIComponent(entry[0]) + eq); - } - } - - return final.join(sep); -} - -export const decode = parse; -export const encode = stringify; -export const unescape = decodeURIComponent; -export const escape = encodeURIComponent; diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node_string_decoder_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node_string_decoder_ts.ts deleted file mode 100644 index ce7c19538ed..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node_string_decoder_ts.ts +++ /dev/null @@ -1,299 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -import { Buffer } from "./buffer.ts"; -import { normalizeEncoding as castEncoding, notImplemented } from "./_utils.ts"; - -enum NotImplemented { - "ascii", - "latin1", - "utf16le", -} - -function normalizeEncoding(enc?: string): string { - const encoding = castEncoding(enc ?? null); - if (encoding && encoding in NotImplemented) notImplemented(encoding); - if (!encoding && typeof enc === "string" && enc.toLowerCase() !== "raw") { - throw new Error(`Unknown encoding: ${enc}`); - } - return String(encoding); -} -/* - * Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a - * continuation byte. If an invalid byte is detected, -2 is returned. - * */ -function utf8CheckByte(byte: number): number { - if (byte <= 0x7f) return 0; - else if (byte >> 5 === 0x06) return 2; - else if (byte >> 4 === 0x0e) return 3; - else if (byte >> 3 === 0x1e) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} - -/* - * Checks at most 3 bytes at the end of a Buffer in order to detect an - * incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) - * needed to complete the UTF-8 character (if applicable) are returned. - * */ -function utf8CheckIncomplete( - self: StringDecoderBase, - buf: Buffer, - i: number, -): number { - let j = buf.length - 1; - if (j < i) return 0; - let nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0; - else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} - -/* - * Validates as many continuation bytes for a multi-byte UTF-8 character as - * needed or are available. If we see a non-continuation byte where we expect - * one, we "replace" the validated continuation bytes we've seen so far with - * a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding - * behavior. The continuation byte check is included three times in the case - * where all of the continuation bytes for a character exist in the same buffer. - * It is also done this way as a slight performance increase instead of using a - * loop. - * */ -function utf8CheckExtraBytes( - self: StringDecoderBase, - buf: Buffer, -): string | undefined { - if ((buf[0] & 0xc0) !== 0x80) { - self.lastNeed = 0; - return "\ufffd"; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xc0) !== 0x80) { - self.lastNeed = 1; - return "\ufffd"; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xc0) !== 0x80) { - self.lastNeed = 2; - return "\ufffd"; - } - } - } -} - -/* - * Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. - * */ -function utf8FillLastComplete( - this: StringDecoderBase, - buf: Buffer, -): string | undefined { - const p = this.lastTotal - this.lastNeed; - const r = utf8CheckExtraBytes(this, buf); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} - -/* - * Attempts to complete a partial non-UTF-8 character using bytes from a Buffer - * */ -function utf8FillLastIncomplete( - this: StringDecoderBase, - buf: Buffer, -): string | undefined { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -} - -/* - * Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a - * partial character, the character's bytes are buffered until the required - * number of bytes are available. - * */ -function utf8Text(this: StringDecoderBase, buf: Buffer, i: number): string { - const total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString("utf8", i); - this.lastTotal = total; - const end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString("utf8", i, end); -} - -/* - * For UTF-8, a replacement character is added when ending on a partial - * character. - * */ -function utf8End(this: Utf8Decoder, buf?: Buffer): string { - const r = buf && buf.length ? this.write(buf) : ""; - if (this.lastNeed) return r + "\ufffd"; - return r; -} - -function utf8Write(this: Utf8Decoder | Base64Decoder, buf: Buffer): string { - if (buf.length === 0) return ""; - let r; - let i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ""; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ""; -} - -function base64Text(this: StringDecoderBase, buf: Buffer, i: number): string { - const n = (buf.length - i) % 3; - if (n === 0) return buf.toString("base64", i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString("base64", i, buf.length - n); -} - -function base64End(this: Base64Decoder, buf?: Buffer): string { - const r = buf && buf.length ? this.write(buf) : ""; - if (this.lastNeed) { - return r + this.lastChar.toString("base64", 0, 3 - this.lastNeed); - } - return r; -} - -function simpleWrite(this: StringDecoderBase, buf: Buffer): string { - return buf.toString(this.encoding); -} - -function simpleEnd(this: GenericDecoder, buf?: Buffer): string { - return buf && buf.length ? this.write(buf) : ""; -} - -class StringDecoderBase { - public lastChar: Buffer; - public lastNeed = 0; - public lastTotal = 0; - constructor(public encoding: string, nb: number) { - this.lastChar = Buffer.allocUnsafe(nb); - } -} - -class Base64Decoder extends StringDecoderBase { - public end = base64End; - public fillLast = utf8FillLastIncomplete; - public text = base64Text; - public write = utf8Write; - - constructor(encoding?: string) { - super(normalizeEncoding(encoding), 3); - } -} - -class GenericDecoder extends StringDecoderBase { - public end = simpleEnd; - public fillLast = undefined; - public text = utf8Text; - public write = simpleWrite; - - constructor(encoding?: string) { - super(normalizeEncoding(encoding), 4); - } -} - -class Utf8Decoder extends StringDecoderBase { - public end = utf8End; - public fillLast = utf8FillLastComplete; - public text = utf8Text; - public write = utf8Write; - - constructor(encoding?: string) { - super(normalizeEncoding(encoding), 4); - } -} - -/* - * StringDecoder provides an interface for efficiently splitting a series of - * buffers into a series of JS strings without breaking apart multi-byte - * characters. - * */ -export class StringDecoder { - public encoding: string; - public end: (buf?: Buffer) => string; - public fillLast: ((buf: Buffer) => string | undefined) | undefined; - public lastChar: Buffer; - public lastNeed: number; - public lastTotal: number; - public text: (buf: Buffer, n: number) => string; - public write: (buf: Buffer) => string; - - constructor(encoding?: string) { - let decoder; - switch (encoding) { - case "utf8": - decoder = new Utf8Decoder(encoding); - break; - case "base64": - decoder = new Base64Decoder(encoding); - break; - default: - decoder = new GenericDecoder(encoding); - } - this.encoding = decoder.encoding; - this.end = decoder.end; - this.fillLast = decoder.fillLast; - this.lastChar = decoder.lastChar; - this.lastNeed = decoder.lastNeed; - this.lastTotal = decoder.lastTotal; - this.text = decoder.text; - this.write = decoder.write; - } -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node_timers_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node_timers_ts.ts deleted file mode 100644 index b91985069e4..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node_timers_ts.ts +++ /dev/null @@ -1,13 +0,0 @@ -// TODO: implement the 'NodeJS.Timeout' and 'NodeJS.Immediate' versions of the timers. -// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/1163ead296d84e7a3c80d71e7c81ecbd1a130e9a/types/node/v12/globals.d.ts#L1120-L1131 -export const setTimeout = window.setTimeout; -export const clearTimeout = window.clearTimeout; -export const setInterval = window.setInterval; -export const clearInterval = window.clearInterval; -export const setImmediate = ( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - cb: (...args: any[]) => void, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - ...args: any[] -): number => window.setTimeout(cb, 0, ...args); -export const clearImmediate = window.clearTimeout; diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node_url_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node_url_ts.ts deleted file mode 100644 index 826a274f85a..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node_url_ts.ts +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -import { - CHAR_LOWERCASE_A, - CHAR_LOWERCASE_Z, - CHAR_FORWARD_SLASH, - CHAR_BACKWARD_SLASH, -} from "../path/_constants.ts"; -import * as path from "./path.ts"; - -const isWindows = Deno.build.os === "windows"; - -const forwardSlashRegEx = /\//g; -const percentRegEx = /%/g; -const backslashRegEx = /\\/g; -const newlineRegEx = /\n/g; -const carriageReturnRegEx = /\r/g; -const tabRegEx = /\t/g; - -export function fileURLToPath(path: string | URL): string { - if (typeof path === "string") path = new URL(path); - else if (!(path instanceof URL)) { - throw new Deno.errors.InvalidData( - "invalid argument path , must be a string or URL", - ); - } - if (path.protocol !== "file:") { - throw new Deno.errors.InvalidData("invalid url scheme"); - } - return isWindows ? getPathFromURLWin(path) : getPathFromURLPosix(path); -} - -function getPathFromURLWin(url: URL): string { - const hostname = url.hostname; - let pathname = url.pathname; - for (let n = 0; n < pathname.length; n++) { - if (pathname[n] === "%") { - const third = pathname.codePointAt(n + 2) || 0x20; - if ( - (pathname[n + 1] === "2" && third === 102) || // 2f 2F / - (pathname[n + 1] === "5" && third === 99) - ) { - // 5c 5C \ - throw new Deno.errors.InvalidData( - "must not include encoded \\ or / characters", - ); - } - } - } - - pathname = pathname.replace(forwardSlashRegEx, "\\"); - pathname = decodeURIComponent(pathname); - if (hostname !== "") { - //TODO add support for punycode encodings - return `\\\\${hostname}${pathname}`; - } else { - // Otherwise, it's a local path that requires a drive letter - const letter = pathname.codePointAt(1)! | 0x20; - const sep = pathname[2]; - if ( - letter < CHAR_LOWERCASE_A || - letter > CHAR_LOWERCASE_Z || // a..z A..Z - sep !== ":" - ) { - throw new Deno.errors.InvalidData("file url path must be absolute"); - } - return pathname.slice(1); - } -} - -function getPathFromURLPosix(url: URL): string { - if (url.hostname !== "") { - throw new Deno.errors.InvalidData("invalid file url hostname"); - } - const pathname = url.pathname; - for (let n = 0; n < pathname.length; n++) { - if (pathname[n] === "%") { - const third = pathname.codePointAt(n + 2) || 0x20; - if (pathname[n + 1] === "2" && third === 102) { - throw new Deno.errors.InvalidData( - "must not include encoded / characters", - ); - } - } - } - return decodeURIComponent(pathname); -} - -export function pathToFileURL(filepath: string): URL { - let resolved = path.resolve(filepath); - // path.resolve strips trailing slashes so we must add them back - const filePathLast = filepath.charCodeAt(filepath.length - 1); - if ( - (filePathLast === CHAR_FORWARD_SLASH || - (isWindows && filePathLast === CHAR_BACKWARD_SLASH)) && - resolved[resolved.length - 1] !== path.sep - ) { - resolved += "/"; - } - const outURL = new URL("file://"); - if (resolved.includes("%")) resolved = resolved.replace(percentRegEx, "%25"); - // In posix, "/" is a valid character in paths - if (!isWindows && resolved.includes("\\")) { - resolved = resolved.replace(backslashRegEx, "%5C"); - } - if (resolved.includes("\n")) resolved = resolved.replace(newlineRegEx, "%0A"); - if (resolved.includes("\r")) { - resolved = resolved.replace(carriageReturnRegEx, "%0D"); - } - if (resolved.includes("\t")) resolved = resolved.replace(tabRegEx, "%09"); - outURL.pathname = resolved; - return outURL; -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_node_util_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_node_util_ts.ts deleted file mode 100644 index 8e3c50b8791..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_node_util_ts.ts +++ /dev/null @@ -1,86 +0,0 @@ -export { promisify } from "./_util/_util_promisify.ts"; -export { callbackify } from "./_util/_util_callbackify.ts"; -import * as types from "./_util/_util_types.ts"; - -export { types }; - -export function isArray(value: unknown): boolean { - return Array.isArray(value); -} - -export function isBoolean(value: unknown): boolean { - return typeof value === "boolean" || value instanceof Boolean; -} - -export function isNull(value: unknown): boolean { - return value === null; -} - -export function isNullOrUndefined(value: unknown): boolean { - return value === null || value === undefined; -} - -export function isNumber(value: unknown): boolean { - return typeof value === "number" || value instanceof Number; -} - -export function isString(value: unknown): boolean { - return typeof value === "string" || value instanceof String; -} - -export function isSymbol(value: unknown): boolean { - return typeof value === "symbol"; -} - -export function isUndefined(value: unknown): boolean { - return value === undefined; -} - -export function isObject(value: unknown): boolean { - return value !== null && typeof value === "object"; -} - -export function isError(e: unknown): boolean { - return e instanceof Error; -} - -export function isFunction(value: unknown): boolean { - return typeof value === "function"; -} - -export function isRegExp(value: unknown): boolean { - return value instanceof RegExp; -} - -export function isPrimitive(value: unknown): boolean { - return ( - value === null || (typeof value !== "object" && typeof value !== "function") - ); -} - -export function validateIntegerRange( - value: number, - name: string, - min = -2147483648, - max = 2147483647, -): void { - // The defaults for min and max correspond to the limits of 32-bit integers. - if (!Number.isInteger(value)) { - throw new Error(`${name} must be 'an integer' but was ${value}`); - } - if (value < min || value > max) { - throw new Error( - `${name} must be >= ${min} && <= ${max}. Value was ${value}`, - ); - } -} - -import { _TextDecoder, _TextEncoder } from "./_utils.ts"; - -/** The global TextDecoder */ -export type TextDecoder = import("./_utils.ts")._TextDecoder; -export const TextDecoder = _TextDecoder; - -/** The global TextEncoder */ -export type TextEncoder = import("./_utils.ts")._TextEncoder; -export const TextEncoder = _TextEncoder; diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_path__constants_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_path__constants_ts.ts deleted file mode 100644 index 186c32ab532..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_path__constants_ts.ts +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright the Browserify authors. MIT License. -// Ported from https://github.com/browserify/path-browserify/ -/** This module is browser compatible. */ - -// Alphabet chars. -export const CHAR_UPPERCASE_A = 65; /* A */ -export const CHAR_LOWERCASE_A = 97; /* a */ -export const CHAR_UPPERCASE_Z = 90; /* Z */ -export const CHAR_LOWERCASE_Z = 122; /* z */ - -// Non-alphabetic chars. -export const CHAR_DOT = 46; /* . */ -export const CHAR_FORWARD_SLASH = 47; /* / */ -export const CHAR_BACKWARD_SLASH = 92; /* \ */ -export const CHAR_VERTICAL_LINE = 124; /* | */ -export const CHAR_COLON = 58; /* : */ -export const CHAR_QUESTION_MARK = 63; /* ? */ -export const CHAR_UNDERSCORE = 95; /* _ */ -export const CHAR_LINE_FEED = 10; /* \n */ -export const CHAR_CARRIAGE_RETURN = 13; /* \r */ -export const CHAR_TAB = 9; /* \t */ -export const CHAR_FORM_FEED = 12; /* \f */ -export const CHAR_EXCLAMATION_MARK = 33; /* ! */ -export const CHAR_HASH = 35; /* # */ -export const CHAR_SPACE = 32; /* */ -export const CHAR_NO_BREAK_SPACE = 160; /* \u00A0 */ -export const CHAR_ZERO_WIDTH_NOBREAK_SPACE = 65279; /* \uFEFF */ -export const CHAR_LEFT_SQUARE_BRACKET = 91; /* [ */ -export const CHAR_RIGHT_SQUARE_BRACKET = 93; /* ] */ -export const CHAR_LEFT_ANGLE_BRACKET = 60; /* < */ -export const CHAR_RIGHT_ANGLE_BRACKET = 62; /* > */ -export const CHAR_LEFT_CURLY_BRACKET = 123; /* { */ -export const CHAR_RIGHT_CURLY_BRACKET = 125; /* } */ -export const CHAR_HYPHEN_MINUS = 45; /* - */ -export const CHAR_PLUS = 43; /* + */ -export const CHAR_DOUBLE_QUOTE = 34; /* " */ -export const CHAR_SINGLE_QUOTE = 39; /* ' */ -export const CHAR_PERCENT = 37; /* % */ -export const CHAR_SEMICOLON = 59; /* ; */ -export const CHAR_CIRCUMFLEX_ACCENT = 94; /* ^ */ -export const CHAR_GRAVE_ACCENT = 96; /* ` */ -export const CHAR_AT = 64; /* @ */ -export const CHAR_AMPERSAND = 38; /* & */ -export const CHAR_EQUAL = 61; /* = */ - -// Digits -export const CHAR_0 = 48; /* 0 */ -export const CHAR_9 = 57; /* 9 */ - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const navigator = (globalThis as any).navigator; - -let isWindows = false; -if (globalThis.Deno != null) { - isWindows = Deno.build.os == "windows"; -} else if (navigator?.appVersion != null) { - isWindows = navigator.appVersion.includes("Win"); -} - -export { isWindows }; diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_path__globrex_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_path__globrex_ts.ts deleted file mode 100644 index 0cc5399fa23..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_path__globrex_ts.ts +++ /dev/null @@ -1,328 +0,0 @@ -// This file is ported from globrex@0.1.2 -// MIT License -// Copyright (c) 2018 Terkel Gjervig Nielsen -/** This module is browser compatible. */ - -import { isWindows as isWin } from "./_constants.ts"; - -const SEP = isWin ? `(?:\\\\|\\/)` : `\\/`; -const SEP_ESC = isWin ? `\\\\` : `/`; -const SEP_RAW = isWin ? `\\` : `/`; -const GLOBSTAR = `(?:(?:[^${SEP_ESC}/]*(?:${SEP_ESC}|\/|$))*)`; -const WILDCARD = `(?:[^${SEP_ESC}/]*)`; -const GLOBSTAR_SEGMENT = `((?:[^${SEP_ESC}/]*(?:${SEP_ESC}|\/|$))*)`; -const WILDCARD_SEGMENT = `(?:[^${SEP_ESC}/]*)`; - -export interface GlobrexOptions { - /** Allow ExtGlob features. - * @default false */ - extended?: boolean; - /** Support globstar. - * @remarks When globstar is `true`, '/foo/**' is equivalent - * to '/foo/*' when globstar is `false`. - * Having globstar set to `true` is the same usage as - * using wildcards in bash. - * @default false */ - globstar?: boolean; - /** Be laissez-faire about mutiple slashes. - * @default true */ - strict?: boolean; - /** Parse as filepath for extra path related features. - * @default false */ - filepath?: boolean; - /** Flag to use in the generated RegExp. */ - flags?: string; -} - -export interface GlobrexResult { - regex: RegExp; - path?: { - regex: RegExp; - segments: RegExp[]; - globstar?: RegExp; - }; -} - -/** - * Convert any glob pattern to a JavaScript Regexp object - * @param glob Glob pattern to convert - * @param opts Configuration object - * @returns Converted object with string, segments and RegExp object - */ -export function globrex( - glob: string, - { - extended = false, - globstar = false, - strict = false, - filepath = false, - flags = "", - }: GlobrexOptions = {}, -): GlobrexResult { - const sepPattern = new RegExp(`^${SEP}${strict ? "" : "+"}$`); - let regex = ""; - let segment = ""; - let pathRegexStr = ""; - const pathSegments = []; - - // If we are doing extended matching, this boolean is true when we are inside - // a group (eg {*.html,*.js}), and false otherwise. - let inGroup = false; - let inRange = false; - - // extglob stack. Keep track of scope - const ext = []; - - interface AddOptions { - split?: boolean; - last?: boolean; - only?: string; - } - - // Helper function to build string and segments - function add( - str: string, - options: AddOptions = { split: false, last: false, only: "" }, - ): void { - const { split, last, only } = options; - if (only !== "path") regex += str; - if (filepath && only !== "regex") { - pathRegexStr += str.match(sepPattern) ? SEP : str; - if (split) { - if (last) segment += str; - if (segment !== "") { - // change it 'includes' - if (!flags.includes("g")) segment = `^${segment}$`; - pathSegments.push(new RegExp(segment, flags)); - } - segment = ""; - } else { - segment += str; - } - } - } - - let c, n; - for (let i = 0; i < glob.length; i++) { - c = glob[i]; - n = glob[i + 1]; - - if (["\\", "$", "^", ".", "="].includes(c)) { - add(`\\${c}`); - continue; - } - - if (c.match(sepPattern)) { - add(SEP, { split: true }); - if (n != null && n.match(sepPattern) && !strict) regex += "?"; - continue; - } - - if (c === "(") { - if (ext.length) { - add(`${c}?:`); - continue; - } - add(`\\${c}`); - continue; - } - - if (c === ")") { - if (ext.length) { - add(c); - const type: string | undefined = ext.pop(); - if (type === "@") { - add("{1}"); - } else if (type === "!") { - add(WILDCARD); - } else { - add(type as string); - } - continue; - } - add(`\\${c}`); - continue; - } - - if (c === "|") { - if (ext.length) { - add(c); - continue; - } - add(`\\${c}`); - continue; - } - - if (c === "+") { - if (n === "(" && extended) { - ext.push(c); - continue; - } - add(`\\${c}`); - continue; - } - - if (c === "@" && extended) { - if (n === "(") { - ext.push(c); - continue; - } - } - - if (c === "!") { - if (extended) { - if (inRange) { - add("^"); - continue; - } - if (n === "(") { - ext.push(c); - add("(?!"); - i++; - continue; - } - add(`\\${c}`); - continue; - } - add(`\\${c}`); - continue; - } - - if (c === "?") { - if (extended) { - if (n === "(") { - ext.push(c); - } else { - add("."); - } - continue; - } - add(`\\${c}`); - continue; - } - - if (c === "[") { - if (inRange && n === ":") { - i++; // skip [ - let value = ""; - while (glob[++i] !== ":") value += glob[i]; - if (value === "alnum") add("(?:\\w|\\d)"); - else if (value === "space") add("\\s"); - else if (value === "digit") add("\\d"); - i++; // skip last ] - continue; - } - if (extended) { - inRange = true; - add(c); - continue; - } - add(`\\${c}`); - continue; - } - - if (c === "]") { - if (extended) { - inRange = false; - add(c); - continue; - } - add(`\\${c}`); - continue; - } - - if (c === "{") { - if (extended) { - inGroup = true; - add("(?:"); - continue; - } - add(`\\${c}`); - continue; - } - - if (c === "}") { - if (extended) { - inGroup = false; - add(")"); - continue; - } - add(`\\${c}`); - continue; - } - - if (c === ",") { - if (inGroup) { - add("|"); - continue; - } - add(`\\${c}`); - continue; - } - - if (c === "*") { - if (n === "(" && extended) { - ext.push(c); - continue; - } - // Move over all consecutive "*"'s. - // Also store the previous and next characters - const prevChar = glob[i - 1]; - let starCount = 1; - while (glob[i + 1] === "*") { - starCount++; - i++; - } - const nextChar = glob[i + 1]; - if (!globstar) { - // globstar is disabled, so treat any number of "*" as one - add(".*"); - } else { - // globstar is enabled, so determine if this is a globstar segment - const isGlobstar = starCount > 1 && // multiple "*"'s - // from the start of the segment - [SEP_RAW, "/", undefined].includes(prevChar) && - // to the end of the segment - [SEP_RAW, "/", undefined].includes(nextChar); - if (isGlobstar) { - // it's a globstar, so match zero or more path segments - add(GLOBSTAR, { only: "regex" }); - add(GLOBSTAR_SEGMENT, { only: "path", last: true, split: true }); - i++; // move over the "/" - } else { - // it's not a globstar, so only match one path segment - add(WILDCARD, { only: "regex" }); - add(WILDCARD_SEGMENT, { only: "path" }); - } - } - continue; - } - - add(c); - } - - // When regexp 'g' flag is specified don't - // constrain the regular expression with ^ & $ - if (!flags.includes("g")) { - regex = `^${regex}$`; - segment = `^${segment}$`; - if (filepath) pathRegexStr = `^${pathRegexStr}$`; - } - - const result: GlobrexResult = { regex: new RegExp(regex, flags) }; - - // Push the last segment - if (filepath) { - pathSegments.push(new RegExp(segment, flags)); - result.path = { - regex: new RegExp(pathRegexStr, flags), - segments: pathSegments, - globstar: new RegExp( - !flags.includes("g") ? `^${GLOBSTAR_SEGMENT}$` : GLOBSTAR_SEGMENT, - flags, - ), - }; - } - - return result; -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_path__interface_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_path__interface_ts.ts deleted file mode 100644 index 6c82c9c35cf..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_path__interface_ts.ts +++ /dev/null @@ -1,29 +0,0 @@ -/** This module is browser compatible. */ - -/** - * A parsed path object generated by path.parse() or consumed by path.format(). - */ -export interface ParsedPath { - /** - * The root of the path such as '/' or 'c:\' - */ - root: string; - /** - * The full directory path such as '/home/user/dir' or 'c:\path\dir' - */ - dir: string; - /** - * The file name including extension (if any) such as 'index.html' - */ - base: string; - /** - * The file extension (if any) such as '.html' - */ - ext: string; - /** - * The file name without extension (if any) such as 'index' - */ - name: string; -} - -export type FormatInputPathObject = Partial; diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_path__util_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_path__util_ts.ts deleted file mode 100644 index ead425a0b83..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_path__util_ts.ts +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright the Browserify authors. MIT License. -// Ported from https://github.com/browserify/path-browserify/ -/** This module is browser compatible. */ - -import type { FormatInputPathObject } from "./_interface.ts"; -import { - CHAR_UPPERCASE_A, - CHAR_LOWERCASE_A, - CHAR_UPPERCASE_Z, - CHAR_LOWERCASE_Z, - CHAR_DOT, - CHAR_FORWARD_SLASH, - CHAR_BACKWARD_SLASH, -} from "./_constants.ts"; - -export function assertPath(path: string): void { - if (typeof path !== "string") { - throw new TypeError( - `Path must be a string. Received ${JSON.stringify(path)}`, - ); - } -} - -export function isPosixPathSeparator(code: number): boolean { - return code === CHAR_FORWARD_SLASH; -} - -export function isPathSeparator(code: number): boolean { - return isPosixPathSeparator(code) || code === CHAR_BACKWARD_SLASH; -} - -export function isWindowsDeviceRoot(code: number): boolean { - return ( - (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z) || - (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) - ); -} - -// Resolves . and .. elements in a path with directory names -export function normalizeString( - path: string, - allowAboveRoot: boolean, - separator: string, - isPathSeparator: (code: number) => boolean, -): string { - let res = ""; - let lastSegmentLength = 0; - let lastSlash = -1; - let dots = 0; - let code: number | undefined; - for (let i = 0, len = path.length; i <= len; ++i) { - if (i < len) code = path.charCodeAt(i); - else if (isPathSeparator(code!)) break; - else code = CHAR_FORWARD_SLASH; - - if (isPathSeparator(code!)) { - if (lastSlash === i - 1 || dots === 1) { - // NOOP - } else if (lastSlash !== i - 1 && dots === 2) { - if ( - res.length < 2 || - lastSegmentLength !== 2 || - res.charCodeAt(res.length - 1) !== CHAR_DOT || - res.charCodeAt(res.length - 2) !== CHAR_DOT - ) { - if (res.length > 2) { - const lastSlashIndex = res.lastIndexOf(separator); - if (lastSlashIndex === -1) { - res = ""; - lastSegmentLength = 0; - } else { - res = res.slice(0, lastSlashIndex); - lastSegmentLength = res.length - 1 - res.lastIndexOf(separator); - } - lastSlash = i; - dots = 0; - continue; - } else if (res.length === 2 || res.length === 1) { - res = ""; - lastSegmentLength = 0; - lastSlash = i; - dots = 0; - continue; - } - } - if (allowAboveRoot) { - if (res.length > 0) res += `${separator}..`; - else res = ".."; - lastSegmentLength = 2; - } - } else { - if (res.length > 0) res += separator + path.slice(lastSlash + 1, i); - else res = path.slice(lastSlash + 1, i); - lastSegmentLength = i - lastSlash - 1; - } - lastSlash = i; - dots = 0; - } else if (code === CHAR_DOT && dots !== -1) { - ++dots; - } else { - dots = -1; - } - } - return res; -} - -export function _format( - sep: string, - pathObject: FormatInputPathObject, -): string { - const dir: string | undefined = pathObject.dir || pathObject.root; - const base: string = pathObject.base || - (pathObject.name || "") + (pathObject.ext || ""); - if (!dir) return base; - if (dir === pathObject.root) return dir + base; - return dir + sep + base; -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_path_common_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_path_common_ts.ts deleted file mode 100644 index 01470105ca9..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_path_common_ts.ts +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -/** This module is browser compatible. */ - -import { SEP } from "./separator.ts"; - -/** Determines the common path from a set of paths, using an optional separator, - * which defaults to the OS default separator. - * - * import { common } from "https://deno.land/std/path/mod.ts"; - * const p = common([ - * "./deno/std/path/mod.ts", - * "./deno/std/fs/mod.ts", - * ]); - * console.log(p); // "./deno/std/" - * - */ -export function common(paths: string[], sep = SEP): string { - const [first = "", ...remaining] = paths; - if (first === "" || remaining.length === 0) { - return first.substring(0, first.lastIndexOf(sep) + 1); - } - const parts = first.split(sep); - - let endOfPrefix = parts.length; - for (const path of remaining) { - const compare = path.split(sep); - for (let i = 0; i < endOfPrefix; i++) { - if (compare[i] !== parts[i]) { - endOfPrefix = i; - } - } - - if (endOfPrefix === 0) { - return ""; - } - } - const prefix = parts.slice(0, endOfPrefix).join(sep); - return prefix.endsWith(sep) ? prefix : `${prefix}${sep}`; -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_path_glob_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_path_glob_ts.ts deleted file mode 100644 index 1725876268d..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_path_glob_ts.ts +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -/** This module is browser compatible. */ - -import { SEP, SEP_PATTERN } from "./separator.ts"; -import { globrex } from "./_globrex.ts"; -import { join, normalize } from "./mod.ts"; -import { assert } from "../_util/assert.ts"; - -export interface GlobOptions { - extended?: boolean; - globstar?: boolean; -} - -export interface GlobToRegExpOptions extends GlobOptions { - flags?: string; -} - -/** - * Generate a regex based on glob pattern and options - * This was meant to be using the the `fs.walk` function - * but can be used anywhere else. - * Examples: - * - * Looking for all the `ts` files: - * walkSync(".", { - * match: [globToRegExp("*.ts")] - * }) - * - * Looking for all the `.json` files in any subfolder: - * walkSync(".", { - * match: [globToRegExp(join("a", "**", "*.json"),{ - * flags: "g", - * extended: true, - * globstar: true - * })] - * }) - * - * @param glob - Glob pattern to be used - * @param options - Specific options for the glob pattern - * @returns A RegExp for the glob pattern - */ -export function globToRegExp( - glob: string, - { extended = false, globstar = true }: GlobToRegExpOptions = {}, -): RegExp { - const result = globrex(glob, { - extended, - globstar, - strict: false, - filepath: true, - }); - assert(result.path != null); - return result.path.regex; -} - -/** Test whether the given string is a glob */ -export function isGlob(str: string): boolean { - const chars: Record = { "{": "}", "(": ")", "[": "]" }; - /* eslint-disable-next-line max-len */ - const regex = - /\\(.)|(^!|\*|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\)|\([^|]+\|[^\\)]+\))/; - - if (str === "") { - return false; - } - - let match: RegExpExecArray | null; - - while ((match = regex.exec(str))) { - if (match[2]) return true; - let idx = match.index + match[0].length; - - // if an open bracket/brace/paren is escaped, - // set the index to the next closing character - const open = match[1]; - const close = open ? chars[open] : null; - if (open && close) { - const n = str.indexOf(close, idx); - if (n !== -1) { - idx = n + 1; - } - } - - str = str.slice(idx); - } - - return false; -} - -/** Like normalize(), but doesn't collapse "**\/.." when `globstar` is true. */ -export function normalizeGlob( - glob: string, - { globstar = false }: GlobOptions = {}, -): string { - if (glob.match(/\0/g)) { - throw new Error(`Glob contains invalid characters: "${glob}"`); - } - if (!globstar) { - return normalize(glob); - } - const s = SEP_PATTERN.source; - const badParentPattern = new RegExp( - `(?<=(${s}|^)\\*\\*${s})\\.\\.(?=${s}|$)`, - "g", - ); - return normalize(glob.replace(badParentPattern, "\0")).replace(/\0/g, ".."); -} - -/** Like join(), but doesn't collapse "**\/.." when `globstar` is true. */ -export function joinGlobs( - globs: string[], - { extended = false, globstar = false }: GlobOptions = {}, -): string { - if (!globstar || globs.length == 0) { - return join(...globs); - } - if (globs.length === 0) return "."; - let joined: string | undefined; - for (const glob of globs) { - const path = glob; - if (path.length > 0) { - if (!joined) joined = path; - else joined += `${SEP}${path}`; - } - } - if (!joined) return "."; - return normalizeGlob(joined, { extended, globstar }); -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_path_mod_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_path_mod_ts.ts deleted file mode 100644 index 0b4156e6998..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_path_mod_ts.ts +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright the Browserify authors. MIT License. -// Ported mostly from https://github.com/browserify/path-browserify/ -/** This module is browser compatible. */ - -import { isWindows } from "./_constants.ts"; -import * as _win32 from "./win32.ts"; -import * as _posix from "./posix.ts"; - -const path = isWindows ? _win32 : _posix; - -export const win32 = _win32; -export const posix = _posix; -export const { - basename, - delimiter, - dirname, - extname, - format, - fromFileUrl, - isAbsolute, - join, - normalize, - parse, - relative, - resolve, - sep, - toNamespacedPath, -} = path; - -export * from "./common.ts"; -export { SEP, SEP_PATTERN } from "./separator.ts"; -export * from "./_interface.ts"; -export * from "./glob.ts"; diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_path_posix_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_path_posix_ts.ts deleted file mode 100644 index afbc9303f2a..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_path_posix_ts.ts +++ /dev/null @@ -1,440 +0,0 @@ -// Copyright the Browserify authors. MIT License. -// Ported from https://github.com/browserify/path-browserify/ -/** This module is browser compatible. */ - -import type { FormatInputPathObject, ParsedPath } from "./_interface.ts"; -import { CHAR_DOT, CHAR_FORWARD_SLASH } from "./_constants.ts"; - -import { - assertPath, - normalizeString, - isPosixPathSeparator, - _format, -} from "./_util.ts"; - -export const sep = "/"; -export const delimiter = ":"; - -// path.resolve([from ...], to) -export function resolve(...pathSegments: string[]): string { - let resolvedPath = ""; - let resolvedAbsolute = false; - - for (let i = pathSegments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - let path: string; - - if (i >= 0) path = pathSegments[i]; - else { - if (globalThis.Deno == null) { - throw new TypeError("Resolved a relative path without a CWD."); - } - path = Deno.cwd(); - } - - assertPath(path); - - // Skip empty entries - if (path.length === 0) { - continue; - } - - resolvedPath = `${path}/${resolvedPath}`; - resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; - } - - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - - // Normalize the path - resolvedPath = normalizeString( - resolvedPath, - !resolvedAbsolute, - "/", - isPosixPathSeparator, - ); - - if (resolvedAbsolute) { - if (resolvedPath.length > 0) return `/${resolvedPath}`; - else return "/"; - } else if (resolvedPath.length > 0) return resolvedPath; - else return "."; -} - -export function normalize(path: string): string { - assertPath(path); - - if (path.length === 0) return "."; - - const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; - const trailingSeparator = - path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH; - - // Normalize the path - path = normalizeString(path, !isAbsolute, "/", isPosixPathSeparator); - - if (path.length === 0 && !isAbsolute) path = "."; - if (path.length > 0 && trailingSeparator) path += "/"; - - if (isAbsolute) return `/${path}`; - return path; -} - -export function isAbsolute(path: string): boolean { - assertPath(path); - return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH; -} - -export function join(...paths: string[]): string { - if (paths.length === 0) return "."; - let joined: string | undefined; - for (let i = 0, len = paths.length; i < len; ++i) { - const path = paths[i]; - assertPath(path); - if (path.length > 0) { - if (!joined) joined = path; - else joined += `/${path}`; - } - } - if (!joined) return "."; - return normalize(joined); -} - -export function relative(from: string, to: string): string { - assertPath(from); - assertPath(to); - - if (from === to) return ""; - - from = resolve(from); - to = resolve(to); - - if (from === to) return ""; - - // Trim any leading backslashes - let fromStart = 1; - const fromEnd = from.length; - for (; fromStart < fromEnd; ++fromStart) { - if (from.charCodeAt(fromStart) !== CHAR_FORWARD_SLASH) break; - } - const fromLen = fromEnd - fromStart; - - // Trim any leading backslashes - let toStart = 1; - const toEnd = to.length; - for (; toStart < toEnd; ++toStart) { - if (to.charCodeAt(toStart) !== CHAR_FORWARD_SLASH) break; - } - const toLen = toEnd - toStart; - - // Compare paths to find the longest common path from root - const length = fromLen < toLen ? fromLen : toLen; - let lastCommonSep = -1; - let i = 0; - for (; i <= length; ++i) { - if (i === length) { - if (toLen > length) { - if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) { - // We get here if `from` is the exact base path for `to`. - // For example: from='/foo/bar'; to='/foo/bar/baz' - return to.slice(toStart + i + 1); - } else if (i === 0) { - // We get here if `from` is the root - // For example: from='/'; to='/foo' - return to.slice(toStart + i); - } - } else if (fromLen > length) { - if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) { - // We get here if `to` is the exact base path for `from`. - // For example: from='/foo/bar/baz'; to='/foo/bar' - lastCommonSep = i; - } else if (i === 0) { - // We get here if `to` is the root. - // For example: from='/foo'; to='/' - lastCommonSep = 0; - } - } - break; - } - const fromCode = from.charCodeAt(fromStart + i); - const toCode = to.charCodeAt(toStart + i); - if (fromCode !== toCode) break; - else if (fromCode === CHAR_FORWARD_SLASH) lastCommonSep = i; - } - - let out = ""; - // Generate the relative path based on the path difference between `to` - // and `from` - for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { - if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) { - if (out.length === 0) out += ".."; - else out += "/.."; - } - } - - // Lastly, append the rest of the destination (`to`) path that comes after - // the common path parts - if (out.length > 0) return out + to.slice(toStart + lastCommonSep); - else { - toStart += lastCommonSep; - if (to.charCodeAt(toStart) === CHAR_FORWARD_SLASH) ++toStart; - return to.slice(toStart); - } -} - -export function toNamespacedPath(path: string): string { - // Non-op on posix systems - return path; -} - -export function dirname(path: string): string { - assertPath(path); - if (path.length === 0) return "."; - const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH; - let end = -1; - let matchedSlash = true; - for (let i = path.length - 1; i >= 1; --i) { - if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { - if (!matchedSlash) { - end = i; - break; - } - } else { - // We saw the first non-path separator - matchedSlash = false; - } - } - - if (end === -1) return hasRoot ? "/" : "."; - if (hasRoot && end === 1) return "//"; - return path.slice(0, end); -} - -export function basename(path: string, ext = ""): string { - if (ext !== undefined && typeof ext !== "string") { - throw new TypeError('"ext" argument must be a string'); - } - assertPath(path); - - let start = 0; - let end = -1; - let matchedSlash = true; - let i: number; - - if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { - if (ext.length === path.length && ext === path) return ""; - let extIdx = ext.length - 1; - let firstNonSlashEnd = -1; - for (i = path.length - 1; i >= 0; --i) { - const code = path.charCodeAt(i); - if (code === CHAR_FORWARD_SLASH) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - start = i + 1; - break; - } - } else { - if (firstNonSlashEnd === -1) { - // We saw the first non-path separator, remember this index in case - // we need it if the extension ends up not matching - matchedSlash = false; - firstNonSlashEnd = i + 1; - } - if (extIdx >= 0) { - // Try to match the explicit extension - if (code === ext.charCodeAt(extIdx)) { - if (--extIdx === -1) { - // We matched the extension, so mark this as the end of our path - // component - end = i; - } - } else { - // Extension does not match, so our result is the entire path - // component - extIdx = -1; - end = firstNonSlashEnd; - } - } - } - } - - if (start === end) end = firstNonSlashEnd; - else if (end === -1) end = path.length; - return path.slice(start, end); - } else { - for (i = path.length - 1; i >= 0; --i) { - if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - start = i + 1; - break; - } - } else if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // path component - matchedSlash = false; - end = i + 1; - } - } - - if (end === -1) return ""; - return path.slice(start, end); - } -} - -export function extname(path: string): string { - assertPath(path); - let startDot = -1; - let startPart = 0; - let end = -1; - let matchedSlash = true; - // Track the state of characters (if any) we see before our first dot and - // after any path separator we find - let preDotState = 0; - for (let i = path.length - 1; i >= 0; --i) { - const code = path.charCodeAt(i); - if (code === CHAR_FORWARD_SLASH) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - startPart = i + 1; - break; - } - continue; - } - if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // extension - matchedSlash = false; - end = i + 1; - } - if (code === CHAR_DOT) { - // If this is our first dot, mark it as the start of our extension - if (startDot === -1) startDot = i; - else if (preDotState !== 1) preDotState = 1; - } else if (startDot !== -1) { - // We saw a non-dot and non-path separator before our dot, so we should - // have a good chance at having a non-empty extension - preDotState = -1; - } - } - - if ( - startDot === -1 || - end === -1 || - // We saw a non-dot character immediately before the dot - preDotState === 0 || - // The (right-most) trimmed path component is exactly '..' - (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) - ) { - return ""; - } - return path.slice(startDot, end); -} - -export function format(pathObject: FormatInputPathObject): string { - /* eslint-disable max-len */ - if (pathObject === null || typeof pathObject !== "object") { - throw new TypeError( - `The "pathObject" argument must be of type Object. Received type ${typeof pathObject}`, - ); - } - return _format("/", pathObject); -} - -export function parse(path: string): ParsedPath { - assertPath(path); - - const ret: ParsedPath = { root: "", dir: "", base: "", ext: "", name: "" }; - if (path.length === 0) return ret; - const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; - let start: number; - if (isAbsolute) { - ret.root = "/"; - start = 1; - } else { - start = 0; - } - let startDot = -1; - let startPart = 0; - let end = -1; - let matchedSlash = true; - let i = path.length - 1; - - // Track the state of characters (if any) we see before our first dot and - // after any path separator we find - let preDotState = 0; - - // Get non-dir info - for (; i >= start; --i) { - const code = path.charCodeAt(i); - if (code === CHAR_FORWARD_SLASH) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - startPart = i + 1; - break; - } - continue; - } - if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // extension - matchedSlash = false; - end = i + 1; - } - if (code === CHAR_DOT) { - // If this is our first dot, mark it as the start of our extension - if (startDot === -1) startDot = i; - else if (preDotState !== 1) preDotState = 1; - } else if (startDot !== -1) { - // We saw a non-dot and non-path separator before our dot, so we should - // have a good chance at having a non-empty extension - preDotState = -1; - } - } - - if ( - startDot === -1 || - end === -1 || - // We saw a non-dot character immediately before the dot - preDotState === 0 || - // The (right-most) trimmed path component is exactly '..' - (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) - ) { - if (end !== -1) { - if (startPart === 0 && isAbsolute) { - ret.base = ret.name = path.slice(1, end); - } else { - ret.base = ret.name = path.slice(startPart, end); - } - } - } else { - if (startPart === 0 && isAbsolute) { - ret.name = path.slice(1, startDot); - ret.base = path.slice(1, end); - } else { - ret.name = path.slice(startPart, startDot); - ret.base = path.slice(startPart, end); - } - ret.ext = path.slice(startDot, end); - } - - if (startPart > 0) ret.dir = path.slice(0, startPart - 1); - else if (isAbsolute) ret.dir = "/"; - - return ret; -} - -/** Converts a file URL to a path string. - * - * fromFileUrl("file:///home/foo"); // "/home/foo" - */ -export function fromFileUrl(url: string | URL): string { - url = url instanceof URL ? url : new URL(url); - if (url.protocol != "file:") { - throw new TypeError("Must be a file URL."); - } - return decodeURIComponent(url.pathname); -} diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_path_separator_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_path_separator_ts.ts deleted file mode 100644 index 4b54ad4384b..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_path_separator_ts.ts +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. -/** This module is browser compatible. */ - -import { isWindows } from "./_constants.ts"; - -export const SEP = isWindows ? "\\" : "/"; -export const SEP_PATTERN = isWindows ? /[\\/]+/ : /\/+/; diff --git a/scripts/build/deno-cache/deno_land_std_0_63_0_path_win32_ts.ts b/scripts/build/deno-cache/deno_land_std_0_63_0_path_win32_ts.ts deleted file mode 100644 index eed1cbdb82e..00000000000 --- a/scripts/build/deno-cache/deno_land_std_0_63_0_path_win32_ts.ts +++ /dev/null @@ -1,931 +0,0 @@ -// Copyright the Browserify authors. MIT License. -// Ported from https://github.com/browserify/path-browserify/ -/** This module is browser compatible. */ - -import type { FormatInputPathObject, ParsedPath } from "./_interface.ts"; -import { - CHAR_DOT, - CHAR_BACKWARD_SLASH, - CHAR_COLON, - CHAR_QUESTION_MARK, -} from "./_constants.ts"; - -import { - assertPath, - isPathSeparator, - isWindowsDeviceRoot, - normalizeString, - _format, -} from "./_util.ts"; -import { assert } from "../_util/assert.ts"; - -export const sep = "\\"; -export const delimiter = ";"; - -export function resolve(...pathSegments: string[]): string { - let resolvedDevice = ""; - let resolvedTail = ""; - let resolvedAbsolute = false; - - for (let i = pathSegments.length - 1; i >= -1; i--) { - let path: string; - if (i >= 0) { - path = pathSegments[i]; - } else if (!resolvedDevice) { - if (globalThis.Deno == null) { - throw new TypeError("Resolved a drive-letter-less path without a CWD."); - } - path = Deno.cwd(); - } else { - if (globalThis.Deno == null) { - throw new TypeError("Resolved a relative path without a CWD."); - } - // Windows has the concept of drive-specific current working - // directories. If we've resolved a drive letter but not yet an - // absolute path, get cwd for that drive, or the process cwd if - // the drive cwd is not available. We're sure the device is not - // a UNC path at this points, because UNC paths are always absolute. - path = Deno.env.get(`=${resolvedDevice}`) || Deno.cwd(); - - // Verify that a cwd was found and that it actually points - // to our drive. If not, default to the drive's root. - if ( - path === undefined || - path.slice(0, 3).toLowerCase() !== `${resolvedDevice.toLowerCase()}\\` - ) { - path = `${resolvedDevice}\\`; - } - } - - assertPath(path); - - const len = path.length; - - // Skip empty entries - if (len === 0) continue; - - let rootEnd = 0; - let device = ""; - let isAbsolute = false; - const code = path.charCodeAt(0); - - // Try to match a root - if (len > 1) { - if (isPathSeparator(code)) { - // Possible UNC root - - // If we started with a separator, we know we at least have an - // absolute path of some kind (UNC or otherwise) - isAbsolute = true; - - if (isPathSeparator(path.charCodeAt(1))) { - // Matched double path separator at beginning - let j = 2; - let last = j; - // Match 1 or more non-path separators - for (; j < len; ++j) { - if (isPathSeparator(path.charCodeAt(j))) break; - } - if (j < len && j !== last) { - const firstPart = path.slice(last, j); - // Matched! - last = j; - // Match 1 or more path separators - for (; j < len; ++j) { - if (!isPathSeparator(path.charCodeAt(j))) break; - } - if (j < len && j !== last) { - // Matched! - last = j; - // Match 1 or more non-path separators - for (; j < len; ++j) { - if (isPathSeparator(path.charCodeAt(j))) break; - } - if (j === len) { - // We matched a UNC root only - device = `\\\\${firstPart}\\${path.slice(last)}`; - rootEnd = j; - } else if (j !== last) { - // We matched a UNC root with leftovers - - device = `\\\\${firstPart}\\${path.slice(last, j)}`; - rootEnd = j; - } - } - } - } else { - rootEnd = 1; - } - } else if (isWindowsDeviceRoot(code)) { - // Possible device root - - if (path.charCodeAt(1) === CHAR_COLON) { - device = path.slice(0, 2); - rootEnd = 2; - if (len > 2) { - if (isPathSeparator(path.charCodeAt(2))) { - // Treat separator following drive name as an absolute path - // indicator - isAbsolute = true; - rootEnd = 3; - } - } - } - } - } else if (isPathSeparator(code)) { - // `path` contains just a path separator - rootEnd = 1; - isAbsolute = true; - } - - if ( - device.length > 0 && - resolvedDevice.length > 0 && - device.toLowerCase() !== resolvedDevice.toLowerCase() - ) { - // This path points to another device so it is not applicable - continue; - } - - if (resolvedDevice.length === 0 && device.length > 0) { - resolvedDevice = device; - } - if (!resolvedAbsolute) { - resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`; - resolvedAbsolute = isAbsolute; - } - - if (resolvedAbsolute && resolvedDevice.length > 0) break; - } - - // At this point the path should be resolved to a full absolute path, - // but handle relative paths to be safe (might happen when process.cwd() - // fails) - - // Normalize the tail path - resolvedTail = normalizeString( - resolvedTail, - !resolvedAbsolute, - "\\", - isPathSeparator, - ); - - return resolvedDevice + (resolvedAbsolute ? "\\" : "") + resolvedTail || "."; -} - -export function normalize(path: string): string { - assertPath(path); - const len = path.length; - if (len === 0) return "."; - let rootEnd = 0; - let device: string | undefined; - let isAbsolute = false; - const code = path.charCodeAt(0); - - // Try to match a root - if (len > 1) { - if (isPathSeparator(code)) { - // Possible UNC root - - // If we started with a separator, we know we at least have an absolute - // path of some kind (UNC or otherwise) - isAbsolute = true; - - if (isPathSeparator(path.charCodeAt(1))) { - // Matched double path separator at beginning - let j = 2; - let last = j; - // Match 1 or more non-path separators - for (; j < len; ++j) { - if (isPathSeparator(path.charCodeAt(j))) break; - } - if (j < len && j !== last) { - const firstPart = path.slice(last, j); - // Matched! - last = j; - // Match 1 or more path separators - for (; j < len; ++j) { - if (!isPathSeparator(path.charCodeAt(j))) break; - } - if (j < len && j !== last) { - // Matched! - last = j; - // Match 1 or more non-path separators - for (; j < len; ++j) { - if (isPathSeparator(path.charCodeAt(j))) break; - } - if (j === len) { - // We matched a UNC root only - // Return the normalized version of the UNC root since there - // is nothing left to process - - return `\\\\${firstPart}\\${path.slice(last)}\\`; - } else if (j !== last) { - // We matched a UNC root with leftovers - - device = `\\\\${firstPart}\\${path.slice(last, j)}`; - rootEnd = j; - } - } - } - } else { - rootEnd = 1; - } - } else if (isWindowsDeviceRoot(code)) { - // Possible device root - - if (path.charCodeAt(1) === CHAR_COLON) { - device = path.slice(0, 2); - rootEnd = 2; - if (len > 2) { - if (isPathSeparator(path.charCodeAt(2))) { - // Treat separator following drive name as an absolute path - // indicator - isAbsolute = true; - rootEnd = 3; - } - } - } - } - } else if (isPathSeparator(code)) { - // `path` contains just a path separator, exit early to avoid unnecessary - // work - return "\\"; - } - - let tail: string; - if (rootEnd < len) { - tail = normalizeString( - path.slice(rootEnd), - !isAbsolute, - "\\", - isPathSeparator, - ); - } else { - tail = ""; - } - if (tail.length === 0 && !isAbsolute) tail = "."; - if (tail.length > 0 && isPathSeparator(path.charCodeAt(len - 1))) { - tail += "\\"; - } - if (device === undefined) { - if (isAbsolute) { - if (tail.length > 0) return `\\${tail}`; - else return "\\"; - } else if (tail.length > 0) { - return tail; - } else { - return ""; - } - } else if (isAbsolute) { - if (tail.length > 0) return `${device}\\${tail}`; - else return `${device}\\`; - } else if (tail.length > 0) { - return device + tail; - } else { - return device; - } -} - -export function isAbsolute(path: string): boolean { - assertPath(path); - const len = path.length; - if (len === 0) return false; - - const code = path.charCodeAt(0); - if (isPathSeparator(code)) { - return true; - } else if (isWindowsDeviceRoot(code)) { - // Possible device root - - if (len > 2 && path.charCodeAt(1) === CHAR_COLON) { - if (isPathSeparator(path.charCodeAt(2))) return true; - } - } - return false; -} - -export function join(...paths: string[]): string { - const pathsCount = paths.length; - if (pathsCount === 0) return "."; - - let joined: string | undefined; - let firstPart: string | null = null; - for (let i = 0; i < pathsCount; ++i) { - const path = paths[i]; - assertPath(path); - if (path.length > 0) { - if (joined === undefined) joined = firstPart = path; - else joined += `\\${path}`; - } - } - - if (joined === undefined) return "."; - - // Make sure that the joined path doesn't start with two slashes, because - // normalize() will mistake it for an UNC path then. - // - // This step is skipped when it is very clear that the user actually - // intended to point at an UNC path. This is assumed when the first - // non-empty string arguments starts with exactly two slashes followed by - // at least one more non-slash character. - // - // Note that for normalize() to treat a path as an UNC path it needs to - // have at least 2 components, so we don't filter for that here. - // This means that the user can use join to construct UNC paths from - // a server name and a share name; for example: - // path.join('//server', 'share') -> '\\\\server\\share\\') - let needsReplace = true; - let slashCount = 0; - assert(firstPart != null); - if (isPathSeparator(firstPart.charCodeAt(0))) { - ++slashCount; - const firstLen = firstPart.length; - if (firstLen > 1) { - if (isPathSeparator(firstPart.charCodeAt(1))) { - ++slashCount; - if (firstLen > 2) { - if (isPathSeparator(firstPart.charCodeAt(2))) ++slashCount; - else { - // We matched a UNC path in the first part - needsReplace = false; - } - } - } - } - } - if (needsReplace) { - // Find any more consecutive slashes we need to replace - for (; slashCount < joined.length; ++slashCount) { - if (!isPathSeparator(joined.charCodeAt(slashCount))) break; - } - - // Replace the slashes if needed - if (slashCount >= 2) joined = `\\${joined.slice(slashCount)}`; - } - - return normalize(joined); -} - -// It will solve the relative path from `from` to `to`, for instance: -// from = 'C:\\orandea\\test\\aaa' -// to = 'C:\\orandea\\impl\\bbb' -// The output of the function should be: '..\\..\\impl\\bbb' -export function relative(from: string, to: string): string { - assertPath(from); - assertPath(to); - - if (from === to) return ""; - - const fromOrig = resolve(from); - const toOrig = resolve(to); - - if (fromOrig === toOrig) return ""; - - from = fromOrig.toLowerCase(); - to = toOrig.toLowerCase(); - - if (from === to) return ""; - - // Trim any leading backslashes - let fromStart = 0; - let fromEnd = from.length; - for (; fromStart < fromEnd; ++fromStart) { - if (from.charCodeAt(fromStart) !== CHAR_BACKWARD_SLASH) break; - } - // Trim trailing backslashes (applicable to UNC paths only) - for (; fromEnd - 1 > fromStart; --fromEnd) { - if (from.charCodeAt(fromEnd - 1) !== CHAR_BACKWARD_SLASH) break; - } - const fromLen = fromEnd - fromStart; - - // Trim any leading backslashes - let toStart = 0; - let toEnd = to.length; - for (; toStart < toEnd; ++toStart) { - if (to.charCodeAt(toStart) !== CHAR_BACKWARD_SLASH) break; - } - // Trim trailing backslashes (applicable to UNC paths only) - for (; toEnd - 1 > toStart; --toEnd) { - if (to.charCodeAt(toEnd - 1) !== CHAR_BACKWARD_SLASH) break; - } - const toLen = toEnd - toStart; - - // Compare paths to find the longest common path from root - const length = fromLen < toLen ? fromLen : toLen; - let lastCommonSep = -1; - let i = 0; - for (; i <= length; ++i) { - if (i === length) { - if (toLen > length) { - if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) { - // We get here if `from` is the exact base path for `to`. - // For example: from='C:\\foo\\bar'; to='C:\\foo\\bar\\baz' - return toOrig.slice(toStart + i + 1); - } else if (i === 2) { - // We get here if `from` is the device root. - // For example: from='C:\\'; to='C:\\foo' - return toOrig.slice(toStart + i); - } - } - if (fromLen > length) { - if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) { - // We get here if `to` is the exact base path for `from`. - // For example: from='C:\\foo\\bar'; to='C:\\foo' - lastCommonSep = i; - } else if (i === 2) { - // We get here if `to` is the device root. - // For example: from='C:\\foo\\bar'; to='C:\\' - lastCommonSep = 3; - } - } - break; - } - const fromCode = from.charCodeAt(fromStart + i); - const toCode = to.charCodeAt(toStart + i); - if (fromCode !== toCode) break; - else if (fromCode === CHAR_BACKWARD_SLASH) lastCommonSep = i; - } - - // We found a mismatch before the first common path separator was seen, so - // return the original `to`. - if (i !== length && lastCommonSep === -1) { - return toOrig; - } - - let out = ""; - if (lastCommonSep === -1) lastCommonSep = 0; - // Generate the relative path based on the path difference between `to` and - // `from` - for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { - if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) { - if (out.length === 0) out += ".."; - else out += "\\.."; - } - } - - // Lastly, append the rest of the destination (`to`) path that comes after - // the common path parts - if (out.length > 0) { - return out + toOrig.slice(toStart + lastCommonSep, toEnd); - } else { - toStart += lastCommonSep; - if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) ++toStart; - return toOrig.slice(toStart, toEnd); - } -} - -export function toNamespacedPath(path: string): string { - // Note: this will *probably* throw somewhere. - if (typeof path !== "string") return path; - if (path.length === 0) return ""; - - const resolvedPath = resolve(path); - - if (resolvedPath.length >= 3) { - if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) { - // Possible UNC root - - if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) { - const code = resolvedPath.charCodeAt(2); - if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) { - // Matched non-long UNC root, convert the path to a long UNC path - return `\\\\?\\UNC\\${resolvedPath.slice(2)}`; - } - } - } else if (isWindowsDeviceRoot(resolvedPath.charCodeAt(0))) { - // Possible device root - - if ( - resolvedPath.charCodeAt(1) === CHAR_COLON && - resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH - ) { - // Matched device root, convert the path to a long UNC path - return `\\\\?\\${resolvedPath}`; - } - } - } - - return path; -} - -export function dirname(path: string): string { - assertPath(path); - const len = path.length; - if (len === 0) return "."; - let rootEnd = -1; - let end = -1; - let matchedSlash = true; - let offset = 0; - const code = path.charCodeAt(0); - - // Try to match a root - if (len > 1) { - if (isPathSeparator(code)) { - // Possible UNC root - - rootEnd = offset = 1; - - if (isPathSeparator(path.charCodeAt(1))) { - // Matched double path separator at beginning - let j = 2; - let last = j; - // Match 1 or more non-path separators - for (; j < len; ++j) { - if (isPathSeparator(path.charCodeAt(j))) break; - } - if (j < len && j !== last) { - // Matched! - last = j; - // Match 1 or more path separators - for (; j < len; ++j) { - if (!isPathSeparator(path.charCodeAt(j))) break; - } - if (j < len && j !== last) { - // Matched! - last = j; - // Match 1 or more non-path separators - for (; j < len; ++j) { - if (isPathSeparator(path.charCodeAt(j))) break; - } - if (j === len) { - // We matched a UNC root only - return path; - } - if (j !== last) { - // We matched a UNC root with leftovers - - // Offset by 1 to include the separator after the UNC root to - // treat it as a "normal root" on top of a (UNC) root - rootEnd = offset = j + 1; - } - } - } - } - } else if (isWindowsDeviceRoot(code)) { - // Possible device root - - if (path.charCodeAt(1) === CHAR_COLON) { - rootEnd = offset = 2; - if (len > 2) { - if (isPathSeparator(path.charCodeAt(2))) rootEnd = offset = 3; - } - } - } - } else if (isPathSeparator(code)) { - // `path` contains just a path separator, exit early to avoid - // unnecessary work - return path; - } - - for (let i = len - 1; i >= offset; --i) { - if (isPathSeparator(path.charCodeAt(i))) { - if (!matchedSlash) { - end = i; - break; - } - } else { - // We saw the first non-path separator - matchedSlash = false; - } - } - - if (end === -1) { - if (rootEnd === -1) return "."; - else end = rootEnd; - } - return path.slice(0, end); -} - -export function basename(path: string, ext = ""): string { - if (ext !== undefined && typeof ext !== "string") { - throw new TypeError('"ext" argument must be a string'); - } - - assertPath(path); - - let start = 0; - let end = -1; - let matchedSlash = true; - let i: number; - - // Check for a drive letter prefix so as not to mistake the following - // path separator as an extra separator at the end of the path that can be - // disregarded - if (path.length >= 2) { - const drive = path.charCodeAt(0); - if (isWindowsDeviceRoot(drive)) { - if (path.charCodeAt(1) === CHAR_COLON) start = 2; - } - } - - if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { - if (ext.length === path.length && ext === path) return ""; - let extIdx = ext.length - 1; - let firstNonSlashEnd = -1; - for (i = path.length - 1; i >= start; --i) { - const code = path.charCodeAt(i); - if (isPathSeparator(code)) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - start = i + 1; - break; - } - } else { - if (firstNonSlashEnd === -1) { - // We saw the first non-path separator, remember this index in case - // we need it if the extension ends up not matching - matchedSlash = false; - firstNonSlashEnd = i + 1; - } - if (extIdx >= 0) { - // Try to match the explicit extension - if (code === ext.charCodeAt(extIdx)) { - if (--extIdx === -1) { - // We matched the extension, so mark this as the end of our path - // component - end = i; - } - } else { - // Extension does not match, so our result is the entire path - // component - extIdx = -1; - end = firstNonSlashEnd; - } - } - } - } - - if (start === end) end = firstNonSlashEnd; - else if (end === -1) end = path.length; - return path.slice(start, end); - } else { - for (i = path.length - 1; i >= start; --i) { - if (isPathSeparator(path.charCodeAt(i))) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - start = i + 1; - break; - } - } else if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // path component - matchedSlash = false; - end = i + 1; - } - } - - if (end === -1) return ""; - return path.slice(start, end); - } -} - -export function extname(path: string): string { - assertPath(path); - let start = 0; - let startDot = -1; - let startPart = 0; - let end = -1; - let matchedSlash = true; - // Track the state of characters (if any) we see before our first dot and - // after any path separator we find - let preDotState = 0; - - // Check for a drive letter prefix so as not to mistake the following - // path separator as an extra separator at the end of the path that can be - // disregarded - - if ( - path.length >= 2 && - path.charCodeAt(1) === CHAR_COLON && - isWindowsDeviceRoot(path.charCodeAt(0)) - ) { - start = startPart = 2; - } - - for (let i = path.length - 1; i >= start; --i) { - const code = path.charCodeAt(i); - if (isPathSeparator(code)) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - startPart = i + 1; - break; - } - continue; - } - if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // extension - matchedSlash = false; - end = i + 1; - } - if (code === CHAR_DOT) { - // If this is our first dot, mark it as the start of our extension - if (startDot === -1) startDot = i; - else if (preDotState !== 1) preDotState = 1; - } else if (startDot !== -1) { - // We saw a non-dot and non-path separator before our dot, so we should - // have a good chance at having a non-empty extension - preDotState = -1; - } - } - - if ( - startDot === -1 || - end === -1 || - // We saw a non-dot character immediately before the dot - preDotState === 0 || - // The (right-most) trimmed path component is exactly '..' - (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) - ) { - return ""; - } - return path.slice(startDot, end); -} - -export function format(pathObject: FormatInputPathObject): string { - /* eslint-disable max-len */ - if (pathObject === null || typeof pathObject !== "object") { - throw new TypeError( - `The "pathObject" argument must be of type Object. Received type ${typeof pathObject}`, - ); - } - return _format("\\", pathObject); -} - -export function parse(path: string): ParsedPath { - assertPath(path); - - const ret: ParsedPath = { root: "", dir: "", base: "", ext: "", name: "" }; - - const len = path.length; - if (len === 0) return ret; - - let rootEnd = 0; - let code = path.charCodeAt(0); - - // Try to match a root - if (len > 1) { - if (isPathSeparator(code)) { - // Possible UNC root - - rootEnd = 1; - if (isPathSeparator(path.charCodeAt(1))) { - // Matched double path separator at beginning - let j = 2; - let last = j; - // Match 1 or more non-path separators - for (; j < len; ++j) { - if (isPathSeparator(path.charCodeAt(j))) break; - } - if (j < len && j !== last) { - // Matched! - last = j; - // Match 1 or more path separators - for (; j < len; ++j) { - if (!isPathSeparator(path.charCodeAt(j))) break; - } - if (j < len && j !== last) { - // Matched! - last = j; - // Match 1 or more non-path separators - for (; j < len; ++j) { - if (isPathSeparator(path.charCodeAt(j))) break; - } - if (j === len) { - // We matched a UNC root only - - rootEnd = j; - } else if (j !== last) { - // We matched a UNC root with leftovers - - rootEnd = j + 1; - } - } - } - } - } else if (isWindowsDeviceRoot(code)) { - // Possible device root - - if (path.charCodeAt(1) === CHAR_COLON) { - rootEnd = 2; - if (len > 2) { - if (isPathSeparator(path.charCodeAt(2))) { - if (len === 3) { - // `path` contains just a drive root, exit early to avoid - // unnecessary work - ret.root = ret.dir = path; - return ret; - } - rootEnd = 3; - } - } else { - // `path` contains just a drive root, exit early to avoid - // unnecessary work - ret.root = ret.dir = path; - return ret; - } - } - } - } else if (isPathSeparator(code)) { - // `path` contains just a path separator, exit early to avoid - // unnecessary work - ret.root = ret.dir = path; - return ret; - } - - if (rootEnd > 0) ret.root = path.slice(0, rootEnd); - - let startDot = -1; - let startPart = rootEnd; - let end = -1; - let matchedSlash = true; - let i = path.length - 1; - - // Track the state of characters (if any) we see before our first dot and - // after any path separator we find - let preDotState = 0; - - // Get non-dir info - for (; i >= rootEnd; --i) { - code = path.charCodeAt(i); - if (isPathSeparator(code)) { - // If we reached a path separator that was not part of a set of path - // separators at the end of the string, stop now - if (!matchedSlash) { - startPart = i + 1; - break; - } - continue; - } - if (end === -1) { - // We saw the first non-path separator, mark this as the end of our - // extension - matchedSlash = false; - end = i + 1; - } - if (code === CHAR_DOT) { - // If this is our first dot, mark it as the start of our extension - if (startDot === -1) startDot = i; - else if (preDotState !== 1) preDotState = 1; - } else if (startDot !== -1) { - // We saw a non-dot and non-path separator before our dot, so we should - // have a good chance at having a non-empty extension - preDotState = -1; - } - } - - if ( - startDot === -1 || - end === -1 || - // We saw a non-dot character immediately before the dot - preDotState === 0 || - // The (right-most) trimmed path component is exactly '..' - (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) - ) { - if (end !== -1) { - ret.base = ret.name = path.slice(startPart, end); - } - } else { - ret.name = path.slice(startPart, startDot); - ret.base = path.slice(startPart, end); - ret.ext = path.slice(startDot, end); - } - - // If the directory is the root, use the entire root as the `dir` including - // the trailing slash if any (`C:\abc` -> `C:\`). Otherwise, strip out the - // trailing slash (`C:\abc\def` -> `C:\abc`). - if (startPart > 0 && startPart !== rootEnd) { - ret.dir = path.slice(0, startPart - 1); - } else ret.dir = ret.root; - - return ret; -} - -/** Converts a file URL to a path string. - * - * fromFileUrl("file:///home/foo"); // "\\home\\foo" - * fromFileUrl("file:///C:/Users/foo"); // "C:\\Users\\foo" - * fromFileUrl("file://localhost/home/foo"); // "\\\\localhost\\home\\foo" - */ -export function fromFileUrl(url: string | URL): string { - url = url instanceof URL ? url : new URL(url); - if (url.protocol != "file:") { - throw new TypeError("Must be a file URL."); - } - let path = decodeURIComponent( - url.pathname - .replace(/^\/*([A-Za-z]:)(\/|$)/, "$1/") - .replace(/\//g, "\\"), - ); - if (url.hostname != "") { - // Note: The `URL` implementation guarantees that the drive letter and - // hostname are mutually exclusive. Otherwise it would not have been valid - // to append the hostname and path like this. - path = `\\\\${url.hostname}${path}`; - } - return path; -} diff --git a/scripts/bundles/plugins/alias-plugin.ts b/scripts/bundles/plugins/alias-plugin.ts index 1d552f153bc..98a26cff044 100644 --- a/scripts/bundles/plugins/alias-plugin.ts +++ b/scripts/bundles/plugins/alias-plugin.ts @@ -9,9 +9,7 @@ export function aliasPlugin(opts: BuildOptions): Plugin { ['@hydrate-factory', '@stencil/core/hydrate-factory'], ['@stencil/core/mock-doc', '@stencil/core/mock-doc'], ['@stencil/core/testing', '@stencil/core/testing'], - ['@sys-api-deno', './index.js'], ['@sys-api-node', './index.js'], - ['@deno-node-compat', './node-compat.js'], ['@dev-server-process', './server-process.js'], ]); diff --git a/scripts/bundles/plugins/deno-std-plugin.ts b/scripts/bundles/plugins/deno-std-plugin.ts deleted file mode 100644 index a9ed2719550..00000000000 --- a/scripts/bundles/plugins/deno-std-plugin.ts +++ /dev/null @@ -1,57 +0,0 @@ -import type { Plugin } from 'rollup'; -import fs from 'fs-extra'; -import fetch from 'node-fetch'; -import ts from 'typescript'; -import type { BuildOptions } from '../../utils/options'; -import { join } from 'path'; - -export function denoStdPlugin(opts: BuildOptions): Plugin { - const cacheDir = join(opts.scriptsBuildDir, 'deno-cache'); - fs.ensureDirSync(cacheDir); - - return { - name: 'denoStdPlugin', - resolveId(id, importer) { - if (id.startsWith('http')) { - return id; - } - - if (importer && importer.startsWith('http')) { - const url = new URL(id, importer); - return url.href; - } - - return null; - }, - async load(id) { - if (id.startsWith('http')) { - const cacheName = id.split('://')[1].replace(/:|\/|\.|@/g, '_') + '.ts'; - const cachePath = join(cacheDir, cacheName); - try { - const cachedContent = await fs.readFile(cachePath, 'utf8'); - return cachedContent; - } catch (e) {} - - const rsp = await fetch(id); - const fetchedContent = await rsp.text(); - - await fs.writeFile(cachePath, fetchedContent); - - return fetchedContent; - } - return null; - }, - transform(code, id) { - if (id.endsWith('.ts')) { - const output = ts.transpileModule(code, { - compilerOptions: { - target: ts.ScriptTarget.ES2018, - module: ts.ModuleKind.ESNext, - }, - }); - return output.outputText; - } - return null; - }, - }; -} diff --git a/scripts/bundles/plugins/typescript-source-plugin.ts b/scripts/bundles/plugins/typescript-source-plugin.ts index 070080700f5..b6f8cef8fa3 100644 --- a/scripts/bundles/plugins/typescript-source-plugin.ts +++ b/scripts/bundles/plugins/typescript-source-plugin.ts @@ -64,8 +64,6 @@ async function bundleTypeScriptSource(tsPath: string, opts: BuildOptions) { // make a nice clean default export // "process.browser" is used by typescript to know if it should use the node sys or not - // this ensures its using our checks. Deno should also use process.browser = true - // because we don't want deno using the node apis const o: string[] = []; o.push(`// TypeScript ${opts.typescriptVersion}`); o.push(`import { IS_NODE_ENV } from '@environment';`); diff --git a/scripts/bundles/sys-deno.ts b/scripts/bundles/sys-deno.ts deleted file mode 100644 index e765a1a2244..00000000000 --- a/scripts/bundles/sys-deno.ts +++ /dev/null @@ -1,99 +0,0 @@ -import fs from 'fs-extra'; -import { join } from 'path'; -import { aliasPlugin } from './plugins/alias-plugin'; -import { BuildOptions } from '../utils/options'; -import { RollupOptions } from 'rollup'; -import { prettyMinifyPlugin } from './plugins/pretty-minify'; -import { replacePlugin } from './plugins/replace-plugin'; -import { denoStdPlugin } from './plugins/deno-std-plugin'; - -export async function sysDeno(opts: BuildOptions) { - const inputFile = join(opts.buildDir, 'sys', 'deno', 'index.js'); - const outputFile = join(opts.output.sysDenoDir, 'index.js'); - - const sysDenoBundle: RollupOptions = { - input: inputFile, - output: { - format: 'esm', - file: outputFile, - preferConst: true, - freeze: false, - }, - plugins: [replacePlugin(opts), aliasPlugin(opts), prettyMinifyPlugin(opts, getDenoBanner()), denoStdPlugin(opts)], - treeshake: { - moduleSideEffects: false, - propertyReadSideEffects: false, - unknownGlobalSideEffects: false, - }, - }; - - const inputWorkerFile = join(opts.buildDir, 'sys', 'deno', 'worker.js'); - const outputWorkerFile = join(opts.output.sysDenoDir, 'worker.js'); - const sysDenoWorkerBundle: RollupOptions = { - input: inputWorkerFile, - output: { - format: 'esm', - file: outputWorkerFile, - preferConst: true, - freeze: false, - }, - plugins: [ - { - name: 'sysDenoWorkerAlias', - resolveId(id) { - if (id === '@stencil/core/compiler') { - return { - id: '../../compiler/stencil.js', - external: true, - }; - } - }, - }, - replacePlugin(opts), - aliasPlugin(opts), - prettyMinifyPlugin(opts, getDenoBanner()), - ], - }; - - const inputNodeCompatFile = join(opts.buildDir, 'sys', 'deno', 'deno-node-compat.js'); - const outputNodeCompatFile = join(opts.output.sysDenoDir, 'node-compat.js'); - const sysDenoNodeCompatBundle: RollupOptions = { - input: inputNodeCompatFile, - output: { - format: 'esm', - file: outputNodeCompatFile, - preferConst: true, - freeze: false, - }, - plugins: [ - { - name: 'denoNodeCompatPlugin', - resolveId(importee) { - if (importee.endsWith('process.ts')) { - return join(opts.buildDir, 'sys', 'deno', 'deno-node-process.js'); - } - return null; - }, - }, - replacePlugin(opts), - aliasPlugin(opts), - denoStdPlugin(opts), - prettyMinifyPlugin(opts, getDenoBanner()), - ], - treeshake: { - moduleSideEffects: false, - propertyReadSideEffects: false, - unknownGlobalSideEffects: false, - }, - }; - - return [sysDenoBundle, sysDenoWorkerBundle, sysDenoNodeCompatBundle]; -} - -function getDenoBanner() { - return [ - `/*! Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.`, - ` * https://github.com/denoland/deno/blob/master/LICENSE`, - ` * https://deno.land/ */`, - ].join('\n'); -} diff --git a/scripts/utils/options.ts b/scripts/utils/options.ts index 8fd4f85f536..ebf67a88eb1 100644 --- a/scripts/utils/options.ts +++ b/scripts/utils/options.ts @@ -50,7 +50,6 @@ export function getOptions(rootDir: string, inputOpts: BuildOptions = {}): Build internalDir: join(rootDir, 'internal'), mockDocDir: join(rootDir, 'mock-doc'), screenshotDir: join(rootDir, 'screenshot'), - sysDenoDir: join(rootDir, 'sys', 'deno'), sysNodeDir: join(rootDir, 'sys', 'node'), testingDir: join(rootDir, 'testing'), }, @@ -161,7 +160,6 @@ export interface BuildOptions { internalDir: string; mockDocDir: string; screenshotDir: string; - sysDenoDir: string; sysNodeDir: string; testingDir: string; }; diff --git a/src/compiler/config/transpile-options.ts b/src/compiler/config/transpile-options.ts index e46688eb975..ab9baa921bf 100644 --- a/src/compiler/config/transpile-options.ts +++ b/src/compiler/config/transpile-options.ts @@ -8,7 +8,7 @@ import type { CompilerSystem, } from '../../declarations'; import { createSystem } from '../sys/stencil-sys'; -import { IS_DENO_ENV, IS_NODE_ENV, requireFunc } from '../sys/environment'; +import { IS_NODE_ENV, requireFunc } from '../sys/environment'; import { isString } from '@utils'; import { parseImportPath } from '../transformers/stencil-import-path'; import { STENCIL_INTERNAL_CLIENT_ID } from '../bundle/entry-alias-ids'; @@ -45,8 +45,6 @@ export const getTranspileConfig = (input: TranspileOptions) => { } else if (!transpileCtx.sys) { if (IS_NODE_ENV) { transpileCtx.sys = requireFunc('../sys/node/index.js').createNodeSys(); - } else if (IS_DENO_ENV) { - throw new Error(`"sys" must be provided in options`); } else { transpileCtx.sys = createSystem(); } diff --git a/src/compiler/sys/environment.ts b/src/compiler/sys/environment.ts index 528fb3ea055..c5e5e8d2327 100644 --- a/src/compiler/sys/environment.ts +++ b/src/compiler/sys/environment.ts @@ -1,16 +1,13 @@ -export const IS_DENO_ENV = typeof Deno !== 'undefined'; - export const IS_NODE_ENV = - !IS_DENO_ENV && typeof global !== 'undefined' && typeof require === 'function' && !!global.process && typeof __filename === 'string' && (!(global as any as Window).origin || typeof (global as any as Window).origin !== 'string'); -export const OS_PLATFORM = IS_NODE_ENV ? process.platform : IS_DENO_ENV ? Deno.build.os : ''; +export const OS_PLATFORM = IS_NODE_ENV ? process.platform : ''; -export const IS_WINDOWS_ENV = OS_PLATFORM === 'win32' || OS_PLATFORM === 'windows'; +export const IS_WINDOWS_ENV = OS_PLATFORM === 'win32'; export const IS_CASE_SENSITIVE_FILE_NAMES = !IS_WINDOWS_ENV; @@ -26,6 +23,4 @@ export const IS_FETCH_ENV = typeof fetch === 'function'; export const requireFunc = IS_NODE_ENV ? require : () => {}; -export const getCurrentDirectory: () => string = IS_NODE_ENV ? process.cwd : IS_DENO_ENV ? Deno.cwd : () => '/'; - -declare const Deno: any; +export const getCurrentDirectory: () => string = IS_NODE_ENV ? process.cwd : () => '/'; diff --git a/src/compiler/sys/modules/os.ts b/src/compiler/sys/modules/os.ts index 2c2341e484c..9e234488a56 100644 --- a/src/compiler/sys/modules/os.ts +++ b/src/compiler/sys/modules/os.ts @@ -2,7 +2,7 @@ import { OS_PLATFORM } from '../environment'; export const EOL = '\n'; -export const platform = () => (OS_PLATFORM === 'windows' ? 'win32' : OS_PLATFORM); +export const platform = () => OS_PLATFORM; export default { EOL, diff --git a/src/compiler/sys/typescript/typescript-sys.ts b/src/compiler/sys/typescript/typescript-sys.ts index 4cedf41eab9..edc878a3844 100644 --- a/src/compiler/sys/typescript/typescript-sys.ts +++ b/src/compiler/sys/typescript/typescript-sys.ts @@ -175,7 +175,7 @@ const patchTypeScriptSysMinimum = () => { if (!ts.sys) { // patches just the bare minimum // if ts.sys already exists then it must be node ts.sys - // otherwise we're either browser or deno + // otherwise we're browser // will be updated later on with the stencil sys ts.sys = { args: [], diff --git a/src/declarations/stencil-public-compiler.ts b/src/declarations/stencil-public-compiler.ts index 3a898b891a3..86370a289f6 100644 --- a/src/declarations/stencil-public-compiler.ts +++ b/src/declarations/stencil-public-compiler.ts @@ -883,7 +883,7 @@ export interface SitemapXmpResults { * of the actual platform it's being ran ontop of. */ export interface CompilerSystem { - name: 'deno' | 'node' | 'in-memory'; + name: 'node' | 'in-memory'; version: string; events?: BuildEvents; details?: SystemDetails; diff --git a/src/sys/deno/deno-copy-tasks.ts b/src/sys/deno/deno-copy-tasks.ts deleted file mode 100644 index 0952c9bd1ab..00000000000 --- a/src/sys/deno/deno-copy-tasks.ts +++ /dev/null @@ -1,181 +0,0 @@ -import type * as d from '../../declarations'; -import type { Deno } from '../../../types/lib.deno'; -import { buildError, catchError, flatOne, normalizePath } from '@utils'; -import { basename, dirname, expandGlob, isGlob, isAbsolute, join, resolve } from './deps'; - -export async function denoCopyTasks(deno: typeof Deno, copyTasks: Required[], srcDir: string) { - const results: d.CopyResults = { - diagnostics: [], - dirPaths: [], - filePaths: [], - }; - - try { - copyTasks = flatOne(await Promise.all(copyTasks.map((task) => processGlobs(task, srcDir)))); - - const allCopyTasks: d.CopyTask[] = []; - - // figure out all the file copy tasks we'll have - // by digging down through any directory copy tasks - while (copyTasks.length > 0) { - const tasks = copyTasks.splice(0, 100); - - await Promise.all(tasks.map((copyTask) => processCopyTask(deno, results, allCopyTasks, copyTask))); - } - - // figure out which directories we'll need to make first - const mkDirs = ensureDirs(allCopyTasks); - - try { - await Promise.all(mkDirs.map((dir) => deno.mkdir(dir, { recursive: true }))); - } catch (mkDirErr) {} - - while (allCopyTasks.length > 0) { - const tasks = allCopyTasks.splice(0, 100); - - await Promise.all(tasks.map((copyTask) => deno.copyFile(copyTask.src, copyTask.dest))); - } - } catch (e) { - catchError(results.diagnostics, e); - } - - return results; -} - -async function processGlobs(copyTask: Required, srcDir: string): Promise[]> { - return isGlob(copyTask.src) - ? await processGlobTask(copyTask, srcDir) - : [ - { - src: getSrcAbsPath(srcDir, copyTask.src), - dest: copyTask.keepDirStructure ? join(copyTask.dest, copyTask.src) : copyTask.dest, - warn: copyTask.warn, - keepDirStructure: copyTask.keepDirStructure, - }, - ]; -} - -function getSrcAbsPath(srcDir: string, src: string) { - if (isAbsolute(src)) { - return src; - } - return join(srcDir, src); -} - -async function processGlobTask(copyTask: Required, srcDir: string): Promise[]> { - const copyTasks: Required[] = []; - - for await (const walkEntry of expandGlob(copyTask.src, { root: srcDir })) { - const ct = createGlobCopyTask(copyTask, srcDir, walkEntry.name); - copyTasks.push(ct); - } - return copyTasks; -} - -function createGlobCopyTask(copyTask: Required, srcDir: string, globRelPath: string): Required { - const dest = join(copyTask.dest, copyTask.keepDirStructure ? globRelPath : basename(globRelPath)); - return { - src: join(srcDir, globRelPath), - dest, - warn: copyTask.warn, - keepDirStructure: copyTask.keepDirStructure, - }; -} - -async function processCopyTask( - deno: typeof Deno, - results: d.CopyResults, - allCopyTasks: d.CopyTask[], - copyTask: d.CopyTask -) { - try { - copyTask.src = normalizePath(copyTask.src); - copyTask.dest = normalizePath(copyTask.dest); - - // get the stats for this src to see if it's a directory or not - const stats = await deno.stat(copyTask.src); - if (stats.isDirectory) { - // still a directory, keep diggin down - if (!results.dirPaths.includes(copyTask.dest)) { - results.dirPaths.push(copyTask.dest); - } - - await processCopyTaskDirectory(deno, results, allCopyTasks, copyTask); - } else if (!shouldIgnore(copyTask.src)) { - // this is a file we should copy - if (!results.filePaths.includes(copyTask.dest)) { - results.filePaths.push(copyTask.dest); - } - - allCopyTasks.push(copyTask); - } - } catch (e) { - if (copyTask.warn !== false) { - const err = buildError(results.diagnostics); - err.messageText = e.message; - } - } -} - -async function processCopyTaskDirectory( - deno: typeof Deno, - results: d.CopyResults, - allCopyTasks: d.CopyTask[], - copyTask: d.CopyTask -) { - try { - for await (const dirEntry of deno.readDir(copyTask.src)) { - const subCopyTask: d.CopyTask = { - src: join(copyTask.src, dirEntry.name), - dest: join(copyTask.dest, dirEntry.name), - warn: copyTask.warn, - }; - - await processCopyTask(deno, results, allCopyTasks, subCopyTask); - } - } catch (e) { - catchError(results.diagnostics, e); - } -} - -function ensureDirs(copyTasks: d.CopyTask[]) { - const mkDirs: string[] = []; - - copyTasks.forEach((copyTask) => { - addMkDir(mkDirs, dirname(copyTask.dest)); - }); - - mkDirs.sort((a, b) => { - const partsA = a.split('/').length; - const partsB = b.split('/').length; - - if (partsA < partsB) return -1; - if (partsA > partsB) return 1; - if (a < b) return -1; - if (a > b) return 1; - return 0; - }); - - return mkDirs; -} - -function addMkDir(mkDirs: string[], destDir: string) { - destDir = normalizePath(destDir); - - if (destDir === ROOT_DIR || destDir + '/' === ROOT_DIR || destDir === '') { - return; - } - - if (!mkDirs.includes(destDir)) { - mkDirs.push(destDir); - } -} - -const ROOT_DIR = normalizePath(resolve('/')); - -function shouldIgnore(filePath: string) { - filePath = filePath.trim().toLowerCase(); - return IGNORE.some((ignoreFile) => filePath.endsWith(ignoreFile)); -} - -const IGNORE = ['.ds_store', '.gitignore', 'desktop.ini', 'thumbs.db']; diff --git a/src/sys/deno/deno-logger.ts b/src/sys/deno/deno-logger.ts deleted file mode 100644 index 75ce87e8b38..00000000000 --- a/src/sys/deno/deno-logger.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { createTerminalLogger, ColorType, TerminalLoggerSys } from '../../compiler/sys/logger/terminal-logger'; -import { bgRed, blue, bold, cyan, dim, gray, green, magenta, red, yellow } from './deps'; -import type { Deno as DenoTypes } from '../../../types/lib.deno'; - -export const createDenoLogger = (c: { Deno: any }) => { - let useColors = true; - const deno: typeof DenoTypes = c.Deno; - const minColumns = 60; - const maxColumns = 120; - - const color = (msg: string, colorType: ColorType) => { - if (useColors && !deno.noColor) { - switch (colorType) { - case 'bgRed': - return bgRed(msg); - case 'blue': - return blue(msg); - case 'bold': - return bold(msg); - case 'cyan': - return cyan(msg); - case 'dim': - return dim(msg); - case 'gray': - return gray(msg); - case 'green': - return green(msg); - case 'magenta': - return magenta(msg); - case 'red': - return red(msg); - case 'yellow': - return yellow(msg); - } - } - return msg; - }; - - const cwd = () => deno.cwd(); - - const emoji = (e: string) => (deno.build.os !== 'windows' ? e : ''); - - const enableColors = (enableClrs: boolean) => (useColors = enableClrs); - - const getColumns = () => { - const terminalWidth = (deno.stdout && (deno.stdout as any).columns) || 80; - return Math.max(Math.min(maxColumns, terminalWidth), minColumns); - }; - - const memoryUsage = () => -1; - - const relativePath = (_from: string, to: string) => to; - - const writeLogs = (logFilePath: string, log: string, append: boolean) => { - const encoder = new TextEncoder(); - const data = encoder.encode(log); - deno.writeFileSync(logFilePath, data, { append }); - }; - - const loggerSys: TerminalLoggerSys = { - color, - cwd, - emoji, - enableColors, - getColumns, - memoryUsage, - relativePath, - writeLogs, - }; - - return createTerminalLogger(loggerSys); -}; diff --git a/src/sys/deno/deno-node-compat.ts b/src/sys/deno/deno-node-compat.ts deleted file mode 100644 index ab4b6718ebd..00000000000 --- a/src/sys/deno/deno-node-compat.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { createRequire, join, nodeFs } from './deps'; -import process from './deno-node-process'; -import type { Deno as DenoTypes } from '../../../types/lib.deno'; - -// idk why the node compat doesn't come with stat and statSync on it?? -// https://deno.land/std/node/fs.ts - -Object.assign(nodeFs, { - stat: (...args: any[]) => { - const path: string = args[0]; - const cb = args.length > 2 ? args[2] : args[1]; - try { - const s = Deno.statSync(path); - cb && - cb(null, { - isFile: () => s.isFile, - isDirectory: () => s.isDirectory, - isSymbolicLink: () => s.isSymlink, - size: s.size, - }); - } catch (e) { - cb && cb(e); - } - }, - statSync: (path: string) => { - const s = Deno.statSync(path); - return { - isFile: () => s.isFile, - isDirectory: () => s.isDirectory, - isSymbolicLink: () => s.isSymlink, - size: s.size, - }; - }, -}); - -export const applyNodeCompat = (opts: { fromDir: string }) => { - (globalThis as any).process = process; - - const nodeRequire = createRequire(join(opts.fromDir, 'noop.js')); - (globalThis as any).require = nodeRequire; -}; - -declare const Deno: typeof DenoTypes; diff --git a/src/sys/deno/deno-node-process.ts b/src/sys/deno/deno-node-process.ts deleted file mode 100644 index 347a588e1cf..00000000000 --- a/src/sys/deno/deno-node-process.ts +++ /dev/null @@ -1,39 +0,0 @@ -import type { Deno as DenoTypes } from '../../../types/lib.deno'; - -export const arch = Deno.build.arch; - -export const chdir = Deno.chdir; - -export const cwd = Deno.cwd; - -export const exit = Deno.exit; - -export const pid = Deno.pid; - -export const platform = Deno.build.os === 'windows' ? 'win32' : Deno.build.os; - -export const version = `v12.0.0`; - -export const versions = { - node: version, - ...Deno.version, -}; - -const process = { - arch, - chdir, - cwd, - exit, - pid, - platform, - version: 'v12.0.0', - versions, - - on() {}, - env: {}, - argv: ['deno', ...Deno.args], -}; - -declare const Deno: typeof DenoTypes; - -export default process; diff --git a/src/sys/deno/deno-sys.ts b/src/sys/deno/deno-sys.ts deleted file mode 100644 index 7cb33aab72a..00000000000 --- a/src/sys/deno/deno-sys.ts +++ /dev/null @@ -1,670 +0,0 @@ -import type { - CompilerSystem, - CompilerSystemCreateDirectoryResults, - CompilerSystemRealpathResults, - CompilerSystemRemoveDirectoryResults, - CompilerSystemRemoveFileResults, - CompilerSystemRenameResults, - CompilerSystemWriteFileResults, - Diagnostic, -} from '../../declarations'; -import { - basename, - delimiter, - dirname, - extname, - isAbsolute, - join, - normalize, - parse, - relative, - resolve, - sep, - win32, - posix, -} from './deps'; -import { convertPathToFileProtocol, isRemoteUrl, normalizePath, catchError, buildError } from '@utils'; -import { createDenoWorkerMainController } from './deno-worker-main'; -import { denoCopyTasks } from './deno-copy-tasks'; -import { version } from '../../version'; -import type { Deno as DenoTypes } from '../../../types/lib.deno'; - -export function createDenoSys(c: { Deno?: any } = {}) { - let tmpDir: string = null; - let stencilBaseUrl: URL; - let stencilRemoteUrl: string; - let stencilExePath = new URL(`../../compiler/stencil.js`, import.meta.url).href; - let typescriptRemoteUrl: string; - let typescriptExePath: string; - const deno: typeof DenoTypes = c.Deno || (globalThis as any).Deno; - const destroys = new Set<() => Promise | void>(); - const hardwareConcurrency = 0; - const isRemoteHost = isRemoteUrl(import.meta.url); - - const getLocalModulePath = (opts: { rootDir: string; moduleId: string; path: string }) => - join(opts.rootDir, 'node_modules', opts.moduleId, opts.path); - - const getRemoteModuleUrl = (module: { moduleId: string; path: string; version?: string }) => { - const npmBaseUrl = 'https://cdn.jsdelivr.net/npm/'; - const path = `${module.moduleId}${module.version ? '@' + module.version : ''}/${module.path}`; - return new URL(path, npmBaseUrl).href; - }; - - const fetchWrite = async (diagnostics: Diagnostic[], remoteUrl: string, localPath: string) => { - try { - await deno.stat(localPath); - return; - } catch (e) {} - - try { - const rsp = await fetch(remoteUrl); - if (rsp.ok) { - const localDir = dirname(localPath); - try { - await deno.mkdir(localDir, { recursive: true }); - } catch (e) {} - - const content = await rsp.clone().text(); - const encoder = new TextEncoder(); - await deno.writeFile(localPath, encoder.encode(content)); - } else { - const diagnostic = buildError(diagnostics); - diagnostic.messageText = `Unable to fetch: ${remoteUrl}, ${rsp.status}`; - } - } catch (e) { - catchError(diagnostics, e); - } - }; - - const sys: CompilerSystem = { - name: 'deno', - version: deno.version.deno, - async access(p) { - try { - await deno.stat(p); - return true; - } catch (e) { - return false; - } - }, - accessSync(p) { - try { - deno.statSync(p); - return true; - } catch (e) { - return false; - } - }, - addDestory(cb) { - destroys.add(cb); - }, - removeDestory(cb) { - destroys.delete(cb); - }, - async copyFile(src, dst) { - try { - await deno.copyFile(src, dst); - return true; - } catch (e) { - return false; - } - }, - async createDir(p, opts) { - const results: CompilerSystemCreateDirectoryResults = { - basename: basename(p), - dirname: dirname(p), - path: p, - newDirs: [], - error: null, - }; - try { - await deno.mkdir(p, opts); - } catch (e) { - results.error = e; - } - return results; - }, - isTTY() { - return !!deno?.isatty(deno?.stdout?.rid); - }, - homeDir() { - return deno.env.get('HOME'); - }, - createDirSync(p, opts) { - const results: CompilerSystemCreateDirectoryResults = { - basename: basename(p), - dirname: dirname(p), - path: p, - newDirs: [], - error: null, - }; - try { - deno.mkdirSync(p, opts); - } catch (e) { - results.error = e; - } - return results; - }, - createWorkerController: (maxConcurrentWorkers) => createDenoWorkerMainController(sys, maxConcurrentWorkers), - async destroy() { - const waits: Promise[] = []; - destroys.forEach((cb) => { - try { - const rtn = cb(); - if (rtn && rtn.then) { - waits.push(rtn); - } - } catch (e) { - console.error(`node sys destroy: ${e}`); - } - }); - await Promise.all(waits); - destroys.clear(); - }, - dynamicImport(p) { - if (isRemoteHost) { - // if this sys is hosted from http://, but the path to be - // imported is a local file, then ensure it is a file:// protocol - p = convertPathToFileProtocol(p); - } - return import(`${p}?${version}`); - }, - encodeToBase64(str) { - return Buffer.from(str).toString('base64'); - }, - async ensureDependencies(opts) { - const timespan = opts.logger.createTimeSpan(`ensure dependencies start`, true); - const diagnostics: Diagnostic[] = []; - const stencilDep = opts.dependencies.find((dep) => dep.name === '@stencil/core'); - const typescriptDep = opts.dependencies.find((dep) => dep.name === 'typescript'); - - stencilRemoteUrl = new URL(`../../compiler/stencil.js`, import.meta.url).href; - if (!isRemoteUrl(stencilRemoteUrl)) { - stencilRemoteUrl = sys.getRemoteModuleUrl({ - moduleId: stencilDep.name, - version: stencilDep.version, - path: stencilDep.main, - }); - } - stencilBaseUrl = new URL(`../../`, stencilRemoteUrl); - stencilExePath = sys.getLocalModulePath({ - rootDir: opts.rootDir, - moduleId: stencilDep.name, - path: stencilDep.main, - }); - - typescriptRemoteUrl = sys.getRemoteModuleUrl({ - moduleId: typescriptDep.name, - version: typescriptDep.version, - path: typescriptDep.main, - }); - typescriptExePath = sys.getLocalModulePath({ - rootDir: opts.rootDir, - moduleId: typescriptDep.name, - path: typescriptDep.main, - }); - - const ensureStencil = fetchWrite(diagnostics, stencilRemoteUrl, stencilExePath); - const ensureTypescript = fetchWrite(diagnostics, typescriptRemoteUrl, typescriptExePath); - - await Promise.all([ensureStencil, ensureTypescript]); - - sys.getCompilerExecutingPath = () => stencilExePath; - - timespan.finish(`ensure dependencies end`); - - return { - stencilPath: stencilExePath, - typescriptPath: typescriptExePath, - diagnostics, - }; - }, - async ensureResources(opts) { - const stencilDep = opts.dependencies.find((dep) => dep.name === '@stencil/core'); - const typescriptDep = opts.dependencies.find((dep) => dep.name === 'typescript'); - - const deps: { url: string; path: string }[] = []; - - const stencilPkg = sys.getLocalModulePath({ - rootDir: opts.rootDir, - moduleId: stencilDep.name, - path: 'package.json', - }); - const typescriptPkg = sys.getLocalModulePath({ - rootDir: opts.rootDir, - moduleId: typescriptDep.name, - path: 'package.json', - }); - - const stencilCheck = sys.access(stencilPkg); - const typescriptCheck = sys.access(typescriptPkg); - - const stencilResourcesExist = await stencilCheck; - const typescriptResourcesExist = await typescriptCheck; - - if (!stencilResourcesExist) { - opts.logger.debug(`stencilBaseUrl: ${stencilBaseUrl.href}`); - stencilDep.resources.forEach((p) => { - deps.push({ - url: new URL(p, stencilBaseUrl).href, - path: sys.getLocalModulePath({ rootDir: opts.rootDir, moduleId: stencilDep.name, path: p }), - }); - }); - } - - if (!typescriptResourcesExist) { - typescriptDep.resources.forEach((p) => { - deps.push({ - url: sys.getRemoteModuleUrl({ moduleId: typescriptDep.name, version: typescriptDep.version, path: p }), - path: sys.getLocalModulePath({ rootDir: opts.rootDir, moduleId: typescriptDep.name, path: p }), - }); - }); - } - - if (deps.length > 0) { - console.log(deps); - const ensuredDirs = new Set(); - const timespan = opts.logger.createTimeSpan(`ensure resources start`, true); - - await Promise.all( - deps.map(async (dep) => { - const rsp = await fetch(dep.url); - if (rsp.ok) { - const content = rsp.text(); - const dir = dirname(dep.path); - if (!ensuredDirs.has(dir)) { - sys.createDir(dir, { recursive: true }); - ensuredDirs.add(dir); - } - await sys.writeFile(dep.path, await content); - } else { - opts.logger.error(`unable to fetch: ${dep.url}`); - } - }) - ); - - timespan.finish(`ensure resources end: ${deps.length}`); - } - }, - exit: async (exitCode) => { - deno.exit(exitCode); - }, - fetch, - getCompilerExecutingPath() { - return stencilExePath; - }, - getCurrentDirectory() { - return normalizePath(deno.cwd()); - }, - getEnvironmentVar(key) { - return deno.env.get(key); - }, - getLocalModulePath, - getRemoteModuleUrl, - glob(_pattern, _opts) { - return null; - }, - hardwareConcurrency, - async isSymbolicLink(p) { - try { - const stat = await deno.stat(p); - return stat.isSymlink; - } catch (e) { - return false; - } - }, - nextTick: queueMicrotask, - normalizePath, - platformPath: { - basename, - dirname, - extname, - isAbsolute, - join, - normalize, - parse, - relative, - resolve, - sep, - delimiter, - posix, - win32, - }, - async readDir(p) { - const dirEntries: string[] = []; - try { - for await (const dirEntry of deno.readDir(p)) { - dirEntries.push(join(p, dirEntry.name)); - } - } catch (e) {} - return dirEntries; - }, - readDirSync(p) { - const dirEntries: string[] = []; - try { - for (const dirEntry of deno.readDirSync(p)) { - dirEntries.push(join(p, dirEntry.name)); - } - } catch (e) {} - return dirEntries; - }, - async readFile(p: string, encoding?: string) { - try { - const data = await deno.readFile(p); - if (encoding === 'binary') { - return data as any; - } - const decoder = new TextDecoder('utf-8'); - return decoder.decode(data); - } catch (e) {} - return undefined; - }, - readFileSync(p) { - try { - const decoder = new TextDecoder('utf-8'); - const data = deno.readFileSync(p); - return decoder.decode(data); - } catch (e) {} - return undefined; - }, - async realpath(p) { - const results: CompilerSystemRealpathResults = { - error: null, - path: undefined, - }; - try { - results.path = await deno.realPath(p); - } catch (e) { - results.error = e; - } - return results; - }, - realpathSync(p) { - const results: CompilerSystemRealpathResults = { - error: null, - path: undefined, - }; - try { - results.path = deno.realPathSync(p); - } catch (e) { - results.error = e; - } - return results; - }, - async rename(oldPath, newPath) { - const results: CompilerSystemRenameResults = { - oldPath, - newPath, - error: null, - oldDirs: [], - oldFiles: [], - newDirs: [], - newFiles: [], - renamed: [], - isFile: false, - isDirectory: false, - }; - try { - await deno.rename(oldPath, newPath); - } catch (e) { - results.error = e; - } - return results; - }, - resolvePath(p) { - return normalizePath(p); - }, - async removeDir(p, opts) { - const results: CompilerSystemRemoveDirectoryResults = { - basename: basename(p), - dirname: dirname(p), - path: p, - removedDirs: [], - removedFiles: [], - error: null, - }; - try { - await deno.remove(p, opts); - } catch (e) { - results.error = e; - } - return results; - }, - removeDirSync(p, opts) { - const results: CompilerSystemRemoveDirectoryResults = { - basename: basename(p), - dirname: dirname(p), - path: p, - removedDirs: [], - removedFiles: [], - error: null, - }; - try { - deno.removeSync(p, opts); - } catch (e) { - results.error = e; - } - return results; - }, - async removeFile(p) { - const results: CompilerSystemRemoveFileResults = { - basename: basename(p), - dirname: dirname(p), - path: p, - error: null, - }; - try { - await deno.remove(p); - } catch (e) { - results.error = e; - } - return results; - }, - removeFileSync(p) { - const results: CompilerSystemRemoveFileResults = { - basename: basename(p), - dirname: dirname(p), - path: p, - error: null, - }; - try { - deno.removeSync(p); - } catch (e) { - results.error = e; - } - return results; - }, - async stat(p) { - // deno hangs when using `stat()`!?!?! - // idk why compilerCtx.fs.emptyDirs(cleanDirs) will hang when stat is async - try { - const fsStat = deno.statSync(p); - return { - isDirectory: fsStat.isDirectory, - isFile: fsStat.isFile, - isSymbolicLink: fsStat.isSymlink, - size: fsStat.size, - mtimeMs: fsStat.mtime.getTime(), - error: null, - }; - } catch (e) { - return { - isDirectory: false, - isFile: false, - isSymbolicLink: false, - size: 0, - mtimeMs: 0, - error: e, - }; - } - }, - statSync(p) { - try { - const fsStat = deno.statSync(p); - return { - isDirectory: fsStat.isDirectory, - isFile: fsStat.isFile, - isSymbolicLink: fsStat.isSymlink, - size: fsStat.size, - mtimeMs: fsStat.mtime.getTime(), - error: null, - }; - } catch (e) { - return { - isDirectory: false, - isFile: false, - isSymbolicLink: false, - size: 0, - mtimeMs: 0, - error: e, - }; - } - }, - tmpDirSync() { - if (tmpDir == null) { - tmpDir = dirname(deno.makeTempDirSync()); - } - return tmpDir; - }, - async writeFile(p, content) { - const results: CompilerSystemWriteFileResults = { - path: p, - error: null, - }; - try { - const encoder = new TextEncoder(); - await deno.writeFile(p, encoder.encode(content)); - } catch (e) { - results.error = e; - } - return results; - }, - writeFileSync(p, content) { - const results: CompilerSystemWriteFileResults = { - path: p, - error: null, - }; - try { - const encoder = new TextEncoder(); - deno.writeFileSync(p, encoder.encode(content)); - } catch (e) { - results.error = e; - } - return results; - }, - watchDirectory(p, callback, recursive) { - const fsWatcher = deno.watchFs(p, { recursive }); - - const dirWatcher = async () => { - try { - for await (const fsEvent of fsWatcher) { - for (const fsPath of fsEvent.paths) { - const fileName = normalizePath(fsPath); - - if (fsEvent.kind === 'create') { - callback(fileName, 'dirAdd'); - sys.events.emit('dirAdd', fileName); - } else if (fsEvent.kind === 'modify') { - callback(fileName, 'fileUpdate'); - sys.events.emit('fileUpdate', fileName); - } else if (fsEvent.kind === 'remove') { - callback(fileName, 'dirDelete'); - sys.events.emit('dirDelete', fileName); - } - } - } - } catch (e) { - // todo - // swallows "BadResource: Bad resource ID at unwrapResponse"?? - } - }; - dirWatcher(); - - const close = async () => { - try { - await fsWatcher.return(); - } catch (e) { - // todo - // swallows "BadResource: Bad resource ID at unwrapResponse"?? - } - }; - sys.addDestory(close); - - return { - close, - }; - }, - watchFile(p, callback) { - const fsWatcher = deno.watchFs(p, { recursive: false }); - - const fileWatcher = async () => { - try { - for await (const fsEvent of fsWatcher) { - for (const fsPath of fsEvent.paths) { - const fileName = normalizePath(fsPath); - - if (fsEvent.kind === 'create') { - callback(fileName, 'fileAdd'); - sys.events.emit('fileAdd', fileName); - } else if (fsEvent.kind === 'modify') { - callback(fileName, 'fileUpdate'); - sys.events.emit('fileUpdate', fileName); - } else if (fsEvent.kind === 'remove') { - callback(fileName, 'fileDelete'); - sys.events.emit('fileDelete', fileName); - } - } - } - } catch (e) { - // todo - // swallows "BadResource: Bad resource ID at unwrapResponse"?? - } - }; - fileWatcher(); - - const close = async () => { - try { - await fsWatcher.return(); - } catch (e) { - // todo - // swallows "BadResource: Bad resource ID at unwrapResponse"?? - } - }; - sys.addDestory(close); - - return { - close, - }; - }, - async generateContentHash(content) { - // https://github.com/denoland/deno/issues/1891 - // https://jsperf.com/hashcodelordvlad/121 - const len = content.length; - if (len === 0) return ''; - let hash = 0; - for (let i = 0; i < len; i++) { - hash = (hash << 5) - hash + content.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - if (hash < 0) { - hash = hash * -1; - } - return hash + ''; - }, - copy: (copyTasks, srcDir) => denoCopyTasks(deno, copyTasks, srcDir), - details: { - // https://github.com/denoland/deno/issues/3802 - cpuModel: 'cpu-model', - freemem: () => 0, - platform: deno.build.os, - release: deno.build.vendor, - totalmem: 0, - }, - applyGlobalPatch: async (fromDir) => { - const { applyNodeCompat } = await import('@deno-node-compat'); - applyNodeCompat({ fromDir }); - }, - }; - - return sys; -} diff --git a/src/sys/deno/deno-worker-main.ts b/src/sys/deno/deno-worker-main.ts deleted file mode 100644 index a6c07d99623..00000000000 --- a/src/sys/deno/deno-worker-main.ts +++ /dev/null @@ -1,163 +0,0 @@ -import type * as d from '../../declarations'; -import { TASK_CANCELED_MSG } from '@utils'; - -export const createDenoWorkerMainController = ( - sys: d.CompilerSystem, - maxConcurrentWorkers: number -): d.WorkerMainController => { - let msgIds = 0; - let isDestroyed = false; - let isQueued = false; - let workerIds = 0; - const tasks = new Map(); - const queuedSendMsgs: d.MsgToWorker[] = []; - const workers: WorkerChild[] = []; - const maxWorkers = Math.max(Math.min(maxConcurrentWorkers, sys.hardwareConcurrency), 2) - 1; - - const times = new Map(); - - const onMsgsFromWorker = (worker: WorkerChild, ev: MessageEvent) => { - if (!isDestroyed) { - const msgsFromWorker: d.MsgFromWorker[] = ev.data; - if (Array.isArray(msgsFromWorker)) { - for (const msgFromWorker of msgsFromWorker) { - if (msgFromWorker) { - const task = tasks.get(msgFromWorker.stencilId); - if (task) { - tasks.delete(msgFromWorker.stencilId); - if (msgFromWorker.stencilRtnError) { - task.reject(msgFromWorker.stencilRtnError); - } else { - task.resolve(msgFromWorker.stencilRtnValue); - } - - worker.activeTasks--; - if (worker.activeTasks < 0 || worker.activeTasks > 50) { - worker.activeTasks = 0; - } - } else if (msgFromWorker.stencilRtnError) { - console.error(msgFromWorker.stencilRtnError); - } - } - } - } - } - }; - - const onWorkerError = (e: ErrorEvent) => console.error(e); - - const createWorkerMain = () => { - const workerUrl = new URL('./worker.js', import.meta.url).href; - - const workerOpts: any = { - name: `stencil.worker.${workerIds++}`, - type: `module`, - // https://github.com/denoland/deno/pull/4784/files#diff-dd54e4bec687ba9ed5ee965039de9fbbR1083 - deno: true, - }; - - const worker = new Worker(workerUrl, workerOpts); - - const workerChild: WorkerChild = { - worker, - activeTasks: 0, - sendQueue: [], - }; - worker.onerror = onWorkerError; - worker.onmessage = (ev) => onMsgsFromWorker(workerChild, ev); - - return workerChild; - }; - - const sendMsgsToWorkers = (w: WorkerChild) => { - if (w.sendQueue.length > 0) { - w.worker.postMessage(w.sendQueue); - w.sendQueue.length = 0; - } - }; - - const queueMsgToWorker = (msg: d.MsgToWorker) => { - let theChosenOne: WorkerChild; - - if (workers.length > 0) { - theChosenOne = workers[0]; - - if (maxWorkers > 1) { - for (const worker of workers) { - if (worker.activeTasks < theChosenOne.activeTasks) { - theChosenOne = worker; - } - } - - if (theChosenOne.activeTasks > 0 && workers.length < maxWorkers) { - theChosenOne = createWorkerMain(); - workers.push(theChosenOne); - } - } - } else { - theChosenOne = createWorkerMain(); - workers.push(theChosenOne); - } - - theChosenOne.activeTasks++; - theChosenOne.sendQueue.push(msg); - }; - - const flushSendQueue = () => { - isQueued = false; - queuedSendMsgs.forEach(queueMsgToWorker); - queuedSendMsgs.length = 0; - workers.forEach(sendMsgsToWorkers); - }; - - const send = (...args: any[]) => - new Promise((resolve, reject) => { - if (isDestroyed) { - reject(TASK_CANCELED_MSG); - } else { - const msg: d.MsgToWorker = { - stencilId: msgIds++, - args, - }; - queuedSendMsgs.push(msg); - times.set(msg.stencilId, Date.now()); - - tasks.set(msg.stencilId, { - resolve, - reject, - }); - - if (!isQueued) { - isQueued = true; - queueMicrotask(flushSendQueue); - } - } - }); - - const destroy = () => { - isDestroyed = true; - tasks.forEach((t) => t.reject(TASK_CANCELED_MSG)); - tasks.clear(); - workers.forEach((w) => w.worker.terminate()); - workers.length = 0; - }; - - const handler = (name: string) => { - return function (...args: any[]) { - return send(name, ...args); - }; - }; - - return { - send, - destroy, - handler, - maxWorkers, - }; -}; - -interface WorkerChild { - worker: Worker; - activeTasks: number; - sendQueue: d.MsgToWorker[]; -} diff --git a/src/sys/deno/deno-worker-thread.ts b/src/sys/deno/deno-worker-thread.ts deleted file mode 100644 index f24daf43e20..00000000000 --- a/src/sys/deno/deno-worker-thread.ts +++ /dev/null @@ -1,71 +0,0 @@ -import type { MsgFromWorker, MsgToWorker, WorkerMsgHandler } from '../../declarations'; - -export const initDenoWorkerThread = (glbl: any, msgHandler: WorkerMsgHandler) => { - let isQueued = false; - - const msgsFromWorkerQueue: MsgFromWorker[] = []; - - const drainMsgQueueFromWorkerToMain = () => { - isQueued = false; - glbl.postMessage(msgsFromWorkerQueue); - msgsFromWorkerQueue.length = 0; - }; - - const queueMsgFromWorkerToMain = (msgFromWorkerToMain: MsgFromWorker) => { - msgsFromWorkerQueue.push(msgFromWorkerToMain); - if (!isQueued) { - isQueued = true; - queueMicrotask(drainMsgQueueFromWorkerToMain); - } - }; - - const error = (stencilMsgId: number, err: any) => { - const errMsgFromWorkerToMain: MsgFromWorker = { - stencilId: stencilMsgId, - stencilRtnValue: null, - stencilRtnError: 'Error', - }; - if (typeof err === 'string') { - errMsgFromWorkerToMain.stencilRtnError += ': ' + err; - } else if (err) { - if (err.stack) { - errMsgFromWorkerToMain.stencilRtnError += ': ' + err.stack; - } else if (err.message) { - errMsgFromWorkerToMain.stencilRtnError += ': ' + err.message; - } - } - queueMsgFromWorkerToMain(errMsgFromWorkerToMain); - }; - - const receiveMsgFromMainToWorker = async (msgToWorker: MsgToWorker) => { - if (msgToWorker && typeof msgToWorker.stencilId === 'number') { - try { - // run the handler to get the data - const msgFromWorkerToMain: MsgFromWorker = { - stencilId: msgToWorker.stencilId, - stencilRtnValue: await msgHandler(msgToWorker), - stencilRtnError: null, - }; - queueMsgFromWorkerToMain(msgFromWorkerToMain); - } catch (e) { - // error occurred while running the task - error(msgToWorker.stencilId, e); - } - } - }; - - glbl.onmessage = (ev: MessageEvent) => { - // message from the main thread - const msgsFromMainToWorker: MsgToWorker[] = ev.data; - if (Array.isArray(msgsFromMainToWorker)) { - for (const msgFromMainToWorker of msgsFromMainToWorker) { - receiveMsgFromMainToWorker(msgFromMainToWorker); - } - } - }; - - glbl.onerror = (e: any) => { - // uncaught error occurred on the worker thread - error(-1, e); - }; -}; diff --git a/src/sys/deno/deps.ts b/src/sys/deno/deps.ts deleted file mode 100644 index df57a193f16..00000000000 --- a/src/sys/deno/deps.ts +++ /dev/null @@ -1,31 +0,0 @@ -export { - basename, - delimiter, - dirname, - extname, - win32, - posix, - isAbsolute, - isGlob, - join, - normalize, - parse, - relative, - resolve, - sep, -} from 'https://deno.land/std@0.63.0/path/mod.ts'; -export { - bgRed, - blue, - bold, - cyan, - dim, - gray, - green, - magenta, - red, - yellow, -} from 'https://deno.land/std@0.63.0/fmt/colors.ts'; -export { ensureDirSync, expandGlob } from 'https://deno.land/std@0.63.0/fs/mod.ts'; -export { createRequire } from 'https://deno.land/std@0.63.0/node/module.ts'; -export * as nodeFs from 'https://deno.land/std@0.63.0/node/fs.ts'; diff --git a/src/sys/deno/index.ts b/src/sys/deno/index.ts deleted file mode 100644 index 80835557888..00000000000 --- a/src/sys/deno/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export { createDenoLogger } from './deno-logger'; -export { createDenoSys } from './deno-sys'; diff --git a/src/sys/deno/readme.md b/src/sys/deno/readme.md deleted file mode 100644 index 68ad1d31abd..00000000000 --- a/src/sys/deno/readme.md +++ /dev/null @@ -1,6 +0,0 @@ -# Deep thoughts 🦕 - -- Why no `tmpdir()` without a random suffix each call? Is `makeTempDir()` the only option? -- Why no `stat()` within node fs compat? https://deno.land/std/node/fs.ts -- Why does the worker take so long to startup? The larger the file, the longer the startup (3 seconds!!!) -- Why does `stat()` hang if there are multiple large files being async stat opened? diff --git a/src/sys/deno/worker.ts b/src/sys/deno/worker.ts deleted file mode 100644 index 7120912fc18..00000000000 --- a/src/sys/deno/worker.ts +++ /dev/null @@ -1,12 +0,0 @@ -import '@stencil/core/compiler'; -import { initDenoWorkerThread } from './deno-worker-thread'; -import { createDenoSys } from '@sys-api-deno'; -import type { Deno as DenoTypes } from '../../../types/lib.deno'; - -declare const Deno: typeof DenoTypes; - -const coreCompiler = (globalThis as any).stencil as typeof import('@stencil/core/compiler'); -const denoSys = createDenoSys({ Deno }); -const msgHandler = coreCompiler.createWorkerMessageHandler(denoSys); - -initDenoWorkerThread(globalThis, msgHandler); diff --git a/tsconfig.json b/tsconfig.json index 931b5f96ce3..b72f10245a6 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -28,9 +28,7 @@ "@hydrate-factory": ["src/hydrate/runner/hydrate-factory.ts"], "@platform": ["src/client/index.ts"], "@runtime": ["src/runtime/index.ts"], - "@deno-node-compat": ["src/sys/deno/deno-node-compat.ts"], "@dev-server-process": ["src/dev-server/server-process.ts"], - "@sys-api-deno": ["src/sys/deno/index.ts"], "@sys-api-node": ["src/sys/node/index.ts"], "@stencil/core/compiler": ["src/compiler/index.ts"], "@stencil/core/dev-server": ["src/dev-server/index.ts"], @@ -64,8 +62,6 @@ "src/internal/default.ts", "src/internal/index.ts", "src/mock-doc/index.ts", - "src/sys/deno/index.ts", - "src/sys/deno/worker.ts", "src/sys/node/index.ts", "src/sys/node/worker.ts", "src/sys/node/public.ts", diff --git a/types/deno-deps.d.ts b/types/deno-deps.d.ts deleted file mode 100644 index 2b491c0585b..00000000000 --- a/types/deno-deps.d.ts +++ /dev/null @@ -1,59 +0,0 @@ -declare module 'https://deno.land/std@0.63.0/fs/mod.ts' { - export interface WalkEntry { - name: string; - isFile: boolean; - isDirectory: boolean; - isSymlink: boolean; - path: string; - } - export function ensureDirSync(dir: string): Promise; - export function expandGlob( - glob: string, - opts?: { - root?: string; - exclude?: string[]; - includeDirs?: boolean; - extended?: boolean; - globstar?: boolean; - }, - ): AsyncIterableIterator; -} - -declare module 'https://deno.land/std@0.63.0/path/mod.ts' { - export function isGlob(p: string): boolean; - export function normalize(p: string): string; - export function join(...paths: string[]): string; - export function resolve(...pathSegments: string[]): string; - export function isAbsolute(p: string): boolean; - export function relative(from: string, to: string): string; - export function dirname(p: string): string; - export function basename(p: string, ext?: string): string; - export function extname(p: string): string; - export function parse(p: string): any; - export const sep: string; - export const delimiter: string; - export const posix: any; - export const win32: any; -} - -declare module 'https://deno.land/std@0.63.0/node/fs.ts' { - export default function nodeFs(): any; -} - -declare module 'https://deno.land/std@0.63.0/fmt/colors.ts' { - export function bgRed(str: string): string; - export function blue(str: string): string; - export function bold(str: string): string; - export function cyan(str: string): string; - export function dim(str: string): string; - export function gray(str: string): string; - export function green(str: string): string; - export function magenta(str: string): string; - export function red(str: string): string; - export function yellow(str: string): string; -} - -declare module 'https://deno.land/std@0.63.0/node/module.ts' { - export const builtinModules: string[]; - export function createRequire(filename: string | URL): any; -} diff --git a/types/lib.deno.d.ts b/types/lib.deno.d.ts deleted file mode 100644 index 3bfe3a50598..00000000000 --- a/types/lib.deno.d.ts +++ /dev/null @@ -1,3351 +0,0 @@ -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. - -/// - -export namespace Deno { - /** A set of error constructors that are raised by Deno APIs. */ - export const errors: { - NotFound: ErrorConstructor; - PermissionDenied: ErrorConstructor; - ConnectionRefused: ErrorConstructor; - ConnectionReset: ErrorConstructor; - ConnectionAborted: ErrorConstructor; - NotConnected: ErrorConstructor; - AddrInUse: ErrorConstructor; - AddrNotAvailable: ErrorConstructor; - BrokenPipe: ErrorConstructor; - AlreadyExists: ErrorConstructor; - InvalidData: ErrorConstructor; - TimedOut: ErrorConstructor; - Interrupted: ErrorConstructor; - WriteZero: ErrorConstructor; - UnexpectedEof: ErrorConstructor; - BadResource: ErrorConstructor; - Http: ErrorConstructor; - Busy: ErrorConstructor; - }; - - /** The current process id of the runtime. */ - export const pid: number; - - /** Reflects the `NO_COLOR` environment variable. - * - * See: https://no-color.org/ */ - export const noColor: boolean; - - export interface TestDefinition { - fn: () => void | Promise; - name: string; - ignore?: boolean; - /** Check that the number of async completed ops after the test is the same - * as number of dispatched ops. Defaults to true.*/ - sanitizeOps?: boolean; - /** Ensure the test case does not "leak" resources - ie. the resource table - * after the test has exactly the same contents as before the test. Defaults - * to true. */ - sanitizeResources?: boolean; - } - - /** Register a test which will be run when `deno test` is used on the command - * line and the containing module looks like a test module. - * `fn` can be async if required. - * ```ts - * import {assert, fail, assertEquals} from "https://deno.land/std/testing/asserts.ts"; - * - * Deno.test({ - * name: "example test", - * fn(): void { - * assertEquals("world", "world"); - * }, - * }); - * - * Deno.test({ - * name: "example ignored test", - * ignore: Deno.build.os === "windows", - * fn(): void { - * // This test is ignored only on Windows machines - * }, - * }); - * - * Deno.test({ - * name: "example async test", - * async fn() { - * const decoder = new TextDecoder("utf-8"); - * const data = await Deno.readFile("hello_world.txt"); - * assertEquals(decoder.decode(data), "Hello world"); - * } - * }); - * ``` - */ - export function test(t: TestDefinition): void; - - /** Register a test which will be run when `deno test` is used on the command - * line and the containing module looks like a test module. - * `fn` can be async if required. - * - * ```ts - * import {assert, fail, assertEquals} from "https://deno.land/std/testing/asserts.ts"; - * - * Deno.test("My test description", ():void => { - * assertEquals("hello", "hello"); - * }); - * - * Deno.test("My async test description", async ():Promise => { - * const decoder = new TextDecoder("utf-8"); - * const data = await Deno.readFile("hello_world.txt"); - * assertEquals(decoder.decode(data), "Hello world"); - * }); - * ``` - * */ - export function test(name: string, fn: () => void | Promise): void; - - /** Exit the Deno process with optional exit code. If no exit code is supplied - * then Deno will exit with return code of 0. - * - * ```ts - * Deno.exit(5); - * ``` - */ - export function exit(code?: number): never; - - export const env: { - /** Retrieve the value of an environment variable. Returns undefined if that - * key doesn't exist. - * - * ```ts - * console.log(Deno.env.get("HOME")); // e.g. outputs "/home/alice" - * console.log(Deno.env.get("MADE_UP_VAR")); // outputs "Undefined" - * ``` - * Requires `allow-env` permission. */ - get(key: string): string | undefined; - - /** Set the value of an environment variable. - * - * ```ts - * Deno.env.set("SOME_VAR", "Value")); - * Deno.env.get("SOME_VAR"); // outputs "Value" - * ``` - * - * Requires `allow-env` permission. */ - set(key: string, value: string): void; - - /** Returns a snapshot of the environment variables at invocation. - * - * ```ts - * Deno.env.set("TEST_VAR", "A"); - * const myEnv = Deno.env.toObject(); - * console.log(myEnv.SHELL); - * Deno.env.set("TEST_VAR", "B"); - * console.log(myEnv.TEST_VAR); // outputs "A" - * ``` - * - * Requires `allow-env` permission. */ - toObject(): { [index: string]: string }; - }; - - /** - * Returns the path to the current deno executable. - * - * ```ts - * console.log(Deno.execPath()); // e.g. "/home/alice/.local/bin/deno" - * ``` - * - * Requires `allow-read` permission. - */ - export function execPath(): string; - - /** - * Change the current working directory to the specified path. - * - * ```ts - * Deno.chdir("/home/userA"); - * Deno.chdir("../userB"); - * Deno.chdir("C:\\Program Files (x86)\\Java"); - * ``` - * - * Throws `Deno.errors.NotFound` if directory not found. - * Throws `Deno.errors.PermissionDenied` if the user does not have access - * rights - * - * Requires --allow-read. - */ - export function chdir(directory: string): void; - - /** - * Return a string representing the current working directory. - * - * If the current directory can be reached via multiple paths (due to symbolic - * links), `cwd()` may return any one of them. - * - * ```ts - * const currentWorkingDirectory = Deno.cwd(); - * ``` - * - * Throws `Deno.errors.NotFound` if directory not available. - * - * Requires --allow-read - */ - export function cwd(): string; - - export enum SeekMode { - Start = 0, - Current = 1, - End = 2, - } - - export interface Reader { - /** Reads up to `p.byteLength` bytes into `p`. It resolves to the number of - * bytes read (`0` < `n` <= `p.byteLength`) and rejects if any error - * encountered. Even if `read()` resolves to `n` < `p.byteLength`, it may - * use all of `p` as scratch space during the call. If some data is - * available but not `p.byteLength` bytes, `read()` conventionally resolves - * to what is available instead of waiting for more. - * - * When `read()` encounters end-of-file condition, it resolves to EOF - * (`null`). - * - * When `read()` encounters an error, it rejects with an error. - * - * Callers should always process the `n` > `0` bytes returned before - * considering the EOF (`null`). Doing so correctly handles I/O errors that - * happen after reading some bytes and also both of the allowed EOF - * behaviors. - * - * Implementations should not retain a reference to `p`. - * - * Use Deno.iter() to turn a Reader into an AsyncIterator. - */ - read(p: Uint8Array): Promise; - } - - export interface ReaderSync { - /** Reads up to `p.byteLength` bytes into `p`. It resolves to the number - * of bytes read (`0` < `n` <= `p.byteLength`) and rejects if any error - * encountered. Even if `read()` returns `n` < `p.byteLength`, it may use - * all of `p` as scratch space during the call. If some data is available - * but not `p.byteLength` bytes, `read()` conventionally returns what is - * available instead of waiting for more. - * - * When `readSync()` encounters end-of-file condition, it returns EOF - * (`null`). - * - * When `readSync()` encounters an error, it throws with an error. - * - * Callers should always process the `n` > `0` bytes returned before - * considering the EOF (`null`). Doing so correctly handles I/O errors that happen - * after reading some bytes and also both of the allowed EOF behaviors. - * - * Implementations should not retain a reference to `p`. - * - * Use Deno.iterSync() to turn a ReaderSync into an Iterator. - */ - readSync(p: Uint8Array): number | null; - } - - export interface Writer { - /** Writes `p.byteLength` bytes from `p` to the underlying data stream. It - * resolves to the number of bytes written from `p` (`0` <= `n` <= - * `p.byteLength`) or reject with the error encountered that caused the - * write to stop early. `write()` must reject with a non-null error if - * would resolve to `n` < `p.byteLength`. `write()` must not modify the - * slice data, even temporarily. - * - * Implementations should not retain a reference to `p`. - */ - write(p: Uint8Array): Promise; - } - - export interface WriterSync { - /** Writes `p.byteLength` bytes from `p` to the underlying data - * stream. It returns the number of bytes written from `p` (`0` <= `n` - * <= `p.byteLength`) and any error encountered that caused the write to - * stop early. `writeSync()` must throw a non-null error if it returns `n` < - * `p.byteLength`. `writeSync()` must not modify the slice data, even - * temporarily. - * - * Implementations should not retain a reference to `p`. - */ - writeSync(p: Uint8Array): number; - } - - export interface Closer { - close(): void; - } - - export interface Seeker { - /** Seek sets the offset for the next `read()` or `write()` to offset, - * interpreted according to `whence`: `Start` means relative to the - * start of the file, `Current` means relative to the current offset, - * and `End` means relative to the end. Seek resolves to the new offset - * relative to the start of the file. - * - * Seeking to an offset before the start of the file is an error. Seeking to - * any positive offset is legal, but the behavior of subsequent I/O - * operations on the underlying object is implementation-dependent. - * It returns the number of cursor position. - */ - seek(offset: number, whence: SeekMode): Promise; - } - - export interface SeekerSync { - /** Seek sets the offset for the next `readSync()` or `writeSync()` to - * offset, interpreted according to `whence`: `Start` means relative - * to the start of the file, `Current` means relative to the current - * offset, and `End` means relative to the end. - * - * Seeking to an offset before the start of the file is an error. Seeking to - * any positive offset is legal, but the behavior of subsequent I/O - * operations on the underlying object is implementation-dependent. - */ - seekSync(offset: number, whence: SeekMode): number; - } - - /** Copies from `src` to `dst` until either EOF (`null`) is read from `src` or - * an error occurs. It resolves to the number of bytes copied or rejects with - * the first error encountered while copying. - * - * ```ts - * const source = await Deno.open("my_file.txt"); - * const buffer = new Deno.Buffer() - * const bytesCopied1 = await Deno.copy(source, Deno.stdout); - * const bytesCopied2 = await Deno.copy(source, buffer); - * ``` - * - * @param src The source to copy from - * @param dst The destination to copy to - * @param options Can be used to tune size of the buffer. Default size is 32kB - */ - export function copy( - src: Reader, - dst: Writer, - options?: { - bufSize?: number; - }, - ): Promise; - - /** Turns a Reader, `r`, into an async iterator. - * - * ```ts - * let f = await Deno.open("/etc/passwd"); - * for await (const chunk of Deno.iter(f)) { - * console.log(chunk); - * } - * f.close(); - * ``` - * - * Second argument can be used to tune size of a buffer. - * Default size of the buffer is 32kB. - * - * ```ts - * let f = await Deno.open("/etc/passwd"); - * const iter = Deno.iter(f, { - * bufSize: 1024 * 1024 - * }); - * for await (const chunk of iter) { - * console.log(chunk); - * } - * f.close(); - * ``` - * - * Iterator uses an internal buffer of fixed size for efficiency; it returns - * a view on that buffer on each iteration. It is therefore caller's - * responsibility to copy contents of the buffer if needed; otherwise the - * next iteration will overwrite contents of previously returned chunk. - */ - export function iter( - r: Reader, - options?: { - bufSize?: number; - }, - ): AsyncIterableIterator; - - /** Turns a ReaderSync, `r`, into an iterator. - * - * ```ts - * let f = Deno.openSync("/etc/passwd"); - * for (const chunk of Deno.iterSync(f)) { - * console.log(chunk); - * } - * f.close(); - * ``` - * - * Second argument can be used to tune size of a buffer. - * Default size of the buffer is 32kB. - * - * ```ts - * let f = await Deno.open("/etc/passwd"); - * const iter = Deno.iterSync(f, { - * bufSize: 1024 * 1024 - * }); - * for (const chunk of iter) { - * console.log(chunk); - * } - * f.close(); - * ``` - * - * Iterator uses an internal buffer of fixed size for efficiency; it returns - * a view on that buffer on each iteration. It is therefore caller's - * responsibility to copy contents of the buffer if needed; otherwise the - * next iteration will overwrite contents of previously returned chunk. - */ - export function iterSync( - r: ReaderSync, - options?: { - bufSize?: number; - }, - ): IterableIterator; - - /** Synchronously open a file and return an instance of `Deno.File`. The - * file does not need to previously exist if using the `create` or `createNew` - * open options. It is the callers responsibility to close the file when finished - * with it. - * - * ```ts - * const file = Deno.openSync("/foo/bar.txt", { read: true, write: true }); - * // Do work with file - * Deno.close(file.rid); - * ``` - * - * Requires `allow-read` and/or `allow-write` permissions depending on options. - */ - export function openSync(path: string, options?: OpenOptions): File; - - /** Open a file and resolve to an instance of `Deno.File`. The - * file does not need to previously exist if using the `create` or `createNew` - * open options. It is the callers responsibility to close the file when finished - * with it. - * - * ```ts - * const file = await Deno.open("/foo/bar.txt", { read: true, write: true }); - * // Do work with file - * Deno.close(file.rid); - * ``` - * - * Requires `allow-read` and/or `allow-write` permissions depending on options. - */ - export function open(path: string, options?: OpenOptions): Promise; - - /** Creates a file if none exists or truncates an existing file and returns - * an instance of `Deno.File`. - * - * ```ts - * const file = Deno.createSync("/foo/bar.txt"); - * ``` - * - * Requires `allow-read` and `allow-write` permissions. - */ - export function createSync(path: string): File; - - /** Creates a file if none exists or truncates an existing file and resolves to - * an instance of `Deno.File`. - * - * ```ts - * const file = await Deno.create("/foo/bar.txt"); - * ``` - * - * Requires `allow-read` and `allow-write` permissions. - */ - export function create(path: string): Promise; - - /** Synchronously read from a resource ID (`rid`) into an array buffer (`buffer`). - * - * Returns either the number of bytes read during the operation or EOF - * (`null`) if there was nothing more to read. - * - * It is possible for a read to successfully return with `0` bytes. This does - * not indicate EOF. - * - * This function is one of the lowest level APIs and most users should not - * work with this directly, but rather use Deno.readAllSync() instead. - * - * **It is not guaranteed that the full buffer will be read in a single call.** - * - * ```ts - * // if "/foo/bar.txt" contains the text "hello world": - * const file = Deno.openSync("/foo/bar.txt"); - * const buf = new Uint8Array(100); - * const numberOfBytesRead = Deno.readSync(file.rid, buf); // 11 bytes - * const text = new TextDecoder().decode(buf); // "hello world" - * Deno.close(file.rid); - * ``` - */ - export function readSync(rid: number, buffer: Uint8Array): number | null; - - /** Read from a resource ID (`rid`) into an array buffer (`buffer`). - * - * Resolves to either the number of bytes read during the operation or EOF - * (`null`) if there was nothing more to read. - * - * It is possible for a read to successfully return with `0` bytes. This does - * not indicate EOF. - * - * This function is one of the lowest level APIs and most users should not - * work with this directly, but rather use Deno.readAll() instead. - * - * **It is not guaranteed that the full buffer will be read in a single call.** - * - * ```ts - * // if "/foo/bar.txt" contains the text "hello world": - * const file = await Deno.open("/foo/bar.txt"); - * const buf = new Uint8Array(100); - * const numberOfBytesRead = await Deno.read(file.rid, buf); // 11 bytes - * const text = new TextDecoder().decode(buf); // "hello world" - * Deno.close(file.rid); - * ``` - */ - export function read(rid: number, buffer: Uint8Array): Promise; - - /** Synchronously write to the resource ID (`rid`) the contents of the array - * buffer (`data`). - * - * Returns the number of bytes written. This function is one of the lowest - * level APIs and most users should not work with this directly, but rather use - * Deno.writeAllSync() instead. - * - * **It is not guaranteed that the full buffer will be written in a single - * call.** - * - * ```ts - * const encoder = new TextEncoder(); - * const data = encoder.encode("Hello world"); - * const file = Deno.openSync("/foo/bar.txt", {write: true}); - * const bytesWritten = Deno.writeSync(file.rid, data); // 11 - * Deno.close(file.rid); - * ``` - */ - export function writeSync(rid: number, data: Uint8Array): number; - - /** Write to the resource ID (`rid`) the contents of the array buffer (`data`). - * - * Resolves to the number of bytes written. This function is one of the lowest - * level APIs and most users should not work with this directly, but rather use - * Deno.writeAll() instead. - * - * **It is not guaranteed that the full buffer will be written in a single - * call.** - * - * ```ts - * const encoder = new TextEncoder(); - * const data = encoder.encode("Hello world"); - * const file = await Deno.open("/foo/bar.txt", { write: true }); - * const bytesWritten = await Deno.write(file.rid, data); // 11 - * Deno.close(file.rid); - * ``` - */ - export function write(rid: number, data: Uint8Array): Promise; - - /** Synchronously seek a resource ID (`rid`) to the given `offset` under mode - * given by `whence`. The new position within the resource (bytes from the - * start) is returned. - * - * ```ts - * const file = Deno.openSync('hello.txt', {read: true, write: true, truncate: true, create: true}); - * Deno.writeSync(file.rid, new TextEncoder().encode("Hello world")); - * // advance cursor 6 bytes - * const cursorPosition = Deno.seekSync(file.rid, 6, Deno.SeekMode.Start); - * console.log(cursorPosition); // 6 - * const buf = new Uint8Array(100); - * file.readSync(buf); - * console.log(new TextDecoder().decode(buf)); // "world" - * ``` - * - * The seek modes work as follows: - * - * ```ts - * // Given file.rid pointing to file with "Hello world", which is 11 bytes long: - * // Seek 6 bytes from the start of the file - * console.log(Deno.seekSync(file.rid, 6, Deno.SeekMode.Start)); // "6" - * // Seek 2 more bytes from the current position - * console.log(Deno.seekSync(file.rid, 2, Deno.SeekMode.Current)); // "8" - * // Seek backwards 2 bytes from the end of the file - * console.log(Deno.seekSync(file.rid, -2, Deno.SeekMode.End)); // "9" (e.g. 11-2) - * ``` - */ - export function seekSync(rid: number, offset: number, whence: SeekMode): number; - - /** Seek a resource ID (`rid`) to the given `offset` under mode given by `whence`. - * The call resolves to the new position within the resource (bytes from the start). - * - * ```ts - * const file = await Deno.open('hello.txt', {read: true, write: true, truncate: true, create: true}); - * await Deno.write(file.rid, new TextEncoder().encode("Hello world")); - * // advance cursor 6 bytes - * const cursorPosition = await Deno.seek(file.rid, 6, Deno.SeekMode.Start); - * console.log(cursorPosition); // 6 - * const buf = new Uint8Array(100); - * await file.read(buf); - * console.log(new TextDecoder().decode(buf)); // "world" - * ``` - * - * The seek modes work as follows: - * - * ```ts - * // Given file.rid pointing to file with "Hello world", which is 11 bytes long: - * // Seek 6 bytes from the start of the file - * console.log(await Deno.seek(file.rid, 6, Deno.SeekMode.Start)); // "6" - * // Seek 2 more bytes from the current position - * console.log(await Deno.seek(file.rid, 2, Deno.SeekMode.Current)); // "8" - * // Seek backwards 2 bytes from the end of the file - * console.log(await Deno.seek(file.rid, -2, Deno.SeekMode.End)); // "9" (e.g. 11-2) - * ``` - */ - export function seek(rid: number, offset: number, whence: SeekMode): Promise; - - /** Close the given resource ID (rid) which has been previously opened, such - * as via opening or creating a file. Closing a file when you are finished - * with it is important to avoid leaking resources. - * - * ```ts - * const file = await Deno.open("my_file.txt"); - * // do work with "file" object - * Deno.close(file.rid); - * ```` - */ - export function close(rid: number): void; - - /** The Deno abstraction for reading and writing files. */ - export class File implements Reader, ReaderSync, Writer, WriterSync, Seeker, SeekerSync, Closer { - readonly rid: number; - constructor(rid: number); - write(p: Uint8Array): Promise; - writeSync(p: Uint8Array): number; - read(p: Uint8Array): Promise; - readSync(p: Uint8Array): number | null; - seek(offset: number, whence: SeekMode): Promise; - seekSync(offset: number, whence: SeekMode): number; - close(): void; - } - - /** A handle for `stdin`. */ - export const stdin: Reader & ReaderSync & Closer & { rid: number }; - /** A handle for `stdout`. */ - export const stdout: Writer & WriterSync & Closer & { rid: number }; - /** A handle for `stderr`. */ - export const stderr: Writer & WriterSync & Closer & { rid: number }; - - export interface OpenOptions { - /** Sets the option for read access. This option, when `true`, means that the - * file should be read-able if opened. */ - read?: boolean; - /** Sets the option for write access. This option, when `true`, means that - * the file should be write-able if opened. If the file already exists, - * any write calls on it will overwrite its contents, by default without - * truncating it. */ - write?: boolean; - /**Sets the option for the append mode. This option, when `true`, means that - * writes will append to a file instead of overwriting previous contents. - * Note that setting `{ write: true, append: true }` has the same effect as - * setting only `{ append: true }`. */ - append?: boolean; - /** Sets the option for truncating a previous file. If a file is - * successfully opened with this option set it will truncate the file to `0` - * size if it already exists. The file must be opened with write access - * for truncate to work. */ - truncate?: boolean; - /** Sets the option to allow creating a new file, if one doesn't already - * exist at the specified path. Requires write or append access to be - * used. */ - create?: boolean; - /** Defaults to `false`. If set to `true`, no file, directory, or symlink is - * allowed to exist at the target location. Requires write or append - * access to be used. When createNew is set to `true`, create and truncate - * are ignored. */ - createNew?: boolean; - /** Permissions to use if creating the file (defaults to `0o666`, before - * the process's umask). - * Ignored on Windows. */ - mode?: number; - } - - /** - * - * Check if a given resource id (`rid`) is a TTY. - * - * ```ts - * // This example is system and context specific - * const nonTTYRid = Deno.openSync("my_file.txt").rid; - * const ttyRid = Deno.openSync("/dev/tty6").rid; - * console.log(Deno.isatty(nonTTYRid)); // false - * console.log(Deno.isatty(ttyRid)); // true - * Deno.close(nonTTYRid); - * Deno.close(ttyRid); - * ``` - */ - export function isatty(rid: number): boolean; - - /** A variable-sized buffer of bytes with `read()` and `write()` methods. - * - * Deno.Buffer is almost always used with some I/O like files and sockets. It - * allows one to buffer up a download from a socket. Buffer grows and shrinks - * as necessary. - * - * Deno.Buffer is NOT the same thing as Node's Buffer. Node's Buffer was - * created in 2009 before JavaScript had the concept of ArrayBuffers. It's - * simply a non-standard ArrayBuffer. - * - * ArrayBuffer is a fixed memory allocation. Deno.Buffer is implemented on top - * of ArrayBuffer. - * - * Based on [Go Buffer](https://golang.org/pkg/bytes/#Buffer). */ - export class Buffer implements Reader, ReaderSync, Writer, WriterSync { - constructor(ab?: ArrayBuffer); - /** Returns a slice holding the unread portion of the buffer. - * - * The slice is valid for use only until the next buffer modification (that - * is, only until the next call to a method like `read()`, `write()`, - * `reset()`, or `truncate()`). The slice aliases the buffer content at - * least until the next buffer modification, so immediate changes to the - * slice will affect the result of future reads. */ - bytes(): Uint8Array; - /** Returns whether the unread portion of the buffer is empty. */ - empty(): boolean; - /** A read only number of bytes of the unread portion of the buffer. */ - readonly length: number; - /** The read only capacity of the buffer's underlying byte slice, that is, - * the total space allocated for the buffer's data. */ - readonly capacity: number; - /** Discards all but the first `n` unread bytes from the buffer but - * continues to use the same allocated storage. It throws if `n` is - * negative or greater than the length of the buffer. */ - truncate(n: number): void; - /** Resets the buffer to be empty, but it retains the underlying storage for - * use by future writes. `.reset()` is the same as `.truncate(0)`. */ - reset(): void; - /** Reads the next `p.length` bytes from the buffer or until the buffer is - * drained. Returns the number of bytes read. If the buffer has no data to - * return, the return is EOF (`null`). */ - readSync(p: Uint8Array): number | null; - /** Reads the next `p.length` bytes from the buffer or until the buffer is - * drained. Resolves to the number of bytes read. If the buffer has no - * data to return, resolves to EOF (`null`). - * - * NOTE: This methods reads bytes sychronously; it's provided for - * compatibility with `Reader` interfaces. - */ - read(p: Uint8Array): Promise; - writeSync(p: Uint8Array): number; - /** NOTE: This methods writes bytes sychronously; it's provided for - * compatibility with `Writer` interface. */ - write(p: Uint8Array): Promise; - /** Grows the buffer's capacity, if necessary, to guarantee space for - * another `n` bytes. After `.grow(n)`, at least `n` bytes can be written to - * the buffer without another allocation. If `n` is negative, `.grow()` will - * throw. If the buffer can't grow it will throw an error. - * - * Based on Go Lang's - * [Buffer.Grow](https://golang.org/pkg/bytes/#Buffer.Grow). */ - grow(n: number): void; - /** Reads data from `r` until EOF (`null`) and appends it to the buffer, - * growing the buffer as needed. It resolves to the number of bytes read. - * If the buffer becomes too large, `.readFrom()` will reject with an error. - * - * Based on Go Lang's - * [Buffer.ReadFrom](https://golang.org/pkg/bytes/#Buffer.ReadFrom). */ - readFrom(r: Reader): Promise; - /** Reads data from `r` until EOF (`null`) and appends it to the buffer, - * growing the buffer as needed. It returns the number of bytes read. If the - * buffer becomes too large, `.readFromSync()` will throw an error. - * - * Based on Go Lang's - * [Buffer.ReadFrom](https://golang.org/pkg/bytes/#Buffer.ReadFrom). */ - readFromSync(r: ReaderSync): number; - } - - /** Read Reader `r` until EOF (`null`) and resolve to the content as - * Uint8Array`. - * - * ```ts - * // Example from stdin - * const stdinContent = await Deno.readAll(Deno.stdin); - * - * // Example from file - * const file = await Deno.open("my_file.txt", {read: true}); - * const myFileContent = await Deno.readAll(file); - * Deno.close(file.rid); - * - * // Example from buffer - * const myData = new Uint8Array(100); - * // ... fill myData array with data - * const reader = new Deno.Buffer(myData.buffer as ArrayBuffer); - * const bufferContent = await Deno.readAll(reader); - * ``` - */ - export function readAll(r: Reader): Promise; - - /** Synchronously reads Reader `r` until EOF (`null`) and returns the content - * as `Uint8Array`. - * - * ```ts - * // Example from stdin - * const stdinContent = Deno.readAllSync(Deno.stdin); - * - * // Example from file - * const file = Deno.openSync("my_file.txt", {read: true}); - * const myFileContent = Deno.readAllSync(file); - * Deno.close(file.rid); - * - * // Example from buffer - * const myData = new Uint8Array(100); - * // ... fill myData array with data - * const reader = new Deno.Buffer(myData.buffer as ArrayBuffer); - * const bufferContent = Deno.readAllSync(reader); - * ``` - */ - export function readAllSync(r: ReaderSync): Uint8Array; - - /** Write all the content of the array buffer (`arr`) to the writer (`w`). - * - * ```ts - * // Example writing to stdout - * const contentBytes = new TextEncoder().encode("Hello World"); - * await Deno.writeAll(Deno.stdout, contentBytes); - * - * // Example writing to file - * const contentBytes = new TextEncoder().encode("Hello World"); - * const file = await Deno.open('test.file', {write: true}); - * await Deno.writeAll(file, contentBytes); - * Deno.close(file.rid); - * - * // Example writing to buffer - * const contentBytes = new TextEncoder().encode("Hello World"); - * const writer = new Deno.Buffer(); - * await Deno.writeAll(writer, contentBytes); - * console.log(writer.bytes().length); // 11 - * ``` - */ - export function writeAll(w: Writer, arr: Uint8Array): Promise; - - /** Synchronously write all the content of the array buffer (`arr`) to the - * writer (`w`). - * - * ```ts - * // Example writing to stdout - * const contentBytes = new TextEncoder().encode("Hello World"); - * Deno.writeAllSync(Deno.stdout, contentBytes); - * - * // Example writing to file - * const contentBytes = new TextEncoder().encode("Hello World"); - * const file = Deno.openSync('test.file', {write: true}); - * Deno.writeAllSync(file, contentBytes); - * Deno.close(file.rid); - * - * // Example writing to buffer - * const contentBytes = new TextEncoder().encode("Hello World"); - * const writer = new Deno.Buffer(); - * Deno.writeAllSync(writer, contentBytes); - * console.log(writer.bytes().length); // 11 - * ``` - */ - export function writeAllSync(w: WriterSync, arr: Uint8Array): void; - - export interface MkdirOptions { - /** Defaults to `false`. If set to `true`, means that any intermediate - * directories will also be created (as with the shell command `mkdir -p`). - * Intermediate directories are created with the same permissions. - * When recursive is set to `true`, succeeds silently (without changing any - * permissions) if a directory already exists at the path, or if the path - * is a symlink to an existing directory. */ - recursive?: boolean; - /** Permissions to use when creating the directory (defaults to `0o777`, - * before the process's umask). - * Ignored on Windows. */ - mode?: number; - } - - /** Synchronously creates a new directory with the specified path. - * - * ```ts - * Deno.mkdirSync("new_dir"); - * Deno.mkdirSync("nested/directories", { recursive: true }); - * Deno.mkdirSync("restricted_access_dir", { mode: 0o700 }); - * ``` - * - * Defaults to throwing error if the directory already exists. - * - * Requires `allow-write` permission. */ - export function mkdirSync(path: string, options?: MkdirOptions): void; - - /** Creates a new directory with the specified path. - * - * ```ts - * await Deno.mkdir("new_dir"); - * await Deno.mkdir("nested/directories", { recursive: true }); - * await Deno.mkdir("restricted_access_dir", { mode: 0o700 }); - * ``` - * - * Defaults to throwing error if the directory already exists. - * - * Requires `allow-write` permission. */ - export function mkdir(path: string, options?: MkdirOptions): Promise; - - export interface MakeTempOptions { - /** Directory where the temporary directory should be created (defaults to - * the env variable TMPDIR, or the system's default, usually /tmp). - * - * Note that if the passed `dir` is relative, the path returned by - * makeTempFile() and makeTempDir() will also be relative. Be mindful of - * this when changing working directory. */ - dir?: string; - /** String that should precede the random portion of the temporary - * directory's name. */ - prefix?: string; - /** String that should follow the random portion of the temporary - * directory's name. */ - suffix?: string; - } - - /** Synchronously creates a new temporary directory in the default directory - * for temporary files (see also `Deno.dir("temp")`), unless `dir` is specified. - * Other optional options include prefixing and suffixing the directory name - * with `prefix` and `suffix` respectively. - * - * The full path to the newly created directory is returned. - * - * Multiple programs calling this function simultaneously will create different - * directories. It is the caller's responsibility to remove the directory when - * no longer needed. - * - * ```ts - * const tempDirName0 = Deno.makeTempDirSync(); // e.g. /tmp/2894ea76 - * const tempDirName1 = Deno.makeTempDirSync({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d - * ``` - * - * Requires `allow-write` permission. */ - // TODO(ry) Doesn't check permissions. - export function makeTempDirSync(options?: MakeTempOptions): string; - - /** Creates a new temporary directory in the default directory for temporary - * files (see also `Deno.dir("temp")`), unless `dir` is specified. Other - * optional options include prefixing and suffixing the directory name with - * `prefix` and `suffix` respectively. - * - * This call resolves to the full path to the newly created directory. - * - * Multiple programs calling this function simultaneously will create different - * directories. It is the caller's responsibility to remove the directory when - * no longer needed. - * - * ```ts - * const tempDirName0 = await Deno.makeTempDir(); // e.g. /tmp/2894ea76 - * const tempDirName1 = await Deno.makeTempDir({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d - * ``` - * - * Requires `allow-write` permission. */ - // TODO(ry) Doesn't check permissions. - export function makeTempDir(options?: MakeTempOptions): Promise; - - /** Synchronously creates a new temporary file in the default directory for - * temporary files (see also `Deno.dir("temp")`), unless `dir` is specified. - * Other optional options include prefixing and suffixing the directory name - * with `prefix` and `suffix` respectively. - * - * The full path to the newly created file is returned. - * - * Multiple programs calling this function simultaneously will create different - * files. It is the caller's responsibility to remove the file when no longer - * needed. - * - * ```ts - * const tempFileName0 = Deno.makeTempFileSync(); // e.g. /tmp/419e0bf2 - * const tempFileName1 = Deno.makeTempFileSync({ prefix: 'my_temp' }); // e.g. /tmp/my_temp754d3098 - * ``` - * - * Requires `allow-write` permission. */ - export function makeTempFileSync(options?: MakeTempOptions): string; - - /** Creates a new temporary file in the default directory for temporary - * files (see also `Deno.dir("temp")`), unless `dir` is specified. Other - * optional options include prefixing and suffixing the directory name with - * `prefix` and `suffix` respectively. - * - * This call resolves to the full path to the newly created file. - * - * Multiple programs calling this function simultaneously will create different - * files. It is the caller's responsibility to remove the file when no longer - * needed. - * - * ```ts - * const tmpFileName0 = await Deno.makeTempFile(); // e.g. /tmp/419e0bf2 - * const tmpFileName1 = await Deno.makeTempFile({ prefix: 'my_temp' }); // e.g. /tmp/my_temp754d3098 - * ``` - * - * Requires `allow-write` permission. */ - export function makeTempFile(options?: MakeTempOptions): Promise; - - /** Synchronously changes the permission of a specific file/directory of - * specified path. Ignores the process's umask. - * - * ```ts - * Deno.chmodSync("/path/to/file", 0o666); - * ``` - * - * For a full description, see [chmod](#chmod) - * - * NOTE: This API currently throws on Windows - * - * Requires `allow-write` permission. */ - export function chmodSync(path: string, mode: number): void; - - /** Changes the permission of a specific file/directory of specified path. - * Ignores the process's umask. - * - * ```ts - * await Deno.chmod("/path/to/file", 0o666); - * ``` - * - * The mode is a sequence of 3 octal numbers. The first/left-most number - * specifies the permissions for the owner. The second number specifies the - * permissions for the group. The last/right-most number specifies the - * permissions for others. For example, with a mode of 0o764, the owner (7) can - * read/write/execute, the group (6) can read/write and everyone else (4) can - * read only. - * - * | Number | Description | - * | ------ | ----------- | - * | 7 | read, write, and execute | - * | 6 | read and write | - * | 5 | read and execute | - * | 4 | read only | - * | 3 | write and execute | - * | 2 | write only | - * | 1 | execute only | - * | 0 | no permission | - * - * NOTE: This API currently throws on Windows - * - * Requires `allow-write` permission. */ - export function chmod(path: string, mode: number): Promise; - - /** Synchronously change owner of a regular file or directory. This functionality - * is not available on Windows. - * - * ```ts - * Deno.chownSync("myFile.txt", 1000, 1002); - * ``` - * - * Requires `allow-write` permission. - * - * Throws Error (not implemented) if executed on Windows - * - * @param path path to the file - * @param uid user id (UID) of the new owner - * @param gid group id (GID) of the new owner - */ - export function chownSync(path: string, uid: number, gid: number): void; - - /** Change owner of a regular file or directory. This functionality - * is not available on Windows. - * - * ```ts - * await Deno.chown("myFile.txt", 1000, 1002); - * ``` - * - * Requires `allow-write` permission. - * - * Throws Error (not implemented) if executed on Windows - * - * @param path path to the file - * @param uid user id (UID) of the new owner - * @param gid group id (GID) of the new owner - */ - export function chown(path: string, uid: number, gid: number): Promise; - - export interface RemoveOptions { - /** Defaults to `false`. If set to `true`, path will be removed even if - * it's a non-empty directory. */ - recursive?: boolean; - } - - /** Synchronously removes the named file or directory. - * - * ```ts - * Deno.removeSync("/path/to/empty_dir/or/file"); - * Deno.removeSync("/path/to/populated_dir/or/file", { recursive: true }); - * ``` - * - * Throws error if permission denied, path not found, or path is a non-empty - * directory and the `recursive` option isn't set to `true`. - * - * Requires `allow-write` permission. */ - export function removeSync(path: string, options?: RemoveOptions): void; - - /** Removes the named file or directory. - * - * ```ts - * await Deno.remove("/path/to/empty_dir/or/file"); - * await Deno.remove("/path/to/populated_dir/or/file", { recursive: true }); - * ``` - * - * Throws error if permission denied, path not found, or path is a non-empty - * directory and the `recursive` option isn't set to `true`. - * - * Requires `allow-write` permission. */ - export function remove(path: string, options?: RemoveOptions): Promise; - - /** Synchronously renames (moves) `oldpath` to `newpath`. Paths may be files or - * directories. If `newpath` already exists and is not a directory, - * `renameSync()` replaces it. OS-specific restrictions may apply when - * `oldpath` and `newpath` are in different directories. - * - * ```ts - * Deno.renameSync("old/path", "new/path"); - * ``` - * - * On Unix, this operation does not follow symlinks at either path. - * - * It varies between platforms when the operation throws errors, and if so what - * they are. It's always an error to rename anything to a non-empty directory. - * - * Requires `allow-read` and `allow-write` permissions. */ - export function renameSync(oldpath: string, newpath: string): void; - - /** Renames (moves) `oldpath` to `newpath`. Paths may be files or directories. - * If `newpath` already exists and is not a directory, `rename()` replaces it. - * OS-specific restrictions may apply when `oldpath` and `newpath` are in - * different directories. - * - * ```ts - * await Deno.rename("old/path", "new/path"); - * ``` - * - * On Unix, this operation does not follow symlinks at either path. - * - * It varies between platforms when the operation throws errors, and if so what - * they are. It's always an error to rename anything to a non-empty directory. - * - * Requires `allow-read` and `allow-write` permission. */ - export function rename(oldpath: string, newpath: string): Promise; - - /** Synchronously reads and returns the entire contents of a file as utf8 encoded string - * encoded string. Reading a directory returns an empty string. - * - * ```ts - * const data = Deno.readTextFileSync("hello.txt"); - * console.log(data); - * ``` - * - * Requires `allow-read` permission. */ - export function readTextFileSync(path: string): string; - - /** Asynchronously reads and returns the entire contents of a file as a utf8 - * encoded string. Reading a directory returns an empty data array. - * - * ```ts - * const data = await Deno.readTextFile("hello.txt"); - * console.log(data); - * ``` - * - * Requires `allow-read` permission. */ - export function readTextFile(path: string): Promise; - - /** Synchronously reads and returns the entire contents of a file as an array - * of bytes. `TextDecoder` can be used to transform the bytes to string if - * required. Reading a directory returns an empty data array. - * - * ```ts - * const decoder = new TextDecoder("utf-8"); - * const data = Deno.readFileSync("hello.txt"); - * console.log(decoder.decode(data)); - * ``` - * - * Requires `allow-read` permission. */ - export function readFileSync(path: string): Uint8Array; - - /** Reads and resolves to the entire contents of a file as an array of bytes. - * `TextDecoder` can be used to transform the bytes to string if required. - * Reading a directory returns an empty data array. - * - * ```ts - * const decoder = new TextDecoder("utf-8"); - * const data = await Deno.readFile("hello.txt"); - * console.log(decoder.decode(data)); - * ``` - * - * Requires `allow-read` permission. */ - export function readFile(path: string): Promise; - - /** A FileInfo describes a file and is returned by `stat`, `lstat`, - * `statSync`, `lstatSync`. */ - export interface FileInfo { - /** True if this is info for a regular file. Mutually exclusive to - * `FileInfo.isDirectory` and `FileInfo.isSymlink`. */ - isFile: boolean; - /** True if this is info for a regular directory. Mutually exclusive to - * `FileInfo.isFile` and `FileInfo.isSymlink`. */ - isDirectory: boolean; - /** True if this is info for a symlink. Mutually exclusive to - * `FileInfo.isFile` and `FileInfo.isDirectory`. */ - isSymlink: boolean; - /** The size of the file, in bytes. */ - size: number; - /** The last modification time of the file. This corresponds to the `mtime` - * field from `stat` on Linux/Mac OS and `ftLastWriteTime` on Windows. This - * may not be available on all platforms. */ - mtime: Date | null; - /** The last access time of the file. This corresponds to the `atime` - * field from `stat` on Unix and `ftLastAccessTime` on Windows. This may not - * be available on all platforms. */ - atime: Date | null; - /** The creation time of the file. This corresponds to the `birthtime` - * field from `stat` on Mac/BSD and `ftCreationTime` on Windows. This may - * not be available on all platforms. */ - birthtime: Date | null; - /** ID of the device containing the file. - * - * _Linux/Mac OS only._ */ - dev: number | null; - /** Inode number. - * - * _Linux/Mac OS only._ */ - ino: number | null; - /** **UNSTABLE**: Match behavior with Go on Windows for `mode`. - * - * The underlying raw `st_mode` bits that contain the standard Unix - * permissions for this file/directory. */ - mode: number | null; - /** Number of hard links pointing to this file. - * - * _Linux/Mac OS only._ */ - nlink: number | null; - /** User ID of the owner of this file. - * - * _Linux/Mac OS only._ */ - uid: number | null; - /** Group ID of the owner of this file. - * - * _Linux/Mac OS only._ */ - gid: number | null; - /** Device ID of this file. - * - * _Linux/Mac OS only._ */ - rdev: number | null; - /** Blocksize for filesystem I/O. - * - * _Linux/Mac OS only._ */ - blksize: number | null; - /** Number of blocks allocated to the file, in 512-byte units. - * - * _Linux/Mac OS only._ */ - blocks: number | null; - } - - /** Returns absolute normalized path, with symbolic links resolved. - * - * ```ts - * // e.g. given /home/alice/file.txt and current directory /home/alice - * Deno.symlinkSync("file.txt", "symlink_file.txt"); - * const realPath = Deno.realPathSync("./file.txt"); - * const realSymLinkPath = Deno.realPathSync("./symlink_file.txt"); - * console.log(realPath); // outputs "/home/alice/file.txt" - * console.log(realSymLinkPath); // outputs "/home/alice/file.txt" - * ``` - * - * Requires `allow-read` permission for the target path. - * Also requires `allow-read` permission for the CWD if the target path is - * relative.*/ - export function realPathSync(path: string): string; - - /** Resolves to the absolute normalized path, with symbolic links resolved. - * - * ```ts - * // e.g. given /home/alice/file.txt and current directory /home/alice - * await Deno.symlink("file.txt", "symlink_file.txt"); - * const realPath = await Deno.realPath("./file.txt"); - * const realSymLinkPath = await Deno.realPath("./symlink_file.txt"); - * console.log(realPath); // outputs "/home/alice/file.txt" - * console.log(realSymLinkPath); // outputs "/home/alice/file.txt" - * ``` - * - * Requires `allow-read` permission for the target path. - * Also requires `allow-read` permission for the CWD if the target path is - * relative.*/ - export function realPath(path: string): Promise; - - export interface DirEntry { - name: string; - isFile: boolean; - isDirectory: boolean; - isSymlink: boolean; - } - - /** Synchronously reads the directory given by `path` and returns an iterable - * of `Deno.DirEntry`. - * - * ```ts - * for (const dirEntry of Deno.readDirSync("/")) { - * console.log(dirEntry.name); - * } - * ``` - * - * Throws error if `path` is not a directory. - * - * Requires `allow-read` permission. */ - export function readDirSync(path: string): Iterable; - - /** Reads the directory given by `path` and returns an async iterable of - * `Deno.DirEntry`. - * - * ```ts - * for await (const dirEntry of Deno.readDir("/")) { - * console.log(dirEntry.name); - * } - * ``` - * - * Throws error if `path` is not a directory. - * - * Requires `allow-read` permission. */ - export function readDir(path: string): AsyncIterable; - - /** Synchronously copies the contents and permissions of one file to another - * specified path, by default creating a new file if needed, else overwriting. - * Fails if target path is a directory or is unwritable. - * - * ```ts - * Deno.copyFileSync("from.txt", "to.txt"); - * ``` - * - * Requires `allow-read` permission on fromPath. - * Requires `allow-write` permission on toPath. */ - export function copyFileSync(fromPath: string, toPath: string): void; - - /** Copies the contents and permissions of one file to another specified path, - * by default creating a new file if needed, else overwriting. Fails if target - * path is a directory or is unwritable. - * - * ```ts - * await Deno.copyFile("from.txt", "to.txt"); - * ``` - * - * Requires `allow-read` permission on fromPath. - * Requires `allow-write` permission on toPath. */ - export function copyFile(fromPath: string, toPath: string): Promise; - - /** Returns the full path destination of the named symbolic link. - * - * ```ts - * Deno.symlinkSync("./test.txt", "./test_link.txt"); - * const target = Deno.readLinkSync("./test_link.txt"); // full path of ./test.txt - * ``` - * - * Throws TypeError if called with a hard link - * - * Requires `allow-read` permission. */ - export function readLinkSync(path: string): string; - - /** Resolves to the full path destination of the named symbolic link. - * - * ```ts - * await Deno.symlink("./test.txt", "./test_link.txt"); - * const target = await Deno.readLink("./test_link.txt"); // full path of ./test.txt - * ``` - * - * Throws TypeError if called with a hard link - * - * Requires `allow-read` permission. */ - export function readLink(path: string): Promise; - - /** Resolves to a `Deno.FileInfo` for the specified `path`. If `path` is a - * symlink, information for the symlink will be returned instead of what it - * points to. - * - * ```ts - * import { assert } from "https://deno.land/std/testing/asserts.ts"; - * const fileInfo = await Deno.lstat("hello.txt"); - * assert(fileInfo.isFile); - * ``` - * - * Requires `allow-read` permission. */ - export function lstat(path: string): Promise; - - /** Synchronously returns a `Deno.FileInfo` for the specified `path`. If - * `path` is a symlink, information for the symlink will be returned instead of - * what it points to.. - * - * ```ts - * const fileInfo = Deno.lstatSync("hello.txt"); - * assert(fileInfo.isFile); - * ``` - * - * Requires `allow-read` permission. */ - export function lstatSync(path: string): FileInfo; - - /** Resolves to a `Deno.FileInfo` for the specified `path`. Will always - * follow symlinks. - * - * ```ts - * import { assert } from "https://deno.land/std/testing/asserts.ts"; - * const fileInfo = await Deno.stat("hello.txt"); - * assert(fileInfo.isFile); - * ``` - * - * Requires `allow-read` permission. */ - export function stat(path: string): Promise; - - /** Synchronously returns a `Deno.FileInfo` for the specified `path`. Will - * always follow symlinks. - * - * ```ts - * import { assert } from "https://deno.land/std/testing/asserts.ts"; - * const fileInfo = Deno.statSync("hello.txt"); - * assert(fileInfo.isFile); - * ``` - * - * Requires `allow-read` permission. */ - export function statSync(path: string): FileInfo; - - /** Options for writing to a file. */ - export interface WriteFileOptions { - /** Defaults to `false`. If set to `true`, will append to a file instead of - * overwriting previous contents. */ - append?: boolean; - /** Sets the option to allow creating a new file, if one doesn't already - * exist at the specified path (defaults to `true`). */ - create?: boolean; - /** Permissions always applied to file. */ - mode?: number; - } - - /** Synchronously write `data` to the given `path`, by default creating a new - * file if needed, else overwriting. - * - * ```ts - * const encoder = new TextEncoder(); - * const data = encoder.encode("Hello world\n"); - * Deno.writeFileSync("hello1.txt", data); // overwrite "hello1.txt" or create it - * Deno.writeFileSync("hello2.txt", data, {create: false}); // only works if "hello2.txt" exists - * Deno.writeFileSync("hello3.txt", data, {mode: 0o777}); // set permissions on new file - * Deno.writeFileSync("hello4.txt", data, {append: true}); // add data to the end of the file - * ``` - * - * Requires `allow-write` permission, and `allow-read` if `options.create` is - * `false`. - */ - export function writeFileSync(path: string, data: Uint8Array, options?: WriteFileOptions): void; - - /** Write `data` to the given `path`, by default creating a new file if needed, - * else overwriting. - * - * ```ts - * const encoder = new TextEncoder(); - * const data = encoder.encode("Hello world\n"); - * await Deno.writeFile("hello1.txt", data); // overwrite "hello1.txt" or create it - * await Deno.writeFile("hello2.txt", data, {create: false}); // only works if "hello2.txt" exists - * await Deno.writeFile("hello3.txt", data, {mode: 0o777}); // set permissions on new file - * await Deno.writeFile("hello4.txt", data, {append: true}); // add data to the end of the file - * ``` - * - * Requires `allow-write` permission, and `allow-read` if `options.create` is `false`. - */ - export function writeFile(path: string, data: Uint8Array, options?: WriteFileOptions): Promise; - - /** Synchronously write string `data` to the given `path`, by default creating a new file if needed, - * else overwriting. - * - * ```ts - * await Deno.writeTextFileSync("hello1.txt", "Hello world\n"); // overwrite "hello1.txt" or create it - * ``` - * - * Requires `allow-write` permission, and `allow-read` if `options.create` is `false`. - */ - export function writeTextFileSync(path: string, data: string): void; - - /** Asynchronously write string `data` to the given `path`, by default creating a new file if needed, - * else overwriting. - * - * ```ts - * await Deno.writeTextFile("hello1.txt", "Hello world\n"); // overwrite "hello1.txt" or create it - * ``` - * - * Requires `allow-write` permission, and `allow-read` if `options.create` is `false`. - */ - export function writeTextFile(path: string, data: string): Promise; - - /** Synchronously truncates or extends the specified file, to reach the - * specified `len`. If `len` is not specified then the entire file contents - * are truncated. - * - * ```ts - * // truncate the entire file - * Deno.truncateSync("my_file.txt"); - * - * // truncate part of the file - * const file = Deno.makeTempFileSync(); - * Deno.writeFileSync(file, new TextEncoder().encode("Hello World")); - * Deno.truncateSync(file, 7); - * const data = Deno.readFileSync(file); - * console.log(new TextDecoder().decode(data)); - * ``` - * - * Requires `allow-write` permission. */ - export function truncateSync(name: string, len?: number): void; - - /** Truncates or extends the specified file, to reach the specified `len`. If - * `len` is not specified then the entire file contents are truncated. - * - * ```ts - * // truncate the entire file - * await Deno.truncate("my_file.txt"); - * - * // truncate part of the file - * const file = await Deno.makeTempFile(); - * await Deno.writeFile(file, new TextEncoder().encode("Hello World")); - * await Deno.truncate(file, 7); - * const data = await Deno.readFile(file); - * console.log(new TextDecoder().decode(data)); // "Hello W" - * ``` - * - * Requires `allow-write` permission. */ - export function truncate(name: string, len?: number): Promise; - - export interface NetAddr { - transport: 'tcp' | 'udp'; - hostname: string; - port: number; - } - - export interface UnixAddr { - transport: 'unix' | 'unixpacket'; - path: string; - } - - export type Addr = NetAddr | UnixAddr; - - /** A generic network listener for stream-oriented protocols. */ - export interface Listener extends AsyncIterable { - /** Waits for and resolves to the next connection to the `Listener`. */ - accept(): Promise; - /** Close closes the listener. Any pending accept promises will be rejected - * with errors. */ - close(): void; - /** Return the address of the `Listener`. */ - readonly addr: Addr; - - [Symbol.asyncIterator](): AsyncIterableIterator; - } - - export interface Conn extends Reader, Writer, Closer { - /** The local address of the connection. */ - readonly localAddr: Addr; - /** The remote address of the connection. */ - readonly remoteAddr: Addr; - /** The resource ID of the connection. */ - readonly rid: number; - /** Shuts down (`shutdown(2)`) the writing side of the TCP connection. Most - * callers should just use `close()`. - * - * **Unstable** because of lack of testing and because Deno.shutdown is also - * unstable. - * */ - closeWrite(): void; - } - - export interface ListenOptions { - /** The port to listen on. */ - port: number; - /** A literal IP address or host name that can be resolved to an IP address. - * If not specified, defaults to `0.0.0.0`. */ - hostname?: string; - } - - /** Listen announces on the local transport address. - * - * ```ts - * const listener1 = Deno.listen({ port: 80 }) - * const listener2 = Deno.listen({ hostname: "192.0.2.1", port: 80 }) - * const listener3 = Deno.listen({ hostname: "[2001:db8::1]", port: 80 }); - * const listener4 = Deno.listen({ hostname: "golang.org", port: 80, transport: "tcp" }); - * ``` - * - * Requires `allow-net` permission. */ - export function listen(options: ListenOptions & { transport?: 'tcp' }): Listener; - - export interface ListenTlsOptions extends ListenOptions { - /** Server certificate file. */ - certFile: string; - /** Server public key file. */ - keyFile: string; - - transport?: 'tcp'; - } - - /** Listen announces on the local transport address over TLS (transport layer - * security). - * - * ```ts - * const lstnr = Deno.listenTls({ port: 443, certFile: "./server.crt", keyFile: "./server.key" }); - * ``` - * - * Requires `allow-net` permission. */ - export function listenTls(options: ListenTlsOptions): Listener; - - export interface ConnectOptions { - /** The port to connect to. */ - port: number; - /** A literal IP address or host name that can be resolved to an IP address. - * If not specified, defaults to `127.0.0.1`. */ - hostname?: string; - transport?: 'tcp'; - } - - /** - * Connects to the hostname (default is "127.0.0.1") and port on the named - * transport (default is "tcp"), and resolves to the connection (`Conn`). - * - * ```ts - * const conn1 = await Deno.connect({ port: 80 }); - * const conn2 = await Deno.connect({ hostname: "192.0.2.1", port: 80 }); - * const conn3 = await Deno.connect({ hostname: "[2001:db8::1]", port: 80 }); - * const conn4 = await Deno.connect({ hostname: "golang.org", port: 80, transport: "tcp" }); - * ``` - * - * Requires `allow-net` permission for "tcp". */ - export function connect(options: ConnectOptions): Promise; - - export interface ConnectTlsOptions { - /** The port to connect to. */ - port: number; - /** A literal IP address or host name that can be resolved to an IP address. - * If not specified, defaults to `127.0.0.1`. */ - hostname?: string; - /** Server certificate file. */ - certFile?: string; - } - - /** Establishes a secure connection over TLS (transport layer security) using - * an optional cert file, hostname (default is "127.0.0.1") and port. The - * cert file is optional and if not included Mozilla's root certificates will - * be used (see also https://github.com/ctz/webpki-roots for specifics) - * - * ```ts - * const conn1 = await Deno.connectTls({ port: 80 }); - * const conn2 = await Deno.connectTls({ certFile: "./certs/my_custom_root_CA.pem", hostname: "192.0.2.1", port: 80 }); - * const conn3 = await Deno.connectTls({ hostname: "[2001:db8::1]", port: 80 }); - * const conn4 = await Deno.connectTls({ certFile: "./certs/my_custom_root_CA.pem", hostname: "golang.org", port: 80}); - * ``` - * - * Requires `allow-net` permission. - */ - export function connectTls(options: ConnectTlsOptions): Promise; - - export interface Metrics { - opsDispatched: number; - opsDispatchedSync: number; - opsDispatchedAsync: number; - opsDispatchedAsyncUnref: number; - opsCompleted: number; - opsCompletedSync: number; - opsCompletedAsync: number; - opsCompletedAsyncUnref: number; - bytesSentControl: number; - bytesSentData: number; - bytesReceived: number; - } - - /** Receive metrics from the privileged side of Deno. This is primarily used - * in the development of Deno. 'Ops', also called 'bindings', are the go-between - * between Deno JavaScript and Deno Rust. - * - * > console.table(Deno.metrics()) - * ┌─────────────────────────┬────────┐ - * │ (index) │ Values │ - * ├─────────────────────────┼────────┤ - * │ opsDispatched │ 3 │ - * │ opsDispatchedSync │ 2 │ - * │ opsDispatchedAsync │ 1 │ - * │ opsDispatchedAsyncUnref │ 0 │ - * │ opsCompleted │ 3 │ - * │ opsCompletedSync │ 2 │ - * │ opsCompletedAsync │ 1 │ - * │ opsCompletedAsyncUnref │ 0 │ - * │ bytesSentControl │ 73 │ - * │ bytesSentData │ 0 │ - * │ bytesReceived │ 375 │ - * └─────────────────────────┴────────┘ - */ - export function metrics(): Metrics; - - interface ResourceMap { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - [rid: number]: any; - } - - /** Returns a map of open resource ids (rid) along with their string - * representations. This is an internal API and as such resource - * representation has `any` type; that means it can change any time. - * - * ```ts - * console.log(Deno.resources()); - * // { 0: "stdin", 1: "stdout", 2: "stderr" } - * Deno.openSync('../test.file'); - * console.log(Deno.resources()); - * // { 0: "stdin", 1: "stdout", 2: "stderr", 3: "fsFile" } - * ``` - */ - export function resources(): ResourceMap; - - export interface FsEvent { - kind: 'any' | 'access' | 'create' | 'modify' | 'remove'; - paths: string[]; - } - - /** Watch for file system events against one or more `paths`, which can be files - * or directories. These paths must exist already. One user action (e.g. - * `touch test.file`) can generate multiple file system events. Likewise, - * one user action can result in multiple file paths in one event (e.g. `mv - * old_name.txt new_name.txt`). Recursive option is `true` by default and, - * for directories, will watch the specified directory and all sub directories. - * Note that the exact ordering of the events can vary between operating systems. - * - * ```ts - * const watcher = Deno.watchFs("/"); - * for await (const event of watcher) { - * console.log(">>>> event", event); - * // { kind: "create", paths: [ "/foo.txt" ] } - * } - *``` - * - * Requires `allow-read` permission. - */ - export function watchFs(paths: string | string[], options?: { recursive: boolean }): AsyncIterableIterator; - - export class Process { - readonly rid: number; - readonly pid: number; - readonly stdin?: Writer & Closer; - readonly stdout?: Reader & Closer; - readonly stderr?: Reader & Closer; - /** Resolves to the current status of the process. */ - status(): Promise; - /** Buffer the stdout until EOF and return it as `Uint8Array`. - * - * You must set stdout to `"piped"` when creating the process. - * - * This calls `close()` on stdout after its done. */ - output(): Promise; - /** Buffer the stderr until EOF and return it as `Uint8Array`. - * - * You must set stderr to `"piped"` when creating the process. - * - * This calls `close()` on stderr after its done. */ - stderrOutput(): Promise; - close(): void; - - /** **UNSTABLE**: The `signo` argument may change to require the Deno.Signal - * enum. - * - * Send a signal to process. This functionality currently only works on - * Linux and Mac OS. - */ - kill(signo: number): void; - } - - export type ProcessStatus = - | { - success: true; - code: 0; - signal?: undefined; - } - | { - success: false; - code: number; - signal?: number; - }; - - export interface RunOptions { - /** Arguments to pass. Note, the first element needs to be a path to the - * binary */ - cmd: string[]; - cwd?: string; - env?: { - [key: string]: string; - }; - stdout?: 'inherit' | 'piped' | 'null' | number; - stderr?: 'inherit' | 'piped' | 'null' | number; - stdin?: 'inherit' | 'piped' | 'null' | number; - } - - /** Spawns new subprocess. RunOptions must contain at a minimum the `opt.cmd`, - * an array of program arguments, the first of which is the binary. - * - * ```ts - * const p = Deno.run({ - * cmd: ["echo", "hello"], - * }); - * ``` - * - * Subprocess uses same working directory as parent process unless `opt.cwd` - * is specified. - * - * Environmental variables for subprocess can be specified using `opt.env` - * mapping. - * - * By default subprocess inherits stdio of parent process. To change that - * `opt.stdout`, `opt.stderr` and `opt.stdin` can be specified independently - - * they can be set to either an rid of open file or set to "inherit" "piped" - * or "null": - * - * `"inherit"` The default if unspecified. The child inherits from the - * corresponding parent descriptor. - * - * `"piped"` A new pipe should be arranged to connect the parent and child - * sub-processes. - * - * `"null"` This stream will be ignored. This is the equivalent of attaching - * the stream to `/dev/null`. - * - * Details of the spawned process are returned. - * - * Requires `allow-run` permission. */ - export function run(opt: RunOptions): Process; - - interface InspectOptions { - depth?: number; - } - - /** Converts the input into a string that has the same format as printed by - * `console.log()`. - * - * ```ts - * const obj = {}; - * obj.propA = 10; - * obj.propB = "hello"; - * const objAsString = Deno.inspect(obj); // { propA: 10, propB: "hello" } - * console.log(obj); // prints same value as objAsString, e.g. { propA: 10, propB: "hello" } - * ``` - * - * You can also register custom inspect functions, via the `customInspect` Deno - * symbol on objects, to control and customize the output. - * - * ```ts - * class A { - * x = 10; - * y = "hello"; - * [Deno.customInspect](): string { - * return "x=" + this.x + ", y=" + this.y; - * } - * } - * ``` - * - * const inStringFormat = Deno.inspect(new A()); // "x=10, y=hello" - * console.log(inStringFormat); // prints "x=10, y=hello" - * - * Finally, a number of output options are also available. - * - * const out = Deno.inspect(obj, {showHidden: true, depth: 4, colors: true, indentLevel: 2}); - * - */ - export function inspect(value: unknown, options?: InspectOptions): string; - - /** Build related information. */ - export const build: { - /** The LLVM target triple */ - target: string; - /** Instruction set architecture */ - arch: 'x86_64'; - /** Operating system */ - os: 'darwin' | 'linux' | 'windows'; - /** Computer vendor */ - vendor: string; - /** Optional environment */ - env?: string; - }; - - interface Version { - deno: string; - v8: string; - typescript: string; - } - /** Version related information. */ - export const version: Version; - - /** Returns the script arguments to the program. If for example we run a - * program: - * - * deno run --allow-read https://deno.land/std/examples/cat.ts /etc/passwd - * - * Then `Deno.args` will contain: - * - * [ "/etc/passwd" ] - */ - export const args: string[]; - - /** A symbol which can be used as a key for a custom method which will be - * called when `Deno.inspect()` is called, or when the object is logged to - * the console. */ - export const customInspect: unique symbol; -} - -// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. - -/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, no-var */ - -/// -/// - -// This follows the WebIDL at: https://webassembly.github.io/spec/js-api/ -// and: https://webassembly.github.io/spec/web-api/ -declare namespace WebAssembly { - interface WebAssemblyInstantiatedSource { - module: Module; - instance: Instance; - } - - /** Compiles a `WebAssembly.Module` from WebAssembly binary code. This - * function is useful if it is necessary to a compile a module before it can - * be instantiated (otherwise, the `WebAssembly.instantiate()` function - * should be used). */ - function compile(bufferSource: BufferSource): Promise; - - /** Compiles a `WebAssembly.Module` directly from a streamed underlying - * source. This function is useful if it is necessary to a compile a module - * before it can be instantiated (otherwise, the - * `WebAssembly.instantiateStreaming()` function should be used). */ - function compileStreaming(source: Promise): Promise; - - /** Takes the WebAssembly binary code, in the form of a typed array or - * `ArrayBuffer`, and performs both compilation and instantiation in one step. - * The returned `Promise` resolves to both a compiled `WebAssembly.Module` and - * its first `WebAssembly.Instance`. */ - function instantiate(bufferSource: BufferSource, importObject?: object): Promise; - - /** Takes an already-compiled `WebAssembly.Module` and returns a `Promise` - * that resolves to an `Instance` of that `Module`. This overload is useful if - * the `Module` has already been compiled. */ - function instantiate(module: Module, importObject?: object): Promise; - - /** Compiles and instantiates a WebAssembly module directly from a streamed - * underlying source. This is the most efficient, optimized way to load wasm - * code. */ - function instantiateStreaming(source: Promise, importObject?: object): Promise; - - /** Validates a given typed array of WebAssembly binary code, returning - * whether the bytes form a valid wasm module (`true`) or not (`false`). */ - function validate(bufferSource: BufferSource): boolean; - - type ImportExportKind = 'function' | 'table' | 'memory' | 'global'; - - interface ModuleExportDescriptor { - name: string; - kind: ImportExportKind; - } - interface ModuleImportDescriptor { - module: string; - name: string; - kind: ImportExportKind; - } - - class Module { - constructor(bufferSource: BufferSource); - - /** Given a `Module` and string, returns a copy of the contents of all - * custom sections in the module with the given string name. */ - static customSections(moduleObject: Module, sectionName: string): ArrayBuffer; - - /** Given a `Module`, returns an array containing descriptions of all the - * declared exports. */ - static exports(moduleObject: Module): ModuleExportDescriptor[]; - - /** Given a `Module`, returns an array containing descriptions of all the - * declared imports. */ - static imports(moduleObject: Module): ModuleImportDescriptor[]; - } - - class Instance { - constructor(module: Module, importObject?: object); - - /** An object containing as its members all the functions exported from the - * WebAssembly module instance, to allow them to be accessed and used by - * JavaScript. */ - readonly exports: T; - } - - interface MemoryDescriptor { - initial: number; - maximum?: number; - } - - class Memory { - constructor(descriptor: MemoryDescriptor); - - /** An accessor property that returns the buffer contained in the memory. */ - readonly buffer: ArrayBuffer; - - /** Increases the size of the memory instance by a specified number of - * WebAssembly pages (each one is 64KB in size). */ - grow(delta: number): number; - } - - type TableKind = 'anyfunc'; - - interface TableDescriptor { - element: TableKind; - initial: number; - maximum?: number; - } - - class Table { - constructor(descriptor: TableDescriptor); - - /** Returns the length of the table, i.e. the number of elements. */ - readonly length: number; - - /** Accessor function — gets the element stored at a given index. */ - get(index: number): (...args: any[]) => any; - - /** Increases the size of the Table instance by a specified number of - * elements. */ - grow(delta: number): number; - - /** Sets an element stored at a given index to a given value. */ - set(index: number, value: (...args: any[]) => any): void; - } - - type ValueType = 'i32' | 'i64' | 'f32' | 'f64'; - - interface GlobalDescriptor { - value: ValueType; - mutable?: boolean; - } - - /** Represents a global variable instance, accessible from both JavaScript and - * importable/exportable across one or more `WebAssembly.Module` instances. - * This allows dynamic linking of multiple modules. */ - class Global { - constructor(descriptor: GlobalDescriptor, value?: any); - - /** Old-style method that returns the value contained inside the global - * variable. */ - valueOf(): any; - - /** The value contained inside the global variable — this can be used to - * directly set and get the global's value. */ - value: any; - } - - /** Indicates an error during WebAssembly decoding or validation */ - class CompileError extends Error { - constructor(message: string, fileName?: string, lineNumber?: string); - } - - /** Indicates an error during module instantiation (besides traps from the - * start function). */ - class LinkError extends Error { - constructor(message: string, fileName?: string, lineNumber?: string); - } - - /** Is thrown whenever WebAssembly specifies a trap. */ - class RuntimeError extends Error { - constructor(message: string, fileName?: string, lineNumber?: string); - } -} - -/** Sets a timer which executes a function once after the timer expires. Returns - * an id which may be used to cancel the timeout. - * - * setTimeout(() => { console.log('hello'); }, 500); - */ -declare function setTimeout( - /** callback function to execute when timer expires */ - cb: (...args: any[]) => void, - /** delay in ms */ - delay?: number, - /** arguments passed to callback function */ - ...args: any[] -): number; - -/** Repeatedly calls a function , with a fixed time delay between each call. - * - * // Outputs 'hello' to the console every 500ms - * setInterval(() => { console.log('hello'); }, 500); - */ -declare function setInterval( - /** callback function to execute when timer expires */ - cb: (...args: any[]) => void, - /** delay in ms */ - delay?: number, - /** arguments passed to callback function */ - ...args: any[] -): number; - -/** Cancels a timed, repeating action which was previously started by a call - * to `setInterval()` - * - * const id = setInterval(()= > {console.log('hello');}, 500); - * ... - * clearInterval(id); - */ -declare function clearInterval(id?: number): void; - -/** Cancels a scheduled action initiated by `setTimeout()` - * - * const id = setTimeout(()= > {console.log('hello');}, 500); - * ... - * clearTimeout(id); - */ -declare function clearTimeout(id?: number): void; - -/** A microtask is a short function which is executed after the function or - * module which created it exits and only if the JavaScript execution stack is - * empty, but before returning control to the event loop being used to drive the - * script's execution environment. This event loop may be either the main event - * loop or the event loop driving a web worker. - * - * queueMicrotask(() => { console.log('This event loop stack is complete'); }); - */ -declare function queueMicrotask(func: Function): void; - -// declare var console: Console; -declare var crypto: Crypto; - -/** Registers an event listener in the global scope, which will be called - * synchronously whenever the event `type` is dispatched. - * - * addEventListener('unload', () => { console.log('All finished!'); }); - * ... - * dispatchEvent(new Event('unload')); - */ -declare function addEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions | undefined): void; - -/** Dispatches an event in the global scope, synchronously invoking any - * registered event listeners for this event in the appropriate order. Returns - * false if event is cancelable and at least one of the event handlers which - * handled this event called Event.preventDefault(). Otherwise it returns true. - * - * dispatchEvent(new Event('unload')); - */ -declare function dispatchEvent(event: Event): boolean; - -/** Remove a previously registered event listener from the global scope - * - * const lstnr = () => { console.log('hello'); }; - * addEventListener('load', lstnr); - * removeEventListener('load', lstnr); - */ -declare function removeEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: boolean | EventListenerOptions | undefined): void; - -declare interface ImportMeta { - url: string; - main: boolean; -} - -interface DomIterable { - keys(): IterableIterator; - values(): IterableIterator; - entries(): IterableIterator<[K, V]>; - [Symbol.iterator](): IterableIterator<[K, V]>; - forEach(callback: (value: V, key: K, parent: this) => void, thisArg?: any): void; -} - -interface ReadableStreamReadDoneResult { - done: true; - value?: T; -} - -interface ReadableStreamReadValueResult { - done: false; - value: T; -} - -type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; - -interface ReadableStreamDefaultReader { - readonly closed: Promise; - cancel(reason?: any): Promise; - read(): Promise>; - releaseLock(): void; -} - -interface ReadableStreamReader { - cancel(): Promise; - read(): Promise>; - releaseLock(): void; -} - -interface ReadableByteStreamControllerCallback { - (controller: ReadableByteStreamController): void | PromiseLike; -} - -interface UnderlyingByteSource { - autoAllocateChunkSize?: number; - cancel?: ReadableStreamErrorCallback; - pull?: ReadableByteStreamControllerCallback; - start?: ReadableByteStreamControllerCallback; - type: 'bytes'; -} - -interface UnderlyingSource { - cancel?: ReadableStreamErrorCallback; - pull?: ReadableStreamDefaultControllerCallback; - start?: ReadableStreamDefaultControllerCallback; - type?: undefined; -} - -interface ReadableStreamErrorCallback { - (reason: any): void | PromiseLike; -} - -interface ReadableStreamDefaultControllerCallback { - (controller: ReadableStreamDefaultController): void | PromiseLike; -} - -interface ReadableStreamDefaultController { - readonly desiredSize: number | null; - close(): void; - enqueue(chunk: R): void; - error(error?: any): void; -} - -interface ReadableByteStreamController { - readonly byobRequest: undefined; - readonly desiredSize: number | null; - close(): void; - enqueue(chunk: ArrayBufferView): void; - error(error?: any): void; -} - -interface PipeOptions { - preventAbort?: boolean; - preventCancel?: boolean; - preventClose?: boolean; - signal?: AbortSignal; -} - -interface QueuingStrategySizeCallback { - (chunk: T): number; -} - -interface QueuingStrategy { - highWaterMark?: number; - size?: QueuingStrategySizeCallback; -} - -/** This Streams API interface provides a built-in byte length queuing strategy - * that can be used when constructing streams. */ -declare class CountQueuingStrategy implements QueuingStrategy { - constructor(options: { highWaterMark: number }); - highWaterMark: number; - size(chunk: any): 1; -} - -declare class ByteLengthQueuingStrategy implements QueuingStrategy { - constructor(options: { highWaterMark: number }); - highWaterMark: number; - size(chunk: ArrayBufferView): number; -} - -/** This Streams API interface represents a readable stream of byte data. The - * Fetch API offers a concrete instance of a ReadableStream through the body - * property of a Response object. */ -interface ReadableStream { - readonly locked: boolean; - cancel(reason?: any): Promise; - getIterator(options?: { preventCancel?: boolean }): AsyncIterableIterator; - // getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; - getReader(): ReadableStreamDefaultReader; - pipeThrough( - { - writable, - readable, - }: { - writable: WritableStream; - readable: ReadableStream; - }, - options?: PipeOptions, - ): ReadableStream; - pipeTo(dest: WritableStream, options?: PipeOptions): Promise; - tee(): [ReadableStream, ReadableStream]; - [Symbol.asyncIterator](options?: { preventCancel?: boolean }): AsyncIterableIterator; -} - -declare var ReadableStream: { - prototype: ReadableStream; - new (underlyingSource: UnderlyingByteSource, strategy?: { highWaterMark?: number; size?: undefined }): ReadableStream; - new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; -}; - -interface WritableStreamDefaultControllerCloseCallback { - (): void | PromiseLike; -} - -interface WritableStreamDefaultControllerStartCallback { - (controller: WritableStreamDefaultController): void | PromiseLike; -} - -interface WritableStreamDefaultControllerWriteCallback { - (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; -} - -interface WritableStreamErrorCallback { - (reason: any): void | PromiseLike; -} - -interface UnderlyingSink { - abort?: WritableStreamErrorCallback; - close?: WritableStreamDefaultControllerCloseCallback; - start?: WritableStreamDefaultControllerStartCallback; - type?: undefined; - write?: WritableStreamDefaultControllerWriteCallback; -} - -/** This Streams API interface provides a standard abstraction for writing - * streaming data to a destination, known as a sink. This object comes with - * built-in backpressure and queuing. */ -declare class WritableStream { - constructor(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy); - readonly locked: boolean; - abort(reason?: any): Promise; - close(): Promise; - getWriter(): WritableStreamDefaultWriter; -} - -/** This Streams API interface represents a controller allowing control of a - * WritableStream's state. When constructing a WritableStream, the underlying - * sink is given a corresponding WritableStreamDefaultController instance to - * manipulate. */ -interface WritableStreamDefaultController { - error(error?: any): void; -} - -/** This Streams API interface is the object returned by - * WritableStream.getWriter() and once created locks the < writer to the - * WritableStream ensuring that no other streams can write to the underlying - * sink. */ -interface WritableStreamDefaultWriter { - readonly closed: Promise; - readonly desiredSize: number | null; - readonly ready: Promise; - abort(reason?: any): Promise; - close(): Promise; - releaseLock(): void; - write(chunk: W): Promise; -} - -declare class TransformStream { - constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); - readonly readable: ReadableStream; - readonly writable: WritableStream; -} - -interface TransformStreamDefaultController { - readonly desiredSize: number | null; - enqueue(chunk: O): void; - error(reason?: any): void; - terminate(): void; -} - -interface Transformer { - flush?: TransformStreamDefaultControllerCallback; - readableType?: undefined; - start?: TransformStreamDefaultControllerCallback; - transform?: TransformStreamDefaultControllerTransformCallback; - writableType?: undefined; -} - -interface TransformStreamDefaultControllerCallback { - (controller: TransformStreamDefaultController): void | PromiseLike; -} - -interface TransformStreamDefaultControllerTransformCallback { - (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; -} - -interface DOMStringList { - /** Returns the number of strings in strings. */ - readonly length: number; - /** Returns true if strings contains string, and false otherwise. */ - contains(string: string): boolean; - /** Returns the string with index index from strings. */ - item(index: number): string | null; - [index: number]: string; -} - -declare class DOMException extends Error { - constructor(message?: string, name?: string); - readonly name: string; - readonly message: string; -} - -type BufferSource = ArrayBufferView | ArrayBuffer; -type BlobPart = BufferSource | Blob | string; - -interface BlobPropertyBag { - type?: string; - ending?: 'transparent' | 'native'; -} - -/** A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. */ -interface Blob { - readonly size: number; - readonly type: string; - arrayBuffer(): Promise; - slice(start?: number, end?: number, contentType?: string): Blob; - stream(): ReadableStream; - text(): Promise; -} - -declare const Blob: { - prototype: Blob; - new (blobParts?: BlobPart[], options?: BlobPropertyBag): Blob; -}; - -interface FilePropertyBag extends BlobPropertyBag { - lastModified?: number; -} - -/** Provides information about files and allows JavaScript in a web page to - * access their content. */ -interface File extends Blob { - readonly lastModified: number; - readonly name: string; -} - -declare const File: { - prototype: File; - new (fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File; -}; - -declare const isConsoleInstance: unique symbol; - -// declare class Console { -// indentLevel: number; -// [isConsoleInstance]: boolean; -// /** Writes the arguments to stdout */ -// log: (...args: unknown[]) => void; -// /** Writes the arguments to stdout */ -// debug: (...args: unknown[]) => void; -// /** Writes the arguments to stdout */ -// info: (...args: unknown[]) => void; -// /** Writes the properties of the supplied `obj` to stdout */ -// dir: ( -// obj: unknown, -// options?: Partial<{ -// depth: number; -// indentLevel: number; -// }> -// ) => void; - -// /** From MDN: -// * Displays an interactive tree of the descendant elements of -// * the specified XML/HTML element. If it is not possible to display -// * as an element the JavaScript Object view is shown instead. -// * The output is presented as a hierarchical listing of expandable -// * nodes that let you see the contents of child nodes. -// * -// * Since we write to stdout, we can't display anything interactive -// * we just fall back to `console.dir`. -// */ -// dirxml: ( -// obj: unknown, -// options?: Partial<{ -// showHidden: boolean; -// depth: number; -// colors: boolean; -// indentLevel: number; -// }> -// ) => void; - -// /** Writes the arguments to stdout */ -// warn: (...args: unknown[]) => void; -// /** Writes the arguments to stdout */ -// error: (...args: unknown[]) => void; -// /** Writes an error message to stdout if the assertion is `false`. If the -// * assertion is `true`, nothing happens. -// * -// * ref: https://console.spec.whatwg.org/#assert -// */ -// assert: (condition?: boolean, ...args: unknown[]) => void; -// count: (label?: string) => void; -// countReset: (label?: string) => void; -// table: (data: unknown, properties?: string[] | undefined) => void; -// time: (label?: string) => void; -// timeLog: (label?: string, ...args: unknown[]) => void; -// timeEnd: (label?: string) => void; -// group: (...label: unknown[]) => void; -// groupCollapsed: (...label: unknown[]) => void; -// groupEnd: () => void; -// clear: () => void; -// trace: (...args: unknown[]) => void; -// static [Symbol.hasInstance](instance: Console): boolean; -// } - -declare interface Crypto { - readonly subtle: null; - getRandomValues( - array: T, - ): T; -} - -type FormDataEntryValue = File | string; - -/** Provides a way to easily construct a set of key/value pairs representing - * form fields and their values, which can then be easily sent using the - * XMLHttpRequest.send() method. It uses the same format a form would use if the - * encoding type were set to "multipart/form-data". */ -interface FormData extends DomIterable { - append(name: string, value: string | Blob, fileName?: string): void; - delete(name: string): void; - get(name: string): FormDataEntryValue | null; - getAll(name: string): FormDataEntryValue[]; - has(name: string): boolean; - set(name: string, value: string | Blob, fileName?: string): void; -} - -declare const FormData: { - prototype: FormData; - // TODO(ry) FormData constructor is non-standard. - // new(form?: HTMLFormElement): FormData; - new (): FormData; -}; - -interface Body { - /** A simple getter used to expose a `ReadableStream` of the body contents. */ - readonly body: ReadableStream | null; - /** Stores a `Boolean` that declares whether the body has been used in a - * response yet. - */ - readonly bodyUsed: boolean; - /** Takes a `Response` stream and reads it to completion. It returns a promise - * that resolves with an `ArrayBuffer`. - */ - arrayBuffer(): Promise; - /** Takes a `Response` stream and reads it to completion. It returns a promise - * that resolves with a `Blob`. - */ - blob(): Promise; - /** Takes a `Response` stream and reads it to completion. It returns a promise - * that resolves with a `FormData` object. - */ - formData(): Promise; - /** Takes a `Response` stream and reads it to completion. It returns a promise - * that resolves with the result of parsing the body text as JSON. - */ - json(): Promise; - /** Takes a `Response` stream and reads it to completion. It returns a promise - * that resolves with a `USVString` (text). - */ - text(): Promise; -} - -type HeadersInit = Headers | string[][] | Record; - -/** This Fetch API interface allows you to perform various actions on HTTP - * request and response headers. These actions include retrieving, setting, - * adding to, and removing. A Headers object has an associated header list, - * which is initially empty and consists of zero or more name and value pairs. - *  You can add to this using methods like append() (see Examples.) In all - * methods of this interface, header names are matched by case-insensitive byte - * sequence. */ -interface Headers { - append(name: string, value: string): void; - delete(name: string): void; - get(name: string): string | null; - has(name: string): boolean; - set(name: string, value: string): void; - forEach(callbackfn: (value: string, key: string, parent: Headers) => void, thisArg?: any): void; -} - -interface Headers extends DomIterable { - /** Appends a new value onto an existing header inside a `Headers` object, or - * adds the header if it does not already exist. - */ - append(name: string, value: string): void; - /** Deletes a header from a `Headers` object. */ - delete(name: string): void; - /** Returns an iterator allowing to go through all key/value pairs - * contained in this Headers object. The both the key and value of each pairs - * are ByteString objects. - */ - entries(): IterableIterator<[string, string]>; - /** Returns a `ByteString` sequence of all the values of a header within a - * `Headers` object with a given name. - */ - get(name: string): string | null; - /** Returns a boolean stating whether a `Headers` object contains a certain - * header. - */ - has(name: string): boolean; - /** Returns an iterator allowing to go through all keys contained in - * this Headers object. The keys are ByteString objects. - */ - keys(): IterableIterator; - /** Sets a new value for an existing header inside a Headers object, or adds - * the header if it does not already exist. - */ - set(name: string, value: string): void; - /** Returns an iterator allowing to go through all values contained in - * this Headers object. The values are ByteString objects. - */ - values(): IterableIterator; - forEach(callbackfn: (value: string, key: string, parent: this) => void, thisArg?: any): void; - /** The Symbol.iterator well-known symbol specifies the default - * iterator for this Headers object - */ - [Symbol.iterator](): IterableIterator<[string, string]>; -} - -declare const Headers: { - prototype: Headers; - new (init?: HeadersInit): Headers; -}; - -type RequestInfo = Request | string; -type RequestCache = 'default' | 'force-cache' | 'no-cache' | 'no-store' | 'only-if-cached' | 'reload'; -type RequestCredentials = 'include' | 'omit' | 'same-origin'; -type RequestMode = 'cors' | 'navigate' | 'no-cors' | 'same-origin'; -type RequestRedirect = 'error' | 'follow' | 'manual'; -type ReferrerPolicy = - | '' - | 'no-referrer' - | 'no-referrer-when-downgrade' - | 'origin' - | 'origin-when-cross-origin' - | 'same-origin' - | 'strict-origin' - | 'strict-origin-when-cross-origin' - | 'unsafe-url'; -type BodyInit = Blob | BufferSource | FormData | URLSearchParams | ReadableStream | string; -type RequestDestination = - | '' - | 'audio' - | 'audioworklet' - | 'document' - | 'embed' - | 'font' - | 'image' - | 'manifest' - | 'object' - | 'paintworklet' - | 'report' - | 'script' - | 'sharedworker' - | 'style' - | 'track' - | 'video' - | 'worker' - | 'xslt'; - -interface RequestInit { - /** - * A BodyInit object or null to set request's body. - */ - body?: BodyInit | null; - /** - * A string indicating how the request will interact with the browser's cache - * to set request's cache. - */ - cache?: RequestCache; - /** - * A string indicating whether credentials will be sent with the request - * always, never, or only when sent to a same-origin URL. Sets request's - * credentials. - */ - credentials?: RequestCredentials; - /** - * A Headers object, an object literal, or an array of two-item arrays to set - * request's headers. - */ - headers?: HeadersInit; - /** - * A cryptographic hash of the resource to be fetched by request. Sets - * request's integrity. - */ - integrity?: string; - /** - * A boolean to set request's keepalive. - */ - keepalive?: boolean; - /** - * A string to set request's method. - */ - method?: string; - /** - * A string to indicate whether the request will use CORS, or will be - * restricted to same-origin URLs. Sets request's mode. - */ - mode?: RequestMode; - /** - * A string indicating whether request follows redirects, results in an error - * upon encountering a redirect, or returns the redirect (in an opaque - * fashion). Sets request's redirect. - */ - redirect?: RequestRedirect; - /** - * A string whose value is a same-origin URL, "about:client", or the empty - * string, to set request's referrer. - */ - referrer?: string; - /** - * A referrer policy to set request's referrerPolicy. - */ - referrerPolicy?: ReferrerPolicy; - /** - * An AbortSignal to set request's signal. - */ - signal?: AbortSignal | null; - /** - * Can only be null. Used to disassociate request from any Window. - */ - window?: any; -} - -/** This Fetch API interface represents a resource request. */ -interface Request extends Body { - /** - * Returns the cache mode associated with request, which is a string - * indicating how the request will interact with the browser's cache when - * fetching. - */ - readonly cache: RequestCache; - /** - * Returns the credentials mode associated with request, which is a string - * indicating whether credentials will be sent with the request always, never, - * or only when sent to a same-origin URL. - */ - readonly credentials: RequestCredentials; - /** - * Returns the kind of resource requested by request, e.g., "document" or "script". - */ - readonly destination: RequestDestination; - /** - * Returns a Headers object consisting of the headers associated with request. - * Note that headers added in the network layer by the user agent will not be - * accounted for in this object, e.g., the "Host" header. - */ - readonly headers: Headers; - /** - * Returns request's subresource integrity metadata, which is a cryptographic - * hash of the resource being fetched. Its value consists of multiple hashes - * separated by whitespace. [SRI] - */ - readonly integrity: string; - /** - * Returns a boolean indicating whether or not request is for a history - * navigation (a.k.a. back-forward navigation). - */ - readonly isHistoryNavigation: boolean; - /** - * Returns a boolean indicating whether or not request is for a reload - * navigation. - */ - readonly isReloadNavigation: boolean; - /** - * Returns a boolean indicating whether or not request can outlive the global - * in which it was created. - */ - readonly keepalive: boolean; - /** - * Returns request's HTTP method, which is "GET" by default. - */ - readonly method: string; - /** - * Returns the mode associated with request, which is a string indicating - * whether the request will use CORS, or will be restricted to same-origin - * URLs. - */ - readonly mode: RequestMode; - /** - * Returns the redirect mode associated with request, which is a string - * indicating how redirects for the request will be handled during fetching. A - * request will follow redirects by default. - */ - readonly redirect: RequestRedirect; - /** - * Returns the referrer of request. Its value can be a same-origin URL if - * explicitly set in init, the empty string to indicate no referrer, and - * "about:client" when defaulting to the global's default. This is used during - * fetching to determine the value of the `Referer` header of the request - * being made. - */ - readonly referrer: string; - /** - * Returns the referrer policy associated with request. This is used during - * fetching to compute the value of the request's referrer. - */ - readonly referrerPolicy: ReferrerPolicy; - /** - * Returns the signal associated with request, which is an AbortSignal object - * indicating whether or not request has been aborted, and its abort event - * handler. - */ - readonly signal: AbortSignal; - /** - * Returns the URL of request as a string. - */ - readonly url: string; - clone(): Request; -} - -declare const Request: { - prototype: Request; - new (input: RequestInfo, init?: RequestInit): Request; -}; - -interface ResponseInit { - headers?: HeadersInit; - status?: number; - statusText?: string; -} - -type ResponseType = 'basic' | 'cors' | 'default' | 'error' | 'opaque' | 'opaqueredirect'; - -/** This Fetch API interface represents the response to a request. */ -interface Response extends Body { - readonly headers: Headers; - readonly ok: boolean; - readonly redirected: boolean; - readonly status: number; - readonly statusText: string; - readonly trailer: Promise; - readonly type: ResponseType; - readonly url: string; - clone(): Response; -} - -declare const Response: { - prototype: Response; - new (body?: BodyInit | null, init?: ResponseInit): Response; - error(): Response; - redirect(url: string, status?: number): Response; -}; - -/** Fetch a resource from the network. It returns a Promise that resolves to the - * Response to that request, whether it is successful or not. - * - * const response = await fetch("http://my.json.host/data.json"); - * console.log(response.status); // e.g. 200 - * console.log(response.statusText); // e.g. "OK" - * const jsonData = await response.json(); - */ -declare function fetch(input: Request | URL | string, init?: RequestInit): Promise; - -/** Decodes a string of data which has been encoded using base-64 encoding. - * - * console.log(atob("aGVsbG8gd29ybGQ=")); // outputs 'hello world' - */ -declare function atob(s: string): string; - -/** Creates a base-64 ASCII encoded string from the input string. - * - * console.log(btoa("hello world")); // outputs "aGVsbG8gd29ybGQ=" - */ -declare function btoa(s: string): string; - -declare class TextDecoder { - /** Returns encoding's name, lowercased. */ - readonly encoding: string; - /** Returns `true` if error mode is "fatal", and `false` otherwise. */ - readonly fatal: boolean; - /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */ - readonly ignoreBOM = false; - constructor(label?: string, options?: { fatal?: boolean; ignoreBOM?: boolean }); - /** Returns the result of running encoding's decoder. */ - decode(input?: BufferSource, options?: { stream?: false }): string; - readonly [Symbol.toStringTag]: string; -} - -declare class TextEncoder { - /** Returns "utf-8". */ - readonly encoding = 'utf-8'; - /** Returns the result of running UTF-8's encoder. */ - encode(input?: string): Uint8Array; - encodeInto(input: string, dest: Uint8Array): { read: number; written: number }; - readonly [Symbol.toStringTag]: string; -} - -interface URLSearchParams { - /** Appends a specified key/value pair as a new search parameter. - * - * ```ts - * let searchParams = new URLSearchParams(); - * searchParams.append('name', 'first'); - * searchParams.append('name', 'second'); - * ``` - */ - append(name: string, value: string): void; - - /** Deletes the given search parameter and its associated value, - * from the list of all search parameters. - * - * ```ts - * let searchParams = new URLSearchParams([['name', 'value']]); - * searchParams.delete('name'); - * ``` - */ - delete(name: string): void; - - /** Returns all the values associated with a given search parameter - * as an array. - * - * ```ts - * searchParams.getAll('name'); - * ``` - */ - getAll(name: string): string[]; - - /** Returns the first value associated to the given search parameter. - * - * ```ts - * searchParams.get('name'); - * ``` - */ - get(name: string): string | null; - - /** Returns a Boolean that indicates whether a parameter with the - * specified name exists. - * - * ```ts - * searchParams.has('name'); - * ``` - */ - has(name: string): boolean; - - /** Sets the value associated with a given search parameter to the - * given value. If there were several matching values, this method - * deletes the others. If the search parameter doesn't exist, this - * method creates it. - * - * ```ts - * searchParams.set('name', 'value'); - * ``` - */ - set(name: string, value: string): void; - - /** Sort all key/value pairs contained in this object in place and - * return undefined. The sort order is according to Unicode code - * points of the keys. - * - * ```ts - * searchParams.sort(); - * ``` - */ - sort(): void; - - /** Calls a function for each element contained in this object in - * place and return undefined. Optionally accepts an object to use - * as this when executing callback as second argument. - * - * ```ts - * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); - * params.forEach((value, key, parent) => { - * console.log(value, key, parent); - * }); - * ``` - * - */ - forEach(callbackfn: (value: string, key: string, parent: this) => void, thisArg?: any): void; - - /** Returns an iterator allowing to go through all keys contained - * in this object. - * - * ```ts - * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); - * for (const key of params.keys()) { - * console.log(key); - * } - * ``` - */ - keys(): IterableIterator; - - /** Returns an iterator allowing to go through all values contained - * in this object. - * - * ```ts - * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); - * for (const value of params.values()) { - * console.log(value); - * } - * ``` - */ - values(): IterableIterator; - - /** Returns an iterator allowing to go through all key/value - * pairs contained in this object. - * - * ```ts - * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); - * for (const [key, value] of params.entries()) { - * console.log(key, value); - * } - * ``` - */ - entries(): IterableIterator<[string, string]>; - - /** Returns an iterator allowing to go through all key/value - * pairs contained in this object. - * - * ```ts - * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); - * for (const [key, value] of params) { - * console.log(key, value); - * } - * ``` - */ - [Symbol.iterator](): IterableIterator<[string, string]>; - - /** Returns a query string suitable for use in a URL. - * - * ```ts - * searchParams.toString(); - * ``` - */ - toString(): string; -} - -declare const URLSearchParams: { - prototype: URLSearchParams; - new (init?: string[][] | Record | string | URLSearchParams): URLSearchParams; - toString(): string; -}; - -/** The URL interface represents an object providing static methods used for creating object URLs. */ -interface URL { - hash: string; - host: string; - hostname: string; - href: string; - toString(): string; - readonly origin: string; - password: string; - pathname: string; - port: string; - protocol: string; - search: string; - readonly searchParams: URLSearchParams; - username: string; - toJSON(): string; -} - -declare const URL: { - prototype: URL; - new (url: string | URL, base?: string | URL): URL; - createObjectURL(object: any): string; - revokeObjectURL(url: string): void; -}; - -interface MessageEventInit extends EventInit { - data?: any; - origin?: string; - lastEventId?: string; -} - -declare class MessageEvent extends Event { - readonly data: any; - readonly origin: string; - readonly lastEventId: string; - constructor(type: string, eventInitDict?: MessageEventInit); -} - -interface ErrorEventInit extends EventInit { - message?: string; - filename?: string; - lineno?: number; - colno?: number; - error?: any; -} - -declare class ErrorEvent extends Event { - readonly message: string; - readonly filename: string; - readonly lineno: number; - readonly colno: number; - readonly error: any; - constructor(type: string, eventInitDict?: ErrorEventInit); -} - -interface PostMessageOptions { - transfer?: any[]; -} - -declare class Worker extends EventTarget { - onerror?: (e: ErrorEvent) => void; - onmessage?: (e: MessageEvent) => void; - onmessageerror?: (e: MessageEvent) => void; - constructor( - specifier: string, - options?: { - type?: 'classic' | 'module'; - name?: string; - /** UNSTABLE: New API. Expect many changes; most likely this - * field will be made into an object for more granular - * configuration of worker thread (permissions, import map, etc.). - * - * Set to `true` to make `Deno` namespace and all of its methods - * available to worker thread. - * - * Currently worker inherits permissions from main thread (permissions - * given using `--allow-*` flags). - * Configurable permissions are on the roadmap to be implemented. - * - * Example: - * - * ```ts - * // mod.ts - * const worker = new Worker("./deno_worker.ts", { type: "module", deno: true }); - * worker.postMessage({ cmd: "readFile", fileName: "./log.txt" }); - * - * // deno_worker.ts - * - * - * self.onmessage = async function (e) { - * const { cmd, fileName } = e.data; - * if (cmd !== "readFile") { - * throw new Error("Invalid command"); - * } - * const buf = await Deno.readFile(fileName); - * const fileContents = new TextDecoder().decode(buf); - * console.log(fileContents); - * } - * ``` - * - * // log.txt - * hello world - * hello world 2 - * - * // run program - * $ deno run --allow-read mod.ts - * hello world - * hello world2 - * - */ - deno?: boolean; - }, - ); - postMessage(message: any, transfer: ArrayBuffer[]): void; - postMessage(message: any, options?: PostMessageOptions): void; - terminate(): void; -} - -declare namespace performance { - /** Returns a current time from Deno's start in milliseconds. - * - * Use the permission flag `--allow-hrtime` return a precise value. - * - * ```ts - * const t = performance.now(); - * console.log(`${t} ms since start!`); - * ``` - */ - export function now(): number; -} - -interface EventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; -} - -/** An event which takes place in the DOM. */ -declare class Event { - constructor(type: string, eventInitDict?: EventInit); - /** Returns true or false depending on how event was initialized. True if - * event goes through its target's ancestors in reverse tree order, and - * false otherwise. */ - readonly bubbles: boolean; - cancelBubble: boolean; - /** Returns true or false depending on how event was initialized. Its return - * value does not always carry meaning, but true can indicate that part of the - * operation during which event was dispatched, can be canceled by invoking - * the preventDefault() method. */ - readonly cancelable: boolean; - /** Returns true or false depending on how event was initialized. True if - * event invokes listeners past a ShadowRoot node that is the root of its - * target, and false otherwise. */ - readonly composed: boolean; - /** Returns the object whose event listener's callback is currently being - * invoked. */ - readonly currentTarget: EventTarget | null; - /** Returns true if preventDefault() was invoked successfully to indicate - * cancellation, and false otherwise. */ - readonly defaultPrevented: boolean; - /** Returns the event's phase, which is one of NONE, CAPTURING_PHASE, - * AT_TARGET, and BUBBLING_PHASE. */ - readonly eventPhase: number; - /** Returns true if event was dispatched by the user agent, and false - * otherwise. */ - readonly isTrusted: boolean; - /** Returns the object to which event is dispatched (its target). */ - readonly target: EventTarget | null; - /** Returns the event's timestamp as the number of milliseconds measured - * relative to the time origin. */ - readonly timeStamp: number; - /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ - readonly type: string; - /** Returns the invocation target objects of event's path (objects on which - * listeners will be invoked), except for any nodes in shadow trees of which - * the shadow root's mode is "closed" that are not reachable from event's - * currentTarget. */ - composedPath(): EventTarget[]; - /** If invoked when the cancelable attribute value is true, and while - * executing a listener for the event with passive set to false, signals to - * the operation that caused event to be dispatched that it needs to be - * canceled. */ - preventDefault(): void; - /** Invoking this method prevents event from reaching any registered event - * listeners after the current one finishes running and, when dispatched in a - * tree, also prevents event from reaching any other objects. */ - stopImmediatePropagation(): void; - /** When dispatched in a tree, invoking this method prevents event from - * reaching any objects other than the current object. */ - stopPropagation(): void; - readonly AT_TARGET: number; - readonly BUBBLING_PHASE: number; - readonly CAPTURING_PHASE: number; - readonly NONE: number; - static readonly AT_TARGET: number; - static readonly BUBBLING_PHASE: number; - static readonly CAPTURING_PHASE: number; - static readonly NONE: number; -} - -/** - * EventTarget is a DOM interface implemented by objects that can receive events - * and may have listeners for them. - */ -declare class EventTarget { - /** Appends an event listener for events whose type attribute value is type. - * The callback argument sets the callback that will be invoked when the event - * is dispatched. - * - * The options argument sets listener-specific options. For compatibility this - * can be a boolean, in which case the method behaves exactly as if the value - * was specified as options's capture. - * - * When set to true, options's capture prevents callback from being invoked - * when the event's eventPhase attribute value is BUBBLING_PHASE. When false - * (or not present), callback will not be invoked when event's eventPhase - * attribute value is CAPTURING_PHASE. Either way, callback will be invoked if - * event's eventPhase attribute value is AT_TARGET. - * - * When set to true, options's passive indicates that the callback will not - * cancel the event by invoking preventDefault(). This is used to enable - * performance optimizations described in § 2.8 Observing event listeners. - * - * When set to true, options's once indicates that the callback will only be - * invoked once after which the event listener will be removed. - * - * The event listener is appended to target's event listener list and is not - * appended if it has the same type, callback, and capture. */ - addEventListener(type: string, listener: EventListenerOrEventListenerObject | null, options?: boolean | AddEventListenerOptions): void; - /** Dispatches a synthetic event event to target and returns true if either - * event's cancelable attribute value is false or its preventDefault() method - * was not invoked, and false otherwise. */ - dispatchEvent(event: Event): boolean; - /** Removes the event listener in target's event listener list with the same - * type, callback, and options. */ - removeEventListener(type: string, callback: EventListenerOrEventListenerObject | null, options?: EventListenerOptions | boolean): void; - [Symbol.toStringTag]: string; -} - -interface EventListener { - (evt: Event): void | Promise; -} - -interface EventListenerObject { - handleEvent(evt: Event): void | Promise; -} - -declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; - -interface AddEventListenerOptions extends EventListenerOptions { - once?: boolean; - passive?: boolean; -} - -interface EventListenerOptions { - capture?: boolean; -} - -/** Events measuring progress of an underlying process, like an HTTP request - * (for an XMLHttpRequest, or the loading of the underlying resource of an - * ,