@cogover/sdk 0.1.2 → 0.6.0

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 (51) hide show
  1. package/README.md +347 -24
  2. package/dist/data.d.ts +49 -0
  3. package/dist/data.js +170 -0
  4. package/dist/errors.d.ts +37 -0
  5. package/dist/errors.js +72 -0
  6. package/dist/fetch.d.ts +28 -0
  7. package/dist/fetch.js +96 -0
  8. package/dist/index.d.ts +23 -3
  9. package/dist/index.js +8 -5
  10. package/dist/internal/bridge.js +48 -0
  11. package/dist/internal/invocation.js +57 -0
  12. package/dist/internal/json.js +81 -0
  13. package/dist/internal/request.js +87 -0
  14. package/dist/internal/trigger-config.js +212 -0
  15. package/dist/internal/trigger-runtime.js +211 -0
  16. package/dist/internal/validation.js +28 -0
  17. package/dist/internal/values.js +6 -0
  18. package/dist/invocation.d.ts +40 -0
  19. package/dist/invocation.js +1 -0
  20. package/dist/legacy.d.ts +2 -0
  21. package/dist/legacy.js +4 -0
  22. package/dist/locks.d.ts +19 -0
  23. package/dist/locks.js +68 -0
  24. package/dist/logger.d.ts +6 -0
  25. package/dist/logger.js +14 -0
  26. package/dist/query.d.ts +52 -0
  27. package/dist/query.js +59 -0
  28. package/dist/records.d.ts +79 -0
  29. package/dist/records.js +1 -0
  30. package/dist/request.d.ts +18 -0
  31. package/dist/request.js +1 -0
  32. package/dist/response.d.ts +21 -0
  33. package/dist/response.js +108 -0
  34. package/dist/router.d.ts +13 -0
  35. package/dist/router.js +104 -0
  36. package/dist/schema.d.ts +26 -0
  37. package/dist/schema.js +11 -0
  38. package/dist/script.d.ts +23 -0
  39. package/dist/script.js +56 -0
  40. package/dist/state.d.ts +24 -0
  41. package/dist/state.js +91 -0
  42. package/dist/trigger.d.ts +121 -0
  43. package/dist/trigger.js +15 -0
  44. package/dist/workspace.d.ts +8 -0
  45. package/dist/workspace.js +1 -0
  46. package/docs/en/api-reference.md +1415 -0
  47. package/docs/en/usage-guide.md +495 -0
  48. package/package.json +17 -5
  49. package/scripts/generate-workspace-types.mjs +135 -0
  50. package/dist/index.d.ts.map +0 -1
  51. package/dist/index.js.map +0 -1
@@ -0,0 +1,1415 @@
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`, and `locks`, awaits the handler,
12
+ 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
+ }
43
+ ```
44
+
45
+ `defineScript` rejects a non-function handler with `ValidationError`. The returned
46
+ handler rejects invalid input JSON and values that cannot be serialized to JSON.
47
+ Returning `null` produces a null handler result; returning `undefined` is invalid.
48
+
49
+ ## HTTP routers and request context
50
+
51
+ `ScriptContext<TInput, TSchema>` provides `input`, `request`, `invocation`, `response`, `data`, `schema`,
52
+ `log`, `state`, and `locks` to both script and route handlers. `input` preserves the invocation
53
+ input. Prefer `request.body` for business data: it excludes invocation metadata and
54
+ transport/authentication fields removed by Cogover.
55
+
56
+ ```typescript
57
+ type RequestMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
58
+ type ScriptQuery = Readonly<Record<string, string | readonly string[]>>;
59
+ type ScriptHeaders = Readonly<Record<string, string>>;
60
+ type ScriptPathParams = Readonly<Record<string, string>>;
61
+
62
+ interface ScriptRequest<TBody = unknown> {
63
+ readonly method: RequestMethod;
64
+ readonly path: string; // Relative to /api/v1/ts-projects/{projectSlug}
65
+ readonly params: ScriptPathParams;
66
+ readonly query: ScriptQuery;
67
+ readonly headers: ScriptHeaders;
68
+ readonly body: TBody;
69
+ }
70
+ ```
71
+
72
+ The descriptor and metadata maps are frozen; its body is not deeply frozen. Method,
73
+ path, query, and allowlisted headers come from Cogover, not from business fields.
74
+ Repeated query names become readonly arrays. Header names are lower-case and
75
+ credentials such as `authorization` and `cookie` are never exposed. Dynamic path
76
+ parameters are percent-decoded after safe route matching. TypeScript types do not
77
+ validate runtime business input.
78
+
79
+ ## Invocation identity and workspace
80
+
81
+ `context.invocation` is a synchronous, immutable snapshot built from metadata that
82
+ Cogover already authenticated and loaded for the current execution. Reading it
83
+ does not make a data API request.
84
+
85
+ ```typescript
86
+ type InvocationContext = UserInvocationContext | SystemInvocationContext;
87
+
88
+ interface CurrentWorkspace {
89
+ readonly id: string;
90
+ readonly name?: string;
91
+ readonly domain?: string;
92
+ readonly language?: string;
93
+ readonly timezone?: string;
94
+ readonly dateFormat?: string;
95
+ readonly timeFormat?: string;
96
+ readonly numberFormat?: string;
97
+ }
98
+
99
+ interface CurrentWorkspaceMembership {
100
+ readonly personnelId?: string;
101
+ readonly language?: string;
102
+ readonly timezone?: string;
103
+ }
104
+
105
+ interface CurrentUser {
106
+ readonly accountId: string;
107
+ readonly email?: string;
108
+ readonly firstName?: string;
109
+ readonly lastName?: string;
110
+ readonly avatar?: string;
111
+ readonly language?: string;
112
+ readonly timezone?: string;
113
+ readonly membership: CurrentWorkspaceMembership;
114
+ }
115
+
116
+ interface UserInvocationContext {
117
+ readonly identity: "user";
118
+ readonly workspace: CurrentWorkspace;
119
+ readonly user: CurrentUser;
120
+ }
121
+
122
+ interface SystemInvocationContext {
123
+ readonly identity: "system";
124
+ readonly workspace: CurrentWorkspace;
125
+ readonly user: null;
126
+ }
127
+ ```
128
+
129
+ All fields are readonly. Optional profile and workspace fields may be absent, so
130
+ scripts must not assume that they contain a value.
131
+
132
+ ```typescript
133
+ export default defineScript(({ invocation }) => {
134
+ if (invocation.identity === "system") {
135
+ return {workspaceId: invocation.workspace.id, user: null};
136
+ }
137
+ return {
138
+ workspaceId: invocation.workspace.id,
139
+ accountId: invocation.user.accountId,
140
+ personnelId: invocation.user.membership.personnelId,
141
+ };
142
+ });
143
+ ```
144
+
145
+ Cogover ignores caller-supplied invocation metadata and creates this snapshot from
146
+ the authenticated request context. Raw authentication data, tokens, and credentials
147
+ are not included. A handler called outside Cogover has no authenticated invocation
148
+ snapshot.
149
+
150
+ ### `createRouter<TSchema = EffectiveWorkspaceObjects>(): ScriptRouter<TSchema>`
151
+
152
+ Creates an independent router. `TSchema extends object` defaults to the effective
153
+ workspace schema, preserving `WorkspaceObjects` augmentation for data and schema
154
+ APIs. Routes match a method and case-sensitive static or dynamic path; static routes
155
+ take precedence over dynamic routes. `/` addresses
156
+ the canonical project URL without a route suffix.
157
+ `/index` is a separate route, registered explicitly. `defineScript()` remains valid
158
+ for `/`; requesting a child path on it throws `NotFoundError` before its handler runs.
159
+
160
+ ### `router.addRoute<TInput = unknown, TOutput = unknown>(method: RequestMethod, path: string, handler: ScriptHandler<TInput, TOutput, TSchema>): ScriptRouter<TSchema>`
161
+
162
+ Registers a handler and returns the same router for chaining. Supported methods are
163
+ `GET`, `POST`, `PUT`, `PATCH`, and `DELETE`. A path is `/` or static/dynamic
164
+ components such as `/orders/:orderId`. Static components start with an ASCII letter
165
+ or digit, may contain letters, digits, `_`, or `-`, and are at most 100 characters.
166
+ Parameter names start with an ASCII letter, may contain letters, digits, or `_`, are
167
+ at most 64 characters, and must be unique in a route. The complete path is at most
168
+ 1,024 characters.
169
+ Child trailing slashes, empty segments, `.`, `..`, percent escapes in the template,
170
+ `?`, `#`, and wildcards are rejected. Duplicate or structurally ambiguous routes for
171
+ one method, invalid handlers, or more than 256 routes throw `ValidationError`.
172
+
173
+ Handlers are ordinary `ScriptHandler` functions, not functions already wrapped in
174
+ `defineScript()`. They receive the same data/schema/log APIs, input and request context.
175
+ The same handler may be registered at more than one path.
176
+
177
+ ### `router.get/post/put/patch/delete(path, handler): ScriptRouter<TSchema>`
178
+
179
+ Method-specific shorthand for `addRoute()`, with identical validation, return value,
180
+ and errors.
181
+
182
+ ### `router.toHandler(): SandboxHandler`
183
+
184
+ Returns a default-exportable handler that captures a snapshot of the current routes.
185
+ Later registrations do not affect an existing handler. It parses input, dispatches
186
+ exactly one route, awaits it, and serializes the result just like `defineScript()`.
187
+ `null` remains null; an undefined result throws `ValidationError`. Missing routes
188
+ throw `NotFoundError` (HTTP 404). Unsupported invocation methods use
189
+ `CogoverApiError` with `code: "METHOD_NOT_ALLOWED"` (HTTP 405). Invalid invocation
190
+ metadata throws `ValidationError`.
191
+ When invoked directly without Cogover request metadata, handlers default to POST `/`.
192
+
193
+ Routes inherit project authentication, permissions and runtime limits. Registering a
194
+ route grants no additional permission or separate security boundary. Idempotency
195
+ replay is scoped to method/path as well as project version and caller; use a new key
196
+ for each distinct business operation.
197
+
198
+ ## HTTP response API
199
+
200
+ Returning a plain JSON-serializable value keeps the compatible `200
201
+ application/json` behavior. Use the context's `response` helpers to control status,
202
+ headers, content type, or body representation:
203
+
204
+ ```typescript
205
+ router.post("/orders", ({ response }) => response.json({ id: "ORD-1" }, {
206
+ status: 201,
207
+ headers: { location: "/orders/ORD-1", "x-request-state": "created" },
208
+ }));
209
+
210
+ router.get("/files/:fileId", ({ response }) =>
211
+ response.bytes(new Uint8Array([0, 1, 255]), { contentType: "application/octet-stream" }));
212
+ ```
213
+
214
+ ```typescript
215
+ type ResponseHeaderValue = string | readonly string[];
216
+
217
+ interface ResponseInit {
218
+ readonly status?: number;
219
+ readonly headers?: Readonly<Record<string, ResponseHeaderValue>>;
220
+ }
221
+
222
+ interface BinaryResponseInit extends ResponseInit {
223
+ readonly contentType?: string;
224
+ }
225
+
226
+ interface ResponseApi {
227
+ json<T>(body: T, init?: ResponseInit): ScriptResponse<T>;
228
+ text(body: string, init?: ResponseInit): ScriptResponse<string>;
229
+ bytes(body: Uint8Array, init?: BinaryResponseInit): ScriptResponse<Uint8Array>;
230
+ empty(init?: ResponseInit): ScriptResponse<null>;
231
+ redirect(location: string, status?: 301 | 302 | 303 | 307 | 308): ScriptResponse<null>;
232
+ }
233
+
234
+ response.json(body, init?)
235
+ response.text(body, init?)
236
+ response.bytes(body: Uint8Array, { status?, headers?, contentType? }?)
237
+ response.empty(init?) // status defaults to 204
238
+ response.redirect(location, status?) // status defaults to 302
239
+ ```
240
+
241
+ Status must be an integer from 200 through 599. Header values may be one string or
242
+ a readonly string array. Hop-by-hop, credential-setting, and reserved Cogover headers
243
+ are rejected. Header names and values cannot contain newlines;
244
+ at most 50 headers are accepted. A header name is at most 128 characters and each
245
+ value at most 8,192 characters. Default content types are
246
+ `application/json; charset=utf-8`, `text/plain; charset=utf-8`, and
247
+ `application/octet-stream`. Redirect status is restricted to 301, 302, 303, 307, or
248
+ 308. Helpers return an opaque `ScriptResponse`; application code must not construct
249
+ the transport envelope directly. A redirect location must be non-empty, at most
250
+ 4,096 characters, and contain no newline. `response.json()` rejects `undefined`;
251
+ `response.text()` requires a string and `response.bytes()` requires `Uint8Array`.
252
+
253
+ ## Record triggers
254
+
255
+ A record trigger runs project code when records of one Object are created, updated,
256
+ or deleted. Declare each trigger with `defineTrigger` and list the results in the
257
+ project's named `triggers` export. The default export is still the HTTP handler and
258
+ is optional in a project that only declares triggers.
259
+
260
+ This example assumes that `workspace.d.ts` declares the `order` Object and the
261
+ fields used below.
262
+
263
+ ```typescript
264
+ import { defineTrigger } from "@cogover/sdk";
265
+
266
+ export const triggers = [
267
+ defineTrigger({
268
+ key: "order_credit_check",
269
+ object: "order",
270
+ timing: "beforeChange",
271
+ operations: ["create", "update"],
272
+ fields: ["status", "amount", "customer"],
273
+ changedFields: ["status", "amount"],
274
+ when: { op: "=", field: "status", params: "confirmed" },
275
+ writableFields: ["approval_level"],
276
+ }, async ({ records }) => {
277
+ for (const record of records) {
278
+ if ((record.new.amount ?? 0) > 1_000_000_000) {
279
+ record.addError("amount", "AMOUNT_TOO_LARGE", "Amount exceeds the approval limit.");
280
+ continue;
281
+ }
282
+ record.new.approval_level = "high";
283
+ }
284
+ }),
285
+ ];
286
+ ```
287
+
288
+ A trigger has one of two timings. A **before-change** trigger runs before the change
289
+ is saved: it can reject records and adjust the values that will be saved. An
290
+ **after-change** trigger runs asynchronously after the change has been saved: it
291
+ cannot reject or modify that change, but it may write records and call `fetch`. See
292
+ [Before-change execution rules](#before-change-execution-rules) and
293
+ [After-change execution rules](#after-change-execution-rules).
294
+
295
+ Cogover reads the trigger configuration when a project version is published and
296
+ applies it while that version is active. Deactivating the project removes its
297
+ triggers. A project can declare at most 50 triggers, and an Object can have at most
298
+ 20 active before-change triggers.
299
+
300
+ ### `defineTrigger(config, handler): TriggerDefinition`
301
+
302
+ ```typescript
303
+ function defineTrigger<
304
+ ObjectSlug extends keyof Schema & string,
305
+ Operation extends TriggerOperation,
306
+ Schema extends object = EffectiveWorkspaceObjects,
307
+ >(
308
+ config: TriggerConfig<ObjectSlug, Operation, Schema>,
309
+ handler: TriggerHandler<ObjectSlug, Operation, Schema>,
310
+ ): TriggerDefinition;
311
+ ```
312
+
313
+ The type arguments are inferred from `config.object` and `config.operations`.
314
+ With a generated `workspace.d.ts`, the object slug, every field slug in the
315
+ configuration, and the values of `record.new` and `record.old` are checked against
316
+ the declared Object. Without Workspace declarations, slugs are strings and field
317
+ values are `unknown`.
318
+
319
+ `defineTrigger` validates the configuration immediately and throws `ValidationError`
320
+ for any violation, for an unknown configuration key, or for a handler that is not a
321
+ function. It returns a frozen `TriggerDefinition`.
322
+
323
+ ```typescript
324
+ type TriggerTiming = "beforeChange" | "afterChange";
325
+ type TriggerOperation = "create" | "update" | "delete";
326
+ type TriggerRunWhen = "always" | "onEnter";
327
+
328
+ interface TriggerConfig<
329
+ ObjectSlug extends string = string,
330
+ Operation extends TriggerOperation = TriggerOperation,
331
+ Schema extends object = EffectiveWorkspaceObjects,
332
+ > {
333
+ readonly key: string;
334
+ readonly name?: string;
335
+ readonly object: ObjectSlug;
336
+ readonly timing: TriggerTiming;
337
+ readonly operations: readonly Operation[];
338
+ readonly fields: readonly FieldSlug[]; // field slugs of the Object
339
+ readonly changedFields?: readonly FieldSlug[];
340
+ readonly when?: TriggerFilter;
341
+ readonly runWhen?: TriggerRunWhen;
342
+ readonly writableFields?: readonly FieldSlug[];
343
+ readonly order?: number;
344
+ readonly timeoutMs?: number;
345
+ }
346
+ ```
347
+
348
+ | Option | Required | Rules and meaning |
349
+ |---|---|---|
350
+ | `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. |
351
+ | `name` | No | Display name of at most 250 characters. Defaults to `key`. |
352
+ | `object` | Yes | Slug of the Object whose records run the trigger. |
353
+ | `timing` | Yes | `"beforeChange"` runs before the change is saved and can reject or adjust it. `"afterChange"` runs asynchronously after the change has been saved. |
354
+ | `operations` | Yes | Non-empty list of `"create"`, `"update"`, and `"delete"` without duplicates. |
355
+ | `fields` | Yes | 1–200 unique field slugs. `record.new` and `record.old` contain only these fields and `id`. |
356
+ | `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. |
357
+ | `when` | No | A `TriggerFilter`. Only matching records run the trigger. |
358
+ | `runWhen` | No | `"always"` (default) or `"onEnter"`. `"onEnter"` requires `when`. |
359
+ | `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 `[]`. |
360
+ | `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. |
361
+ | `timeoutMs` | No | Integer from 100 through 3000; defaults to `2000`. Time budget of one handler call. |
362
+
363
+ Object and field slugs start with an ASCII letter or `_`, contain letters, digits,
364
+ or `_`, and are at most 355 characters. `changedFields` and `writableFields` do not
365
+ have to be listed in `fields`.
366
+
367
+ ### Trigger filters
368
+
369
+ ```typescript
370
+ interface TriggerFilterCondition {
371
+ readonly op: FilterOperator;
372
+ readonly field: string;
373
+ readonly params?: unknown;
374
+ }
375
+
376
+ interface TriggerFilterGroup {
377
+ readonly op: "and" | "or";
378
+ readonly conditions: readonly TriggerFilter[];
379
+ }
380
+
381
+ type TriggerFilter = TriggerFilterCondition | TriggerFilterGroup;
382
+ ```
383
+
384
+ ```typescript
385
+ when: {
386
+ op: "and",
387
+ conditions: [
388
+ { op: "=", field: "status", params: "confirmed" },
389
+ { op: "or", conditions: [
390
+ { op: ">=", field: "amount", params: 1_000_000 },
391
+ { op: "in", field: "priority", params: ["high", "urgent"] },
392
+ ] },
393
+ ],
394
+ }
395
+ ```
396
+
397
+ A condition compares one field using a `FilterOperator`. `params` is the JSON
398
+ comparison value: it is required for every operator except `"is null"` and
399
+ `"not null"`, which take none. `"in"` and `"not in"` take a non-empty array and
400
+ `"between"` takes exactly two values. A group combines a non-empty list of
401
+ filters. A filter is nested at most 8 levels deep and contains at most 50
402
+ conditions. Trigger filters are plain objects: expressions built with `and()`,
403
+ `or()`, or field references are for `records.list` and are rejected here.
404
+
405
+ `when` is evaluated on the new values, or on the old values when a record is
406
+ deleted. With `runWhen: "onEnter"` the trigger runs only when the record did not
407
+ match `when` before the change and matches after it; a record that is being created
408
+ counts as not matching before, and `runWhen` is ignored for deletes.
409
+
410
+ Cogover decides which triggers run once, before the first trigger of a change, from
411
+ the values submitted by the writer together with field defaults. A value changed by
412
+ an earlier trigger does not change which triggers run, but later triggers see it in
413
+ `record.new`.
414
+
415
+ ### `TriggerDefinition` and `TriggerManifest`
416
+
417
+ ```typescript
418
+ interface TriggerManifest {
419
+ readonly key: string;
420
+ readonly name?: string;
421
+ readonly object: string;
422
+ readonly timing: TriggerTiming;
423
+ readonly operations: readonly TriggerOperation[];
424
+ readonly fields: readonly string[];
425
+ readonly changedFields?: readonly string[];
426
+ readonly when?: TriggerFilter;
427
+ readonly runWhen: TriggerRunWhen;
428
+ readonly writableFields: readonly string[];
429
+ readonly order: number;
430
+ readonly timeoutMs: number;
431
+ }
432
+
433
+ type TriggerSandboxHandler = (inputJson: string) => Promise<string>;
434
+
435
+ interface TriggerDefinition {
436
+ readonly key: string;
437
+ readonly config: TriggerManifest;
438
+ readonly __cogoverTriggerHandler: TriggerSandboxHandler;
439
+ }
440
+ ```
441
+
442
+ `config` is the normalized configuration as deeply frozen plain JSON, with every
443
+ default applied: `runWhen: "always"`, `writableFields: []`, `order: 5000`, and
444
+ `timeoutMs: 2000`. Optional settings that were not provided are absent. It is
445
+ detached from the object passed to `defineTrigger`, so later edits of that object
446
+ have no effect. `__cogoverTriggerHandler` is reserved for Cogover; project code
447
+ does not call it.
448
+
449
+ ### Trigger handler context
450
+
451
+ ```typescript
452
+ type TriggerHandler<
453
+ ObjectSlug extends string = string,
454
+ Operation extends TriggerOperation = TriggerOperation,
455
+ Schema extends object = EffectiveWorkspaceObjects,
456
+ > = (context: TriggerContext<ObjectSlug, Operation, Schema>) => void | Promise<void>;
457
+
458
+ interface TriggerContext<
459
+ ObjectSlug extends string = string,
460
+ Operation extends TriggerOperation = TriggerOperation,
461
+ Schema extends object = EffectiveWorkspaceObjects,
462
+ > {
463
+ readonly records: readonly TriggerRecord<Fields, Operation>[]; // Fields of ObjectSlug
464
+ readonly trigger: TriggerInfo<Operation>;
465
+ readonly invocation: InvocationContext;
466
+ readonly data: DataApi<Schema>;
467
+ readonly schema: SchemaApi<Schema>;
468
+ readonly log: ScriptLogger;
469
+ }
470
+
471
+ interface TriggerInfo<Operation extends TriggerOperation = TriggerOperation> {
472
+ readonly id: string;
473
+ readonly key: string;
474
+ readonly timing: TriggerTiming;
475
+ readonly operation: Operation;
476
+ readonly objectSlug: string;
477
+ readonly changeId: string;
478
+ }
479
+
480
+ interface TriggerRecord<Fields = Record<string, unknown>, Operation extends TriggerOperation = TriggerOperation> {
481
+ readonly key: string;
482
+ readonly id: CogoverRecordId | null;
483
+ readonly new: TriggerNewValues<Fields> | null;
484
+ readonly old: TriggerOldValues<Fields> | null;
485
+ readonly changedFields: readonly (keyof Fields & string)[];
486
+ addError(field: (keyof Fields & string) | null, code: string, message?: string): void;
487
+ }
488
+
489
+ type TriggerNewValues<Fields> = {
490
+ -readonly [K in keyof Fields]?: Fields[K] | UpdateFields<Fields>[K];
491
+ };
492
+
493
+ type TriggerOldValues<Fields> = {
494
+ readonly [K in keyof Fields]?: Fields[K];
495
+ };
496
+ ```
497
+
498
+ A handler may be synchronous or asynchronous; its return value is ignored. One call
499
+ receives all records of the same change that run the trigger, up to 200 records and
500
+ 200 KiB, so a batch write or an import calls the handler once per chunk instead of
501
+ once per record. Keep `fields` short, and read related data for the whole list with
502
+ one `records.getMany` call rather than one read per record.
503
+
504
+ `data`, `schema`, `log`, and `invocation` are the same APIs that scripts receive. A
505
+ trigger context has no `input`, `request`, `response`, `state`, or `locks`.
506
+ `trigger.operation` is the operation of the current call, `trigger.id` identifies the
507
+ trigger registration, and `trigger.changeId` identifies the record change that caused
508
+ the call.
509
+
510
+ Each `TriggerRecord` describes one record:
511
+
512
+ - `key` correlates the record with its result. It is not a record ID.
513
+ - `id` is the record ID, or `null` while a record that is being created has no ID yet.
514
+ In an after-change trigger it is always set.
515
+ - `new` holds the values after the change as a plain, mutable object. It is `null`
516
+ when the record is deleted.
517
+ - `old` holds the values before the change and is deeply frozen. It is `null` when the
518
+ record is created.
519
+ - `changedFields` is a frozen list of the field slugs that changed. For a created
520
+ record it lists every field that has a value.
521
+
522
+ The declared `operations` narrow these types: `new` is never `null` unless
523
+ `"delete"` is declared, `old` is never `null` unless `"create"` is declared, and a
524
+ trigger that only declares `"delete"` has `new: null`. `TriggerNewValues` and
525
+ `TriggerOldValues` make every field optional because a field that is not listed in
526
+ `fields`, or that has no value, is `undefined`.
527
+
528
+ ### Validating and changing records
529
+
530
+ This section applies to before-change triggers. In an after-change trigger the
531
+ change is already saved: `addError` only reports to the project log and
532
+ `record.new` must not be changed (see
533
+ [After-change execution rules](#after-change-execution-rules)).
534
+
535
+ `record.addError(field, code, message?)` rejects the record. `field` is a field slug,
536
+ or `null` for an error about the whole record. `code` starts with an upper-case ASCII
537
+ letter and contains upper-case letters, digits, or `_`; at most 64 characters, for
538
+ example `AMOUNT_TOO_LARGE`. `message` is an optional English text of at most 500
539
+ characters that Cogover shows to the end user when it has no translation for the
540
+ code; an empty message is ignored. Invalid arguments throw `ValidationError`. A
541
+ record may collect several errors.
542
+
543
+ A rejected record is not saved, and any change the handler made to it is discarded.
544
+ The writer receives HTTP 400 with `msg: "BEFORE_CHANGE_TRIGGER_REJECTED"`, the error
545
+ codes in `meta` keyed by field slug (`$record` for an error about the whole record),
546
+ and the optional texts in `messages` keyed by code. A rejected single-record write
547
+ stops at the first trigger that reports an error. In a batch write only the rejected
548
+ rows fail, and a rejected row is not passed to later triggers.
549
+
550
+ To change the values that will be saved, assign fields of `record.new`:
551
+
552
+ ```typescript
553
+ record.new.approval_level = "high";
554
+ record.new.customer = "ACC-1"; // same format as records.update() input
555
+ record.new.note = null; // clears the field
556
+ ```
557
+
558
+ - Only fields listed in `writableFields` may change. When the handler returns, the
559
+ SDK compares every top-level field of `record.new` with a snapshot taken before the
560
+ handler ran, using a deep JSON comparison. Changing any other field, including
561
+ `id`, throws `ValidationError` naming the field, and the write fails.
562
+ - Assigned values use the same format as `records.update` input and must be JSON
563
+ data. `NaN`, functions, `Map`, `Set`, and class instances are rejected; a `Date` is
564
+ stored as its ISO string. Assigning `null` clears a field; assigning `undefined` or
565
+ deleting the field has the same effect.
566
+ - A change inside an array or object value is detected and sends the whole field value.
567
+ - `record.new` itself cannot be replaced, and a record that is being deleted has
568
+ nothing to change.
569
+ - Cogover validates the final values again before saving, including field types and
570
+ required, unique, and duplicate rules. For the fields a trigger changed, the
571
+ field's manual create/modify setting and the writer's field edit permission are
572
+ not applied. Read-only fields such as formulas, auto numbers, and rollups, and
573
+ system fields, are always refused.
574
+
575
+ ### Before-change execution rules
576
+
577
+ A before-change trigger runs for every source of a write: the Cogover web
578
+ application, API keys, imports, automation processes, other Custom Backend Modules,
579
+ and writes made through `data.asUser()` or `data.asSystem()`. Maintenance writes
580
+ made by Cogover itself — recalculating formula and rollup fields, background record
581
+ merges, and cascading deletes — do not run before-change triggers, and neither does
582
+ a request that only validates input without saving.
583
+
584
+ - **Read-only.** A before-change trigger may read records and schema, but every
585
+ record write, `fetch`, lock, and state write is refused with
586
+ `PermissionDeniedError` whose `details.reason` is `"TRIGGER_READ_ONLY"`. This
587
+ applies to every identity, including `data.asSystem()`.
588
+ - **Identity.** `data.object()` acts as the user who made the change, with that
589
+ user's permissions, and `invocation` describes the same user. When a change has
590
+ no user, `invocation.identity` is `"system"` and `data.object()` works only if the
591
+ project's approved identity policy sets `allowInternalSystem: true`; otherwise its
592
+ calls throw `PermissionDeniedError` with `details.reason` `"IDENTITY_NOT_GRANTED"`
593
+ while the handler still receives `records`. `data.asUser()` and `data.asSystem()`
594
+ follow the project's identity policy as usual.
595
+ - **Fail closed.** When a handler throws, exceeds `timeoutMs`, exceeds a runtime
596
+ limit, or cannot be run, the write is rejected and nothing is saved. The writer
597
+ receives `msg: "BEFORE_CHANGE_TRIGGER_FAILED"` without internal details.
598
+ - **Time.** Each call must finish within `timeoutMs`. All before-change triggers of
599
+ one write share a total budget of 8 seconds.
600
+
601
+ ### After-change execution rules
602
+
603
+ An after-change trigger (`timing: "afterChange"`) runs asynchronously, shortly after
604
+ the change has been saved. Use it for follow-up work such as creating or updating
605
+ related records or notifying another system. It runs for the same sources of a
606
+ write as a before-change trigger, with the same exceptions.
607
+
608
+ ```typescript
609
+ import { defineTrigger, fetch, RetryableError } from "@cogover/sdk";
610
+
611
+ export const triggers = [
612
+ defineTrigger({
613
+ key: "order_confirmed_notify",
614
+ object: "order",
615
+ timing: "afterChange",
616
+ operations: ["create", "update"],
617
+ fields: ["status", "amount"],
618
+ changedFields: ["status"],
619
+ when: { op: "=", field: "status", params: "confirmed" },
620
+ runWhen: "onEnter",
621
+ }, async ({ records, trigger }) => {
622
+ for (const record of records) {
623
+ const response = await fetch("https://erp.example.com/orders", {
624
+ method: "POST",
625
+ headers: {
626
+ "content-type": "application/json",
627
+ // The same change of the same record always produces the same key.
628
+ "idempotency-key": `${trigger.changeId}:${record.id}`,
629
+ },
630
+ body: JSON.stringify({ id: record.id, amount: record.new.amount }),
631
+ });
632
+ if (response.status >= 500) {
633
+ throw new RetryableError("The ERP is temporarily unavailable");
634
+ }
635
+ }
636
+ }),
637
+ ];
638
+ ```
639
+
640
+ - **Cannot block or change the saved record.** The writer has already received its
641
+ response. `writableFields` is not allowed, and changing `record.new` makes the call
642
+ fail with `ValidationError`. `record.addError()` rejects nothing: the reported
643
+ errors are only written to the project log. To change the record, call
644
+ `records.update`; that is a new write and runs triggers again.
645
+ - **Saved values.** `record.id` is always set. `record.new` holds the values as they
646
+ were saved, including the record ID and values assigned while saving, such as an
647
+ auto number. For a deleted record `record.new` is `null` and `record.old` holds the
648
+ last values.
649
+ - **May write and call out.** Record writes and `fetch` work as they do in a script,
650
+ within the same runtime limits. `data.object()` acts as the user who made the
651
+ change, and the other identity rules of before-change triggers apply. The trigger
652
+ context has no `state` or `locks`.
653
+ - **Best-effort delivery.** Cogover does not guarantee that an after-change handler
654
+ runs exactly once. It may occasionally run more than once for the same change, or
655
+ not at all. Make every handler idempotent: `trigger.changeId` together with
656
+ `record.id` identifies one change of one record. Never make an after-change
657
+ trigger the only guarantee of a critical rule; enforce such rules in a
658
+ before-change trigger.
659
+ - **Retries.** Throw `RetryableError` when a handler fails for a temporary reason,
660
+ such as an external service that is unavailable. Cogover runs the handler again
661
+ later: by default up to 5 more times, waiting longer before each attempt, from
662
+ about one second to about ten minutes. A call that exceeds `timeoutMs`, or that
663
+ Cogover could not run for a temporary reason, is retried the same way. Any other
664
+ error is not retried: the failure is logged and the handler does not run again for
665
+ that change. When the retries are used up, the handler does not run again for that
666
+ change either.
667
+ - **Loops end.** A write made by a trigger runs triggers again, possibly including
668
+ the same trigger. Cogover limits such chains: every automated write uses one step
669
+ of a fixed budget (10 steps for a change made directly by a user or an API
670
+ client), and after-change triggers no longer run once the budget is used up. Use
671
+ `changedFields`, `when`, and `runWhen: "onEnter"` so that a handler's own writes
672
+ do not start it again.
673
+ - **Order and time.** Each call must finish within `timeoutMs`. After-change triggers
674
+ of one change run independently of each other: do not rely on their relative
675
+ order. A retried call may run after a later change of the same record has already
676
+ been processed, so read the current record when the latest values matter.
677
+
678
+ ## Outbound HTTP `fetch`
679
+
680
+ ```typescript
681
+ function fetch(input: string, init?: CogoverFetchInit): Promise<CogoverFetchResponse>;
682
+
683
+ interface CogoverFetchInit {
684
+ readonly method?: "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE";
685
+ readonly headers?: Readonly<Record<string, string>>;
686
+ readonly body?: string;
687
+ readonly timeoutMs?: number;
688
+ }
689
+
690
+ interface CogoverFetchHeaders {
691
+ get(name: string): string | null;
692
+ has(name: string): boolean;
693
+ entries(): IterableIterator<[string, string]>;
694
+ [Symbol.iterator](): IterableIterator<[string, string]>;
695
+ }
696
+
697
+ interface CogoverFetchResponse {
698
+ readonly ok: boolean;
699
+ readonly status: number;
700
+ readonly statusText: string;
701
+ readonly url: string;
702
+ readonly redirected: false;
703
+ readonly headers: CogoverFetchHeaders;
704
+ readonly bodyUsed: boolean;
705
+ text(): Promise<string>;
706
+ json<T = unknown>(): Promise<T>;
707
+ }
708
+ ```
709
+
710
+ Cogover installs the global `fetch()` function in the hosted runtime. Import
711
+ `{ fetch }` from `@cogover/sdk` when the dependency should be explicit; this also
712
+ prevents local Node.js from silently using its native, unrestricted `fetch` during
713
+ tests. The SDK function requires the Cogover runtime and always uses Cogover's
714
+ managed network layer. `input` must be an absolute public HTTPS URL on port 443
715
+ without userinfo, a fragment, or an IP-literal host. `body` accepts only a string;
716
+ use `JSON.stringify()` for JSON. `timeoutMs` must be a positive integer and is
717
+ always clamped by the platform limit.
718
+
719
+ ```typescript
720
+ import { fetch } from "@cogover/sdk";
721
+
722
+ const response = await fetch("https://api.example.com/v1/orders", {
723
+ method: "POST",
724
+ headers: { "content-type": "application/json" },
725
+ body: JSON.stringify({ id: "ORD-1" }),
726
+ timeoutMs: 5_000,
727
+ });
728
+ ```
729
+
730
+ `CogoverFetchResponse` exposes `ok`, `status`, `statusText`, `url`, `redirected`
731
+ (always `false`), `headers`, `bodyUsed`, `text()`, and `json<T>()`. The bounded,
732
+ buffered body can be consumed once. Header `get(name)`, `has(name)`, `entries()`,
733
+ and iteration are case-insensitive.
734
+
735
+ V1 does not follow redirects, persist or send cookies, stream requests/responses,
736
+ or support WebSocket. It does not accept `signal`, `credentials`, `redirect`, proxy,
737
+ dispatcher, agent, DNS resolver, or TLS configuration. HTTP URLs, ports other than
738
+ 443, userinfo, and IP-literal hosts are unsupported. Framing, hop-by-hop, proxy,
739
+ forwarding, and reserved Cogover request headers are rejected. Request/response sizes,
740
+ headers, time, calls, destinations, and concurrency are bounded by platform quotas.
741
+
742
+ Failures are `CogoverApiError` instances with `FETCH_DISABLED`, `FETCH_BLOCKED`,
743
+ `FETCH_REQUEST_TOO_LARGE`, `FETCH_RESPONSE_TOO_LARGE`, `FETCH_TIMEOUT`, or
744
+ `FETCH_FAILED`; quota failures use `RateLimitError`. When POST, PUT, PATCH, or DELETE
745
+ times out or loses its response, the remote server may already have applied the
746
+ request. Use the remote API's idempotency mechanism and never retry blindly.
747
+
748
+ ## Record API
749
+
750
+ ```typescript
751
+ const orders = data.object("order");
752
+ await orders.records.get(id, { fields });
753
+ await orders.records.getMany(ids, { fields });
754
+ await orders.records.list({ where, orderBy, fields, limit, cursor });
755
+ await orders.records.create(fields);
756
+ await orders.records.update(id, fields);
757
+ await orders.records.batchInsert(records);
758
+ await orders.records.batchUpdate(records);
759
+ await orders.records.upsertByUniqueField(matchBy, fields);
760
+ await orders.records.deleteMany(ids);
761
+ ```
762
+
763
+ ### Record values and results
764
+
765
+ ```typescript
766
+ type CogoverRecordId = string & {
767
+ readonly __cogoverRecordIdBrand: unique symbol;
768
+ };
769
+
770
+ interface RecordReference<ObjectSlug extends string = string> {
771
+ readonly id: CogoverRecordId;
772
+ readonly name: string;
773
+ readonly objectSlug?: ObjectSlug;
774
+ }
775
+
776
+ interface UrlValue {
777
+ readonly url: string;
778
+ readonly alias?: string;
779
+ }
780
+
781
+ interface FileValue {
782
+ readonly id: string;
783
+ readonly name: string;
784
+ readonly size?: number;
785
+ readonly contentType?: string;
786
+ readonly url?: string;
787
+ }
788
+
789
+ interface CogoverRecord<Fields> {
790
+ readonly id: CogoverRecordId;
791
+ readonly fields: Readonly<Fields>;
792
+ readonly system: {
793
+ readonly createdAt: number;
794
+ readonly updatedAt: number;
795
+ readonly createdBy?: { readonly id: string; readonly name: string };
796
+ };
797
+ }
798
+
799
+ interface RecordPage<Fields> {
800
+ readonly items: CogoverRecord<Fields>[];
801
+ readonly total: number;
802
+ readonly nextCursor?: string;
803
+ }
804
+
805
+ interface GetManyResult<Fields> {
806
+ readonly records: CogoverRecord<Fields>[];
807
+ readonly missingIds: CogoverRecordId[];
808
+ }
809
+
810
+ interface DeleteResult {
811
+ readonly deleted: CogoverRecordId[];
812
+ readonly notDeleted: CogoverRecordId[];
813
+ }
814
+
815
+ interface BatchWriteRowResult {
816
+ readonly referenceId: string;
817
+ readonly id?: CogoverRecordId;
818
+ readonly r: number;
819
+ readonly msg?: string;
820
+ readonly success: boolean;
821
+ }
822
+
823
+ interface BatchWriteResponse {
824
+ readonly r: number;
825
+ readonly msg?: string;
826
+ readonly results: readonly BatchWriteRowResult[];
827
+ readonly success: boolean;
828
+ }
829
+
830
+ interface BatchUpdateItem<Fields> {
831
+ readonly id: CogoverRecordId;
832
+ readonly fields: UpdateFields<Fields>;
833
+ }
834
+
835
+ interface UpsertResult {
836
+ readonly id: CogoverRecordId;
837
+ readonly created: boolean;
838
+ }
839
+ ```
840
+
841
+ `CreateFields<Fields>` and `UpdateFields<Fields>` are partial mapped types over the
842
+ workspace fields. Reference values accept a string, `CogoverRecordId`, or matching
843
+ `RecordReference`; array fields accept readonly arrays. `UpsertFields<Fields,
844
+ MatchBy>` is a create-field map that requires the selected match field to be present
845
+ and non-null.
846
+
847
+ ### Data clients and operations
848
+
849
+ ```typescript
850
+ interface GetRecordOptions<Fields> {
851
+ readonly fields?: readonly (keyof Fields & string)[];
852
+ }
853
+
854
+ interface GetManyOptions<Fields> {
855
+ readonly fields: readonly (keyof Fields & string)[];
856
+ }
857
+
858
+ interface ListOptions<Fields> {
859
+ readonly where?: FilterExpression;
860
+ readonly orderBy?: readonly SortExpression[];
861
+ readonly fields?: readonly (keyof Fields & string)[];
862
+ readonly limit?: number;
863
+ readonly cursor?: string;
864
+ }
865
+
866
+ interface RecordWritesApi<Fields> {
867
+ create(fields: CreateFields<Fields>): Promise<CogoverRecordId>;
868
+ update(id: CogoverRecordId, fields: UpdateFields<Fields>): Promise<void>;
869
+ batchInsert(records: readonly CreateFields<Fields>[]): Promise<BatchWriteResponse>;
870
+ batchUpdate(records: readonly BatchUpdateItem<Fields>[]): Promise<BatchWriteResponse>;
871
+ upsertByUniqueField<MatchBy extends keyof Fields & string>(
872
+ matchBy: MatchBy,
873
+ fields: UpsertFields<Fields, MatchBy>,
874
+ ): Promise<UpsertResult>;
875
+ deleteMany(ids: readonly CogoverRecordId[]): Promise<DeleteResult>;
876
+ }
877
+
878
+ interface RecordsApi<Fields> extends RecordWritesApi<Fields> {
879
+ get(id: string, options?: GetRecordOptions<Fields>): Promise<CogoverRecord<Fields> | null>;
880
+ getMany(ids: readonly string[], options: GetManyOptions<Fields>): Promise<GetManyResult<Fields>>;
881
+ list(options?: ListOptions<Fields>): Promise<RecordPage<Fields>>;
882
+ }
883
+
884
+ interface WriteObjectClient<Fields> {
885
+ readonly slug: string;
886
+ readonly fields: FieldReferences<Fields>;
887
+ readonly records: RecordWritesApi<Fields>;
888
+ }
889
+
890
+ interface ObjectClient<Fields> extends WriteObjectClient<Fields> {
891
+ readonly records: RecordsApi<Fields>;
892
+ }
893
+
894
+ interface AsUserDataApi<Schema extends object = EffectiveWorkspaceObjects> {
895
+ object<Slug extends keyof Schema & string>(slug: Slug): ObjectClient<Schema[Slug]>;
896
+ }
897
+
898
+ interface DataApi<Schema extends object = EffectiveWorkspaceObjects> {
899
+ object<Slug extends keyof Schema & string>(slug: Slug): ObjectClient<Schema[Slug]>;
900
+ asUser(personnelId: string): AsUserDataApi<Schema>;
901
+ asSystem(): DataApi<Schema>;
902
+ }
903
+ ```
904
+
905
+ `list` returns `RecordPage<T>` with `items`, `total`, and an optional opaque
906
+ `nextCursor`. A `CogoverRecord<T>` has `id`, business `fields`, and a separate
907
+ `system` object containing creation/update metadata.
908
+
909
+ `getMany(ids, { fields })` reads up to 200 records by ID with a single capability
910
+ call. `fields` is required and must be a non-empty list of field slugs. IDs are
911
+ trimmed and deduplicated in their original order; more than 200 unique IDs, a blank
912
+ ID, or an invalid `fields` list throws `ValidationError` before any request is sent.
913
+ An empty `ids` array resolves to `{ records: [], missingIds: [] }` without a request.
914
+ The result contains the readable `records` and `missingIds`: every requested ID that
915
+ could not be read, because the record does not exist or the identity in use cannot
916
+ see it. IDs are never dropped silently. The order of `records` is not guaranteed to
917
+ follow `ids`, so index them by `id`:
918
+
919
+ ```typescript
920
+ const accounts = data.object("account");
921
+ const { records, missingIds } = await accounts.records.getMany(accountIds, { fields: ["credit_limit"] });
922
+ const accountById = new Map(records.map(record => [record.id, record]));
923
+ ```
924
+
925
+ Use `getMany` instead of calling `get` in a loop. Every capability call counts
926
+ towards the project's limits, and a record trigger can receive 200 records at once.
927
+
928
+ Service `0`/`1` booleans are normalized to JavaScript booleans. Lookup/reference
929
+ responses expose only `id`, `name`, and `objectSlug`; writes accept an ID or a
930
+ `RecordReference` and send only the ID to Cogover.
931
+
932
+ ## Filters and sorting
933
+
934
+ ```typescript
935
+ type FilterOperator =
936
+ | "=" | "!=" | ">" | ">=" | "<" | "<="
937
+ | "like" | "not like" | "startsWith" | "endsWith"
938
+ | "in" | "not in" | "is null" | "not null" | "between";
939
+
940
+ interface FilterCondition {
941
+ readonly kind: "condition";
942
+ readonly field: string;
943
+ readonly operator: FilterOperator;
944
+ readonly value?: unknown;
945
+ }
946
+
947
+ interface FilterGroup {
948
+ readonly kind: "group";
949
+ readonly operator: "and" | "or";
950
+ readonly expressions: readonly FilterExpression[];
951
+ }
952
+
953
+ type FilterExpression = FilterCondition | FilterGroup;
954
+
955
+ interface SortExpression {
956
+ readonly field: string;
957
+ readonly direction: "asc" | "desc";
958
+ }
959
+
960
+ interface FieldReference<Value> {
961
+ readonly slug: string;
962
+ eq(value: NonNullable<Value>): FilterCondition;
963
+ neq(value: NonNullable<Value>): FilterCondition;
964
+ gt(value: NonNullable<Value>): FilterCondition;
965
+ gte(value: NonNullable<Value>): FilterCondition;
966
+ lt(value: NonNullable<Value>): FilterCondition;
967
+ lte(value: NonNullable<Value>): FilterCondition;
968
+ like(value: string): FilterCondition;
969
+ notLike(value: string): FilterCondition;
970
+ startsWith(value: string): FilterCondition;
971
+ endsWith(value: string): FilterCondition;
972
+ in(values: readonly (
973
+ NonNullable<Value> extends readonly (infer Item)[] ? NonNullable<Item> : NonNullable<Value>
974
+ )[]): FilterCondition;
975
+ notIn(values: readonly (
976
+ NonNullable<Value> extends readonly (infer Item)[] ? NonNullable<Item> : NonNullable<Value>
977
+ )[]): FilterCondition;
978
+ isNull(): FilterCondition;
979
+ notNull(): FilterCondition;
980
+ between(from: NonNullable<Value>, to: NonNullable<Value>): FilterCondition;
981
+ asc(): SortExpression;
982
+ desc(): SortExpression;
983
+ }
984
+ ```
985
+
986
+ Each `FieldReference<Value>` exposes `slug`, `eq`, `neq`, `gt`, `gte`, `lt`,
987
+ `lte`, `like`, `notLike`, `startsWith`, `endsWith`, `in`, `notIn`, `isNull`,
988
+ `notNull`, `between`, `asc`, and `desc`. `FieldReferences<Fields>` provides these
989
+ references for workspace fields and the system fields `id`, `created`, `updated`,
990
+ and `created_by`. `and(...expressions)` and `or(...expressions)` return a
991
+ `FilterGroup` and require at least one expression.
992
+ For array-valued fields, `in` and `notIn` accept the array's element type.
993
+
994
+ Transport-specific field metadata and response envelopes are handled by Cogover.
995
+
996
+ `create` and `update` require a non-empty field object. `batchInsert` accepts 1–200
997
+ field objects; `batchUpdate` accepts 1–200 `{ id, fields }` items. Both are
998
+ best-effort operations: their `BatchWriteResponse`
999
+ contains one result per input row, and callers must inspect the top-level `success`
1000
+ flag or each row's `success`, `r`, and `msg`. A successful request is not an
1001
+ all-or-none transaction and does not guarantee that every row was written.
1002
+ `referenceId` identifies the zero-based input index as a string.
1003
+
1004
+ `deleteMany` requires at least one non-blank record ID and returns separate
1005
+ `deleted` and `notDeleted` arrays. Record IDs, object slugs, and field slugs are
1006
+ validated before a request is sent.
1007
+
1008
+ `upsertByUniqueField(matchBy, fields)` updates the record whose configured unique
1009
+ field equals `fields[matchBy]`, or creates it when no record matches. The match field
1010
+ must be a single, non-multiple field with uniqueness enabled, and the business key
1011
+ must be non-null and non-blank. The result is `{ id, created }`. Because the server
1012
+ chooses the create/update branch, the operation requires both record-create and
1013
+ record-update permission.
1014
+
1015
+ A unique-key conflict is exposed as `ValidationError` with
1016
+ `details.reason === "UNIQUE_KEY_VIOLATION"`, `objectSlug`, and `fieldSlug`. The
1017
+ public error does not echo the rejected business-key value.
1018
+
1019
+ ## Record execution identities
1020
+
1021
+ `data.object(slug)` inherits the invocation identity. For an authenticated public
1022
+ invocation this is the caller; a system invocation keeps system access.
1023
+
1024
+ ### `data.asUser(personnelId: string): AsUserDataApi<TSchema>`
1025
+
1026
+ Returns a new immutable client for reads and writes as the specified personnel ID (not an
1027
+ account ID), in the same workspace. `personnelId` is trimmed; a non-string or blank
1028
+ value throws `ValidationError`. Its `object(slug)` returns `ObjectClient<TFields>`,
1029
+ whose `records: RecordsApi<TFields>` exposes `get`, `getMany`, `list`, `create`, `update`, and
1030
+ `deleteMany` as well as batch insert, batch update, and business upsert, with the
1031
+ same argument and return types as the default record API.
1032
+
1033
+ `get(id, options?)` returns `CogoverRecord<TFields> | null`; `list(options?)` returns
1034
+ `RecordPage<TFields>`. Field selection, filters, sorting and cursors work as on the
1035
+ default client. Reads apply the selected user's permissions and approved project
1036
+ field restrictions. An empty successful lookup returns `null`; server failures
1037
+ throw errors instead of being treated as missing records or an empty page.
1038
+
1039
+ ```typescript
1040
+ const delegatedOrders = data.asUser(personnelId).object("order");
1041
+ const order = await delegatedOrders.records.get(recordId, { fields: ["description"] });
1042
+ const page = await delegatedOrders.records.list({
1043
+ fields: ["description"],
1044
+ where: delegatedOrders.fields.description.eq("Pending review"),
1045
+ limit: 20,
1046
+ });
1047
+ ```
1048
+
1049
+ ### `data.asSystem(): DataApi<TSchema>`
1050
+
1051
+ Returns a new immutable client for system record access, including during an
1052
+ authenticated public invocation. It supports `get`, `getMany`, `list`, `create`, `update`, and
1053
+ `deleteMany`, including batch writes and business upsert. System access does not
1054
+ apply the caller's record permissions; approved project restrictions, field
1055
+ validation, workspace boundaries, and runtime limits still apply. It neither
1056
+ changes the invocation's caller nor modifies existing clients.
1057
+
1058
+ ```typescript
1059
+ const orders = data.object("order");
1060
+ await orders.records.update(order.id, { description: "Caller update" });
1061
+ await data.asUser(personnelId).object("order").records.update(order.id, { description: "Delegated update" });
1062
+ await data.asSystem().object("order").records.update(order.id, { description: "System update" });
1063
+ ```
1064
+
1065
+ Identity selection needs administrator approval for the project version, permitted
1066
+ callers, target personnel, objects, operations, and fields. Selection alone grants
1067
+ no permission. Unauthorized operations throw `PermissionDeniedError`; invalid or
1068
+ unresolvable identities never fall back to system or caller access. Server failures
1069
+ retain their original `CogoverApiError.r`. No credentials or workspace override are
1070
+ accepted by these methods. Schema access is unchanged. Each write is independent;
1071
+ the three example calls above are not a transaction.
1072
+
1073
+ ## Project state
1074
+
1075
+ State is durable JSON scoped by workspace, project, namespace, and key. It is not
1076
+ version-scoped, so it remains available after a new project version is published.
1077
+
1078
+ ```typescript
1079
+ interface StateEntry<T> {
1080
+ readonly value: T;
1081
+ readonly version: number;
1082
+ readonly expiresAt?: number;
1083
+ readonly createdAt: number;
1084
+ readonly updatedAt: number;
1085
+ }
1086
+
1087
+ interface StateWriteOptions {
1088
+ readonly expectedVersion?: number;
1089
+ readonly ttlSeconds?: number;
1090
+ }
1091
+
1092
+ interface StateDeleteOptions {
1093
+ readonly expectedVersion?: number;
1094
+ }
1095
+
1096
+ interface StateNamespace {
1097
+ readonly name: string;
1098
+ get<T>(key: string): Promise<StateEntry<T> | null>;
1099
+ set<T>(key: string, value: T, options?: StateWriteOptions): Promise<StateEntry<T>>;
1100
+ delete(key: string, options?: StateDeleteOptions): Promise<boolean>;
1101
+ }
1102
+
1103
+ interface ProjectState {
1104
+ namespace(name: string): StateNamespace;
1105
+ }
1106
+ ```
1107
+
1108
+ ```typescript
1109
+ const progress = state.namespace("inventory-sync");
1110
+ const current = await progress.get<{ cursor: string }>("cursor");
1111
+
1112
+ const saved = await progress.set("cursor", { cursor: "next-page" }, {
1113
+ expectedVersion: current?.version ?? 0,
1114
+ ttlSeconds: 3600,
1115
+ });
1116
+
1117
+ await progress.delete("cursor", { expectedVersion: saved.version });
1118
+ ```
1119
+
1120
+ ### `state.namespace(name): StateNamespace`
1121
+
1122
+ Creates an immutable namespace client. Namespaces are at most 128 characters and
1123
+ keys at most 255. Both start with an ASCII letter or digit and may contain letters,
1124
+ digits, `.`, `_`, `:`, `/`, and `-`.
1125
+
1126
+ ### `namespace.get<T>(key): Promise<StateEntry<T> | null>`
1127
+
1128
+ Returns `null` when the entry is missing or expired. An entry contains `value`,
1129
+ `version`, `createdAt`, `updatedAt`, and optional `expiresAt`; timestamps are Unix
1130
+ milliseconds.
1131
+
1132
+ ### `namespace.set<T>(key, value, options?): Promise<StateEntry<T>>`
1133
+
1134
+ Stores a JSON value of at most 32 KiB (32,768 UTF-8 bytes after serialization).
1135
+ `ttlSeconds` ranges from one second through 365 days; omit it for no automatic
1136
+ expiry. Both option values must be safe integers. `expectedVersion` enables
1137
+ compare-and-set: `0` means create only, a positive value must match the current
1138
+ version, and omission is an unconditional upsert.
1139
+ Conflicts throw `StateConflictError`; the returned entry has the new version.
1140
+
1141
+ ### `namespace.delete(key, options?): Promise<boolean>`
1142
+
1143
+ Deletes an entry and returns whether it existed. `expectedVersion` has the same CAS
1144
+ meaning as on `set`. Expired entries are treated as absent. State operations do not
1145
+ form a transaction with Record API calls. Do not use state for secrets, files, or
1146
+ large data.
1147
+
1148
+ ## Distributed locks
1149
+
1150
+ Locks are distributed leases scoped by workspace, project, namespace, and key. They
1151
+ prevent concurrent executions from entering the same protected section. Prefer
1152
+ `withLock` for automatic release:
1153
+
1154
+ ```typescript
1155
+ interface LockOptions {
1156
+ readonly namespace?: string;
1157
+ readonly waitMs?: number;
1158
+ readonly leaseMs?: number;
1159
+ }
1160
+
1161
+ interface LockLease {
1162
+ readonly id: string;
1163
+ readonly key: string;
1164
+ readonly namespace: string;
1165
+ readonly fencingToken: number;
1166
+ readonly expiresAt: number;
1167
+ renew(leaseMs?: number): Promise<void>;
1168
+ release(): Promise<void>;
1169
+ }
1170
+
1171
+ interface DistributedLocks {
1172
+ acquire(key: string, options?: LockOptions): Promise<LockLease | null>;
1173
+ withLock<T>(key: string, callback: (lease: LockLease) => T | Promise<T>): Promise<T>;
1174
+ withLock<T>(key: string, options: LockOptions,
1175
+ callback: (lease: LockLease) => T | Promise<T>): Promise<T>;
1176
+ }
1177
+ ```
1178
+
1179
+ ```typescript
1180
+ await locks.withLock("INV-1", { namespace: "invoice", waitMs: 500 }, async lease => {
1181
+ await processInvoice("INV-1", lease.fencingToken);
1182
+ // Renew only if work can approach expiresAt.
1183
+ // await lease.renew(30_000);
1184
+ });
1185
+ ```
1186
+
1187
+ ### `locks.acquire(key, options?): Promise<LockLease | null>`
1188
+
1189
+ Returns a lease, or `null` when it cannot acquire one within `waitMs`. The namespace
1190
+ defaults to `default`; `waitMs` ranges from 0 through 10,000 ms; `leaseMs` ranges
1191
+ from 5,000 through 60,000 ms and defaults to 30,000 ms. One invocation may hold at
1192
+ most 16 locks. Keys are at most 255 characters and namespaces at most 128; both use
1193
+ the same character rules as state names. Numeric options must be safe integers.
1194
+
1195
+ A lease exposes `id`, `key`, `namespace`, `fencingToken`, `expiresAt`,
1196
+ `renew(leaseMs?)`, and `release()`. Renew and release verify ownership with a
1197
+ token managed by Cogover; that token is never exposed to scripts. A lost or expired
1198
+ lease throws `LockLostError`. Repeated `release()` on the same successfully released
1199
+ lease object is a no-op.
1200
+
1201
+ ### `locks.withLock(key, callback)` / `locks.withLock(key, options, callback)`
1202
+
1203
+ Acquires the lock, runs the callback, and releases in `finally`. Failure to acquire
1204
+ throws `LockUnavailableError`. It does not auto-renew; long callbacks must call
1205
+ `lease.renew()` before `expiresAt`.
1206
+
1207
+ A lock only guarantees one valid lease at a time. Timeouts, pauses, or network
1208
+ failures may let old work continue after its lease expires. When the downstream
1209
+ system supports it, store/check `fencingToken` and reject stale tokens. Locks do not
1210
+ replace idempotency, provide exactly-once execution, or combine Record API and state
1211
+ operations into a transaction.
1212
+
1213
+ ## Schema API
1214
+
1215
+ `SchemaApi<Schema>.object(slug)` reads Object metadata and returns:
1216
+
1217
+ ```typescript
1218
+ interface ObjectMetadata {
1219
+ readonly id: string;
1220
+ readonly name: string;
1221
+ readonly slug: string;
1222
+ readonly fields: readonly {
1223
+ readonly id: string;
1224
+ readonly name: string;
1225
+ readonly slug: string;
1226
+ readonly fieldType: string;
1227
+ readonly required: boolean;
1228
+ readonly multiple: boolean;
1229
+ readonly readOnly: boolean;
1230
+ readonly manualModifyAllow?: boolean;
1231
+ readonly metaData?: Readonly<Record<string, unknown>>;
1232
+ readonly options?: readonly {
1233
+ readonly id: string;
1234
+ readonly slug: string;
1235
+ readonly value: string;
1236
+ readonly isDefault?: boolean;
1237
+ }[];
1238
+ }[];
1239
+ }
1240
+
1241
+ interface SchemaApi<Schema extends object = EffectiveWorkspaceObjects> {
1242
+ object<Slug extends keyof Schema & string>(slug: Slug): Promise<ObjectMetadata>;
1243
+ }
1244
+ ```
1245
+
1246
+ Object and field mutation are not part of this SDK. An invalid object slug throws
1247
+ `ValidationError`; service failures use the error types described below.
1248
+
1249
+ ## Logging
1250
+
1251
+ `context.log` implements `ScriptLogger`:
1252
+
1253
+ ```typescript
1254
+ interface ScriptLogger {
1255
+ debug(message: string, details?: unknown): void;
1256
+ info(message: string, details?: unknown): void;
1257
+ warn(message: string, details?: unknown): void;
1258
+ error(message: string, details?: unknown): void;
1259
+ }
1260
+ ```
1261
+
1262
+ The optional `details` value is logged separately from the message. Do not include
1263
+ credentials, tokens, personal data, or other secrets in either argument.
1264
+
1265
+ ## Errors
1266
+
1267
+ API failures become `NotFoundError`, `ValidationError`,
1268
+ `PermissionDeniedError`, `RateLimitError`, `StateConflictError`,
1269
+ `LockUnavailableError`, `LockLostError`, or `CogoverApiError`.
1270
+
1271
+ ```typescript
1272
+ class CogoverApiError extends Error {
1273
+ readonly code: string;
1274
+ readonly r: number | undefined;
1275
+ readonly details?: unknown;
1276
+ constructor(code: string, message: string, details?: unknown);
1277
+ }
1278
+
1279
+ class NotFoundError extends CogoverApiError {
1280
+ readonly resource: string;
1281
+ readonly resourceId: string;
1282
+ constructor(resource: string, resourceId: string, message?: string, details?: unknown);
1283
+ }
1284
+
1285
+ class ValidationError extends CogoverApiError {
1286
+ constructor(message: string, details?: unknown);
1287
+ }
1288
+
1289
+ class PermissionDeniedError extends CogoverApiError {
1290
+ constructor(message: string, details?: unknown);
1291
+ }
1292
+
1293
+ class RateLimitError extends CogoverApiError {
1294
+ constructor(message: string, details?: unknown);
1295
+ }
1296
+
1297
+ class RetryableError extends CogoverApiError {
1298
+ constructor(message: string, details?: unknown);
1299
+ }
1300
+
1301
+ class StateConflictError extends CogoverApiError {
1302
+ constructor(message: string, details?: unknown);
1303
+ }
1304
+
1305
+ class LockUnavailableError extends CogoverApiError {
1306
+ constructor(key: string, message?: string, details?: unknown);
1307
+ }
1308
+
1309
+ class LockLostError extends CogoverApiError {
1310
+ constructor(message: string, details?: unknown);
1311
+ }
1312
+ ```
1313
+
1314
+ Errors expose the SDK category in `error.code` and the original numeric server
1315
+ result in `error.r` (also retained in `error.details.r`). `r` is `undefined` when
1316
+ there was no server response, such as local SDK validation. The original message
1317
+ remains in `error.message`.
1318
+
1319
+ `RetryableError` (`code: "RETRYABLE"`) is thrown by project code, never by the SDK.
1320
+ An after-change trigger handler throws it to report a temporary failure, and Cogover
1321
+ runs the handler again later (see
1322
+ [After-change execution rules](#after-change-execution-rules)). Anywhere else it
1323
+ has no special meaning: a script that lets it escape returns HTTP 422, and a
1324
+ before-change trigger that throws it rejects the write like any other failure.
1325
+
1326
+ Scripts can catch `CogoverApiError`, inspect `error.r`, and return their own client
1327
+ error, such as `{ r: 1001, msg: "You cannot update this order." }`, without exposing
1328
+ the original code or message. A script's returned JSON remains its own response
1329
+ with HTTP 200. All client-facing text in `msg`, `message`, and equivalent response
1330
+ fields must be written in English, including responses created by customer scripts.
1331
+
1332
+ ```typescript
1333
+ try {
1334
+ await orders.records.update(id, fields);
1335
+ } catch (error) {
1336
+ if (error instanceof CogoverApiError && error.r === 37) {
1337
+ return { r: 1001, msg: "You do not have permission to update this order." };
1338
+ }
1339
+ throw error;
1340
+ }
1341
+ ```
1342
+
1343
+ Import `CogoverApiError` from `@cogover/sdk`.
1344
+
1345
+ For SDK errors escaping `defineScript`, the HTTP endpoint returns an error with
1346
+ `r` equal to the HTTP status, `code`, and a safe `msg`:
1347
+
1348
+ | SDK code | HTTP / `r` |
1349
+ |---|---|
1350
+ | `PERMISSION_DENIED` | 403 |
1351
+ | `NOT_FOUND` | 404 |
1352
+ | `METHOD_NOT_ALLOWED` | 405 |
1353
+ | `VALIDATION_ERROR` | 400 |
1354
+ | `RATE_LIMITED` | 429 |
1355
+ | `STATE_CONFLICT` | 409 |
1356
+ | `LOCK_NOT_ACQUIRED` | 409 |
1357
+ | `LOCK_LOST` | 409 |
1358
+ | `STATE_SERVICE_UNAVAILABLE` | 503 |
1359
+ | `LOCK_SERVICE_UNAVAILABLE` | 503 |
1360
+ | `FETCH_DISABLED` | 503 |
1361
+ | `FETCH_BLOCKED` | 400 |
1362
+ | `FETCH_REQUEST_TOO_LARGE` | 413 |
1363
+ | `FETCH_RESPONSE_TOO_LARGE` | 502 |
1364
+ | `FETCH_TIMEOUT` | 504 |
1365
+ | `FETCH_FAILED` | 502 |
1366
+ | `COGOVER_API_ERROR` | 422 |
1367
+ | `RETRYABLE` | 422 |
1368
+
1369
+ Missing approval for an explicit identity adds `reason: "IDENTITY_NOT_GRANTED"`;
1370
+ it does not mean the selected user was denied access to a particular record.
1371
+ Raw error messages, stack traces and arbitrary details are not returned.
1372
+ `writesMayHaveCompleted` is true if any record write was dispatched, even if a later
1373
+ operation failed. It is a conservative warning, not confirmation of a successful write.
1374
+ Unknown errors and resource-limit failures retain the generic HTTP 422 response.
1375
+ These responses do not roll back earlier writes; do not retry writes automatically.
1376
+
1377
+ ## Workspace declarations
1378
+
1379
+ `WorkspaceObjects` is an open interface. Without augmentation, object and field
1380
+ slugs are strings with unknown field values. Generate and include a declaration to
1381
+ make them workspace-specific:
1382
+
1383
+ ```bash
1384
+ npx cogover-generate-workspace-types objects.json workspace.d.ts
1385
+ ```
1386
+
1387
+ The generator reads Object metadata, sorts object and field slugs, and maps field
1388
+ types as follows:
1389
+
1390
+ | Object field type | Generated TypeScript type |
1391
+ |---|---|
1392
+ | `short_text`, `long_text`, `phone`, `email`, `regex`, `auto_number`, `date` | `string` |
1393
+ | `boolean` | `boolean` |
1394
+ | `numeric`, `decimal`, `currency`, `percent`, `rating`, `time`, `date_time`, `time_duration` | `number` |
1395
+ | `single_choice` | union of option slugs, or `string` |
1396
+ | `multi_choices`, `label`, `cascading` | readonly array of option slugs, or strings |
1397
+ | `url` | `UrlValue` |
1398
+ | `file` | `FileValue` |
1399
+ | `lookup_normal`, `reference` | `RecordReference<ObjectSlug>` when the target is known |
1400
+ | `date_range` | `readonly [string, string]` |
1401
+ | `date_time_range`, `time_range` | `readonly [number, number]` |
1402
+ | unknown field type | `unknown` |
1403
+
1404
+ Fields that are not required include `null`; metadata marked `multiple` becomes a
1405
+ readonly array unless its base type is already an array. Add the generated file to
1406
+ the project's TypeScript compilation and do not edit it manually.
1407
+
1408
+ ## Compatibility helper
1409
+
1410
+ ```typescript
1411
+ function createGreeting(name: string): string;
1412
+ ```
1413
+
1414
+ `createGreeting("Cogover")` returns `"Hello Cogover"`. It remains available for
1415
+ SDK 0.1.x compatibility and is not part of the data APIs.