/** * Tests for key resource classes — validates that each resource method builds * the correct HTTP path and returns the correct shaped data. All tests use a * mock `HttpTransport` (no network, no ScribaseClient construction). */ import { describe, it } from 'node:test'; import assert from 'node:assert/strict'; import type { HttpTransport, ApiResult, RequestOptions } from '../src/client.js'; import { EnvironmentsResource } from '../src/resources/environments.js'; import { ProjectsResource } from '../src/resources/projects.js'; import { AuthResource } from '../src/resources/auth.js'; import { StorageResource } from '../src/resources/storage.js'; import { FunctionsResource } from '../src/resources/functions.js'; import { UsageResource } from '../src/resources/usage.js'; import { MetricsResource } from '../src/resources/metrics.js'; import { AuditResource } from '../src/resources/audit.js'; import { DatabaseResource } from '../src/resources/database.js'; import type { Environment, Project, Operation, AuditEvent, } from '../src/types.gen.js'; import { NotFoundError } from '../src/errors.js'; // --------------------------------------------------------------------------- // Mock transport // --------------------------------------------------------------------------- interface CapturedRequest { options: RequestOptions; } function makeTransport(data: unknown, status = 200, idempotencyReplayed = false): { transport: HttpTransport; calls: CapturedRequest[]; } { const calls: CapturedRequest[] = []; const transport: HttpTransport = { async send(options: RequestOptions): Promise> { calls.push({ options }); return { data: data as T, status, idempotencyReplayed, headers: new Headers(), }; }, }; return { transport, calls }; } function makeFailing(status: number, code: string): HttpTransport { const problem = { type: 'about:blank', title: 'Error', status, code }; return { async send(_options: RequestOptions): Promise> { const { errorFromResponse } = await import('../src/errors.js'); throw errorFromResponse(status, problem); }, }; } // --------------------------------------------------------------------------- // EnvironmentsResource // --------------------------------------------------------------------------- describe('EnvironmentsResource', () => { const ref = { organizationId: 'acme', projectId: 'store', environmentId: 'production', }; const sampleEnv: Environment = { organization_id: 'acme', project_id: 'store', environment_id: 'production', kind: 'production', data_mode: 'snapshot', region: 'us-east', postgres_major: 17, phase: 'ready', desired_generation: 1, observed_generation: 1, retry_count: 0, last_activity_epoch_seconds: 0, finalizers: [], }; it('list calls GET /v1/environments with org query param', async () => { const { transport, calls } = makeTransport({ environments: [sampleEnv] }); const resource = new EnvironmentsResource(transport); const envs = await resource.list({ organizationId: 'acme' }); assert.equal(calls.length, 1); const call = calls[0]!; assert.equal(call.options.method, 'GET'); assert.equal(call.options.path, '/v1/environments'); assert.equal(call.options.query?.['organization_id'], 'acme'); assert.equal(envs.length, 1); assert.equal(envs[0]?.environment_id, 'production'); }); it('list narrows to a project when projectId is provided', async () => { const { transport, calls } = makeTransport({ environments: [] }); const resource = new EnvironmentsResource(transport); await resource.list({ organizationId: 'acme', projectId: 'store' }); const call = calls[0]!; assert.equal(call.options.query?.['project_id'], 'store'); }); it('get calls the correct environment path', async () => { const { transport, calls } = makeTransport(sampleEnv); const resource = new EnvironmentsResource(transport); const env = await resource.get(ref); const call = calls[0]!; assert.equal(call.options.method, 'GET'); assert.ok(call.options.path.includes('/organizations/acme/projects/store/environments/production')); assert.equal(env.environment_id, 'production'); }); it('delete calls DELETE and returns an AcceptedOperation', async () => { const op: Operation = { id: 'op-1', kind: 'delete_environment', environment: { organization_id: 'acme', project_id: 'store', environment_id: 'production' }, state: 'pending', attempt_count: 0, }; const { transport, calls } = makeTransport(op); const resource = new EnvironmentsResource(transport); const accepted = await resource.delete(ref, { idempotencyKey: 'idem-1' }); const call = calls[0]!; assert.equal(call.options.method, 'DELETE'); assert.equal(call.options.idempotencyKey, 'idem-1'); assert.equal(accepted.operation.id, 'op-1'); assert.equal(accepted.idempotencyReplayed, false); }); it('suspend calls POST …/suspend', async () => { const op: Operation = { id: 'op-2', kind: 'suspend_environment', environment: ref, state: 'pending', attempt_count: 0, }; const { transport, calls } = makeTransport(op); const resource = new EnvironmentsResource(transport); await resource.suspend(ref, { idempotencyKey: 'idem-2' }); const call = calls[0]!; assert.ok(call.options.path.endsWith('/suspend')); }); it('resume calls POST …/resume', async () => { const op: Operation = { id: 'op-3', kind: 'resume_environment', environment: ref, state: 'pending', attempt_count: 0, }; const { transport, calls } = makeTransport(op); const resource = new EnvironmentsResource(transport); await resource.resume(ref); const call = calls[0]!; assert.ok(call.options.path.endsWith('/resume')); }); it('propagates errors from the transport', async () => { const transport = makeFailing(404, 'not_found'); const resource = new EnvironmentsResource(transport); await assert.rejects(() => resource.get(ref), NotFoundError); }); it('apiKeys() GETs the environment client keys', async () => { const keys = { api_url: 'https://acme-store-production-1a2b3c4d.scribase.com', anon_key: 'eyJ.anon.sig', publishable_key: 'sb_publishable_abc', service_role_key: null, secret_key: null, jwt_secret_version: 1, jwt_secret_source: 'control_plane' as const, }; const { transport, calls } = makeTransport(keys); const resource = new EnvironmentsResource(transport); const result = await resource.apiKeys(ref); assert.equal(calls[0]!.options.method, 'GET'); assert.equal( calls[0]!.options.path, '/v1/organizations/acme/projects/store/environments/production/api-keys', ); assert.equal(result.publishable_key, 'sb_publishable_abc'); assert.equal(result.service_role_key, null); }); }); // --------------------------------------------------------------------------- // ProjectsResource // --------------------------------------------------------------------------- describe('ProjectsResource', () => { const sampleProject: Project = { organization_id: 'acme', project_id: 'store', region: 'us-east', postgres_major: 17, }; it('get calls GET on the correct project path', async () => { const { transport, calls } = makeTransport(sampleProject); const resource = new ProjectsResource(transport); const project = await resource.get('acme', 'store'); const call = calls[0]!; assert.equal(call.options.method, 'GET'); assert.ok(call.options.path.includes('/organizations/acme/projects/store')); assert.equal(project.project_id, 'store'); }); it('put calls PUT with the request body', async () => { const { transport, calls } = makeTransport(sampleProject); const resource = new ProjectsResource(transport); await resource.put('acme', 'store', { region: 'us-east', postgres_major: 17 }); const call = calls[0]!; assert.equal(call.options.method, 'PUT'); assert.deepEqual(call.options.body, { region: 'us-east', postgres_major: 17 }); }); }); // --------------------------------------------------------------------------- // AuthResource // --------------------------------------------------------------------------- describe('AuthResource', () => { const ref = { organizationId: 'acme', projectId: 'store', environmentId: 'prod' }; it('updateConfig PATCHes auth/config and applyConfig POSTs with an idempotency key', async () => { const config = { settings: { external_anonymous_users_enabled: true }, secrets: { smtp_pass: false, external: {} }, supported_providers: ['apple', 'google'], apply: { version: 2, applied_version: 2, status: 'applied', pending: false, error: null, operation_id: null }, live: null, notes: [], }; const { transport, calls } = makeTransport(config); const resource = new AuthResource(transport); const saved = await resource.updateConfig(ref, { external_anonymous_users_enabled: true, external: { apple: { enabled: true, client_id: 'com.example.app' } }, }); assert.equal(calls[0]!.options.method, 'PATCH'); assert.ok(calls[0]!.options.path.endsWith('/environments/prod/auth/config')); assert.equal(saved.apply.pending, false); await resource.applyConfig(ref); assert.equal(calls[1]!.options.method, 'POST'); assert.ok(calls[1]!.options.path.endsWith('/auth/config/apply')); assert.ok((calls[1]!.options.idempotencyKey ?? '').length > 0); }); it('listUsers calls the correct auth/users path', async () => { const result = { data: { users: [{ id: 'u-1' }] }, notes: [] }; const { transport, calls } = makeTransport(result); const resource = new AuthResource(transport); const users = await resource.listUsers(ref); const call = calls[0]!; assert.ok(call.options.path.endsWith('/auth/users')); assert.equal(users.data.users.length, 1); }); it('listProviders calls the correct auth/providers path', async () => { const result = { data: { external: { google: true } }, notes: [] }; const { transport, calls } = makeTransport(result); const resource = new AuthResource(transport); await resource.listProviders(ref); const call = calls[0]!; assert.ok(call.options.path.endsWith('/auth/providers')); }); }); // --------------------------------------------------------------------------- // StorageResource // --------------------------------------------------------------------------- describe('StorageResource', () => { const ref = { organizationId: 'acme', projectId: 'store', environmentId: 'prod' }; it('listBuckets calls the correct storage/buckets path', async () => { const result = { buckets: [{ id: 'b-1', name: 'assets' }] }; const { transport, calls } = makeTransport(result); const resource = new StorageResource(transport); const buckets = await resource.listBuckets(ref); const call = calls[0]!; assert.ok(call.options.path.endsWith('/storage/buckets')); assert.equal(buckets.buckets.length, 1); }); it('listObjects calls the correct buckets/{bucket}/objects path', async () => { const result = { bucket: 'assets', objects: [{ name: 'logo.png' }] }; const { transport, calls } = makeTransport(result); const resource = new StorageResource(transport); const objects = await resource.listObjects(ref, 'assets'); const call = calls[0]!; assert.ok(call.options.path.endsWith('/storage/buckets/assets/objects')); assert.equal(objects.objects.length, 1); }); it('listObjects passes prefix and limit as query params', async () => { const result = { bucket: 'assets', objects: [] }; const { transport, calls } = makeTransport(result); const resource = new StorageResource(transport); await resource.listObjects(ref, 'assets', { prefix: 'images/', limit: 10 }); const call = calls[0]!; assert.equal(call.options.query?.['prefix'], 'images/'); assert.equal(call.options.query?.['limit'], 10); }); }); // --------------------------------------------------------------------------- // FunctionsResource // --------------------------------------------------------------------------- describe('FunctionsResource', () => { const ref = { organizationId: 'acme', projectId: 'store', environmentId: 'prod' }; it('list calls the correct functions path', async () => { const result = { environment: ref, functions: [{ slug: 'hello-world' }], notes: null, }; const { transport, calls } = makeTransport(result); const resource = new FunctionsResource(transport); const list = await resource.list(ref); const call = calls[0]!; assert.ok(call.options.path.endsWith('/functions')); assert.equal(list.functions.length, 1); assert.equal(list.notes, null); }); it('deploy sends multi-file bodies with verify_jwt and refuses an empty one', async () => { const { transport, calls } = makeTransport({ function: 'hello', result: { ok: true } }); const resource = new FunctionsResource(transport); await resource.deploy(ref, { name: 'hello', files: { 'hello/index.ts': 'Deno.serve(() => new Response("hi"))', '_shared/a.ts': 'export {}' }, entrypoint: 'hello/index.ts', verify_jwt: false, }); const body = calls[0]!.options.body as Record; assert.equal(calls[0]!.options.method, 'POST'); assert.equal(body['verify_jwt'], false); assert.ok((body['files'] as Record)['_shared/a.ts'] !== undefined); await assert.rejects(() => resource.deploy(ref, { name: 'hello' }), RangeError); }); }); // --------------------------------------------------------------------------- // UsageResource // --------------------------------------------------------------------------- describe('UsageResource', () => { const ref = { organizationId: 'acme', projectId: 'store', environmentId: 'prod' }; const envelope = { environment: { organization_id: 'acme', project_id: 'store', environment_id: 'prod' }, plan: 'base', flat_price_usd: 25, period_start_epoch_seconds: 0, period_end_epoch_seconds: 86400, lines: [ { metric: 'database_bytes', label: 'Database', used: 5, included: 8, cap: 8, unit: 'GB' }, { metric: 'storage_bytes', label: 'Storage', used: 10, included: 100, cap: 100, unit: 'GB' }, ], packs: [], }; it('get calls the env-scoped usage path', async () => { const { transport, calls } = makeTransport(envelope); const resource = new UsageResource(transport); const usage = await resource.get(ref); const call = calls[0]!; assert.ok(call.options.path.endsWith('/projects/store/environments/prod/usage')); assert.equal(usage.plan, 'base'); }); it('capsNearingLimit filters by threshold', async () => { const { transport } = makeTransport(envelope); const resource = new UsageResource(transport); const nearing = await resource.capsNearingLimit(ref, 0.8); assert.equal(nearing.length, 0); }); it('capsNearingLimit finds lines above threshold', async () => { const nearFull = { ...envelope, lines: [{ metric: 'database_bytes', label: 'Database', used: 7, included: 8, cap: 8, unit: 'GB' }], }; const { transport } = makeTransport(nearFull); const resource = new UsageResource(transport); const nearing = await resource.capsNearingLimit(ref, 0.8); assert.equal(nearing.length, 1); assert.equal(nearing[0]!.metric, 'database_bytes'); }); }); // --------------------------------------------------------------------------- // MetricsResource // --------------------------------------------------------------------------- describe('MetricsResource', () => { const ref = { organizationId: 'acme', projectId: 'store', environmentId: 'prod' }; it('get calls the correct metrics path', async () => { const report = { environment: ref, source: 'postgres', range: { start_epoch_seconds: 0, end_epoch_seconds: 300, step_seconds: 60 }, series: [ { metric: 'requests', unit: 'count', points: [{ epoch_seconds: 0, value: 42 }] }, ], notes: '', }; const { transport, calls } = makeTransport(report); const resource = new MetricsResource(transport); const result = await resource.get(ref); const call = calls[0]!; assert.ok(call.options.path.endsWith('/metrics')); assert.equal(result.source, 'postgres'); assert.equal(result.series.length, 1); }); }); // --------------------------------------------------------------------------- // AuditResource // --------------------------------------------------------------------------- describe('AuditResource', () => { const sampleEvent: AuditEvent = { sequence: 1, actor_subject: 'user@example.com', action: 'create_environment', organization_id: 'acme', detail: 'environment store/production created', }; it('list calls the correct audit-events path', async () => { const { transport, calls } = makeTransport({ items: [sampleEvent] }); const resource = new AuditResource(transport); const events = await resource.list('acme'); const call = calls[0]!; assert.ok(call.options.path.includes('/audit-events')); assert.equal(events.length, 1); assert.equal(events[0]!.action, 'create_environment'); }); it('list passes after and limit query params', async () => { const { transport, calls } = makeTransport({ items: [] }); const resource = new AuditResource(transport); await resource.list('acme', { after: 5, limit: 20 }); const call = calls[0]!; assert.equal(call.options.query?.['after'], 5); assert.equal(call.options.query?.['limit'], 20); }); }); // --------------------------------------------------------------------------- // DatabaseResource.generateTypes // --------------------------------------------------------------------------- describe('DatabaseResource.generateTypes', () => { const ref = { organizationId: 'acme', projectId: 'app', environmentId: 'production' }; it('calls the environment types path with the schema list', async () => { const { transport, calls } = makeTransport({ types: 'export type Database = {}', schemas: ['public', 'app'] }); const resource = new DatabaseResource(transport); const result = await resource.generateTypes(ref, { schemas: ['public', 'app'] }); const call = calls[0]!; assert.equal(call.options.method, 'GET'); assert.ok(call.options.path.endsWith('/environments/production/types')); assert.equal(call.options.query?.['schema'], 'public,app'); assert.equal(result.types, 'export type Database = {}'); }); it('defaults to the public schema and rejects empty or comma names', async () => { const { transport, calls } = makeTransport({ types: '', schemas: ['public'] }); const resource = new DatabaseResource(transport); await resource.generateTypes(ref); assert.equal(calls[0]!.options.query?.['schema'], 'public'); await assert.rejects(resource.generateTypes(ref, { schemas: [] }), RangeError); await assert.rejects(resource.generateTypes(ref, { schemas: ['a,b'] }), RangeError); }); }); // --------------------------------------------------------------------------- // ProjectsResource quotas // --------------------------------------------------------------------------- describe('ProjectsResource quotas', () => { const quotas = { organization_id: 'agency', project_id: 'customer-42', overrides: [ { metric: 'storage_gb', label: 'File storage', unit: 'GB', cap: 5, updated_by: 'u', updated_at_epoch_seconds: 1 }, ], metrics: [], threshold: 0.8, }; it('getQuotas reads the project quotas path', async () => { const { transport, calls } = makeTransport(quotas); const resource = new ProjectsResource(transport); const result = await resource.getQuotas('agency', 'customer-42'); assert.equal(calls[0]!.options.method, 'GET'); assert.equal(calls[0]!.options.path, '/v1/organizations/agency/projects/customer-42/quotas'); assert.equal(result.overrides[0]!.cap, 5); }); it('setQuotas PUTs the overrides and validates caps', async () => { const { transport, calls } = makeTransport(quotas); const resource = new ProjectsResource(transport); await resource.setQuotas('agency', 'customer-42', { storage_gb: 5, rows: null }); assert.equal(calls[0]!.options.method, 'PUT'); assert.deepEqual(calls[0]!.options.body, { overrides: { storage_gb: 5, rows: null } }); await assert.rejects(resource.setQuotas('agency', 'customer-42', {}), RangeError); await assert.rejects(resource.setQuotas('agency', 'customer-42', { rows: -1 }), RangeError); }); });