@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

main
ts 59 lines 1.92 KB
Raw
1 import * as Effect from "effect/Effect";
2 import * as Schema from "effect/Schema";
3 import * as SchemaGetter from "effect/SchemaGetter";
4 import * as SchemaIssue from "effect/SchemaIssue";
5 import * as SchemaTransformation from "effect/SchemaTransformation";
6 import {
7 YAMLParseError,
8 parse as parseYamlString,
9 stringify as stringifyYamlValue,
10 type CreateNodeOptions,
11 type DocumentOptions,
12 type ParseOptions,
13 type SchemaOptions,
14 type ToJSOptions,
15 type ToStringOptions,
16 } from "yaml";
17
18 export type YamlParseOptions = ParseOptions & DocumentOptions & SchemaOptions & ToJSOptions;
19 export type YamlStringifyOptions = DocumentOptions &
20 SchemaOptions &
21 ParseOptions &
22 CreateNodeOptions &
23 ToStringOptions;
24
25 function formatYamlParseError(error: unknown): string {
26 if (!(error instanceof YAMLParseError)) {
27 return "Invalid YAML.";
28 }
29
30 const position = error.linePos?.[0];
31 const location = position === undefined ? "" : `, line=${position.line}, column=${position.col}`;
32 return `Invalid YAML (code=${error.code}${location}).`;
33 }
34
35 function parseYaml<E extends string>(options?: YamlParseOptions): SchemaGetter.Getter<unknown, E> {
36 return SchemaGetter.transformEffect((input: E) =>
37 Effect.try({
38 try: () => parseYamlString(input, options) as unknown,
39 catch: (error) => new SchemaIssue.InvalidValue({ message: formatYamlParseError(error) }),
40 }),
41 );
42 }
43
44 function stringifyYaml(options?: YamlStringifyOptions): SchemaGetter.Getter<string, unknown> {
45 return SchemaGetter.transformEffect((input: unknown) =>
46 Effect.try({
47 try: () => stringifyYamlValue(input, options),
48 catch: () => new SchemaIssue.InvalidValue({ message: "Failed to stringify YAML." }),
49 }),
50 );
51 }
52
53 const fromYamlString = new SchemaTransformation.Transformation<unknown, string>(
54 parseYaml(),
55 stringifyYaml(),
56 );
57
58 export const fromYaml = <S extends Schema.Top>(schema: S) =>
59 Schema.String.pipe(Schema.decodeTo(schema, fromYamlString));