|
| 1 | +// CLI entry: `npm run rollback -- <org> --to <ISO-timestamp>` | |
| 2 | +// `npm run rollback -- <org> --list` |
| 3 | +// |
| 4 | +// Reads .vapi-state.<env>.snapshots/<timestamp>/<resource-type>/<id>.json |
| 5 | +// and re-applies the captured *platform* payload via PATCH, restoring the |
| 6 | +// dashboard to its state at that snapshot moment. |
| 7 | +// |
| 8 | +// Self-contained (does not import config.ts) so it can run in isolation |
| 9 | +// without triggering the global CLI parser. |
| 10 | + |
| 11 | +import { existsSync, readFileSync } from "fs"; |
| 12 | +import { dirname, join } from "path"; |
| 13 | +import { fileURLToPath } from "url"; |
| 14 | +import { |
| 15 | + listSnapshotTimestamps, |
| 16 | + loadSnapshot, |
| 17 | +} from "./snapshot.ts"; |
| 18 | + |
| 19 | +const __dirname = dirname(fileURLToPath(import.meta.url)); |
| 20 | +const BASE_DIR = join(__dirname, ".."); |
| 21 | + |
| 22 | +interface RollbackEnv { |
| 23 | + env: string; |
| 24 | + token: string; |
| 25 | + baseUrl: string; |
| 26 | +} |
| 27 | + |
| 28 | +function loadEnvFile(env: string): RollbackEnv { |
| 29 | + const envFiles = [ |
| 30 | + join(BASE_DIR, `.env.${env}`), |
| 31 | + join(BASE_DIR, `.env.${env}.local`), |
| 32 | + join(BASE_DIR, ".env.local"), |
| 33 | + ]; |
| 34 | + const envVars: Record<string, string> = {}; |
| 35 | + for (const envFile of envFiles) { |
| 36 | + if (!existsSync(envFile)) continue; |
| 37 | + for (const line of readFileSync(envFile, "utf-8").split("\n")) { |
| 38 | + const trimmed = line.trim(); |
| 39 | + if (!trimmed || trimmed.startsWith("#")) continue; |
| 40 | + const eq = trimmed.indexOf("="); |
| 41 | + if (eq === -1) continue; |
| 42 | + const key = trimmed.slice(0, eq).trim(); |
| 43 | + let value = trimmed.slice(eq + 1).trim(); |
| 44 | + if ( |
| 45 | + (value.startsWith('"') && value.endsWith('"')) || |
| 46 | + (value.startsWith("'") && value.endsWith("'")) |
| 47 | + ) { |
| 48 | + value = value.slice(1, -1); |
| 49 | + } |
| 50 | + if (envVars[key] === undefined) envVars[key] = value; |
| 51 | + } |
| 52 | + } |
| 53 | + const token = process.env.VAPI_TOKEN || envVars.VAPI_TOKEN; |
| 54 | + const baseUrl = |
| 55 | + process.env.VAPI_BASE_URL || |
| 56 | + envVars.VAPI_BASE_URL || |
| 57 | + "https://api.vapi.ai"; |
| 58 | + if (!token) { |
| 59 | + console.error(`❌ VAPI_TOKEN not found. Create .env.${env} with VAPI_TOKEN=your-token`); |
| 60 | + process.exit(1); |
| 61 | + } |
| 62 | + return { env, token, baseUrl }; |
| 63 | +} |
| 64 | + |
| 65 | +function printUsage(): void { |
| 66 | + console.error( |
| 67 | + [ |
| 68 | + "Usage:", |
| 69 | + " npm run rollback -- <org> --list", |
| 70 | + " npm run rollback -- <org> --to <ISO-timestamp>", |
| 71 | + "", |
| 72 | + "Snapshots are written automatically before each `npm run push` operation", |
| 73 | + "to .vapi-state.<env>.snapshots/<timestamp>/. Use --list to inspect available", |
| 74 | + "timestamps; use --to <ts> to re-apply the platform payloads from that snapshot.", |
| 75 | + ].join("\n"), |
| 76 | + ); |
| 77 | +} |
| 78 | + |
| 79 | +const ENDPOINT_MAP: Record<string, string> = { |
| 80 | + tools: "/tool", |
| 81 | + structuredOutputs: "/structured-output", |
| 82 | + assistants: "/assistant", |
| 83 | + squads: "/squad", |
| 84 | + personalities: "/eval/simulation/personality", |
| 85 | + scenarios: "/eval/simulation/scenario", |
| 86 | + simulations: "/eval/simulation", |
| 87 | + simulationSuites: "/eval/simulation/suite", |
| 88 | + evals: "/eval", |
| 89 | +}; |
| 90 | + |
| 91 | +interface ParsedArgs { |
| 92 | + env: string; |
| 93 | + list: boolean; |
| 94 | + to?: string; |
| 95 | +} |
| 96 | + |
| 97 | +function parseArgs(): ParsedArgs { |
| 98 | + const args = process.argv.slice(2); |
| 99 | + const env = args[0]; |
| 100 | + if (!env) { |
| 101 | + printUsage(); |
| 102 | + process.exit(1); |
| 103 | + } |
| 104 | + const SLUG_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/; |
| 105 | + if (!SLUG_RE.test(env)) { |
| 106 | + console.error(`❌ Invalid org name: ${env}`); |
| 107 | + process.exit(1); |
| 108 | + } |
| 109 | + const parsed: ParsedArgs = { env, list: false }; |
| 110 | + for (let i = 1; i < args.length; i++) { |
| 111 | + const a = args[i]; |
| 112 | + if (a === "--list") parsed.list = true; |
| 113 | + else if (a === "--to") parsed.to = args[++i]; |
| 114 | + else if (a === "--help" || a === "-h") { |
| 115 | + printUsage(); |
| 116 | + process.exit(0); |
| 117 | + } |
| 118 | + } |
| 119 | + if (!parsed.list && !parsed.to) { |
| 120 | + console.error("❌ Specify --list or --to <timestamp>"); |
| 121 | + printUsage(); |
| 122 | + process.exit(1); |
| 123 | + } |
| 124 | + return parsed; |
| 125 | +} |
| 126 | + |
| 127 | +async function main(): Promise<void> { |
| 128 | + const args = parseArgs(); |
| 129 | + |
| 130 | + if (args.list) { |
| 131 | + const timestamps = await listSnapshotTimestamps(BASE_DIR, args.env); |
| 132 | + if (timestamps.length === 0) { |
| 133 | + console.log(`No snapshots found for ${args.env}.`); |
| 134 | + return; |
| 135 | + } |
| 136 | + console.log(`Snapshots for ${args.env}:`); |
| 137 | + for (const t of timestamps) console.log(` ${t}`); |
| 138 | + return; |
| 139 | + } |
| 140 | + |
| 141 | + const cfg = loadEnvFile(args.env); |
| 142 | + const entries = await loadSnapshot(BASE_DIR, args.env, args.to!); |
| 143 | + if (entries.length === 0) { |
| 144 | + console.log("Snapshot directory exists but contains no resources."); |
| 145 | + return; |
| 146 | + } |
| 147 | + |
| 148 | + // We need state so we can resolve resourceId → UUID for the PATCH path. |
| 149 | + // Snapshot files don't store the UUID directly because the snapshot is |
| 150 | + // keyed by resourceId; the same resourceId points at the same UUID across |
| 151 | + // pushes (unless renamed, in which case the snapshot is stale anyway). |
| 152 | + const stateFile = join(BASE_DIR, `.vapi-state.${args.env}.json`); |
| 153 | + if (!existsSync(stateFile)) { |
| 154 | + console.error(`❌ State file not found: ${stateFile}`); |
| 155 | + process.exit(1); |
| 156 | + } |
| 157 | + const state = JSON.parse(readFileSync(stateFile, "utf-8")) as Record< |
| 158 | + string, |
| 159 | + Record<string, { uuid: string }> |
| 160 | + >; |
| 161 | + |
| 162 | + console.log(`🔁 Rollback ${args.env} → snapshot ${args.to}`); |
| 163 | + console.log(` ${entries.length} resource(s) to restore\n`); |
| 164 | + |
| 165 | + let restored = 0; |
| 166 | + let skipped = 0; |
| 167 | + for (const entry of entries) { |
| 168 | + const endpoint = ENDPOINT_MAP[entry.resourceType]; |
| 169 | + if (!endpoint) { |
| 170 | + console.warn(` ⚠️ Unknown resource type: ${entry.resourceType}, skipping`); |
| 171 | + skipped++; |
| 172 | + continue; |
| 173 | + } |
| 174 | + const section = state[entry.resourceType]; |
| 175 | + const uuid = section?.[entry.resourceId]?.uuid; |
| 176 | + if (!uuid) { |
| 177 | + console.warn( |
| 178 | + ` ⚠️ No UUID in state for ${entry.resourceType}/${entry.resourceId} — skipping`, |
| 179 | + ); |
| 180 | + skipped++; |
| 181 | + continue; |
| 182 | + } |
| 183 | + process.stdout.write(` 🔁 ${entry.resourceType}/${entry.resourceId} ... `); |
| 184 | + const response = await fetch(`${cfg.baseUrl}${endpoint}/${uuid}`, { |
| 185 | + method: "PATCH", |
| 186 | + headers: { |
| 187 | + Authorization: `Bearer ${cfg.token}`, |
| 188 | + "Content-Type": "application/json", |
| 189 | + }, |
| 190 | + body: JSON.stringify(entry.payload.platform), |
| 191 | + }); |
| 192 | + if (!response.ok) { |
| 193 | + const text = await response.text(); |
| 194 | + console.log(`❌ ${response.status}`); |
| 195 | + console.error(` ${text}`); |
| 196 | + skipped++; |
| 197 | + continue; |
| 198 | + } |
| 199 | + console.log("✅"); |
| 200 | + restored++; |
| 201 | + } |
| 202 | + |
| 203 | + console.log( |
| 204 | + `\n📊 Rollback summary: ${restored} restored, ${skipped} skipped`, |
| 205 | + ); |
| 206 | + if (skipped > 0) process.exit(1); |
| 207 | +} |
| 208 | + |
| 209 | +main().catch((error) => { |
| 210 | + console.error("\n❌ Rollback failed:", error instanceof Error ? error.message : error); |
| 211 | + process.exit(1); |
| 212 | +}); |
0 commit comments