@composable-os/sdk 0.0.0-stage → 0.1.0-beta.11
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/LICENSE +109 -0
- package/dist/allowance.d.ts +198 -0
- package/dist/allowance.js +374 -0
- package/dist/automation-check.d.ts +38 -0
- package/dist/automation-check.js +454 -0
- package/dist/automation.d.ts +767 -0
- package/dist/automation.js +303 -0
- package/dist/behaviour.d.ts +3 -0
- package/dist/behaviour.js +153 -0
- package/dist/capacity.d.ts +146 -0
- package/dist/capacity.js +189 -0
- package/dist/contract.d.ts +851 -0
- package/dist/contract.js +42 -0
- package/dist/document.d.ts +211 -0
- package/dist/document.js +726 -0
- package/dist/field-types.d.ts +11 -0
- package/dist/field-types.js +98 -0
- package/dist/formula/ast.d.ts +67 -0
- package/dist/formula/ast.js +22 -0
- package/dist/formula/compile.d.ts +37 -0
- package/dist/formula/compile.js +379 -0
- package/dist/formula/index.d.ts +3 -0
- package/dist/formula/index.js +4 -0
- package/dist/formula/parser.d.ts +13 -0
- package/dist/formula/parser.js +365 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +24 -0
- package/dist/manifest.d.ts +1708 -0
- package/dist/manifest.js +1494 -0
- package/dist/media.d.ts +41 -0
- package/dist/media.js +90 -0
- package/dist/permissions.d.ts +17 -0
- package/dist/permissions.js +44 -0
- package/dist/recurring.d.ts +114 -0
- package/dist/recurring.js +173 -0
- package/dist/renamed.d.ts +16 -0
- package/dist/renamed.js +59 -0
- package/dist/rich-text-fixture.d.ts +121 -0
- package/dist/rich-text-fixture.js +67 -0
- package/dist/rich-text.d.ts +48 -0
- package/dist/rich-text.js +184 -0
- package/dist/runtime.d.ts +95 -0
- package/dist/runtime.js +312 -0
- package/dist/sellable.d.ts +331 -0
- package/dist/sellable.js +746 -0
- package/dist/slug.d.ts +11 -0
- package/dist/slug.js +23 -0
- package/dist/states.d.ts +292 -0
- package/dist/states.js +383 -0
- package/dist/testing.d.ts +151 -0
- package/dist/testing.js +679 -0
- package/dist/unique.d.ts +20 -0
- package/dist/unique.js +58 -0
- package/package.json +34 -4
- package/src/allowance.ts +522 -0
- package/src/automation-check.ts +534 -0
- package/src/automation.ts +743 -0
- package/src/behaviour.ts +215 -0
- package/src/capacity.ts +303 -0
- package/src/contract.ts +909 -0
- package/src/document.ts +935 -0
- package/src/field-types.ts +111 -0
- package/src/formula/ast.ts +72 -0
- package/src/formula/compile.ts +454 -0
- package/src/formula/index.ts +4 -0
- package/src/formula/parser.ts +417 -0
- package/src/index.ts +36 -0
- package/src/manifest.ts +1785 -0
- package/src/media.ts +108 -0
- package/src/permissions.ts +60 -0
- package/src/recurring.ts +321 -0
- package/src/renamed.ts +63 -0
- package/src/rich-text-fixture.ts +68 -0
- package/src/rich-text.ts +221 -0
- package/src/runtime.ts +410 -0
- package/src/sellable.ts +1138 -0
- package/src/slug.ts +25 -0
- package/src/states.ts +598 -0
- package/src/testing.ts +847 -0
- package/src/unique.ts +81 -0
- package/README.md +0 -3
package/dist/testing.js
ADDED
|
@@ -0,0 +1,679 @@
|
|
|
1
|
+
// @composable-os/sdk/testing: unit-test an extension locally with in-memory host modules.
|
|
2
|
+
//
|
|
3
|
+
// const host = createTestHost(extension, { records: { organisation: [{ id: "org_1", name: "Acme" }] } });
|
|
4
|
+
// expect(host.issues).toEqual([]);
|
|
5
|
+
// const out = await host.runTool("scoreOrganisation", { organisationId: "org_1" });
|
|
6
|
+
// expect(host.calls).toContainEqual({ operation: "record.get", input: { ... } });
|
|
7
|
+
//
|
|
8
|
+
// The in-memory `ops` module enforces the extension's declared permissions with the host's rules
|
|
9
|
+
// (`checkGrant`) and implements the generic record operations over an in-memory store. Pass
|
|
10
|
+
// `operations` to fake anything else.
|
|
11
|
+
//
|
|
12
|
+
// Automations run in memory too, start to finish, without the Workflow:
|
|
13
|
+
//
|
|
14
|
+
// const run = await host.runAutomation("wonOnboarding", { record: { object: "deals.deal", id: "d1" } });
|
|
15
|
+
// expect(run.steps.map((s) => s.name)).toEqual(["createTasks", "notifyOwner", "wait", "notifyManager"]);
|
|
16
|
+
// expect(run.notifications[0]?.userIds).toEqual(["usr_owner"]);
|
|
17
|
+
//
|
|
18
|
+
// `step.do` runs its function, `step.sleep` and `step.waitForEvent` return at once (recorded with
|
|
19
|
+
// how long they would wait; pass `events` for waitForEvent payloads), and every step name is held
|
|
20
|
+
// to the automation's declarations like the host does. Writes and notifications a step did not
|
|
21
|
+
// declare are listed in `undeclared`.
|
|
22
|
+
import { durationMs, notificationInput, } from "./automation.js";
|
|
23
|
+
import { GATEKEEPER_MODULES } from "./contract.js";
|
|
24
|
+
import { validateDocument } from "./document.js";
|
|
25
|
+
import { CORE_OBJECT_NAMES, toManifest, validateManifest } from "./manifest.js";
|
|
26
|
+
import { checkGrant } from "./permissions.js";
|
|
27
|
+
import { documentMaxBytesOf, documentSchemaOf } from "./rich-text.js";
|
|
28
|
+
import { buildContext, runExtension } from "./runtime.js";
|
|
29
|
+
/** Thrown into `run` when it uses a step name it did not declare (the host refuses it too). */
|
|
30
|
+
export class AutomationStepError extends Error {
|
|
31
|
+
name = "AutomationStepError";
|
|
32
|
+
code = "undeclared_step";
|
|
33
|
+
}
|
|
34
|
+
export class ExtensionToolError extends Error {
|
|
35
|
+
code;
|
|
36
|
+
details;
|
|
37
|
+
name = "ExtensionToolError";
|
|
38
|
+
constructor(code, message, details) {
|
|
39
|
+
super(message);
|
|
40
|
+
this.code = code;
|
|
41
|
+
this.details = details;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function riskOf(operation) {
|
|
45
|
+
const verb = operation.split(".").at(-1) ?? "";
|
|
46
|
+
if (/^(get|list|search|listForRecord|listMine|sql|global|count|unreadCount|version|versions)$/.test(verb))
|
|
47
|
+
return "read";
|
|
48
|
+
if (verb === "createMany")
|
|
49
|
+
return "bulk-write";
|
|
50
|
+
if (/^(delete|erase|merge|deleteMany)$/.test(verb))
|
|
51
|
+
return "destructive";
|
|
52
|
+
return "write";
|
|
53
|
+
}
|
|
54
|
+
function objectOf(operation, input) {
|
|
55
|
+
// As the host's operationObject: record.* and my.* name their object in the input.
|
|
56
|
+
if (operation.startsWith("record.") ||
|
|
57
|
+
operation.startsWith("my.") ||
|
|
58
|
+
operation === "state.resolve")
|
|
59
|
+
return typeof input.object === "string" ? input.object : null;
|
|
60
|
+
const prefix = operation.split(".")[0] ?? "";
|
|
61
|
+
return CORE_OBJECT_NAMES.includes(prefix) ? prefix : null;
|
|
62
|
+
}
|
|
63
|
+
let sequence = 0;
|
|
64
|
+
export function createTestHost(extension, options = {}) {
|
|
65
|
+
const { manifest: validated, issues } = validateManifest(toManifest(extension), options.validate);
|
|
66
|
+
const manifest = validated ?? toManifest(extension);
|
|
67
|
+
const records = new Map();
|
|
68
|
+
for (const [object, rows] of Object.entries(options.records ?? {})) {
|
|
69
|
+
records.set(object, new Map(rows.map((row) => [row.id, { ...row }])));
|
|
70
|
+
}
|
|
71
|
+
const table = (object) => {
|
|
72
|
+
let rows = records.get(object);
|
|
73
|
+
if (!rows) {
|
|
74
|
+
rows = new Map();
|
|
75
|
+
records.set(object, rows);
|
|
76
|
+
}
|
|
77
|
+
return rows;
|
|
78
|
+
};
|
|
79
|
+
const calls = [];
|
|
80
|
+
const logs = [];
|
|
81
|
+
const storage = new Map();
|
|
82
|
+
const versions = new Map();
|
|
83
|
+
/** A person publishing a record (ADR 0446): its `publishable.content` becomes a version. */
|
|
84
|
+
const publish = (object, id) => {
|
|
85
|
+
const local = object.startsWith(`${manifest.id}.`) ? object.slice(manifest.id.length + 1) : "";
|
|
86
|
+
const content = manifest.objects[local]?.publishable?.content;
|
|
87
|
+
if (!content)
|
|
88
|
+
throw new ExtensionToolError("invalid_input", `${object} is not publishable`);
|
|
89
|
+
const row = table(object).get(id);
|
|
90
|
+
if (!row)
|
|
91
|
+
throw new ExtensionToolError("not_found", `No ${object} with id ${id}`);
|
|
92
|
+
const list = versions.get(`${object}|${id}`) ?? [];
|
|
93
|
+
const version = list.length + 1;
|
|
94
|
+
list.push({
|
|
95
|
+
version,
|
|
96
|
+
publishedAt: new Date().toISOString(),
|
|
97
|
+
values: structuredClone(Object.fromEntries(content.map((f) => [f, row[f] ?? null]))),
|
|
98
|
+
});
|
|
99
|
+
versions.set(`${object}|${id}`, list);
|
|
100
|
+
row.publishedVersion = version;
|
|
101
|
+
return version;
|
|
102
|
+
};
|
|
103
|
+
// Records are stored flat ({ id, ...values }) and returned in the host's record shape.
|
|
104
|
+
const titleOf = (object, row) => {
|
|
105
|
+
const local = object.startsWith(`${manifest.id}.`)
|
|
106
|
+
? object.slice(manifest.id.length + 1)
|
|
107
|
+
: null;
|
|
108
|
+
const field = local ? manifest.objects[local]?.titleField : undefined;
|
|
109
|
+
const title = field ? row[field] : (row.name ?? row.displayName ?? row.title);
|
|
110
|
+
return title == null ? null : String(title);
|
|
111
|
+
};
|
|
112
|
+
const shape = (object, row) => {
|
|
113
|
+
const { id, ...values } = row;
|
|
114
|
+
return { object, id, title: titleOf(object, row), values, createdAt: null, updatedAt: null };
|
|
115
|
+
};
|
|
116
|
+
const matches = (row, filter) => {
|
|
117
|
+
if (!filter || typeof filter !== "object")
|
|
118
|
+
return true;
|
|
119
|
+
const f = filter;
|
|
120
|
+
if (f.and)
|
|
121
|
+
return f.and.every((child) => matches(row, child));
|
|
122
|
+
if (f.or)
|
|
123
|
+
return f.or.some((child) => matches(row, child));
|
|
124
|
+
const value = f.field ? row[f.field] : undefined;
|
|
125
|
+
switch (f.op) {
|
|
126
|
+
case "eq":
|
|
127
|
+
return value === f.value;
|
|
128
|
+
case "neq":
|
|
129
|
+
return value !== f.value;
|
|
130
|
+
case "is_null":
|
|
131
|
+
return value == null;
|
|
132
|
+
case "is_not_null":
|
|
133
|
+
return value != null;
|
|
134
|
+
case "in":
|
|
135
|
+
return Array.isArray(f.value) && f.value.includes(value);
|
|
136
|
+
case "not_in":
|
|
137
|
+
return Array.isArray(f.value) && !f.value.includes(value);
|
|
138
|
+
case "lt":
|
|
139
|
+
return value != null && value < f.value;
|
|
140
|
+
case "lte":
|
|
141
|
+
return value != null && value <= f.value;
|
|
142
|
+
case "gt":
|
|
143
|
+
return value != null && value > f.value;
|
|
144
|
+
case "gte":
|
|
145
|
+
return value != null && value >= f.value;
|
|
146
|
+
case "contains":
|
|
147
|
+
return String(value ?? "").includes(String(f.value));
|
|
148
|
+
case "not_contains":
|
|
149
|
+
return !String(value ?? "").includes(String(f.value));
|
|
150
|
+
case "starts_with":
|
|
151
|
+
return String(value ?? "").startsWith(String(f.value));
|
|
152
|
+
case "ends_with":
|
|
153
|
+
return String(value ?? "").endsWith(String(f.value));
|
|
154
|
+
default:
|
|
155
|
+
throw new ExtensionToolError("unsupported", `The test host does not fake filter op ${f.op}`);
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
// A document field's value is checked against its schema, as the host checks it (ADR 0445).
|
|
159
|
+
const checkDocuments = (object, values) => {
|
|
160
|
+
const local = object.startsWith(`${manifest.id}.`) ? object.slice(manifest.id.length + 1) : "";
|
|
161
|
+
for (const [name, field] of Object.entries(manifest.objects[local]?.fields ?? {})) {
|
|
162
|
+
const schema = documentSchemaOf(field);
|
|
163
|
+
if (!schema || values[name] === undefined || values[name] === null)
|
|
164
|
+
continue;
|
|
165
|
+
const maxBytes = documentMaxBytesOf(field);
|
|
166
|
+
const result = validateDocument(schema, values[name], maxBytes === undefined ? {} : { maxBytes });
|
|
167
|
+
if (!result.ok) {
|
|
168
|
+
const first = result.issues[0];
|
|
169
|
+
throw new ExtensionToolError("invalid_input", `Invalid value for ${object}.${name}: ${[name, ...(first?.path ?? [])].join(".")}: ${first?.message}`, { field: name, issues: result.issues });
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
};
|
|
173
|
+
const create = (object, values) => {
|
|
174
|
+
checkDocuments(object, values);
|
|
175
|
+
sequence += 1;
|
|
176
|
+
const id = `rec_test${sequence}`;
|
|
177
|
+
// A record with a state machine starts in its initial state, as the host makes it.
|
|
178
|
+
const local = object.startsWith(`${manifest.id}.`) ? object.slice(manifest.id.length + 1) : "";
|
|
179
|
+
const states = manifest.objects[local]?.states;
|
|
180
|
+
const initial = states && values[states.field] == null ? { [states.field]: states.initial } : {};
|
|
181
|
+
const row = { ...initial, ...values, id };
|
|
182
|
+
table(object).set(id, row);
|
|
183
|
+
return row;
|
|
184
|
+
};
|
|
185
|
+
const builtIn = {
|
|
186
|
+
"record.create": (input) => {
|
|
187
|
+
const object = String(input.object);
|
|
188
|
+
return shape(object, create(object, input.values));
|
|
189
|
+
},
|
|
190
|
+
"record.createMany": (input) => {
|
|
191
|
+
const object = String(input.object);
|
|
192
|
+
const rows = input.records.map((values) => {
|
|
193
|
+
checkDocuments(object, values);
|
|
194
|
+
return values;
|
|
195
|
+
});
|
|
196
|
+
return { ids: rows.map((values) => create(object, values).id) };
|
|
197
|
+
},
|
|
198
|
+
// Versions a person published (`host.publish`), ADR 0446.
|
|
199
|
+
"record.version": (input) => {
|
|
200
|
+
const list = versions.get(`${input.object}|${input.id}`) ?? [];
|
|
201
|
+
const found = input.version === undefined
|
|
202
|
+
? list.at(-1)
|
|
203
|
+
: list.find((v) => v.version === Number(input.version));
|
|
204
|
+
if (!found) {
|
|
205
|
+
throw new ExtensionToolError("not_found", `No published version of ${input.id}`);
|
|
206
|
+
}
|
|
207
|
+
return {
|
|
208
|
+
version: found.version,
|
|
209
|
+
current: found === list.at(-1),
|
|
210
|
+
publishedAt: found.publishedAt,
|
|
211
|
+
publishedBy: "usr_admin",
|
|
212
|
+
note: null,
|
|
213
|
+
bytes: JSON.stringify(found.values).length,
|
|
214
|
+
values: structuredClone(found.values),
|
|
215
|
+
};
|
|
216
|
+
},
|
|
217
|
+
"record.get": (input) => {
|
|
218
|
+
const object = String(input.object);
|
|
219
|
+
const row = table(object).get(String(input.id));
|
|
220
|
+
if (!row)
|
|
221
|
+
throw new ExtensionToolError("not_found", `No ${object} with id ${input.id}`);
|
|
222
|
+
return shape(object, row);
|
|
223
|
+
},
|
|
224
|
+
"record.update": (input) => {
|
|
225
|
+
const object = String(input.object);
|
|
226
|
+
const rows = table(object);
|
|
227
|
+
const row = rows.get(String(input.id));
|
|
228
|
+
if (!row)
|
|
229
|
+
throw new ExtensionToolError("not_found", `No ${object} with id ${input.id}`);
|
|
230
|
+
if (typeof input.from === "string") {
|
|
231
|
+
// `from` (ADR 0437): move only out of this state, refused as the host refuses it.
|
|
232
|
+
const local = object.startsWith(`${manifest.id}.`)
|
|
233
|
+
? object.slice(manifest.id.length + 1)
|
|
234
|
+
: "";
|
|
235
|
+
const spec = manifest.objects[local];
|
|
236
|
+
const field = spec?.states?.field ?? spec?.stages?.field;
|
|
237
|
+
const values = input.values;
|
|
238
|
+
if (!field || values[field] === undefined || values[field] === input.from) {
|
|
239
|
+
throw new ExtensionToolError("invalid_input", `With "from", the write must move ${field}`);
|
|
240
|
+
}
|
|
241
|
+
if (row[field] !== input.from) {
|
|
242
|
+
throw new ExtensionToolError("conflict", `${object} is no longer ${input.from}`, {
|
|
243
|
+
reason: "not_in_position",
|
|
244
|
+
field,
|
|
245
|
+
from: input.from,
|
|
246
|
+
current: row[field] ?? null,
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
checkDocuments(object, input.values);
|
|
251
|
+
const next = { ...row, ...input.values, id: row.id };
|
|
252
|
+
rows.set(row.id, next);
|
|
253
|
+
return shape(object, next);
|
|
254
|
+
},
|
|
255
|
+
"record.delete": (input) => {
|
|
256
|
+
table(String(input.object)).delete(String(input.id));
|
|
257
|
+
return { id: input.id };
|
|
258
|
+
},
|
|
259
|
+
"record.list": (input) => {
|
|
260
|
+
const object = String(input.object);
|
|
261
|
+
return {
|
|
262
|
+
items: [...table(object).values()]
|
|
263
|
+
.filter((row) => matches(row, input.filter))
|
|
264
|
+
.map((row) => shape(object, row)),
|
|
265
|
+
nextCursor: null,
|
|
266
|
+
};
|
|
267
|
+
},
|
|
268
|
+
};
|
|
269
|
+
for (const object of CORE_OBJECT_NAMES) {
|
|
270
|
+
builtIn[`${object}.get`] = (input) => builtIn["record.get"]?.({ ...input, object });
|
|
271
|
+
}
|
|
272
|
+
// Tasks, in the task operations' shape (status, assignee, links).
|
|
273
|
+
const taskShape = (row) => ({
|
|
274
|
+
title: null,
|
|
275
|
+
notes: null,
|
|
276
|
+
dueAt: null,
|
|
277
|
+
status: "open",
|
|
278
|
+
assigneeId: null,
|
|
279
|
+
links: [],
|
|
280
|
+
...row,
|
|
281
|
+
});
|
|
282
|
+
const requireTask = (id) => {
|
|
283
|
+
const row = table("task").get(String(id));
|
|
284
|
+
if (!row)
|
|
285
|
+
throw new ExtensionToolError("not_found", `No task with id ${id}`);
|
|
286
|
+
return row;
|
|
287
|
+
};
|
|
288
|
+
Object.assign(builtIn, {
|
|
289
|
+
"task.create": (input) => {
|
|
290
|
+
sequence += 1;
|
|
291
|
+
const row = {
|
|
292
|
+
status: "open",
|
|
293
|
+
assigneeId: null,
|
|
294
|
+
links: [],
|
|
295
|
+
...input,
|
|
296
|
+
id: `tsk_test${sequence}`,
|
|
297
|
+
};
|
|
298
|
+
table("task").set(row.id, row);
|
|
299
|
+
return taskShape(row);
|
|
300
|
+
},
|
|
301
|
+
"task.get": (input) => taskShape(requireTask(input.id)),
|
|
302
|
+
"task.update": (input) => {
|
|
303
|
+
const row = { ...requireTask(input.id), ...input };
|
|
304
|
+
table("task").set(row.id, row);
|
|
305
|
+
return taskShape(row);
|
|
306
|
+
},
|
|
307
|
+
"task.complete": (input) => {
|
|
308
|
+
const row = { ...requireTask(input.id), status: "done" };
|
|
309
|
+
table("task").set(row.id, row);
|
|
310
|
+
return taskShape(row);
|
|
311
|
+
},
|
|
312
|
+
"task.list": (input) => {
|
|
313
|
+
const linked = (row, filter) => {
|
|
314
|
+
const f = filter;
|
|
315
|
+
if (f?.and)
|
|
316
|
+
return f.and.every((child) => linked(row, child));
|
|
317
|
+
if (f?.field !== "linkedRecordId")
|
|
318
|
+
return matches(row, f);
|
|
319
|
+
return row.links.some((link) => link.id === f.value);
|
|
320
|
+
};
|
|
321
|
+
return {
|
|
322
|
+
items: [...table("task").values()]
|
|
323
|
+
.filter((row) => linked(row, input.filter))
|
|
324
|
+
.map(taskShape),
|
|
325
|
+
nextCursor: null,
|
|
326
|
+
};
|
|
327
|
+
},
|
|
328
|
+
});
|
|
329
|
+
// notification.send: resolves recipients like the host (managerOf → the admins, with a note,
|
|
330
|
+
// since users have no manager field) and keeps one notification per (user, dedupeKey).
|
|
331
|
+
const users = options.users ?? [{ id: "usr_admin", role: "admin" }];
|
|
332
|
+
const notifications = [];
|
|
333
|
+
const delivered = new Set();
|
|
334
|
+
let currentStep = null;
|
|
335
|
+
let observer = null;
|
|
336
|
+
builtIn["notification.send"] = (input) => {
|
|
337
|
+
const notes = [];
|
|
338
|
+
const admins = users.filter((u) => u.role === "admin").map((u) => u.id);
|
|
339
|
+
const ids = [];
|
|
340
|
+
for (const to of input.to) {
|
|
341
|
+
if (typeof to.userId === "string")
|
|
342
|
+
ids.push(to.userId);
|
|
343
|
+
else if (to.role === "admin")
|
|
344
|
+
ids.push(...admins);
|
|
345
|
+
else if (typeof to.managerOf === "string") {
|
|
346
|
+
notes.push("Users have no manager field: sent to the admins instead");
|
|
347
|
+
ids.push(...admins);
|
|
348
|
+
}
|
|
349
|
+
else if (typeof to.field === "string") {
|
|
350
|
+
const ref = to.record;
|
|
351
|
+
const value = table(ref.object).get(ref.id)?.[to.field];
|
|
352
|
+
if (typeof value === "string" && value)
|
|
353
|
+
ids.push(value);
|
|
354
|
+
else
|
|
355
|
+
notes.push(`${ref.object} ${ref.id} has no ${to.field}`);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
const key = typeof input.dedupeKey === "string" ? input.dedupeKey : null;
|
|
359
|
+
const userIds = [...new Set(ids)].filter((id) => !key || !delivered.has(`${id}\n${key}`));
|
|
360
|
+
for (const id of userIds)
|
|
361
|
+
if (key)
|
|
362
|
+
delivered.add(`${id}\n${key}`);
|
|
363
|
+
const { dedupeKey: _key, type, ...rest } = input;
|
|
364
|
+
notifications.push({
|
|
365
|
+
...rest,
|
|
366
|
+
type: String(type ?? "system.message"),
|
|
367
|
+
dedupeKey: key,
|
|
368
|
+
userIds,
|
|
369
|
+
notes,
|
|
370
|
+
step: currentStep,
|
|
371
|
+
});
|
|
372
|
+
return { sent: userIds.length, userIds, notes };
|
|
373
|
+
};
|
|
374
|
+
const has = (name) => manifest.permissions.modules.includes(name);
|
|
375
|
+
const raw = {};
|
|
376
|
+
if (has("ops")) {
|
|
377
|
+
raw.ops = {
|
|
378
|
+
call: async (operation, input) => {
|
|
379
|
+
const name = String(operation);
|
|
380
|
+
const body = (input ?? {});
|
|
381
|
+
const decision = checkGrant(manifest.id, manifest.permissions, {
|
|
382
|
+
operation: name,
|
|
383
|
+
risk: riskOf(name),
|
|
384
|
+
object: objectOf(name, body),
|
|
385
|
+
});
|
|
386
|
+
calls.push({ operation: name, input: body, allowed: decision.ok });
|
|
387
|
+
if (!decision.ok)
|
|
388
|
+
return { ok: false, error: { code: "forbidden", message: decision.reason } };
|
|
389
|
+
const fake = options.operations?.[name] ?? builtIn[name];
|
|
390
|
+
if (!fake) {
|
|
391
|
+
return {
|
|
392
|
+
ok: false,
|
|
393
|
+
error: { code: "unknown_operation", message: `No fake for ${name}` },
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
try {
|
|
397
|
+
const value = structuredClone(await fake(body));
|
|
398
|
+
observer?.(name, body, value);
|
|
399
|
+
return { ok: true, value };
|
|
400
|
+
}
|
|
401
|
+
catch (error) {
|
|
402
|
+
const e = error;
|
|
403
|
+
// As the real host: a refusal's details (its rule) reach the tool, as OpsCallError's.
|
|
404
|
+
return {
|
|
405
|
+
ok: false,
|
|
406
|
+
error: {
|
|
407
|
+
code: e.code ?? "internal",
|
|
408
|
+
message: e.message ?? String(error),
|
|
409
|
+
...(e.code && e.code !== "internal" && e.details !== undefined
|
|
410
|
+
? { details: e.details }
|
|
411
|
+
: {}),
|
|
412
|
+
},
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
},
|
|
416
|
+
};
|
|
417
|
+
}
|
|
418
|
+
if (has("storage")) {
|
|
419
|
+
raw.storage = {
|
|
420
|
+
get: async (key) => storage.get(String(key)) ?? null,
|
|
421
|
+
set: async (key, value) => {
|
|
422
|
+
storage.set(String(key), structuredClone(value));
|
|
423
|
+
},
|
|
424
|
+
del: async (key) => {
|
|
425
|
+
storage.delete(String(key));
|
|
426
|
+
},
|
|
427
|
+
list: async (prefix) => [...storage]
|
|
428
|
+
.filter(([key]) => key.startsWith(String(prefix ?? "")))
|
|
429
|
+
.map(([key, value]) => ({ key, value })),
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
if (has("log")) {
|
|
433
|
+
raw.log = {
|
|
434
|
+
write: async (level, message, data) => {
|
|
435
|
+
logs.push({ level: String(level), message: String(message), data });
|
|
436
|
+
},
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
const gatekeeperCalls = [];
|
|
440
|
+
for (const name of manifest.permissions.modules) {
|
|
441
|
+
if (!GATEKEEPER_MODULES.includes(name))
|
|
442
|
+
continue;
|
|
443
|
+
const declared = Object.values(manifest.automations).flatMap((a) => (a.connections ?? []).filter((c) => c.gatekeeper === name).map((c) => c.id));
|
|
444
|
+
raw[name] = {
|
|
445
|
+
connections: async () => [...new Set(declared.length ? declared : ["default"])].map((id) => ({
|
|
446
|
+
id,
|
|
447
|
+
title: id,
|
|
448
|
+
resources: [{ key: `${id}-resource`, bindingName: "RESOURCE", tsType: "unknown" }],
|
|
449
|
+
})),
|
|
450
|
+
call: async (connectionId, resource, method, args) => {
|
|
451
|
+
const call = {
|
|
452
|
+
connectionId: String(connectionId),
|
|
453
|
+
resource: String(resource),
|
|
454
|
+
method: String(method),
|
|
455
|
+
args: args ?? [],
|
|
456
|
+
};
|
|
457
|
+
gatekeeperCalls.push({ gatekeeper: name, ...call, step: currentStep });
|
|
458
|
+
try {
|
|
459
|
+
const fake = options.gatekeepers?.[name];
|
|
460
|
+
const value = fake ? await fake(call) : { status: "pending" };
|
|
461
|
+
return { ok: true, value: { value: structuredClone(value), pending: [], applied: [] } };
|
|
462
|
+
}
|
|
463
|
+
catch (error) {
|
|
464
|
+
const e = error;
|
|
465
|
+
return {
|
|
466
|
+
ok: false,
|
|
467
|
+
error: { code: e.code ?? "internal", message: e.message ?? String(error) },
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
},
|
|
471
|
+
types: async () => "",
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
if (has("ai")) {
|
|
475
|
+
const ai = {
|
|
476
|
+
summarise: async (text) => String(text).slice(0, 100),
|
|
477
|
+
extract: async (_text, fields) => Object.fromEntries(Object.keys(fields).map((k) => [k, null])),
|
|
478
|
+
classify: async (_text, labels) => ({ label: labels[0] ?? "" }),
|
|
479
|
+
...options.ai,
|
|
480
|
+
};
|
|
481
|
+
raw.ai = {
|
|
482
|
+
summarise: (text, opts) => ai.summarise(String(text), opts),
|
|
483
|
+
extract: (text, fields) => ai.extract(String(text), fields),
|
|
484
|
+
classify: (text, labels) => ai.classify(String(text), labels),
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
async function runAutomation(name, run = {}) {
|
|
488
|
+
const automation = extension.automations?.[name];
|
|
489
|
+
if (!automation) {
|
|
490
|
+
throw new ExtensionToolError("unknown_automation", `No automation named ${name}`);
|
|
491
|
+
}
|
|
492
|
+
const declared = new Map(automation.steps.map((step) => [step.name, step]));
|
|
493
|
+
const result = {
|
|
494
|
+
matched: true,
|
|
495
|
+
value: null,
|
|
496
|
+
error: null,
|
|
497
|
+
steps: [],
|
|
498
|
+
writes: [],
|
|
499
|
+
notifications: [],
|
|
500
|
+
undeclared: [],
|
|
501
|
+
};
|
|
502
|
+
let row;
|
|
503
|
+
if (run.record) {
|
|
504
|
+
row = records.get(run.record.object)?.get(run.record.id);
|
|
505
|
+
if (!row) {
|
|
506
|
+
throw new ExtensionToolError("not_found", `Seed ${run.record.object} ${run.record.id} in records to use it as the trigger record`);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
if (automation.conditions && row && !matches(row, automation.conditions)) {
|
|
510
|
+
result.matched = false;
|
|
511
|
+
return result;
|
|
512
|
+
}
|
|
513
|
+
const event = {
|
|
514
|
+
automation: `${manifest.id}.${name}`,
|
|
515
|
+
runId: run.runId ?? "arn_TEST",
|
|
516
|
+
trigger: automation.trigger.type,
|
|
517
|
+
...(run.record && row
|
|
518
|
+
? {
|
|
519
|
+
record: {
|
|
520
|
+
object: run.record.object,
|
|
521
|
+
id: run.record.id,
|
|
522
|
+
data: Object.fromEntries(Object.entries(row).filter(([key]) => key !== "id")),
|
|
523
|
+
title: titleOf(run.record.object, row),
|
|
524
|
+
},
|
|
525
|
+
}
|
|
526
|
+
: {}),
|
|
527
|
+
...(run.change ? { change: run.change } : {}),
|
|
528
|
+
...(run.period ? { period: run.period } : {}),
|
|
529
|
+
...(run.manual ? { manual: run.manual } : {}),
|
|
530
|
+
...(run.approval ? { approval: run.approval } : {}),
|
|
531
|
+
test: run.test ?? false,
|
|
532
|
+
};
|
|
533
|
+
const ran = new Set();
|
|
534
|
+
const claim = (stepName, kind) => {
|
|
535
|
+
const step = declared.get(stepName);
|
|
536
|
+
if (!step || (step.kind ?? "do") !== kind) {
|
|
537
|
+
throw new AutomationStepError(`step.${kind}("${stepName}") is not a declared ${kind} step of ${name}; declare it in steps`);
|
|
538
|
+
}
|
|
539
|
+
if (ran.has(stepName)) {
|
|
540
|
+
throw new AutomationStepError(`Step ${stepName} already ran; each step runs once per run`);
|
|
541
|
+
}
|
|
542
|
+
ran.add(stepName);
|
|
543
|
+
return step;
|
|
544
|
+
};
|
|
545
|
+
const declaredWrites = (stepName) => {
|
|
546
|
+
const step = stepName ? declared.get(stepName) : undefined;
|
|
547
|
+
return step && (step.kind ?? "do") === "do"
|
|
548
|
+
? (step.writes ?? []).map((w) => w.object)
|
|
549
|
+
: [];
|
|
550
|
+
};
|
|
551
|
+
const declaresNotify = (stepName) => {
|
|
552
|
+
const step = stepName ? declared.get(stepName) : undefined;
|
|
553
|
+
return Boolean(step?.notifies?.length);
|
|
554
|
+
};
|
|
555
|
+
const where = (stepName) => stepName ? `step ${stepName}` : "run (outside a step)";
|
|
556
|
+
const notificationsBefore = notifications.length;
|
|
557
|
+
observer = (operation, input, value) => {
|
|
558
|
+
if (operation === "notification.send") {
|
|
559
|
+
if (!declaresNotify(currentStep)) {
|
|
560
|
+
result.undeclared.push(`${where(currentStep)} sent a notification (not in its notifies)`);
|
|
561
|
+
}
|
|
562
|
+
return;
|
|
563
|
+
}
|
|
564
|
+
if (riskOf(operation) === "read")
|
|
565
|
+
return;
|
|
566
|
+
const object = objectOf(operation, input);
|
|
567
|
+
const id = value && typeof value === "object" && "id" in value
|
|
568
|
+
? String(value.id)
|
|
569
|
+
: null;
|
|
570
|
+
result.writes.push({ step: currentStep, operation, object, id });
|
|
571
|
+
if (!object || !declaredWrites(currentStep).includes(object)) {
|
|
572
|
+
result.undeclared.push(`${where(currentStep)} called ${operation}${object ? ` on ${object}` : ""} (not in its writes)`);
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
const pending = [];
|
|
576
|
+
const base = buildContext(extension, raw, pending);
|
|
577
|
+
const notifyCounts = new Map();
|
|
578
|
+
const ctx = {
|
|
579
|
+
...base,
|
|
580
|
+
async notify(to, message) {
|
|
581
|
+
const key = currentStep ?? "run";
|
|
582
|
+
const n = (notifyCounts.get(key) ?? 0) + 1;
|
|
583
|
+
notifyCounts.set(key, n);
|
|
584
|
+
const input = notificationInput(event, to, message, `${key}:${n}`);
|
|
585
|
+
const sent = await base.ops.call("notification.send", input);
|
|
586
|
+
return { sent: sent.sent };
|
|
587
|
+
},
|
|
588
|
+
};
|
|
589
|
+
const stepApi = {
|
|
590
|
+
async do(stepName, a, b) {
|
|
591
|
+
const fn = (typeof a === "function" ? a : b);
|
|
592
|
+
const step = claim(stepName, "do");
|
|
593
|
+
if (typeof a === "object" && a !== null) {
|
|
594
|
+
const intent = a;
|
|
595
|
+
const allowed = declaredWrites(step.name);
|
|
596
|
+
for (const write of intent.writes ?? []) {
|
|
597
|
+
if (!allowed.includes(write.object)) {
|
|
598
|
+
throw new AutomationStepError(`step.do("${stepName}") says it writes ${write.object}, but its declaration does not`);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
const first = calls.length;
|
|
603
|
+
currentStep = stepName;
|
|
604
|
+
try {
|
|
605
|
+
const value = await fn();
|
|
606
|
+
result.steps.push({
|
|
607
|
+
name: stepName,
|
|
608
|
+
kind: "do",
|
|
609
|
+
value: value === undefined ? null : structuredClone(value),
|
|
610
|
+
calls: calls.slice(first),
|
|
611
|
+
});
|
|
612
|
+
return value;
|
|
613
|
+
}
|
|
614
|
+
finally {
|
|
615
|
+
currentStep = null;
|
|
616
|
+
}
|
|
617
|
+
},
|
|
618
|
+
async sleep(stepName, duration) {
|
|
619
|
+
claim(stepName, "sleep");
|
|
620
|
+
result.steps.push({
|
|
621
|
+
name: stepName,
|
|
622
|
+
kind: "sleep",
|
|
623
|
+
skippedMs: durationMs(duration),
|
|
624
|
+
calls: [],
|
|
625
|
+
});
|
|
626
|
+
},
|
|
627
|
+
async waitForEvent(stepName) {
|
|
628
|
+
const step = claim(stepName, "waitForEvent");
|
|
629
|
+
const value = (run.events?.[stepName] ?? null);
|
|
630
|
+
result.steps.push({
|
|
631
|
+
name: stepName,
|
|
632
|
+
kind: "waitForEvent",
|
|
633
|
+
value,
|
|
634
|
+
skippedMs: durationMs((step.timeout ?? "7 days")),
|
|
635
|
+
calls: [],
|
|
636
|
+
});
|
|
637
|
+
return value;
|
|
638
|
+
},
|
|
639
|
+
};
|
|
640
|
+
try {
|
|
641
|
+
const value = await automation.run(event, stepApi, ctx);
|
|
642
|
+
result.value = value === undefined ? null : structuredClone(value);
|
|
643
|
+
}
|
|
644
|
+
catch (error) {
|
|
645
|
+
const e = error;
|
|
646
|
+
result.error = {
|
|
647
|
+
code: typeof e.code === "string" ? e.code : "automation_error",
|
|
648
|
+
message: typeof e.message === "string" ? e.message : String(error),
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
finally {
|
|
652
|
+
observer = null;
|
|
653
|
+
currentStep = null;
|
|
654
|
+
await Promise.all(pending);
|
|
655
|
+
}
|
|
656
|
+
result.notifications = notifications.slice(notificationsBefore);
|
|
657
|
+
return result;
|
|
658
|
+
}
|
|
659
|
+
return {
|
|
660
|
+
manifest,
|
|
661
|
+
issues,
|
|
662
|
+
calls,
|
|
663
|
+
logs,
|
|
664
|
+
storage,
|
|
665
|
+
records,
|
|
666
|
+
notifications,
|
|
667
|
+
gatekeeperCalls,
|
|
668
|
+
runAutomation,
|
|
669
|
+
publish,
|
|
670
|
+
async runTool(tool, input, options = {}) {
|
|
671
|
+
const caller = options.caller ?? { kind: "staff", userId: "usr_admin", name: "Admin" };
|
|
672
|
+
const response = await runExtension(extension, { kind: "tool", tool, input, caller }, raw);
|
|
673
|
+
if (!response.ok) {
|
|
674
|
+
throw new ExtensionToolError(response.error.code, response.error.message, response.error.details);
|
|
675
|
+
}
|
|
676
|
+
return response.value;
|
|
677
|
+
},
|
|
678
|
+
};
|
|
679
|
+
}
|