|
| 1 | +/** |
| 2 | + * Persistent registry mapping Appwrite project IDs to the absolute project |
| 3 | + * directory (the dir containing that project's `appwriteConfig.yaml` / |
| 4 | + * `appwrite.json` / etc.). |
| 5 | + * |
| 6 | + * Backed by `~/.appwrite/projects.json` — sibling to the Appwrite CLI's |
| 7 | + * `prefs.json`, but written and read independently. This module MUST NOT read |
| 8 | + * or write `prefs.json` — that file is owned by the upstream Appwrite CLI and |
| 9 | + * touching it risks corrupting the user's CLI session state. |
| 10 | + * |
| 11 | + * Schema: |
| 12 | + * ```jsonc |
| 13 | + * { |
| 14 | + * "<projectId>": { |
| 15 | + * "projectDir": "/abs/path/to/project", |
| 16 | + * "endpoint": "https://cloud.appwrite.io/v1", // optional |
| 17 | + * "lastSelectedAt": "2026-05-29T12:34:56.789Z" |
| 18 | + * } |
| 19 | + * } |
| 20 | + * ``` |
| 21 | + * |
| 22 | + * @packageDocumentation |
| 23 | + */ |
| 24 | + |
| 25 | +import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; |
| 26 | +import { dirname, join } from "node:path"; |
| 27 | +import { homedir } from "node:os"; |
| 28 | +import { randomBytes } from "node:crypto"; |
| 29 | + |
| 30 | +export interface ProjectRegistryEntry { |
| 31 | + projectDir: string; |
| 32 | + endpoint?: string; |
| 33 | + lastSelectedAt: string; |
| 34 | +} |
| 35 | + |
| 36 | +export interface ProjectRegistrySnapshot { |
| 37 | + [projectId: string]: ProjectRegistryEntry; |
| 38 | +} |
| 39 | + |
| 40 | +/** |
| 41 | + * Default location: `~/.appwrite/projects.json`. Lives alongside prefs.json |
| 42 | + * but is fully independent — the Appwrite CLI never reads or writes it. |
| 43 | + */ |
| 44 | +function defaultRegistryPath(): string { |
| 45 | + return join(homedir(), ".appwrite", "projects.json"); |
| 46 | +} |
| 47 | + |
| 48 | +/** |
| 49 | + * Persistent project-directory registry. Safe for concurrent MCP instances: |
| 50 | + * writes go through an atomic tmp-file rename so a crash mid-write can't |
| 51 | + * leave a half-written JSON file. Reads tolerate a missing or corrupt file |
| 52 | + * (treated as empty) — losing the registry is annoying, not catastrophic. |
| 53 | + */ |
| 54 | +export class ProjectRegistry { |
| 55 | + private readonly filePath: string; |
| 56 | + private cache: ProjectRegistrySnapshot | null = null; |
| 57 | + |
| 58 | + constructor(filePath: string = defaultRegistryPath()) { |
| 59 | + this.filePath = filePath; |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * Where the registry is persisted on disk. Surfaced for debugging / |
| 64 | + * `list_appwrite_projects` output. |
| 65 | + */ |
| 66 | + public getFilePath(): string { |
| 67 | + return this.filePath; |
| 68 | + } |
| 69 | + |
| 70 | + /** |
| 71 | + * Load the registry from disk. Cached after first call. A missing or |
| 72 | + * corrupt file becomes an empty snapshot — never throws. |
| 73 | + */ |
| 74 | + public async load(): Promise<ProjectRegistrySnapshot> { |
| 75 | + if (this.cache) return this.cache; |
| 76 | + try { |
| 77 | + const raw = await readFile(this.filePath, "utf-8"); |
| 78 | + const parsed = JSON.parse(raw) as unknown; |
| 79 | + this.cache = normalize(parsed); |
| 80 | + } catch { |
| 81 | + this.cache = {}; |
| 82 | + } |
| 83 | + return this.cache; |
| 84 | + } |
| 85 | + |
| 86 | + /** |
| 87 | + * Look up the registry entry for a project ID. Returns null when unknown. |
| 88 | + */ |
| 89 | + public async get(projectId: string): Promise<ProjectRegistryEntry | null> { |
| 90 | + if (!projectId) return null; |
| 91 | + const snapshot = await this.load(); |
| 92 | + const entry = snapshot[projectId]; |
| 93 | + return entry ? { ...entry } : null; |
| 94 | + } |
| 95 | + |
| 96 | + /** |
| 97 | + * Upsert an entry for a project ID. Always stamps `lastSelectedAt` with |
| 98 | + * the current ISO timestamp. Persists atomically to disk. |
| 99 | + */ |
| 100 | + public async set( |
| 101 | + projectId: string, |
| 102 | + entry: Omit<ProjectRegistryEntry, "lastSelectedAt"> & { |
| 103 | + lastSelectedAt?: string; |
| 104 | + } |
| 105 | + ): Promise<ProjectRegistryEntry> { |
| 106 | + if (!projectId) throw new Error("ProjectRegistry.set: projectId is required"); |
| 107 | + if (!entry.projectDir) { |
| 108 | + throw new Error("ProjectRegistry.set: projectDir is required"); |
| 109 | + } |
| 110 | + const snapshot = await this.load(); |
| 111 | + const next: ProjectRegistryEntry = { |
| 112 | + projectDir: entry.projectDir, |
| 113 | + endpoint: entry.endpoint, |
| 114 | + lastSelectedAt: entry.lastSelectedAt ?? new Date().toISOString(), |
| 115 | + }; |
| 116 | + snapshot[projectId] = next; |
| 117 | + this.cache = snapshot; |
| 118 | + await this.persist(snapshot); |
| 119 | + return { ...next }; |
| 120 | + } |
| 121 | + |
| 122 | + /** |
| 123 | + * Remove an entry for a project ID. No-op when the entry doesn't exist. |
| 124 | + */ |
| 125 | + public async remove(projectId: string): Promise<boolean> { |
| 126 | + if (!projectId) return false; |
| 127 | + const snapshot = await this.load(); |
| 128 | + if (!(projectId in snapshot)) return false; |
| 129 | + delete snapshot[projectId]; |
| 130 | + this.cache = snapshot; |
| 131 | + await this.persist(snapshot); |
| 132 | + return true; |
| 133 | + } |
| 134 | + |
| 135 | + /** |
| 136 | + * Return every registered project as a flat array, sorted by most-recently |
| 137 | + * selected first. |
| 138 | + */ |
| 139 | + public async list(): Promise< |
| 140 | + Array<ProjectRegistryEntry & { projectId: string }> |
| 141 | + > { |
| 142 | + const snapshot = await this.load(); |
| 143 | + return Object.entries(snapshot) |
| 144 | + .map(([projectId, entry]) => ({ projectId, ...entry })) |
| 145 | + .sort((a, b) => (b.lastSelectedAt ?? "").localeCompare(a.lastSelectedAt ?? "")); |
| 146 | + } |
| 147 | + |
| 148 | + /** |
| 149 | + * Drop the in-memory cache. Next read will hit disk. Useful in tests so |
| 150 | + * one test's writes don't leak into the next. |
| 151 | + */ |
| 152 | + public invalidate(): void { |
| 153 | + this.cache = null; |
| 154 | + } |
| 155 | + |
| 156 | + /** |
| 157 | + * Write the snapshot to disk via tmp-file + rename so a crash mid-write |
| 158 | + * can't leave a half-written JSON file. Creates the parent directory if |
| 159 | + * needed (mode 0700 since prefs/projects can contain endpoint strings). |
| 160 | + */ |
| 161 | + private async persist(snapshot: ProjectRegistrySnapshot): Promise<void> { |
| 162 | + const dir = dirname(this.filePath); |
| 163 | + await mkdir(dir, { recursive: true, mode: 0o700 }); |
| 164 | + const tmpPath = `${this.filePath}.${randomBytes(6).toString("hex")}.tmp`; |
| 165 | + const body = `${JSON.stringify(snapshot, null, 2)}\n`; |
| 166 | + await writeFile(tmpPath, body, { mode: 0o600 }); |
| 167 | + await rename(tmpPath, this.filePath); |
| 168 | + } |
| 169 | +} |
| 170 | + |
| 171 | +/** |
| 172 | + * Coerce arbitrary parsed JSON into a valid registry snapshot. Drops entries |
| 173 | + * that don't have a string `projectDir`. Never throws. |
| 174 | + */ |
| 175 | +function normalize(parsed: unknown): ProjectRegistrySnapshot { |
| 176 | + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {}; |
| 177 | + const out: ProjectRegistrySnapshot = {}; |
| 178 | + for (const [pid, raw] of Object.entries(parsed as Record<string, unknown>)) { |
| 179 | + if (!raw || typeof raw !== "object") continue; |
| 180 | + const entry = raw as { |
| 181 | + projectDir?: unknown; |
| 182 | + endpoint?: unknown; |
| 183 | + lastSelectedAt?: unknown; |
| 184 | + }; |
| 185 | + if (typeof entry.projectDir !== "string" || !entry.projectDir) continue; |
| 186 | + out[pid] = { |
| 187 | + projectDir: entry.projectDir, |
| 188 | + endpoint: |
| 189 | + typeof entry.endpoint === "string" && entry.endpoint ? entry.endpoint : undefined, |
| 190 | + lastSelectedAt: |
| 191 | + typeof entry.lastSelectedAt === "string" && entry.lastSelectedAt |
| 192 | + ? entry.lastSelectedAt |
| 193 | + : new Date(0).toISOString(), |
| 194 | + }; |
| 195 | + } |
| 196 | + return out; |
| 197 | +} |
0 commit comments