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 | emitAmbientEventsInputSchema, |
| 7 | appPermissionSchema, |
| 8 | type AppPermission, |
| 9 | type BatchDeleteAppIndexDocumentsInput, |
| 10 | type BatchUpsertAppIndexDocumentsInput, |
| 11 | type ColineAppRegistrationPayload, |
| 12 | type CreateNotificationInputInput, |
| 13 | type EmitAmbientEventsInputInput, |
| 14 | } from "./manifest"; |
| 15 | import { ColineApiError } from "./errors"; |
| 16 |
| 17 | interface ApiErrorPayload { |
| 18 | error?: { |
| 19 | code?: string; |
| 20 | message?: string; |
| 21 | }; |
| 22 | } |
| 23 |
| 24 | async function parseJsonResponse<T>(response: Response): Promise<T> { |
| 25 | const payload = (await response.json().catch(() => null)) as T | null; |
| 26 |
| 27 | if (!response.ok) { |
| 28 | const errorMessage = |
| 29 | payload && |
| 30 | typeof payload === "object" && |
| 31 | "error_description" in payload && |
| 32 | typeof (payload as Record<string, unknown>)["error_description"] === "string" |
| 33 | ? ((payload as Record<string, unknown>)["error_description"] as string) |
| 34 | : `Request failed (${response.status}).`; |
| 35 |
| 36 | throw new ColineApiError({ |
| 37 | message: errorMessage, |
| 38 | type: "oauth", |
| 39 | status: response.status, |
| 40 | code: |
| 41 | payload && |
| 42 | typeof payload === "object" && |
| 43 | "error" in payload && |
| 44 | typeof (payload as Record<string, unknown>)["error"] === "string" |
| 45 | ? ((payload as Record<string, unknown>)["error"] as string) |
| 46 | : null, |
| 47 | }); |
| 48 | } |
| 49 |
| 50 | if (!payload) { |
| 51 | throw new ColineApiError({ |
| 52 | message: "Invalid JSON response.", |
| 53 | type: "oauth", |
| 54 | status: response.status, |
| 55 | }); |
| 56 | } |
| 57 |
| 58 | return payload; |
| 59 | } |
| 60 |
| 61 | async function parseApiResponse<T>(response: Response): Promise<T> { |
| 62 | const payload = (await response.json().catch(() => null)) as |
| 63 | | { data?: T; error?: ApiErrorPayload["error"] } |
| 64 | | null; |
| 65 |
| 66 | if (!response.ok) { |
| 67 | throw new ColineApiError({ |
| 68 | message: payload?.error?.message ?? `Request failed (${response.status}).`, |
| 69 | type: "api", |
| 70 | status: response.status, |
| 71 | code: payload?.error?.code ?? null, |
| 72 | }); |
| 73 | } |
| 74 |
| 75 | if (!payload || !("data" in payload)) { |
| 76 | throw new ColineApiError({ |
| 77 | message: "Invalid API response.", |
| 78 | type: "api", |
| 79 | status: response.status, |
| 80 | }); |
| 81 | } |
| 82 |
| 83 | return payload.data as T; |
| 84 | } |
| 85 |
| 86 | export interface ColineApiClientOptions { |
| 87 | baseUrl: string; |
| 88 | apiKey?: string; |
| 89 | fetch?: typeof fetch; |
| 90 | headers?: HeadersInit; |
| 91 | } |
| 92 |
| 93 | export interface RegisteredAppRecord { |
| 94 | appId: string; |
| 95 | appKey: string; |
| 96 | name: string; |
| 97 | description: string | null; |
| 98 | iconUrl: string | null; |
| 99 | status: "draft" | "active" | "disabled" | "archived"; |
| 100 | ownerUserId: string | null; |
| 101 | latestPublishedVersion: string | null; |
| 102 | } |
| 103 |
| 104 | export interface RegisteredAppDetail extends RegisteredAppRecord { |
| 105 | latestPublishedVersionId: string | null; |
| 106 | } |
| 107 |
| 108 | export interface RegisteredAppVersionSummary { |
| 109 | versionId: string; |
| 110 | version: string; |
| 111 | status: "draft" | "published" | "deprecated"; |
| 112 | apiBaseUrl: string; |
| 113 | permissions: string[]; |
| 114 | fileTypes: Array<{ |
| 115 | typeKey: string; |
| 116 | name: string; |
| 117 | description: string | null; |
| 118 | }>; |
| 119 | createdAt: string; |
| 120 | updatedAt: string; |
| 121 | } |
| 122 |
| 123 | export interface WorkspaceInstalledApp { |
| 124 | installId: string; |
| 125 | appId: string; |
| 126 | appKey: string; |
| 127 | name: string; |
| 128 | description: string | null; |
| 129 | iconUrl: string | null; |
| 130 | status: "active" | "suspended" | "revoked"; |
| 131 | installScope: "workspace" | "user"; |
| 132 | scopeSubjectId: string; |
| 133 | version: string | null; |
| 134 | } |
| 135 |
| 136 | export interface WorkspaceAppCatalogItem { |
| 137 | appId: string; |
| 138 | appKey: string; |
| 139 | name: string; |
| 140 | description: string | null; |
| 141 | iconUrl: string | null; |
| 142 | status: "draft" | "active" | "disabled" | "archived"; |
| 143 | latestPublishedVersion: string | null; |
| 144 | latestPublishedVersionId: string | null; |
| 145 | isInstalled: boolean; |
| 146 | } |
| 147 |
| 148 | export interface WorkspaceAppsResponse { |
| 149 | installedApps: WorkspaceInstalledApp[]; |
| 150 | catalog: WorkspaceAppCatalogItem[]; |
| 151 | permissions: { |
| 152 | canManageApps: boolean; |
| 153 | }; |
| 154 | } |
| 155 |
| 156 | export interface InstallWorkspaceAppInput { |
| 157 | appId: string; |
| 158 | pinnedVersionId?: string; |
| 159 | grantedPermissions?: AppPermission[]; |
| 160 | } |
| 161 |
| 162 | export interface InstallWorkspaceAppResponse { |
| 163 | installId: string; |
| 164 | appId: string; |
| 165 | appKey: string; |
| 166 | version: string; |
| 167 | grantedPermissions: AppPermission[]; |
| 168 | } |
| 169 |
| 170 | export interface WorkspaceAppPermissionsResponse { |
| 171 | install: WorkspaceInstalledApp; |
| 172 | availablePermissions: string[]; |
| 173 | grantedPermissions: string[]; |
| 174 | permissions: { |
| 175 | canManageApps: boolean; |
| 176 | }; |
| 177 | } |
| 178 |
| 179 | export interface WorkspaceInstalledAppResponse { |
| 180 | install: WorkspaceInstalledApp; |
| 181 | permissions: { |
| 182 | canManageApps: boolean; |
| 183 | }; |
| 184 | } |
| 185 |
| 186 | export interface AppFileDocumentResponse { |
| 187 | file: { |
| 188 | id: string; |
| 189 | name: string; |
| 190 | fileType: string; |
| 191 | appKey: string; |
| 192 | appName: string; |
| 193 | typeLabel: string; |
| 194 | openHref: string; |
| 195 | updatedAt: string; |
| 196 | }; |
| 197 | document: Record<string, unknown>; |
| 198 | version: number; |
| 199 | capabilities: { |
| 200 | canRead: boolean; |
| 201 | canWrite: boolean; |
| 202 | canManage: boolean; |
| 203 | }; |
| 204 | } |
| 205 |
| 206 | export interface TabModelRecord { |
| 207 | id: string; |
| 208 | object: "model"; |
| 209 | created: number; |
| 210 | owned_by: string; |
| 211 | providerModelId: string; |
| 212 | pricing: { |
| 213 | inputPerMillionUsd: number; |
| 214 | outputPerMillionUsd: number; |
| 215 | }; |
| 216 | capabilities: { |
| 217 | streaming: boolean; |
| 218 | surfaces: string[]; |
| 219 | }; |
| 220 | } |
| 221 |
| 222 | export interface OAuthTokenResponse { |
| 223 | access_token: string; |
| 224 | token_type: "Bearer"; |
| 225 | expires_in: number; |
| 226 | refresh_token: string; |
| 227 | scope: string; |
| 228 | } |
| 229 |
| 230 | export interface OAuthUserInfoResponse { |
| 231 | sub: string; |
| 232 | email: string; |
| 233 | email_verified: boolean; |
| 234 | name: string; |
| 235 | given_name: string | null; |
| 236 | family_name: string | null; |
| 237 | picture: string | null; |
| 238 | preferred_username: string | null; |
| 239 | scope: string; |
| 240 | } |
| 241 |
| 242 | export interface UpdateWorkspaceAppPermissionsInput { |
| 243 | grantedPermissions: AppPermission[]; |
| 244 | } |
| 245 |
| 246 | function joinUrl(baseUrl: string, path: string): string { |
| 247 | return `${baseUrl.replace(/\/+$/, "")}${path}`; |
| 248 | } |
| 249 |
| 250 | export class ColineApiClient { |
| 251 | private readonly baseUrl: string; |
| 252 | private readonly apiKey: string | undefined; |
| 253 | private readonly fetchImpl: typeof fetch; |
| 254 | private readonly defaultHeaders: HeadersInit | undefined; |
| 255 |
| 256 | constructor(options: ColineApiClientOptions) { |
| 257 | this.baseUrl = options.baseUrl; |
| 258 | this.apiKey = options.apiKey; |
| 259 | this.fetchImpl = options.fetch ?? fetch; |
| 260 | this.defaultHeaders = options.headers; |
| 261 | } |
| 262 |
| 263 | private async request<T>(path: string, init?: RequestInit): Promise<T> { |
| 264 | const headers = new Headers(this.defaultHeaders); |
| 265 | const requestHeaders = new Headers(init?.headers); |
| 266 | requestHeaders.forEach((value, key) => headers.set(key, value)); |
| 267 |
| 268 | if (!headers.has("Content-Type") && init?.body) { |
| 269 | headers.set("Content-Type", "application/json"); |
| 270 | } |
| 271 |
| 272 | if (this.apiKey && !headers.has("Authorization")) { |
| 273 | headers.set("Authorization", `Bearer ${this.apiKey}`); |
| 274 | } |
| 275 |
| 276 | const response = await this.fetchImpl(joinUrl(this.baseUrl, path), { |
| 277 | ...init, |
| 278 | headers, |
| 279 | }); |
| 280 |
| 281 | return parseApiResponse<T>(response); |
| 282 | } |
| 283 |
| 284 | withApiKey(apiKey: string): ColineApiClient { |
| 285 | const options: ColineApiClientOptions = { |
| 286 | baseUrl: this.baseUrl, |
| 287 | apiKey, |
| 288 | fetch: this.fetchImpl, |
| 289 | }; |
| 290 |
| 291 | if (this.defaultHeaders !== undefined) { |
| 292 | options.headers = this.defaultHeaders; |
| 293 | } |
| 294 |
| 295 | return new ColineApiClient(options); |
| 296 | } |
| 297 |
| 298 | withHeaders(headers: HeadersInit): ColineApiClient { |
| 299 | const mergedHeaders = new Headers(this.defaultHeaders); |
| 300 | new Headers(headers).forEach((value, key) => mergedHeaders.set(key, value)); |
| 301 |
| 302 | const options: ColineApiClientOptions = { |
| 303 | baseUrl: this.baseUrl, |
| 304 | fetch: this.fetchImpl, |
| 305 | headers: mergedHeaders, |
| 306 | }; |
| 307 |
| 308 | if (this.apiKey !== undefined) { |
| 309 | options.apiKey = this.apiKey; |
| 310 | } |
| 311 |
| 312 | return new ColineApiClient(options); |
| 313 | } |
| 314 |
| 315 | buildLoginWithColineAuthorizeUrl(input: { |
| 316 | clientId: string; |
| 317 | redirectUri: string; |
| 318 | scope?: string; |
| 319 | state?: string; |
| 320 | codeChallenge?: string; |
| 321 | codeChallengeMethod?: "S256" | "plain"; |
| 322 | }): string { |
| 323 | const url = new URL("/api/v1/oauth/authorize", this.baseUrl); |
| 324 | url.searchParams.set("response_type", "code"); |
| 325 | url.searchParams.set("client_id", input.clientId); |
| 326 | url.searchParams.set("redirect_uri", input.redirectUri); |
| 327 | if (input.scope) { |
| 328 | url.searchParams.set("scope", input.scope); |
| 329 | } |
| 330 | if (input.state) { |
| 331 | url.searchParams.set("state", input.state); |
| 332 | } |
| 333 | if (input.codeChallenge) { |
| 334 | url.searchParams.set("code_challenge", input.codeChallenge); |
| 335 | } |
| 336 | if (input.codeChallengeMethod) { |
| 337 | url.searchParams.set("code_challenge_method", input.codeChallengeMethod); |
| 338 | } |
| 339 | return url.toString(); |
| 340 | } |
| 341 |
| 342 | async listApps(): Promise<{ apps: RegisteredAppRecord[] }> { |
| 343 | return this.request<{ apps: RegisteredAppRecord[] }>("/api/v1/apps"); |
| 344 | } |
| 345 |
| 346 | async getApp(appKey: string): Promise<{ app: RegisteredAppDetail }> { |
| 347 | return this.request<{ app: RegisteredAppDetail }>(`/api/v1/apps/${appKey}`); |
| 348 | } |
| 349 |
| 350 | async listAppVersions( |
| 351 | appKey: string, |
| 352 | ): Promise<{ versions: RegisteredAppVersionSummary[] }> { |
| 353 | return this.request<{ versions: RegisteredAppVersionSummary[] }>( |
| 354 | `/api/v1/apps/${appKey}/versions`, |
| 355 | ); |
| 356 | } |
| 357 |
| 358 | async registerApp( |
| 359 | payload: ColineAppRegistrationPayload, |
| 360 | ): Promise<{ appId: string; appKey: string; versionId: string; version: string }> { |
| 361 | const body = colineAppRegistrationPayloadSchema.parse(payload); |
| 362 |
| 363 | return this.request<{ |
| 364 | appId: string; |
| 365 | appKey: string; |
| 366 | versionId: string; |
| 367 | version: string; |
| 368 | }>("/api/apps", { |
| 369 | method: "POST", |
| 370 | body: JSON.stringify(body), |
| 371 | }); |
| 372 | } |
| 373 |
| 374 | async listWorkspaceApps(workspaceSlug: string): Promise<WorkspaceAppsResponse> { |
| 375 | return this.request<WorkspaceAppsResponse>( |
| 376 | `/api/v1/workspaces/${workspaceSlug}/apps`, |
| 377 | ); |
| 378 | } |
| 379 |
| 380 | async installWorkspaceApp( |
| 381 | workspaceSlug: string, |
| 382 | input: InstallWorkspaceAppInput, |
| 383 | ): Promise<InstallWorkspaceAppResponse> { |
| 384 | const grantedPermissions = input.grantedPermissions |
| 385 | ? input.grantedPermissions.map((permission) => |
| 386 | appPermissionSchema.parse(permission), |
| 387 | ) |
| 388 | : undefined; |
| 389 |
| 390 | return this.request<InstallWorkspaceAppResponse>( |
| 391 | `/api/v1/workspaces/${workspaceSlug}/apps`, |
| 392 | { |
| 393 | method: "POST", |
| 394 | body: JSON.stringify({ |
| 395 | appId: input.appId, |
| 396 | ...(input.pinnedVersionId |
| 397 | ? { pinnedVersionId: input.pinnedVersionId } |
| 398 | : {}), |
| 399 | ...(grantedPermissions ? { grantedPermissions } : {}), |
| 400 | }), |
| 401 | }, |
| 402 | ); |
| 403 | } |
| 404 |
| 405 | async getWorkspaceAppPermissions( |
| 406 | workspaceSlug: string, |
| 407 | appKey: string, |
| 408 | ): Promise<WorkspaceAppPermissionsResponse> { |
| 409 | return this.request<WorkspaceAppPermissionsResponse>( |
| 410 | `/api/v1/workspaces/${workspaceSlug}/apps/${appKey}/permissions`, |
| 411 | ); |
| 412 | } |
| 413 |
| 414 | async getWorkspaceInstalledApp( |
| 415 | workspaceSlug: string, |
| 416 | appKey: string, |
| 417 | ): Promise<WorkspaceInstalledAppResponse> { |
| 418 | return this.request<WorkspaceInstalledAppResponse>( |
| 419 | `/api/v1/workspaces/${workspaceSlug}/apps/${appKey}`, |
| 420 | ); |
| 421 | } |
| 422 |
| 423 | async updateWorkspaceAppPermissions( |
| 424 | workspaceSlug: string, |
| 425 | appKey: string, |
| 426 | input: UpdateWorkspaceAppPermissionsInput, |
| 427 | ): Promise<WorkspaceAppPermissionsResponse> { |
| 428 | return this.request<WorkspaceAppPermissionsResponse>( |
| 429 | `/api/v1/workspaces/${workspaceSlug}/apps/${appKey}/permissions`, |
| 430 | { |
| 431 | method: "PUT", |
| 432 | body: JSON.stringify({ |
| 433 | grantedPermissions: input.grantedPermissions.map((permission) => |
| 434 | appPermissionSchema.parse(permission), |
| 435 | ), |
| 436 | }), |
| 437 | }, |
| 438 | ); |
| 439 | } |
| 440 |
| 441 | async uninstallWorkspaceApp( |
| 442 | workspaceSlug: string, |
| 443 | appKey: string, |
| 444 | ): Promise<{ ok: true }> { |
| 445 | return this.request<{ ok: true }>( |
| 446 | `/api/v1/workspaces/${workspaceSlug}/apps/${appKey}`, |
| 447 | { |
| 448 | method: "DELETE", |
| 449 | }, |
| 450 | ); |
| 451 | } |
| 452 |
| 453 | async emitAppAmbientEvents( |
| 454 | workspaceSlug: string, |
| 455 | appKey: string, |
| 456 | input: EmitAmbientEventsInputInput, |
| 457 | ): Promise<{ events: Array<{ id: string; dedupeKey: string }> }> { |
| 458 | const body = emitAmbientEventsInputSchema.parse(input); |
| 459 |
| 460 | return this.request<{ events: Array<{ id: string; dedupeKey: string }> }>( |
| 461 | `/api/v1/workspaces/${workspaceSlug}/apps/${appKey}/ambient/events`, |
| 462 | { |
| 463 | method: "POST", |
| 464 | body: JSON.stringify(body), |
| 465 | }, |
| 466 | ); |
| 467 | } |
| 468 |
| 469 | async createAppNotification( |
| 470 | workspaceSlug: string, |
| 471 | appKey: string, |
| 472 | input: CreateNotificationInputInput, |
| 473 | ): Promise<{ ok: true }> { |
| 474 | const body = createNotificationInputSchema.parse(input); |
| 475 |
| 476 | return this.request<{ ok: true }>( |
| 477 | `/api/v1/workspaces/${workspaceSlug}/apps/${appKey}/notifications`, |
| 478 | { |
| 479 | method: "POST", |
| 480 | body: JSON.stringify(body), |
| 481 | }, |
| 482 | ); |
| 483 | } |
| 484 |
| 485 | async upsertAppIndexDocuments( |
| 486 | workspaceSlug: string, |
| 487 | appKey: string, |
| 488 | input: BatchUpsertAppIndexDocumentsInput, |
| 489 | ): Promise<{ documents: Array<{ id: string; documentKey: string; visibilityMode: string }> }> { |
| 490 | const body = batchUpsertAppIndexDocumentsSchema.parse(input); |
| 491 |
| 492 | return this.request<{ |
| 493 | documents: Array<{ id: string; documentKey: string; visibilityMode: string }>; |
| 494 | }>(`/api/v1/workspaces/${workspaceSlug}/apps/${appKey}/index-documents`, { |
| 495 | method: "POST", |
| 496 | body: JSON.stringify(body), |
| 497 | }); |
| 498 | } |
| 499 |
| 500 | async deleteAppIndexDocuments( |
| 501 | workspaceSlug: string, |
| 502 | appKey: string, |
| 503 | input: BatchDeleteAppIndexDocumentsInput, |
| 504 | ): Promise<{ deleted: Array<{ id: string; documentKey: string }> }> { |
| 505 | const body = batchDeleteAppIndexDocumentsSchema.parse(input); |
| 506 |
| 507 | return this.request<{ deleted: Array<{ id: string; documentKey: string }> }>( |
| 508 | `/api/v1/workspaces/${workspaceSlug}/apps/${appKey}/index-documents`, |
| 509 | { |
| 510 | method: "DELETE", |
| 511 | body: JSON.stringify(body), |
| 512 | }, |
| 513 | ); |
| 514 | } |
| 515 |
| 516 | async getAppFileDocument( |
| 517 | workspaceSlug: string, |
| 518 | appKey: string, |
| 519 | fileId: string, |
| 520 | ): Promise<AppFileDocumentResponse> { |
| 521 | return this.request<AppFileDocumentResponse>( |
| 522 | `/api/v1/workspaces/${workspaceSlug}/apps/${appKey}/files/${fileId}`, |
| 523 | ); |
| 524 | } |
| 525 |
| 526 | async updateAppFileDocument( |
| 527 | workspaceSlug: string, |
| 528 | appKey: string, |
| 529 | fileId: string, |
| 530 | document: Record<string, unknown>, |
| 531 | ): Promise<{ document: Record<string, unknown>; version: number; updatedAt: string }> { |
| 532 | return this.request<{ |
| 533 | document: Record<string, unknown>; |
| 534 | version: number; |
| 535 | updatedAt: string; |
| 536 | }>(`/api/v1/workspaces/${workspaceSlug}/apps/${appKey}/files/${fileId}`, { |
| 537 | method: "PATCH", |
| 538 | body: JSON.stringify({ document }), |
| 539 | }); |
| 540 | } |
| 541 |
| 542 | async listTabModels(): Promise<{ object: "list"; data: TabModelRecord[] }> { |
| 543 | return this.request<{ object: "list"; data: TabModelRecord[] }>( |
| 544 | "/api/v1/tab/models", |
| 545 | ); |
| 546 | } |
| 547 |
| 548 | async createTabChatCompletion(input: { |
| 549 | model: string; |
| 550 | stream?: boolean; |
| 551 | tab_context: Record<string, unknown>; |
| 552 | messages?: Array<{ role?: string; content?: string }>; |
| 553 | }): Promise<{ |
| 554 | id: string; |
| 555 | object: "chat.completion"; |
| 556 | created: number; |
| 557 | model: string; |
| 558 | choices: Array<{ |
| 559 | index: number; |
| 560 | message: { role: "assistant"; content: string }; |
| 561 | finish_reason: "stop"; |
| 562 | }>; |
| 563 | usage: { |
| 564 | prompt_tokens: number; |
| 565 | completion_tokens: number; |
| 566 | total_tokens: number; |
| 567 | }; |
| 568 | }> { |
| 569 | return this.request("/api/v1/tab/chat/completions", { |
| 570 | method: "POST", |
| 571 | body: JSON.stringify(input), |
| 572 | }); |
| 573 | } |
| 574 |
| 575 | async exchangeOAuthCode(input: { |
| 576 | clientId: string; |
| 577 | clientSecret: string; |
| 578 | code: string; |
| 579 | redirectUri: string; |
| 580 | codeVerifier?: string; |
| 581 | }): Promise<OAuthTokenResponse> { |
| 582 | const response = await this.fetchImpl(joinUrl(this.baseUrl, "/api/v1/oauth/token"), { |
| 583 | method: "POST", |
| 584 | headers: { |
| 585 | "Content-Type": "application/json", |
| 586 | }, |
| 587 | body: JSON.stringify({ |
| 588 | grant_type: "authorization_code", |
| 589 | client_id: input.clientId, |
| 590 | client_secret: input.clientSecret, |
| 591 | code: input.code, |
| 592 | redirect_uri: input.redirectUri, |
| 593 | ...(input.codeVerifier ? { code_verifier: input.codeVerifier } : {}), |
| 594 | }), |
| 595 | }); |
| 596 |
| 597 | return parseJsonResponse<OAuthTokenResponse>(response); |
| 598 | } |
| 599 |
| 600 | async getOAuthUserInfo(accessToken: string): Promise<OAuthUserInfoResponse> { |
| 601 | const response = await this.fetchImpl(joinUrl(this.baseUrl, "/api/v1/oauth/userinfo"), { |
| 602 | method: "GET", |
| 603 | headers: { |
| 604 | Authorization: `Bearer ${accessToken}`, |
| 605 | }, |
| 606 | }); |
| 607 |
| 608 | return parseJsonResponse<OAuthUserInfoResponse>(response); |
| 609 | } |
| 610 | } |
| 611 |