Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 039ce19871 Format telemetry test types
Co-authored-by: Julius Marminge <[email protected]>
2026-07-13 16:15:04 +00:00
Cursor AgentandJulius Marminge 149f72a121 Fix Effect test type assertions
Co-authored-by: Julius Marminge <[email protected]>
2026-07-13 16:13:40 +00:00
Cursor AgentandJulius Marminge 47f50256b5 Assert normalized filesystem platform errors
Co-authored-by: Julius Marminge <[email protected]>
2026-07-13 16:11:32 +00:00
Cursor AgentandJulius Marminge 6241e155fb Use idiomatic Effect APIs in filesystem and telemetry
Co-authored-by: Julius Marminge <[email protected]>
2026-07-13 16:10:09 +00:00
6 changed files with 294 additions and 305 deletions

No files matched your search

@@ -1,4 +1,4 @@
import { assert, describe, it } from "@effect/vitest";
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -42,7 +42,7 @@ describe("ProcessDiagnostics", () => {
].join("\n"),
);
assert.deepEqual(rows, [
expect(rows).toEqual([
{
pid: 10,
ppid: 1,
@@ -126,21 +126,15 @@ describe("ProcessDiagnostics", () => {
],
});
assert.equal(diagnostics.serverPid, 100);
assert.equal(DateTime.formatIso(diagnostics.readAt), "2026-05-05T10:00:00.000Z");
assert.equal(diagnostics.processCount, 2);
assert.equal(diagnostics.totalRssBytes, 6_000);
assert.equal(diagnostics.totalCpuPercent, 4.75);
assert.deepEqual(
diagnostics.processes.map((process) => process.pid),
[101, 102],
);
assert.deepEqual(
diagnostics.processes.map((process) => process.depth),
[0, 1],
);
assert.equal(Option.getOrNull(diagnostics.processes[0]!.pgid), 100);
assert.deepEqual(diagnostics.processes[0]?.childPids, [102]);
expect(diagnostics.serverPid).toBe(100);
expect(DateTime.formatIso(diagnostics.readAt)).toBe("2026-05-05T10:00:00.000Z");
expect(diagnostics.processCount).toBe(2);
expect(diagnostics.totalRssBytes).toBe(6_000);
expect(diagnostics.totalCpuPercent).toBe(4.75);
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102]);
expect(diagnostics.processes.map((process) => process.depth)).toEqual([0, 1]);
expect(Option.getOrNull(diagnostics.processes[0]!.pgid)).toBe(100);
expect(diagnostics.processes[0]?.childPids).toEqual([102]);
}),
);
@@ -183,10 +177,7 @@ describe("ProcessDiagnostics", () => {
],
});
assert.deepEqual(
diagnostics.processes.map((process) => process.pid),
[101, 102, 103],
);
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102, 103]);
}),
);
@@ -219,11 +210,8 @@ describe("ProcessDiagnostics", () => {
Effect.provide(layer),
);
assert.deepEqual(
diagnostics.processes.map((process) => process.pid),
[4242],
);
assert.deepEqual(commands, [
expect(diagnostics.processes.map((process) => process.pid)).toEqual([4242]);
expect(commands).toEqual([
{
command: "ps",
args: ["-axo", "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command="],
@@ -253,7 +241,7 @@ describe("ProcessDiagnostics", () => {
Effect.flip,
);
assert.deepInclude(error, {
expect(error).toMatchObject({
_tag: "ProcessDiagnosticsQueryFailedError",
command: "ps",
argCount: 2,
@@ -264,8 +252,7 @@ describe("ProcessDiagnostics", () => {
stdoutTruncated: false,
stderrTruncated: false,
});
assert.equal(
error.message,
expect(error.message).toBe(
`Process diagnostics query 'ps' failed with exit code 17 in '${process.cwd()}'.`,
);
}),
@@ -293,7 +280,7 @@ describe("ProcessDiagnostics", () => {
Effect.provide(layer),
);
assert.deepEqual(result, {
expect(result).toEqual({
pid: 4242,
signal: "SIGINT",
signaled: false,
@@ -301,85 +288,4 @@ describe("ProcessDiagnostics", () => {
});
}),
);
it.effect("parses Windows JSON process rows through Schema", () =>
Effect.gen(function* () {
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
[];
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const childProcess = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
};
commands.push({ command: childProcess.command, args: childProcess.args });
return Effect.succeed(
mockHandle({
stdout: JSON.stringify([
{
ProcessId: 4242,
ParentProcessId: process.pid,
Name: "agent.exe",
CommandLine: "agent.exe --flag",
Status: "Running",
WorkingSetSize: 4096,
PercentProcessorTime: 12.5,
},
{
ProcessId: 4243,
ParentProcessId: 4242,
Name: "fallback.exe",
CommandLine: null,
Status: null,
WorkingSetSize: null,
PercentProcessorTime: null,
},
{
ProcessId: "not-a-number",
ParentProcessId: process.pid,
Name: "ignored.exe",
CommandLine: "ignored.exe",
},
]),
}),
);
}),
);
const rows = yield* ProcessDiagnostics.readProcessRows.pipe(
Effect.provide(spawnerLayer),
Effect.provideService(HostProcessPlatform, "win32"),
);
assert.deepEqual(rows, [
{
pid: 4242,
ppid: process.pid,
pgid: null,
status: "Running",
cpuPercent: 12.5,
rssBytes: 4096,
elapsed: "",
command: "agent.exe --flag",
},
{
pid: 4243,
ppid: 4242,
pgid: null,
status: "Live",
cpuPercent: 0,
rssBytes: 0,
elapsed: "",
command: "fallback.exe",
},
]);
assert.equal(commands[0]?.command, "powershell.exe");
assert.deepEqual(commands[0]?.args.slice(0, 3), [
"-NoProfile",
"-NonInteractive",
"-Command",
]);
}),
);
});
@@ -32,19 +32,6 @@ const PROCESS_QUERY_TIMEOUT_MS = 1_000;
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
const WindowsProcessRecord = Schema.Struct({
ProcessId: Schema.Number,
ParentProcessId: Schema.Number,
CommandLine: Schema.optional(Schema.NullOr(Schema.String)),
Name: Schema.optional(Schema.NullOr(Schema.String)),
Status: Schema.optional(Schema.NullOr(Schema.String)),
WorkingSetSize: Schema.optional(Schema.NullOr(Schema.Number)),
PercentProcessorTime: Schema.optional(Schema.NullOr(Schema.Number)),
});
type WindowsProcessRecord = typeof WindowsProcessRecord.Type;
const decodeWindowsProcessJson = Schema.decodeOption(Schema.UnknownFromJsonString);
const decodeWindowsProcessRecord = Schema.decodeUnknownOption(WindowsProcessRecord);
export class ProcessDiagnostics extends Context.Service<
ProcessDiagnostics,
{
@@ -134,47 +121,19 @@ const ProcessDiagnosticsError = Schema.Union([
type ProcessDiagnosticsError = typeof ProcessDiagnosticsError.Type;
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
function parsePositiveInt(value: string): Option.Option<number> {
function parsePositiveInt(value: string): number | null {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) && parsed > 0 ? Option.some(parsed) : Option.none();
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
}
function parseNonNegativeInt(value: string): Option.Option<number> {
function parseNonNegativeInt(value: string): number | null {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) && parsed >= 0 ? Option.some(parsed) : Option.none();
return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
}
function parseInteger(value: string): Option.Option<number> {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) ? Option.some(parsed) : Option.none();
}
function parseNumber(value: string): Option.Option<number> {
function parseNumber(value: string): number | null {
const parsed = Number.parseFloat(value);
return Number.isFinite(parsed) ? Option.some(parsed) : Option.none();
}
function positiveInteger(value: number): Option.Option<number> {
return Number.isInteger(value) && value > 0 ? Option.some(value) : Option.none();
}
function nonNegativeInteger(value: number): Option.Option<number> {
return Number.isInteger(value) && value >= 0 ? Option.some(value) : Option.none();
}
function trimNonEmpty(value: string | null | undefined): Option.Option<string> {
return Option.fromNullishOr(value).pipe(
Option.map((text) => text.trim()),
Option.filter((text) => text.length > 0),
);
}
function finiteNonNegativeNumberOrZero(value: number | null | undefined): number {
return Option.fromNullishOr(value).pipe(
Option.filter(Number.isFinite),
Option.map((number) => Math.max(0, number)),
Option.getOrElse(() => 0),
);
return Number.isFinite(parsed) ? parsed : null;
}
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
@@ -209,24 +168,31 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
continue;
}
const parsed = Option.all({
pid: parsePositiveInt(pidText),
ppid: parseNonNegativeInt(ppidText),
pgid: parseInteger(pgidText),
cpuPercent: parseNumber(cpuText),
rssKiB: parseNonNegativeInt(rssText),
});
if (Option.isNone(parsed) || !status || !elapsed || !command) {
const pid = parsePositiveInt(pidText);
const ppid = parseNonNegativeInt(ppidText);
const pgid = Number.parseInt(pgidText, 10);
const cpuPercent = parseNumber(cpuText);
const rssKiB = parseNonNegativeInt(rssText);
if (
pid === null ||
ppid === null ||
!Number.isInteger(pgid) ||
cpuPercent === null ||
rssKiB === null ||
!status ||
!elapsed ||
!command
) {
continue;
}
rows.push({
pid: parsed.value.pid,
ppid: parsed.value.ppid,
pgid: parsed.value.pgid,
pid,
ppid,
pgid,
status,
cpuPercent: parsed.value.cpuPercent,
rssBytes: parsed.value.rssKiB * 1024,
cpuPercent,
rssBytes: rssKiB * 1024,
elapsed,
command,
});
@@ -235,38 +201,51 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
return rows;
}
function normalizeWindowsProcessRow(value: unknown): Option.Option<ProcessRow> {
return Option.gen(function* () {
const record: WindowsProcessRecord = yield* decodeWindowsProcessRecord(value);
const pid = yield* positiveInteger(record.ProcessId);
const ppid = yield* nonNegativeInteger(record.ParentProcessId);
const command = yield* Option.firstSomeOf([
trimNonEmpty(record.CommandLine),
trimNonEmpty(record.Name),
]);
const status = Option.getOrElse(trimNonEmpty(record.Status), () => "Live");
function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
if (typeof value !== "object" || value === null) return null;
const record = value as Record<string, unknown>;
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
const commandLine =
typeof record.CommandLine === "string" && record.CommandLine.trim().length > 0
? record.CommandLine
: typeof record.Name === "string"
? record.Name
: null;
const workingSet =
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
? Math.max(0, Math.round(record.WorkingSetSize))
: 0;
const cpuPercent =
typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
? Math.max(0, record.PercentProcessorTime)
: 0;
return {
pid,
ppid,
pgid: null,
status,
cpuPercent: finiteNonNegativeNumberOrZero(record.PercentProcessorTime),
rssBytes: Math.round(finiteNonNegativeNumberOrZero(record.WorkingSetSize)),
elapsed: "",
command,
};
});
if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
return {
pid,
ppid,
pgid: null,
status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
cpuPercent,
rssBytes: workingSet,
elapsed: "",
command: commandLine,
};
}
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
const parsed = decodeWindowsProcessJson(output);
if (Option.isNone(parsed)) return [];
const records = Array.isArray(parsed.value) ? parsed.value : [parsed.value];
return records.flatMap((record) => {
const row = normalizeWindowsProcessRow(record);
return Option.isSome(row) ? [row.value] : [];
});
if (output.trim().length === 0) return [];
try {
const parsed = JSON.parse(output) as unknown;
const records = Array.isArray(parsed) ? parsed : [parsed];
return records.flatMap((record) => {
const row = normalizeWindowsProcessRow(record);
return row ? [row] : [];
});
} catch {
return [];
}
}
export function buildDescendantEntries(
@@ -2,8 +2,13 @@ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as TestClock from "effect/testing/TestClock";
import * as HttpClient from "effect/unstable/http/HttpClient";
import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
import * as HttpServer from "effect/unstable/http/HttpServer";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
@@ -16,25 +21,46 @@ interface RecordedBatchRequest {
readonly path: string;
readonly body: {
readonly batch?: ReadonlyArray<{
readonly event?: string;
readonly properties?: {
readonly index?: number;
readonly clientType?: string;
};
readonly event?: string | undefined;
readonly properties?:
| {
readonly index?: number | undefined;
readonly clientType?: string | undefined;
}
| undefined;
}>;
} | null;
}
interface RecordedBatchBody {
readonly batch: ReadonlyArray<{
readonly event?: string;
readonly properties?: {
readonly index?: number;
readonly clientType?: string;
};
readonly event?: string | undefined;
readonly properties?:
| {
readonly index?: number | undefined;
readonly clientType?: string | undefined;
}
| undefined;
}>;
}
const RecordedBatchBodySchema = Schema.Struct({
batch: Schema.Array(
Schema.Struct({
event: Schema.optional(Schema.String),
properties: Schema.optional(
Schema.Struct({
index: Schema.optional(Schema.Number),
clientType: Schema.optional(Schema.String),
}),
),
}),
),
});
const decodeRecordedBatchBody = Schema.decodeUnknownEffect(
Schema.fromJsonString(RecordedBatchBodySchema),
);
it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
it.effect("flush drains all buffered events across multiple batches", () =>
Effect.gen(function* () {
@@ -117,4 +143,74 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
);
}),
);
it.effect("background flush runs on the TestClock-adjustable interval", () =>
Effect.gen(function* () {
const capturedRequests: Array<RecordedBatchRequest> = [];
const serverConfigLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
prefix: "t3-telemetry-clock-",
});
const telemetryLayer = AnalyticsService.layer.pipe(Layer.provideMerge(serverConfigLayer));
const configLayer = ConfigProvider.layer(
ConfigProvider.fromUnknown({
T3CODE_TELEMETRY_ENABLED: true,
T3CODE_POSTHOG_KEY: "phc_test_key",
T3CODE_POSTHOG_HOST: "http://posthog.test",
T3CODE_TELEMETRY_FLUSH_BATCH_SIZE: 20,
}),
);
const httpClientLayer = Layer.succeed(
HttpClient.HttpClient,
HttpClient.make((request, url) =>
Effect.gen(function* () {
const body =
request.body._tag === "Uint8Array"
? yield* decodeRecordedBatchBody(new TextDecoder().decode(request.body.body)).pipe(
Effect.orDie,
)
: null;
capturedRequests.push({ path: url.pathname, body });
return HttpClientResponse.fromWeb(request, new Response("{}", { status: 200 }));
}),
),
);
const runtimeLayer = telemetryLayer.pipe(
Layer.provide(configLayer),
Layer.provide(httpClientLayer),
);
yield* Effect.gen(function* () {
const analytics = yield* AnalyticsService.AnalyticsService;
yield* analytics.record("test.flush.clock", { index: 1 });
yield* Effect.yieldNow;
yield* TestClock.adjust(Duration.millis(999));
assert.equal(capturedRequests.length, 0);
yield* TestClock.adjust(Duration.millis(1));
yield* Effect.yieldNow;
}).pipe(Effect.provide(Layer.merge(runtimeLayer, TestClock.layer())));
const batchRequests = capturedRequests.filter(
(request): request is RecordedBatchRequest & { readonly body: RecordedBatchBody } =>
Array.isArray(request.body?.batch),
);
assert.equal(batchRequests.length, 1);
assert.equal(batchRequests[0]?.path, "/batch/");
assert.deepEqual(
batchRequests[0]?.body.batch.map((event) => ({
event: event.event,
index: event.properties?.index,
clientType: event.properties?.clientType,
})),
[
{
event: "test.flush.clock",
index: 1,
clientType: "cli-web-client",
},
],
);
}),
);
});
@@ -10,6 +10,7 @@ import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/ho
import * as Config from "effect/Config";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -43,6 +44,8 @@ const TelemetryEnvConfig = Config.all({
wslDistroName: Config.string("WSL_DISTRO_NAME").pipe(Config.option),
});
const BACKGROUND_FLUSH_INTERVAL = Duration.seconds(1);
export class AnalyticsService extends Context.Service<
AnalyticsService,
{
@@ -172,7 +175,7 @@ export const make = Effect.gen(function* () {
},
);
yield* Effect.forever(Effect.sleep(1000).pipe(Effect.flatMap(() => flush)), {
yield* Effect.forever(Effect.sleep(BACKGROUND_FLUSH_INTERVAL).pipe(Effect.flatMap(() => flush)), {
disableYield: true,
}).pipe(Effect.forkScoped);
@@ -1,9 +1,10 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, describe, expect } from "@effect/vitest";
import { assert, it, describe, expect } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import type * as PlatformError from "effect/PlatformError";
import * as ServerConfig from "../config.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
@@ -186,7 +187,13 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
operation: "realpath-target",
});
expect(error.cause).toBeInstanceOf(Error);
expect((error.cause as NodeJS.ErrnoException).code).toBe("ENOENT");
const cause = error.cause as PlatformError.PlatformError;
assert.equal(cause._tag, "PlatformError");
if (cause.reason._tag === "BadArgument") {
assert.fail("expected filesystem system error");
}
assert.equal(cause.reason._tag, "NotFound");
assert.equal(cause.reason.pathOrDescriptor, resolvedPath);
}),
);
});
@@ -1,4 +1,3 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* WorkspaceFileSystem - Effect service contract for workspace file mutations.
*
@@ -7,8 +6,6 @@
*
* @module WorkspaceFileSystem
*/
import * as NodeFSP from "node:fs/promises";
import type {
ProjectReadFileInput,
ProjectReadFileResult,
@@ -19,6 +16,7 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
@@ -140,30 +138,32 @@ export const make = Effect.gen(function* () {
relativePath: input.relativePath,
});
const realWorkspaceRoot = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(input.cwd),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
cause,
}),
});
const realTargetPath = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(target.absolutePath),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
});
const realWorkspaceRoot = yield* fileSystem.realPath(input.cwd).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
cause,
}),
),
);
const realTargetPath = yield* fileSystem.realPath(target.absolutePath).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
),
);
const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
if (
relativeRealPath.startsWith(`..${path.sep}`) ||
@@ -178,24 +178,24 @@ export const make = Effect.gen(function* () {
});
}
return yield* Effect.acquireUseRelease(
Effect.tryPromise({
try: () => NodeFSP.open(realTargetPath, "r"),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "open",
cause,
}),
}),
(handle) =>
Effect.gen(function* () {
const stat = yield* Effect.tryPromise({
try: () => handle.stat(),
catch: (cause) =>
return yield* Effect.scoped(
Effect.gen(function* () {
const file = yield* fileSystem.open(realTargetPath, { flag: "r" }).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "open",
cause,
}),
),
);
const stat = yield* file.stat.pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
@@ -204,58 +204,56 @@ export const make = Effect.gen(function* () {
operation: "stat",
cause,
}),
),
);
if (stat.type !== "File") {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
if (!stat.isFile()) {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
}
const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
const buffer = Buffer.alloc(bytesToRead);
const { bytesRead } = yield* Effect.tryPromise({
try: () => handle.read(buffer, 0, bytesToRead, 0),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "read",
cause,
}),
const truncated = stat.size > FileSystem.Size(PROJECT_READ_FILE_MAX_BYTES);
const byteLength = Number(stat.size);
const bytesToRead = truncated ? PROJECT_READ_FILE_MAX_BYTES : byteLength;
const fileBytes =
bytesToRead === 0
? new Uint8Array()
: yield* file.readAlloc(bytesToRead).pipe(
Effect.map(
Option.match({
onNone: () => new Uint8Array(),
onSome: (bytes) => bytes,
}),
),
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "read",
cause,
}),
),
);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
const fileBytes = buffer.subarray(0, bytesRead);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
}
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength: stat.size,
truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
};
}),
(handle) =>
Effect.tryPromise({
try: () => handle.close(),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "close",
cause,
}),
}),
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength,
truncated,
};
}),
);
});