@cogover/sdk 0.6.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.
package/README.md CHANGED
@@ -45,7 +45,7 @@ export default defineScript<Input, Output>(async ({ input, data, log }) => {
45
45
  ```
46
46
 
47
47
  `defineScript` parses the input JSON, provides invocation metadata and scoped
48
- data, schema, logging, state, and lock APIs, waits for the async handler, and
48
+ data, schema, logging, state, lock, and push APIs, waits for the async handler, and
49
49
  serializes its result. Cogover authentication credentials are not exposed to
50
50
  project code, and Cogover enforces the configured permissions and limits on
51
51
  capability calls.
@@ -145,7 +145,7 @@ the trigger runs.
145
145
 
146
146
  A handler receives up to 200 records per call, so read related data once with
147
147
  `records.getMany` instead of once per record. Before-change triggers are read-only:
148
- record writes, `fetch`, locks, and state writes are refused with
148
+ record writes, `fetch`, locks, state writes, and push messages are refused with
149
149
  `PermissionDeniedError` (`details.reason === "TRIGGER_READ_ONLY"`). `data.object()`
150
150
  acts as the user who made the change. A handler that throws or exceeds its
151
151
  `timeoutMs` (default 2,000 ms) rejects the write.
@@ -366,6 +366,31 @@ export default defineScript(async ({ locks }) =>
366
366
  State conflicts throw `StateConflictError`; failed lock acquisition and lost leases
367
367
  use `LockUnavailableError` and `LockLostError`.
368
368
 
369
+ ## Push messages to web clients
370
+
371
+ `push` asks the web app to react to what a script did: reload the records that are
372
+ open on screen, show a toast, or deliver a silent message. Recipients are the people
373
+ viewing the given records (the default) or explicit personnel IDs, and
374
+ `exclude: ["actor"]` skips the user who caused the execution.
375
+
376
+ ```typescript
377
+ export default defineTrigger({
378
+ key: "order_totals_changed",
379
+ object: "order",
380
+ timing: "afterChange",
381
+ operations: ["update"],
382
+ fields: ["total"],
383
+ }, async ({ records, push }) => {
384
+ const ids = records.flatMap(record => record.id === null ? [] : [record.id]);
385
+ await push.refreshRecords("order", ids);
386
+ await push.toast({ title: "Order totals updated", object: "order", recordIds: ids });
387
+ });
388
+ ```
389
+
390
+ Delivery is best-effort, each call counts as one capability call, and before-change
391
+ triggers cannot push. Invalid input throws `ValidationError`; an unknown object or
392
+ personnel throws `NotFoundError`.
393
+
369
394
  ## Workspace types
370
395
 
371
396
  `WorkspaceObjects` is an open interface augmented by a generated declaration for
package/dist/index.d.ts CHANGED
@@ -17,6 +17,7 @@ export type { RequestMethod, ScriptRequest, ScriptQuery, ScriptHeaders, ScriptPa
17
17
  export type { ResponseApi, ResponseInit, BinaryResponseInit, ResponseHeaderValue, ScriptResponse, } from "./response.js";
18
18
  export type { ProjectState, StateNamespace, StateEntry, StateWriteOptions, StateDeleteOptions, } from "./state.js";
19
19
  export type { DistributedLocks, LockLease, LockOptions, } from "./locks.js";
20
+ export type { PushRecipients, PushOptions, ToastPosition, ToastSize, ToastLink, ToastMessage, BackgroundContentType, BackgroundMessage, PushApi, } from "./push.js";
20
21
  export { fetch } from "./fetch.js";
21
22
  export type { CogoverFetchInit, CogoverFetchHeaders, CogoverFetchResponse, } from "./fetch.js";
22
23
  export { CogoverApiError, NotFoundError, ValidationError, PermissionDeniedError, RateLimitError, RetryableError, StateConflictError, LockUnavailableError, LockLostError, } from "./errors.js";
@@ -2,6 +2,7 @@ import { createDataApi } from "../data.js";
2
2
  import { ValidationError } from "../errors.js";
3
3
  import { installCogoverFetch } from "../fetch.js";
4
4
  import { SCRIPT_LOGGER } from "../logger.js";
5
+ import { createPushApi } from "../push.js";
5
6
  import { createSchemaApi } from "../schema.js";
6
7
  import { invocationContext } from "./invocation.js";
7
8
  import { cloneJson, deepFreeze, jsonEquals, toJsonValue } from "./json.js";
@@ -49,6 +50,7 @@ export function createTriggerSandboxHandler(manifest, handler) {
49
50
  data: createDataApi(),
50
51
  schema: createSchemaApi(),
51
52
  log: SCRIPT_LOGGER,
53
+ push: createPushApi(),
52
54
  }));
53
55
  const results = [];
54
56
  for (const entry of entries) {
package/dist/push.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ import type { EffectiveWorkspaceObjects, StringKeyOf } from "./workspace.js";
2
+ /** Who receives a push message: everyone who currently has a target record open, or explicit personnel. */
3
+ export type PushRecipients = "viewers" | readonly string[];
4
+ export interface PushOptions {
5
+ /** Defaults to `"viewers"`. Personnel IDs deliver to those people wherever they are in the workspace. */
6
+ readonly recipients?: PushRecipients;
7
+ /** Personnel IDs that never receive the message; `"actor"` is the user whose action started this execution. */
8
+ readonly exclude?: readonly string[];
9
+ }
10
+ export type ToastPosition = "TOP_LEFT" | "TOP_CENTER" | "TOP_RIGHT" | "BOTTOM_LEFT" | "BOTTOM_CENTER" | "BOTTOM_RIGHT";
11
+ export type ToastSize = "SMALL" | "MEDIUM" | "LARGE";
12
+ export interface ToastLink {
13
+ readonly label: string;
14
+ /** Absolute `http` or `https` URL. */
15
+ readonly url: string;
16
+ }
17
+ /** A short notification shown by the web app. At least one of `title` and `content` is required. */
18
+ export interface ToastMessage<TObject extends string = string> {
19
+ readonly title?: string;
20
+ readonly content?: string;
21
+ readonly links?: readonly ToastLink[];
22
+ /** Defaults to `"TOP_RIGHT"`. */
23
+ readonly position?: ToastPosition;
24
+ /** Defaults to `"MEDIUM"`. */
25
+ readonly size?: ToastSize;
26
+ /** Seconds the toast stays visible, 1 to 60; defaults to 5. */
27
+ readonly durationSeconds?: number;
28
+ /** Records the toast is about; required when the recipients are `"viewers"`. */
29
+ readonly object?: TObject;
30
+ readonly recordIds?: readonly string[];
31
+ }
32
+ export type BackgroundContentType = "text" | "template";
33
+ /** A message the web app handles without showing a notification. */
34
+ export interface BackgroundMessage<TObject extends string = string> {
35
+ readonly content: string;
36
+ /** Defaults to `"text"`. */
37
+ readonly contentType?: BackgroundContentType;
38
+ /** Records the message is about; required when the recipients are `"viewers"`. */
39
+ readonly object?: TObject;
40
+ readonly recordIds?: readonly string[];
41
+ }
42
+ /** Sends push messages to web clients of the workspace. Delivery is best-effort and never awaited. */
43
+ export interface PushApi<TSchema extends object = EffectiveWorkspaceObjects> {
44
+ /** Asks every client that shows one of these records to reload it. */
45
+ refreshRecords(object: StringKeyOf<TSchema>, recordIds: readonly string[], options?: PushOptions): Promise<void>;
46
+ toast(message: ToastMessage<StringKeyOf<TSchema>>, options?: PushOptions): Promise<void>;
47
+ message(message: BackgroundMessage<StringKeyOf<TSchema>>, options?: PushOptions): Promise<void>;
48
+ }
package/dist/push.js ADDED
@@ -0,0 +1,190 @@
1
+ import { ValidationError } from "./errors.js";
2
+ import { callBridge } from "./internal/bridge.js";
3
+ import { requireSlug } from "./internal/validation.js";
4
+ import { isRecord } from "./internal/values.js";
5
+ import { optionalInteger } from "./state.js";
6
+ const MAX_RECORDS = 200;
7
+ const MAX_PERSONNEL = 200;
8
+ const MAX_TITLE_CHARS = 200;
9
+ const MAX_TOAST_CONTENT_CHARS = 4_000;
10
+ const MAX_MESSAGE_CONTENT_CHARS = 16_384;
11
+ const MAX_LINKS = 5;
12
+ const MAX_LINK_LABEL_CHARS = 100;
13
+ const MAX_LINK_URL_CHARS = 2_048;
14
+ const MIN_DURATION_SECONDS = 1;
15
+ const MAX_DURATION_SECONDS = 60;
16
+ const DEFAULT_DURATION_SECONDS = 5;
17
+ const RECORD_ID = /^[A-Za-z0-9_-]{1,64}$/u;
18
+ const PERSONNEL_ID = /^[A-Za-z0-9_-]{1,128}$/u;
19
+ const ACTOR = "actor";
20
+ const VIEWERS = "viewers";
21
+ const POSITIONS = new Set([
22
+ "TOP_LEFT", "TOP_CENTER", "TOP_RIGHT", "BOTTOM_LEFT", "BOTTOM_CENTER", "BOTTOM_RIGHT",
23
+ ]);
24
+ const SIZES = new Set(["SMALL", "MEDIUM", "LARGE"]);
25
+ const CONTENT_TYPES = new Set(["text", "template"]);
26
+ /** @internal */
27
+ export function createPushApi() {
28
+ return Object.freeze({
29
+ async refreshRecords(object, recordIds, options) {
30
+ const payload = { ...target(object, recordIds), ...audience(options) };
31
+ await callBridge("push.refreshRecords", payload);
32
+ },
33
+ async toast(message, options) {
34
+ requireMessageObject(message, "push.toast()");
35
+ const recipients = audience(options);
36
+ const title = optionalText(message.title, "title", MAX_TITLE_CHARS);
37
+ const content = optionalText(message.content, "content", MAX_TOAST_CONTENT_CHARS);
38
+ if (title === undefined && content === undefined) {
39
+ throw new ValidationError("A toast requires a title or content");
40
+ }
41
+ const payload = {
42
+ ...optionalTarget(message.object, message.recordIds, recipients),
43
+ ...recipients,
44
+ position: choice(message.position, "position", POSITIONS, "TOP_RIGHT"),
45
+ size: choice(message.size, "size", SIZES, "MEDIUM"),
46
+ duration: optionalInteger(message.durationSeconds, "durationSeconds", MIN_DURATION_SECONDS, MAX_DURATION_SECONDS) ?? DEFAULT_DURATION_SECONDS,
47
+ };
48
+ if (title !== undefined)
49
+ payload.title = title;
50
+ if (content !== undefined)
51
+ payload.content = content;
52
+ const links = toastLinks(message.links);
53
+ if (links !== undefined)
54
+ payload.links = links;
55
+ await callBridge("push.toast", payload);
56
+ },
57
+ async message(message, options) {
58
+ requireMessageObject(message, "push.message()");
59
+ const recipients = audience(options);
60
+ const content = optionalText(message.content, "content", MAX_MESSAGE_CONTENT_CHARS);
61
+ if (content === undefined)
62
+ throw new ValidationError("A background message requires content");
63
+ const payload = {
64
+ ...optionalTarget(message.object, message.recordIds, recipients),
65
+ ...recipients,
66
+ content,
67
+ contentType: choice(message.contentType, "contentType", CONTENT_TYPES, "text"),
68
+ };
69
+ await callBridge("push.message", payload);
70
+ },
71
+ });
72
+ }
73
+ /** Checks the shape without narrowing the typed parameter, so property types stay those of the message. */
74
+ function requireMessageObject(value, method) {
75
+ if (!isRecord(value))
76
+ throw new ValidationError(`${method} requires a message object`);
77
+ }
78
+ function audience(options) {
79
+ if (options === undefined)
80
+ return { recipients: VIEWERS, exclude: [] };
81
+ if (!isRecord(options))
82
+ throw new ValidationError("push options must be an object");
83
+ const recipients = options.recipients;
84
+ let normalized;
85
+ if (recipients === undefined || recipients === VIEWERS) {
86
+ normalized = VIEWERS;
87
+ }
88
+ else if (Array.isArray(recipients)) {
89
+ normalized = personnelIds(recipients, "recipients", false);
90
+ if (normalized.length === 0)
91
+ throw new ValidationError("recipients must name at least one personnel ID");
92
+ }
93
+ else {
94
+ throw new ValidationError("recipients must be \"viewers\" or a list of personnel IDs");
95
+ }
96
+ const exclude = options.exclude === undefined ? [] : personnelIds(options.exclude, "exclude", true);
97
+ return { recipients: normalized, exclude };
98
+ }
99
+ function personnelIds(value, label, allowActor) {
100
+ if (!Array.isArray(value))
101
+ throw new ValidationError(`${label} must be a list of personnel IDs`);
102
+ if (value.length > MAX_PERSONNEL) {
103
+ throw new ValidationError(`${label} must not list more than ${MAX_PERSONNEL} personnel IDs`);
104
+ }
105
+ const ids = new Set();
106
+ for (const entry of value) {
107
+ // "actor" is a reserved word of `exclude`, never a personnel ID.
108
+ const accepted = typeof entry === "string"
109
+ && (entry === ACTOR ? allowActor : PERSONNEL_ID.test(entry));
110
+ if (!accepted) {
111
+ throw new ValidationError(`${label} must only contain personnel IDs${allowActor ? ` or "${ACTOR}"` : ""}`);
112
+ }
113
+ ids.add(entry);
114
+ }
115
+ return [...ids];
116
+ }
117
+ function target(object, recordIds) {
118
+ if (typeof object !== "string")
119
+ throw new ValidationError("object must be an object slug");
120
+ const objectSlug = requireSlug(object);
121
+ if (!Array.isArray(recordIds))
122
+ throw new ValidationError("recordIds must be a list of record IDs");
123
+ const ids = new Set();
124
+ for (const entry of recordIds) {
125
+ if (typeof entry !== "string" || !RECORD_ID.test(entry)) {
126
+ throw new ValidationError("recordIds must only contain record IDs");
127
+ }
128
+ ids.add(entry);
129
+ }
130
+ if (ids.size === 0 || ids.size > MAX_RECORDS) {
131
+ throw new ValidationError(`recordIds must contain 1 to ${MAX_RECORDS} record IDs`);
132
+ }
133
+ return { objectSlug, recordIds: [...ids] };
134
+ }
135
+ function optionalTarget(object, recordIds, recipients) {
136
+ if (object === undefined && recordIds === undefined) {
137
+ if (recipients.recipients === VIEWERS) {
138
+ throw new ValidationError("object and recordIds are required when the recipients are \"viewers\"");
139
+ }
140
+ return {};
141
+ }
142
+ return target(object, recordIds);
143
+ }
144
+ function optionalText(value, label, maximumChars) {
145
+ if (value === undefined || value === null)
146
+ return undefined;
147
+ if (typeof value !== "string")
148
+ throw new ValidationError(`${label} must be a string`);
149
+ if (value.trim().length === 0)
150
+ return undefined;
151
+ if (value.length > maximumChars) {
152
+ throw new ValidationError(`${label} must not exceed ${maximumChars} characters`);
153
+ }
154
+ return value;
155
+ }
156
+ function choice(value, label, allowed, fallback) {
157
+ if (value === undefined)
158
+ return fallback;
159
+ if (typeof value !== "string" || !allowed.has(value)) {
160
+ throw new ValidationError(`${label} must be one of ${[...allowed].sort().join(", ")}`);
161
+ }
162
+ return value;
163
+ }
164
+ function toastLinks(value) {
165
+ if (value === undefined)
166
+ return undefined;
167
+ if (!Array.isArray(value))
168
+ throw new ValidationError("links must be a list of { label, url }");
169
+ if (value.length === 0)
170
+ return undefined;
171
+ if (value.length > MAX_LINKS)
172
+ throw new ValidationError(`links must not contain more than ${MAX_LINKS} links`);
173
+ return value.map(entry => {
174
+ if (!isRecord(entry))
175
+ throw new ValidationError("links must be a list of { label, url }");
176
+ const { label, url } = entry;
177
+ if (typeof label !== "string" || label.trim().length === 0 || label.length > MAX_LINK_LABEL_CHARS) {
178
+ throw new ValidationError(`Each link label must be a string of 1 to ${MAX_LINK_LABEL_CHARS} characters`);
179
+ }
180
+ if (typeof url !== "string" || !isHttpUrl(url)) {
181
+ throw new ValidationError(`Each link url must be an absolute http or https URL of at most ${MAX_LINK_URL_CHARS} characters`);
182
+ }
183
+ return { label, url };
184
+ });
185
+ }
186
+ // The sandbox has no WHATWG `URL` global, so the shape is checked with a pattern; Cogover parses it again.
187
+ const HTTP_URL = /^https?:\/\/[^\s/?#\\@]+(?:[/?#]\S*)?$/iu;
188
+ function isHttpUrl(value) {
189
+ return value.length > 0 && value.length <= MAX_LINK_URL_CHARS && HTTP_URL.test(value);
190
+ }
package/dist/router.js CHANGED
@@ -59,6 +59,7 @@ export function createRouter() {
59
59
  response: context.response,
60
60
  state: context.state,
61
61
  locks: context.locks,
62
+ push: context.push,
62
63
  });
63
64
  });
64
65
  },
package/dist/script.d.ts CHANGED
@@ -6,6 +6,7 @@ import type { SchemaApi } from "./schema.js";
6
6
  import type { EffectiveWorkspaceObjects } from "./workspace.js";
7
7
  import type { ProjectState } from "./state.js";
8
8
  import type { DistributedLocks } from "./locks.js";
9
+ import type { PushApi } from "./push.js";
9
10
  import type { InvocationContext } from "./invocation.js";
10
11
  export interface ScriptContext<TInput, TSchema extends object = EffectiveWorkspaceObjects> {
11
12
  readonly input: TInput;
@@ -17,6 +18,7 @@ export interface ScriptContext<TInput, TSchema extends object = EffectiveWorkspa
17
18
  readonly response: ResponseApi;
18
19
  readonly state: ProjectState;
19
20
  readonly locks: DistributedLocks;
21
+ readonly push: PushApi<TSchema>;
20
22
  }
21
23
  export type ScriptHandler<TInput, TOutput, TSchema extends object = EffectiveWorkspaceObjects> = (context: ScriptContext<TInput, TSchema>) => TOutput | ScriptResponse<unknown> | null | Promise<TOutput | ScriptResponse<unknown> | null>;
22
24
  export type SandboxHandler = (inputJson: string) => Promise<string | null>;
package/dist/script.js CHANGED
@@ -7,6 +7,7 @@ import { SCRIPT_LOGGER } from "./logger.js";
7
7
  import { createSchemaApi } from "./schema.js";
8
8
  import { createStateApi } from "./state.js";
9
9
  import { createLocksApi } from "./locks.js";
10
+ import { createPushApi } from "./push.js";
10
11
  import { installCogoverFetch } from "./fetch.js";
11
12
  import { invocationContext } from "./internal/invocation.js";
12
13
  export function defineScript(handler) {
@@ -43,6 +44,7 @@ export function createSandboxHandler(handler) {
43
44
  response: createResponseApi(),
44
45
  state: createStateApi(),
45
46
  locks: createLocksApi(),
47
+ push: createPushApi(),
46
48
  });
47
49
  if (output === null) {
48
50
  return null;
package/dist/trigger.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { DataApi } from "./data.js";
2
2
  import type { InvocationContext } from "./invocation.js";
3
3
  import type { ScriptLogger } from "./logger.js";
4
+ import type { PushApi } from "./push.js";
4
5
  import type { FilterOperator } from "./query.js";
5
6
  import type { CogoverRecordId, UpdateFields } from "./records.js";
6
7
  import type { SchemaApi } from "./schema.js";
@@ -114,6 +115,8 @@ export interface TriggerContext<TObject extends string = string, TOperation exte
114
115
  readonly data: DataApi<TSchema>;
115
116
  readonly schema: SchemaApi<TSchema>;
116
117
  readonly log: ScriptLogger;
118
+ /** Refused with `TRIGGER_READ_ONLY` in a before-change trigger. */
119
+ readonly push: PushApi<TSchema>;
117
120
  }
118
121
  export type TriggerHandler<TObject extends string = string, TOperation extends TriggerOperation = TriggerOperation, TSchema extends object = EffectiveWorkspaceObjects> = (context: TriggerContext<TObject, TOperation, TSchema>) => void | Promise<void>;
119
122
  /** Declares a record trigger. Add the result to the project's `triggers` export. */
@@ -8,7 +8,7 @@ configured for the project.
8
8
  ## `defineScript`
9
9
 
10
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,
11
+ the input JSON, supplies `input`, `request`, `invocation`, `response`, `data`, `schema`, `log`, `state`, `locks`, and `push`, awaits the handler,
12
12
  and serializes its result.
13
13
 
14
14
  ```typescript
@@ -39,6 +39,7 @@ interface ScriptContext<Input, Schema extends object = EffectiveWorkspaceObjects
39
39
  readonly response: ResponseApi;
40
40
  readonly state: ProjectState;
41
41
  readonly locks: DistributedLocks;
42
+ readonly push: PushApi<Schema>;
42
43
  }
43
44
  ```
44
45
 
@@ -49,7 +50,7 @@ Returning `null` produces a null handler result; returning `undefined` is invali
49
50
  ## HTTP routers and request context
50
51
 
51
52
  `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
+ `log`, `state`, `locks`, and `push` to both script and route handlers. `input` preserves the invocation
53
54
  input. Prefer `request.body` for business data: it excludes invocation metadata and
54
55
  transport/authentication fields removed by Cogover.
55
56
 
@@ -466,6 +467,7 @@ interface TriggerContext<
466
467
  readonly data: DataApi<Schema>;
467
468
  readonly schema: SchemaApi<Schema>;
468
469
  readonly log: ScriptLogger;
470
+ readonly push: PushApi<Schema>;
469
471
  }
470
472
 
471
473
  interface TriggerInfo<Operation extends TriggerOperation = TriggerOperation> {
@@ -501,8 +503,9 @@ receives all records of the same change that run the trigger, up to 200 records
501
503
  once per record. Keep `fields` short, and read related data for the whole list with
502
504
  one `records.getMany` call rather than one read per record.
503
505
 
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
+ `data`, `schema`, `log`, `push`, and `invocation` are the same APIs that scripts receive.
507
+ A trigger context has no `input`, `request`, `response`, `state`, or `locks`; `push` is
508
+ refused in a before-change trigger.
506
509
  `trigger.operation` is the operation of the current call, `trigger.id` identifies the
507
510
  trigger registration, and `trigger.changeId` identifies the record change that caused
508
511
  the call.
@@ -582,7 +585,7 @@ merges, and cascading deletes — do not run before-change triggers, and neither
582
585
  a request that only validates input without saving.
583
586
 
584
587
  - **Read-only.** A before-change trigger may read records and schema, but every
585
- record write, `fetch`, lock, and state write is refused with
588
+ record write, `fetch`, lock, state write, and push message is refused with
586
589
  `PermissionDeniedError` whose `details.reason` is `"TRIGGER_READ_ONLY"`. This
587
590
  applies to every identity, including `data.asSystem()`.
588
591
  - **Identity.** `data.object()` acts as the user who made the change, with that
@@ -649,7 +652,8 @@ export const triggers = [
649
652
  - **May write and call out.** Record writes and `fetch` work as they do in a script,
650
653
  within the same runtime limits. `data.object()` acts as the user who made the
651
654
  change, and the other identity rules of before-change triggers apply. The trigger
652
- context has no `state` or `locks`.
655
+ context has no `state` or `locks`; `push` is available and is the usual way to
656
+ refresh the records the handler changed for everyone who has them open.
653
657
  - **Best-effort delivery.** Cogover does not guarantee that an after-change handler
654
658
  runs exactly once. It may occasionally run more than once for the same change, or
655
659
  not at all. Make every handler idempotent: `trigger.changeId` together with
@@ -1210,6 +1214,115 @@ system supports it, store/check `fencingToken` and reject stale tokens. Locks do
1210
1214
  replace idempotency, provide exactly-once execution, or combine Record API and state
1211
1215
  operations into a transaction.
1212
1216
 
1217
+ ## Push messages
1218
+
1219
+ `push` sends messages to the web clients of the workspace: a request to reload
1220
+ records, a toast, or a background message the client handles silently. It is the
1221
+ same mechanism as the Workflow "Push Message" action, so the standard record pages
1222
+ react without custom client code. Delivery is best-effort: a call resolves once the
1223
+ messages are handed to Cogover, never when a client receives them.
1224
+
1225
+ ```typescript
1226
+ type PushRecipients = "viewers" | readonly string[];
1227
+
1228
+ interface PushOptions {
1229
+ readonly recipients?: PushRecipients;
1230
+ readonly exclude?: readonly string[];
1231
+ }
1232
+
1233
+ type ToastPosition = "TOP_LEFT" | "TOP_CENTER" | "TOP_RIGHT"
1234
+ | "BOTTOM_LEFT" | "BOTTOM_CENTER" | "BOTTOM_RIGHT";
1235
+ type ToastSize = "SMALL" | "MEDIUM" | "LARGE";
1236
+
1237
+ interface ToastLink {
1238
+ readonly label: string;
1239
+ readonly url: string;
1240
+ }
1241
+
1242
+ interface ToastMessage<ObjectSlug extends string = string> {
1243
+ readonly title?: string;
1244
+ readonly content?: string;
1245
+ readonly links?: readonly ToastLink[];
1246
+ readonly position?: ToastPosition;
1247
+ readonly size?: ToastSize;
1248
+ readonly durationSeconds?: number;
1249
+ readonly object?: ObjectSlug;
1250
+ readonly recordIds?: readonly string[];
1251
+ }
1252
+
1253
+ type BackgroundContentType = "text" | "template";
1254
+
1255
+ interface BackgroundMessage<ObjectSlug extends string = string> {
1256
+ readonly content: string;
1257
+ readonly contentType?: BackgroundContentType;
1258
+ readonly object?: ObjectSlug;
1259
+ readonly recordIds?: readonly string[];
1260
+ }
1261
+
1262
+ interface PushApi<Schema extends object = EffectiveWorkspaceObjects> {
1263
+ refreshRecords(object: StringKeyOf<Schema>, recordIds: readonly string[],
1264
+ options?: PushOptions): Promise<void>;
1265
+ toast(message: ToastMessage<StringKeyOf<Schema>>, options?: PushOptions): Promise<void>;
1266
+ message(message: BackgroundMessage<StringKeyOf<Schema>>, options?: PushOptions): Promise<void>;
1267
+ }
1268
+ ```
1269
+
1270
+ ```typescript
1271
+ // After-change trigger: the handler changed the records, so everyone who has them
1272
+ // open must reload, including the user whose save started the trigger.
1273
+ await data.object("order").records.batchUpdate(items);
1274
+ await push.refreshRecords("order", items.map(item => item.id));
1275
+ ```
1276
+
1277
+ ### Recipients
1278
+
1279
+ Every method accepts the same `options`. `recipients` defaults to `"viewers"`:
1280
+ everyone who currently has one of the target records open receives the message, so
1281
+ `object` and `recordIds` are required. A list of personnel IDs delivers to those
1282
+ people wherever they are in the workspace; `object` and `recordIds` are then
1283
+ optional for `toast` and `message` and, when given, tell the client which records
1284
+ the message is about. `exclude` lists personnel IDs that never receive the message;
1285
+ the special value `"actor"` is the user whose action started the current execution
1286
+ (the caller of an HTTP script, the user whose save ran a trigger). A system
1287
+ execution has no actor, so `"actor"` excludes nobody. Personnel without a user
1288
+ account are skipped silently; an unknown personnel ID or object slug throws
1289
+ `NotFoundError` before anything is sent. A call accepts at most 200 record IDs and
1290
+ 200 personnel IDs; duplicates are removed.
1291
+
1292
+ ### `push.refreshRecords(object, recordIds, options?): Promise<void>`
1293
+
1294
+ Asks the clients that show these records to reload them. The record page of the
1295
+ web app handles the request itself. `recordIds` accepts 1 to 200 IDs.
1296
+
1297
+ ### `push.toast(message, options?): Promise<void>`
1298
+
1299
+ Shows a short notification. At least one of `title` (up to 200 characters) and
1300
+ `content` (up to 4,000 characters) is required. `links` holds up to 5 entries whose
1301
+ `url` is an absolute `http` or `https` URL. `position` defaults to `"TOP_RIGHT"`,
1302
+ `size` to `"MEDIUM"` and `durationSeconds` to 5 (1 to 60). When `object` and
1303
+ `recordIds` are given, the client shows the toast only while one of those records
1304
+ is open.
1305
+
1306
+ ### `push.message(message, options?): Promise<void>`
1307
+
1308
+ Sends a message the client handles without a visible notification, for example a
1309
+ custom component listening for it. `content` is required (up to 16,384 characters);
1310
+ `contentType` is `"text"` (default) or `"template"`.
1311
+
1312
+ ### Rules
1313
+
1314
+ - Each call costs one capability call regardless of the number of records or
1315
+ recipients; when the recipients are `"viewers"`, one message is sent per record.
1316
+ - Inputs are validated by the SDK and again by Cogover; invalid input throws
1317
+ `ValidationError` before any message is sent.
1318
+ - `push` is available in scripts, routes, after-change triggers and Development
1319
+ Sessions. A before-change trigger is read-only and receives `PermissionDeniedError`
1320
+ with reason `TRIGGER_READ_ONLY`; a read-only Development Session refuses it too.
1321
+ - When push messages are switched off for the deployment, every call throws
1322
+ `CogoverApiError` with code `PUSH_DISABLED`.
1323
+ - A sent message cannot be recalled, and retrying a failed execution may send it
1324
+ again.
1325
+
1213
1326
  ## Schema API
1214
1327
 
1215
1328
  `SchemaApi<Schema>.object(slug)` reads Object metadata and returns:
@@ -10,7 +10,8 @@ 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:
@@ -209,6 +210,32 @@ longer work, watch `expiresAt` and call `renew()` before expiry. Use the fencing
209
210
  token in downstream systems where possible to reject stale writers. Locks do not
210
211
  replace idempotency or provide exactly-once execution.
211
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
+
212
239
  ## Choose the identity for record operations
213
240
 
214
241
  Keep using `data.object("order")` to inherit the caller's identity. When an
@@ -359,10 +386,10 @@ inside the loop. Collect the IDs, call `records.getMany` once, and look the resu
359
386
  up from a `Map`, as in the example above.
360
387
 
361
388
  **Read-only.** A before-change trigger may read records and schema. Record writes,
362
- `fetch`, locks, and state writes are refused with `PermissionDeniedError`
389
+ `fetch`, locks, state writes, and push messages are refused with `PermissionDeniedError`
363
390
  (`details.reason === "TRIGGER_READ_ONLY"`), for every identity. The trigger context
364
- has `records`, `trigger`, `invocation`, `data`, `schema`, and `log`; it has no
365
- `request`, `response`, `state`, or `locks`.
391
+ has `records`, `trigger`, `invocation`, `data`, `schema`, `log`, and `push`; it has
392
+ no `request`, `response`, `state`, or `locks`.
366
393
 
367
394
  **Identity.** `data.object()` acts as the user who made the change, with that user's
368
395
  permissions, so a read can legitimately return nothing for a record the user cannot
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cogover/sdk",
3
- "version": "0.6.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,