-
-
Notifications
You must be signed in to change notification settings - Fork 313
Expand file tree
/
Copy pathpayload-input.ts
More file actions
55 lines (49 loc) · 1.7 KB
/
Copy pathpayload-input.ts
File metadata and controls
55 lines (49 loc) · 1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import fs from 'node:fs';
import { AppError } from '@agent-device/kernel/errors';
function looksLikeInlineJson(value: string): boolean {
const trimmed = value.trim();
return (
(trimmed.startsWith('{') && trimmed.endsWith('}')) ||
(trimmed.startsWith('[') && trimmed.endsWith(']'))
);
}
export type ResolvedPayloadInput =
| { kind: 'file'; path: string }
| { kind: 'inline'; text: string };
export function resolvePayloadInput(
value: string,
options?: {
subject?: string;
cwd?: string;
expandPath?: (value: string, cwd?: string) => string;
},
): ResolvedPayloadInput {
const subject = options?.subject ?? 'Payload';
const trimmed = value.trim();
if (!trimmed) {
throw new AppError('INVALID_ARGS', `${subject} cannot be empty`);
}
const resolvedPath = options?.expandPath ? options.expandPath(trimmed, options.cwd) : trimmed;
try {
const stat = fs.statSync(resolvedPath);
if (!stat.isFile()) {
throw new AppError('INVALID_ARGS', `${subject} path is not a file: ${resolvedPath}`);
}
return { kind: 'file', path: resolvedPath };
} catch (error) {
if (error instanceof AppError) throw error;
const code = (error as NodeJS.ErrnoException).code;
if (code === 'EACCES' || code === 'EPERM') {
throw new AppError('INVALID_ARGS', `${subject} file is not readable: ${resolvedPath}`);
}
if (code && code !== 'ENOENT') {
throw new AppError('COMMAND_FAILED', `Unable to read ${subject} file: ${resolvedPath}`, {
cause: String(error),
});
}
}
if (looksLikeInlineJson(trimmed)) {
return { kind: 'inline', text: trimmed };
}
throw new AppError('INVALID_ARGS', `${subject} file not found: ${resolvedPath}`);
}