@cogover/sdk 0.11.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +65 -21
  2. package/dist/crypto.js +89 -46
  3. package/dist/data.js +4 -1
  4. package/dist/email.d.ts +77 -0
  5. package/dist/email.js +192 -0
  6. package/dist/index.d.ts +2 -0
  7. package/dist/internal/base64.js +76 -27
  8. package/dist/internal/bridge.js +41 -3
  9. package/dist/internal/job-config.js +7 -1
  10. package/dist/internal/job-runtime.js +4 -0
  11. package/dist/internal/messaging.js +75 -0
  12. package/dist/internal/trigger-runtime.js +5 -0
  13. package/dist/internal/utf8.js +18 -17
  14. package/dist/jobs.d.ts +4 -0
  15. package/dist/locks.js +13 -3
  16. package/dist/logger.js +47 -1
  17. package/dist/notifications.d.ts +56 -0
  18. package/dist/notifications.js +92 -0
  19. package/dist/org.js +14 -14
  20. package/dist/records.d.ts +13 -0
  21. package/dist/response.js +21 -1
  22. package/dist/router.js +2 -0
  23. package/dist/schema.d.ts +1 -0
  24. package/dist/script.d.ts +4 -0
  25. package/dist/script.js +11 -3
  26. package/dist/trigger.d.ts +6 -0
  27. package/docs/en/api-reference/background-jobs.md +288 -0
  28. package/docs/en/api-reference/cryptography.md +317 -0
  29. package/docs/en/api-reference/fetch-and-secrets.md +184 -0
  30. package/docs/en/api-reference/inbound-webhooks.md +65 -0
  31. package/docs/en/api-reference/notifications-and-email.md +317 -0
  32. package/docs/en/api-reference/organization-structure.md +304 -0
  33. package/docs/en/api-reference/overview.md +198 -0
  34. package/docs/en/api-reference/push-messages.md +115 -0
  35. package/docs/en/api-reference/record-triggers.md +469 -0
  36. package/docs/en/api-reference/records.md +447 -0
  37. package/docs/en/api-reference/scripts-and-routes.md +354 -0
  38. package/docs/en/api-reference/state-and-locks.md +162 -0
  39. package/docs/en/usage-guide.md +218 -19
  40. package/package.json +1 -1
  41. package/docs/en/api-reference.md +0 -2619
package/dist/logger.js CHANGED
@@ -1,9 +1,55 @@
1
+ // Longest details text written for one log line; the rest is cut and marked.
2
+ const MAX_DETAILS_CHARS = 8192;
1
3
  function writeLog(level, message, details) {
2
4
  if (details === undefined) {
3
5
  console.log(`[${level}] ${message}`);
4
6
  return;
5
7
  }
6
- console.log(`[${level}] ${message}`, details);
8
+ // One preformatted string: the sandbox console does not format a second argument ("[object Object]").
9
+ console.log(`[${level}] ${message} ${formatDetails(details)}`);
10
+ }
11
+ /** JSON text of a details value that never throws, whatever the value contains. */
12
+ function formatDetails(details) {
13
+ let text;
14
+ try {
15
+ text = JSON.stringify(details, safeReplacer());
16
+ }
17
+ catch {
18
+ // A hostile toJSON() or getter must not turn a log call into a failure.
19
+ text = undefined;
20
+ }
21
+ if (text === undefined)
22
+ text = "[unserializable]";
23
+ return text.length > MAX_DETAILS_CHARS ? `${text.slice(0, MAX_DETAILS_CHARS)}…[truncated]` : text;
24
+ }
25
+ /** Replaces cycles, BigInt, errors, maps and sets, which JSON.stringify would reject or print as {}. */
26
+ function safeReplacer() {
27
+ // Objects on the path from the root to the value being written; a value found on it is a cycle.
28
+ const ancestors = [];
29
+ return function replacer(_key, value) {
30
+ if (ancestors.length > 0) {
31
+ const holder = ancestors.indexOf(this);
32
+ if (holder >= 0)
33
+ ancestors.length = holder + 1;
34
+ else
35
+ ancestors.push(this);
36
+ }
37
+ if (typeof value === "bigint")
38
+ return value.toString();
39
+ if (typeof value !== "object" || value === null)
40
+ return value;
41
+ if (ancestors.includes(value))
42
+ return "[Circular]";
43
+ if (ancestors.length === 0)
44
+ ancestors.push(value);
45
+ if (value instanceof Error)
46
+ return { name: value.name, message: value.message };
47
+ if (value instanceof Map)
48
+ return Object.fromEntries(value);
49
+ if (value instanceof Set)
50
+ return [...value];
51
+ return value;
52
+ };
7
53
  }
8
54
  /** @internal */
9
55
  export const SCRIPT_LOGGER = Object.freeze({
@@ -0,0 +1,56 @@
1
+ /** `"html"` content is reduced to basic formatting (paragraphs, lists, tables, links) before it is stored. */
2
+ export type NotificationContentType = "text" | "html";
3
+ /** `"FULL"` shows the subtitle; `"SIMPLE"` shows only the title and content. */
4
+ export type NotificationDisplay = "SIMPLE" | "FULL";
5
+ /** `"workspace"` sends as the workspace; `"actor"` shows the user whose action started this execution. */
6
+ export type NotificationSender = "workspace" | "actor";
7
+ export type NotificationLinkTarget = "SAME_TAB" | "NEW_TAB";
8
+ /** Page opened when the recipient clicks the notification. */
9
+ export interface NotificationLink {
10
+ /** A path of the Cogover web app starting with `/`, or an absolute `http` or `https` URL. */
11
+ readonly url: string;
12
+ /** Defaults to `"SAME_TAB"` for a path and `"NEW_TAB"` for an absolute URL. */
13
+ readonly openIn?: NotificationLinkTarget;
14
+ }
15
+ /** A notification saved in the recipients' notification list. */
16
+ export interface NotificationMessage {
17
+ /** Personnel IDs, 1 to 200. Personnel without a user account are skipped and reported in the result. */
18
+ readonly to: readonly string[];
19
+ /** Personnel IDs that never receive the notification; `"actor"` is the user who started this execution. */
20
+ readonly exclude?: readonly string[];
21
+ /** At most 200 characters; also the subject of the email copy. */
22
+ readonly title: string;
23
+ /** At most 16,384 characters. */
24
+ readonly content: string;
25
+ /** Defaults to `"text"`. */
26
+ readonly contentType?: NotificationContentType;
27
+ /** At most 200 characters; requires `display: "FULL"`, which is the default when a subtitle is given. */
28
+ readonly subtitle?: string;
29
+ /** Defaults to `"FULL"` with a subtitle and `"SIMPLE"` without one. */
30
+ readonly display?: NotificationDisplay;
31
+ readonly link?: NotificationLink;
32
+ /** Defaults to `"workspace"`. */
33
+ readonly sender?: NotificationSender;
34
+ /**
35
+ * Record ID of a notification channel of the workspace. The channel decides which deliveries (in-app, web push,
36
+ * mobile push, email) are enabled; without one, all of them are.
37
+ */
38
+ readonly channel?: string;
39
+ /** Whether to include an email copy for channels that enable email. Defaults to `true`. */
40
+ readonly email?: boolean;
41
+ /** A retry with the same key returns the first result instead of notifying again. */
42
+ readonly idempotencyKey?: string;
43
+ }
44
+ export interface NotificationResult {
45
+ readonly requestId: string;
46
+ /** Accounts the notification was addressed to after exclusions. */
47
+ readonly notified: number;
48
+ /** Recipients skipped because they have no user account. */
49
+ readonly skippedPersonnelIds: readonly string[];
50
+ /** `true` when an earlier call with the same `idempotencyKey` already sent it. */
51
+ readonly duplicate: boolean;
52
+ }
53
+ /** Sends notifications to people of the workspace. Delivery is asynchronous and best-effort. */
54
+ export interface NotificationsApi {
55
+ send(message: NotificationMessage): Promise<NotificationResult>;
56
+ }
@@ -0,0 +1,92 @@
1
+ import { CogoverApiError, ValidationError } from "./errors.js";
2
+ import { callBridge } from "./internal/bridge.js";
3
+ import { optionalBoolean, optionalChoice, optionalIdempotencyKey, optionalText, personnelIds, requireKnownKeys, requiredText, } from "./internal/messaging.js";
4
+ import { isRecord } from "./internal/values.js";
5
+ const MAX_RECIPIENTS = 200;
6
+ const MAX_TITLE_CHARS = 200;
7
+ const MAX_SUBTITLE_CHARS = 200;
8
+ const MAX_CONTENT_CHARS = 16_384;
9
+ const MAX_LINK_CHARS = 2_048;
10
+ const CHANNEL_ID = /^[A-Za-z0-9_-]{1,64}$/u;
11
+ // The sandbox has no WHATWG `URL` global, so the shape is checked with a pattern; Cogover parses it again.
12
+ const HTTP_URL = /^https?:\/\/[^\s/?#\\@]+(?:[/?#]\S*)?$/iu;
13
+ const APP_PATH = /^\/(?!\/)[^\s\\]*$/u;
14
+ const MESSAGE_KEYS = new Set([
15
+ "to", "exclude", "title", "content", "contentType", "subtitle", "display", "link", "sender", "channel",
16
+ "email", "idempotencyKey",
17
+ ]);
18
+ const LINK_KEYS = new Set(["url", "openIn"]);
19
+ const CONTENT_TYPES = new Set(["text", "html"]);
20
+ const DISPLAYS = new Set(["SIMPLE", "FULL"]);
21
+ const SENDERS = new Set(["workspace", "actor"]);
22
+ const LINK_TARGETS = new Set(["SAME_TAB", "NEW_TAB"]);
23
+ /** @internal */
24
+ export function createNotificationsApi() {
25
+ return Object.freeze({
26
+ async send(message) {
27
+ const result = await callBridge("notifications.send", notificationPayload(message));
28
+ if (!isRecord(result) || typeof result.requestId !== "string" || typeof result.notified !== "number"
29
+ || !Array.isArray(result.skippedPersonnelIds) || typeof result.duplicate !== "boolean") {
30
+ throw new CogoverApiError("INVALID_BRIDGE_RESPONSE", "Notification result is invalid");
31
+ }
32
+ return Object.freeze({
33
+ requestId: result.requestId,
34
+ notified: result.notified,
35
+ skippedPersonnelIds: Object.freeze(result.skippedPersonnelIds.filter((id) => typeof id === "string")),
36
+ duplicate: result.duplicate,
37
+ });
38
+ },
39
+ });
40
+ }
41
+ function notificationPayload(message) {
42
+ const input = requireKnownKeys(message, MESSAGE_KEYS, "notifications.send() message");
43
+ const to = personnelIds(input.to, "to", MAX_RECIPIENTS, false);
44
+ if (to.length === 0)
45
+ throw new ValidationError("to must name at least one personnel ID");
46
+ const payload = {
47
+ to,
48
+ title: requiredText(input.title, "title", MAX_TITLE_CHARS),
49
+ content: requiredText(input.content, "content", MAX_CONTENT_CHARS),
50
+ };
51
+ if (input.exclude !== undefined)
52
+ payload.exclude = personnelIds(input.exclude, "exclude", MAX_RECIPIENTS, true);
53
+ const contentType = optionalChoice(input.contentType, "contentType", CONTENT_TYPES);
54
+ if (contentType !== undefined)
55
+ payload.contentType = contentType;
56
+ const subtitle = optionalText(input.subtitle, "subtitle", MAX_SUBTITLE_CHARS);
57
+ const display = optionalChoice(input.display, "display", DISPLAYS);
58
+ if (subtitle !== undefined) {
59
+ if (display === "SIMPLE")
60
+ throw new ValidationError("subtitle requires display \"FULL\"");
61
+ payload.subtitle = subtitle;
62
+ }
63
+ if (display !== undefined)
64
+ payload.display = display;
65
+ if (input.link !== undefined)
66
+ payload.link = notificationLink(input.link);
67
+ const sender = optionalChoice(input.sender, "sender", SENDERS);
68
+ if (sender !== undefined)
69
+ payload.sender = sender;
70
+ if (input.channel !== undefined) {
71
+ if (typeof input.channel !== "string" || !CHANNEL_ID.test(input.channel)) {
72
+ throw new ValidationError("channel must be a notification channel record ID");
73
+ }
74
+ payload.channel = input.channel;
75
+ }
76
+ const email = optionalBoolean(input.email, "email");
77
+ if (email !== undefined)
78
+ payload.email = email;
79
+ const idempotencyKey = optionalIdempotencyKey(input.idempotencyKey, "notifications.send()");
80
+ if (idempotencyKey !== undefined)
81
+ payload.idempotencyKey = idempotencyKey;
82
+ return payload;
83
+ }
84
+ function notificationLink(value) {
85
+ const link = requireKnownKeys(value, LINK_KEYS, "link");
86
+ const url = requiredText(link.url, "link.url", MAX_LINK_CHARS);
87
+ if (!APP_PATH.test(url) && !HTTP_URL.test(url)) {
88
+ throw new ValidationError("link.url must be a path starting with / or an absolute http or https URL");
89
+ }
90
+ const openIn = optionalChoice(link.openIn, "link.openIn", LINK_TARGETS);
91
+ return openIn === undefined ? { url } : { url, openIn };
92
+ }
package/dist/org.js CHANGED
@@ -81,12 +81,12 @@ export function createOrgApi(invocation) {
81
81
  includeSubDepartments: "boolean", accountOnly: "boolean", limit: "limit", cursor: "cursor",
82
82
  };
83
83
  const personnel = {
84
- get(id, options) {
84
+ async get(id, options) {
85
85
  return nullableObject("org.personnel.get", {
86
86
  ...payloadFor("personnel.get()", options, {}, true), id: requireId(id, "personnel id"),
87
87
  });
88
88
  },
89
- getMany(ids, options) {
89
+ async getMany(ids, options) {
90
90
  if (!Array.isArray(ids))
91
91
  throw new ValidationError("personnel.getMany() requires an array of ids");
92
92
  const unique = [...new Set(ids.map(id => requireId(id, "personnel id")))];
@@ -97,7 +97,7 @@ export function createOrgApi(invocation) {
97
97
  ...payloadFor("personnel.getMany()", options, {}, true), ids: unique,
98
98
  });
99
99
  },
100
- managerChain(id, options) {
100
+ async managerChain(id, options) {
101
101
  return list("org.personnel.managerChain", {
102
102
  ...payloadFor("personnel.managerChain()", options, { departmentId: "id", accountOnly: "boolean" }, true),
103
103
  id: requireId(id, "personnel id"),
@@ -105,32 +105,32 @@ export function createOrgApi(invocation) {
105
105
  },
106
106
  };
107
107
  const departments = {
108
- get(id, options) {
108
+ async get(id, options) {
109
109
  return nullableObject("org.departments.get", {
110
110
  ...payloadFor("departments.get()", options, {}, true), id: requireId(id, "department id"),
111
111
  });
112
112
  },
113
- tree(options) {
113
+ async tree(options) {
114
114
  return list("org.departments.tree", payloadFor("departments.tree()", options, { rootId: "id", depth: "depth" }, true));
115
115
  },
116
- ancestors(id, options) {
116
+ async ancestors(id, options) {
117
117
  return list("org.departments.ancestors", {
118
118
  ...payloadFor("departments.ancestors()", options, {}, true), id: requireId(id, "department id"),
119
119
  });
120
120
  },
121
- members(id, options) {
121
+ async members(id, options) {
122
122
  return object("org.departments.members", {
123
123
  ...payloadFor("departments.members()", options, { ...pageOptions, positionId: "id" }, true),
124
124
  id: requireId(id, "department id"),
125
125
  });
126
126
  },
127
- managers(id, options) {
127
+ async managers(id, options) {
128
128
  return list("org.departments.managers", {
129
129
  ...payloadFor("departments.managers()", options, { accountOnly: "boolean" }, true),
130
130
  id: requireId(id, "department id"),
131
131
  });
132
132
  },
133
- managerChain(id, options) {
133
+ async managerChain(id, options) {
134
134
  return object("org.departments.managerChain", {
135
135
  ...payloadFor("departments.managerChain()", options, { accountOnly: "boolean" }, true),
136
136
  id: requireId(id, "department id"),
@@ -138,15 +138,15 @@ export function createOrgApi(invocation) {
138
138
  },
139
139
  };
140
140
  const positions = {
141
- list(options) {
141
+ async list(options) {
142
142
  return list("org.positions.list", payloadFor("positions.list()", options, {}, true));
143
143
  },
144
- get(id, options) {
144
+ async get(id, options) {
145
145
  return nullableObject("org.positions.get", {
146
146
  ...payloadFor("positions.get()", options, {}, true), id: requireId(id, "position id"),
147
147
  });
148
148
  },
149
- members(id, options) {
149
+ async members(id, options) {
150
150
  return object("org.positions.members", {
151
151
  ...payloadFor("positions.members()", options, { ...pageOptions, departmentId: "id" }, true),
152
152
  id: requireId(id, "position id"),
@@ -166,14 +166,14 @@ export function createOrgApi(invocation) {
166
166
  return null;
167
167
  return personnel.get(personnelId, options);
168
168
  },
169
- isInDepartment(personnelId, departmentId, options) {
169
+ async isInDepartment(personnelId, departmentId, options) {
170
170
  return flag("org.isInDepartment", {
171
171
  ...payloadFor("isInDepartment()", options, { includeSubDepartments: "boolean" }, false),
172
172
  personnelId: requireId(personnelId, "personnel id"),
173
173
  departmentId: requireId(departmentId, "department id"),
174
174
  });
175
175
  },
176
- isManagerOf(managerId, personnelId, options) {
176
+ async isManagerOf(managerId, personnelId, options) {
177
177
  return flag("org.isManagerOf", {
178
178
  ...payloadFor("isManagerOf()", options, { departmentId: "id", directOnly: "boolean" }, false),
179
179
  managerId: requireId(managerId, "manager id"),
package/dist/records.d.ts CHANGED
@@ -42,6 +42,15 @@ export interface GetManyResult<TFields> {
42
42
  export interface DeleteResult {
43
43
  readonly deleted: CogoverRecordId[];
44
44
  readonly notDeleted: CogoverRecordId[];
45
+ /**
46
+ * Present only when a before-change record trigger kept some of the records from being deleted: record ID to
47
+ * the trigger's error codes by field slug (`$record` for the whole record) and its texts.
48
+ */
49
+ readonly recordErrors?: Readonly<Record<CogoverRecordId, {
50
+ readonly reason: "TRIGGER_REJECTED";
51
+ readonly fieldErrors?: Readonly<Record<string, string>>;
52
+ readonly messages?: readonly string[];
53
+ }>>;
45
54
  }
46
55
  export interface BatchWriteRowResult {
47
56
  readonly referenceId: string;
@@ -49,6 +58,10 @@ export interface BatchWriteRowResult {
49
58
  readonly r: number;
50
59
  readonly msg?: string;
51
60
  readonly success: boolean;
61
+ /** Row a before-change record trigger rejected (`r` 70): error code by field slug, `$record` for the whole record. */
62
+ readonly fieldErrors?: Readonly<Record<string, string>>;
63
+ /** Row a before-change record trigger rejected (`r` 70): the texts the trigger attached to its error codes. */
64
+ readonly messages?: readonly string[];
52
65
  }
53
66
  /** Batch writes are best-effort per row; inspect `success` or every row result. */
54
67
  export interface BatchWriteResponse {
package/dist/response.js CHANGED
@@ -1,11 +1,14 @@
1
1
  import { ValidationError } from "./errors.js";
2
2
  import { encodeBase64 } from "./internal/base64.js";
3
3
  const RESPONSE_KEY = "__cogoverHttpResponse";
4
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
4
5
  const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}$/;
5
6
  const DENIED_HEADERS = new Set([
6
7
  "connection", "content-length", "transfer-encoding", "keep-alive", "upgrade", "trailer",
7
8
  "set-cookie", "server", "date", "proxy-authenticate",
8
9
  ]);
10
+ // Only objects made by these helpers are responses. A returned value that merely has the same JSON shape is data.
11
+ const envelopes = new WeakMap();
9
12
  /** @internal */
10
13
  export function createResponseApi() {
11
14
  return Object.freeze({
@@ -40,6 +43,9 @@ export function createResponseApi() {
40
43
  || /[\r\n]/.test(location)) {
41
44
  throw new ValidationError("response.redirect() location is invalid");
42
45
  }
46
+ if (!REDIRECT_STATUSES.has(status)) {
47
+ throw new ValidationError("response.redirect() status must be 301, 302, 303, 307 or 308");
48
+ }
43
49
  return response("empty", null, { status, headers: { location } });
44
50
  },
45
51
  });
@@ -54,9 +60,23 @@ function response(bodyType, body, init, defaultContentType) {
54
60
  bodyType,
55
61
  body,
56
62
  });
57
- return Object.freeze({
63
+ const scriptResponse = Object.freeze({
58
64
  toJSON: () => Object.freeze({ [RESPONSE_KEY]: envelope }),
59
65
  });
66
+ envelopes.set(scriptResponse, envelope);
67
+ return scriptResponse;
68
+ }
69
+ /**
70
+ * @internal JSON text of a handler result. Cogover passes each invocation a token that only a response made by
71
+ * these helpers carries, so a returned value can never choose the status, headers or body type by imitating the
72
+ * envelope. Without a token (outside Cogover) a response serializes to the bare envelope.
73
+ */
74
+ export function serializeHandlerOutput(output, responseToken) {
75
+ const envelope = typeof output === "object" && output !== null ? envelopes.get(output) : undefined;
76
+ if (envelope !== undefined && typeof responseToken === "string" && responseToken.length > 0) {
77
+ return JSON.stringify({ [RESPONSE_KEY]: { ...envelope, token: responseToken } });
78
+ }
79
+ return JSON.stringify(output);
60
80
  }
61
81
  function validateStatus(status) {
62
82
  if (!Number.isInteger(status) || status < 200 || status > 599) {
package/dist/router.js CHANGED
@@ -60,6 +60,8 @@ export function createRouter() {
60
60
  state: context.state,
61
61
  locks: context.locks,
62
62
  push: context.push,
63
+ notifications: context.notifications,
64
+ email: context.email,
63
65
  jobs: context.jobs,
64
66
  secrets: context.secrets,
65
67
  crypto: context.crypto,
package/dist/schema.d.ts CHANGED
@@ -12,6 +12,7 @@ export interface ObjectMetadata {
12
12
  readonly multiple: boolean;
13
13
  readonly readOnly: boolean;
14
14
  readonly manualModifyAllow?: boolean;
15
+ readonly creatable?: boolean;
15
16
  readonly metaData?: Readonly<Record<string, unknown>>;
16
17
  readonly options?: readonly {
17
18
  readonly id: string;
package/dist/script.d.ts CHANGED
@@ -7,6 +7,8 @@ import type { EffectiveWorkspaceObjects } from "./workspace.js";
7
7
  import type { ProjectState } from "./state.js";
8
8
  import type { DistributedLocks } from "./locks.js";
9
9
  import type { PushApi } from "./push.js";
10
+ import type { NotificationsApi } from "./notifications.js";
11
+ import type { EmailApi } from "./email.js";
10
12
  import type { InvocationContext } from "./invocation.js";
11
13
  import type { JobsApi } from "./jobs.js";
12
14
  import type { SecretsApi } from "./secrets.js";
@@ -23,6 +25,8 @@ export interface ScriptContext<TInput, TSchema extends object = EffectiveWorkspa
23
25
  readonly state: ProjectState;
24
26
  readonly locks: DistributedLocks;
25
27
  readonly push: PushApi<TSchema>;
28
+ readonly notifications: NotificationsApi;
29
+ readonly email: EmailApi<TSchema>;
26
30
  readonly jobs: JobsApi;
27
31
  readonly secrets: SecretsApi;
28
32
  readonly crypto: CryptoApi;
package/dist/script.js CHANGED
@@ -1,19 +1,22 @@
1
1
  import { createDataApi } from "./data.js";
2
2
  import { NotFoundError, ValidationError } from "./errors.js";
3
3
  import { scriptRequest } from "./internal/request.js";
4
- import { createResponseApi } from "./response.js";
4
+ import { createResponseApi, serializeHandlerOutput } from "./response.js";
5
5
  import { errorMessage } from "./internal/values.js";
6
6
  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
10
  import { createPushApi } from "./push.js";
11
+ import { createNotificationsApi } from "./notifications.js";
12
+ import { createEmailApi } from "./email.js";
11
13
  import { installCogoverFetch } from "./fetch.js";
12
14
  import { invocationContext } from "./internal/invocation.js";
13
15
  import { createJobsApi } from "./internal/jobs-api.js";
14
16
  import { createSecretsApi } from "./secrets.js";
15
17
  import { crypto } from "./crypto.js";
16
18
  import { createOrgApi } from "./org.js";
19
+ const RESPONSE_TOKEN_VERSION_MEMBER = "__cogoverResponseTokenVersion";
17
20
  export function defineScript(handler) {
18
21
  if (typeof handler !== "function") {
19
22
  throw new ValidationError("defineScript() requires a handler function");
@@ -26,7 +29,7 @@ export function defineScript(handler) {
26
29
  }
27
30
  /** @internal */
28
31
  export function createSandboxHandler(handler) {
29
- return async (inputJson) => {
32
+ const sandboxHandler = async (inputJson, responseToken) => {
30
33
  installCogoverFetch();
31
34
  let input;
32
35
  try {
@@ -49,6 +52,8 @@ export function createSandboxHandler(handler) {
49
52
  state: createStateApi(),
50
53
  locks: createLocksApi(),
51
54
  push: createPushApi(),
55
+ notifications: createNotificationsApi(),
56
+ email: createEmailApi(),
52
57
  jobs: createJobsApi(),
53
58
  secrets: createSecretsApi(),
54
59
  crypto,
@@ -57,10 +62,13 @@ export function createSandboxHandler(handler) {
57
62
  if (output === null) {
58
63
  return null;
59
64
  }
60
- const outputJson = JSON.stringify(output);
65
+ const outputJson = serializeHandlerOutput(output, responseToken);
61
66
  if (outputJson === undefined) {
62
67
  throw new ValidationError("Script output must be JSON serializable");
63
68
  }
64
69
  return outputJson;
65
70
  };
71
+ // Tells Cogover that this handler accepts a per-invocation response token as its second argument.
72
+ Object.defineProperty(sandboxHandler, RESPONSE_TOKEN_VERSION_MEMBER, { value: 1 });
73
+ return sandboxHandler;
66
74
  }
package/dist/trigger.d.ts CHANGED
@@ -6,6 +6,8 @@ import type { SecretsApi } from "./secrets.js";
6
6
  import type { InvocationContext } from "./invocation.js";
7
7
  import type { ScriptLogger } from "./logger.js";
8
8
  import type { PushApi } from "./push.js";
9
+ import type { NotificationsApi } from "./notifications.js";
10
+ import type { EmailApi } from "./email.js";
9
11
  import type { FilterOperator } from "./query.js";
10
12
  import type { CogoverRecordId, UpdateFields } from "./records.js";
11
13
  import type { SchemaApi } from "./schema.js";
@@ -121,6 +123,10 @@ export interface TriggerContext<TObject extends string = string, TOperation exte
121
123
  readonly log: ScriptLogger;
122
124
  /** Refused with `TRIGGER_READ_ONLY` in a before-change trigger. */
123
125
  readonly push: PushApi<TSchema>;
126
+ /** Refused with `TRIGGER_READ_ONLY` in a before-change trigger. */
127
+ readonly notifications: NotificationsApi;
128
+ /** Refused with `TRIGGER_READ_ONLY` in a before-change trigger. */
129
+ readonly email: EmailApi<TSchema>;
124
130
  /** Available in after-change triggers; a before-change trigger is refused with `PermissionDeniedError`. */
125
131
  readonly jobs: JobsApi;
126
132
  /** Available in after-change triggers; a before-change trigger is refused with `PermissionDeniedError`. */