@pollis-inc/app 0.0.0-stage → 0.1.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.
@@ -0,0 +1,323 @@
1
+ /**
2
+ * The manifest: what an App asks for. Written in code, inside `app({ manifest })`,
3
+ * and emitted as `pollis-app.json` by `pollis app build`, so it cannot drift from
4
+ * what the code expects. An admin can narrow it when approving the App, never
5
+ * widen it, and the runtime enforces it.
6
+ *
7
+ * The rules here mirror the runtime's (`pollis-app-manifest`) so a mistake is
8
+ * reported at build time; the build then checks the emitted file with the
9
+ * runtime's own parser too.
10
+ */
11
+ export const TRIGGERS = ["messages", "mentions", "commands", "schedule", "requests", "webhook"];
12
+ export const ACTIONS = ["post", "reply", "react", "edit_own", "delete_own", "transfer_history"];
13
+ export const EVENTS = ["created", "edited"];
14
+ /** Which handler each trigger calls. */
15
+ export const HANDLER_FOR = {
16
+ messages: "onMessage",
17
+ mentions: "onMention",
18
+ commands: "onCommand",
19
+ schedule: "onSchedule",
20
+ requests: "onRequest",
21
+ webhook: "onWebhook",
22
+ };
23
+ /** A mistake in the manifest, with the field it is about. */
24
+ export class ManifestError extends Error {
25
+ constructor(message) {
26
+ super(message);
27
+ this.name = "ManifestError";
28
+ }
29
+ }
30
+ const NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
31
+ const COMMAND_NAME = /^[a-z][a-z0-9_-]{0,31}$/;
32
+ const SCHEDULE_NAME = /^[a-z0-9-]{1,32}$/;
33
+ export const MAX_COMMANDS = 25;
34
+ export const MIN_SCHEDULE_SECS = 60;
35
+ export const MAX_SCHEDULE_SECS = 7 * 24 * 3600;
36
+ const CHANNEL = /^(\*|#?[^\s*#][^\s*]*)$/;
37
+ const HOST = /^(?=.{1,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]([a-z0-9-]{0,61}[a-z0-9])?$/;
38
+ /** A package name as an App name: `@acme/Linear_Bot` becomes `linear-bot`. */
39
+ export function nameFromPackage(pkg) {
40
+ if (!pkg) {
41
+ return undefined;
42
+ }
43
+ const bare = pkg.replace(/^@[^/]+\//, "").toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+/, "");
44
+ return bare.slice(0, 64) || undefined;
45
+ }
46
+ function list(field, value, allowed) {
47
+ if (value === undefined) {
48
+ return [];
49
+ }
50
+ if (!Array.isArray(value) || value.some((v) => typeof v !== "string")) {
51
+ throw new ManifestError(`\`${field}\` must be a list of strings`);
52
+ }
53
+ const out = [];
54
+ for (const v of value) {
55
+ if (allowed && !allowed.includes(v)) {
56
+ throw new ManifestError(`\`${field}\` has ${JSON.stringify(v)}; use one of ${allowed.map((a) => JSON.stringify(a)).join(", ")}`);
57
+ }
58
+ // The runtime reads these lists as sets: a repeat is harmless.
59
+ if (!out.includes(v)) {
60
+ out.push(v);
61
+ }
62
+ }
63
+ return out;
64
+ }
65
+ function count(field, value) {
66
+ if (value === undefined) {
67
+ return 0;
68
+ }
69
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) {
70
+ throw new ManifestError(`\`${field}\` must be a whole number, 0 or more`);
71
+ }
72
+ return value;
73
+ }
74
+ function only(field, value, keys) {
75
+ for (const key of Object.keys(value)) {
76
+ if (!keys.includes(key)) {
77
+ throw new ManifestError(`\`${field ? field + "." : ""}${key}\` is not a manifest field; the fields are ${keys.map((k) => `\`${k}\``).join(", ")}`);
78
+ }
79
+ }
80
+ }
81
+ function oneLine(text, max) {
82
+ if (typeof text !== "string") {
83
+ return false;
84
+ }
85
+ const t = text.trim();
86
+ return t.length > 0 && [...t].length <= max && !t.includes("\n");
87
+ }
88
+ function hintOk(text, max) {
89
+ return text.trim().length > 0 && [...text].length <= max && !text.includes("\n");
90
+ }
91
+ function checkCommands(triggers, commands) {
92
+ if (triggers.includes("commands") && !commands.some((c) => !c.request)) {
93
+ throw new ManifestError("`commands`: the `commands` trigger needs at least one command that is not a `request`");
94
+ }
95
+ if (commands.length > MAX_COMMANDS) {
96
+ throw new ManifestError(`\`commands\`: at most ${MAX_COMMANDS} commands`);
97
+ }
98
+ const seen = new Set();
99
+ for (const c of commands) {
100
+ if (typeof c.name !== "string" || !COMMAND_NAME.test(c.name)) {
101
+ throw new ManifestError(`\`commands\`: name ${JSON.stringify(c.name)} is not valid: lowercase letters, digits, '-' and '_', 1 to 32 characters, starting with a letter`);
102
+ }
103
+ if (seen.has(c.name)) {
104
+ throw new ManifestError(`\`commands\`: /${c.name} is declared twice`);
105
+ }
106
+ seen.add(c.name);
107
+ if (!oneLine(c.description, 100)) {
108
+ throw new ManifestError(`\`commands\`: /${c.name}: \`description\` is one line of 1 to 100 characters`);
109
+ }
110
+ if (c.arg_hint !== undefined && (typeof c.arg_hint !== "string" || !hintOk(c.arg_hint, 60))) {
111
+ throw new ManifestError(`\`commands\`: /${c.name}: \`arg_hint\` is one line of 1 to 60 characters (leave it out for no arguments)`);
112
+ }
113
+ const needs = c.request ? "requests" : "commands";
114
+ if (!triggers.includes(needs)) {
115
+ throw new ManifestError(`\`commands\`: /${c.name} needs \`${needs}\` in \`triggers\`${c.request ? " (it is a `request` command)" : ""}`);
116
+ }
117
+ }
118
+ }
119
+ function checkSchedules(triggers, schedules) {
120
+ const bad = (why) => new ManifestError(`\`schedules\` is not valid: ${why}`);
121
+ const declared = triggers.includes("schedule");
122
+ if (declared && schedules.length === 0) {
123
+ throw bad("the `schedule` trigger needs at least one entry in `schedules`");
124
+ }
125
+ if (!declared && schedules.length > 0) {
126
+ throw bad("`schedules` needs the `schedule` trigger in `triggers`");
127
+ }
128
+ const names = new Set();
129
+ for (const s of schedules) {
130
+ if (typeof s.name !== "string" || !SCHEDULE_NAME.test(s.name)) {
131
+ throw bad(`name ${JSON.stringify(s.name)}: lowercase letters, digits and '-', 1 to 32 characters`);
132
+ }
133
+ if (names.has(s.name)) {
134
+ throw bad(`name ${JSON.stringify(s.name)} appears twice`);
135
+ }
136
+ names.add(s.name);
137
+ if (!Number.isSafeInteger(s.every) || s.every < MIN_SCHEDULE_SECS || s.every > MAX_SCHEDULE_SECS) {
138
+ throw bad(`${JSON.stringify(s.name)}: \`every\` is ${MIN_SCHEDULE_SECS} to ${MAX_SCHEDULE_SECS} seconds`);
139
+ }
140
+ if (!Number.isSafeInteger(s.offset ?? 0) || (s.offset ?? 0) < 0) {
141
+ throw bad(`${JSON.stringify(s.name)}: \`offset\` must be a whole number of seconds`);
142
+ }
143
+ if ((s.offset ?? 0) >= s.every) {
144
+ throw bad(`${JSON.stringify(s.name)}: \`offset\` must be less than \`every\``);
145
+ }
146
+ }
147
+ }
148
+ function commandList(value) {
149
+ if (value === undefined) {
150
+ return [];
151
+ }
152
+ if (!Array.isArray(value)) {
153
+ throw new ManifestError("`commands` must be a list of { name, description, arg_hint?, request? }");
154
+ }
155
+ return value.map((c) => {
156
+ if (c === null || typeof c !== "object") {
157
+ throw new ManifestError("`commands` entries must be objects { name, description, arg_hint?, request? }");
158
+ }
159
+ only("commands[]", c, ["name", "description", "arg_hint", "request"]);
160
+ if (c.request !== undefined && typeof c.request !== "boolean") {
161
+ throw new ManifestError("`commands[].request` must be true or false");
162
+ }
163
+ const out = { name: c.name, description: c.description };
164
+ if (c.arg_hint !== undefined) {
165
+ out.arg_hint = c.arg_hint;
166
+ }
167
+ if (c.request) {
168
+ out.request = true;
169
+ }
170
+ return out;
171
+ });
172
+ }
173
+ function scheduleList(value) {
174
+ if (value === undefined) {
175
+ return [];
176
+ }
177
+ if (!Array.isArray(value)) {
178
+ throw new ManifestError("`schedules` must be a list of { name, every, offset? }");
179
+ }
180
+ return value.map((s) => {
181
+ if (s === null || typeof s !== "object") {
182
+ throw new ManifestError("`schedules` entries must be objects { name, every, offset? }");
183
+ }
184
+ only("schedules[]", s, ["name", "every", "offset"]);
185
+ return { name: s.name, every: s.every, offset: s.offset ?? 0 };
186
+ });
187
+ }
188
+ const FIELDS = ["name", "version", "description", "triggers", "read", "actions", "state", "egress", "commands", "schedules"];
189
+ /**
190
+ * Check a manifest exactly as the runtime does (`Manifest::from_json` in
191
+ * pollis-app-manifest), in the same order and with the same messages. The
192
+ * input is the manifest as `pollis-app.json` holds it.
193
+ */
194
+ export function validateManifest(json) {
195
+ if (json === null || typeof json !== "object" || Array.isArray(json)) {
196
+ throw new ManifestError("`pollis-app.json` must be an object");
197
+ }
198
+ const m = json;
199
+ only("", m, ["$schema", ...FIELDS]);
200
+ for (const required of ["name", "version"]) {
201
+ if (typeof m[required] !== "string") {
202
+ throw new ManifestError(`\`${required}\` is missing`);
203
+ }
204
+ }
205
+ const read = (m.read ?? {});
206
+ if (typeof read !== "object" || read === null) {
207
+ throw new ManifestError("`read` must be an object");
208
+ }
209
+ only("read", read, ["channels", "history", "events"]);
210
+ const state = (m.state ?? {});
211
+ only("state", state, ["quota"]);
212
+ if (m.description !== undefined && typeof m.description !== "string") {
213
+ throw new ManifestError("`description` must be a string");
214
+ }
215
+ const triggers = list("triggers", m.triggers, TRIGGERS);
216
+ const channels = list("read.channels", read.channels);
217
+ const events = read.events === undefined ? ["created"] : list("read.events", read.events, EVENTS);
218
+ const actions = list("actions", m.actions, ACTIONS);
219
+ const egress = list("egress", m.egress);
220
+ const history = count("read.history", read.history);
221
+ if (history > 0xffffffff) {
222
+ throw new ManifestError("`read.history` is too large");
223
+ }
224
+ const quota = count("state.quota", state.quota);
225
+ const commands = commandList(m.commands);
226
+ const schedules = scheduleList(m.schedules);
227
+ const name = m.name;
228
+ if (!NAME.test(name)) {
229
+ throw new ManifestError(`\`name\` ${JSON.stringify(name)} is not valid: lowercase letters, digits and '-', 1 to 64 characters, starting with a letter or digit`);
230
+ }
231
+ if (m.version.trim() === "") {
232
+ throw new ManifestError("`version` must not be empty");
233
+ }
234
+ for (const c of channels) {
235
+ if (!CHANNEL.test(c)) {
236
+ throw new ManifestError(`\`read.channels\` entry ${JSON.stringify(c)} is not valid: use "#name" or "*"`);
237
+ }
238
+ }
239
+ for (const host of egress) {
240
+ if (!HOST.test(host)) {
241
+ throw new ManifestError(`\`egress\` entry ${JSON.stringify(host)} is not valid: an exact lowercase host name such as "api.example.com", with no scheme, port, path, wildcard or IP address`);
242
+ }
243
+ }
244
+ checkCommands(triggers, commands);
245
+ checkSchedules(triggers, schedules);
246
+ const out = {
247
+ name,
248
+ version: m.version,
249
+ description: m.description ?? "",
250
+ triggers,
251
+ read: { channels, history, events },
252
+ actions,
253
+ state: { quota },
254
+ egress,
255
+ };
256
+ if (commands.length > 0) {
257
+ out.commands = commands;
258
+ }
259
+ if (schedules.length > 0) {
260
+ out.schedules = schedules;
261
+ }
262
+ return out;
263
+ }
264
+ /**
265
+ * Fill in defaults from package.json and the handlers, check that triggers
266
+ * and handlers agree, then check every rule the runtime applies
267
+ * ({@link validateManifest}). Returns the manifest as it will be written.
268
+ * `handlers` are the handler names the App defines.
269
+ */
270
+ export function resolveManifest(manifest, handlers, pkg = {}) {
271
+ if (manifest === null || typeof manifest !== "object") {
272
+ throw new ManifestError("`manifest` must be an object");
273
+ }
274
+ only("", manifest, FIELDS);
275
+ const name = manifest.name ?? nameFromPackage(pkg.name);
276
+ if (!name) {
277
+ throw new ManifestError("`name` is missing: set it in the manifest or in package.json");
278
+ }
279
+ const version = manifest.version ?? pkg.version;
280
+ if (version === undefined) {
281
+ throw new ManifestError("`version` is missing: set it in the manifest or in package.json");
282
+ }
283
+ const defined = TRIGGERS.filter((t) => handlers.includes(HANDLER_FOR[t]));
284
+ let triggers;
285
+ if (manifest.triggers === undefined) {
286
+ triggers = defined;
287
+ }
288
+ else {
289
+ triggers = list("triggers", manifest.triggers, TRIGGERS);
290
+ for (const t of triggers) {
291
+ if (!handlers.includes(HANDLER_FOR[t])) {
292
+ throw new ManifestError(`\`triggers\` has "${t}" but the App has no \`${HANDLER_FOR[t]}\` handler`);
293
+ }
294
+ }
295
+ for (const t of defined) {
296
+ if (!triggers.includes(t)) {
297
+ throw new ManifestError(`\`${HANDLER_FOR[t]}\` would never run: add "${t}" to \`triggers\` (or leave \`triggers\` out to derive it from your handlers)`);
298
+ }
299
+ }
300
+ }
301
+ if (triggers.length === 0) {
302
+ throw new ManifestError("the App has no handlers: define at least one of onMessage, onMention, onCommand, onSchedule, onRequest, onWebhook");
303
+ }
304
+ if (handlers.includes("onCommand") && !(manifest.commands ?? []).some((c) => !c?.request)) {
305
+ throw new ManifestError('`onCommand` needs its commands declared: add `commands: [{ name: "hello", description: "Say hello" }]` to the manifest');
306
+ }
307
+ if (handlers.includes("onSchedule") && (manifest.schedules ?? []).length === 0) {
308
+ throw new ManifestError('`onSchedule` needs `schedules`, e.g. `schedules: [{ name: "daily", every: 86400 }]`');
309
+ }
310
+ const full = {
311
+ name,
312
+ version,
313
+ description: manifest.description ?? pkg.description ?? "",
314
+ triggers,
315
+ read: manifest.read ?? {},
316
+ actions: manifest.actions,
317
+ state: manifest.state ?? {},
318
+ egress: manifest.egress,
319
+ commands: manifest.commands,
320
+ schedules: manifest.schedules,
321
+ };
322
+ return validateManifest(full);
323
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The bridge between an App's handlers and the bot runtime's host functions
3
+ * (`pollis:app/host@0.1.0`). Only the built component loads this module:
4
+ * `pollis app build` generates an entry that calls {@link exportsFor} on the
5
+ * App's default export and exports the six WIT handlers.
6
+ *
7
+ * Host calls are synchronous; the context presents them as promises so App
8
+ * code reads like ordinary async TypeScript. A host refusal becomes a
9
+ * rejected promise ({@link RefusedError}); a handler that throws or rejects
10
+ * makes the job fail, and the runtime then applies none of its queued actions
11
+ * or state writes.
12
+ */
13
+ import type * as wit from "pollis:app/types@0.1.0";
14
+ import { type AppDefinition, type Context } from "./index.js";
15
+ /** The context handed to every handler. */
16
+ export declare function createContext(): Context;
17
+ /** The six WIT exports, each running the App's handler (if any) with a fresh context. */
18
+ export interface Exports {
19
+ onMessage(message: wit.Message): Promise<void>;
20
+ onMention(message: wit.Message): Promise<void>;
21
+ onCommand(command: wit.Command): Promise<void>;
22
+ onSchedule(schedule: wit.Schedule): Promise<void>;
23
+ onRequest(request: wit.Request): Promise<void>;
24
+ onWebhook(webhook: wit.Webhook): Promise<void>;
25
+ }
26
+ export declare function exportsFor(definition: AppDefinition): Exports;
@@ -0,0 +1,238 @@
1
+ /// <reference path="./generated/app.d.ts" />
2
+ /**
3
+ * The bridge between an App's handlers and the bot runtime's host functions
4
+ * (`pollis:app/host@0.1.0`). Only the built component loads this module:
5
+ * `pollis app build` generates an entry that calls {@link exportsFor} on the
6
+ * App's default export and exports the six WIT handlers.
7
+ *
8
+ * Host calls are synchronous; the context presents them as promises so App
9
+ * code reads like ordinary async TypeScript. A host refusal becomes a
10
+ * rejected promise ({@link RefusedError}); a handler that throws or rejects
11
+ * makes the job fail, and the runtime then applies none of its queued actions
12
+ * or state writes.
13
+ */
14
+ import * as host from "pollis:app/host@0.1.0";
15
+ import { RefusedError, } from "./index.js";
16
+ const encoder = new TextEncoder();
17
+ const decoder = new TextDecoder();
18
+ /** The text of an error thrown by a host import or by App code. */
19
+ function errorText(e) {
20
+ if (typeof e === "string") {
21
+ return e;
22
+ }
23
+ if (e && typeof e === "object") {
24
+ const payload = e.payload;
25
+ if (typeof payload === "string") {
26
+ return payload;
27
+ }
28
+ const message = e.message;
29
+ if (typeof message === "string" && message) {
30
+ return message;
31
+ }
32
+ }
33
+ return String(e);
34
+ }
35
+ /** Call a host import that returns `result<T, string>`. */
36
+ function call(fn) {
37
+ try {
38
+ return Promise.resolve(fn());
39
+ }
40
+ catch (e) {
41
+ return Promise.reject(new RefusedError(errorText(e)));
42
+ }
43
+ }
44
+ function ms(value) {
45
+ return value === undefined ? undefined : Number(value);
46
+ }
47
+ function toMessage(m) {
48
+ return {
49
+ id: m.id,
50
+ channel: m.channel,
51
+ author: { id: m.author.id, displayName: m.author.displayName, isBot: m.author.isBot },
52
+ text: m.text,
53
+ attachments: m.attachments.map((a) => ({ name: a.name, mimeType: a.mimeType, size: Number(a.size) })),
54
+ replyTo: m.replyTo,
55
+ thread: m.thread,
56
+ sentAt: Number(m.sentAt),
57
+ editedAt: ms(m.editedAt),
58
+ };
59
+ }
60
+ function idOf(target) {
61
+ return typeof target === "string" ? target : target.id;
62
+ }
63
+ function time(value) {
64
+ if (value === undefined) {
65
+ return undefined;
66
+ }
67
+ return BigInt(Math.floor(value instanceof Date ? value.getTime() : value));
68
+ }
69
+ function bodyBytes(body) {
70
+ if (body === undefined) {
71
+ return undefined;
72
+ }
73
+ if (typeof body === "string") {
74
+ return encoder.encode(body);
75
+ }
76
+ if (body instanceof Uint8Array) {
77
+ return body;
78
+ }
79
+ if (body instanceof ArrayBuffer) {
80
+ return new Uint8Array(body);
81
+ }
82
+ throw new TypeError("ctx.fetch body must be a string, Uint8Array or ArrayBuffer");
83
+ }
84
+ function headerList(headers) {
85
+ if (!headers) {
86
+ return [];
87
+ }
88
+ if (Symbol.iterator in Object(headers)) {
89
+ return Array.from(headers, ([k, v]) => [String(k), String(v)]);
90
+ }
91
+ return Object.entries(headers).map(([k, v]) => [k, String(v)]);
92
+ }
93
+ class Headers {
94
+ #list;
95
+ constructor(list) {
96
+ this.#list = list.map(([k, v]) => [k.toLowerCase(), v]);
97
+ }
98
+ get(name) {
99
+ const n = name.toLowerCase();
100
+ const values = this.#list.filter(([k]) => k === n).map(([, v]) => v);
101
+ return values.length ? values.join(", ") : null;
102
+ }
103
+ has(name) {
104
+ return this.get(name) !== null;
105
+ }
106
+ forEach(fn) {
107
+ for (const [k, v] of this.#list) {
108
+ fn(v, k);
109
+ }
110
+ }
111
+ entries() {
112
+ return this.#list[Symbol.iterator]();
113
+ }
114
+ [Symbol.iterator]() {
115
+ return this.entries();
116
+ }
117
+ }
118
+ class Response {
119
+ status;
120
+ ok;
121
+ headers;
122
+ #body;
123
+ constructor(r) {
124
+ this.status = r.status;
125
+ this.ok = r.status >= 200 && r.status < 300;
126
+ this.headers = new Headers(r.headers);
127
+ this.#body = r.body;
128
+ }
129
+ async text() {
130
+ return decoder.decode(this.#body);
131
+ }
132
+ async json() {
133
+ return JSON.parse(decoder.decode(this.#body));
134
+ }
135
+ async bytes() {
136
+ return this.#body;
137
+ }
138
+ async arrayBuffer() {
139
+ return this.#body.slice().buffer;
140
+ }
141
+ }
142
+ /** The context handed to every handler. */
143
+ export function createContext() {
144
+ return {
145
+ post: (channel, text) => call(() => host.post(channel, text)),
146
+ reply: (to, text) => call(() => host.reply(idOf(to), text)),
147
+ react: (to, emoji) => call(() => host.react(idOf(to), emoji)),
148
+ editOwn: (message, text) => call(() => host.editOwn(idOf(message), text)),
149
+ deleteOwn: (message) => call(() => host.deleteOwn(idOf(message))),
150
+ messages: (query = {}) => call(() => host
151
+ .queryMessages({
152
+ channel: query.channel,
153
+ since: time(query.since),
154
+ until: time(query.until),
155
+ limit: query.limit ?? 50,
156
+ })
157
+ .map(toMessage)),
158
+ state: {
159
+ get: (key) => call(() => host.kvGet(key)),
160
+ getText: (key) => call(() => host.kvGet(key)).then((v) => (v === undefined ? undefined : decoder.decode(v))),
161
+ getJSON: (key) => call(() => host.kvGet(key)).then((v) => (v === undefined ? undefined : JSON.parse(decoder.decode(v)))),
162
+ set: (key, value) => call(() => host.kvSet(key, typeof value === "string" ? encoder.encode(value) : value)),
163
+ setJSON: (key, value) => call(() => host.kvSet(key, encoder.encode(JSON.stringify(value)))),
164
+ delete: (key) => call(() => host.kvDelete(key)),
165
+ },
166
+ fetch: (url, init = {}) => {
167
+ let request;
168
+ try {
169
+ request = {
170
+ method: (init.method ?? "GET").toUpperCase(),
171
+ url: String(url),
172
+ headers: headerList(init.headers),
173
+ body: bodyBytes(init.body),
174
+ };
175
+ }
176
+ catch (e) {
177
+ return Promise.reject(e);
178
+ }
179
+ return call(() => new Response(host.httpFetch(request)));
180
+ },
181
+ log: {
182
+ trace: (text) => host.log("trace", String(text)),
183
+ debug: (text) => host.log("debug", String(text)),
184
+ info: (text) => host.log("info", String(text)),
185
+ warn: (text) => host.log("warn", String(text)),
186
+ error: (text) => host.log("error", String(text)),
187
+ },
188
+ now: () => Number(host.now()),
189
+ };
190
+ }
191
+ /**
192
+ * Run a handler and settle as the WIT export must: resolve for ok, reject
193
+ * with a string for err (the string becomes the job's error).
194
+ */
195
+ async function run(name, handler, arg) {
196
+ if (typeof handler !== "function") {
197
+ throw `the App has no ${name} handler`;
198
+ }
199
+ try {
200
+ await handler(arg, createContext());
201
+ }
202
+ catch (e) {
203
+ throw errorText(e);
204
+ }
205
+ }
206
+ export function exportsFor(definition) {
207
+ const d = definition;
208
+ return {
209
+ onMessage: (m) => run("onMessage", d.onMessage, toMessage(m)),
210
+ onMention: (m) => run("onMention", d.onMention, toMessage(m)),
211
+ onCommand: (c) => {
212
+ const command = { name: c.name, args: c.args, message: toMessage(c.message) };
213
+ return run("onCommand", d.onCommand, command);
214
+ },
215
+ onSchedule: (s) => {
216
+ const schedule = { name: s.name, slot: Number(s.slot) };
217
+ return run("onSchedule", d.onSchedule, schedule);
218
+ },
219
+ onRequest: (r) => {
220
+ const request = {
221
+ id: r.id,
222
+ requester: { id: r.requester.id, displayName: r.requester.displayName, isBot: r.requester.isBot },
223
+ body: r.body,
224
+ };
225
+ return run("onRequest", d.onRequest, request);
226
+ },
227
+ onWebhook: (w) => {
228
+ const webhook = {
229
+ deliveryId: w.deliveryId,
230
+ headers: w.headers,
231
+ body: w.body,
232
+ text: () => decoder.decode(w.body),
233
+ json: () => JSON.parse(decoder.decode(w.body)),
234
+ };
235
+ return run("onWebhook", d.onWebhook, webhook);
236
+ },
237
+ };
238
+ }