From 81dc9d3a70221d2b0e9b35c80401746e84d41780 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Mon, 6 Jul 2026 21:26:55 -0500 Subject: [PATCH] feat(validation): vendor Standard Schema types + isStandardSchema/flattenPath Signed-off-by: Diego Resendez --- src/standard-schema.ts | 34 ++++++++++++++++++++++++++++++++++ test/standard-schema.test.ts | 23 +++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 src/standard-schema.ts create mode 100644 test/standard-schema.test.ts diff --git a/src/standard-schema.ts b/src/standard-schema.ts new file mode 100644 index 0000000..dde28c1 --- /dev/null +++ b/src/standard-schema.ts @@ -0,0 +1,34 @@ +// src/standard-schema.ts — vendored Standard Schema (~standard) types + helpers. No imports. +export interface StandardSchemaV1 { + readonly '~standard': { + readonly version: 1; + readonly vendor: string; + validate(value: unknown): StandardResult | Promise>; + readonly types?: { readonly input: Input; readonly output: Output }; + }; +} + +export type StandardResult = + | { readonly value: T; readonly issues?: undefined } + | { readonly issues: ReadonlyArray }; + +export interface StandardIssue { + readonly message: string; + readonly path?: ReadonlyArray; +} + +export function isStandardSchema(x: unknown): x is StandardSchemaV1 { + return ( + typeof x === 'object' && x !== null && + '~standard' in x && + typeof (x as { ['~standard']?: { validate?: unknown } })['~standard']?.validate === 'function' + ); +} + +export function flattenPath(issue: StandardIssue): string { + if (!issue.path) return ''; + return issue.path + .map((seg) => (typeof seg === 'object' && seg !== null && 'key' in seg ? seg.key : seg)) + .map((k) => String(k)) + .join('.'); +} diff --git a/test/standard-schema.test.ts b/test/standard-schema.test.ts new file mode 100644 index 0000000..1c59d34 --- /dev/null +++ b/test/standard-schema.test.ts @@ -0,0 +1,23 @@ +import { describe, it, expect } from 'vitest'; +import { isStandardSchema, flattenPath } from '../src/standard-schema'; + +const schema = { '~standard': { version: 1, vendor: 't', validate: (v: unknown) => ({ value: v }) } }; + +describe('isStandardSchema', () => { + it('true for a Standard Schema, false for string/array/plain object/null', () => { + expect(isStandardSchema(schema)).toBe(true); + expect(isStandardSchema('id')).toBe(false); + expect(isStandardSchema(['a', 'b'])).toBe(false); + expect(isStandardSchema({})).toBe(false); + expect(isStandardSchema(null)).toBe(false); + expect(isStandardSchema({ '~standard': {} })).toBe(false); // no validate fn + }); +}); + +describe('flattenPath', () => { + it('flattens key + {key} segments to a dot string', () => { + expect(flattenPath({ message: 'x', path: ['address', 'city'] })).toBe('address.city'); + expect(flattenPath({ message: 'x', path: ['items', 0, { key: 'qty' }] })).toBe('items.0.qty'); + expect(flattenPath({ message: 'x' })).toBe(''); + }); +});