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

main
ts 436 lines 18.9 KB
Raw
1 /** Watch-loop tests use injected events and TestClock; the CLI test uses real watchers. */
2 import * as Generator from "@effect/graphql-generator/Generator"
3 import * as Watch from "@effect/graphql-generator/internal/Watch"
4 import * as NodeServices from "@effect/platform-node/NodeServices"
5 import { assert, describe, it } from "@effect/vitest"
6 import * as Cause from "effect/Cause"
7 import { CliOutput } from "effect/cli"
8 import * as Deferred from "effect/Deferred"
9 import * as Effect from "effect/Effect"
10 import * as Exit from "effect/Exit"
11 import type * as Fiber from "effect/Fiber"
12 import * as FileSystem from "effect/FileSystem"
13 import * as Layer from "effect/Layer"
14 import * as Path from "effect/Path"
15 import * as PubSub from "effect/PubSub"
16 import * as Stdio from "effect/Stdio"
17 import * as Stream from "effect/Stream"
18 import { TestClock, TestConsole } from "effect/testing"
19 import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
20 import { fileURLToPath } from "node:url"
21
22 const schemaSdl = `type User {
23 id: ID!
24 name: String!
25 }
26
27 type Query {
28 viewer: User!
29 }
30 `
31
32 const query = (name: string, ...fields: ReadonlyArray<string>): string =>
33 `query ${name} {\n viewer {\n${fields.map((field) => ` ${field}\n`).join("")} }\n}\n`
34
35 const config = {
36 schema: "./schema.graphql",
37 documents: ["src/**/*.graphql"]
38 }
39
40 const configSource = (value: unknown): string =>
41 `import { defineConfig } from "@effect/graphql-generator/Config"\n\nexport default defineConfig(${
42 JSON.stringify(value, null, 2)
43 })\n`
44
45 const tmpRoot = fileURLToPath(new URL("./.tmp", import.meta.url))
46
47 const project = Effect.fnUntraced(function*(documents: Readonly<Record<string, string>>) {
48 const fs = yield* FileSystem.FileSystem
49 const path = yield* Path.Path
50 yield* fs.makeDirectory(tmpRoot, { recursive: true })
51 const dir = yield* fs.makeTempDirectoryScoped({ directory: tmpRoot, prefix: "watch-" })
52 yield* write(dir, { "graphql.config.ts": configSource(config), "schema.graphql": schemaSdl, ...documents })
53 return {
54 dir,
55 configPath: path.join(dir, "graphql.config.ts"),
56 file: (relative: string) => path.join(dir, relative)
57 }
58 })
59
60 const write = Effect.fnUntraced(function*(dir: string, files: Readonly<Record<string, string>>) {
61 const fs = yield* FileSystem.FileSystem
62 const path = yield* Path.Path
63 for (const [relative, body] of Object.entries(files)) {
64 const file = path.join(dir, relative)
65 yield* fs.makeDirectory(path.dirname(file), { recursive: true })
66 yield* fs.writeFileString(file, body)
67 }
68 })
69
70 const exists = Effect.fnUntraced(function*(file: string) {
71 const fs = yield* FileSystem.FileSystem
72 return yield* fs.exists(file)
73 })
74
75 const read = Effect.fnUntraced(function*(file: string) {
76 const fs = yield* FileSystem.FileSystem
77 return yield* fs.readFileString(file)
78 })
79
80 /** What a single run would write for `file`. */
81 const generated = Effect.fnUntraced(function*(dir: string, file: string) {
82 const result = yield* Generator.generate(config, { cwd: dir })
83 return result.files.find((output) => output.path === file)!.contents
84 })
85
86 const liveSleep = (millis: number) => Effect.sleep(millis).pipe(TestClock.withLive)
87
88 interface Output {
89 readonly stdout: ReadonlyArray<string>
90 readonly stderr: ReadonlyArray<string>
91 }
92
93 const output: Effect.Effect<Output> = Effect.gen(function*() {
94 return {
95 stdout: (yield* TestConsole.logLines).map(String),
96 stderr: (yield* TestConsole.errorLines).map(String)
97 }
98 })
99
100 const cycles = (out: Output): ReadonlyArray<string> => out.stdout.filter((line) => line.startsWith("regenerated "))
101
102 const show = (out: Output): string => `stdout:\n${out.stdout.join("\n")}\nstderr:\n${out.stderr.join("\n")}`
103
104 /**
105 * Polls the console until `done` holds, failing if the loop exits first.
106 * Each poll moves the TestClock past the debounce.
107 */
108 const waitFor = Effect.fnUntraced(function*(
109 fiber: Fiber.Fiber<unknown, unknown>,
110 description: string,
111 done: (out: Output) => boolean
112 ) {
113 for (let attempt = 0; attempt < 200; attempt++) {
114 const exit = fiber.pollUnsafe()
115 if (exit !== undefined) {
116 const reason = Exit.isFailure(exit) ? Cause.pretty(exit.cause) : "it completed"
117 return assert.fail(`the watch loop exited while waiting for ${description}: ${reason}\n${show(yield* output)}`)
118 }
119 const out = yield* output
120 if (done(out)) return out
121 yield* TestClock.adjust("50 millis")
122 yield* liveSleep(25)
123 }
124 return assert.fail(`timed out waiting for ${description}\n${show(yield* output)}`)
125 })
126
127 /** Starts `Watch.run` over a fake `FileSystem.watch` and returns a handle to drive it. */
128 const start = Effect.fnUntraced(function*(configPath: string, onWatch?: (watched: string) => void) {
129 const path = yield* Path.Path
130 const events = yield* PubSub.unbounded<{ readonly file: string; readonly tag: "Create" | "Update" }>()
131 const watch: Parameters<typeof Watch.run>[0]["watch"] = (watched, _kind, onReady) => {
132 onWatch?.(watched)
133 return Stream.unwrap(Effect.gen(function*() {
134 const subscription = yield* PubSub.subscribe(events)
135 onReady()
136 return Stream.fromSubscription(subscription)
137 })).pipe(
138 Stream.map(({ file, tag }): FileSystem.WatchEvent | undefined => {
139 if (file === watched) return { _tag: tag, path: path.basename(watched) }
140 const relative = path.relative(watched, file)
141 return relative.startsWith("..") || path.isAbsolute(relative) ? undefined : { _tag: tag, path: relative }
142 }),
143 Stream.filter((event): event is FileSystem.WatchEvent => event !== undefined)
144 )
145 }
146 const fiber = yield* Watch.run({ configPath, watch }).pipe(Effect.forkScoped)
147 return {
148 emit: (file: string, tag: "Create" | "Update" = "Update") => PubSub.publish(events, { file, tag }),
149 waitFor: (
150 description: string,
151 done: (out: Output) => boolean
152 ) => waitFor(fiber, description, done),
153 waitForCycle: (count: number) =>
154 waitFor(fiber, `cycle ${count}`, (out) => cycles(out).length >= count).pipe(
155 Effect.map((out) => {
156 assert.strictEqual(cycles(out).length, count, show(out))
157 return cycles(out)[count - 1]
158 })
159 )
160 }
161 })
162
163 describe("graphqlgen --watch", () => {
164 it.effect(
165 "removing a subtree during nested discovery does not block initial generation",
166 () =>
167 Effect.gen(function*() {
168 const fs = yield* FileSystem.FileSystem
169 const path = yield* Path.Path
170 const p = yield* project({ "src/a.graphql": query("A", "id") })
171 const parent = p.file("src/c")
172 const nested = p.file("src/c/d")
173 yield* fs.makeDirectory(parent)
174 const scanningParent = yield* Deferred.make<void>()
175 const releaseParent = yield* Deferred.make<void>()
176 const scanningNested = yield* Deferred.make<void>()
177 const initialScanFoundNested = yield* Deferred.make<void>()
178 const discoveryCancelled = yield* Deferred.make<void>()
179 const holdNested = yield* Deferred.make<void>()
180 const rootEvents = yield* PubSub.unbounded<FileSystem.WatchEvent>()
181 const parentEvents = yield* PubSub.unbounded<FileSystem.WatchEvent>()
182 let nestedStats = 0
183 const gatedFs: FileSystem.FileSystem = {
184 ...fs,
185 watch: (directory, options) =>
186 Stream.unwrap(Effect.gen(function*() {
187 const events = directory === parent ? parentEvents : rootEvents
188 const subscription = yield* PubSub.subscribe(events)
189 options?.onReady?.()
190 return Stream.fromSubscription(subscription)
191 })),
192 readDirectory: Effect.fnUntraced(function*(directory, options) {
193 if (directory === parent) {
194 yield* Deferred.succeed(scanningParent, undefined)
195 yield* Deferred.await(releaseParent)
196 } else if (directory === nested) {
197 yield* Deferred.succeed(scanningNested, undefined)
198 yield* Deferred.await(holdNested).pipe(
199 Effect.ensuring(Deferred.succeed(discoveryCancelled, undefined))
200 )
201 }
202 return yield* fs.readDirectory(directory, options)
203 }),
204 stat: (file) =>
205 fs.stat(file).pipe(Effect.tap(() => {
206 // The create handler stats D first; the initial scan discovers it second.
207 if (file === nested && ++nestedStats === 2) {
208 return Deferred.succeed(initialScanFoundNested, undefined)
209 }
210 return Effect.void
211 }))
212 }
213 const fiber = yield* Watch.run({
214 configPath: p.configPath,
215 watch: Watch.fileSystemWatch(gatedFs, path)
216 }).pipe(Effect.forkScoped)
217
218 // C owns discovery of D while the initial tree scan is still visiting C.
219 yield* Deferred.await(scanningParent)
220 yield* fs.makeDirectory(nested)
221 yield* PubSub.publish(parentEvents, { _tag: "Create", path: "d" } as FileSystem.WatchEvent)
222 yield* Deferred.await(scanningNested)
223 yield* Deferred.succeed(releaseParent, undefined)
224 yield* Deferred.await(initialScanFoundNested)
225 yield* Effect.yieldNow
226 assert.deepStrictEqual(cycles(yield* output), [], "generation ran before subtree discovery completed")
227
228 // The root stays alive, but removing C cancels the owner of D's discovery.
229 yield* fs.remove(parent, { recursive: true })
230 yield* PubSub.publish(rootEvents, { _tag: "Remove", path: "c" } as FileSystem.WatchEvent)
231 yield* Deferred.await(discoveryCancelled)
232 yield* waitFor(
233 fiber,
234 "initial generation after nested discovery was cancelled",
235 (out) => cycles(out).length > 0 && existsSync(p.file("src/a.graphql.ts"))
236 )
237 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
238 15_000
239 )
240
241 it.effect(
242 "a document replaced during the installation gap is regenerated without another edit",
243 () =>
244 Effect.gen(function*() {
245 const fs = yield* FileSystem.FileSystem
246 const p = yield* project({ "src/a.graphql": query("A", "id") })
247 const installing = yield* Deferred.make<void>()
248 const release = yield* Deferred.make<void>()
249 const installed = yield* Deferred.make<void>()
250 const events = yield* PubSub.unbounded<FileSystem.WatchEvent>()
251 const watch: Parameters<typeof Watch.run>[0]["watch"] = (watched, _kind, onReady) =>
252 Stream.unwrap(Effect.gen(function*() {
253 if (watched === p.file("src")) {
254 yield* Deferred.succeed(installing, undefined)
255 yield* Deferred.await(release)
256 }
257 // Acquiring the subscription, not constructing the stream, installs this watcher.
258 const subscription = yield* PubSub.subscribe(events)
259 onReady()
260 if (watched === p.file("src")) {
261 yield* Deferred.succeed(installed, undefined)
262 }
263 return Stream.fromSubscription(subscription)
264 }))
265 const fiber = yield* Watch.run({ configPath: p.configPath, watch }).pipe(Effect.forkScoped)
266 yield* Deferred.await(installing)
267 const initial = yield* generated(p.dir, p.file("src/a.graphql.ts"))
268 yield* TestClock.adjust("200 millis")
269 yield* liveSleep(100)
270 assert.isUndefined(fiber.pollUnsafe(), "the watch loop exited before installation")
271 assert.deepStrictEqual(cycles(yield* output), [], "generation ran before document watcher installation")
272 assert.isFalse(yield* exists(p.file("src/a.graphql.ts")))
273
274 // An editor saves while no document subscription exists. No event is replayed on installation.
275 yield* write(p.dir, { "src/a.tmp": query("A", "id", "name") })
276 yield* fs.rename(p.file("src/a.tmp"), p.file("src/a.graphql"))
277 const expected = yield* generated(p.dir, p.file("src/a.graphql.ts"))
278 assert.notStrictEqual(initial, expected)
279 yield* Deferred.succeed(release, undefined)
280 yield* Deferred.await(installed)
281
282 yield* waitFor(
283 fiber,
284 "the installation-gap replacement output without another edit",
285 () => existsSync(p.file("src/a.graphql.ts")) && readFileSync(p.file("src/a.graphql.ts"), "utf8") === expected
286 )
287 assert.strictEqual(yield* read(p.file("src/a.graphql.ts")), expected)
288 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
289 15_000
290 )
291
292 it.effect("a document root created during watch installation stays watched", () =>
293 Effect.gen(function*() {
294 const p = yield* project({})
295 let created = false
296 const loop = yield* start(p.configPath, (watched) => {
297 if (watched !== p.file("src") || created) return
298 created = true
299 // Appear after target selection, before installation, without emitting an event.
300 mkdirSync(p.file("src"))
301 writeFileSync(p.file("src/a.graphql"), query("A", "id"))
302 })
303 // The reconcile cycle replaces the pending watcher with a tree watcher on the new root.
304 // It needs no event, so it can land before the initial cycle is observed.
305 const reconciled = yield* loop.waitFor("the reconcile cycle", (out) => cycles(out).length >= 2)
306 assert.deepStrictEqual(
307 cycles(reconciled),
308 ["regenerated 2 files, deleted 0", "regenerated 0 files, deleted 0"],
309 show(reconciled)
310 )
311 assert.isTrue(existsSync(p.file("src/a.graphql.ts")))
312
313 yield* write(p.dir, { "src/a.graphql": query("A", "id", "name") })
314 yield* loop.emit(p.file("src/a.graphql"))
315 yield* loop.waitForCycle(3)
316 assert.strictEqual(yield* read(p.file("src/a.graphql.ts")), yield* generated(p.dir, p.file("src/a.graphql.ts")))
317 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)))
318
319 it.effect("a document root created after startup is watched", () =>
320 Effect.gen(function*() {
321 const p = yield* project({})
322 const loop = yield* start(p.configPath)
323 yield* loop.waitForCycle(1)
324
325 yield* write(p.dir, { "src/a.graphql": query("A", "id") })
326 yield* loop.emit(p.file("src"), "Create")
327 yield* loop.waitForCycle(2)
328 assert.strictEqual(yield* read(p.file("src/a.graphql.ts")), yield* generated(p.dir, p.file("src/a.graphql.ts")))
329 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)))
330
331 it.effect("an error cycle reports diagnostics without replacing the last good output", () =>
332 Effect.gen(function*() {
333 const p = yield* project({ "src/a.graphql": query("A", "id") })
334 const loop = yield* start(p.configPath)
335 yield* loop.waitForCycle(1)
336 const good = yield* read(p.file("src/a.graphql.ts"))
337
338 yield* write(p.dir, { "src/a.graphql": query("A", "nope") })
339 yield* loop.emit(p.file("src/a.graphql"))
340 const failed = yield* loop.waitFor(
341 "the error diagnostic",
342 (out) => out.stderr.some((line) => line.includes(`src/a.graphql:3:5: error: Cannot query field "nope"`))
343 )
344 assert.strictEqual(cycles(failed).length, 1, show(failed))
345 assert.strictEqual(yield* read(p.file("src/a.graphql.ts")), good)
346 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)))
347
348 it.effect("an invalid config edit keeps the previous config active", () =>
349 Effect.gen(function*() {
350 const fs = yield* FileSystem.FileSystem
351 const p = yield* project({ "src/a.graphql": query("A", "id") })
352 const loop = yield* start(p.configPath)
353 yield* loop.waitForCycle(1)
354
355 yield* write(p.dir, { "graphql.config.ts": configSource({ ...config, documents: "src/**/*.graphql" }) })
356 yield* fs.utimes(p.configPath, 1_000, 1_000)
357 yield* loop.emit(p.configPath)
358 yield* loop.waitFor("the config error", (out) => out.stderr.some((line) => line.includes("not a valid config")))
359
360 yield* write(p.dir, { "src/a.graphql": query("A", "id", "name") })
361 yield* loop.emit(p.file("src/a.graphql"))
362 assert.strictEqual(yield* loop.waitForCycle(2), "regenerated 1 file, deleted 0")
363 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)))
364
365 it.effect("a burst of document events runs one debounced cycle", () =>
366 Effect.gen(function*() {
367 const p = yield* project({ "src/a.graphql": query("A", "id") })
368 const loop = yield* start(p.configPath)
369 yield* loop.waitForCycle(1)
370
371 yield* write(p.dir, { "src/a.graphql": query("A", "id", "name") })
372 for (let i = 0; i < 3; i++) {
373 yield* loop.emit(p.file("src/a.graphql"))
374 yield* liveSleep(25)
375 yield* TestClock.adjust("20 millis")
376 }
377 yield* liveSleep(100)
378 assert.strictEqual(cycles(yield* output).length, 1, "a cycle ran within 20 ms of the last event")
379
380 yield* loop.waitForCycle(2)
381 yield* TestClock.adjust("200 millis")
382 yield* liveSleep(100)
383 assert.deepStrictEqual(cycles(yield* output), ["regenerated 2 files, deleted 0", "regenerated 1 file, deleted 0"])
384 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)))
385
386 it.live(
387 "real watchers survive rename-over and in-place saves",
388 () =>
389 Effect.gen(function*() {
390 const fs = yield* FileSystem.FileSystem
391 const p = yield* project({ "src/a.graphql": query("A", "id") })
392 const main = (yield* Effect.promise(
393 () => import(new URL("../src/main.ts", import.meta.url).href)
394 )) as { readonly run: Effect.Effect<void, unknown, never> }
395 const fiber = yield* main.run.pipe(
396 Effect.provide(Layer.mergeAll(
397 TestConsole.layer,
398 CliOutput.layer(CliOutput.defaultFormatter({ colors: false })),
399 Stdio.layerTest({ args: Effect.succeed(["--config", p.configPath, "--watch"]) })
400 )),
401 Effect.forkScoped
402 )
403 const until = Effect.fnUntraced(
404 function*(description: string, done: Effect.Effect<boolean, unknown, FileSystem.FileSystem>) {
405 for (let attempt = 0; attempt < 300; attempt++) {
406 const exit = fiber.pollUnsafe()
407 if (exit !== undefined) {
408 const reason = Exit.isFailure(exit) ? Cause.pretty(exit.cause) : "it completed"
409 return assert.fail(`graphqlgen --watch exited while waiting for ${description}: ${reason}`)
410 }
411 if (yield* done) return
412 yield* Effect.sleep("50 millis")
413 }
414 return assert.fail(`timed out waiting for ${description}`)
415 }
416 )
417
418 yield* until("the first run", exists(p.file("src/a.graphql.ts")))
419 const untilOutput = Effect.fnUntraced(function*(description: string) {
420 const expected = yield* generated(p.dir, p.file("src/a.graphql.ts"))
421 yield* until(
422 description,
423 read(p.file("src/a.graphql.ts")).pipe(Effect.map((contents) => contents === expected))
424 )
425 })
426
427 yield* write(p.dir, { "src/a.tmp": query("A", "id", "name") })
428 yield* fs.rename(p.file("src/a.tmp"), p.file("src/a.graphql"))
429 yield* untilOutput("the rename-over output")
430
431 yield* write(p.dir, { "src/a.graphql": query("A", "id") })
432 yield* untilOutput("the in-place edited output")
433 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
434 30_000
435 )
436 })