Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Implement standard schema interface #2258

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
"@babel/preset-typescript": "^7.22.5",
"@rollup/plugin-babel": "^5.3.1",
"@rollup/plugin-node-resolve": "^13.3.0",
"@standard-schema/spec": "^1.0.0-rc.0",
"@types/jest": "^27.5.2",
"@typescript-eslint/eslint-plugin": "^5.62.0",
"@typescript-eslint/parser": "^5.62.0",
Expand Down
19 changes: 18 additions & 1 deletion src/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ import isAbsent from './util/isAbsent';
import type { Flags, Maybe, ResolveFlags, _ } from './util/types';
import toArray from './util/toArray';
import cloneDeep from './util/cloneDeep';
import {
createStandardSchemaProps,
type StandardSchema,
type StandardSchemaProps,
} from './standardSchema';

export type SchemaSpec<TDefault> = {
coerce: boolean;
Expand Down Expand Up @@ -147,7 +152,9 @@ export default abstract class Schema<
TContext = any,
TDefault = any,
TFlags extends Flags = '',
> implements ISchema<TType, TContext, TFlags, TDefault>
> implements
ISchema<TType, TContext, TFlags, TDefault>,
StandardSchema<TType, ResolveFlags<TType, TFlags, TDefault>>
{
readonly type: string;

Expand All @@ -174,6 +181,11 @@ export default abstract class Schema<
protected exclusiveTests: Record<string, boolean> = Object.create(null);
protected _typeCheck: (value: any) => value is NonNullable<TType>;

public '~standard': StandardSchemaProps<
TType,
ResolveFlags<TType, TFlags, TDefault>
>;

spec: SchemaSpec<any>;

constructor(options: SchemaOptions<TType, any>) {
Expand Down Expand Up @@ -202,6 +214,11 @@ export default abstract class Schema<
this.withMutation((s) => {
s.nonNullable();
});

this['~standard'] = createStandardSchemaProps<
TType,
ResolveFlags<TType, TFlags, TDefault>
>(this);
}

// TODO: remove
Expand Down
176 changes: 176 additions & 0 deletions src/standardSchema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
/**
* Copied from @standard-schema/spec to avoid having a dependency on it.
* https://github.com/standard-schema/standard-schema/blob/main/packages/spec/src/index.ts
*/

import type { AnySchema } from './types';
import ValidationError from './ValidationError';

export interface StandardSchema<Input = unknown, Output = Input> {
readonly '~standard': StandardSchemaProps<Input, Output>;
}

export interface StandardSchemaProps<Input = unknown, Output = Input> {
readonly version: 1;
readonly vendor: string;
readonly validate: (
value: unknown,
) => StandardResult<Output> | Promise<StandardResult<Output>>;
readonly types?: StandardTypes<Input, Output> | undefined;
}

type StandardResult<Output> =
| StandardSuccessResult<Output>
| StandardFailureResult;

interface StandardSuccessResult<Output> {
readonly value: Output;
readonly issues?: undefined;
}

interface StandardFailureResult {
readonly issues: ReadonlyArray<StandardIssue>;
}

interface StandardIssue {
readonly message: string;
readonly path?: ReadonlyArray<PropertyKey | StandardPathSegment> | undefined;
}

interface StandardPathSegment {
readonly key: PropertyKey;
}

interface StandardTypes<Input, Output> {
readonly input: Input;
readonly output: Output;
}

export function createStandardSchemaProps<TIn, Output>(
schema: AnySchema,
): StandardSchemaProps<TIn, Output> {
/**
* Adapts the schema's validate method to the standard schema's validate method.
*/
async function validate(value: unknown): Promise<StandardResult<Output>> {
try {
const result = await schema.validate(value, {
abortEarly: false,
});

return {
value: result as Output,
};
} catch (err) {
if (err instanceof ValidationError) {
return {
issues: issuesFromValidationError(err),
};
}

throw err;
}
}

return {
version: 1,
vendor: 'yup',
validate,
};
}

function createStandardPath(path: string | undefined): StandardIssue['path'] {
if (!path?.length) {
return undefined;
}

// Array to store the final path segments
const segments: string[] = [];
// Buffer for building the current segment
let currentSegment = '';
// Track if we're inside square brackets (array/property access)
let inBrackets = false;
// Track if we're inside quotes (for property names with special chars)
let inQuotes = false;

for (let i = 0; i < path.length; i++) {
const char = path[i];

if (char === '[' && !inQuotes) {
// When entering brackets, push any accumulated segment after splitting on dots
if (currentSegment) {
segments.push(...currentSegment.split('.').filter(Boolean));
currentSegment = '';
}
inBrackets = true;
continue;
}

if (char === ']' && !inQuotes) {
if (currentSegment) {
// Handle numeric indices (e.g. arr[0])
if (/^\d+$/.test(currentSegment)) {
segments.push(currentSegment);
} else {
// Handle quoted property names (e.g. obj["foo.bar"])
segments.push(currentSegment.replace(/^"|"$/g, ''));
}
currentSegment = '';
}
inBrackets = false;
continue;
}

if (char === '"') {
// Toggle quote state for handling quoted property names
inQuotes = !inQuotes;
continue;
}

if (char === '.' && !inBrackets && !inQuotes) {
// On dots outside brackets/quotes, push current segment
if (currentSegment) {
segments.push(currentSegment);
currentSegment = '';
}
continue;
}

currentSegment += char;
}

// Push any remaining segment after splitting on dots
if (currentSegment) {
segments.push(...currentSegment.split('.').filter(Boolean));
}

return segments;
}

function createStandardIssues(
error: ValidationError,
parentPath?: string,
): StandardIssue[] {
const path = parentPath ? `${parentPath}.${error.path}` : error.path;

return error.errors.map(
(err) =>
({
message: err,
path: createStandardPath(path),
} satisfies StandardIssue),
);
}

function issuesFromValidationError(
error: ValidationError,
parentPath?: string,
): StandardIssue[] {
if (!error.inner?.length && error.errors.length) {
return createStandardIssues(error, parentPath);
}

const path = parentPath ? `${parentPath}.${error.path}` : error.path;

return error.inner.flatMap((err) => issuesFromValidationError(err, path));
}
67 changes: 67 additions & 0 deletions test/standardSchema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import {
string,
number,
array,
bool,
object,
date,
mixed,
tuple,
} from '../src';
import type { StandardSchemaV1 } from '@standard-schema/spec';

function verifyStandardSchema<Input, Output>(
schema: StandardSchemaV1<Input, Output>,
) {
return (
schema['~standard'].version === 1 &&
schema['~standard'].vendor === 'yup' &&
typeof schema['~standard'].validate === 'function'
);
}

test('is compatible with standard schema', () => {
expect(verifyStandardSchema(string())).toBe(true);
expect(verifyStandardSchema(number())).toBe(true);
expect(verifyStandardSchema(array())).toBe(true);
expect(verifyStandardSchema(bool())).toBe(true);
expect(verifyStandardSchema(object())).toBe(true);
expect(verifyStandardSchema(date())).toBe(true);
expect(verifyStandardSchema(mixed())).toBe(true);
expect(verifyStandardSchema(tuple([mixed()]))).toBe(true);
});

test('issues path is an array of property paths', async () => {
const schema = object({
obj: object({
foo: string().required(),
'not.obj.nested': string().required(),
}).required(),
arr: array(
object({
foo: string().required(),
'not.array.nested': string().required(),
}),
).required(),
'not.a.field': string().required(),
});

const result = await schema['~standard'].validate({
obj: { foo: '', 'not.obj.nested': '' },
arr: [{ foo: '', 'not.array.nested': '' }],
});

expect(result.issues).toEqual([
{ path: ['obj', 'foo'], message: 'obj.foo is a required field' },
{
path: ['obj', 'not.obj.nested'],
message: 'obj["not.obj.nested"] is a required field',
},
{ path: ['arr', '0', 'foo'], message: 'arr[0].foo is a required field' },
{
path: ['arr', '0', 'not.array.nested'],
message: 'arr[0]["not.array.nested"] is a required field',
},
{ path: ['not.a.field'], message: '["not.a.field"] is a required field' },
]);
});
8 changes: 8 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2203,6 +2203,13 @@ __metadata:
languageName: node
linkType: hard

"@standard-schema/spec@npm:^1.0.0-rc.0":
version: 1.0.0-rc.0
resolution: "@standard-schema/spec@npm:1.0.0-rc.0"
checksum: 10c0/ddc5352a51704760717b91d27a5ea26724e0d36771cf3b8ac266b1ae930fe3cfb1159ad7b3cea157c3ca1e0c650aa15fd9e7b3f2540ae074c716a147a276d3f0
languageName: node
linkType: hard

"@textlint/ast-node-types@npm:^12.1.1":
version: 12.1.1
resolution: "@textlint/ast-node-types@npm:12.1.1"
Expand Down Expand Up @@ -15117,6 +15124,7 @@ __metadata:
"@babel/preset-typescript": "npm:^7.22.5"
"@rollup/plugin-babel": "npm:^5.3.1"
"@rollup/plugin-node-resolve": "npm:^13.3.0"
"@standard-schema/spec": "npm:^1.0.0-rc.0"
"@types/jest": "npm:^27.5.2"
"@typescript-eslint/eslint-plugin": "npm:^5.62.0"
"@typescript-eslint/parser": "npm:^5.62.0"
Expand Down