Skip to content
Draft
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
113 changes: 113 additions & 0 deletions evals/docs/build-docs-036-generating-types/EVAL.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import {
buildDocsResult,
type CheckResult,
type LocalStackEvalContext,
type LocalStackScorer,
} from '@supabase-evals/core';
import { REFRESH_SCRIPT, type Refresh, refreshAfterChange } from './refresh.js';
import { type Analysis, analyze, PROBE } from './typecheck.js';

const GUIDE_PATH = 'guides/api/rest/generating-types';
const CONTROL_NOTE =
'a known-bad control raised no error, so the types could not be judged';

const scorer: LocalStackScorer = async (ctx) => {
try {
const snapshot = analyze(ctx.hostWorkspace);
const refreshed = await refreshAfterChange(ctx);

const checks: CheckResult[] = [
checkAppTypeChecks(snapshot),
checkTypesMatchSchema(snapshot),
checkRefreshFollowsChange(refreshed),
checkGuideWasRead(ctx),
];

return { passed: checks.every((check) => check.passed), checks };
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return {
passed: false,
checks: [
{
name: 'scorer evaluated the database types',
passed: false,
notes: message,
},
],
};
}
};

export default scorer;

function checkAppTypeChecks(analysis: Analysis): CheckResult {
const name =
'the app type-checks in strict mode with no suppression comments';
if (!analysis.ok) return { name, passed: false, notes: analysis.reason };
const { appDiagnostics, suppressions } = analysis;
const problems = [
appDiagnostics.length > 0
? `${appDiagnostics.length} diagnostics: ${appDiagnostics.slice(0, 5).join('; ')}`
: '',
suppressions.length > 0
? `suppression comments at ${suppressions.slice(0, 5).join(', ')}`
: '',
].filter((problem) => problem.length > 0);
return {
name,
passed: problems.length === 0,
notes:
problems.length === 0
? 'no diagnostics with strict mode forced on, and no @ts-ignore, @ts-expect-error or @ts-nocheck'
: problems.join('; '),
};
}

function checkTypesMatchSchema(analysis: Analysis): CheckResult {
const name = 'the types match the local tables and function the app uses';
if (!analysis.ok) return { name, passed: false, notes: analysis.reason };
if (analysis.failedProbes.length > 0) {
return {
name,
passed: false,
notes: `wrong or missing: ${analysis.failedProbes.join(', ')}`,
};
}
if (!analysis.controlFired) {
return { name, passed: false, notes: CONTROL_NOTE };
}
return { name, passed: true, notes: Object.values(PROBE).join(', ') };
}

function checkRefreshFollowsChange(refresh: Refresh): CheckResult {
const name =
'the refresh command picks up a new column in the local database';
if (!refresh.ran) return { name, passed: false, notes: refresh.reason };
const { analysis, column } = refresh;
if (!analysis.ok) return { name, passed: false, notes: analysis.reason };
return {
name,
passed: analysis.booksRowMatches,
notes: analysis.booksRowMatches
? `npm run ${REFRESH_SCRIPT} added catalog.books.${column} to the types the app is created with`
: `after npm run ${REFRESH_SCRIPT}, the types the app is created with do not describe catalog.books with ${column}`,
};
}

function checkGuideWasRead(ctx: LocalStackEvalContext): CheckResult {
const calls = buildDocsResult(ctx.toolCalls).calls.filter((call) =>
call.pages?.some((page) => page.url.includes(GUIDE_PATH))
);
const withContent = calls.filter((call) => call.hasContent);
return {
name: 'the agent read the generating types guide the prompt referenced',
passed: withContent.length > 0,
notes:
withContent.length > 0
? withContent.map((call) => call.source).join(', ')
: calls.length > 0
? `reached the guide via ${calls.map((call) => call.source).join(', ')} but retrieved no page content`
: 'no docs call reached the guide',
};
}
31 changes: 31 additions & 0 deletions evals/docs/build-docs-036-generating-types/PROMPT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
---
stage: build
interface: cli
product:
- database
- data-api
topic:
- sdk
services: []
motivation: >-
Typed Supabase apps break when their types miss part of the database.
Customers report a second schema missing from the generated types
(supabase/supabase#54000), a schema silently left out of a types file
(supabase/cli#7625), and database functions typed as never until types are
generated. This checks that an agent reading the Generating Types guide gives
an app types that match the local database, including a second schema and a
function, and a refresh command that picks up a database change. The prompt
omits the guide's vocabulary on purpose, so read README.md before editing it.
---

The TypeScript in src/ for our bookshop app talks to the local Supabase
database, but `npm run typecheck` fails and nothing tells us when the code and
the database drift apart. Get the app's types in line with the local database
so the check passes, and make the refresh command in CONTRIBUTING.md work so we
can keep them current after each database change.

Read the guide below before you start and rely on it for how to set this up,
rather than on what you already know.

REFERENCE
https://supabase.com/docs/guides/api/rest/generating-types.md
81 changes: 81 additions & 0 deletions evals/docs/build-docs-036-generating-types/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
# build-docs-036-generating-types

## What this eval measures

The subject is [Generating TypeScript Types](https://supabase.com/docs/guides/api/rest/generating-types), not the agent.
The prompt is a product request plus the page's url, and the checks say whether an agent that read the page gives an app
types that match the local database.

One claim: the types the app is created with match the live local schema, including a second exposed schema and a
database function, and the team's refresh command regenerates them after the schema changes.

## How it differs from build-database-006-regenerate-types

`evals/cli/build-database-006-regenerate-types` measures the agent across CLI versions and Docker setups. It hands over a
migration, and scores regenerating stale types and fixing app code that no longer compiles. This eval measures a docs
page on one CLI. The app code is already correct, the types do not exist yet, part of the schema sits outside `public`,
and the refresh command is run again by the scorer after it changes the database.

## Do not reintroduce the vocabulary

Keep all of these out of `PROMPT.md`:

generate, gen types, CLI, `supabase gen`, `--local`, `--schema`, schema, catalog, introspection, `database.types.ts`,
`Database`, `createClient<Database>`, type definitions, rpc, function, migration.

## The seed carries the contract

- `src/lib/supabase.ts` already calls `createClient<Database>` with `Database` from `./database.types`, which does not
exist. The answer has a place to land. The checks find every `createClient<...>` call under `src/` and use its type
argument and that file's imports, so a moved client, a namespace import or types kept under `supabase/` all pass.
- `CONTRIBUTING.md` names `npm run db:types` and says it refreshes the app's types from the local database.
`package.json` has no such script. The refresh check needs a fixed command to run, so the name is given rather than
discovered. The command behind it is the agent's choice.
- The migration puts `books`, the `book_format` enum and the `search_books` function in a `catalog` schema that
`config.toml` exposes, and `orders` in `public`. A types file limited to `public` cannot compile the app.
- `config.toml` is minimal and has no `[inbucket]` section, so a newer CLI can read it too.
- `services: []` starts only the database. On CLI 2.117.0, `gen types --local` runs a one-off `postgres-meta` container
of its own, so it works without that service started.

## Do not drop the positive controls

The probe holds two controls: `Equals<1, 2>` and a wrong row shape for `catalog.books`. Both must raise an error. The
second one catches a types module that did not resolve, because TypeScript stays silent about assertions on an
unresolved import. Without it an empty workspace scores green.

## How the checks read the end state

- The type checks run host-side on a copy of every `.ts` file outside `node_modules`, `.git` and `supabase/functions`,
with the repo's TypeScript and `@supabase/supabase-js`. The workspace's `node_modules` is linked in for any other
import, such as `type-fest`. The scorer and the read-back of the sandbox share one file filter.
- The whole strict family is removed from the agent's `tsconfig.json` and `strict` is forced on. Any `@ts-ignore`,
`@ts-expect-error` or `@ts-nocheck` in a compiled file outside `node_modules` fails the first check. The seed has none.
- The probe compares, by type identity after flattening intersections, the `Row` of `catalog.books`, the `Args` and
`Returns` of `catalog.search_books`, and the `Row` and `Insert` of `public.orders`. An `any` or `string` column fails.
Output from CLI 2.117.0 and 3.4.0 both pass.
- `the refresh command picks up a new column in the local database` adds a column with a run-scoped name to
`catalog.books`, links the sandbox's pinned CLI to `node_modules/.bin/supabase` when nothing is there, runs
`npm run db:types`, reads the workspace back, and asserts the column is in the `catalog.books` row. The link means
`supabase` and `npx supabase` in the script both run the pinned CLI with no download. It runs last because it changes
the database. Score once per stack.

## The guide has to actually be read

`the agent read the generating types guide the prompt referenced` requires a docs call that reached the page with
content. Read `docs.calls` before reading a score.

## Checks expected to saturate

`the app type-checks in strict mode with no suppression comments`, because the agent can run `npm run typecheck` and see
the failure. The signal is expected in the probe check, for a types file limited to `public`, and in the refresh check,
for hand-written types, a script that writes somewhere the app does not import, or a script that targets a hosted
project.

## What this eval does not score

- **Whether the app code changed.** The seed's code is correct against the schema. The probe does not read it.
- **Generating types from a hosted project.** None is reachable locally.
- **Generating types for other languages.**
- **Overriding generated types.** An override that keeps the shapes above passes.
- **Keeping types current on a schedule.** Only the refresh command is run.
- **A stopped stack.** If the agent stops the database, the refresh check cannot add its column and fails.
48 changes: 48 additions & 0 deletions evals/docs/build-docs-036-generating-types/files.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import type { Dirent } from 'node:fs';

type ReadDir = (path: string) => Dirent[];

export function isSourcePath(path: string): boolean {
const segments = path
.split(/[\\/]/)
.filter((segment) => segment !== '' && segment !== '.');
if (
segments.some((segment) => segment === 'node_modules' || segment === '.git')
) {
return false;
}
if (segments[0] === 'supabase' && segments[1] === 'functions') {
return false;
}
return /\.(ts|tsx|mts|cts)$/.test(segments[segments.length - 1] ?? '');
}

export function listSources(root: string, readDir: ReadDir): string[] {
const found: string[] = [];
const pending = [''];
while (pending.length > 0) {
const relative = pending.pop() ?? '';
for (const entry of readDir(relative ? `${root}/${relative}` : root)) {
const child = relative ? `${relative}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
if (isSourcePath(`${child}/index.ts`)) pending.push(child);
} else if (entry.isFile() && isSourcePath(child)) {
found.push(child);
}
}
}
return found.sort();
}

export function collectSourcesScript(): string {
return [
'const __name = (target) => target;',
"const fs = require('fs');",
isSourcePath.toString(),
listSources.toString(),
'const readDir = (path) => fs.readdirSync(path, { withFileTypes: true });',
'const out = {};',
"for (const file of listSources('.', readDir)) out[file] = fs.readFileSync(file, 'utf8');",
'process.stdout.write(JSON.stringify(out));',
].join('\n');
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Contributing

Database changes go in `supabase/migrations`.

After a database change, run `npm run db:types` to bring the app's types up to date with the local database. Then run
`npm run typecheck`. Both have to pass before a change is merged.
14 changes: 14 additions & 0 deletions evals/docs/build-docs-036-generating-types/local/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"name": "bookshop",
"private": true,
"type": "module",
"scripts": {
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@supabase/supabase-js": "^2.105.1"
},
"devDependencies": {
"typescript": "^5.9.3"
}
}
37 changes: 37 additions & 0 deletions evals/docs/build-docs-036-generating-types/local/src/catalog.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import type { Client } from './lib/supabase';

export type BookFormat = 'paperback' | 'hardcover' | 'ebook';

export type BookCard = {
id: number;
title: string;
author: string;
price_cents: number;
format: BookFormat;
};

export async function listBooks(db: Client): Promise<BookCard[]> {
const { data, error } = await db
.schema('catalog')
.from('books')
.select('id, title, author, price_cents, format')
.order('title');
if (error) throw error;
return data;
}

export async function searchBooks(db: Client, term: string) {
const { data, error } = await db
.schema('catalog')
.rpc('search_books', { term });
if (error) throw error;
return data.map((book) => ({
id: book.id,
title: book.title,
blurb: book.blurb ?? '',
}));
}

export function priceLabel(book: BookCard): string {
return `$${(book.price_cents / 100).toFixed(2)}`;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { createClient } from '@supabase/supabase-js';
import type { Database } from './database.types';

export function connect(url: string, key: string) {
return createClient<Database>(url, key);
}

export type Client = ReturnType<typeof connect>;
16 changes: 16 additions & 0 deletions evals/docs/build-docs-036-generating-types/local/src/orders.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import type { Client } from './lib/supabase';

export async function placeOrder(
db: Client,
bookId: number,
quantity: number,
giftNote?: string
) {
const { data, error } = await db
.from('orders')
.insert({ book_id: bookId, quantity, gift_note: giftNote ?? null })
.select('id, placed_at')
.single();
if (error) throw error;
return { orderId: data.id, placedAt: new Date(data.placed_at) };
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
project_id = "sandbox-generating-types"

[api]
enabled = true
port = 54321
schemas = ["public", "graphql_public", "catalog"]
extra_search_path = ["public", "extensions"]
max_rows = 1000

[db]
port = 54322
shadow_port = 54320
major_version = 17

[db.migrations]
enabled = true

[db.seed]
enabled = false
Loading
Loading