import { SqliteError } from '@rocicorp/zero-sqlite3';
import { runSchemaMigrations, } from "../../db/migration-lite.js";
import { AutoResetSignal } from "../change-streamer/schema/tables.js";
import { CREATE_RUNTIME_EVENTS_TABLE, recordEvent, } from "../replicator/schema/replication-state.js";
export async function initReplica(log, debugName, dbPath, initialSync) {
    const setupMigration = {
        migrateSchema: (log, tx) => initialSync(log, tx),
        minSafeVersion: 1,
    };
    try {
        await runSchemaMigrations(log, debugName, dbPath, setupMigration, schemaVersionMigrationMap);
    }
    catch (e) {
        if (e instanceof SqliteError && e.code === 'SQLITE_CORRUPT') {
            throw new AutoResetSignal(e.message);
        }
        throw e;
    }
}
export async function upgradeReplica(log, debugName, dbPath) {
    await runSchemaMigrations(log, debugName, dbPath, 
    // setupMigration should never be invoked
    {
        migrateSchema: () => {
            throw new Error('This should only be called for already synced replicas');
        },
    }, schemaVersionMigrationMap);
}
export const schemaVersionMigrationMap = {
    // There's no incremental migration from v1. Just reset the replica.
    4: {
        migrateSchema: () => {
            throw new AutoResetSignal('upgrading replica to new schema');
        },
        minSafeVersion: 3,
    },
    5: {
        migrateSchema: (_, db) => {
            db.exec(CREATE_RUNTIME_EVENTS_TABLE);
        },
        migrateData: (_, db) => {
            recordEvent(db, 'upgrade');
        },
    },
};
//# sourceMappingURL=replica-schema.js.map