@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 366 lines 13.4 KB
Raw
1 import * as NodeFileSystem from "@effect/platform-node-shared/NodeFileSystem"
2 import { assert, describe, it } from "@effect/vitest"
3 import * as ByteSize from "effect/ByteSize"
4 import * as Deferred from "effect/Deferred"
5 import * as Effect from "effect/Effect"
6 import * as Fiber from "effect/Fiber"
7 import * as FileSystem from "effect/FileSystem"
8 import * as Layer from "effect/Layer"
9 import * as Option from "effect/Option"
10 import * as Stream from "effect/Stream"
11 import * as TestClock from "effect/testing/TestClock"
12 import * as NFS from "node:fs"
13 import * as Path from "node:path"
14 import { afterEach, beforeEach, vi } from "vitest"
15 import { testGlob, testLayer } from "../../../effect/test/FileSystem.test-utils.ts"
16
17 const startWatch = Effect.fnUntraced(function*<E, R>(
18 fs: FileSystem.FileSystem,
19 root: string,
20 watch: () => Stream.Stream<FileSystem.WatchEvent, E, R>
21 ) {
22 const ready = yield* Deferred.make<void>()
23 const readyName = ".watch-ready"
24 const fiber = yield* watch().pipe(
25 Stream.tap((event) =>
26 event.path === readyName
27 ? Deferred.succeed(ready, undefined)
28 : Effect.void
29 ),
30 Stream.dropUntil((event) => event.path === readyName),
31 Stream.filter((event) => event.path !== readyName),
32 Stream.runHead,
33 Effect.flatMap(Effect.fromOption),
34 Effect.forkChild
35 )
36 const signalFiber = yield* Effect.sleep("10 millis").pipe(
37 TestClock.withLive,
38 Effect.andThen(fs.writeFileString(`${root}/${readyName}`, "")),
39 Effect.forever,
40 Effect.forkChild
41 )
42 yield* Deferred.await(ready).pipe(
43 Effect.raceFirst(Fiber.join(fiber).pipe(Effect.asVoid)),
44 Effect.ensuring(Fiber.interrupt(signalFiber))
45 )
46 return fiber
47 })
48
49 // A file system whose listings report every entry as `"Unknown"`, so `glob`
50 // learns entry types from `stat` and `readLink` alone.
51 const untypedLayer = Layer.effect(
52 FileSystem.FileSystem,
53 Effect.gen(function*() {
54 const fs = yield* FileSystem.FileSystem
55 return FileSystem.make({
56 ...fs,
57 readDirectoryEntries: (path) =>
58 Effect.map(fs.readDirectory(path), (names) => names.map((name) => ({ name, type: "Unknown" as const })))
59 })
60 })
61 ).pipe(Layer.provide(NodeFileSystem.layer))
62
63 describe("FileSystem without typed directory listings", { concurrent: false }, () => {
64 testGlob(untypedLayer)
65 })
66
67 describe("FileSystem", { concurrent: false }, () => {
68 testLayer(NodeFileSystem.layer, { noFollow: process.platform !== "win32" })
69
70 it.effect("realPath resolves a directory alias to its physical target", () =>
71 Effect.gen(function*() {
72 const fs = yield* FileSystem.FileSystem
73 const root = yield* fs.realPath(yield* fs.makeTempDirectoryScoped())
74 const target = Path.join(root, "target")
75 const alias = Path.join(root, "alias")
76 yield* fs.makeDirectory(target)
77 NFS.symlinkSync(target, alias, process.platform === "win32" ? "junction" : "dir")
78 assert.strictEqual(yield* fs.realPath(alias), target)
79 }).pipe(
80 Effect.provide(NodeFileSystem.layer)
81 ))
82
83 it.effect("writeAll accepts an empty buffer", () =>
84 Effect.gen(function*() {
85 const fs = yield* FileSystem.FileSystem
86 const path = yield* fs.makeTempFileScoped()
87 const file = yield* fs.open(path, { flag: "r+" })
88
89 yield* file.writeAll(new Uint8Array(0))
90 }).pipe(
91 Effect.provide(NodeFileSystem.layer)
92 ))
93
94 it.effect("watch reports Create for a new file outside the current directory", () =>
95 Effect.gen(function*() {
96 const fs = yield* FileSystem.FileSystem
97 const root = yield* fs.makeTempDirectoryScoped()
98 const name = "created.txt"
99 const path = `${root}/${name}`
100 assert.strictEqual(yield* fs.exists(name), false)
101
102 const fiber = yield* startWatch(fs, root, () => fs.watch(root))
103 yield* fs.writeFileString(path, "")
104
105 const event = yield* Fiber.join(fiber)
106 assert.strictEqual(yield* fs.exists(path), true)
107 assert.deepStrictEqual(event, { _tag: "Create", path: name })
108 }).pipe(
109 Effect.provide(NodeFileSystem.layer)
110 ))
111
112 it.effect("watch does not report nested changes when recursive is false", () =>
113 Effect.gen(function*() {
114 const fs = yield* FileSystem.FileSystem
115 const root = yield* fs.makeTempDirectoryScoped()
116 const nested = `${root}/nested`
117 yield* fs.makeDirectory(nested)
118
119 const fiber = yield* startWatch(fs, root, () => fs.watch(root, { recursive: false }))
120
121 yield* fs.writeFileString(`${nested}/nested.txt`, "")
122 yield* fs.writeFileString(`${root}/direct.txt`, "")
123
124 const event = yield* Fiber.join(fiber)
125 assert.strictEqual(event.path, "direct.txt")
126 }).pipe(
127 Effect.provide(NodeFileSystem.layer)
128 ))
129
130 it.effect("watch is non-recursive when options are omitted", () =>
131 Effect.gen(function*() {
132 const fs = yield* FileSystem.FileSystem
133 const root = yield* fs.makeTempDirectoryScoped()
134 const nested = `${root}/nested`
135 yield* fs.makeDirectory(nested)
136
137 const fiber = yield* startWatch(fs, root, () => fs.watch(root))
138
139 yield* fs.writeFileString(`${nested}/nested.txt`, "")
140 yield* fs.writeFileString(`${root}/direct.txt`, "")
141
142 const event = yield* Fiber.join(fiber)
143 assert.strictEqual(event.path, "direct.txt")
144 }).pipe(
145 Effect.provide(NodeFileSystem.layer)
146 ))
147
148 it.live("watch uses a WatchBackend provided after the layer is built", () =>
149 Effect.gen(function*() {
150 const fs = yield* FileSystem.FileSystem
151 const root = yield* fs.makeTempDirectoryScoped()
152 const backendEvent: FileSystem.WatchEvent = { _tag: "Create", path: "from-backend" }
153 const event = yield* fs.watch(root).pipe(
154 Stream.runHead,
155 Effect.provideService(FileSystem.WatchBackend, {
156 register: () => Option.some(Stream.make(backendEvent))
157 }),
158 Effect.timeout("1 second")
159 )
160 assert.deepStrictEqual(event, Option.some(backendEvent))
161 }).pipe(
162 Effect.provide(NodeFileSystem.layer)
163 ))
164
165 it.effect("watch prefers the caller WatchBackend over the construction backend", () =>
166 Effect.gen(function*() {
167 const fs = yield* FileSystem.FileSystem
168 const root = yield* fs.makeTempDirectoryScoped()
169 const callerEvent: FileSystem.WatchEvent = { _tag: "Create", path: "from-caller" }
170 const event = yield* fs.watch(root).pipe(
171 Stream.runHead,
172 Effect.provideService(FileSystem.WatchBackend, {
173 register: () => Option.some(Stream.make(callerEvent))
174 })
175 )
176 assert.deepStrictEqual(event, Option.some(callerEvent))
177 }).pipe(
178 Effect.provide(NodeFileSystem.layer),
179 Effect.provideService(FileSystem.WatchBackend, {
180 register: () => Option.some(Stream.make({ _tag: "Create" as const, path: "from-construction" }))
181 })
182 ))
183
184 it.effect("watch reports nested changes when recursive is true", () =>
185 Effect.gen(function*() {
186 const fs = yield* FileSystem.FileSystem
187 const root = yield* fs.makeTempDirectoryScoped()
188 const nested = `${root}/nested`
189 yield* fs.makeDirectory(nested)
190
191 const fiber = yield* startWatch(fs, root, () => fs.watch(root, { recursive: true }))
192
193 yield* fs.writeFileString(`${nested}/nested.txt`, "")
194
195 const event = yield* Fiber.join(fiber)
196 assert(event.path.endsWith("nested.txt"))
197 }).pipe(
198 Effect.provide(NodeFileSystem.layer)
199 ))
200 })
201
202 const state = vi.hoisted(() => ({
203 enabled: false,
204 values: {} as Record<string, bigint>,
205 positions: [] as Array<number | bigint | undefined>
206 }))
207
208 vi.mock("node:fs", async (importOriginal) => {
209 const original = await importOriginal<typeof NFS>()
210 // Match Node's number and bigint stat modes.
211 const stat = (
212 _pathOrFd: string | number,
213 optionsOrCallback: { bigint?: boolean } | ((error: null, stats: object) => void),
214 callback?: (error: null, stats: object) => void
215 ) => {
216 const bigint = typeof optionsOrCallback === "object" && optionsOrCallback.bigint
217 const done = typeof optionsOrCallback === "function" ? optionsOrCallback : callback!
218 done(null, {
219 ...Object.fromEntries(Object.entries(state.values).map(([key, value]) => [key, bigint ? value : Number(value)])),
220 mtime: new Date(0),
221 atime: new Date(0),
222 birthtime: new Date(0),
223 isFile: () => true
224 })
225 }
226 const doubles = {
227 open: (_path: string, _flags: string, _mode: unknown, callback: (error: null, fd: number) => void) =>
228 callback(null, 42),
229 close: (_fd: number, callback: (error: null) => void) => callback(null),
230 stat,
231 fstat: stat,
232 write: (
233 _fd: number,
234 _buffer: Uint8Array,
235 _offset: unknown,
236 _length: unknown,
237 position: number | bigint | undefined,
238 callback: (error: null, bytesWritten: number) => void
239 ) => {
240 state.positions.push(position)
241 callback(null, 1)
242 }
243 }
244 return {
245 ...original,
246 ...Object.fromEntries(
247 Object.entries(doubles).map(([name, implementation]) => [
248 name,
249 (...args: Array<unknown>) =>
250 Reflect.apply(state.enabled ? implementation : original[name as keyof typeof doubles], original, args)
251 ])
252 )
253 }
254 })
255
256 const maxSafe = BigInt(Number.MAX_SAFE_INTEGER)
257 const oversized = maxSafe + 2n
258
259 describe("NodeFileSystem precision", { concurrent: false }, () => {
260 afterEach(() => {
261 state.enabled = false
262 })
263 beforeEach(() => {
264 state.enabled = true
265 state.positions = []
266 state.values = {
267 size: 4n,
268 blksize: 4096n,
269 dev: 1n,
270 ino: 2n,
271 mode: 33188n,
272 nlink: 1n,
273 uid: 1000n,
274 gid: 1000n,
275 rdev: 0n,
276 blocks: 8n
277 }
278 })
279
280 for (const method of ["write", "writeAll"] as const) {
281 it.effect(`${method} rejects an unsafe position before writing`, () =>
282 Effect.gen(function*() {
283 const fs = yield* FileSystem.FileSystem
284 const file = yield* fs.open("precision.bin", { flag: "r+" })
285 yield* file.seek(oversized, "start")
286 const error = yield* Effect.flip(file[method](new Uint8Array([1])))
287 assert.strictEqual(error.reason._tag, "BadArgument")
288 assert.deepStrictEqual(state.positions, [])
289 }).pipe(Effect.provide(NodeFileSystem.layer)))
290 }
291
292 it.effect("writeAll stops when a partial write advances beyond the safe integer limit", () =>
293 Effect.gen(function*() {
294 const fs = yield* FileSystem.FileSystem
295 const file = yield* fs.open("precision.bin", { flag: "r+" })
296 yield* file.seek(maxSafe, "start")
297 const error = yield* Effect.flip(file.writeAll(new Uint8Array([1, 2])))
298 assert.strictEqual(error.reason._tag, "BadArgument")
299 assert.deepStrictEqual(state.positions, [Number.MAX_SAFE_INTEGER])
300 assert.strictEqual(yield* file.seek(0n, "current"), maxSafe + 1n)
301 }).pipe(Effect.provide(NodeFileSystem.layer)))
302
303 for (const method of ["stat", "fstat"] as const) {
304 const getInfo = Effect.gen(function*() {
305 const fs = yield* FileSystem.FileSystem
306 return yield* method === "stat" ? fs.stat("precision.bin") : (yield* fs.open("precision.bin")).stat
307 })
308
309 it.effect(`${method} preserves oversized byte counts`, () =>
310 Effect.gen(function*() {
311 state.values.size = oversized
312 state.values.blksize = oversized
313 const info = yield* getInfo
314 assert.strictEqual(info.size, ByteSize.bytes(oversized))
315 assert.strictEqual(Option.getOrThrow(info.blksize), ByteSize.bytes(oversized))
316 }).pipe(Effect.provide(NodeFileSystem.layer)))
317
318 it.effect(`${method} rejects unsafe mode metadata`, () =>
319 Effect.gen(function*() {
320 state.values.mode = maxSafe + 1n
321 const error = yield* Effect.flip(getInfo)
322 assert.strictEqual(error.reason._tag, "BadArgument")
323 }).pipe(Effect.provide(NodeFileSystem.layer)))
324
325 for (
326 const { expected, name, value } of [
327 { name: "preserves metadata above MAX_SAFE_INTEGER", value: maxSafe + 1n, expected: 9007199254740992n },
328 { name: "interprets signed identifiers as unsigned 64-bit", value: -2n, expected: 18446744073709551614n }
329 ]
330 ) {
331 it.effect(`${method} ${name}`, () =>
332 Effect.gen(function*() {
333 Object.assign(state.values, { dev: value, ino: value, rdev: value, nlink: value, blocks: value })
334 const info = yield* getInfo
335 assert.strictEqual(info.dev, expected)
336 for (const field of ["ino", "rdev", "nlink"] as const) {
337 assert.deepStrictEqual(info[field], Option.some(expected), field)
338 }
339 assert.deepStrictEqual(info.blocks, Option.some(value))
340 }).pipe(Effect.provide(NodeFileSystem.layer)))
341 }
342
343 it.effect(`${method} preserves numeric ownership metadata`, () =>
344 Effect.gen(function*() {
345 Object.assign(state.values, { uid: 1000n, gid: 1001n })
346 const info = yield* getInfo
347 assert.deepStrictEqual(info.uid, Option.some(1000))
348 assert.deepStrictEqual(info.gid, Option.some(1001))
349 }).pipe(Effect.provide(NodeFileSystem.layer)))
350
351 it.effect(`${method} omits missing optional metadata`, () =>
352 Effect.gen(function*() {
353 const fields = ["ino", "nlink", "uid", "gid", "rdev", "blocks"] as const
354 for (const field of fields) {
355 delete state.values[field]
356 }
357 const info = yield* getInfo
358 for (const field of fields) {
359 assert.deepStrictEqual(info[field], Option.none(), field)
360 }
361 assert.strictEqual(info.type, "File")
362 assert.strictEqual(info.size, ByteSize.bytes(4n))
363 assert.deepStrictEqual(info.mtime, Option.some(new Date(0)))
364 }).pipe(Effect.provide(NodeFileSystem.layer)))
365 }
366 })