@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.
- package/README.md +127 -5
- package/dist/data.d.ts +6 -1
- package/dist/data.js +28 -1
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +10 -0
- package/dist/index.d.ts +6 -3
- package/dist/index.js +2 -1
- package/dist/internal/json.js +81 -0
- package/dist/internal/trigger-config.js +212 -0
- package/dist/internal/trigger-runtime.js +213 -0
- package/dist/push.d.ts +48 -0
- package/dist/push.js +190 -0
- package/dist/records.d.ts +5 -0
- package/dist/router.js +1 -0
- package/dist/script.d.ts +2 -0
- package/dist/script.js +2 -0
- package/dist/trigger.d.ts +124 -0
- package/dist/trigger.js +15 -0
- package/docs/en/api-reference.md +584 -4
- package/docs/en/usage-guide.md +242 -4
- package/package.json +1 -1
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { createDataApi } from "../data.js";
|
|
2
|
+
import { ValidationError } from "../errors.js";
|
|
3
|
+
import { installCogoverFetch } from "../fetch.js";
|
|
4
|
+
import { SCRIPT_LOGGER } from "../logger.js";
|
|
5
|
+
import { createPushApi } from "../push.js";
|
|
6
|
+
import { createSchemaApi } from "../schema.js";
|
|
7
|
+
import { invocationContext } from "./invocation.js";
|
|
8
|
+
import { cloneJson, deepFreeze, jsonEquals, toJsonValue } from "./json.js";
|
|
9
|
+
import { TRIGGER_SLUG } from "./trigger-config.js";
|
|
10
|
+
import { errorMessage, isRecord } from "./values.js";
|
|
11
|
+
const ERROR_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
12
|
+
const MAX_ERROR_MESSAGE_LENGTH = 500;
|
|
13
|
+
// Both spellings of a timing and an operation are accepted; project code only ever sees the SDK literals.
|
|
14
|
+
const TIMINGS = new Map([
|
|
15
|
+
["beforeChange", "beforeChange"],
|
|
16
|
+
["BEFORE_CHANGE", "beforeChange"],
|
|
17
|
+
["afterChange", "afterChange"],
|
|
18
|
+
["AFTER_CHANGE", "afterChange"],
|
|
19
|
+
]);
|
|
20
|
+
const OPERATIONS = new Map([
|
|
21
|
+
["create", "create"],
|
|
22
|
+
["CREATE", "create"],
|
|
23
|
+
["update", "update"],
|
|
24
|
+
["UPDATE", "update"],
|
|
25
|
+
["delete", "delete"],
|
|
26
|
+
["DELETE", "delete"],
|
|
27
|
+
]);
|
|
28
|
+
export function createTriggerSandboxHandler(manifest, handler) {
|
|
29
|
+
const writableFields = new Set(manifest.writableFields);
|
|
30
|
+
return async (inputJson) => {
|
|
31
|
+
installCogoverFetch();
|
|
32
|
+
let input;
|
|
33
|
+
try {
|
|
34
|
+
input = JSON.parse(inputJson);
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
throw new ValidationError("Trigger input must be valid JSON", errorMessage(error));
|
|
38
|
+
}
|
|
39
|
+
if (!isRecord(input))
|
|
40
|
+
throw new ValidationError("Trigger input must be a JSON object");
|
|
41
|
+
const trigger = triggerInfo(input, manifest);
|
|
42
|
+
const entries = recordEntries(input.records, trigger.operation);
|
|
43
|
+
let invocation;
|
|
44
|
+
await handler(Object.freeze({
|
|
45
|
+
records: Object.freeze(entries.map(entry => entry.record)),
|
|
46
|
+
trigger,
|
|
47
|
+
get invocation() {
|
|
48
|
+
return invocation ??= invocationContext(input);
|
|
49
|
+
},
|
|
50
|
+
data: createDataApi(),
|
|
51
|
+
schema: createSchemaApi(),
|
|
52
|
+
log: SCRIPT_LOGGER,
|
|
53
|
+
push: createPushApi(),
|
|
54
|
+
}));
|
|
55
|
+
const results = [];
|
|
56
|
+
for (const entry of entries) {
|
|
57
|
+
// Always diff: changing a field outside writableFields is a bug even on a rejected record.
|
|
58
|
+
const changes = recordChanges(entry, manifest.key, writableFields);
|
|
59
|
+
if (entry.errors.length > 0) {
|
|
60
|
+
results.push({ key: entry.key, errors: entry.errors });
|
|
61
|
+
}
|
|
62
|
+
else if (changes !== null) {
|
|
63
|
+
results.push({ key: entry.key, changes });
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return JSON.stringify({ results });
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function triggerInfo(input, manifest) {
|
|
70
|
+
const context = isRecord(input.__context) ? input.__context : undefined;
|
|
71
|
+
const raw = context !== undefined && isRecord(context.trigger) ? context.trigger : undefined;
|
|
72
|
+
if (raw === undefined) {
|
|
73
|
+
throw new ValidationError("Trigger metadata is unavailable outside Cogover Runtime");
|
|
74
|
+
}
|
|
75
|
+
const timing = TIMINGS.get(raw.timing);
|
|
76
|
+
const operation = OPERATIONS.get(raw.operation);
|
|
77
|
+
if (timing === undefined)
|
|
78
|
+
throw new ValidationError("Invalid trigger timing metadata");
|
|
79
|
+
if (operation === undefined)
|
|
80
|
+
throw new ValidationError("Invalid trigger operation metadata");
|
|
81
|
+
const info = Object.freeze({
|
|
82
|
+
id: requiredString(raw.id, "id"),
|
|
83
|
+
key: requiredString(raw.key, "key"),
|
|
84
|
+
timing,
|
|
85
|
+
operation,
|
|
86
|
+
objectSlug: requiredString(raw.objectSlug, "objectSlug"),
|
|
87
|
+
changeId: requiredString(raw.changeId, "changeId"),
|
|
88
|
+
});
|
|
89
|
+
// A mismatch means the call was routed to a definition it was not registered for.
|
|
90
|
+
if (info.key !== manifest.key || info.timing !== manifest.timing
|
|
91
|
+
|| info.objectSlug !== manifest.object || !manifest.operations.includes(info.operation)) {
|
|
92
|
+
throw new ValidationError(`Trigger input for '${info.key}' (${info.timing} ${info.operation} on '${info.objectSlug}') `
|
|
93
|
+
+ `does not match the definition of '${manifest.key}' `
|
|
94
|
+
+ `(${manifest.timing} ${manifest.operations.join("/")} on '${manifest.object}')`);
|
|
95
|
+
}
|
|
96
|
+
return info;
|
|
97
|
+
}
|
|
98
|
+
function requiredString(value, name) {
|
|
99
|
+
if (typeof value !== "string" || value === "") {
|
|
100
|
+
throw new ValidationError(`Invalid trigger ${name} metadata`);
|
|
101
|
+
}
|
|
102
|
+
return value;
|
|
103
|
+
}
|
|
104
|
+
function recordEntries(records, operation) {
|
|
105
|
+
if (!Array.isArray(records))
|
|
106
|
+
throw new ValidationError("Trigger input records must be an array");
|
|
107
|
+
const keys = new Set();
|
|
108
|
+
return records.map((raw, index) => {
|
|
109
|
+
const invalid = (reason) => new ValidationError(`Trigger input record at index ${index} is invalid: ${reason}`);
|
|
110
|
+
if (!isRecord(raw))
|
|
111
|
+
throw invalid("it must be an object");
|
|
112
|
+
const key = raw.key;
|
|
113
|
+
if (typeof key !== "string" || key === "")
|
|
114
|
+
throw invalid("key must be a non-empty string");
|
|
115
|
+
if (keys.has(key))
|
|
116
|
+
throw invalid(`duplicate key '${key}'`);
|
|
117
|
+
keys.add(key);
|
|
118
|
+
if (raw.id !== undefined && raw.id !== null && typeof raw.id !== "string") {
|
|
119
|
+
throw invalid("id must be a string or null");
|
|
120
|
+
}
|
|
121
|
+
// An omitted value means null: JSON writers commonly drop null properties.
|
|
122
|
+
const current = fieldValues(raw.new, "new", invalid);
|
|
123
|
+
const old = fieldValues(raw.old, "old", invalid);
|
|
124
|
+
if ((operation === "delete") !== (current === null)) {
|
|
125
|
+
throw invalid(operation === "delete"
|
|
126
|
+
? "new must be null when the operation is delete"
|
|
127
|
+
: `new is required when the operation is ${operation}`);
|
|
128
|
+
}
|
|
129
|
+
if ((operation === "create") !== (old === null)) {
|
|
130
|
+
throw invalid(operation === "create"
|
|
131
|
+
? "old must be null when the operation is create"
|
|
132
|
+
: `old is required when the operation is ${operation}`);
|
|
133
|
+
}
|
|
134
|
+
const changedFields = raw.changedFields ?? [];
|
|
135
|
+
if (!Array.isArray(changedFields) || changedFields.some(field => typeof field !== "string")) {
|
|
136
|
+
throw invalid("changedFields must be an array of field slugs");
|
|
137
|
+
}
|
|
138
|
+
const errors = [];
|
|
139
|
+
const record = {
|
|
140
|
+
key,
|
|
141
|
+
id: typeof raw.id === "string" ? raw.id : null,
|
|
142
|
+
get new() {
|
|
143
|
+
return current;
|
|
144
|
+
},
|
|
145
|
+
set new(_value) {
|
|
146
|
+
throw new ValidationError(current === null
|
|
147
|
+
? "A record that is being deleted has no new values and cannot be modified"
|
|
148
|
+
: "record.new cannot be replaced; assign its fields instead, for example record.new.status = \"approved\"");
|
|
149
|
+
},
|
|
150
|
+
old: deepFreeze(old),
|
|
151
|
+
changedFields: deepFreeze([...changedFields]),
|
|
152
|
+
addError(field, code, message) {
|
|
153
|
+
errors.push(recordError(field, code, message));
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
return {
|
|
157
|
+
key,
|
|
158
|
+
record: Object.freeze(record),
|
|
159
|
+
current,
|
|
160
|
+
snapshot: current === null ? null : cloneJson(current),
|
|
161
|
+
errors,
|
|
162
|
+
};
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
function fieldValues(value, name, invalid) {
|
|
166
|
+
if (value === undefined || value === null)
|
|
167
|
+
return null;
|
|
168
|
+
if (!isRecord(value))
|
|
169
|
+
throw invalid(`${name} must be an object or null`);
|
|
170
|
+
return value;
|
|
171
|
+
}
|
|
172
|
+
function recordError(field, code, message) {
|
|
173
|
+
if (field !== null && (typeof field !== "string" || !TRIGGER_SLUG.test(field))) {
|
|
174
|
+
throw new ValidationError("addError() field must be a valid field slug, or null for a record-level error");
|
|
175
|
+
}
|
|
176
|
+
if (typeof code !== "string" || !ERROR_CODE.test(code)) {
|
|
177
|
+
throw new ValidationError("addError() code must start with an upper-case letter and contain "
|
|
178
|
+
+ "at most 64 upper-case letters, digits or underscores, for example AMOUNT_TOO_LARGE");
|
|
179
|
+
}
|
|
180
|
+
if (message === undefined || message === null || message === "")
|
|
181
|
+
return { field, code };
|
|
182
|
+
if (typeof message !== "string" || message.length > MAX_ERROR_MESSAGE_LENGTH) {
|
|
183
|
+
throw new ValidationError(`addError() message must be a string of at most ${MAX_ERROR_MESSAGE_LENGTH} characters`);
|
|
184
|
+
}
|
|
185
|
+
return { field, code, message };
|
|
186
|
+
}
|
|
187
|
+
/** Top-level diff of record.new against its snapshot, or null when the handler changed nothing. */
|
|
188
|
+
function recordChanges(entry, triggerKey, writableFields) {
|
|
189
|
+
const { current, snapshot } = entry;
|
|
190
|
+
if (current === null || snapshot === null)
|
|
191
|
+
return null;
|
|
192
|
+
// A null prototype keeps every field slug, including "__proto__", an ordinary own property.
|
|
193
|
+
const changes = Object.create(null);
|
|
194
|
+
let changed = false;
|
|
195
|
+
for (const field of new Set([...Object.keys(snapshot), ...Object.keys(current)])) {
|
|
196
|
+
const existed = Object.prototype.hasOwnProperty.call(snapshot, field);
|
|
197
|
+
const assigned = Object.prototype.hasOwnProperty.call(current, field) ? current[field] : undefined;
|
|
198
|
+
if (assigned === undefined && !existed)
|
|
199
|
+
continue;
|
|
200
|
+
// Deleting a field or assigning undefined clears it.
|
|
201
|
+
const after = assigned === undefined
|
|
202
|
+
? null
|
|
203
|
+
: toJsonValue(assigned, `Trigger '${triggerKey}': the value assigned to field '${field}'`);
|
|
204
|
+
if (existed && jsonEquals(snapshot[field], after))
|
|
205
|
+
continue;
|
|
206
|
+
if (!writableFields.has(field)) {
|
|
207
|
+
throw new ValidationError(`Trigger '${triggerKey}' changed field '${field}', which is not listed in writableFields`, { triggerKey, field, recordKey: entry.key });
|
|
208
|
+
}
|
|
209
|
+
changes[field] = after;
|
|
210
|
+
changed = true;
|
|
211
|
+
}
|
|
212
|
+
return changed ? changes : null;
|
|
213
|
+
}
|
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/records.d.ts
CHANGED
|
@@ -34,6 +34,11 @@ export interface RecordPage<TFields> {
|
|
|
34
34
|
readonly total: number;
|
|
35
35
|
readonly nextCursor?: string;
|
|
36
36
|
}
|
|
37
|
+
/** Result of `records.getMany`: the readable records plus every requested ID that could not be read. */
|
|
38
|
+
export interface GetManyResult<TFields> {
|
|
39
|
+
readonly records: CogoverRecord<TFields>[];
|
|
40
|
+
readonly missingIds: CogoverRecordId[];
|
|
41
|
+
}
|
|
37
42
|
export interface DeleteResult {
|
|
38
43
|
readonly deleted: CogoverRecordId[];
|
|
39
44
|
readonly notDeleted: CogoverRecordId[];
|
package/dist/router.js
CHANGED
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;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import type { DataApi } from "./data.js";
|
|
2
|
+
import type { InvocationContext } from "./invocation.js";
|
|
3
|
+
import type { ScriptLogger } from "./logger.js";
|
|
4
|
+
import type { PushApi } from "./push.js";
|
|
5
|
+
import type { FilterOperator } from "./query.js";
|
|
6
|
+
import type { CogoverRecordId, UpdateFields } from "./records.js";
|
|
7
|
+
import type { SchemaApi } from "./schema.js";
|
|
8
|
+
import type { EffectiveWorkspaceObjects, FieldsFor, StringKeyOf } from "./workspace.js";
|
|
9
|
+
/** When a record trigger runs relative to the record change. */
|
|
10
|
+
export type TriggerTiming = "beforeChange" | "afterChange";
|
|
11
|
+
/** Record operations a trigger can subscribe to. */
|
|
12
|
+
export type TriggerOperation = "create" | "update" | "delete";
|
|
13
|
+
/** `"onEnter"` runs only when a record starts matching `when`; `"always"` runs whenever it matches. */
|
|
14
|
+
export type TriggerRunWhen = "always" | "onEnter";
|
|
15
|
+
/** One field comparison of a trigger `when` filter. */
|
|
16
|
+
export interface TriggerFilterCondition {
|
|
17
|
+
readonly op: FilterOperator;
|
|
18
|
+
readonly field: string;
|
|
19
|
+
/** Comparison value; omitted for `"is null"` and `"not null"`. */
|
|
20
|
+
readonly params?: unknown;
|
|
21
|
+
}
|
|
22
|
+
/** Combines trigger `when` filters with `and` or `or`. */
|
|
23
|
+
export interface TriggerFilterGroup {
|
|
24
|
+
readonly op: "and" | "or";
|
|
25
|
+
readonly conditions: readonly TriggerFilter[];
|
|
26
|
+
}
|
|
27
|
+
export type TriggerFilter = TriggerFilterCondition | TriggerFilterGroup;
|
|
28
|
+
type TriggerObjectFields<TObject extends string, TSchema extends object> = TObject extends keyof TSchema ? FieldsFor<TSchema, TObject> : Record<string, unknown>;
|
|
29
|
+
type TriggerFieldSlug<TObject extends string, TSchema extends object> = StringKeyOf<TriggerObjectFields<TObject, TSchema>>;
|
|
30
|
+
/** Options accepted by `defineTrigger`. */
|
|
31
|
+
export interface TriggerConfig<TObject extends string = string, TOperation extends TriggerOperation = TriggerOperation, TSchema extends object = EffectiveWorkspaceObjects> {
|
|
32
|
+
/** Stable identifier of the trigger inside the project. */
|
|
33
|
+
readonly key: string;
|
|
34
|
+
/** Display name; defaults to `key`. */
|
|
35
|
+
readonly name?: string;
|
|
36
|
+
/** Slug of the Object whose records run this trigger. */
|
|
37
|
+
readonly object: TObject;
|
|
38
|
+
readonly timing: TriggerTiming;
|
|
39
|
+
readonly operations: readonly TOperation[];
|
|
40
|
+
/** Fields delivered in `record.new` and `record.old`. */
|
|
41
|
+
readonly fields: readonly TriggerFieldSlug<TObject, TSchema>[];
|
|
42
|
+
/** Updates run the trigger only when at least one of these fields changed. */
|
|
43
|
+
readonly changedFields?: readonly TriggerFieldSlug<TObject, TSchema>[];
|
|
44
|
+
/** Only records matching this filter run the trigger. */
|
|
45
|
+
readonly when?: TriggerFilter;
|
|
46
|
+
readonly runWhen?: TriggerRunWhen;
|
|
47
|
+
/** Fields the handler may change through `record.new`. */
|
|
48
|
+
readonly writableFields?: readonly TriggerFieldSlug<TObject, TSchema>[];
|
|
49
|
+
/** Position among the triggers of the same Object; lower values run first. */
|
|
50
|
+
readonly order?: number;
|
|
51
|
+
/** Time budget of one handler call, in milliseconds. */
|
|
52
|
+
readonly timeoutMs?: number;
|
|
53
|
+
}
|
|
54
|
+
/** Normalized, immutable trigger configuration with every default applied. */
|
|
55
|
+
export interface TriggerManifest {
|
|
56
|
+
readonly key: string;
|
|
57
|
+
readonly name?: string;
|
|
58
|
+
readonly object: string;
|
|
59
|
+
readonly timing: TriggerTiming;
|
|
60
|
+
readonly operations: readonly TriggerOperation[];
|
|
61
|
+
readonly fields: readonly string[];
|
|
62
|
+
readonly changedFields?: readonly string[];
|
|
63
|
+
readonly when?: TriggerFilter;
|
|
64
|
+
readonly runWhen: TriggerRunWhen;
|
|
65
|
+
readonly writableFields: readonly string[];
|
|
66
|
+
readonly order: number;
|
|
67
|
+
readonly timeoutMs: number;
|
|
68
|
+
}
|
|
69
|
+
/** Entry point reserved for Cogover; project code does not call it. */
|
|
70
|
+
export type TriggerSandboxHandler = (inputJson: string) => Promise<string>;
|
|
71
|
+
/** Result of `defineTrigger`; list it in the project's `triggers` export. */
|
|
72
|
+
export interface TriggerDefinition {
|
|
73
|
+
readonly key: string;
|
|
74
|
+
readonly config: TriggerManifest;
|
|
75
|
+
/** Reserved for Cogover; project code does not call it. */
|
|
76
|
+
readonly __cogoverTriggerHandler: TriggerSandboxHandler;
|
|
77
|
+
}
|
|
78
|
+
/** Identifies the trigger and the record change of the current call. */
|
|
79
|
+
export interface TriggerInfo<TOperation extends TriggerOperation = TriggerOperation> {
|
|
80
|
+
readonly id: string;
|
|
81
|
+
readonly key: string;
|
|
82
|
+
readonly timing: TriggerTiming;
|
|
83
|
+
readonly operation: TOperation;
|
|
84
|
+
readonly objectSlug: string;
|
|
85
|
+
/** Identifies the record change that caused this call. */
|
|
86
|
+
readonly changeId: string;
|
|
87
|
+
}
|
|
88
|
+
/** Mutable field values after the change. Assigned values use the `records.update` input format. */
|
|
89
|
+
export type TriggerNewValues<TFields> = {
|
|
90
|
+
-readonly [K in keyof TFields]?: TFields[K] | Exclude<UpdateFields<TFields>[K], undefined>;
|
|
91
|
+
};
|
|
92
|
+
/** Immutable field values before the change. */
|
|
93
|
+
export type TriggerOldValues<TFields> = {
|
|
94
|
+
readonly [K in keyof TFields]?: TFields[K];
|
|
95
|
+
};
|
|
96
|
+
type TriggerValuesFor<TAbsentFor extends TriggerOperation, TOperation extends TriggerOperation, TValues> = [TOperation] extends [TAbsentFor] ? null : TAbsentFor extends TOperation ? TValues | null : TValues;
|
|
97
|
+
/** One record of the change being processed. */
|
|
98
|
+
export interface TriggerRecord<TFields = Record<string, unknown>, TOperation extends TriggerOperation = TriggerOperation> {
|
|
99
|
+
/** Correlates this record with its result; not a record ID. */
|
|
100
|
+
readonly key: string;
|
|
101
|
+
/** `null` while a record that is being created has no ID yet. */
|
|
102
|
+
readonly id: CogoverRecordId | null;
|
|
103
|
+
/** `null` when the record is being deleted. */
|
|
104
|
+
readonly new: TriggerValuesFor<"delete", TOperation, TriggerNewValues<TFields>>;
|
|
105
|
+
/** `null` when the record is being created. */
|
|
106
|
+
readonly old: TriggerValuesFor<"create", TOperation, TriggerOldValues<TFields>>;
|
|
107
|
+
readonly changedFields: readonly StringKeyOf<TFields>[];
|
|
108
|
+
/** Rejects this record. Pass `null` as the field for an error about the whole record. */
|
|
109
|
+
addError(field: StringKeyOf<TFields> | null, code: string, message?: string): void;
|
|
110
|
+
}
|
|
111
|
+
export interface TriggerContext<TObject extends string = string, TOperation extends TriggerOperation = TriggerOperation, TSchema extends object = EffectiveWorkspaceObjects> {
|
|
112
|
+
readonly records: readonly TriggerRecord<TriggerObjectFields<TObject, TSchema>, TOperation>[];
|
|
113
|
+
readonly trigger: TriggerInfo<TOperation>;
|
|
114
|
+
readonly invocation: InvocationContext;
|
|
115
|
+
readonly data: DataApi<TSchema>;
|
|
116
|
+
readonly schema: SchemaApi<TSchema>;
|
|
117
|
+
readonly log: ScriptLogger;
|
|
118
|
+
/** Refused with `TRIGGER_READ_ONLY` in a before-change trigger. */
|
|
119
|
+
readonly push: PushApi<TSchema>;
|
|
120
|
+
}
|
|
121
|
+
export type TriggerHandler<TObject extends string = string, TOperation extends TriggerOperation = TriggerOperation, TSchema extends object = EffectiveWorkspaceObjects> = (context: TriggerContext<TObject, TOperation, TSchema>) => void | Promise<void>;
|
|
122
|
+
/** Declares a record trigger. Add the result to the project's `triggers` export. */
|
|
123
|
+
export declare function defineTrigger<TObject extends StringKeyOf<TSchema>, TOperation extends TriggerOperation, TSchema extends object = EffectiveWorkspaceObjects>(config: TriggerConfig<TObject, TOperation, TSchema>, handler: TriggerHandler<TObject, TOperation, TSchema>): TriggerDefinition;
|
|
124
|
+
export {};
|
package/dist/trigger.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { ValidationError } from "./errors.js";
|
|
2
|
+
import { normalizeTriggerConfig } from "./internal/trigger-config.js";
|
|
3
|
+
import { createTriggerSandboxHandler } from "./internal/trigger-runtime.js";
|
|
4
|
+
/** Declares a record trigger. Add the result to the project's `triggers` export. */
|
|
5
|
+
export function defineTrigger(config, handler) {
|
|
6
|
+
const manifest = normalizeTriggerConfig(config);
|
|
7
|
+
if (typeof handler !== "function") {
|
|
8
|
+
throw new ValidationError(`Trigger '${manifest.key}' requires a handler function`);
|
|
9
|
+
}
|
|
10
|
+
return Object.freeze({
|
|
11
|
+
key: manifest.key,
|
|
12
|
+
config: manifest,
|
|
13
|
+
__cogoverTriggerHandler: createTriggerSandboxHandler(manifest, handler),
|
|
14
|
+
});
|
|
15
|
+
}
|