@openmuster/muster 0.0.0-stage → 0.3.1-alpha.2
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 +201 -0
- package/README.md +309 -2
- package/dist/args-DHgAmYge.js +7043 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +31 -0
- package/dist/index.d.ts +2138 -0
- package/dist/index.js +1938 -0
- package/dist/inspect/app.js +163 -0
- package/dist/main-A4nHL5oa.js +3941 -0
- package/dist/main-CuIC8iF4.js +6 -0
- package/dist/mcp-GkdeWAnr.js +6 -0
- package/dist/module-CT_R33MB.js +4 -0
- package/dist/module-DOkWwWoU.js +439 -0
- package/dist/skills/board/SKILL.md +214 -0
- package/dist/skills/board/references/build-a-ui.md +63 -0
- package/dist/skills/board/references/claude.md +54 -0
- package/dist/skills/board/references/codex.md +61 -0
- package/dist/skills/board/references/software-factory.md +89 -0
- package/dist/skills/board/references/swarm.md +165 -0
- package/dist/skills/configure-factory/SKILL.md +116 -0
- package/dist/skills/loop-card/SKILL.md +95 -0
- package/dist/steps-ByzmEzLQ.js +3175 -0
- package/docs/01-concepts/01-overview.md +73 -0
- package/docs/01-concepts/02-boards.md +71 -0
- package/docs/01-concepts/03-channels.md +56 -0
- package/docs/01-concepts/04-threads.md +75 -0
- package/docs/01-concepts/05-labels.md +65 -0
- package/docs/01-concepts/06-actors.md +66 -0
- package/docs/01-concepts/07-events.md +126 -0
- package/docs/01-concepts/08-tasks.md +244 -0
- package/docs/01-concepts/09-watchers.md +172 -0
- package/docs/01-concepts/10-schedules.md +39 -0
- package/docs/01-concepts/11-access.md +182 -0
- package/docs/01-concepts/12-files-and-data.md +79 -0
- package/docs/01-concepts/13-budgets.md +35 -0
- package/docs/01-concepts/14-runners.md +102 -0
- package/docs/01-concepts/15-outgoing-webhooks.md +177 -0
- package/docs/01-concepts/16-workflows.md +350 -0
- package/docs/01-concepts/17-board-module.md +122 -0
- package/docs/01-quickstart.md +141 -0
- package/docs/02-sync/01-overview.md +239 -0
- package/docs/02-sync/02-github.md +158 -0
- package/docs/02-sync/03-linear.md +290 -0
- package/docs/02-sync/04-slack.md +232 -0
- package/docs/02-sync/05-notion.md +92 -0
- package/docs/03-guides/01-coding-agents.md +98 -0
- package/docs/03-guides/02-swarm.md +85 -0
- package/docs/03-guides/03-factory.md +216 -0
- package/docs/03-guides/04-inspector.md +53 -0
- package/docs/03-guides/05-running-agents.md +73 -0
- package/docs/03-guides/06-sandboxed-agents.md +441 -0
- package/docs/03-guides/07-build-a-ui.md +61 -0
- package/docs/03-guides/08-ci.md +168 -0
- package/docs/03-guides/09-daemon.md +103 -0
- package/docs/03-guides/10-two-agents.md +76 -0
- package/docs/03-guides/11-person-in-the-loop.md +123 -0
- package/docs/03-guides/12-unattended.md +110 -0
- package/docs/03-guides/13-terminals.md +153 -0
- package/docs/03-guides/14-no-cloud.md +82 -0
- package/docs/03-guides/15-several-boards.md +71 -0
- package/docs/03-guides/16-non-code.md +69 -0
- package/docs/03-guides/17-mcp.md +126 -0
- package/docs/03-guides/18-a-board-on-a-server.md +162 -0
- package/docs/03-guides/19-a-card-queue.md +261 -0
- package/docs/03-guides/20-a-feedback-loop.md +225 -0
- package/docs/03-guides/21-running-the-loop.md +196 -0
- package/docs/04-reference/01-cli.md +166 -0
- package/docs/04-reference/02-handle.md +409 -0
- package/docs/04-reference/03-http.md +157 -0
- package/docs/04-reference/04-events.md +72 -0
- package/docs/04-reference/05-errors.md +221 -0
- package/docs/04-reference/06-conformance.md +52 -0
- package/docs/04-reference/07-porting.md +116 -0
- package/docs/index.md +103 -0
- package/package.json +52 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1938 @@
|
|
|
1
|
+
import { A as file, B as fetchFile, G as SEND_MS, H as refused, M as mint, N as verify, Q as channelPath, R as declared, S as listen, U as sizeOf, V as noteOut, W as withLines, b as createHandler, d as board, it as misuse, j as boardKey, k as boardPath, rt as Failure, w as SANDBOX_ROUTES, z as env } from "./args-DHgAmYge.js";
|
|
2
|
+
import { A as claude, C as boardPolicy, D as agentEnv, F as conformance, M as generic, O as runLocal, P as http, S as applyPolicy, T as installationToken, a as workflowResult, d as workflowsPath, f as e2b, h as vercel, j as codex, k as AGENTS, m as cloudflare, o as fenced, u as loadWorkflows, w as githubApp } from "./steps-ByzmEzLQ.js";
|
|
3
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { basename, dirname, join } from "node:path";
|
|
6
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
|
|
9
|
+
//#region src/watch/command.ts
|
|
10
|
+
const WATCHER_ENV = [
|
|
11
|
+
"PATH",
|
|
12
|
+
"HOME",
|
|
13
|
+
"USER",
|
|
14
|
+
"LOGNAME",
|
|
15
|
+
"SHELL",
|
|
16
|
+
"LANG",
|
|
17
|
+
"LC_ALL",
|
|
18
|
+
"TMPDIR",
|
|
19
|
+
"MUSTER_DIR",
|
|
20
|
+
"MUSTER_BOARD",
|
|
21
|
+
"MUSTER_CONFIG",
|
|
22
|
+
"MUSTER_URL",
|
|
23
|
+
"MUSTER_INSECURE_HTTP"
|
|
24
|
+
];
|
|
25
|
+
/**
|
|
26
|
+
* What a watcher's command starts with: built from nothing, then the few names above. The host holds
|
|
27
|
+
* the platforms' secrets in its own environment, and what it wakes is often an agent reading text a
|
|
28
|
+
* stranger wrote, so nothing else is passed on unless the watcher names it.
|
|
29
|
+
*/
|
|
30
|
+
function watcherEnv(extra, allow = [], from = process.env) {
|
|
31
|
+
const env$1 = {};
|
|
32
|
+
for (const name of [...WATCHER_ENV, ...allow]) if (from[name] !== void 0) env$1[name] = from[name];
|
|
33
|
+
return {
|
|
34
|
+
...env$1,
|
|
35
|
+
...extra
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/** Whether a gate's output says not to wake: its last non-empty line is JSON with `wake: false`. */
|
|
39
|
+
function gateSaysNo(stdout) {
|
|
40
|
+
const last = stdout.split("\n").map((line) => line.trim()).filter(Boolean).at(-1);
|
|
41
|
+
if (!last) return false;
|
|
42
|
+
try {
|
|
43
|
+
return JSON.parse(last).wake === false;
|
|
44
|
+
} catch {
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/** The most of a command's output kept: a gate's answer is its last line. */
|
|
49
|
+
const KEPT = 64 * 1024;
|
|
50
|
+
/**
|
|
51
|
+
* Runs a command in a process group of its own. A gate (`answer`) is read whole: settled once it has
|
|
52
|
+
* exited and its output has closed, so an answer printed by a child it left behind is heard. A command
|
|
53
|
+
* that wakes something (`wake`) writes to this process's output and is settled when it exits: what it
|
|
54
|
+
* started in the background (an agent) lives on, and nothing here waits for it or kills it. Until it is
|
|
55
|
+
* settled, `signal` tells the group to stop, and kills it after `grace`.
|
|
56
|
+
*/
|
|
57
|
+
function run(argv, env$1, signal, grace, mode) {
|
|
58
|
+
return new Promise((resolve$1) => {
|
|
59
|
+
let stdout = "";
|
|
60
|
+
let settled = false;
|
|
61
|
+
const settle = (ended) => {
|
|
62
|
+
if (settled) return;
|
|
63
|
+
settled = true;
|
|
64
|
+
signal.removeEventListener("abort", stop);
|
|
65
|
+
resolve$1({
|
|
66
|
+
...ended,
|
|
67
|
+
stdout
|
|
68
|
+
});
|
|
69
|
+
};
|
|
70
|
+
const child = spawn(argv[0], argv.slice(1), {
|
|
71
|
+
env: env$1,
|
|
72
|
+
stdio: [
|
|
73
|
+
"ignore",
|
|
74
|
+
mode === "answer" ? "pipe" : "inherit",
|
|
75
|
+
"inherit"
|
|
76
|
+
],
|
|
77
|
+
detached: true
|
|
78
|
+
});
|
|
79
|
+
const group = (name) => {
|
|
80
|
+
try {
|
|
81
|
+
if (child.pid !== void 0) process.kill(-child.pid, name);
|
|
82
|
+
} catch {}
|
|
83
|
+
};
|
|
84
|
+
function stop() {
|
|
85
|
+
group("SIGTERM");
|
|
86
|
+
setTimeout(() => group("SIGKILL"), grace).unref();
|
|
87
|
+
}
|
|
88
|
+
child.stdout?.on("data", (chunk) => {
|
|
89
|
+
stdout += chunk.toString();
|
|
90
|
+
if (stdout.length > KEPT) stdout = stdout.slice(-KEPT);
|
|
91
|
+
});
|
|
92
|
+
child.on("error", () => settle({
|
|
93
|
+
code: 127,
|
|
94
|
+
signal: null
|
|
95
|
+
}));
|
|
96
|
+
child.on(mode === "answer" ? "close" : "exit", (code, killed) => settle({
|
|
97
|
+
code,
|
|
98
|
+
signal: killed
|
|
99
|
+
}));
|
|
100
|
+
if (signal.aborted) stop();
|
|
101
|
+
else signal.addEventListener("abort", stop, { once: true });
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* What a command a watcher wakes starts with: nothing of this process's environment but PATH, HOME and
|
|
106
|
+
* the like, the names the watcher passes on, and a pointer to what happened. Never the text: the
|
|
107
|
+
* command reads the thread itself, as the profile it is woken as.
|
|
108
|
+
*/
|
|
109
|
+
function pointer(context) {
|
|
110
|
+
const { event, watcher, board: board$1 } = context;
|
|
111
|
+
const env$1 = {
|
|
112
|
+
MUSTER_WATCHER: watcher.name,
|
|
113
|
+
MUSTER_THREAD: event.thread === null ? "" : String(event.thread),
|
|
114
|
+
MUSTER_CHANNEL: event.channel ?? "",
|
|
115
|
+
MUSTER_EVENT: String(event.seq),
|
|
116
|
+
MUSTER_EVENT_TYPE: event.type,
|
|
117
|
+
MUSTER_ATTEMPT: String(context.attempt)
|
|
118
|
+
};
|
|
119
|
+
if (watcher.as !== null) env$1.MUSTER_PROFILE = watcher.as;
|
|
120
|
+
const where = board$1.backend.where;
|
|
121
|
+
if (board$1.backend.kind === "file" && where !== ":memory:") {
|
|
122
|
+
env$1.MUSTER_DIR = dirname(where);
|
|
123
|
+
env$1.MUSTER_BOARD = basename(where, ".db");
|
|
124
|
+
}
|
|
125
|
+
return env$1;
|
|
126
|
+
}
|
|
127
|
+
const wordsOf = (argv, context) => {
|
|
128
|
+
const words = typeof argv === "function" ? argv(context) : argv;
|
|
129
|
+
if (!Array.isArray(words) || words.length === 0 || !words.every((word) => typeof word === "string")) throw new Error("A command is a list of words, the first the program to run.");
|
|
130
|
+
return words;
|
|
131
|
+
};
|
|
132
|
+
/**
|
|
133
|
+
* A watcher's `run` that starts a command, the way to wake an agent: `command(['./wake.sh'])`, or
|
|
134
|
+
* `command(({ event }) => ['./wake.sh', String(event.thread)])`. It is woken with a pointer in its
|
|
135
|
+
* environment (`MUSTER_THREAD`, `MUSTER_EVENT`, ...) and nothing else of this process's but what `env`
|
|
136
|
+
* names. Exit 0 is delivered; anything else is a failed try. At the watcher's timeout its process group
|
|
137
|
+
* is stopped.
|
|
138
|
+
*/
|
|
139
|
+
function command(argv, options = {}) {
|
|
140
|
+
const grace = options.grace ?? 5e3;
|
|
141
|
+
return async (context) => {
|
|
142
|
+
const env$1 = watcherEnv(pointer(context), options.env ?? []);
|
|
143
|
+
const named = new Set(options.env ?? []);
|
|
144
|
+
const elsewhere = [
|
|
145
|
+
"MUSTER_URL",
|
|
146
|
+
"MUSTER_INSECURE_HTTP",
|
|
147
|
+
...pointer(context).MUSTER_DIR === void 0 ? ["MUSTER_DIR", "MUSTER_BOARD"] : []
|
|
148
|
+
];
|
|
149
|
+
for (const name of elsewhere) if (!named.has(name)) delete env$1[name];
|
|
150
|
+
if (options.gate !== void 0) {
|
|
151
|
+
if (gateSaysNo((await run(wordsOf(options.gate, context), env$1, context.signal, grace, "answer")).stdout)) return;
|
|
152
|
+
}
|
|
153
|
+
const words = wordsOf(argv, context);
|
|
154
|
+
const ended = await run(words, env$1, context.signal, grace, "wake");
|
|
155
|
+
if (ended.code === 0) return;
|
|
156
|
+
const why = ended.code === null ? `killed by ${ended.signal ?? "a signal"}` : `exit ${ended.code}`;
|
|
157
|
+
throw Object.assign(/* @__PURE__ */ new Error(`${words[0]} ended with ${why}`), { why });
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
//#endregion
|
|
162
|
+
//#region src/sync/providers.ts
|
|
163
|
+
const hmac = (secret, body) => createHmac("sha256", secret).update(body).digest("hex");
|
|
164
|
+
const same = (a, b) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
|
|
165
|
+
const bad = () => new Failure("unauthorized", "bad signature");
|
|
166
|
+
const slug = (text) => text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40) || "run";
|
|
167
|
+
const CONTROL = /[\u0000-\u001f\u007f]+/g;
|
|
168
|
+
/** The most labels and assignees a thread is filed under: a message holds 64 labels, and its own come too. */
|
|
169
|
+
const MOST_FILED = 40;
|
|
170
|
+
/**
|
|
171
|
+
* A platform's names (its labels, an item's assignees) as board labels under a prefix:
|
|
172
|
+
* `tag.needs-review=needs review`. The key is the name cut down to what a label key may hold, the prefix
|
|
173
|
+
* included; the value is the name in lowercase, so a filter written once matches however it was typed
|
|
174
|
+
* there. A name with nothing a key can hold makes no label. Two names that make one key are one label,
|
|
175
|
+
* the one that sorts first, so what a thread carries doesn't turn on the order a platform listed them in.
|
|
176
|
+
*/
|
|
177
|
+
function filed(prefix, names) {
|
|
178
|
+
const out = /* @__PURE__ */ new Map();
|
|
179
|
+
for (const name of names.filter((each) => typeof each === "string").sort()) {
|
|
180
|
+
const key = name.toLowerCase().replace(/[^a-z0-9_.]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 64 - prefix.length);
|
|
181
|
+
const value = name.replace(CONTROL, " ").trim().toLowerCase().slice(0, 256);
|
|
182
|
+
if (key && value && !out.has(prefix + key)) out.set(prefix + key, value);
|
|
183
|
+
}
|
|
184
|
+
return [...out];
|
|
185
|
+
}
|
|
186
|
+
/** What an item is filed under, tags before assignees, up to the most a thread takes. */
|
|
187
|
+
const filedUnder = (tags, assignees) => Object.fromEntries([...filed("tag.", tags), ...filed("assignee.", assignees)].slice(0, MOST_FILED));
|
|
188
|
+
async function send(fetcher, url, init) {
|
|
189
|
+
const response = await fetcher(url, {
|
|
190
|
+
signal: AbortSignal.timeout(SEND_MS),
|
|
191
|
+
...init
|
|
192
|
+
});
|
|
193
|
+
const body = await response.json().catch(() => ({}));
|
|
194
|
+
if (!response.ok) throw new Failure(`platform_${response.status}`, `The platform answered ${response.status}.`);
|
|
195
|
+
return body;
|
|
196
|
+
}
|
|
197
|
+
/** GitHub catch-up reads at most this many pages of 100 of each list per repo. */
|
|
198
|
+
const GITHUB_CATCHUP_PAGES = 10;
|
|
199
|
+
/** Past a catch-up's page cap, how many more pages it reads while all of it changed at one time. */
|
|
200
|
+
const CATCHUP_EXTRA_PAGES = 5;
|
|
201
|
+
/** Of several lists cut short, the next catch-up starts where the one read least far got to. */
|
|
202
|
+
const soonest = (cuts) => {
|
|
203
|
+
const first = [...cuts].sort((a, b) => Date.parse(a.resume) - Date.parse(b.resume))[0];
|
|
204
|
+
const skipped = cuts.flatMap((cut) => cut.skipped ? [cut.skipped] : []);
|
|
205
|
+
return {
|
|
206
|
+
resume: first.resume,
|
|
207
|
+
...skipped.length ? { skipped: skipped.sort()[0] } : {}
|
|
208
|
+
};
|
|
209
|
+
};
|
|
210
|
+
const newestOf = (times) => Math.max(...times.filter((time) => !Number.isNaN(time)));
|
|
211
|
+
/**
|
|
212
|
+
* Where the next catch-up starts after one cut short, given when the changes it read were made. It goes back to
|
|
213
|
+
* the newest of them, so others made at that same time are read again, not skipped. Unless that is no later than
|
|
214
|
+
* where this one started: then so many changed at one time that reading them again would never move on, so it
|
|
215
|
+
* goes past that time and says so (`skipped`). A platform whose `since` takes what changed at that time
|
|
216
|
+
* (`inclusive`) has times to the second (`step`).
|
|
217
|
+
*/
|
|
218
|
+
function cutShort(times, since, inclusive, step) {
|
|
219
|
+
const newest = newestOf(times);
|
|
220
|
+
const again = inclusive ? newest : newest - 1;
|
|
221
|
+
if (again > Date.parse(since)) return { resume: new Date(again).toISOString() };
|
|
222
|
+
return {
|
|
223
|
+
resume: new Date(newest + (inclusive ? step : 0)).toISOString(),
|
|
224
|
+
skipped: new Date(newest).toISOString()
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* GitHub: issues, pull requests and their comments come in as threads. Nothing goes back unless a repo mirrors.
|
|
229
|
+
* `token` is one that may comment, needed only where a repo mirrors; `appId` and `appKey` name a GitHub App
|
|
230
|
+
* to comment as instead.
|
|
231
|
+
*/
|
|
232
|
+
const github = (options) => {
|
|
233
|
+
if (options.appId === void 0 !== (options.appKey === void 0)) throw misuse("invalid_sync", "A github sync needs \"appId\" and \"appKey\" together: the App's ID and its private key.");
|
|
234
|
+
return declared("github", options, githubWith, ["appId", "appKey"]);
|
|
235
|
+
};
|
|
236
|
+
/** How long before an App's token runs out a new one is made: no request goes out with one about to end. */
|
|
237
|
+
const APP_TOKEN_MARGIN_MS = 5 * 6e4;
|
|
238
|
+
function githubWith(options) {
|
|
239
|
+
const api = options.api ?? "https://api.github.com";
|
|
240
|
+
let app;
|
|
241
|
+
if (options.appId !== void 0 && options.appKey !== void 0) try {
|
|
242
|
+
app = githubApp({
|
|
243
|
+
GITHUB_APP_ID: options.appId,
|
|
244
|
+
[options.appKey.includes("-----BEGIN") ? "GITHUB_APP_PRIVATE_KEY" : "GITHUB_APP_KEY_FILE"]: options.appKey
|
|
245
|
+
});
|
|
246
|
+
} catch (error) {
|
|
247
|
+
throw new Failure("invalid_config", `A github sync's App can't be used: ${error.message}`, { hint: "\"appId\" is the App's numeric ID, and \"appKey\" its private key or the path to it." });
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* The App's token for each repository, kept until it is about to run out, and asked for once however many
|
|
251
|
+
* requests wait on it. One that couldn't be made is asked for again by the next request.
|
|
252
|
+
*/
|
|
253
|
+
const tokens = /* @__PURE__ */ new Map();
|
|
254
|
+
const mint$1 = (repo, fetcher, now) => {
|
|
255
|
+
const [owner, name] = repo.split("/");
|
|
256
|
+
const to = options.repos[repo];
|
|
257
|
+
const pulls = typeof to === "string" || typeof to === "object" && to.pulls !== void 0;
|
|
258
|
+
const made = installationToken(app, {
|
|
259
|
+
owner,
|
|
260
|
+
name,
|
|
261
|
+
slug: repo
|
|
262
|
+
}, {
|
|
263
|
+
issues: "write",
|
|
264
|
+
metadata: "read",
|
|
265
|
+
...pulls ? { pull_requests: "write" } : {}
|
|
266
|
+
}, {
|
|
267
|
+
api,
|
|
268
|
+
fetch: fetcher,
|
|
269
|
+
now
|
|
270
|
+
});
|
|
271
|
+
tokens.set(repo, made);
|
|
272
|
+
made.catch(() => tokens.get(repo) === made && tokens.delete(repo));
|
|
273
|
+
return made;
|
|
274
|
+
};
|
|
275
|
+
/** What a request to `repo` is signed with: the App's token for it when there is an App, or else `token`. */
|
|
276
|
+
const bearer = async (repo, fetcher) => {
|
|
277
|
+
if (!app) return `Bearer ${options.token}`;
|
|
278
|
+
const now = (options.now ?? Date.now)();
|
|
279
|
+
const held = tokens.get(repo) ?? mint$1(repo, fetcher, now);
|
|
280
|
+
let token = await held;
|
|
281
|
+
if (Date.parse(token.expiresAt) - now < APP_TOKEN_MARGIN_MS) token = await (tokens.get(repo) === held ? mint$1(repo, fetcher, now) : tokens.get(repo));
|
|
282
|
+
return `Bearer ${token.token}`;
|
|
283
|
+
};
|
|
284
|
+
const named = (message, text) => withLines(text, message.attachments.map((file$1) => noteOut(`${file$1.name} (${sizeOf(file$1.size)})`, "GitHub takes no uploads, it is on the board")));
|
|
285
|
+
/**
|
|
286
|
+
* An issue's or a pull request's labels and assignees, as GitHub lists them now. Every event about one
|
|
287
|
+
* carries both whole, so the thread is made to say the same: `owns` is each list the item came with.
|
|
288
|
+
*/
|
|
289
|
+
const filing = (item) => {
|
|
290
|
+
const names = (list, field) => Array.isArray(list) ? list.map((each) => each?.[field]) : [];
|
|
291
|
+
return {
|
|
292
|
+
labels: filedUnder(names(item.labels, "name"), names(item.assignees, "login")),
|
|
293
|
+
owns: [...Array.isArray(item.labels) ? ["tag."] : [], ...Array.isArray(item.assignees) ? ["assignee."] : []]
|
|
294
|
+
};
|
|
295
|
+
};
|
|
296
|
+
/** An issue or pull request as a thread's first message, written by whoever opened it, in the state it is in now. */
|
|
297
|
+
const rootOf = (repo, item, isPull, id) => {
|
|
298
|
+
const thread = `${repo}#${item.number}`;
|
|
299
|
+
const opener = item.user?.login;
|
|
300
|
+
const merged = Boolean(item.merged || item.merged_at || item.pull_request?.merged_at);
|
|
301
|
+
return {
|
|
302
|
+
id,
|
|
303
|
+
author: String(opener ?? "unknown"),
|
|
304
|
+
place: `${repo}|${isPull ? "pulls" : "issues"}`,
|
|
305
|
+
self: options.bot !== void 0 && opener === options.bot,
|
|
306
|
+
kind: "root",
|
|
307
|
+
thread,
|
|
308
|
+
external: thread,
|
|
309
|
+
text: `${item.title ?? ""}\n\n${item.body ?? ""}`.trim(),
|
|
310
|
+
labels: {
|
|
311
|
+
kind: isPull ? "pr" : "issue",
|
|
312
|
+
state: item.state === "closed" ? merged ? "merged" : "closed" : "open",
|
|
313
|
+
ref: thread,
|
|
314
|
+
...filing(item).labels
|
|
315
|
+
}
|
|
316
|
+
};
|
|
317
|
+
};
|
|
318
|
+
const mapping = (place) => {
|
|
319
|
+
const [repo, kind] = place.split("|");
|
|
320
|
+
return {
|
|
321
|
+
repo,
|
|
322
|
+
kind,
|
|
323
|
+
to: options.repos[repo]
|
|
324
|
+
};
|
|
325
|
+
};
|
|
326
|
+
return {
|
|
327
|
+
type: "github",
|
|
328
|
+
verify({ headers, body }) {
|
|
329
|
+
if (!same(headers["x-hub-signature-256"] ?? "", `sha256=${hmac(options.secret, body)}`)) throw bad();
|
|
330
|
+
},
|
|
331
|
+
parse({ headers, body }) {
|
|
332
|
+
const payload = JSON.parse(body);
|
|
333
|
+
const kind = headers["x-github-event"];
|
|
334
|
+
const delivery = `gh:${hmac("id", body).slice(0, 32)}`;
|
|
335
|
+
const repo = payload.repository?.full_name;
|
|
336
|
+
if (!repo) return [];
|
|
337
|
+
const self = options.bot !== void 0 && payload.sender?.login === options.bot;
|
|
338
|
+
const author = String(payload.sender?.login ?? "unknown");
|
|
339
|
+
const item = payload.issue ?? payload.pull_request;
|
|
340
|
+
const isPull = payload.pull_request !== void 0 || payload.issue?.pull_request !== void 0;
|
|
341
|
+
const place = `${repo}|${isPull ? "pulls" : "issues"}`;
|
|
342
|
+
const thread = item ? `${repo}#${item.number}` : "";
|
|
343
|
+
const base = {
|
|
344
|
+
id: delivery,
|
|
345
|
+
author,
|
|
346
|
+
place,
|
|
347
|
+
self
|
|
348
|
+
};
|
|
349
|
+
if ((kind === "issues" || kind === "pull_request") && payload.action === "opened") return [{
|
|
350
|
+
...base,
|
|
351
|
+
kind: "root",
|
|
352
|
+
thread,
|
|
353
|
+
external: thread,
|
|
354
|
+
text: `${item.title}\n\n${item.body ?? ""}`.trim(),
|
|
355
|
+
labels: {
|
|
356
|
+
kind: isPull ? "pr" : "issue",
|
|
357
|
+
state: "open",
|
|
358
|
+
ref: thread,
|
|
359
|
+
...filing(item).labels
|
|
360
|
+
}
|
|
361
|
+
}];
|
|
362
|
+
const withRoot = (events) => {
|
|
363
|
+
if (!item) return events;
|
|
364
|
+
const { author: opener, text, labels } = rootOf(repo, item, isPull, "");
|
|
365
|
+
return events.map((event) => ({
|
|
366
|
+
...event,
|
|
367
|
+
parent: {
|
|
368
|
+
author: opener,
|
|
369
|
+
text: text ?? "",
|
|
370
|
+
labels: labels ?? {}
|
|
371
|
+
}
|
|
372
|
+
}));
|
|
373
|
+
};
|
|
374
|
+
if ((kind === "issues" || kind === "pull_request") && [
|
|
375
|
+
"labeled",
|
|
376
|
+
"unlabeled",
|
|
377
|
+
"assigned",
|
|
378
|
+
"unassigned"
|
|
379
|
+
].includes(payload.action)) return withRoot([{
|
|
380
|
+
...base,
|
|
381
|
+
kind: "labels",
|
|
382
|
+
thread,
|
|
383
|
+
external: delivery,
|
|
384
|
+
...filing(item)
|
|
385
|
+
}]);
|
|
386
|
+
if ((kind === "issues" || kind === "pull_request") && (payload.action === "closed" || payload.action === "reopened")) return [{
|
|
387
|
+
...base,
|
|
388
|
+
kind: "labels",
|
|
389
|
+
thread,
|
|
390
|
+
external: `${delivery}`,
|
|
391
|
+
labels: { state: payload.action === "reopened" ? "open" : item.merged ? "merged" : "closed" }
|
|
392
|
+
}];
|
|
393
|
+
if (kind === "issue_comment" && payload.action === "edited") return [{
|
|
394
|
+
...base,
|
|
395
|
+
kind: "edit",
|
|
396
|
+
thread,
|
|
397
|
+
external: `comment:${payload.comment.id}`,
|
|
398
|
+
text: String(payload.comment.body ?? "")
|
|
399
|
+
}];
|
|
400
|
+
if (kind === "issue_comment" && payload.action === "deleted") return [{
|
|
401
|
+
...base,
|
|
402
|
+
kind: "delete",
|
|
403
|
+
thread,
|
|
404
|
+
external: `comment:${payload.comment.id}`
|
|
405
|
+
}];
|
|
406
|
+
if ((kind === "issues" || kind === "pull_request") && payload.action === "edited") return [{
|
|
407
|
+
...base,
|
|
408
|
+
kind: "edit",
|
|
409
|
+
thread,
|
|
410
|
+
external: thread,
|
|
411
|
+
text: `${item.title}\n\n${item.body ?? ""}`.trim()
|
|
412
|
+
}];
|
|
413
|
+
if (kind === "issue_comment" && payload.action === "created") return withRoot([{
|
|
414
|
+
...base,
|
|
415
|
+
kind: "reply",
|
|
416
|
+
thread,
|
|
417
|
+
external: `comment:${payload.comment.id}`,
|
|
418
|
+
text: String(payload.comment.body ?? "")
|
|
419
|
+
}]);
|
|
420
|
+
if (kind === "pull_request_review" && payload.action === "submitted") {
|
|
421
|
+
const out = [{
|
|
422
|
+
...base,
|
|
423
|
+
kind: "labels",
|
|
424
|
+
thread,
|
|
425
|
+
external: delivery,
|
|
426
|
+
labels: { review: String(payload.review.state).toLowerCase() }
|
|
427
|
+
}];
|
|
428
|
+
if (payload.review.body) out.push({
|
|
429
|
+
...base,
|
|
430
|
+
id: `${delivery}:body`,
|
|
431
|
+
kind: "reply",
|
|
432
|
+
thread,
|
|
433
|
+
external: `review:${payload.review.id}`,
|
|
434
|
+
text: String(payload.review.body)
|
|
435
|
+
});
|
|
436
|
+
return withRoot(out);
|
|
437
|
+
}
|
|
438
|
+
if (kind === "workflow_run" && payload.action === "completed") return (payload.workflow_run.pull_requests ?? []).map((pull, index) => ({
|
|
439
|
+
...base,
|
|
440
|
+
id: `${delivery}:${index}`,
|
|
441
|
+
place: `${repo}|pulls`,
|
|
442
|
+
kind: "labels",
|
|
443
|
+
thread: `${repo}#${pull.number}`,
|
|
444
|
+
external: `${delivery}:${index}`,
|
|
445
|
+
labels: { [`ci.${slug(String(payload.workflow_run.name ?? "run"))}`]: String(payload.workflow_run.conclusion ?? "unknown") }
|
|
446
|
+
}));
|
|
447
|
+
return [];
|
|
448
|
+
},
|
|
449
|
+
channelFor(place) {
|
|
450
|
+
const { kind, to } = mapping(place);
|
|
451
|
+
const channel = typeof to === "string" ? to : to?.[kind];
|
|
452
|
+
return channel ? channelPath(channel) : null;
|
|
453
|
+
},
|
|
454
|
+
placeFor(channel) {
|
|
455
|
+
for (const [repo, to] of Object.entries(options.repos)) if (typeof to === "object" && to.mirror === true && to.issues === channel) return `${repo}|issues`;
|
|
456
|
+
return null;
|
|
457
|
+
},
|
|
458
|
+
async update(external, text, place, fetcher) {
|
|
459
|
+
if (!external.startsWith("comment:")) return;
|
|
460
|
+
const repo = place.split("|")[0];
|
|
461
|
+
await send(fetcher, `${api}/repos/${repo}/issues/comments/${external.slice(8)}`, {
|
|
462
|
+
method: "PATCH",
|
|
463
|
+
headers: {
|
|
464
|
+
authorization: await bearer(repo, fetcher),
|
|
465
|
+
accept: "application/vnd.github+json",
|
|
466
|
+
"content-type": "application/json",
|
|
467
|
+
"user-agent": "muster"
|
|
468
|
+
},
|
|
469
|
+
body: JSON.stringify({ body: text })
|
|
470
|
+
});
|
|
471
|
+
},
|
|
472
|
+
async remove(external, place, fetcher) {
|
|
473
|
+
if (!external.startsWith("comment:")) return;
|
|
474
|
+
const repo = place.split("|")[0];
|
|
475
|
+
await fetcher(`${api}/repos/${repo}/issues/comments/${external.slice(8)}`, {
|
|
476
|
+
method: "DELETE",
|
|
477
|
+
headers: {
|
|
478
|
+
authorization: await bearer(repo, fetcher),
|
|
479
|
+
accept: "application/vnd.github+json",
|
|
480
|
+
"user-agent": "muster"
|
|
481
|
+
}
|
|
482
|
+
});
|
|
483
|
+
},
|
|
484
|
+
async catchUp(since, fetcher) {
|
|
485
|
+
if (!options.token && !app) return [];
|
|
486
|
+
const out = [];
|
|
487
|
+
const cuts = [];
|
|
488
|
+
const when = (list) => list.map((each) => Date.parse(String(each.updated_at)));
|
|
489
|
+
/**
|
|
490
|
+
* A list oldest change first, up to the page cap. Each page after the first is asked for from the newest change
|
|
491
|
+
* read so far, not by its number: something changed during the read moves to the end, not past a page already
|
|
492
|
+
* read. Only a whole page changed in the same second goes by number, and that may run a few pages past the cap.
|
|
493
|
+
*/
|
|
494
|
+
const read = async (repo, path) => {
|
|
495
|
+
const headers = {
|
|
496
|
+
authorization: await bearer(repo, fetcher),
|
|
497
|
+
accept: "application/vnd.github+json",
|
|
498
|
+
"user-agent": "muster"
|
|
499
|
+
};
|
|
500
|
+
const out$1 = [];
|
|
501
|
+
let from = since;
|
|
502
|
+
let page = 1;
|
|
503
|
+
for (let asked = 1; asked <= GITHUB_CATCHUP_PAGES + CATCHUP_EXTRA_PAGES; asked++) {
|
|
504
|
+
if (asked > GITHUB_CATCHUP_PAGES && page === 1) break;
|
|
505
|
+
const got = await send(fetcher, `${api}/repos/${repo}/${path}since=${encodeURIComponent(from)}&sort=updated&direction=asc&per_page=100&page=${page}`, { headers });
|
|
506
|
+
if (!Array.isArray(got)) throw new Failure("platform_refused", "GitHub did not answer with a list.");
|
|
507
|
+
out$1.push(...got);
|
|
508
|
+
if (got.length < 100) return out$1;
|
|
509
|
+
const newest = newestOf(when(got));
|
|
510
|
+
if (!Number.isFinite(newest)) throw new Failure("platform_refused", "GitHub listed changes without when they were made.");
|
|
511
|
+
if (newest > Date.parse(from)) {
|
|
512
|
+
from = new Date(newest).toISOString();
|
|
513
|
+
page = 1;
|
|
514
|
+
} else page++;
|
|
515
|
+
}
|
|
516
|
+
cuts.push(cutShort(when(out$1), since, true, 1e3));
|
|
517
|
+
return out$1;
|
|
518
|
+
};
|
|
519
|
+
for (const repo of Object.keys(options.repos)) {
|
|
520
|
+
const items = await read(repo, "issues?state=all&");
|
|
521
|
+
const parents = /* @__PURE__ */ new Map();
|
|
522
|
+
for (const item of items) {
|
|
523
|
+
const root = rootOf(repo, item, item.pull_request !== void 0, `catchup:issue:${repo}#${item.number}`);
|
|
524
|
+
out.push(root);
|
|
525
|
+
parents.set(String(item.number), {
|
|
526
|
+
author: root.author,
|
|
527
|
+
text: root.text ?? "",
|
|
528
|
+
labels: root.labels ?? {}
|
|
529
|
+
});
|
|
530
|
+
const filedNow = filing(item);
|
|
531
|
+
out.push({
|
|
532
|
+
...root,
|
|
533
|
+
author: "",
|
|
534
|
+
self: false,
|
|
535
|
+
...item.updated_at ? { at: String(item.updated_at) } : {},
|
|
536
|
+
id: `catchup:state:${repo}#${item.number}:${item.updated_at ?? ""}`,
|
|
537
|
+
kind: "labels",
|
|
538
|
+
external: `catchup:state:${repo}#${item.number}:${item.updated_at ?? ""}`,
|
|
539
|
+
labels: {
|
|
540
|
+
state: root.labels.state,
|
|
541
|
+
...filedNow.labels
|
|
542
|
+
},
|
|
543
|
+
owns: filedNow.owns
|
|
544
|
+
});
|
|
545
|
+
}
|
|
546
|
+
const comments = await read(repo, "issues/comments?");
|
|
547
|
+
for (const comment of comments) {
|
|
548
|
+
const number = String(comment.issue_url ?? "").split("/").pop();
|
|
549
|
+
const isPull = String(comment.html_url ?? "").includes("/pull/");
|
|
550
|
+
const parent = parents.get(number ?? "");
|
|
551
|
+
out.push({
|
|
552
|
+
id: `catchup:comment:${comment.id}`,
|
|
553
|
+
author: String(comment.user?.login ?? "unknown"),
|
|
554
|
+
place: `${repo}|${isPull ? "pulls" : "issues"}`,
|
|
555
|
+
self: options.bot !== void 0 && comment.user?.login === options.bot,
|
|
556
|
+
kind: "reply",
|
|
557
|
+
thread: `${repo}#${number}`,
|
|
558
|
+
external: `comment:${comment.id}`,
|
|
559
|
+
text: String(comment.body ?? ""),
|
|
560
|
+
...parent ? { parent } : {}
|
|
561
|
+
});
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
return cuts.length ? {
|
|
565
|
+
events: out,
|
|
566
|
+
...soonest(cuts)
|
|
567
|
+
} : out;
|
|
568
|
+
},
|
|
569
|
+
mirrors(place) {
|
|
570
|
+
const { to } = mapping(place);
|
|
571
|
+
return typeof to === "object" && to.mirror === true && (options.token !== void 0 || app !== void 0);
|
|
572
|
+
},
|
|
573
|
+
async deliver(message, target, fetcher) {
|
|
574
|
+
const headersFor = async (repo$1) => ({
|
|
575
|
+
authorization: await bearer(repo$1, fetcher),
|
|
576
|
+
accept: "application/vnd.github+json",
|
|
577
|
+
"content-type": "application/json",
|
|
578
|
+
"user-agent": "muster"
|
|
579
|
+
});
|
|
580
|
+
if (target.threadExternal === null) {
|
|
581
|
+
const repo$1 = target.place.split("|")[0];
|
|
582
|
+
const headers = await headersFor(repo$1);
|
|
583
|
+
const [title, ...rest] = message.text.split("\n");
|
|
584
|
+
const made = await send(fetcher, `${api}/repos/${repo$1}/issues`, {
|
|
585
|
+
method: "POST",
|
|
586
|
+
headers,
|
|
587
|
+
body: JSON.stringify({
|
|
588
|
+
title: title.slice(0, 250),
|
|
589
|
+
body: named(message, rest.join("\n").trim())
|
|
590
|
+
})
|
|
591
|
+
});
|
|
592
|
+
return {
|
|
593
|
+
external: `${repo$1}#${made.number}`,
|
|
594
|
+
thread: `${repo$1}#${made.number}`,
|
|
595
|
+
labels: {
|
|
596
|
+
kind: "issue",
|
|
597
|
+
state: "open",
|
|
598
|
+
ref: `${repo$1}#${made.number}`
|
|
599
|
+
}
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
const [repo, number] = target.threadExternal.split("#");
|
|
603
|
+
return { external: `comment:${(await send(fetcher, `${api}/repos/${repo}/issues/${number}/comments`, {
|
|
604
|
+
method: "POST",
|
|
605
|
+
headers: await headersFor(repo),
|
|
606
|
+
body: JSON.stringify({ body: named(message, message.text) })
|
|
607
|
+
})).id}` };
|
|
608
|
+
}
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
/** Catch-up reads at most this many pages of each list, of this many each: Linear limits requests and their cost. */
|
|
612
|
+
const LINEAR_CATCHUP_PAGES = 10;
|
|
613
|
+
const LINEAR_CATCHUP_PAGE = 50;
|
|
614
|
+
/** Linear: issues and comments come in as threads, and board replies go back as comments. */
|
|
615
|
+
const linear = (options) => {
|
|
616
|
+
if (options.clientId === void 0 !== (options.clientSecret === void 0)) throw misuse("invalid_sync", "A linear sync needs \"clientId\" and \"clientSecret\" together: the OAuth application's own.");
|
|
617
|
+
return declared("linear", options, linearWith, [
|
|
618
|
+
"clientId",
|
|
619
|
+
"clientSecret",
|
|
620
|
+
"appSecret"
|
|
621
|
+
]);
|
|
622
|
+
};
|
|
623
|
+
/** How often Linear is told an issue is still being worked on: a session with nothing new for 30 minutes goes stale. */
|
|
624
|
+
const LINEAR_WORKING_TTL_MS = 25 * 6e4;
|
|
625
|
+
/**
|
|
626
|
+
* What an app's token may do unless the module says: read what comes in, and write the comments and issues that go
|
|
627
|
+
* back. Anything else that asks for a token for the same app asks with these: a token asked for with other scopes ends
|
|
628
|
+
* the app's earlier ones, the sync's included.
|
|
629
|
+
*/
|
|
630
|
+
const LINEAR_SCOPES = ["read", "write"];
|
|
631
|
+
function linearWith(options) {
|
|
632
|
+
const team = (place) => options.teams[place];
|
|
633
|
+
const api = options.api ?? "https://api.linear.app/graphql";
|
|
634
|
+
const app = options.clientId !== void 0 && options.clientSecret !== void 0 ? {
|
|
635
|
+
id: options.clientId,
|
|
636
|
+
secret: options.clientSecret
|
|
637
|
+
} : void 0;
|
|
638
|
+
/**
|
|
639
|
+
* The app's own user in the workspace, once Linear has said who it is. What an agent session says as it ends
|
|
640
|
+
* is a comment by that user, which the board has no ID for: so with sessions on, a comment by it isn't brought in.
|
|
641
|
+
*/
|
|
642
|
+
let appUser;
|
|
643
|
+
const own = (author) => options.bot !== void 0 && author === options.bot || appUser !== void 0 && author === appUser;
|
|
644
|
+
/** Whether the sync has something to send and read with: a token, or an app to ask for one. */
|
|
645
|
+
const signed = options.token !== void 0 || app !== void 0;
|
|
646
|
+
/**
|
|
647
|
+
* The app's own token: asked for once, kept until it is about to run out (thirty days, and Linear gives no
|
|
648
|
+
* refresh token, so the next one is asked for the same way), and asked for again after one Linear refused.
|
|
649
|
+
*/
|
|
650
|
+
let appToken;
|
|
651
|
+
const askToken = (fetcher) => {
|
|
652
|
+
const now = (options.now ?? Date.now)();
|
|
653
|
+
const asked = send(fetcher, new URL("/oauth/token", api).href, {
|
|
654
|
+
method: "POST",
|
|
655
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
656
|
+
body: new URLSearchParams({
|
|
657
|
+
grant_type: "client_credentials",
|
|
658
|
+
scope: (options.scopes ?? LINEAR_SCOPES).join(","),
|
|
659
|
+
client_id: app.id,
|
|
660
|
+
client_secret: app.secret
|
|
661
|
+
}).toString()
|
|
662
|
+
}).then((answer) => {
|
|
663
|
+
if (typeof answer?.access_token !== "string" || !answer.access_token) throw new Failure("platform_refused", `Linear made no token for the app${typeof answer?.error_description === "string" ? `: ${answer.error_description.slice(0, 200)}` : ""}.`);
|
|
664
|
+
return {
|
|
665
|
+
token: answer.access_token,
|
|
666
|
+
until: now + (Number(answer.expires_in) || 0) * 1e3
|
|
667
|
+
};
|
|
668
|
+
});
|
|
669
|
+
appToken = asked;
|
|
670
|
+
asked.catch(() => appToken === asked && (appToken = void 0));
|
|
671
|
+
return asked;
|
|
672
|
+
};
|
|
673
|
+
/**
|
|
674
|
+
* What an issue is filed under, as the webhook says it: its labels, its assignee, its priority and its
|
|
675
|
+
* project. Linear leaves an empty assignee or project out rather than sending `null`, so one that is
|
|
676
|
+
* missing with no ID either is empty, and one named by its ID alone is left as it was. Its labels are
|
|
677
|
+
* the whole list when the payload has one, and none when it lists no label IDs.
|
|
678
|
+
*
|
|
679
|
+
* How a payload is read here, and the profile-handle pattern, follow `propertiesOf` and `handleOf` in
|
|
680
|
+
* @vercel/board's `sync/linear.ts` (Apache-2.0, Copyright Vercel, Inc.).
|
|
681
|
+
*/
|
|
682
|
+
const filing = (data) => {
|
|
683
|
+
const labels = {};
|
|
684
|
+
const unset = [];
|
|
685
|
+
const owns = [];
|
|
686
|
+
const tags = Array.isArray(data.labels) ? data.labels.map((each) => each?.name) : Array.isArray(data.labelIds) && data.labelIds.length === 0 ? [] : null;
|
|
687
|
+
if (tags) owns.push("tag.");
|
|
688
|
+
const handle = data.assignee ? /\/profiles\/([^/?#]+)/.exec(String(data.assignee.url ?? ""))?.[1] ?? data.assignee.displayName ?? data.assignee.name : null;
|
|
689
|
+
if (data.assignee || !data.assigneeId) owns.push("assignee.");
|
|
690
|
+
Object.assign(labels, filedUnder(tags ?? [], handle ? [handle] : []));
|
|
691
|
+
const priority = [
|
|
692
|
+
"",
|
|
693
|
+
"urgent",
|
|
694
|
+
"high",
|
|
695
|
+
"medium",
|
|
696
|
+
"low"
|
|
697
|
+
][Number(data.priority)];
|
|
698
|
+
if (priority) labels.priority = priority;
|
|
699
|
+
else if (data.priority === 0) unset.push("priority");
|
|
700
|
+
const project = typeof data.project?.name === "string" ? data.project.name.replace(CONTROL, " ").trim().toLowerCase().slice(0, 256) : "";
|
|
701
|
+
if (project) labels.project = project;
|
|
702
|
+
else if (!data.project && !data.projectId) unset.push("project");
|
|
703
|
+
return {
|
|
704
|
+
labels,
|
|
705
|
+
unset,
|
|
706
|
+
owns
|
|
707
|
+
};
|
|
708
|
+
};
|
|
709
|
+
/** An issue as the API lists it, in the shape its webhook has: its labels are a list there, not a page of one. */
|
|
710
|
+
const listed = (issue) => Array.isArray(issue.labels?.nodes) ? {
|
|
711
|
+
...issue,
|
|
712
|
+
labels: issue.labels.nodes
|
|
713
|
+
} : issue;
|
|
714
|
+
let organization;
|
|
715
|
+
const authorization = async (fetcher) => {
|
|
716
|
+
if (app) {
|
|
717
|
+
const held = appToken;
|
|
718
|
+
let got = await (held ?? askToken(fetcher));
|
|
719
|
+
if (got.until - (options.now ?? Date.now)() < APP_TOKEN_MARGIN_MS) got = await (appToken === held || !appToken ? askToken(fetcher) : appToken);
|
|
720
|
+
return `Bearer ${got.token}`;
|
|
721
|
+
}
|
|
722
|
+
const token = options.token;
|
|
723
|
+
return token.startsWith("lin_api_") || /^bearer /i.test(token) ? token : `Bearer ${token}`;
|
|
724
|
+
};
|
|
725
|
+
/** Files uploaded to Linear, as the markdown links its text carries. Links anywhere else are only text. */
|
|
726
|
+
const uploads = (text) => {
|
|
727
|
+
const found = [...String(text ?? "").matchAll(/!?\[([^\]\n]*)\]\((https:\/\/uploads\.linear\.app\/[^\s)]+)\)/g)].map((match) => ({
|
|
728
|
+
url: match[2],
|
|
729
|
+
name: match[1] || match[2].split("/").pop()
|
|
730
|
+
}));
|
|
731
|
+
const once = found.filter((file$1, index) => found.findIndex((other) => other.url === file$1.url) === index);
|
|
732
|
+
return once.length ? once : void 0;
|
|
733
|
+
};
|
|
734
|
+
const postAs = async (query, variables, fetcher) => {
|
|
735
|
+
const ask = async () => send(fetcher, api, {
|
|
736
|
+
method: "POST",
|
|
737
|
+
headers: {
|
|
738
|
+
authorization: await authorization(fetcher),
|
|
739
|
+
"content-type": "application/json"
|
|
740
|
+
},
|
|
741
|
+
body: JSON.stringify({
|
|
742
|
+
query,
|
|
743
|
+
variables
|
|
744
|
+
})
|
|
745
|
+
});
|
|
746
|
+
try {
|
|
747
|
+
return await ask();
|
|
748
|
+
} catch (error) {
|
|
749
|
+
if (!app || !(error instanceof Failure) || error.reason !== "platform_401") throw error;
|
|
750
|
+
appToken = void 0;
|
|
751
|
+
return ask();
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
/** An issue as a thread's first message, as its webhook would have brought it, in the state it is in now. */
|
|
755
|
+
const rootOf = (issue, id) => {
|
|
756
|
+
const thread = `issue:${issue.id}`;
|
|
757
|
+
const author = String(issue.creator?.id ?? "unknown");
|
|
758
|
+
return {
|
|
759
|
+
id,
|
|
760
|
+
author,
|
|
761
|
+
place: String(issue.team?.key ?? ""),
|
|
762
|
+
self: own(author),
|
|
763
|
+
kind: "root",
|
|
764
|
+
thread,
|
|
765
|
+
external: thread,
|
|
766
|
+
text: `${issue.title ?? ""}\n\n${issue.description ?? ""}`.trim(),
|
|
767
|
+
labels: {
|
|
768
|
+
kind: "issue",
|
|
769
|
+
ref: String(issue.identifier ?? ""),
|
|
770
|
+
...issue.state?.name ? { state: slug(String(issue.state.name)) } : {},
|
|
771
|
+
...filing(listed(issue)).labels
|
|
772
|
+
},
|
|
773
|
+
...uploads(issue.description) ? { files: uploads(issue.description) } : {}
|
|
774
|
+
};
|
|
775
|
+
};
|
|
776
|
+
return {
|
|
777
|
+
type: "linear",
|
|
778
|
+
verify({ headers, body }) {
|
|
779
|
+
const signature = headers["linear-signature"] ?? "";
|
|
780
|
+
if (!same(signature, hmac(options.secret, body)) && !(options.appSecret !== void 0 && same(signature, hmac(options.appSecret, body)))) throw bad();
|
|
781
|
+
},
|
|
782
|
+
...options.agent && app ? {
|
|
783
|
+
workingTtl: LINEAR_WORKING_TTL_MS,
|
|
784
|
+
async working(target, step, now, fetcher) {
|
|
785
|
+
const kept = now.state ?? {};
|
|
786
|
+
if (typeof kept.user === "string") appUser = kept.user;
|
|
787
|
+
if (appUser === void 0) {
|
|
788
|
+
const who = (await postAs("{ viewer { id } }", void 0, fetcher))?.data?.viewer?.id;
|
|
789
|
+
if (typeof who === "string" && who) appUser = who;
|
|
790
|
+
}
|
|
791
|
+
const said = async (session$1) => {
|
|
792
|
+
return (await postAs("mutation($input: AgentActivityCreateInput!) { agentActivityCreate(input: $input) { success } }", { input: {
|
|
793
|
+
agentSessionId: session$1,
|
|
794
|
+
content: {
|
|
795
|
+
type: step === "end" ? "response" : "thought",
|
|
796
|
+
body: now.text
|
|
797
|
+
},
|
|
798
|
+
...step === "end" ? {} : { ephemeral: true }
|
|
799
|
+
} }, fetcher))?.data?.agentActivityCreate?.success === true;
|
|
800
|
+
};
|
|
801
|
+
const state = (session$1) => ({
|
|
802
|
+
...session$1 ? { session: session$1 } : {},
|
|
803
|
+
...appUser ? { user: appUser } : {}
|
|
804
|
+
});
|
|
805
|
+
let session = typeof kept.session === "string" ? kept.session : void 0;
|
|
806
|
+
if (session && await said(session)) return state(session);
|
|
807
|
+
if (step === "end" && !session) return state();
|
|
808
|
+
if (session && step !== "start") throw new Failure("platform_refused", "Linear did not take the session's activity.");
|
|
809
|
+
const opened = await postAs("mutation($input: AgentSessionCreateOnIssue!) { agentSessionCreateOnIssue(input: $input) { success agentSession { id } } }", { input: { issueId: target.threadExternal.replace(/^issue:/, "") } }, fetcher);
|
|
810
|
+
session = opened?.data?.agentSessionCreateOnIssue?.agentSession?.id;
|
|
811
|
+
if (typeof session !== "string" || !session) {
|
|
812
|
+
const why = opened?.errors?.[0]?.extensions?.userPresentableMessage ?? opened?.errors?.[0]?.message;
|
|
813
|
+
throw new Failure("platform_refused", `Linear opened no agent session${typeof why === "string" ? `: ${why.slice(0, 200)}` : "."}`);
|
|
814
|
+
}
|
|
815
|
+
if (!await said(session)) throw new Failure("platform_refused", "Linear did not take the session's activity.");
|
|
816
|
+
return state(session);
|
|
817
|
+
}
|
|
818
|
+
} : {},
|
|
819
|
+
parse({ headers, body }) {
|
|
820
|
+
if (!same(headers["linear-signature"] ?? "", hmac(options.secret, body))) return [];
|
|
821
|
+
const payload = JSON.parse(body);
|
|
822
|
+
const data = payload.data ?? {};
|
|
823
|
+
const delivery = `lin:${hmac("id", body).slice(0, 32)}`;
|
|
824
|
+
const author = String(data.userId ?? data.user?.id ?? payload.actor?.id ?? "unknown");
|
|
825
|
+
const self = own(author);
|
|
826
|
+
const updated = typeof data.updatedAt === "string" ? { updated: data.updatedAt } : {};
|
|
827
|
+
if (payload.type === "Issue" && payload.action === "create") {
|
|
828
|
+
const thread = `issue:${data.id}`;
|
|
829
|
+
return [{
|
|
830
|
+
id: delivery,
|
|
831
|
+
author: String(data.creatorId ?? author),
|
|
832
|
+
place: String(data.team?.key ?? ""),
|
|
833
|
+
self,
|
|
834
|
+
kind: "root",
|
|
835
|
+
thread,
|
|
836
|
+
external: thread,
|
|
837
|
+
text: `${data.title}\n\n${data.description ?? ""}`.trim(),
|
|
838
|
+
labels: {
|
|
839
|
+
kind: "issue",
|
|
840
|
+
ref: String(data.identifier ?? ""),
|
|
841
|
+
...data.state?.name ? { state: slug(String(data.state.name)) } : {},
|
|
842
|
+
...filing(data).labels
|
|
843
|
+
},
|
|
844
|
+
...uploads(data.description) ? { files: uploads(data.description) } : {}
|
|
845
|
+
}];
|
|
846
|
+
}
|
|
847
|
+
if (payload.type === "Issue" && payload.action === "update") {
|
|
848
|
+
const filed$1 = filing(data);
|
|
849
|
+
const opener = typeof data.title === "string" ? rootOf({
|
|
850
|
+
...data,
|
|
851
|
+
creator: data.creator ?? (data.creatorId ? { id: data.creatorId } : void 0)
|
|
852
|
+
}, "") : null;
|
|
853
|
+
const parent = opener ? { parent: {
|
|
854
|
+
author: opener.author,
|
|
855
|
+
text: opener.text ?? "",
|
|
856
|
+
labels: opener.labels ?? {}
|
|
857
|
+
} } : {};
|
|
858
|
+
return [{
|
|
859
|
+
id: delivery,
|
|
860
|
+
author,
|
|
861
|
+
place: String(data.team?.key ?? ""),
|
|
862
|
+
self,
|
|
863
|
+
kind: "labels",
|
|
864
|
+
thread: `issue:${data.id}`,
|
|
865
|
+
external: delivery,
|
|
866
|
+
...filed$1,
|
|
867
|
+
labels: {
|
|
868
|
+
...data.state?.name ? { state: slug(String(data.state.name)) } : {},
|
|
869
|
+
...filed$1.labels
|
|
870
|
+
},
|
|
871
|
+
...parent,
|
|
872
|
+
...updated
|
|
873
|
+
}];
|
|
874
|
+
}
|
|
875
|
+
if (payload.type === "Comment" && (payload.action === "update" || payload.action === "remove")) return [{
|
|
876
|
+
id: delivery,
|
|
877
|
+
author,
|
|
878
|
+
place: String(data.issue?.team?.key ?? data.team?.key ?? ""),
|
|
879
|
+
self,
|
|
880
|
+
kind: payload.action === "remove" ? "delete" : "edit",
|
|
881
|
+
thread: `issue:${data.issueId ?? data.issue?.id}`,
|
|
882
|
+
external: `comment:${data.id}`,
|
|
883
|
+
...payload.action === "update" ? {
|
|
884
|
+
text: String(data.body ?? ""),
|
|
885
|
+
...updated
|
|
886
|
+
} : {}
|
|
887
|
+
}];
|
|
888
|
+
if (payload.type === "Comment" && payload.action === "create") {
|
|
889
|
+
const issue = data.issue;
|
|
890
|
+
const parent = typeof issue?.title === "string" ? { parent: {
|
|
891
|
+
author: "",
|
|
892
|
+
text: issue.title.trim(),
|
|
893
|
+
labels: {
|
|
894
|
+
kind: "issue",
|
|
895
|
+
...issue.identifier ? { ref: String(issue.identifier) } : {}
|
|
896
|
+
}
|
|
897
|
+
} } : {};
|
|
898
|
+
return [{
|
|
899
|
+
id: delivery,
|
|
900
|
+
author,
|
|
901
|
+
place: String(data.issue?.team?.key ?? data.team?.key ?? ""),
|
|
902
|
+
self,
|
|
903
|
+
kind: "reply",
|
|
904
|
+
thread: `issue:${data.issueId ?? data.issue?.id}`,
|
|
905
|
+
external: `comment:${data.id}`,
|
|
906
|
+
text: String(data.body ?? ""),
|
|
907
|
+
...uploads(data.body) ? { files: uploads(data.body) } : {},
|
|
908
|
+
...parent,
|
|
909
|
+
...updated
|
|
910
|
+
}];
|
|
911
|
+
}
|
|
912
|
+
return [];
|
|
913
|
+
},
|
|
914
|
+
channelFor(place) {
|
|
915
|
+
const to = team(place);
|
|
916
|
+
const channel = typeof to === "string" ? to : to?.channel;
|
|
917
|
+
return channel ? channelPath(channel) : null;
|
|
918
|
+
},
|
|
919
|
+
placeFor(channel) {
|
|
920
|
+
for (const [key, to] of Object.entries(options.teams)) if ((typeof to === "string" ? to : to.channel) === channel) return key;
|
|
921
|
+
return null;
|
|
922
|
+
},
|
|
923
|
+
mirrors(place) {
|
|
924
|
+
const to = team(place);
|
|
925
|
+
return signed && to !== void 0 && !(typeof to === "object" && to.mirror === false);
|
|
926
|
+
},
|
|
927
|
+
async download(file$1, fetcher, limit) {
|
|
928
|
+
if (!signed) throw refused("no token to fetch it with");
|
|
929
|
+
organization ??= postAs("{ organization { id } }", void 0, fetcher).then((answer) => {
|
|
930
|
+
const id = answer?.data?.organization?.id;
|
|
931
|
+
if (typeof id !== "string" || !id) throw new Failure("platform_refused", "Linear did not say which workspace the key is for.");
|
|
932
|
+
return id;
|
|
933
|
+
});
|
|
934
|
+
const workspace = await organization.catch((error) => {
|
|
935
|
+
organization = void 0;
|
|
936
|
+
throw error;
|
|
937
|
+
});
|
|
938
|
+
if ((URL.canParse(file$1.url) ? new URL(file$1.url).pathname.split("/")[1] : void 0) !== workspace) throw refused("not an upload of this board's Linear workspace");
|
|
939
|
+
return fetchFile(fetcher, file$1.url, {
|
|
940
|
+
hosts: ["uploads.linear.app"],
|
|
941
|
+
headers: { authorization: await authorization(fetcher) },
|
|
942
|
+
limit
|
|
943
|
+
});
|
|
944
|
+
},
|
|
945
|
+
async catchUp(since, fetcher) {
|
|
946
|
+
if (!signed) return [];
|
|
947
|
+
const keys = Object.keys(options.teams);
|
|
948
|
+
if (keys.length === 0) return [];
|
|
949
|
+
const refused$1 = (field, answer) => new Failure("platform_refused", `Linear did not list ${field}: ${String(answer?.errors?.[0]?.message ?? "no data").slice(0, 200)}`);
|
|
950
|
+
/**
|
|
951
|
+
* Reads a list oldest change first, up to the page cap. A call that fails throws, and the board asks again
|
|
952
|
+
* from the same point. Issues sort that way; comments can't be sorted, and Linear lists them newest first,
|
|
953
|
+
* so they are read from the end backwards. Cut short, it says where the next catch-up starts: the newest
|
|
954
|
+
* change it read, less a millisecond, so one made in that same millisecond is read again, not skipped.
|
|
955
|
+
*/
|
|
956
|
+
const read = async (field, nodes, filter) => {
|
|
957
|
+
const type = field === "issues" ? "IssueFilter" : "CommentFilter";
|
|
958
|
+
const list = async (variables, args, page) => {
|
|
959
|
+
const answer = await postAs(`query($filter: ${type}, $cursor: String) { ${field}(filter: $filter, ${args}) { nodes { ${nodes} } pageInfo { ${page} } } }`, variables, fetcher);
|
|
960
|
+
const got = answer?.data?.[field];
|
|
961
|
+
if (!got || !Array.isArray(got.nodes)) throw refused$1(field, answer);
|
|
962
|
+
return got;
|
|
963
|
+
};
|
|
964
|
+
const out$1 = [];
|
|
965
|
+
let cursor = null;
|
|
966
|
+
let more = false;
|
|
967
|
+
const when = (list$1) => list$1.map((node) => Date.parse(String(node.updatedAt)));
|
|
968
|
+
const from = Date.parse(filter.updatedAt.gt);
|
|
969
|
+
for (let page = 0; page < LINEAR_CATCHUP_PAGES + CATCHUP_EXTRA_PAGES; page++) {
|
|
970
|
+
if (page >= LINEAR_CATCHUP_PAGES && newestOf(when(out$1)) - 1 > from) break;
|
|
971
|
+
const got = field === "issues" ? await list({
|
|
972
|
+
filter,
|
|
973
|
+
cursor
|
|
974
|
+
}, `first: ${LINEAR_CATCHUP_PAGE}, after: $cursor, sort: [{ updatedAt: { order: Ascending } }]`, "hasNextPage endCursor") : await list({
|
|
975
|
+
filter,
|
|
976
|
+
cursor
|
|
977
|
+
}, `last: ${LINEAR_CATCHUP_PAGE}, before: $cursor, orderBy: updatedAt`, "hasPreviousPage startCursor");
|
|
978
|
+
out$1.push(...got.nodes);
|
|
979
|
+
const next = field === "issues" ? [got.pageInfo?.hasNextPage, got.pageInfo?.endCursor] : [got.pageInfo?.hasPreviousPage, got.pageInfo?.startCursor];
|
|
980
|
+
more = Boolean(next[0] && next[1]);
|
|
981
|
+
if (!more) break;
|
|
982
|
+
cursor = String(next[1]);
|
|
983
|
+
}
|
|
984
|
+
if (!more || out$1.length === 0) return { nodes: out$1 };
|
|
985
|
+
const times = out$1.map((node) => Date.parse(String(node.updatedAt))).filter((time) => !Number.isNaN(time));
|
|
986
|
+
if (times.length !== out$1.length) throw new Failure("platform_refused", `Linear listed ${field} without when they changed.`);
|
|
987
|
+
if ((await list({
|
|
988
|
+
filter: {
|
|
989
|
+
...filter,
|
|
990
|
+
updatedAt: {
|
|
991
|
+
gt: filter.updatedAt.gt,
|
|
992
|
+
lt: new Date(Math.min(...times)).toISOString()
|
|
993
|
+
}
|
|
994
|
+
},
|
|
995
|
+
cursor: null
|
|
996
|
+
}, "first: 1", "hasNextPage")).nodes.length > 0) throw new Failure("platform_refused", `Linear did not list ${field} oldest first.`);
|
|
997
|
+
return {
|
|
998
|
+
nodes: out$1,
|
|
999
|
+
cut: cutShort(times, filter.updatedAt.gt, false, 0)
|
|
1000
|
+
};
|
|
1001
|
+
};
|
|
1002
|
+
const issueFields = "id identifier title description creator { id } team { key } state { name } priority assignee { id name displayName url } project { name } labels { nodes { name } } updatedAt";
|
|
1003
|
+
const changed = { updatedAt: { gt: since } };
|
|
1004
|
+
const issues = await read("issues", issueFields, {
|
|
1005
|
+
...changed,
|
|
1006
|
+
team: { key: { in: keys } }
|
|
1007
|
+
});
|
|
1008
|
+
const comments = await read("comments", `id body updatedAt user { id } issue { ${issueFields} }`, {
|
|
1009
|
+
...changed,
|
|
1010
|
+
issue: { team: { key: { in: keys } } }
|
|
1011
|
+
});
|
|
1012
|
+
const out = [];
|
|
1013
|
+
for (const issue of issues.nodes) {
|
|
1014
|
+
const root = rootOf(issue, `catchup:issue:${issue.id}`);
|
|
1015
|
+
out.push(root);
|
|
1016
|
+
if (root.labels?.state) {
|
|
1017
|
+
const filedNow = filing(listed(issue));
|
|
1018
|
+
out.push({
|
|
1019
|
+
...root,
|
|
1020
|
+
id: `catchup:state:${issue.id}:${issue.updatedAt ?? ""}`,
|
|
1021
|
+
author: "",
|
|
1022
|
+
self: false,
|
|
1023
|
+
...issue.updatedAt ? {
|
|
1024
|
+
at: String(issue.updatedAt),
|
|
1025
|
+
updated: String(issue.updatedAt)
|
|
1026
|
+
} : {},
|
|
1027
|
+
kind: "labels",
|
|
1028
|
+
external: `catchup:state:${issue.id}:${issue.updatedAt ?? ""}`,
|
|
1029
|
+
...filedNow,
|
|
1030
|
+
labels: {
|
|
1031
|
+
state: root.labels.state,
|
|
1032
|
+
...filedNow.labels
|
|
1033
|
+
}
|
|
1034
|
+
});
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
for (const comment of comments.nodes) {
|
|
1038
|
+
if (!comment.issue?.id) continue;
|
|
1039
|
+
const { author, text, labels, place } = rootOf(comment.issue, "");
|
|
1040
|
+
const by = String(comment.user?.id ?? "unknown");
|
|
1041
|
+
out.push({
|
|
1042
|
+
id: `catchup:comment:${comment.id}`,
|
|
1043
|
+
author: by,
|
|
1044
|
+
place,
|
|
1045
|
+
self: own(by),
|
|
1046
|
+
kind: "reply",
|
|
1047
|
+
thread: `issue:${comment.issue.id}`,
|
|
1048
|
+
external: `comment:${comment.id}`,
|
|
1049
|
+
text: String(comment.body ?? ""),
|
|
1050
|
+
parent: {
|
|
1051
|
+
author,
|
|
1052
|
+
text: text ?? "",
|
|
1053
|
+
labels: labels ?? {}
|
|
1054
|
+
},
|
|
1055
|
+
...uploads(comment.body) ? { files: uploads(comment.body) } : {},
|
|
1056
|
+
...comment.updatedAt ? { updated: String(comment.updatedAt) } : {}
|
|
1057
|
+
});
|
|
1058
|
+
}
|
|
1059
|
+
const cuts = [issues.cut, comments.cut].filter((cut) => cut !== void 0);
|
|
1060
|
+
return cuts.length ? {
|
|
1061
|
+
events: out,
|
|
1062
|
+
...soonest(cuts)
|
|
1063
|
+
} : out;
|
|
1064
|
+
},
|
|
1065
|
+
async deliver(message, target, fetcher, read) {
|
|
1066
|
+
const post = (query, variables) => postAs(query, variables, fetcher);
|
|
1067
|
+
const lines = [];
|
|
1068
|
+
for (const file$1 of message.attachments) {
|
|
1069
|
+
const bytes = read(file$1.id);
|
|
1070
|
+
if (!bytes) {
|
|
1071
|
+
lines.push(noteOut(file$1.name, "the board no longer has it"));
|
|
1072
|
+
continue;
|
|
1073
|
+
}
|
|
1074
|
+
try {
|
|
1075
|
+
const upload = (await post("mutation($type: String!, $name: String!, $size: Int!) { fileUpload(contentType: $type, filename: $name, size: $size) { success uploadFile { uploadUrl assetUrl headers { key value } } } }", {
|
|
1076
|
+
type: file$1.type,
|
|
1077
|
+
name: file$1.name,
|
|
1078
|
+
size: bytes.length
|
|
1079
|
+
}))?.data?.fileUpload?.uploadFile;
|
|
1080
|
+
const to = URL.canParse(String(upload?.uploadUrl)) ? new URL(String(upload.uploadUrl)) : null;
|
|
1081
|
+
if (!to || to.protocol !== "https:" || to.hostname !== "storage.googleapis.com" || to.port !== "" || to.username !== "" || !String(upload.assetUrl).startsWith("https://uploads.linear.app/")) throw new Failure("platform_refused", "Linear gave no upload URL.");
|
|
1082
|
+
const headers = {
|
|
1083
|
+
"content-type": file$1.type,
|
|
1084
|
+
"cache-control": "public, max-age=31536000"
|
|
1085
|
+
};
|
|
1086
|
+
for (const { key, value } of upload.headers ?? []) if (/^(x-goog-[a-z0-9-]+|content-disposition)$/i.test(String(key))) headers[String(key).toLowerCase()] = String(value);
|
|
1087
|
+
const put = await fetcher(to.href, {
|
|
1088
|
+
method: "PUT",
|
|
1089
|
+
headers,
|
|
1090
|
+
body: new Uint8Array(bytes),
|
|
1091
|
+
redirect: "manual",
|
|
1092
|
+
signal: AbortSignal.timeout(SEND_MS)
|
|
1093
|
+
});
|
|
1094
|
+
if (!put.ok) throw new Failure(`platform_${put.status}`, `Linear's storage answered ${put.status}.`);
|
|
1095
|
+
lines.push(`${file$1.type.startsWith("image/") ? "!" : ""}[${file$1.name.replace(/[[\]\n]/g, "_")}](${upload.assetUrl})`);
|
|
1096
|
+
} catch {
|
|
1097
|
+
lines.push(noteOut(file$1.name, "Linear did not take it"));
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
if (target.threadExternal === null) {
|
|
1101
|
+
const teamId = (await post("query($key: String!) { teams(filter: { key: { eq: $key } }) { nodes { id } } }", { key: target.place }))?.data?.teams?.nodes?.[0]?.id;
|
|
1102
|
+
if (!teamId) throw new Failure("platform_refused", `Linear has no team "${target.place}".`);
|
|
1103
|
+
const [title, ...rest] = message.text.split("\n");
|
|
1104
|
+
const created = (await post("mutation($input: IssueCreateInput!) { issueCreate(input: $input) { success issue { id identifier state { name } } } }", { input: {
|
|
1105
|
+
teamId,
|
|
1106
|
+
title: title.slice(0, 250),
|
|
1107
|
+
description: withLines(rest.join("\n").trim(), lines)
|
|
1108
|
+
} }))?.data?.issueCreate?.issue;
|
|
1109
|
+
const issue = created?.id;
|
|
1110
|
+
if (!issue) throw new Failure("platform_refused", "Linear did not make the issue.");
|
|
1111
|
+
const labels = {
|
|
1112
|
+
kind: "issue",
|
|
1113
|
+
...created.identifier ? { ref: String(created.identifier) } : {},
|
|
1114
|
+
...created.state?.name ? { state: slug(String(created.state.name)) } : {}
|
|
1115
|
+
};
|
|
1116
|
+
return {
|
|
1117
|
+
external: `issue:${issue}`,
|
|
1118
|
+
thread: `issue:${issue}`,
|
|
1119
|
+
labels
|
|
1120
|
+
};
|
|
1121
|
+
}
|
|
1122
|
+
const id = (await post("mutation($input: CommentCreateInput!) { commentCreate(input: $input) { success comment { id } } }", { input: {
|
|
1123
|
+
issueId: target.threadExternal.replace(/^issue:/, ""),
|
|
1124
|
+
body: withLines(message.text, lines)
|
|
1125
|
+
} }))?.data?.commentCreate?.comment?.id;
|
|
1126
|
+
if (!id) throw new Failure("platform_refused", "Linear did not make the comment.");
|
|
1127
|
+
return { external: `comment:${id}` };
|
|
1128
|
+
}
|
|
1129
|
+
};
|
|
1130
|
+
}
|
|
1131
|
+
/** How often Slack is told a thread is still being worked on: it stops showing it an hour after it was last told. */
|
|
1132
|
+
const SLACK_WORKING_TTL_MS = 50 * 6e4;
|
|
1133
|
+
/**
|
|
1134
|
+
* Requests one catch-up tick makes for what was posted while down, shared by the mapped channels, each getting at
|
|
1135
|
+
* least three. Ticks come a minute apart while a read is cut short: Slack allows an app made for its own
|
|
1136
|
+
* workspace 50 or more of these a minute.
|
|
1137
|
+
*/
|
|
1138
|
+
const SLACK_REQUESTS = 24;
|
|
1139
|
+
/** Threads started before the downtime, among the 200 messages before it, whose new replies a tick reads per channel. */
|
|
1140
|
+
const SLACK_OLD_THREADS = 2;
|
|
1141
|
+
/** How far back from its start a catch-up looks for those threads. */
|
|
1142
|
+
const SLACK_LOOKBACK_US = 168 * 3600 * 1e6;
|
|
1143
|
+
/** History is read oldest first, a stretch of time at a time: this long to begin with, longer while quiet. */
|
|
1144
|
+
const SLACK_WINDOW_US = 1800 * 1e6;
|
|
1145
|
+
/** The shortest stretch. One busier than a tick can read is gone past, and said to be. */
|
|
1146
|
+
const SLACK_MIN_WINDOW_US = 60 * 1e6;
|
|
1147
|
+
/** Pages a stretch longer than the shortest may take before it is read as shorter ones. */
|
|
1148
|
+
const SLACK_STRETCH_PAGES = 2;
|
|
1149
|
+
/** A Slack ts, `1700000000.000100`, as whole microseconds, and back. */
|
|
1150
|
+
const fromTs = (ts) => {
|
|
1151
|
+
const [seconds = "0", fraction = ""] = String(ts).split(".");
|
|
1152
|
+
return Number(seconds) * 1e6 + Number(fraction.padEnd(6, "0").slice(0, 6));
|
|
1153
|
+
};
|
|
1154
|
+
const toTs = (us) => `${Math.floor(us / 1e6)}.${String(us % 1e6).padStart(6, "0")}`;
|
|
1155
|
+
/** Slack: messages in mapped channels come in as threads, and board replies go back into the Slack thread. */
|
|
1156
|
+
const slack = (options) => declared("slack", options, slackWith);
|
|
1157
|
+
function slackWith(options) {
|
|
1158
|
+
const now = options.now ?? (() => Date.now());
|
|
1159
|
+
const base = options.api ?? "https://slack.com/api";
|
|
1160
|
+
/** The files on a message. One Slack only links to, or no longer offers, is named and not fetched. */
|
|
1161
|
+
const filesOf = (files) => {
|
|
1162
|
+
if (!Array.isArray(files) || files.length === 0) return void 0;
|
|
1163
|
+
return files.map((file$1) => {
|
|
1164
|
+
const url = String(file$1.url_private_download ?? file$1.url_private ?? "");
|
|
1165
|
+
const skip = file$1.mode === "external" || file$1.is_external === true || file$1.filetype === "remote" ? "a link to somewhere outside Slack" : !url || file$1.mode === "tombstone" || file$1.mode === "hidden_by_limit" ? "Slack does not offer it" : void 0;
|
|
1166
|
+
return {
|
|
1167
|
+
url,
|
|
1168
|
+
id: String(file$1.id ?? ""),
|
|
1169
|
+
name: String(file$1.name ?? file$1.title ?? file$1.id ?? "file"),
|
|
1170
|
+
...file$1.mimetype ? { type: String(file$1.mimetype) } : {},
|
|
1171
|
+
...typeof file$1.size === "number" ? { size: file$1.size } : {},
|
|
1172
|
+
...skip ? { skip } : {}
|
|
1173
|
+
};
|
|
1174
|
+
});
|
|
1175
|
+
};
|
|
1176
|
+
const isSelf = (message) => message.bot_id !== void 0 && (options.bot === void 0 || message.bot_id === options.bot);
|
|
1177
|
+
/** A Web API read. Slack says no with a 200 and `ok: false`, which is a failure here too, never "nothing new". */
|
|
1178
|
+
const api = async (fetcher, method, query) => {
|
|
1179
|
+
const body = await send(fetcher, `${base}/${method}?${new URLSearchParams(query)}`, { headers: { authorization: `Bearer ${options.token}` } });
|
|
1180
|
+
if (body.ok !== true) throw new Failure(`slack_${body.error ?? "error"}`, `Slack refused ${method}: ${body.error ?? "unknown"}.`);
|
|
1181
|
+
return body;
|
|
1182
|
+
};
|
|
1183
|
+
/** A message read back, as the webhook for it would have made it. */
|
|
1184
|
+
const inbound = (channel, each, thread, parent) => ({
|
|
1185
|
+
id: `catchup:${channel}:${each.ts}`,
|
|
1186
|
+
author: String(each.user ?? each.bot_id ?? "unknown"),
|
|
1187
|
+
place: channel,
|
|
1188
|
+
self: isSelf(each),
|
|
1189
|
+
kind: thread === each.ts ? "root" : "reply",
|
|
1190
|
+
thread: `${channel}:${thread}`,
|
|
1191
|
+
external: `${channel}:${each.ts}`,
|
|
1192
|
+
text: String(each.text ?? ""),
|
|
1193
|
+
...parent ? { parent } : {},
|
|
1194
|
+
...filesOf(each.files) ? { files: filesOf(each.files) } : {}
|
|
1195
|
+
});
|
|
1196
|
+
const isPlain = (each) => (each.subtype === void 0 || each.subtype === "file_share") && (each.thread_ts === void 0 || each.thread_ts === each.ts);
|
|
1197
|
+
/** Whether a thread may have had replies after a point. A parent that doesn't say when its last came is read to find out. */
|
|
1198
|
+
const repliedAfter = (each, from) => Number(each.reply_count) > 0 && (each.latest_reply === void 0 || fromTs(each.latest_reply) > from);
|
|
1199
|
+
/** A thread's replies after a point, oldest first, in up to `pages` requests; `done` is false if there were more. */
|
|
1200
|
+
const repliesOf = async (fetcher, channel, parent, from, pages) => {
|
|
1201
|
+
const opener = isSelf(parent) ? void 0 : {
|
|
1202
|
+
author: String(parent.user ?? parent.bot_id ?? "unknown"),
|
|
1203
|
+
text: String(parent.text ?? ""),
|
|
1204
|
+
labels: {}
|
|
1205
|
+
};
|
|
1206
|
+
const out = [];
|
|
1207
|
+
let cursor = "";
|
|
1208
|
+
let used = 0;
|
|
1209
|
+
while (used < pages) {
|
|
1210
|
+
const got = await api(fetcher, "conversations.replies", {
|
|
1211
|
+
channel,
|
|
1212
|
+
ts: parent.ts,
|
|
1213
|
+
oldest: toTs(from),
|
|
1214
|
+
limit: "200",
|
|
1215
|
+
...cursor ? { cursor } : {}
|
|
1216
|
+
});
|
|
1217
|
+
used++;
|
|
1218
|
+
for (const reply of got.messages ?? []) if (reply.ts !== parent.ts && fromTs(reply.ts) > from && (reply.subtype === void 0 || reply.subtype === "file_share")) out.push(inbound(channel, reply, parent.ts, opener));
|
|
1219
|
+
cursor = got.has_more ? got.response_metadata?.next_cursor ?? "" : "";
|
|
1220
|
+
if (!cursor) return {
|
|
1221
|
+
events: out,
|
|
1222
|
+
used,
|
|
1223
|
+
done: true
|
|
1224
|
+
};
|
|
1225
|
+
}
|
|
1226
|
+
return {
|
|
1227
|
+
events: out,
|
|
1228
|
+
used,
|
|
1229
|
+
done: false
|
|
1230
|
+
};
|
|
1231
|
+
};
|
|
1232
|
+
/**
|
|
1233
|
+
* What was posted in a stretch of time, and the replies in threads started in it, in up to `pages` history pages
|
|
1234
|
+
* and `budget` requests in all. Not `done` when there was more: what it did read is kept in `events`, newest
|
|
1235
|
+
* history first if it was the history that ran over.
|
|
1236
|
+
*/
|
|
1237
|
+
const stretch = async (fetcher, channel, lo, hi, from, pages, budget) => {
|
|
1238
|
+
const messages = [];
|
|
1239
|
+
let cursor = "";
|
|
1240
|
+
let used = 0;
|
|
1241
|
+
let done = true;
|
|
1242
|
+
for (;;) {
|
|
1243
|
+
const got = await api(fetcher, "conversations.history", {
|
|
1244
|
+
channel,
|
|
1245
|
+
oldest: toTs(lo - 1),
|
|
1246
|
+
latest: toTs(hi),
|
|
1247
|
+
limit: "200",
|
|
1248
|
+
...cursor ? { cursor } : {}
|
|
1249
|
+
});
|
|
1250
|
+
used++;
|
|
1251
|
+
messages.push(...got.messages ?? []);
|
|
1252
|
+
cursor = got.has_more ? got.response_metadata?.next_cursor ?? "" : "";
|
|
1253
|
+
if (!cursor) break;
|
|
1254
|
+
if (used >= Math.min(pages, budget)) {
|
|
1255
|
+
done = false;
|
|
1256
|
+
break;
|
|
1257
|
+
}
|
|
1258
|
+
}
|
|
1259
|
+
const historyPages = used;
|
|
1260
|
+
if (!done && used < budget) return {
|
|
1261
|
+
events: [],
|
|
1262
|
+
used,
|
|
1263
|
+
pages: historyPages,
|
|
1264
|
+
done
|
|
1265
|
+
};
|
|
1266
|
+
messages.sort((a, b) => fromTs(a.ts) - fromTs(b.ts));
|
|
1267
|
+
const events = [];
|
|
1268
|
+
for (const each of messages) {
|
|
1269
|
+
if (!isPlain(each)) continue;
|
|
1270
|
+
events.push(inbound(channel, each, each.ts));
|
|
1271
|
+
if (!repliedAfter(each, from)) continue;
|
|
1272
|
+
if (used >= budget) {
|
|
1273
|
+
done = false;
|
|
1274
|
+
continue;
|
|
1275
|
+
}
|
|
1276
|
+
const replies = await repliesOf(fetcher, channel, each, from, budget - used);
|
|
1277
|
+
used += replies.used;
|
|
1278
|
+
events.push(...replies.events);
|
|
1279
|
+
if (!replies.done) done = false;
|
|
1280
|
+
}
|
|
1281
|
+
return {
|
|
1282
|
+
events,
|
|
1283
|
+
used,
|
|
1284
|
+
pages: historyPages,
|
|
1285
|
+
done
|
|
1286
|
+
};
|
|
1287
|
+
};
|
|
1288
|
+
return {
|
|
1289
|
+
type: "slack",
|
|
1290
|
+
verify({ headers, body }) {
|
|
1291
|
+
const stamp = headers["x-slack-request-timestamp"] ?? "";
|
|
1292
|
+
if (!/^\d+$/.test(stamp) || Math.abs(now() / 1e3 - Number(stamp)) > 300) throw bad();
|
|
1293
|
+
if (!same(headers["x-slack-signature"] ?? "", `v0=${hmac(options.secret, `v0:${stamp}:${body}`)}`)) throw bad();
|
|
1294
|
+
},
|
|
1295
|
+
challenge({ body }) {
|
|
1296
|
+
const payload = JSON.parse(body);
|
|
1297
|
+
return payload.type === "url_verification" ? String(payload.challenge) : null;
|
|
1298
|
+
},
|
|
1299
|
+
parse({ body }) {
|
|
1300
|
+
const payload = JSON.parse(body);
|
|
1301
|
+
const event = payload.event ?? {};
|
|
1302
|
+
if (payload.type !== "event_callback" || event.type !== "message") return [];
|
|
1303
|
+
const self = (message) => message.bot_id !== void 0 && (options.bot === void 0 || message.bot_id === options.bot);
|
|
1304
|
+
if (event.subtype === "message_changed" && event.message) return [{
|
|
1305
|
+
id: String(payload.event_id ?? `${event.channel}:${event.ts}`),
|
|
1306
|
+
author: String(event.message.user ?? "unknown"),
|
|
1307
|
+
place: String(event.channel),
|
|
1308
|
+
self: self(event.message),
|
|
1309
|
+
kind: "edit",
|
|
1310
|
+
thread: `${event.channel}:${event.message.thread_ts ?? event.message.ts}`,
|
|
1311
|
+
external: `${event.channel}:${event.message.ts}`,
|
|
1312
|
+
text: String(event.message.text ?? "")
|
|
1313
|
+
}];
|
|
1314
|
+
if (event.subtype === "message_deleted") return [{
|
|
1315
|
+
id: String(payload.event_id ?? `${event.channel}:${event.ts}`),
|
|
1316
|
+
author: String(event.previous_message?.user ?? "unknown"),
|
|
1317
|
+
place: String(event.channel),
|
|
1318
|
+
self: false,
|
|
1319
|
+
kind: "delete",
|
|
1320
|
+
thread: `${event.channel}:${event.previous_message?.thread_ts ?? event.deleted_ts}`,
|
|
1321
|
+
external: `${event.channel}:${event.deleted_ts}`
|
|
1322
|
+
}];
|
|
1323
|
+
if (event.subtype !== void 0 && event.subtype !== "file_share") return [];
|
|
1324
|
+
const root = event.thread_ts === void 0 || event.thread_ts === event.ts;
|
|
1325
|
+
return [{
|
|
1326
|
+
id: String(payload.event_id ?? `${event.channel}:${event.ts}`),
|
|
1327
|
+
author: String(event.user ?? event.bot_id ?? "unknown"),
|
|
1328
|
+
place: String(event.channel),
|
|
1329
|
+
self: event.bot_id !== void 0 && (options.bot === void 0 || event.bot_id === options.bot),
|
|
1330
|
+
kind: root ? "root" : "reply",
|
|
1331
|
+
thread: `${event.channel}:${event.thread_ts ?? event.ts}`,
|
|
1332
|
+
external: `${event.channel}:${event.ts}`,
|
|
1333
|
+
text: String(event.text ?? ""),
|
|
1334
|
+
...filesOf(event.files) ? { files: filesOf(event.files) } : {}
|
|
1335
|
+
}];
|
|
1336
|
+
},
|
|
1337
|
+
channelFor(place) {
|
|
1338
|
+
const to = options.channels[place];
|
|
1339
|
+
const channel = typeof to === "string" ? to : to?.channel;
|
|
1340
|
+
return channel ? channelPath(channel) : null;
|
|
1341
|
+
},
|
|
1342
|
+
placeFor(channel) {
|
|
1343
|
+
for (const [id, to] of Object.entries(options.channels)) if ((typeof to === "string" ? to : to.channel) === channel) return id;
|
|
1344
|
+
return null;
|
|
1345
|
+
},
|
|
1346
|
+
async update(external, text, _place, fetcher) {
|
|
1347
|
+
const [channel, ts] = external.split(":");
|
|
1348
|
+
await send(fetcher, `${base}/chat.update`, {
|
|
1349
|
+
method: "POST",
|
|
1350
|
+
headers: {
|
|
1351
|
+
authorization: `Bearer ${options.token}`,
|
|
1352
|
+
"content-type": "application/json; charset=utf-8"
|
|
1353
|
+
},
|
|
1354
|
+
body: JSON.stringify({
|
|
1355
|
+
channel,
|
|
1356
|
+
ts,
|
|
1357
|
+
text
|
|
1358
|
+
})
|
|
1359
|
+
});
|
|
1360
|
+
},
|
|
1361
|
+
...options.agent ? {
|
|
1362
|
+
workingTtl: SLACK_WORKING_TTL_MS,
|
|
1363
|
+
async working(target, step, _now, fetcher) {
|
|
1364
|
+
const [channel, ts] = target.threadExternal.split(":");
|
|
1365
|
+
const answer = await send(fetcher, `${base}/agents.sessions.setStatus`, {
|
|
1366
|
+
method: "POST",
|
|
1367
|
+
headers: {
|
|
1368
|
+
authorization: `Bearer ${options.token}`,
|
|
1369
|
+
"content-type": "application/json; charset=utf-8"
|
|
1370
|
+
},
|
|
1371
|
+
body: JSON.stringify({
|
|
1372
|
+
channel_id: channel,
|
|
1373
|
+
thread_ts: ts,
|
|
1374
|
+
status: step === "end" ? "active" : "processing"
|
|
1375
|
+
})
|
|
1376
|
+
});
|
|
1377
|
+
if (answer.ok !== true) throw new Failure(`slack_${answer.error ?? "error"}`, `Slack refused the status: ${answer.error ?? "unknown"}.`);
|
|
1378
|
+
return null;
|
|
1379
|
+
}
|
|
1380
|
+
} : {},
|
|
1381
|
+
async remove(external, _place, fetcher) {
|
|
1382
|
+
const [channel, ts] = external.split(":");
|
|
1383
|
+
await send(fetcher, `${base}/chat.delete`, {
|
|
1384
|
+
method: "POST",
|
|
1385
|
+
headers: {
|
|
1386
|
+
authorization: `Bearer ${options.token}`,
|
|
1387
|
+
"content-type": "application/json; charset=utf-8"
|
|
1388
|
+
},
|
|
1389
|
+
body: JSON.stringify({
|
|
1390
|
+
channel,
|
|
1391
|
+
ts
|
|
1392
|
+
})
|
|
1393
|
+
});
|
|
1394
|
+
},
|
|
1395
|
+
async catchUp(since, fetcher) {
|
|
1396
|
+
if (!options.token) return [];
|
|
1397
|
+
const channels = Object.keys(options.channels);
|
|
1398
|
+
const start = Date.parse(since) * 1e3;
|
|
1399
|
+
const end = now() * 1e3;
|
|
1400
|
+
const events = [];
|
|
1401
|
+
let resume = end;
|
|
1402
|
+
let skipped;
|
|
1403
|
+
for (const channel of channels) {
|
|
1404
|
+
const before = await api(fetcher, "conversations.history", {
|
|
1405
|
+
channel,
|
|
1406
|
+
oldest: toTs(Math.max(0, start - SLACK_LOOKBACK_US)),
|
|
1407
|
+
latest: toTs(start),
|
|
1408
|
+
limit: "200"
|
|
1409
|
+
});
|
|
1410
|
+
for (const parent of (before.messages ?? []).filter((each) => isPlain(each) && repliedAfter(each, start)).slice(0, SLACK_OLD_THREADS)) events.push(...(await repliesOf(fetcher, channel, parent, start, 1)).events);
|
|
1411
|
+
let lo = start;
|
|
1412
|
+
let width = SLACK_WINDOW_US;
|
|
1413
|
+
let budget = Math.max(3, Math.floor(SLACK_REQUESTS / channels.length));
|
|
1414
|
+
let moved = false;
|
|
1415
|
+
while (lo < end && budget > 0) {
|
|
1416
|
+
if (!moved && budget <= 2) width = SLACK_MIN_WINDOW_US;
|
|
1417
|
+
const shortest = width <= SLACK_MIN_WINDOW_US;
|
|
1418
|
+
const hi = Math.min(lo + width, end);
|
|
1419
|
+
const read = await stretch(fetcher, channel, lo, hi, start, shortest ? budget : SLACK_STRETCH_PAGES, shortest || moved ? budget : budget - 2);
|
|
1420
|
+
budget -= read.used;
|
|
1421
|
+
if (read.done || shortest) {
|
|
1422
|
+
if (!read.done) skipped = Math.min(skipped ?? lo, lo);
|
|
1423
|
+
events.push(...read.events);
|
|
1424
|
+
lo = hi;
|
|
1425
|
+
moved = true;
|
|
1426
|
+
if (read.done && read.pages === 1) width *= 2;
|
|
1427
|
+
continue;
|
|
1428
|
+
}
|
|
1429
|
+
width = Math.max(SLACK_MIN_WINDOW_US, Math.floor(width / 4));
|
|
1430
|
+
}
|
|
1431
|
+
resume = Math.min(resume, lo);
|
|
1432
|
+
}
|
|
1433
|
+
if (resume >= end && skipped === void 0) return events;
|
|
1434
|
+
const at = (point) => new Date(Math.floor(point / 1e3)).toISOString();
|
|
1435
|
+
return {
|
|
1436
|
+
events,
|
|
1437
|
+
resume: at(resume),
|
|
1438
|
+
...skipped !== void 0 ? { skipped: at(skipped) } : {}
|
|
1439
|
+
};
|
|
1440
|
+
},
|
|
1441
|
+
mirrors(place) {
|
|
1442
|
+
const to = options.channels[place];
|
|
1443
|
+
return options.token !== void 0 && to !== void 0 && !(typeof to === "object" && to.mirror === false);
|
|
1444
|
+
},
|
|
1445
|
+
async download(file$1, fetcher, limit) {
|
|
1446
|
+
if (!options.token) throw refused("no token to fetch it with");
|
|
1447
|
+
const got = await fetchFile(fetcher, file$1.url, {
|
|
1448
|
+
hosts: ["files.slack.com"],
|
|
1449
|
+
headers: { authorization: `Bearer ${options.token}` },
|
|
1450
|
+
limit,
|
|
1451
|
+
...file$1.size !== void 0 ? { size: file$1.size } : {}
|
|
1452
|
+
});
|
|
1453
|
+
if ((got.type ?? "").startsWith("text/html") && !(file$1.type ?? "").startsWith("text/html")) throw refused("Slack sent a page, not the file: does the app have files:read?");
|
|
1454
|
+
if (file$1.size !== void 0 && got.bytes.length !== file$1.size) throw refused(`Slack sent ${sizeOf(got.bytes.length)}, not the ${sizeOf(file$1.size)} it named`);
|
|
1455
|
+
return got;
|
|
1456
|
+
},
|
|
1457
|
+
async deliver(message, target, fetcher, read) {
|
|
1458
|
+
const [channel, ts] = (target.threadExternal ?? target.place).split(":");
|
|
1459
|
+
const auth = { authorization: `Bearer ${options.token}` };
|
|
1460
|
+
const uploaded = [];
|
|
1461
|
+
const lines = [];
|
|
1462
|
+
for (const file$1 of message.attachments) {
|
|
1463
|
+
const bytes = read(file$1.id);
|
|
1464
|
+
if (!bytes) {
|
|
1465
|
+
lines.push(noteOut(file$1.name, "the board no longer has it"));
|
|
1466
|
+
continue;
|
|
1467
|
+
}
|
|
1468
|
+
try {
|
|
1469
|
+
const got = await send(fetcher, `${base}/files.getUploadURLExternal`, {
|
|
1470
|
+
method: "POST",
|
|
1471
|
+
headers: {
|
|
1472
|
+
...auth,
|
|
1473
|
+
"content-type": "application/x-www-form-urlencoded"
|
|
1474
|
+
},
|
|
1475
|
+
body: new URLSearchParams({
|
|
1476
|
+
filename: file$1.name,
|
|
1477
|
+
length: String(bytes.length)
|
|
1478
|
+
}).toString()
|
|
1479
|
+
});
|
|
1480
|
+
const to = new URL(String(got.upload_url ?? "about:blank"));
|
|
1481
|
+
if (got.ok !== true || to.protocol !== "https:" || to.hostname !== "files.slack.com") throw new Failure("platform_refused", "Slack gave no upload URL.");
|
|
1482
|
+
const put = await fetcher(to.href, {
|
|
1483
|
+
method: "POST",
|
|
1484
|
+
headers: { "content-type": "application/octet-stream" },
|
|
1485
|
+
body: new Uint8Array(bytes),
|
|
1486
|
+
redirect: "manual",
|
|
1487
|
+
signal: AbortSignal.timeout(SEND_MS)
|
|
1488
|
+
});
|
|
1489
|
+
if (!put.ok) throw new Failure(`platform_${put.status}`, `Slack answered ${put.status}.`);
|
|
1490
|
+
uploaded.push({
|
|
1491
|
+
id: String(got.file_id),
|
|
1492
|
+
title: file$1.name
|
|
1493
|
+
});
|
|
1494
|
+
} catch {
|
|
1495
|
+
lines.push(noteOut(file$1.name, "Slack did not take it"));
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
const text = withLines(message.text, lines);
|
|
1499
|
+
const made = await send(fetcher, `${base}/chat.postMessage`, {
|
|
1500
|
+
method: "POST",
|
|
1501
|
+
headers: {
|
|
1502
|
+
...auth,
|
|
1503
|
+
"content-type": "application/json; charset=utf-8"
|
|
1504
|
+
},
|
|
1505
|
+
body: JSON.stringify({
|
|
1506
|
+
channel,
|
|
1507
|
+
thread_ts: ts,
|
|
1508
|
+
text
|
|
1509
|
+
})
|
|
1510
|
+
});
|
|
1511
|
+
if (made.ok !== true) throw new Failure(`slack_${made.error ?? "error"}`, `Slack refused the message: ${made.error ?? "unknown"}.`);
|
|
1512
|
+
if (uploaded.length) try {
|
|
1513
|
+
const shared = await send(fetcher, `${base}/files.completeUploadExternal`, {
|
|
1514
|
+
method: "POST",
|
|
1515
|
+
headers: {
|
|
1516
|
+
...auth,
|
|
1517
|
+
"content-type": "application/json; charset=utf-8"
|
|
1518
|
+
},
|
|
1519
|
+
body: JSON.stringify({
|
|
1520
|
+
files: uploaded,
|
|
1521
|
+
channel_id: channel,
|
|
1522
|
+
thread_ts: ts ?? made.ts
|
|
1523
|
+
})
|
|
1524
|
+
});
|
|
1525
|
+
if (shared.ok !== true) throw new Failure(`slack_${shared.error ?? "error"}`, "Slack did not share the files.");
|
|
1526
|
+
} catch {
|
|
1527
|
+
await send(fetcher, `${base}/chat.update`, {
|
|
1528
|
+
method: "POST",
|
|
1529
|
+
headers: {
|
|
1530
|
+
...auth,
|
|
1531
|
+
"content-type": "application/json; charset=utf-8"
|
|
1532
|
+
},
|
|
1533
|
+
body: JSON.stringify({
|
|
1534
|
+
channel,
|
|
1535
|
+
ts: made.ts,
|
|
1536
|
+
text: withLines(text, uploaded.map((file$1) => noteOut(file$1.title, "Slack did not take it")))
|
|
1537
|
+
})
|
|
1538
|
+
}).catch(() => void 0);
|
|
1539
|
+
uploaded.length = 0;
|
|
1540
|
+
}
|
|
1541
|
+
return {
|
|
1542
|
+
external: `${channel}:${made.ts}`,
|
|
1543
|
+
...target.threadExternal === null ? { thread: `${channel}:${made.ts}` } : {},
|
|
1544
|
+
...uploaded.length ? { files: uploaded.map((file$1) => file$1.id) } : {}
|
|
1545
|
+
};
|
|
1546
|
+
}
|
|
1547
|
+
};
|
|
1548
|
+
}
|
|
1549
|
+
/** Catch-up reads at most this many pages of each Notion database, of 100 each. */
|
|
1550
|
+
const NOTION_CATCHUP_PAGES = 10;
|
|
1551
|
+
/** The most of a page a thread's first message holds: the rest is on Notion, a link away. */
|
|
1552
|
+
const NOTION_TEXT_MAX = 9e3;
|
|
1553
|
+
/** Notion takes at most 2,000 characters in one rich text item, and 100 items in a comment. */
|
|
1554
|
+
const NOTION_RICH_MAX = 2e3;
|
|
1555
|
+
/**
|
|
1556
|
+
* Notion: each page of a mapped database is a thread, its title and text the first message and its Status the
|
|
1557
|
+
* `state` label, and its comments are replies, both ways. Notion's webhooks say only what changed, so each event
|
|
1558
|
+
* is read from Notion's API on the ticker before it is imported. `secret` is the subscription's verification
|
|
1559
|
+
* token, which Notion signs every delivery with.
|
|
1560
|
+
*/
|
|
1561
|
+
const notion = (options) => declared("notion", options, notionWith);
|
|
1562
|
+
/** What `secret` is set to until Notion has sent its verification token: the one time an unsigned request is taken. */
|
|
1563
|
+
const NOTION_PENDING = "pending";
|
|
1564
|
+
/** A Notion ID as one form: lowercase, without dashes, so a database named either way is the same one. */
|
|
1565
|
+
const notionId = (id) => String(id ?? "").replace(/-/g, "").toLowerCase();
|
|
1566
|
+
/** Where a Notion subscription's one-time verification token is written for the operator, and nowhere else. */
|
|
1567
|
+
const notionTokenFile = () => join(process.env.MUSTER_CONFIG ?? join(process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"), "muster"), "notion-verification-token");
|
|
1568
|
+
function notionWith(options) {
|
|
1569
|
+
const api = (options.api ?? "https://api.notion.com/v1").replace(/\/$/, "");
|
|
1570
|
+
const databases = new Map(Object.entries(options.databases).map(([id, to]) => [notionId(id), to]));
|
|
1571
|
+
const call = (fetcher, path, init = {}) => {
|
|
1572
|
+
if (!options.token) throw new Failure("platform_refused", "The Notion sync has no token to read Notion with.");
|
|
1573
|
+
return send(fetcher, `${api}${path}`, {
|
|
1574
|
+
method: init.method ?? "GET",
|
|
1575
|
+
headers: {
|
|
1576
|
+
authorization: `Bearer ${options.token}`,
|
|
1577
|
+
"notion-version": options.version ?? "2026-03-11",
|
|
1578
|
+
...init.body !== void 0 ? { "content-type": "application/json" } : {}
|
|
1579
|
+
},
|
|
1580
|
+
...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {}
|
|
1581
|
+
});
|
|
1582
|
+
};
|
|
1583
|
+
const plain = (rich$1) => Array.isArray(rich$1) ? rich$1.map((each) => String(each?.plain_text ?? each?.text?.content ?? "")).join("") : "";
|
|
1584
|
+
/** Text as Notion's rich text, in items it takes, as much of it as a comment can hold. */
|
|
1585
|
+
const rich = (text) => {
|
|
1586
|
+
const out = [];
|
|
1587
|
+
for (let at = 0; at < text.length && out.length < 100; at += NOTION_RICH_MAX) out.push({ text: { content: text.slice(at, at + NOTION_RICH_MAX) } });
|
|
1588
|
+
return out.length ? out : [{ text: { content: " " } }];
|
|
1589
|
+
};
|
|
1590
|
+
/** The database a page is in, as this sync names it: its data source, or its database on an older workspace. */
|
|
1591
|
+
const placeOf = (page) => {
|
|
1592
|
+
const parent = page.parent ?? {};
|
|
1593
|
+
for (const id of [parent.data_source_id, parent.database_id]) if (id && databases.has(notionId(id))) return notionId(id);
|
|
1594
|
+
return null;
|
|
1595
|
+
};
|
|
1596
|
+
const titleOf = (page) => {
|
|
1597
|
+
for (const property of Object.values(page.properties ?? {})) if (property?.type === "title") return plain(property.title).trim();
|
|
1598
|
+
return "";
|
|
1599
|
+
};
|
|
1600
|
+
/** Its Status, or a select called Status, as the thread's `state` label. */
|
|
1601
|
+
const stateOf = (page) => {
|
|
1602
|
+
for (const [name, property] of Object.entries(page.properties ?? {})) {
|
|
1603
|
+
const value = property?.type === "status" ? property.status?.name : property?.type === "select" && /^status$/i.test(name) ? property.select?.name : void 0;
|
|
1604
|
+
if (typeof value === "string" && value) return slug(value);
|
|
1605
|
+
}
|
|
1606
|
+
};
|
|
1607
|
+
const byOf = (who) => String(who?.id ?? "");
|
|
1608
|
+
const selfOf = (who) => options.bot !== void 0 && who?.id !== void 0 && notionId(who.id) === notionId(options.bot);
|
|
1609
|
+
/** A page as a thread's first message: its title, a blank line, its text as markdown, cut to what a message holds. */
|
|
1610
|
+
const pageText = async (page, fetcher) => {
|
|
1611
|
+
const body = await call(fetcher, `/pages/${page.id}/markdown`).then((answer) => String(answer?.markdown ?? ""), (error) => {
|
|
1612
|
+
if (error instanceof Failure && error.reason === "platform_404") return "";
|
|
1613
|
+
throw error;
|
|
1614
|
+
});
|
|
1615
|
+
const text = `${titleOf(page)}\n\n${body}`.trim();
|
|
1616
|
+
return text.length > NOTION_TEXT_MAX ? `${text.slice(0, NOTION_TEXT_MAX)}\n\n… the rest is on Notion: ${String(page.url ?? "")}` : text;
|
|
1617
|
+
};
|
|
1618
|
+
const pageLabels = (page) => {
|
|
1619
|
+
const state = stateOf(page);
|
|
1620
|
+
return {
|
|
1621
|
+
kind: "page",
|
|
1622
|
+
...typeof page.url === "string" ? { ref: page.url.slice(0, 256) } : {},
|
|
1623
|
+
...state ? { state } : {}
|
|
1624
|
+
};
|
|
1625
|
+
};
|
|
1626
|
+
/** What a page is now, as the first message of a thread the board may not have yet. */
|
|
1627
|
+
const parentOf = async (page, fetcher) => ({
|
|
1628
|
+
author: byOf(page.created_by),
|
|
1629
|
+
text: await pageText(page, fetcher),
|
|
1630
|
+
labels: pageLabels(page)
|
|
1631
|
+
});
|
|
1632
|
+
const isVerification = (body) => {
|
|
1633
|
+
try {
|
|
1634
|
+
const parsed = JSON.parse(body);
|
|
1635
|
+
return parsed !== null && typeof parsed === "object" && Object.keys(parsed).length === 1 && typeof parsed.verification_token === "string" && /^secret_[A-Za-z0-9]{10,200}$/.test(parsed.verification_token);
|
|
1636
|
+
} catch {
|
|
1637
|
+
return false;
|
|
1638
|
+
}
|
|
1639
|
+
};
|
|
1640
|
+
return {
|
|
1641
|
+
type: "notion",
|
|
1642
|
+
verify({ headers, body }) {
|
|
1643
|
+
const signature = headers["x-notion-signature"];
|
|
1644
|
+
if (options.secret === NOTION_PENDING) {
|
|
1645
|
+
if (isVerification(body)) return;
|
|
1646
|
+
throw bad();
|
|
1647
|
+
}
|
|
1648
|
+
if (!same(signature ?? "", `sha256=${hmac(options.secret, body)}`)) throw bad();
|
|
1649
|
+
},
|
|
1650
|
+
challenge({ body }) {
|
|
1651
|
+
if (options.secret !== NOTION_PENDING || !isVerification(body)) return null;
|
|
1652
|
+
try {
|
|
1653
|
+
const file$1 = notionTokenFile();
|
|
1654
|
+
mkdirSync(dirname(file$1), { recursive: true });
|
|
1655
|
+
writeFileSync(file$1, `${JSON.parse(body).verification_token}\n`, {
|
|
1656
|
+
mode: 384,
|
|
1657
|
+
flag: "wx"
|
|
1658
|
+
});
|
|
1659
|
+
} catch {}
|
|
1660
|
+
return "ok";
|
|
1661
|
+
},
|
|
1662
|
+
parse({ body }) {
|
|
1663
|
+
const payload = JSON.parse(body);
|
|
1664
|
+
const type = String(payload.type ?? "");
|
|
1665
|
+
const entity = payload.entity ?? {};
|
|
1666
|
+
const data = payload.data ?? {};
|
|
1667
|
+
const author = payload.authors?.[0];
|
|
1668
|
+
const base = {
|
|
1669
|
+
id: `notion:${payload.id}`,
|
|
1670
|
+
author: byOf(author),
|
|
1671
|
+
place: "",
|
|
1672
|
+
self: selfOf(author),
|
|
1673
|
+
unread: true
|
|
1674
|
+
};
|
|
1675
|
+
if (!entity.id) return [];
|
|
1676
|
+
const page = `page:${notionId(entity.id)}`;
|
|
1677
|
+
if (type === "page.created") return [{
|
|
1678
|
+
...base,
|
|
1679
|
+
kind: "root",
|
|
1680
|
+
thread: page,
|
|
1681
|
+
external: page
|
|
1682
|
+
}];
|
|
1683
|
+
if (type === "page.content_updated") return [{
|
|
1684
|
+
...base,
|
|
1685
|
+
kind: "edit",
|
|
1686
|
+
thread: page,
|
|
1687
|
+
external: page
|
|
1688
|
+
}];
|
|
1689
|
+
if (type === "page.properties_updated") return [{
|
|
1690
|
+
...base,
|
|
1691
|
+
kind: "labels",
|
|
1692
|
+
thread: page,
|
|
1693
|
+
external: base.id
|
|
1694
|
+
}];
|
|
1695
|
+
if (type === "page.deleted") return [{
|
|
1696
|
+
...base,
|
|
1697
|
+
kind: "delete",
|
|
1698
|
+
thread: page,
|
|
1699
|
+
external: page
|
|
1700
|
+
}];
|
|
1701
|
+
if (type.startsWith("comment.") && data.page_id) {
|
|
1702
|
+
const kind = type === "comment.created" ? "reply" : type === "comment.updated" ? "edit" : type === "comment.deleted" ? "delete" : null;
|
|
1703
|
+
if (kind) return [{
|
|
1704
|
+
...base,
|
|
1705
|
+
kind,
|
|
1706
|
+
thread: `page:${notionId(data.page_id)}`,
|
|
1707
|
+
external: `comment:${notionId(entity.id)}`
|
|
1708
|
+
}];
|
|
1709
|
+
}
|
|
1710
|
+
return [];
|
|
1711
|
+
},
|
|
1712
|
+
async read(event, fetcher) {
|
|
1713
|
+
const page = await call(fetcher, `/pages/${event.thread.replace(/^page:/, "")}`);
|
|
1714
|
+
const place = placeOf(page);
|
|
1715
|
+
if (place === null) return [];
|
|
1716
|
+
const read = {
|
|
1717
|
+
...event,
|
|
1718
|
+
place
|
|
1719
|
+
};
|
|
1720
|
+
if (event.kind === "delete") return [read];
|
|
1721
|
+
if (!event.external.startsWith("comment:")) {
|
|
1722
|
+
const text = await pageText(page, fetcher);
|
|
1723
|
+
if (event.kind === "root") return [{
|
|
1724
|
+
...read,
|
|
1725
|
+
author: byOf(page.created_by),
|
|
1726
|
+
self: selfOf(page.created_by),
|
|
1727
|
+
text,
|
|
1728
|
+
labels: pageLabels(page)
|
|
1729
|
+
}];
|
|
1730
|
+
const parent = { parent: {
|
|
1731
|
+
author: byOf(page.created_by),
|
|
1732
|
+
text,
|
|
1733
|
+
labels: pageLabels(page)
|
|
1734
|
+
} };
|
|
1735
|
+
return [{
|
|
1736
|
+
...read,
|
|
1737
|
+
kind: "edit",
|
|
1738
|
+
external: event.thread,
|
|
1739
|
+
author: byOf(page.last_edited_by),
|
|
1740
|
+
self: selfOf(page.last_edited_by),
|
|
1741
|
+
text,
|
|
1742
|
+
...parent
|
|
1743
|
+
}, {
|
|
1744
|
+
...read,
|
|
1745
|
+
id: `${event.id}:labels`,
|
|
1746
|
+
kind: "labels",
|
|
1747
|
+
external: `${event.id}:labels`,
|
|
1748
|
+
labels: pageLabels(page),
|
|
1749
|
+
...parent
|
|
1750
|
+
}];
|
|
1751
|
+
}
|
|
1752
|
+
const comment = await call(fetcher, `/comments/${event.external.replace(/^comment:/, "")}`);
|
|
1753
|
+
return [{
|
|
1754
|
+
...read,
|
|
1755
|
+
author: byOf(comment.created_by),
|
|
1756
|
+
self: selfOf(comment.created_by),
|
|
1757
|
+
text: plain(comment.rich_text),
|
|
1758
|
+
parent: await parentOf(page, fetcher)
|
|
1759
|
+
}];
|
|
1760
|
+
},
|
|
1761
|
+
channelFor(place) {
|
|
1762
|
+
const to = databases.get(notionId(place));
|
|
1763
|
+
const channel = typeof to === "string" ? to : to?.channel;
|
|
1764
|
+
return channel ? channelPath(channel) : null;
|
|
1765
|
+
},
|
|
1766
|
+
placeFor(channel) {
|
|
1767
|
+
for (const [id, to] of databases) if ((typeof to === "string" ? to : to.channel) === channel) return id;
|
|
1768
|
+
return null;
|
|
1769
|
+
},
|
|
1770
|
+
mirrors(place) {
|
|
1771
|
+
const to = databases.get(notionId(place));
|
|
1772
|
+
return options.token !== void 0 && to !== void 0 && !(typeof to === "object" && to.mirror === false);
|
|
1773
|
+
},
|
|
1774
|
+
async update(external, text, _place, fetcher) {
|
|
1775
|
+
if (!external.startsWith("comment:")) return;
|
|
1776
|
+
await call(fetcher, `/comments/${external.slice(8)}`, {
|
|
1777
|
+
method: "PATCH",
|
|
1778
|
+
body: { rich_text: rich(text) }
|
|
1779
|
+
});
|
|
1780
|
+
},
|
|
1781
|
+
async remove(external, _place, fetcher) {
|
|
1782
|
+
if (!external.startsWith("comment:")) return;
|
|
1783
|
+
await call(fetcher, `/comments/${external.slice(8)}`, { method: "DELETE" });
|
|
1784
|
+
},
|
|
1785
|
+
async catchUp(since, fetcher) {
|
|
1786
|
+
if (!options.token) return [];
|
|
1787
|
+
const out = [];
|
|
1788
|
+
const cuts = [];
|
|
1789
|
+
for (const id of databases.keys()) {
|
|
1790
|
+
const pages = [];
|
|
1791
|
+
let cursor;
|
|
1792
|
+
let more = false;
|
|
1793
|
+
for (let read = 0; read < NOTION_CATCHUP_PAGES; read++) {
|
|
1794
|
+
const answer = await call(fetcher, `/data_sources/${id}/query`, {
|
|
1795
|
+
method: "POST",
|
|
1796
|
+
body: {
|
|
1797
|
+
filter: {
|
|
1798
|
+
timestamp: "last_edited_time",
|
|
1799
|
+
last_edited_time: { after: since }
|
|
1800
|
+
},
|
|
1801
|
+
sorts: [{
|
|
1802
|
+
timestamp: "last_edited_time",
|
|
1803
|
+
direction: "ascending"
|
|
1804
|
+
}],
|
|
1805
|
+
page_size: 100,
|
|
1806
|
+
...cursor ? { start_cursor: cursor } : {}
|
|
1807
|
+
}
|
|
1808
|
+
});
|
|
1809
|
+
if (!Array.isArray(answer?.results)) throw new Failure("platform_refused", "Notion did not list the database's pages.");
|
|
1810
|
+
pages.push(...answer.results.filter((each) => each?.object === "page"));
|
|
1811
|
+
more = Boolean(answer.has_more && answer.next_cursor);
|
|
1812
|
+
if (!more) break;
|
|
1813
|
+
cursor = String(answer.next_cursor);
|
|
1814
|
+
}
|
|
1815
|
+
for (const page of pages) {
|
|
1816
|
+
const pageId = notionId(page.id);
|
|
1817
|
+
const thread = `page:${pageId}`;
|
|
1818
|
+
const text = await pageText(page, fetcher);
|
|
1819
|
+
const labels = pageLabels(page);
|
|
1820
|
+
const edited = String(page.last_edited_time ?? "");
|
|
1821
|
+
out.push({
|
|
1822
|
+
id: `catchup:page:${pageId}`,
|
|
1823
|
+
author: byOf(page.created_by),
|
|
1824
|
+
place: id,
|
|
1825
|
+
self: selfOf(page.created_by),
|
|
1826
|
+
kind: "root",
|
|
1827
|
+
thread,
|
|
1828
|
+
external: thread,
|
|
1829
|
+
text,
|
|
1830
|
+
labels
|
|
1831
|
+
});
|
|
1832
|
+
out.push({
|
|
1833
|
+
id: `catchup:edit:${pageId}:${edited}`,
|
|
1834
|
+
author: byOf(page.last_edited_by),
|
|
1835
|
+
self: selfOf(page.last_edited_by),
|
|
1836
|
+
place: id,
|
|
1837
|
+
kind: "edit",
|
|
1838
|
+
thread,
|
|
1839
|
+
external: thread,
|
|
1840
|
+
text
|
|
1841
|
+
});
|
|
1842
|
+
out.push({
|
|
1843
|
+
id: `catchup:state:${pageId}:${edited}`,
|
|
1844
|
+
author: "",
|
|
1845
|
+
place: id,
|
|
1846
|
+
kind: "labels",
|
|
1847
|
+
thread,
|
|
1848
|
+
external: `catchup:state:${pageId}:${edited}`,
|
|
1849
|
+
labels,
|
|
1850
|
+
...edited ? { at: edited } : {}
|
|
1851
|
+
});
|
|
1852
|
+
const parent = {
|
|
1853
|
+
author: byOf(page.created_by),
|
|
1854
|
+
text,
|
|
1855
|
+
labels
|
|
1856
|
+
};
|
|
1857
|
+
let start;
|
|
1858
|
+
for (let read = 0; read < NOTION_CATCHUP_PAGES; read++) {
|
|
1859
|
+
const comments = await call(fetcher, `/comments?block_id=${page.id}&page_size=100${start ? `&start_cursor=${encodeURIComponent(start)}` : ""}`);
|
|
1860
|
+
for (const comment of Array.isArray(comments?.results) ? comments.results : []) {
|
|
1861
|
+
const made = String(comment.created_time ?? "") > since;
|
|
1862
|
+
const changed = String(comment.last_edited_time ?? "") > since;
|
|
1863
|
+
if (!made && !changed) continue;
|
|
1864
|
+
const external = `comment:${notionId(comment.id)}`;
|
|
1865
|
+
const common = {
|
|
1866
|
+
author: byOf(comment.created_by),
|
|
1867
|
+
place: id,
|
|
1868
|
+
self: selfOf(comment.created_by),
|
|
1869
|
+
thread,
|
|
1870
|
+
external,
|
|
1871
|
+
text: plain(comment.rich_text),
|
|
1872
|
+
parent
|
|
1873
|
+
};
|
|
1874
|
+
out.push({
|
|
1875
|
+
...common,
|
|
1876
|
+
id: `catchup:comment:${notionId(comment.id)}`,
|
|
1877
|
+
kind: "reply"
|
|
1878
|
+
});
|
|
1879
|
+
if (changed) out.push({
|
|
1880
|
+
...common,
|
|
1881
|
+
id: `catchup:comment:${notionId(comment.id)}:${String(comment.last_edited_time)}`,
|
|
1882
|
+
kind: "edit"
|
|
1883
|
+
});
|
|
1884
|
+
}
|
|
1885
|
+
if (!comments?.has_more || !comments.next_cursor) break;
|
|
1886
|
+
start = String(comments.next_cursor);
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
if (more) cuts.push(cutShort(pages.map((page) => Date.parse(String(page.last_edited_time))), since, false, 0));
|
|
1890
|
+
}
|
|
1891
|
+
return cuts.length ? {
|
|
1892
|
+
events: out,
|
|
1893
|
+
...soonest(cuts)
|
|
1894
|
+
} : out;
|
|
1895
|
+
},
|
|
1896
|
+
async deliver(message, target, fetcher, read) {
|
|
1897
|
+
const lines = message.attachments.map((file$1) => read(file$1.id) ? noteOut(file$1.name, "the Notion sync sends no files yet") : noteOut(file$1.name, "the board no longer has it"));
|
|
1898
|
+
if (target.threadExternal === null) {
|
|
1899
|
+
const source = await call(fetcher, `/data_sources/${target.place}`);
|
|
1900
|
+
const title = Object.entries(source?.properties ?? {}).find(([, property]) => property?.type === "title")?.[0];
|
|
1901
|
+
if (!title) throw new Failure("platform_refused", "Notion did not say which property is the database's title.");
|
|
1902
|
+
const [first, ...rest] = message.text.split("\n");
|
|
1903
|
+
const body = withLines(rest.join("\n").trim(), lines);
|
|
1904
|
+
const made$1 = await call(fetcher, "/pages", {
|
|
1905
|
+
method: "POST",
|
|
1906
|
+
body: {
|
|
1907
|
+
parent: { data_source_id: target.place },
|
|
1908
|
+
properties: { [title]: { title: rich(first.slice(0, NOTION_RICH_MAX)) } },
|
|
1909
|
+
children: body ? [{
|
|
1910
|
+
object: "block",
|
|
1911
|
+
type: "paragraph",
|
|
1912
|
+
paragraph: { rich_text: rich(body) }
|
|
1913
|
+
}] : []
|
|
1914
|
+
}
|
|
1915
|
+
});
|
|
1916
|
+
if (!made$1?.id) throw new Failure("platform_refused", "Notion did not make the page.");
|
|
1917
|
+
const thread = `page:${notionId(made$1.id)}`;
|
|
1918
|
+
return {
|
|
1919
|
+
external: thread,
|
|
1920
|
+
thread,
|
|
1921
|
+
labels: pageLabels(made$1)
|
|
1922
|
+
};
|
|
1923
|
+
}
|
|
1924
|
+
const made = await call(fetcher, "/comments", {
|
|
1925
|
+
method: "POST",
|
|
1926
|
+
body: {
|
|
1927
|
+
parent: { page_id: target.threadExternal.replace(/^page:/, "") },
|
|
1928
|
+
rich_text: rich(withLines(message.text, lines))
|
|
1929
|
+
}
|
|
1930
|
+
});
|
|
1931
|
+
if (!made?.id) throw new Failure("platform_refused", "Notion did not make the comment.");
|
|
1932
|
+
return { external: `comment:${notionId(made.id)}` };
|
|
1933
|
+
}
|
|
1934
|
+
};
|
|
1935
|
+
}
|
|
1936
|
+
|
|
1937
|
+
//#endregion
|
|
1938
|
+
export { AGENTS, Failure, LINEAR_SCOPES, SANDBOX_ROUTES, agentEnv, applyPolicy, board, boardKey, boardPath, boardPolicy, claude, cloudflare, codex, command, conformance, createHandler, e2b, env, fenced, file, generic, github, http, linear, listen, loadWorkflows, mint, notion, runLocal, slack, vercel, verify, workflowResult, workflowsPath };
|