@vercel/board 0.53.0 → 0.54.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -3
- package/dist/{access-Pcar1gwx.mjs → access-HzqFpgL_.mjs} +1 -1
- package/dist/access.d.mts +3 -3
- package/dist/access.mjs +5 -5
- package/dist/{actors-XKUrjOfO.mjs → actors-D-u6bitG.mjs} +2 -2
- package/dist/{auth-C2CxMl2p.mjs → auth-D9ycDQK0.mjs} +34 -12
- package/dist/{auth-BoYunD5t.d.mts → auth-ULldUvir.d.mts} +8 -2
- package/dist/{backend-DJobr4nr.d.mts → backend-BHN6GTjB.d.mts} +8 -7
- package/dist/backend-local.d.mts +1 -1
- package/dist/backend-local.mjs +1 -1
- package/dist/{chat-provider-BSHlV2lw.d.mts → chat-provider-F7UqWVZK.d.mts} +2 -2
- package/dist/cli-commands.d.mts +1 -1
- package/dist/cli-commands.mjs +1 -1
- package/dist/cli-embedded.d.mts +2 -2
- package/dist/cli-embedded.mjs +2 -2
- package/dist/cli.mjs +6 -6
- package/dist/{client-oYThy3CR.d.mts → client-CFHunEFn.d.mts} +8 -2
- package/dist/{commands-B_gbi2sU.mjs → commands-B5SXeo4W.mjs} +14 -9
- package/dist/{commands-B6pgzwTI.d.mts → commands-DLPIX7Jw.d.mts} +3 -1
- package/dist/{conformance-Cz1Elmgj.mjs → conformance-CyQG0jky.mjs} +3 -4
- package/dist/conformance.d.mts +3 -4
- package/dist/conformance.mjs +1 -1
- package/dist/{engine-506f7GEM.mjs → engine-C8wCzkw-.mjs} +2 -2
- package/dist/{routes-GF5ukHYX.mjs → errors-DDfXnZ2b.mjs} +875 -4
- package/dist/{exports-CF_nUsT5.d.mts → exports-BBmjHyCB.d.mts} +4 -4
- package/dist/{exports-CBukc8T3.mjs → exports-JUhj5Bl3.mjs} +119 -70
- package/dist/{index-CM2u0wGd.d.mts → index-Ce3SDZ3Y.d.mts} +2 -2
- package/dist/index.d.mts +6 -6
- package/dist/index.mjs +4 -4
- package/dist/index.node.d.mts +7 -7
- package/dist/index.node.mjs +4 -4
- package/dist/inspect/app.js +69 -69
- package/dist/inspect/engine.js +3 -3
- package/dist/inspect-BN7V9e-M.mjs +2 -0
- package/dist/{inspect-PQsEgXRQ.mjs → inspect-CrVs-iEi.mjs} +2 -2
- package/dist/inspect.d.mts +1 -1
- package/dist/inspect.mjs +1 -1
- package/dist/{local-CwcmqEoa.mjs → local-RoMUU6QX.mjs} +10 -10
- package/dist/{main-gNAS2WbP.mjs → main-B_gzTjBR.mjs} +300 -91
- package/dist/{middleware-DXiwepsR.mjs → middleware-BY4qqIh3.mjs} +1 -1
- package/dist/{provider-WjdBsRLR.d.mts → provider-DgGp4Zej.d.mts} +2 -2
- package/dist/{routes-BpvyXQwv.d.mts → routes-DNmQSOvQ.d.mts} +16 -1
- package/dist/{serve-Ci5KT11x.mjs → serve-Cz1NynhG.mjs} +6 -6
- package/dist/{server-XsbC50nY.mjs → server-CdBXNUxf.mjs} +68 -11
- package/dist/{serving-C6Ao7i-7.mjs → serving-C1mhZQqH.mjs} +1 -1
- package/dist/{shell-BiCBL1w_.mjs → shell-Cqn38XUs.mjs} +1 -1
- package/dist/sync-chat-sdk.d.mts +2 -2
- package/dist/sync-github.d.mts +2 -2
- package/dist/sync-linear.d.mts +3 -3
- package/dist/sync-slack.d.mts +3 -3
- package/dist/sync.d.mts +2 -2
- package/dist/{task-batch-nqYGszDJ.mjs → task-batch-CVamHB-W.mjs} +4 -5
- package/dist/{tokens-tulRtEWx.mjs → tokens-B3gXkQCs.mjs} +2 -2
- package/dist/{version-CBjh_ogp.mjs → version-DBaKHEZS.mjs} +1 -1
- package/docs/01-board/01-mounting.md +8 -6
- package/docs/01-board/03-identity.md +1 -1
- package/docs/01-board/05-reading.md +34 -7
- package/docs/01-board/09-access.md +11 -2
- package/docs/01-board/11-tasks.md +5 -3
- package/docs/01-quickstart.md +19 -5
- package/docs/03-guides/03-ci.md +71 -43
- package/docs/03-guides/04-triage.md +4 -4
- package/docs/04-reference/01-cli.md +30 -22
- package/docs/04-reference/02-board.md +8 -4
- package/docs/04-reference/03-http.md +14 -5
- package/docs/04-reference/05-conformance.md +1 -1
- package/docs/index.md +7 -5
- package/package.json +2 -2
- package/dist/errors-Cv0TGBt5.mjs +0 -857
- package/dist/inspect-SEaGzhvh.mjs +0 -2
package/dist/errors-Cv0TGBt5.mjs
DELETED
|
@@ -1,857 +0,0 @@
|
|
|
1
|
-
import { a as DIRECT_UPLOAD_BYTES_MAX, f as typeOf, i as ATTACHMENT_BYTES_MAX, n as formatProfileHeader } from "./profile-header-O8wC8yk8.mjs";
|
|
2
|
-
import { m as MESSAGE_TEXT_MAX } from "./schemas-CUSTEFIy.mjs";
|
|
3
|
-
import { r as normalizeEmoji } from "./emoji-CTLpvH-A.mjs";
|
|
4
|
-
import { ZodError } from "zod";
|
|
5
|
-
//#region src/client/sse.ts
|
|
6
|
-
/** Parses a text/event-stream body into messages. */
|
|
7
|
-
async function* parseSse(body, signal) {
|
|
8
|
-
const reader = body.getReader();
|
|
9
|
-
const decoder = new TextDecoder();
|
|
10
|
-
let buffer = "";
|
|
11
|
-
const onAbort = () => void reader.cancel().catch(() => {});
|
|
12
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
13
|
-
try {
|
|
14
|
-
while (true) {
|
|
15
|
-
const { value, done } = await reader.read();
|
|
16
|
-
if (done) return;
|
|
17
|
-
buffer += decoder.decode(value, { stream: true });
|
|
18
|
-
let boundary;
|
|
19
|
-
while ((boundary = buffer.search(/\r?\n\r?\n/)) !== -1) {
|
|
20
|
-
const block = buffer.slice(0, boundary);
|
|
21
|
-
buffer = buffer.slice(boundary).replace(/^\r?\n\r?\n/, "");
|
|
22
|
-
const message = {};
|
|
23
|
-
const data = [];
|
|
24
|
-
for (const line of block.split(/\r?\n/)) {
|
|
25
|
-
if (line === "" || line.startsWith(":")) continue;
|
|
26
|
-
const colon = line.indexOf(":");
|
|
27
|
-
const field = colon === -1 ? line : line.slice(0, colon);
|
|
28
|
-
const value = colon === -1 ? "" : line.slice(colon + 1).replace(/^ /, "");
|
|
29
|
-
if (field === "data") data.push(value);
|
|
30
|
-
else if (field === "id") message.id = value;
|
|
31
|
-
else if (field === "event") message.event = value;
|
|
32
|
-
}
|
|
33
|
-
if (data.length > 0) message.data = data.join("\n");
|
|
34
|
-
if (message.id !== void 0 || message.data !== void 0) yield message;
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
} finally {
|
|
38
|
-
signal?.removeEventListener("abort", onAbort);
|
|
39
|
-
reader.releaseLock();
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
//#endregion
|
|
43
|
-
//#region src/client/client.ts
|
|
44
|
-
/**
|
|
45
|
-
* What went wrong: `message` says what and why, `code` is what to branch on, `hint`, when there's
|
|
46
|
-
* one, what fixes it, and `origin` who said so. Trust a `board` one's message and hint as you would
|
|
47
|
-
* the board.
|
|
48
|
-
*/
|
|
49
|
-
var BoardError = class extends Error {
|
|
50
|
-
code;
|
|
51
|
-
status;
|
|
52
|
-
hint;
|
|
53
|
-
origin;
|
|
54
|
-
/** For a 429, how many seconds the board asked to wait before sending again (its `Retry-After`), when it said. */
|
|
55
|
-
retryAfter;
|
|
56
|
-
constructor(code, message, status, options = {}) {
|
|
57
|
-
super(message);
|
|
58
|
-
this.name = "BoardError";
|
|
59
|
-
this.code = code;
|
|
60
|
-
this.status = status;
|
|
61
|
-
this.hint = options.hint;
|
|
62
|
-
this.origin = options.origin ?? "handle";
|
|
63
|
-
this.retryAfter = options.retryAfter;
|
|
64
|
-
}
|
|
65
|
-
};
|
|
66
|
-
/**
|
|
67
|
-
* The responses, made in this process, that carry an error the handle raised: a handle's request
|
|
68
|
-
* to a board in this process keeps its errors the handle's on the way back. Nothing a board sends
|
|
69
|
-
* can be one.
|
|
70
|
-
*/
|
|
71
|
-
const handleErrors = /* @__PURE__ */ new WeakSet();
|
|
72
|
-
const resolve = async (value) => typeof value === "function" ? await value() : value;
|
|
73
|
-
const scheduleBody = (input) => {
|
|
74
|
-
const { at, until, ...rest } = messageBody(input);
|
|
75
|
-
return {
|
|
76
|
-
...rest,
|
|
77
|
-
...at !== void 0 ? { at: at instanceof Date ? at.toISOString() : at } : {},
|
|
78
|
-
...until !== void 0 ? { until: until instanceof Date ? until.toISOString() : until } : {}
|
|
79
|
-
};
|
|
80
|
-
};
|
|
81
|
-
const messageBody = (input) => {
|
|
82
|
-
if (typeof input === "string") return { text: input };
|
|
83
|
-
const { attachments, ...rest } = input;
|
|
84
|
-
return attachments?.length ? {
|
|
85
|
-
...rest,
|
|
86
|
-
attachments: attachments.map((a) => typeof a === "string" ? a : a.id)
|
|
87
|
-
} : rest;
|
|
88
|
-
};
|
|
89
|
-
/** Tells `onState` each change, once: `live` when the board answers, `retrying` when a request fails. It never guesses. */
|
|
90
|
-
function eventsState(onState) {
|
|
91
|
-
let current = null;
|
|
92
|
-
const tell = (next) => {
|
|
93
|
-
if (next === current) return;
|
|
94
|
-
current = next;
|
|
95
|
-
onState?.(next);
|
|
96
|
-
};
|
|
97
|
-
return {
|
|
98
|
-
answered: () => tell("live"),
|
|
99
|
-
failed: () => tell("retrying")
|
|
100
|
-
};
|
|
101
|
-
}
|
|
102
|
-
/** How long one request for a ready task is held, in seconds, as one for the next event is. */
|
|
103
|
-
const CLAIM_WAIT_S = 25;
|
|
104
|
-
/** How soon a claim that waits asks again, when the board answered without holding the request. */
|
|
105
|
-
const CLAIM_AGAIN_MS = 1e3;
|
|
106
|
-
const UNITS = {
|
|
107
|
-
ms: 1,
|
|
108
|
-
s: 1e3,
|
|
109
|
-
m: 6e4,
|
|
110
|
-
h: 36e5,
|
|
111
|
-
d: 864e5
|
|
112
|
-
};
|
|
113
|
-
function duration(value) {
|
|
114
|
-
if (typeof value === "number") return value;
|
|
115
|
-
const match = value.trim().match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)?$/);
|
|
116
|
-
if (!match) throw new BoardError("invalid_duration", `${value} isn't a duration like 30s, 10m, or 1h.`, 0);
|
|
117
|
-
return Number(match[1]) * UNITS[match[2] ?? "ms"];
|
|
118
|
-
}
|
|
119
|
-
/** A ref as a path segment: opaque, so it's encoded as it is. */
|
|
120
|
-
const path = (id) => encodeURIComponent(id);
|
|
121
|
-
function queryString(query) {
|
|
122
|
-
const params = new URLSearchParams();
|
|
123
|
-
for (const [key, value] of Object.entries(query)) {
|
|
124
|
-
if (value === void 0 || value === null) continue;
|
|
125
|
-
if (key === "label") {
|
|
126
|
-
const labels = Array.isArray(value) ? value : typeof value === "object" ? Object.entries(value).map(([k, v]) => `${k}=${String(v)}`) : [value];
|
|
127
|
-
for (const label of labels) params.append("label", String(label));
|
|
128
|
-
} else params.set(key, String(value));
|
|
129
|
-
}
|
|
130
|
-
const text = params.toString();
|
|
131
|
-
return text ? `?${text}` : "";
|
|
132
|
-
}
|
|
133
|
-
/** A `can` as the wire takes it: `'none'` at a pattern is `[]`. */
|
|
134
|
-
function wireCan(can) {
|
|
135
|
-
if (can === null || typeof can !== "object" || Array.isArray(can)) return can;
|
|
136
|
-
return Object.fromEntries(Object.entries(can).map(([pattern, grant]) => [pattern, grant === "none" ? [] : grant]));
|
|
137
|
-
}
|
|
138
|
-
/** A principal to grant as the wire takes it: a project's environments, and every project's, are production when left out. */
|
|
139
|
-
const withEnvironments = (principal) => (principal.kind === "project" || principal.kind === "all-projects") && principal.environments === void 0 ? {
|
|
140
|
-
...principal,
|
|
141
|
-
environments: ["production"]
|
|
142
|
-
} : principal;
|
|
143
|
-
/** A grant as the wire takes it. */
|
|
144
|
-
const wireGrant = (input) => ({
|
|
145
|
-
principals: input.principals.map(withEnvironments),
|
|
146
|
-
can: wireCan(input.can)
|
|
147
|
-
});
|
|
148
|
-
/** What a grant write's body says to go ahead with a lockout: nothing, unless it was asked to. */
|
|
149
|
-
const goAhead = ({ lockMeOut }) => lockMeOut ? { lockMeOut: true } : {};
|
|
150
|
-
/**
|
|
151
|
-
* The principal a private channel lets its creator in as, from what `/me` says it is: a person's
|
|
152
|
-
* user, or a deployment's project in the environment it runs in. Anyone else is refused before
|
|
153
|
-
* anything is written.
|
|
154
|
-
*/
|
|
155
|
-
function creatorOf(me, path) {
|
|
156
|
-
const [source, kind, id, environment] = me.principal.split(":");
|
|
157
|
-
if ((source === "vercel" || source === "local") && kind === "user" && id) return {
|
|
158
|
-
kind: "user",
|
|
159
|
-
userId: me.principal.split(":").slice(2).join(":")
|
|
160
|
-
};
|
|
161
|
-
if (source === "vercel" && kind === "project" && id && environment) return {
|
|
162
|
-
kind: "project",
|
|
163
|
-
project: id,
|
|
164
|
-
environments: [environment]
|
|
165
|
-
};
|
|
166
|
-
throw new BoardError("no_own_principal", `A private channel lets its creator in, as a person or a project's deployment, and ${me.principal} is neither, so ${path} wasn't made.`, 400, { hint: "Make it as a person or a deployment, or make it and its grants yourself." });
|
|
167
|
-
}
|
|
168
|
-
function createBoardClient(options) {
|
|
169
|
-
const base = options.url.replace(/\/+$/, "");
|
|
170
|
-
const doFetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
171
|
-
const storeFetch = options.storeFetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
172
|
-
async function headers(auth, as) {
|
|
173
|
-
const out = { ...options.headers ? await resolve(options.headers) : {} };
|
|
174
|
-
if (!auth) return out;
|
|
175
|
-
if (options.token !== void 0) out.authorization = `Bearer ${await resolve(options.token)}`;
|
|
176
|
-
const profile = as !== void 0 ? as : options.profile === void 0 ? null : await resolve(options.profile);
|
|
177
|
-
if (profile !== null) out["x-board-profile"] = formatProfileHeader(typeof profile === "string" ? { name: profile } : profile);
|
|
178
|
-
return out;
|
|
179
|
-
}
|
|
180
|
-
async function raw(method, path, init = {}) {
|
|
181
|
-
const response = await doFetch(`${base}${path}`, {
|
|
182
|
-
method,
|
|
183
|
-
headers: {
|
|
184
|
-
...await headers(init.auth ?? true),
|
|
185
|
-
...init.body === void 0 ? {} : { "content-type": "application/json" },
|
|
186
|
-
...init.headers
|
|
187
|
-
},
|
|
188
|
-
...init.body === void 0 ? {} : { body: JSON.stringify(init.body) },
|
|
189
|
-
...init.signal ? { signal: init.signal } : {}
|
|
190
|
-
});
|
|
191
|
-
if (!response.ok) throw await toError(response);
|
|
192
|
-
return response;
|
|
193
|
-
}
|
|
194
|
-
async function call(method, path, init) {
|
|
195
|
-
return await (await raw(method, path, init)).json();
|
|
196
|
-
}
|
|
197
|
-
const filtersQuery = (filters = {}) => filters;
|
|
198
|
-
async function poll(query = {}, signal) {
|
|
199
|
-
return call("GET", `/events${queryString(query)}`, signal ? { signal } : {});
|
|
200
|
-
}
|
|
201
|
-
/** One write to task `id`, which answers its root. */
|
|
202
|
-
const taskWrite = async (id, verb, body = {}) => (await call("POST", `/tasks/${path(id)}/${verb}`, { body })).task;
|
|
203
|
-
/** What a claim on task `id` does, with the `epoch` and `token` the claim answered. */
|
|
204
|
-
const held = (id, proof) => {
|
|
205
|
-
const { epoch, token } = proof;
|
|
206
|
-
return {
|
|
207
|
-
async renew(lease) {
|
|
208
|
-
const { task, until } = await call("POST", `/tasks/${path(id)}/renew`, { body: {
|
|
209
|
-
epoch,
|
|
210
|
-
token,
|
|
211
|
-
...lease !== void 0 ? { lease } : {}
|
|
212
|
-
} });
|
|
213
|
-
return claimed(task, {
|
|
214
|
-
epoch,
|
|
215
|
-
token,
|
|
216
|
-
until
|
|
217
|
-
});
|
|
218
|
-
},
|
|
219
|
-
release: () => taskWrite(id, "release", {
|
|
220
|
-
epoch,
|
|
221
|
-
token
|
|
222
|
-
}),
|
|
223
|
-
complete: (result) => taskWrite(id, "complete", {
|
|
224
|
-
epoch,
|
|
225
|
-
token,
|
|
226
|
-
...result !== void 0 ? { result } : {}
|
|
227
|
-
}),
|
|
228
|
-
fail: (reason) => taskWrite(id, "fail", {
|
|
229
|
-
epoch,
|
|
230
|
-
token,
|
|
231
|
-
reason
|
|
232
|
-
}),
|
|
233
|
-
block: (reason, opts = {}) => taskWrite(id, "block", {
|
|
234
|
-
epoch,
|
|
235
|
-
token,
|
|
236
|
-
reason,
|
|
237
|
-
...opts
|
|
238
|
-
})
|
|
239
|
-
};
|
|
240
|
-
};
|
|
241
|
-
/** A claim as a handle answers it: the task, the claim, and what the claim does. */
|
|
242
|
-
const claimed = (task, claim) => ({
|
|
243
|
-
task,
|
|
244
|
-
...claim,
|
|
245
|
-
...held(task.id, claim)
|
|
246
|
-
});
|
|
247
|
-
async function createTask(target, input = {}) {
|
|
248
|
-
const where = typeof target === "string" ? { channel: target } : { re: target.re };
|
|
249
|
-
const made = typeof input === "string" ? { text: input } : "attachments" in input && input.attachments?.length ? {
|
|
250
|
-
...input,
|
|
251
|
-
attachments: input.attachments.map((file) => typeof file === "string" ? file : file.id)
|
|
252
|
-
} : input;
|
|
253
|
-
const { task, claim, mentions } = await call("POST", "/tasks", { body: {
|
|
254
|
-
...where,
|
|
255
|
-
...made
|
|
256
|
-
} });
|
|
257
|
-
return {
|
|
258
|
-
task,
|
|
259
|
-
...claim ? { claim: claimed(task, claim) } : {},
|
|
260
|
-
...mentions ? { mentions } : {}
|
|
261
|
-
};
|
|
262
|
-
}
|
|
263
|
-
/**
|
|
264
|
-
* Starts a thread in `channel` for each of `tasks`, as tasks, in one write: all of them or none,
|
|
265
|
-
* and none shows before all have landed. It answers their roots in the order given. A task waits
|
|
266
|
-
* for the ones made with it by their `key`. With `id`, a retry answers the tasks the first call
|
|
267
|
-
* made. A board makes 100 at most, and throws a 400 `batch_too_large` for more, or for more than it
|
|
268
|
-
* holds in one write: `createTasksInChunks` makes a longer plan, in several.
|
|
269
|
-
*/
|
|
270
|
-
async function createTasks(channel, tasks, opts = {}) {
|
|
271
|
-
return (await call("POST", "/tasks/batch", { body: {
|
|
272
|
-
channel,
|
|
273
|
-
tasks: tasks.map((task) => task.attachments?.length ? {
|
|
274
|
-
...task,
|
|
275
|
-
attachments: task.attachments.map((file) => typeof file === "string" ? file : file.id)
|
|
276
|
-
} : task),
|
|
277
|
-
...opts.id !== void 0 ? { id: opts.id } : {}
|
|
278
|
-
} })).tasks;
|
|
279
|
-
}
|
|
280
|
-
async function claimTask(target, opts = {}) {
|
|
281
|
-
const signal = opts.signal ? { signal: opts.signal } : {};
|
|
282
|
-
if (typeof target === "string") {
|
|
283
|
-
const body = {
|
|
284
|
-
...opts.lease !== void 0 ? { lease: opts.lease } : {},
|
|
285
|
-
...opts.token !== void 0 ? { token: opts.token } : {}
|
|
286
|
-
};
|
|
287
|
-
const { task, claim } = await call("POST", `/tasks/${path(target)}/claim`, {
|
|
288
|
-
body,
|
|
289
|
-
...signal
|
|
290
|
-
});
|
|
291
|
-
return claimed(task, claim);
|
|
292
|
-
}
|
|
293
|
-
const { wait, ...ready } = target;
|
|
294
|
-
const deadline = Date.now() + (wait ?? 0) * 1e3;
|
|
295
|
-
for (;;) {
|
|
296
|
-
const asked = Date.now();
|
|
297
|
-
const hold = Math.max(0, Math.min(CLAIM_WAIT_S, (deadline - asked) / 1e3));
|
|
298
|
-
const answer = await call("POST", "/tasks/claim", {
|
|
299
|
-
body: {
|
|
300
|
-
...ready,
|
|
301
|
-
...hold > 0 ? { wait: hold } : {}
|
|
302
|
-
},
|
|
303
|
-
...signal
|
|
304
|
-
});
|
|
305
|
-
if (answer.task) return claimed(answer.task, answer.claim);
|
|
306
|
-
if (Date.now() >= deadline || opts.signal?.aborted) return null;
|
|
307
|
-
const pause = Math.min(CLAIM_AGAIN_MS - (Date.now() - asked), deadline - Date.now());
|
|
308
|
-
if (pause > 0) await new Promise((resolve) => setTimeout(resolve, pause));
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
return {
|
|
312
|
-
url: base,
|
|
313
|
-
/**
|
|
314
|
-
* The board's HTTP API with this client's credentials, and the response as
|
|
315
|
-
* the board sent it, errors included: for proxies like `vb inspect`.
|
|
316
|
-
*/
|
|
317
|
-
request: async (path, init = {}) => doFetch(`${base}${path}`, {
|
|
318
|
-
method: init.method ?? "GET",
|
|
319
|
-
headers: {
|
|
320
|
-
...init.headers,
|
|
321
|
-
...await headers(true, init.as)
|
|
322
|
-
},
|
|
323
|
-
...init.body ? { body: init.body } : {},
|
|
324
|
-
...init.signal ? { signal: init.signal } : {}
|
|
325
|
-
}),
|
|
326
|
-
discovery: () => call("GET", "/", { auth: false }),
|
|
327
|
-
me: () => call("GET", "/me"),
|
|
328
|
-
/**
|
|
329
|
-
* A page of the board's channels: `prefix` keeps the ones whose path starts with it (`dev/`), `limit` is how many
|
|
330
|
-
* (100 unless it says, 500 at most), and `after` takes a page's `next`, which is null on the last.
|
|
331
|
-
*/
|
|
332
|
-
channels: async (query = {}) => {
|
|
333
|
-
const page = await call("GET", `/channels${queryString(query)}`);
|
|
334
|
-
return {
|
|
335
|
-
...page,
|
|
336
|
-
next: page.next ?? null
|
|
337
|
-
};
|
|
338
|
-
},
|
|
339
|
-
/**
|
|
340
|
-
* Makes a channel before anything posts to it, as a first post would. Needs `read` and `post`
|
|
341
|
-
* there. `created` is false when it was there already; it's left as it is.
|
|
342
|
-
*
|
|
343
|
-
* `private` makes it closed to everyone but you, from the protocol's own methods: a grant
|
|
344
|
-
* letting you in at `<path>/`, then one closing `<path>/` to everyone else, then the channel,
|
|
345
|
-
* answering the two grants as `grants`. A failure part way leaves the channel open with a grant
|
|
346
|
-
* too many, or closed and not made yet, and never shuts you out. Before it writes anything, it
|
|
347
|
-
* refuses a caller that's neither a person nor a project's deployment (400 `no_own_principal`),
|
|
348
|
-
* one that can't list grants, a path a grant other than `*`'s reaches already (409
|
|
349
|
-
* `channel_granted`: the channel, `<path>/`, or a pattern under it, whose grants would still let
|
|
350
|
-
* in whoever they name), and a path where it or a channel under it is there already (409
|
|
351
|
-
* `channel_exists`), since closing `security/` closes `security/incidents` too. A board that
|
|
352
|
-
* keeps no grants fails on the listing, with nothing made. Once its own grant is made it lists
|
|
353
|
-
* them again, and takes its own back when another reaches the path, so of two callers making
|
|
354
|
-
* the same channel at once, at most one keeps a way in; and once the lock is made, it lists them
|
|
355
|
-
* a last time, and takes both back when a grant made in between still reaches the path, or its
|
|
356
|
-
* own two aren't as it made them (someone added themselves to its grant, or opened the lock).
|
|
357
|
-
*/
|
|
358
|
-
createChannel: async (path, options = {}) => {
|
|
359
|
-
if (!options.private) return call("POST", "/channels", { body: { path } });
|
|
360
|
-
const creator = creatorOf(await call("GET", "/me"), path);
|
|
361
|
-
const pattern = `${path}/`;
|
|
362
|
-
const reaching = async () => (await call("GET", "/grants")).grants.filter((grant) => Object.keys(grant.can).some((at) => at === path || at.startsWith(pattern)));
|
|
363
|
-
const granted = (grants, mine = []) => {
|
|
364
|
-
const changed = grants.filter((grant) => mine.some((ours) => ours.id === grant.id)).map((grant) => grant.id);
|
|
365
|
-
if (changed.length === grants.length) return new BoardError("channel_granted", `${changed.join(" and ")} changed while ${path} was being made, so a private ${path} wouldn't be yours alone: nothing was made.`, 409);
|
|
366
|
-
const named = grants.filter((grant) => !changed.includes(grant.id)).map((grant) => grant.id);
|
|
367
|
-
return new BoardError("channel_granted", `${named.length === 1 ? named[0] : `${named.slice(0, -1).join(", ")} and ${named.at(-1)}`} already ${named.length === 1 ? "grants" : "grant"} in ${path}, so a private ${path} wouldn't be yours alone: nothing was made.`, 409, { hint: named.length === 1 ? `Revoke it first: vb grants revoke ${named[0]}` : "Revoke them first, each with vb grants revoke <id>." });
|
|
368
|
-
};
|
|
369
|
-
const before = await reaching();
|
|
370
|
-
if (before.length > 0) throw granted(before);
|
|
371
|
-
const first = async (prefix) => (await call("GET", `/channels${queryString({
|
|
372
|
-
prefix,
|
|
373
|
-
limit: 1
|
|
374
|
-
})}`)).channels.find((channel) => channel.path === path || channel.path.startsWith(pattern));
|
|
375
|
-
const there = await first(path) ?? await first(pattern);
|
|
376
|
-
if (there) throw new BoardError("channel_exists", there.path === path ? `${path} is a channel already, so it stays as it is.` : `${there.path} is a channel already, and a private ${path} would close it too, so nothing was made.`, 409, { hint: `Close it with a grant: everyone at ${pattern} with 'none'.` });
|
|
377
|
-
const own = await call("POST", "/grants", { body: {
|
|
378
|
-
principals: [creator],
|
|
379
|
-
can: { [pattern]: "all" }
|
|
380
|
-
} });
|
|
381
|
-
const takeBack = (id) => {
|
|
382
|
-
const revoke = (body) => call("POST", `/grants/${encodeURIComponent(id)}/revoke`, { body });
|
|
383
|
-
return revoke({}).catch((error) => {
|
|
384
|
-
if (error instanceof BoardError && error.code === "grant_lockout") return revoke({ lockMeOut: true });
|
|
385
|
-
throw error;
|
|
386
|
-
});
|
|
387
|
-
};
|
|
388
|
-
const others = (grants, mine) => grants.filter((grant) => {
|
|
389
|
-
const made = mine.find((ours) => ours.id === grant.id);
|
|
390
|
-
return made === void 0 || JSON.stringify([grant.principals, grant.can]) !== JSON.stringify([made.principals, made.can]);
|
|
391
|
-
});
|
|
392
|
-
const raced = others(await reaching(), [own.grant]);
|
|
393
|
-
if (raced.length > 0) {
|
|
394
|
-
await takeBack(own.grant.id);
|
|
395
|
-
throw granted(raced, [own.grant]);
|
|
396
|
-
}
|
|
397
|
-
const closed = await call("POST", "/grants", { body: {
|
|
398
|
-
principals: [{ kind: "everyone" }],
|
|
399
|
-
can: { [pattern]: [] }
|
|
400
|
-
} });
|
|
401
|
-
const late = others(await reaching(), [own.grant, closed.grant]);
|
|
402
|
-
if (late.length > 0) {
|
|
403
|
-
for (const id of [closed.grant.id, own.grant.id]) await takeBack(id);
|
|
404
|
-
throw granted(late, [own.grant, closed.grant]);
|
|
405
|
-
}
|
|
406
|
-
return {
|
|
407
|
-
...await call("POST", "/channels", { body: { path } }),
|
|
408
|
-
grants: [own.grant, closed.grant]
|
|
409
|
-
};
|
|
410
|
-
},
|
|
411
|
-
actors: async () => (await call("GET", "/actors")).actors,
|
|
412
|
-
/**
|
|
413
|
-
* One channel, by its whole name: a board lists messages a channel at a time, never across channels. Its
|
|
414
|
-
* `messages()` are the channel's across its threads, oldest first: the newest `limit` (50 without one), or with
|
|
415
|
-
* `after`, a cursor a read of this channel answered, the ones posted since.
|
|
416
|
-
*/
|
|
417
|
-
channel: (name) => ({ messages: (query = {}) => call("GET", `/messages${queryString({
|
|
418
|
-
channel: name,
|
|
419
|
-
...query
|
|
420
|
-
})}`) }),
|
|
421
|
-
/**
|
|
422
|
-
* A thread: its root and its replies. `after`, one of its messages, answers the replies after it, and `limit` that
|
|
423
|
-
* many of them: with `after` the first after it, to read on from, and without, the newest.
|
|
424
|
-
*/
|
|
425
|
-
thread: (id, range = {}) => call("GET", `/messages/${path(id)}${queryString(range)}`),
|
|
426
|
-
/** Your own post with the client ID you gave it, as posting it answered: 404 `post_not_found` when there's none. */
|
|
427
|
-
posted: async (id) => (await call("GET", `/posts/${path(id)}`)).message,
|
|
428
|
-
/** Threads with a matching message, one summary each (root, reply count, latest reply), by latest activity. `limit` counts threads; `before` takes a page's `older`. */
|
|
429
|
-
threads: (query = {}) => call("GET", `/threads${queryString(query)}`),
|
|
430
|
-
/**
|
|
431
|
-
* Starts a thread. An `@handle` in the text that names exactly one actor you can see is stored as
|
|
432
|
-
* `@[actor-id]`, a mention of them; one that names none or several stays as typed, a mention of
|
|
433
|
-
* no one. `mentions` on what comes back says what became of each, when the text typed any.
|
|
434
|
-
*/
|
|
435
|
-
async post(channel, input) {
|
|
436
|
-
const { message, mentions } = await call("POST", "/messages", { body: {
|
|
437
|
-
channel,
|
|
438
|
-
...messageBody(input)
|
|
439
|
-
} });
|
|
440
|
-
return mentions ? {
|
|
441
|
-
...message,
|
|
442
|
-
mentions
|
|
443
|
-
} : message;
|
|
444
|
-
},
|
|
445
|
-
/** Replies in a thread. Its `@handle`s are settled as `post`'s are: of several who share one, it's the one who wrote in the thread. */
|
|
446
|
-
async reply(id, input) {
|
|
447
|
-
const { message, mentions } = await call("POST", "/messages", { body: {
|
|
448
|
-
re: id,
|
|
449
|
-
...messageBody(input)
|
|
450
|
-
} });
|
|
451
|
-
return mentions ? {
|
|
452
|
-
...message,
|
|
453
|
-
mentions
|
|
454
|
-
} : message;
|
|
455
|
-
},
|
|
456
|
-
/**
|
|
457
|
-
* Posts later, as you: a new thread when `target` is a channel, a reply when it's
|
|
458
|
-
* `{ re }`, any message's ID in the thread. Each message it posts carries
|
|
459
|
-
* `schedule: { id, n }`. Needs a board with a scheduler.
|
|
460
|
-
*/
|
|
461
|
-
async schedule(target, input) {
|
|
462
|
-
const { schedule, mentions } = await call("POST", "/schedules", { body: {
|
|
463
|
-
...typeof target === "string" ? { channel: target } : { re: target.re },
|
|
464
|
-
...scheduleBody(input)
|
|
465
|
-
} });
|
|
466
|
-
return mentions ? {
|
|
467
|
-
...schedule,
|
|
468
|
-
mentions
|
|
469
|
-
} : schedule;
|
|
470
|
-
},
|
|
471
|
-
/** Pending schedules (`all` for done and canceled too), oldest first. `re` is any message in a thread. */
|
|
472
|
-
schedules: async (query = {}) => (await call("GET", `/schedules${queryString(query)}`)).schedules,
|
|
473
|
-
/** Stops a schedule: yours, or any with manage in its channel. `canceled` is false when it was already done or canceled. */
|
|
474
|
-
cancelSchedule: (id) => call("POST", `/schedules/${path(id)}/cancel`, { body: {} }),
|
|
475
|
-
/**
|
|
476
|
-
* Tasks: threads someone's agents are to do, with a state the board keeps. A task's ID is its
|
|
477
|
-
* root's, and its root's `task` says its state, whose it is, what it waits for, and who holds
|
|
478
|
-
* it. A board that keeps no tasks fails each of these with 501 `no_tasks`.
|
|
479
|
-
*/
|
|
480
|
-
tasks: {
|
|
481
|
-
/**
|
|
482
|
-
* Tasks, oldest first, each as its thread's summary: open ones (`waiting`, `ready`, `claimed`,
|
|
483
|
-
* `blocked`) unless `state` says `all` or names one. `owner` and `for` take a handle or an ID,
|
|
484
|
-
* `needs` a task's ID, for the tasks that wait for it. `cursor`, as `after`, reads the next page.
|
|
485
|
-
* `latest` answers the `limit` last active instead, the latest active last: the board reads every
|
|
486
|
-
* task to find them, and builds only those.
|
|
487
|
-
*/
|
|
488
|
-
list: (query = {}) => call("GET", `/tasks${queryString(query)}`),
|
|
489
|
-
create: createTask,
|
|
490
|
-
createMany: createTasks,
|
|
491
|
-
claim: claimTask,
|
|
492
|
-
/** What a claim you hold does, from the `epoch` and `token` it answered: for a process that kept them, as `vb` does between commands. */
|
|
493
|
-
held,
|
|
494
|
-
/** Holds a task no one has claimed for a person: yours, or any with manage in its channel. A claimed one's hold is its claim's (`claim.block`). */
|
|
495
|
-
block: (id, reason, opts = {}) => taskWrite(id, "block", {
|
|
496
|
-
reason,
|
|
497
|
-
...opts
|
|
498
|
-
}),
|
|
499
|
-
/** Lifts a hold: the task is ready again, or waiting while a task it needs hasn't completed. */
|
|
500
|
-
unblock: (id) => taskWrite(id, "unblock"),
|
|
501
|
-
/** Makes a failed task ready again, in place: what waits for it still does. */
|
|
502
|
-
reopen: (id) => taskWrite(id, "reopen"),
|
|
503
|
-
/** Assigns a task to one of its owner's actors (`<owner>+<profile>`), the only one that claims it then, or with null to anyone who may. */
|
|
504
|
-
assign: (id, actor) => taskWrite(id, "assign", { for: actor }),
|
|
505
|
-
/**
|
|
506
|
-
* Replaces what a task waits for, by their IDs: it waits for those now, and is ready once they've all completed, or
|
|
507
|
-
* at once with none. For its owner, while no one holds it and it isn't finished. One that would make it wait for
|
|
508
|
-
* itself, through however many tasks, throws a 400 `invalid_needs`.
|
|
509
|
-
*/
|
|
510
|
-
needs: (id, needs) => taskWrite(id, "needs", { needs }),
|
|
511
|
-
/** Cancels a task that hasn't completed, ending any claim. What waits for it keeps waiting. */
|
|
512
|
-
cancel: (id, reason) => taskWrite(id, "cancel", { reason })
|
|
513
|
-
},
|
|
514
|
-
/**
|
|
515
|
-
* A new grant: `principals` may do what `can` says, a map from channel pattern to permissions
|
|
516
|
-
* (`[]` for none). The same principals again are another grant. At each channel, the most
|
|
517
|
-
* specific pattern among the grants that name a caller decides, then the closest principal,
|
|
518
|
-
* and grants tied there add up. Needs manage at each pattern `can` names.
|
|
519
|
-
*
|
|
520
|
-
* One you couldn't take back, since it takes your own manage at a pattern it names (closing
|
|
521
|
-
* `security/` to `everyone` closes it to you), is 409 `grant_lockout`: keep yourself in with
|
|
522
|
-
* `createGrants`, or pass `lockMeOut` to make it anyway. Every grant write takes it.
|
|
523
|
-
*/
|
|
524
|
-
createGrant: (input, options = {}) => call("POST", "/grants", { body: {
|
|
525
|
-
...wireGrant(input),
|
|
526
|
-
...goAhead(options)
|
|
527
|
-
} }),
|
|
528
|
-
/**
|
|
529
|
-
* Several grants in one write, all of them or none, judged together: each needs what
|
|
530
|
-
* `createGrant` does on the grants as they are, and what they leave you with is judged with
|
|
531
|
-
* all of them made. So a lock and the grant that keeps you in go together, in any order.
|
|
532
|
-
*/
|
|
533
|
-
createGrants: (inputs, options = {}) => call("POST", "/grants/batch", { body: {
|
|
534
|
-
grants: inputs.map(wireGrant),
|
|
535
|
-
...goAhead(options)
|
|
536
|
-
} }),
|
|
537
|
-
/** Adds and removes principals (by who they are, environments aside), or replaces its `can`. Needs what `checkGrantChange` says, for the grant as it was and as it'd be. */
|
|
538
|
-
updateGrant: (id, { add, remove, can }, options = {}) => call("PATCH", `/grants/${path(id)}`, { body: {
|
|
539
|
-
...add ? { add: add.map(withEnvironments) } : {},
|
|
540
|
-
...remove ? { remove } : {},
|
|
541
|
-
...can ? { can: wireCan(can) } : {},
|
|
542
|
-
...goAhead(options)
|
|
543
|
-
} }),
|
|
544
|
-
/**
|
|
545
|
-
* Which grants decide `channel`, and what they give: for you, or with manage at `*`, for the
|
|
546
|
-
* principal `principal` names (`{ user }`, `{ project, environment }`, `{ github, workflow,
|
|
547
|
-
* branch, event }`, or `{ oidc, claims }`).
|
|
548
|
-
*/
|
|
549
|
-
explain: (channel, principal = {}) => {
|
|
550
|
-
const { claims, ...rest } = principal;
|
|
551
|
-
const params = new URLSearchParams({ channel });
|
|
552
|
-
for (const [name, value] of Object.entries(rest)) if (value !== void 0) params.set(name, value);
|
|
553
|
-
for (const [name, value] of Object.entries(claims ?? {})) params.append("claim", `${name}=${value}`);
|
|
554
|
-
return call("GET", `/grants/explain?${params}`);
|
|
555
|
-
},
|
|
556
|
-
/** The board's grants. Needs manage at `*`, or a team owner. */
|
|
557
|
-
grants: async () => (await call("GET", "/grants")).grants,
|
|
558
|
-
/** `revoked` is false when it was already gone. Its principals' next requests are refused. */
|
|
559
|
-
revokeGrant: (id, options = {}) => call("POST", `/grants/${path(id)}/revoke`, { body: goAhead(options) }),
|
|
560
|
-
/** Every schema: the built-ins, then the board's own, by name and version. */
|
|
561
|
-
schemas: async () => (await call("GET", "/schemas")).schemas,
|
|
562
|
-
/** One schema version, by its ID: `sandbox@1`. */
|
|
563
|
-
schema: async (id) => (await call("GET", `/schemas/${path(id)}`)).schema,
|
|
564
|
-
/**
|
|
565
|
-
* Registers a schema version, for good: `schema` is a JSON Schema for an object, in structural
|
|
566
|
-
* keywords only. Needs manage at `*`. `created` is false for one that's there with the same
|
|
567
|
-
* definition; another definition is refused, since a version never changes.
|
|
568
|
-
*/
|
|
569
|
-
createSchema: (input) => call("POST", "/schemas", { body: input }),
|
|
570
|
-
/**
|
|
571
|
-
* Stores a file on the board, for a post or reply's `attachments`. Up to 4 MB goes in one
|
|
572
|
-
* request; bigger, up to 100 MB, goes straight to the board's blob store on a URL the board
|
|
573
|
-
* signs, where its store can (`no_direct_uploads` where it can't).
|
|
574
|
-
*/
|
|
575
|
-
async upload(input) {
|
|
576
|
-
const type = input.type || (input.data instanceof Blob ? input.data.type : "") || typeOf(input.name);
|
|
577
|
-
const size = input.data instanceof Blob ? input.data.size : input.data.byteLength;
|
|
578
|
-
if (size > 4194304) {
|
|
579
|
-
if (size > 104857600) throw new BoardError("too_large", `Attachments are at most ${DIRECT_UPLOAD_BYTES_MAX / 1024 / 1024} MB.`, 413);
|
|
580
|
-
const bytes = input.data instanceof Blob ? await input.data.arrayBuffer() : input.data;
|
|
581
|
-
const sha256 = btoa(String.fromCharCode(...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))));
|
|
582
|
-
const ticket = await call("POST", "/attachments/uploads", { body: {
|
|
583
|
-
name: input.name,
|
|
584
|
-
type,
|
|
585
|
-
size,
|
|
586
|
-
sha256
|
|
587
|
-
} }).catch((error) => {
|
|
588
|
-
if (error instanceof BoardError && error.status === 404 && error.code === "not_found") throw new BoardError("too_large", `This board takes files of at most ${ATTACHMENT_BYTES_MAX / 1024 / 1024} MB.`, 413);
|
|
589
|
-
throw error;
|
|
590
|
-
});
|
|
591
|
-
const put = await storeFetch(ticket.url, {
|
|
592
|
-
method: "PUT",
|
|
593
|
-
headers: ticket.headers,
|
|
594
|
-
body: input.data
|
|
595
|
-
});
|
|
596
|
-
if (!put.ok) throw new BoardError("upload_failed", `The blob store refused the file: ${put.status} ${(await put.text().catch(() => "")).slice(0, 300) || put.statusText}`, put.status);
|
|
597
|
-
return (await call("POST", `/attachments/uploads/${encodeURIComponent(ticket.id)}`, { body: {} })).attachment;
|
|
598
|
-
}
|
|
599
|
-
const response = await doFetch(`${base}/attachments`, {
|
|
600
|
-
method: "POST",
|
|
601
|
-
headers: {
|
|
602
|
-
...await headers(true),
|
|
603
|
-
"content-type": type,
|
|
604
|
-
"x-board-filename": encodeURIComponent(input.name)
|
|
605
|
-
},
|
|
606
|
-
body: input.data
|
|
607
|
-
});
|
|
608
|
-
if (!response.ok) throw await toError(response);
|
|
609
|
-
return (await response.json()).attachment;
|
|
610
|
-
},
|
|
611
|
-
/** An attachment's bytes, as the board serves them: `content-type` is the file's type. */
|
|
612
|
-
download: (id, opts = {}) => raw("GET", `/attachments/${encodeURIComponent(id)}`, opts.signal ? { signal: opts.signal } : {}),
|
|
613
|
-
/**
|
|
614
|
-
* `revision` is the message's as you read it: if it's been edited or deleted since, nothing
|
|
615
|
-
* changes, and it throws a 409 `revision_conflict`.
|
|
616
|
-
*/
|
|
617
|
-
edit: (id, text, opts = {}) => call("POST", `/messages/${path(id)}/edit`, { body: {
|
|
618
|
-
text,
|
|
619
|
-
...opts
|
|
620
|
-
} }),
|
|
621
|
-
delete: (id, opts = {}) => call("POST", `/messages/${path(id)}/delete`, { body: { ...opts } }),
|
|
622
|
-
/** `emoji` is a short name, `:name:`, or the character itself. */
|
|
623
|
-
react: (id, emoji, opts = {}) => call("POST", `/messages/${path(id)}/reactions`, { body: {
|
|
624
|
-
emoji: normalizeEmoji(emoji),
|
|
625
|
-
...opts
|
|
626
|
-
} }),
|
|
627
|
-
/**
|
|
628
|
-
* `if` is what the labels must be now, a value or null for one that mustn't be set: if one
|
|
629
|
-
* isn't, nothing changes, and it throws a 409 `label_conflict`.
|
|
630
|
-
*/
|
|
631
|
-
label: (id, change) => call("POST", `/messages/${path(id)}/labels`, { body: change }),
|
|
632
|
-
/**
|
|
633
|
-
* Shows typing in the platform threads the message's thread is synced to.
|
|
634
|
-
* Ephemeral: nothing goes in the log. Answers the external threads that took it.
|
|
635
|
-
* `status` replaces "Typing…" on Slack ("running tests…").
|
|
636
|
-
*/
|
|
637
|
-
typing: async (id, status) => (await call("POST", `/messages/${path(id)}/typing`, { body: status ? { status } : {} })).targets,
|
|
638
|
-
/**
|
|
639
|
-
* With a target, attaches the message's thread to it, backfilling it: attaching twice is a no-op.
|
|
640
|
-
* Without one, where the thread is synced, and this message's copy on each target, with its link.
|
|
641
|
-
*/
|
|
642
|
-
sync: ((id, target) => target === void 0 ? call("GET", `/messages/${path(id)}/sync`) : call("POST", `/messages/${path(id)}/sync`, { body: { target } })),
|
|
643
|
-
/**
|
|
644
|
-
* The thread of the board message a platform link names (a Slack permalink, a GitHub comment's
|
|
645
|
-
* URL), from what the board synced: the platform is never asked. 404 for one it didn't sync.
|
|
646
|
-
*/
|
|
647
|
-
linked: (url) => call("GET", `/links${queryString({ url })}`),
|
|
648
|
-
/** Raw platform events for a sync entry, newest first. */
|
|
649
|
-
inbox: async (key, opts = {}) => (await call("GET", `/inbox/${key}${queryString(opts)}`)).events,
|
|
650
|
-
/** Registers the caller's watchers, replacing its last registration: what a board on `http()` does. */
|
|
651
|
-
register: (input) => call("POST", "/watchers", { body: input }),
|
|
652
|
-
/** Registered watchers: every one to `manage` everywhere, the caller's own to anyone else. */
|
|
653
|
-
watchers: async () => (await call("GET", "/watchers")).watchers,
|
|
654
|
-
/** The caller's matches it can run now, each leased to it until it acks. `wait` holds the request up to that many seconds for one. */
|
|
655
|
-
matches: async (opts = {}) => {
|
|
656
|
-
const { signal, ...query } = opts;
|
|
657
|
-
return (await call("GET", `/watchers/matches${queryString(query)}`, signal ? { signal } : {})).matches;
|
|
658
|
-
},
|
|
659
|
-
/** How a pulled match went: done, an error to try again, or `skip` to drop it. */
|
|
660
|
-
ack: (id, body) => call("POST", `/watchers/matches/${encodeURIComponent(id)}/ack`, { body }),
|
|
661
|
-
/**
|
|
662
|
-
* Reads a platform channel (`#name`, an ID), thread (`C0123:1727000000.123456`),
|
|
663
|
-
* or message permalink on demand, without syncing or storing it. Full access only.
|
|
664
|
-
*/
|
|
665
|
-
readSource: (key, target, opts = {}) => call("GET", `/sources/${key}/read${queryString({
|
|
666
|
-
target,
|
|
667
|
-
...opts
|
|
668
|
-
})}`),
|
|
669
|
-
/** Adds the app to a public channel so `readSource` can read it, where the sync opted in with `join`. Full access only. */
|
|
670
|
-
joinSource: (key, target) => call("POST", `/sources/${key}/join`, { body: { target } }),
|
|
671
|
-
poll,
|
|
672
|
-
/** A platform's write, as its platform author: idempotent per platform event for a post, found from its origin otherwise. */
|
|
673
|
-
syncImport: (body) => call("POST", "/sync/imports", { body }),
|
|
674
|
-
/** What sync did on a platform: a delivery, its files, a failure, or a thread's new target. */
|
|
675
|
-
syncReceipt: (body) => call("POST", "/sync/receipts", { body }),
|
|
676
|
-
/** A board thread's sync, by its key. */
|
|
677
|
-
syncThread: (thread) => call("GET", `/sync/threads/${path(thread)}`),
|
|
678
|
-
/** What platform IDs are on the board: a thread, or a message. */
|
|
679
|
-
syncFind: (query, opts = {}) => call("GET", `/sync/find${queryString(query)}`, opts.signal ? { signal: opts.signal } : {}),
|
|
680
|
-
/** Messages' copies on platforms, by message and target. */
|
|
681
|
-
syncCopies: async (messages) => (await call("GET", `/sync/copies?${messages.map((id) => `message=${encodeURIComponent(id)}`).join("&")}`)).copies,
|
|
682
|
-
/** Pushes platform events into your inbox for sync key `key`; each platform ID lands once. */
|
|
683
|
-
inboxPush: (key, events) => call("POST", `/inbox/${path(key)}`, { body: { events } }),
|
|
684
|
-
/** Your next inbox events for `key`, leased to you until you ack them, one platform thread at a time. */
|
|
685
|
-
inboxNext: async (key, opts = {}) => (await call("GET", `/inbox/${path(key)}/next${queryString(opts)}`)).items,
|
|
686
|
-
/** How an inbox event went: done, or an error to try it again. */
|
|
687
|
-
inboxAck: (key, id, body) => call("POST", `/inbox/${path(key)}/${path(id)}/ack`, { body }),
|
|
688
|
-
/** Live events. Reconnects from the last seen index whenever the stream closes, and tells `onState` whether it's live or retrying. */
|
|
689
|
-
async *events(query = {}, opts = {}) {
|
|
690
|
-
const { last, ...rest } = query;
|
|
691
|
-
let after = query.after;
|
|
692
|
-
let failures = 0;
|
|
693
|
-
const state = eventsState(opts.onState);
|
|
694
|
-
while (!opts.signal?.aborted) {
|
|
695
|
-
let response;
|
|
696
|
-
try {
|
|
697
|
-
response = await raw("GET", `/events${queryString({
|
|
698
|
-
...filtersQuery(rest),
|
|
699
|
-
...after === void 0 && last !== void 0 ? { last } : {},
|
|
700
|
-
after
|
|
701
|
-
})}`, {
|
|
702
|
-
headers: { accept: "text/event-stream" },
|
|
703
|
-
...opts.signal ? { signal: opts.signal } : {}
|
|
704
|
-
});
|
|
705
|
-
} catch (error) {
|
|
706
|
-
if (opts.signal?.aborted) return;
|
|
707
|
-
if (error instanceof BoardError && (error.status === 501 || error.status >= 400 && error.status < 500)) throw error;
|
|
708
|
-
state.failed();
|
|
709
|
-
await new Promise((r) => setTimeout(r, Math.min(3e4, 500 * 2 ** failures++)));
|
|
710
|
-
continue;
|
|
711
|
-
}
|
|
712
|
-
failures = 0;
|
|
713
|
-
state.answered();
|
|
714
|
-
try {
|
|
715
|
-
for await (const message of parseSse(response.body, opts.signal)) {
|
|
716
|
-
if (message.id !== void 0) after = message.id;
|
|
717
|
-
if (message.event === "board" && message.data) yield JSON.parse(message.data);
|
|
718
|
-
}
|
|
719
|
-
} catch (error) {
|
|
720
|
-
if (opts.signal?.aborted) return;
|
|
721
|
-
state.failed();
|
|
722
|
-
await new Promise((r) => setTimeout(r, Math.min(3e4, 500 * 2 ** failures++)));
|
|
723
|
-
}
|
|
724
|
-
}
|
|
725
|
-
},
|
|
726
|
-
/** The next matching event after `after` (default: now), or null on timeout. */
|
|
727
|
-
async wait(query = {}, opts = {}) {
|
|
728
|
-
const deadline = Date.now() + duration(opts.timeout ?? "30m");
|
|
729
|
-
let after = query.after ?? (await poll({
|
|
730
|
-
...query,
|
|
731
|
-
after: void 0,
|
|
732
|
-
wait: 0
|
|
733
|
-
}, opts.signal)).cursor;
|
|
734
|
-
while (Date.now() < deadline && !opts.signal?.aborted) {
|
|
735
|
-
const wait = Math.max(0, Math.min(25, Math.ceil((deadline - Date.now()) / 1e3)));
|
|
736
|
-
const page = await poll({
|
|
737
|
-
...query,
|
|
738
|
-
after,
|
|
739
|
-
wait
|
|
740
|
-
}, opts.signal);
|
|
741
|
-
if (page.events.length > 0) return page.events[0];
|
|
742
|
-
after = page.cursor;
|
|
743
|
-
}
|
|
744
|
-
return null;
|
|
745
|
-
}
|
|
746
|
-
};
|
|
747
|
-
}
|
|
748
|
-
async function toError(response) {
|
|
749
|
-
try {
|
|
750
|
-
const body = await response.json();
|
|
751
|
-
const retryAfter = response.status === 429 ? /^\d{1,6}$/.exec(response.headers.get("retry-after") ?? "")?.[0] : void 0;
|
|
752
|
-
if (body.error?.message) return new BoardError(body.error.code ?? "error", body.error.message, response.status, {
|
|
753
|
-
...typeof body.error.hint === "string" ? { hint: body.error.hint } : {},
|
|
754
|
-
origin: handleErrors.has(response) ? "handle" : "board",
|
|
755
|
-
...retryAfter !== void 0 ? { retryAfter: Number(retryAfter) } : {}
|
|
756
|
-
});
|
|
757
|
-
} catch {}
|
|
758
|
-
return new BoardError("http_error", `The board answered ${`${response.status} ${response.statusText}`.trim()}.`, response.status);
|
|
759
|
-
}
|
|
760
|
-
//#endregion
|
|
761
|
-
//#region src/server/errors.ts
|
|
762
|
-
var HttpError = class extends Error {
|
|
763
|
-
status;
|
|
764
|
-
code;
|
|
765
|
-
/** What fixes it, when there's one (`BoardError`'s `hint`). */
|
|
766
|
-
hint;
|
|
767
|
-
/** `handle` for a handle's own error on its way through: everything else is the board's. */
|
|
768
|
-
origin;
|
|
769
|
-
/** For a 429, how many seconds until it's worth sending again, when that's known: the response's `Retry-After`. */
|
|
770
|
-
retryAfter;
|
|
771
|
-
constructor(status, code, message, options = {}) {
|
|
772
|
-
super(message);
|
|
773
|
-
this.status = status;
|
|
774
|
-
this.code = code;
|
|
775
|
-
this.hint = options.hint;
|
|
776
|
-
this.origin = options.origin ?? "board";
|
|
777
|
-
this.retryAfter = options.retryAfter;
|
|
778
|
-
}
|
|
779
|
-
};
|
|
780
|
-
/** A request a host's own verifier rejected with `response`, which the board answers with as it is. */
|
|
781
|
-
var RejectedError = class extends HttpError {
|
|
782
|
-
response;
|
|
783
|
-
constructor(response) {
|
|
784
|
-
super(response.status, "rejected", `rejected with ${response.status}`);
|
|
785
|
-
this.response = response;
|
|
786
|
-
}
|
|
787
|
-
};
|
|
788
|
-
const badRequest = (message, code = "invalid_request") => new HttpError(400, code, message);
|
|
789
|
-
const unauthorized = (message) => new HttpError(401, "unauthorized", message);
|
|
790
|
-
const forbidden = (message) => new HttpError(403, "forbidden", message);
|
|
791
|
-
const notFound = (message, code = "not_found") => new HttpError(404, code, message);
|
|
792
|
-
const textTooLong = () => new HttpError(400, "text_too_long", `A message's text is at most ${MESSAGE_TEXT_MAX.toLocaleString("en-US")} characters.`, { hint: "Put the long part in a file and attach it to a message, with a short summary as the text." });
|
|
793
|
-
const duplicateId = () => new HttpError(409, "duplicate_id", "that id was already used for a different write");
|
|
794
|
-
/** More tasks than a board makes in one batch: `most` is how many it does. Nothing was made, and its sender splits it. */
|
|
795
|
-
const batchTooLarge = (tasks, most) => new HttpError(400, "batch_too_large", `a batch makes ${most} tasks at most, and this one has ${tasks}: send it in parts`);
|
|
796
|
-
const json = (body, status = 200, headers) => new Response(JSON.stringify(body), {
|
|
797
|
-
status,
|
|
798
|
-
headers: {
|
|
799
|
-
"content-type": "application/json",
|
|
800
|
-
...headers
|
|
801
|
-
}
|
|
802
|
-
});
|
|
803
|
-
/**
|
|
804
|
-
* The issue a request is told about. A union that matched no option says only "Invalid input", so
|
|
805
|
-
* it's the first issue of the option that came closest, the one with the fewest, at its own path.
|
|
806
|
-
*/
|
|
807
|
-
function reported(issue) {
|
|
808
|
-
if (issue.code === "invalid_key" && issue.issues[0]) return reported({
|
|
809
|
-
...issue.issues[0],
|
|
810
|
-
path: issue.path.slice(0, -1)
|
|
811
|
-
});
|
|
812
|
-
if (issue.code !== "invalid_union" || issue.errors.length === 0) return issue;
|
|
813
|
-
const first = issue.errors.reduce((best, option) => option.length < best.length ? option : best)[0];
|
|
814
|
-
return first ? reported({
|
|
815
|
-
...first,
|
|
816
|
-
path: [...issue.path, ...first.path]
|
|
817
|
-
}) : issue;
|
|
818
|
-
}
|
|
819
|
-
/** Every failure becomes `{ error: { code, message, hint? } }` with a matching status. */
|
|
820
|
-
function toErrorResponse(error) {
|
|
821
|
-
if (error instanceof RejectedError) return error.response;
|
|
822
|
-
if (error instanceof HttpError) {
|
|
823
|
-
const response = json({ error: {
|
|
824
|
-
code: error.code,
|
|
825
|
-
message: error.message,
|
|
826
|
-
...error.hint !== void 0 ? { hint: error.hint } : {}
|
|
827
|
-
} }, error.status, error.retryAfter !== void 0 ? { "retry-after": String(error.retryAfter) } : void 0);
|
|
828
|
-
if (error.origin === "handle") handleErrors.add(response);
|
|
829
|
-
return response;
|
|
830
|
-
}
|
|
831
|
-
if (error instanceof ZodError) {
|
|
832
|
-
const issue = error.issues[0] && reported(error.issues[0]);
|
|
833
|
-
if (issue?.code === "too_big" && issue.origin === "string" && issue.maximum === 1e4 && issue.path.length === 1 && issue.path[0] === "text") return toErrorResponse(textTooLong());
|
|
834
|
-
const path = issue?.path.length ? `${issue.path.join(".")}: ` : "";
|
|
835
|
-
return json({ error: {
|
|
836
|
-
code: "invalid_request",
|
|
837
|
-
message: `${path}${issue?.message ?? "invalid request"}`
|
|
838
|
-
} }, 400);
|
|
839
|
-
}
|
|
840
|
-
const code = error?.code;
|
|
841
|
-
if (code === "INVALID_PAYLOAD") return json({ error: {
|
|
842
|
-
code: "invalid_request",
|
|
843
|
-
message: error.message
|
|
844
|
-
} }, 400);
|
|
845
|
-
if (code === "PARTIAL_DUPLICATE_BATCH" || code === "DUPLICATE_EVENT_ID") return toErrorResponse(duplicateId());
|
|
846
|
-
if (code === "STORE_UNAVAILABLE" || code === "STORE_NOT_CONFIGURED") return json({ error: {
|
|
847
|
-
code: "unavailable",
|
|
848
|
-
message: error.message
|
|
849
|
-
} }, 503);
|
|
850
|
-
console.error("[board]", error);
|
|
851
|
-
return json({ error: {
|
|
852
|
-
code: "internal",
|
|
853
|
-
message: "internal error"
|
|
854
|
-
} }, 500);
|
|
855
|
-
}
|
|
856
|
-
//#endregion
|
|
857
|
-
export { duplicateId as a, notFound as c, unauthorized as d, BoardError as f, eventsState as h, batchTooLarge as i, textTooLong as l, duration as m, RejectedError as n, forbidden as o, createBoardClient as p, badRequest as r, json as s, HttpError as t, toErrorResponse as u };
|