1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-25 15:29:32 -05:00

reorg: move JS ops implementations to cli/js/ops/, part 3 (#4302)

Following JS ops were moved to separate files in cli/js/ops directory:
- net
- tls
- fs
This commit is contained in:
Bartek Iwańczuk 2020-03-10 00:22:15 +01:00 committed by GitHub
parent 2115b38fef
commit b7eb241c35
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
30 changed files with 369 additions and 193 deletions

View file

@ -2,7 +2,7 @@
import { ASSETS, MediaType, SourceFile } from "./compiler_sourcefile.ts"; import { ASSETS, MediaType, SourceFile } from "./compiler_sourcefile.ts";
import { OUT_DIR, WriteFileCallback, getAsset } from "./compiler_util.ts"; import { OUT_DIR, WriteFileCallback, getAsset } from "./compiler_util.ts";
import { cwd } from "./dir.ts"; import { cwd } from "./ops/fs/dir.ts";
import { assert, notImplemented } from "./util.ts"; import { assert, notImplemented } from "./util.ts";
import * as util from "./util.ts"; import * as util from "./util.ts";

View file

@ -6,7 +6,7 @@ import {
SourceFileJson SourceFileJson
} from "./compiler_sourcefile.ts"; } from "./compiler_sourcefile.ts";
import { normalizeString, CHAR_FORWARD_SLASH } from "./compiler_util.ts"; import { normalizeString, CHAR_FORWARD_SLASH } from "./compiler_util.ts";
import { cwd } from "./dir.ts"; import { cwd } from "./ops/fs/dir.ts";
import { assert } from "./util.ts"; import { assert } from "./util.ts";
import * as util from "./util.ts"; import * as util from "./util.ts";
import * as compilerOps from "./ops/compiler.ts"; import * as compilerOps from "./ops/compiler.ts";

View file

@ -9,18 +9,18 @@ export {
writeAllSync writeAllSync
} from "./buffer.ts"; } from "./buffer.ts";
export { build, OperatingSystem, Arch } from "./build.ts"; export { build, OperatingSystem, Arch } from "./build.ts";
export { chmodSync, chmod } from "./chmod.ts"; export { chmodSync, chmod } from "./ops/fs/chmod.ts";
export { chownSync, chown } from "./chown.ts"; export { chownSync, chown } from "./ops/fs/chown.ts";
export { transpileOnly, compile, bundle } from "./compiler_api.ts"; export { transpileOnly, compile, bundle } from "./compiler_api.ts";
export { inspect } from "./console.ts"; export { inspect } from "./console.ts";
export { copyFileSync, copyFile } from "./copy_file.ts"; export { copyFileSync, copyFile } from "./ops/fs/copy_file.ts";
export { export {
Diagnostic, Diagnostic,
DiagnosticCategory, DiagnosticCategory,
DiagnosticItem, DiagnosticItem,
DiagnosticMessageChain DiagnosticMessageChain
} from "./diagnostics.ts"; } from "./diagnostics.ts";
export { chdir, cwd } from "./dir.ts"; export { chdir, cwd } from "./ops/fs/dir.ts";
export { applySourceMap, formatDiagnostics } from "./ops/errors.ts"; export { applySourceMap, formatDiagnostics } from "./ops/errors.ts";
export { errors } from "./errors.ts"; export { errors } from "./errors.ts";
export { FileInfo } from "./file_info.ts"; export { FileInfo } from "./file_info.ts";
@ -59,16 +59,16 @@ export {
ReadWriteCloser, ReadWriteCloser,
ReadWriteSeeker ReadWriteSeeker
} from "./io.ts"; } from "./io.ts";
export { linkSync, link } from "./link.ts"; export { linkSync, link } from "./ops/fs/link.ts";
export { export {
makeTempDirSync, makeTempDirSync,
makeTempDir, makeTempDir,
makeTempFileSync, makeTempFileSync,
makeTempFile, makeTempFile,
MakeTempOptions MakeTempOptions
} from "./make_temp.ts"; } from "./ops/fs/make_temp.ts";
export { metrics, Metrics } from "./ops/runtime.ts"; export { metrics, Metrics } from "./ops/runtime.ts";
export { mkdirSync, mkdir, MkdirOptions } from "./mkdir.ts"; export { mkdirSync, mkdir, MkdirOptions } from "./ops/fs/mkdir.ts";
export { export {
Addr, Addr,
connect, connect,
@ -100,20 +100,20 @@ export {
export { openPlugin } from "./plugins.ts"; export { openPlugin } from "./plugins.ts";
export { kill } from "./ops/process.ts"; export { kill } from "./ops/process.ts";
export { run, RunOptions, Process, ProcessStatus, Signal } from "./process.ts"; export { run, RunOptions, Process, ProcessStatus, Signal } from "./process.ts";
export { readdirSync, readdir } from "./read_dir.ts"; export { readdirSync, readdir } from "./ops/fs/read_dir.ts";
export { readFileSync, readFile } from "./read_file.ts"; export { readFileSync, readFile } from "./read_file.ts";
export { readlinkSync, readlink } from "./read_link.ts"; export { readlinkSync, readlink } from "./ops/fs/read_link.ts";
export { realpathSync, realpath } from "./realpath.ts"; export { realpathSync, realpath } from "./ops/fs/realpath.ts";
export { removeSync, remove, RemoveOptions } from "./remove.ts"; export { removeSync, remove, RemoveOptions } from "./ops/fs/remove.ts";
export { renameSync, rename } from "./rename.ts"; export { renameSync, rename } from "./ops/fs/rename.ts";
export { resources, close } from "./ops/resources.ts"; export { resources, close } from "./ops/resources.ts";
export { signal, signals, SignalStream } from "./signals.ts"; export { signal, signals, SignalStream } from "./signals.ts";
export { statSync, lstatSync, stat, lstat } from "./stat.ts"; export { statSync, lstatSync, stat, lstat } from "./ops/fs/stat.ts";
export { symlinkSync, symlink } from "./symlink.ts"; export { symlinkSync, symlink } from "./ops/fs/symlink.ts";
export { connectTLS, listenTLS } from "./tls.ts"; export { connectTLS, listenTLS } from "./tls.ts";
export { truncateSync, truncate } from "./truncate.ts"; export { truncateSync, truncate } from "./ops/fs/truncate.ts";
export { isatty, setRaw } from "./ops/tty.ts"; export { isatty, setRaw } from "./ops/tty.ts";
export { utimeSync, utime } from "./utime.ts"; export { utimeSync, utime } from "./ops/fs/utime.ts";
export { version } from "./version.ts"; export { version } from "./version.ts";
export { writeFileSync, writeFile, WriteFileOptions } from "./write_file.ts"; export { writeFileSync, writeFile, WriteFileOptions } from "./write_file.ts";
export const args: string[] = []; export const args: string[] = [];

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { StatResponse } from "./stat.ts"; import { StatResponse } from "./ops/fs/stat.ts";
import { build } from "./build.ts"; import { build } from "./build.ts";
/** A FileInfo describes a file and is returned by `stat`, `lstat`, /** A FileInfo describes a file and is returned by `stat`, `lstat`,

View file

@ -10,12 +10,17 @@ import {
SyncWriter, SyncWriter,
SyncSeeker SyncSeeker
} from "./io.ts"; } from "./io.ts";
import {
sendSync as sendSyncJson,
sendAsync as sendAsyncJson
} from "./ops/dispatch_json.ts";
import { close } from "./ops/resources.ts"; import { close } from "./ops/resources.ts";
import { read, readSync, write, writeSync } from "./ops/io.ts"; import { read, readSync, write, writeSync } from "./ops/io.ts";
import { seek, seekSync } from "./ops/fs/seek.ts";
export { seek, seekSync } from "./ops/fs/seek.ts";
import {
open as opOpen,
openSync as opOpenSync,
OpenOptions,
OpenMode
} from "./ops/fs/open.ts";
export { OpenOptions, OpenMode } from "./ops/fs/open.ts";
/** Synchronously open a file and return an instance of the `File` object. /** Synchronously open a file and return an instance of the `File` object.
* *
@ -24,31 +29,22 @@ import { read, readSync, write, writeSync } from "./ops/io.ts";
* Requires `allow-read` and `allow-write` permissions depending on mode. * Requires `allow-read` and `allow-write` permissions depending on mode.
*/ */
export function openSync(path: string, mode?: OpenOptions): File; export function openSync(path: string, mode?: OpenOptions): File;
/** Synchronously open a file and return an instance of the `File` object.
*
* const file = Deno.openSync("/foo/bar.txt", "r");
*
* Requires `allow-read` and `allow-write` permissions depending on mode.
*/
export function openSync(path: string, mode?: OpenMode): File; export function openSync(path: string, mode?: OpenMode): File;
/**@internal*/
export function openSync( export function openSync(
path: string, path: string,
modeOrOptions: OpenOptions | OpenMode = "r" modeOrOptions: OpenOptions | OpenMode = "r"
): File { ): File {
let mode = null; let mode = undefined;
let options = null; let options = undefined;
if (typeof modeOrOptions === "string") { if (typeof modeOrOptions === "string") {
mode = modeOrOptions; mode = modeOrOptions;
} else { } else {
checkOpenOptions(modeOrOptions); checkOpenOptions(modeOrOptions);
options = modeOrOptions; options = modeOrOptions as OpenOptions;
} }
const rid = sendSyncJson("op_open", { path, options, mode }); const rid = opOpenSync(path, mode as OpenMode, options);
return new File(rid); return new File(rid);
} }
@ -59,35 +55,22 @@ export function openSync(
* Requires `allow-read` and `allow-write` permissions depending on mode. * Requires `allow-read` and `allow-write` permissions depending on mode.
*/ */
export async function open(path: string, options?: OpenOptions): Promise<File>; export async function open(path: string, options?: OpenOptions): Promise<File>;
/** Open a file and resolves to an instance of `Deno.File`.
*
* const file = await Deno.open("/foo/bar.txt, "w+");
*
* Requires `allow-read` and `allow-write` permissions depending on mode.
*/
export async function open(path: string, mode?: OpenMode): Promise<File>; export async function open(path: string, mode?: OpenMode): Promise<File>;
/**@internal*/
export async function open( export async function open(
path: string, path: string,
modeOrOptions: OpenOptions | OpenMode = "r" modeOrOptions: OpenOptions | OpenMode = "r"
): Promise<File> { ): Promise<File> {
let mode = null; let mode = undefined;
let options = null; let options = undefined;
if (typeof modeOrOptions === "string") { if (typeof modeOrOptions === "string") {
mode = modeOrOptions; mode = modeOrOptions;
} else { } else {
checkOpenOptions(modeOrOptions); checkOpenOptions(modeOrOptions);
options = modeOrOptions; options = modeOrOptions as OpenOptions;
} }
const rid = await sendAsyncJson("op_open", { const rid = await opOpen(path, mode as OpenMode, options);
path,
options,
mode
});
return new File(rid); return new File(rid);
} }
@ -113,36 +96,6 @@ export function create(path: string): Promise<File> {
return open(path, "w+"); return open(path, "w+");
} }
/** Synchronously seek a file ID to the given offset under mode given by `whence`.
*
* Returns the number of cursor position.
*
* const file = Deno.openSync("/foo/bar.txt");
* const position = Deno.seekSync(file.rid, 0, 0);
*/
export function seekSync(
rid: number,
offset: number,
whence: SeekMode
): number {
return sendSyncJson("op_seek", { rid, offset, whence });
}
/** Seek a file ID to the given offset under mode given by `whence`.
*
* Resolves with the number of cursor position.
*
* const file = await Deno.open("/foo/bar.txt");
* const position = await Deno.seek(file.rid, 0, 0);
*/
export async function seek(
rid: number,
offset: number,
whence: SeekMode
): Promise<number> {
return await sendAsyncJson("op_seek", { rid, offset, whence });
}
/** The Deno abstraction for reading and writing files. */ /** The Deno abstraction for reading and writing files. */
export class File export class File
implements implements
@ -191,51 +144,6 @@ export const stdout = new File(1);
/** An instance of `Deno.File` for `stderr`. */ /** An instance of `Deno.File` for `stderr`. */
export const stderr = new File(2); export const stderr = new File(2);
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`
* length 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;
}
/** A set of string literals which specify the open mode of a file.
*
* |Value |Description |
* |------|--------------------------------------------------------------------------------------------------|
* |`"r"` |Read-only. Default. Starts at beginning of file. |
* |`"r+"`|Read-write. Start at beginning of file. |
* |`"w"` |Write-only. Opens and truncates existing file or creates new one for writing only. |
* |`"w+"`|Read-write. Opens and truncates existing file or creates new one for writing and reading. |
* |`"a"` |Write-only. Opens existing file or creates new one. Each write appends content to the end of file.|
* |`"a+"`|Read-write. Behaves like `"a"` and allows to read from file. |
* |`"x"` |Write-only. Exclusive create - creates new file only if one doesn't exist already. |
* |`"x+"`|Read-write. Behaves like `x` and allows reading from file. |
*/
export type OpenMode = "r" | "r+" | "w" | "w+" | "a" | "a+" | "x" | "x+";
/** Check if OpenOptions is set to valid combination of options. /** Check if OpenOptions is set to valid combination of options.
* @returns Tuple representing if openMode is valid and error message if it's not * @returns Tuple representing if openMode is valid and error message if it's not
* @internal * @internal

View file

@ -2,11 +2,9 @@
import { EOF, Reader, Writer, Closer } from "./io.ts"; import { EOF, Reader, Writer, Closer } from "./io.ts";
import { read, write } from "./ops/io.ts"; import { read, write } from "./ops/io.ts";
import { close } from "./ops/resources.ts"; import { close } from "./ops/resources.ts";
import { sendSync, sendAsync } from "./ops/dispatch_json.ts"; import * as netOps from "./ops/net.ts";
import { Transport } from "./ops/net.ts";
export type Transport = "tcp" | "udp"; export { ShutdownMode, shutdown, Transport } from "./ops/net.ts";
// TODO support other types:
// export type Transport = "tcp" | "tcp4" | "tcp6" | "unix" | "unixpacket";
export interface Addr { export interface Addr {
transport: Transport; transport: Transport;
@ -55,26 +53,6 @@ export interface Listener extends AsyncIterator<Conn> {
[Symbol.asyncIterator](): AsyncIterator<Conn>; [Symbol.asyncIterator](): AsyncIterator<Conn>;
} }
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,
ReadWrite // unused
}
/** Shut down socket send and receive operations.
*
* Matches behavior of POSIX shutdown(3).
*
* const listener = Deno.listen({ port: 80 });
* const conn = await listener.accept();
* Deno.shutdown(conn.rid, Deno.ShutdownMode.Write);
*/
export function shutdown(rid: number, how: ShutdownMode): void {
sendSync("op_shutdown", { rid, how });
}
export class ConnImpl implements Conn { export class ConnImpl implements Conn {
constructor( constructor(
readonly rid: number, readonly rid: number,
@ -98,14 +76,14 @@ export class ConnImpl implements Conn {
* Most callers should just use close(). * Most callers should just use close().
*/ */
closeRead(): void { closeRead(): void {
shutdown(this.rid, ShutdownMode.Read); netOps.shutdown(this.rid, netOps.ShutdownMode.Read);
} }
/** closeWrite shuts down (shutdown(2)) the writing side of the TCP /** closeWrite shuts down (shutdown(2)) the writing side of the TCP
* connection. Most callers should just use close(). * connection. Most callers should just use close().
*/ */
closeWrite(): void { closeWrite(): void {
shutdown(this.rid, ShutdownMode.Write); netOps.shutdown(this.rid, netOps.ShutdownMode.Write);
} }
} }
@ -117,7 +95,7 @@ export class ListenerImpl implements Listener {
) {} ) {}
async accept(): Promise<Conn> { async accept(): Promise<Conn> {
const res = await sendAsync("op_accept", { rid: this.rid }); const res = await netOps.accept(this.rid);
return new ConnImpl(res.rid, res.remoteAddr, res.localAddr); return new ConnImpl(res.rid, res.remoteAddr, res.localAddr);
} }
@ -152,7 +130,7 @@ export async function recvfrom(
rid: number, rid: number,
p: Uint8Array p: Uint8Array
): Promise<[number, Addr]> { ): Promise<[number, Addr]> {
const { size, remoteAddr } = await sendAsync("op_receive", { rid }, p); const { size, remoteAddr } = await netOps.receive(rid, p);
return [size, remoteAddr]; return [size, remoteAddr];
} }
@ -175,7 +153,7 @@ export class UDPConnImpl implements UDPConn {
const remote = { hostname: "127.0.0.1", transport: "udp", ...addr }; const remote = { hostname: "127.0.0.1", transport: "udp", ...addr };
if (remote.transport !== "udp") throw Error("Remote transport must be UDP"); if (remote.transport !== "udp") throw Error("Remote transport must be UDP");
const args = { ...remote, rid: this.rid }; const args = { ...remote, rid: this.rid };
await sendAsync("op_send", args, p); await netOps.send(args as netOps.SendRequest, p);
} }
close(): void { close(): void {
@ -253,7 +231,7 @@ export function listen(
export function listen(options: ListenOptions & { transport: "udp" }): UDPConn; export function listen(options: ListenOptions & { transport: "udp" }): UDPConn;
export function listen(options: ListenOptions): Listener | UDPConn { export function listen(options: ListenOptions): Listener | UDPConn {
const args = { ...listenDefaults, ...options }; const args = { ...listenDefaults, ...options };
const res = sendSync("op_listen", args); const res = netOps.listen(args as netOps.ListenRequest);
if (args.transport === "tcp") { if (args.transport === "tcp") {
return new ListenerImpl(res.rid, res.localAddr); return new ListenerImpl(res.rid, res.localAddr);
@ -289,6 +267,6 @@ const connectDefaults = { hostname: "127.0.0.1", transport: "tcp" };
*/ */
export async function connect(options: ConnectOptions): Promise<Conn> { export async function connect(options: ConnectOptions): Promise<Conn> {
options = Object.assign(connectDefaults, options); options = Object.assign(connectDefaults, options);
const res = await sendAsync("op_connect", options); const res = await netOps.connect(options as netOps.ConnectRequest);
return new ConnImpl(res.rid, res.remoteAddr!, res.localAddr!); return new ConnImpl(res.rid, res.remoteAddr!, res.localAddr!);
} }

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./ops/dispatch_json.ts"; import { sendSync, sendAsync } from "../dispatch_json.ts";
/** Synchronously changes the permission of a specific file/directory of /** Synchronously changes the permission of a specific file/directory of
* specified path. Ignores the process's umask. * specified path. Ignores the process's umask.

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./ops/dispatch_json.ts"; import { sendSync, sendAsync } from "../dispatch_json.ts";
/** Synchronously change owner of a regular file or directory. Linux/Mac OS /** Synchronously change owner of a regular file or directory. Linux/Mac OS
* only at the moment. * only at the moment.

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./ops/dispatch_json.ts"; import { sendSync, sendAsync } from "../dispatch_json.ts";
/** Synchronously copies the contents and permissions of one file to another /** Synchronously copies the contents and permissions of one file to another
* specified path, by default creating a new file if needed, else overwriting. * specified path, by default creating a new file if needed, else overwriting.

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync } from "./ops/dispatch_json.ts"; import { sendSync } from "../dispatch_json.ts";
/** /**
* **UNSTABLE**: maybe needs permissions. * **UNSTABLE**: maybe needs permissions.

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./ops/dispatch_json.ts"; import { sendSync, sendAsync } from "../dispatch_json.ts";
/** Creates `newname` as a hard link to `oldname`. /** Creates `newname` as a hard link to `oldname`.
* *

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./ops/dispatch_json.ts"; import { sendSync, sendAsync } from "../dispatch_json.ts";
export interface MakeTempOptions { export interface MakeTempOptions {
/** Directory where the temporary directory should be created (defaults to /** Directory where the temporary directory should be created (defaults to

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./ops/dispatch_json.ts"; import { sendSync, sendAsync } from "../dispatch_json.ts";
// TODO(ry) The complexity in argument parsing is to support deprecated forms of // TODO(ry) The complexity in argument parsing is to support deprecated forms of
// mkdir and mkdirSync. // mkdir and mkdirSync.

67
cli/js/ops/fs/open.ts Normal file
View file

@ -0,0 +1,67 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "../dispatch_json.ts";
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`
* length 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;
}
/** A set of string literals which specify the open mode of a file.
*
* |Value |Description |
* |------|--------------------------------------------------------------------------------------------------|
* |`"r"` |Read-only. Default. Starts at beginning of file. |
* |`"r+"`|Read-write. Start at beginning of file. |
* |`"w"` |Write-only. Opens and truncates existing file or creates new one for writing only. |
* |`"w+"`|Read-write. Opens and truncates existing file or creates new one for writing and reading. |
* |`"a"` |Write-only. Opens existing file or creates new one. Each write appends content to the end of file.|
* |`"a+"`|Read-write. Behaves like `"a"` and allows to read from file. |
* |`"x"` |Write-only. Exclusive create - creates new file only if one doesn't exist already. |
* |`"x+"`|Read-write. Behaves like `x` and allows reading from file. |
*/
export type OpenMode = "r" | "r+" | "w" | "w+" | "a" | "a+" | "x" | "x+";
export function openSync(
path: string,
mode: OpenMode | undefined,
options: OpenOptions | undefined
): number {
return sendSync("op_open", { path, options, mode });
}
export async function open(
path: string,
mode: OpenMode | undefined,
options: OpenOptions | undefined
): Promise<number> {
return await sendAsync("op_open", {
path,
options,
mode
});
}

View file

@ -1,6 +1,6 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./ops/dispatch_json.ts"; import { sendSync, sendAsync } from "../dispatch_json.ts";
import { FileInfo, FileInfoImpl } from "./file_info.ts"; import { FileInfo, FileInfoImpl } from "../../file_info.ts";
import { StatResponse } from "./stat.ts"; import { StatResponse } from "./stat.ts";
interface ReadDirResponse { interface ReadDirResponse {

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./ops/dispatch_json.ts"; import { sendSync, sendAsync } from "../dispatch_json.ts";
/** Returns the destination of the named symbolic link. /** Returns the destination of the named symbolic link.
* *

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./ops/dispatch_json.ts"; import { sendSync, sendAsync } from "../dispatch_json.ts";
/** Returns absolute normalized path with symbolic links resolved synchronously. /** Returns absolute normalized path with symbolic links resolved synchronously.
* *

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./ops/dispatch_json.ts"; import { sendSync, sendAsync } from "../dispatch_json.ts";
export interface RemoveOptions { export interface RemoveOptions {
/** Defaults to `false`. If set to `true`, path will be removed even if /** Defaults to `false`. If set to `true`, path will be removed even if

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./ops/dispatch_json.ts"; import { sendSync, sendAsync } from "../dispatch_json.ts";
/** Synchronously renames (moves) `oldpath` to `newpath`. If `newpath` already /** Synchronously renames (moves) `oldpath` to `newpath`. If `newpath` already
* exists and is not a directory, `renameSync()` replaces it. OS-specific * exists and is not a directory, `renameSync()` replaces it. OS-specific

33
cli/js/ops/fs/seek.ts Normal file
View file

@ -0,0 +1,33 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "../dispatch_json.ts";
import { SeekMode } from "../../io.ts";
/** Synchronously seek a file ID to the given offset under mode given by `whence`.
*
* Returns the number of cursor position.
*
* const file = Deno.openSync("/foo/bar.txt");
* const position = Deno.seekSync(file.rid, 0, 0);
*/
export function seekSync(
rid: number,
offset: number,
whence: SeekMode
): number {
return sendSync("op_seek", { rid, offset, whence });
}
/** Seek a file ID to the given offset under mode given by `whence`.
*
* Resolves with the number of cursor position.
*
* const file = await Deno.open("/foo/bar.txt");
* const position = await Deno.seek(file.rid, 0, 0);
*/
export async function seek(
rid: number,
offset: number,
whence: SeekMode
): Promise<number> {
return await sendAsync("op_seek", { rid, offset, whence });
}

View file

@ -1,6 +1,6 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./ops/dispatch_json.ts"; import { sendSync, sendAsync } from "../dispatch_json.ts";
import { FileInfo, FileInfoImpl } from "./file_info.ts"; import { FileInfo, FileInfoImpl } from "../../file_info.ts";
/** @internal */ /** @internal */
export interface StatResponse { export interface StatResponse {

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./ops/dispatch_json.ts"; import { sendSync, sendAsync } from "../dispatch_json.ts";
import * as util from "./util.ts"; import * as util from "../../util.ts";
import { build } from "./build.ts"; import { build } from "../../build.ts";
/** **UNSTABLE**: `type` argument type may be changed to `"dir" | "file"`. /** **UNSTABLE**: `type` argument type may be changed to `"dir" | "file"`.
* *

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./ops/dispatch_json.ts"; import { sendSync, sendAsync } from "../dispatch_json.ts";
function coerceLen(len?: number): number { function coerceLen(len?: number): number {
if (!len) { if (!len) {

View file

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

117
cli/js/ops/net.ts Normal file
View file

@ -0,0 +1,117 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./dispatch_json.ts";
export type Transport = "tcp" | "udp";
// TODO support other types:
// export type Transport = "tcp" | "tcp4" | "tcp6" | "unix" | "unixpacket";
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,
ReadWrite // unused
}
/** Shut down socket send and receive operations.
*
* Matches behavior of POSIX shutdown(3).
*
* const listener = Deno.listen({ port: 80 });
* const conn = await listener.accept();
* Deno.shutdown(conn.rid, Deno.ShutdownMode.Write);
*/
export function shutdown(rid: number, how: ShutdownMode): void {
sendSync("op_shutdown", { rid, how });
}
interface AcceptResponse {
rid: number;
localAddr: {
hostname: string;
port: number;
transport: Transport;
};
remoteAddr: {
hostname: string;
port: number;
transport: Transport;
};
}
export async function accept(rid: number): Promise<AcceptResponse> {
return await sendAsync("op_accept", { rid });
}
export interface ListenRequest {
transport: Transport;
hostname: string;
port: number;
}
interface ListenResponse {
rid: number;
localAddr: {
hostname: string;
port: number;
transport: Transport;
};
}
export function listen(args: ListenRequest): ListenResponse {
return sendSync("op_listen", args);
}
interface ConnectResponse {
rid: number;
localAddr: {
hostname: string;
port: number;
transport: Transport;
};
remoteAddr: {
hostname: string;
port: number;
transport: Transport;
};
}
export interface ConnectRequest {
transport: Transport;
hostname: string;
port: number;
}
export async function connect(args: ConnectRequest): Promise<ConnectResponse> {
return await sendAsync("op_connect", args);
}
interface ReceiveResponse {
size: number;
remoteAddr: {
hostname: string;
port: number;
transport: Transport;
};
}
export async function receive(
rid: number,
zeroCopy: Uint8Array
): Promise<ReceiveResponse> {
return await sendAsync("op_receive", { rid }, zeroCopy);
}
export interface SendRequest {
rid: number;
hostname: string;
port: number;
transport: Transport;
}
export async function send(
args: SendRequest,
zeroCopy: Uint8Array
): Promise<void> {
await sendAsync("op_send", args, zeroCopy);
}

View file

@ -8,3 +8,12 @@ export function stopGlobalTimer(): void {
export async function startGlobalTimer(timeout: number): Promise<void> { export async function startGlobalTimer(timeout: number): Promise<void> {
await sendAsync("op_global_timer", { timeout }); await sendAsync("op_global_timer", { timeout });
} }
interface NowResponse {
seconds: number;
subsecNanos: number;
}
export function now(): NowResponse {
return sendSync("op_now");
}

69
cli/js/ops/tls.ts Normal file
View file

@ -0,0 +1,69 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendAsync, sendSync } from "./dispatch_json.ts";
import { Transport } from "./net.ts";
export interface ConnectTLSRequest {
transport: Transport;
hostname: string;
port: number;
cert_file?: string;
}
interface ConnectTLSResponse {
rid: number;
localAddr: {
hostname: string;
port: number;
transport: Transport;
};
remoteAddr: {
hostname: string;
port: number;
transport: Transport;
};
}
export async function connectTLS(
args: ConnectTLSRequest
): Promise<ConnectTLSResponse> {
return await sendAsync("op_connect_tls", args);
}
interface AcceptTLSResponse {
rid: number;
localAddr: {
hostname: string;
port: number;
transport: Transport;
};
remoteAddr: {
hostname: string;
port: number;
transport: Transport;
};
}
export async function acceptTLS(rid: number): Promise<AcceptTLSResponse> {
return await sendAsync("op_accept_tls", { rid });
}
export interface ListenTLSRequest {
port: number;
hostname: string;
transport: Transport;
certFile: string;
keyFile: string;
}
interface ListenTLSResponse {
rid: number;
localAddr: {
hostname: string;
port: number;
transport: Transport;
};
}
export function listenTLS(args: ListenTLSRequest): ListenTLSResponse {
return sendSync("op_listen_tls", args);
}

View file

@ -1,10 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendSync } from "./ops/dispatch_json.ts"; import { now as opNow } from "./ops/timers.ts";
interface NowResponse {
seconds: number;
subsecNanos: number;
}
export class Performance { export class Performance {
/** Returns a current time from Deno's start in milliseconds. /** Returns a current time from Deno's start in milliseconds.
@ -15,7 +10,7 @@ export class Performance {
* console.log(`${t} ms since start!`); * console.log(`${t} ms since start!`);
*/ */
now(): number { now(): number {
const res = sendSync("op_now") as NowResponse; const res = opNow();
return res.seconds * 1e3 + res.subsecNanos / 1e6; return res.seconds * 1e3 + res.subsecNanos / 1e6;
} }
} }

View file

@ -1,5 +1,5 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { sendAsync, sendSync } from "./ops/dispatch_json.ts"; import * as tlsOps from "./ops/tls.ts";
import { Listener, Transport, Conn, ConnImpl, ListenerImpl } from "./net.ts"; import { Listener, Transport, Conn, ConnImpl, ListenerImpl } from "./net.ts";
// TODO(ry) There are many configuration options to add... // TODO(ry) There are many configuration options to add...
@ -17,13 +17,13 @@ const connectTLSDefaults = { hostname: "127.0.0.1", transport: "tcp" };
*/ */
export async function connectTLS(options: ConnectTLSOptions): Promise<Conn> { export async function connectTLS(options: ConnectTLSOptions): Promise<Conn> {
options = Object.assign(connectTLSDefaults, options); options = Object.assign(connectTLSDefaults, options);
const res = await sendAsync("op_connect_tls", options); const res = await tlsOps.connectTLS(options as tlsOps.ConnectTLSRequest);
return new ConnImpl(res.rid, res.remoteAddr!, res.localAddr!); return new ConnImpl(res.rid, res.remoteAddr!, res.localAddr!);
} }
class TLSListenerImpl extends ListenerImpl { class TLSListenerImpl extends ListenerImpl {
async accept(): Promise<Conn> { async accept(): Promise<Conn> {
const res = await sendAsync("op_accept_tls", { rid: this.rid }); const res = await tlsOps.acceptTLS(this.rid);
return new ConnImpl(res.rid, res.remoteAddr, res.localAddr); return new ConnImpl(res.rid, res.remoteAddr, res.localAddr);
} }
} }
@ -52,7 +52,7 @@ export interface ListenTLSOptions {
export function listenTLS(options: ListenTLSOptions): Listener { export function listenTLS(options: ListenTLSOptions): Listener {
const hostname = options.hostname || "0.0.0.0"; const hostname = options.hostname || "0.0.0.0";
const transport = options.transport || "tcp"; const transport = options.transport || "tcp";
const res = sendSync("op_listen_tls", { const res = tlsOps.listenTLS({
hostname, hostname,
port: options.port, port: options.port,
transport, transport,

View file

@ -1,7 +1,7 @@
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. // Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
import { stat, statSync } from "./stat.ts"; import { stat, statSync } from "./ops/fs/stat.ts";
import { open, openSync } from "./files.ts"; import { open, openSync } from "./files.ts";
import { chmod, chmodSync } from "./chmod.ts"; import { chmod, chmodSync } from "./ops/fs/chmod.ts";
import { writeAll, writeAllSync } from "./buffer.ts"; import { writeAll, writeAllSync } from "./buffer.ts";
/** Options for writing to a file. */ /** Options for writing to a file. */