scribase-cli/tests/cli.test.ts

621 lines
31 KiB
TypeScript
Raw Permalink Normal View History

/**
* Tests for `npx scribase init`: framework detection, env-file merging, the
* proof of work, and the whole flow against an in-memory filesystem and a
* fake control plane (no network, no child processes).
*/
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { clientSource, conventionsFor, detectFramework, installCommand, packageManager } from '../src/cli/framework.js';
import { ensureDirIgnored, ensureIgnored, mergeEnv, readEnvValue } from '../src/cli/envfile.js';
import { leadingZeroBits, solveChallenge } from '../src/cli/pow.js';
import { DEFAULT_REGION, InitError, billingNextStep, consoleUrlFor, parseInitArgs, projectSlug, runInit } from '../src/cli/init.js';
import type { InitIo } from '../src/cli/init.js';
const ROOT = '/work/app';
function facts(pkg: Record<string, unknown> | null, files: string[] = []) {
return {
packageJson: pkg as never,
exists: (path: string) => files.includes(path),
};
}
describe('framework detection', () => {
it('detects Next.js, Expo, Vite and falls back to Node', () => {
assert.equal(detectFramework(facts({ dependencies: { next: '15' } })), 'next');
assert.equal(detectFramework(facts(null, ['next.config.mjs'])), 'next');
assert.equal(detectFramework(facts({ dependencies: { expo: '52', 'react-native': '0.76' } })), 'expo');
assert.equal(detectFramework(facts({ devDependencies: { vite: '6' } })), 'vite');
assert.equal(detectFramework(facts({ dependencies: { express: '5' } })), 'node');
assert.equal(detectFramework(facts(null)), 'node');
});
it('detects SvelteKit before plain Vite, even though every SvelteKit app is also a Vite app', () => {
// A real `npm create svelte@latest` package.json: @sveltejs/kit plus vite,
// both as devDependencies, and a vite.config.ts on disk.
assert.equal(
detectFramework(facts({ devDependencies: { '@sveltejs/kit': '2', vite: '6' } }, ['vite.config.ts', 'svelte.config.js'])),
'sveltekit',
);
// svelte.config.js alone (no package.json dependency read, e.g. a
// monorepo workspace root) is still enough.
assert.equal(detectFramework(facts(null, ['svelte.config.js'])), 'sveltekit');
// A plain Vite app with neither signal still falls through to 'vite'.
assert.equal(detectFramework(facts({ devDependencies: { vite: '6' } }, ['vite.config.ts'])), 'vite');
});
it('uses each framework’s public variable prefix and never ships the service key to a bundle', () => {
const next = conventionsFor('next', facts({}, ['tsconfig.json', 'src']));
assert.equal(next.envFile, '.env.local');
assert.equal(next.urlVar, 'NEXT_PUBLIC_SUPABASE_URL');
assert.equal(next.serviceRoleVar, 'SUPABASE_SERVICE_ROLE_KEY');
assert.equal(next.clientFile, 'src/lib/supabase.ts');
const expo = conventionsFor('expo', facts({}));
assert.equal(expo.urlVar, 'EXPO_PUBLIC_SUPABASE_URL');
assert.equal(expo.anonKeyVar, 'EXPO_PUBLIC_SUPABASE_ANON_KEY');
assert.equal(expo.serviceRoleVar, null);
const vite = conventionsFor('vite', facts({}, ['tsconfig.json']));
assert.equal(vite.urlVar, 'VITE_SUPABASE_URL');
assert.equal(vite.serviceRoleVar, null);
assert.match(clientSource(vite), /import\.meta\.env\.VITE_SUPABASE_URL!/);
const node = conventionsFor('node', facts({}));
assert.equal(node.envFile, '.env');
assert.equal(node.clientFile, 'supabase.mjs');
assert.match(clientSource(node), /process\.env\.SUPABASE_ANON_KEY\)/);
// Unlike Next.js/Vite/Expo, plain Node never auto-loads its env file:
// without this, `createClient` sees undefined env vars and throws
// "supabaseUrl is required." the moment a fresh `scribase init` user
// imports the generated client, before any query ever runs.
assert.match(clientSource(node), /process\.loadEnvFile\(\)/);
assert.doesNotMatch(clientSource(next), /process\.loadEnvFile\(\)/);
assert.doesNotMatch(clientSource(vite), /process\.loadEnvFile\(\)/);
assert.doesNotMatch(clientSource(expo), /process\.loadEnvFile\(\)/);
// SvelteKit: real $env/static/public bindings (not VITE_-prefixed
// import.meta.env like plain Vite), and a real service-role var since
// SvelteKit has a server runtime, unlike Vite/Expo's pure client bundles.
const sveltekit = conventionsFor('sveltekit', facts({}, ['tsconfig.json']));
assert.equal(sveltekit.envFile, '.env');
assert.equal(sveltekit.urlVar, 'PUBLIC_SUPABASE_URL');
assert.equal(sveltekit.anonKeyVar, 'PUBLIC_SUPABASE_ANON_KEY');
assert.equal(sveltekit.serviceRoleVar, 'SUPABASE_SERVICE_ROLE_KEY');
assert.equal(sveltekit.clientFile, 'src/lib/supabase.ts');
const sveltekitSource = clientSource(sveltekit);
assert.match(sveltekitSource, /import \{ PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY \} from '\$env\/static\/public';/);
assert.match(sveltekitSource, /createClient\(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY\);/);
// $env/static/public is already typed `string` (SvelteKit fails the
// build itself if a value is missing), so a `!` non-null assertion here
// would just be noise unlike every other framework's env read.
assert.doesNotMatch(sveltekitSource, /PUBLIC_SUPABASE_URL!/);
assert.doesNotMatch(sveltekitSource, /process\.loadEnvFile\(\)/);
});
it('picks the package manager from the lockfile', () => {
assert.equal(packageManager((p) => p === 'pnpm-lock.yaml'), 'pnpm');
assert.equal(packageManager((p) => p === 'yarn.lock'), 'yarn');
assert.equal(packageManager(() => false), 'npm');
assert.deepEqual(installCommand('npm'), ['npm', ['install', '@supabase/supabase-js', '--no-audit', '--no-fund']]);
assert.deepEqual(installCommand('pnpm'), ['pnpm', ['add', '@supabase/supabase-js']]);
});
});
describe('env files', () => {
it('replaces keys in place, keeps everything else, appends new keys', () => {
const before = '# mine\nOTHER=1\nNEXT_PUBLIC_SUPABASE_URL=https://old\n';
const after = mergeEnv(before, {
NEXT_PUBLIC_SUPABASE_URL: 'https://new.example.com',
NEXT_PUBLIC_SUPABASE_ANON_KEY: 'eyJ.x.y',
});
assert.equal(
after,
'# mine\nOTHER=1\nNEXT_PUBLIC_SUPABASE_URL=https://new.example.com\n\n# Scribase (written by `npx scribase init`)\nNEXT_PUBLIC_SUPABASE_ANON_KEY=eyJ.x.y\n',
);
assert.equal(readEnvValue(after, 'NEXT_PUBLIC_SUPABASE_URL'), 'https://new.example.com');
assert.equal(readEnvValue(mergeEnv('', { A: 'has space' }), 'A'), 'has space');
});
it('adds the env file to .gitignore unless a pattern already covers it', () => {
assert.equal(ensureIgnored('node_modules\n', '.env'), 'node_modules\n.env\n');
assert.equal(ensureIgnored('.env*.local\n', '.env.local'), null);
assert.equal(ensureIgnored('.env*', '.env'), null);
assert.equal(ensureIgnored('', '.env.local'), '.env.local\n');
});
it('adds .scribase/ (the claim link) to .gitignore unless already ignored', () => {
assert.equal(ensureDirIgnored('.env\n', '.scribase'), '.env\n.scribase/\n');
assert.equal(ensureDirIgnored('.env', '.scribase'), '.env\n.scribase/\n');
assert.equal(ensureDirIgnored('/.scribase\n', '.scribase'), null);
assert.equal(ensureDirIgnored('.scribase/\n', '.scribase/'), null);
});
});
describe('proof of work', () => {
it('finds a nonce with the requested leading zero bits', () => {
const nonce = solveChallenge('123.abc.def', 10);
const digest = createHash('sha256').update(`123.abc.def:${nonce}`).digest();
assert.ok(leadingZeroBits(digest) >= 10);
assert.match(nonce, /^[a-z0-9]+$/);
assert.equal(leadingZeroBits(new Uint8Array([0, 0x0f])), 12);
});
});
describe('argument parsing', () => {
it('parses flags and rejects unknown ones', () => {
const options = parseInitArgs(['--temp', '--yes', '--json', '--name', 'My App', '--wait=10', '--no-install']);
assert.equal(options.temp, true);
assert.equal(options.yes, true);
assert.equal(options.json, true);
assert.equal(options.name, 'My App');
assert.equal(options.waitSeconds, 10);
assert.equal(options.install, false);
assert.throws(() => parseInitArgs(['--bogus']), InitError);
assert.throws(() => parseInitArgs(['--name']), InitError);
assert.equal(projectSlug('My Cool App!'), 'my-cool-app');
assert.equal(projectSlug('x'), 'my-app');
});
});
/* ------------------------------ full flow ------------------------------- */
interface Call {
method: string;
path: string;
auth: string | null;
body: unknown;
}
function memoryIo(
files: Record<string, string>,
handler: (call: Call) => { status: number; body: unknown },
env: Record<string, string> = {},
) {
const calls: Call[] = [];
const runs: string[] = [];
const io: InitIo = {
cwd: ROOT,
env,
fetch: (async (url: string | URL | Request, init?: RequestInit) => {
const target = new URL(String(url));
const headers = new Headers(init?.headers);
const call: Call = {
method: init?.method ?? 'GET',
path: target.pathname,
auth: headers.get('authorization'),
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
};
calls.push(call);
const answer = handler(call);
return new Response(JSON.stringify(answer.body), { status: answer.status });
}) as typeof fetch,
readFile: (path) => files[path] ?? null,
writeFile: (path, contents) => {
files[path] = contents;
},
exists: (path) => path in files || Object.keys(files).some((file) => file.startsWith(`${path}/`)),
run: (command, args) => {
runs.push(`${command} ${args.join(' ')}`);
return { ok: true, output: '' };
},
sleep: async () => {},
log: () => {},
credentials: () => ({}),
};
return { io, calls, runs, files };
}
const KEYS = {
api_url: 'https://tmp-abc-my-app-production.scribase.app',
anon_key: 'eyJanon',
service_role_key: 'eyJservice',
};
describe('init --temp', () => {
it('creates a temporary project, writes Next.js env vars, the client and installs supabase-js', async () => {
let polls = 0;
const { io, calls, runs, files } = memoryIo(
{ [`${ROOT}/package.json`]: JSON.stringify({ name: 'shop', dependencies: { next: '15' } }), [`${ROOT}/tsconfig.json`]: '{}' },
(call) => {
if (call.path === '/v1/temporary-projects/challenge') {
return { status: 200, body: { challenge: '9999999999.aa.bb', bits: 4 } };
}
if (call.path === '/v1/temporary-projects' && call.method === 'POST') {
return {
status: 201,
body: {
id: 'tmp_0123456789abcdef01234567',
organization_id: 'tmp-0123456789abcdef01234567',
project_id: 'shop',
environment_id: 'production',
agent_token: 'scb_agt_secret',
claim_url: 'https://console.scribase.com/claim/tmp_0123456789abcdef01234567#scb_claim_x',
expires_at: 1_900_000_000,
},
};
}
if (call.path === '/v1/temporary-projects/tmp_0123456789abcdef01234567') {
polls += 1;
return polls < 2
? { status: 200, body: { status: 'provisioning', keys: null } }
: { status: 200, body: { status: 'ready', keys: KEYS } };
}
return { status: 404, body: { code: 'not_found' } };
},
);
const result = await runInit(parseInitArgs(['--temp', '--yes', '--json', '--name', 'shop']), io);
assert.equal(result.framework, 'next');
assert.equal(result.temporary, true);
assert.equal(result.api_url, KEYS.api_url);
assert.equal(result.claim_url, 'https://console.scribase.com/claim/tmp_0123456789abcdef01234567#scb_claim_x');
assert.equal(result.client_file, 'lib/supabase.ts');
assert.equal(result.installed, true);
assert.deepEqual(runs, ['npm install @supabase/supabase-js --no-audit --no-fund']);
// The first next step works on an empty database: it creates the table
// the second step queries. No step reads a table nobody created.
assert.match(result.next_steps[0] ?? '', /^create your first table .*npx scribase sql "create table notes /);
assert.match(result.next_steps[1] ?? '', /supabase\.from\('notes'\)\.select\(\)/);
assert.ok(result.next_steps.every((step) => !/todos/.test(step)), 'no step queries a table that does not exist');
const create = calls.find((call) => call.path === '/v1/temporary-projects');
const body = create?.body as { challenge: string; nonce: string; name: string };
assert.equal(body.name, 'shop');
const digest = createHash('sha256').update(`${body.challenge}:${body.nonce}`).digest();
assert.ok(leadingZeroBits(digest) >= 4, 'the nonce solves the challenge');
assert.equal(create?.auth, null, 'creation is anonymous');
assert.ok(calls.filter((call) => call.path.startsWith('/v1/temporary-projects/tmp_')).every((call) => call.auth === 'Bearer scb_agt_secret'));
const env = files[`${ROOT}/.env.local`] ?? '';
assert.equal(readEnvValue(env, 'NEXT_PUBLIC_SUPABASE_URL'), KEYS.api_url);
assert.equal(readEnvValue(env, 'NEXT_PUBLIC_SUPABASE_ANON_KEY'), KEYS.anon_key);
assert.equal(readEnvValue(env, 'SUPABASE_SERVICE_ROLE_KEY'), KEYS.service_role_key);
assert.equal(readEnvValue(env, 'SCRIBASE_ACCESS_TOKEN'), 'scb_agt_secret');
assert.match(files[`${ROOT}/.gitignore`] ?? '', /\.env\.local/);
assert.match(files[`${ROOT}/.gitignore`] ?? '', /^\.scribase\/$/m, 'the claim link is never committed');
assert.match(files[`${ROOT}/lib/supabase.ts`] ?? '', /createClient\(process\.env\.NEXT_PUBLIC_SUPABASE_URL!/);
const state = JSON.parse(files[`${ROOT}/.scribase/project.json`] ?? '{}') as Record<string, unknown>;
assert.equal(state.temporary, true);
assert.equal(state.agent_token, undefined, 'no secret in the state file');
});
it('detects a SvelteKit project and writes $env/static/public-style env vars plus a real service-role key', async () => {
let polls = 0;
const { io, files } = memoryIo(
{
[`${ROOT}/package.json`]: JSON.stringify({ name: 'shop', devDependencies: { '@sveltejs/kit': '2', vite: '6' } }),
[`${ROOT}/svelte.config.js`]: 'export default {};\n',
[`${ROOT}/tsconfig.json`]: '{}',
},
(call) => {
if (call.path === '/v1/temporary-projects/challenge') {
return { status: 200, body: { challenge: '9999999999.aa.bb', bits: 4 } };
}
if (call.path === '/v1/temporary-projects' && call.method === 'POST') {
return {
status: 201,
body: {
id: 'tmp_0123456789abcdef01234567',
organization_id: 'tmp-0123456789abcdef01234567',
project_id: 'shop',
environment_id: 'production',
agent_token: 'scb_agt_secret',
claim_url: 'https://console.scribase.com/claim/tmp_0123456789abcdef01234567#scb_claim_x',
expires_at: 1_900_000_000,
},
};
}
if (call.path === '/v1/temporary-projects/tmp_0123456789abcdef01234567') {
polls += 1;
return polls < 2 ? { status: 200, body: { status: 'provisioning', keys: null } } : { status: 200, body: { status: 'ready', keys: KEYS } };
}
return { status: 404, body: { code: 'not_found' } };
},
);
const result = await runInit(parseInitArgs(['--temp', '--yes', '--json', '--name', 'shop']), io);
assert.equal(result.framework, 'sveltekit');
assert.equal(result.env_file, '.env');
assert.equal(result.client_file, 'src/lib/supabase.ts');
const env = files[`${ROOT}/.env`] ?? '';
assert.equal(readEnvValue(env, 'PUBLIC_SUPABASE_URL'), KEYS.api_url);
assert.equal(readEnvValue(env, 'PUBLIC_SUPABASE_ANON_KEY'), KEYS.anon_key);
// Unlike Vite/Expo, SvelteKit has a real server, so the temporary
// project's service-role key is written (never to a PUBLIC_ variable).
assert.equal(readEnvValue(env, 'SUPABASE_SERVICE_ROLE_KEY'), KEYS.service_role_key);
assert.match(files[`${ROOT}/.gitignore`] ?? '', /^\.env$/m);
const client = files[`${ROOT}/src/lib/supabase.ts`] ?? '';
assert.match(client, /import \{ PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY \} from '\$env\/static\/public';/);
assert.match(client, /createClient\(PUBLIC_SUPABASE_URL, PUBLIC_SUPABASE_ANON_KEY\);/);
});
it('prints the project URL and the claim link before the client install starts (SG-D8)', async () => {
const timeline: string[] = [];
const { io } = memoryIo(
{ [`${ROOT}/package.json`]: JSON.stringify({ name: 'shop', dependencies: { next: '15' } }) },
(call) => {
if (call.path === '/v1/temporary-projects/challenge') return { status: 200, body: { challenge: '9999999999.aa.bb', bits: 4 } };
if (call.path === '/v1/temporary-projects' && call.method === 'POST') {
return {
status: 201,
body: {
id: 'tmp_0123456789abcdef01234567',
organization_id: 'tmp-0123456789abcdef01234567',
project_id: 'shop',
environment_id: 'production',
agent_token: 'scb_agt_secret',
claim_url: 'https://console.scribase.com/claim/tmp_0123456789abcdef01234567#scb_claim_x',
expires_at: 1_900_000_000,
},
};
}
if (call.path === '/v1/temporary-projects/tmp_0123456789abcdef01234567') return { status: 200, body: { status: 'ready', keys: KEYS } };
return { status: 404, body: {} };
},
);
const logged: InitIo = {
...io,
log: (line: string) => timeline.push(`log ${line}`),
run: (command, args, cwd) => {
timeline.push(`run ${command}`);
return io.run(command, args, cwd);
},
};
await runInit(parseInitArgs(['--temp', '--yes', '--name', 'shop']), logged);
const urlAt = timeline.findIndex((entry) => entry.startsWith('log ') && entry.includes(KEYS.api_url));
const claimAt = timeline.findIndex((entry) => entry.startsWith('log ') && entry.includes('/claim/tmp_0123456789abcdef01234567'));
const installAt = timeline.findIndex((entry) => entry.startsWith('run '));
assert.ok(urlAt >= 0, `the URL is printed: ${timeline.join(' | ')}`);
assert.ok(claimAt >= 0, `the claim link is printed: ${timeline.join(' | ')}`);
assert.ok(installAt > urlAt && installAt > claimAt, `both come before the install: ${timeline.join(' | ')}`);
assert.ok(!timeline.some((entry) => entry.includes('scb_agt_secret')), 'the agent token is never printed');
});
it('sends the signed-in token with --temp so limits count per account (SX-D5)', async () => {
const { io, calls } = memoryIo({}, (call) => {
if (call.path === '/v1/temporary-projects/challenge') return { status: 200, body: { challenge: '9999999999.aa.bb', bits: 1 } };
return { status: 503, body: { code: 'temporary_projects_disabled' } };
}, { SCRIBASE_ACCESS_TOKEN: 'scb_pat_person' });
await assert.rejects(runInit(parseInitArgs(['--temp', '--yes']), io));
const create = calls.find((call) => call.path === '/v1/temporary-projects');
assert.equal(create?.auth, 'Bearer scb_pat_person');
});
it('asks for a region id that names no hosting provider', async () => {
const { io, calls } = memoryIo({}, () => ({ status: 503, body: { code: 'temporary_projects_disabled' } }));
await assert.rejects(runInit(parseInitArgs(['--temp', '--yes']), io));
const text = JSON.stringify(calls);
assert.ok(!/oci|oracle|hetzner|contabo|aws|gcp|azure/i.test(text), text);
assert.equal(DEFAULT_REGION, 'eu-frankfurt');
});
it('reuses the directory’s temporary project on a second run', async () => {
const files: Record<string, string> = {
[`${ROOT}/package.json`]: JSON.stringify({ dependencies: { vite: '6', '@supabase/supabase-js': '2' } }),
[`${ROOT}/.env.local`]: 'SCRIBASE_ACCESS_TOKEN=scb_agt_kept\n',
[`${ROOT}/.scribase/project.json`]: JSON.stringify({
organization_id: 'tmp-1',
project_id: 'shop',
environment_id: 'production',
api_url: 'https://api.scribase.com',
temporary: true,
claim_url: 'https://console.scribase.com/claim/x#y',
}),
};
const { io, calls, runs } = memoryIo(files, (call) => {
if (call.path.endsWith('/environments/production')) return { status: 200, body: { phase: 'ready' } };
if (call.path.endsWith('/api-keys')) return { status: 200, body: KEYS };
return { status: 500, body: {} };
});
const result = await runInit(parseInitArgs(['--temp', '--json']), io);
assert.equal(result.reused, true);
assert.equal(result.framework, 'vite');
assert.ok(calls.every((call) => call.auth === 'Bearer scb_agt_kept'));
assert.ok(!calls.some((call) => call.path === '/v1/temporary-projects'), 'no new project');
assert.deepEqual(runs, [], 'supabase-js already installed');
assert.equal(readEnvValue(files[`${ROOT}/.env.local`] ?? '', 'VITE_SUPABASE_ANON_KEY'), KEYS.anon_key);
assert.equal(readEnvValue(files[`${ROOT}/.env.local`] ?? '', 'SUPABASE_SERVICE_ROLE_KEY'), undefined);
});
it('reports a disabled deployment as a coded error with a next step', async () => {
const { io } = memoryIo({}, () => ({
status: 503,
body: { code: 'temporary_projects_disabled', detail: 'temporary projects are not enabled' },
}));
await assert.rejects(runInit(parseInitArgs(['--temp', '--yes']), io), (error: unknown) => {
assert.ok(error instanceof InitError);
assert.equal(error.code, 'temporary_projects_disabled');
assert.ok(error.next);
return true;
});
});
});
describe('init with an account', () => {
it('creates the project and production environment, then writes Expo variables', async () => {
let envReads = 0;
const { io, calls, files } = memoryIo(
{ [`${ROOT}/package.json`]: JSON.stringify({ dependencies: { expo: '52', '@supabase/supabase-js': '2' } }) },
(call) => {
if (call.path === '/v1/organizations') return { status: 200, body: { items: [{ organization_id: 'acme' }] } };
if (call.path === '/v1/organizations/acme/projects/mobile' && call.method === 'PUT') return { status: 200, body: {} };
if (call.path === '/v1/environments') return { status: 202, body: { id: 'op-1' } };
if (call.path.endsWith('/environments/production')) {
envReads += 1;
return { status: 200, body: { phase: envReads > 1 ? 'ready' : 'provisioning' } };
}
if (call.path.endsWith('/api-keys')) return { status: 200, body: KEYS };
return { status: 404, body: {} };
},
{ SCRIBASE_ACCESS_TOKEN: 'scb_pat_user', SCRIBASE_API_URL: 'https://api.example.com/' },
);
const result = await runInit(parseInitArgs(['--yes', '--name', 'mobile']), io);
assert.equal(result.framework, 'expo');
assert.equal(result.temporary, false);
assert.equal(result.organization_id, 'acme');
const env = files[`${ROOT}/.env`] ?? '';
assert.equal(readEnvValue(env, 'EXPO_PUBLIC_SUPABASE_URL'), KEYS.api_url);
assert.equal(readEnvValue(env, 'SUPABASE_SERVICE_ROLE_KEY'), undefined, 'never in an app bundle');
assert.equal(readEnvValue(env, 'SCRIBASE_API_URL'), 'https://api.example.com');
const createEnv = calls.find((call) => call.path === '/v1/environments');
assert.deepEqual(createEnv?.body, {
organization_id: 'acme',
project_id: 'mobile',
environment_id: 'production',
kind: 'production',
data_mode: 'schema_only',
region: 'eu-frankfurt',
postgres_major: 17,
});
assert.ok(calls.every((call) => call.auth === 'Bearer scb_pat_user'));
});
it('turns a card requirement into a clear next step', async () => {
const { io } = memoryIo({}, (call) =>
call.path === '/v1/organizations'
? { status: 200, body: { items: [{ organization_id: 'acme' }] } }
: { status: 402, body: { code: 'card_required', detail: 'add a card to start' } },
{ SCRIBASE_ACCESS_TOKEN: 'scb_pat_user' },
);
await assert.rejects(runInit(parseInitArgs(['--yes']), io), (error: unknown) => {
assert.ok(error instanceof InitError);
assert.equal(error.code, 'card_required');
assert.match(error.next ?? '', /card/);
assert.match(error.next ?? '', /https:\/\/console\.scribase\.com\/start/);
return true;
});
});
it('asks the person to approve a billable project and sends the amount they approved (SB4)', async () => {
const puts: unknown[] = [];
const { io } = memoryIo({}, (call) => {
if (call.path === '/v1/organizations') return { status: 200, body: { items: [{ organization_id: 'acme' }] } };
if (call.method === 'PUT') {
puts.push(call.body);
return {
status: 402,
body: {
code: 'confirm_billable',
detail: "creating this project adds $25 to this month's bill (monthly_delta_cents 2500).",
},
};
}
return { status: 404, body: {} };
}, { SCRIBASE_ACCESS_TOKEN: 'scb_agt_x' });
await assert.rejects(runInit(parseInitArgs(['--yes', '--name', 'shop']), io), (error: unknown) => {
assert.ok(error instanceof InitError);
assert.equal(error.code, 'confirm_billable');
assert.match(error.next ?? '', /adds \$25 a month/);
assert.match(error.next ?? '', /--confirm-billable 2500/);
return true;
});
// --yes alone never confirms money.
assert.equal((puts[0] as Record<string, unknown>).confirm_billable_cents, undefined);
await assert.rejects(runInit(parseInitArgs(['--name', 'shop', '--confirm-billable', '2500']), io));
assert.equal((puts[1] as Record<string, unknown>).confirm_billable_cents, 2500);
});
it('names the way out of the other billing refusals', () => {
const consoleUrl = 'https://console.scribase.com';
assert.match(billingNextStep({ code: 'spend_cap_reached', detail: '' }, consoleUrl), /spend cap/);
assert.match(billingNextStep({ code: 'plan_project_cap', detail: '' }, consoleUrl), /switch plans/);
assert.match(billingNextStep({ code: 'agent_project_limit', detail: '' }, consoleUrl), /agent project limit/);
assert.match(billingNextStep({ code: 'card_required', detail: '' }, consoleUrl), /\/start/);
assert.throws(() => parseInitArgs(['--confirm-billable', 'lots']));
});
it('points card_required at the console that matches the API origin', () => {
assert.equal(consoleUrlFor('https://api.scribase.com', {}), 'https://console.scribase.com');
assert.equal(consoleUrlFor('https://api.example.com', {}), 'https://console.example.com');
assert.equal(consoleUrlFor('http://127.0.0.1:8080', {}), 'https://console.scribase.com');
assert.equal(consoleUrlFor('https://api.example.com', { SCRIBASE_CONSOLE_URL: 'https://c.example.com/' }), 'https://c.example.com');
});
it('without a token and without --account, creates a temporary project (temporary-first)', async () => {
const { io, calls } = memoryIo({}, (call) => {
if (call.path === '/v1/temporary-projects/challenge') return { status: 200, body: { challenge: 'c', bits: 0 } };
if (call.path === '/v1/temporary-projects') return { status: 503, body: { code: 'temporary_projects_disabled', detail: 'off' } };
return { status: 500, body: {} };
});
await assert.rejects(runInit(parseInitArgs([]), io), (error: unknown) => {
assert.ok(error instanceof InitError);
assert.equal(error.code, 'temporary_projects_disabled');
return true;
});
assert.ok(calls.some((call) => call.path === '/v1/temporary-projects'), 'went for a temporary project');
});
it('with --account but no browser sign-in available, says how to sign in', async () => {
const { io } = memoryIo({}, () => ({ status: 500, body: {} }));
await assert.rejects(runInit(parseInitArgs(['--account']), io), (error: unknown) => {
assert.ok(error instanceof InitError);
assert.equal(error.code, 'not_signed_in');
assert.match(error.next ?? '', /scribase login/);
return true;
});
});
});
describe('native projects (PS2.4)', () => {
it('detects Flutter, Swift, Android and Python projects without a package.json', async () => {
const { detectNative, nativeNextSteps } = await import('../src/cli/framework.js');
const at = (...files: string[]) => facts(null, files);
assert.equal(detectNative(at('pubspec.yaml')), 'flutter');
assert.equal(detectNative(at('Package.swift')), 'swift');
assert.equal(detectNative(at('settings.gradle.kts')), 'android');
assert.equal(detectNative(at('build.gradle')), 'android');
assert.equal(detectNative(at('pyproject.toml')), 'python');
assert.equal(detectNative(at('requirements.txt')), 'python');
assert.equal(detectNative(at()), null);
// A JavaScript project is never native, whatever else the folder holds.
assert.equal(detectNative(facts({ dependencies: { next: '15' } }, ['requirements.txt'])), null);
const steps = nativeNextSteps('swift', { organization_id: 'acme', project_id: 'app', environment_id: 'production' });
assert.ok(steps.some((step) => step.includes('https://github.com/supabase/supabase-swift.git')));
assert.ok(steps.some((step) => step.includes('scribase gen types acme app production --lang swift')));
assert.ok(nativeNextSteps('python', { organization_id: 'a', project_id: 'b', environment_id: 'c' }).some((step) => step.includes('pip install supabase')));
assert.ok(nativeNextSteps('flutter', { organization_id: 'a', project_id: 'b', environment_id: 'c' }).some((step) => step.includes('flutter pub add supabase_flutter')));
assert.ok(nativeNextSteps('android', { organization_id: 'a', project_id: 'b', environment_id: 'c' }).some((step) => step.includes('io.github.jan-tennert.supabase')));
});
});
describe('init in a native project (PS2.4)', () => {
it('a Flutter folder gets the project and the env file, no JavaScript client and no npm install', async () => {
let polls = 0;
const { io, runs, files } = memoryIo({ [`${ROOT}/pubspec.yaml`]: 'name: app\n' }, (call) => {
if (call.path === '/v1/temporary-projects/challenge') return { status: 200, body: { challenge: '9999999999.aa.bb', bits: 4 } };
if (call.path === '/v1/temporary-projects' && call.method === 'POST') {
return {
status: 201,
body: {
id: 'tmp_0123456789abcdef01234567',
organization_id: 'tmp-0123456789abcdef01234567',
project_id: 'app',
environment_id: 'production',
agent_token: 'scb_agt_secret',
expires_at: 1_900_000_000,
},
};
}
if (call.path === '/v1/temporary-projects/tmp_0123456789abcdef01234567') {
polls += 1;
return polls < 2 ? { status: 200, body: { status: 'provisioning', keys: null } } : { status: 200, body: { status: 'ready', keys: KEYS } };
}
return { status: 404, body: { code: 'not_found' } };
});
const result = await runInit(parseInitArgs(['--temp', '--yes', '--json', '--name', 'app']), io);
assert.equal(result.client_file, null);
assert.deepEqual(runs, []);
assert.equal(readEnvValue(files[`${ROOT}/.env`] ?? '', 'SUPABASE_URL'), KEYS.api_url);
assert.ok(result.next_steps.some((step) => step.includes('flutter pub add supabase_flutter')));
assert.ok(result.next_steps.some((step) => step.includes('--lang dart')));
assert.ok(!result.next_steps.some((step) => step.includes('npm init')));
});
});