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.
| 4 | import type { ColineTask, ColineCalendarEvent, ColineMessage } from "../capabilities/workspace"; |
| 5 | import type { |
| 6 | ColineActorRef, |
| 7 | ColineCapabilities, |
| 8 | ColineConnectionStatus, |
| 9 | ColineFileSummaryV2, |
| 10 | ColineJobRun, |
| 11 | ColineJobStatus, |
| 12 | ColineMemberSummary, |
| 13 | ColineNetFetchInput, |
| 14 | ColineNetFetchResult, |
| 15 | ColineRecordEnvelope, |
| 16 | } from "../capabilities/types"; |
| 17 | import type { ColineAppManifestV2 } from "../manifest/manifest"; |
| 18 | import { EFFECT_CEILINGS, MUTATION_CLASS_RANK, type ToolEffect } from "../manifest/effect"; |
| 19 | import { uploadDataToBytes } from "../capabilities/upload"; |
| 20 |
| 21 | function toJobRun(run: TestJobRun): ColineJobRun { |
| 22 | return { |
| 23 | id: run.id, |
| 24 | name: run.name, |
| 25 | status: run.status, |
| 26 | attempt: run.attempt, |
| 27 | maxAttempts: run.maxAttempts, |
| 28 | progress: run.progress, |
| 29 | result: run.result ?? null, |
| 30 | error: run.error, |
| 31 | runAt: run.runAt, |
| 32 | createdAt: run.createdAt, |
| 33 | startedAt: run.startedAt, |
| 34 | finishedAt: run.finishedAt, |
| 35 | }; |
| 36 | } |
| 37 |
| 38 | /** |
| 39 | * The in-memory capability fake behind `createTestWorkspace` (plan §14.2). |
| 40 | * Implements the same `coline.*` contract apps run against in production, |
| 41 | * backed by maps — no network, no database, fully inspectable. |
| 42 | */ |
| 43 |
| 44 | export interface TestWorkspaceOptions { |
| 45 | grantedPermissions?: import("../manifest/permissions").AppPermissionV2[]; |
| 46 | workspaceId?: string; |
| 47 | workspaceSlug?: string; |
| 48 | workspaceName?: string; |
| 49 | appKey?: string; |
| 50 | installId?: string; |
| 51 | members?: Array<Partial<ColineMemberSummary> & { userId: string }>; |
| 52 | /** Handler for coline.net.fetch; defaults to rejecting. */ |
| 53 | onNetFetch?: (input: ColineNetFetchInput) => Promise<ColineNetFetchResult>; |
| 54 | /** Models enabled by the deterministic test provider. */ |
| 55 | aiModels?: import("../capabilities/ai").ColineAiModelInfo[]; |
| 56 | onAiJob?: Parameters<typeof fakeAi>[3]; |
| 57 | /** Handler for coline.ai.generate; defaults to echoing. */ |
| 58 | onAiGenerate?: (prompt: string) => Promise<string>; |
| 59 | /** Picker results; default null (dismissed) / false (confirm). */ |
| 60 | pickers?: { |
| 61 | file?: () => Promise<{ fileId: string } | null>; |
| 62 | member?: () => Promise<{ userId: string } | null>; |
| 63 | destination?: () => Promise<{ driveId: string; parentId: string | null } | null>; |
| 64 | confirm?: () => Promise<boolean>; |
| 65 | }; |
| 66 | /** Connections already made, by key. `connect()` marks a connection connected. */ |
| 67 | connections?: Record<string, { accountLabel?: string; scopes?: string[] }>; |
| 68 | } |
| 69 |
| 70 | export interface TestJobRun { |
| 71 | id: string; |
| 72 | name: string; |
| 73 | payload: Record<string, unknown>; |
| 74 | actor: ColineActorRef; |
| 75 | status: ColineJobStatus; |
| 76 | attempt: number; |
| 77 | maxAttempts: number; |
| 78 | runAt: string; |
| 79 | createdAt: string; |
| 80 | startedAt: string | null; |
| 81 | finishedAt: string | null; |
| 82 | checkpoint: unknown; |
| 83 | progress: { value: number; message: string | null } | null; |
| 84 | result: unknown; |
| 85 | error: { code: string; message: string } | null; |
| 86 | idempotencyKey: string | null; |
| 87 | } |
| 88 |
| 89 | export interface TestUpload { |
| 90 | file: TestFile; |
| 91 | mimeType: string; |
| 92 | bytes: Uint8Array; |
| 93 | } |
| 94 |
| 95 | export interface TestFile extends ColineFileSummaryV2 { |
| 96 | document: Record<string, unknown>; |
| 97 | trashed: boolean; |
| 98 | } |
| 99 |
| 100 | export interface TestNotification { |
| 101 | channelKey: string; |
| 102 | title: string; |
| 103 | body?: string | undefined; |
| 104 | href: string; |
| 105 | recipients: string[]; |
| 106 | } |
| 107 |
| 108 | export interface TestIndexDocument { |
| 109 | documentKey: string; |
| 110 | documentType: string; |
| 111 | title: string; |
| 112 | body: string; |
| 113 | fileId?: string | undefined; |
| 114 | } |
| 115 |
| 116 | export interface TestNavigationEvent { |
| 117 | intent: "openFile" | "openAppHome" | "navigate" | "openReference"; |
| 118 | payload: Record<string, unknown>; |
| 119 | } |
| 120 |
| 121 | export class TestWorkspaceState { |
| 122 | readonly tasks = new Map<string, ColineTask>(); |
| 123 | readonly calendar = new Map<string, ColineCalendarEvent>(); |
| 124 | readonly messages = new Map<string, ColineMessage[]>(); |
| 125 | readonly files = new Map<string, TestFile>(); |
| 126 | readonly kv = new Map<string, unknown>(); |
| 127 | readonly recordRevisions = new Map<string, number>(); |
| 128 | readonly realtimeListeners = new Map< |
| 129 | string, |
| 130 | Set<(message: { event: string; data: unknown }) => void> |
| 131 | >(); |
| 132 | readonly records = new Map<string, Map<string, ColineRecordEnvelope<Record<string, unknown>>>>(); |
| 133 | readonly notifications: TestNotification[] = []; |
| 134 | readonly indexDocuments = new Map<string, TestIndexDocument>(); |
| 135 | readonly navigations: TestNavigationEvent[] = []; |
| 136 | readonly events: { kind: string; payload?: Record<string, unknown> }[] = []; |
| 137 | readonly published: { event: string; data: unknown }[] = []; |
| 138 | readonly netRequests: ColineNetFetchInput[] = []; |
| 139 | readonly jobs = new Map<string, TestJobRun>(); |
| 140 | readonly uploads = new Map<string, TestUpload>(); |
| 141 | readonly connections = new Map<string, { accountLabel: string | null; scopes: string[]; connectedAt: string }>(); |
| 142 |
| 143 | private fileCounter = 0; |
| 144 | private recordCounter = 0; |
| 145 | private jobCounter = 0; |
| 146 |
| 147 | nextJobId(): string { |
| 148 | this.jobCounter += 1; |
| 149 | return `job_test_${this.jobCounter}`; |
| 150 | } |
| 151 |
| 152 | nextFileId(): string { |
| 153 | this.fileCounter += 1; |
| 154 | return `file_test_${this.fileCounter}`; |
| 155 | } |
| 156 |
| 157 | nextRecordId(): string { |
| 158 | this.recordCounter += 1; |
| 159 | return `rec_test_${this.recordCounter}`; |
| 160 | } |
| 161 |
| 162 | filesByType(typeKey: string): TestFile[] { |
| 163 | return [...this.files.values()].filter((file) => file.typeKey === typeKey && !file.trashed); |
| 164 | } |
| 165 | } |
| 166 |
| 167 | export function createFakeCapabilities( |
| 168 | state: TestWorkspaceState, |
| 169 | options: Required< |
| 170 | Pick< |
| 171 | TestWorkspaceOptions, |
| 172 | "workspaceId" | "workspaceSlug" | "workspaceName" | "appKey" | "installId" |
| 173 | > |
| 174 | > & { |
| 175 | members: ColineMemberSummary[]; |
| 176 | actor: ColineActorRef; |
| 177 | onNetFetch: TestWorkspaceOptions["onNetFetch"]; |
| 178 | onAiGenerate: TestWorkspaceOptions["onAiGenerate"]; |
| 179 | aiModels?: TestWorkspaceOptions["aiModels"]; |
| 180 | onAiJob?: TestWorkspaceOptions["onAiJob"]; |
| 181 | pickers: NonNullable<TestWorkspaceOptions["pickers"]>; |
| 182 | manifest: ColineAppManifestV2; |
| 183 | /** Ceiling of the executing unit; batches with deletes need destructive. */ |
| 184 | destructiveAllowed: boolean; |
| 185 | /** The executing unit's effect; a job it enqueues may not exceed it. */ |
| 186 | effect?: ToolEffect; |
| 187 | /** Records created here belong to this actor (a site tool's visitor). */ |
| 188 | createdBy?: ColineActorRef; |
| 189 | }, |
| 190 | ): ColineCapabilities { |
| 191 | const now = () => new Date().toISOString(); |
| 192 | const fail = (code: string, message: string): never => { |
| 193 | throw Object.assign(new Error(message), { code }); |
| 194 | }; |
| 195 | const connectionStatus = (key: string): ColineConnectionStatus => { |
| 196 | const declared = options.manifest.connections.find((connection) => connection.key === key); |
| 197 | if (!declared) return fail("connection_not_found", `This app does not declare connection "${key}".`); |
| 198 | const made = state.connections.get(key); |
| 199 | return { |
| 200 | key, |
| 201 | name: declared.name, |
| 202 | scope: declared.scope, |
| 203 | connected: Boolean(made), |
| 204 | account: made ? { label: made.accountLabel } : null, |
| 205 | scopes: made?.scopes ?? [], |
| 206 | connectedAt: made?.connectedAt ?? null, |
| 207 | }; |
| 208 | }; |
| 209 | const files = { |
| 210 | readUrl: async (fileId: string) => { |
| 211 | const upload = state.uploads.get(fileId); |
| 212 | if (!upload) return fail("file_not_binary", "This file has no binary content."); |
| 213 | return { url: `memory://uploads/${fileId}`, mimeType: upload.mimeType }; |
| 214 | }, |
| 215 | }; |
| 216 |
| 217 | return { |
| 218 | ...createFakeWorkspaceCapabilities( |
| 219 | state, |
| 220 | options.actor.kind === "user" ? options.actor.userId : null, |
| 221 | ), |
| 222 | tools: { |
| 223 | invoke: async () => { |
| 224 | throw new Error("Use createTestWorkspace to invoke tools."); |
| 225 | }, |
| 226 | }, |
| 227 | workspace: { |
| 228 | get: async () => ({ |
| 229 | workspaceId: options.workspaceId, |
| 230 | workspaceSlug: options.workspaceSlug, |
| 231 | workspaceName: options.workspaceName, |
| 232 | }), |
| 233 | }, |
| 234 | members: { |
| 235 | list: async () => ({ members: options.members }), |
| 236 | get: async (userId) => options.members.find((member) => member.userId === userId) ?? null, |
| 237 | }, |
| 238 | files: { |
| 239 | readUrl: files.readUrl, |
| 240 | upload: async (input) => { |
| 241 | const bytes = await uploadDataToBytes(input.data); |
| 242 | if (bytes.byteLength > 25 * 1024 * 1024) |
| 243 | return fail("upload_too_large", "files.upload accepts up to 25 MB."); |
| 244 | const mimeType = input.mimeType ?? "application/octet-stream"; |
| 245 | const file: TestFile = { |
| 246 | fileId: state.nextFileId(), |
| 247 | name: input.name, |
| 248 | typeKey: "file", |
| 249 | driveId: input.driveId ?? "drive_test_app", |
| 250 | parentId: input.parentId ?? null, |
| 251 | version: 1, |
| 252 | createdAt: now(), |
| 253 | updatedAt: now(), |
| 254 | document: {}, |
| 255 | trashed: false, |
| 256 | }; |
| 257 | state.files.set(file.fileId, file); |
| 258 | state.uploads.set(file.fileId, { file, mimeType, bytes }); |
| 259 | return { ...structuredClone(file), mimeType, size: bytes.byteLength }; |
| 260 | }, |
| 261 | createUpload: async (input) => ({ |
| 262 | uploadId: `upload_${input.name}`, |
| 263 | url: `memory://upload/${encodeURIComponent(input.name)}`, |
| 264 | headers: { "content-type": input.mimeType }, |
| 265 | expiresAt: new Date(Date.now() + 3_600_000).toISOString(), |
| 266 | }), |
| 267 | completeUpload: async () => |
| 268 | fail("upload_not_found", "Direct uploads are not simulated; use files.upload in tests."), |
| 269 | move: async (fileId, destination) => { |
| 270 | const file = state.files.get(fileId) ?? fail("file_not_found", "File not found."); |
| 271 | file.driveId = destination.driveId; |
| 272 | file.parentId = destination.parentId ?? null; |
| 273 | file.updatedAt = now(); |
| 274 | return structuredClone(file); |
| 275 | }, |
| 276 | saveAs: async (fileId) => { |
| 277 | const destination = options.pickers.destination ? await options.pickers.destination() : null; |
| 278 | if (!destination) return null; |
| 279 | const file = state.files.get(fileId) ?? fail("file_not_found", "File not found."); |
| 280 | file.driveId = destination.driveId; |
| 281 | file.parentId = destination.parentId; |
| 282 | file.updatedAt = now(); |
| 283 | return structuredClone(file); |
| 284 | }, |
| 285 | preview: async (fileId) => { |
| 286 | const file = state.files.get(fileId) ?? fail("file_not_found", "File not found."); |
| 287 | const upload = state.uploads.get(fileId); |
| 288 | return { |
| 289 | fileId, |
| 290 | name: file.name, |
| 291 | typeKey: file.typeKey, |
| 292 | tree: null, |
| 293 | media: upload ? { url: `memory://uploads/${fileId}`, mimeType: upload.mimeType } : null, |
| 294 | href: null, |
| 295 | }; |
| 296 | }, |
| 297 | list: async (input) => { |
| 298 | let files = [...state.files.values()].filter((file) => !file.trashed); |
| 299 | if (input?.typeKey) files = files.filter((file) => file.typeKey === input.typeKey); |
| 300 | if (input?.driveId) files = files.filter((file) => file.driveId === input.driveId); |
| 301 | const start = input?.cursor |
| 302 | ? files.findIndex((file) => file.fileId === input.cursor) + 1 |
| 303 | : 0; |
| 304 | const limit = input?.limit ?? 50; |
| 305 | const page = files.slice(start, start + limit); |
| 306 | return { |
| 307 | files: structuredClone(page), |
| 308 | nextCursor: files.length > start + limit ? page.at(-1)!.fileId : null, |
| 309 | }; |
| 310 | }, |
| 311 | get: async (fileId) => state.files.get(fileId) ?? null, |
| 312 | create: async (input) => { |
| 313 | const file: TestFile = { |
| 314 | fileId: state.nextFileId(), |
| 315 | name: input.name, |
| 316 | typeKey: input.typeKey, |
| 317 | driveId: input.driveId ?? "drive_test_app", |
| 318 | parentId: input.parentId ?? null, |
| 319 | version: 1, |
| 320 | createdAt: now(), |
| 321 | updatedAt: now(), |
| 322 | document: input.document ?? {}, |
| 323 | trashed: false, |
| 324 | }; |
| 325 | state.files.set(file.fileId, file); |
| 326 | return file; |
| 327 | }, |
| 328 | update: async (fileId, input) => { |
| 329 | const file = state.files.get(fileId); |
| 330 | if (!file) throw new Error(`Test file not found: ${fileId}`); |
| 331 | if (input.name) file.name = input.name; |
| 332 | file.updatedAt = now(); |
| 333 | return file; |
| 334 | }, |
| 335 | trash: async (fileId) => { |
| 336 | const file = state.files.get(fileId); |
| 337 | if (!file) throw new Error(`Test file not found: ${fileId}`); |
| 338 | file.trashed = true; |
| 339 | }, |
| 340 | getDocument: async (fileId) => { |
| 341 | const file = state.files.get(fileId); |
| 342 | if (!file) throw new Error(`Test file not found: ${fileId}`); |
| 343 | return file.document; |
| 344 | }, |
| 345 | updateDocument: async (fileId, document, options) => { |
| 346 | const file = state.files.get(fileId); |
| 347 | if (!file) throw new Error(`Test file not found: ${fileId}`); |
| 348 | if (options?.expectedVersion !== undefined && options.expectedVersion !== file.version) |
| 349 | throw Object.assign(new Error("The document changed. Reload before saving."), { |
| 350 | code: "document_conflict", |
| 351 | }); |
| 352 | file.document = structuredClone(document); |
| 353 | file.version += 1; |
| 354 | file.updatedAt = now(); |
| 355 | return { version: file.version, updatedAt: file.updatedAt }; |
| 356 | }, |
| 357 | }, |
| 358 | drives: { |
| 359 | getAppDrive: async () => ({ driveId: "drive_test_app" }), |
| 360 | }, |
| 361 | storage: { |
| 362 | kv: { |
| 363 | get: async (key) => state.kv.get(key) ?? null, |
| 364 | set: async (key, value) => { |
| 365 | state.kv.set(key, value ?? null); |
| 366 | }, |
| 367 | delete: async (key) => { |
| 368 | state.kv.delete(key); |
| 369 | }, |
| 370 | list: async (input) => ({ |
| 371 | keys: [...state.kv.keys()] |
| 372 | .filter((key) => !input?.prefix || key.startsWith(input.prefix)) |
| 373 | .sort() |
| 374 | .slice(0, input?.limit ?? 200), |
| 375 | }), |
| 376 | }, |
| 377 | collection: <TData>(name: string) => |
| 378 | createFakeCollection<TData>(state, name, options.actor, options.installId, { |
| 379 | destructiveAllowed: options.destructiveAllowed, |
| 380 | ...(options.createdBy ? { createdBy: options.createdBy } : {}), |
| 381 | }), |
| 382 | batch: async (operations) => { |
| 383 | // Atomic across collections: snapshot every touched collection. |
| 384 | const names = [...new Set(operations.map((operation) => operation.collection))]; |
| 385 | const snapshots = new Map( |
| 386 | names.map((name) => [name, structuredClone([...(state.records.get(name) ?? new Map())])]), |
| 387 | ); |
| 388 | try { |
| 389 | const results = []; |
| 390 | for (const operation of operations) { |
| 391 | const { collection, ...rest } = operation; |
| 392 | const handle = createFakeCollection<Record<string, unknown>>( |
| 393 | state, |
| 394 | collection, |
| 395 | options.actor, |
| 396 | options.installId, |
| 397 | { |
| 398 | destructiveAllowed: options.destructiveAllowed, |
| 399 | ...(options.createdBy ? { createdBy: options.createdBy } : {}), |
| 400 | }, |
| 401 | ); |
| 402 | const { results: [result] } = await handle.batch([rest]); |
| 403 | results.push(result ?? null); |
| 404 | } |
| 405 | return { results }; |
| 406 | } catch (error) { |
| 407 | for (const [name, rows] of snapshots) state.records.set(name, new Map(rows)); |
| 408 | throw error; |
| 409 | } |
| 410 | }, |
| 411 | }, |
| 412 | jobs: { |
| 413 | enqueue: async (name, payload = {}, enqueueOptions = {}) => { |
| 414 | const declared = |
| 415 | options.manifest.jobs.find((job) => job.name === name) ?? |
| 416 | fail("job_not_found", `This app does not declare job "${name}".`); |
| 417 | // Same rule as production: a job may not exceed its enqueuer. |
| 418 | if ( |
| 419 | options.effect && |
| 420 | MUTATION_CLASS_RANK[EFFECT_CEILINGS[declared.effect].maxMutation] > |
| 421 | MUTATION_CLASS_RANK[EFFECT_CEILINGS[options.effect].maxMutation] |
| 422 | ) { |
| 423 | fail( |
| 424 | "effect_exceeds_caller", |
| 425 | `Job "${name}" is declared "${declared.effect}", which exceeds the "${options.effect}" effect of the code enqueueing it.`, |
| 426 | ); |
| 427 | } |
| 428 | // Like production, a key belongs to the principal that chose it: |
| 429 | // two members using "refresh" get their own runs. |
| 430 | const principal = options.actor.kind === "user" ? options.actor.userId : "app"; |
| 431 | const idempotencyKey = enqueueOptions.idempotencyKey ? `${principal}:${enqueueOptions.idempotencyKey}` : null; |
| 432 | if (idempotencyKey) { |
| 433 | const existing = [...state.jobs.values()].find((run) => run.idempotencyKey === idempotencyKey); |
| 434 | if (existing) return toJobRun(existing); |
| 435 | } |
| 436 | const runAt = enqueueOptions.runAt |
| 437 | ? new Date(enqueueOptions.runAt) |
| 438 | : new Date(Date.now() + (enqueueOptions.delaySeconds ?? 0) * 1000); |
| 439 | const run: TestJobRun = { |
| 440 | id: state.nextJobId(), |
| 441 | name, |
| 442 | payload: structuredClone(payload), |
| 443 | actor: options.actor, |
| 444 | status: "queued", |
| 445 | attempt: 0, |
| 446 | maxAttempts: declared.maxAttempts, |
| 447 | runAt: runAt.toISOString(), |
| 448 | createdAt: now(), |
| 449 | startedAt: null, |
| 450 | finishedAt: null, |
| 451 | checkpoint: null, |
| 452 | progress: null, |
| 453 | result: null, |
| 454 | error: null, |
| 455 | idempotencyKey, |
| 456 | }; |
| 457 | state.jobs.set(run.id, run); |
| 458 | return toJobRun(run); |
| 459 | }, |
| 460 | get: async (jobId) => { |
| 461 | const run = state.jobs.get(jobId); |
| 462 | return run ? toJobRun(run) : null; |
| 463 | }, |
| 464 | list: async (input) => { |
| 465 | const runs = [...state.jobs.values()] |
| 466 | .filter((run) => (!input?.name || run.name === input.name) && (!input?.status || run.status === input.status)) |
| 467 | .reverse(); |
| 468 | const offset = Number(input?.cursor ?? 0); |
| 469 | const limit = input?.limit ?? 50; |
| 470 | return { |
| 471 | runs: runs.slice(offset, offset + limit).map(toJobRun), |
| 472 | nextCursor: runs.length > offset + limit ? String(offset + limit) : null, |
| 473 | }; |
| 474 | }, |
| 475 | cancel: async (jobId) => { |
| 476 | const run = state.jobs.get(jobId) ?? fail("job_not_found", "Job run not found."); |
| 477 | if (run.status === "queued") { |
| 478 | run.status = "cancelled"; |
| 479 | run.finishedAt = now(); |
| 480 | } |
| 481 | return toJobRun(run); |
| 482 | }, |
| 483 | }, |
| 484 | connections: { |
| 485 | list: async () => ({ |
| 486 | connections: options.manifest.connections.map((connection) => connectionStatus(connection.key)), |
| 487 | }), |
| 488 | get: async (key) => connectionStatus(key), |
| 489 | connect: async (key) => { |
| 490 | connectionStatus(key); |
| 491 | if (!state.connections.has(key)) { |
| 492 | state.connections.set(key, { accountLabel: "test-account", scopes: [], connectedAt: now() }); |
| 493 | } |
| 494 | return connectionStatus(key); |
| 495 | }, |
| 496 | disconnect: async (key) => { |
| 497 | connectionStatus(key); |
| 498 | state.connections.delete(key); |
| 499 | }, |
| 500 | }, |
| 501 | endpoints: { |
| 502 | url: async (id) => { |
| 503 | if (!options.manifest.endpoints.some((endpoint) => endpoint.id === id)) |
| 504 | return fail("endpoint_not_found", `This app does not declare endpoint "${id}".`); |
| 505 | return { id, url: `https://coline.test/api/apps/endpoints/${options.installId}-${id}` }; |
| 506 | }, |
| 507 | list: async () => ({ |
| 508 | endpoints: options.manifest.endpoints.map((endpoint) => ({ |
| 509 | id: endpoint.id, |
| 510 | url: `https://coline.test/api/apps/endpoints/${options.installId}-${endpoint.id}`, |
| 511 | methods: endpoint.methods, |
| 512 | })), |
| 513 | }), |
| 514 | }, |
| 515 | search: { |
| 516 | query: async (input) => { |
| 517 | const query = input.query.toLowerCase(); |
| 518 | const matches = [...state.indexDocuments.values()].filter((doc) => |
| 519 | `${doc.title} ${doc.body}`.toLowerCase().includes(query), |
| 520 | ); |
| 521 | const offset = Number(input.cursor ?? 0), |
| 522 | limit = input.limit ?? 50; |
| 523 | return { |
| 524 | results: matches.slice(offset, offset + limit).map((doc) => ({ |
| 525 | documentKey: doc.documentKey, |
| 526 | documentType: doc.documentType, |
| 527 | title: doc.title, |
| 528 | snippet: doc.body, |
| 529 | url: null, |
| 530 | fileId: doc.fileId ?? null, |
| 531 | })), |
| 532 | nextCursor: matches.length > offset + limit ? String(offset + limit) : null, |
| 533 | }; |
| 534 | }, |
| 535 | index: { |
| 536 | upsert: async (input) => { |
| 537 | for (const document of input.documents) { |
| 538 | state.indexDocuments.set(document.documentKey, { |
| 539 | documentKey: document.documentKey, |
| 540 | documentType: document.documentType, |
| 541 | title: document.title, |
| 542 | body: document.body, |
| 543 | fileId: document.fileId, |
| 544 | }); |
| 545 | } |
| 546 | return { upserted: input.documents.length }; |
| 547 | }, |
| 548 | delete: async (input) => { |
| 549 | let deleted = 0; |
| 550 | for (const key of input.documentKeys) { |
| 551 | if (state.indexDocuments.delete(key)) deleted += 1; |
| 552 | } |
| 553 | return { deleted }; |
| 554 | }, |
| 555 | }, |
| 556 | }, |
| 557 | notifications: { |
| 558 | create: async (input) => { |
| 559 | state.notifications.push({ |
| 560 | channelKey: input.channelKey, |
| 561 | title: input.title, |
| 562 | body: input.body, |
| 563 | href: input.href, |
| 564 | recipients: input.recipients.map((recipient) => recipient.userId), |
| 565 | }); |
| 566 | }, |
| 567 | }, |
| 568 | ai: { |
| 569 | ...fakeAi(state, options.actor.kind === "user" ? options.actor.userId : null, options.aiModels ?? [], options.onAiJob), |
| 570 | generate: async (prompt) => ({ |
| 571 | text: options.onAiGenerate ? await options.onAiGenerate(prompt) : `echo: ${prompt}`, |
| 572 | }), |
| 573 | }, |
| 574 | net: { |
| 575 | fetch: async (input) => { |
| 576 | state.netRequests.push(input); |
| 577 | if (!options.onNetFetch) { |
| 578 | throw new Error("coline.net.fetch called in a test without an onNetFetch handler."); |
| 579 | } |
| 580 | return options.onNetFetch(input); |
| 581 | }, |
| 582 | }, |
| 583 | pickers: { |
| 584 | file: async () => (options.pickers.file ? options.pickers.file() : null), |
| 585 | member: async () => (options.pickers.member ? options.pickers.member() : null), |
| 586 | destination: async () => |
| 587 | options.pickers.destination ? options.pickers.destination() : null, |
| 588 | confirm: async () => (options.pickers.confirm ? options.pickers.confirm() : false), |
| 589 | }, |
| 590 | navigation: { |
| 591 | openFile: async (fileId) => { |
| 592 | state.navigations.push({ intent: "openFile", payload: { fileId } }); |
| 593 | }, |
| 594 | openAppHome: async () => { |
| 595 | state.navigations.push({ intent: "openAppHome", payload: {} }); |
| 596 | }, |
| 597 | navigate: async (href) => { |
| 598 | state.navigations.push({ intent: "navigate", payload: { href } }); |
| 599 | }, |
| 600 | openReference: async (reference) => { |
| 601 | state.navigations.push({ intent: "openReference", payload: { reference } }); |
| 602 | }, |
| 603 | }, |
| 604 | realtime: { |
| 605 | subscribe: async (event, handler) => { |
| 606 | const listeners = state.realtimeListeners.get(event) ?? new Set(); |
| 607 | listeners.add(handler); |
| 608 | state.realtimeListeners.set(event, listeners); |
| 609 | return { |
| 610 | unsubscribe: () => { |
| 611 | listeners.delete(handler); |
| 612 | }, |
| 613 | }; |
| 614 | }, |
| 615 | publish: async (event, data) => { |
| 616 | state.published.push({ event, data: data ?? null }); |
| 617 | for (const listener of state.realtimeListeners.get(event) ?? []) |
| 618 | listener({ event, data: data ?? null }); |
| 619 | return { delivered: true }; |
| 620 | }, |
| 621 | }, |
| 622 | events: { |
| 623 | emit: async (event, data) => { |
| 624 | state.events.push({ kind: event, ...(data ? { payload: data } : {}) }); |
| 625 | return { emitted: true }; |
| 626 | }, |
| 627 | }, |
| 628 | context: { |
| 629 | publish: async () => undefined, |
| 630 | clear: async () => undefined, |
| 631 | }, |
| 632 | }; |
| 633 | } |
| 634 |