Skip to content
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
18 changes: 17 additions & 1 deletion packages/core/src/generators/schema-definition.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type {
InputFiltersOption,
} from '../types';
import {
conventionName,
isReference,
isString,
jsDoc,
Expand Down Expand Up @@ -146,7 +147,22 @@ export const generateSchemasDefinition = (
[],
);

return models;
// Deduplicate schemas by normalized name to prevent duplicate exports
// This handles cases where different source schemas produce the same normalized name
const seenNames = new Set<string>();
const deduplicatedModels: GeneratorSchema[] = [];
for (const schema of models) {
const normalizedName = conventionName(
schema.name,
context.output.namingConvention,
);
if (!seenNames.has(normalizedName)) {
seenNames.add(normalizedName);
deduplicatedModels.push(schema);
}
}

return deduplicatedModels;
};

function shouldCreateInterface(schema: SchemaObject) {
Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/getters/combine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,9 @@ export const combineSchemas = ({

const isAllEnums = resolvedData.isEnum.every(Boolean);

if (isAllEnums && name && items.length > 1) {
// For oneOf, we should generate union types instead of const objects
// even when all subschemas are enums
if (isAllEnums && name && items.length > 1 && separator !== 'oneOf') {
const newEnum = `// eslint-disable-next-line @typescript-eslint/no-redeclare\nexport const ${pascal(
name,
)} = ${getCombineEnumValue(resolvedData)}`;
Expand Down
56 changes: 19 additions & 37 deletions packages/core/src/writers/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,63 +135,45 @@ export const writeSchemas = async ({
await fs.ensureFile(schemaFilePath);

// Ensure separate files are used for parallel schema writing.
// Throw an exception, which list all duplicates, before attempting
// multiple writes on the same file.
const schemaNamesSet = new Set<string>();
// Throw an exception if duplicates are detected (using convention names)
const ext = fileExtension.endsWith('.ts')
? fileExtension.slice(0, -3)
: fileExtension;
const conventionNamesSet = new Set<string>();
const duplicateNamesMap = new Map<string, number>();
for (const schema of schemas) {
if (schemaNamesSet.has(schema.name)) {
const conventionNameValue = conventionName(schema.name, namingConvention);
if (conventionNamesSet.has(conventionNameValue)) {
duplicateNamesMap.set(
schema.name,
(duplicateNamesMap.get(schema.name) || 1) + 1,
conventionNameValue,
(duplicateNamesMap.get(conventionNameValue) ?? 0) + 1,
);
} else {
schemaNamesSet.add(schema.name);
conventionNamesSet.add(conventionNameValue);
}
}
if (duplicateNamesMap.size > 0) {
throw new Error(
'Duplicate schema names detected:\n' +
'Duplicate schema names detected (after naming convention):\n' +
[...duplicateNamesMap]
.map((duplicate) => ` ${duplicate[1]}x ${duplicate[0]}`)
.map((duplicate) => ` ${duplicate[1] + 1}x ${duplicate[0]}`)
.join('\n'),
);
}

try {
const data = await fs.readFile(schemaFilePath);
// Create unique export statements from schemas (deduplicate by schema name)
const uniqueSchemaNames = [...conventionNamesSet];

const stringData = data.toString();

const ext = fileExtension.endsWith('.ts')
? fileExtension.slice(0, -3)
: fileExtension;

const importStatements = schemas
.filter((schema) => {
const name = conventionName(schema.name, namingConvention);

return (
!stringData.includes(`export * from './${name}${ext}'`) &&
!stringData.includes(`export * from "./${name}${ext}"`)
);
})
.map(
(schema) =>
`export * from './${conventionName(schema.name, namingConvention)}${ext}';`,
);

const currentFileExports = (stringData
.match(/export \* from(.*)('|")/g)
?.map((s) => s + ';') ?? []) as string[];

const exports = [...currentFileExports, ...importStatements]
.sort()
// Create export statements
const exports = uniqueSchemaNames
.map((schemaName) => `export * from './${schemaName}${ext}';`)
.toSorted((a, b) => a.localeCompare(b))
.join('\n');

const fileContent = `${header}\n${exports}`;

await fs.writeFile(schemaFilePath, fileContent);
await fs.writeFile(schemaFilePath, fileContent, { encoding: 'utf8' });
} catch (error) {
throw new Error(
`Oups... 🍻. An Error occurred while writing schema index file ${schemaFilePath} => ${error}`,
Expand Down
10 changes: 7 additions & 3 deletions packages/zod/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -239,11 +239,13 @@ export const generateZodValidationSchemaDefinition = (
| ReferenceObject
)[];

const baseSchemas = schemas.map((schema) =>
// Use index-based naming to ensure uniqueness when processing multiple schemas
// This prevents duplicate schema names when nullable refs are used
const baseSchemas = schemas.map((schema, index) =>
generateZodValidationSchemaDefinition(
schema as SchemaObject,
context,
camel(name),
`${camel(name)}${pascal(getNumberWord(index + 1))}`,
strict,
isZodV4,
{
Expand All @@ -261,11 +263,13 @@ export const generateZodValidationSchemaDefinition = (
type: schema.type,
} as SchemaObject;

// Use index-based naming to ensure uniqueness
const additionalIndex = baseSchemas.length + 1;
const additionalPropertiesDefinition =
generateZodValidationSchemaDefinition(
additionalPropertiesSchema,
context,
camel(name),
`${camel(name)}${pascal(getNumberWord(additionalIndex))}`,
strict,
isZodV4,
{
Expand Down
Loading