feat(supabase): @faunosteo/supabase package with PGlite harness and typed client

- tests/db: PGlite (PostgreSQL 17 WASM) applies the Supabase shim + migrations and
  runs supabase/tests/*.sql through pgTAP without Docker
- schema-types test pins tables, columns, enums, RPC args, RLS-on, no using(true)
- database.types.ts in supabase gen types format; createBrowserClient (PKCE)
- Supabase CLI pinned as root devDependency; db:* root scripts
This commit is contained in:
bchanot committed 2026-10-08 22:20:54 +02:00
1 parent 2d5ff0c33e
commit ce76c6597a
15 files changed
+1020 -2

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
import globals from 'globals'
import tseslint from 'typescript-eslint'
export default tseslint.config(
{ ignores: ['node_modules/**'] },
{
files: ['**/*.ts'],
extends: [...tseslint.configs.recommended],
languageOptions: {
globals: { ...globals.node, ...globals.es2022 },
},
rules: {
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
},
},
)
+33
View File
@@ -0,0 +1,33 @@
{
"name": "@faunosteo/supabase",
"version": "0.1.0",
"private": true,
"description": "Faunosteo Supabase access layer: typed browser client, generated database types, SQL test harness",
"license": "MIT",
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts",
"./types": "./src/database.types.ts"
},
"scripts": {
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "vitest",
"test:run": "vitest run",
"lint": "eslint . --max-warnings 0",
"build": "tsc -p tsconfig.json --noEmit"
},
"dependencies": {
"@supabase/supabase-js": "^2.100.0"
},
"devDependencies": {
"@electric-sql/pglite": "^0.3.0",
"@types/node": "^20.19.41",
"eslint": "^9.17.0",
"globals": "^15.14.0",
"typescript": "^5.7.2",
"typescript-eslint": "^8.19.0",
"vitest": "^3.2.7"
}
}
+29
View File
@@ -0,0 +1,29 @@
import { createClient, type SupabaseClient } from '@supabase/supabase-js'
import type { Database } from './database.types'
/** Typed Supabase client for the Faunosteo database. */
export type FaunosteoClient = SupabaseClient<Database>
/**
* Public connection settings. The anon (publishable) key is safe to ship to
* the browser: every table is behind RLS. The service-role key never is.
*/
export interface SupabaseConnection {
url: string
anonKey: string
}
/**
* Browser client: session persisted in localStorage, tokens refreshed in the
* background, PKCE for OAuth and magic-link redirects.
*/
export function createBrowserClient(connection: SupabaseConnection): FaunosteoClient {
return createClient<Database>(connection.url, connection.anonKey, {
auth: {
persistSession: true,
autoRefreshToken: true,
detectSessionInUrl: true,
flowType: 'pkce',
},
})
}
+271
View File
@@ -0,0 +1,271 @@
// Database types in the `supabase gen types typescript` format.
// Regenerate after every migration: `pnpm db:types` (needs the local stack);
// CI runs `pnpm db:types:check`. packages/supabase/tests/db/schema-types.test.ts
// checks tables, columns, enums and RPC names against the migrated schema.
export type Json =
| string
| number
| boolean
| null
| { [key: string]: Json | undefined }
| Json[]
export type Database = {
// Allows to automatically instantiate createClient with right options
// instead of createClient<Database, { PostgrestVersion: 'XX' }>(URL, KEY)
__InternalSupabase: {
PostgrestVersion: "13"
}
public: {
Tables: {
profile_roles: {
Row: {
granted_at: string
granted_by: string | null
id: string
revoke_reason: string | null
revoked_at: string | null
revoked_by: string | null
role: Database["public"]["Enums"]["platform_role"]
user_id: string
}
Insert: {
granted_at?: string
granted_by?: string | null
id?: string
revoke_reason?: string | null
revoked_at?: string | null
revoked_by?: string | null
role: Database["public"]["Enums"]["platform_role"]
user_id: string
}
Update: {
granted_at?: string
granted_by?: string | null
id?: string
revoke_reason?: string | null
revoked_at?: string | null
revoked_by?: string | null
role?: Database["public"]["Enums"]["platform_role"]
user_id?: string
}
Relationships: [
{
foreignKeyName: "profile_roles_granted_by_fkey"
columns: ["granted_by"]
isOneToOne: false
referencedRelation: "profiles"
referencedColumns: ["id"]
},
{
foreignKeyName: "profile_roles_revoked_by_fkey"
columns: ["revoked_by"]
isOneToOne: false
referencedRelation: "profiles"
referencedColumns: ["id"]
},
{
foreignKeyName: "profile_roles_user_id_fkey"
columns: ["user_id"]
isOneToOne: false
referencedRelation: "profiles"
referencedColumns: ["id"]
},
]
}
profiles: {
Row: {
active: boolean
created_at: string
display_name: string
first_name: string | null
id: string
last_name: string | null
locale: string
phone: string | null
phone_verified_at: string | null
timezone: string
updated_at: string
}
Insert: {
active?: boolean
created_at?: string
display_name: string
first_name?: string | null
id: string
last_name?: string | null
locale?: string
phone?: string | null
phone_verified_at?: string | null
timezone?: string
updated_at?: string
}
Update: {
active?: boolean
created_at?: string
display_name?: string
first_name?: string | null
id?: string
last_name?: string | null
locale?: string
phone?: string | null
phone_verified_at?: string | null
timezone?: string
updated_at?: string
}
Relationships: []
}
}
Views: {
[_ in never]: never
}
Functions: {
grant_platform_role: {
Args: {
role: Database["public"]["Enums"]["platform_role"]
target_user_id: string
}
Returns: string
}
revoke_platform_role: {
Args: {
reason?: string
role: Database["public"]["Enums"]["platform_role"]
target_user_id: string
}
Returns: string
}
}
Enums: {
platform_role: "owner" | "admin" | "moderator" | "support"
}
CompositeTypes: {
[_ in never]: never
}
}
}
type DatabaseWithoutInternals = Omit<Database, "__InternalSupabase">
type DefaultSchema = DatabaseWithoutInternals[Extract<keyof DatabaseWithoutInternals, "public">]
export type Tables<
DefaultSchemaTableNameOrOptions extends
| keyof (DefaultSchema["Tables"] & DefaultSchema["Views"])
| { schema: keyof DatabaseWithoutInternals },
TableName extends DefaultSchemaTableNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? keyof (DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]]["Tables"] &
DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]]["Views"])
: never = never,
> = DefaultSchemaTableNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? (DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]]["Tables"] &
DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]]["Views"])[TableName] extends {
Row: infer R
}
? R
: never
: DefaultSchemaTableNameOrOptions extends keyof (DefaultSchema["Tables"] &
DefaultSchema["Views"])
? (DefaultSchema["Tables"] &
DefaultSchema["Views"])[DefaultSchemaTableNameOrOptions] extends {
Row: infer R
}
? R
: never
: never
export type TablesInsert<
DefaultSchemaTableNameOrOptions extends
| keyof DefaultSchema["Tables"]
| { schema: keyof DatabaseWithoutInternals },
TableName extends DefaultSchemaTableNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? keyof DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]]["Tables"]
: never = never,
> = DefaultSchemaTableNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]]["Tables"][TableName] extends {
Insert: infer I
}
? I
: never
: DefaultSchemaTableNameOrOptions extends keyof DefaultSchema["Tables"]
? DefaultSchema["Tables"][DefaultSchemaTableNameOrOptions] extends {
Insert: infer I
}
? I
: never
: never
export type TablesUpdate<
DefaultSchemaTableNameOrOptions extends
| keyof DefaultSchema["Tables"]
| { schema: keyof DatabaseWithoutInternals },
TableName extends DefaultSchemaTableNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? keyof DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]]["Tables"]
: never = never,
> = DefaultSchemaTableNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions["schema"]]["Tables"][TableName] extends {
Update: infer U
}
? U
: never
: DefaultSchemaTableNameOrOptions extends keyof DefaultSchema["Tables"]
? DefaultSchema["Tables"][DefaultSchemaTableNameOrOptions] extends {
Update: infer U
}
? U
: never
: never
export type Enums<
DefaultSchemaEnumNameOrOptions extends
| keyof DefaultSchema["Enums"]
| { schema: keyof DatabaseWithoutInternals },
EnumName extends DefaultSchemaEnumNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? keyof DatabaseWithoutInternals[DefaultSchemaEnumNameOrOptions["schema"]]["Enums"]
: never = never,
> = DefaultSchemaEnumNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? DatabaseWithoutInternals[DefaultSchemaEnumNameOrOptions["schema"]]["Enums"][EnumName]
: DefaultSchemaEnumNameOrOptions extends keyof DefaultSchema["Enums"]
? DefaultSchema["Enums"][DefaultSchemaEnumNameOrOptions]
: never
export type CompositeTypes<
PublicCompositeTypeNameOrOptions extends
| keyof DefaultSchema["CompositeTypes"]
| { schema: keyof DatabaseWithoutInternals },
CompositeTypeName extends PublicCompositeTypeNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? keyof DatabaseWithoutInternals[PublicCompositeTypeNameOrOptions["schema"]]["CompositeTypes"]
: never = never,
> = PublicCompositeTypeNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? DatabaseWithoutInternals[PublicCompositeTypeNameOrOptions["schema"]]["CompositeTypes"][CompositeTypeName]
: PublicCompositeTypeNameOrOptions extends keyof DefaultSchema["CompositeTypes"]
? DefaultSchema["CompositeTypes"][PublicCompositeTypeNameOrOptions]
: never
export const Constants = {
public: {
Enums: {
platform_role: ["owner", "admin", "moderator", "support"],
},
},
} as const
+23
View File
@@ -0,0 +1,23 @@
export {
createBrowserClient,
type FaunosteoClient,
type SupabaseConnection,
} from './client'
export type {
Database,
Enums,
Json,
Tables,
TablesInsert,
TablesUpdate,
} from './database.types'
export { Constants } from './database.types'
import type { Enums, Tables } from './database.types'
/** Row of public.profiles. */
export type Profile = Tables<'profiles'>
/** Row of public.profile_roles. */
export type ProfileRole = Tables<'profile_roles'>
/** owner | admin | moderator | support. Not a professional status. */
export type PlatformRole = Enums<'platform_role'>
+21
View File
@@ -0,0 +1,21 @@
import { createBrowserClient, Constants, type PlatformRole } from '../src'
describe('createBrowserClient', () => {
it('builds a typed client bound to the given project URL', () => {
const client = createBrowserClient({
url: 'http://127.0.0.1:54321',
anonKey: 'anon-key-placeholder',
})
expect(typeof client.from).toBe('function')
expect(client.auth).toBeDefined()
// supabase-js keeps the resolved REST URL on the client instance.
expect(String((client as unknown as { supabaseUrl: string }).supabaseUrl)).toContain(
'127.0.0.1:54321',
)
})
it('exposes the platform roles as runtime constants', () => {
const roles: readonly PlatformRole[] = Constants.public.Enums.platform_role
expect(roles).toEqual(['owner', 'admin', 'moderator', 'support'])
})
})
+80
View File
@@ -0,0 +1,80 @@
/**
* PGlite harness: a real PostgreSQL (WASM) that applies the Supabase shim,
* then every migration under supabase/migrations, in filename order.
* Lets the pgTAP suite and the schema checks run without Docker. The same
* SQL runs unchanged under `supabase test db` on the real stack.
*/
import { readdir, readFile } from 'node:fs/promises'
import { resolve, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { PGlite } from '@electric-sql/pglite'
import { pgtap } from '@electric-sql/pglite/pgtap'
const here = fileURLToPath(new URL('.', import.meta.url))
export const repoRoot = resolve(here, '../../../..')
export const supabaseDir = join(repoRoot, 'supabase')
export const migrationsDir = join(supabaseDir, 'migrations')
export const pgTapTestsDir = join(supabaseDir, 'tests')
async function listSqlFiles(dir: string): Promise<string[]> {
const entries = await readdir(dir)
return entries.filter((f) => f.endsWith('.sql')).sort()
}
export async function listMigrations(): Promise<string[]> {
return listSqlFiles(migrationsDir)
}
export async function listPgTapTests(): Promise<string[]> {
return listSqlFiles(pgTapTestsDir)
}
/** Boots PGlite, installs the shim and applies all migrations. */
export async function createMigratedDatabase(): Promise<PGlite> {
const db = await PGlite.create({ extensions: { pgtap } })
await db.exec(await readFile(join(here, 'supabase-shim.sql'), 'utf8'))
// Same placement as `supabase test db`: pgTAP lives in extensions, out of public.
await db.exec('create extension if not exists pgtap with schema extensions;')
await db.exec('set search_path to public, extensions;')
for (const file of await listMigrations()) {
await db.exec(await readFile(join(migrationsDir, file), 'utf8'))
}
return db
}
export interface TapReport {
lines: string[]
failures: string[]
}
function collectTapLines(results: Array<{ rows: unknown[] }>): string[] {
const lines: string[] = []
for (const result of results) {
for (const row of result.rows) {
const values = Object.values(row as Record<string, unknown>)
for (const value of values) {
if (typeof value === 'string') lines.push(...value.split('\n'))
}
}
}
return lines
}
/**
* Runs one pgTAP file (which must wrap itself in begin/rollback) and reports
* every `not ok` line plus plan mismatches announced by finish().
*/
export async function runPgTapFile(db: PGlite, file: string): Promise<TapReport> {
const sql = await readFile(join(pgTapTestsDir, file), 'utf8')
let lines: string[]
try {
lines = collectTapLines(await db.exec(sql))
} finally {
// A failing statement leaves the transaction aborted: always clean up.
await db.exec('rollback;').catch(() => undefined)
}
const failures = lines.filter(
(line) => /^not ok\b/.test(line) || /^# Looks like/.test(line),
)
return { lines, failures }
}
+36
View File
@@ -0,0 +1,36 @@
/**
* Runs every pgTAP file under supabase/tests against a migrated PGlite
* database. One vitest case per SQL file: the failing TAP lines are the
* assertion message, so a red test names the exact pgTAP check.
*/
import type { PGlite } from '@electric-sql/pglite'
import {
createMigratedDatabase,
listPgTapTests,
runPgTapFile,
} from './harness'
const files = await listPgTapTests()
describe('pgTAP suite (supabase/tests) on PGlite', () => {
let db: PGlite
beforeAll(async () => {
db = await createMigratedDatabase()
})
afterAll(async () => {
await db?.close()
})
it('finds at least one pgTAP file', () => {
expect(files.length).toBeGreaterThan(0)
})
it.each(files)('%s passes', async (file) => {
const report = await runPgTapFile(db, file)
const okCount = report.lines.filter((l) => /^ok\b/.test(l)).length
expect(report.failures, report.lines.join('\n')).toEqual([])
expect(okCount).toBeGreaterThan(0)
})
})
@@ -0,0 +1,157 @@
/**
* database.types.ts must describe the migrated schema: same tables, same
* columns, same enum labels, same RPC names and arguments. The column map
* below is checked twice: by the compiler (every listed name exists in the
* type, and the type has no column missing from the list) and at runtime
* against information_schema in PGlite.
*
* Also pins two invariants for every future table in public: RLS enabled, and
* no `using (true)` policy for authenticated.
*/
import type { PGlite } from '@electric-sql/pglite'
import { Constants, type Database } from '../../src/database.types'
import { createMigratedDatabase } from './harness'
type Tables = Database['public']['Tables']
type Functions = Database['public']['Functions']
type ColumnMap = { readonly [T in keyof Tables]: readonly (keyof Tables[T]['Row'] & string)[] }
const expectedColumns = {
profile_roles: [
'granted_at',
'granted_by',
'id',
'revoke_reason',
'revoked_at',
'revoked_by',
'role',
'user_id',
],
profiles: [
'active',
'created_at',
'display_name',
'first_name',
'id',
'last_name',
'locale',
'phone',
'phone_verified_at',
'timezone',
'updated_at',
],
} as const satisfies ColumnMap
// Compile-time: a column present in the type but absent from the list is an error.
type MissingColumns = {
[T in keyof Tables]: Exclude<keyof Tables[T]['Row'], (typeof expectedColumns)[T][number]>
}[keyof Tables]
const noMissingColumn: MissingColumns extends never ? true : never = true
type FunctionArgs = { readonly [F in keyof Functions]: readonly (keyof Functions[F]['Args'] & string)[] }
const expectedFunctionArgs = {
grant_platform_role: ['role', 'target_user_id'],
revoke_platform_role: ['reason', 'role', 'target_user_id'],
} as const satisfies FunctionArgs
type MissingArgs = {
[F in keyof Functions]: Exclude<keyof Functions[F]['Args'], (typeof expectedFunctionArgs)[F][number]>
}[keyof Functions]
const noMissingArg: MissingArgs extends never ? true : never = true
interface ColumnRow {
table_name: string
column_name: string
}
interface NameRow {
name: string
}
interface FunctionRow {
name: string
args: string[]
}
interface PolicyRow {
tablename: string
policyname: string
}
describe('database.types.ts matches the migrated schema', () => {
let db: PGlite
beforeAll(async () => {
db = await createMigratedDatabase()
})
afterAll(async () => {
await db?.close()
})
it('has the compile-time exhaustiveness witnesses', () => {
expect(noMissingColumn).toBe(true)
expect(noMissingArg).toBe(true)
})
it('lists exactly the public tables and their columns', async () => {
const { rows } = await db.query<ColumnRow>(
`select table_name, column_name
from information_schema.columns
where table_schema = 'public'
order by table_name, column_name`,
)
const actual: Record<string, string[]> = {}
for (const row of rows) (actual[row.table_name] ??= []).push(row.column_name)
const expected = Object.fromEntries(
Object.entries(expectedColumns).map(([table, cols]) => [table, [...cols].sort()]),
)
expect(actual).toEqual(expected)
})
it('lists the enum labels in order', async () => {
const { rows } = await db.query<NameRow>(
`select e.enumlabel as name
from pg_enum e join pg_type t on t.oid = e.enumtypid
join pg_namespace n on n.oid = t.typnamespace
where n.nspname = 'public' and t.typname = 'platform_role'
order by e.enumsortorder`,
)
expect(rows.map((r) => r.name)).toEqual([...Constants.public.Enums.platform_role])
})
it('lists exactly the public functions and their argument names', async () => {
const { rows } = await db.query<FunctionRow>(
`select p.proname as name, coalesce(p.proargnames, '{}') as args
from pg_proc p join pg_namespace n on n.oid = p.pronamespace
where n.nspname = 'public' and p.prokind = 'f'
and not exists (
select 1 from pg_depend d where d.objid = p.oid and d.deptype = 'e'
)
order by p.proname`,
)
const actual = Object.fromEntries(rows.map((r) => [r.name, [...r.args].sort()]))
const expected = Object.fromEntries(
Object.entries(expectedFunctionArgs).map(([fn, args]) => [fn, [...args].sort()]),
)
expect(actual).toEqual(expected)
})
it('keeps RLS enabled on every public table', async () => {
const { rows } = await db.query<NameRow>(
`select c.relname as name
from pg_class c join pg_namespace n on n.oid = c.relnamespace
where n.nspname = 'public' and c.relkind = 'r' and not c.relrowsecurity`,
)
expect(rows).toEqual([])
})
it('has no unconditional policy for API roles', async () => {
const { rows } = await db.query<PolicyRow>(
`select tablename, policyname
from pg_policies
where schemaname = 'public'
and (qual = 'true' or with_check = 'true')
and roles && array['authenticated', 'anon']::name[]`,
)
expect(rows).toEqual([])
})
})
@@ -0,0 +1,75 @@
-- Minimal stand-in for the Supabase base schema, applied to a bare PGlite
-- database before the project migrations. Mirrors what the hosted/local stack
-- provides: API roles, auth schema with users table + JWT claim helpers, and
-- the permissive default privileges on public (ALL to the API roles), so a
-- migration that forgets to revoke is caught by the tests.
-- Test-only file: never applied to a real Supabase database.
create role anon nologin noinherit;
create role authenticated nologin noinherit;
create role service_role nologin noinherit bypassrls;
create schema auth;
create schema extensions;
create table auth.users (
instance_id uuid,
id uuid primary key default gen_random_uuid(),
aud varchar(255),
role varchar(255),
email varchar(255),
encrypted_password varchar(255),
email_confirmed_at timestamptz,
raw_app_meta_data jsonb,
raw_user_meta_data jsonb,
created_at timestamptz default now(),
updated_at timestamptz default now()
);
create or replace function auth.uid()
returns uuid
language sql
stable
as $$
select nullif(
coalesce(
current_setting('request.jwt.claim.sub', true),
(nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub')
),
''
)::uuid
$$;
create or replace function auth.role()
returns text
language sql
stable
as $$
select nullif(
coalesce(
current_setting('request.jwt.claim.role', true),
(nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'role')
),
''
)::text
$$;
create or replace function auth.jwt()
returns jsonb
language sql
stable
as $$
select coalesce(
nullif(current_setting('request.jwt.claim', true), ''),
nullif(current_setting('request.jwt.claims', true), '')
)::jsonb
$$;
grant usage on schema auth to anon, authenticated, service_role;
grant execute on function auth.uid(), auth.role(), auth.jwt() to anon, authenticated, service_role;
grant usage on schema public to anon, authenticated, service_role;
grant usage on schema extensions to anon, authenticated, service_role;
alter default privileges in schema public grant all on tables to anon, authenticated, service_role;
alter default privileges in schema public grant all on functions to anon, authenticated, service_role;
alter default privileges in schema public grant all on sequences to anon, authenticated, service_role;
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM"],
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"skipLibCheck": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"isolatedModules": true,
"types": ["node", "vitest/globals"],
"noEmit": true
},
"include": ["src", "tests"],
"exclude": ["node_modules"]
}
+12
View File
@@ -0,0 +1,12 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
environment: 'node',
globals: true,
include: ['tests/**/*.test.ts'],
// PGlite boots a WASM Postgres per file: give it room on slow CI runners.
testTimeout: 60_000,
hookTimeout: 120_000,
},
})