Skip to content

Commit

Permalink
feat(schema-utils): Support Toml format (#23930)
Browse files Browse the repository at this point in the history
  • Loading branch information
zharinov committed Aug 18, 2023
1 parent 24c49a7 commit 0777f54
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
53 changes: 53 additions & 0 deletions lib/util/schema-utils.spec.ts
@@ -1,9 +1,11 @@
import { codeBlock } from 'common-tags';
import { z } from 'zod';
import {
Json,
Json5,
LooseArray,
LooseRecord,
Toml,
Url,
UtcDate,
Yaml,
Expand Down Expand Up @@ -340,4 +342,55 @@ describe('util/schema-utils', () => {
});
});
});

describe('Toml', () => {
const Schema = Toml.pipe(
z.object({ foo: z.object({ bar: z.literal('baz') }) })
);

it('parses valid toml', () => {
const content = codeBlock`
[foo]
bar = "baz"
`;
expect(Schema.parse(content)).toEqual({
foo: { bar: 'baz' },
});
});

it('throws error for invalid schema', () => {
const content = codeBlock`
[foo]
bar = "brb"
`;
expect(Schema.safeParse(content)).toMatchObject({
error: {
issues: [
{
received: 'brb',
code: 'invalid_literal',
expected: 'baz',
path: ['foo', 'bar'],
},
],
},
success: false,
});
});

it('throws error for invalid toml', () => {
expect(Schema.safeParse('clearly_invalid')).toMatchObject({
error: {
issues: [
{
message: 'Invalid TOML',
code: 'custom',
path: [],
},
],
},
success: false,
});
});
});
});
10 changes: 10 additions & 0 deletions lib/util/schema-utils.ts
@@ -1,3 +1,4 @@
import { JsonMap, parse } from '@iarna/toml';
import { load } from 'js-yaml';
import JSON5 from 'json5';
import { DateTime } from 'luxon';
Expand Down Expand Up @@ -242,3 +243,12 @@ export const Yaml = z.string().transform((str, ctx): JsonValue => {
return z.NEVER;
}
});

export const Toml = z.string().transform((str, ctx): JsonMap => {
try {
return parse(str);
} catch (e) {
ctx.addIssue({ code: 'custom', message: 'Invalid TOML' });
return z.NEVER;
}
});

0 comments on commit 0777f54

Please sign in to comment.