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

[WIP] Add uniqueItems action #870

Draft
wants to merge 3 commits into
base: main
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 library/src/actions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ export * from './trimEnd/index.ts';
export * from './trimStart/index.ts';
export * from './types.ts';
export * from './ulid/index.ts';
export * from './uniqueItems/index.ts';
export * from './url/index.ts';
export * from './uuid/index.ts';
export * from './value/index.ts';
1 change: 1 addition & 0 deletions library/src/actions/uniqueItems/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './uniqueItems.ts';
50 changes: 50 additions & 0 deletions library/src/actions/uniqueItems/uniqueItems.test-d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { describe, expectTypeOf, test } from 'vitest';
import type { InferInput, InferIssue, InferOutput } from '../../types/index.ts';
import {
uniqueItems,
type UniqueItemsAction,
type UniqueItemsIssue,
} from './uniqueItems.ts';

describe('uniqueItems', () => {
describe('should return action object', () => {
test('with undefined message', () => {
type Action = UniqueItemsAction<unknown[], undefined>;
expectTypeOf(uniqueItems<unknown[]>()).toEqualTypeOf<Action>();
expectTypeOf(
uniqueItems<unknown[], undefined>(undefined)
).toEqualTypeOf<Action>();
});

test('with string message', () => {
expectTypeOf(uniqueItems<unknown[], 'message'>('message')).toEqualTypeOf<
UniqueItemsAction<unknown[], 'message'>
>();
});

test('with function message', () => {
expectTypeOf(
uniqueItems<unknown[], () => string>(() => 'message')
).toEqualTypeOf<UniqueItemsAction<unknown[], () => string>>();
});
});

describe('should infer correct types', () => {
type Input = [1, 'two', { value: 'three' }];
type Action = UniqueItemsAction<Input, undefined>;

test('of input', () => {
expectTypeOf<InferInput<Action>>().toEqualTypeOf<Input>();
});

test('of output', () => {
expectTypeOf<InferOutput<Action>>().toEqualTypeOf<Input>();
});

test('of issue', () => {
expectTypeOf<InferIssue<Action>>().toEqualTypeOf<
UniqueItemsIssue<Input>
>();
});
});
});
137 changes: 137 additions & 0 deletions library/src/actions/uniqueItems/uniqueItems.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
import { describe, expect, test } from 'vitest';
import type { StringIssue } from '../../schemas/index.ts';
import type { PartialDataset } from '../../types/dataset.ts';
import { expectNoActionIssue } from '../../vitest/index.ts';
import {
uniqueItems,
type UniqueItemsAction,
type UniqueItemsIssue,
} from './uniqueItems.ts';

describe('uniqueItems', () => {
describe('should return action object', () => {
const baseAction: Omit<UniqueItemsAction<unknown[], never>, 'message'> = {
kind: 'validation',
type: 'unique_items',
reference: uniqueItems,
expects: null,
async: false,
'~validate': expect.any(Function),
};

test('with undefined message', () => {
const action: UniqueItemsAction<unknown[], undefined> = {
...baseAction,
message: undefined,
};
expect(uniqueItems()).toStrictEqual(action);
expect(uniqueItems<unknown[], undefined>(undefined)).toStrictEqual(
action
);
});

test('with string message', () => {
const message = 'message';
expect(uniqueItems<unknown[], 'message'>(message)).toStrictEqual({
...baseAction,
message,
} satisfies UniqueItemsAction<unknown[], 'message'>);
});

test('with function message', () => {
const message = () => 'message';
expect(uniqueItems<unknown[], typeof message>(message)).toStrictEqual({
...baseAction,
message,
} satisfies UniqueItemsAction<unknown[], typeof message>);
});
});

describe('should return dataset without issues', () => {
const action = uniqueItems<unknown[]>();

test('for untyped inputs', () => {
const issues: [StringIssue] = [
{
kind: 'schema',
type: 'string',
input: null,
expected: 'string',
received: 'null',
message: 'message',
},
];
expect(
action['~validate']({ typed: false, value: null, issues }, {})
).toStrictEqual({
typed: false,
value: null,
issues,
});
});

test('for empty array', () => {
expectNoActionIssue(action, [[]]);
});

test('for valid content', () => {
expectNoActionIssue(action, [[10, 11, 12, 13, 99]]);
});
});

describe('should return dataset with issues', () => {
const action = uniqueItems<number[], 'message'>('message');

const baseIssue: Omit<UniqueItemsIssue<number[]>, 'input' | 'received'> = {
kind: 'validation',
type: 'unique_items',
expected: null,
message: 'message',
requirement: undefined,
issues: undefined,
lang: undefined,
abortEarly: undefined,
abortPipeEarly: undefined,
};

test('for invalid(duplicated) content', () => {
const input = [5, 30, 2, 30, 8, 30];
expect(
action['~validate']({ typed: true, value: input }, {})
).toStrictEqual({
typed: true,
value: input,
issues: [
{
...baseIssue,
input: input[3],
received: `${input[3]}`,
path: [
{
type: 'array',
origin: 'value',
input,
key: 3,
value: input[3],
},
],
},
{
...baseIssue,
input: input[5],
received: `${input[5]}`,
path: [
{
type: 'array',
origin: 'value',
input,
key: 5,
value: input[5],
},
],
},
],
} satisfies PartialDataset<number[], UniqueItemsIssue<number[]>>);
});
});
});
115 changes: 115 additions & 0 deletions library/src/actions/uniqueItems/uniqueItems.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import type {
BaseIssue,
BaseValidation,
ErrorMessage,
} from '../../types/index.ts';
import { _addIssue } from '../../utils/index.ts';
import type { ArrayInput } from '../types.ts';

/**
* Unique items issue type.
*/
export interface UniqueItemsIssue<TInput extends ArrayInput>
extends BaseIssue<TInput[number]> {
/**
* The issue kind.
*/
readonly kind: 'validation';
/**
* The issue type.
*/
readonly type: 'unique_items';
/**
* The expected input.
*/
readonly expected: null;
}

/**
* Unique items action type.
*/
export interface UniqueItemsAction<
TInput extends ArrayInput,
TMessage extends ErrorMessage<UniqueItemsIssue<TInput>> | undefined,
> extends BaseValidation<TInput, TInput, UniqueItemsIssue<TInput>> {
/**
* The action type.
*/
readonly type: 'unique_items';
/**
* The action reference.
*/
readonly reference: typeof uniqueItems;
/**
* The expected property.
*/
readonly expects: null;
/**
* The error message.
*/
readonly message: TMessage;
}

/**
* Creates an unique items validation action.
*
* @returns An unique items action.
*/
export function uniqueItems<TInput extends ArrayInput>(): UniqueItemsAction<
TInput,
undefined
>;

/**
* Creates an unique items validation action.
*
* @param message The error message.
*
* @returns An unique items action.
*/
export function uniqueItems<
TInput extends ArrayInput,
const TMessage extends ErrorMessage<UniqueItemsIssue<TInput>> | undefined,
>(message: TMessage): UniqueItemsAction<TInput, TMessage>;

export function uniqueItems(
message?: ErrorMessage<UniqueItemsIssue<unknown[]>>
): UniqueItemsAction<
unknown[],
ErrorMessage<UniqueItemsIssue<unknown[]>> | undefined
> {
return {
kind: 'validation',
type: 'unique_items',
reference: uniqueItems,
async: false,
expects: null,
message,
'~validate'(dataset, config) {
if (dataset.typed) {
const set = new Set<unknown>();

for (let index = 0; index < dataset.value.length; index++) {
const item = dataset.value[index];
if (set.has(item)) {
_addIssue(this, 'item', dataset, config, {
input: item,
path: [
{
type: 'array',
origin: 'value',
input: dataset.value,
key: index,
value: item,
},
],
});
} else {
set.add(item);
}
}
}
return dataset;
},
};
}
51 changes: 51 additions & 0 deletions packages/to-json-schema/src/convertAction.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -490,4 +490,55 @@ describe('convertAction', () => {
'The "transform" action cannot be converted to JSON Schema.'
);
});

test('should convert unique items action for array', () => {
expect(
convertAction(
{
type: 'array',
},
v.uniqueItems<v.ArrayInput>(),
undefined
)
).toStrictEqual({
type: 'array',
uniqueItems: true,
});
});

test('should throw error for unique items action with invalid type', () => {
expect(() =>
convertAction({}, v.uniqueItems<v.ArrayInput>(), undefined)
).toThrowError(
'The "unique_items" action is not supported on type "undefined".'
);
expect(() =>
convertAction(
{ type: 'string' },
v.uniqueItems<v.ArrayInput>(),
undefined
)
).toThrowError(
'The "unique_items" action is not supported on type "string".'
);
});

test('should force conversion for unique items action with invalid type', () => {
expect(
convertAction({}, v.uniqueItems<v.ArrayInput>(), { force: true })
).toStrictEqual({
uniqueItems: true,
});
expect(console.warn).toHaveBeenLastCalledWith(
'The "unique_items" action is not supported on type "undefined".'
);
expect(
convertAction({ type: 'string' }, v.uniqueItems<v.ArrayInput>(), {
force: true,
})
).toStrictEqual({ type: 'string', uniqueItems: true });
expect(console.warn).toHaveBeenLastCalledWith(
'The "unique_items" action is not supported on type "string".'
);
});
});
Loading