scribase-migrate/lib/project.mjs
caelum0x d7bbaf483b fix: resend without an account, working --create-project preview, idempotent re-runs, closing CTA line
- resend no longer demands --to or a Scribase token (it only exports JSON)
- --create-project read --region from argv[0] when the flag was absent
- --create-project --kind preview now creates an empty schema_only env; a
  snapshot failed with source_environment_missing on a new project
- clerk --dry-run created users; neon --dry-run wrote into the real
  supabase/migrations folder
- a second neon run re-added the schema step; identical steps are reused and
  pg_dump version banners are stripped so identical dumps stay identical
- <source> --help, --version, clear errors for a missing pg_dump, a reused
  deleted environment name and a missing token (with the signup link)
- output ends with one plain line pointing at scribase.com/migrate
- README: quickstart that works today (npx from Rithub, not the unpublished
  npm name), real output sample, verified/not-verified split; add LICENSE

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-17 20:10:39 +03:00

94 lines
4.0 KiB
JavaScript

/**
* Creates (idempotently) a real Scribase project + environment to migrate
* into. Used both by `scribase-migrate --create-project` for a first-time
* destination and by this repo's own local verification run.
*/
/**
* @param {import('scribase').ScribaseClient} client
* @param {{ organizationId?: string, projectId: string, environmentId?: string, region?: string, postgresMajor?: number, dataMode?: 'schema_only'|'sanitized'|'snapshot', kind?: 'preview'|'staging'|'production', ttlHours?: number }} opts
*/
export async function ensureProject(client, opts) {
const organizationId = opts.organizationId ?? (await firstOrganization(client));
const projectId = opts.projectId;
const environmentId = opts.environmentId ?? 'production';
const region = opts.region ?? 'us-east';
const postgresMajor = opts.postgresMajor ?? 17;
const dataMode = opts.dataMode ?? 'snapshot';
// `production` environments cannot be deleted once created (verified
// live) — callers doing throwaway verification should pass
// `kind: 'preview'` explicitly.
const kind = opts.kind ?? 'production';
await client.projects.put(organizationId, projectId, { region, postgres_major: postgresMajor });
let environment;
try {
environment = await client.environments.get({ organizationId, projectId, environmentId });
} catch {
environment = null;
}
// A deleted environment lingers as a tombstone and its name cannot be
// reused (verified live: re-creating one answers 409 conflict).
if (environment?.phase === 'deleted') {
throw new Error(
`environment "${environmentId}" in ${organizationId}/${projectId} was deleted and its name cannot be reused. Pick a different environment name in --to.`,
);
}
if (!environment) {
const accepted = await client.environments.create({
organization_id: organizationId,
project_id: projectId,
environment_id: environmentId,
kind,
data_mode: dataMode,
region,
postgres_major: postgresMajor,
...(opts.ttlHours ? { ttl_hours: opts.ttlHours } : {}),
});
await client.operations.wait(accepted.operation.id, organizationId, { timeoutMs: 10 * 60_000 });
environment = await waitUntilReady(client, { organizationId, projectId, environmentId });
} else {
environment = await waitUntilReady(client, { organizationId, projectId, environmentId });
}
const connection = await client.environments.connection({ organizationId, projectId, environmentId });
const apiKeys = await client.environments.apiKeys({ organizationId, projectId, environmentId });
return { organizationId, projectId, environmentId, environment, connection, apiKeys };
}
async function waitUntilReady(client, ref, { timeoutMs = 5 * 60_000, intervalMs = 2000 } = {}) {
const deadline = Date.now() + timeoutMs;
for (;;) {
const env = await client.environments.get(ref);
if (env.phase === 'ready') return env;
if (env.phase === 'failed_recoverable' || env.phase === 'deleted') {
throw new Error(`environment ${ref.environmentId} is ${env.phase}: ${env.last_error?.message ?? 'no detail'}`);
}
if (Date.now() > deadline) {
throw new Error(`environment ${ref.environmentId} did not become ready within ${timeoutMs}ms (phase=${env.phase})`);
}
await new Promise((resolve) => setTimeout(resolve, intervalMs));
}
}
async function firstOrganization(client) {
const orgs = await client.organizations.list();
if (!orgs.length) {
throw new Error('this Scribase account belongs to no organization; create one first (console.scribase.com)');
}
return orgs[0].organization_id;
}
/** Tears a verification project down (environment delete; the project spec can stay). */
export async function deleteEnvironment(client, { organizationId, projectId, environmentId }) {
const accepted = await client.environments.delete({ organizationId, projectId, environmentId });
await client.operations.wait(accepted.operation.id, organizationId, {
timeoutMs: 5 * 60_000,
throwOnFailure: false,
});
}