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 #1

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
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-beta.4",
"@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
179 changes: 179 additions & 0 deletions src/standardSchema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
/**
* 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[] {
return error.errors.map(
(err) =>
({
message: err,
path: createStandardPath(
parentPath ? `${parentPath}.${error.path}` : error.path,
Copy link

@Sheraff Sheraff Dec 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like this string here is not dependant on the map item err, so could it be declared outside of the .map for a (very minor) perf improvement? Or should it actually depend on the err item somehow?

(And the same goes for the .flatMap in issuesFromValidationError)

),
} satisfies StandardIssue),
);
}

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

return error.inner.flatMap((err) =>
issuesFromValidationError(
err,
parentPath ? `${parentPath}.${error.path}` : error.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' },
]);
});
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1592,6 +1592,11 @@
dependencies:
"@sinonjs/commons" "^1.7.0"

"@standard-schema/spec@^1.0.0-beta.4":
version "1.0.0-beta.4"
resolved "https://registry.yarnpkg.com/@standard-schema/spec/-/spec-1.0.0-beta.4.tgz#62f520109add3eb016004098363bfee0678dd1ec"
integrity sha512-d3IxtzLo7P1oZ8s8YNvxzBUXRXojSut8pbPrTYtzsc5sn4+53jVqbk66pQerSZbZSJZQux6LkclB/+8IDordHg==

"@textlint/ast-node-types@^12.1.1":
version "12.1.1"
resolved "https://registry.yarnpkg.com/@textlint/ast-node-types/-/ast-node-types-12.1.1.tgz#189cdc932a50b9dd14b6829848408c22bb72f976"
Expand Down