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

fix: use of strict for anyOf #821

Merged
merged 3 commits into from
Feb 18, 2024
Merged
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
5 changes: 5 additions & 0 deletions .changeset/silver-suits-wait.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@kubb/swagger-zod": patch
---

anyOf with strict when using z.object
8 changes: 4 additions & 4 deletions packages/swagger-faker/src/FakerGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@
members.push({ keyword: fakerKeywords.catchall, args: addionalValidationFunctions })
}

return [{ keyword: fakerKeywords.object, args: objectMembers }]
return [{ keyword: fakerKeywords.object, args: { entries: objectMembers } }]
}

/**
Expand All @@ -137,9 +137,9 @@
#getRefAlias(obj: OpenAPIV3.ReferenceObject, _baseName?: string): FakerMeta[] {
const { $ref } = obj
let ref = this.refs[$ref]

1
if (ref) {
return [{ keyword: fakerKeywords.ref, args: ref.propertyName }]
return [{ keyword: fakerKeywords.ref, args: { name: ref.propertyName } }]

Check warning on line 142 in packages/swagger-faker/src/FakerGenerator.ts

View check run for this annotation

Codecov / codecov/patch

packages/swagger-faker/src/FakerGenerator.ts#L142

Added line #L142 was not covered by tests
}

const originalName = getUniqueName($ref.replace(/.+\//, ''), this.#usedAliasNames)
Expand All @@ -159,7 +159,7 @@
isTypeOnly: false,
})

return [{ keyword: fakerKeywords.ref, args: ref.propertyName }]
return [{ keyword: fakerKeywords.ref, args: { name: ref.propertyName } }]
}

#getParsedSchema(schema?: OasTypes.SchemaObject) {
Expand Down
10 changes: 6 additions & 4 deletions packages/swagger-faker/src/fakerParser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const input = [
{
input: parseFakerMeta({
keyword: 'ref',
args: 'createPet',
args: { name: 'createPet' },
}),
expected: 'createPet()',
},
Expand Down Expand Up @@ -85,7 +85,7 @@ const input = [
{
input: parseFakerMeta({
keyword: 'array',
args: [{ keyword: 'ref', args: 'createPet' }],
args: [{ keyword: 'ref', args: { name: 'createPet' } }],
}),
expected: 'faker.helpers.arrayElements([createPet()]) as any',
},
Expand Down Expand Up @@ -132,8 +132,10 @@ const input = [
input: parseFakerMeta({
keyword: 'object',
args: {
firstName: [{ keyword: 'string', args: { min: 2 } }],
address: [{ keyword: 'string' }, { keyword: 'null' }],
entries: {
firstName: [{ keyword: 'string', args: { min: 2 } }],
address: [{ keyword: 'string' }, { keyword: 'null' }],
},
},
}),
expected: '{"firstName": faker.string.alpha({"min":2}),"address": faker.helpers.arrayElement([faker.string.alpha(),null])}',
Expand Down
158 changes: 61 additions & 97 deletions packages/swagger-faker/src/fakerParser.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,31 @@
export type FakerMetaMapper = {
object: { keyword: 'object'; args: { entries: { [x: string]: FakerMeta[] }; strict?: boolean } }
url: { keyword: 'url' }
uuid: { keyword: 'uuid' }
email: { keyword: 'email' }
firstName: { keyword: 'firstName' }
lastName: { keyword: 'lastName' }
phone: { keyword: 'phone' }
password: { keyword: 'password' }
datetime: { keyword: 'datetime' }
tuple: { keyword: 'tuple'; args?: FakerMeta[] }
array: { keyword: 'array'; args?: FakerMeta[] }
enum: { keyword: 'enum'; args?: Array<string | number> }
and: { keyword: 'and'; args?: FakerMeta[] }
union: { keyword: 'union'; args?: FakerMeta[] }
ref: { keyword: 'ref'; args?: { name: string } }
catchall: { keyword: 'catchall'; args?: FakerMeta[] }
matches: { keyword: 'matches'; args?: string }
boolean: { keyword: 'boolean' }
string: { keyword: 'string'; args?: { min?: number; max?: number } }
integer: { keyword: 'integer'; args?: { min?: number; max?: number } }
number: { keyword: 'number'; args?: { min?: number; max?: number } }
undefined: { keyword: 'undefined' }
null: { keyword: 'null' }
any: { keyword: 'any' }
unknown: { keyword: 'unknown' }
}

export const fakerKeywords = {
any: 'any',
unknown: 'unknown',
Expand Down Expand Up @@ -27,7 +55,7 @@
lastName: 'lastName',
password: 'password',
phone: 'phone',
} as const
} satisfies { [K in keyof FakerMetaMapper]: FakerMetaMapper[K]['keyword'] }

export type FakerKeyword = keyof typeof fakerKeywords

Expand Down Expand Up @@ -60,86 +88,21 @@
lastName: 'faker.person.lastName',
password: 'faker.internet.password',
phone: 'faker.phone.number',
} as const satisfies Record<FakerKeyword, string>
} satisfies { [K in keyof FakerMetaMapper]: string }

type FakerMetaBase<T> = {
keyword: FakerKeyword
args: T
}

type FakerMetaUnknown = { keyword: typeof fakerKeywords.unknown }

type FakerMetaAny = { keyword: typeof fakerKeywords.any }
type FakerMetaNull = { keyword: typeof fakerKeywords.null }
type FakerMetaUndefined = { keyword: typeof fakerKeywords.undefined }

type FakerMetaNumber = { keyword: typeof fakerKeywords.number; args?: { min?: number; max?: number } }
type FakerMetaInteger = { keyword: typeof fakerKeywords.integer; args?: { min?: number; max?: number } }

type FakerMetaString = { keyword: typeof fakerKeywords.string; args?: { min?: number; max?: number } }

type FakerMetaBoolean = { keyword: typeof fakerKeywords.boolean }

type FakerMetaMatches = { keyword: typeof fakerKeywords.matches; args?: string }

type FakerMetaObject = { keyword: typeof fakerKeywords.object; args?: { [x: string]: FakerMeta[] } }

type FakerMetaCatchall = { keyword: typeof fakerKeywords.catchall; args?: FakerMeta[] }

type FakerMetaRef = { keyword: typeof fakerKeywords.ref; args?: string }

type FakerMetaUnion = { keyword: typeof fakerKeywords.union; args?: FakerMeta[] }

type FakerMetaAnd = { keyword: typeof fakerKeywords.and; args?: FakerMeta[] }

type FakerMetaEnum = { keyword: typeof fakerKeywords.enum; args?: Array<string | number> }

type FakerMetaArray = { keyword: typeof fakerKeywords.array; args?: FakerMeta[] }

type FakerMetaTuple = { keyword: typeof fakerKeywords.tuple; args?: FakerMeta[] }
type FakerMetaEmail = { keyword: typeof fakerKeywords.email }

type FakerMetaFirstName = { keyword: typeof fakerKeywords.firstName }

type FakerMetaLastName = { keyword: typeof fakerKeywords.lastName }
type FakerMetaPassword = { keyword: typeof fakerKeywords.password }

type FakerMetaPhone = { keyword: typeof fakerKeywords.phone }

type FakerMetaDatetime = { keyword: typeof fakerKeywords.datetime }

type FakerMetaUuid = { keyword: typeof fakerKeywords.uuid }

type FakerMetaUrl = { keyword: typeof fakerKeywords.url }

export type FakerMeta =
| { keyword: string }
| FakerMetaUnknown
| FakerMetaAny
| FakerMetaNull
| FakerMetaUndefined
| FakerMetaNumber
| FakerMetaInteger
| FakerMetaString
| FakerMetaBoolean
| FakerMetaMatches
| FakerMetaObject
| FakerMetaCatchall
| FakerMetaRef
| FakerMetaUnion
| FakerMetaAnd
| FakerMetaEnum
| FakerMetaArray
| FakerMetaTuple
| FakerMetaEmail
| FakerMetaFirstName
| FakerMetaLastName
| FakerMetaPassword
| FakerMetaPhone
| FakerMetaDatetime
| FakerMetaUuid
| FakerMetaUrl
// use example
| FakerMetaMapper[keyof FakerMetaMapper]

export function isKeyword<T extends FakerMeta, K extends keyof FakerMetaMapper>(meta: T, keyword: K): meta is Extract<T, FakerMetaMapper[K]> {
return meta.keyword === keyword
}

/**
* @link based on https://github.com/cellular/oazapfts/blob/7ba226ebb15374e8483cc53e7532f1663179a22c/src/codegen/generate.ts#L398
*/
Expand All @@ -164,45 +127,42 @@
}

export function parseFakerMeta(
item: FakerMeta,
item: FakerMeta = {} as FakerMeta,
{ mapper = fakerKeywordMapper, withOverride }: { mapper?: Record<FakerKeyword, string>; withOverride?: boolean } = {},
): string {
// eslint-disable-next-line prefer-const
let { keyword, args } = (item || {}) as FakerMetaBase<unknown>
const value = mapper[keyword]
const value = mapper[item.keyword as keyof typeof mapper]

if (keyword === fakerKeywords.tuple || keyword === fakerKeywords.array || keyword === fakerKeywords.union) {
if (isKeyword(item, fakerKeywords.tuple) || isKeyword(item, fakerKeywords.array) || isKeyword(item, fakerKeywords.union)) {
return `${value}(${
Array.isArray(args) ? `[${args.map((item) => parseFakerMeta(item as FakerMeta, { mapper })).join(',')}]` : parseFakerMeta(args as FakerMeta)
Array.isArray(item.args)
? `[${item.args.map((orItem) => parseFakerMeta(orItem, { mapper })).join(',')}]`
: parseFakerMeta(item.args)

Check warning on line 139 in packages/swagger-faker/src/fakerParser.ts

View check run for this annotation

Codecov / codecov/patch

packages/swagger-faker/src/fakerParser.ts#L139

Added line #L139 was not covered by tests
}) as any`
}

if (keyword === fakerKeywords.and) {
if (isKeyword(item, fakerKeywords.and)) {
return `${value}({},${
Array.isArray(args) ? `${args.map((item) => parseFakerMeta(item as FakerMeta, { mapper })).join(',')}` : parseFakerMeta(args as FakerMeta)
Array.isArray(item.args) ? `${item.args.map((andItem) => parseFakerMeta(andItem, { mapper })).join(',')}` : parseFakerMeta(item.args)
})`
}

if (keyword === fakerKeywords.enum) {
return `${value}(${Array.isArray(args) ? `${args.join(',')}` : parseFakerMeta(args as FakerMeta)})`
if (isKeyword(item, fakerKeywords.enum)) {
return `${value}(${Array.isArray(item.args) ? `${item.args.join(',')}` : parseFakerMeta(item.args)})`
}

if (keyword === fakerKeywords.catchall) {
if (isKeyword(item, fakerKeywords.catchall)) {
throw new Error('catchall is not implemented')
}

if (keyword === fakerKeywords.object) {
if (!args) {
args = '{}'
}
const argsObject = Object.entries(args as FakerMeta)
if (isKeyword(item, fakerKeywords.object)) {
const argsObject = Object.entries(item.args?.entries || '{}')
.filter((item) => {
const schema = item[1] as FakerMeta[]
const schema = item[1]
return schema && typeof schema.map === 'function'
})
.map((item) => {
const name = item[0]
const schema = item[1] as FakerMeta[]
const schema = item[1]
return `"${name}": ${
joinItems(
schema
Expand All @@ -217,19 +177,23 @@
}

// custom type
if (keyword === fakerKeywords.ref) {
if (isKeyword(item, fakerKeywords.ref)) {
if (!item.args?.name) {
throw new Error(`Name not defined for keyword ${item.keyword}`)
}

Check warning on line 183 in packages/swagger-faker/src/fakerParser.ts

View check run for this annotation

Codecov / codecov/patch

packages/swagger-faker/src/fakerParser.ts#L182-L183

Added lines #L182 - L183 were not covered by tests

if (withOverride) {
return `${args as string}(override)`
return `${item.args.name}(override)`
}
return `${args as string}()`
return `${item.args.name}()`
}

if (keyword === fakerKeywords.null || keyword === fakerKeywords.undefined || keyword === fakerKeywords.any) {
if (isKeyword(item, fakerKeywords.null) || isKeyword(item, fakerKeywords.undefined) || isKeyword(item, fakerKeywords.any)) {
return value
}

if (keyword in mapper) {
const options = JSON.stringify(args)
if (item.keyword in mapper) {
const options = JSON.stringify((item as FakerMetaBase<unknown>).args)
return `${value}(${options ?? ''})`
}

Expand Down
24 changes: 24 additions & 0 deletions packages/swagger-zod/mocks/anyof.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
info:
title: anyof test cases
version: 1.0.0
openapi: 3.1.0
paths: {}
components:
schemas:
test:
anyOf:
- type: object
properties:
propertyA:
type: string
required:
- propertyA
- type: object
properties:
propertyA:
type: string
propertyB:
type: string
required:
- propertyA
- propertyB
26 changes: 26 additions & 0 deletions packages/swagger-zod/src/ZodGenerator.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -267,3 +267,29 @@ describe('ZodGenerator recursive', async () => {
expect(node).toMatchSnapshot()
})
})

describe('ZodGenerator anyof', async () => {
const discriminatorPath = path.resolve(__dirname, '../mocks/anyof.yaml')
const oas = await new OasManager().parse(discriminatorPath)
const generator = new ZodGenerator({
exclude: undefined,
include: undefined,
override: undefined,
transformers: {},
typed: false,
dateType: 'string',
unknownType: 'any',
}, {
oas,
pluginManager: mockedPluginManager,
})
// eslint-disable-next-line @typescript-eslint/no-non-null-asserted-optional-chain
const schemas = oas.getDefinition().components?.schemas!

test('anyof with 2 objects', async () => {
const schema = schemas['test'] as OasTypes.SchemaObject
const node = generator.build({ schema, baseName: 'test' })

expect(node).toMatchSnapshot()
})
})
15 changes: 13 additions & 2 deletions packages/swagger-zod/src/ZodGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { getSchemaFactory, isReference } from '@kubb/swagger/utils'
import { pluginKey as swaggerTypeScriptPluginKey } from '@kubb/swagger-ts'

import { pluginKey } from './plugin.ts'
import { zodKeywords, zodParser } from './zodParser.ts'
import { isKeyword, zodKeywords, zodParser } from './zodParser.ts'

import type { PluginManager } from '@kubb/core'
import type { ts } from '@kubb/parser'
Expand Down Expand Up @@ -140,7 +140,7 @@ export class ZodGenerator extends Generator<PluginOptions['resolvedOptions'], Co

const members: ZodMeta[] = []

members.push({ keyword: zodKeywords.object, args: objectMembers })
members.push({ keyword: zodKeywords.object, args: { entries: objectMembers } })

if (additionalProperties) {
const addionalValidationFunctions: ZodMeta[] = additionalProperties === true
Expand Down Expand Up @@ -256,6 +256,17 @@ export class ZodGenerator extends Generator<PluginOptions['resolvedOptions'], Co
.filter(Boolean)
.filter((item) => {
return item && item.keyword !== this.#unknownReturn
}).map(item => {
if (isKeyword(item, zodKeywords.object)) {
return {
...item,
args: {
...item.args,
strict: true,
},
}
}
return item
}),
}
if (schemaWithoutAnyOf.properties) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ exports[`ZodGenerator PetStore > generate schema for Pets 1`] = `
]
`;

exports[`ZodGenerator anyof > anyof with 2 objects 1`] = `
[
"export const test = z.union([z.object({"propertyA": z.string()}).strict(),z.object({"propertyA": z.string(),"propertyB": z.string()}).strict()]);",
]
`;

exports[`ZodGenerator constCases > MixedValueTypeConst generates zod literal value correctly, overriding the type constraint 1`] = `
[
"export const MixedValueTypeConst = z.object({"foobar": z.literal("foobar")}).describe(\`This probably should fail miserably\`);",
Expand Down
Loading
Loading