forked from aws/agentcore-cli
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdocument.ts
More file actions
64 lines (56 loc) · 1.74 KB
/
Copy pathdocument.ts
File metadata and controls
64 lines (56 loc) · 1.74 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
56
57
58
59
60
61
62
63
64
import { readFile, writeFile } from 'fs/promises';
import type { ZodType } from 'zod';
export interface LoadDocumentResult {
content: string;
validationError?: string;
}
export interface SaveDocumentResult {
ok: boolean;
content?: string;
error?: string;
}
/**
* Loads a JSON document and optionally validates it against a schema.
* Returns the raw content and any validation errors.
*/
export async function loadSchemaDocument<T>(filePath: string, schema: ZodType<T>): Promise<LoadDocumentResult> {
const content = await readFile(filePath, 'utf-8');
let validationError: string | undefined;
try {
const parsed: unknown = JSON.parse(content);
const result = schema.safeParse(parsed);
if (!result.success) {
validationError = result.error.message;
}
} catch (err) {
validationError = err instanceof Error ? err.message : 'Invalid JSON';
}
return { content, validationError };
}
/**
* Validates and saves a JSON document.
* Returns the formatted content on success, or an error message on failure.
*/
export async function saveSchemaDocument<T>(
filePath: string,
content: string,
schema: ZodType<T>
): Promise<SaveDocumentResult> {
let parsed: unknown;
try {
parsed = JSON.parse(content);
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : 'Invalid JSON' };
}
const result = schema.safeParse(parsed);
if (!result.success) {
return { ok: false, error: result.error.message };
}
const formatted = JSON.stringify(result.data, null, 2);
try {
await writeFile(filePath, formatted, 'utf-8');
return { ok: true, content: formatted };
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : 'Failed to write file' };
}
}