1
import { randomUUID } from "node:crypto";2
import { type PlatformPath, posix, win32 } from "node:path";3
import { StringDecoder } from "node:string_decoder";4
import { fileURLToPath } from "node:url";5
import type { Context } from "@earendil-works/chord";6
import {7
type BinaryReader,8
type DirReader,9
type ExecutionEnv,10
ExecutionError,11
err,12
FileError,13
type FileInfo,14
type FileKind,15
type FileListing,16
type FileWatcher,17
type LineScan,18
type ListFilesOptions,19
ok,20
type Result,21
type ShellExecOptions,22
type ShellExecResult,23
type ShellOutputInfo,24
type ShellOutputSkip,25
StreamDecoder,26
type TextLine,27
type TextLineReader,28
type WatchChange,29
type WatchTarget,30
} from "@earendil-works/pi-durable/env";31
import { type Connection, type Json, nodePlatform, RemoteError, type RemoteInfo } from "./connection.ts";32
import { abortResult, toFileError } from "./errors.ts";33
import { listFilesOver } from "./list-files.ts";34
import { RemoteWatcher, type RemoteWatchOptions } from "./watch.ts";36
const MAX_TIMEOUT_MS = 2_147_483_647;37
const MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;38
/** Bytes per `pread` request of a binary reader; several are in flight at once. */39
const READ_CHUNK = 256 * 1024;40
const READ_DEPTH = 8;41
/** Node's `writeFile` writes at most this much per call and checks for an abort before each. */42
const WRITE_CHUNK = 512 * 1024;43
const WRITE_DEPTH = 8;44
/** Node's `readFile`: chunk of known-size reads, chunk of unknown-size reads, and the largest file it reads. */45
const READ_FILE_CHUNK = 512 * 1024;46
const READ_FILE_UNKNOWN_CHUNK = 64 * 1024;47
const READ_FILE_MAX = 2 ** 31 - 1;48
/** `NodeTextLineReader`'s read size. */49
const LINE_CHUNK = 64 * 1024;51
export interface RemoteExecutionEnvOptions {52
connection: Connection;53
/** The file namespace: equal ids see the same files (`FileSystem.id`), e.g. `pi-env:<env name>`. */54
id: string;55
cwd: string;56
shellPath?: string;57
/** Added to the remote environment of every command that inherits it, like `NodeExecutionEnv`'s `shellEnv`. */58
shellEnv?: Record<string, string>;59
/** How the daemon watches, like `NodeExecutionEnv`'s `watch` option. */60
watch?: RemoteWatchOptions;61
}63
/** An info record from the daemon. */64
type RemoteFileInfo = { name: string; kind: FileKind | "other"; size: number; mtimeSec: number; mtimeNsec: number };65
type RemoteDirEntry = { name: string; raw?: number[]; info?: RemoteFileInfo; error?: Json };67
/** Node's path rules of the remote system. */68
export async function remotePath(connection: Connection): Promise<PlatformPath> {69
return nodePlatform(await connection.info()).platform === "win32" ? win32 : posix;70
}72
function toInfo(path: string, remote: RemoteFileInfo, paths: PlatformPath): Result<FileInfo, FileError> {73
if (remote.kind === "other") return err(new FileError("invalid", "Unsupported file type", path));74
return ok({75
name: paths.basename(path),76
path,77
kind: remote.kind,78
size: remote.size,79
mtimeMs: remote.mtimeSec * 1000 + remote.mtimeNsec / 1e6,80
});81
}83
function concat(chunks: readonly Uint8Array[], total: number): Uint8Array {84
if (chunks.length === 1) return chunks[0]!;85
const bytes = new Uint8Array(total);86
let position = 0;87
for (const chunk of chunks) {88
bytes.set(chunk, position);89
position += chunk.length;90
}91
return bytes;92
}94
/**95
* Read `length` bytes from `offset` as consecutive reads of at most `chunk` bytes, several in flight. Ends early at96
* the end of the file. A short read continues from where it ended, as sequential reads would. `aborted` is checked97
* after each read; `undefined` means aborted.98
*/99
async function readRange(100
read: (offset: number, length: number) => Promise<Uint8Array>,101
offset: number,102
length: number,103
chunk: number,104
aborted: () => boolean,105
): Promise<{ chunks: Uint8Array[]; total: number } | undefined> {106
const chunks: Uint8Array[] = [];107
let total = 0;108
let next = offset;109
const inFlight: { length: number; bytes: Promise<Uint8Array> }[] = [];110
while (total < length) {111
while (inFlight.length < READ_DEPTH && next < offset + length) {112
const size = Math.min(offset + length - next, chunk);113
const bytes = read(next, size);114
bytes.catch(() => {});115
inFlight.push({ length: size, bytes });116
next += size;117
}118
const head = inFlight.shift()!;119
const bytes = await head.bytes;120
if (aborted()) return undefined;121
if (bytes.length === 0) break;122
chunks.push(bytes);123
total += bytes.length;124
if (bytes.length < head.length) {125
// Reads already in flight assumed a full read; continue right after this one.126
inFlight.length = 0;127
next = offset + total;128
}129
}130
return { chunks, total };131
}133
/** A daemon handle: valid only in the session that opened it. */134
class Handle {135
readonly env: RemoteExecutionEnv;136
readonly id: number;137
readonly session: number;138
readonly path: string;140
constructor(env: RemoteExecutionEnv, id: number, session: number, path: string) {141
this.env = env;142
this.id = id;143
this.session = session;144
this.path = path;145
}147
request(op: string, json: Json = {}, options: { signal?: AbortSignal; payload?: Uint8Array } = {}) {148
return this.env.connection.request(op, { ...json, handle: this.id }, { ...options, session: this.session });149
}151
async pread(offset: number | undefined, length: number): Promise<Uint8Array> {152
return (await this.request("pread", { ...(offset === undefined ? {} : { offset }), length })).payload;153
}155
async close(): Promise<void> {156
await this.request("close").catch(() => undefined);157
}158
}160
class RemoteBinaryReader implements BinaryReader {161
readonly #handle: Handle;162
#closed = false;164
constructor(handle: Handle) {165
this.#handle = handle;166
}168
get #path(): string {169
return this.#handle.path;170
}172
#closedResult<T>(): Result<T, FileError> | undefined {173
return this.#closed ? err(new FileError("invalid", "Binary reader is closed", this.#path)) : undefined;174
}176
async info(context: Context): Promise<Result<FileInfo, FileError>> {177
const early = abortResult<FileInfo>(context.abortSignal, this.#path) ?? this.#closedResult<FileInfo>();178
if (early) return early;179
try {180
const { json } = await this.#handle.request("fstat");181
return toInfo(this.#path, json as unknown as RemoteFileInfo, await remotePath(this.#handle.env.connection));182
} catch (error) {183
return err(toFileError(error, this.#path));184
}185
}187
async read(offset: number, length: number, context: Context): Promise<Result<Uint8Array, FileError>> {188
const early = abortResult<Uint8Array>(context.abortSignal, this.#path) ?? this.#closedResult<Uint8Array>();189
if (early) return early;190
if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(length) || length < 0) {191
return err(new FileError("invalid", "Offset and length must be non-negative safe integers", this.#path));192
}193
try {194
const read = await readRange(195
(at, size) => this.#handle.pread(at, size),196
offset,197
length,198
READ_CHUNK,199
() => context.abortSignal?.aborted === true,200
);201
if (read === undefined) return err(new FileError("aborted", "aborted", this.#path));202
return ok(concat(read.chunks, read.total));203
} catch (error) {204
return err(toFileError(error, this.#path));205
}206
}208
async scanLines(209
options: { startLine: number; endLine?: number },210
context: Context,211
): Promise<Result<LineScan, FileError>> {212
const early = abortResult<LineScan>(context.abortSignal, this.#path) ?? this.#closedResult<LineScan>();213
if (early) return early;214
const { startLine, endLine } = options;215
if (216
!Number.isSafeInteger(startLine) ||217
startLine < 0 ||218
(endLine !== undefined && (!Number.isSafeInteger(endLine) || endLine <= startLine))219
) {220
return err(new FileError("invalid", "Invalid line range", this.#path));221
}222
try {223
const { json } = await this.#handle.request(224
"scanLines",225
{ startLine, ...(endLine === undefined ? {} : { endLine }) },226
context.abortSignal ? { signal: context.abortSignal } : {},227
);228
return ok(json as unknown as LineScan);229
} catch (error) {230
return err(toFileError(error, this.#path));231
}232
}234
async close(_context: Context): Promise<void> {235
if (this.#closed) return;236
this.#closed = true;237
await this.#handle.close();238
}239
}241
class RemoteDirReader implements DirReader {242
readonly #handle: Handle;243
#done = false;244
#closed = false;246
constructor(handle: Handle) {247
this.#handle = handle;248
}250
async next(251
maxEntries: number,252
context: Context,253
): Promise<Result<{ entries: FileInfo[]; done: boolean }, FileError>> {254
const path = this.#handle.path;255
const aborted = abortResult<{ entries: FileInfo[]; done: boolean }>(context.abortSignal, path);256
if (aborted) return aborted;257
if (this.#closed) return err(new FileError("invalid", "Directory reader is closed", path));258
if (!Number.isSafeInteger(maxEntries) || maxEntries <= 0) {259
return err(new FileError("invalid", "maxEntries must be a positive safe integer", path));260
}261
const entries: FileInfo[] = [];262
try {263
const paths = await remotePath(this.#handle.env.connection);264
// Like `NodeDirReader`, count only entries that are part of the listing.265
while (!this.#done && entries.length < maxEntries) {266
const { json } = await this.#handle.request("readdir", { max: maxEntries - entries.length });267
const loopAbort = abortResult<{ entries: FileInfo[]; done: boolean }>(context.abortSignal, path);268
if (loopAbort) return loopAbort;269
for (const entry of json.entries as RemoteDirEntry[]) {270
const entryPath = paths.resolve(path, entry.name);271
if (entry.error !== undefined) {272
// Removed between enumeration and lstat: not part of the listing any more.273
if (entry.error.code === "ENOENT") continue;274
return err(toFileError(new RemoteError(entry.error), entryPath));275
}276
const info = toInfo(entryPath, entry.info!, paths);277
if (info.ok) entries.push(info.value);278
}279
this.#done = json.done === true;280
}281
return ok({ entries, done: this.#done });282
} catch (error) {283
return err(toFileError(error, path));284
}285
}287
async close(_context: Context): Promise<void> {288
if (this.#closed) return;289
this.#closed = true;290
await this.#handle.close();291
}292
}294
/** `NodeTextLineReader`: positional reads of a file opened like `open(path, "r")`. */295
class RemoteTextLineReader implements TextLineReader {296
readonly #handle: Handle;297
readonly #decoder = new StreamDecoder();298
#offset = 0;299
#buffered = "";300
#ended = false;301
#closed = false;303
constructor(handle: Handle) {304
this.#handle = handle;305
}307
async readLine(context: Context): Promise<Result<TextLine | undefined, FileError>> {308
const path = this.#handle.path;309
const aborted = abortResult<TextLine | undefined>(context.abortSignal, path);310
if (aborted) return aborted;311
if (this.#closed) return err(new FileError("invalid", "Text line reader is closed", path));312
try {313
while (true) {314
const newline = this.#buffered.indexOf("\n");315
if (newline !== -1) {316
const text = this.#buffered.slice(0, newline);317
this.#buffered = this.#buffered.slice(newline + 1);318
return ok({ text, terminated: true });319
}320
if (this.#ended) {321
if (this.#buffered.length === 0) return ok(undefined);322
const text = this.#buffered;323
this.#buffered = "";324
return ok({ text, terminated: false });325
}326
const bytes = await this.#handle.pread(this.#offset, LINE_CHUNK);327
const afterReadAbort = abortResult<TextLine | undefined>(context.abortSignal, path);328
if (afterReadAbort) return afterReadAbort;329
this.#offset += bytes.length;330
if (bytes.length === 0) {331
this.#buffered += this.#decoder.decode();332
this.#ended = true;333
} else {334
this.#buffered += this.#decoder.decode(bytes);335
}336
}337
} catch (error) {338
return err(toFileError(error, path));339
}340
}342
async close(_context: Context): Promise<void> {343
if (this.#closed) return;344
this.#closed = true;345
this.#buffered = "";346
await this.#handle.close();347
}348
}350
/**351
* An `ExecutionEnv` on another machine, reached through a pi-env daemon. Results match `NodeExecutionEnv` running on352
* that machine: the daemon performs the system calls, and this class applies Node's path, error, and result rules.353
*/354
export class RemoteExecutionEnv implements ExecutionEnv {355
readonly id: string;356
cwd: string;357
readonly connection: Connection;358
readonly #shellPath: string | undefined;359
readonly #shellEnv: Record<string, string> | undefined;360
readonly #watchOptions: RemoteWatchOptions;361
/** Running commands this environment started, for `cleanup()`. */362
readonly #running = new Map<number, number>();364
constructor(options: RemoteExecutionEnvOptions) {365
this.id = options.id;366
this.cwd = options.cwd;367
this.connection = options.connection;368
this.#shellPath = options.shellPath;369
this.#shellEnv = options.shellEnv;370
this.#watchOptions = options.watch ?? {};371
}373
/** Node's `resolvePath` on the remote system, with its home directory and working directories. */374
async #resolve(path: string): Promise<string> {375
const info = await this.connection.info();376
const windows = nodePlatform(info).platform === "win32";377
const paths = windows ? win32 : posix;378
let normalized = path;379
if (normalized === "~") {380
normalized = info.home;381
} else if (normalized.startsWith("~/") || (windows && normalized.startsWith("~\\"))) {382
normalized = paths.join(info.home, normalized.slice(2));383
} else if (normalized.startsWith("file://")) {384
try {385
normalized = fileURLToPath(normalized, { windows });386
} catch {387
// Keep malformed URLs as ordinary paths, as Node does.388
}389
}390
if (paths.isAbsolute(normalized)) return paths.resolve(normalized);391
if (windows) {392
// A drive-relative path on another drive: Node on Windows resolves it against that drive's working directory393
// (`=D:`), else its own working directory if on that drive, else the drive's root.394
const drive = /^([a-zA-Z]:)(?![\\/])/.exec(normalized)?.[1];395
if (drive !== undefined && drive.toLowerCase() !== this.cwd.slice(0, 2).toLowerCase()) {396
let base = info.driveCwds[drive.toUpperCase()] ?? info.cwd;397
if (base.slice(0, 2).toLowerCase() !== drive.toLowerCase() && base[2] === "\\") base = `${drive}\\`;398
return win32.resolve(base, normalized);399
}400
}401
return paths.resolve(this.cwd, normalized);402
}404
async #fileOp<T>(405
path: string,406
context: Context,407
run: (resolved: string) => Promise<T>,408
check: "before" | "both" = "before",409
): Promise<Result<T, FileError>> {410
let resolved: string;411
try {412
resolved = await this.#resolve(path);413
} catch (error) {414
return err(toFileError(error, path));415
}416
const aborted = abortResult<T>(context.abortSignal, resolved);417
if (aborted) return aborted;418
try {419
const value = await run(resolved);420
if (check === "both") {421
const after = abortResult<T>(context.abortSignal, resolved);422
if (after) return after;423
}424
return ok(value);425
} catch (error) {426
return err(toFileError(error, resolved));427
}428
}430
async #open(resolved: string, json: Json): Promise<{ handle: Handle; json: Json }> {431
const reply = await this.connection.request("open", { path: resolved, ...json });432
return { handle: new Handle(this, reply.json.handle as number, reply.session, resolved), json: reply.json };433
}435
async absolutePath(path: string, _context: Context): Promise<Result<string, FileError>> {436
try {437
return ok(await this.#resolve(path));438
} catch (error) {439
return err(toFileError(error, path));440
}441
}443
async joinPath(parts: string[], _context: Context): Promise<Result<string, FileError>> {444
try {445
return ok((await remotePath(this.connection)).join(...parts));446
} catch (error) {447
return err(toFileError(error));448
}449
}451
/** Node's `readFile`, with or without UTF-8 decoding, over a file opened like `open(path, "r")`. */452
async #readFile(path: string, encoding: boolean, context: Context): Promise<Result<Uint8Array | string, FileError>> {453
const signal = context.abortSignal;454
return this.#fileOp(path, context, async (resolved) => {455
const { handle, json } = await this.#open(resolved, { mode: "read" });456
const aborted = () => signal?.aborted === true;457
const abort = () => new FileError("aborted", "The operation was aborted", resolved);458
try {459
if (json.statError !== undefined) throw new RemoteError(json.statError as Json);460
if (aborted()) throw abort();461
const stat = json.stat as RemoteFileInfo;462
const size = stat.kind === "file" ? stat.size : 0;463
if (size > READ_FILE_MAX) {464
throw new FileError("unknown", `File size (${size}) is greater than 2 GiB`, resolved);465
}466
if (size === 0) {467
// Unknown size: sequential reads until the end, as for FIFOs and devices.468
const decoder = new StringDecoder("utf8");469
const chunks: Uint8Array[] = [];470
let total = 0;471
let text = "";472
while (true) {473
if (aborted()) throw abort();474
const bytes = await handle.pread(undefined, READ_FILE_UNKNOWN_CHUNK);475
if (bytes.length === 0) break;476
total += bytes.length;477
chunks.push(bytes);478
if (encoding) text += decoder.write(bytes);479
}480
if (!encoding) return Buffer.concat(chunks, total);481
return total === 0 ? "" : text + decoder.end();482
}483
if (!encoding) {484
// A single read of the whole size, or reads of 512 KiB until the size or the end of the file.485
if (size <= READ_FILE_CHUNK) return Buffer.from(await handle.pread(0, size));486
const read = await readRange(487
(at, length) => handle.pread(at, length),488
0,489
size,490
READ_FILE_CHUNK,491
aborted,492
);493
if (read === undefined) throw abort();494
return Buffer.concat(read.chunks, read.total);495
}496
// Decoding: reads of min(size, 512 KiB) until the size, a short read, or the end of the file.497
const length = Math.min(size, READ_FILE_CHUNK);498
const decoder = new StringDecoder("utf8");499
let text = "";500
let total = 0;501
let first = true;502
const inFlight: Promise<Uint8Array>[] = [];503
let next = 0;504
while (true) {505
while (inFlight.length < READ_DEPTH) {506
const bytes = handle.pread(next, length);507
bytes.catch(() => {});508
inFlight.push(bytes);509
next += length;510
}511
const bytes = await inFlight.shift()!;512
if (aborted()) throw abort();513
total += bytes.length;514
if (bytes.length === 0 || total === size || bytes.length !== length) {515
return first ? Buffer.from(bytes).toString("utf8") : text + decoder.end(Buffer.from(bytes));516
}517
text += decoder.write(Buffer.from(bytes));518
first = false;519
}520
} finally {521
await handle.close();522
}523
});524
}526
async readTextFile(path: string, context: Context): Promise<Result<string, FileError>> {527
return (await this.#readFile(path, true, context)) as Result<string, FileError>;528
}530
async readBinaryFile(path: string, context: Context): Promise<Result<Uint8Array, FileError>> {531
return (await this.#readFile(path, false, context)) as Result<Uint8Array, FileError>;532
}534
async openBinaryReader(535
path: string,536
options: { noFollow?: boolean } | undefined,537
context: Context,538
): Promise<Result<BinaryReader, FileError>> {539
const opened = await this.#fileOp(path, context, async (resolved) => {540
return (await this.#open(resolved, { noFollow: options?.noFollow === true })).handle;541
});542
if (!opened.ok) return opened;543
const aborted = abortResult<BinaryReader>(context.abortSignal, opened.value.path);544
if (aborted) {545
await opened.value.close();546
return aborted;547
}548
return ok(new RemoteBinaryReader(opened.value));549
}551
async openTextLineReader(path: string, context: Context): Promise<Result<TextLineReader, FileError>> {552
const opened = await this.#fileOp(path, context, async (resolved) => {553
return (await this.#open(resolved, { mode: "read" })).handle;554
});555
if (!opened.ok) return opened;556
const aborted = abortResult<TextLineReader>(context.abortSignal, opened.value.path);557
if (aborted) {558
await opened.value.close();559
return aborted;560
}561
return ok(new RemoteTextLineReader(opened.value));562
}564
async readTextLines(565
path: string,566
options: { maxLines?: number } | undefined,567
context: Context,568
): Promise<Result<string[], FileError>> {569
if (options?.maxLines !== undefined && options.maxLines <= 0) return ok([]);570
const opened = await this.openTextLineReader(path, context);571
if (!opened.ok) return opened;572
const lines: string[] = [];573
try {574
while (options?.maxLines === undefined || lines.length < options.maxLines) {575
const line = await opened.value.readLine(context);576
if (!line.ok) return line;577
if (line.value === undefined) break;578
lines.push(line.value.text);579
}580
return ok(lines);581
} finally {582
await opened.value.close(context);583
}584
}586
/**587
* Node's `writeFile` (abort checked before each 512 KiB write) or `appendFile` (no checks, one after): the first588
* request creates parents, opens, and writes the first chunk; later chunks go to the same open file.589
*/590
async #write(path: string, content: string | Uint8Array, append: boolean, context: Context) {591
const bytes = typeof content === "string" ? Buffer.from(content, "utf8") : content;592
const signal = append ? undefined : context.abortSignal;593
return this.#fileOp(594
path,595
context,596
async (resolved) => {597
const first = bytes.subarray(0, WRITE_CHUNK);598
const keep = bytes.length > WRITE_CHUNK;599
const reply = await this.connection.request("write", { path: resolved, append, keep }, { payload: first });600
if (!keep) return;601
const handle = new Handle(this, reply.json.handle as number, reply.session, resolved);602
const inFlight: Promise<unknown>[] = [];603
try {604
for (let offset = WRITE_CHUNK; offset < bytes.length; offset += WRITE_CHUNK) {605
if (signal?.aborted) {606
// A chunk that failed before this check fails the write, as it would have in sequence.607
const failed = (await Promise.allSettled(inFlight)).find((result) => result.status === "rejected");608
if (failed !== undefined) throw failed.reason;609
throw new FileError("aborted", "The operation was aborted", resolved);610
}611
const written = handle.request(612
"writeChunk",613
{},614
{ payload: bytes.subarray(offset, offset + WRITE_CHUNK) },615
);616
written.catch(() => {});617
inFlight.push(written);618
if (inFlight.length >= WRITE_DEPTH) await inFlight.shift();619
}620
// The first failure; later chunks are refused by the daemon, so the file has no gaps.621
for (const written of inFlight) await written;622
} finally {623
await Promise.allSettled(inFlight);624
await handle.close();625
}626
},627
append ? "both" : "before",628
);629
}631
writeFile(path: string, content: string | Uint8Array, context: Context): Promise<Result<void, FileError>> {632
return this.#write(path, content, false, context);633
}635
appendFile(path: string, content: string | Uint8Array, context: Context): Promise<Result<void, FileError>> {636
return this.#write(path, content, true, context);637
}639
async truncateFile(path: string, size: number, context: Context): Promise<Result<void, FileError>> {640
return this.#fileOp(641
path,642
context,643
async (resolved) => {644
if (!Number.isSafeInteger(size) || size < 0) {645
throw new FileError("invalid", "File size must be a non-negative safe integer", resolved);646
}647
await this.connection.request("truncate", { path: resolved, size });648
},649
"both",650
);651
}653
flushFile(path: string, context: Context): Promise<Result<void, FileError>> {654
return this.#fileOp(655
path,656
context,657
async (resolved) => {658
await this.connection.request("fsync", { path: resolved });659
},660
"both",661
);662
}664
async renameFile(sourcePath: string, destinationPath: string, context: Context): Promise<Result<void, FileError>> {665
let source: string;666
let destination: string;667
try {668
source = await this.#resolve(sourcePath);669
destination = await this.#resolve(destinationPath);670
} catch (error) {671
return err(toFileError(error, sourcePath));672
}673
const aborted = abortResult<void>(context.abortSignal, destination);674
if (aborted) return aborted;675
try {676
await this.connection.request("rename", { path: source, to: destination });677
return ok(undefined);678
} catch (error) {679
return err(toFileError(error, source));680
}681
}683
async fileInfo(path: string, context: Context): Promise<Result<FileInfo, FileError>> {684
const result = await this.#fileOp(path, context, async (resolved) => {685
const { json } = await this.connection.request("lstat", { path: resolved });686
return toInfo(resolved, json as unknown as RemoteFileInfo, await remotePath(this.connection));687
});688
return result.ok ? result.value : result;689
}691
listDir(path: string, context: Context): Promise<Result<FileInfo[], FileError>> {692
return this.#fileOp(path, context, async (resolved) => {693
const { handle } = await this.#openDir(resolved);694
const entries: RemoteDirEntry[] = [];695
try {696
for (let done = false; !done; ) {697
const { json } = await handle.request("readdir", { max: 1000 });698
entries.push(...(json.entries as RemoteDirEntry[]));699
done = json.done === true;700
}701
} finally {702
await handle.close();703
}704
// Node's `readdir` fails on any entry it cannot lstat. libuv sorts names by their bytes on POSIX; on Windows it705
// keeps the file system's order, which the daemon reports.706
const paths = await remotePath(this.connection);707
if (paths === posix) {708
const key = (entry: RemoteDirEntry) => Buffer.from(entry.raw ?? Buffer.from(entry.name, "utf8"));709
entries.sort((a, b) => Buffer.compare(key(a), key(b)));710
}711
const infos: FileInfo[] = [];712
for (const entry of entries) {713
if (context.abortSignal?.aborted) throw new FileError("aborted", "aborted", resolved);714
const entryPath = paths.resolve(resolved, entry.name);715
if (entry.error !== undefined) throw toFileError(new RemoteError(entry.error), entryPath);716
const info = toInfo(entryPath, entry.info!, paths);717
if (info.ok) infos.push(info.value);718
}719
return infos;720
});721
}723
/** Through the daemon; `not_supported` with a daemon released before `listFiles`. */724
async listFiles(725
path: string,726
options: ListFilesOptions | undefined,727
context: Context,728
): Promise<Result<FileListing, FileError>> {729
let resolved: string;730
try {731
resolved = await this.#resolve(path);732
} catch (error) {733
return err(toFileError(error, path));734
}735
return listFilesOver(this.connection, resolved, options, context);736
}738
async #openDir(resolved: string): Promise<{ handle: Handle }> {739
const reply = await this.connection.request("opendir", { path: resolved });740
return { handle: new Handle(this, reply.json.handle as number, reply.session, resolved) };741
}743
async openDirReader(path: string, context: Context): Promise<Result<DirReader, FileError>> {744
const opened = await this.#fileOp(path, context, async (resolved) => (await this.#openDir(resolved)).handle);745
if (!opened.ok) return opened;746
const aborted = abortResult<DirReader>(context.abortSignal, opened.value.path);747
if (aborted) {748
await opened.value.close();749
return aborted;750
}751
return ok(new RemoteDirReader(opened.value));752
}754
canonicalPath(path: string, context: Context): Promise<Result<string, FileError>> {755
return this.#fileOp(path, context, async (resolved) => {756
const { json } = await this.connection.request("realpath", { path: resolved });757
return json.path as string;758
});759
}761
async exists(path: string, context: Context): Promise<Result<boolean, FileError>> {762
const result = await this.fileInfo(path, context);763
if (result.ok) return ok(true);764
if (result.error.code === "not_found") return ok(false);765
return err(result.error);766
}768
createDir(769
path: string,770
options: { recursive?: boolean } | undefined,771
context: Context,772
): Promise<Result<void, FileError>> {773
return this.#fileOp(path, context, async (resolved) => {774
await this.connection.request("mkdir", { path: resolved, recursive: options?.recursive ?? true });775
});776
}778
remove(779
path: string,780
options: { recursive?: boolean; force?: boolean } | undefined,781
context: Context,782
): Promise<Result<void, FileError>> {783
return this.#fileOp(path, context, async (resolved) => {784
await this.connection.request("rm", {785
path: resolved,786
recursive: options?.recursive ?? false,787
force: options?.force ?? false,788
});789
});790
}792
async createTempDir(prefix: string | undefined, context: Context): Promise<Result<string, FileError>> {793
const aborted = abortResult<string>(context.abortSignal);794
if (aborted) return aborted;795
try {796
const { tmpdir } = await this.connection.info();797
const paths = await remotePath(this.connection);798
const { json } = await this.connection.request("mkdtemp", { path: paths.join(tmpdir, prefix ?? "tmp-") });799
return ok(json.path as string);800
} catch (error) {801
return err(toFileError(error));802
}803
}805
async createTempFile(806
options: { prefix?: string; suffix?: string } | undefined,807
context: Context,808
): Promise<Result<string, FileError>> {809
const dir = await this.createTempDir("tmp-", context);810
if (!dir.ok) return dir;811
let filePath = "";812
try {813
const paths = await remotePath(this.connection);814
filePath = paths.join(dir.value, `${options?.prefix ?? ""}${randomUUID()}${options?.suffix ?? ""}`);815
// Node's `writeFile(filePath, "")`, which does not create parents.816
await this.connection.request(817
"write",818
{ path: filePath, append: false, parents: false },819
{ payload: new Uint8Array(0) },820
);821
return ok(filePath);822
} catch (error) {823
return err(toFileError(error, filePath));824
}825
}827
async watch(828
targets: readonly WatchTarget[],829
onChange: (change: WatchChange) => void,830
context: Context,831
): Promise<Result<FileWatcher, FileError>> {832
const aborted = abortResult<FileWatcher>(context.abortSignal);833
if (aborted) return aborted;834
try {835
const resolved = await Promise.all(836
targets.map(async (target) => ({ ...target, path: await this.#resolve(target.path) })),837
);838
const afterResolve = abortResult<FileWatcher>(context.abortSignal);839
if (afterResolve) return afterResolve;840
const watcher = await RemoteWatcher.open(this.connection, resolved, onChange, this.#watchOptions);841
const afterOpen = abortResult<FileWatcher>(context.abortSignal);842
if (afterOpen) {843
await watcher.close(context);844
return afterOpen;845
}846
return ok(watcher);847
} catch (error) {848
return err(toFileError(error));849
}850
}852
async exec(853
command: string | readonly string[],854
options: ShellExecOptions | undefined,855
context: Context,856
): Promise<Result<ShellExecResult, ExecutionError>> {857
const signal = context.abortSignal;858
if (signal?.aborted) return err(new ExecutionError("aborted", "aborted"));859
const timeout = options?.timeout;860
if (timeout !== undefined) {861
if (!Number.isFinite(timeout) || timeout <= 0) {862
return err(new ExecutionError("timeout", "Invalid timeout: must be a finite number of seconds"));863
}864
if (timeout * 1000 > MAX_TIMEOUT_MS) {865
return err(new ExecutionError("timeout", `Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`));866
}867
}868
const inheritEnv = options?.inheritEnv ?? true;869
let cwd: string;870
try {871
cwd = options?.cwd ? await this.#resolve(options.cwd) : this.cwd;872
} catch (error) {873
return err(new ExecutionError("unknown", error instanceof Error ? error.message : String(error)));874
}875
if (signal?.aborted) return err(new ExecutionError("aborted", "aborted"));876
const env: Record<string, string> = {};877
for (const [key, value] of Object.entries(878
inheritEnv ? { ...this.#shellEnv, ...options?.env } : { ...options?.env },879
)) {880
if (value !== undefined) env[key.toWellFormed()] = value;881
}882
let callbackError: ExecutionError | undefined;883
let settled = false;884
let running: number | undefined;885
const controller = new AbortController();886
const onAbort = () => controller.abort();887
signal?.addEventListener("abort", onAbort, { once: true });888
try {889
const { json } = await this.connection.request(890
"exec",891
{892
...(typeof command === "string" ? { command } : { argv: [...command] }),893
cwd,894
env,895
inheritEnv,896
...(this.#shellPath === undefined ? {} : { shellPath: this.#shellPath }),897
...(timeout === undefined ? {} : { timeoutMs: timeout * 1000 }),898
...(options?.spill === undefined ? {} : { spill: options.spill }),899
...(options?.window === undefined ? {} : { window: options.window }),900
},901
{902
signal: controller.signal,903
onStart: (requestId, session) => {904
running = requestId;905
this.#running.set(requestId, session);906
},907
onEvent: (event, payload) => {908
if (settled || callbackError !== undefined || event.kind !== "output") return;909
const text = Buffer.from(payload.buffer, payload.byteOffset, payload.length).toString("utf8");910
if (text === "" || options?.onOutput === undefined) return;911
const info: ShellOutputInfo = { stream: event.stream === "stderr" ? "stderr" : "stdout" };912
if (event.skipped !== undefined) info.skipped = event.skipped as ShellOutputSkip;913
try {914
options.onOutput(text, context, info);915
} catch (error) {916
const cause = error instanceof Error ? error : new Error(String(error));917
callbackError = new ExecutionError("callback_error", cause.message, cause);918
controller.abort();919
}920
},921
},922
);923
if (callbackError) return err(callbackError);924
return ok({925
exitCode: json.exitCode as number,926
...(typeof json.spillPath === "string" ? { spillPath: json.spillPath } : {}),927
});928
} catch (error) {929
if (callbackError) return err(callbackError);930
if (!(error instanceof RemoteError)) {931
return err(new ExecutionError("unknown", error instanceof Error ? error.message : String(error)));932
}933
const failure =934
error.code === "timeout"935
? new ExecutionError("timeout", `timeout:${timeout}`)936
: error.code === "aborted"937
? new ExecutionError("aborted", "aborted")938
: error.code === "shell_unavailable" || error.code === "spawn_error"939
? new ExecutionError(error.code, error.message)940
: new ExecutionError("unknown", error.message);941
if (typeof error.fields.spillPath === "string") failure.spillPath = error.fields.spillPath;942
return err(failure);943
} finally {944
settled = true;945
signal?.removeEventListener("abort", onAbort);946
if (running !== undefined) this.#running.delete(running);947
}948
}950
async cleanup(_context: Context): Promise<void> {951
// Kill without aborting, so the commands settle with their killed status, as `NodeExecutionEnv` does.952
for (const [id, session] of this.#running) this.connection.kill(id, session);953
this.#running.clear();954
}955
}957
export type { RemoteInfo };