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

main
ts 119 lines 4.59 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off - parent watches need native filename filtering and path resolution.
2 import * as NodeFS from "node:fs";
3 import * as NodePath from "node:path";
4
5 import { resolveSymlinkTarget } from "@t3tools/shared/symlink";
6 import * as Cause from "effect/Cause";
7 import * as Deferred from "effect/Deferred";
8 import * as Effect from "effect/Effect";
9 import * as FileSystem from "effect/FileSystem";
10 import * as Option from "effect/Option";
11 import * as Path from "effect/Path";
12 import * as PlatformError from "effect/PlatformError";
13 import * as Queue from "effect/Queue";
14 import * as Stream from "effect/Stream";
15
16 /** Buffer parent events before opening the child watch so a replacement cannot strand it. */
17 export const watchDirectoryReplacements = <R>(
18 watchParent: (ready: Deferred.Deferred<void>) => Stream.Stream<unknown, unknown>,
19 watchChild: Stream.Stream<void, never, R>,
20 ) =>
21 Stream.unwrap(
22 Effect.gen(function* () {
23 const ready = yield* Deferred.make<void>();
24 const replacements = yield* watchParent(ready).pipe(
25 Stream.ignoreCause({ log: true }),
26 Stream.ensuring(Deferred.succeed(ready, undefined)),
27 Stream.toQueue({ capacity: 1, strategy: "sliding" }),
28 );
29 yield* Deferred.await(ready);
30
31 return Stream.make(watchChild).pipe(
32 Stream.concat(Stream.fromQueue(replacements).pipe(Stream.as(watchChild))),
33 Stream.switchMap((events) => events),
34 );
35 }),
36 );
37
38 const watchDirectoryEntry = (path: string, ready: Deferred.Deferred<void>) => {
39 const directory = NodePath.dirname(path);
40 const name = NodePath.basename(path);
41 const watchError = (cause: unknown) =>
42 PlatformError.systemError({
43 _tag: "Unknown",
44 module: "FileSystem",
45 method: "watch",
46 pathOrDescriptor: directory,
47 cause,
48 });
49 // Filter in the native callback to avoid queueing and statting unrelated entries.
50 return Stream.callback<void, PlatformError.PlatformError>(
51 (events) =>
52 Effect.acquireRelease(
53 Effect.try({
54 try: () => {
55 const watcher = NodeFS.watch(directory, (_, filename) => {
56 if (filename === name || filename === null) Queue.offerUnsafe(events, undefined);
57 });
58 watcher.on("error", (error) =>
59 Queue.failCauseUnsafe(events, Cause.fail(watchError(error))),
60 );
61 watcher.on("close", () => Queue.endUnsafe(events));
62 return watcher;
63 },
64 catch: watchError,
65 }),
66 (watcher) => Effect.sync(() => watcher.close()),
67 ).pipe(Effect.tap(() => Deferred.succeed(ready, undefined))),
68 { bufferSize: 1, strategy: "sliding" },
69 );
70 };
71
72 // Node's JS realpath can collapse `..` before resolving a symlink in the preceding segment.
73 const realPath = (entry: string) =>
74 Effect.callback<string, NodeJS.ErrnoException>((resume) => {
75 NodeFS.realpath.native(entry, (error, resolved) => {
76 resume(error ? Effect.fail(error) : Effect.succeed(resolved));
77 });
78 });
79
80 const resolveWatchTarget = Effect.fn("watchDirectoryReplacements.resolveWatchTarget")(function* (
81 entry: string,
82 ) {
83 const fs = yield* FileSystem.FileSystem;
84 const path = yield* Path.Path;
85 const link = yield* fs.readLink(entry).pipe(Effect.option);
86 if (Option.isNone(link)) return entry;
87
88 const resolved = yield* realPath(entry).pipe(Effect.option);
89 if (Option.isSome(resolved)) return resolved.value;
90
91 // A dangling link needs a watch on the directory where its target should appear.
92 const rawTarget = path.isAbsolute(link.value)
93 ? link.value
94 : `${path.dirname(entry)}${path.sep}${link.value}`;
95 const parent = yield* realPath(path.dirname(rawTarget)).pipe(Effect.option);
96 const unresolved = Option.isSome(parent)
97 ? path.join(parent.value, path.basename(rawTarget))
98 : entry;
99 return yield* resolveSymlinkTarget(unresolved).pipe(Effect.orElseSucceed(() => unresolved));
100 });
101
102 /** Watch replacements of a configured directory, its symlink target, and the target's parent. */
103 export const watchDirectoryPath = (directory: string, watchChild: Stream.Stream<void>) => {
104 const entry = NodePath.resolve(directory);
105 return watchDirectoryReplacements(
106 (ready) => watchDirectoryEntry(entry, ready),
107 Stream.unwrap(
108 resolveWatchTarget(entry).pipe(
109 Effect.map((target) => {
110 if (target === entry) return watchChild;
111 return watchDirectoryReplacements(
112 (ready) => watchDirectoryEntry(NodePath.dirname(target), ready),
113 watchDirectoryReplacements((ready) => watchDirectoryEntry(target, ready), watchChild),
114 );
115 }),
116 ),
117 ),
118 );
119 };