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
5 changes: 5 additions & 0 deletions .changeset/rich-falcons-warn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@astrojs/starlight': patch
---

Fixes a regression when using a union to [extend](https://starlight.astro.build/reference/frontmatter/#extend) Starlight’s `docsSchema()`.
13 changes: 13 additions & 0 deletions packages/starlight/__tests__/basics/schema.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,17 @@ describe('docs schema', () => {
expectTypeOf(parsed).toExtend<PartialDocsSchemaOutput>();
expectTypeOf(parsed.sidebar.custom).toBeNumber();
});

test('docs schema should parse to expected shape when extending with a union of objects', () => {
const baseSchema = z.object({ type: z.literal('base').optional().default('base') });
const extendedSchema = baseSchema.extend({ type: z.literal('extended'), name: z.string() });

const schema = docsSchema({ extend: z.union([baseSchema, extendedSchema]) })({
image: () => ({}) as any,
});
const parsed = schema.parse({});

expectTypeOf(parsed.type).toEqualTypeOf<'base' | 'extended'>();
if (parsed.type === 'extended') expectTypeOf(parsed.name).toBeString();
});
});
73 changes: 73 additions & 0 deletions packages/starlight/__tests__/basics/schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -372,4 +372,77 @@ describe('docsSchema', () => {
]]
`);
});

test('docs schema can be extended with a union of objects', () => {
const baseSchema = z.object({ type: z.literal('base').optional().default('base') });
const extendedSchema = baseSchema.extend({ type: z.literal('extended'), name: z.string() });

const schema = docsSchema({ extend: z.union([baseSchema, extendedSchema]) })({
image: () => ({}) as never,
});

const parsedBase = schema.parse({ title: 'Base' });
expect(parsedBase).toMatchInlineSnapshot(`
{
"draft": false,
"editUrl": true,
"head": [],
"pagefind": true,
"sidebar": {
"attrs": {},
"hidden": false,
},
"template": "doc",
"title": "Base",
"type": "base",
}
`);

const parsedExtended = schema.parse({ title: 'Extended', type: 'extended', name: 'test' });
expect(parsedExtended).toMatchInlineSnapshot(`
{
"draft": false,
"editUrl": true,
"head": [],
"name": "test",
"pagefind": true,
"sidebar": {
"attrs": {},
"hidden": false,
},
"template": "doc",
"title": "Extended",
"type": "extended",
}
`);
});

test('docs schema can be extended with a discriminated union of objects', () => {
const schema = docsSchema({
extend: z.discriminatedUnion('type', [
z.object({ type: z.literal('base') }),
z.object({ type: z.literal('extended'), name: z.string() }),
]),
})({
image: () => ({}) as never,
});

const parsed = schema.parse({ title: 'Extended', type: 'extended', name: 'test' });
expect(parsed).toMatchInlineSnapshot(`
{
"draft": false,
"editUrl": true,
"head": [],
"name": "test",
"pagefind": true,
"sidebar": {
"attrs": {},
"hidden": false,
},
"template": "doc",
"title": "Extended",
"type": "extended",
}
`);
});
});
3 changes: 2 additions & 1 deletion packages/starlight/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,8 @@ const StarlightFrontmatterSchema = (context: SchemaContext) =>
type DefaultSchema = ReturnType<typeof StarlightFrontmatterSchema>;

/** Base subset of Zod types that we support passing to the `extend` option. */
type BaseSchema<T extends z.ZodRawShape = z.ZodRawShape> = z.ZodObject<T>;
type BaseObjectSchema = z.ZodObject<z.ZodRawShape, z.core.$ZodObjectConfig>;
type BaseSchema = BaseObjectSchema | z.ZodUnion<readonly BaseObjectSchema[]>;

/** Type that extends Starlight’s default schema with an optional, user-defined schema. */
type ExtendedSchema<T extends BaseSchema = never> = [T] extends [never]
Expand Down
43 changes: 33 additions & 10 deletions packages/starlight/utils/zodDeepMerge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,19 @@ export type DeepMergedSchema<Default extends z.core.$ZodType, User extends z.cor
? z.ZodDefault<DeepMergedSchema<UnwrappedSchema<Default>, WrappedSchema>>
: User extends z.ZodPrefault<infer WrappedSchema extends z.core.$ZodType>
? z.ZodPrefault<DeepMergedSchema<UnwrappedSchema<Default>, WrappedSchema>>
: UnwrappedSchema<Default> extends z.ZodObject<infer DefaultShape>
? User extends z.ZodObject<infer UserShape, infer UserConfig>
? z.ZodObject<DeepMergedShape<DefaultShape, UserShape>, UserConfig>
: User
: UnwrappedSchema<Default> extends z.ZodArray<
infer DefaultItemSchema extends z.core.$ZodType
>
? User extends z.ZodArray<infer UserItemSchema extends z.core.$ZodType>
? z.ZodArray<DeepMergedSchema<DefaultItemSchema, UserItemSchema>>
: User extends z.ZodUnion<infer Users extends readonly z.core.$ZodType[]>
? z.ZodUnion<DeepMergedUnionMembers<UnwrappedSchema<Default>, Users>>
: UnwrappedSchema<Default> extends z.ZodObject<infer DefaultShape>
? User extends z.ZodObject<infer UserShape, infer UserConfig>
? z.ZodObject<DeepMergedShape<DefaultShape, UserShape>, UserConfig>
: User
: User;
: UnwrappedSchema<Default> extends z.ZodArray<
infer DefaultItemSchema extends z.core.$ZodType
>
? User extends z.ZodArray<infer UserItemSchema extends z.core.$ZodType>
? z.ZodArray<DeepMergedSchema<DefaultItemSchema, UserItemSchema>>
: User
: User;

/** Type-level equivalent of {@link unwrapSchema}. */
type UnwrappedSchema<T extends z.core.$ZodType> =
Expand Down Expand Up @@ -48,6 +50,16 @@ type DeepMergedShape<Default extends z.ZodRawShape, User extends z.ZodRawShape>
: never;
};

/** Merged union schemas where each union member is deep-merged with the default schema. */
type DeepMergedUnionMembers<
Default extends z.core.$ZodType,
Users extends readonly z.core.$ZodType[],
> = {
[Key in keyof Users]: Users[Key] extends z.core.$ZodType
? DeepMergedSchema<Default, Users[Key]>
: Users[Key];
};

export function deepMergeSchemas(defaultSchema: z.ZodType, userSchema: z.ZodType): z.ZodType {
const unwrappedDefaultSchema = unwrapSchema(defaultSchema);

Expand All @@ -58,6 +70,13 @@ export function deepMergeSchemas(defaultSchema: z.ZodType, userSchema: z.ZodType
} as Parameters<typeof userSchema.clone>[0]);
}

if (isZodUnion(userSchema)) {
return userSchema.clone({
...userSchema._zod.def,
options: userSchema.options.map((schema) => deepMergeSchemas(unwrappedDefaultSchema, schema)),
});
}

if (isZodObject(unwrappedDefaultSchema) && isZodObject(userSchema)) {
const shape: z.core.$ZodLooseShape = { ...unwrappedDefaultSchema.shape };

Expand Down Expand Up @@ -119,3 +138,7 @@ function isZodObject(schema: z.ZodType): schema is z.ZodObject<z.ZodRawShape> {
function isZodArray(schema: z.ZodType): schema is z.ZodArray<z.ZodType> {
return schema._zod.def.type === 'array';
}

function isZodUnion(schema: z.ZodType): schema is z.ZodUnion<readonly z.ZodType[]> {
return schema._zod.def.type === 'union';
}