The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as firestore from "@distilled.cloud/gcp/firestore_v1"; |
| 2 | import { unownedUnlessPrevious } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import * as Provider from "alchemy/Provider"; |
| 5 | import { Resource } from "alchemy/Resource"; |
| 6 | import * as Data from "effect/Data"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import { GcpEnvironment } from "../Environment.ts"; |
| 9 | import type { Providers } from "../Providers.ts"; |
| 10 | import { databaseNameOf, lastSegment, parseDatabaseName, toResourceId } from "./internal.ts"; |
| 11 | |
| 12 | const DEFAULT_DATABASE = "(default)"; |
| 13 | const DEFAULT_COLLECTION = "_alchemy"; |
| 14 | |
| 15 | export type DocumentFieldValue = { |
| 16 | /** UTF-8 string. */ |
| 17 | stringValue?: string; |
| 18 | /** Integer encoded as a decimal string. */ |
| 19 | integerValue?: string; |
| 20 | /** Boolean. */ |
| 21 | booleanValue?: boolean; |
| 22 | /** IEEE 754 double. */ |
| 23 | doubleValue?: number; |
| 24 | /** RFC3339 timestamp. */ |
| 25 | timestampValue?: string; |
| 26 | /** Null sentinel (`NULL_VALUE`). */ |
| 27 | nullValue?: string; |
| 28 | }; |
| 29 | |
| 30 | export type DocumentProps = { |
| 31 | /** |
| 32 | * Database id or `projects/{project}/databases/{database}`. Defaults |
| 33 | * to `"(default)"`. Immutable — changing it replaces the document. |
| 34 | * @default "(default)" |
| 35 | */ |
| 36 | database?: string; |
| 37 | /** |
| 38 | * Collection id relative to `parent`. Immutable — changing it |
| 39 | * replaces the document. |
| 40 | * @default "_alchemy" |
| 41 | */ |
| 42 | collectionId?: string; |
| 43 | /** |
| 44 | * Parent document path relative to the database (no leading slash), |
| 45 | * or empty for a root collection. Immutable — changing it replaces |
| 46 | * the document. |
| 47 | */ |
| 48 | parentPath?: string; |
| 49 | /** |
| 50 | * Client-assigned document id. If omitted, a unique id is generated |
| 51 | * from the stack, stage, and logical id. Immutable — changing it |
| 52 | * replaces the document. |
| 53 | */ |
| 54 | documentId?: string; |
| 55 | /** |
| 56 | * Document fields. Fields absent here are removed from the document. |
| 57 | */ |
| 58 | fields?: Record<string, DocumentFieldValue>; |
| 59 | }; |
| 60 | |
| 61 | export type Document = Resource< |
| 62 | "GCP.Firestore.Document", |
| 63 | DocumentProps, |
| 64 | { |
| 65 | /** Full resource name `projects/{project}/databases/{database}/documents/{path}`. */ |
| 66 | name: string; |
| 67 | /** Document id (last path segment). */ |
| 68 | documentId: string; |
| 69 | /** Database resource name. */ |
| 70 | database: string; |
| 71 | /** Database id. */ |
| 72 | databaseId: string; |
| 73 | /** Collection id. */ |
| 74 | collectionId: string; |
| 75 | /** Parent path relative to the database documents root. */ |
| 76 | parentPath: string; |
| 77 | /** Path relative to the database documents root. */ |
| 78 | documentPath: string; |
| 79 | /** Project id. */ |
| 80 | project: string; |
| 81 | /** Document fields. */ |
| 82 | fields: Record<string, DocumentFieldValue>; |
| 83 | /** RFC3339 creation timestamp. */ |
| 84 | createTime: string | undefined; |
| 85 | /** RFC3339 last-update timestamp. */ |
| 86 | updateTime: string | undefined; |
| 87 | }, |
| 88 | never, |
| 89 | Providers |
| 90 | >; |
| 91 | |
| 92 | /** |
| 93 | * A Cloud Firestore document. |
| 94 | * |
| 95 | * Documents have no labels field and Alchemy writes nothing but the given |
| 96 | * fields: `read` reports a document it finds without prior state as |
| 97 | * unowned (adopt it with `--adopt`). Changing |
| 98 | * `database`, `collectionId`, `parentPath`, or `documentId` replaces |
| 99 | * the document. User fields update in place via `documents.patch`. |
| 100 | * |
| 101 | * Runtime get/patch/delete of arbitrary documents still goes through |
| 102 | * {@link GetDocument} / {@link PatchDocument} / {@link DeleteDocument}. |
| 103 | * |
| 104 | * ### Creating a Document |
| 105 | * **Example:** Generated id in `_alchemy` |
| 106 | * ```typescript |
| 107 | * const doc = yield* GCP.Firestore.Document("Flag", { |
| 108 | * fields: { env: { stringValue: "test" } }, |
| 109 | * }); |
| 110 | * ``` |
| 111 | * |
| 112 | * **Example:** Named document |
| 113 | * ```typescript |
| 114 | * const doc = yield* GCP.Firestore.Document("Alice", { |
| 115 | * database: "(default)", |
| 116 | * collectionId: "users", |
| 117 | * documentId: "alice", |
| 118 | * fields: { name: { stringValue: "Alice" } }, |
| 119 | * }); |
| 120 | * ``` |
| 121 | * |
| 122 | * @resource |
| 123 | * @category Firestore |
| 124 | */ |
| 125 | export const Document = Resource<Document>("GCP.Firestore.Document"); |
| 126 | |
| 127 | export class DocumentNotResolved extends Data.TaggedError("GCP.Firestore.DocumentNotResolved")<{ |
| 128 | resourceName: string; |
| 129 | }> {} |
| 130 | |
| 131 | const databaseIdOf = (value: string | undefined, project: string) => { |
| 132 | if (value === undefined || value.length === 0) return DEFAULT_DATABASE; |
| 133 | return parseDatabaseName(databaseNameOf(project, value)).databaseId; |
| 134 | }; |
| 135 | |
| 136 | const collectionOf = (value: string | undefined) => |
| 137 | value && value.length > 0 ? value : DEFAULT_COLLECTION; |
| 138 | |
| 139 | const parentPathOf = (value: string | undefined) => (value ?? "").replace(/^\/+|\/+$/g, ""); |
| 140 | |
| 141 | const documentsParent = (databaseName: string, parentPath: string) => |
| 142 | parentPath.length === 0 ? `${databaseName}/documents` : `${databaseName}/documents/${parentPath}`; |
| 143 | |
| 144 | const documentName = ( |
| 145 | databaseName: string, |
| 146 | parentPath: string, |
| 147 | collectionId: string, |
| 148 | documentId: string, |
| 149 | ) => `${documentsParent(databaseName, parentPath)}/${collectionId}/${documentId}`; |
| 150 | |
| 151 | const parseDocumentName = (name: string) => { |
| 152 | const marker = "/documents/"; |
| 153 | const at = name.indexOf(marker); |
| 154 | const databaseName = at >= 0 ? name.slice(0, at) : name; |
| 155 | const relative = at >= 0 ? name.slice(at + marker.length) : lastSegment(name); |
| 156 | const parts = relative.split("/").filter((part) => part.length > 0); |
| 157 | const documentId = parts[parts.length - 1] ?? ""; |
| 158 | const collectionId = parts.length >= 2 ? parts[parts.length - 2]! : DEFAULT_COLLECTION; |
| 159 | const parentParts = parts.slice(0, Math.max(0, parts.length - 2)); |
| 160 | return { |
| 161 | ...parseDatabaseName(databaseName), |
| 162 | databaseName, |
| 163 | documentPath: relative, |
| 164 | documentId, |
| 165 | collectionId, |
| 166 | parentPath: parentParts.join("/"), |
| 167 | }; |
| 168 | }; |
| 169 | |
| 170 | const fieldOf = (value: firestore.Value | undefined): DocumentFieldValue => ({ |
| 171 | stringValue: value?.stringValue, |
| 172 | integerValue: value?.integerValue, |
| 173 | booleanValue: value?.booleanValue, |
| 174 | doubleValue: value?.doubleValue, |
| 175 | timestampValue: value?.timestampValue, |
| 176 | nullValue: value?.nullValue, |
| 177 | }); |
| 178 | |
| 179 | const userFields = (fields: firestore.ValueMap | undefined): Record<string, DocumentFieldValue> => { |
| 180 | const next: Record<string, DocumentFieldValue> = {}; |
| 181 | for (const [key, value] of Object.entries(fields ?? {})) { |
| 182 | next[key] = fieldOf(value); |
| 183 | } |
| 184 | return next; |
| 185 | }; |
| 186 | |
| 187 | const desiredFields = (news: DocumentProps): firestore.ValueMap => ({ |
| 188 | ...news.fields, |
| 189 | }); |
| 190 | |
| 191 | const jsonOf = (value: unknown) => JSON.stringify(value ?? null); |
| 192 | |
| 193 | const toAttrs = (current: firestore.Document, project: string) => { |
| 194 | const name = current.name ?? ""; |
| 195 | const parsed = parseDocumentName(name); |
| 196 | return { |
| 197 | name, |
| 198 | documentId: parsed.documentId, |
| 199 | database: parsed.databaseName, |
| 200 | databaseId: parsed.databaseId, |
| 201 | collectionId: parsed.collectionId, |
| 202 | parentPath: parsed.parentPath, |
| 203 | documentPath: parsed.documentPath, |
| 204 | project: parsed.project || project, |
| 205 | fields: userFields(current.fields), |
| 206 | createTime: current.createTime, |
| 207 | updateTime: current.updateTime, |
| 208 | }; |
| 209 | }; |
| 210 | |
| 211 | const getByName = (name: string) => |
| 212 | name.length === 0 |
| 213 | ? Effect.undefined |
| 214 | : firestore |
| 215 | .getProjectsDatabasesDocuments({ name }) |
| 216 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 217 | |
| 218 | export const DocumentProvider = () => |
| 219 | Provider.succeed(Document, { |
| 220 | stables: [ |
| 221 | "name", |
| 222 | "documentId", |
| 223 | "database", |
| 224 | "databaseId", |
| 225 | "collectionId", |
| 226 | "parentPath", |
| 227 | "documentPath", |
| 228 | "project", |
| 229 | "createTime", |
| 230 | ], |
| 231 | |
| 232 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 233 | if (!isResolved(news)) return undefined; |
| 234 | const previousDatabase = olds?.database ?? output?.databaseId; |
| 235 | const previousCollection = olds?.collectionId ?? output?.collectionId; |
| 236 | const previousParent = olds?.parentPath ?? output?.parentPath; |
| 237 | const previousId = olds?.documentId ?? output?.documentId; |
| 238 | if ( |
| 239 | (previousDatabase !== undefined && |
| 240 | news.database !== undefined && |
| 241 | news.database !== previousDatabase) || |
| 242 | (previousCollection !== undefined && |
| 243 | news.collectionId !== undefined && |
| 244 | news.collectionId !== previousCollection) || |
| 245 | (previousParent !== undefined && |
| 246 | news.parentPath !== undefined && |
| 247 | parentPathOf(news.parentPath) !== parentPathOf(previousParent)) || |
| 248 | (previousId !== undefined && |
| 249 | news.documentId !== undefined && |
| 250 | news.documentId !== previousId) |
| 251 | ) { |
| 252 | return { action: "replace" as const, deleteFirst: true }; |
| 253 | } |
| 254 | return undefined; |
| 255 | }), |
| 256 | |
| 257 | read: Effect.fn(function* ({ id, olds, output, previous }) { |
| 258 | const env = yield* GcpEnvironment.current; |
| 259 | const databaseId = databaseIdOf( |
| 260 | olds?.database ?? output?.database ?? output?.databaseId, |
| 261 | env.project, |
| 262 | ); |
| 263 | const databaseName = databaseNameOf(env.project, databaseId); |
| 264 | const collectionId = collectionOf(olds?.collectionId ?? output?.collectionId); |
| 265 | const parentPath = parentPathOf(olds?.parentPath ?? output?.parentPath); |
| 266 | const documentId = yield* toResourceId(id, olds?.documentId, output?.documentId); |
| 267 | const name = output?.name ?? documentName(databaseName, parentPath, collectionId, documentId); |
| 268 | const existing = yield* getByName(name); |
| 269 | if (existing === undefined) return undefined; |
| 270 | const attrs = toAttrs(existing, env.project); |
| 271 | // No labels field: without prior state it may not be ours. |
| 272 | return output !== undefined ? attrs : unownedUnlessPrevious(attrs, previous, "name"); |
| 273 | }), |
| 274 | |
| 275 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 276 | const env = yield* GcpEnvironment.current; |
| 277 | const databaseId = databaseIdOf( |
| 278 | news.database ?? output?.database ?? output?.databaseId, |
| 279 | env.project, |
| 280 | ); |
| 281 | const databaseName = databaseNameOf(env.project, databaseId); |
| 282 | const collectionId = collectionOf(news.collectionId); |
| 283 | const parentPath = parentPathOf(news.parentPath); |
| 284 | const documentId = yield* toResourceId(id, news.documentId, output?.documentId); |
| 285 | const parent = documentsParent(databaseName, parentPath); |
| 286 | const name = documentName(databaseName, parentPath, collectionId, documentId); |
| 287 | const fields = desiredFields(news); |
| 288 | |
| 289 | let current = yield* getByName(output?.name ?? name); |
| 290 | |
| 291 | if (current === undefined) { |
| 292 | const created = yield* firestore |
| 293 | .createDocumentProjectsDatabasesDocuments({ |
| 294 | parent, |
| 295 | collectionId, |
| 296 | documentId, |
| 297 | body: { fields }, |
| 298 | }) |
| 299 | .pipe(Effect.catchTag("Conflict", () => getByName(name))); |
| 300 | current = created ?? undefined; |
| 301 | } |
| 302 | |
| 303 | if (current === undefined) { |
| 304 | return yield* new DocumentNotResolved({ resourceName: name }); |
| 305 | } |
| 306 | |
| 307 | if (jsonOf(current.fields) !== jsonOf(fields)) { |
| 308 | current = yield* firestore.patchProjectsDatabasesDocuments({ |
| 309 | name: current.name ?? name, |
| 310 | // Masking observed fields too removes the ones no longer desired. |
| 311 | "updateMask.fieldPaths": Object.keys({ |
| 312 | ...current.fields, |
| 313 | ...fields, |
| 314 | }), |
| 315 | body: { fields }, |
| 316 | }); |
| 317 | } |
| 318 | |
| 319 | return toAttrs(current, env.project); |
| 320 | }), |
| 321 | |
| 322 | delete: Effect.fn(function* ({ output }) { |
| 323 | if (!output.name) return; |
| 324 | yield* firestore |
| 325 | .deleteProjectsDatabasesDocuments({ name: output.name }) |
| 326 | .pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 327 | }), |
| 328 | }); |