|
| 1 | +import { VAPI_ENV, VAPI_BASE_URL, VAPI_TOKEN } from "./config.ts"; |
| 2 | +import { loadState } from "./state.ts"; |
| 3 | + |
| 4 | +// ───────────────────────────────────────────────────────────────────────────── |
| 5 | +// Dangerous Sync - Delete everything NOT in state file |
| 6 | +// ───────────────────────────────────────────────────────────────────────────── |
| 7 | + |
| 8 | +const REQUEST_DELAY_MS = 700; |
| 9 | + |
| 10 | +async function sleep(ms: number): Promise<void> { |
| 11 | + return new Promise((resolve) => setTimeout(resolve, ms)); |
| 12 | +} |
| 13 | + |
| 14 | +async function vapiGet<T>(endpoint: string, debug = false): Promise<T> { |
| 15 | + await sleep(REQUEST_DELAY_MS); |
| 16 | + const response = await fetch(`${VAPI_BASE_URL}${endpoint}`, { |
| 17 | + headers: { Authorization: `Bearer ${VAPI_TOKEN}` }, |
| 18 | + }); |
| 19 | + if (!response.ok) { |
| 20 | + throw new Error(`GET ${endpoint} failed: ${response.status}`); |
| 21 | + } |
| 22 | + const data = await response.json(); |
| 23 | + |
| 24 | + if (debug) { |
| 25 | + console.log(` DEBUG: Response keys: ${Object.keys(data)}`); |
| 26 | + } |
| 27 | + |
| 28 | + // Handle paginated responses - check various wrapper formats |
| 29 | + if (data && typeof data === "object" && !Array.isArray(data)) { |
| 30 | + // Try common pagination patterns: { data }, { results }, { items }, { structuredOutputs } |
| 31 | + const possibleArrayKeys = ["data", "results", "items", "structuredOutputs", "assistants", "tools", "squads"]; |
| 32 | + for (const key of possibleArrayKeys) { |
| 33 | + if (Array.isArray(data[key])) { |
| 34 | + return data[key] as T; |
| 35 | + } |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + return data as T; |
| 40 | +} |
| 41 | + |
| 42 | +async function vapiDelete(endpoint: string): Promise<void> { |
| 43 | + await sleep(REQUEST_DELAY_MS); |
| 44 | + const response = await fetch(`${VAPI_BASE_URL}${endpoint}`, { |
| 45 | + method: "DELETE", |
| 46 | + headers: { Authorization: `Bearer ${VAPI_TOKEN}` }, |
| 47 | + }); |
| 48 | + if (!response.ok && response.status !== 404) { |
| 49 | + throw new Error(`DELETE ${endpoint} failed: ${response.status}`); |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +interface VapiResource { |
| 54 | + id: string; |
| 55 | + name?: string; |
| 56 | +} |
| 57 | + |
| 58 | +async function main(): Promise<void> { |
| 59 | + const dryRun = !process.argv.includes("--force"); |
| 60 | + |
| 61 | + console.log("═══════════════════════════════════════════════════════════════"); |
| 62 | + console.log(`🧹 Vapi Cleanup - Environment: ${VAPI_ENV}`); |
| 63 | + console.log(` API: ${VAPI_BASE_URL}`); |
| 64 | + console.log(` Mode: ${dryRun ? "🔒 DRY-RUN (use --force to delete)" : "⚠️ DELETING"}`); |
| 65 | + console.log("═══════════════════════════════════════════════════════════════\n"); |
| 66 | + |
| 67 | + const state = loadState(); |
| 68 | + const stateIds = new Set([ |
| 69 | + ...Object.values(state.assistants), |
| 70 | + ...Object.values(state.tools), |
| 71 | + ...Object.values(state.structuredOutputs), |
| 72 | + ...Object.values(state.squads), |
| 73 | + ...Object.values(state.personalities), |
| 74 | + ...Object.values(state.scenarios), |
| 75 | + ...Object.values(state.simulations), |
| 76 | + ...Object.values(state.simulationSuites), |
| 77 | + ]); |
| 78 | + |
| 79 | + console.log(`📄 State file has ${stateIds.size} resource IDs to keep\n`); |
| 80 | + |
| 81 | + const toDelete: { type: string; id: string; name: string; endpoint: string }[] = []; |
| 82 | + |
| 83 | + // Fetch and compare each resource type |
| 84 | + const resourceTypes = [ |
| 85 | + { name: "assistants", endpoint: "/assistant", deleteEndpoint: "/assistant" }, |
| 86 | + { name: "tools", endpoint: "/tool", deleteEndpoint: "/tool" }, |
| 87 | + { name: "structured outputs", endpoint: "/structured-output", deleteEndpoint: "/structured-output" }, |
| 88 | + { name: "squads", endpoint: "/squad", deleteEndpoint: "/squad" }, |
| 89 | + { name: "personalities", endpoint: "/eval/simulation/personality", deleteEndpoint: "/eval/simulation/personality" }, |
| 90 | + { name: "scenarios", endpoint: "/eval/simulation/scenario", deleteEndpoint: "/eval/simulation/scenario" }, |
| 91 | + { name: "simulations", endpoint: "/eval/simulation", deleteEndpoint: "/eval/simulation" }, |
| 92 | + { name: "simulation suites", endpoint: "/eval/simulation/suite", deleteEndpoint: "/eval/simulation/suite" }, |
| 93 | + ]; |
| 94 | + |
| 95 | + for (const { name, endpoint, deleteEndpoint } of resourceTypes) { |
| 96 | + console.log(`📥 Fetching ${name}...`); |
| 97 | + try { |
| 98 | + // Enable debug for structured outputs to see response format |
| 99 | + const debug = name === "structured outputs"; |
| 100 | + const resources = await vapiGet<VapiResource[]>(endpoint, debug); |
| 101 | + |
| 102 | + if (!Array.isArray(resources)) { |
| 103 | + console.log(` ⚠️ Unexpected response format for ${name}: ${typeof resources}, keys: ${Object.keys(resources as object)}`); |
| 104 | + continue; |
| 105 | + } |
| 106 | + |
| 107 | + const orphans = resources.filter((r) => !stateIds.has(r.id)); |
| 108 | + |
| 109 | + if (orphans.length > 0) { |
| 110 | + console.log(` Found ${orphans.length} orphaned ${name} (${resources.length} total)`); |
| 111 | + for (const r of orphans) { |
| 112 | + toDelete.push({ |
| 113 | + type: name, |
| 114 | + id: r.id, |
| 115 | + name: r.name || "(unnamed)", |
| 116 | + endpoint: `${deleteEndpoint}/${r.id}`, |
| 117 | + }); |
| 118 | + } |
| 119 | + } else { |
| 120 | + console.log(` ✅ All ${resources.length} ${name} are in state`); |
| 121 | + } |
| 122 | + } catch (error) { |
| 123 | + console.log(` ⚠️ Could not fetch ${name}: ${error}`); |
| 124 | + } |
| 125 | + } |
| 126 | + |
| 127 | + console.log("\n═══════════════════════════════════════════════════════════════"); |
| 128 | + |
| 129 | + if (toDelete.length === 0) { |
| 130 | + console.log("✅ Nothing to delete - all resources match state file\n"); |
| 131 | + return; |
| 132 | + } |
| 133 | + |
| 134 | + console.log(`\n⚠️ Found ${toDelete.length} resources to delete:\n`); |
| 135 | + |
| 136 | + for (const { type, id, name } of toDelete) { |
| 137 | + console.log(` 🗑️ ${type}: ${name} (${id})`); |
| 138 | + } |
| 139 | + |
| 140 | + if (dryRun) { |
| 141 | + console.log("\n═══════════════════════════════════════════════════════════════"); |
| 142 | + console.log("🔒 DRY-RUN MODE - No resources were deleted"); |
| 143 | + console.log(" To actually delete, run:"); |
| 144 | + console.log(` npm run cleanup:${VAPI_ENV} -- --force`); |
| 145 | + console.log("═══════════════════════════════════════════════════════════════\n"); |
| 146 | + return; |
| 147 | + } |
| 148 | + |
| 149 | + console.log("\n🗑️ Deleting...\n"); |
| 150 | + |
| 151 | + let deleted = 0; |
| 152 | + let failed = 0; |
| 153 | + |
| 154 | + for (const { type, id, name, endpoint } of toDelete) { |
| 155 | + try { |
| 156 | + await vapiDelete(endpoint); |
| 157 | + console.log(` ✅ Deleted ${type}: ${name}`); |
| 158 | + deleted++; |
| 159 | + } catch (error) { |
| 160 | + console.log(` ❌ Failed to delete ${type}: ${name} - ${error}`); |
| 161 | + failed++; |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + console.log("\n═══════════════════════════════════════════════════════════════"); |
| 166 | + console.log(`✅ Cleanup complete: ${deleted} deleted, ${failed} failed`); |
| 167 | + console.log("═══════════════════════════════════════════════════════════════\n"); |
| 168 | +} |
| 169 | + |
| 170 | +main().catch((error) => { |
| 171 | + console.error("\n❌ Cleanup failed:", error); |
| 172 | + process.exit(1); |
| 173 | +}); |
0 commit comments