1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-22 15:06:54 -05:00

clean up code in cli/js (#6611)

This commit is contained in:
Stanislav 2020-07-07 04:45:39 +03:00 committed by GitHub
parent ab4c574f52
commit 158ae0bfe9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
89 changed files with 395 additions and 354 deletions

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
// TODO(ry) Combine this implementation with //deno_typescript/compiler_main.js
// This module is the entry point for "compiler" isolate, ie. the one
@ -286,8 +287,7 @@ class SourceFile {
): string | undefined {
const containingCache = RESOLVED_SPECIFIER_CACHE.get(containingFile);
if (containingCache) {
const resolvedUrl = containingCache.get(moduleSpecifier);
return resolvedUrl;
return containingCache.get(moduleSpecifier);
}
return undefined;
}
@ -315,8 +315,8 @@ function getAssetInternal(filename: string): SourceFile {
class Host implements ts.CompilerHost {
protected _options = DEFAULT_COMPILE_OPTIONS;
#target: CompilerHostTarget;
#writeFile: WriteFileCallback;
readonly #target: CompilerHostTarget;
readonly #writeFile: WriteFileCallback;
/* Deno specific APIs */
constructor({
@ -519,7 +519,7 @@ class Host implements ts.CompilerHost {
}
class IncrementalCompileHost extends Host {
#buildInfo: undefined | string = undefined;
readonly #buildInfo?: string;
constructor(options: IncrementalCompilerHostOptions) {
super(options);
@ -1123,9 +1123,7 @@ function buildBundle(
target === ts.ScriptTarget.ES3 ||
target === ts.ScriptTarget.ES5 ||
target === ts.ScriptTarget.ES2015 ||
target === ts.ScriptTarget.ES2016
? true
: false;
target === ts.ScriptTarget.ES2016;
return `${
es5Bundle ? SYSTEM_LOADER_ES5 : SYSTEM_LOADER
}\n${data}\n${instantiate}`;

View file

@ -52,8 +52,8 @@ export async function compile(
const emitMap: Record<string, string> = {};
for (const [key, emmitedSource] of Object.entries(result.emitMap)) {
emitMap[key] = emmitedSource.contents;
for (const [key, emittedSource] of Object.entries(result.emitMap)) {
emitMap[key] = emittedSource.contents;
}
return [maybeDiagnostics, emitMap];

View file

@ -1,6 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
// Public deno module.
// This module exports stable Deno APIs.
export {
Buffer,
readAll,

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
// Some of the code here is adapted directly from V8 and licensed under a BSD
// style license available here: https://github.com/v8/v8/blob/24886f2d1c565287d33d71e4109a53bf0b54b75c/LICENSE.v8
import * as colors from "./colors.ts";
@ -94,10 +95,10 @@ function getMethodCall(callSite: CallSite): string {
return result;
}
function getFileLocation(callSite: CallSite, isInternal = false): string {
const cyan = isInternal ? colors.gray : colors.cyan;
const yellow = isInternal ? colors.gray : colors.yellow;
const black = isInternal ? colors.gray : (s: string): string => s;
function getFileLocation(callSite: CallSite, internal = false): string {
const cyan = internal ? colors.gray : colors.cyan;
const yellow = internal ? colors.gray : colors.yellow;
const black = internal ? colors.gray : (s: string): string => s;
if (callSite.isNative()) {
return cyan("native");
}
@ -130,9 +131,9 @@ function getFileLocation(callSite: CallSite, isInternal = false): string {
return result;
}
function callSiteToString(callSite: CallSite, isInternal = false): string {
const cyan = isInternal ? colors.gray : colors.cyan;
const black = isInternal ? colors.gray : (s: string): string => s;
function callSiteToString(callSite: CallSite, internal = false): string {
const cyan = internal ? colors.gray : colors.cyan;
const black = internal ? colors.gray : (s: string): string => s;
let result = "";
const functionName = callSite.getFunctionName();
@ -164,13 +165,11 @@ function callSiteToString(callSite: CallSite, isInternal = false): string {
} else if (functionName) {
result += colors.bold(colors.italic(black(functionName)));
} else {
result += getFileLocation(callSite, isInternal);
result += getFileLocation(callSite, internal);
return result;
}
result += ` ${black("(")}${getFileLocation(callSite, isInternal)}${black(
")"
)}`;
result += ` ${black("(")}${getFileLocation(callSite, internal)}${black(")")}`;
return result;
}

View file

@ -26,7 +26,11 @@ export enum ErrorKind {
Busy = 23,
}
export function getErrorClass(kind: ErrorKind): { new (msg: string): Error } {
interface ErrorClass {
new (msg: string): Error;
}
export function getErrorClass(kind: ErrorKind): ErrorClass {
switch (kind) {
case ErrorKind.TypeError:
return TypeError;
@ -79,102 +83,119 @@ class NotFound extends Error {
this.name = "NotFound";
}
}
class PermissionDenied extends Error {
constructor(msg: string) {
super(msg);
this.name = "PermissionDenied";
}
}
class ConnectionRefused extends Error {
constructor(msg: string) {
super(msg);
this.name = "ConnectionRefused";
}
}
class ConnectionReset extends Error {
constructor(msg: string) {
super(msg);
this.name = "ConnectionReset";
}
}
class ConnectionAborted extends Error {
constructor(msg: string) {
super(msg);
this.name = "ConnectionAborted";
}
}
class NotConnected extends Error {
constructor(msg: string) {
super(msg);
this.name = "NotConnected";
}
}
class AddrInUse extends Error {
constructor(msg: string) {
super(msg);
this.name = "AddrInUse";
}
}
class AddrNotAvailable extends Error {
constructor(msg: string) {
super(msg);
this.name = "AddrNotAvailable";
}
}
class BrokenPipe extends Error {
constructor(msg: string) {
super(msg);
this.name = "BrokenPipe";
}
}
class AlreadyExists extends Error {
constructor(msg: string) {
super(msg);
this.name = "AlreadyExists";
}
}
class InvalidData extends Error {
constructor(msg: string) {
super(msg);
this.name = "InvalidData";
}
}
class TimedOut extends Error {
constructor(msg: string) {
super(msg);
this.name = "TimedOut";
}
}
class Interrupted extends Error {
constructor(msg: string) {
super(msg);
this.name = "Interrupted";
}
}
class WriteZero extends Error {
constructor(msg: string) {
super(msg);
this.name = "WriteZero";
}
}
class UnexpectedEof extends Error {
constructor(msg: string) {
super(msg);
this.name = "UnexpectedEof";
}
}
class BadResource extends Error {
constructor(msg: string) {
super(msg);
this.name = "BadResource";
}
}
class Http extends Error {
constructor(msg: string) {
super(msg);
this.name = "Http";
}
}
class Busy extends Error {
constructor(msg: string) {
super(msg);
@ -183,22 +204,22 @@ class Busy extends Error {
}
export const errors = {
NotFound: NotFound,
PermissionDenied: PermissionDenied,
ConnectionRefused: ConnectionRefused,
ConnectionReset: ConnectionReset,
ConnectionAborted: ConnectionAborted,
NotConnected: NotConnected,
AddrInUse: AddrInUse,
AddrNotAvailable: AddrNotAvailable,
BrokenPipe: BrokenPipe,
AlreadyExists: AlreadyExists,
InvalidData: InvalidData,
TimedOut: TimedOut,
Interrupted: Interrupted,
WriteZero: WriteZero,
UnexpectedEof: UnexpectedEof,
BadResource: BadResource,
Http: Http,
Busy: Busy,
NotFound,
PermissionDenied,
ConnectionRefused,
ConnectionReset,
ConnectionAborted,
NotConnected,
AddrInUse,
AddrNotAvailable,
BrokenPipe,
AlreadyExists,
InvalidData,
TimedOut,
Interrupted,
WriteZero,
UnexpectedEof,
BadResource,
Http,
Busy,
};

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import {
Reader,
Writer,
@ -97,10 +98,7 @@ export class File
}
class Stdin implements Reader, ReaderSync, Closer {
readonly rid: number;
constructor() {
this.rid = 0;
}
readonly rid = 0;
read(p: Uint8Array): Promise<number | null> {
return read(this.rid, p);
@ -116,10 +114,7 @@ class Stdin implements Reader, ReaderSync, Closer {
}
class Stdout implements Writer, WriterSync, Closer {
readonly rid: number;
constructor() {
this.rid = 1;
}
readonly rid = 1;
write(p: Uint8Array): Promise<number> {
return write(this.rid, p);
@ -135,10 +130,7 @@ class Stdout implements Writer, WriterSync, Closer {
}
export class Stderr implements Writer, WriterSync, Closer {
readonly rid: number;
constructor() {
this.rid = 2;
}
readonly rid = 2;
write(p: Uint8Array): Promise<number> {
return write(this.rid, p);

View file

@ -1,9 +1,10 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
export const internalSymbol = Symbol("Deno.internal");
// The object where all the internal fields for testing will be living.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const internalObject: { [key: string]: any } = {};
export const internalObject: Record<string, any> = {};
// Register a field to internalObject for test access,
// through Deno[Deno.internal][name].

View file

@ -1,7 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
// Interfaces 100% copied from Go.
// Documentation liberally lifted from them too.
// Thank you! We love Go!
// Thank you! We love Go! <3
const DEFAULT_BUFFER_SIZE = 32 * 1024;

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { bootstrapMainRuntime } from "./runtime_main.ts";
import { bootstrapWorkerRuntime } from "./runtime_worker.ts";

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { errors } from "./errors.ts";
import { Reader, Writer, Closer } from "./io.ts";
import { read, write } from "./ops/io.ts";
@ -109,12 +110,11 @@ export class DatagramImpl implements DatagramConn {
return [sub, remoteAddr];
}
async send(p: Uint8Array, addr: Addr): Promise<number> {
send(p: Uint8Array, addr: Addr): Promise<number> {
const remote = { hostname: "127.0.0.1", ...addr };
const args = { ...remote, rid: this.rid };
const byteLength = await netOps.send(args as netOps.SendRequest, p);
return byteLength;
return netOps.send(args as netOps.SendRequest, p);
}
close(): void {
@ -125,11 +125,11 @@ export class DatagramImpl implements DatagramConn {
while (true) {
try {
yield await this.receive();
} catch (error) {
if (error instanceof errors.BadResource) {
} catch (err) {
if (err instanceof errors.BadResource) {
break;
}
throw error;
throw err;
}
}
}

View file

@ -1,3 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import * as netOps from "./ops/net.ts";
import {
Listener,
@ -22,6 +24,11 @@ export interface UnixListenOptions {
path: string;
}
export interface UnixConnectOptions {
transport: "unix";
path: string;
}
export function listen(
options: ListenOptions & { transport?: "tcp" }
): Listener;
@ -60,13 +67,6 @@ export function listenDatagram(
return new DatagramImpl(res.rid, res.localAddr);
}
export interface UnixConnectOptions {
transport: "unix";
path: string;
}
export async function connect(options: UnixConnectOptions): Promise<Conn>;
export async function connect(options: ConnectOptions): Promise<Conn>;
export async function connect(
options: ConnectOptions | UnixConnectOptions
): Promise<Conn> {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import * as util from "../util.ts";
import { core } from "../core.ts";
import { ErrorKind, getErrorClass } from "../errors.ts";
@ -18,9 +19,10 @@ interface JsonResponse {
}
// Using an object without a prototype because `Map` was causing GC problems.
const promiseTable: {
[key: number]: util.Resolvable<JsonResponse>;
} = Object.create(null);
const promiseTable: Record<
number,
util.Resolvable<JsonResponse>
> = Object.create(null);
let _nextPromiseId = 1;
function nextPromiseId(): number {
@ -28,13 +30,11 @@ function nextPromiseId(): number {
}
function decode(ui8: Uint8Array): JsonResponse {
const s = core.decode(ui8);
return JSON.parse(s) as JsonResponse;
return JSON.parse(core.decode(ui8));
}
function encode(args: object): Uint8Array {
const s = JSON.stringify(args);
return core.encode(s);
return core.encode(JSON.stringify(args));
}
function unwrapResponse(res: JsonResponse): Ok {
@ -80,7 +80,7 @@ export async function sendAsync(
const promise = util.createResolvable<Ok>();
const argsUi8 = encode(args);
const buf = core.dispatchByName(opName, argsUi8, ...zeroCopy);
if (buf) {
if (buf != null) {
// Sync result.
const res = decode(buf);
promise.resolve(res);

View file

@ -1,13 +1,15 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import * as util from "../util.ts";
import { core } from "../core.ts";
import { TextDecoder } from "../web/text_encoding.ts";
import { ErrorKind, errors, getErrorClass } from "../errors.ts";
// Using an object without a prototype because `Map` was causing GC problems.
const promiseTableMin: {
[key: number]: util.Resolvable<RecordMinimal>;
} = Object.create(null);
const promiseTableMin: Record<
number,
util.Resolvable<RecordMinimal>
> = Object.create(null);
// Note it's important that promiseId starts at 1 instead of 0, because sync
// messages are indicated with promiseId 0. If we ever add wrap around logic for
@ -93,7 +95,7 @@ export async function sendAsyncMinimal(
scratch32[2] = 0; // result
const promise = util.createResolvable<RecordMinimal>();
const buf = core.dispatchByName(opName, scratchBytes, zeroCopy);
if (buf) {
if (buf != null) {
const record = recordFromBufMinimal(buf);
// Sync result.
promise.resolve(record);

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { DiagnosticItem } from "../diagnostics.ts";
import { sendSync } from "./dispatch_json.ts";
@ -13,12 +14,7 @@ export interface Location {
}
export function applySourceMap(location: Location): Location {
const { fileName, lineNumber, columnNumber } = location;
const res = sendSync("op_apply_source_map", {
fileName,
lineNumber: lineNumber,
columnNumber: columnNumber,
});
const res = sendSync("op_apply_source_map", location);
return {
fileName: res.fileName,
lineNumber: res.lineNumber,

View file

@ -17,10 +17,10 @@ export interface FetchResponse {
export function fetch(
args: FetchRequest,
body: ArrayBufferView | undefined
body?: ArrayBufferView
): Promise<FetchResponse> {
let zeroCopy = undefined;
if (body) {
let zeroCopy;
if (body != null) {
zeroCopy = new Uint8Array(body.buffer, body.byteOffset, body.byteLength);
}

View file

@ -1,13 +1,12 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "../dispatch_json.ts";
import { pathFromURL } from "../../util.ts";
export function chmodSync(path: string | URL, mode: number): void {
path = pathFromURL(path);
sendSync("op_chmod", { path, mode });
sendSync("op_chmod", { path: pathFromURL(path), mode });
}
export async function chmod(path: string | URL, mode: number): Promise<void> {
path = pathFromURL(path);
await sendAsync("op_chmod", { path, mode });
await sendAsync("op_chmod", { path: pathFromURL(path), mode });
}

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "../dispatch_json.ts";
import { pathFromURL } from "../../util.ts";
@ -7,8 +8,7 @@ export function chownSync(
uid: number | null,
gid: number | null
): void {
path = pathFromURL(path);
sendSync("op_chown", { path, uid, gid });
sendSync("op_chown", { path: pathFromURL(path), uid, gid });
}
export async function chown(
@ -16,6 +16,5 @@ export async function chown(
uid: number | null,
gid: number | null
): Promise<void> {
path = pathFromURL(path);
await sendAsync("op_chown", { path, uid, gid });
await sendAsync("op_chown", { path: pathFromURL(path), uid, gid });
}

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "../dispatch_json.ts";
import { pathFromURL } from "../../util.ts";
@ -6,18 +7,18 @@ export function copyFileSync(
fromPath: string | URL,
toPath: string | URL
): void {
fromPath = pathFromURL(fromPath);
toPath = pathFromURL(toPath);
sendSync("op_copy_file", { from: fromPath, to: toPath });
sendSync("op_copy_file", {
from: pathFromURL(fromPath),
to: pathFromURL(toPath),
});
}
export async function copyFile(
fromPath: string | URL,
toPath: string | URL
): Promise<void> {
fromPath = pathFromURL(fromPath);
toPath = pathFromURL(toPath);
await sendAsync("op_copy_file", { from: fromPath, to: toPath });
await sendAsync("op_copy_file", {
from: pathFromURL(fromPath),
to: pathFromURL(toPath),
});
}

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync } from "../dispatch_json.ts";
export function cwd(): string {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "../dispatch_json.ts";
export function linkSync(oldpath: string, newpath: string): void {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "../dispatch_json.ts";
export interface MakeTempOptions {

View file

@ -1,11 +1,21 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "../dispatch_json.ts";
type MkdirArgs = { path: string; recursive: boolean; mode?: number };
export interface MkdirOptions {
recursive?: boolean;
mode?: number;
}
interface MkdirArgs {
path: string;
recursive: boolean;
mode?: number;
}
function mkdirArgs(path: string, options?: MkdirOptions): MkdirArgs {
const args: MkdirArgs = { path, recursive: false };
if (options) {
if (options != null) {
if (typeof options.recursive == "boolean") {
args.recursive = options.recursive;
}
@ -16,11 +26,6 @@ function mkdirArgs(path: string, options?: MkdirOptions): MkdirArgs {
return args;
}
export interface MkdirOptions {
recursive?: boolean;
mode?: number;
}
export function mkdirSync(path: string, options?: MkdirOptions): void {
sendSync("op_mkdir", mkdirArgs(path, options));
}

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "../dispatch_json.ts";
import { pathFromURL } from "../../util.ts";
@ -18,8 +19,7 @@ export interface OpenOptions {
export function openSync(path: string | URL, options: OpenOptions): number {
const mode: number | undefined = options?.mode;
path = pathFromURL(path);
return sendSync("op_open", { path, options, mode });
return sendSync("op_open", { path: pathFromURL(path), options, mode });
}
export function open(
@ -27,10 +27,5 @@ export function open(
options: OpenOptions
): Promise<number> {
const mode: number | undefined = options?.mode;
path = pathFromURL(path);
return sendAsync("op_open", {
path,
options,
mode,
});
return sendAsync("op_open", { path: pathFromURL(path), options, mode });
}

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "../dispatch_json.ts";
import { pathFromURL } from "../../util.ts";
@ -18,13 +19,13 @@ function res(response: ReadDirResponse): DirEntry[] {
}
export function readDirSync(path: string | URL): Iterable<DirEntry> {
path = pathFromURL(path);
return res(sendSync("op_read_dir", { path }))[Symbol.iterator]();
return res(sendSync("op_read_dir", { path: pathFromURL(path) }))[
Symbol.iterator
]();
}
export function readDir(path: string | URL): AsyncIterable<DirEntry> {
path = pathFromURL(path);
const array = sendAsync("op_read_dir", { path }).then(res);
const array = sendAsync("op_read_dir", { path: pathFromURL(path) }).then(res);
return {
async *[Symbol.asyncIterator](): AsyncIterableIterator<DirEntry> {
yield* await array;

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "../dispatch_json.ts";
export function readLinkSync(path: string): string {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "../dispatch_json.ts";
export function realPathSync(path: string): string {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "../dispatch_json.ts";
import { pathFromURL } from "../../util.ts";
@ -10,14 +11,18 @@ export function removeSync(
path: string | URL,
options: RemoveOptions = {}
): void {
path = pathFromURL(path);
sendSync("op_remove", { path, recursive: !!options.recursive });
sendSync("op_remove", {
path: pathFromURL(path),
recursive: !!options.recursive,
});
}
export async function remove(
path: string | URL,
options: RemoveOptions = {}
): Promise<void> {
path = pathFromURL(path);
await sendAsync("op_remove", { path, recursive: !!options.recursive });
await sendAsync("op_remove", {
path: pathFromURL(path),
recursive: !!options.recursive,
});
}

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "../dispatch_json.ts";
export function renameSync(oldpath: string, newpath: string): void {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "../dispatch_json.ts";
import { SeekMode } from "../../io.ts";

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "../dispatch_json.ts";
import { build } from "../../build.ts";
import { pathFromURL } from "../../util.ts";
@ -44,7 +45,7 @@ export interface StatResponse {
// @internal
export function parseFileInfo(response: StatResponse): FileInfo {
const isUnix = build.os === "darwin" || build.os === "linux";
const unix = build.os === "darwin" || build.os === "linux";
return {
isFile: response.isFile,
isDirectory: response.isDirectory,
@ -54,15 +55,15 @@ export function parseFileInfo(response: StatResponse): FileInfo {
atime: response.atime != null ? new Date(response.atime) : null,
birthtime: response.birthtime != null ? new Date(response.birthtime) : null,
// Only non-null if on Unix
dev: isUnix ? response.dev : null,
ino: isUnix ? response.ino : null,
mode: isUnix ? response.mode : null,
nlink: isUnix ? response.nlink : null,
uid: isUnix ? response.uid : null,
gid: isUnix ? response.gid : null,
rdev: isUnix ? response.rdev : null,
blksize: isUnix ? response.blksize : null,
blocks: isUnix ? response.blocks : null,
dev: unix ? response.dev : null,
ino: unix ? response.ino : null,
mode: unix ? response.mode : null,
nlink: unix ? response.nlink : null,
uid: unix ? response.uid : null,
gid: unix ? response.gid : null,
rdev: unix ? response.rdev : null,
blksize: unix ? response.blksize : null,
blocks: unix ? response.blocks : null,
};
}
@ -75,37 +76,33 @@ export async function fstat(rid: number): Promise<FileInfo> {
}
export async function lstat(path: string | URL): Promise<FileInfo> {
path = pathFromURL(path);
const res = (await sendAsync("op_stat", {
path,
const res = await sendAsync("op_stat", {
path: pathFromURL(path),
lstat: true,
})) as StatResponse;
});
return parseFileInfo(res);
}
export function lstatSync(path: string | URL): FileInfo {
path = pathFromURL(path);
const res = sendSync("op_stat", {
path,
path: pathFromURL(path),
lstat: true,
}) as StatResponse;
});
return parseFileInfo(res);
}
export async function stat(path: string | URL): Promise<FileInfo> {
path = pathFromURL(path);
const res = (await sendAsync("op_stat", {
path,
const res = await sendAsync("op_stat", {
path: pathFromURL(path),
lstat: false,
})) as StatResponse;
});
return parseFileInfo(res);
}
export function statSync(path: string | URL): FileInfo {
path = pathFromURL(path);
const res = sendSync("op_stat", {
path,
path: pathFromURL(path),
lstat: false,
}) as StatResponse;
});
return parseFileInfo(res);
}

View file

@ -1,14 +1,15 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "../dispatch_json.ts";
export type symlinkOptions = {
export interface SymlinkOptions {
type: "file" | "dir";
};
}
export function symlinkSync(
oldpath: string,
newpath: string,
options?: symlinkOptions
options?: SymlinkOptions
): void {
sendSync("op_symlink", { oldpath, newpath, options });
}
@ -16,7 +17,7 @@ export function symlinkSync(
export async function symlink(
oldpath: string,
newpath: string,
options?: symlinkOptions
options?: SymlinkOptions
): Promise<void> {
await sendAsync("op_symlink", { oldpath, newpath, options });
}

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "../dispatch_json.ts";
export function fdatasyncSync(rid: number): void {

View file

@ -1,12 +1,9 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "../dispatch_json.ts";
function coerceLen(len?: number): number {
if (!len) {
return 0;
}
if (len < 0) {
if (len == null || len < 0) {
return 0;
}

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync } from "../dispatch_json.ts";
export function umask(mask?: number): number {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "../dispatch_json.ts";
function toSecondsFromEpoch(v: number | Date): number {

View file

@ -1,4 +1,5 @@
// Copyright 2019 the Deno authors. All rights reserved. MIT license.
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./dispatch_json.ts";
import { close } from "./resources.ts";
@ -7,10 +8,14 @@ export interface FsEvent {
paths: string[];
}
interface FsWatcherOptions {
recursive: boolean;
}
class FsWatcher implements AsyncIterableIterator<FsEvent> {
readonly rid: number;
constructor(paths: string[], options: { recursive: boolean }) {
constructor(paths: string[], options: FsWatcherOptions) {
const { recursive } = options;
this.rid = sendSync("op_fs_events_open", { recursive, paths });
}
@ -33,7 +38,7 @@ class FsWatcher implements AsyncIterableIterator<FsEvent> {
export function watchFs(
paths: string | string[],
options = { recursive: true }
options: FsWatcherOptions = { recursive: true }
): AsyncIterableIterator<FsEvent> {
return new FsWatcher(Array.isArray(paths) ? paths : [paths], options);
}

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync } from "./dispatch_json.ts";
import { assert } from "../util.ts";

View file

@ -3,50 +3,48 @@
import { sendAsyncMinimal, sendSyncMinimal } from "./dispatch_minimal.ts";
export function readSync(rid: number, buffer: Uint8Array): number | null {
if (buffer.length == 0) {
if (buffer.length === 0) {
return 0;
}
const nread = sendSyncMinimal("op_read", rid, buffer);
if (nread < 0) {
throw new Error("read error");
} else if (nread == 0) {
return null;
} else {
return nread;
}
return nread === 0 ? null : nread;
}
export async function read(
rid: number,
buffer: Uint8Array
): Promise<number | null> {
if (buffer.length == 0) {
if (buffer.length === 0) {
return 0;
}
const nread = await sendAsyncMinimal("op_read", rid, buffer);
if (nread < 0) {
throw new Error("read error");
} else if (nread == 0) {
return null;
} else {
return nread;
}
return nread === 0 ? null : nread;
}
export function writeSync(rid: number, data: Uint8Array): number {
const result = sendSyncMinimal("op_write", rid, data);
if (result < 0) {
throw new Error("write error");
} else {
return result;
}
return result;
}
export async function write(rid: number, data: Uint8Array): Promise<number> {
const result = await sendAsyncMinimal("op_write", rid, data);
if (result < 0) {
throw new Error("write error");
} else {
return result;
}
return result;
}

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./dispatch_json.ts";
export interface NetAddr {
@ -18,7 +19,7 @@ export enum ShutdownMode {
// See http://man7.org/linux/man-pages/man2/shutdown.2.html
// Corresponding to SHUT_RD, SHUT_WR, SHUT_RDWR
Read = 0,
Write,
Write = 1,
ReadWrite, // unused
}
@ -80,10 +81,6 @@ export type SendRequest = {
rid: number;
} & Addr;
export async function send(
args: SendRequest,
zeroCopy: Uint8Array
): Promise<number> {
const byteLength = await sendAsync("op_datagram_send", args, zeroCopy);
return byteLength;
export function send(args: SendRequest, zeroCopy: Uint8Array): Promise<number> {
return sendAsync("op_datagram_send", args, zeroCopy);
}

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync } from "./dispatch_json.ts";
export function loadavg(): number[] {
@ -32,7 +33,7 @@ function deleteEnv(key: string): void {
export const env = {
get: getEnv,
toObject(): { [key: string]: string } {
toObject(): Record<string, string> {
return sendSync("op_env");
},
set: setEnv,

View file

@ -1,9 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync } from "./dispatch_json.ts";
// TODO(bartlomieju): duplicated in `cli/js/permissions.ts` as
// `PermissionState
export type PermissionResponse = "granted" | "denied" | "prompt";
import { sendSync } from "./dispatch_json.ts";
import { PermissionState } from "../permissions.ts";
interface PermissionRequest {
name: string;
@ -11,14 +9,14 @@ interface PermissionRequest {
path?: string;
}
export function query(desc: PermissionRequest): PermissionResponse {
export function query(desc: PermissionRequest): PermissionState {
return sendSync("op_query_permission", desc).state;
}
export function revoke(desc: PermissionRequest): PermissionResponse {
export function revoke(desc: PermissionRequest): PermissionState {
return sendSync("op_revoke_permission", desc).state;
}
export function request(desc: PermissionRequest): PermissionResponse {
export function request(desc: PermissionRequest): PermissionState {
return sendSync("op_request_permission", desc).state;
}

View file

@ -1,6 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync } from "./dispatch_json.ts";
export function openPlugin(filename: string): number {
const rid = sendSync("op_open_plugin", { filename });
return rid;
return sendSync("op_open_plugin", { filename });
}

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./dispatch_json.ts";
import { assert } from "../util.ts";

View file

@ -1,9 +1,8 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync } from "./dispatch_json.ts";
export interface ResourceMap {
[rid: number]: string;
}
export type ResourceMap = Record<number, string>;
export function resources(): ResourceMap {
const res = sendSync("op_resources") as Array<[number, string]>;

View file

@ -1,11 +1,20 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./dispatch_json.ts";
export function bindSignal(signo: number): { rid: number } {
interface BindSignalResponse {
rid: number;
}
interface PollSignalResponse {
done: boolean;
}
export function bindSignal(signo: number): BindSignalResponse {
return sendSync("op_signal_bind", { signo });
}
export function pollSignal(rid: number): Promise<{ done: boolean }> {
export function pollSignal(rid: number): Promise<PollSignalResponse> {
return sendAsync("op_signal_poll", { rid });
}

View file

@ -1,6 +1,12 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./dispatch_json.ts";
interface NowResponse {
seconds: number;
subsecNanos: number;
}
export function stopGlobalTimer(): void {
sendSync("op_global_timer_stop");
}
@ -9,11 +15,6 @@ export async function startGlobalTimer(timeout: number): Promise<void> {
await sendAsync("op_global_timer", { timeout });
}
interface NowResponse {
seconds: number;
subsecNanos: number;
}
export function now(): NowResponse {
return sendSync("op_now");
}

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendAsync, sendSync } from "./dispatch_json.ts";
export interface ConnectTLSRequest {

View file

@ -1,3 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync } from "./dispatch_json.ts";
export function isatty(rid: number): boolean {
@ -5,8 +7,5 @@ export function isatty(rid: number): boolean {
}
export function setRaw(rid: number, mode: boolean): void {
sendSync("op_set_raw", {
rid,
mode,
});
sendSync("op_set_raw", { rid, mode });
}

View file

@ -1,14 +1,19 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
/* eslint-disable @typescript-eslint/no-explicit-any */
import { sendAsync, sendSync } from "./dispatch_json.ts";
interface CreateWorkerResponse {
id: number;
}
export function createWorker(
specifier: string,
hasSourceCode: boolean,
sourceCode: string,
useDenoNamespace: boolean,
name?: string
): { id: number } {
): CreateWorkerResponse {
return sendSync("op_create_worker", {
specifier,
hasSourceCode,

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import * as permissionsOps from "./ops/permissions.ts";
export type PermissionName =

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { File } from "./files.ts";
import { close } from "./ops/resources.ts";
import { Closer, Reader, Writer } from "./io.ts";
@ -10,7 +11,7 @@ import { kill, runStatus as runStatusOp, run as runOp } from "./ops/process.ts";
export interface RunOptions {
cmd: string[];
cwd?: string;
env?: { [key: string]: string };
env?: Record<string, string>;
stdout?: "inherit" | "piped" | "null" | number;
stderr?: "inherit" | "piped" | "null" | number;
stdin?: "inherit" | "piped" | "null" | number;
@ -100,16 +101,8 @@ export class Process<T extends RunOptions = RunOptions> {
}
export type ProcessStatus =
| {
success: true;
code: 0;
signal?: undefined;
}
| {
success: false;
code: number;
signal?: number;
};
| { success: true; code: 0; signal?: undefined }
| { success: false; code: number; signal?: number };
function isRid(arg: unknown): arg is number {
return !isNaN(arg as number);

View file

@ -1,3 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
// Derived from https://github.com/vadimg/js_bintrees. MIT Licensed.
import { assert } from "./util.ts";
@ -27,7 +29,7 @@ class RBNode<T> {
}
export class RBTree<T> {
#comparator: (a: T, b: T) => number;
readonly #comparator: (a: T, b: T) => number;
#root: RBNode<T> | null;
constructor(comparator: (a: T, b: T) => number) {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { open, openSync } from "./files.ts";
import { readAll, readAllSync } from "./buffer.ts";

View file

@ -1,18 +1,20 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { open, openSync } from "./files.ts";
import { readAll, readAllSync } from "./buffer.ts";
export function readTextFileSync(path: string | URL): string {
const decoder = new TextDecoder();
const file = openSync(path);
const content = readAllSync(file);
const contents = readAllSync(file);
file.close();
return decoder.decode(content);
const decoder = new TextDecoder();
return decoder.decode(contents);
}
export async function readTextFile(path: string | URL): Promise<string> {
const decoder = new TextDecoder();
const file = await open(path);
const content = await readAll(file);
const contents = await readAll(file);
file.close();
return decoder.decode(content);
const decoder = new TextDecoder();
return decoder.decode(contents);
}

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { exit } from "./ops/os.ts";
import { core } from "./core.ts";
import { version } from "./version.ts";

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { core } from "./core.ts";
import * as dispatchMinimal from "./ops/dispatch_minimal.ts";
import * as dispatchJson from "./ops/dispatch_json.ts";

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { bindSignal, pollSignal, unbindSignal } from "./ops/signal.ts";
import { build } from "./build.ts";
@ -129,7 +130,7 @@ export class SignalStream
implements AsyncIterableIterator<void>, PromiseLike<void> {
#disposed = false;
#pollingPromise: Promise<boolean> = Promise.resolve(false);
#rid: number;
readonly #rid: number;
constructor(signo: number) {
this.#rid = bindSignal(signo).rid;

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { gray, green, italic, red, yellow } from "./colors.ts";
import { exit } from "./ops/os.ts";
import { Console, stringifyArgs } from "./web/console.ts";
@ -11,9 +12,9 @@ import { assert } from "./util.ts";
const disabledConsole = new Console((): void => {});
function delay(n: number): Promise<void> {
return new Promise((resolve: () => void, _) => {
setTimeout(resolve, n);
function delay(ms: number): Promise<void> {
return new Promise((resolve: () => void) => {
setTimeout(resolve, ms);
});
}
@ -241,7 +242,7 @@ class TestRunner {
passed: 0,
failed: 0,
};
private usedOnly: boolean;
readonly #usedOnly: boolean;
constructor(
tests: TestDefinition[],
@ -249,8 +250,8 @@ class TestRunner {
public failFast: boolean
) {
const onlyTests = tests.filter(({ only }) => only);
this.usedOnly = onlyTests.length > 0;
const unfilteredTests = this.usedOnly ? onlyTests : tests;
this.#usedOnly = onlyTests.length > 0;
const unfilteredTests = this.#usedOnly ? onlyTests : tests;
this.testsToRun = unfilteredTests.filter(filterFn);
this.stats.filtered = unfilteredTests.length - this.testsToRun.length;
}
@ -292,7 +293,7 @@ class TestRunner {
const duration = +new Date() - suiteStart;
yield {
end: { ...this.stats, usedOnly: this.usedOnly, duration, results },
end: { ...this.stats, usedOnly: this.#usedOnly, duration, results },
};
}
}

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import * as tlsOps from "./ops/tls.ts";
import { Listener, Conn, ConnImpl, ListenerImpl } from "./net.ts";
@ -65,7 +66,7 @@ interface StartTlsOptions {
export async function startTls(
conn: Conn,
{ hostname = "127.0.0.1", certFile = undefined }: StartTlsOptions = {}
{ hostname = "127.0.0.1", certFile }: StartTlsOptions = {}
): Promise<Conn> {
const res = await tlsOps.startTls({
rid: conn.rid,

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { build } from "./build.ts";
import { exposeForTest } from "./internals.ts";

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
interface Version {
deno: string;
v8: string;

View file

@ -2,10 +2,10 @@
This directory facilities Web APIs that are available in Deno.
Please note, that some of implementations might not be completely aligned with
Please note, that some implementations might not be completely aligned with
specification.
Some of the Web APIs are using ops under the hood, eg. `console`, `performance`.
Some Web APIs are using ops under the hood, eg. `console`, `performance`.
## Implemented Web APIs

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { AbortSignalImpl, signalAbort } from "./abort_signal.ts";
export class AbortControllerImpl implements AbortController {

View file

@ -1,3 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
// Forked from https://github.com/beatgammit/base64-js
// Copyright (c) 2014 Jameson Little. MIT License.

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { TextDecoder, TextEncoder } from "./text_encoding.ts";
import { build } from "../build.ts";
import { ReadableStreamImpl } from "./streams/readable_stream.ts";

View file

@ -1,3 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import * as blob from "./blob.ts";
import * as encoding from "./text_encoding.ts";
import * as domTypes from "./dom_types.d.ts";

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { isInvalidDate, isTypedArray, TypedArray } from "./util.ts";
import { cliTable } from "./console_table.ts";
import { exposeForTest } from "../internals.ts";
@ -381,7 +382,7 @@ function createTypedArrayString(
displayName: `${typedArrayName}(${valueLength})`,
delims: ["[", "]"],
entryHandler: (entry, ctx, level, maxLevel): string => {
const [_, val] = entry;
const val = entry[1];
return stringifyWithQuotes(val, ctx, level + 1, maxLevel);
},
group: true,
@ -400,7 +401,7 @@ function createSetString(
displayName: "Set",
delims: ["{", "}"],
entryHandler: (entry, ctx, level, maxLevel): string => {
const [_, val] = entry;
const val = entry[1];
return stringifyWithQuotes(val, ctx, level + 1, maxLevel);
},
group: false,
@ -508,7 +509,7 @@ function createRawObjectString(
}
ctx.add(value);
let baseString = "";
let baseString: string;
let shouldShowDisplayName = false;
let displayName = (value as { [Symbol.toStringTag]: string })[
@ -724,7 +725,7 @@ const timerMap = new Map<string, number>();
const isConsoleInstance = Symbol("isConsoleInstance");
export class Console {
#printFunc: PrintFunc;
readonly #printFunc: PrintFunc;
indentLevel: number;
[isConsoleInstance] = false;

View file

@ -1,3 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
// Copyright Joyent, Inc. and other Node contributors. MIT license.
// Forked from Node's lib/internal/cli_table.js

View file

@ -1,10 +1,11 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { EventImpl as Event } from "./event.ts";
import { requiredArguments } from "./util.ts";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export class CustomEventImpl<T = any> extends Event implements CustomEvent {
#detail: T;
readonly #detail: T;
constructor(type: string, eventInitDict: CustomEventInit<T> = {}) {
super(type, eventInitDict);

View file

@ -1,3 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
// This module is based on Bjoern Hoehrmann's DFA UTF-8 decoder.
// See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details.
//

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
export class DOMExceptionImpl extends Error implements DOMException {
#name: string;
readonly #name: string;
constructor(message = "", name = "Error") {
super(message);

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import * as blob from "./blob.ts";
export class DomFileImpl extends blob.DenoBlob implements File {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { requiredArguments } from "./util.ts";
import { exposeForTest } from "../internals.ts";

View file

@ -4,12 +4,12 @@ import { EventImpl as Event } from "./event.ts";
import { defineEnumerableProps } from "./util.ts";
export class ErrorEventImpl extends Event implements ErrorEvent {
#message: string;
#filename: string;
#lineno: number;
#colno: number;
readonly #message: string;
readonly #filename: string;
readonly #lineno: number;
readonly #colno: number;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
#error: any;
readonly #error: any;
get message(): string {
return this.#message;

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { notImplemented } from "../util.ts";
import { isTypedArray } from "./util.ts";
import * as domTypes from "./dom_types.d.ts";
@ -55,7 +56,6 @@ export class Response extends Body.Body implements domTypes.Response {
if (!type) {
type = "default";
} else {
type = type;
if (type == "error") {
// spec: https://fetch.spec.whatwg.org/#concept-network-error
status = 0;
@ -144,12 +144,11 @@ export class Response extends Body.Body implements domTypes.Response {
resBody = tees[1];
}
const cloned = new Response(resBody, {
return new Response(resBody, {
status: this.status,
statusText: this.statusText,
headers: new Headers(headersList),
});
return cloned;
}
static redirect(url: URL | string, status: number): domTypes.Response {
@ -260,7 +259,7 @@ export async function fetch(
}
let responseBody;
let responseInit: ResponseInit = {};
let responseInit: domTypes.ResponseInit = {};
while (remRedirectCount) {
const fetchResponse = await sendFetchReq(url, method, headers, body);

View file

@ -19,12 +19,9 @@ interface MultipartHeaders {
export class MultipartBuilder {
readonly boundary: string;
readonly formData: FormData;
readonly writer: Buffer;
constructor(formData: FormData, boundary?: string) {
readonly writer = new Buffer();
constructor(readonly formData: FormData, boundary?: string) {
this.boundary = boundary ?? this.#createBoundary();
this.formData = formData;
this.writer = new Buffer();
}
getContentType(): string {

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import * as blob from "./blob.ts";
import * as domFile from "./dom_file.ts";
import { DomIterableMixin } from "./dom_iterable.ts";
@ -96,10 +97,13 @@ class FormDataBase {
if (value instanceof domFile.DomFileImpl) {
this[dataSymbol][i][1] = value;
} else if (value instanceof blob.DenoBlob) {
const dfile = new domFile.DomFileImpl([value], filename || "blob", {
this[dataSymbol][i][1] = new domFile.DomFileImpl(
[value],
filename || "blob",
{
type: value.type,
});
this[dataSymbol][i][1] = dfile;
}
);
} else {
this[dataSymbol][i][1] = String(value);
}

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { DomIterableMixin } from "./dom_iterable.ts";
import { requiredArguments } from "./util.ts";
import { customInspect } from "./console.ts";

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { now as opNow } from "../ops/timers.ts";
export class Performance {

View file

@ -1,7 +1,9 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
export enum PromiseState {
Pending = 0,
Fulfilled = 1,
Rejected = 2,
Pending,
Fulfilled,
Rejected,
}
export type PromiseDetails<T> = [PromiseState, T | undefined];

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import * as body from "./body.ts";
import * as domTypes from "./dom_types.d.ts";
import { ReadableStreamImpl } from "./streams/readable_stream.ts";
@ -128,12 +129,11 @@ export class Request extends body.Body implements domTypes.Request {
body2 = tees[1];
}
const cloned = new Request(this.url, {
return new Request(this.url, {
body: body2,
method: this.method,
headers: new Headers(headersList),
credentials: this.credentials,
});
return cloned;
}
}

View file

@ -5,7 +5,6 @@
//
// There are some parts that are not fully implemented, and there are some
// comments which point to steps of the specification that are not implemented.
//
/* eslint-disable @typescript-eslint/no-explicit-any,require-await */
import { ReadableByteStreamControllerImpl } from "./readable_byte_stream_controller.ts";
@ -62,7 +61,7 @@ export interface ReadableStreamGenericReader<R = any>
export interface ReadableStreamAsyncIterator<T = any> extends AsyncIterator<T> {
[sym.asyncIteratorReader]: ReadableStreamDefaultReaderImpl<T>;
[sym.preventCancel]: boolean;
return(value?: any | PromiseLike<any>): Promise<IteratorResult<T, any>>;
return(value?: any | PromiseLike<any>): Promise<IteratorResult<T>>;
}
export function acquireReadableStreamDefaultReader<T>(
@ -97,6 +96,7 @@ function createAlgorithmFromUnderlyingMethod<
algoArgCount: 0,
...extraArgs: any[]
): () => Promise<void>;
function createAlgorithmFromUnderlyingMethod<
O extends UnderlyingByteSource | UnderlyingSource | Transformer,
P extends keyof O
@ -317,79 +317,72 @@ function isFiniteNonNegativeNumber(v: unknown): v is number {
export function isReadableByteStreamController(
x: unknown
): x is ReadableByteStreamControllerImpl {
return typeof x !== "object" ||
return !(
typeof x !== "object" ||
x === null ||
!(sym.controlledReadableByteStream in x)
? false
: true;
);
}
export function isReadableStream(x: unknown): x is ReadableStreamImpl {
return typeof x !== "object" ||
return !(
typeof x !== "object" ||
x === null ||
!(sym.readableStreamController in x)
? false
: true;
);
}
export function isReadableStreamAsyncIterator(
x: unknown
): x is ReadableStreamAsyncIterator<any> {
): x is ReadableStreamAsyncIterator {
if (typeof x !== "object" || x === null) {
return false;
}
if (!(sym.asyncIteratorReader in x)) {
return false;
}
return true;
return sym.asyncIteratorReader in x;
}
export function isReadableStreamDefaultController(
x: unknown
): x is ReadableStreamDefaultControllerImpl {
return typeof x !== "object" ||
return !(
typeof x !== "object" ||
x === null ||
!(sym.controlledReadableStream in x)
? false
: true;
);
}
export function isReadableStreamDefaultReader<T>(
x: unknown
): x is ReadableStreamDefaultReaderImpl<T> {
return typeof x !== "object" || x === null || !(sym.readRequests in x)
? false
: true;
return !(typeof x !== "object" || x === null || !(sym.readRequests in x));
}
export function isReadableStreamLocked(stream: ReadableStreamImpl): boolean {
assert(isReadableStream(stream));
return stream[sym.reader] ? true : false;
return !!stream[sym.reader];
}
export function isReadableStreamDisturbed(stream: ReadableStream): boolean {
assert(isReadableStream(stream));
return stream[sym.disturbed] ? true : false;
return !!stream[sym.disturbed];
}
export function isTransformStream(
x: unknown
): x is TransformStreamImpl<any, any> {
return typeof x !== "object" ||
export function isTransformStream(x: unknown): x is TransformStreamImpl {
return !(
typeof x !== "object" ||
x === null ||
!(sym.transformStreamController in x)
? false
: true;
);
}
export function isTransformStreamDefaultController(
x: unknown
): x is TransformStreamDefaultControllerImpl<any, any> {
return typeof x !== "object" ||
): x is TransformStreamDefaultControllerImpl {
return !(
typeof x !== "object" ||
x === null ||
!(sym.controlledTransformStream in x)
? false
: true;
);
}
export function isUnderlyingByteSource(
@ -401,37 +394,36 @@ export function isUnderlyingByteSource(
}
export function isWritableStream(x: unknown): x is WritableStreamImpl {
return typeof x !== "object" ||
return !(
typeof x !== "object" ||
x === null ||
!(sym.writableStreamController in x)
? false
: true;
);
}
export function isWritableStreamDefaultController(
x: unknown
): x is WritableStreamDefaultControllerImpl<any> {
return typeof x !== "object" ||
return !(
typeof x !== "object" ||
x === null ||
!(sym.controlledWritableStream in x)
? false
: true;
);
}
export function isWritableStreamDefaultWriter(
x: unknown
): x is WritableStreamDefaultWriterImpl<any> {
return typeof x !== "object" || x === null || !(sym.ownerWritableStream in x)
? false
: true;
return !(
typeof x !== "object" ||
x === null ||
!(sym.ownerWritableStream in x)
);
}
export function isWritableStreamLocked(stream: WritableStreamImpl): boolean {
assert(isWritableStream(stream));
if (stream[sym.writer] === undefined) {
return false;
}
return true;
return stream[sym.writer] !== undefined;
}
export function makeSizeAlgorithmFromSizeFunction<T>(
@ -476,10 +468,7 @@ function readableByteStreamControllerShouldCallPull(
// ReadableStreamGetNumReadIntoRequests(stream) > 0, return true.
const desiredSize = readableByteStreamControllerGetDesiredSize(controller);
assert(desiredSize !== null);
if (desiredSize > 0) {
return true;
}
return false;
return desiredSize > 0;
}
export function readableByteStreamControllerCallPullIfNeeded(
@ -730,10 +719,7 @@ export function readableStreamDefaultControllerCanCloseOrEnqueue<T>(
controller: ReadableStreamDefaultControllerImpl<T>
): boolean {
const state = controller[sym.controlledReadableStream][sym.state];
if (!controller[sym.closeRequested] && state === "readable") {
return true;
}
return false;
return !controller[sym.closeRequested] && state === "readable";
}
export function readableStreamDefaultControllerClearAlgorithms<T>(
@ -813,9 +799,7 @@ export function readableStreamDefaultControllerError<T>(
function readableStreamDefaultControllerHasBackpressure<T>(
controller: ReadableStreamDefaultControllerImpl<T>
): boolean {
return readableStreamDefaultControllerShouldCallPull(controller)
? true
: false;
return readableStreamDefaultControllerShouldCallPull(controller);
}
function readableStreamDefaultControllerShouldCallPull<T>(
@ -836,10 +820,7 @@ function readableStreamDefaultControllerShouldCallPull<T>(
}
const desiredSize = readableStreamDefaultControllerGetDesiredSize(controller);
assert(desiredSize !== null);
if (desiredSize > 0) {
return true;
}
return false;
return desiredSize > 0;
}
export function readableStreamDefaultReaderRead<R>(
@ -914,9 +895,7 @@ export function readableStreamHasDefaultReader(
stream: ReadableStreamImpl
): boolean {
const reader = stream[sym.reader];
return reader === undefined || !isReadableStreamDefaultReader(reader)
? false
: true;
return !(reader === undefined || !isReadableStreamDefaultReader(reader));
}
export function readableStreamPipeTo<T>(
@ -1927,13 +1906,10 @@ export function writableStreamClose<W>(
export function writableStreamCloseQueuedOrInFlight<W>(
stream: WritableStreamImpl<W>
): boolean {
if (
return !(
stream[sym.closeRequest] === undefined &&
stream[sym.inFlightCloseRequest] === undefined
) {
return false;
}
return true;
);
}
function writableStreamDealWithRejection<W>(
@ -2348,13 +2324,10 @@ function writableStreamFinishInFlightWriteWithError<W>(
function writableStreamHasOperationMarkedInFlight<W>(
stream: WritableStreamImpl<W>
): boolean {
if (
return !(
stream[sym.inFlightWriteRequest] === undefined &&
stream[sym.inFlightCloseRequest] === undefined
) {
return false;
}
return true;
);
}
function writableStreamMarkCloseRequestInFlight<W>(

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
// The following code is based off of text-encoding at:
// https://github.com/inexorabletash/text-encoding
//
@ -151,8 +152,8 @@ interface Encoder {
}
class SingleByteDecoder implements Decoder {
#index: number[];
#fatal: boolean;
readonly #index: number[];
readonly #fatal: boolean;
constructor(
index: number[],
@ -422,7 +423,7 @@ function isEitherArrayBuffer(x: any): x is EitherArrayBuffer {
}
export class TextDecoder {
#encoding: string;
readonly #encoding: string;
get encoding(): string {
return this.#encoding;

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { assert } from "../util.ts";
import { startGlobalTimer, stopGlobalTimer } from "../ops/timers.ts";
import { RBTree } from "../rbtree.ts";

View file

@ -24,7 +24,7 @@ const searchParamsMethods: Array<keyof URLSearchParams> = [
const specialSchemes = ["ftp", "file", "http", "https", "ws", "wss"];
// https://url.spec.whatwg.org/#special-scheme
const schemePorts: { [key: string]: string } = {
const schemePorts: Record<string, string> = {
ftp: "21",
file: "",
http: "80",
@ -179,8 +179,8 @@ function resolvePathFromBase(
let driveLetterPrefix = "";
if (build.os == "windows" && isFilePath) {
let driveLetter = "";
let baseDriveLetter = "";
let driveLetter: string;
let baseDriveLetter: string;
[driveLetter, normalizedPath] = takePattern(
normalizedPath,
/^(\/[A-Za-z]:)(?=\/)/
@ -214,7 +214,8 @@ function resolvePathFromBase(
function isValidPort(value: string): boolean {
// https://url.spec.whatwg.org/#port-state
if (value === "") true;
if (value === "") return true;
const port = Number(value);
return Number.isInteger(port) && port >= 0 && port <= MAX_PORT;
}
@ -409,7 +410,7 @@ export class URLImpl implements URL {
let baseParts: URLParts | undefined;
if (base) {
baseParts = typeof base === "string" ? parse(base) : parts.get(base);
if (baseParts == undefined) {
if (baseParts === undefined) {
throw new TypeError("Invalid base URL.");
}
}

View file

@ -6,7 +6,7 @@ import { isIterable, requiredArguments } from "./util.ts";
export const urls = new WeakMap<URLSearchParams, URL | null>();
export class URLSearchParamsImpl implements URLSearchParams {
#params: Array<[string, string]> = [];
readonly #params: Array<[string, string]> = [];
constructor(init: string | string[][] | Record<string, string> = "") {
if (typeof init === "string") {

View file

@ -81,7 +81,7 @@ export interface WorkerOptions {
export class WorkerImpl extends EventTarget implements Worker {
readonly #id: number;
#name: string;
readonly #name: string;
#terminated = false;
public onerror?: (e: ErrorEvent) => void;

View file

@ -1,4 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { stat, statSync } from "./ops/fs/stat.ts";
import { open, openSync } from "./files.ts";
import { chmod, chmodSync } from "./ops/fs/chmod.ts";

View file

@ -1,10 +1,12 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { open, openSync } from "./files.ts";
import { writeAll, writeAllSync } from "./buffer.ts";
export function writeTextFileSync(path: string | URL, data: string): void {
const file = openSync(path, { write: true, create: true, truncate: true });
const enc = new TextEncoder();
const contents = enc.encode(data);
const encoder = new TextEncoder();
const contents = encoder.encode(data);
writeAllSync(file, contents);
file.close();
}
@ -14,8 +16,8 @@ export async function writeTextFile(
data: string
): Promise<void> {
const file = await open(path, { write: true, create: true, truncate: true });
const enc = new TextEncoder();
const contents = enc.encode(data);
const encoder = new TextEncoder();
const contents = encoder.encode(data);
await writeAll(file, contents);
file.close();
}