opencode-windows-scheduler 1.4.0 → 1.5.0
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/CHANGELOG.md +24 -0
- package/README.md +2 -2
- package/ROADMAP-STRATEGY.md +43 -24
- package/ROADMAP.md +280 -31
- package/dist/core/dry-run.d.ts +31 -0
- package/dist/core/dry-run.d.ts.map +1 -1
- package/dist/core/dry-run.js +129 -1
- package/dist/core/file-watcher.d.ts.map +1 -1
- package/dist/core/file-watcher.js +53 -10
- package/dist/core/git-trigger.d.ts +80 -0
- package/dist/core/git-trigger.d.ts.map +1 -0
- package/dist/core/git-trigger.js +288 -0
- package/dist/core/glob.d.ts +38 -0
- package/dist/core/glob.d.ts.map +1 -0
- package/dist/core/glob.js +233 -0
- package/dist/core/ps-wrapper.d.ts.map +1 -1
- package/dist/core/ps-wrapper.js +7 -0
- package/dist/core/schedule-gate.js +55 -30
- package/dist/core/schedule-v2.d.ts +29 -1
- package/dist/core/schedule-v2.d.ts.map +1 -1
- package/dist/core/schedule-v2.js +81 -3
- package/dist/core/scheduler/types.d.ts +1 -1
- package/dist/core/scheduler/types.d.ts.map +1 -1
- package/dist/core/wrappers/bash.d.ts.map +1 -1
- package/dist/core/wrappers/bash.js +4 -0
- package/dist/db/git-state-repo.d.ts +16 -0
- package/dist/db/git-state-repo.d.ts.map +1 -0
- package/dist/db/git-state-repo.js +38 -0
- package/dist/db/schema.d.ts +1 -1
- package/dist/db/schema.d.ts.map +1 -1
- package/dist/db/schema.js +8 -0
- package/dist/index.d.ts +44 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +247 -26
- package/dist/rpc.d.ts +223 -0
- package/dist/rpc.d.ts.map +1 -1
- package/dist/rpc.js +73 -0
- package/dist/task-transfer.d.ts +30 -3
- package/dist/task-transfer.d.ts.map +1 -1
- package/dist/task-transfer.js +83 -6
- package/dist/templates.d.ts +1 -1
- package/dist/templates.d.ts.map +1 -1
- package/docs/ARCHITECTURE.md +1 -0
- package/docs/FEATURES.md +51 -0
- package/docs/README.ru.md +2 -2
- package/gui-experimental.cjs +9 -4
- package/package.json +6 -3
- package/src/core/dry-run.ts +188 -1
- package/src/core/file-watcher.ts +65 -10
- package/src/core/git-trigger.ts +367 -0
- package/src/core/glob.ts +226 -0
- package/src/core/ps-wrapper.ts +7 -0
- package/src/core/schedule-gate.ts +67 -33
- package/src/core/schedule-v2.ts +108 -3
- package/src/core/scheduler/types.ts +1 -1
- package/src/core/wrappers/bash.ts +4 -0
- package/src/db/git-state-repo.ts +62 -0
- package/src/db/schema.ts +8 -0
- package/src/gui.tsx +225 -4
- package/src/index.ts +338 -28
- package/src/rpc.ts +73 -0
- package/src/task-transfer.ts +124 -5
- package/src/templates.ts +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-windows-scheduler",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"description": "OpenCode v2 plugin for scheduling and orchestrating AI agent jobs: cron, one-shot runs, DAG pipelines, matrix builds, quality gates, SQLite history, metrics and a local web dashboard. Windows, macOS and Linux. Free and open source (MIT).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "opencode-windows-scheduler contributors",
|
|
@@ -69,7 +69,7 @@
|
|
|
69
69
|
"demo": "node scripts/demo-dashboard.mjs",
|
|
70
70
|
"prepare": "npm run build",
|
|
71
71
|
"prepublishOnly": "npm run build && npm run build:gui",
|
|
72
|
-
"test": "node test-sqlite.mjs && node test-crash-recovery.mjs && node test-workspaces.mjs && node test-role-scoped.mjs && node test-dry-run.mjs && node test-matrix.mjs && node test-matrix-lifecycle.mjs && node test-matrix-sync.mjs && node test-retention.mjs && node test-metrics.mjs && node test-schedule-v2.mjs && node test-notifications-v2.mjs && node test-notifications-v3.mjs && node test-secrets.mjs && node test-audit.mjs && node test-profiles.mjs && node test-env.mjs && node test-agent-tools.mjs && node test-skill.mjs && node test-integrations.mjs && node test-one-shot.mjs && node test-session-continuity.mjs && node test-task-status.mjs && node test-jobs-view.mjs && node test-dag.mjs && node test-dashboard.mjs && node test-dashboard-dag.mjs && node test-dashboard-json.mjs && node test-docs.mjs",
|
|
72
|
+
"test": "node test-sqlite.mjs && node test-crash-recovery.mjs && node test-workspaces.mjs && node test-role-scoped.mjs && node test-dry-run.mjs && node test-matrix.mjs && node test-matrix-lifecycle.mjs && node test-matrix-sync.mjs && node test-retention.mjs && node test-metrics.mjs && node test-schedule-v2.mjs && node test-notifications-v2.mjs && node test-notifications-v3.mjs && node test-secrets.mjs && node test-audit.mjs && node test-profiles.mjs && node test-env.mjs && node test-agent-tools.mjs && node test-skill.mjs && node test-integrations.mjs && node test-one-shot.mjs && node test-session-continuity.mjs && node test-task-status.mjs && node test-jobs-view.mjs && node test-dag.mjs && node test-dashboard.mjs && node test-dashboard-dag.mjs && node test-dashboard-json.mjs && node test-docs.mjs && node test-glob.mjs && node test-git-trigger.mjs && node test-window-v3.mjs",
|
|
73
73
|
"test:sqlite": "node test-sqlite.mjs",
|
|
74
74
|
"test:crash": "node test-crash-recovery.mjs",
|
|
75
75
|
"test:workspaces": "node test-workspaces.mjs",
|
|
@@ -98,7 +98,10 @@
|
|
|
98
98
|
"test:dashboard": "node test-dashboard.mjs",
|
|
99
99
|
"test:dashboard-dag": "node test-dashboard-dag.mjs",
|
|
100
100
|
"test:dashboard-json": "node test-dashboard-json.mjs",
|
|
101
|
-
"test:docs": "node test-docs.mjs"
|
|
101
|
+
"test:docs": "node test-docs.mjs",
|
|
102
|
+
"test:glob": "node test-glob.mjs",
|
|
103
|
+
"test:git-trigger": "node test-git-trigger.mjs",
|
|
104
|
+
"test:window-v3": "node test-window-v3.mjs"
|
|
102
105
|
},
|
|
103
106
|
"dependencies": {
|
|
104
107
|
"@opencode/plugin": "^2.2.7",
|
package/src/core/dry-run.ts
CHANGED
|
@@ -10,7 +10,8 @@ import { loadTaskDefinitions } from "../task-transfer.js";
|
|
|
10
10
|
import { getHistory } from "../db/history-repo.js";
|
|
11
11
|
import { getWorkspace } from "../workspaces.js";
|
|
12
12
|
import { expandMatrixTask } from "./matrix.js";
|
|
13
|
-
import { nextRun } from "./schedule-v2.js";
|
|
13
|
+
import { nextRun, activeWindowState } from "./schedule-v2.js";
|
|
14
|
+
import { checkGitTrigger } from "./git-trigger.js";
|
|
14
15
|
import type { TaskDefinition } from "../task-transfer.js";
|
|
15
16
|
|
|
16
17
|
export interface DryRunRoleScoped {
|
|
@@ -18,6 +19,36 @@ export interface DryRunRoleScoped {
|
|
|
18
19
|
denied?: string[];
|
|
19
20
|
}
|
|
20
21
|
|
|
22
|
+
/**
|
|
23
|
+
* Детали триггера (Спринт 27): чем задача запускается и не будет ли запуск
|
|
24
|
+
* пропущен из-за окна/дней недели. Для git-триггера — состояние репозитория.
|
|
25
|
+
*/
|
|
26
|
+
export interface DryRunTriggerDetails {
|
|
27
|
+
type: "manual" | "cron" | "file" | "git" | "mcp-event" | "once";
|
|
28
|
+
/** Человекочитаемое объяснение условия запуска. */
|
|
29
|
+
explanation: string;
|
|
30
|
+
/** Состояние окна запуска и разрешённых дней недели (если заданы). */
|
|
31
|
+
activeWindow?: {
|
|
32
|
+
active: boolean;
|
|
33
|
+
reason?: string;
|
|
34
|
+
nextOpenAt: string | null;
|
|
35
|
+
};
|
|
36
|
+
/** Состояние git-триггера на момент dry-run. */
|
|
37
|
+
git?: {
|
|
38
|
+
branch: string | null;
|
|
39
|
+
head: string | null;
|
|
40
|
+
lastCommit: string | null;
|
|
41
|
+
changedFiles: string[];
|
|
42
|
+
matched: string[];
|
|
43
|
+
};
|
|
44
|
+
/** Настройки файлового триггера. */
|
|
45
|
+
file?: {
|
|
46
|
+
watchPath: string | null;
|
|
47
|
+
globs: string[];
|
|
48
|
+
ignore: string[];
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
21
52
|
export interface DryRunTaskItem {
|
|
22
53
|
name: string;
|
|
23
54
|
order: number;
|
|
@@ -51,6 +82,8 @@ export interface DryRunTaskItem {
|
|
|
51
82
|
pausedUntil: string | null;
|
|
52
83
|
nextRuns: string[];
|
|
53
84
|
};
|
|
85
|
+
/** Детали триггера и причина возможного пропуска (Спринт 27). */
|
|
86
|
+
triggerDetails?: DryRunTriggerDetails;
|
|
54
87
|
}
|
|
55
88
|
|
|
56
89
|
export interface DryRunTotals {
|
|
@@ -79,6 +112,151 @@ const DANGEROUS_PATTERNS: Array<{ test: RegExp; message: string }> = [
|
|
|
79
112
|
{ test: /git\s+push\s+.*--force(?:\s|$)/, message: "принудительный push в git (`git push --force`)" },
|
|
80
113
|
];
|
|
81
114
|
|
|
115
|
+
/**
|
|
116
|
+
* Свойства для описания триггера задачи в dry-run (Спринт 27).
|
|
117
|
+
*/
|
|
118
|
+
interface DescribeTriggerOptions {
|
|
119
|
+
/** Задание задачи (может содержать новые поля Спринта 27). */
|
|
120
|
+
def: TaskDefinition;
|
|
121
|
+
/** Эффективная рабочая директория задачи. */
|
|
122
|
+
cwd: string;
|
|
123
|
+
/** Вычисляемый тип триггера для поля `trigger`. */
|
|
124
|
+
triggerType: string;
|
|
125
|
+
/** Куда накапливать предупреждения (префикс [task] добавится в цикле). */
|
|
126
|
+
warnings: string[];
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Описывает триггер задачи: что запускает задачу, не будет ли запуск
|
|
131
|
+
* пропущен из-за окна/дней недели, и (для git) состояние репозитория.
|
|
132
|
+
* Не имеет побочных эффектов (для git используется persist: false).
|
|
133
|
+
*/
|
|
134
|
+
async function describeTrigger(opts: DescribeTriggerOptions): Promise<DryRunTriggerDetails> {
|
|
135
|
+
const { def, cwd, triggerType, warnings } = opts;
|
|
136
|
+
const policy: "skip" | "postpone" | "run" = def.windowPolicy ?? "postpone";
|
|
137
|
+
|
|
138
|
+
const base: DryRunTriggerDetails = {
|
|
139
|
+
type: triggerType as DryRunTriggerDetails["type"],
|
|
140
|
+
explanation: "",
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
const hasWindow = Boolean((def.notBefore ?? "").trim() || (def.notAfter ?? "").trim());
|
|
144
|
+
const hasDays = Array.isArray(def.activeDays) && def.activeDays.length > 0;
|
|
145
|
+
|
|
146
|
+
switch (triggerType) {
|
|
147
|
+
case "git": {
|
|
148
|
+
try {
|
|
149
|
+
const result = await checkGitTrigger(
|
|
150
|
+
{
|
|
151
|
+
name: def.name,
|
|
152
|
+
cwd,
|
|
153
|
+
branch: def.gitBranch ?? undefined,
|
|
154
|
+
paths: def.gitPaths ?? undefined,
|
|
155
|
+
ignore: def.gitIgnore ?? undefined,
|
|
156
|
+
},
|
|
157
|
+
{ persist: false }
|
|
158
|
+
);
|
|
159
|
+
base.git = {
|
|
160
|
+
branch: result.branch ?? null,
|
|
161
|
+
head: result.head ?? null,
|
|
162
|
+
lastCommit: result.from ?? null,
|
|
163
|
+
changedFiles: result.files,
|
|
164
|
+
matched: result.matched,
|
|
165
|
+
};
|
|
166
|
+
base.explanation = result.message;
|
|
167
|
+
|
|
168
|
+
if (result.status === "no-repo") {
|
|
169
|
+
warnings.push("Задача с git-триггером, но рабочая директория не является git-репозиторием.");
|
|
170
|
+
} else if (result.status === "branch-mismatch") {
|
|
171
|
+
warnings.push(`Ветка не подходит под фильтр «${def.gitBranch ?? ""}».`);
|
|
172
|
+
}
|
|
173
|
+
} catch (err: any) {
|
|
174
|
+
base.explanation = `Git-триггер: ошибка проверки — ${err instanceof Error ? err.message : String(err)}.`;
|
|
175
|
+
warnings.push(base.explanation);
|
|
176
|
+
}
|
|
177
|
+
break;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
case "file": {
|
|
181
|
+
base.file = {
|
|
182
|
+
watchPath: def.watchPath ?? null,
|
|
183
|
+
globs: Array.isArray(def.watchGlobs) ? def.watchGlobs : [],
|
|
184
|
+
ignore: Array.isArray(def.watchIgnore) ? def.watchIgnore : [],
|
|
185
|
+
};
|
|
186
|
+
const parts: string[] = [];
|
|
187
|
+
if (def.watchPath) parts.push(`«${def.watchPath}»`);
|
|
188
|
+
if (def.watchGlobs?.length) parts.push(`маски: ${def.watchGlobs.length}`);
|
|
189
|
+
if (def.watchIgnore?.length) parts.push(`исключения: ${def.watchIgnore.length}`);
|
|
190
|
+
base.explanation =
|
|
191
|
+
parts.length > 0
|
|
192
|
+
? `Файловый триггер: ${parts.join("; ")}.`
|
|
193
|
+
: "Файловый триггер: любое изменение подходит.";
|
|
194
|
+
break;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
case "mcp-event": {
|
|
198
|
+
const ev = def.mcpEvent;
|
|
199
|
+
base.explanation = ev && ev.event
|
|
200
|
+
? `MCP-событие ${ev.server}:${ev.event}${ev.filter ? ` (фильтр «${ev.filter}»)` : ""}.`
|
|
201
|
+
: "MCP-событие (параметры не заданы).";
|
|
202
|
+
break;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
case "cron": {
|
|
206
|
+
let text = `По расписанию «${def.schedule}»`;
|
|
207
|
+
if (def.timezone) text += ` (${def.timezone})`;
|
|
208
|
+
base.explanation = text + ".";
|
|
209
|
+
break;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
case "once": {
|
|
213
|
+
base.explanation = def.runAt ? `Однократно в ${def.runAt}.` : "Однократный запуск.";
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
case "manual":
|
|
218
|
+
default: {
|
|
219
|
+
base.explanation = "Запуск вручную (в составе конвейера).";
|
|
220
|
+
break;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Окно запуска и дни недели (если заданы).
|
|
225
|
+
if (hasWindow || hasDays) {
|
|
226
|
+
const state = activeWindowState(new Date(), {
|
|
227
|
+
notBefore: def.notBefore ?? undefined,
|
|
228
|
+
notAfter: def.notAfter ?? undefined,
|
|
229
|
+
days: def.activeDays ?? undefined,
|
|
230
|
+
timeZone: def.timezone ?? undefined,
|
|
231
|
+
});
|
|
232
|
+
base.activeWindow = {
|
|
233
|
+
active: state.active,
|
|
234
|
+
...(state.reason ? { reason: state.reason } : {}),
|
|
235
|
+
nextOpenAt: state.nextOpenAt ? state.nextOpenAt.toISOString() : null,
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
if (!state.active && policy !== "run") {
|
|
239
|
+
if (policy === "skip") {
|
|
240
|
+
warnings.push(
|
|
241
|
+
`Сейчас ${state.reason ?? "вне окна"}: при политике skip запуск будет пропущен.`
|
|
242
|
+
);
|
|
243
|
+
} else {
|
|
244
|
+
// postpone — переносим на ближайшее открытие.
|
|
245
|
+
const iso = base.activeWindow.nextOpenAt ?? null;
|
|
246
|
+
warnings.push(
|
|
247
|
+
iso
|
|
248
|
+
? `Сейчас ${state.reason ?? "вне окна"}: запуск будет перенесён на ${iso}.`
|
|
249
|
+
: `Сейчас ${state.reason ?? "вне окна"}: открытие окна не найдено, запуск пропущен.`
|
|
250
|
+
);
|
|
251
|
+
}
|
|
252
|
+
} else if (!state.active && policy === "run") {
|
|
253
|
+
warnings.push(`Сейчас ${state.reason ?? "вне окна"}: политика run — задача выполнится всё равно.`);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
return base;
|
|
258
|
+
}
|
|
259
|
+
|
|
82
260
|
/**
|
|
83
261
|
* Симулирует конвейер задачи: сама задача + все зависимости (dependsOn)
|
|
84
262
|
* в топологическом порядке. Возвращает отчёт без реального запуска.
|
|
@@ -230,6 +408,14 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
|
|
|
230
408
|
? "manual"
|
|
231
409
|
: "dag";
|
|
232
410
|
|
|
411
|
+
// Детали триггера (Спринт 27): состояние окна/дней недели, git-статус.
|
|
412
|
+
const triggerDetails = await describeTrigger({
|
|
413
|
+
def,
|
|
414
|
+
cwd,
|
|
415
|
+
triggerType,
|
|
416
|
+
warnings: taskWarnings,
|
|
417
|
+
});
|
|
418
|
+
|
|
233
419
|
// Команда, которую выполнит обёртка.
|
|
234
420
|
const modelArg = def.model ? ` --model ${def.model}` : "";
|
|
235
421
|
const promptPreview = (def.prompt ?? "").replace(/\s+/g, " ").trim();
|
|
@@ -329,6 +515,7 @@ export async function simulatePipeline(taskName: string): Promise<DryRunReport>
|
|
|
329
515
|
estimatedTokens: estimatedTokens != null ? Math.round(estimatedTokens) : null,
|
|
330
516
|
...(matrixParent ? { matrixParent } : {}),
|
|
331
517
|
...(scheduleDetails ? { scheduleDetails } : {}),
|
|
518
|
+
...(triggerDetails ? { triggerDetails } : {}),
|
|
332
519
|
});
|
|
333
520
|
|
|
334
521
|
if (taskWarnings.length > 0) {
|
package/src/core/file-watcher.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { watch, type FSWatcher } from "chokidar";
|
|
2
2
|
import { loadTaskDefinitions } from "../task-transfer.js";
|
|
3
|
+
import { filterPaths, relativeTo } from "./glob.js";
|
|
3
4
|
|
|
4
5
|
/**
|
|
5
6
|
* Задержка между последним изменением файла и запуском задачи.
|
|
@@ -18,6 +19,9 @@ interface WatchedTask {
|
|
|
18
19
|
name: string;
|
|
19
20
|
/** Нормализованный путь, который отслеживаем. */
|
|
20
21
|
path: string;
|
|
22
|
+
/** Спринт 27: glob-маски и ignore-список (пусто — любое изменение). */
|
|
23
|
+
globs: string[];
|
|
24
|
+
ignore: string[];
|
|
21
25
|
watcher: FSWatcher;
|
|
22
26
|
/** Таймер дебаунса (одна задача = один отложенный запуск). */
|
|
23
27
|
timer: NodeJS.Timeout | null;
|
|
@@ -57,15 +61,30 @@ export class FileWatchManager {
|
|
|
57
61
|
typeof d.watchPath === "string" &&
|
|
58
62
|
d.watchPath.trim().length > 0
|
|
59
63
|
)
|
|
60
|
-
.map((d) => ({
|
|
64
|
+
.map((d) => ({
|
|
65
|
+
name: d.name.trim(),
|
|
66
|
+
path: d.watchPath!.trim(),
|
|
67
|
+
globs: Array.isArray(d.watchGlobs)
|
|
68
|
+
? d.watchGlobs.filter((g): g is string => typeof g === "string" && g.trim().length > 0)
|
|
69
|
+
: [],
|
|
70
|
+
ignore: Array.isArray(d.watchIgnore)
|
|
71
|
+
? d.watchIgnore.filter((g): g is string => typeof g === "string" && g.trim().length > 0)
|
|
72
|
+
: [],
|
|
73
|
+
}))
|
|
61
74
|
.filter((d) => d.name.length > 0);
|
|
62
75
|
|
|
63
76
|
const wantedKeys = new Set(wanted.map((d) => d.name.toLowerCase()));
|
|
64
77
|
|
|
65
|
-
// Убираем watcher'ы для задач, которых больше нет или у которых сменился
|
|
78
|
+
// Убираем watcher'ы для задач, которых больше нет или у которых сменился
|
|
79
|
+
// путь/маски (Спринт 27).
|
|
66
80
|
for (const [key, entry] of Array.from(this.entries.entries())) {
|
|
67
81
|
const target = wanted.find((d) => d.name.toLowerCase() === key);
|
|
68
|
-
if (
|
|
82
|
+
if (
|
|
83
|
+
!target ||
|
|
84
|
+
target.path !== entry.path ||
|
|
85
|
+
target.globs.join("\u0000") !== entry.globs.join("\u0000") ||
|
|
86
|
+
target.ignore.join("\u0000") !== entry.ignore.join("\u0000")
|
|
87
|
+
) {
|
|
69
88
|
await this.remove(key);
|
|
70
89
|
}
|
|
71
90
|
}
|
|
@@ -74,7 +93,7 @@ export class FileWatchManager {
|
|
|
74
93
|
for (const item of wanted) {
|
|
75
94
|
const key = item.name.toLowerCase();
|
|
76
95
|
if (this.entries.has(key) || !wantedKeys.has(key)) continue;
|
|
77
|
-
this.add(item.name, item.path);
|
|
96
|
+
this.add(item.name, item.path, item.globs, item.ignore);
|
|
78
97
|
}
|
|
79
98
|
|
|
80
99
|
return this.entries.size;
|
|
@@ -88,14 +107,22 @@ export class FileWatchManager {
|
|
|
88
107
|
}
|
|
89
108
|
}
|
|
90
109
|
|
|
91
|
-
private add(
|
|
110
|
+
private add(
|
|
111
|
+
name: string,
|
|
112
|
+
watchPath: string,
|
|
113
|
+
globs: string[] = [],
|
|
114
|
+
ignore: string[] = []
|
|
115
|
+
): void {
|
|
116
|
+
// Спринт 27: маски с "**" требуют рекурсивного обхода директории.
|
|
117
|
+
const needsRecursive = globs.some((g) => g.includes("**"));
|
|
92
118
|
let watcher: FSWatcher;
|
|
93
119
|
try {
|
|
94
120
|
watcher = watch(watchPath, {
|
|
95
121
|
// Не считаем уже существующий файл «изменением» при старте.
|
|
96
122
|
ignoreInitial: true,
|
|
97
|
-
// Следим за одним файлом/папкой, без рекурсии в
|
|
98
|
-
|
|
123
|
+
// Следим за одним файлом/папкой, без рекурсии в глубину, если маски
|
|
124
|
+
// этого не требуют.
|
|
125
|
+
depth: needsRecursive ? undefined : 0,
|
|
99
126
|
// Файлы могут быть большими: дождёмся, пока запись успокоится.
|
|
100
127
|
awaitWriteFinish: { stabilityThreshold: 500, pollInterval: 100 },
|
|
101
128
|
ignorePermissionErrors: true,
|
|
@@ -109,10 +136,32 @@ export class FileWatchManager {
|
|
|
109
136
|
return;
|
|
110
137
|
}
|
|
111
138
|
|
|
112
|
-
const entry: WatchedTask = {
|
|
139
|
+
const entry: WatchedTask = {
|
|
140
|
+
name,
|
|
141
|
+
path: watchPath,
|
|
142
|
+
globs,
|
|
143
|
+
ignore,
|
|
144
|
+
watcher,
|
|
145
|
+
timer: null,
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
/** Спринт 27: маски применяются к пути относительно watchPath. */
|
|
149
|
+
const accepts = (changedPath: string): boolean => {
|
|
150
|
+
if (globs.length === 0 && ignore.length === 0) return true;
|
|
151
|
+
if (globs.length === 0) {
|
|
152
|
+
const rel = relativeTo(watchPath, changedPath) ?? changedPath;
|
|
153
|
+
return filterPaths([rel], undefined, ignore).length > 0;
|
|
154
|
+
}
|
|
155
|
+
const rel = relativeTo(watchPath, changedPath);
|
|
156
|
+
const candidates = rel ? [rel, changedPath] : [changedPath];
|
|
157
|
+
return candidates.some(
|
|
158
|
+
(candidate) => filterPaths([candidate], globs, ignore).length > 0
|
|
159
|
+
);
|
|
160
|
+
};
|
|
113
161
|
|
|
114
|
-
|
|
162
|
+
const onChange = (changedPath: string) => {
|
|
115
163
|
if (this.stopped) return;
|
|
164
|
+
if (!accepts(changedPath)) return;
|
|
116
165
|
if (entry.timer) clearTimeout(entry.timer);
|
|
117
166
|
entry.timer = setTimeout(() => {
|
|
118
167
|
entry.timer = null;
|
|
@@ -138,7 +187,13 @@ export class FileWatchManager {
|
|
|
138
187
|
}, this.debounceMs);
|
|
139
188
|
// Таймер не должен удерживать процесс, если хост завершается.
|
|
140
189
|
if (typeof entry.timer.unref === "function") entry.timer.unref();
|
|
141
|
-
}
|
|
190
|
+
};
|
|
191
|
+
|
|
192
|
+
// Спринт 27: переименование/удаление файла тоже считается изменением —
|
|
193
|
+
// иначе mac/win-редакторы, пишущие через rename, «пропадали» бы.
|
|
194
|
+
watcher.on("change", onChange);
|
|
195
|
+
watcher.on("add", onChange);
|
|
196
|
+
watcher.on("unlink", onChange);
|
|
142
197
|
|
|
143
198
|
watcher.on("error", (err) => {
|
|
144
199
|
console.error(
|