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 { canAccessRecord, DEFAULT_RECORD_ACCESS } from "../capabilities/record-access"; |
| 9 | import { |
| 10 | aggregateRecords, |
| 11 | compareRecords, |
| 12 | matchesRecordWhere, |
| 13 | normalizeRecordSort, |
| 14 | } from "../capabilities/record-query"; |
| 15 | import type { TestWorkspaceState } from "./fake-capabilities"; |
| 16 |
| 17 | type Row = ColineRecordEnvelope<unknown> & { data: Record<string, unknown> }; |
| 18 |
| 19 | const MAX_PAGE = 1000; |
| 20 | const MAX_BATCH = 500; |
| 21 | const MAX_BULK = 5000; |
| 22 |
| 23 | export function createFakeCollection<T>( |
| 24 | state: TestWorkspaceState, |
| 25 | name: string, |
| 26 | actor: ColineActorRef, |
| 27 | installId: string, |
| 28 | options: { destructiveAllowed?: boolean } = {}, |
| 29 | ): ColineCollection<T> { |
| 30 | if (!state.records.has(name)) state.records.set(name, new Map()); |
| 31 | const records = state.records.get(name)! as Map<string, Row>; |
| 32 | const userId = actor.kind === "user" ? actor.userId : null; |
| 33 | const fail = (code: string, message: string): never => { |
| 34 | throw Object.assign(new Error(message), { code }); |
| 35 | }; |
| 36 | const visible = (row: Row) => canAccessRecord(row.access, row.createdBy, userId, "read"); |
| 37 | const wrap = (row: Row) => structuredClone(row) as unknown as ColineRecordEnvelope<T>; |
| 38 | const changed = () => { |
| 39 | state.recordRevisions.set(name, (state.recordRevisions.get(name) ?? 0) + 1); |
| 40 | for (const listener of state.realtimeListeners.get("coline.records.changed") ?? []) |
| 41 | listener({ event: "coline.records.changed", data: null }); |
| 42 | }; |
| 43 | function writable(id: string, expectedVersion?: number, manage = false) { |
| 44 | const row = records.get(id); |
| 45 | if (!row || !visible(row)) return fail("record_not_found", "Record not found."); |
| 46 | if (!canAccessRecord(row.access, row.createdBy, userId, manage ? "manage" : "write")) |
| 47 | return fail("record_forbidden", "You cannot change this record."); |
| 48 | if (expectedVersion !== undefined && row.version !== expectedVersion) |
| 49 | return fail("record_conflict", "This record changed. Refresh before saving again."); |
| 50 | return row; |
| 51 | } |
| 52 | function matching(where: unknown) { |
| 53 | return [...records.values()].filter((row) => visible(row) && matchesRecordWhere(row.data, where)); |
| 54 | } |
| 55 | function query(input?: ColineRecordQuery<T>) { |
| 56 | const rows = matching(input?.where); |
| 57 | const sorts = normalizeRecordSort(input); |
| 58 | if (sorts.length > 3) return fail("invalid_query", "Sort by at most three fields."); |
| 59 | rows.sort((a, b) => compareRecords(a, b, sorts)); |
| 60 | const offset = Number(input?.cursor ?? 0), |
| 61 | limit = input?.limit ?? 50; |
| 62 | if (!Number.isSafeInteger(offset) || offset < 0) |
| 63 | return fail("invalid_cursor", "Invalid collection cursor."); |
| 64 | if (!Number.isInteger(limit) || limit < 1 || limit > MAX_PAGE) |
| 65 | return fail("invalid_query", `Record limit must be 1–${MAX_PAGE}.`); |
| 66 | return { |
| 67 | records: rows.slice(offset, offset + limit).map(wrap), |
| 68 | nextCursor: rows.length > offset + limit ? String(offset + limit) : null, |
| 69 | }; |
| 70 | } |
| 71 | function insertRow(data: unknown, insertOptions?: { id?: string | undefined; access?: Row["access"] | undefined }) { |
| 72 | const id = insertOptions?.id ?? state.nextRecordId(); |
| 73 | const existing = records.get(id); |
| 74 | if (existing) { |
| 75 | if ( |
| 76 | JSON.stringify(existing.createdBy) !== JSON.stringify(actor) || |
| 77 | JSON.stringify(existing.data) !== JSON.stringify(data) || |
| 78 | JSON.stringify(existing.access) !== |
| 79 | JSON.stringify(insertOptions?.access ?? DEFAULT_RECORD_ACCESS) |
| 80 | ) |
| 81 | return fail("record_identity_conflict", "Record identity already in use."); |
| 82 | return existing; |
| 83 | } |
| 84 | const now = new Date().toISOString(); |
| 85 | const row: Row = { |
| 86 | id, |
| 87 | appId: "app_test", |
| 88 | installId, |
| 89 | collection: name, |
| 90 | createdBy: actor, |
| 91 | createdAt: now, |
| 92 | updatedAt: now, |
| 93 | version: 1, |
| 94 | access: structuredClone(insertOptions?.access ?? DEFAULT_RECORD_ACCESS), |
| 95 | data: structuredClone(data) as Record<string, unknown>, |
| 96 | }; |
| 97 | records.set(id, row); |
| 98 | return row; |
| 99 | } |
| 100 | function patchRow(row: Row, patch: unknown) { |
| 101 | row.data = { ...row.data, ...(structuredClone(patch) as Record<string, unknown>) }; |
| 102 | row.version++; |
| 103 | row.updatedAt = new Date().toISOString(); |
| 104 | } |
| 105 | function atomically<R>(work: () => R): R { |
| 106 | const snapshot = new Map([...records].map(([id, row]) => [id, structuredClone(row)])); |
| 107 | try { |
| 108 | const result = work(); |
| 109 | changed(); |
| 110 | return result; |
| 111 | } catch (error) { |
| 112 | records.clear(); |
| 113 | for (const [id, row] of snapshot) records.set(id, row); |
| 114 | throw error; |
| 115 | } |
| 116 | } |
| 117 | function applyBatch(operations: Array<ColineRecordBatchOperation<T>>) { |
| 118 | if (operations.length > MAX_BATCH) return fail("batch_too_large", `Batches are limited to ${MAX_BATCH} operations.`); |
| 119 | if (operations.some((operation) => operation.op === "delete") && options.destructiveAllowed === false) |
| 120 | return fail("effect_ceiling_exceeded", "Batches with deletes need a destructive effect."); |
| 121 | return atomically(() => |
| 122 | operations.map((operation) => { |
| 123 | if (operation.op === "insert") return wrap(insertRow(operation.data, operation)); |
| 124 | if (operation.op === "update") { |
| 125 | const row = writable(operation.id, operation.expectedVersion); |
| 126 | patchRow(row, operation.data); |
| 127 | return wrap(row); |
| 128 | } |
| 129 | writable(operation.id, operation.expectedVersion); |
| 130 | records.delete(operation.id); |
| 131 | return null; |
| 132 | }), |
| 133 | ); |
| 134 | } |
| 135 | return { |
| 136 | insert: async (data, insertOptions) => { |
| 137 | const row = insertRow(data, insertOptions); |
| 138 | changed(); |
| 139 | return wrap(row); |
| 140 | }, |
| 141 | get: async (id) => { |
| 142 | const row = records.get(id); |
| 143 | return row && visible(row) ? wrap(row) : null; |
| 144 | }, |
| 145 | update: async (id, patch, writeOptions) => { |
| 146 | const row = writable(id, writeOptions?.expectedVersion); |
| 147 | patchRow(row, patch); |
| 148 | changed(); |
| 149 | return wrap(row); |
| 150 | }, |
| 151 | delete: async (id, writeOptions) => { |
| 152 | writable(id, writeOptions?.expectedVersion); |
| 153 | records.delete(id); |
| 154 | changed(); |
| 155 | }, |
| 156 | setAccess: async (id, access, writeOptions) => { |
| 157 | const row = writable(id, writeOptions?.expectedVersion, true); |
| 158 | row.access = structuredClone(access); |
| 159 | row.version++; |
| 160 | row.updatedAt = new Date().toISOString(); |
| 161 | changed(); |
| 162 | return wrap(row); |
| 163 | }, |
| 164 | query: async (input) => query(input), |
| 165 | sync: async (input, revision) => { |
| 166 | const current = state.recordRevisions.get(name) ?? 0; |
| 167 | return { |
| 168 | revision: current, |
| 169 | ...(revision === current ? { records: null, nextCursor: null } : query(input)), |
| 170 | }; |
| 171 | }, |
| 172 | count: async (where) => ({ count: matching(where).length }), |
| 173 | aggregate: async (input) => { |
| 174 | if ((input.groupBy?.length ?? 0) > 3) return fail("invalid_query", "Group by at most three fields."); |
| 175 | if (Object.keys(input.metrics).length === 0) return fail("invalid_query", "Name at least one metric."); |
| 176 | return aggregateRecords(matching(input.where) as Array<{ data: T }>, input); |
| 177 | }, |
| 178 | batch: async (operations) => ({ results: applyBatch(operations) }), |
| 179 | insertMany: async (rows) => ({ |
| 180 | records: applyBatch(rows.map((row) => ({ op: "insert" as const, ...row }))) as Array< |
| 181 | ColineRecordEnvelope<T> |
| 182 | >, |
| 183 | }), |
| 184 | updateMany: async (input) => |
| 185 | atomically(() => { |
| 186 | const rows = matching(input.where).filter((row) => |
| 187 | canAccessRecord(row.access, row.createdBy, userId, "write"), |
| 188 | ); |
| 189 | if (rows.length > MAX_BULK) return fail("bulk_too_large", `Bulk updates are limited to ${MAX_BULK} records.`); |
| 190 | for (const row of rows) patchRow(row, input.data); |
| 191 | return { count: rows.length }; |
| 192 | }), |
| 193 | deleteMany: async (input) => |
| 194 | atomically(() => { |
| 195 | const rows = matching(input.where).filter((row) => |
| 196 | canAccessRecord(row.access, row.createdBy, userId, "write"), |
| 197 | ); |
| 198 | if (rows.length > MAX_BULK) return fail("bulk_too_large", `Bulk deletes are limited to ${MAX_BULK} records.`); |
| 199 | for (const row of rows) records.delete(row.id); |
| 200 | return { count: rows.length }; |
| 201 | }), |
| 202 | }; |
| 203 | } |
| 204 |