ronantakizawa/codereview-bench huggingface dataset:
Repository: withastro/astro
File: packages/astro/src/content/types-generator.ts (TypeScript)

Code before:
		return collection.loader.schema;
	}
	const result = await getSchemaContextResult(collection, collectionKey);
	return result?.schema;
}

async function typeForCollection<T extends keyof ContentConfig['collections']>(
	collection: ContentConfig['collections'][T] | undefined,
	collectionKey: T,
): Promise<{ type: string; injectedType?: InjectedType }> {
	if (collection?.schema) {
		return { type: `InferEntrySchema<${collectionKey}>` };
	}
	if (!collection?.type || typeof collection.loader === 'function') {
		return { type: 'any' };
	}
	if (collection.loader.schema) {
		return { type: `InferLoaderSchema<${collectionKey}>` };
	}
	const result = await getSchemaContextResult(collection, collectionKey);
	if (!result) {
		return { type: 'any' };
	}
	const filename = `loaders/${collectionKey.slice(1, -1)}.ts`;
	return {
		type: `import("./${filename}").Collection`,
		injectedType: {
			filename,
			content: result.types,
		},
	};
}

async function writeContentFiles({
	fs,
	contentPaths,
	collectionEntryMap,
	typeTemplateContent,
	contentEntryTypes,
	contentConfig,
	viteServer,
	logger,
	settings,
}: {
	fs: typeof fsMod;
	contentPaths: ContentPaths;
	collectionEntryMap: CollectionEntryMap;
	typeTemplateContent: string;
	contentEntryTypes: Pick<ContentEntryType, 'contentModuleTypes'>[];
	contentConfig?: ContentConfig;
	viteServer: Pick<ViteDevServer, 'hot'>;

Review comment (suggestion):
This isn't the filename, is it? It should be the runtime type, so with a `.js` extension

Code after:
		createSchemaResultCache.set(collectionKey, result);
		return result;
	}
}

async function getContentLayerSchema<T extends keyof ContentConfig['collections']>(
	collection: ContentConfig['collections'][T],
	collectionKey: T,
): Promise<ZodSchema | undefined> {
	if (collection?.type !== CONTENT_LAYER_TYPE || typeof collection.loader === 'function') {
		return;
	}
	if (collection.loader.schema) {
		return collection.loader.schema;
	}
	const result = await getCreateSchemaResult(collection, collectionKey);
	return result?.schema;
}

async function typeForCollection<T extends keyof ContentConfig['collections']>(
	collection: ContentConfig['collections'][T] | undefined,
	collectionKey: T,
): Promise<{ type: string; injectedType?: InjectedType }> {
	if (collection?.schema) {
		return { type: `InferEntrySchema<${collectionKey}>` };
	}
	if (!collection?.type || typeof collection.loader === 'function') {
		return { type: 'any' };
	}
	if (collection.loader.schema) {
		return { type: `InferLoaderSchema<${collectionKey}>` };
	}
	const result = await getCreateSchemaResult(collection, collectionKey);
	if (!result) {
		return { type: 'any' };
	}
	const base = `loaders/${collectionKey.slice(1, -1)}`;
	return {
		type: `import("./${base}.js").Entry`,
		injectedType: {
			filename: `${base}.ts`,
			content: result.types,
		},
	};
}

async function writeContentFiles({
	fs,
	contentPaths,
	collectionEntryMap,
	typeTemplateContent,
Repository: withastro/astro
File: packages/astro/src/content/types-generator.ts (TypeScript)

Code before:
	}
	if (collection.loader.schema) {
		return collection.loader.schema;
	}
	const result = await getSchemaContextResult(collection, collectionKey);
	return result?.schema;
}

async function typeForCollection<T extends keyof ContentConfig['collections']>(
	collection: ContentConfig['collections'][T] | undefined,
	collectionKey: T,
): Promise<{ type: string; injectedType?: InjectedType }> {
	if (collection?.schema) {
		return { type: `InferEntrySchema<${collectionKey}>` };
	}
	if (!collection?.type || typeof collection.loader === 'function') {
		return { type: 'any' };
	}
	if (collection.loader.schema) {
		return { type: `InferLoaderSchema<${collectionKey}>` };
	}
	const result = await getSchemaContextResult(collection, collectionKey);
	if (!result) {
		return { type: 'any' };
	}
	const filename = `loaders/${collectionKey.slice(1, -1)}.ts`;
	return {
		type: `import("./${filename}").Collection`,
		injectedType: {
			filename,
			content: result.types,
		},
	};
}

async function writeContentFiles({
	fs,
	contentPaths,
	collectionEntryMap,
	typeTemplateContent,
	contentEntryTypes,
	contentConfig,
	viteServer,
	logger,
	settings,
}: {
	fs: typeof fsMod;
	contentPaths: ContentPaths;
	collectionEntryMap: CollectionEntryMap;
	typeTemplateContent: string;
	contentEntryTypes: Pick<ContentEntryType, 'contentModuleTypes'>[];

Review comment (suggestion):
```suggestion
	const filename = `loaders/${collectionKey.slice(1, -1)}.js`;
```

Code after:
	) {
		const result = await collection.loader.createSchema();
		createSchemaResultCache.set(collectionKey, result);
		return result;
	}
}

async function getContentLayerSchema<T extends keyof ContentConfig['collections']>(
	collection: ContentConfig['collections'][T],
	collectionKey: T,
): Promise<ZodSchema | undefined> {
	if (collection?.type !== CONTENT_LAYER_TYPE || typeof collection.loader === 'function') {
		return;
	}
	if (collection.loader.schema) {
		return collection.loader.schema;
	}
	const result = await getCreateSchemaResult(collection, collectionKey);
	return result?.schema;
}

async function typeForCollection<T extends keyof ContentConfig['collections']>(
	collection: ContentConfig['collections'][T] | undefined,
	collectionKey: T,
): Promise<{ type: string; injectedType?: InjectedType }> {
	if (collection?.schema) {
		return { type: `InferEntrySchema<${collectionKey}>` };
	}
	if (!collection?.type || typeof collection.loader === 'function') {
		return { type: 'any' };
	}
	if (collection.loader.schema) {
		return { type: `InferLoaderSchema<${collectionKey}>` };
	}
	const result = await getCreateSchemaResult(collection, collectionKey);
	if (!result) {
		return { type: 'any' };
	}
	const base = `loaders/${collectionKey.slice(1, -1)}`;
	return {
		type: `import("./${base}.js").Entry`,
		injectedType: {
			filename: `${base}.ts`,
			content: result.types,
		},
	};
}

async function writeContentFiles({
	fs,
	contentPaths,
Repository: withastro/astro
File: packages/astro/test/fixtures/content-layer/src/content.config.ts (TypeScript)

Code before:
			const lastValue = entry?.data.lastValue ?? 0;
			const raw = {
				id: 'value',
				data: {
					lastValue: lastValue + 1,
					lastUpdated: new Date(),
					refreshContextData,
					slug: 'slimy'
				},
			}
			const parsed = await parseData(raw)
			store.set({
				id: raw.id,
				data: parsed,
				rendered: await renderMarkdown(markdownContent)
			});
		},
		getSchemaContext: async () => {
			return {
				schema: z.object({
				lastValue: z.number(),
				lastUpdated: z.date(),
				refreshContextData: z.record(z.unknown()).optional(),
				slug: z.string().optional(),
			}),
			types: `export interface Collection {
	lastValue: number;
	lastUpdated: Date;
	refreshContextData?: Record<string, unknown> | undefined;
	slug?: string | undefined;
}`
			}
		}
	},
});

const artists = defineCollection({
        loader: file('src/data/artists.toml'),
        schema: z.object({
                name: z.string(),
                genre: z.string().array(),
        }),
});

const songs = defineCollection({
        loader: file('src/data/songs.toml'),
        schema: z.object({
                name: z.string(),
                artists: z.array(reference('artists')),
        }),
});

Review comment (suggestion):
```suggestion
			types: /* ts */`export interface Collection {
```

Code after:
			const entry = store.get<{ lastValue: number }>('value');
			const lastValue = entry?.data.lastValue ?? 0;
			const raw = {
				id: 'value',
				data: {
					lastValue: lastValue + 1,
					lastUpdated: new Date(),
					refreshContextData,
					slug: 'slimy'
				},
			}
			const parsed = await parseData(raw)
			store.set({
				id: raw.id,
				data: parsed,
				rendered: await renderMarkdown(markdownContent)
			});
		},
		createSchema: async () => {
			return {
				schema: z.object({
				lastValue: z.number(),
				lastUpdated: z.date(),
				refreshContextData: z.record(z.unknown()).optional(),
				slug: z.string().optional(),
			}),
			types: /* ts */`export interface Entry {
	lastValue: number;
	lastUpdated: Date;
	refreshContextData?: Record<string, unknown> | undefined;
	slug?: string | undefined;
}`
			}
		}
	},
});

const artists = defineCollection({
        loader: file('src/data/artists.toml'),
        schema: z.object({
                name: z.string(),
                genre: z.string().array(),
        }),
});

const songs = defineCollection({
        loader: file('src/data/songs.toml'),
        schema: z.object({
                name: z.string(),
                artists: z.array(reference('artists')),
        }),
Repository: withastro/astro
File: packages/astro/test/fixtures/content-layer/src/loaders/post-loader.ts (TypeScript)

Code before:
			if (lastSynced && (Date.now() - Number(lastSynced) < 1000 * 60)) {
					logger.info('Skipping sync');
					return;
			}

			const posts = await fetch(config.url)
				.then((res) => res.json());

			store.clear();

			for (const data of posts) {
				store.set({id: data.id, data});
			}
			meta.set('lastSynced', String(Date.now()));
		},
		createSchema: async () => {
			// Simulate a delay
			await new Promise((resolve) => setTimeout(resolve, 1000));
			return {
				schema: z.object({
				title: z.string(),
				body: z.string(),
				userId: z.number(),
				id: z.number(),
			}),
			types: /* ts */`export interface Collection {
	title: string;
	body: string;
	userId: number;
	id: number;
}`
			}
		}
	};
}


Review comment (suggestion):
```suggestion
			types: /* ts */`export interface Entry {
```

Code after:
			if (lastSynced && (Date.now() - Number(lastSynced) < 1000 * 60)) {
					logger.info('Skipping sync');
					return;
			}

			const posts = await fetch(config.url)
				.then((res) => res.json());

			store.clear();

			for (const data of posts) {
				store.set({id: data.id, data});
			}
			meta.set('lastSynced', String(Date.now()));
		},
		createSchema: async () => {
			// Simulate a delay
			await new Promise((resolve) => setTimeout(resolve, 1000));
			return {
				schema: z.object({
				title: z.string(),
				body: z.string(),
				userId: z.number(),
				id: z.number(),
			}),
			types: /* ts */`export interface Entry {
	title: string;
	body: string;
	userId: number;
	id: number;
}`
			}
		}
	};
}
Repository: withastro/astro
File: packages/astro/test/fixtures/content-layer/src/content.config.ts (TypeScript)

Code before:
			const lastValue = entry?.data.lastValue ?? 0;
			const raw = {
				id: 'value',
				data: {
					lastValue: lastValue + 1,
					lastUpdated: new Date(),
					refreshContextData,
					slug: 'slimy'
				},
			}
			const parsed = await parseData(raw)
			store.set({
				id: raw.id,
				data: parsed,
				rendered: await renderMarkdown(markdownContent)
			});
		},
		createSchema: async () => {
			return {
				schema: z.object({
				lastValue: z.number(),
				lastUpdated: z.date(),
				refreshContextData: z.record(z.unknown()).optional(),
				slug: z.string().optional(),
			}),
			types: /* ts */`export interface Collection {
	lastValue: number;
	lastUpdated: Date;
	refreshContextData?: Record<string, unknown> | undefined;
	slug?: string | undefined;
}`
			}
		}
	},
});

const artists = defineCollection({
        loader: file('src/data/artists.toml'),
        schema: z.object({
                name: z.string(),
                genre: z.string().array(),
        }),
});

const songs = defineCollection({
        loader: file('src/data/songs.toml'),
        schema: z.object({
                name: z.string(),
                artists: z.array(reference('artists')),
        }),
});

Review comment (suggestion):
```suggestion
			types: /* ts */`export interface Entry {
```

Code after:
			const entry = store.get<{ lastValue: number }>('value');
			const lastValue = entry?.data.lastValue ?? 0;
			const raw = {
				id: 'value',
				data: {
					lastValue: lastValue + 1,
					lastUpdated: new Date(),
					refreshContextData,
					slug: 'slimy'
				},
			}
			const parsed = await parseData(raw)
			store.set({
				id: raw.id,
				data: parsed,
				rendered: await renderMarkdown(markdownContent)
			});
		},
		createSchema: async () => {
			return {
				schema: z.object({
				lastValue: z.number(),
				lastUpdated: z.date(),
				refreshContextData: z.record(z.unknown()).optional(),
				slug: z.string().optional(),
			}),
			types: /* ts */`export interface Entry {
	lastValue: number;
	lastUpdated: Date;
	refreshContextData?: Record<string, unknown> | undefined;
	slug?: string | undefined;
}`
			}
		}
	},
});

const artists = defineCollection({
        loader: file('src/data/artists.toml'),
        schema: z.object({
                name: z.string(),
                genre: z.string().array(),
        }),
});

const songs = defineCollection({
        loader: file('src/data/songs.toml'),
        schema: z.object({
                name: z.string(),
                artists: z.array(reference('artists')),
        }),
Repository: withastro/astro
File: packages/astro/src/content/utils.ts (TypeScript)

Code before:
			.object({
				id: z
					.string({
						invalid_type_error: 'Content entry `id` must be a string',
					})
					.optional(),
			})
			.passthrough(),
	),
]);

const collectionConfigParser = z.union([
	z.object({
		type: z.literal(CONTENT_LAYER_TYPE),
		schema: z.any().optional(),
		loader: z.union([
			z.function(),
			z.object({
				name: z.string(),
				load: z.function().args(z.custom<LoaderContext>()).returns(z.promise(z.void())),
				schema: z
					.any()
					.transform((v) => {
						if (typeof v === 'function') {
							console.warn(
								`Since Astro 6, a loader schema cannot be a function. It is ignored and will break in a future major. Report it to the loader author or check the docs: TODO:`,
							);
							return undefined;
						}
						return v;
					})
					.superRefine((v, ctx) => {
						if (v !== undefined && !('_def' in v)) {
							ctx.addIssue({
								code: z.ZodIssueCode.custom,
								message: 'Invalid Zod schema',
							});
							return z.NEVER;
						}
					})
					.optional(),
				createSchema: z
					.function()
					.returns(
						z.promise(
							z.object({
								schema: z.custom<ZodSchema>((v) => '_def' in v),
								types: z.string(),
							}),
						),
					)

Review comment (security):
```suggestion
								`Your loader's schema is defined using a function. This is no longer supported and the schema will be ignored. Please update your loader to use the `createSchema()` utility instead, or report this to the loader author. In a future major version, this will cause the loader to break entirely.`,
```
Maybe something like this? 

Code after:
			.object({
				id: z
					.string({
						invalid_type_error: 'Content entry `id` must be a string',
					})
					.optional(),
			})
			.passthrough(),
	),
]);

const collectionConfigParser = z.union([
	z.object({
		type: z.literal(CONTENT_LAYER_TYPE),
		schema: z.any().optional(),
		loader: z.union([
			z.function(),
			z.object({
				name: z.string(),
				load: z.function().args(z.custom<LoaderContext>()).returns(z.promise(z.void())),
				schema: z
					.any()
					.transform((v) => {
						if (typeof v === 'function') {
							console.warn(
								`Your loader's schema is defined using a function. This is no longer supported and the schema will be ignored. Please update your loader to use the \`createSchema()\` utility instead, or report this to the loader author. In a future major version, this will cause the loader to break entirely.`,
							);
							return undefined;
						}
						return v;
					})
					.superRefine((v, ctx) => {
						if (v !== undefined && !('_def' in v)) {
							ctx.addIssue({
								code: z.ZodIssueCode.custom,
								message: 'Invalid Zod schema',
							});
							return z.NEVER;
						}
					})
					.optional(),
				createSchema: z
					.function()
					.returns(
						z.promise(
							z.object({
								schema: z.custom<ZodSchema>((v) => '_def' in v),
								types: z.string(),
							}),
						),
					)
Repository: withastro/astro
File: packages/astro/src/content/utils.ts (TypeScript)

Code before:
			.object({
				id: z
					.string({
						invalid_type_error: 'Content entry `id` must be a string',
					})
					.optional(),
			})
			.passthrough(),
	),
]);

const collectionConfigParser = z.union([
	z.object({
		type: z.literal(CONTENT_LAYER_TYPE),
		schema: z.any().optional(),
		loader: z.union([
			z.function(),
			z.object({
				name: z.string(),
				load: z.function().args(z.custom<LoaderContext>()).returns(z.promise(z.void())),
				schema: z
					.any()
					.transform((v) => {
						if (typeof v === 'function') {
							console.warn(
								`Your loader's schema is defined using a function. This is no longer supported and the schema will be ignored. Please update your loader to use the `createSchema()` utility instead, or report this to the loader author. In a future major version, this will cause the loader to break entirely.`,
							);
							return undefined;
						}
						return v;
					})
					.superRefine((v, ctx) => {
						if (v !== undefined && !('_def' in v)) {
							ctx.addIssue({
								code: z.ZodIssueCode.custom,
								message: 'Invalid Zod schema',
							});
							return z.NEVER;
						}
					})
					.optional(),
				createSchema: z
					.function()
					.returns(
						z.promise(
							z.object({
								schema: z.custom<ZodSchema>((v) => '_def' in v),
								types: z.string(),
							}),
						),
					)

Review comment (security):
```suggestion
								`Your loader's schema is defined using a function. This is no longer supported and the schema will be ignored. Please update your loader to use the \`createSchema()\` utility instead, or report this to the loader author. In a future major version, this will cause the loader to break entirely.`,
```

Code after:
			.object({
				id: z
					.string({
						invalid_type_error: 'Content entry `id` must be a string',
					})
					.optional(),
			})
			.passthrough(),
	),
]);

const collectionConfigParser = z.union([
	z.object({
		type: z.literal(CONTENT_LAYER_TYPE),
		schema: z.any().optional(),
		loader: z.union([
			z.function(),
			z.object({
				name: z.string(),
				load: z.function().args(z.custom<LoaderContext>()).returns(z.promise(z.void())),
				schema: z
					.any()
					.transform((v) => {
						if (typeof v === 'function') {
							console.warn(
								`Your loader's schema is defined using a function. This is no longer supported and the schema will be ignored. Please update your loader to use the \`createSchema()\` utility instead, or report this to the loader author. In a future major version, this will cause the loader to break entirely.`,
							);
							return undefined;
						}
						return v;
					})
					.superRefine((v, ctx) => {
						if (v !== undefined && !('_def' in v)) {
							ctx.addIssue({
								code: z.ZodIssueCode.custom,
								message: 'Invalid Zod schema',
							});
							return z.NEVER;
						}
					})
					.optional(),
				createSchema: z
					.function()
					.returns(
						z.promise(
							z.object({
								schema: z.custom<ZodSchema>((v) => '_def' in v),
								types: z.string(),
							}),
						),
					)
Repository: withastro/astro
File: packages/astro/src/core/errors/errors.ts (TypeScript)

Code before:
		this.hint = hint;
		this.frame = frame;
	}

	public setLocation(location: ErrorLocation): void {
		this.loc = location;
	}

	public setName(name: string): void {
		this.name = name;
	}

	public setMessage(message: string): void {
		this.message = message;
	}

	public setHint(hint: string): void {
		this.hint = hint;
	}

	public setFrame(source: string, location: ErrorLocation): void {
		this.frame = codeFrame(source, location);
	}

	static is(err: unknown): err is AstroError {
		return err != null && (err as AstroError).type === 'AstroError';
	}
}

export class CompilerError extends AstroError {
	type: ErrorTypes = 'CompilerError';

	constructor(props: ErrorProperties, options?: ErrorOptions) {
		super(props, options);
	}

	static is(err: unknown): err is CompilerError {
		return err != null && (err as CompilerError).type === 'CompilerError';
	}
}

export class CSSError extends AstroError {
	type: ErrorTypes = 'CSSError';

	static is(err: unknown): err is CSSError {
		return err != null && (err as CSSError).type === 'CSSError';
	}
}

export class MarkdownError extends AstroError {
	type: ErrorTypes = 'MarkdownError';

Review comment (suggestion):
More a stylistic thing, but I guess we might as well use optional chaining for all of these?
```suggestion
		return (err as AstroError)?.type === 'AstroError';
```

Code after:
		this.hint = hint;
		this.frame = frame;
	}

	public setLocation(location: ErrorLocation): void {
		this.loc = location;
	}

	public setName(name: string): void {
		this.name = name;
	}

	public setMessage(message: string): void {
		this.message = message;
	}

	public setHint(hint: string): void {
		this.hint = hint;
	}

	public setFrame(source: string, location: ErrorLocation): void {
		this.frame = codeFrame(source, location);
	}

	static is(err: unknown): err is AstroError {
		return (err as AstroError)?.type === 'AstroError';
	}
}

export class CompilerError extends AstroError {
	type: ErrorTypes = 'CompilerError';

	constructor(props: ErrorProperties, options?: ErrorOptions) {
		super(props, options);
	}

	static is(err: unknown): err is CompilerError {
		return (err as CompilerError)?.type === 'CompilerError';
	}
}

export class CSSError extends AstroError {
	type: ErrorTypes = 'CSSError';

	static is(err: unknown): err is CSSError {
		return (err as CSSError)?.type === 'CSSError';
	}
}

export class MarkdownError extends AstroError {
	type: ErrorTypes = 'MarkdownError';
Repository: withastro/astro
File: packages/astro/src/core/sync/index.ts (TypeScript)

Code before:
 */
async function syncContentCollections(
	settings: AstroSettings,
	{
		mode,
		logger,
		fs,
		routesList,
		manifest,
	}: Required<Pick<SyncOptions, 'mode' | 'logger' | 'fs' | 'routesList' | 'manifest'>>,
): Promise<void> {
	// Needed to load content config
	const tempViteServer = await createServer(
		await createVite(
			{
				server: { middlewareMode: true, hmr: false, watch: null, ws: false },
				optimizeDeps: { noDiscovery: true },
				ssr: { external: [] },
				logLevel: 'silent',
			},
			{
				settings: {
					...settings,
					buildOutput: undefined,
					injectedCsp: {
						fontResources: new Set(),
						styleHashes: [],
					},
				},
				logger,
				mode,
				command: 'build',
				fs,
				sync: true,
				routesList,
				manifest,
			},
		),
	);

	// Patch `hot.send` to bubble up error events
	// `hot.on('error')` does not fire for some reason
	const hotSend = tempViteServer.hot.send;
	tempViteServer.hot.send = (payload: HMRPayload) => {
		if (payload.type === 'error') {
			throw payload.err;
		}
		return hotSend(payload);
	};

	try {

Review comment (suggestion):
```suggestion
					// Prevent mutation by vite plugins during sync
					buildOutput: undefined,
```

Code after:
 */
async function syncContentCollections(
	settings: AstroSettings,
	{
		mode,
		logger,
		fs,
		routesList,
		manifest,
	}: Required<Pick<SyncOptions, 'mode' | 'logger' | 'fs' | 'routesList' | 'manifest'>>,
): Promise<void> {
	// Needed to load content config
	const tempViteServer = await createServer(
		await createVite(
			{
				server: { middlewareMode: true, hmr: false, watch: null, ws: false },
				optimizeDeps: { noDiscovery: true },
				ssr: { external: [] },
				logLevel: 'silent',
			},
			{
				// Prevent mutation of specific properties by vite plugins during sync
				settings: {
					...settings,
					// Prevent mutation by vite plugins during sync
					buildOutput: undefined,
					// Sync causes font resources and style hashes to be duplicated
					injectedCsp: {
						fontResources: new Set(),
						styleHashes: [],
					},
				},
				logger,
				mode,
				command: 'build',
				fs,
				sync: true,
				routesList,
				manifest,
			},
		),
	);

	// Patch `hot.send` to bubble up error events
	// `hot.on('error')` does not fire for some reason
	const hotSend = tempViteServer.hot.send;
	tempViteServer.hot.send = (payload: HMRPayload) => {
		if (payload.type === 'error') {
			throw payload.err;
		}
		return hotSend(payload);