@tagma/sdk 0.5.2 → 0.6.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/LICENSE +21 -21
- package/package.json +2 -2
- package/scripts/preinstall.js +31 -31
- package/src/adapters/stdin-approval.ts +106 -106
- package/src/adapters/websocket-approval.ts +224 -224
- package/src/approval.ts +131 -131
- package/src/completions/exit-code.ts +34 -34
- package/src/completions/file-exists.ts +66 -66
- package/src/config-ops.ts +307 -307
- package/src/dag.ts +245 -245
- package/src/drivers/opencode.ts +371 -371
- package/src/logger.ts +182 -182
- package/src/prompt-doc.ts +49 -49
- package/src/task-ref.test.ts +401 -401
- package/src/task-ref.ts +120 -120
- package/src/triggers/file.ts +164 -164
- package/src/triggers/manual.ts +86 -86
- package/src/types.ts +18 -18
- package/src/utils.ts +203 -203
- package/dist/templates.d.ts +0 -20
- package/dist/templates.d.ts.map +0 -1
- package/dist/templates.js +0 -93
- package/dist/templates.js.map +0 -1
package/src/task-ref.ts
CHANGED
|
@@ -1,120 +1,120 @@
|
|
|
1
|
-
// ═══ Task reference resolution — single source of truth ═══
|
|
2
|
-
//
|
|
3
|
-
// Before this module existed, four sites each carried their own copy of the
|
|
4
|
-
// "what is a valid id" + "how do I resolve a bare / same-track-shorthand /
|
|
5
|
-
// fully qualified ref" logic:
|
|
6
|
-
//
|
|
7
|
-
// - dag.ts/buildDag (threw on unresolved, threw on ambiguous)
|
|
8
|
-
// - dag.ts/buildRawDag (silently skipped unresolved and ambiguous)
|
|
9
|
-
// - validate-raw.ts (reported both as errors, with different wording)
|
|
10
|
-
// - engine.ts/resolveRefInDag (returned null on ambiguous)
|
|
11
|
-
//
|
|
12
|
-
// In addition, the editor shipped its own regex for id validation in
|
|
13
|
-
// `shared/config-id.ts` and a test-local copy in `config-id-generation.test.ts`,
|
|
14
|
-
// creating multiple places where the character set could drift from the
|
|
15
|
-
// validator. Bugs observed downstream (silent context loss when two tracks
|
|
16
|
-
// happened to share a bare task name; editor-generated ids occasionally
|
|
17
|
-
// failing SDK validate-raw) all traced back to this duplication.
|
|
18
|
-
//
|
|
19
|
-
// Callers now build a TaskIndex once and use `resolveTaskRef` to classify
|
|
20
|
-
// each reference, then decide themselves whether to throw / warn / skip —
|
|
21
|
-
// instead of re-implementing the index build and the lookup logic.
|
|
22
|
-
|
|
23
|
-
import type { PipelineConfig, RawPipelineConfig } from './types';
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* D8: task and track ids must match this pattern. No dots: the `.` is the
|
|
27
|
-
* qualified-id separator ("trackId.taskId"), so allowing it inside either
|
|
28
|
-
* part would make qid parsing ambiguous and break every resolver below.
|
|
29
|
-
*/
|
|
30
|
-
export const TASK_ID_RE = /^[A-Za-z_][A-Za-z0-9_-]*$/;
|
|
31
|
-
|
|
32
|
-
export function isValidTaskId(id: unknown): id is string {
|
|
33
|
-
return typeof id === 'string' && TASK_ID_RE.test(id);
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
/** Canonical qualified form used throughout the engine. */
|
|
37
|
-
export function qualifyTaskId(trackId: string, taskId: string): string {
|
|
38
|
-
return `${trackId}.${taskId}`;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
/** Does the reference already include a track prefix? */
|
|
42
|
-
export function isQualifiedRef(ref: string): boolean {
|
|
43
|
-
return ref.includes('.');
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* Sentinel stored in `TaskIndex.bareToQualified` when a bare task id is
|
|
48
|
-
* shared by more than one track, making it unresolvable without a prefix.
|
|
49
|
-
* Exposed so callers that want to inspect the index directly know what to
|
|
50
|
-
* look for — but prefer `resolveTaskRef` which returns a typed `kind`.
|
|
51
|
-
*/
|
|
52
|
-
export const AMBIGUOUS = '__ambiguous__';
|
|
53
|
-
|
|
54
|
-
export interface TaskIndex {
|
|
55
|
-
/** All fully-qualified ids ("trackId.taskId") present in the config. */
|
|
56
|
-
readonly allQualified: ReadonlySet<string>;
|
|
57
|
-
/** bare taskId → qid, or the {@link AMBIGUOUS} sentinel. */
|
|
58
|
-
readonly bareToQualified: ReadonlyMap<string, string>;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* Build the index used by {@link resolveTaskRef}. Tolerant of partially
|
|
63
|
-
* malformed configs: tracks or tasks missing an `id` are skipped so the
|
|
64
|
-
* editor can call this during real-time validation on in-progress edits.
|
|
65
|
-
*/
|
|
66
|
-
export function buildTaskIndex(config: RawPipelineConfig | PipelineConfig): TaskIndex {
|
|
67
|
-
const allQualified = new Set<string>();
|
|
68
|
-
const bareToQualified = new Map<string, string>();
|
|
69
|
-
for (const track of config.tracks ?? []) {
|
|
70
|
-
if (!track?.id) continue;
|
|
71
|
-
for (const task of track.tasks ?? []) {
|
|
72
|
-
if (!task?.id) continue;
|
|
73
|
-
const qid = qualifyTaskId(track.id, task.id);
|
|
74
|
-
allQualified.add(qid);
|
|
75
|
-
if (bareToQualified.has(task.id)) {
|
|
76
|
-
bareToQualified.set(task.id, AMBIGUOUS);
|
|
77
|
-
} else {
|
|
78
|
-
bareToQualified.set(task.id, qid);
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
return { allQualified, bareToQualified };
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
export type RefResolution =
|
|
86
|
-
| { readonly kind: 'resolved'; readonly qid: string }
|
|
87
|
-
| { readonly kind: 'ambiguous'; readonly ref: string }
|
|
88
|
-
| { readonly kind: 'not_found'; readonly ref: string };
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* Resolve a dependency / continue_from reference to a canonical qid.
|
|
92
|
-
*
|
|
93
|
-
* 1. If the ref already contains a `.`, treat it as fully qualified —
|
|
94
|
-
* return `resolved` when the qid exists, `not_found` otherwise.
|
|
95
|
-
* 2. Otherwise, prefer the same-track shorthand (`fromTrackId.ref`).
|
|
96
|
-
* 3. Fall back to a global bare lookup. Returns `ambiguous` when more
|
|
97
|
-
* than one track has a task with that bare name.
|
|
98
|
-
*
|
|
99
|
-
* Callers decide the policy: `buildDag` throws on non-resolved, `buildRawDag`
|
|
100
|
-
* skips silently, `validateRaw` emits a structured ValidationError.
|
|
101
|
-
*/
|
|
102
|
-
export function resolveTaskRef(
|
|
103
|
-
ref: string,
|
|
104
|
-
fromTrackId: string,
|
|
105
|
-
index: TaskIndex,
|
|
106
|
-
): RefResolution {
|
|
107
|
-
if (isQualifiedRef(ref)) {
|
|
108
|
-
return index.allQualified.has(ref)
|
|
109
|
-
? { kind: 'resolved', qid: ref }
|
|
110
|
-
: { kind: 'not_found', ref };
|
|
111
|
-
}
|
|
112
|
-
const sameTrack = qualifyTaskId(fromTrackId, ref);
|
|
113
|
-
if (index.allQualified.has(sameTrack)) {
|
|
114
|
-
return { kind: 'resolved', qid: sameTrack };
|
|
115
|
-
}
|
|
116
|
-
const global = index.bareToQualified.get(ref);
|
|
117
|
-
if (global === AMBIGUOUS) return { kind: 'ambiguous', ref };
|
|
118
|
-
if (global !== undefined) return { kind: 'resolved', qid: global };
|
|
119
|
-
return { kind: 'not_found', ref };
|
|
120
|
-
}
|
|
1
|
+
// ═══ Task reference resolution — single source of truth ═══
|
|
2
|
+
//
|
|
3
|
+
// Before this module existed, four sites each carried their own copy of the
|
|
4
|
+
// "what is a valid id" + "how do I resolve a bare / same-track-shorthand /
|
|
5
|
+
// fully qualified ref" logic:
|
|
6
|
+
//
|
|
7
|
+
// - dag.ts/buildDag (threw on unresolved, threw on ambiguous)
|
|
8
|
+
// - dag.ts/buildRawDag (silently skipped unresolved and ambiguous)
|
|
9
|
+
// - validate-raw.ts (reported both as errors, with different wording)
|
|
10
|
+
// - engine.ts/resolveRefInDag (returned null on ambiguous)
|
|
11
|
+
//
|
|
12
|
+
// In addition, the editor shipped its own regex for id validation in
|
|
13
|
+
// `shared/config-id.ts` and a test-local copy in `config-id-generation.test.ts`,
|
|
14
|
+
// creating multiple places where the character set could drift from the
|
|
15
|
+
// validator. Bugs observed downstream (silent context loss when two tracks
|
|
16
|
+
// happened to share a bare task name; editor-generated ids occasionally
|
|
17
|
+
// failing SDK validate-raw) all traced back to this duplication.
|
|
18
|
+
//
|
|
19
|
+
// Callers now build a TaskIndex once and use `resolveTaskRef` to classify
|
|
20
|
+
// each reference, then decide themselves whether to throw / warn / skip —
|
|
21
|
+
// instead of re-implementing the index build and the lookup logic.
|
|
22
|
+
|
|
23
|
+
import type { PipelineConfig, RawPipelineConfig } from './types';
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* D8: task and track ids must match this pattern. No dots: the `.` is the
|
|
27
|
+
* qualified-id separator ("trackId.taskId"), so allowing it inside either
|
|
28
|
+
* part would make qid parsing ambiguous and break every resolver below.
|
|
29
|
+
*/
|
|
30
|
+
export const TASK_ID_RE = /^[A-Za-z_][A-Za-z0-9_-]*$/;
|
|
31
|
+
|
|
32
|
+
export function isValidTaskId(id: unknown): id is string {
|
|
33
|
+
return typeof id === 'string' && TASK_ID_RE.test(id);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Canonical qualified form used throughout the engine. */
|
|
37
|
+
export function qualifyTaskId(trackId: string, taskId: string): string {
|
|
38
|
+
return `${trackId}.${taskId}`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Does the reference already include a track prefix? */
|
|
42
|
+
export function isQualifiedRef(ref: string): boolean {
|
|
43
|
+
return ref.includes('.');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Sentinel stored in `TaskIndex.bareToQualified` when a bare task id is
|
|
48
|
+
* shared by more than one track, making it unresolvable without a prefix.
|
|
49
|
+
* Exposed so callers that want to inspect the index directly know what to
|
|
50
|
+
* look for — but prefer `resolveTaskRef` which returns a typed `kind`.
|
|
51
|
+
*/
|
|
52
|
+
export const AMBIGUOUS = '__ambiguous__';
|
|
53
|
+
|
|
54
|
+
export interface TaskIndex {
|
|
55
|
+
/** All fully-qualified ids ("trackId.taskId") present in the config. */
|
|
56
|
+
readonly allQualified: ReadonlySet<string>;
|
|
57
|
+
/** bare taskId → qid, or the {@link AMBIGUOUS} sentinel. */
|
|
58
|
+
readonly bareToQualified: ReadonlyMap<string, string>;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Build the index used by {@link resolveTaskRef}. Tolerant of partially
|
|
63
|
+
* malformed configs: tracks or tasks missing an `id` are skipped so the
|
|
64
|
+
* editor can call this during real-time validation on in-progress edits.
|
|
65
|
+
*/
|
|
66
|
+
export function buildTaskIndex(config: RawPipelineConfig | PipelineConfig): TaskIndex {
|
|
67
|
+
const allQualified = new Set<string>();
|
|
68
|
+
const bareToQualified = new Map<string, string>();
|
|
69
|
+
for (const track of config.tracks ?? []) {
|
|
70
|
+
if (!track?.id) continue;
|
|
71
|
+
for (const task of track.tasks ?? []) {
|
|
72
|
+
if (!task?.id) continue;
|
|
73
|
+
const qid = qualifyTaskId(track.id, task.id);
|
|
74
|
+
allQualified.add(qid);
|
|
75
|
+
if (bareToQualified.has(task.id)) {
|
|
76
|
+
bareToQualified.set(task.id, AMBIGUOUS);
|
|
77
|
+
} else {
|
|
78
|
+
bareToQualified.set(task.id, qid);
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return { allQualified, bareToQualified };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export type RefResolution =
|
|
86
|
+
| { readonly kind: 'resolved'; readonly qid: string }
|
|
87
|
+
| { readonly kind: 'ambiguous'; readonly ref: string }
|
|
88
|
+
| { readonly kind: 'not_found'; readonly ref: string };
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Resolve a dependency / continue_from reference to a canonical qid.
|
|
92
|
+
*
|
|
93
|
+
* 1. If the ref already contains a `.`, treat it as fully qualified —
|
|
94
|
+
* return `resolved` when the qid exists, `not_found` otherwise.
|
|
95
|
+
* 2. Otherwise, prefer the same-track shorthand (`fromTrackId.ref`).
|
|
96
|
+
* 3. Fall back to a global bare lookup. Returns `ambiguous` when more
|
|
97
|
+
* than one track has a task with that bare name.
|
|
98
|
+
*
|
|
99
|
+
* Callers decide the policy: `buildDag` throws on non-resolved, `buildRawDag`
|
|
100
|
+
* skips silently, `validateRaw` emits a structured ValidationError.
|
|
101
|
+
*/
|
|
102
|
+
export function resolveTaskRef(
|
|
103
|
+
ref: string,
|
|
104
|
+
fromTrackId: string,
|
|
105
|
+
index: TaskIndex,
|
|
106
|
+
): RefResolution {
|
|
107
|
+
if (isQualifiedRef(ref)) {
|
|
108
|
+
return index.allQualified.has(ref)
|
|
109
|
+
? { kind: 'resolved', qid: ref }
|
|
110
|
+
: { kind: 'not_found', ref };
|
|
111
|
+
}
|
|
112
|
+
const sameTrack = qualifyTaskId(fromTrackId, ref);
|
|
113
|
+
if (index.allQualified.has(sameTrack)) {
|
|
114
|
+
return { kind: 'resolved', qid: sameTrack };
|
|
115
|
+
}
|
|
116
|
+
const global = index.bareToQualified.get(ref);
|
|
117
|
+
if (global === AMBIGUOUS) return { kind: 'ambiguous', ref };
|
|
118
|
+
if (global !== undefined) return { kind: 'resolved', qid: global };
|
|
119
|
+
return { kind: 'not_found', ref };
|
|
120
|
+
}
|
package/src/triggers/file.ts
CHANGED
|
@@ -1,164 +1,164 @@
|
|
|
1
|
-
import { watch } from 'chokidar';
|
|
2
|
-
import { resolve, dirname } from 'path';
|
|
3
|
-
import { mkdir } from 'fs/promises';
|
|
4
|
-
import type { TriggerPlugin, TriggerContext } from '../types';
|
|
5
|
-
import { parseDuration, validatePath } from '../utils';
|
|
6
|
-
import { TriggerTimeoutError } from '../engine';
|
|
7
|
-
|
|
8
|
-
const IS_WINDOWS = process.platform === 'win32';
|
|
9
|
-
|
|
10
|
-
function pathsEqual(a: string, b: string): boolean {
|
|
11
|
-
return IS_WINDOWS ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
export const FileTrigger: TriggerPlugin = {
|
|
15
|
-
name: 'file',
|
|
16
|
-
schema: {
|
|
17
|
-
description: 'Wait for a file to appear or be modified before the task runs.',
|
|
18
|
-
fields: {
|
|
19
|
-
path: {
|
|
20
|
-
type: 'path',
|
|
21
|
-
required: true,
|
|
22
|
-
description: 'Path to the file to watch (relative to workDir or absolute).',
|
|
23
|
-
placeholder: 'e.g. build/output.json',
|
|
24
|
-
},
|
|
25
|
-
timeout: {
|
|
26
|
-
type: 'duration',
|
|
27
|
-
description: 'Maximum wait time (e.g. 30s, 5m). Omit or 0 to wait indefinitely.',
|
|
28
|
-
placeholder: '30s',
|
|
29
|
-
},
|
|
30
|
-
},
|
|
31
|
-
},
|
|
32
|
-
|
|
33
|
-
watch(config: Record<string, unknown>, ctx: TriggerContext): Promise<unknown> {
|
|
34
|
-
const filePath = config.path as string;
|
|
35
|
-
if (!filePath) throw new Error(`file trigger: "path" is required`);
|
|
36
|
-
|
|
37
|
-
const safePath = validatePath(filePath, ctx.workDir);
|
|
38
|
-
const timeoutMs = config.timeout != null ? parseDuration(String(config.timeout)) : 0;
|
|
39
|
-
|
|
40
|
-
// Hoist the async work into a named async function so the Promise
|
|
41
|
-
// constructor itself is synchronous — avoids the no-async-promise-executor
|
|
42
|
-
// lint error and ensures exceptions are always propagated via reject().
|
|
43
|
-
async function start(
|
|
44
|
-
resolve_p: (value: unknown) => void,
|
|
45
|
-
reject: (reason?: unknown) => void,
|
|
46
|
-
): Promise<void> {
|
|
47
|
-
if (ctx.signal.aborted) {
|
|
48
|
-
reject(new Error('Pipeline aborted'));
|
|
49
|
-
return;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
let settled = false;
|
|
53
|
-
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
54
|
-
|
|
55
|
-
// Ensure the parent directory exists so the watcher doesn't fail
|
|
56
|
-
// with ENOENT for nested paths like `build/output/result.json`.
|
|
57
|
-
const dir = dirname(safePath);
|
|
58
|
-
try {
|
|
59
|
-
await mkdir(dir, { recursive: true });
|
|
60
|
-
} catch {
|
|
61
|
-
/* best effort — dir may already exist */
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
// Pass `cwd: dir` so chokidar resolves paths relative to the watched
|
|
65
|
-
// directory. The 'add'/'change' events will then carry paths relative
|
|
66
|
-
// to `dir`, which we resolve with `resolve(dir, addedPath)` for an
|
|
67
|
-
// accurate absolute comparison — fixing the ambiguous process.cwd()
|
|
68
|
-
// resolution of the previous implementation.
|
|
69
|
-
const watcher = watch(dir, {
|
|
70
|
-
ignoreInitial: true,
|
|
71
|
-
depth: 0,
|
|
72
|
-
cwd: dir,
|
|
73
|
-
awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 50 },
|
|
74
|
-
});
|
|
75
|
-
|
|
76
|
-
const cleanup = () => {
|
|
77
|
-
if (settled) return;
|
|
78
|
-
settled = true;
|
|
79
|
-
watcher.close().catch(() => {
|
|
80
|
-
/* ignore */
|
|
81
|
-
});
|
|
82
|
-
if (timer) clearTimeout(timer);
|
|
83
|
-
ctx.signal.removeEventListener('abort', onAbort);
|
|
84
|
-
};
|
|
85
|
-
|
|
86
|
-
const onAbort = () => {
|
|
87
|
-
cleanup();
|
|
88
|
-
reject(new Error('Pipeline aborted'));
|
|
89
|
-
};
|
|
90
|
-
|
|
91
|
-
watcher.on('add', (addedPath: string) => {
|
|
92
|
-
if (settled) return;
|
|
93
|
-
if (pathsEqual(resolve(dir, addedPath), safePath)) {
|
|
94
|
-
cleanup();
|
|
95
|
-
resolve_p({ path: safePath });
|
|
96
|
-
}
|
|
97
|
-
});
|
|
98
|
-
|
|
99
|
-
// Also fire on 'change' so that overwriting an existing file is detected.
|
|
100
|
-
// Without this, upstream tasks that truncate-and-rewrite a file emit only
|
|
101
|
-
// a 'change' event and the downstream trigger would never resolve.
|
|
102
|
-
watcher.on('change', (changedPath: string) => {
|
|
103
|
-
if (settled) return;
|
|
104
|
-
if (pathsEqual(resolve(dir, changedPath), safePath)) {
|
|
105
|
-
cleanup();
|
|
106
|
-
resolve_p({ path: safePath });
|
|
107
|
-
}
|
|
108
|
-
});
|
|
109
|
-
|
|
110
|
-
watcher.on('error', (err: unknown) => {
|
|
111
|
-
if (settled) return;
|
|
112
|
-
cleanup();
|
|
113
|
-
reject(
|
|
114
|
-
new Error(
|
|
115
|
-
`file trigger watch error: ${err instanceof Error ? err.message : String(err)}`,
|
|
116
|
-
),
|
|
117
|
-
);
|
|
118
|
-
});
|
|
119
|
-
|
|
120
|
-
// After the watcher finishes its initial scan, check if the file already exists.
|
|
121
|
-
// Doing this inside 'ready' eliminates the race window between existence check
|
|
122
|
-
// and watcher startup, so we neither miss events nor double-resolve.
|
|
123
|
-
watcher.on('ready', () => {
|
|
124
|
-
if (settled) return;
|
|
125
|
-
Bun.file(safePath)
|
|
126
|
-
.exists()
|
|
127
|
-
.then((exists) => {
|
|
128
|
-
if (settled) return;
|
|
129
|
-
if (exists) {
|
|
130
|
-
cleanup();
|
|
131
|
-
resolve_p({ path: safePath });
|
|
132
|
-
}
|
|
133
|
-
})
|
|
134
|
-
.catch((err: unknown) => {
|
|
135
|
-
if (settled) return;
|
|
136
|
-
cleanup();
|
|
137
|
-
reject(
|
|
138
|
-
new Error(
|
|
139
|
-
`file trigger existence check failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
140
|
-
),
|
|
141
|
-
);
|
|
142
|
-
});
|
|
143
|
-
});
|
|
144
|
-
|
|
145
|
-
if (timeoutMs > 0) {
|
|
146
|
-
timer = setTimeout(() => {
|
|
147
|
-
if (settled) return;
|
|
148
|
-
cleanup();
|
|
149
|
-
reject(
|
|
150
|
-
new TriggerTimeoutError(
|
|
151
|
-
`file trigger timeout: ${filePath} did not appear within ${config.timeout}`,
|
|
152
|
-
),
|
|
153
|
-
);
|
|
154
|
-
}, timeoutMs);
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
ctx.signal.addEventListener('abort', onAbort);
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
return new Promise((resolve_p, reject) => {
|
|
161
|
-
start(resolve_p, reject).catch(reject);
|
|
162
|
-
});
|
|
163
|
-
},
|
|
164
|
-
};
|
|
1
|
+
import { watch } from 'chokidar';
|
|
2
|
+
import { resolve, dirname } from 'path';
|
|
3
|
+
import { mkdir } from 'fs/promises';
|
|
4
|
+
import type { TriggerPlugin, TriggerContext } from '../types';
|
|
5
|
+
import { parseDuration, validatePath } from '../utils';
|
|
6
|
+
import { TriggerTimeoutError } from '../engine';
|
|
7
|
+
|
|
8
|
+
const IS_WINDOWS = process.platform === 'win32';
|
|
9
|
+
|
|
10
|
+
function pathsEqual(a: string, b: string): boolean {
|
|
11
|
+
return IS_WINDOWS ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const FileTrigger: TriggerPlugin = {
|
|
15
|
+
name: 'file',
|
|
16
|
+
schema: {
|
|
17
|
+
description: 'Wait for a file to appear or be modified before the task runs.',
|
|
18
|
+
fields: {
|
|
19
|
+
path: {
|
|
20
|
+
type: 'path',
|
|
21
|
+
required: true,
|
|
22
|
+
description: 'Path to the file to watch (relative to workDir or absolute).',
|
|
23
|
+
placeholder: 'e.g. build/output.json',
|
|
24
|
+
},
|
|
25
|
+
timeout: {
|
|
26
|
+
type: 'duration',
|
|
27
|
+
description: 'Maximum wait time (e.g. 30s, 5m). Omit or 0 to wait indefinitely.',
|
|
28
|
+
placeholder: '30s',
|
|
29
|
+
},
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
|
|
33
|
+
watch(config: Record<string, unknown>, ctx: TriggerContext): Promise<unknown> {
|
|
34
|
+
const filePath = config.path as string;
|
|
35
|
+
if (!filePath) throw new Error(`file trigger: "path" is required`);
|
|
36
|
+
|
|
37
|
+
const safePath = validatePath(filePath, ctx.workDir);
|
|
38
|
+
const timeoutMs = config.timeout != null ? parseDuration(String(config.timeout)) : 0;
|
|
39
|
+
|
|
40
|
+
// Hoist the async work into a named async function so the Promise
|
|
41
|
+
// constructor itself is synchronous — avoids the no-async-promise-executor
|
|
42
|
+
// lint error and ensures exceptions are always propagated via reject().
|
|
43
|
+
async function start(
|
|
44
|
+
resolve_p: (value: unknown) => void,
|
|
45
|
+
reject: (reason?: unknown) => void,
|
|
46
|
+
): Promise<void> {
|
|
47
|
+
if (ctx.signal.aborted) {
|
|
48
|
+
reject(new Error('Pipeline aborted'));
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
let settled = false;
|
|
53
|
+
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
54
|
+
|
|
55
|
+
// Ensure the parent directory exists so the watcher doesn't fail
|
|
56
|
+
// with ENOENT for nested paths like `build/output/result.json`.
|
|
57
|
+
const dir = dirname(safePath);
|
|
58
|
+
try {
|
|
59
|
+
await mkdir(dir, { recursive: true });
|
|
60
|
+
} catch {
|
|
61
|
+
/* best effort — dir may already exist */
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// Pass `cwd: dir` so chokidar resolves paths relative to the watched
|
|
65
|
+
// directory. The 'add'/'change' events will then carry paths relative
|
|
66
|
+
// to `dir`, which we resolve with `resolve(dir, addedPath)` for an
|
|
67
|
+
// accurate absolute comparison — fixing the ambiguous process.cwd()
|
|
68
|
+
// resolution of the previous implementation.
|
|
69
|
+
const watcher = watch(dir, {
|
|
70
|
+
ignoreInitial: true,
|
|
71
|
+
depth: 0,
|
|
72
|
+
cwd: dir,
|
|
73
|
+
awaitWriteFinish: { stabilityThreshold: 100, pollInterval: 50 },
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
const cleanup = () => {
|
|
77
|
+
if (settled) return;
|
|
78
|
+
settled = true;
|
|
79
|
+
watcher.close().catch(() => {
|
|
80
|
+
/* ignore */
|
|
81
|
+
});
|
|
82
|
+
if (timer) clearTimeout(timer);
|
|
83
|
+
ctx.signal.removeEventListener('abort', onAbort);
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const onAbort = () => {
|
|
87
|
+
cleanup();
|
|
88
|
+
reject(new Error('Pipeline aborted'));
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
watcher.on('add', (addedPath: string) => {
|
|
92
|
+
if (settled) return;
|
|
93
|
+
if (pathsEqual(resolve(dir, addedPath), safePath)) {
|
|
94
|
+
cleanup();
|
|
95
|
+
resolve_p({ path: safePath });
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// Also fire on 'change' so that overwriting an existing file is detected.
|
|
100
|
+
// Without this, upstream tasks that truncate-and-rewrite a file emit only
|
|
101
|
+
// a 'change' event and the downstream trigger would never resolve.
|
|
102
|
+
watcher.on('change', (changedPath: string) => {
|
|
103
|
+
if (settled) return;
|
|
104
|
+
if (pathsEqual(resolve(dir, changedPath), safePath)) {
|
|
105
|
+
cleanup();
|
|
106
|
+
resolve_p({ path: safePath });
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
watcher.on('error', (err: unknown) => {
|
|
111
|
+
if (settled) return;
|
|
112
|
+
cleanup();
|
|
113
|
+
reject(
|
|
114
|
+
new Error(
|
|
115
|
+
`file trigger watch error: ${err instanceof Error ? err.message : String(err)}`,
|
|
116
|
+
),
|
|
117
|
+
);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
// After the watcher finishes its initial scan, check if the file already exists.
|
|
121
|
+
// Doing this inside 'ready' eliminates the race window between existence check
|
|
122
|
+
// and watcher startup, so we neither miss events nor double-resolve.
|
|
123
|
+
watcher.on('ready', () => {
|
|
124
|
+
if (settled) return;
|
|
125
|
+
Bun.file(safePath)
|
|
126
|
+
.exists()
|
|
127
|
+
.then((exists) => {
|
|
128
|
+
if (settled) return;
|
|
129
|
+
if (exists) {
|
|
130
|
+
cleanup();
|
|
131
|
+
resolve_p({ path: safePath });
|
|
132
|
+
}
|
|
133
|
+
})
|
|
134
|
+
.catch((err: unknown) => {
|
|
135
|
+
if (settled) return;
|
|
136
|
+
cleanup();
|
|
137
|
+
reject(
|
|
138
|
+
new Error(
|
|
139
|
+
`file trigger existence check failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
140
|
+
),
|
|
141
|
+
);
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
if (timeoutMs > 0) {
|
|
146
|
+
timer = setTimeout(() => {
|
|
147
|
+
if (settled) return;
|
|
148
|
+
cleanup();
|
|
149
|
+
reject(
|
|
150
|
+
new TriggerTimeoutError(
|
|
151
|
+
`file trigger timeout: ${filePath} did not appear within ${config.timeout}`,
|
|
152
|
+
),
|
|
153
|
+
);
|
|
154
|
+
}, timeoutMs);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
ctx.signal.addEventListener('abort', onAbort);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return new Promise((resolve_p, reject) => {
|
|
161
|
+
start(resolve_p, reject).catch(reject);
|
|
162
|
+
});
|
|
163
|
+
},
|
|
164
|
+
};
|