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: experimental content collection JSON schemas #10145

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 34 additions & 0 deletions .changeset/slow-items-heal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
---
"astro": minor
alexanderniebuhr marked this conversation as resolved.
Show resolved Hide resolved
---

Adds experimental JSON Schema support for content collections of with `type: 'data'`.

To enable this feature, add the experimental flag:
alexanderniebuhr marked this conversation as resolved.
Show resolved Hide resolved

```
{
experimental: {
contentCollectionJSONSchemas: true,
},
}
```

To be able to use the schemas, you need to adapt your zod definition and reference it inside the json manually:

```diff
const test = defineCollection({
type: 'data',
schema: z.object({
+ "$schema": z.string().optional(),
natemoo-re marked this conversation as resolved.
Show resolved Hide resolved
test: z.string()
}),
});
```

```json
{
"$schema": "../../../.astro/schemas/collections/test.json",
"test": "test"
}
```
alexanderniebuhr marked this conversation as resolved.
Show resolved Hide resolved
3 changes: 2 additions & 1 deletion packages/astro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,8 @@
"vitefu": "^0.2.5",
"which-pm": "^2.1.1",
"yargs-parser": "^21.1.1",
"zod": "^3.22.4"
"zod": "^3.22.4",
"zod-to-json-schema": "^3.22.4"
alexanderniebuhr marked this conversation as resolved.
Show resolved Hide resolved
},
"optionalDependencies": {
"sharp": "^0.32.6"
Expand Down
19 changes: 19 additions & 0 deletions packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1640,6 +1640,25 @@ export interface AstroUserConfig {
*/
contentCollectionCache?: boolean;

/**
* @docs
* @name experimental.contentCollectionJSONSchema
* @type {boolean}
* @default `false`
* @version 4.5.0
* @description
* Enables generation of JSON Schema files for content collections of type `data`.
Copy link
Member

Choose a reason for hiding this comment

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

"Once the changeset is figured out, those instructions, limitations etc should also be here! This is the place in docs where people will go to figure out what this does and how it works!

When we like the changeset, it can be a mostly copy-paste here, except that this can be less "here's a new feature!" and more just boring, "here's what you do."

Reminder to self: this should also link to the content collections page in docs.

*
* ```js
* {
* experimental: {
* contentCollectionJSONSchema: true,
* },
* }
* ```
*/
contentCollectionJSONSchema?: boolean;
natemoo-re marked this conversation as resolved.
Show resolved Hide resolved

/**
* @docs
* @name experimental.clientPrerender
Expand Down
27 changes: 27 additions & 0 deletions packages/astro/src/content/types-generator.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import glob from 'fast-glob';
import { bold, cyan } from 'kleur/colors';
import { zodToJsonSchema } from 'zod-to-json-schema';
import type fsMod from 'node:fs';
import * as path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
Expand Down Expand Up @@ -310,6 +311,7 @@ export async function createContentTypesGenerator({
contentConfig: observable.status === 'loaded' ? observable.config : undefined,
contentEntryTypes: settings.contentEntryTypes,
viteServer,
settings
});
invalidateVirtualMod(viteServer);
}
Expand Down Expand Up @@ -352,6 +354,7 @@ async function writeContentFiles({
contentEntryTypes,
contentConfig,
viteServer,
settings
}: {
fs: typeof fsMod;
contentPaths: ContentPaths;
Expand All @@ -360,6 +363,7 @@ async function writeContentFiles({
contentEntryTypes: Pick<ContentEntryType, 'contentModuleTypes'>[];
contentConfig?: ContentConfig;
viteServer: Pick<ViteDevServer, 'hot'>;
settings: AstroSettings;
}) {
let contentTypesStr = '';
let dataTypesStr = '';
Expand Down Expand Up @@ -419,6 +423,29 @@ async function writeContentFiles({
for (const entryKey of Object.keys(collection.entries).sort()) {
const dataType = collectionConfig?.schema ? `InferEntrySchema<${collectionKey}>` : 'any';
dataTypesStr += `${entryKey}: {\n id: ${entryKey};\n collection: ${collectionKey};\n data: ${dataType}\n};\n`;
if(settings.config.experimental.contentCollectionJSONSchema) {
if (collectionConfig) {
alexanderniebuhr marked this conversation as resolved.
Show resolved Hide resolved
// writing inside loop makes sense for the json schema, since we want to have a file per collection
const collectionSchemasDir = new URL('./schemas/collections/', contentPaths.cacheDir);
alexanderniebuhr marked this conversation as resolved.
Show resolved Hide resolved
alexanderniebuhr marked this conversation as resolved.
Show resolved Hide resolved
if (!fs.existsSync(collectionSchemasDir)) {
fs.mkdirSync(collectionSchemasDir, { recursive: true });
}

if (collectionConfig?.schema)
alexanderniebuhr marked this conversation as resolved.
Show resolved Hide resolved
await fs.promises.writeFile(
new URL(`./${collectionKey.replace(/"/g, '')}.json`, collectionSchemasDir),
JSON.stringify(
zodToJsonSchema(collectionConfig?.schema, {
alexanderniebuhr marked this conversation as resolved.
Show resolved Hide resolved
alexanderniebuhr marked this conversation as resolved.
Show resolved Hide resolved
name: collectionKey.replace(/"/g, ''),
markdownDescription: true,
errorMessages: true,
}),
null,
2
)
);
}
}
}
dataTypesStr += `};\n`;
break;
Expand Down
5 changes: 5 additions & 0 deletions packages/astro/src/core/config/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ const ASTRO_CONFIG_DEFAULTS = {
experimental: {
optimizeHoistedScript: false,
contentCollectionCache: false,
contentCollectionJSONSchema: false,
clientPrerender: false,
globalRoutePriority: false,
i18nDomains: false,
Expand Down Expand Up @@ -492,6 +493,10 @@ export const AstroConfigSchema = z.object({
.boolean()
.optional()
.default(ASTRO_CONFIG_DEFAULTS.experimental.contentCollectionCache),
contentCollectionJSONSchema: z
.boolean()
.optional()
.default(ASTRO_CONFIG_DEFAULTS.experimental.contentCollectionJSONSchema),
clientPrerender: z
.boolean()
.optional()
Expand Down
11 changes: 11 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.