The Coline App SDK: apps, tools, file types and surfaces that run inside Coline workspaces, and public websites with Coline Sites. TypeScript, with an in-memory test workspace. MIT.
| 6 | ColineRecordQuery, |
| 7 | } from "../capabilities/types"; |
| 8 | import { |
| 9 | actorKey, |
| 10 | canAccessRecord, |
| 11 | canVisitorAccess, |
| 12 | DEFAULT_RECORD_ACCESS, |
| 13 | parseActorKey, |
| 14 | sameActor, |
| 15 | } from "../capabilities/record-access"; |
| 16 | import { |
| 17 | aggregateRecords, |
| 18 | compareRecords, |
| 19 | matchesRecordWhere, |
| 20 | normalizeRecordSort, |
| 21 | } from "../capabilities/record-query"; |
| 22 | import type { CollectionAccess } from "../manifest/collections"; |
| 23 | import type { TestWorkspaceState } from "./fake-capabilities"; |
| 24 |
| 25 | type Row = ColineRecordEnvelope<unknown> & { data: Record<string, unknown> }; |
| 26 |
| 27 | const MAX_PAGE = 1000; |
| 28 | const MAX_BATCH = 500; |
| 29 | const MAX_BULK = 5000; |
| 30 |
| 31 | const TEAM_ONLY: CollectionAccess = { read: "team", create: "team", update: "team", delete: "team" }; |
| 32 |
| 33 | export interface FakeCollectionOptions { |
| 34 | destructiveAllowed?: boolean; |
| 35 | /** Records created here belong to this actor (a site tool's visitor). */ |
| 36 | createdBy?: ColineActorRef; |
| 37 | /** The collection's declared visitor rules; used when `actor` is a visitor. */ |
| 38 | rules?: CollectionAccess; |
| 39 | /** The collection's zod schema; visitor writes must match it, as on Coline. */ |
| 40 | schema?: { safeParse(data: unknown): { success: boolean; error?: { message: string } } }; |
| 41 | } |
| 42 |
| 43 | /** |
| 44 | * The in-memory collection, with the same access semantics as the server: |
| 45 | * members and app logic use the per-record ACL, visitors use the |
| 46 | * collection's declared rules and only the operations a site page may call. |
| 47 | */ |
| 48 | export function createFakeCollection<T>( |
| 49 | state: TestWorkspaceState, |
| 50 | name: string, |
| 51 | actor: ColineActorRef, |
| 52 | installId: string, |
| 53 | options: FakeCollectionOptions = {}, |
| 54 | ): ColineCollection<T> { |
| 55 | if (!state.records.has(name)) state.records.set(name, new Map()); |
| 56 | const records = state.records.get(name)! as Map<string, Row>; |
| 57 | const visitor = actor.kind === "visitor" ? actor : null; |
| 58 | const rules = options.rules ?? TEAM_ONLY; |
| 59 | const creator = options.createdBy ?? actor; |
| 60 | const fail = (code: string, message: string): never => { |
| 61 | throw Object.assign(new Error(message), { code }); |
| 62 | }; |
| 63 | const visitorOnly = (operation: string): never => |
| 64 | fail("unavailable_to_visitors", `Site visitors cannot call "${operation}".`); |
| 65 | const assertShape = (data: unknown) => { |
| 66 | if (!visitor || !options.schema) return; |
| 67 | const result = options.schema.safeParse(data); |
| 68 | if (!result.success) fail("record_invalid", `This record doesn't match the collection's schema. ${result.error?.message ?? ""}`); |
| 69 | }; |
| 70 | const visible = (row: Row) => |
| 71 | visitor |
| 72 | ? canVisitorAccess(rules.read, visitor, rules.read === "owner" ? row.createdBy : null) && |
| 73 | (rules.read !== "owner" || sameActor(row.createdBy, visitor)) |
| 74 | : canAccessRecord(row.access, row.createdBy, actor, "read"); |
| 75 | const wrap = (row: Row) => structuredClone(row) as unknown as ColineRecordEnvelope<T>; |
| 76 | const changed = () => { |
| 77 | state.recordRevisions.set(name, (state.recordRevisions.get(name) ?? 0) + 1); |
| 78 | for (const listener of state.realtimeListeners.get("coline.records.changed") ?? []) |
| 79 | listener({ event: "coline.records.changed", data: null }); |
| 80 | }; |
| 81 | function writable(id: string, expectedVersion?: number, action: "update" | "delete" | "manage" = "update") { |
| 82 | const row = records.get(id); |
| 83 | if (!row || !visible(row)) return fail("record_not_found", "Record not found."); |
| 84 | const permitted = visitor |
| 85 | ? action !== "manage" && canVisitorAccess(rules[action], visitor, row.createdBy) |
| 86 | : canAccessRecord(row.access, row.createdBy, actor, action === "manage" ? "manage" : "write"); |
| 87 | if (!permitted) return fail("record_forbidden", "You cannot change this record."); |
| 88 | if (expectedVersion !== undefined && row.version !== expectedVersion) |
| 89 | return fail("record_conflict", "This record changed. Refresh before saving again."); |
| 90 | return row; |
| 91 | } |
| 92 | function matching(where: unknown) { |
| 93 | return [...records.values()].filter((row) => visible(row) && matchesRecordWhere(row.data, where)); |
| 94 | } |
| 95 | function query(input?: ColineRecordQuery<T>) { |
| 96 | const rows = matching(input?.where); |
| 97 | const sorts = normalizeRecordSort(input); |
| 98 | if (sorts.length > 3) return fail("invalid_query", "Sort by at most three fields."); |
| 99 | rows.sort((a, b) => compareRecords(a, b, sorts)); |
| 100 | const offset = Number(input?.cursor ?? 0), |
| 101 | limit = input?.limit ?? 50; |
| 102 | if (!Number.isSafeInteger(offset) || offset < 0) |
| 103 | return fail("invalid_cursor", "Invalid collection cursor."); |
| 104 | if (!Number.isInteger(limit) || limit < 1 || limit > MAX_PAGE) |
| 105 | return fail("invalid_query", `Record limit must be 1–${MAX_PAGE}.`); |
| 106 | return { |
| 107 | records: rows.slice(offset, offset + limit).map(wrap), |
| 108 | nextCursor: rows.length > offset + limit ? String(offset + limit) : null, |
| 109 | }; |
| 110 | } |
| 111 | function insertRow(data: unknown, insertOptions?: { id?: string | undefined; access?: Row["access"] | undefined }) { |
| 112 | if (visitor) { |
| 113 | if (!canVisitorAccess(rules.create, visitor, null)) |
| 114 | return fail("record_forbidden", "Visitors cannot add records here."); |
| 115 | if (insertOptions?.id || insertOptions?.access) |
| 116 | return fail("unavailable_to_visitors", "Visitors cannot choose record ids or access."); |
| 117 | assertShape(data); |
| 118 | } |
| 119 | const id = insertOptions?.id ?? state.nextRecordId(); |
| 120 | const existing = records.get(id); |
| 121 | if (existing) { |
| 122 | if ( |
| 123 | !sameActor(existing.createdBy, creator) || |
| 124 | JSON.stringify(existing.data) !== JSON.stringify(data) || |
| 125 | JSON.stringify(existing.access) !== |
| 126 | JSON.stringify(insertOptions?.access ?? DEFAULT_RECORD_ACCESS) |
| 127 | ) |
| 128 | return fail("record_identity_conflict", "Record identity already in use."); |
| 129 | return existing; |
| 130 | } |
| 131 | const now = new Date().toISOString(); |
| 132 | const row: Row = { |
| 133 | id, |
| 134 | appId: "app_test", |
| 135 | installId, |
| 136 | collection: name, |
| 137 | // Coline stores only who created a record, never their name or |
| 138 | // email, so a public record shows no visitor's profile. |
| 139 | createdBy: parseActorKey(actorKey(creator)), |
| 140 | createdAt: now, |
| 141 | updatedAt: now, |
| 142 | version: 1, |
| 143 | access: structuredClone(insertOptions?.access ?? DEFAULT_RECORD_ACCESS), |
| 144 | data: structuredClone(data) as Record<string, unknown>, |
| 145 | }; |
| 146 | records.set(id, row); |
| 147 | return row; |
| 148 | } |
| 149 | function patchRow(row: Row, patch: unknown) { |
| 150 | row.data = { ...row.data, ...(structuredClone(patch) as Record<string, unknown>) }; |
| 151 | row.version++; |
| 152 | row.updatedAt = new Date().toISOString(); |
| 153 | } |
| 154 | function atomically<R>(work: () => R): R { |
| 155 | const snapshot = new Map([...records].map(([id, row]) => [id, structuredClone(row)])); |
| 156 | try { |
| 157 | const result = work(); |
| 158 | changed(); |
| 159 | return result; |
| 160 | } catch (error) { |
| 161 | records.clear(); |
| 162 | for (const [id, row] of snapshot) records.set(id, row); |
| 163 | throw error; |
| 164 | } |
| 165 | } |
| 166 | function applyBatch(operations: Array<ColineRecordBatchOperation<T>>) { |
| 167 | if (operations.length > MAX_BATCH) return fail("batch_too_large", `Batches are limited to ${MAX_BATCH} operations.`); |
| 168 | if (operations.some((operation) => operation.op === "delete") && options.destructiveAllowed === false) |
| 169 | return fail("effect_ceiling_exceeded", "Batches with deletes need a destructive effect."); |
| 170 | return atomically(() => |
| 171 | operations.map((operation) => { |
| 172 | if (operation.op === "insert") return wrap(insertRow(operation.data, operation)); |
| 173 | if (operation.op === "update") { |
| 174 | const row = writable(operation.id, operation.expectedVersion); |
| 175 | patchRow(row, operation.data); |
| 176 | return wrap(row); |
| 177 | } |
| 178 | writable(operation.id, operation.expectedVersion, "delete"); |
| 179 | records.delete(operation.id); |
| 180 | return null; |
| 181 | }), |
| 182 | ); |
| 183 | } |
| 184 | return { |
| 185 | insert: async (data, insertOptions) => { |
| 186 | const row = insertRow(data, insertOptions); |
| 187 | changed(); |
| 188 | return wrap(row); |
| 189 | }, |
| 190 | get: async (id) => { |
| 191 | const row = records.get(id); |
| 192 | return row && visible(row) ? wrap(row) : null; |
| 193 | }, |
| 194 | update: async (id, patch, writeOptions) => { |
| 195 | const row = writable(id, writeOptions?.expectedVersion); |
| 196 | assertShape({ ...(row.data as Record<string, unknown>), ...(patch as Record<string, unknown>) }); |
| 197 | patchRow(row, patch); |
| 198 | changed(); |
| 199 | return wrap(row); |
| 200 | }, |
| 201 | delete: async (id, writeOptions) => { |
| 202 | writable(id, writeOptions?.expectedVersion, "delete"); |
| 203 | records.delete(id); |
| 204 | changed(); |
| 205 | }, |
| 206 | setAccess: async (id, access, writeOptions) => { |
| 207 | if (visitor) return visitorOnly("storage.records.setAccess"); |
| 208 | const row = writable(id, writeOptions?.expectedVersion, "manage"); |
| 209 | row.access = structuredClone(access); |
| 210 | row.version++; |
| 211 | row.updatedAt = new Date().toISOString(); |
| 212 | changed(); |
| 213 | return wrap(row); |
| 214 | }, |
| 215 | query: async (input) => query(input), |
| 216 | sync: async (input, revision) => { |
| 217 | const current = state.recordRevisions.get(name) ?? 0; |
| 218 | return { |
| 219 | revision: current, |
| 220 | ...(revision === current ? { records: null, nextCursor: null } : query(input)), |
| 221 | }; |
| 222 | }, |
| 223 | count: async (where) => ({ count: matching(where).length }), |
| 224 | aggregate: async (input) => { |
| 225 | if (visitor) return visitorOnly("storage.records.aggregate"); |
| 226 | if ((input.groupBy?.length ?? 0) > 3) return fail("invalid_query", "Group by at most three fields."); |
| 227 | if (Object.keys(input.metrics).length === 0) return fail("invalid_query", "Name at least one metric."); |
| 228 | return aggregateRecords(matching(input.where) as Array<{ data: T }>, input); |
| 229 | }, |
| 230 | batch: async (operations) => |
| 231 | visitor ? visitorOnly("storage.records.batch") : { results: applyBatch(operations) }, |
| 232 | insertMany: async (rows) => |
| 233 | visitor |
| 234 | ? visitorOnly("storage.records.insertMany") |
| 235 | : { |
| 236 | records: applyBatch(rows.map((row) => ({ op: "insert" as const, ...row }))) as Array< |
| 237 | ColineRecordEnvelope<T> |
| 238 | >, |
| 239 | }, |
| 240 | updateMany: async (input) => |
| 241 | visitor |
| 242 | ? visitorOnly("storage.records.updateMany") |
| 243 | : atomically(() => { |
| 244 | const rows = matching(input.where).filter((row) => |
| 245 | canAccessRecord(row.access, row.createdBy, actor, "write"), |
| 246 | ); |
| 247 | if (rows.length > MAX_BULK) return fail("bulk_too_large", `Bulk updates are limited to ${MAX_BULK} records.`); |
| 248 | for (const row of rows) patchRow(row, input.data); |
| 249 | return { count: rows.length }; |
| 250 | }), |
| 251 | deleteMany: async (input) => |
| 252 | visitor |
| 253 | ? visitorOnly("storage.records.deleteMany") |
| 254 | : atomically(() => { |
| 255 | const rows = matching(input.where).filter((row) => |
| 256 | canAccessRecord(row.access, row.createdBy, actor, "write"), |
| 257 | ); |
| 258 | if (rows.length > MAX_BULK) return fail("bulk_too_large", `Bulk deletes are limited to ${MAX_BULK} records.`); |
| 259 | for (const row of rows) records.delete(row.id); |
| 260 | return { count: rows.length }; |
| 261 | }), |
| 262 | }; |
| 263 | } |
| 264 |