@cogover/sdk 0.5.0 → 0.7.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.
@@ -4,20 +4,22 @@
4
4
 
5
5
  A **Custom Backend Module** adds server-side business logic to a Cogover
6
6
  workspace. Use one to process requests, validate or transform data, automate
7
- record operations, expose HTTP routes, or integrate Cogover with an external
8
- service. It is different from a Custom Frontend Module, which implements a user
7
+ record operations, check or adjust records before they are saved, expose HTTP
8
+ routes, or integrate Cogover with an external service. It is different from a Custom Frontend Module, which implements a user
9
9
  interface.
10
10
 
11
11
  Custom Backend Modules are written in TypeScript. `@cogover/sdk` supplies the
12
12
  types and APIs for the current invocation, workspace data, schema metadata,
13
- logging, outbound HTTPS requests, state, and distributed locks. Cogover executes
13
+ logging, outbound HTTPS requests, state, distributed locks, and push messages to
14
+ web clients. Cogover executes
14
15
  the module with the permissions and resource limits configured for the project.
15
16
 
16
17
  A typical development flow is:
17
18
 
18
19
  1. Create a TypeScript project and install `@cogover/sdk`.
19
20
  2. Generate `workspace.d.ts` so workspace Objects and fields are type-safe.
20
- 3. Implement and locally type-check the module's default handler.
21
+ 3. Implement and locally type-check the module's default handler and its record
22
+ triggers.
21
23
  4. Publish the module to Cogover, configure its permissions, and invoke it
22
24
  through the intended trigger or HTTP route.
23
25
 
@@ -108,6 +110,24 @@ export default defineScript(async ({ data }) => {
108
110
  });
109
111
  ```
110
112
 
113
+ ## Read many records by ID
114
+
115
+ `records.getMany` reads up to 200 records with one capability call. `fields` is
116
+ required, and IDs that cannot be read are reported instead of being dropped:
117
+
118
+ ```typescript
119
+ const accounts = data.object("account");
120
+ const { records, missingIds } = await accounts.records.getMany(accountIds, {
121
+ fields: ["name", "credit_limit"],
122
+ });
123
+ const accountById = new Map(records.map(record => [String(record.id), record]));
124
+ if (missingIds.length > 0) log.warn("Accounts could not be read", { missingIds });
125
+ ```
126
+
127
+ Duplicate IDs are sent once. The order of `records` is not guaranteed to follow
128
+ `ids`, so look records up by `id`. Prefer `getMany` to calling `get` in a loop:
129
+ every capability call counts towards the project's limits.
130
+
111
131
  ## Call an external API with `fetch`
112
132
 
113
133
  ```typescript
@@ -190,6 +210,32 @@ longer work, watch `expiresAt` and call `renew()` before expiry. Use the fencing
190
210
  token in downstream systems where possible to reject stale writers. Locks do not
191
211
  replace idempotency or provide exactly-once execution.
192
212
 
213
+ ## Tell open record pages to reload
214
+
215
+ ```typescript
216
+ export default defineTrigger({
217
+ key: "recalculate_totals",
218
+ object: "order",
219
+ timing: "afterChange",
220
+ operations: ["update"],
221
+ fields: ["subtotal", "tax"],
222
+ }, async ({ records, data, push }) => {
223
+ const items = records.flatMap(record => record.id === null ? [] : [{
224
+ id: record.id,
225
+ fields: { total: (record.new.subtotal ?? 0) + (record.new.tax ?? 0) },
226
+ }]);
227
+ await data.object("order").records.batchUpdate(items);
228
+ // Everyone who has one of these orders open reloads it, including the user who saved.
229
+ await push.refreshRecords("order", items.map(item => item.id));
230
+ });
231
+ ```
232
+
233
+ `push` also shows a toast (`push.toast`) or sends a silent message
234
+ (`push.message`) to the people viewing given records or to explicit personnel IDs
235
+ (`recipients`); `exclude: ["actor"]` skips the user who caused the execution.
236
+ Delivery is best-effort and each call counts as one capability call. The API
237
+ reference lists the limits and message fields.
238
+
193
239
  ## Choose the identity for record operations
194
240
 
195
241
  Keep using `data.object("order")` to inherit the caller's identity. When an
@@ -237,6 +283,198 @@ authentication object in module code, and never log or return credentials for an
237
283
  external service. See
238
284
  [API reference](api-reference.md#record-execution-identities).
239
285
 
286
+ ## Record triggers
287
+
288
+ A record trigger runs your code when records of one Object are created, updated, or
289
+ deleted. A **before-change** trigger runs before the change is saved: it can reject
290
+ the change with validation errors and it can adjust the values that will be saved.
291
+ An **after-change** trigger runs after the change has been saved, for follow-up work
292
+ such as updating related records or notifying another system; see
293
+ [After-change triggers](#after-change-triggers). A trigger runs for every source of a write — the Cogover web application, API keys,
294
+ imports, automation processes, and other Custom Backend Modules — so a rule placed
295
+ in a trigger cannot be bypassed by choosing a different way to write the record.
296
+ Maintenance writes made by Cogover itself, such as recalculating formula and rollup
297
+ fields, background record merges, and cascading deletes, do not run triggers.
298
+
299
+ Declare triggers with `defineTrigger` and list them in the named `triggers` export.
300
+ The default export remains the HTTP handler and is optional in a project that only
301
+ has triggers. This example assumes that `workspace.d.ts` declares the Objects and
302
+ fields it uses.
303
+
304
+ ```typescript
305
+ import { defineTrigger, type RecordReference } from "@cogover/sdk";
306
+
307
+ const referenceId = (value: string | RecordReference | null | undefined): string | undefined =>
308
+ typeof value === "string" ? value : value?.id;
309
+
310
+ export const triggers = [
311
+ defineTrigger({
312
+ key: "order_credit_check",
313
+ name: "Order credit check",
314
+ object: "order",
315
+ timing: "beforeChange",
316
+ operations: ["create", "update"],
317
+ fields: ["status", "amount", "customer"],
318
+ changedFields: ["status", "amount", "customer"],
319
+ when: { op: "=", field: "status", params: "confirmed" },
320
+ writableFields: ["approval_level"],
321
+ }, async ({ records, data }) => {
322
+ // One read for the whole list, never one read per record.
323
+ const customerIds = records.flatMap(record => referenceId(record.new.customer) ?? []);
324
+ const customers = await data.object("account").records.getMany(customerIds, {
325
+ fields: ["credit_limit"],
326
+ });
327
+ const limitById = new Map<string, number>(
328
+ customers.records.map(customer => [customer.id, customer.fields.credit_limit ?? 0]),
329
+ );
330
+
331
+ for (const record of records) {
332
+ const amount = record.new.amount ?? 0;
333
+ const limit = limitById.get(referenceId(record.new.customer) ?? "");
334
+ if (limit === undefined) {
335
+ record.addError("customer", "CUSTOMER_NOT_AVAILABLE", "Select a customer that you can access.");
336
+ continue;
337
+ }
338
+ if (amount > limit) {
339
+ record.addError("amount", "CREDIT_LIMIT_EXCEEDED", "Amount exceeds the customer's credit limit.");
340
+ continue;
341
+ }
342
+ record.new.approval_level = amount > 100_000_000 ? "high" : "standard";
343
+ }
344
+ }),
345
+ ];
346
+ ```
347
+
348
+ Cogover applies the triggers of the active project version. What each setting does:
349
+
350
+ - `fields` selects the values delivered in `record.new` and `record.old`. Only
351
+ these fields and `id` are present, so a field that is not listed is `undefined`.
352
+ List only what the handler reads: one call is limited to 200 KiB.
353
+ - `operations` chooses `"create"`, `"update"`, and `"delete"`. `record.old` is
354
+ `null` for a created record and `record.new` is `null` for a deleted one; the
355
+ TypeScript types follow the operations you declare.
356
+ - `changedFields` makes an update run the trigger only when at least one listed
357
+ field changed. `record.changedFields` tells the handler which fields changed.
358
+ - `when` only runs the trigger for matching records. It is a plain object such as
359
+ `{ op: "=", field: "status", params: "confirmed" }`, combined with
360
+ `{ op: "and", conditions: [...] }` or `{ op: "or", conditions: [...] }`.
361
+ `runWhen: "onEnter"` runs the trigger only when a record starts matching `when`,
362
+ instead of on every matching write.
363
+ - `writableFields` lists the fields the handler may change (before-change only).
364
+ - `order` (1000–8999, default 5000) positions the trigger among the triggers of the
365
+ same Object. Later triggers see the values changed by earlier ones.
366
+ - `timeoutMs` (100–3000, default 2000) is the time budget of one call.
367
+
368
+ **Validate.** Call `record.addError(field, code, message?)` to reject a record; pass
369
+ `null` as the field for an error about the whole record. The code is an upper-case
370
+ identifier such as `CREDIT_LIMIT_EXCEEDED`. The optional message is an English text
371
+ of at most 500 characters that Cogover shows to the end user when it has no
372
+ translation for the code. A rejected record is not saved. In a batch write the other
373
+ rows continue.
374
+
375
+ **Modify.** Assign fields of `record.new`, for example
376
+ `record.new.approval_level = "high"`. Only `writableFields` may change; changing any
377
+ other field makes the write fail with a `ValidationError` naming the field. Assigned
378
+ values use the same format as `records.update` input, so a reference field accepts a
379
+ record ID and a date field accepts `"yyyy-MM-dd"`. Assigning `null` clears a field. Cogover validates the final values again before saving. A trigger
380
+ may fill a field whose manual entry is disabled, but never a read-only field such as
381
+ a formula, auto number, or rollup.
382
+
383
+ **Process the whole list.** A handler receives up to 200 records in one call: a
384
+ batch write or an import calls it once per chunk, not once per record. Never read
385
+ inside the loop. Collect the IDs, call `records.getMany` once, and look the results
386
+ up from a `Map`, as in the example above.
387
+
388
+ **Read-only.** A before-change trigger may read records and schema. Record writes,
389
+ `fetch`, locks, state writes, and push messages are refused with `PermissionDeniedError`
390
+ (`details.reason === "TRIGGER_READ_ONLY"`), for every identity. The trigger context
391
+ has `records`, `trigger`, `invocation`, `data`, `schema`, `log`, and `push`; it has
392
+ no `request`, `response`, `state`, or `locks`.
393
+
394
+ **Identity.** `data.object()` acts as the user who made the change, with that user's
395
+ permissions, so a read can legitimately return nothing for a record the user cannot
396
+ see. `data.asUser()` and `data.asSystem()` need the same administrator approval as
397
+ in scripts.
398
+
399
+ **Time budget and failures.** A call must finish within `timeoutMs`, and all
400
+ before-change triggers of one write share 8 seconds. Before-change triggers fail
401
+ closed: when a handler throws, runs out of time, or cannot be run, the write is
402
+ rejected and nothing is saved. Keep handlers short and deterministic. See the
403
+ [record trigger reference](api-reference.md#record-triggers).
404
+
405
+ ### After-change triggers
406
+
407
+ Set `timing: "afterChange"` to run code after a change has been saved. The handler
408
+ runs asynchronously, shortly after the write: the writer does not wait for it, and
409
+ the handler can neither reject nor modify the saved change. Unlike a before-change
410
+ trigger it may write records and call `fetch`, like a script.
411
+
412
+ ```typescript
413
+ import { defineTrigger, fetch, RetryableError } from "@cogover/sdk";
414
+
415
+ export const triggers = [
416
+ defineTrigger({
417
+ key: "order_confirmed_followup",
418
+ object: "order",
419
+ timing: "afterChange",
420
+ operations: ["create", "update"],
421
+ fields: ["status", "amount", "customer"],
422
+ changedFields: ["status"],
423
+ when: { op: "=", field: "status", params: "confirmed" },
424
+ runWhen: "onEnter",
425
+ }, async ({ records, trigger, data }) => {
426
+ for (const record of records) {
427
+ // record.new holds the saved values; record.id is always set after the save.
428
+ const response = await fetch("https://erp.example.com/orders", {
429
+ method: "POST",
430
+ headers: {
431
+ "content-type": "application/json",
432
+ "idempotency-key": `${trigger.changeId}:${record.id}`,
433
+ },
434
+ body: JSON.stringify({ id: record.id, amount: record.new.amount }),
435
+ });
436
+ if (response.status >= 500) {
437
+ // Temporary problem: ask Cogover to run this handler again later.
438
+ throw new RetryableError("The ERP is temporarily unavailable");
439
+ }
440
+ if (!response.ok) continue; // Permanent problem: retrying would not help.
441
+
442
+ await data.object("order_activity").records.create({
443
+ order: record.id,
444
+ activity: "Sent to ERP",
445
+ });
446
+ }
447
+ }),
448
+ ];
449
+ ```
450
+
451
+ - **Saved values.** `record.new` contains the values as saved, including the record
452
+ ID and values assigned while saving, such as an auto number. `record.old` contains
453
+ the values before the change. A deleted record has `record.new === null`.
454
+ - **No blocking, no changes.** `writableFields` is not allowed and `record.new` must
455
+ not be changed. `record.addError()` rejects nothing here; the errors are only
456
+ written to the project log. To change the record, call `records.update`.
457
+ - **Best-effort delivery.** Cogover does not guarantee that the handler runs exactly
458
+ once: it may occasionally run more than once for the same change, or not at all.
459
+ Make handlers idempotent — `trigger.changeId` together with `record.id` identifies
460
+ one change of one record — and never rely on an after-change trigger as the only
461
+ guarantee of a critical rule. Put such rules in a before-change trigger.
462
+ - **Retries.** Throw `RetryableError` for a temporary failure. Cogover runs the
463
+ handler again later, by default up to 5 more times with growing delays from about
464
+ one second to about ten minutes. A call that runs out of time is retried the same
465
+ way. Any other error is logged and not retried, so catch the errors you can handle
466
+ and decide which of them deserve a retry.
467
+ - **Loops end.** A write made by the handler runs triggers again, possibly including
468
+ the same one. Cogover limits such chains: every automated write uses one step of a
469
+ fixed budget (10 steps for a change made directly by a user or an API client), and
470
+ after-change triggers stop running once it is used up. Narrow the trigger with
471
+ `changedFields`, `when`, and `runWhen: "onEnter"` so its own writes do not start
472
+ it again.
473
+ - **Order.** After-change triggers of one change run independently; do not rely on
474
+ their relative order, and read the current record when the latest values matter.
475
+
476
+ See [After-change execution rules](api-reference.md#after-change-execution-rules).
477
+
240
478
  ## Recommended TypeScript configuration
241
479
 
242
480
  ```json
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cogover/sdk",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "description": "TypeScript SDK for developing Custom Backend Modules on Cogover",
5
5
  "type": "module",
6
6
  "sideEffects": false,