@cogover/sdk 0.12.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2944 +0,0 @@
1
- # API reference: `@cogover/sdk`
2
-
3
- `@cogover/sdk` is the public TypeScript contract for developing Custom Backend
4
- Modules on Cogover. Cogover authentication credentials are never exposed to
5
- module code; capability calls are restricted by the permissions and limits
6
- configured for the project.
7
-
8
- ## `defineScript`
9
-
10
- `defineScript<Input, Output>(handler)` wraps an async Cogover script. It parses
11
- the input JSON, supplies `input`, `request`, `invocation`, `response`, `data`, `schema`, `log`, `state`, `locks`,
12
- `push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, and `org`, awaits the handler, and serializes its
13
- result.
14
-
15
- ```typescript
16
- function defineScript<
17
- Input = unknown,
18
- Output = unknown,
19
- Schema extends object = EffectiveWorkspaceObjects,
20
- >(handler: ScriptHandler<Input, Output, Schema>): SandboxHandler;
21
- ```
22
-
23
- The related public types are:
24
-
25
- ```typescript
26
- type SandboxHandler = (inputJson: string) => Promise<string | null>;
27
-
28
- type ScriptHandler<Input, Output, Schema extends object = EffectiveWorkspaceObjects> =
29
- (context: ScriptContext<Input, Schema>) =>
30
- Output | ScriptResponse<unknown> | null |
31
- Promise<Output | ScriptResponse<unknown> | null>;
32
-
33
- interface ScriptContext<Input, Schema extends object = EffectiveWorkspaceObjects> {
34
- readonly input: Input;
35
- readonly request: ScriptRequest<Input>;
36
- readonly invocation: InvocationContext;
37
- readonly data: DataApi<Schema>;
38
- readonly schema: SchemaApi<Schema>;
39
- readonly log: ScriptLogger;
40
- readonly response: ResponseApi;
41
- readonly state: ProjectState;
42
- readonly locks: DistributedLocks;
43
- readonly push: PushApi<Schema>;
44
- readonly notifications: NotificationsApi;
45
- readonly email: EmailApi<Schema>;
46
- readonly jobs: JobsApi;
47
- readonly secrets: SecretsApi;
48
- readonly crypto: CryptoApi;
49
- readonly org: OrgApi;
50
- }
51
- ```
52
-
53
- `defineScript` rejects a non-function handler with `ValidationError`. The returned
54
- handler rejects invalid input JSON and values that cannot be serialized to JSON.
55
- Returning `null` produces a null handler result; returning `undefined` is invalid.
56
-
57
- ## HTTP routers and request context
58
-
59
- `ScriptContext<TInput, TSchema>` provides `input`, `request`, `invocation`, `response`, `data`, `schema`,
60
- `log`, `state`, `locks`, `push`, `notifications`, `email`, `jobs`, `secrets`, `crypto`, and `org` to both script
61
- and route handlers. `input`
62
- preserves the invocation input. Prefer `request.body` for business data: it excludes invocation
63
- metadata and transport/authentication fields removed by Cogover.
64
-
65
- ```typescript
66
- type RequestMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
67
- type ScriptQuery = Readonly<Record<string, string | readonly string[]>>;
68
- type ScriptHeaders = Readonly<Record<string, string>>;
69
- type ScriptPathParams = Readonly<Record<string, string>>;
70
-
71
- interface ScriptRequest<TBody = unknown> {
72
- readonly method: RequestMethod;
73
- readonly path: string; // Relative to /api/v1/ts-projects/{projectSlug}
74
- readonly params: ScriptPathParams;
75
- readonly query: ScriptQuery;
76
- readonly headers: ScriptHeaders;
77
- readonly body: TBody;
78
- readonly rawBody?: string; // Webhook calls only
79
- readonly contentType?: string; // Webhook calls only
80
- }
81
- ```
82
-
83
- The descriptor and metadata maps are frozen; its body is not deeply frozen. Method,
84
- path, query, and allowlisted headers come from Cogover, not from business fields.
85
- Repeated query names become readonly arrays. Header names are lower-case and
86
- credentials such as `authorization` and `cookie` are never exposed. Dynamic path
87
- parameters are percent-decoded after safe route matching. TypeScript types do not
88
- validate runtime business input.
89
-
90
- `rawBody` and `contentType` are present only for a call that reached the project
91
- through an inbound webhook (see [Inbound webhooks](#inbound-webhooks)): `rawBody`
92
- is the request body exactly as received, as a UTF-8 string, and `contentType` is
93
- the request's `Content-Type` header. For every other call both fields are absent.
94
-
95
- ## Invocation identity and workspace
96
-
97
- `context.invocation` is a synchronous, immutable snapshot built from metadata that
98
- Cogover already authenticated and loaded for the current execution. Reading it
99
- does not make a data API request.
100
-
101
- ```typescript
102
- type InvocationContext = UserInvocationContext | SystemInvocationContext | InboundInvocationContext;
103
-
104
- interface CurrentWorkspace {
105
- readonly id: string;
106
- readonly name?: string;
107
- readonly domain?: string;
108
- readonly language?: string;
109
- readonly timezone?: string;
110
- readonly dateFormat?: string;
111
- readonly timeFormat?: string;
112
- readonly numberFormat?: string;
113
- }
114
-
115
- interface CurrentWorkspaceRole {
116
- readonly id: string;
117
- readonly name: string;
118
- }
119
-
120
- interface CurrentWorkspaceMembership {
121
- readonly personnelId?: string;
122
- readonly language?: string;
123
- readonly timezone?: string;
124
- readonly isSuperAdmin: boolean; // Holds the workspace's Super Admin role
125
- readonly roles: readonly CurrentWorkspaceRole[]; // Sorted by name
126
- }
127
-
128
- interface CurrentUser {
129
- readonly accountId: string;
130
- readonly email?: string;
131
- readonly firstName?: string;
132
- readonly lastName?: string;
133
- readonly avatar?: string;
134
- readonly language?: string;
135
- readonly timezone?: string;
136
- readonly membership: CurrentWorkspaceMembership;
137
- }
138
-
139
- interface UserInvocationContext {
140
- readonly identity: "user";
141
- readonly workspace: CurrentWorkspace;
142
- readonly user: CurrentUser;
143
- }
144
-
145
- interface SystemInvocationContext {
146
- readonly identity: "system";
147
- readonly workspace: CurrentWorkspace;
148
- readonly user: null;
149
- }
150
-
151
- interface InboundInvocationContext {
152
- readonly identity: "inbound";
153
- readonly workspace: CurrentWorkspace;
154
- readonly user: null;
155
- readonly inbound: {
156
- readonly id: string; // Part of the webhook URL
157
- readonly name: string;
158
- readonly mode: "KEY" | "HMAC"; // How the call was authenticated
159
- };
160
- }
161
- ```
162
-
163
- All fields are readonly. Optional profile and workspace fields may be absent, so
164
- scripts must not assume that they contain a value.
165
-
166
- `identity` is `"user"` for a call made by an authenticated Workspace user,
167
- `"system"` for an execution without a user, such as a scheduled job, and
168
- `"inbound"` for a webhook call authenticated by one of the project's inbound
169
- accesses (see [Inbound webhooks](#inbound-webhooks)). An inbound invocation has no
170
- user; `inbound` identifies the inbound access that authenticated the call.
171
-
172
- ```typescript
173
- export default defineScript(({ invocation }) => {
174
- if (invocation.identity === "system") {
175
- return {workspaceId: invocation.workspace.id, user: null};
176
- }
177
- if (invocation.identity === "inbound") {
178
- return {workspaceId: invocation.workspace.id, inbound: invocation.inbound.name};
179
- }
180
- return {
181
- workspaceId: invocation.workspace.id,
182
- accountId: invocation.user.accountId,
183
- personnelId: invocation.user.membership.personnelId,
184
- };
185
- });
186
- ```
187
-
188
- Cogover ignores caller-supplied invocation metadata and creates this snapshot from
189
- the authenticated request context. Raw authentication data, tokens, inbound keys,
190
- and credentials are not included. A handler called outside Cogover has no
191
- authenticated invocation snapshot.
192
-
193
- ### Workspace roles of the current user
194
-
195
- `user.membership` describes the caller's membership in the current workspace:
196
-
197
- - `isSuperAdmin` is `true` when one of the user's roles is the workspace's
198
- highest administrator (Super Admin) role, otherwise `false`.
199
- - `roles` lists the roles assigned to the user in the current workspace, sorted
200
- by name. Each `CurrentWorkspaceRole` has only an `id` and a `name`; the list is
201
- empty when the user has no role. Role permissions are not exposed.
202
-
203
- Compare roles by `id`: a role can be renamed, and the same role name has a
204
- different `id` in each workspace. Record and field access is still enforced by
205
- Cogover under the user's identity, so use these fields for business rules, such
206
- as who may approve an order, not as a replacement for security rules.
207
-
208
- ```typescript
209
- const APPROVER_ROLE_ID = "RO6P2N1K9X4A";
210
-
211
- export default defineScript(({ invocation }) => {
212
- const user = invocation.user;
213
- const canApprove = user !== null && (user.membership.isSuperAdmin
214
- || user.membership.roles.some((role) => role.id === APPROVER_ROLE_ID));
215
- return {canApprove};
216
- });
217
- ```
218
-
219
- HTTP invocations reflect the user's roles at the time of the request. Record
220
- triggers and background jobs may see a role change up to about one minute late.
221
- In local development with the Cogover Dev CLI, the values are captured when the
222
- development session starts; restart `cogover-dev` to pick up role changes. A
223
- `system` or `inbound` invocation has `user: null` and therefore no membership.
224
-
225
- ### `createRouter<TSchema = EffectiveWorkspaceObjects>(): ScriptRouter<TSchema>`
226
-
227
- Creates an independent router. `TSchema extends object` defaults to the effective
228
- workspace schema, preserving `WorkspaceObjects` augmentation for data and schema
229
- APIs. Routes match a method and case-sensitive static or dynamic path; static routes
230
- take precedence over dynamic routes. `/` addresses
231
- the canonical project URL without a route suffix.
232
- `/index` is a separate route, registered explicitly. `defineScript()` remains valid
233
- for `/`; requesting a child path on it throws `NotFoundError` before its handler runs.
234
-
235
- ### `router.addRoute<TInput = unknown, TOutput = unknown>(method: RequestMethod, path: string, handler: ScriptHandler<TInput, TOutput, TSchema>): ScriptRouter<TSchema>`
236
-
237
- Registers a handler and returns the same router for chaining. Supported methods are
238
- `GET`, `POST`, `PUT`, `PATCH`, and `DELETE`. A path is `/` or static/dynamic
239
- components such as `/orders/:orderId`. Static components start with an ASCII letter
240
- or digit, may contain letters, digits, `_`, or `-`, and are at most 100 characters.
241
- Parameter names start with an ASCII letter, may contain letters, digits, or `_`, are
242
- at most 64 characters, and must be unique in a route. The complete path is at most
243
- 1,024 characters.
244
- Child trailing slashes, empty segments, `.`, `..`, percent escapes in the template,
245
- `?`, `#`, and wildcards are rejected. Duplicate or structurally ambiguous routes for
246
- one method, invalid handlers, or more than 256 routes throw `ValidationError`.
247
-
248
- Handlers are ordinary `ScriptHandler` functions, not functions already wrapped in
249
- `defineScript()`. They receive the same data/schema/log APIs, input and request context.
250
- The same handler may be registered at more than one path.
251
-
252
- ### `router.get/post/put/patch/delete(path, handler): ScriptRouter<TSchema>`
253
-
254
- Method-specific shorthand for `addRoute()`, with identical validation, return value,
255
- and errors.
256
-
257
- ### `router.toHandler(): SandboxHandler`
258
-
259
- Returns a default-exportable handler that captures a snapshot of the current routes.
260
- Later registrations do not affect an existing handler. It parses input, dispatches
261
- exactly one route, awaits it, and serializes the result just like `defineScript()`.
262
- `null` remains null; an undefined result throws `ValidationError`. Missing routes
263
- throw `NotFoundError` (HTTP 404). Unsupported invocation methods use
264
- `CogoverApiError` with `code: "METHOD_NOT_ALLOWED"` (HTTP 405). Invalid invocation
265
- metadata throws `ValidationError`.
266
- When invoked directly without Cogover request metadata, handlers default to POST `/`.
267
-
268
- Routes inherit project authentication, permissions and runtime limits. Registering a
269
- route grants no additional permission or separate security boundary. Idempotency
270
- replay is scoped to method/path as well as project version and caller; use a new key
271
- for each distinct business operation.
272
-
273
- ## HTTP response API
274
-
275
- Returning a plain JSON-serializable value keeps the compatible `200
276
- application/json` behavior. Use the context's `response` helpers to control status,
277
- headers, content type, or body representation:
278
-
279
- ```typescript
280
- router.post("/orders", ({ response }) => response.json({ id: "ORD-1" }, {
281
- status: 201,
282
- headers: { location: "/orders/ORD-1", "x-request-state": "created" },
283
- }));
284
-
285
- router.get("/files/:fileId", ({ response }) =>
286
- response.bytes(new Uint8Array([0, 1, 255]), { contentType: "application/octet-stream" }));
287
- ```
288
-
289
- ```typescript
290
- type ResponseHeaderValue = string | readonly string[];
291
-
292
- interface ResponseInit {
293
- readonly status?: number;
294
- readonly headers?: Readonly<Record<string, ResponseHeaderValue>>;
295
- }
296
-
297
- interface BinaryResponseInit extends ResponseInit {
298
- readonly contentType?: string;
299
- }
300
-
301
- interface ResponseApi {
302
- json<T>(body: T, init?: ResponseInit): ScriptResponse<T>;
303
- text(body: string, init?: ResponseInit): ScriptResponse<string>;
304
- bytes(body: Uint8Array, init?: BinaryResponseInit): ScriptResponse<Uint8Array>;
305
- empty(init?: ResponseInit): ScriptResponse<null>;
306
- redirect(location: string, status?: 301 | 302 | 303 | 307 | 308): ScriptResponse<null>;
307
- }
308
-
309
- response.json(body, init?)
310
- response.text(body, init?)
311
- response.bytes(body: Uint8Array, { status?, headers?, contentType? }?)
312
- response.empty(init?) // status defaults to 204
313
- response.redirect(location, status?) // status defaults to 302
314
- ```
315
-
316
- Status must be an integer from 200 through 599. Header values may be one string or
317
- a readonly string array. Hop-by-hop, credential-setting, and reserved Cogover headers
318
- are rejected. Header names and values cannot contain newlines;
319
- at most 50 headers are accepted. A header name is at most 128 characters and each
320
- value at most 8,192 characters. Default content types are
321
- `application/json; charset=utf-8`, `text/plain; charset=utf-8`, and
322
- `application/octet-stream`. Redirect status is restricted to 301, 302, 303, 307, or
323
- 308. Helpers return an opaque `ScriptResponse`; application code must not construct
324
- the transport envelope directly. A redirect location must be non-empty, at most
325
- 4,096 characters, and contain no newline. `response.json()` rejects `undefined`;
326
- `response.text()` requires a string and `response.bytes()` requires `Uint8Array`.
327
-
328
- ## Record triggers
329
-
330
- A record trigger runs project code when records of one Object are created, updated,
331
- or deleted. Declare each trigger with `defineTrigger` and list the results in the
332
- project's named `triggers` export. The default export is still the HTTP handler and
333
- is optional in a project that only declares triggers.
334
-
335
- This example assumes that `workspace.d.ts` declares the `order` Object and the
336
- fields used below.
337
-
338
- ```typescript
339
- import { defineTrigger } from "@cogover/sdk";
340
-
341
- export const triggers = [
342
- defineTrigger({
343
- key: "order_credit_check",
344
- object: "order",
345
- timing: "beforeChange",
346
- operations: ["create", "update"],
347
- fields: ["status", "amount", "customer"],
348
- changedFields: ["status", "amount"],
349
- when: { op: "=", field: "status", params: "confirmed" },
350
- writableFields: ["approval_level"],
351
- }, async ({ records }) => {
352
- for (const record of records) {
353
- if ((record.new.amount ?? 0) > 1_000_000_000) {
354
- record.addError("amount", "AMOUNT_TOO_LARGE", "Amount exceeds the approval limit.");
355
- continue;
356
- }
357
- record.new.approval_level = "high";
358
- }
359
- }),
360
- ];
361
- ```
362
-
363
- A trigger has one of two timings. A **before-change** trigger runs before the change
364
- is saved: it can reject records and adjust the values that will be saved. An
365
- **after-change** trigger runs asynchronously after the change has been saved: it
366
- cannot reject or modify that change, but it may write records and call `fetch`. See
367
- [Before-change execution rules](#before-change-execution-rules) and
368
- [After-change execution rules](#after-change-execution-rules).
369
-
370
- Cogover reads the trigger configuration when a project version is published and
371
- applies it while that version is active. Deactivating the project removes its
372
- triggers. A project can declare at most 50 triggers, and an Object can have at most
373
- 20 active before-change triggers.
374
-
375
- ### `defineTrigger(config, handler): TriggerDefinition`
376
-
377
- ```typescript
378
- function defineTrigger<
379
- ObjectSlug extends keyof Schema & string,
380
- Operation extends TriggerOperation,
381
- Schema extends object = EffectiveWorkspaceObjects,
382
- >(
383
- config: TriggerConfig<ObjectSlug, Operation, Schema>,
384
- handler: TriggerHandler<ObjectSlug, Operation, Schema>,
385
- ): TriggerDefinition;
386
- ```
387
-
388
- The type arguments are inferred from `config.object` and `config.operations`.
389
- With a generated `workspace.d.ts`, the object slug, every field slug in the
390
- configuration, and the values of `record.new` and `record.old` are checked against
391
- the declared Object. Without Workspace declarations, slugs are strings and field
392
- values are `unknown`.
393
-
394
- `defineTrigger` validates the configuration immediately and throws `ValidationError`
395
- for any violation, for an unknown configuration key, or for a handler that is not a
396
- function. It returns a frozen `TriggerDefinition`.
397
-
398
- ```typescript
399
- type TriggerTiming = "beforeChange" | "afterChange";
400
- type TriggerOperation = "create" | "update" | "delete";
401
- type TriggerRunWhen = "always" | "onEnter";
402
-
403
- interface TriggerConfig<
404
- ObjectSlug extends string = string,
405
- Operation extends TriggerOperation = TriggerOperation,
406
- Schema extends object = EffectiveWorkspaceObjects,
407
- > {
408
- readonly key: string;
409
- readonly name?: string;
410
- readonly object: ObjectSlug;
411
- readonly timing: TriggerTiming;
412
- readonly operations: readonly Operation[];
413
- readonly fields: readonly FieldSlug[]; // field slugs of the Object
414
- readonly changedFields?: readonly FieldSlug[];
415
- readonly when?: TriggerFilter;
416
- readonly runWhen?: TriggerRunWhen;
417
- readonly writableFields?: readonly FieldSlug[];
418
- readonly order?: number;
419
- readonly timeoutMs?: number;
420
- }
421
- ```
422
-
423
- | Option | Required | Rules and meaning |
424
- |---|---|---|
425
- | `key` | Yes | Identifies the trigger inside the project. Starts with an ASCII letter and contains letters, digits, or `_`; at most 100 characters. Keep it stable between versions: a new key is a different trigger. |
426
- | `name` | No | Display name of at most 250 characters. Defaults to `key`. |
427
- | `object` | Yes | Slug of the Object whose records run the trigger. |
428
- | `timing` | Yes | `"beforeChange"` runs before the change is saved and can reject or adjust it. `"afterChange"` runs asynchronously after the change has been saved. |
429
- | `operations` | Yes | Non-empty list of `"create"`, `"update"`, and `"delete"` without duplicates. |
430
- | `fields` | Yes | 1–200 unique field slugs. `record.new` and `record.old` contain only these fields and `id`. |
431
- | `changedFields` | No | 1–200 unique field slugs; requires the `"update"` operation. An update runs the trigger only when at least one of these fields changed. Creates and deletes are not affected. |
432
- | `when` | No | A `TriggerFilter`. Only matching records run the trigger. |
433
- | `runWhen` | No | `"always"` (default) or `"onEnter"`. `"onEnter"` requires `when`. |
434
- | `writableFields` | No | At most 100 unique field slugs that the handler may change. Only for `"beforeChange"`; must be empty when `"delete"` is the only operation. Defaults to `[]`. |
435
- | `order` | No | Integer from 1000 through 8999; defaults to `5000`. Triggers of an Object run in ascending order. Other values are reserved for Cogover. Do not rely on the relative order of triggers that share a value. |
436
- | `timeoutMs` | No | Integer from 100 through 3000; defaults to `2000`. Time budget of one handler call. |
437
-
438
- Object and field slugs start with an ASCII letter or `_`, contain letters, digits,
439
- or `_`, and are at most 355 characters. `changedFields` and `writableFields` do not
440
- have to be listed in `fields`.
441
-
442
- ### Trigger filters
443
-
444
- ```typescript
445
- interface TriggerFilterCondition {
446
- readonly op: FilterOperator;
447
- readonly field: string;
448
- readonly params?: unknown;
449
- }
450
-
451
- interface TriggerFilterGroup {
452
- readonly op: "and" | "or";
453
- readonly conditions: readonly TriggerFilter[];
454
- }
455
-
456
- type TriggerFilter = TriggerFilterCondition | TriggerFilterGroup;
457
- ```
458
-
459
- ```typescript
460
- when: {
461
- op: "and",
462
- conditions: [
463
- { op: "=", field: "status", params: "confirmed" },
464
- { op: "or", conditions: [
465
- { op: ">=", field: "amount", params: 1_000_000 },
466
- { op: "in", field: "priority", params: ["high", "urgent"] },
467
- ] },
468
- ],
469
- }
470
- ```
471
-
472
- A condition compares one field using a `FilterOperator`. `params` is the JSON
473
- comparison value: it is required for every operator except `"is null"` and
474
- `"not null"`, which take none. `"in"` and `"not in"` take a non-empty array and
475
- `"between"` takes exactly two values. A group combines a non-empty list of
476
- filters. A filter is nested at most 8 levels deep and contains at most 50
477
- conditions. Trigger filters are plain objects: expressions built with `and()`,
478
- `or()`, or field references are for `records.list` and are rejected here.
479
-
480
- `when` is evaluated on the new values, or on the old values when a record is
481
- deleted. With `runWhen: "onEnter"` the trigger runs only when the record did not
482
- match `when` before the change and matches after it; a record that is being created
483
- counts as not matching before, and `runWhen` is ignored for deletes.
484
-
485
- Cogover decides which triggers run once, before the first trigger of a change, from
486
- the values submitted by the writer together with field defaults. A value changed by
487
- an earlier trigger does not change which triggers run, but later triggers see it in
488
- `record.new`.
489
-
490
- ### `TriggerDefinition` and `TriggerManifest`
491
-
492
- ```typescript
493
- interface TriggerManifest {
494
- readonly key: string;
495
- readonly name?: string;
496
- readonly object: string;
497
- readonly timing: TriggerTiming;
498
- readonly operations: readonly TriggerOperation[];
499
- readonly fields: readonly string[];
500
- readonly changedFields?: readonly string[];
501
- readonly when?: TriggerFilter;
502
- readonly runWhen: TriggerRunWhen;
503
- readonly writableFields: readonly string[];
504
- readonly order: number;
505
- readonly timeoutMs: number;
506
- }
507
-
508
- type TriggerSandboxHandler = (inputJson: string) => Promise<string>;
509
-
510
- interface TriggerDefinition {
511
- readonly key: string;
512
- readonly config: TriggerManifest;
513
- readonly __cogoverTriggerHandler: TriggerSandboxHandler;
514
- }
515
- ```
516
-
517
- `config` is the normalized configuration as deeply frozen plain JSON, with every
518
- default applied: `runWhen: "always"`, `writableFields: []`, `order: 5000`, and
519
- `timeoutMs: 2000`. Optional settings that were not provided are absent. It is
520
- detached from the object passed to `defineTrigger`, so later edits of that object
521
- have no effect. `__cogoverTriggerHandler` is reserved for Cogover; project code
522
- does not call it.
523
-
524
- ### Trigger handler context
525
-
526
- ```typescript
527
- type TriggerHandler<
528
- ObjectSlug extends string = string,
529
- Operation extends TriggerOperation = TriggerOperation,
530
- Schema extends object = EffectiveWorkspaceObjects,
531
- > = (context: TriggerContext<ObjectSlug, Operation, Schema>) => void | Promise<void>;
532
-
533
- interface TriggerContext<
534
- ObjectSlug extends string = string,
535
- Operation extends TriggerOperation = TriggerOperation,
536
- Schema extends object = EffectiveWorkspaceObjects,
537
- > {
538
- readonly records: readonly TriggerRecord<Fields, Operation>[]; // Fields of ObjectSlug
539
- readonly trigger: TriggerInfo<Operation>;
540
- readonly invocation: InvocationContext;
541
- readonly data: DataApi<Schema>;
542
- readonly schema: SchemaApi<Schema>;
543
- readonly log: ScriptLogger;
544
- readonly push: PushApi<Schema>;
545
- readonly notifications: NotificationsApi;
546
- readonly email: EmailApi<Schema>;
547
- readonly jobs: JobsApi;
548
- readonly secrets: SecretsApi;
549
- readonly crypto: CryptoApi;
550
- readonly org: OrgApi;
551
- }
552
-
553
- interface TriggerInfo<Operation extends TriggerOperation = TriggerOperation> {
554
- readonly id: string;
555
- readonly key: string;
556
- readonly timing: TriggerTiming;
557
- readonly operation: Operation;
558
- readonly objectSlug: string;
559
- readonly changeId: string;
560
- }
561
-
562
- interface TriggerRecord<Fields = Record<string, unknown>, Operation extends TriggerOperation = TriggerOperation> {
563
- readonly key: string;
564
- readonly id: CogoverRecordId | null;
565
- readonly new: TriggerNewValues<Fields> | null;
566
- readonly old: TriggerOldValues<Fields> | null;
567
- readonly changedFields: readonly (keyof Fields & string)[];
568
- addError(field: (keyof Fields & string) | null, code: string, message?: string): void;
569
- }
570
-
571
- type TriggerNewValues<Fields> = {
572
- -readonly [K in keyof Fields]?: Fields[K] | UpdateFields<Fields>[K];
573
- };
574
-
575
- type TriggerOldValues<Fields> = {
576
- readonly [K in keyof Fields]?: Fields[K];
577
- };
578
- ```
579
-
580
- A handler may be synchronous or asynchronous; its return value is ignored. One call
581
- receives all records of the same change that run the trigger, up to 200 records and
582
- 200 KiB, so a batch write or an import calls the handler once per chunk instead of
583
- once per record. Keep `fields` short, and read related data for the whole list with
584
- one `records.getMany` call rather than one read per record.
585
-
586
- `data`, `schema`, `log`, `invocation`, `push`, `notifications`, `email`, `jobs`, `secrets`,
587
- `crypto`, and `org` are the same APIs that scripts receive. A trigger context has no `input`,
588
- `request`, `response`, `state`, or `locks`; `push`, `notifications`, and `email` are refused in a
589
- before-change trigger. `trigger.operation` is
590
- the operation of the current call, `trigger.id` identifies the trigger registration, and
591
- `trigger.changeId` identifies the record change that caused the call.
592
-
593
- Each `TriggerRecord` describes one record:
594
-
595
- - `key` correlates the record with its result. It is not a record ID.
596
- - `id` is the record ID, or `null` while a record that is being created has no ID yet.
597
- In an after-change trigger it is always set.
598
- - `new` holds the values after the change as a plain, mutable object. It is `null`
599
- when the record is deleted.
600
- - `old` holds the values before the change and is deeply frozen. It is `null` when the
601
- record is created.
602
- - `changedFields` is a frozen list of the field slugs that changed. For a created
603
- record it lists every field that has a value.
604
-
605
- The declared `operations` narrow these types: `new` is never `null` unless
606
- `"delete"` is declared, `old` is never `null` unless `"create"` is declared, and a
607
- trigger that only declares `"delete"` has `new: null`. `TriggerNewValues` and
608
- `TriggerOldValues` make every field optional because a field that is not listed in
609
- `fields`, or that has no value, is `undefined`.
610
-
611
- ### Validating and changing records
612
-
613
- This section applies to before-change triggers. In an after-change trigger the
614
- change is already saved: `addError` only reports to the project log and
615
- `record.new` must not be changed (see
616
- [After-change execution rules](#after-change-execution-rules)).
617
-
618
- `record.addError(field, code, message?)` rejects the record. `field` is a field slug,
619
- or `null` for an error about the whole record. `code` starts with an upper-case ASCII
620
- letter and contains upper-case letters, digits, or `_`; at most 64 characters, for
621
- example `AMOUNT_TOO_LARGE`. `message` is an optional English text of at most 500
622
- characters that Cogover shows to the end user when it has no translation for the
623
- code; an empty message is ignored. Invalid arguments throw `ValidationError`. A
624
- record may collect several errors.
625
-
626
- A rejected record is not saved, and any change the handler made to it is discarded.
627
- The writer receives HTTP 400 with `msg: "BEFORE_CHANGE_TRIGGER_REJECTED"`, the error
628
- codes in `meta` keyed by field slug (`$record` for an error about the whole record),
629
- and the optional texts in `messages` keyed by code. A rejected single-record write
630
- stops at the first trigger that reports an error. In a batch write only the rejected
631
- rows fail, and a rejected row is not passed to later triggers.
632
-
633
- To change the values that will be saved, assign fields of `record.new`:
634
-
635
- ```typescript
636
- record.new.approval_level = "high";
637
- record.new.customer = "ACC-1"; // same format as records.update() input
638
- record.new.note = null; // clears the field
639
- ```
640
-
641
- - Only fields listed in `writableFields` may change. When the handler returns, the
642
- SDK compares every top-level field of `record.new` with a snapshot taken before the
643
- handler ran, using a deep JSON comparison. Changing any other field, including
644
- `id`, throws `ValidationError` naming the field, and the write fails.
645
- - Assigned values use the same format as `records.update` input and must be JSON
646
- data. `NaN`, functions, `Map`, `Set`, and class instances are rejected; a `Date` is
647
- stored as its ISO string. Assigning `null` clears a field; assigning `undefined` or
648
- deleting the field has the same effect.
649
- - A change inside an array or object value is detected and sends the whole field value.
650
- - `record.new` itself cannot be replaced, and a record that is being deleted has
651
- nothing to change.
652
- - Cogover validates the final values again before saving, including field types and
653
- required, unique, and duplicate rules. For the fields a trigger changed, the
654
- field's manual create/modify setting and the writer's field edit permission are
655
- not applied. Read-only fields such as formulas, auto numbers, and rollups, and
656
- system fields, are always refused.
657
-
658
- ### Before-change execution rules
659
-
660
- A before-change trigger runs for every source of a write: the Cogover web
661
- application, API keys, imports, automation processes, other Custom Backend Modules,
662
- and writes made through `data.asUser()` or `data.asSystem()`. Maintenance writes
663
- made by Cogover itself — recalculating formula and rollup fields, background record
664
- merges, and cascading deletes — do not run before-change triggers, and neither does
665
- a request that only validates input without saving.
666
-
667
- - **Read-only.** A before-change trigger may read records and schema, but every
668
- record write, `fetch`, lock, state write, push message, notification, email (including
669
- `email.senders()`), `jobs.enqueue`, `secrets.get`, and every `crypto` operation with a
670
- `{ secret }` key is refused with
671
- `PermissionDeniedError` whose `details.reason` is `"TRIGGER_READ_ONLY"`. This
672
- applies to every identity, including `data.asSystem()`. Every `crypto` operation
673
- with a key given in the call remains available, as do `crypto.sha256`,
674
- `crypto.randomBytes`, `crypto.randomUUID`, `crypto.timingSafeEqual`, and every
675
- [`org`](#organization-structure) read.
676
- - **Identity.** `data.object()` acts as the user who made the change, with that
677
- user's permissions, and `invocation` describes the same user. When a change has
678
- no user, `invocation.identity` is `"system"` and `data.object()` works only if the
679
- project's approved identity policy sets `allowInternalSystem: true`; otherwise its
680
- calls throw `PermissionDeniedError` with `details.reason` `"IDENTITY_NOT_GRANTED"`
681
- while the handler still receives `records`. `data.asUser()` and `data.asSystem()`
682
- follow the project's identity policy as usual.
683
- - **Fail closed.** When a handler throws, exceeds `timeoutMs`, exceeds a runtime
684
- limit, or cannot be run, the write is rejected and nothing is saved. The writer
685
- receives `msg: "BEFORE_CHANGE_TRIGGER_FAILED"` without internal details.
686
- - **Time.** Each call must finish within `timeoutMs`. All before-change triggers of
687
- one write share a total budget of 8 seconds.
688
-
689
- ### After-change execution rules
690
-
691
- An after-change trigger (`timing: "afterChange"`) runs asynchronously, shortly after
692
- the change has been saved. Use it for follow-up work such as creating or updating
693
- related records or notifying another system. It runs for the same sources of a
694
- write as a before-change trigger, with the same exceptions.
695
-
696
- ```typescript
697
- import { defineTrigger, fetch, RetryableError } from "@cogover/sdk";
698
-
699
- export const triggers = [
700
- defineTrigger({
701
- key: "order_confirmed_notify",
702
- object: "order",
703
- timing: "afterChange",
704
- operations: ["create", "update"],
705
- fields: ["status", "amount"],
706
- changedFields: ["status"],
707
- when: { op: "=", field: "status", params: "confirmed" },
708
- runWhen: "onEnter",
709
- }, async ({ records, trigger }) => {
710
- for (const record of records) {
711
- const response = await fetch("https://erp.example.com/orders", {
712
- method: "POST",
713
- headers: {
714
- "content-type": "application/json",
715
- // The same change of the same record always produces the same key.
716
- "idempotency-key": `${trigger.changeId}:${record.id}`,
717
- },
718
- body: JSON.stringify({ id: record.id, amount: record.new.amount }),
719
- });
720
- if (response.status >= 500) {
721
- throw new RetryableError("The ERP is temporarily unavailable");
722
- }
723
- }
724
- }),
725
- ];
726
- ```
727
-
728
- - **Cannot block or change the saved record.** The writer has already received its
729
- response. `writableFields` is not allowed, and changing `record.new` makes the call
730
- fail with `ValidationError`. `record.addError()` rejects nothing: the reported
731
- errors are only written to the project log. To change the record, call
732
- `records.update`; that is a new write and runs triggers again.
733
- - **Saved values.** `record.id` is always set. `record.new` holds the values as they
734
- were saved, including the record ID and values assigned while saving, such as an
735
- auto number. For a deleted record `record.new` is `null` and `record.old` holds the
736
- last values.
737
- - **May write and call out.** Record writes, `fetch`, `push`, `notifications`, `email`,
738
- `jobs.enqueue`, `secrets.get`, and `crypto` work as they do in a script, within the
739
- same runtime limits. `data.object()` acts as the user who made the change, and the other identity
740
- rules of before-change triggers apply. The trigger context has no `state` or `locks`;
741
- `push` is the usual way to refresh the records the handler changed for everyone who
742
- has them open, and longer work, or work that needs `state` or `locks`, belongs in a
743
- [background job](#background-jobs).
744
- - **Best-effort delivery.** Cogover does not guarantee that an after-change handler
745
- runs exactly once. It may occasionally run more than once for the same change, or
746
- not at all. Make every handler idempotent: `trigger.changeId` together with
747
- `record.id` identifies one change of one record. Never make an after-change
748
- trigger the only guarantee of a critical rule; enforce such rules in a
749
- before-change trigger.
750
- - **Retries.** Throw `RetryableError` when a handler fails for a temporary reason,
751
- such as an external service that is unavailable. Cogover runs the handler again
752
- later: by default up to 5 more times, waiting longer before each attempt, from
753
- about one second to about ten minutes. A call that exceeds `timeoutMs`, or that
754
- Cogover could not run for a temporary reason, is retried the same way. Any other
755
- error is not retried: the failure is logged and the handler does not run again for
756
- that change. When the retries are used up, the handler does not run again for that
757
- change either.
758
- - **Loops end.** A write made by a trigger runs triggers again, possibly including
759
- the same trigger. Cogover limits such chains: every automated write uses one step
760
- of a fixed budget (10 steps for a change made directly by a user or an API
761
- client), and after-change triggers no longer run once the budget is used up. Use
762
- `changedFields`, `when`, and `runWhen: "onEnter"` so that a handler's own writes
763
- do not start it again.
764
- - **Order and time.** Each call must finish within `timeoutMs`. After-change triggers
765
- of one change run independently of each other: do not rely on their relative
766
- order. A retried call may run after a later change of the same record has already
767
- been processed, so read the current record when the latest values matter.
768
-
769
- ## Background jobs
770
-
771
- A background job runs project code outside an HTTP request: enqueued by a script, a
772
- trigger, another job, or an administrator, or started by a cron schedule. Declare
773
- each job with `defineJob` and list the results in the project's named `jobs`
774
- export. The default export is still the HTTP handler and is optional in a project
775
- that only declares jobs and triggers.
776
-
777
- This example assumes that `workspace.d.ts` declares the `order` Object and the
778
- fields used below.
779
-
780
- ```typescript
781
- import { defineJob } from "@cogover/sdk";
782
-
783
- interface RecalcPayload {
784
- cursor?: string;
785
- }
786
-
787
- export const jobs = [
788
- // Enqueued by a route or a trigger; walks all orders one page per run.
789
- defineJob<RecalcPayload>({
790
- key: "recalc_totals",
791
- name: "Recalculate order totals",
792
- timeoutMs: 60_000,
793
- }, async ({ payload, data, jobs, log }) => {
794
- const orders = data.object("order");
795
- const page = await orders.records.list({
796
- fields: ["subtotal", "tax"],
797
- limit: 200,
798
- ...(payload?.cursor ? { cursor: payload.cursor } : {}),
799
- });
800
- for (const order of page.items) {
801
- await orders.records.update(order.id, {
802
- total: (order.fields.subtotal ?? 0) + (order.fields.tax ?? 0),
803
- });
804
- }
805
- if (page.nextCursor) {
806
- // Continue with the next page in a new run instead of one long run.
807
- await jobs.enqueue("recalc_totals", { cursor: page.nextCursor });
808
- return;
809
- }
810
- log.info("Order totals recalculated");
811
- }),
812
-
813
- // Runs every day at 02:00 in the given time zone.
814
- defineJob({
815
- key: "cancel_stale_orders",
816
- schedule: { cron: "0 2 * * *", timezone: "Asia/Ho_Chi_Minh" },
817
- }, async ({ data }) => {
818
- const orders = data.object("order");
819
- const stale = await orders.records.list({
820
- where: orders.fields.status.eq("new"),
821
- fields: ["status"],
822
- limit: 200,
823
- });
824
- for (const order of stale.items) {
825
- await orders.records.update(order.id, { status: "cancelled" });
826
- }
827
- }),
828
- ];
829
- ```
830
-
831
- Cogover reads the job configuration when a project version is published and applies
832
- it while that version is active: `jobs.enqueue` accepts only the keys declared by the
833
- active version, and schedules run only while their version is active. Deactivating
834
- the project removes its schedules. A project can declare at most 50 jobs.
835
-
836
- ### `defineJob(config, handler): JobDefinition`
837
-
838
- ```typescript
839
- function defineJob<
840
- Payload = unknown,
841
- Schema extends object = EffectiveWorkspaceObjects,
842
- >(config: JobConfig, handler: JobHandler<Payload, Schema>): JobDefinition;
843
- ```
844
-
845
- `Payload` is the type of the value passed to `jobs.enqueue`; it is not validated at
846
- run time, so treat the payload like request input. `defineJob` validates the
847
- configuration immediately and throws `ValidationError` for any violation, for an
848
- unknown configuration key, or for a handler that is not a function. It returns a
849
- frozen `JobDefinition`.
850
-
851
- ```typescript
852
- interface JobConfig {
853
- readonly key: string;
854
- readonly name?: string;
855
- readonly timeoutMs?: number;
856
- readonly maxAttempts?: number;
857
- readonly schedule?: JobSchedule;
858
- }
859
-
860
- interface JobSchedule {
861
- readonly cron: string;
862
- readonly timezone?: string;
863
- }
864
- ```
865
-
866
- | Option | Required | Rules and meaning |
867
- |---|---|---|
868
- | `key` | Yes | Identifies the job inside the project. Starts with an ASCII letter and contains letters, digits, or `_`; at most 100 characters; unique in the project regardless of case. Keep it stable between versions: a new key is a different job. |
869
- | `name` | No | Display name of at most 250 characters. Defaults to `key`. |
870
- | `timeoutMs` | No | Integer from 1000 through 60000; defaults to `30000`. Time budget of one attempt. |
871
- | `maxAttempts` | No | Integer from 1 through 10; defaults to `5`. Total number of attempts of one run, including the first. |
872
- | `schedule` | No | Runs the job automatically. `cron` has five fields — minute, hour, day-of-month, month, day-of-week — and `timezone` is an IANA time zone ID of at most 64 characters, defaulting to `"UTC"`. |
873
-
874
- A cron field is `*`, a number, a range `a-b`, a list `a,b`, a step `*/n`, or a
875
- stepped range `a-b/n`; the fields accept minutes 0–59, hours 0–23, days 1–31,
876
- months 1–12, and weekdays 0–7 where both 0 and 7 are Sunday. Names such as `MON`,
877
- the characters `L`, `W`, `#`, and `?`, and macros such as `@daily` are not supported.
878
- The shortest period is one minute. Whitespace between the fields is normalized to
879
- one space in the manifest.
880
-
881
- ### `JobDefinition` and `JobManifest`
882
-
883
- ```typescript
884
- interface JobManifest {
885
- readonly key: string;
886
- readonly name?: string;
887
- readonly timeoutMs: number;
888
- readonly maxAttempts: number;
889
- readonly schedule?: { readonly cron: string; readonly timezone: string };
890
- }
891
-
892
- interface JobDefinition {
893
- readonly key: string;
894
- readonly config: JobManifest;
895
- readonly __cogoverJobHandler: SandboxHandler;
896
- }
897
- ```
898
-
899
- `config` is the normalized configuration as deeply frozen plain JSON, with every
900
- default applied: `timeoutMs: 30000`, `maxAttempts: 5`, and `schedule.timezone:
901
- "UTC"`. Optional settings that were not provided are absent. It is detached from the
902
- object passed to `defineJob`, so later edits of that object have no effect.
903
- `__cogoverJobHandler` is reserved for Cogover; project code does not call it.
904
-
905
- ### Job handler context
906
-
907
- ```typescript
908
- type JobHandler<
909
- Payload = unknown,
910
- Schema extends object = EffectiveWorkspaceObjects,
911
- > = (context: JobContext<Payload, Schema>) => void | Promise<void>;
912
-
913
- interface JobContext<Payload = unknown, Schema extends object = EffectiveWorkspaceObjects> {
914
- readonly job: JobInfo;
915
- readonly payload: Payload | null;
916
- readonly invocation: InvocationContext;
917
- readonly data: DataApi<Schema>;
918
- readonly schema: SchemaApi<Schema>;
919
- readonly log: ScriptLogger;
920
- readonly state: ProjectState;
921
- readonly locks: DistributedLocks;
922
- readonly notifications: NotificationsApi;
923
- readonly email: EmailApi<Schema>;
924
- readonly jobs: JobsApi;
925
- readonly secrets: SecretsApi;
926
- readonly crypto: CryptoApi;
927
- readonly org: OrgApi;
928
- }
929
-
930
- interface JobInfo {
931
- readonly id: string;
932
- readonly key: string;
933
- readonly attempt: number;
934
- readonly maxAttempts: number;
935
- readonly source: "enqueue" | "schedule";
936
- readonly runAt: number;
937
- readonly enqueuedAt?: number;
938
- }
939
- ```
940
-
941
- A handler may be synchronous or asynchronous; its return value is ignored. `data`,
942
- `schema`, `log`, `invocation`, `state`, `locks`, `notifications`, `email`, `jobs`,
943
- `secrets`, `crypto`, and `org` are the same APIs that scripts receive. A job context has
944
- no `input`, `request`, `response`, or `push`.
945
-
946
- - `job.id` identifies the run and stays the same across its attempts; use it as the
947
- idempotency key of external calls. `job.attempt` starts at 1.
948
- - `job.source` is `"enqueue"` for a run created by `jobs.enqueue` or by an
949
- administrator and `"schedule"` for a run created by the job's schedule. `job.runAt`
950
- is when the run became due and `job.enqueuedAt` when it was enqueued; both are Unix
951
- milliseconds, and `enqueuedAt` is absent for a scheduled run.
952
- - `payload` is the JSON value passed to `jobs.enqueue`, or `null` when none was
953
- passed or the run is scheduled. It is plain, mutable data.
954
-
955
- ### `jobs.enqueue(jobKey, payload?, options?): Promise<EnqueueResult>`
956
-
957
- ```typescript
958
- interface JobsApi {
959
- enqueue(jobKey: string, payload?: unknown, options?: EnqueueOptions): Promise<EnqueueResult>;
960
- }
961
-
962
- interface EnqueueOptions {
963
- readonly delayMs?: number;
964
- readonly runAt?: number;
965
- readonly idempotencyKey?: string;
966
- }
967
-
968
- interface EnqueueResult {
969
- readonly runId: string;
970
- readonly duplicate: boolean;
971
- }
972
- ```
973
-
974
- ```typescript
975
- const { runId, duplicate } = await jobs.enqueue("sync_order", { orderId: order.id }, {
976
- delayMs: 60_000,
977
- idempotencyKey: `sync_order:${order.id}:${order.system.updatedAt}`,
978
- });
979
- ```
980
-
981
- `jobKey` must be a job declared by the active version; otherwise Cogover throws
982
- `ValidationError`. `payload` is any JSON value of at most 65,536 UTF-8 bytes after
983
- serialization; `undefined` and `null` enqueue the run without a payload. Values that
984
- JSON would silently change, such as `NaN` or class instances, are rejected with
985
- `ValidationError`. `delayMs` is an integer from 0 through 2,592,000,000 (30 days)
986
- and `runAt` a Unix millisecond time at most 30 days ahead; pass one or neither, not
987
- both. `idempotencyKey` starts with a letter or digit, contains letters, digits, `.`,
988
- `_`, `:`, or `-`, and is at most 128 characters: a second enqueue of the same job
989
- with the same key while the earlier run is still kept returns that run with
990
- `duplicate: true` instead of creating another. Run history is kept for 7 days.
991
-
992
- `enqueue` works in scripts and routes, after-change triggers, jobs, and inbound
993
- webhook calls. A before-change trigger is refused with `PermissionDeniedError`
994
- (`details.reason === "TRIGGER_READ_ONLY"`), and so is a local development session
995
- without write permission (`"DEVELOPMENT_SESSION_READ_ONLY"`). One invocation may
996
- enqueue at most 50 runs, and a project may have at most 10,000 runs waiting or
997
- running; beyond that `RateLimitError` is thrown. When jobs are not enabled for the
998
- Workspace, the error is `CogoverApiError` with `code: "JOBS_DISABLED"`.
999
-
1000
- ### Job execution rules
1001
-
1002
- - **Identity.** A run enqueued from a script, route, or trigger runs as the user of
1003
- that invocation: `invocation` describes that user and `data.object()` acts with
1004
- that user's permissions. A scheduled run, a run enqueued by an administrator, and
1005
- a run enqueued from an inbound webhook call have no user: `invocation.identity`
1006
- is `"system"`, and `data.object()` works only if the project's approved identity
1007
- policy sets `allowInternalSystem: true`; otherwise its calls throw
1008
- `PermissionDeniedError` with `details.reason` `"IDENTITY_NOT_GRANTED"`.
1009
- `data.asUser()` and `data.asSystem()` follow the identity policy as usual.
1010
- - **Capabilities.** A job may read and write records, call `fetch`, use `state` and
1011
- `locks`, send notifications and email, enqueue jobs, read secrets, and use `crypto`,
1012
- within the runtime limits of the job lane.
1013
- - **Time.** Each attempt must finish within `timeoutMs`. Work that needs longer is
1014
- split: process one page, save the cursor, and enqueue the same job again with the
1015
- cursor in the payload, as in the example above.
1016
- - **At least once.** Cogover does not guarantee that a run executes exactly once: an
1017
- attempt that was interrupted, for example by a restart, is started again. Make
1018
- every handler idempotent. `job.id` identifies the run across attempts, and
1019
- `idempotencyKey` on `enqueue` prevents duplicate runs.
1020
- - **Retries.** Throw `RetryableError` when the handler fails for a temporary reason,
1021
- such as an external service that is unavailable. Cogover runs the attempt again
1022
- later, waiting longer before each attempt, from a few seconds to about half an
1023
- hour, until `maxAttempts` attempts have been made. An attempt that exceeds
1024
- `timeoutMs`, or that Cogover could not run for a temporary reason, is retried the
1025
- same way. Any other error ends the run as failed: the failure is logged and the
1026
- handler does not run again for that run.
1027
- - **Order and concurrency.** Runs execute in no guaranteed order, and two runs of the
1028
- same project, even of the same job, may execute at the same time. Use `locks` when
1029
- a section must not run concurrently, and delay through `delayMs` or `runAt` rather
1030
- than by waiting inside the handler.
1031
- - **Loops end.** Record writes made by a run carry the automation budget of the
1032
- invocation that enqueued it (a scheduled run and an administrator's enqueue start
1033
- with the full budget of 10 steps), so a chain of jobs and triggers started by
1034
- record writes ends the same way as a trigger chain. Enqueueing a job does not use
1035
- a step: a job that enqueues itself must stop on its own, for example when the
1036
- cursor is exhausted.
1037
-
1038
- A scheduled job creates one run for each time the schedule matches, in the
1039
- schedule's time zone; the run may start a little later than the scheduled minute
1040
- under load. A slot that is missed while the project is inactive is not run later.
1041
- A run is still created when the previous scheduled run has not finished, so a
1042
- schedule whose work can take longer than its period should guard itself with a
1043
- lock.
1044
-
1045
- ## Outbound HTTP `fetch`
1046
-
1047
- ```typescript
1048
- function fetch(input: string, init?: CogoverFetchInit): Promise<CogoverFetchResponse>;
1049
-
1050
- interface CogoverFetchInit {
1051
- readonly method?: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE";
1052
- readonly headers?: Readonly<Record<string, string>>;
1053
- readonly body?: string;
1054
- readonly timeoutMs?: number;
1055
- readonly credential?: string;
1056
- }
1057
-
1058
- interface CogoverFetchHeaders {
1059
- get(name: string): string | null;
1060
- has(name: string): boolean;
1061
- entries(): IterableIterator<[string, string]>;
1062
- [Symbol.iterator](): IterableIterator<[string, string]>;
1063
- }
1064
-
1065
- interface CogoverFetchResponse {
1066
- readonly ok: boolean;
1067
- readonly status: number;
1068
- readonly statusText: string;
1069
- readonly url: string;
1070
- readonly redirected: false;
1071
- readonly headers: CogoverFetchHeaders;
1072
- readonly bodyUsed: boolean;
1073
- text(): Promise<string>;
1074
- json<T = unknown>(): Promise<T>;
1075
- }
1076
- ```
1077
-
1078
- Cogover installs the global `fetch()` function in the hosted runtime. Import
1079
- `{ fetch }` from `@cogover/sdk` when the dependency should be explicit; this also
1080
- prevents local Node.js from silently using its native, unrestricted `fetch` during
1081
- tests. The SDK function requires the Cogover runtime and always uses Cogover's
1082
- managed network layer. `input` must be an absolute public HTTPS URL on port 443
1083
- without userinfo, a fragment, or an IP-literal host. `body` accepts only a string;
1084
- use `JSON.stringify()` for JSON. `timeoutMs` must be a positive integer and is
1085
- always clamped by the platform limit.
1086
-
1087
- ```typescript
1088
- import { fetch } from "@cogover/sdk";
1089
-
1090
- const response = await fetch("https://api.example.com/v1/orders", {
1091
- method: "POST",
1092
- headers: { "content-type": "application/json" },
1093
- body: JSON.stringify({ id: "ORD-1" }),
1094
- timeoutMs: 5_000,
1095
- });
1096
- ```
1097
-
1098
- `CogoverFetchResponse` exposes `ok`, `status`, `statusText`, `url`, `redirected`
1099
- (always `false`), `headers`, `bodyUsed`, `text()`, and `json<T>()`. The bounded,
1100
- buffered body can be consumed once. Header `get(name)`, `has(name)`, `entries()`,
1101
- and iteration are case-insensitive.
1102
-
1103
- V1 does not follow redirects, persist or send cookies, stream requests/responses,
1104
- or support WebSocket. It does not accept `signal`, `credentials`, `redirect`, proxy,
1105
- dispatcher, agent, DNS resolver, or TLS configuration. HTTP URLs, ports other than
1106
- 443, userinfo, and IP-literal hosts are unsupported. Framing, hop-by-hop, proxy,
1107
- forwarding, and reserved Cogover request headers are rejected. Request/response sizes,
1108
- headers, time, calls, destinations, and concurrency are bounded by platform quotas.
1109
-
1110
- Failures are `CogoverApiError` instances with `FETCH_DISABLED`, `FETCH_BLOCKED`,
1111
- `FETCH_REQUEST_TOO_LARGE`, `FETCH_RESPONSE_TOO_LARGE`, `FETCH_TIMEOUT`, or
1112
- `FETCH_FAILED`; quota failures use `RateLimitError`. When POST, PUT, PATCH, or DELETE
1113
- times out or loses its response, the remote server may already have applied the
1114
- request. Use the remote API's idempotency mechanism and never retry blindly.
1115
-
1116
- ### Authenticating with a credential
1117
-
1118
- `credential` names a credential that an administrator stored for the project (see
1119
- [Secrets and credentials](#secrets-and-credentials)). Cogover adds the credential's
1120
- authentication header to the request, so project code never handles the value:
1121
-
1122
- ```typescript
1123
- const response = await fetch("https://erp.example.com/v1/orders", {
1124
- method: "POST",
1125
- credential: "erp_api",
1126
- headers: { "content-type": "application/json" },
1127
- body: JSON.stringify({ id: "ORD-1" }),
1128
- });
1129
- ```
1130
-
1131
- Depending on how the credential was created, Cogover sends `Authorization: Bearer
1132
- <value>`, `Authorization: Basic <base64 of value>`, or a header with the configured
1133
- name. The name must start with a letter and contain at most 64 letters, digits, or
1134
- underscores. A credential can only be sent to the hosts its administrator allowed;
1135
- a request to another host, a request that sets the same header itself, or a name
1136
- that is not an active credential fails with `FETCH_BLOCKED`. Redirects are never
1137
- followed, so a credential never leaves an allowed host.
1138
-
1139
- ## Secrets and credentials
1140
-
1141
- An administrator stores secrets for a project through the Cogover management API.
1142
- Each one is either a **secret**, whose value code reads with `secrets.get`, or a
1143
- **credential**, which only `fetch` uses (see
1144
- [Authenticating with a credential](#authenticating-with-a-credential)); the value
1145
- of a credential is never readable by code. Values are stored encrypted and are
1146
- never returned by the management API, logged, or included in error messages.
1147
-
1148
- ```typescript
1149
- interface SecretsApi {
1150
- get(name: string): Promise<string>;
1151
- }
1152
- ```
1153
-
1154
- ```typescript
1155
- const token = await secrets.get("erp_token");
1156
- const response = await fetch("https://erp.example.com/v1/orders", {
1157
- headers: { authorization: `Bearer ${token}` },
1158
- });
1159
- ```
1160
-
1161
- ### `secrets.get(name): Promise<string>`
1162
-
1163
- Returns the current value of the secret. `name` starts with a letter and contains
1164
- at most 64 letters, digits, or underscores; other names throw `ValidationError`
1165
- before the call. A secret that does not exist or is disabled throws
1166
- `ValidationError` with the message `Secret '<name>' is not available`, and a
1167
- credential throws `ValidationError` with `Secret '<name>' is a credential and
1168
- cannot be read`.
1169
-
1170
- `secrets.get` works in scripts and routes, after-change triggers, jobs, and inbound
1171
- webhook calls. A before-change trigger is refused with `PermissionDeniedError`
1172
- (`details.reason === "TRIGGER_READ_ONLY"`); a local development session reads
1173
- secrets only when its administrator allowed it, otherwise the reason is
1174
- `"SECRETS_NOT_ALLOWED"`. One invocation may read at most 20 secrets; reading the
1175
- same name again in the same invocation returns the cached value. When secrets are
1176
- not enabled for the Workspace, the error is `CogoverApiError` with
1177
- `code: "SECRETS_DISABLED"`. Never write a secret value to the log, to a record, to
1178
- state, or to a response. To sign, encrypt, or decrypt with a secret without
1179
- reading it, pass `{ secret: name }` as the key of a [`crypto`](#cryptography)
1180
- operation.
1181
-
1182
- ## Cryptography
1183
-
1184
- `crypto` provides hashing, message authentication, randomness, AES and RSA
1185
- encryption, and RSA and ECDSA signatures through Cogover's managed
1186
- implementation. Import it from `@cogover/sdk` or read it from `context.crypto`;
1187
- both are the same frozen object.
1188
-
1189
- ```typescript
1190
- const crypto: CryptoApi;
1191
-
1192
- type BinaryEncoding = "base64" | "base64url" | "hex";
1193
- type DecryptOutput = "utf8" | "bytes" | BinaryEncoding;
1194
-
1195
- interface SecretKeyReference {
1196
- readonly secret: string;
1197
- }
1198
- type AesKey =
1199
- | string
1200
- | Uint8Array
1201
- | (SecretKeyReference & { readonly encoding?: "utf8" | "base64" | "hex" });
1202
- type AsymmetricKey = string | SecretKeyReference;
1203
-
1204
- interface CryptoApi {
1205
- sha256(data: string | Uint8Array, encoding?: "hex" | "base64"): Promise<string>;
1206
- hmacSha256(
1207
- key: string | Uint8Array | { readonly secret: string },
1208
- data: string | Uint8Array,
1209
- encoding?: "hex" | "base64",
1210
- ): Promise<string>;
1211
- randomBytes(length: number): Promise<Uint8Array>;
1212
- randomUUID(): Promise<string>;
1213
- timingSafeEqual(a: string | Uint8Array, b: string | Uint8Array): boolean;
1214
-
1215
- aesEncrypt(key: AesKey, data: string | Uint8Array, options?: AesEncryptOptions): Promise<AesEncryptResult>;
1216
- aesDecrypt(key: AesKey, ciphertext: string | Uint8Array, options: AesDecryptOptions): Promise<string>;
1217
- aesDecrypt(
1218
- key: AesKey,
1219
- ciphertext: string | Uint8Array,
1220
- options: AesDecryptOptions & { readonly output: "bytes" },
1221
- ): Promise<Uint8Array>;
1222
- rsaEncrypt(publicKey: AsymmetricKey, data: string | Uint8Array, options?: RsaEncryptOptions): Promise<string>;
1223
- rsaDecrypt(privateKey: AsymmetricKey, ciphertext: string | Uint8Array, options?: RsaDecryptOptions): Promise<string>;
1224
- rsaDecrypt(
1225
- privateKey: AsymmetricKey,
1226
- ciphertext: string | Uint8Array,
1227
- options: RsaDecryptOptions & { readonly output: "bytes" },
1228
- ): Promise<Uint8Array>;
1229
- sign(
1230
- algorithm: SignatureAlgorithm,
1231
- privateKey: AsymmetricKey,
1232
- data: string | Uint8Array,
1233
- options?: SignatureOptions,
1234
- ): Promise<string>;
1235
- verify(
1236
- algorithm: SignatureAlgorithm,
1237
- publicKey: AsymmetricKey,
1238
- data: string | Uint8Array,
1239
- signature: string | Uint8Array,
1240
- options?: SignatureOptions,
1241
- ): Promise<boolean>;
1242
- }
1243
- ```
1244
-
1245
- `aesDecrypt` and `rsaDecrypt` return a string unless `output` is `"bytes"`; when
1246
- `output` is only known as a `DecryptOutput`, the result type is
1247
- `string | Uint8Array`.
1248
-
1249
- ```typescript
1250
- import { crypto } from "@cogover/sdk";
1251
-
1252
- const digest = await crypto.sha256(JSON.stringify(payload));
1253
- const signature = await crypto.hmacSha256({ secret: "webhook_secret" }, request.rawBody ?? "");
1254
- if (!crypto.timingSafeEqual(signature, request.headers["x-signature"] ?? "")) {
1255
- return response.empty({ status: 401 });
1256
- }
1257
- const token = await crypto.randomUUID();
1258
- ```
1259
-
1260
- ### Hashing, HMAC, and randomness
1261
-
1262
- - `sha256(data, encoding?)` returns the SHA-256 digest of `data`. A string is
1263
- hashed as UTF-8; a `Uint8Array` is hashed as is. `encoding` is `"hex"` (default)
1264
- or `"base64"`.
1265
- - `hmacSha256(key, data, encoding?)` returns the HMAC-SHA256 of `data`. The key is a
1266
- non-empty string (UTF-8), a non-empty `Uint8Array`, or `{ secret: name }` to use
1267
- a project secret without reading its value.
1268
- - `randomBytes(length)` returns `length` cryptographically secure random bytes;
1269
- `length` is an integer from 1 through 1024.
1270
- - `randomUUID()` returns a random version 4 UUID such as
1271
- `"3f9c2d6e-8b1a-4c7d-9e2f-1a2b3c4d5e6f"`.
1272
- - `timingSafeEqual(a, b)` compares two strings or byte arrays in constant time and
1273
- returns `false` for different lengths. Strings are compared as UTF-8 bytes. Use
1274
- it for every comparison of a signature, token, or key.
1275
-
1276
- ### Keys
1277
-
1278
- Every key can be given in the call or as `{ secret: name }`. A secret key is
1279
- resolved by Cogover and its value never reaches project code; the named secret
1280
- must be readable by `secrets.get` in the same context and counts as one secret
1281
- read. Store every private key and every AES key as a project secret; a key written
1282
- in source code is visible to everyone who can read the project.
1283
-
1284
- - **AES keys** are 16, 24, or 32 bytes (AES-128, AES-192, AES-256). A string is
1285
- used as its UTF-8 bytes and a `Uint8Array` as is. For a secret, `encoding` states
1286
- how the secret's value holds the key: `"utf8"` (default) uses the text itself,
1287
- and `"base64"` or `"hex"` decode it first, ignoring surrounding whitespace.
1288
- - **RSA and EC keys** (`AsymmetricKey`) are PEM text, or the base64 body of one
1289
- without the `-----BEGIN` lines (DER as `PUBLIC KEY` for a public key and as
1290
- `PRIVATE KEY` for a private key). Text before the PEM block and an
1291
- `EC PARAMETERS` block are ignored.
1292
-
1293
- | Key | Accepted PEM types |
1294
- |---|---|
1295
- | Public key (`rsaEncrypt`, `verify`) | `PUBLIC KEY` (SubjectPublicKeyInfo), `RSA PUBLIC KEY` (PKCS #1), `CERTIFICATE` (X.509; only its public key is used) |
1296
- | Private key (`rsaDecrypt`, `sign`) | `PRIVATE KEY` (PKCS #8), `RSA PRIVATE KEY` (PKCS #1), `EC PRIVATE KEY` (SEC1) |
1297
-
1298
- RSA keys must be 2048 to 4096 bits. EC keys must use the P-256, P-384, or P-521
1299
- curve. Encrypted private keys (`ENCRYPTED PRIVATE KEY`, or PEM with
1300
- `Proc-Type` headers) and OpenSSH keys are not supported; store the unencrypted
1301
- PKCS #8 key as a secret instead. Key text is limited to 16,384 characters. A
1302
- certificate is not checked for expiry, revocation, or its issuer: it is only a
1303
- container for the public key.
1304
-
1305
- ### `crypto.aesEncrypt(key, data, options?): Promise<AesEncryptResult>`
1306
-
1307
- ```typescript
1308
- type AesMode = "GCM" | "CBC";
1309
-
1310
- interface AesEncryptOptions {
1311
- readonly mode?: AesMode; // Default "GCM"
1312
- readonly iv?: string | Uint8Array; // Default: random
1313
- readonly aad?: string | Uint8Array; // GCM only
1314
- readonly separateTag?: boolean; // GCM only, default false
1315
- readonly encoding?: BinaryEncoding; // Default "base64"
1316
- }
1317
-
1318
- interface AesEncryptResult {
1319
- readonly ciphertext: string;
1320
- readonly iv: string;
1321
- readonly tag?: string; // Only with separateTag
1322
- }
1323
- ```
1324
-
1325
- Encrypts `data` (a string is encoded as UTF-8) and returns the ciphertext and IV in
1326
- `encoding`.
1327
-
1328
- - `"GCM"` (default) is authenticated encryption: decryption detects any change to
1329
- the ciphertext, IV, tag, or `aad`. `ciphertext` is the encrypted data followed by
1330
- the 16-byte authentication tag, the form used by Java, .NET, and Web Crypto.
1331
- With `separateTag: true` the tag is returned in `tag` instead, as systems built
1332
- on Node.js or OpenSSL usually expect.
1333
- - `"CBC"` uses PKCS #7 padding. It does not detect changes to the ciphertext; use
1334
- it only when an external system requires it, and authenticate the ciphertext
1335
- separately, for example with `hmacSha256`.
1336
- - Without `iv`, a random IV is generated: 12 bytes for GCM and 16 bytes for CBC.
1337
- A given `iv` must be 12 to 16 bytes for GCM and exactly 16 bytes for CBC; a
1338
- string `iv` is decoded with `encoding`. **Never use the same IV twice with the
1339
- same GCM key**: doing so breaks both confidentiality and authentication. Pass
1340
- an IV only when an external system dictates it.
1341
- - `aad` is additional data that is authenticated but not encrypted, such as a
1342
- record ID; a string is encoded as UTF-8. The same `aad` must be given to
1343
- decryption.
1344
-
1345
- ### `crypto.aesDecrypt(key, ciphertext, options): Promise<string | Uint8Array>`
1346
-
1347
- ```typescript
1348
- interface AesDecryptOptions {
1349
- readonly mode?: AesMode; // Default "GCM"
1350
- readonly iv: string | Uint8Array;
1351
- readonly tag?: string | Uint8Array; // GCM only, when not appended to the ciphertext
1352
- readonly aad?: string | Uint8Array; // GCM only
1353
- readonly encoding?: BinaryEncoding; // Of a string ciphertext, iv, and tag; default "base64"
1354
- readonly output?: DecryptOutput; // Default "utf8"
1355
- }
1356
- ```
1357
-
1358
- Decrypts an AES ciphertext. `iv` is required. In GCM mode, the last 16 bytes of
1359
- `ciphertext` are the tag unless `tag` is given. `output` selects the result:
1360
- `"utf8"` (default) decodes the plaintext as UTF-8 text and throws
1361
- `ValidationError` if it is not valid UTF-8, `"bytes"` returns a `Uint8Array`, and
1362
- `"base64"`, `"base64url"`, or `"hex"` return the plaintext bytes in that encoding.
1363
-
1364
- A wrong key, IV, tag, or `aad`, a modified ciphertext, or invalid CBC padding
1365
- throws `CogoverApiError` with `code: "DECRYPTION_FAILED"`. The error is the same
1366
- for every cause, so that the result reveals nothing about the key or plaintext.
1367
-
1368
- ```typescript
1369
- import { crypto, CogoverApiError, defineScript } from "@cogover/sdk";
1370
-
1371
- export default defineScript(async ({ request }) => {
1372
- const { data, iv, tag } = request.body as { data: string; iv: string; tag: string };
1373
- try {
1374
- const json = await crypto.aesDecrypt({ secret: "partner_aes_key", encoding: "base64" }, data, { iv, tag });
1375
- return { payment: JSON.parse(json) };
1376
- } catch (error) {
1377
- if (error instanceof CogoverApiError && error.code === "DECRYPTION_FAILED") {
1378
- return { r: 1001, msg: "The payload could not be decrypted." };
1379
- }
1380
- throw error;
1381
- }
1382
- });
1383
- ```
1384
-
1385
- ### `crypto.rsaEncrypt(publicKey, data, options?)` and `crypto.rsaDecrypt(privateKey, ciphertext, options?)`
1386
-
1387
- ```typescript
1388
- type RsaPadding = "OAEP-SHA256" | "OAEP-SHA1" | "PKCS1";
1389
-
1390
- interface RsaEncryptOptions {
1391
- readonly padding?: RsaPadding; // Default "OAEP-SHA256"
1392
- readonly encoding?: BinaryEncoding; // Of the ciphertext; default "base64"
1393
- }
1394
-
1395
- interface RsaDecryptOptions {
1396
- readonly padding?: RsaPadding; // Default "OAEP-SHA256"
1397
- readonly encoding?: BinaryEncoding; // Of a string ciphertext; default "base64"
1398
- readonly output?: DecryptOutput; // Default "utf8"
1399
- }
1400
- ```
1401
-
1402
- `rsaEncrypt` encrypts `data` (a string is encoded as UTF-8) with an RSA public key
1403
- and returns the ciphertext in `encoding`. `rsaDecrypt` decrypts it with the
1404
- matching private key and returns the plaintext as `output`, like `aesDecrypt`.
1405
-
1406
- - `"OAEP-SHA256"` (default) is RSA-OAEP with SHA-256, and its mask generation
1407
- function MGF1 also uses SHA-256, as in Web Crypto, Node.js, and OpenSSL.
1408
- `"OAEP-SHA1"` uses SHA-1 for both. Some Java code written as
1409
- `OAEPWithSHA-256AndMGF1Padding` keeps MGF1 on SHA-1 and is compatible with
1410
- neither; ask the other system which digest its MGF1 uses.
1411
- - `"PKCS1"` is PKCS #1 v1.5 padding. Use it only when an external system requires
1412
- it.
1413
- - RSA encrypts only a small amount of data: at most the key size in bytes minus
1414
- 66 bytes for `"OAEP-SHA256"`, minus 42 for `"OAEP-SHA1"`, and minus 11 for
1415
- `"PKCS1"` — 190, 214, and 245 bytes for a 2048-bit key. Larger data throws
1416
- `ValidationError`. To send more, encrypt the data with `aesEncrypt` under a
1417
- random key from `randomBytes(32)` and encrypt only that key with `rsaEncrypt`.
1418
- - A decryption that fails for any reason throws `CogoverApiError` with
1419
- `code: "DECRYPTION_FAILED"`.
1420
-
1421
- ```typescript
1422
- const cardToken = await crypto.rsaEncrypt({ secret: "bank_public_key" }, "4111111111111111");
1423
- const plain = await crypto.rsaDecrypt({ secret: "our_private_key" }, request.body.data as string);
1424
- ```
1425
-
1426
- ### `crypto.sign(algorithm, privateKey, data, options?)` and `crypto.verify(algorithm, publicKey, data, signature, options?)`
1427
-
1428
- ```typescript
1429
- type SignatureAlgorithm =
1430
- | "RSA-SHA1" | "RSA-SHA256" | "RSA-SHA384" | "RSA-SHA512"
1431
- | "RSA-PSS-SHA256" | "RSA-PSS-SHA384" | "RSA-PSS-SHA512"
1432
- | "ECDSA-SHA256" | "ECDSA-SHA384" | "ECDSA-SHA512";
1433
-
1434
- interface SignatureOptions {
1435
- readonly encoding?: BinaryEncoding; // Of the signature; default "base64"
1436
- readonly signatureFormat?: "der" | "ieee-p1363"; // ECDSA only; default "der"
1437
- }
1438
- ```
1439
-
1440
- `sign` signs `data` (a string is encoded as UTF-8) with a private key and returns
1441
- the signature in `encoding`. `verify` returns `true` when `signature` is a valid
1442
- signature of `data` for the public key, and `false` otherwise, including when the
1443
- signature cannot be decoded or has the wrong length; a signature normally comes
1444
- from the party being verified, so a malformed one is not an error. An invalid
1445
- key or algorithm still throws `ValidationError`.
1446
-
1447
- - `RSA-SHA*` is RSASSA-PKCS1-v1_5 and requires an RSA key. `RSA-SHA1` exists only
1448
- to verify signatures of systems that still use it; do not use it for new
1449
- signatures.
1450
- - `RSA-PSS-SHA*` is RSASSA-PSS with MGF1 on the same digest and a salt as long as
1451
- the digest (32, 48, or 64 bytes), and requires an RSA key.
1452
- - `ECDSA-SHA*` requires an EC key. `signatureFormat` is `"der"` (ASN.1, used by
1453
- OpenSSL and Java) or `"ieee-p1363"` (the fixed-length `r || s` form used by JWT
1454
- and Web Crypto); it is rejected for RSA algorithms.
1455
-
1456
- | JWT `alg` | `algorithm` | Options |
1457
- |---|---|---|
1458
- | `RS256`, `RS384`, `RS512` | `RSA-SHA256`, `RSA-SHA384`, `RSA-SHA512` | `{ encoding: "base64url" }` |
1459
- | `PS256`, `PS384`, `PS512` | `RSA-PSS-SHA256`, `RSA-PSS-SHA384`, `RSA-PSS-SHA512` | `{ encoding: "base64url" }` |
1460
- | `ES256`, `ES384`, `ES512` | `ECDSA-SHA256`, `ECDSA-SHA384`, `ECDSA-SHA512` | `{ encoding: "base64url", signatureFormat: "ieee-p1363" }` |
1461
-
1462
- ```typescript
1463
- // Verify an ES256 JWT issued by a partner. Also check its claims (exp, iss, aud) before trusting it.
1464
- const [header, payload, signature] = token.split(".");
1465
- const valid = await crypto.verify("ECDSA-SHA256", { secret: "partner_jwt_public_key" },
1466
- `${header}.${payload}`, signature ?? "", { encoding: "base64url", signatureFormat: "ieee-p1363" });
1467
- if (!valid) return response.empty({ status: 401 });
1468
-
1469
- // Sign a request to a bank that expects SHA256withRSA in base64.
1470
- const body = JSON.stringify(order);
1471
- const bankSignature = await crypto.sign("RSA-SHA256", { secret: "bank_signing_key" }, body);
1472
- ```
1473
-
1474
- ### Limits and availability
1475
-
1476
- `data`, `aad`, and an explicit HMAC key are limited to 256 KiB, and a ciphertext
1477
- to 256 KiB plus its tag; larger values and invalid arguments throw
1478
- `ValidationError` before the call. The key, algorithm, and option errors that
1479
- Cogover detects, such as a key of the wrong size or type, also throw
1480
- `ValidationError`. Every operation except `timingSafeEqual` is a capability call
1481
- and counts towards the invocation's limits.
1482
-
1483
- The operations work in every context, including before-change triggers, with a key
1484
- given in the call. A `{ secret }` key follows the rules of `secrets.get`: a
1485
- before-change trigger is refused with `PermissionDeniedError`
1486
- (`details.reason === "TRIGGER_READ_ONLY"`) and a local development session without
1487
- secret access with `details.reason === "SECRETS_NOT_ALLOWED"`.
1488
-
1489
- ## Inbound webhooks
1490
-
1491
- An administrator can create an **inbound access** for a project so that an external
1492
- system calls a route without a Cogover user session. The external system receives
1493
- a URL of the form
1494
-
1495
- ```text
1496
- https://{WORKSPACE_DOMAIN}/api/v1/ts-projects/{projectSlug}/hooks/{inboundId}/{route}
1497
- ```
1498
-
1499
- and authenticates each call with the inbound key or the HMAC signature that was
1500
- configured for the inbound access. Cogover verifies the key or signature, applies
1501
- the rate limit, and rejects the call before any project code runs. A route handler
1502
- sees such a call as `request.path === "/hooks/{route}"`: register webhook routes
1503
- under `/hooks/` and the inbound ID is not part of the path.
1504
-
1505
- ```typescript
1506
- import { createRouter } from "@cogover/sdk";
1507
-
1508
- const router = createRouter();
1509
- router.post("/hooks/payments", async ({ request, invocation, crypto, jobs, response }) => {
1510
- if (invocation.identity !== "inbound") return response.empty({ status: 403 });
1511
-
1512
- // Optional: verify the external system's own signature over the raw body.
1513
- const expected = await crypto.hmacSha256({ secret: "payment_signing_secret" }, request.rawBody ?? "");
1514
- if (!crypto.timingSafeEqual(expected, request.headers["x-payment-signature"] ?? "")) {
1515
- return response.empty({ status: 401 });
1516
- }
1517
-
1518
- const event = request.body as { id: string; orderId: string };
1519
- await jobs.enqueue("sync_payment", event, { idempotencyKey: `payment:${event.id}` });
1520
- return response.json({ received: true }, { status: 202 });
1521
- });
1522
- export default router.toHandler();
1523
- ```
1524
-
1525
- - **Identity.** `invocation.identity` is `"inbound"`, `invocation.user` is `null`,
1526
- and `invocation.inbound` holds the `id`, `name`, and authentication `mode` of the
1527
- inbound access. `data.object()` acts as the system identity and works only if the
1528
- project's approved identity policy sets `allowInternalSystem: true`; otherwise its
1529
- calls throw `PermissionDeniedError` with `details.reason` `"IDENTITY_NOT_GRANTED"`.
1530
- `data.asUser()` and `data.asSystem()` follow the identity policy as usual.
1531
- - **Body.** The request body is limited to 256 KiB. When it is a JSON object it is
1532
- `request.body`; a form, text, or other body leaves `request.body` empty (`{}`).
1533
- `request.rawBody` always holds the body exactly as received, as a UTF-8 string,
1534
- and `request.contentType` the request's `Content-Type`, so a handler can verify a
1535
- signature or parse another format itself.
1536
- - **Response.** The handler's return value and the `response` helpers work as for
1537
- any route. Keep the handler short: acknowledge the event and enqueue a job for
1538
- the actual work, so that the external system gets a quick answer and retries
1539
- cannot overlap with slow processing.
1540
- - **Retries.** External systems usually retry a webhook that did not receive a
1541
- 2xx response, so a handler may see the same event more than once. Use the event's
1542
- own identifier as the `idempotencyKey` of the job it enqueues, or as a state key.
1543
- An `Idempotency-Key` request header works as for any route.
1544
-
1545
- ## Record API
1546
-
1547
- ```typescript
1548
- const orders = data.object("order");
1549
- await orders.records.get(id, { fields });
1550
- await orders.records.getMany(ids, { fields });
1551
- await orders.records.list({ where, orderBy, fields, limit, cursor });
1552
- await orders.records.create(fields);
1553
- await orders.records.update(id, fields);
1554
- await orders.records.batchInsert(records);
1555
- await orders.records.batchUpdate(records);
1556
- await orders.records.upsertByUniqueField(matchBy, fields);
1557
- await orders.records.deleteMany(ids);
1558
- ```
1559
-
1560
- ### Record values and results
1561
-
1562
- ```typescript
1563
- type CogoverRecordId = string & {
1564
- readonly __cogoverRecordIdBrand: unique symbol;
1565
- };
1566
-
1567
- interface RecordReference<ObjectSlug extends string = string> {
1568
- readonly id: CogoverRecordId;
1569
- readonly name: string;
1570
- readonly objectSlug?: ObjectSlug;
1571
- }
1572
-
1573
- interface UrlValue {
1574
- readonly url: string;
1575
- readonly alias?: string;
1576
- }
1577
-
1578
- interface FileValue {
1579
- readonly id: string;
1580
- readonly name: string;
1581
- readonly size?: number;
1582
- readonly contentType?: string;
1583
- readonly url?: string;
1584
- }
1585
-
1586
- interface CogoverRecord<Fields> {
1587
- readonly id: CogoverRecordId;
1588
- readonly fields: Readonly<Fields>;
1589
- readonly system: {
1590
- readonly createdAt: number;
1591
- readonly updatedAt: number;
1592
- readonly createdBy?: { readonly id: string; readonly name: string };
1593
- };
1594
- }
1595
-
1596
- interface RecordPage<Fields> {
1597
- readonly items: CogoverRecord<Fields>[];
1598
- readonly total: number;
1599
- readonly nextCursor?: string;
1600
- }
1601
-
1602
- interface GetManyResult<Fields> {
1603
- readonly records: CogoverRecord<Fields>[];
1604
- readonly missingIds: CogoverRecordId[];
1605
- }
1606
-
1607
- interface DeleteResult {
1608
- readonly deleted: CogoverRecordId[];
1609
- readonly notDeleted: CogoverRecordId[];
1610
- }
1611
-
1612
- interface BatchWriteRowResult {
1613
- readonly referenceId: string;
1614
- readonly id?: CogoverRecordId;
1615
- readonly r: number;
1616
- readonly msg?: string;
1617
- readonly success: boolean;
1618
- }
1619
-
1620
- interface BatchWriteResponse {
1621
- readonly r: number;
1622
- readonly msg?: string;
1623
- readonly results: readonly BatchWriteRowResult[];
1624
- readonly success: boolean;
1625
- }
1626
-
1627
- interface BatchUpdateItem<Fields> {
1628
- readonly id: CogoverRecordId;
1629
- readonly fields: UpdateFields<Fields>;
1630
- }
1631
-
1632
- interface UpsertResult {
1633
- readonly id: CogoverRecordId;
1634
- readonly created: boolean;
1635
- }
1636
- ```
1637
-
1638
- `CreateFields<Fields>` and `UpdateFields<Fields>` are partial mapped types over the
1639
- workspace fields. Reference values accept a string, `CogoverRecordId`, or matching
1640
- `RecordReference`; array fields accept readonly arrays. `UpsertFields<Fields,
1641
- MatchBy>` is a create-field map that requires the selected match field to be present
1642
- and non-null.
1643
-
1644
- ### Data clients and operations
1645
-
1646
- ```typescript
1647
- interface GetRecordOptions<Fields> {
1648
- readonly fields?: readonly (keyof Fields & string)[];
1649
- }
1650
-
1651
- interface GetManyOptions<Fields> {
1652
- readonly fields: readonly (keyof Fields & string)[];
1653
- }
1654
-
1655
- interface ListOptions<Fields> {
1656
- readonly where?: FilterExpression;
1657
- readonly orderBy?: readonly SortExpression[];
1658
- readonly fields?: readonly (keyof Fields & string)[];
1659
- readonly limit?: number;
1660
- readonly cursor?: string;
1661
- }
1662
-
1663
- interface RecordWritesApi<Fields> {
1664
- create(fields: CreateFields<Fields>): Promise<CogoverRecordId>;
1665
- update(id: CogoverRecordId, fields: UpdateFields<Fields>): Promise<void>;
1666
- batchInsert(records: readonly CreateFields<Fields>[]): Promise<BatchWriteResponse>;
1667
- batchUpdate(records: readonly BatchUpdateItem<Fields>[]): Promise<BatchWriteResponse>;
1668
- upsertByUniqueField<MatchBy extends keyof Fields & string>(
1669
- matchBy: MatchBy,
1670
- fields: UpsertFields<Fields, MatchBy>,
1671
- ): Promise<UpsertResult>;
1672
- deleteMany(ids: readonly CogoverRecordId[]): Promise<DeleteResult>;
1673
- }
1674
-
1675
- interface RecordsApi<Fields> extends RecordWritesApi<Fields> {
1676
- get(id: string, options?: GetRecordOptions<Fields>): Promise<CogoverRecord<Fields> | null>;
1677
- getMany(ids: readonly string[], options: GetManyOptions<Fields>): Promise<GetManyResult<Fields>>;
1678
- list(options?: ListOptions<Fields>): Promise<RecordPage<Fields>>;
1679
- }
1680
-
1681
- interface WriteObjectClient<Fields> {
1682
- readonly slug: string;
1683
- readonly fields: FieldReferences<Fields>;
1684
- readonly records: RecordWritesApi<Fields>;
1685
- }
1686
-
1687
- interface ObjectClient<Fields> extends WriteObjectClient<Fields> {
1688
- readonly records: RecordsApi<Fields>;
1689
- }
1690
-
1691
- interface AsUserDataApi<Schema extends object = EffectiveWorkspaceObjects> {
1692
- object<Slug extends keyof Schema & string>(slug: Slug): ObjectClient<Schema[Slug]>;
1693
- }
1694
-
1695
- interface DataApi<Schema extends object = EffectiveWorkspaceObjects> {
1696
- object<Slug extends keyof Schema & string>(slug: Slug): ObjectClient<Schema[Slug]>;
1697
- asUser(personnelId: string): AsUserDataApi<Schema>;
1698
- asSystem(): DataApi<Schema>;
1699
- }
1700
- ```
1701
-
1702
- `list` returns `RecordPage<T>` with `items`, `total`, and an optional opaque
1703
- `nextCursor`. A `CogoverRecord<T>` has `id`, business `fields`, and a separate
1704
- `system` object containing creation/update metadata.
1705
-
1706
- `getMany(ids, { fields })` reads up to 200 records by ID with a single capability
1707
- call. `fields` is required and must be a non-empty list of field slugs. IDs are
1708
- trimmed and deduplicated in their original order; more than 200 unique IDs, a blank
1709
- ID, or an invalid `fields` list throws `ValidationError` before any request is sent.
1710
- An empty `ids` array resolves to `{ records: [], missingIds: [] }` without a request.
1711
- The result contains the readable `records` and `missingIds`: every requested ID that
1712
- could not be read, because the record does not exist or the identity in use cannot
1713
- see it. IDs are never dropped silently. The order of `records` is not guaranteed to
1714
- follow `ids`, so index them by `id`:
1715
-
1716
- ```typescript
1717
- const accounts = data.object("account");
1718
- const { records, missingIds } = await accounts.records.getMany(accountIds, { fields: ["credit_limit"] });
1719
- const accountById = new Map(records.map(record => [record.id, record]));
1720
- ```
1721
-
1722
- Use `getMany` instead of calling `get` in a loop. Every capability call counts
1723
- towards the project's limits, and a record trigger can receive 200 records at once.
1724
-
1725
- Service `0`/`1` booleans are normalized to JavaScript booleans. Lookup/reference
1726
- responses expose only `id`, `name`, and `objectSlug`; writes accept an ID or a
1727
- `RecordReference` and send only the ID to Cogover.
1728
-
1729
- ## Filters and sorting
1730
-
1731
- ```typescript
1732
- type FilterOperator =
1733
- | "=" | "!=" | ">" | ">=" | "<" | "<="
1734
- | "like" | "not like" | "startsWith" | "endsWith"
1735
- | "in" | "not in" | "is null" | "not null" | "between";
1736
-
1737
- interface FilterCondition {
1738
- readonly kind: "condition";
1739
- readonly field: string;
1740
- readonly operator: FilterOperator;
1741
- readonly value?: unknown;
1742
- }
1743
-
1744
- interface FilterGroup {
1745
- readonly kind: "group";
1746
- readonly operator: "and" | "or";
1747
- readonly expressions: readonly FilterExpression[];
1748
- }
1749
-
1750
- type FilterExpression = FilterCondition | FilterGroup;
1751
-
1752
- interface SortExpression {
1753
- readonly field: string;
1754
- readonly direction: "asc" | "desc";
1755
- }
1756
-
1757
- interface FieldReference<Value> {
1758
- readonly slug: string;
1759
- eq(value: NonNullable<Value>): FilterCondition;
1760
- neq(value: NonNullable<Value>): FilterCondition;
1761
- gt(value: NonNullable<Value>): FilterCondition;
1762
- gte(value: NonNullable<Value>): FilterCondition;
1763
- lt(value: NonNullable<Value>): FilterCondition;
1764
- lte(value: NonNullable<Value>): FilterCondition;
1765
- like(value: string): FilterCondition;
1766
- notLike(value: string): FilterCondition;
1767
- startsWith(value: string): FilterCondition;
1768
- endsWith(value: string): FilterCondition;
1769
- in(values: readonly (
1770
- NonNullable<Value> extends readonly (infer Item)[] ? NonNullable<Item> : NonNullable<Value>
1771
- )[]): FilterCondition;
1772
- notIn(values: readonly (
1773
- NonNullable<Value> extends readonly (infer Item)[] ? NonNullable<Item> : NonNullable<Value>
1774
- )[]): FilterCondition;
1775
- isNull(): FilterCondition;
1776
- notNull(): FilterCondition;
1777
- between(from: NonNullable<Value>, to: NonNullable<Value>): FilterCondition;
1778
- asc(): SortExpression;
1779
- desc(): SortExpression;
1780
- }
1781
- ```
1782
-
1783
- Each `FieldReference<Value>` exposes `slug`, `eq`, `neq`, `gt`, `gte`, `lt`,
1784
- `lte`, `like`, `notLike`, `startsWith`, `endsWith`, `in`, `notIn`, `isNull`,
1785
- `notNull`, `between`, `asc`, and `desc`. `FieldReferences<Fields>` provides these
1786
- references for workspace fields and the system fields `id`, `created`, `updated`,
1787
- and `created_by`. `and(...expressions)` and `or(...expressions)` return a
1788
- `FilterGroup` and require at least one expression.
1789
- For array-valued fields, `in` and `notIn` accept the array's element type.
1790
-
1791
- Transport-specific field metadata and response envelopes are handled by Cogover.
1792
-
1793
- `create` and `update` require a non-empty field object. `batchInsert` accepts 1–200
1794
- field objects; `batchUpdate` accepts 1–200 `{ id, fields }` items. Both are
1795
- best-effort operations: their `BatchWriteResponse`
1796
- contains one result per input row, and callers must inspect the top-level `success`
1797
- flag or each row's `success`, `r`, and `msg`. A successful request is not an
1798
- all-or-none transaction and does not guarantee that every row was written.
1799
- `referenceId` identifies the zero-based input index as a string.
1800
-
1801
- `deleteMany` requires at least one non-blank record ID and returns separate
1802
- `deleted` and `notDeleted` arrays. Record IDs, object slugs, and field slugs are
1803
- validated before a request is sent.
1804
-
1805
- `upsertByUniqueField(matchBy, fields)` updates the record whose configured unique
1806
- field equals `fields[matchBy]`, or creates it when no record matches. The match field
1807
- must be a single, non-multiple field with uniqueness enabled, and the business key
1808
- must be non-null and non-blank. The result is `{ id, created }`. Because the server
1809
- chooses the create/update branch, the operation requires both record-create and
1810
- record-update permission.
1811
-
1812
- A unique-key conflict is exposed as `ValidationError` with
1813
- `details.reason === "UNIQUE_KEY_VIOLATION"`, `objectSlug`, and `fieldSlug`. The
1814
- public error does not echo the rejected business-key value.
1815
-
1816
- ## Record execution identities
1817
-
1818
- `data.object(slug)` inherits the invocation identity. For an authenticated public
1819
- invocation this is the caller; a system invocation keeps system access.
1820
-
1821
- ### `data.asUser(personnelId: string): AsUserDataApi<TSchema>`
1822
-
1823
- Returns a new immutable client for reads and writes as the specified personnel ID (not an
1824
- account ID), in the same workspace. `personnelId` is trimmed; a non-string or blank
1825
- value throws `ValidationError`. Its `object(slug)` returns `ObjectClient<TFields>`,
1826
- whose `records: RecordsApi<TFields>` exposes `get`, `getMany`, `list`, `create`, `update`, and
1827
- `deleteMany` as well as batch insert, batch update, and business upsert, with the
1828
- same argument and return types as the default record API.
1829
-
1830
- `get(id, options?)` returns `CogoverRecord<TFields> | null`; `list(options?)` returns
1831
- `RecordPage<TFields>`. Field selection, filters, sorting and cursors work as on the
1832
- default client. Reads apply the selected user's permissions and approved project
1833
- field restrictions. An empty successful lookup returns `null`; server failures
1834
- throw errors instead of being treated as missing records or an empty page.
1835
-
1836
- ```typescript
1837
- const delegatedOrders = data.asUser(personnelId).object("order");
1838
- const order = await delegatedOrders.records.get(recordId, { fields: ["description"] });
1839
- const page = await delegatedOrders.records.list({
1840
- fields: ["description"],
1841
- where: delegatedOrders.fields.description.eq("Pending review"),
1842
- limit: 20,
1843
- });
1844
- ```
1845
-
1846
- ### `data.asSystem(): DataApi<TSchema>`
1847
-
1848
- Returns a new immutable client for system record access, including during an
1849
- authenticated public invocation. It supports `get`, `getMany`, `list`, `create`, `update`, and
1850
- `deleteMany`, including batch writes and business upsert. System access does not
1851
- apply the caller's record permissions; approved project restrictions, field
1852
- validation, workspace boundaries, and runtime limits still apply. It neither
1853
- changes the invocation's caller nor modifies existing clients.
1854
-
1855
- ```typescript
1856
- const orders = data.object("order");
1857
- await orders.records.update(order.id, { description: "Caller update" });
1858
- await data.asUser(personnelId).object("order").records.update(order.id, { description: "Delegated update" });
1859
- await data.asSystem().object("order").records.update(order.id, { description: "System update" });
1860
- ```
1861
-
1862
- Identity selection needs administrator approval for the project version, permitted
1863
- callers, target personnel, objects, operations, and fields. Selection alone grants
1864
- no permission. Unauthorized operations throw `PermissionDeniedError`; invalid or
1865
- unresolvable identities never fall back to system or caller access. Server failures
1866
- retain their original `CogoverApiError.r`. No credentials or workspace override are
1867
- accepted by these methods. Schema access is unchanged. Each write is independent;
1868
- the three example calls above are not a transaction.
1869
-
1870
- ## Project state
1871
-
1872
- State is durable JSON scoped by workspace, project, namespace, and key. It is not
1873
- version-scoped, so it remains available after a new project version is published.
1874
-
1875
- ```typescript
1876
- interface StateEntry<T> {
1877
- readonly value: T;
1878
- readonly version: number;
1879
- readonly expiresAt?: number;
1880
- readonly createdAt: number;
1881
- readonly updatedAt: number;
1882
- }
1883
-
1884
- interface StateWriteOptions {
1885
- readonly expectedVersion?: number;
1886
- readonly ttlSeconds?: number;
1887
- }
1888
-
1889
- interface StateDeleteOptions {
1890
- readonly expectedVersion?: number;
1891
- }
1892
-
1893
- interface StateNamespace {
1894
- readonly name: string;
1895
- get<T>(key: string): Promise<StateEntry<T> | null>;
1896
- set<T>(key: string, value: T, options?: StateWriteOptions): Promise<StateEntry<T>>;
1897
- delete(key: string, options?: StateDeleteOptions): Promise<boolean>;
1898
- }
1899
-
1900
- interface ProjectState {
1901
- namespace(name: string): StateNamespace;
1902
- }
1903
- ```
1904
-
1905
- ```typescript
1906
- const progress = state.namespace("inventory-sync");
1907
- const current = await progress.get<{ cursor: string }>("cursor");
1908
-
1909
- const saved = await progress.set("cursor", { cursor: "next-page" }, {
1910
- expectedVersion: current?.version ?? 0,
1911
- ttlSeconds: 3600,
1912
- });
1913
-
1914
- await progress.delete("cursor", { expectedVersion: saved.version });
1915
- ```
1916
-
1917
- ### `state.namespace(name): StateNamespace`
1918
-
1919
- Creates an immutable namespace client. Namespaces are at most 128 characters and
1920
- keys at most 255. Both start with an ASCII letter or digit and may contain letters,
1921
- digits, `.`, `_`, `:`, `/`, and `-`.
1922
-
1923
- ### `namespace.get<T>(key): Promise<StateEntry<T> | null>`
1924
-
1925
- Returns `null` when the entry is missing or expired. An entry contains `value`,
1926
- `version`, `createdAt`, `updatedAt`, and optional `expiresAt`; timestamps are Unix
1927
- milliseconds.
1928
-
1929
- ### `namespace.set<T>(key, value, options?): Promise<StateEntry<T>>`
1930
-
1931
- Stores a JSON value of at most 32 KiB (32,768 UTF-8 bytes after serialization).
1932
- `ttlSeconds` ranges from one second through 365 days; omit it for no automatic
1933
- expiry. Both option values must be safe integers. `expectedVersion` enables
1934
- compare-and-set: `0` means create only, a positive value must match the current
1935
- version, and omission is an unconditional upsert.
1936
- Conflicts throw `StateConflictError`; the returned entry has the new version.
1937
-
1938
- ### `namespace.delete(key, options?): Promise<boolean>`
1939
-
1940
- Deletes an entry and returns whether it existed. `expectedVersion` has the same CAS
1941
- meaning as on `set`. Expired entries are treated as absent. State operations do not
1942
- form a transaction with Record API calls. Do not use state for secrets, files, or
1943
- large data.
1944
-
1945
- ## Distributed locks
1946
-
1947
- Locks are distributed leases scoped by workspace, project, namespace, and key. They
1948
- prevent concurrent executions from entering the same protected section. Prefer
1949
- `withLock` for automatic release:
1950
-
1951
- ```typescript
1952
- interface LockOptions {
1953
- readonly namespace?: string;
1954
- readonly waitMs?: number;
1955
- readonly leaseMs?: number;
1956
- }
1957
-
1958
- interface LockLease {
1959
- readonly id: string;
1960
- readonly key: string;
1961
- readonly namespace: string;
1962
- readonly fencingToken: number;
1963
- readonly expiresAt: number;
1964
- renew(leaseMs?: number): Promise<void>;
1965
- release(): Promise<void>;
1966
- }
1967
-
1968
- interface DistributedLocks {
1969
- acquire(key: string, options?: LockOptions): Promise<LockLease | null>;
1970
- withLock<T>(key: string, callback: (lease: LockLease) => T | Promise<T>): Promise<T>;
1971
- withLock<T>(key: string, options: LockOptions,
1972
- callback: (lease: LockLease) => T | Promise<T>): Promise<T>;
1973
- }
1974
- ```
1975
-
1976
- ```typescript
1977
- await locks.withLock("INV-1", { namespace: "invoice", waitMs: 500 }, async lease => {
1978
- await processInvoice("INV-1", lease.fencingToken);
1979
- // Renew only if work can approach expiresAt.
1980
- // await lease.renew(30_000);
1981
- });
1982
- ```
1983
-
1984
- ### `locks.acquire(key, options?): Promise<LockLease | null>`
1985
-
1986
- Returns a lease, or `null` when it cannot acquire one within `waitMs`. The namespace
1987
- defaults to `default`; `waitMs` ranges from 0 through 10,000 ms; `leaseMs` ranges
1988
- from 5,000 through 60,000 ms and defaults to 30,000 ms. One invocation may hold at
1989
- most 16 locks. Keys are at most 255 characters and namespaces at most 128; both use
1990
- the same character rules as state names. Numeric options must be safe integers.
1991
-
1992
- A lease exposes `id`, `key`, `namespace`, `fencingToken`, `expiresAt`,
1993
- `renew(leaseMs?)`, and `release()`. Renew and release verify ownership with a
1994
- token managed by Cogover; that token is never exposed to scripts. A lost or expired
1995
- lease throws `LockLostError`. Repeated `release()` on the same successfully released
1996
- lease object is a no-op.
1997
-
1998
- ### `locks.withLock(key, callback)` / `locks.withLock(key, options, callback)`
1999
-
2000
- Acquires the lock, runs the callback, and releases in `finally`. Failure to acquire
2001
- throws `LockUnavailableError`. It does not auto-renew; long callbacks must call
2002
- `lease.renew()` before `expiresAt`.
2003
-
2004
- A lock only guarantees one valid lease at a time. Timeouts, pauses, or network
2005
- failures may let old work continue after its lease expires. When the downstream
2006
- system supports it, store/check `fencingToken` and reject stale tokens. Locks do not
2007
- replace idempotency, provide exactly-once execution, or combine Record API and state
2008
- operations into a transaction.
2009
-
2010
- ## Push messages
2011
-
2012
- `push` sends messages to the web clients of the workspace: a request to reload
2013
- records, a toast, or a background message the client handles silently. It is the
2014
- same mechanism as the Workflow "Push Message" action, so the standard record pages
2015
- react without custom client code. Delivery is best-effort: a call resolves once the
2016
- messages are handed to Cogover, never when a client receives them.
2017
-
2018
- ```typescript
2019
- type PushRecipients = "viewers" | readonly string[];
2020
-
2021
- interface PushOptions {
2022
- readonly recipients?: PushRecipients;
2023
- readonly exclude?: readonly string[];
2024
- }
2025
-
2026
- type ToastPosition = "TOP_LEFT" | "TOP_CENTER" | "TOP_RIGHT"
2027
- | "BOTTOM_LEFT" | "BOTTOM_CENTER" | "BOTTOM_RIGHT";
2028
- type ToastSize = "SMALL" | "MEDIUM" | "LARGE";
2029
-
2030
- interface ToastLink {
2031
- readonly label: string;
2032
- readonly url: string;
2033
- }
2034
-
2035
- interface ToastMessage<ObjectSlug extends string = string> {
2036
- readonly title?: string;
2037
- readonly content?: string;
2038
- readonly links?: readonly ToastLink[];
2039
- readonly position?: ToastPosition;
2040
- readonly size?: ToastSize;
2041
- readonly durationSeconds?: number;
2042
- readonly object?: ObjectSlug;
2043
- readonly recordIds?: readonly string[];
2044
- }
2045
-
2046
- type BackgroundContentType = "text" | "template";
2047
-
2048
- interface BackgroundMessage<ObjectSlug extends string = string> {
2049
- readonly content: string;
2050
- readonly contentType?: BackgroundContentType;
2051
- readonly object?: ObjectSlug;
2052
- readonly recordIds?: readonly string[];
2053
- }
2054
-
2055
- interface PushApi<Schema extends object = EffectiveWorkspaceObjects> {
2056
- refreshRecords(object: StringKeyOf<Schema>, recordIds: readonly string[],
2057
- options?: PushOptions): Promise<void>;
2058
- toast(message: ToastMessage<StringKeyOf<Schema>>, options?: PushOptions): Promise<void>;
2059
- message(message: BackgroundMessage<StringKeyOf<Schema>>, options?: PushOptions): Promise<void>;
2060
- }
2061
- ```
2062
-
2063
- ```typescript
2064
- // After-change trigger: the handler changed the records, so everyone who has them
2065
- // open must reload, including the user whose save started the trigger.
2066
- await data.object("order").records.batchUpdate(items);
2067
- await push.refreshRecords("order", items.map(item => item.id));
2068
- ```
2069
-
2070
- ### Recipients
2071
-
2072
- Every method accepts the same `options`. `recipients` defaults to `"viewers"`:
2073
- everyone who currently has one of the target records open receives the message, so
2074
- `object` and `recordIds` are required. A list of personnel IDs delivers to those
2075
- people wherever they are in the workspace; `object` and `recordIds` are then
2076
- optional for `toast` and `message` and, when given, tell the client which records
2077
- the message is about. `exclude` lists personnel IDs that never receive the message;
2078
- the special value `"actor"` is the user whose action started the current execution
2079
- (the caller of an HTTP script, the user whose save ran a trigger). A system
2080
- execution has no actor, so `"actor"` excludes nobody. Personnel without a user
2081
- account are skipped silently; an unknown personnel ID or object slug throws
2082
- `NotFoundError` before anything is sent. A call accepts at most 200 record IDs and
2083
- 200 personnel IDs; duplicates are removed.
2084
-
2085
- ### `push.refreshRecords(object, recordIds, options?): Promise<void>`
2086
-
2087
- Asks the clients that show these records to reload them. The record page of the
2088
- web app handles the request itself. `recordIds` accepts 1 to 200 IDs.
2089
-
2090
- ### `push.toast(message, options?): Promise<void>`
2091
-
2092
- Shows a short notification. At least one of `title` (up to 200 characters) and
2093
- `content` (up to 4,000 characters) is required. `links` holds up to 5 entries whose
2094
- `url` is an absolute `http` or `https` URL. `position` defaults to `"TOP_RIGHT"`,
2095
- `size` to `"MEDIUM"` and `durationSeconds` to 5 (1 to 60). When `object` and
2096
- `recordIds` are given, the client shows the toast only while one of those records
2097
- is open.
2098
-
2099
- ### `push.message(message, options?): Promise<void>`
2100
-
2101
- Sends a message the client handles without a visible notification, for example a
2102
- custom component listening for it. `content` is required (up to 16,384 characters);
2103
- `contentType` is `"text"` (default) or `"template"`.
2104
-
2105
- ### Rules
2106
-
2107
- - Each call costs one capability call regardless of the number of records or
2108
- recipients; when the recipients are `"viewers"`, one message is sent per record.
2109
- - Inputs are validated by the SDK and again by Cogover; invalid input throws
2110
- `ValidationError` before any message is sent.
2111
- - `push` is available in scripts, routes, after-change triggers and Development
2112
- Sessions. A before-change trigger is read-only and receives `PermissionDeniedError`
2113
- with reason `TRIGGER_READ_ONLY`; a read-only Development Session refuses it too.
2114
- - When push messages are switched off for the deployment, every call throws
2115
- `CogoverApiError` with code `PUSH_DISABLED`.
2116
- - A sent message cannot be recalled, and retrying a failed execution may send it
2117
- again.
2118
-
2119
- ## Notifications
2120
-
2121
- `notifications` saves a notification in the notification list (the bell) of each
2122
- recipient and delivers it in the web app, by web push, by mobile push, and as an
2123
- email copy, as the workspace's notification channels decide. Unlike a
2124
- [push message](#push-messages), a notification stays in the list after it was
2125
- delivered, so it suits something a person must act on later, such as an approval
2126
- request. Delivery is asynchronous and best-effort: a call resolves once Cogover has
2127
- accepted the notification, never when it reaches a device or an inbox.
2128
-
2129
- ```typescript
2130
- type NotificationContentType = "text" | "html";
2131
- type NotificationDisplay = "SIMPLE" | "FULL";
2132
- type NotificationSender = "workspace" | "actor";
2133
- type NotificationLinkTarget = "SAME_TAB" | "NEW_TAB";
2134
-
2135
- interface NotificationLink {
2136
- readonly url: string;
2137
- readonly openIn?: NotificationLinkTarget;
2138
- }
2139
-
2140
- interface NotificationMessage {
2141
- readonly to: readonly string[];
2142
- readonly exclude?: readonly string[];
2143
- readonly title: string;
2144
- readonly content: string;
2145
- readonly contentType?: NotificationContentType;
2146
- readonly subtitle?: string;
2147
- readonly display?: NotificationDisplay;
2148
- readonly link?: NotificationLink;
2149
- readonly sender?: NotificationSender;
2150
- readonly channel?: string;
2151
- readonly email?: boolean;
2152
- readonly idempotencyKey?: string;
2153
- }
2154
-
2155
- interface NotificationResult {
2156
- readonly requestId: string;
2157
- readonly notified: number;
2158
- readonly skippedPersonnelIds: readonly string[];
2159
- readonly duplicate: boolean;
2160
- }
2161
-
2162
- interface NotificationsApi {
2163
- send(message: NotificationMessage): Promise<NotificationResult>;
2164
- }
2165
- ```
2166
-
2167
- ```typescript
2168
- const result = await notifications.send({
2169
- to: approverIds,
2170
- exclude: ["actor"],
2171
- title: "Leave request waiting for your approval",
2172
- content: "A leave request of 3 days was submitted and needs your decision.",
2173
- link: { url: `/app/leave_request/${recordId}` },
2174
- channel: approvalChannelId,
2175
- idempotencyKey: `leave-approval:${recordId}`,
2176
- });
2177
- // result.notified: accounts addressed; result.skippedPersonnelIds: personnel without an account
2178
- ```
2179
-
2180
- ### `notifications.send(message): Promise<NotificationResult>`
2181
-
2182
- **Recipients.** `to` lists 1 to 200 personnel IDs; duplicates are removed. The
2183
- notification goes to the user account of each personnel. Personnel without a user
2184
- account are skipped and returned in `skippedPersonnelIds`, and `notified` is the
2185
- number of accounts the notification was addressed to after exclusions. `exclude`
2186
- lists personnel IDs that never receive it; the special value `"actor"` is the user
2187
- whose action started the current execution (the caller of an HTTP route, the user
2188
- whose save ran a trigger, the user whose call enqueued a job run). An execution
2189
- without a user has no actor, so `"actor"` excludes nobody. A personnel ID in `to`
2190
- that does not exist throws `NotFoundError` with `resource` `"personnel"` before
2191
- anything is sent. When every recipient is excluded or skipped, nothing is sent and
2192
- `notified` is `0`.
2193
-
2194
- **Content and appearance.**
2195
-
2196
- - `title` (required, at most 200 characters) is the heading of the notification and
2197
- the subject of its email copy.
2198
- - `content` (required, at most 16,384 characters) is the body. With
2199
- `contentType: "text"`, the default, it is plain text. With `"html"` it is reduced
2200
- to basic formatting before it is stored — paragraphs, headings, lists, tables,
2201
- links, and emphasis; scripts, styles, and images are removed — and it must still
2202
- contain visible text, otherwise `ValidationError` is thrown.
2203
- - `subtitle` (at most 200 characters) is shown only in the `"FULL"` display.
2204
- `display` defaults to `"FULL"` when a subtitle is given and to `"SIMPLE"`
2205
- otherwise; a subtitle together with `display: "SIMPLE"` throws `ValidationError`.
2206
- - `link` is the page opened when the recipient clicks the notification. `url` is a
2207
- path of the Cogover web app starting with `/`, or an absolute `http` or `https`
2208
- URL, at most 2,048 characters. `openIn` is `"SAME_TAB"` or `"NEW_TAB"`; it defaults
2209
- to `"SAME_TAB"` for a path and to `"NEW_TAB"` for an absolute URL.
2210
- - `sender` is `"workspace"`, the default, or `"actor"`, which shows the name and
2211
- avatar of the user whose action started the execution. `"actor"` in an execution
2212
- without a user throws `ValidationError`.
2213
-
2214
- **Channels and the email copy.** `channel` is the record ID of one of the
2215
- workspace's notification channels. The channel decides which deliveries are enabled
2216
- — in the web app, web push, mobile push, and email — and each user may override that
2217
- choice in their own notification settings. Without `channel`, every delivery is
2218
- enabled. An unknown channel throws `NotFoundError` with `resource`
2219
- `"notificationChannel"`; a workspace in which notifications are not set up throws
2220
- `NotFoundError` with `resource` `"object"` and `resourceId` `"notification_channel"`.
2221
-
2222
- `email: false` leaves out the email copy even when the channel enables email. The
2223
- copy uses `title` as its subject and `content` as its body, is sent from a Cogover
2224
- notification address rather than from a workspace mailbox, and counts against the
2225
- daily notification-email limit of the workspace's plan. To send an email from a
2226
- workspace mailbox, use [`email.send`](#email).
2227
-
2228
- **Idempotency.** `idempotencyKey` starts with a letter or digit and contains at most
2229
- 128 letters, digits, `.`, `_`, `:`, or `-`. A call whose key the project already
2230
- used for a notification in the last 7 days sends nothing and returns the first
2231
- call's result with `duplicate: true`. A call made while the first call with the same
2232
- key is still sending throws `CogoverApiError` with `code: "DUPLICATE_IN_PROGRESS"`;
2233
- retry it a moment later. A call that failed does not keep its key, so it can be
2234
- retried. Keys belong to the project and are separate from the keys of `email.send`.
2235
- In an after-change trigger or a job, which may run more than once, derive the key
2236
- from `trigger.changeId` and `record.id`, or from `job.id` or a business key.
2237
-
2238
- ### Rules
2239
-
2240
- - `notifications` is available in scripts, routes, after-change triggers, background
2241
- jobs, inbound webhook calls, and Development Sessions with write permission. A
2242
- before-change trigger is read-only and receives `PermissionDeniedError` with
2243
- `details.reason` `"TRIGGER_READ_ONLY"`; a read-only preview and a read-only
2244
- Development Session refuse it too.
2245
- - Notifications need no grant in the identity policy: a project may notify any
2246
- personnel of the workspace.
2247
- - A project may address at most 5,000 recipients per hour by default. A call that
2248
- would exceed this throws `RateLimitError` and sends nothing.
2249
- - Inputs are validated by the SDK and again by Cogover; invalid input throws
2250
- `ValidationError` before anything is sent. Each call counts as one capability call.
2251
- - When notifications are switched off for the deployment, every call throws
2252
- `CogoverApiError` with code `NOTIFICATIONS_DISABLED`.
2253
- - A sent notification cannot be recalled. Retrying a failed execution may notify
2254
- again unless the call uses an `idempotencyKey`.
2255
-
2256
- ## Email
2257
-
2258
- `email` sends email from the workspace's mailboxes: a shared workspace mailbox, or
2259
- the default personal mailbox of the user whose action started the execution. The
2260
- Project's approved identity policy decides which mailboxes a project may use. With
2261
- `record`, the email is also logged as an email activity on that record's timeline,
2262
- like an email sent from the record page. Sending is asynchronous: a call resolves
2263
- once Cogover has accepted the email for delivery, and a delivery failure after that
2264
- is not reported back to the script.
2265
-
2266
- ```typescript
2267
- type EmailSender = { readonly mailbox: string } | "actor";
2268
-
2269
- type EmailRecipient =
2270
- | string
2271
- | { readonly email: string; readonly name?: string }
2272
- | { readonly personnelId: string };
2273
-
2274
- interface EmailRecordLink<ObjectSlug extends string = string> {
2275
- readonly object: ObjectSlug;
2276
- readonly recordId: string;
2277
- }
2278
-
2279
- interface EmailAttachment<ObjectSlug extends string = string> {
2280
- readonly object: ObjectSlug;
2281
- readonly recordId: string;
2282
- readonly field: string;
2283
- }
2284
-
2285
- type EmailMessage<ObjectSlug extends string = string> = {
2286
- readonly from: EmailSender;
2287
- readonly to?: readonly EmailRecipient[];
2288
- readonly cc?: readonly EmailRecipient[];
2289
- readonly bcc?: readonly EmailRecipient[];
2290
- readonly subject: string;
2291
- readonly record?: EmailRecordLink<ObjectSlug>;
2292
- readonly recordEmailFields?: readonly string[];
2293
- readonly attachments?: readonly EmailAttachment<ObjectSlug>[];
2294
- readonly appendSignature?: boolean;
2295
- readonly idempotencyKey?: string;
2296
- } & (
2297
- | { readonly html: string; readonly text?: never }
2298
- | { readonly text: string; readonly html?: never }
2299
- );
2300
-
2301
- type EmailDelivery = "activity" | "direct";
2302
-
2303
- interface EmailSendResult {
2304
- readonly requestId: string;
2305
- readonly delivery: EmailDelivery;
2306
- readonly recipients: number;
2307
- readonly duplicate: boolean;
2308
- }
2309
-
2310
- type EmailSenderKind = "workspace" | "actor";
2311
-
2312
- interface EmailSenderInfo {
2313
- readonly id: string;
2314
- readonly kind: EmailSenderKind;
2315
- readonly email: string;
2316
- readonly displayName: string;
2317
- }
2318
-
2319
- interface EmailApi<Schema extends object = EffectiveWorkspaceObjects> {
2320
- send(message: EmailMessage<StringKeyOf<Schema>>): Promise<EmailSendResult>;
2321
- senders(): Promise<readonly EmailSenderInfo[]>;
2322
- }
2323
- ```
2324
-
2325
- ```typescript
2326
- const result = await email.send({
2327
- from: { mailbox: "EMWXXXXXXXXXXXX" },
2328
- bcc: ["sales-archive@example.com"],
2329
- subject: `Quote ${quote.fields.code}`,
2330
- html: "<p>Dear customer,</p><p>Please find our quote attached.</p>",
2331
- record: { object: "quote", recordId: quote.id },
2332
- recordEmailFields: ["contact_email"],
2333
- attachments: [{ object: "quote", recordId: quote.id, field: "quote_pdf" }],
2334
- idempotencyKey: `quote-email:${quote.id}`,
2335
- });
2336
- // result.delivery === "activity": the email appears on the quote's timeline.
2337
- ```
2338
-
2339
- ### `email.send(message): Promise<EmailSendResult>`
2340
-
2341
- **Sender.** `from: { mailbox: id }` sends from a shared workspace mailbox;
2342
- `from: "actor"` sends from the default personal mailbox of the user whose action
2343
- started the execution. The sender must be allowed by the `email` section of the
2344
- Project's approved identity policy: `workspaceMailboxIds` lists the shared mailboxes
2345
- and `allowActorMailbox` allows `"actor"`. Like the rest of the policy, the section
2346
- applies only to the callers selected by `callerPersonnelIds`, and to executions
2347
- without a user only when the policy sets `allowInternalSystem: true`. A project
2348
- whose policy has no `email` section cannot send email. A sender that is not allowed
2349
- throws `PermissionDeniedError` with `details.reason` `"EMAIL_SENDER_NOT_GRANTED"`;
2350
- this check comes before anything else is looked up. A mailbox that does not exist or
2351
- is deactivated, and an actor without an active personal mailbox, throw
2352
- `NotFoundError` with `resource` `"mailbox"`. `"actor"` in an execution without a
2353
- user throws `ValidationError`.
2354
-
2355
- **Recipients.**
2356
-
2357
- - `to`, `cc`, and `bcc` accept an address string, `{ email, name? }`, or
2358
- `{ personnelId }`. A personnel is resolved to their work email, or to the email of
2359
- their user account when there is no work email; a personnel with neither throws
2360
- `ValidationError`, and an unknown personnel throws `NotFoundError` with `resource`
2361
- `"personnel"`.
2362
- - Duplicates are removed within each list, ignoring case. The three lists together
2363
- accept at most 50 recipients. A `name` is a single line of at most 200 characters.
2364
- - `to` must name at least one recipient unless `recordEmailFields` is given.
2365
-
2366
- **Content.** `subject` is required: a single line of at most 255 characters. Provide
2367
- exactly one of `html` and `text`; the body is at most 192 KB (196,608 bytes) in
2368
- UTF-8.
2369
-
2370
- **Record.** `record: { object, recordId }` logs the email as an email activity on
2371
- that record's timeline: Cogover tracks opens and link clicks and threads replies
2372
- with it, and `result.delivery` is `"activity"`. The record must be readable by the
2373
- default identity of the execution, otherwise `NotFoundError` with `resource`
2374
- `"record"` is thrown. Without `record`, the email is only sent from the mailbox and
2375
- `delivery` is `"direct"`. The following options require `record`; without it they
2376
- throw `ValidationError`:
2377
-
2378
- - `recordEmailFields` lists up to 20 email fields of that record whose addresses are
2379
- added to `to`. A field that is not an email field throws `ValidationError`.
2380
- - `attachments` attaches every file stored in the file field `field` of each listed
2381
- record: at most 10 files and 20 MB in total. The records must be readable by the
2382
- default identity; a field that is not a file field throws `ValidationError`.
2383
- - `appendSignature: true` appends the sender's default email signature. It requires a
2384
- personal mailbox, that is `from: "actor"`; otherwise `ValidationError` is thrown.
2385
-
2386
- **Result.** `requestId` identifies the send. `recipients` counts the addresses in
2387
- `to`, `cc`, and `bcc` after duplicates were removed; the addresses of
2388
- `recordEmailFields` are resolved later and are not counted. `duplicate` is `true`
2389
- when an earlier call with the same `idempotencyKey` already sent the email.
2390
-
2391
- **Idempotency.** `idempotencyKey` follows the same rules as for
2392
- [notifications](#notifications): a retry with the same key within 7 days returns
2393
- the first result with `duplicate: true` instead of sending again, and a retry while
2394
- the first call is still sending throws `CogoverApiError` with
2395
- `code: "DUPLICATE_IN_PROGRESS"`. Email keys are separate from notification keys.
2396
-
2397
- ### `email.senders(): Promise<readonly EmailSenderInfo[]>`
2398
-
2399
- Returns the active mailboxes this execution may send from: one `kind: "workspace"`
2400
- entry for each active shared mailbox that the applicable policy lists in
2401
- `workspaceMailboxIds`, to be used as `{ mailbox: id }`, and, when the policy sets
2402
- `allowActorMailbox` and the actor has an active personal mailbox, at most one
2403
- `kind: "actor"` entry describing the mailbox that `from: "actor"` uses. The list is
2404
- empty when the policy grants this execution no sender. Use it to show the available
2405
- senders or to pick one by `email` address instead of hard-coding an ID. It sends
2406
- nothing, so it also works in a read-only preview and a read-only Development
2407
- Session.
2408
-
2409
- ### Rules
2410
-
2411
- - `email` is available in scripts, routes, after-change triggers, background jobs,
2412
- inbound webhook calls, and Development Sessions. A before-change trigger receives
2413
- `PermissionDeniedError` with `details.reason` `"TRIGGER_READ_ONLY"` for both
2414
- methods; a read-only preview and a read-only Development Session refuse
2415
- `email.send`.
2416
- - A project may send at most 500 emails per hour by default; beyond that,
2417
- `RateLimitError` is thrown and nothing is sent. One call is one email, however many
2418
- recipients it has.
2419
- - Inputs are validated by the SDK and again by Cogover; invalid input throws
2420
- `ValidationError` before anything is sent. Each call counts as one capability call.
2421
- - When email is switched off for the deployment, every call throws
2422
- `CogoverApiError` with code `EMAIL_DISABLED`.
2423
- - A sent email cannot be recalled. Retrying a failed execution may send it again
2424
- unless the call uses an `idempotencyKey`.
2425
-
2426
- ## Organization structure
2427
-
2428
- `org` reads the departments, positions and personnel of the workspace: who works in
2429
- which department, which positions apply where, and who manages whom. Every method is
2430
- a read. Structure answers are served from a cached copy of the organization, so they
2431
- are fast; a change made in Cogover is visible within a few seconds. Add
2432
- `withDisplay: true` to also receive department and position names in a language and,
2433
- for personnel, their display name, email, avatar and code. Other personnel fields,
2434
- such as phone numbers or custom fields, are read with `data.object("personnel")`,
2435
- which applies record permissions.
2436
-
2437
- ```typescript
2438
- interface OrgApi {
2439
- readonly personnel: OrgPersonnelApi;
2440
- readonly departments: OrgDepartmentsApi;
2441
- readonly positions: OrgPositionsApi;
2442
- me(options?: OrgReadOptions): Promise<OrgPersonnel | null>;
2443
- isInDepartment(personnelId: string, departmentId: string,
2444
- options?: OrgIsInDepartmentOptions): Promise<boolean>;
2445
- isManagerOf(managerId: string, personnelId: string,
2446
- options?: OrgIsManagerOfOptions): Promise<boolean>;
2447
- }
2448
-
2449
- interface OrgPersonnelApi {
2450
- get(id: string, options?: OrgReadOptions): Promise<OrgPersonnel | null>;
2451
- getMany(ids: readonly string[], options?: OrgReadOptions):
2452
- Promise<OrgGetManyResult<OrgPersonnel>>;
2453
- managerChain(id: string, options?: OrgPersonnelChainOptions):
2454
- Promise<readonly OrgManagerChain[]>;
2455
- }
2456
-
2457
- interface OrgDepartmentsApi {
2458
- get(id: string, options?: OrgReadOptions): Promise<OrgDepartment | null>;
2459
- tree(options?: OrgTreeOptions): Promise<readonly OrgDepartmentNode[]>;
2460
- ancestors(id: string, options?: OrgReadOptions): Promise<readonly OrgDepartment[]>;
2461
- members(id: string, options?: OrgDepartmentMembersOptions): Promise<OrgPage<OrgMember>>;
2462
- managers(id: string, options?: OrgManagerOptions): Promise<readonly OrgManagerTier[]>;
2463
- managerChain(id: string, options?: OrgManagerOptions): Promise<OrgManagerChain>;
2464
- }
2465
-
2466
- interface OrgPositionsApi {
2467
- list(options?: OrgReadOptions): Promise<readonly OrgPosition[]>;
2468
- get(id: string, options?: OrgReadOptions): Promise<OrgPosition | null>;
2469
- members(id: string, options?: OrgPositionMembersOptions): Promise<OrgPage<OrgMember>>;
2470
- }
2471
- ```
2472
-
2473
- Every method that returns data has a second overload: when `options.withDisplay` is
2474
- the literal `true`, the result type is the `<true>` variant of the types below, whose
2475
- display fields are always present. Without it, the display fields do not exist on the
2476
- type.
2477
-
2478
- ```typescript
2479
- interface OrgReadOptions {
2480
- readonly withDisplay?: boolean;
2481
- readonly language?: string; // such as "vi-VN"; defaults to the invocation language
2482
- }
2483
-
2484
- interface OrgPageOptions extends OrgReadOptions {
2485
- readonly includeSubDepartments?: boolean;
2486
- readonly accountOnly?: boolean;
2487
- readonly limit?: number; // default 500, at most 2000; 200 with withDisplay
2488
- readonly cursor?: string;
2489
- }
2490
- interface OrgDepartmentMembersOptions extends OrgPageOptions { readonly positionId?: string; }
2491
- interface OrgPositionMembersOptions extends OrgPageOptions { readonly departmentId?: string; }
2492
- interface OrgManagerOptions extends OrgReadOptions { readonly accountOnly?: boolean; }
2493
- interface OrgPersonnelChainOptions extends OrgManagerOptions { readonly departmentId?: string; }
2494
- interface OrgTreeOptions extends OrgReadOptions {
2495
- readonly rootId?: string;
2496
- readonly depth?: number; // 1 to 100; defaults to every level
2497
- }
2498
- interface OrgIsInDepartmentOptions { readonly includeSubDepartments?: boolean; }
2499
- interface OrgIsManagerOfOptions {
2500
- readonly departmentId?: string;
2501
- readonly directOnly?: boolean;
2502
- }
2503
-
2504
- interface OrgPersonnelDisplay {
2505
- readonly name: string;
2506
- readonly email: string | null;
2507
- readonly avatar: string | null; // public URL
2508
- readonly code: string | null;
2509
- }
2510
- interface OrgNameDisplay { readonly name: string; }
2511
-
2512
- type OrgMembership<D extends boolean = false> = {
2513
- readonly personnelId: string;
2514
- readonly departmentId: string;
2515
- readonly positionId: string | null;
2516
- readonly level: number; // 0 staff, 1 highest manager level, 2 next, ...
2517
- readonly primary: boolean;
2518
- } & (D extends true
2519
- ? { readonly departmentName: string | null; readonly positionName: string | null }
2520
- : {});
2521
-
2522
- type OrgPersonnel<D extends boolean = false> = {
2523
- readonly id: string;
2524
- readonly accountId: string | null; // null: no workspace account
2525
- readonly memberships: readonly OrgMembership<D>[];
2526
- } & (D extends true ? { readonly display: OrgPersonnelDisplay | null } : {});
2527
-
2528
- type OrgMember<D extends boolean = false> = OrgMembership<D> & {
2529
- readonly accountId: string | null;
2530
- } & (D extends true ? { readonly display: OrgPersonnelDisplay | null } : {});
2531
-
2532
- type OrgDepartment<D extends boolean = false> = {
2533
- readonly id: string;
2534
- readonly parentId: string | null;
2535
- readonly level: number; // 1 for a root department
2536
- readonly childIds: readonly string[];
2537
- readonly positionIds: readonly string[];
2538
- } & (D extends true ? { readonly display: OrgNameDisplay | null } : {});
2539
-
2540
- type OrgDepartmentNode<D extends boolean = false> = OrgDepartment<D> & {
2541
- readonly children: readonly OrgDepartmentNode<D>[];
2542
- };
2543
-
2544
- type OrgPosition<D extends boolean = false> = {
2545
- readonly id: string;
2546
- readonly departmentOnly: boolean;
2547
- readonly departmentIds: readonly string[];
2548
- readonly excludedDepartmentIds: readonly string[];
2549
- } & (D extends true ? { readonly display: OrgNameDisplay | null } : {});
2550
-
2551
- type OrgManagerTier<D extends boolean = false> = {
2552
- readonly departmentId: string;
2553
- readonly level: number;
2554
- readonly distance: number; // 0 starting department, 1 its parent, ...
2555
- readonly personnelIds: readonly string[];
2556
- } & (D extends true ? {
2557
- readonly departmentName: string | null;
2558
- readonly personnel: readonly { readonly id: string; readonly display: OrgPersonnelDisplay | null }[];
2559
- } : {});
2560
-
2561
- interface OrgManagerChain<D extends boolean = false> {
2562
- readonly fromDepartmentId: string;
2563
- readonly personnelLevel: number;
2564
- readonly tiers: readonly OrgManagerTier<D>[];
2565
- readonly vacantDepartmentIds: readonly string[];
2566
- readonly truncated: boolean;
2567
- }
2568
-
2569
- interface OrgPage<T> {
2570
- readonly items: readonly T[];
2571
- readonly total: number;
2572
- readonly nextCursor?: string;
2573
- }
2574
-
2575
- interface OrgGetManyResult<T> {
2576
- readonly items: readonly T[];
2577
- readonly missingIds: readonly string[];
2578
- }
2579
- ```
2580
-
2581
- ```typescript
2582
- export default defineScript(async ({ org, input }) => {
2583
- const order = input as { ownerId: string; departmentId: string };
2584
- // Structure only: answered without reading records.
2585
- const [chain] = await org.personnel.managerChain(order.ownerId, {
2586
- departmentId: order.departmentId,
2587
- accountOnly: true,
2588
- });
2589
- const approverIds = chain?.tiers[0]?.personnelIds ?? [];
2590
-
2591
- // Names for a screen: one extra read per kind of data.
2592
- const me = await org.me({ withDisplay: true });
2593
- return {
2594
- approverIds,
2595
- greeting: me?.display?.name,
2596
- departments: me?.memberships.map(m => m.departmentName) ?? [],
2597
- };
2598
- });
2599
- ```
2600
-
2601
- ### Display data
2602
-
2603
- - `withDisplay` adds `display` to personnel, departments and positions, and
2604
- `departmentName`/`positionName` to memberships. A value is `null` when the record
2605
- behind it cannot be read, for example because it was deleted a moment ago.
2606
- - `language` selects the translation of department and position names, such as
2607
- `"vi-VN"` or `"en-US"`; a tag without a region (`"vi"`) matches the first
2608
- translation of that language. It defaults to the language of the invocation's user
2609
- membership, then of the user, then of the workspace, and falls back to the stored
2610
- name when there is no matching translation.
2611
- - A personnel `name` is the full name the workspace shows; `email` is the account
2612
- email, else the work email; `avatar` is a public image URL.
2613
- - Display data is limited to these fields and is readable by every member of the
2614
- workspace, as in user pickers. It costs at most one read per kind of data and per
2615
- 200 IDs, and recently read values are cached.
2616
-
2617
- ### `org.me(options?)`
2618
-
2619
- Returns the personnel of the invocation's user, or `null` for a `system` or
2620
- `inbound` invocation. It is `org.personnel.get` with
2621
- `invocation.user.membership.personnelId`.
2622
-
2623
- ### `org.personnel.get(id, options?)` and `org.personnel.getMany(ids, options?)`
2624
-
2625
- `get` returns an active personnel with every department membership, primary
2626
- department first, or `null` when the ID is not an active personnel of the workspace.
2627
- `getMany` reads up to 200 IDs in one call: duplicates are removed, `items` follows
2628
- the request order, and unknown IDs are listed in `missingIds`. A personnel without a
2629
- workspace account has `accountId: null`; people who left the workspace are not
2630
- returned.
2631
-
2632
- ### `org.departments.get(id, options?)`, `tree(options?)` and `ancestors(id, options?)`
2633
-
2634
- - `get` returns one active department or `null`. `childIds` are in display order;
2635
- `positionIds` are the positions that apply to the department.
2636
- - `tree` returns the root departments (or `rootId` alone) with their sub-departments.
2637
- `depth: 1` returns only the roots; below the requested depth `children` is empty
2638
- while `childIds` still lists the sub-departments. A tree of more than 5000
2639
- departments throws `ValidationError`; narrow it with `rootId` or `depth`.
2640
- - `ancestors` returns the parent first and the root last.
2641
- - A department whose parent is inactive or deleted is returned as a root
2642
- (`parentId: null`).
2643
-
2644
- ### `org.departments.members(id, options?)` and `org.positions.members(id, options?)`
2645
-
2646
- Return one page of memberships: managers first by level, then staff. A personnel who
2647
- belongs to several listed departments appears once per department.
2648
- `includeSubDepartments` adds every sub-department in tree order, `positionId` keeps
2649
- only the holders of a position, `departmentId` limits position holders to a
2650
- department, and `accountOnly` keeps only personnel with a workspace account. Pass
2651
- `nextCursor` as `cursor` to read the next page; `total` counts every page. The page
2652
- size is 500 by default and at most 2000, or at most 200 with `withDisplay`.
2653
-
2654
- ### `org.positions.list(options?)` and `org.positions.get(id, options?)`
2655
-
2656
- Return active positions, oldest first. A department-only position applies to
2657
- `departmentIds`; any other position applies to every department except
2658
- `excludedDepartmentIds`.
2659
-
2660
- ### Managers and manager chains
2661
-
2662
- A membership's `level` marks managers: `0` is staff, `1` the highest manager level of
2663
- the department, `2` the next one, and so on. Several people may share a level.
2664
-
2665
- - `org.departments.managers(id, options?)` returns the managers of that department
2666
- only, one tier per level, level `1` first.
2667
- - `org.departments.managerChain(id, options?)` returns the managers above a staff
2668
- member of the department, nearest first, up to the root department.
2669
- - `org.personnel.managerChain(id, options?)` returns one chain per department of the
2670
- personnel, primary department first; `departmentId` keeps only the chain that
2671
- starts in that department. The result is empty for an unknown personnel.
2672
-
2673
- A chain is built with these rules:
2674
-
2675
- 1. In the starting department, the managers of the personnel are those with a lower
2676
- level number than the personnel's own level (every manager for staff), nearest
2677
- first: level `3`, then `2`, then `1`. A department head has none there.
2678
- 2. Then every parent department up to the root adds all its managers, largest level
2679
- number first. Every manager of a parent department ranks above every manager of
2680
- its sub-departments.
2681
- 3. A personnel is listed once, at the nearest tier, and the starting personnel is
2682
- never listed.
2683
- 4. `accountOnly: true` skips personnel without a workspace account, for example when
2684
- the chain lists approvers.
2685
- 5. `vacantDepartmentIds` lists the departments passed without any eligible manager;
2686
- the chain continues with their parent. A department head's own department is not
2687
- vacant.
2688
- 6. `truncated` is `true` when a parent department is inactive, so the chain stops
2689
- before the real root.
2690
-
2691
- For example, with a company board (CEO level `1`, deputy CEO level `2`), an
2692
- Engineering department under it (director level `1`), and a Testing department under
2693
- Engineering (head `1`, deputy `2`, team lead `3`), the chain of a tester is: team lead,
2694
- deputy, head, director, deputy CEO, CEO. The chain of the Testing deputy is: head,
2695
- director, deputy CEO, CEO.
2696
-
2697
- ### `org.isInDepartment(personnelId, departmentId, options?)` and `org.isManagerOf(managerId, personnelId, options?)`
2698
-
2699
- `isInDepartment` tells whether the personnel belongs to the department, or to one of
2700
- its sub-departments with `includeSubDepartments`. `isManagerOf` tells whether
2701
- `managerId` appears in a manager chain of `personnelId`; `departmentId` considers
2702
- only the chain that starts there and `directOnly` only its nearest tier. Both return
2703
- `false` for unknown IDs.
2704
-
2705
- ### Rules
2706
-
2707
- - `org` is available in scripts, routes, record triggers of both timings, background
2708
- jobs and Development Sessions.
2709
- - It follows the default identity of the execution: an execution with a user or a
2710
- system identity may read it. An execution without a user (a background job, an
2711
- inbound webhook, or a record trigger started by a system write) may read it only
2712
- when the project's approved identity policy sets `allowInternalSystem: true`;
2713
- otherwise every call throws `PermissionDeniedError` with `details.reason`
2714
- `"IDENTITY_NOT_GRANTED"`.
2715
- - All calls of one execution read the same version of the structure.
2716
- - IDs are validated by the SDK and again by Cogover; an invalid ID or option throws
2717
- `ValidationError`. `get` methods return `null` for an unknown ID; `members`,
2718
- `managers`, `managerChain`, `ancestors` and `tree({ rootId })` throw
2719
- `NotFoundError` with `resource` `"department"` or `"position"`.
2720
- - When the structure cannot be read, the call throws `CogoverApiError` with code
2721
- `ORGANIZATION_UNAVAILABLE`.
2722
- - Call `getMany` or `members` instead of calling `get` in a loop: each call is one
2723
- capability call.
2724
-
2725
- ## Schema API
2726
-
2727
- `SchemaApi<Schema>.object(slug)` reads Object metadata and returns:
2728
-
2729
- ```typescript
2730
- interface ObjectMetadata {
2731
- readonly id: string;
2732
- readonly name: string;
2733
- readonly slug: string;
2734
- readonly fields: readonly {
2735
- readonly id: string;
2736
- readonly name: string;
2737
- readonly slug: string;
2738
- readonly fieldType: string;
2739
- readonly required: boolean;
2740
- readonly multiple: boolean;
2741
- readonly readOnly: boolean;
2742
- readonly manualModifyAllow?: boolean;
2743
- readonly metaData?: Readonly<Record<string, unknown>>;
2744
- readonly options?: readonly {
2745
- readonly id: string;
2746
- readonly slug: string;
2747
- readonly value: string;
2748
- readonly isDefault?: boolean;
2749
- }[];
2750
- }[];
2751
- }
2752
-
2753
- interface SchemaApi<Schema extends object = EffectiveWorkspaceObjects> {
2754
- object<Slug extends keyof Schema & string>(slug: Slug): Promise<ObjectMetadata>;
2755
- }
2756
- ```
2757
-
2758
- Object and field mutation are not part of this SDK. An invalid object slug throws
2759
- `ValidationError`; service failures use the error types described below.
2760
-
2761
- ## Logging
2762
-
2763
- `context.log` implements `ScriptLogger`:
2764
-
2765
- ```typescript
2766
- interface ScriptLogger {
2767
- debug(message: string, details?: unknown): void;
2768
- info(message: string, details?: unknown): void;
2769
- warn(message: string, details?: unknown): void;
2770
- error(message: string, details?: unknown): void;
2771
- }
2772
- ```
2773
-
2774
- The optional `details` value is logged separately from the message. Do not include
2775
- credentials, tokens, personal data, or other secrets in either argument.
2776
-
2777
- ## Errors
2778
-
2779
- API failures become `NotFoundError`, `ValidationError`,
2780
- `PermissionDeniedError`, `RateLimitError`, `StateConflictError`,
2781
- `LockUnavailableError`, `LockLostError`, or `CogoverApiError`.
2782
-
2783
- ```typescript
2784
- class CogoverApiError extends Error {
2785
- readonly code: string;
2786
- readonly r: number | undefined;
2787
- readonly details?: unknown;
2788
- constructor(code: string, message: string, details?: unknown);
2789
- }
2790
-
2791
- class NotFoundError extends CogoverApiError {
2792
- readonly resource: string;
2793
- readonly resourceId: string;
2794
- constructor(resource: string, resourceId: string, message?: string, details?: unknown);
2795
- }
2796
-
2797
- class ValidationError extends CogoverApiError {
2798
- constructor(message: string, details?: unknown);
2799
- }
2800
-
2801
- class PermissionDeniedError extends CogoverApiError {
2802
- constructor(message: string, details?: unknown);
2803
- }
2804
-
2805
- class RateLimitError extends CogoverApiError {
2806
- constructor(message: string, details?: unknown);
2807
- }
2808
-
2809
- class RetryableError extends CogoverApiError {
2810
- constructor(message: string, details?: unknown);
2811
- }
2812
-
2813
- class StateConflictError extends CogoverApiError {
2814
- constructor(message: string, details?: unknown);
2815
- }
2816
-
2817
- class LockUnavailableError extends CogoverApiError {
2818
- constructor(key: string, message?: string, details?: unknown);
2819
- }
2820
-
2821
- class LockLostError extends CogoverApiError {
2822
- constructor(message: string, details?: unknown);
2823
- }
2824
- ```
2825
-
2826
- Errors expose the SDK category in `error.code` and the original numeric server
2827
- result in `error.r` (also retained in `error.details.r`). `r` is `undefined` when
2828
- there was no server response, such as local SDK validation. The original message
2829
- remains in `error.message`.
2830
-
2831
- `RetryableError` (`code: "RETRYABLE"`) is thrown by project code, never by the SDK.
2832
- An after-change trigger handler or a job handler throws it to report a temporary
2833
- failure, and Cogover runs the handler again later (see
2834
- [After-change execution rules](#after-change-execution-rules) and
2835
- [Job execution rules](#job-execution-rules)). Anywhere else it has no special
2836
- meaning: a script that lets it escape returns HTTP 422, and a before-change trigger
2837
- that throws it rejects the write like any other failure.
2838
-
2839
- `jobs.enqueue`, `secrets.get`, and `crypto` fail with `ValidationError`,
2840
- `PermissionDeniedError`, or `RateLimitError` as described in their sections, and
2841
- with `CogoverApiError` whose `code` is `JOBS_DISABLED` or `SECRETS_DISABLED` when
2842
- the feature is not enabled for the Workspace. `crypto.aesDecrypt` and
2843
- `crypto.rsaDecrypt` throw `CogoverApiError` with `code: "DECRYPTION_FAILED"` when
2844
- the ciphertext cannot be decrypted.
2845
-
2846
- `notifications.send` and `email.send` fail with `ValidationError`, `NotFoundError`,
2847
- `PermissionDeniedError`, or `RateLimitError` as described in their sections, with
2848
- `CogoverApiError` whose `code` is `NOTIFICATIONS_DISABLED` or `EMAIL_DISABLED` when
2849
- the feature is switched off, and with `CogoverApiError` whose `code` is
2850
- `DUPLICATE_IN_PROGRESS` while an earlier call with the same `idempotencyKey` is
2851
- still sending. A sender mailbox that the Project policy does not allow is reported
2852
- as `PermissionDeniedError` with `details.reason` `"EMAIL_SENDER_NOT_GRANTED"`.
2853
-
2854
- Scripts can catch `CogoverApiError`, inspect `error.r`, and return their own client
2855
- error, such as `{ r: 1001, msg: "You cannot update this order." }`, without exposing
2856
- the original code or message. A script's returned JSON remains its own response
2857
- with HTTP 200. All client-facing text in `msg`, `message`, and equivalent response
2858
- fields must be written in English, including responses created by customer scripts.
2859
-
2860
- ```typescript
2861
- try {
2862
- await orders.records.update(id, fields);
2863
- } catch (error) {
2864
- if (error instanceof CogoverApiError && error.r === 37) {
2865
- return { r: 1001, msg: "You do not have permission to update this order." };
2866
- }
2867
- throw error;
2868
- }
2869
- ```
2870
-
2871
- Import `CogoverApiError` from `@cogover/sdk`.
2872
-
2873
- For SDK errors escaping `defineScript`, the HTTP endpoint returns an error with
2874
- `r` equal to the HTTP status, `code`, and a safe `msg`:
2875
-
2876
- | SDK code | HTTP / `r` |
2877
- |---|---|
2878
- | `PERMISSION_DENIED` | 403 |
2879
- | `NOT_FOUND` | 404 |
2880
- | `METHOD_NOT_ALLOWED` | 405 |
2881
- | `VALIDATION_ERROR` | 400 |
2882
- | `RATE_LIMITED` | 429 |
2883
- | `STATE_CONFLICT` | 409 |
2884
- | `LOCK_NOT_ACQUIRED` | 409 |
2885
- | `LOCK_LOST` | 409 |
2886
- | `STATE_SERVICE_UNAVAILABLE` | 503 |
2887
- | `LOCK_SERVICE_UNAVAILABLE` | 503 |
2888
- | `ORGANIZATION_UNAVAILABLE` | 503 |
2889
- | `FETCH_DISABLED` | 503 |
2890
- | `FETCH_BLOCKED` | 400 |
2891
- | `FETCH_REQUEST_TOO_LARGE` | 413 |
2892
- | `FETCH_RESPONSE_TOO_LARGE` | 502 |
2893
- | `FETCH_TIMEOUT` | 504 |
2894
- | `FETCH_FAILED` | 502 |
2895
- | `COGOVER_API_ERROR` | 422 |
2896
- | `RETRYABLE` | 422 |
2897
-
2898
- Missing approval for an explicit identity adds `reason: "IDENTITY_NOT_GRANTED"`;
2899
- it does not mean the selected user was denied access to a particular record.
2900
- Raw error messages, stack traces and arbitrary details are not returned.
2901
- `writesMayHaveCompleted` is true if any record write was dispatched, even if a later
2902
- operation failed. It is a conservative warning, not confirmation of a successful write.
2903
- Unknown errors and resource-limit failures retain the generic HTTP 422 response.
2904
- These responses do not roll back earlier writes; do not retry writes automatically.
2905
-
2906
- ## Workspace declarations
2907
-
2908
- `WorkspaceObjects` is an open interface. Without augmentation, object and field
2909
- slugs are strings with unknown field values. Generate and include a declaration to
2910
- make them workspace-specific:
2911
-
2912
- ```bash
2913
- npx cogover-generate-workspace-types objects.json workspace.d.ts
2914
- ```
2915
-
2916
- The generator reads Object metadata, sorts object and field slugs, and maps field
2917
- types as follows:
2918
-
2919
- | Object field type | Generated TypeScript type |
2920
- |---|---|
2921
- | `short_text`, `long_text`, `phone`, `email`, `regex`, `auto_number`, `date` | `string` |
2922
- | `boolean` | `boolean` |
2923
- | `numeric`, `decimal`, `currency`, `percent`, `rating`, `time`, `date_time`, `time_duration` | `number` |
2924
- | `single_choice` | union of option slugs, or `string` |
2925
- | `multi_choices`, `label`, `cascading` | readonly array of option slugs, or strings |
2926
- | `url` | `UrlValue` |
2927
- | `file` | `FileValue` |
2928
- | `lookup_normal`, `reference` | `RecordReference<ObjectSlug>` when the target is known |
2929
- | `date_range` | `readonly [string, string]` |
2930
- | `date_time_range`, `time_range` | `readonly [number, number]` |
2931
- | unknown field type | `unknown` |
2932
-
2933
- Fields that are not required include `null`; metadata marked `multiple` becomes a
2934
- readonly array unless its base type is already an array. Add the generated file to
2935
- the project's TypeScript compilation and do not edit it manually.
2936
-
2937
- ## Compatibility helper
2938
-
2939
- ```typescript
2940
- function createGreeting(name: string): string;
2941
- ```
2942
-
2943
- `createGreeting("Cogover")` returns `"Hello Cogover"`. It remains available for
2944
- SDK 0.1.x compatibility and is not part of the data APIs.