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