t3code-session-manager 0.0.0-stage → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +21 -0
- package/.claude-plugin/plugin.json +19 -0
- package/CHANGELOG.md +149 -0
- package/LICENSE +21 -0
- package/README.md +661 -2
- package/README.pt.md +617 -0
- package/bin/entry.d.mts +2 -0
- package/bin/entry.mjs +19 -0
- package/bin/t3sm.mjs +44 -0
- package/commands/import.md +30 -0
- package/commands/organize.md +36 -0
- package/commands/status.md +24 -0
- package/commands/sync.md +26 -0
- package/dist/apply/apply.js +993 -0
- package/dist/apply/claudeWriter.js +168 -0
- package/dist/apply/copyTranscript.js +116 -0
- package/dist/apply/importer.js +697 -0
- package/dist/apply/materialize.js +335 -0
- package/dist/apply/waves.js +108 -0
- package/dist/assistant/core.js +295 -0
- package/dist/assistant/deps.js +256 -0
- package/dist/assistant/i18n.js +38 -0
- package/dist/assistant/messages.en.js +494 -0
- package/dist/assistant/messages.pt.js +495 -0
- package/dist/assistant/runner.js +64 -0
- package/dist/assistant/steps.js +1362 -0
- package/dist/build.json +1 -0
- package/dist/cli/applyScreen.js +158 -0
- package/dist/cli/commands/accounts.js +254 -0
- package/dist/cli/commands/apply.js +199 -0
- package/dist/cli/commands/changelog.js +61 -0
- package/dist/cli/commands/doctor.js +105 -0
- package/dist/cli/commands/help.js +158 -0
- package/dist/cli/commands/merge.js +224 -0
- package/dist/cli/commands/organize.js +872 -0
- package/dist/cli/commands/plan.js +161 -0
- package/dist/cli/commands/projects.js +430 -0
- package/dist/cli/commands/quarantine.js +203 -0
- package/dist/cli/commands/recover.js +230 -0
- package/dist/cli/commands/rollback.js +281 -0
- package/dist/cli/commands/scan.js +117 -0
- package/dist/cli/commands/schedule.js +288 -0
- package/dist/cli/commands/start.js +45 -0
- package/dist/cli/commands/status.js +615 -0
- package/dist/cli/commands/sync.js +336 -0
- package/dist/cli/commands/update.js +398 -0
- package/dist/cli/errors.js +53 -0
- package/dist/cli/failures.js +91 -0
- package/dist/cli/flags.js +53 -0
- package/dist/cli/help.en.js +549 -0
- package/dist/cli/help.pt.js +566 -0
- package/dist/cli/helpText.js +211 -0
- package/dist/cli/helpTopics.js +58 -0
- package/dist/cli/locked.js +12 -0
- package/dist/cli/main.js +155 -0
- package/dist/cli/screen.js +3 -0
- package/dist/cli/ui.js +111 -0
- package/dist/cli/words.js +2 -0
- package/dist/core/activity.js +16 -0
- package/dist/core/changelog.js +47 -0
- package/dist/core/config.js +530 -0
- package/dist/core/fsutil.js +171 -0
- package/dist/core/glob.js +34 -0
- package/dist/core/history.js +32 -0
- package/dist/core/journal.js +274 -0
- package/dist/core/lock.js +337 -0
- package/dist/core/mask.js +31 -0
- package/dist/core/paths.js +68 -0
- package/dist/core/pid.js +101 -0
- package/dist/core/run.js +4 -0
- package/dist/core/semver.js +18 -0
- package/dist/core/sysroot.js +29 -0
- package/dist/core/types.js +229 -0
- package/dist/core/uuid.js +29 -0
- package/dist/core/version.js +72 -0
- package/dist/help/convert.md +20 -0
- package/dist/help/convert.pt.md +21 -0
- package/dist/help/cwd-unreadable.md +22 -0
- package/dist/help/cwd-unreadable.pt.md +22 -0
- package/dist/help/decisions.md +20 -0
- package/dist/help/decisions.pt.md +20 -0
- package/dist/help/errors.md +20 -0
- package/dist/help/errors.pt.md +22 -0
- package/dist/help/held.md +20 -0
- package/dist/help/held.pt.md +20 -0
- package/dist/help/history.md +27 -0
- package/dist/help/history.pt.md +29 -0
- package/dist/help/instance-unavailable.md +18 -0
- package/dist/help/instance-unavailable.pt.md +19 -0
- package/dist/help/not-imported.md +19 -0
- package/dist/help/not-imported.pt.md +19 -0
- package/dist/help/orphaned.md +19 -0
- package/dist/help/orphaned.pt.md +19 -0
- package/dist/help/project-mismatch.md +15 -0
- package/dist/help/project-mismatch.pt.md +15 -0
- package/dist/help/t3-native.md +22 -0
- package/dist/help/t3-native.pt.md +22 -0
- package/dist/help/updates.md +26 -0
- package/dist/help/updates.pt.md +28 -0
- package/dist/help/watcher.md +24 -0
- package/dist/help/watcher.pt.md +25 -0
- package/dist/i18n/cli.js +41 -0
- package/dist/i18n/lang.js +55 -0
- package/dist/i18n/messages.en.js +1140 -0
- package/dist/i18n/messages.pt.js +1149 -0
- package/dist/i18n/words.js +12 -0
- package/dist/ops/accounts.js +170 -0
- package/dist/ops/autoUpdate.js +223 -0
- package/dist/ops/discoverAccounts.js +343 -0
- package/dist/ops/doctor.js +811 -0
- package/dist/ops/elevated.js +47 -0
- package/dist/ops/errorCodes.js +39 -0
- package/dist/ops/follow.js +558 -0
- package/dist/ops/merge.js +830 -0
- package/dist/ops/notify.js +249 -0
- package/dist/ops/plugin.js +92 -0
- package/dist/ops/projects.js +113 -0
- package/dist/ops/quarantine.js +415 -0
- package/dist/ops/rollback.js +868 -0
- package/dist/ops/schedule.js +464 -0
- package/dist/ops/successor.js +51 -0
- package/dist/ops/sync.js +859 -0
- package/dist/ops/syncStatus.js +290 -0
- package/dist/ops/update.js +273 -0
- package/dist/ops/updater.js +641 -0
- package/dist/ops/watch.js +676 -0
- package/dist/ops/watcherControl.js +212 -0
- package/dist/ops/watcherHealth.js +75 -0
- package/dist/organize/apply.js +495 -0
- package/dist/organize/history.js +192 -0
- package/dist/organize/plan.js +283 -0
- package/dist/organize/rename.js +58 -0
- package/dist/organize/sessions.js +100 -0
- package/dist/organize/titles.js +70 -0
- package/dist/organize/types.js +73 -0
- package/dist/plan/categories.js +104 -0
- package/dist/plan/dedupe.js +137 -0
- package/dist/plan/folders.js +82 -0
- package/dist/plan/names.js +93 -0
- package/dist/plan/ownership.js +316 -0
- package/dist/plan/planner.js +669 -0
- package/dist/plan/rehome.js +101 -0
- package/dist/plan/report.js +407 -0
- package/dist/sources/cache.js +89 -0
- package/dist/sources/claude.js +297 -0
- package/dist/sources/codex.js +496 -0
- package/dist/sources/flatten.js +23 -0
- package/dist/sources/jsonl.js +169 -0
- package/dist/sources/native.js +233 -0
- package/dist/sources/opencode.js +483 -0
- package/dist/sources/pi.js +133 -0
- package/dist/sources/registry.js +67 -0
- package/dist/sources/types.js +80 -0
- package/dist/t3/api.js +492 -0
- package/dist/t3/auth.js +248 -0
- package/dist/t3/compat.js +62 -0
- package/dist/t3/decode.js +408 -0
- package/dist/t3/errors.js +185 -0
- package/dist/t3/rpc.js +185 -0
- package/dist/t3/runtime.js +80 -0
- package/dist/ui/caps.js +56 -0
- package/dist/ui/components.js +202 -0
- package/dist/ui/layout.js +205 -0
- package/dist/ui/list.js +423 -0
- package/dist/ui/locale.js +73 -0
- package/dist/ui/organizePreview.js +72 -0
- package/dist/ui/progress.js +237 -0
- package/dist/ui/style.js +32 -0
- package/dist/ui/terminal.js +126 -0
- package/dist/ui/text.js +186 -0
- package/package.json +58 -4
- package/skills/t3code-sessions/SKILL.md +183 -0
|
@@ -0,0 +1,676 @@
|
|
|
1
|
+
// `t3sm sync --watch`: a resident loop around runSyncCycle.
|
|
2
|
+
//
|
|
3
|
+
// Scheduling (one timer armed at the earliest deadline):
|
|
4
|
+
// - a cycle at start, then a safety-net cycle every schedule.everyMinutes after each cycle;
|
|
5
|
+
// - a transcript event (*.jsonl, or an event without a file name) sets a debounced cycle at event + debounce (each
|
|
6
|
+
// new event pushes it back: bursts coalesce) and a follow-up at event + 10 min + debounce, because a session is
|
|
7
|
+
// importable only once it has been idle for ACTIVE_WINDOW_MS;
|
|
8
|
+
// - events during a cycle (our own file-time bumps, or a session being written) only schedule the follow-up;
|
|
9
|
+
// - T3 down or the lock held: retry in 60 s, the loop keeps running;
|
|
10
|
+
// - errors: back off 1, 2, 5, 10 min (cap); nothing runs earlier; a successful cycle resets it;
|
|
11
|
+
// - a directory that can only be polled adds a cycle every 60 s.
|
|
12
|
+
// Exactly one cycle runs at a time; deadlines falling due during a cycle run once right after it.
|
|
13
|
+
// SIGINT/SIGTERM: stop after the current cycle (applyPlan itself stops after the running wave), close the watchers,
|
|
14
|
+
// write a final heartbeat with stoppedAt. A stop request over the endpoint does the same, and reaches the running cycle
|
|
15
|
+
// like SIGTERM (withStopRequest): it stops after its current step instead of running to its end. Debounce-only cycles run at most once per max(debounce, 2 min). The
|
|
16
|
+
// heartbeat is rewritten after every cycle and whenever an event moves the next cycle (serialized writes).
|
|
17
|
+
// Single instance: acquireWatcherSingleton (named pipe / unix socket, released by the OS when the process ends).
|
|
18
|
+
// Updates: after every cycle that does not stop the loop, `afterCycle` runs the daily update check (src/ops/autoUpdate.ts),
|
|
19
|
+
// which starts any install in a separate detached process (the install stops this watcher).
|
|
20
|
+
// Version: the heartbeat names the watcher's version, install stamp and install root (src/core/version.ts). After every
|
|
21
|
+
// cycle the install root's stamp is read again; a different version or stamp (a newer t3sm was installed) stops the
|
|
22
|
+
// loop like a stop request, with `reason: "restart"` in the final heartbeat, then calls `restart` (the command releases
|
|
23
|
+
// the singleton and spawns a successor from the new install). A stamp that cannot be read never restarts (reported once).
|
|
24
|
+
//
|
|
25
|
+
// Watching: fs.watch recursive (native on Windows and macOS; on Linux Node >= 20 emulates it with one inotify watch
|
|
26
|
+
// per directory). Where recursive watching is unavailable (ERR_FEATURE_UNAVAILABLE_ON_PLATFORM) each directory down to
|
|
27
|
+
// depth 3 is watched on its own (Claude: projects/<dir>/; Codex: sessions/YYYY/MM/DD/), new directories picked up as
|
|
28
|
+
// they appear. If watching fails (inotify limit ENOSPC, EMFILE, EPERM, a watcher error) the directory falls back to
|
|
29
|
+
// polling: a cycle every 60 s (discovery is cached, so a quiet cycle is cheap).
|
|
30
|
+
|
|
31
|
+
import { watch as fsWatchReal, linkSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync, } from "node:fs";
|
|
32
|
+
import { chmod, lstat, mkdir, open, readFile, rm } from "node:fs/promises";
|
|
33
|
+
import { renameRetrying, } from "../core/fsutil.js";
|
|
34
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
35
|
+
import { connect, createServer, } from "node:net";
|
|
36
|
+
import { tmpdir } from "node:os";
|
|
37
|
+
import { dirname, join, resolve } from "node:path";
|
|
38
|
+
import { ACTIVE_WINDOW_MS } from "../sources/types.js";
|
|
39
|
+
import { STOP_SIGNALS, } from "../apply/apply.js";
|
|
40
|
+
import { resultSummary, } from "./sync.js";
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
export const RETRY_MS = 60_000;
|
|
44
|
+
export const POLL_MS = 60_000;
|
|
45
|
+
export const BACKOFF_MS = [60_000, 120_000, 300_000, 600_000];
|
|
46
|
+
/** Debounce-only cycles run at most once per max(debounce, this). */
|
|
47
|
+
export const DEBOUNCE_MIN_GAP_MS = 120_000;
|
|
48
|
+
const TIMER_MAX = 2_147_483_647;
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
export const realClock = {
|
|
57
|
+
now: () => Date.now(),
|
|
58
|
+
setTimer: (fn, ms) => setTimeout(fn, Math.min(Math.max(0, ms), TIMER_MAX)),
|
|
59
|
+
clearTimer: (h) => clearTimeout(h ),
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
const isTranscript = (f ) => f === null || /\.jsonl$/i.test(f);
|
|
120
|
+
|
|
121
|
+
export function startWatch(deps ) {
|
|
122
|
+
const { clock } = deps;
|
|
123
|
+
const iso = (t ) => (t === null ? null : new Date(t).toISOString());
|
|
124
|
+
const watchers = new Map ();
|
|
125
|
+
const hb = { pid: deps.pid, startedAt: new Date(clock.now()).toISOString(), lastCycleAt: null, lastResult: null, nextCycleAt: null, protocol: 1, ...(deps.socket !== undefined ? { socket: deps.socket } : {}) };
|
|
126
|
+
if (deps.install) { hb.version = deps.install.stamp.version; hb.stamp = deps.install.stamp.stamp; hb.installRoot = deps.install.root; }
|
|
127
|
+
else if (deps.version !== undefined) hb.version = deps.version;
|
|
128
|
+
/** Set when the install changed: the loop stops after this cycle and restarts into it. */
|
|
129
|
+
let restartInto = null;
|
|
130
|
+
let stampFailing = false;
|
|
131
|
+
const installChanged = async () => {
|
|
132
|
+
const inst = deps.install;
|
|
133
|
+
if (!inst) return null;
|
|
134
|
+
let cur ;
|
|
135
|
+
try { cur = await inst.read(); } catch (e) {
|
|
136
|
+
if (!stampFailing) { stampFailing = true; try { deps.onStampError?.(e); } catch { /* ignore */ } }
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
stampFailing = false;
|
|
140
|
+
if (cur.version === inst.stamp.version && cur.stamp === inst.stamp.stamp) return null;
|
|
141
|
+
// A new install still being written (or just written) waits for the next cycle.
|
|
142
|
+
try { if (inst.ready && !(await inst.ready())) return null; } catch { return null; }
|
|
143
|
+
return cur;
|
|
144
|
+
};
|
|
145
|
+
let timer = null;
|
|
146
|
+
let nextAt = null;
|
|
147
|
+
let running = false;
|
|
148
|
+
let eventsDuringCycle = false;
|
|
149
|
+
let stopping = false;
|
|
150
|
+
let errors = 0;
|
|
151
|
+
let blockedUntil = 0;
|
|
152
|
+
const due = { safety: clock.now() , debounce: null , followUp: null , cycleFollowUp: null , retry: null , poll: null };
|
|
153
|
+
let resolveDone ;
|
|
154
|
+
const done = new Promise ((r) => { resolveDone = r; });
|
|
155
|
+
|
|
156
|
+
const beat = async () => {
|
|
157
|
+
hb.nextCycleAt = stopping ? null : iso(nextAt);
|
|
158
|
+
const snapshot = { ...hb };
|
|
159
|
+
// Serialized: a re-arm beat and a cycle-end beat never write concurrently (the last one wins, in order).
|
|
160
|
+
beats = beats.then(async () => { try { await deps.writeHeartbeat(snapshot); } catch { /* best effort */ } });
|
|
161
|
+
await beats;
|
|
162
|
+
};
|
|
163
|
+
let beats = Promise.resolve();
|
|
164
|
+
let lastBeatNext = null;
|
|
165
|
+
/** A re-arm moved the next cycle: tell the heartbeat (only when it changed; never while a cycle runs). */
|
|
166
|
+
const beatIfMoved = () => {
|
|
167
|
+
if (running || stopping || nextAt === lastBeatNext) return;
|
|
168
|
+
lastBeatNext = nextAt;
|
|
169
|
+
void beat();
|
|
170
|
+
};
|
|
171
|
+
/** Start of the last cycle a debounce deadline triggered (rate limit for debounce-only cycles). */
|
|
172
|
+
let lastDebounceCycle = -Infinity;
|
|
173
|
+
const debounceGap = Math.max(deps.debounceMs, DEBOUNCE_MIN_GAP_MS);
|
|
174
|
+
|
|
175
|
+
const arm = () => {
|
|
176
|
+
if (timer !== null) { clock.clearTimer(timer); timer = null; }
|
|
177
|
+
nextAt = null;
|
|
178
|
+
if (stopping) return;
|
|
179
|
+
const times = Object.values(due).filter((t) => t !== null);
|
|
180
|
+
if (times.length === 0) return;
|
|
181
|
+
nextAt = Math.max(Math.min(...times), blockedUntil);
|
|
182
|
+
timer = clock.setTimer(fire, nextAt - clock.now());
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
const fire = () => {
|
|
186
|
+
timer = null;
|
|
187
|
+
if (stopping) return;
|
|
188
|
+
const t = clock.now();
|
|
189
|
+
if (running) return; // never armed while a cycle runs; runCycle re-arms when it ends
|
|
190
|
+
if (due.debounce !== null && due.debounce <= t) lastDebounceCycle = t;
|
|
191
|
+
for (const k of Object.keys(due) ) if (due[k] !== null && due[k] <= t) due[k] = null;
|
|
192
|
+
void runCycle();
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
const onEvent = (file ) => {
|
|
196
|
+
if (stopping || !isTranscript(file)) return;
|
|
197
|
+
if (running) { eventsDuringCycle = true; return; }
|
|
198
|
+
const t = clock.now();
|
|
199
|
+
// Trailing debounce, but at most one debounce-triggered cycle per max(debounce, 2 min): a session written every
|
|
200
|
+
// few seconds for hours must not turn into a cycle every 30 s.
|
|
201
|
+
due.debounce = Math.max(t + deps.debounceMs, lastDebounceCycle + debounceGap);
|
|
202
|
+
due.followUp = t + ACTIVE_WINDOW_MS + deps.debounceMs;
|
|
203
|
+
arm();
|
|
204
|
+
beatIfMoved();
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
const syncWatchers = async () => {
|
|
208
|
+
let dirs ;
|
|
209
|
+
try { dirs = await deps.dirs(); } catch { return; }
|
|
210
|
+
const want = new Set(dirs);
|
|
211
|
+
for (const [d, w] of watchers) {
|
|
212
|
+
if (!want.has(d) || w.mode === "poll") { w.close(); watchers.delete(d); }
|
|
213
|
+
}
|
|
214
|
+
for (const d of dirs) {
|
|
215
|
+
if (stopping || watchers.has(d)) continue;
|
|
216
|
+
try { watchers.set(d, deps.watch(d, onEvent)); } catch { watchers.set(d, { mode: "poll", close() {} }); }
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
const runCycle = async () => {
|
|
221
|
+
running = true;
|
|
222
|
+
eventsDuringCycle = false;
|
|
223
|
+
let o ;
|
|
224
|
+
try { o = await deps.cycle(); } catch (e) { o = { kind: "error", exitCode: 1, error: e }; }
|
|
225
|
+
const t = clock.now();
|
|
226
|
+
hb.lastCycleAt = new Date(t).toISOString();
|
|
227
|
+
hb.lastResult = resultSummary(o);
|
|
228
|
+
due.safety = t + deps.everyMinutes * 60_000;
|
|
229
|
+
due.retry = null;
|
|
230
|
+
if (o.kind === "error") {
|
|
231
|
+
errors++;
|
|
232
|
+
blockedUntil = t + BACKOFF_MS[Math.min(errors, BACKOFF_MS.length) - 1] ;
|
|
233
|
+
due.retry = blockedUntil;
|
|
234
|
+
} else {
|
|
235
|
+
errors = 0;
|
|
236
|
+
blockedUntil = 0;
|
|
237
|
+
if (o.kind === "t3-down" || o.kind === "locked") due.retry = t + RETRY_MS;
|
|
238
|
+
}
|
|
239
|
+
// A follow-up that fell due during the cycle stays due (the session was still active when the cycle started).
|
|
240
|
+
if (eventsDuringCycle) due.cycleFollowUp = t + ACTIVE_WINDOW_MS + deps.debounceMs;
|
|
241
|
+
try { await deps.onCycle?.(o, t); } catch { /* logging never stops the loop */ }
|
|
242
|
+
if (!stopping) {
|
|
243
|
+
restartInto = await installChanged();
|
|
244
|
+
if (restartInto) stopping = true; // a newer install: stop like a stop request, then restart into it
|
|
245
|
+
}
|
|
246
|
+
if (!stopping && deps.afterCycle) { try { await deps.afterCycle(() => stopping); } catch { /* never stops the loop */ } }
|
|
247
|
+
if (!stopping) await syncWatchers();
|
|
248
|
+
due.poll = [...watchers.values()].some((w) => w.mode === "poll") ? t + POLL_MS : null;
|
|
249
|
+
running = false;
|
|
250
|
+
if (stopping) { await finish(); return; }
|
|
251
|
+
arm();
|
|
252
|
+
lastBeatNext = nextAt;
|
|
253
|
+
await beat();
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
let finished = false;
|
|
257
|
+
const finish = async () => {
|
|
258
|
+
if (finished) return;
|
|
259
|
+
finished = true;
|
|
260
|
+
if (timer !== null) { clock.clearTimer(timer); timer = null; }
|
|
261
|
+
for (const w of watchers.values()) { try { w.close(); } catch { /* ignore */ } }
|
|
262
|
+
watchers.clear();
|
|
263
|
+
for (const s of STOP_SIGNALS) deps.signals.off(s, stop);
|
|
264
|
+
hb.stoppedAt = new Date(clock.now()).toISOString();
|
|
265
|
+
if (restartInto) hb.reason = "restart";
|
|
266
|
+
nextAt = null;
|
|
267
|
+
await beat();
|
|
268
|
+
if (restartInto && deps.restart) { try { await deps.restart(restartInto); } catch { /* the keep-alive trigger or the next logon starts one */ } }
|
|
269
|
+
resolveDone();
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
function stop() {
|
|
273
|
+
if (stopping) return;
|
|
274
|
+
stopping = true;
|
|
275
|
+
if (timer !== null) { clock.clearTimer(timer); timer = null; }
|
|
276
|
+
if (!running) void finish();
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
for (const s of STOP_SIGNALS) deps.signals.on(s, stop); // SIGHUP: the console window closed
|
|
280
|
+
void (async () => {
|
|
281
|
+
await syncWatchers();
|
|
282
|
+
if (stopping) { await finish(); return; }
|
|
283
|
+
due.poll = [...watchers.values()].some((w) => w.mode === "poll") ? clock.now() + POLL_MS : null;
|
|
284
|
+
arm();
|
|
285
|
+
lastBeatNext = nextAt;
|
|
286
|
+
await beat();
|
|
287
|
+
})();
|
|
288
|
+
return { done, stop };
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* The watcher's stop sources in one: the process signals of `base`, plus a stop request over the endpoint (`fire`).
|
|
293
|
+
* `fire` reaches every SIGTERM listener as if the process had been sent SIGTERM once, so a running cycle (applyPlan's
|
|
294
|
+
* waves, organize, follow, merge) stops after its current step exactly as on Ctrl+C, instead of running to its end
|
|
295
|
+
* while the client waits and finally kills it. After `fire`, a listener registered later (a step that starts after the
|
|
296
|
+
* request) is called at once: it never starts work the request already stopped.
|
|
297
|
+
*/
|
|
298
|
+
export function withStopRequest(base ) {
|
|
299
|
+
const term = new Set ();
|
|
300
|
+
let fired = false;
|
|
301
|
+
return {
|
|
302
|
+
on(sig, fn) {
|
|
303
|
+
base.on(sig, fn);
|
|
304
|
+
if (sig !== "SIGTERM") return;
|
|
305
|
+
term.add(fn);
|
|
306
|
+
if (fired) fn();
|
|
307
|
+
},
|
|
308
|
+
off(sig, fn) {
|
|
309
|
+
base.off(sig, fn);
|
|
310
|
+
if (sig === "SIGTERM") term.delete(fn);
|
|
311
|
+
},
|
|
312
|
+
fire() {
|
|
313
|
+
if (fired) return;
|
|
314
|
+
fired = true;
|
|
315
|
+
for (const fn of [...term]) { try { fn(); } catch { /* a listener never stops the others */ } }
|
|
316
|
+
},
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// ---------- single instance ----------
|
|
321
|
+
|
|
322
|
+
/** The two file operations behind the persisted directory suffix; tests inject an in-memory one. Both may throw. */
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
export const realSuffixIo = {
|
|
330
|
+
read: (file) => readFileSync(file, "utf8"),
|
|
331
|
+
create(file, content) {
|
|
332
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
333
|
+
// A random temp name: a leftover from a crashed process whose pid is reused would otherwise fail `wx` forever.
|
|
334
|
+
const tmp = `${file}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
335
|
+
writeFileSync(tmp, content, { mode: 0o600, flag: "wx" });
|
|
336
|
+
try { linkSync(tmp, file); } catch (e) { if ((e ).code !== "EEXIST") throw e; } finally { try { unlinkSync(tmp); } catch { /* ignore */ } }
|
|
337
|
+
},
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
/** Where the POSIX fallback socket directory comes from; tests inject it (this host may not be POSIX). */
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
const SUFFIX_FILE = "socket-dir-suffix";
|
|
350
|
+
const SUFFIX_RE = /^[0-9a-f]{16}$/;
|
|
351
|
+
|
|
352
|
+
/** Per process and per SuffixIo: state dir -> suffix. Computed once, so a later transient failure cannot change the address. */
|
|
353
|
+
const suffixCache = new WeakMap ();
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* The persisted unguessable part of the fallback directory name: 16 random hex chars, created once in
|
|
357
|
+
* <state>/socket-dir-suffix (0600, atomic, no clobber), read back, and cached for the life of the process. A missing
|
|
358
|
+
* file is created; ANY other failure (unreadable, not creatable, malformed content) throws SocketDirSuffixError:
|
|
359
|
+
* silently using another name would give two processes two different addresses (two watchers, or a stop that
|
|
360
|
+
* misses). A corrupt file is never overwritten.
|
|
361
|
+
*/
|
|
362
|
+
function socketDirSuffix(stateDir , io ) {
|
|
363
|
+
const file = join(stateDir, SUFFIX_FILE);
|
|
364
|
+
let cache = suffixCache.get(io);
|
|
365
|
+
if (!cache) suffixCache.set(io, (cache = new Map()));
|
|
366
|
+
const hit = cache.get(file);
|
|
367
|
+
if (hit !== undefined) return hit;
|
|
368
|
+
const read = () => {
|
|
369
|
+
const v = io.read(file).trim();
|
|
370
|
+
if (!SUFFIX_RE.test(v)) throw new SocketDirSuffixError(file, "its content is not a 16-character hex suffix");
|
|
371
|
+
return v;
|
|
372
|
+
};
|
|
373
|
+
const fail = (e ) => {
|
|
374
|
+
if (e instanceof SocketDirSuffixError) throw e;
|
|
375
|
+
throw new SocketDirSuffixError(file, (e ).code ?? (e instanceof Error ? e.message : String(e)));
|
|
376
|
+
};
|
|
377
|
+
let v ;
|
|
378
|
+
try {
|
|
379
|
+
try { v = read(); } catch (e) {
|
|
380
|
+
if ((e ).code !== "ENOENT") throw e;
|
|
381
|
+
io.create(file, `${randomBytes(8).toString("hex")}
|
|
382
|
+
`);
|
|
383
|
+
v = read(); // a concurrent creator may have won: always use what is on disk
|
|
384
|
+
}
|
|
385
|
+
} catch (e) { return fail(e); }
|
|
386
|
+
cache.set(file, v);
|
|
387
|
+
return v;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* The directory of the POSIX fallback socket (the state path is too long for a socket): `<tmp>/t3sm-<uid>-<suffix>`
|
|
392
|
+
* with a random suffix persisted in the state dir, so another local user cannot guess (and pre-create) it. Verified
|
|
393
|
+
* (and created 0700) by checkSocketDir before the socket is bound. If the suffix cannot be read or created it throws
|
|
394
|
+
* SocketDirSuffixError (there is no second name: see socketDirSuffix). It deliberately does NOT depend on the
|
|
395
|
+
* environment (no XDG_RUNTIME_DIR): the keep-alive cron job, a login shell and launchd run with different
|
|
396
|
+
* environments and must all compute the same address, or two watchers could run and `stop` would probe the wrong one.
|
|
397
|
+
* Every caller passes the same state dir.
|
|
398
|
+
*/
|
|
399
|
+
export function fallbackSocketDir(stateDir , o = {}) {
|
|
400
|
+
const uid = "uid" in o ? o.uid : process.getuid?.();
|
|
401
|
+
return join(o.tmp ?? tmpdir(), `t3sm-${uid ?? "user"}-${socketDirSuffix(stateDir, o.suffixIo ?? realSuffixIo)}`);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* The watcher's single-instance endpoint, derived from the state dir: a named pipe on Windows, a unix socket in the
|
|
406
|
+
* state dir elsewhere (in a per-user 0700 directory under the temp dir, see fallbackSocketDir, when that path would
|
|
407
|
+
* pass the ~100-byte socket path limit). The same for every caller, whatever its environment.
|
|
408
|
+
*/
|
|
409
|
+
export function singletonAddress(stateDir , platform = process.platform, o = {}) {
|
|
410
|
+
const h = createHash("sha1").update(resolve(stateDir)).digest("hex").slice(0, 12);
|
|
411
|
+
if (platform === "win32") return `\\\\.\\pipe\\t3sm-watcher-${h}`;
|
|
412
|
+
const inState = join(stateDir, "watcher.sock");
|
|
413
|
+
return Buffer.byteLength(inState) <= 100 ? inState : join(fallbackSocketDir(stateDir, o), `watcher-${h}.sock`);
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* 0.2.1 put the fallback socket directly in the temp dir (<tmp>/t3sm-watcher-<h>.sock). A 0.2.1 watcher may still be
|
|
418
|
+
* running there after an upgrade, so that address is probed too. null when the state path does not need the fallback
|
|
419
|
+
* (and on Windows, where the pipe name never changed).
|
|
420
|
+
*/
|
|
421
|
+
export function legacySingletonAddress(stateDir , platform = process.platform, o = {}) {
|
|
422
|
+
if (platform === "win32") return null;
|
|
423
|
+
if (Buffer.byteLength(join(stateDir, "watcher.sock")) <= 100) return null; // the socket lives in the state dir
|
|
424
|
+
return join(o.tmp ?? tmpdir(), `t3sm-watcher-${createHash("sha1").update(resolve(stateDir)).digest("hex").slice(0, 12)}.sock`);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/** The fallback socket directory failed checkSocketDir: starting the watcher there is refused (typed, so callers can word it). */
|
|
428
|
+
export class UnsafeSocketDirError extends Error {
|
|
429
|
+
dir ;
|
|
430
|
+
constructor(dir , message ) {
|
|
431
|
+
super(message ?? `the socket directory ${dir} is not safe (it must be a real directory owned by you with mode 0700, no group or other access). `
|
|
432
|
+
+ `Remove or fix it (for example chmod 700 ${dir}), or use a state directory whose path is under 100 bytes. The watcher was not started.`);
|
|
433
|
+
this.name = "UnsafeSocketDirError";
|
|
434
|
+
this.dir = dir;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** The persisted directory suffix could not be read or created: there is no safe address, so nothing is bound (dir = the suffix file). */
|
|
439
|
+
export class SocketDirSuffixError extends UnsafeSocketDirError {
|
|
440
|
+
constructor(file , why ) {
|
|
441
|
+
super(file, `the socket directory suffix file ${file} cannot be used (${why}). The watcher needs it to compute its address, `
|
|
442
|
+
+ `so it was not started. Fix or remove that file (it is recreated when missing), or use a state directory whose path is under 100 bytes.`);
|
|
443
|
+
this.name = "SocketDirSuffixError";
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** What a legacy (0.2.1) socket must be before a live one counts as "a 0.2.1 watcher": ours, a real socket, not a link. */
|
|
448
|
+
|
|
449
|
+
export async function checkLegacySocket(addr , fs , uid ) {
|
|
450
|
+
try {
|
|
451
|
+
const st = await fs.lstat(addr);
|
|
452
|
+
return !st.isSymbolicLink() && st.isSocket() && (uid === undefined || st.uid === uid);
|
|
453
|
+
} catch { return false; }
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** The fallback directory must be ours alone: a pre-planted or symlinked directory in /tmp must never carry the socket. */
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
/*
|
|
462
|
+
* Accepted TOCTOU: the directory could in theory be swapped between this check and the bind. Nobody but us can do it:
|
|
463
|
+
* it must be owned by this user and 0700, so no other user can create, rename or replace entries in it (replacing the
|
|
464
|
+
* directory itself needs write access to its parent: the same user, or root). A bind onto anything unexpected fails
|
|
465
|
+
* (EADDRINUSE / EACCES) and the watcher does not start: fail safe.
|
|
466
|
+
*/
|
|
467
|
+
export async function checkSocketDir(dir , fs , uid ) {
|
|
468
|
+
try {
|
|
469
|
+
try { await fs.lstat(dir); } catch (e) {
|
|
470
|
+
if ((e ).code !== "ENOENT") return false;
|
|
471
|
+
await fs.mkdir(dir, { mode: 0o700 });
|
|
472
|
+
}
|
|
473
|
+
const st = await fs.lstat(dir);
|
|
474
|
+
return !st.isSymbolicLink() && st.isDirectory() && (uid === undefined || st.uid === uid) && (st.mode & 0o077) === 0;
|
|
475
|
+
} catch { return false; }
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/** The shared secret a stop request must carry; written by the running watcher, read by the client (same user). */
|
|
479
|
+
export const watcherTokenPath = (stateDir ) => join(stateDir, "watcher.token");
|
|
480
|
+
|
|
481
|
+
/** What the endpoint does with a request: `stop <token>` with the right token answers ok and calls onStop. */
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
/** The socket operations acquireWatcherSingleton needs (tests inject a fake). */
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
const safeEqual = (a , b ) => {
|
|
504
|
+
const x = Buffer.from(a);
|
|
505
|
+
const y = Buffer.from(b);
|
|
506
|
+
return x.length === y.length && timingSafeEqual(x, y);
|
|
507
|
+
};
|
|
508
|
+
|
|
509
|
+
export const realSingletonNet = {
|
|
510
|
+
listen: (addr, ctl) => new Promise((ok, fail) => {
|
|
511
|
+
// Protocol: one line `stop <token>` -> "ok", then onStop(). Anything else (or silence) -> the socket is destroyed.
|
|
512
|
+
const srv = createServer((sock) => {
|
|
513
|
+
let buf = "";
|
|
514
|
+
sock.setTimeout(2000, () => sock.destroy());
|
|
515
|
+
sock.on("error", () => sock.destroy());
|
|
516
|
+
sock.on("data", (c) => {
|
|
517
|
+
buf += c.toString("utf8");
|
|
518
|
+
const nl = buf.indexOf("\n");
|
|
519
|
+
if (nl < 0) { if (buf.length > 128) sock.destroy(); return; }
|
|
520
|
+
const tok = ctl?.token() ?? null;
|
|
521
|
+
if (ctl && tok !== null && safeEqual(buf.slice(0, nl), `stop ${tok}`)) {
|
|
522
|
+
sock.end("ok\n", () => { try { ctl.onStop(); } catch { /* ignore */ } });
|
|
523
|
+
} else sock.destroy();
|
|
524
|
+
});
|
|
525
|
+
});
|
|
526
|
+
const posix = !addr.startsWith("\\\\.\\pipe\\");
|
|
527
|
+
srv.once("error", (e ) => (e.code === "EADDRINUSE" ? ok("in-use") : fail(e)));
|
|
528
|
+
srv.listen(addr, () => {
|
|
529
|
+
srv.unref(); // never keeps the process alive on its own
|
|
530
|
+
const done = () => ok({ release: () => new Promise ((r) => srv.close(() => r())) });
|
|
531
|
+
if (posix) chmod(addr, 0o600).then(done, done); else done(); // owner-only socket, best effort
|
|
532
|
+
});
|
|
533
|
+
}),
|
|
534
|
+
probe: (addr) => new Promise((ok) => {
|
|
535
|
+
const c = connect(addr);
|
|
536
|
+
c.once("connect", () => { c.destroy(); ok("alive"); });
|
|
537
|
+
c.once("error", (e ) => ok(e.code === "ECONNREFUSED" ? "refused" : e.code === "ENOENT" ? "absent" : "other"));
|
|
538
|
+
}),
|
|
539
|
+
request: (addr, line) => new Promise((ok) => {
|
|
540
|
+
let answer = "";
|
|
541
|
+
let settled = false;
|
|
542
|
+
const c = connect(addr);
|
|
543
|
+
const end = (r ) => { if (settled) return; settled = true; c.destroy(); ok(r); };
|
|
544
|
+
c.setTimeout(3000, () => end("timed-out"));
|
|
545
|
+
c.once("connect", () => c.write(line));
|
|
546
|
+
c.on("data", (d) => { answer += d.toString("utf8"); if (answer.includes("\n")) end(answer.startsWith("ok\n") ? "ok" : "closed"); });
|
|
547
|
+
c.once("close", () => end("closed"));
|
|
548
|
+
c.once("error", (e ) => end(e.code === "ECONNREFUSED" || e.code === "ENOENT" ? "no-watcher" : "closed"));
|
|
549
|
+
}),
|
|
550
|
+
remove: (addr) => rm(addr, { force: true }),
|
|
551
|
+
secureDir: (dir) => checkSocketDir(dir, { mkdir: (p, o) => mkdir(p, o), lstat: (p) => lstat(p) }, process.getuid?.()),
|
|
552
|
+
legacySafe: (addr) => checkLegacySocket(addr, { lstat: (p) => lstat(p) }, process.getuid?.()),
|
|
553
|
+
};
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* Write the token owner-only (0600; on Windows the per-user state dir is the protection), atomically. The rename is
|
|
557
|
+
* retried while Windows refuses it (renameRetrying: an antivirus scan holding the old token); the temp file never
|
|
558
|
+
* outlives a failure.
|
|
559
|
+
*/
|
|
560
|
+
export async function writeToken(stateDir , token , deps = {}) {
|
|
561
|
+
const file = watcherTokenPath(stateDir);
|
|
562
|
+
const tmp = `${file}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
563
|
+
try {
|
|
564
|
+
const fh = await open(tmp, "w", 0o600);
|
|
565
|
+
try { await fh.writeFile(token, "utf8"); } finally { await fh.close(); }
|
|
566
|
+
await chmod(tmp, 0o600).catch(() => {});
|
|
567
|
+
await renameRetrying(tmp, file, deps);
|
|
568
|
+
} catch (e) {
|
|
569
|
+
await rm(tmp, { force: true }).catch(() => {});
|
|
570
|
+
throw e;
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* Listen on singletonAddress. The OS releases it when the process dies (pipe handle closed / socket closed), so a
|
|
576
|
+
* crashed watcher never blocks the next one; the heartbeat is only for `doctor`. EADDRINUSE = already running.
|
|
577
|
+
* POSIX only: a socket FILE survives a crash. It is removed only when a connect attempt right before fails with
|
|
578
|
+
* ECONNREFUSED (nobody listens: stale); a live or unclear one is never deleted. After removing it the bind is tried
|
|
579
|
+
* once more; if that fails with EADDRINUSE, another watcher bound in between: probe once more (for the record) and
|
|
580
|
+
* report "already running". Never two binds after a removal, never a removal without a fresh ECONNREFUSED.
|
|
581
|
+
* With `onStop`, a random token is written to <state>/watcher.token (only after the bind succeeded, so a second
|
|
582
|
+
* instance never overwrites the running watcher's token) and a stop request must carry it; release() removes it.
|
|
583
|
+
*/
|
|
584
|
+
export async function acquireWatcherSingleton(
|
|
585
|
+
stateDir , platform = process.platform, net = realSingletonNet,
|
|
586
|
+
onStop , addrOpts = {},
|
|
587
|
+
/** How the token is written (tests inject a refused rename). */
|
|
588
|
+
tokenWriter = writeToken,
|
|
589
|
+
) {
|
|
590
|
+
const addr = singletonAddress(stateDir, platform, addrOpts);
|
|
591
|
+
const legacy = legacySingletonAddress(stateDir, platform, addrOpts);
|
|
592
|
+
if (legacy !== null) {
|
|
593
|
+
// A 0.2.1 watcher bound the legacy address: it is running, whatever the new address says. Only a socket that is
|
|
594
|
+
// ours (a real socket, not a link) counts: anyone can create one in the temp dir to keep us from starting.
|
|
595
|
+
if ((await net.probe(legacy)) === "alive" && (!net.legacySafe || (await net.legacySafe(legacy)))) return null;
|
|
596
|
+
if (net.secureDir && !(await net.secureDir(dirname(addr)))) throw new UnsafeSocketDirError(dirname(addr));
|
|
597
|
+
}
|
|
598
|
+
let token = null;
|
|
599
|
+
const ctl = onStop ? { token: () => token, onStop } : undefined;
|
|
600
|
+
const won = async (h ) => {
|
|
601
|
+
if (!ctl) return { release: () => h.release(), addr };
|
|
602
|
+
const t = randomBytes(16).toString("hex");
|
|
603
|
+
// A token a crashed predecessor left behind goes first: were the new one not written, a client sending the old one
|
|
604
|
+
// would read the refusal as the 0.2.1 signature and kill at once instead of waiting (watcherControl).
|
|
605
|
+
await rm(watcherTokenPath(stateDir), { force: true }).catch(() => {});
|
|
606
|
+
try { await tokenWriter(stateDir, t); token = t; } catch { /* no token: stop requests are refused; the verified-pid fallback remains */ }
|
|
607
|
+
return { addr, release: async () => { token = null; await rm(watcherTokenPath(stateDir), { force: true }).catch(() => {}); await h.release(); } };
|
|
608
|
+
};
|
|
609
|
+
const first = await net.listen(addr, ctl);
|
|
610
|
+
if (first !== "in-use") return won(first);
|
|
611
|
+
if (platform === "win32") return null; // a named pipe in use is a live watcher; nothing to clean up
|
|
612
|
+
if ((await net.probe(addr)) !== "refused") return null; // alive, or not provably stale: leave it alone
|
|
613
|
+
await net.remove(addr);
|
|
614
|
+
const second = await net.listen(addr, ctl);
|
|
615
|
+
if (second !== "in-use") return won(second);
|
|
616
|
+
await net.probe(addr); // re-check after the failed bind: someone else won the race; either way we stand down
|
|
617
|
+
return null;
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
export { pidAlive } from "../core/pid.js";
|
|
621
|
+
|
|
622
|
+
export async function readHeartbeat(stateDir ) {
|
|
623
|
+
try {
|
|
624
|
+
const h = JSON.parse(await readFile(join(stateDir, "sync-status.json"), "utf8")) ;
|
|
625
|
+
return h && typeof h.pid === "number" ? h : null;
|
|
626
|
+
} catch { return null; }
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
|
|
631
|
+
const PER_DIR_DEPTH = 3;
|
|
632
|
+
const PER_DIR_MAX = 2000;
|
|
633
|
+
|
|
634
|
+
/** One watched directory: recursive, else per directory, else poll (see the header). */
|
|
635
|
+
export function createDirWatch(dir , onEvent , o = {}) {
|
|
636
|
+
const fsWatch = o.fsWatch ?? (fsWatchReal );
|
|
637
|
+
const name = (f ) => (f === null || f === undefined ? null : String(f));
|
|
638
|
+
let mode = "recursive";
|
|
639
|
+
const handles = new Map ();
|
|
640
|
+
const closeAll = () => { for (const h of handles.values()) { try { h.close(); } catch { /* ignore */ } } handles.clear(); };
|
|
641
|
+
const toPoll = () => { closeAll(); mode = "poll"; };
|
|
642
|
+
const guard = (h ) => { h.on?.("error", () => toPoll()); return h; };
|
|
643
|
+
|
|
644
|
+
try {
|
|
645
|
+
handles.set(dir, guard(fsWatch(dir, { recursive: true, persistent: true }, (_e, f) => onEvent(name(f)))));
|
|
646
|
+
} catch (e) {
|
|
647
|
+
if ((e ).code !== "ERR_FEATURE_UNAVAILABLE_ON_PLATFORM") {
|
|
648
|
+
toPoll();
|
|
649
|
+
} else {
|
|
650
|
+
mode = "per-dir";
|
|
651
|
+
const add = (d , depth ) => {
|
|
652
|
+
if (mode !== "per-dir" || handles.has(d)) return;
|
|
653
|
+
if (handles.size >= PER_DIR_MAX) { toPoll(); return; }
|
|
654
|
+
try {
|
|
655
|
+
handles.set(d, guard(fsWatch(d, { persistent: true }, (_e, f) => {
|
|
656
|
+
const n = name(f);
|
|
657
|
+
onEvent(n === null ? null : join(d, n));
|
|
658
|
+
if (n !== null && depth < PER_DIR_DEPTH) add2(join(d, n), depth + 1); // a new subdirectory
|
|
659
|
+
})));
|
|
660
|
+
} catch { toPoll(); return; }
|
|
661
|
+
if (depth >= PER_DIR_DEPTH) return;
|
|
662
|
+
let subs = [];
|
|
663
|
+
try { subs = readdirSync(d, { withFileTypes: true }).filter((x) => x.isDirectory()).map((x) => join(d, x.name)); } catch { /* gone */ }
|
|
664
|
+
for (const s of subs) add(s, depth + 1);
|
|
665
|
+
};
|
|
666
|
+
const add2 = (p , depth ) => {
|
|
667
|
+
try { if (readdirSync(p) && !handles.has(p)) add(p, depth); } catch { /* a file, or gone */ }
|
|
668
|
+
};
|
|
669
|
+
add(dir, 0);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
return {
|
|
673
|
+
get mode() { return mode; },
|
|
674
|
+
close: closeAll,
|
|
675
|
+
};
|
|
676
|
+
}
|