@vercel/board 0.32.0 → 0.34.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.
Files changed (167) hide show
  1. package/README.md +25 -20
  2. package/dist/{access-CY5xVMIK.mjs → access-CdBcYPQH.mjs} +170 -13
  3. package/dist/access.d.mts +4 -5
  4. package/dist/access.mjs +5 -5
  5. package/dist/{actors-Bm-ojWWT.mjs → actors-MrIEr9LI.mjs} +3 -3
  6. package/dist/auth-DjoJygbG.mjs +599 -0
  7. package/dist/{auth-K8dY1nBY.d.mts → auth-aaoKt5DK.d.mts} +133 -100
  8. package/dist/backend-local.d.mts +28 -0
  9. package/dist/backend-local.mjs +2 -0
  10. package/dist/{backend-DxE9wGKm.d.mts → backend-u1sVvybh.d.mts} +108 -55
  11. package/dist/{chat-provider-DkFp2hrh.mjs → chat-provider-9hCT654s.mjs} +2 -2
  12. package/dist/{chat-provider-BChYrrA7.d.mts → chat-provider-De0iDnUB.d.mts} +2 -3
  13. package/dist/cli-commands.d.mts +1 -1
  14. package/dist/cli-commands.mjs +1 -1
  15. package/dist/cli-embedded.d.mts +2 -2
  16. package/dist/cli-embedded.mjs +1 -1
  17. package/dist/cli.mjs +6 -6
  18. package/dist/{commands-DsnQKTdB.mjs → commands-B8oZEByR.mjs} +37 -52
  19. package/dist/{commands-CpyPV_tk.d.mts → commands-BkVMdXP1.d.mts} +9 -6
  20. package/dist/{conformance-3RBKxwbp.mjs → conformance-gqYBkXFS.mjs} +79 -86
  21. package/dist/conformance.d.mts +1 -1
  22. package/dist/conformance.mjs +1 -1
  23. package/dist/{engine-DurYIRt8.mjs → engine-rtOVWsiF.mjs} +6 -8
  24. package/dist/{errors-CJXhhzvT.mjs → errors-D8ifv16L.mjs} +75 -6
  25. package/dist/{events-lujPA3gQ.mjs → events-IQg0k281.mjs} +2 -2
  26. package/dist/exports-Bx2dGpzr.mjs +3252 -0
  27. package/dist/exports-uwRl5qIj.d.mts +4 -0
  28. package/dist/{external-D3p5T57R.mjs → external-CYe424fO.mjs} +1 -1
  29. package/dist/index-D6mK0Ial.d.mts +11 -0
  30. package/dist/index.d.mts +10 -9
  31. package/dist/index.mjs +21 -8
  32. package/dist/index.node.d.mts +6 -7
  33. package/dist/index.node.mjs +3 -3
  34. package/dist/inspect/app.js +95 -95
  35. package/dist/{internal-CvsrprnU-zZMpDiRY.mjs → internal-CvsrprnU-CEPOUpAv.mjs} +63 -43
  36. package/dist/local-CPz22MQ8.mjs +9225 -0
  37. package/dist/{main-CcYDo9Hb.mjs → main-DScDKwQN.mjs} +129 -54
  38. package/dist/{backend-a2/store-memory.mjs → memory-7RRnLa4X.mjs} +3 -3
  39. package/dist/middleware-BjYpk4yq.mjs +103 -0
  40. package/dist/{provider-gynDUoyW.d.mts → provider-hB8QNrwm.d.mts} +369 -3
  41. package/dist/{client-COfYrgfV.d.mts → routes-De4W6lEs.d.mts} +997 -367
  42. package/dist/{schemas-DBmUO6pr.mjs → schemas-BG205xds.mjs} +2 -5
  43. package/dist/{serve-Bplieh0C.mjs → serve-B1noQRkn.mjs} +33 -24
  44. package/dist/{node-BgeGcwX0.mjs → server-Ov6GBJ8j.mjs} +419 -6
  45. package/dist/{serving-Y7s7VDjB.mjs → serving-2s7lqSBS.mjs} +1 -1
  46. package/dist/{sql-E1K5g_ih.mjs → sql-BQzKUqQt.mjs} +349 -114
  47. package/dist/sqlite-DCtZFEVm.mjs +30 -0
  48. package/dist/{sqlite-db-CzcD_FW8.mjs → sqlite-db-qLTs52Ny.mjs} +2 -3
  49. package/dist/{store-codec-pAG2oPgQ-SqDXlPBR.mjs → store-N8PXxDAS-BdL4Sq-f.mjs} +6 -2
  50. package/dist/{store-memory-B0PkVSuQ.mjs → store-memory-CKQVEzXN.mjs} +2 -4
  51. package/dist/store-memory-OdGsc-t_.mjs +2 -0
  52. package/dist/{store-polling-BZt2Rf3D-Div-bJ_D.mjs → store-polling-BZt2Rf3D-oh3aU_An.mjs} +1 -1
  53. package/dist/store-sqlite-CTxAVCcz.mjs +2 -0
  54. package/dist/{store-sqlite-D85t3tE7.mjs → store-sqlite-D6fIszST.mjs} +3 -4
  55. package/dist/sync-chat-sdk.d.mts +2 -2
  56. package/dist/sync-chat-sdk.mjs +2 -2
  57. package/dist/sync-github.d.mts +2 -2
  58. package/dist/sync-github.mjs +2 -2
  59. package/dist/sync-linear.d.mts +3 -3
  60. package/dist/sync-linear.mjs +2 -2
  61. package/dist/sync-slack.d.mts +3 -3
  62. package/dist/sync-slack.mjs +4 -4
  63. package/dist/sync.d.mts +2 -2
  64. package/dist/sync.mjs +2 -2
  65. package/dist/{watchers-hash-CurCzwhe.mjs → targets-aMdbp84G.mjs} +134 -16
  66. package/dist/{tokens-C7kYyrAG.mjs → tokens-LHLrnV_P.mjs} +15 -43
  67. package/docs/01-board/01-mounting.md +245 -288
  68. package/docs/01-board/03-identity.md +42 -50
  69. package/docs/01-board/04-messages.md +15 -14
  70. package/docs/01-board/05-reading.md +3 -3
  71. package/docs/01-board/06-watchers.md +58 -105
  72. package/docs/01-board/07-schedules.md +21 -41
  73. package/docs/01-board/08-middleware.md +11 -17
  74. package/docs/01-board/09-access.md +187 -343
  75. package/docs/01-board/10-local.md +81 -0
  76. package/docs/01-quickstart.md +49 -126
  77. package/docs/02-sync/01-overview.md +25 -80
  78. package/docs/02-sync/02-functions.md +10 -16
  79. package/docs/02-sync/03-slack.md +13 -26
  80. package/docs/02-sync/04-github.md +8 -20
  81. package/docs/02-sync/07-linear.md +6 -10
  82. package/docs/03-guides/02-inspector.md +3 -3
  83. package/docs/03-guides/03-ci.md +88 -128
  84. package/docs/03-guides/04-triage.md +7 -15
  85. package/docs/03-guides/05-agent-factory.md +29 -36
  86. package/docs/04-reference/01-cli.md +113 -38
  87. package/docs/04-reference/02-board.md +79 -82
  88. package/docs/04-reference/03-http.md +138 -69
  89. package/docs/04-reference/05-conformance.md +32 -46
  90. package/docs/index.md +41 -65
  91. package/package.json +12 -83
  92. package/dist/a2-DiDc77Uf.mjs +0 -4238
  93. package/dist/access-DPcrKIH_.d.mts +0 -37
  94. package/dist/auth-8pRZnF1M.mjs +0 -393
  95. package/dist/backend-a2/blob-vercel.d.mts +0 -8
  96. package/dist/backend-a2/blob-vercel.mjs +0 -81
  97. package/dist/backend-a2/contract.d.mts +0 -828
  98. package/dist/backend-a2/contract.mjs +0 -5
  99. package/dist/backend-a2/scheduler-local.d.mts +0 -11
  100. package/dist/backend-a2/scheduler-local.mjs +0 -2
  101. package/dist/backend-a2/scheduler-qstash.d.mts +0 -79
  102. package/dist/backend-a2/scheduler-qstash.mjs +0 -522
  103. package/dist/backend-a2/scheduler-vercel.d.mts +0 -38
  104. package/dist/backend-a2/scheduler-vercel.mjs +0 -204
  105. package/dist/backend-a2/store-memory.d.mts +0 -11
  106. package/dist/backend-a2/store-postgres.d.mts +0 -38
  107. package/dist/backend-a2/store-postgres.mjs +0 -2977
  108. package/dist/backend-a2/store-redis-http.d.mts +0 -17
  109. package/dist/backend-a2/store-redis-http.mjs +0 -520
  110. package/dist/backend-a2/store-redis.d.mts +0 -31
  111. package/dist/backend-a2/store-redis.mjs +0 -88
  112. package/dist/backend-a2/store-sqlite.d.mts +0 -12
  113. package/dist/backend-a2/store-sqlite.mjs +0 -31
  114. package/dist/backend-a2.d.mts +0 -2633
  115. package/dist/backend-a2.mjs +0 -3
  116. package/dist/backend-http-CaN06CaD.d.mts +0 -672
  117. package/dist/backend-http-CoaCghuJ.mjs +0 -18
  118. package/dist/backend-http-l5A8UmL-.mjs +0 -585
  119. package/dist/backend-http.d.mts +0 -10
  120. package/dist/backend-http.mjs +0 -2
  121. package/dist/backend-http.node.d.mts +0 -10
  122. package/dist/backend-http.node.mjs +0 -2
  123. package/dist/backend-vercel-BE65okBC.mjs +0 -86
  124. package/dist/backend-vercel-CVxoTNF2.mjs +0 -1744
  125. package/dist/backend-vercel-jg-6PAgD.d.mts +0 -674
  126. package/dist/backend-vercel.d.mts +0 -9
  127. package/dist/backend-vercel.mjs +0 -11
  128. package/dist/backend-vercel.node.d.mts +0 -17
  129. package/dist/backend-vercel.node.mjs +0 -2
  130. package/dist/blob-Bx8QPWEd.d.mts +0 -40
  131. package/dist/blob-WbB2DJKn.mjs +0 -201
  132. package/dist/errors-2vGs49Db.d.mts +0 -16
  133. package/dist/exports-BnUZuRm9.mjs +0 -1389
  134. package/dist/exports-u5mApVvn.d.mts +0 -5
  135. package/dist/files-SniSmeEr.mjs +0 -47
  136. package/dist/folds-DLUzfibJ.d.mts +0 -558
  137. package/dist/folds-DsWfIftc.mjs +0 -208
  138. package/dist/index-UXpTPWNc.d.mts +0 -11
  139. package/dist/index.default-Dp8gexln.mjs +0 -12
  140. package/dist/local-C76Fy5ad.mjs +0 -44
  141. package/dist/middleware-BavYSDUa.mjs +0 -62
  142. package/dist/platform-B4TnJtWu-Do3agKr5.mjs +0 -32
  143. package/dist/project-4Vl7_uy5.mjs +0 -124
  144. package/dist/redis-tables-BFRj_SEJ.mjs +0 -3895
  145. package/dist/reducer-Bswr11ar-P324o9vn.mjs +0 -74
  146. package/dist/reducer-CYPHsSmd-BXjGiptm.d.mts +0 -170
  147. package/dist/reducers-DQVSP3kk.mjs +0 -538
  148. package/dist/retryable-lazy-DZWmHpii-DpTc5PIP.mjs +0 -19
  149. package/dist/scheduler-task-X1SToDjP-D2Il2rln.mjs +0 -69
  150. package/dist/server-B9gu0qi1-DI1WvcVK.d.mts +0 -391
  151. package/dist/server-DX7mM6nm-D7N_7bug.mjs +0 -3611
  152. package/dist/server-wIpAEjpX.mjs +0 -17
  153. package/dist/session-clear-XJYpmUpg-2q8l_FJR.mjs +0 -63
  154. package/dist/store-DEzcHZOA-B-5vhxef.d.mts +0 -540
  155. package/dist/store-N8PXxDAS-DWWgv-Vz.mjs +0 -5
  156. package/dist/store-memory-4IBl0Ztu.mjs +0 -2
  157. package/dist/store-presence-polling-JuAy2Ck2-Dh-g_KYM.mjs +0 -109
  158. package/dist/store-sqlite-iBTYYKBj.mjs +0 -2
  159. package/dist/stream-buffer-DrTyiIuo-Be10yOBR.mjs +0 -53
  160. package/dist/targets-Cgjs29T0.mjs +0 -33
  161. package/dist/types-CmrFjpml.d.mts +0 -102
  162. package/dist/wait-until-Dw4XrIDQ.mjs +0 -42
  163. package/docs/01-board/02-database.md +0 -258
  164. package/docs/04-reference/04-log.md +0 -247
  165. package/sql/postgres/board.sql +0 -145
  166. package/sql/postgres/notifications.sql +0 -24
  167. package/sql/postgres/schema.sql +0 -451
@@ -1,1744 +0,0 @@
1
- import { r as IMPORT_BYTES_MAX } from "./files-SniSmeEr.mjs";
2
- import { _ as RemoteWatcherId } from "./schemas-DBmUO6pr.mjs";
3
- import { A as RegisterBody, a as METHODS, d as VERSION, n as compileWatcher, t as canonicalWatchers } from "./watchers-hash-CurCzwhe.mjs";
4
- import { a as forbidden, f as duration, o as json, r as badRequest, s as notFound, t as HttpError } from "./errors-CJXhhzvT.mjs";
5
- import { o as sha256, r as derivedId } from "./wait-until-Dw4XrIDQ.mjs";
6
- import { a as wakePath, i as registrant, n as callerProfile, t as PROJECTS_OWN } from "./backend-http-l5A8UmL-.mjs";
7
- import { o as mediaType, r as fileName } from "./blob-WbB2DJKn.mjs";
8
- //#region src/server/backend-vercel.ts
9
- const PROFILE = /^[A-Za-z][A-Za-z0-9-]{0,31}$/;
10
- const SESSION = /^[A-Za-z0-9_.:-]{1,128}$/;
11
- const CLIENT_ID = /^[A-Za-z0-9_.:-]{1,128}$/;
12
- const MESSAGE_ID = /^msg_([0-9a-f-]{36})_([1-9]\d*)$/;
13
- /** Whether `value` is a message ID Vercel's API hands out (`msg_<thread>_<n>`): the CLI takes one as a message, even where a channel has its name. */
14
- const isApiMessageId = (value) => MESSAGE_ID.test(value);
15
- /** A cursor this backend made: a time, then the position it names, in base 36. */
16
- const CURSOR = /^([0-9a-z]+)(?:\.([0-9a-z]+))?$/;
17
- /** The API's own cursor for one channel, which its message list and feed share, and any process resumes. */
18
- const API_CURSOR = /^c1\./;
19
- /** The API's longest page of a channel's messages, and longest long-poll, in seconds. */
20
- const PAGE_MAX = 100;
21
- const WAIT_MAX_S = 25;
22
- /** Pages a filtered read of one channel scans for matches before it answers with what it found. */
23
- const SCAN_PAGES = 10;
24
- /** A file as the board names it. */
25
- const fileOf = ({ id, name, type, size }) => ({
26
- id,
27
- name,
28
- type,
29
- size
30
- });
31
- const notSupported = (what) => new HttpError(501, "not_supported", `Vercel's boards don't support ${what} yet`);
32
- /** What a caller board() verified may do. Null for this deployment's own code, which may do what its credentials may. */
33
- const accessOf = (caller) => "identity" in caller ? caller.identity.principal.access : null;
34
- /** A verified caller's grant, which the API can't check: it sees this deployment's credentials. */
35
- function need(access, permission, channel) {
36
- if (access && !access.can(permission, channel)) throw forbidden(`this token can't ${permission} in ${channel}`);
37
- }
38
- const apiKind = (kind) => kind === "app" ? "workflow" : kind;
39
- /** A UUIDv7, which the API takes as an operation ID. */
40
- function operationId() {
41
- const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
42
- const now = BigInt(Date.now());
43
- for (let i = 0; i < 6; i++) bytes[i] = Number(now >> BigInt(8 * (5 - i)) & 255n);
44
- bytes[6] = bytes[6] & 15 | 112;
45
- bytes[8] = bytes[8] & 63 | 128;
46
- const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
47
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
48
- }
49
- const iso = (ms) => new Date(ms).toISOString();
50
- const idAt = (threadId, sequence) => `msg_${threadId.slice(4)}_${sequence}`;
51
- /** Where a message ID points: its thread and its place in it. Null for one that isn't a message's. */
52
- function locate(id) {
53
- const found = MESSAGE_ID.exec(id);
54
- return found ? {
55
- threadId: `thr_${found[1]}`,
56
- sequence: Number(found[2])
57
- } : null;
58
- }
59
- /** A principal as board names it: `vercel:user:<id>`, `vercel:app:<id>`, `vercel:project:<id>:<env>`. */
60
- function principalId(principal) {
61
- if (principal.type === "user") return `vercel:user:${principal.userId}`;
62
- if (principal.type === "app") return `vercel:app:${principal.clientId}`;
63
- return `vercel:project:${principal.projectId}:${principal.environment}`;
64
- }
65
- const authorOf = (actor) => ({
66
- actor: actor.id,
67
- principal: principalId(actor.principal),
68
- profile: actor.profile?.name ?? null,
69
- session: actor.session ?? null
70
- });
71
- /** Who cancels a schedule when no one did: the API, once its creator can no longer post it, as a2()'s scheduler. */
72
- const SCHEDULER = {
73
- actor: "board:schedule",
74
- principal: "board:schedule",
75
- profile: null,
76
- session: null
77
- };
78
- /** The API names nobody, so an actor's handle is its profile, or a short form of its principal. */
79
- function actorView(actor) {
80
- const { principal } = actor;
81
- const base = principal.type === "user" ? `user-${principal.userId.slice(0, 6).toLowerCase()}` : principal.type === "app" ? `app-${principal.clientId.slice(0, 6).toLowerCase()}` : principal.environment === "production" ? principal.projectId : `${principal.projectId}@${principal.environment}`;
82
- const handle = actor.profile?.name ?? base;
83
- const kind = actor.profile ? "agent" : principal.type === "user" ? "person" : principal.type === "project" ? "deployment" : "workflow";
84
- return {
85
- id: actor.id,
86
- kind,
87
- handle,
88
- name: handle,
89
- avatar: actor.profile?.avatar ?? null
90
- };
91
- }
92
- /**
93
- * Vercel's board for your team, in Vercel's API: this deployment keeps nothing and reads and writes
94
- * it as itself, its people as themselves. Messages, threads, reactions, labels, a channel's
95
- * changes, schedules, files, and watchers work; what the API keeps none of yet (sync) answers 501.
96
- */
97
- function createVercel(options, environment) {
98
- const origin = (options.api ?? "https://api.vercel.com").replace(/\/+$/, "");
99
- if (!/^https:\/\/[^/]+$|^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin)) throw new Error(`vercel: ${origin} isn't Vercel's API: pass an https origin`);
100
- if (!options.fetch && !environment) throw new Error("vercel: pass a fetch that sends credentials: outside Node there's no environment to find them in");
101
- const doFetch = options.fetch ?? environment.fetch();
102
- const filesFetch = options.files ?? fetch;
103
- let binding = null;
104
- /** This board's own code's names, which a caller here never takes as its profile. */
105
- const own = /* @__PURE__ */ new Set();
106
- let team = null;
107
- const teamId = () => team ??= options.team ? Promise.resolve(options.team) : environment?.team() ?? Promise.resolve(null);
108
- /** One request to the API, as `who`. Its errors are the API's own, with its status and code. */
109
- async function api(who, method, path, init = {}) {
110
- const url = new URL(`${origin}/v1/messageboard${path}`);
111
- const id = await teamId();
112
- if (id) url.searchParams.set(id.startsWith("team_") ? "teamId" : "slug", id);
113
- for (const [name, value] of Object.entries(init.query ?? {})) if (value !== void 0) url.searchParams.set(name, value);
114
- const headers = { "content-type": "application/json" };
115
- if (who.profile) headers["x-board-profile"] = who.profile.name;
116
- if (who.profile?.avatar?.startsWith("https://")) headers["x-board-avatar"] = who.profile.avatar;
117
- if (who.session && SESSION.test(who.session)) headers["x-board-session"] = who.session;
118
- let response;
119
- try {
120
- response = await doFetch(url, {
121
- method,
122
- headers,
123
- redirect: "error",
124
- ...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {},
125
- ...init.signal ? { signal: init.signal } : {}
126
- });
127
- } catch (error) {
128
- if (error instanceof HttpError || error instanceof Error && error.name === "AbortError") throw error;
129
- throw new HttpError(502, "unreachable", `Vercel's API didn't answer: ${error instanceof Error ? error.message : String(error)}`);
130
- }
131
- const text = await response.text();
132
- let body;
133
- try {
134
- body = text ? JSON.parse(text) : void 0;
135
- } catch {}
136
- if (response.ok) return body;
137
- const error = body?.error;
138
- throw new HttpError(response.status, error?.code ?? "remote_error", error?.message ?? `Vercel's API answered ${response.status}`);
139
- }
140
- /** Every page of a list, in order. */
141
- async function all(who, path, key, query = {}, signal) {
142
- const out = [];
143
- let cursor;
144
- do {
145
- const page = await api(who, "GET", path, {
146
- query: {
147
- ...query,
148
- cursor
149
- },
150
- ...signal ? { signal } : {}
151
- });
152
- out.push(...page[key]);
153
- cursor = page.cursor ?? void 0;
154
- } while (cursor);
155
- return out;
156
- }
157
- let board = null;
158
- /**
159
- * The board's ID: the one given, or the team's, which the API names only to those it lets in. A
160
- * team with none gets one the first time a person uses it, as the API asks of its clients; a
161
- * project can't make it, and needs a person to grant it the board anyway.
162
- */
163
- const boardId = (who) => (board ??= options.board ? Promise.resolve(options.board) : api(who, "GET", "/boards").then(async ({ defaultBoardId }) => {
164
- if (defaultBoardId) return defaultBoardId;
165
- if ((await self(who)).actor.principal.type === "project") throw new HttpError(404, "no_board", "Vercel's API names no board this project may use: ask someone on the team to grant it the team's board, or pass `board`");
166
- const { board: made } = await api(who, "POST", "/boards/default", { body: { operationId: operationId() } });
167
- return made.id;
168
- })).catch((error) => {
169
- board = null;
170
- throw error;
171
- });
172
- const onBoard = async (who, path = "") => `/boards/${encodeURIComponent(await boardId(who))}${path}`;
173
- let channels = null;
174
- const loadChannels = async (who, fresh = false) => {
175
- if (fresh) channels = null;
176
- channels ??= onBoard(who, "/channels").then((path) => all(who, path, "channels"));
177
- return channels.catch((error) => {
178
- channels = null;
179
- throw error;
180
- });
181
- };
182
- /** The channel by `name`, which the API finds without listing the board's. */
183
- const named = /* @__PURE__ */ new Map();
184
- async function channelNamed(who, name) {
185
- const known = named.get(name);
186
- if (known) return known;
187
- const { channels: [found] } = await api(who, "GET", await onBoard(who, "/channels"), { query: { name } });
188
- if (found) named.set(name, found);
189
- return found ?? null;
190
- }
191
- async function channelById(who, id) {
192
- const found = (await loadChannels(who)).find((channel) => channel.id === id) ?? (await loadChannels(who, true)).find((channel) => channel.id === id);
193
- if (!found) throw new HttpError(502, "remote_error", `Vercel's API names a channel it doesn't list: ${id}`);
194
- return found;
195
- }
196
- /** The channel by `name`, made if it isn't there: `created` says whether this made it. */
197
- async function ensureChannel(who, name) {
198
- const found = await channelNamed(who, name);
199
- if (found) return {
200
- channel: found,
201
- created: false
202
- };
203
- try {
204
- const { channel } = await api(who, "POST", await onBoard(who, "/channels"), { body: {
205
- operationId: operationId(),
206
- name
207
- } });
208
- channels = null;
209
- named.set(name, channel);
210
- return {
211
- channel,
212
- created: true
213
- };
214
- } catch (error) {
215
- if (error instanceof HttpError && error.code === "channel_name_taken") {
216
- const made = await channelNamed(who, name);
217
- if (made) return {
218
- channel: made,
219
- created: false
220
- };
221
- }
222
- throw error;
223
- }
224
- }
225
- /** A channel to post in, made the first time something posts to it, as on any board. */
226
- const channelToPost = async (who, name) => (await ensureChannel(who, name)).channel;
227
- /** The channels a filter names that `access` reads: one, a channel and those under it (`dev/`), or every one. */
228
- async function channelsFor(who, filter, access) {
229
- const readable = (channel) => access === null || access.readable(channel.name);
230
- if (filter !== void 0 && !filter.endsWith("/")) {
231
- const found = await channelNamed(who, filter);
232
- return found && readable(found) ? [found] : [];
233
- }
234
- const listed = (await loadChannels(who, true)).filter(readable);
235
- if (filter === void 0) return listed;
236
- const path = filter.slice(0, -1);
237
- return listed.filter((channel) => channel.name === path || channel.name.startsWith(filter));
238
- }
239
- async function messageById(who, id, signal) {
240
- if (!locate(id)) throw notFound(`message not found: ${id}`, "message_not_found");
241
- try {
242
- return await api(who, "GET", await onBoard(who, `/messages/${encodeURIComponent(id)}`), signal ? { signal } : {});
243
- } catch (error) {
244
- if (error instanceof HttpError && error.code === "thread_not_found") throw notFound(`message not found: ${id}`, "message_not_found");
245
- throw error;
246
- }
247
- }
248
- /** A message `access` may read, and its channel: one it can't is as missing as one that isn't there. */
249
- async function readableMessage(who, access, id, signal) {
250
- const found = await messageById(who, id, signal);
251
- const channel = await channelById(who, found.thread.channelId);
252
- if (access && !access.readable(channel.name)) throw notFound(`message not found: ${id}`, "message_not_found");
253
- return {
254
- ...found,
255
- channel
256
- };
257
- }
258
- /**
259
- * Each thread a read needs, read once, with the labels its messages match on: a label matches on
260
- * its root's, which the API keeps on the thread. It reads the root, which names its thread, so it
261
- * knows when the root is deleted.
262
- */
263
- function threadReader(who, signal) {
264
- const read = /* @__PURE__ */ new Map();
265
- return (id) => {
266
- let thread = read.get(id);
267
- if (!thread) read.set(id, thread = messageById(who, idAt(id, 1), signal).then(({ thread, message }) => labeledBy(thread, message)));
268
- return thread;
269
- };
270
- }
271
- /** A thread as its root's labels find it: the API keeps a deleted root's labels on its thread, and a deleted message has none. */
272
- const labeledBy = (thread, root) => {
273
- if (root?.deletedAt === void 0) return thread;
274
- const { labels: _kept, ...rest } = thread;
275
- return rest;
276
- };
277
- /** A message's labels: a deleted message keeps none, though the API still holds them. */
278
- const labelsOf = (message) => message.deletedAt === void 0 ? { ...message.labels } : {};
279
- const threadMessages = async (who, threadId, signal) => all(who, await onBoard(who, `/threads/${encodeURIComponent(threadId)}/messages`), "messages", {}, signal);
280
- /** Who reacted with each emoji. The API counts them on the message and lists them apart. */
281
- async function reactors(who, message) {
282
- if (!message.reactions || Object.keys(message.reactions).length === 0) return {};
283
- const named = message.reactors ?? {};
284
- if (Object.entries(message.reactions).every(([emoji, count]) => (named[emoji]?.length ?? 0) >= count)) return Object.fromEntries(Object.entries(named).map(([emoji, actors]) => [emoji, [...actors]]));
285
- const path = await onBoard(who, `/threads/${encodeURIComponent(message.threadId)}/messages/${message.sequence}/reactions`);
286
- const out = {};
287
- for (const reaction of await all(who, path, "reactions")) (out[reaction.emoji] ??= []).push(reaction.actor.id);
288
- return out;
289
- }
290
- /** Who's written here, by actor ID, as the API names them: messages carry only the actor. */
291
- let actorNames = null;
292
- /** How long names are kept before they're read again: someone renamed shows by their new name after this. */
293
- const NAMES_FRESH_MS = 3e5;
294
- /** Actors a list read again for them didn't have: it isn't read again for them. */
295
- const unlisted = /* @__PURE__ */ new Set();
296
- /** Reads the list, kept as the current one; a read that fails isn't kept, so the next name tries again. */
297
- const readNames = (who) => {
298
- const views = (async () => new Map((await all(who, await onBoard(who, "/actors"), "actors")).map((view) => [view.id, view])))();
299
- const read = {
300
- at: Date.now(),
301
- views
302
- };
303
- actorNames = read;
304
- views.catch(() => {
305
- if (actorNames === read) actorNames = null;
306
- });
307
- return read;
308
- };
309
- /** The actor in a read of the list, or undefined when it doesn't have them or failed. */
310
- const inList = (read, id) => read.views.then((views) => views.get(id), () => void 0);
311
- /**
312
- * An actor as board shows them: a person by their Vercel username and name, and an agent acting
313
- * for a person by its profile under them, as the API names them; anyone else (a project, an app,
314
- * an agent of one), or someone the API doesn't list, by their principal. The list is read again
315
- * every few minutes, and at once for someone who wrote since it was.
316
- */
317
- async function nameOf(who, actor) {
318
- const current = !actorNames || Date.now() - actorNames.at > NAMES_FRESH_MS ? readNames(who) : actorNames;
319
- let found = await inList(current, actor.id);
320
- if (!found && !unlisted.has(actor.id)) {
321
- const again = actorNames && actorNames !== current ? actorNames : readNames(who);
322
- found = await inList(again, actor.id);
323
- if (!found && await again.views.then(() => true, () => false)) unlisted.add(actor.id);
324
- }
325
- const kind = found && apiKind(found.kind);
326
- if (!found || !(kind === "person" || kind === "agent" && actor.principal.type === "user")) return actorView(actor);
327
- return {
328
- id: actor.id,
329
- kind,
330
- handle: found.handle,
331
- name: found.name ?? found.handle,
332
- avatar: found.avatar ?? null
333
- };
334
- }
335
- async function view(who, message, channel) {
336
- const root = message.sequence === 1;
337
- return {
338
- id: message.id,
339
- channel,
340
- text: message.text,
341
- re: root ? null : idAt(message.threadId, 1),
342
- replyTo: message.replyTo !== void 0 && message.replyTo !== 1 ? idAt(message.threadId, message.replyTo) : null,
343
- thread: message.threadId,
344
- labels: labelsOf(message),
345
- reactions: message.deletedAt === void 0 ? await reactors(who, message) : {},
346
- mentions: [],
347
- by: authorOf(message.createdBy),
348
- noSync: false,
349
- origin: null,
350
- from: null,
351
- createdAt: iso(message.createdAt),
352
- editedAt: message.editedAt === void 0 ? null : iso(message.editedAt),
353
- deleted: message.deletedAt !== void 0,
354
- undelivered: {},
355
- attachments: message.attachments ?? [],
356
- links: [],
357
- version: message.version,
358
- revision: message.revision,
359
- author: await nameOf(who, message.createdBy),
360
- ...message.schedule ? { schedule: {
361
- id: message.schedule.id,
362
- n: message.schedule.n
363
- } } : {}
364
- };
365
- }
366
- async function scheduleView(who, schedule) {
367
- const { canceled } = schedule;
368
- return {
369
- id: schedule.id,
370
- channel: (await channelById(who, schedule.channelId)).name,
371
- re: schedule.threadId === void 0 ? null : idAt(schedule.threadId, 1),
372
- text: schedule.text,
373
- labels: { ...schedule.labels },
374
- noSync: false,
375
- attachments: [],
376
- first: iso(schedule.firstAt),
377
- every: schedule.every ?? null,
378
- until: schedule.until === void 0 ? null : iso(schedule.until),
379
- times: schedule.times ?? null,
380
- sent: schedule.sent,
381
- next: schedule.nextAt === null ? null : iso(schedule.nextAt),
382
- last: schedule.lastMessageId ?? null,
383
- state: schedule.state,
384
- canceled: canceled ? {
385
- by: canceled.by ? authorOf(canceled.by) : SCHEDULER,
386
- reason: canceled.reason === "disabled" ? "revoked" : canceled.reason
387
- } : null,
388
- by: authorOf(schedule.createdBy),
389
- author: await nameOf(who, schedule.createdBy),
390
- createdAt: iso(schedule.createdAt)
391
- };
392
- }
393
- const positions = /* @__PURE__ */ new Map();
394
- function cursorOf(position) {
395
- const key = `${position.t.toString(36)}.${Math.floor(Math.random() * 36 ** 8).toString(36)}`;
396
- positions.set(key, position);
397
- if (positions.size > 1e4) positions.delete(positions.keys().next().value);
398
- return key;
399
- }
400
- function positionOf(cursor) {
401
- const kept = positions.get(cursor);
402
- if (kept) return kept;
403
- const found = CURSOR.exec(cursor);
404
- if (!found) throw new HttpError(400, "invalid_cursor", `after: ${cursor} isn't a cursor here or a message's ID`);
405
- return {
406
- t: parseInt(found[1], 36),
407
- feeds: {}
408
- };
409
- }
410
- /** A time a read goes on from: a cursor's, or a message's own. */
411
- async function timeOf(who, after) {
412
- return locate(after) ? (await messageById(who, after)).message.createdAt : positionOf(after).t;
413
- }
414
- /** Each channel's feed now, taken before a read, so what's posted while it reads comes after. */
415
- async function heads(who, listed) {
416
- const path = await onBoard(who, "/changes");
417
- const found = await Promise.all(listed.map((channel) => api(who, "GET", path, { query: {
418
- channelId: channel.id,
419
- from: "latest"
420
- } })));
421
- return Object.fromEntries(listed.map((channel, i) => [channel.id, {
422
- at: found[i].cursor,
423
- skip: 0
424
- }]));
425
- }
426
- /**
427
- * Whether a message matches a read's filters. A label matches on the message or its thread's root:
428
- * `thread`'s labels, as `labeledBy` gives them when the read filters on labels.
429
- */
430
- function matches(filters, message, thread, me) {
431
- if (filters.re !== void 0 && filters.re !== message.id && filters.re !== idAt(thread.id, 1)) return false;
432
- if (filters.by !== void 0) {
433
- const { createdBy } = message;
434
- const names = [
435
- createdBy.id,
436
- principalId(createdBy.principal),
437
- createdBy.profile?.name
438
- ];
439
- if (!(filters.by === "me" ? createdBy.id === me : names.includes(filters.by))) return false;
440
- }
441
- if (filters.mentions !== void 0) return false;
442
- if (filters.from !== void 0 && filters.from !== "board") return false;
443
- if (filters.text !== void 0 && !message.text.toLowerCase().includes(filters.text.toLowerCase())) return false;
444
- for (const [key, values] of filters.label ?? []) {
445
- const on = (labels) => labels !== void 0 && Object.hasOwn(labels, key) && (values === null || values.includes(labels[key]));
446
- if (!on(labelsOf(message)) && !on(thread.labels)) return false;
447
- }
448
- return true;
449
- }
450
- /** The label the API's index can narrow a channel's threads by: a root's `key` or `key=value`. */
451
- function indexed(filters) {
452
- const first = filters.label?.find(([, values]) => values === null || values.length === 1);
453
- return first && (first[1] === null ? first[0] : `${first[0]}=${first[1][0]}`);
454
- }
455
- async function threadsOf(who, channel, filters, signal) {
456
- const label = indexed(filters);
457
- return all(who, await onBoard(who, "/threads"), "threads", {
458
- channelId: channel.id,
459
- label
460
- }, signal);
461
- }
462
- /**
463
- * A channel's threads, as far as a read needs: the API lists them most recently active first, so
464
- * it stops at the first not active since `after`, or at the `limit` newest when it's given one
465
- * (not when the read filters what's listed). One it lists by a label comes oldest first, so it
466
- * reads every page.
467
- */
468
- async function latestThreads(who, channel, label, page, signal) {
469
- const path = await onBoard(who, "/threads");
470
- const out = [];
471
- let cursor;
472
- do {
473
- const found = await api(who, "GET", path, {
474
- query: {
475
- channelId: channel.id,
476
- label,
477
- cursor
478
- },
479
- signal
480
- });
481
- out.push(...found.threads);
482
- cursor = found.cursor ?? void 0;
483
- const last = out.at(-1);
484
- if (label === void 0 && (page.after !== void 0 ? last !== void 0 && last.lastActivityAt <= page.after : page.limit !== void 0 && out.length >= page.limit)) break;
485
- } while (cursor);
486
- return out;
487
- }
488
- /** A thread at a glance: its root, its reply count, and its latest reply, read by reference. */
489
- async function summary(who, thread, channel, signal) {
490
- const [root, last] = await Promise.all([messageById(who, idAt(thread.id, 1), signal), thread.lastMessage && thread.lastMessage.sequence > 1 ? messageById(who, thread.lastMessage.id, signal) : null]);
491
- return {
492
- message: await view(who, root.message, channel.name),
493
- replies: thread.messageCount - 1,
494
- last: last && await view(who, last.message, channel.name)
495
- };
496
- }
497
- let me = null;
498
- /** Who these credentials are, asked once. */
499
- const self = (who) => (me ??= api(who, "GET", "/me")).catch((error) => {
500
- me = null;
501
- throw error;
502
- });
503
- /** The actor `who` writes as: the credentials' principal, and its profile, as the API names it. */
504
- const actorOf = async (who) => `${principalId((await self(who)).actor.principal)}${who.profile ? `+${who.profile.name.toLowerCase()}` : ""}`;
505
- /** Who a caller acts as there: its profile and session, beside this deployment's credentials. */
506
- function whoOf(caller) {
507
- if ("identity" in caller) {
508
- const avatar = caller.identity.actor.avatar?.startsWith("https://") ? caller.identity.actor.avatar : void 0;
509
- return {
510
- profile: {
511
- name: callerProfile(caller.identity.actor.handle, own),
512
- ...avatar ? { avatar } : {}
513
- },
514
- session: null
515
- };
516
- }
517
- const named = (profile) => {
518
- if (profile === null) return null;
519
- const name = typeof profile === "string" ? profile : profile.name;
520
- if (!PROFILE.test(name)) throw new HttpError(400, "invalid_request", `as: ${name}: profiles start with a letter and use up to 32 letters, numbers, and hyphens`);
521
- return typeof profile === "string" || !profile.avatar ? { name } : {
522
- name,
523
- avatar: profile.avatar
524
- };
525
- };
526
- if (caller.origin.via?.kind === "client") {
527
- const asked = "profile" in caller ? caller.profile : caller.self ?? void 0;
528
- const found = environment?.profile() ?? {
529
- profile: null,
530
- session: null
531
- };
532
- if (asked === void 0) return {
533
- profile: named(found.profile),
534
- session: found.session
535
- };
536
- return {
537
- profile: named(asked),
538
- session: asked === null ? null : found.session
539
- };
540
- }
541
- return {
542
- profile: named(caller.self ?? "client"),
543
- session: null
544
- };
545
- }
546
- /** A post's client ID, as the API takes one: its own when it fits, a hash of it when it doesn't. */
547
- const clientIdOf = async (id) => CLIENT_ID.test(id) ? id : `h.${(await sha256(id)).slice(0, 64)}`;
548
- /** A gateway caller's post IDs are its own, derived under who it is here, since the API sees this deployment. */
549
- const postId = async (caller, id) => clientIdOf("identity" in caller ? await derivedId("board-gateway", caller.identity.principal.id, id) : id);
550
- /** Messages a read covers, newest last: every thread's in the channels it names, or one thread's. */
551
- async function collect(who, access, filters, signal) {
552
- let listed;
553
- let threads;
554
- if (filters.re !== void 0) {
555
- const found = await readableMessage(who, access, filters.re, signal).catch((error) => {
556
- if (error instanceof HttpError && error.status === 404) return null;
557
- throw error;
558
- });
559
- if (!found) return {
560
- messages: [],
561
- feeds: {},
562
- newest: 0
563
- };
564
- const { channel } = found;
565
- if (filters.channel !== void 0 && !(await channelsFor(who, filters.channel, access)).some((c) => c.id === channel.id)) return {
566
- messages: [],
567
- feeds: {},
568
- newest: 0
569
- };
570
- listed = [channel];
571
- threads = [{
572
- thread: found.thread,
573
- channel
574
- }];
575
- } else {
576
- listed = await channelsFor(who, filters.channel, access);
577
- threads = (await Promise.all(listed.map(async (channel) => (await threadsOf(who, channel, filters, signal)).map((thread) => ({
578
- thread,
579
- channel
580
- }))))).flat();
581
- }
582
- const feeds = await heads(who, listed);
583
- const mine = await actorOf(who);
584
- let newest = 0;
585
- const messages = [];
586
- for (const { thread, channel } of threads) {
587
- const all = await threadMessages(who, thread.id, signal);
588
- const labeled = labeledBy(thread, all.find((message) => message.sequence === 1));
589
- for (const message of all) {
590
- newest = Math.max(newest, message.createdAt);
591
- if (matches(filters, message, labeled, mine)) messages.push({
592
- message,
593
- thread,
594
- channel
595
- });
596
- }
597
- }
598
- messages.sort((a, b) => a.message.createdAt - b.message.createdAt || a.thread.id.localeCompare(b.thread.id) || a.message.sequence - b.message.sequence);
599
- return {
600
- messages,
601
- feeds,
602
- newest
603
- };
604
- }
605
- /** A change in the API's feed as a board event, with the message as it is now. Null for what isn't a message's. */
606
- async function eventOf(who, change, channel, cursor, filters, me, given, threads = threadReader(who)) {
607
- if (!change.messageId || !change.type.startsWith("message.")) return null;
608
- let found = given ?? await messageById(who, change.messageId).catch((error) => {
609
- if (error instanceof HttpError && error.status === 404) return null;
610
- throw error;
611
- });
612
- if (found && !given && filters.label?.length) found = {
613
- ...found,
614
- thread: found.message.sequence === 1 ? labeledBy(found.thread, found.message) : await threads(found.thread.id)
615
- };
616
- if (!found || !matches(filters, found.message, found.thread, me)) return null;
617
- const message = await view(who, found.message, channel);
618
- const by = authorOf(change.actor);
619
- const base = {
620
- id: message.id,
621
- thread: message.thread
622
- };
623
- let type;
624
- let payload;
625
- switch (change.type) {
626
- case "message.posted":
627
- type = "message.posted";
628
- payload = {
629
- channel,
630
- text: message.text,
631
- re: message.re,
632
- replyTo: message.replyTo,
633
- thread: message.thread,
634
- labels: message.labels,
635
- noSync: false,
636
- mentions: [],
637
- by,
638
- origin: null,
639
- from: null,
640
- attachments: message.attachments,
641
- links: []
642
- };
643
- break;
644
- case "message.edited":
645
- type = "message.edited";
646
- payload = {
647
- ...base,
648
- text: message.text,
649
- mentions: [],
650
- by,
651
- from: null
652
- };
653
- break;
654
- case "message.deleted":
655
- type = "message.deleted";
656
- payload = {
657
- ...base,
658
- by,
659
- from: null
660
- };
661
- break;
662
- case "message.reaction_added":
663
- case "message.reaction_removed":
664
- type = change.type === "message.reaction_added" ? "reaction.added" : "reaction.removed";
665
- payload = {
666
- ...base,
667
- emoji: change.emoji,
668
- by,
669
- from: null
670
- };
671
- break;
672
- case "message.labeled": {
673
- const changed = Object.entries(change.labels ?? {});
674
- type = "labels.changed";
675
- payload = {
676
- ...base,
677
- set: Object.fromEntries(changed.flatMap(([key, { to }]) => to === void 0 ? [] : [[key, to]])),
678
- unset: changed.flatMap(([key, { to }]) => to === void 0 ? [key] : []),
679
- by
680
- };
681
- break;
682
- }
683
- default: return null;
684
- }
685
- return {
686
- cursor,
687
- type,
688
- createdAt: iso(change.createdAt),
689
- payload,
690
- message,
691
- actor: await nameOf(who, change.actor)
692
- };
693
- }
694
- /**
695
- * One read of every channel's feed from `position`: its events, merged by time, each with the
696
- * position right after it, and the position after them all.
697
- */
698
- async function read(who, listed, position, filters, signal) {
699
- const path = await onBoard(who, "/changes");
700
- const pages = await Promise.all(listed.map(async (channel) => {
701
- const from = position.feeds[channel.id];
702
- const page = await api(who, "GET", path, {
703
- query: {
704
- channelId: channel.id,
705
- ...from?.at ? { cursor: from.at } : {}
706
- },
707
- signal
708
- });
709
- const skip = from?.skip ?? 0;
710
- const events = page.events.map((change, i) => ({
711
- change,
712
- i
713
- })).slice(skip).filter(({ change }) => from || change.createdAt > position.t);
714
- return {
715
- channel,
716
- at: from?.at ?? null,
717
- next: page.cursor,
718
- events
719
- };
720
- }));
721
- const mine = await actorOf(who);
722
- const threads = threadReader(who, signal);
723
- const running = { ...position.feeds };
724
- const merged = pages.flatMap((page) => page.events.map((event) => ({
725
- ...event,
726
- page
727
- }))).sort((a, b) => a.change.createdAt - b.change.createdAt);
728
- const events = [];
729
- for (const { change, i, page } of merged) {
730
- running[page.channel.id] = {
731
- at: page.at,
732
- skip: i + 1
733
- };
734
- const event = await eventOf(who, change, page.channel.name, cursorOf({
735
- t: change.createdAt,
736
- feeds: { ...running }
737
- }), filters, mine, void 0, threads);
738
- if (event) events.push(event);
739
- }
740
- const after = { ...position.feeds };
741
- for (const page of pages) after[page.channel.id] = {
742
- at: page.next,
743
- skip: 0
744
- };
745
- return {
746
- events,
747
- position: {
748
- t: Math.max(position.t, ...merged.map(({ change }) => change.createdAt)),
749
- feeds: after
750
- }
751
- };
752
- }
753
- /** `ms` passing, or `signal` stopping it first. */
754
- const pause = (ms, signal) => ms <= 0 || signal.aborted ? Promise.resolve() : new Promise((resolve) => {
755
- const timer = setTimeout(resolve, ms);
756
- signal.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
757
- });
758
- /**
759
- * Until one of `listed`'s feeds has something after `position` (true), or it's `until` (false). The API's feed is
760
- * one channel's, and only it can wait for what comes next, so this waits on each at once and lets
761
- * the rest go when the first answers with something: a read across channels costs a request a
762
- * channel each time it waits, not each second it does.
763
- */
764
- async function changed(who, listed, position, until, signal) {
765
- const wait = Math.min(WAIT_MAX_S, Math.ceil((until - Date.now()) / 1e3));
766
- if (wait <= 0) return false;
767
- if (listed.length === 0) {
768
- await pause(until - Date.now(), signal);
769
- return false;
770
- }
771
- const stop = new AbortController();
772
- const either = AbortSignal.any([signal, stop.signal]);
773
- const path = await onBoard(who, "/changes");
774
- try {
775
- return await new Promise((resolve, reject) => {
776
- let pending = listed.length;
777
- for (const channel of listed) {
778
- const at = position.feeds[channel.id]?.at;
779
- api(who, "GET", path, {
780
- query: {
781
- channelId: channel.id,
782
- ...at ? { cursor: at } : { from: "latest" },
783
- wait: String(wait)
784
- },
785
- signal: either
786
- }).then((page) => {
787
- if (page.events.length > 0) resolve(true);
788
- else if (--pending === 0) resolve(false);
789
- }).catch((error) => stop.signal.aborted && !signal.aborted ? void 0 : reject(error));
790
- }
791
- });
792
- } finally {
793
- stop.abort();
794
- }
795
- }
796
- /** Whether a read filters on what messages say, who wrote them, or their labels: what the API can't narrow by. */
797
- const filtered = (filters) => filters.by !== void 0 || filters.mentions !== void 0 || filters.text !== void 0 || filters.from !== void 0 || (filters.label?.length ?? 0) > 0;
798
- /**
799
- * One channel's messages, from the API's message list: the latest `limit`, or those after one of
800
- * its cursors. A filtered read checks each page here, and asks only for as many as it still needs,
801
- * so the cursor it answers with never passes a match it left out.
802
- */
803
- async function channelMessages(who, channel, query, signal) {
804
- const path = await onBoard(who, "/messages");
805
- const limit = query.limit ?? 50;
806
- const thread = threadReader(who, signal);
807
- const narrowed = filtered(query);
808
- const me = narrowed ? await actorOf(who) : null;
809
- const keep = async (message) => !narrowed || matches(query, message, query.label?.length ? await thread(message.threadId) : { id: message.threadId }, me);
810
- const kept = [];
811
- if (query.after === void 0) {
812
- const page = await api(who, "GET", path, {
813
- query: {
814
- channelId: channel.id,
815
- limit: String(narrowed ? PAGE_MAX : Math.min(limit, PAGE_MAX))
816
- },
817
- signal
818
- });
819
- for (const message of page.messages) if (await keep(message)) kept.push(message);
820
- return {
821
- messages: kept.slice(-limit),
822
- cursor: page.cursor
823
- };
824
- }
825
- let cursor = query.after;
826
- for (let pages = 0; pages < SCAN_PAGES && kept.length < limit; pages++) {
827
- const page = await api(who, "GET", path, {
828
- query: {
829
- channelId: channel.id,
830
- after: cursor,
831
- limit: String(Math.min(limit - kept.length, PAGE_MAX))
832
- },
833
- signal
834
- });
835
- cursor = page.cursor;
836
- for (const message of page.messages) if (await keep(message)) kept.push(message);
837
- if (page.messages.length === 0) break;
838
- }
839
- return {
840
- messages: kept,
841
- cursor
842
- };
843
- }
844
- /** One channel's events, from the API's feed after one of its cursors, or from now: a long-poll holds there, not here. */
845
- async function channelEvents(who, channel, query, signal) {
846
- const path = await onBoard(who, "/changes");
847
- const thread = threadReader(who, signal);
848
- const me = await actorOf(who);
849
- const until = Date.now() + (query.wait ?? 0) * 1e3;
850
- let cursor = query.after;
851
- for (;;) {
852
- const wait = Math.min(WAIT_MAX_S, Math.max(0, Math.ceil((until - Date.now()) / 1e3)));
853
- const page = await api(who, "GET", path, {
854
- query: {
855
- channelId: channel.id,
856
- include: "message",
857
- ...cursor === void 0 ? { from: "latest" } : { cursor },
858
- ...wait > 0 ? { wait: String(wait) } : {}
859
- },
860
- signal
861
- });
862
- cursor = page.cursor;
863
- const events = [];
864
- for (const change of page.events) {
865
- const message = change.currentMessage;
866
- const found = message && change.threadId ? {
867
- message,
868
- thread: query.label?.length ? await thread(change.threadId) : { id: change.threadId }
869
- } : null;
870
- if (!found) continue;
871
- const event = await eventOf(who, change, channel.name, change.cursor ?? page.cursor, query, me, found);
872
- if (event) events.push(event);
873
- }
874
- if (events.length > 0 || Date.now() >= until || signal.aborted) return {
875
- events,
876
- cursor
877
- };
878
- }
879
- }
880
- /** The one channel a read names, when the API can read it directly: not a subtree, and from one of its cursors or now. */
881
- async function oneChannel(who, access, query) {
882
- if (query.channel === void 0 || query.channel.endsWith("/") || query.re !== void 0) return null;
883
- if (query.after !== void 0 && !API_CURSOR.test(query.after)) return null;
884
- const [channel] = await channelsFor(who, query.channel, access);
885
- return channel ?? null;
886
- }
887
- /** Who wrote or reacted in the latest messages of each channel `access` reads. */
888
- async function actorsSeen(who, access, signal) {
889
- const path = await onBoard(who, "/messages");
890
- const seen = /* @__PURE__ */ new Set();
891
- for (const channel of await channelsFor(who, void 0, access)) {
892
- const { messages } = await api(who, "GET", path, {
893
- query: {
894
- channelId: channel.id,
895
- limit: String(PAGE_MAX)
896
- },
897
- signal
898
- });
899
- for (const message of messages) {
900
- seen.add(message.createdBy.id);
901
- for (const actors of Object.values(message.reactors ?? {})) for (const actor of actors) seen.add(actor);
902
- }
903
- }
904
- return seen;
905
- }
906
- /** What a gateway caller does here, as this deployment: never what's the project's own. */
907
- function checkCaller(method, caller) {
908
- if ("identity" in caller && PROJECTS_OWN.has(method)) throw forbidden(`this board's callers act as its project on Vercel's board, which can't tell them apart: ${method} is the project's own to do there`);
909
- }
910
- /**
911
- * The API owns messages and schedules by principal, and sees every caller here as this project:
912
- * a caller that is the project (its own deployment's token) changes what it wrote, as on any
913
- * board, and anyone else would be changing what the project wrote for others.
914
- */
915
- /** Whether a caller is this project: the deployment's own code, or a caller verified as its principal. */
916
- const isProject = async (caller, who) => !("identity" in caller) || caller.identity.principal.id === principalId((await self(who)).actor.principal);
917
- async function checkOwner(what, caller, who) {
918
- if (!await isProject(caller, who)) throw forbidden(`this board's callers act as its project on Vercel's board, which owns what any of them wrote: only the project itself may ${what} there`);
919
- }
920
- /** A file is no use until a post or an import carries it, so uploading takes `post` or `sync` somewhere, as on a2(). */
921
- async function checkUploader(caller, who) {
922
- await checkOwner("upload", caller, who);
923
- const access = accessOf(caller);
924
- if (access && !access.anywhere("post") && !access.anywhere("sync")) throw forbidden("this token can't post anywhere, so it can't upload");
925
- }
926
- const meOf = (identity) => {
927
- const { principal, author, actor } = identity;
928
- return {
929
- actor: actor.id,
930
- principal: principal.id,
931
- kind: actor.kind,
932
- handle: actor.handle,
933
- name: actor.name,
934
- avatar: actor.avatar,
935
- profile: author.profile,
936
- session: author.session,
937
- expiresAt: principal.expiresAt?.toISOString() ?? null,
938
- can: principal.access.summary()
939
- };
940
- };
941
- /** A watcher's tail registers with the API as its own: an API watcher, so a match is the API's to make. */
942
- const tagOf = async (watch) => (await sha256(canonicalWatchers(watch))).slice(0, 32);
943
- /** Who `--by` names, as the API's authors: an actor, a principal, or everyone here with that handle or profile, as of now. */
944
- async function authorsOf(who, by) {
945
- if (by === "me") return [await actorOf(who)];
946
- if (by.startsWith("vercel:")) return [by];
947
- const named = (await all(who, await onBoard(who, "/actors"), "actors")).filter((actor) => actor.handle === by || actor.id.endsWith(`+${by.toLowerCase()}`)).map((actor) => actor.id);
948
- if (named.length === 0) throw new HttpError(400, "bad_watcher", `--by ${by}: nobody here goes by that yet: name them by their actor ID`);
949
- return named;
950
- }
951
- /**
952
- * A tail as the filter the API matches. The API reads no tails: channels, people, and threads are
953
- * looked up here, now, and what it can't match (mentions, other sources) is refused rather than
954
- * left to match nothing.
955
- */
956
- async function filterOf(who, id, spec) {
957
- const bad = (message) => new HttpError(400, "bad_watcher", `watch ${id}: ${message}`);
958
- if (!RemoteWatcherId.safeParse(id).success) throw bad("ids start with a letter and use up to 32 letters, numbers, and hyphens");
959
- let filters;
960
- try {
961
- ({filters} = compileWatcher(id, spec));
962
- } catch (error) {
963
- throw new HttpError(400, "bad_watcher", error.message);
964
- }
965
- if (filters.mentions !== void 0) throw bad("Vercel's boards can't match mentions yet");
966
- if (filters.from !== void 0 && filters.from !== "board") throw bad(`nothing comes from ${filters.from} here: every message is written on the board`);
967
- const filter = {};
968
- if (filters.channel !== void 0) {
969
- if (filters.channel.endsWith("/")) filter.channelTree = filters.channel.slice(0, -1);
970
- else {
971
- const found = await channelNamed(who, filters.channel);
972
- if (found) filter.channelIds = [found.id];
973
- else filter.channelTree = filters.channel;
974
- }
975
- }
976
- if (filters.re !== void 0) {
977
- const at = locate(filters.re);
978
- if (!at) throw bad(`--re ${filters.re} names no message here`);
979
- filter.threadId = at.threadId;
980
- }
981
- if (filters.by !== void 0) filter.authors = await authorsOf(who, filters.by);
982
- if (filters.text !== void 0) filter.text = filters.text;
983
- if (filters.label?.length) filter.labels = filters.label.map(([key, values]) => values === null ? { key } : {
984
- key,
985
- values: [...values]
986
- });
987
- return {
988
- filter,
989
- when: spec.when ?? "matches"
990
- };
991
- }
992
- /** A filter shown as a tail again, for listing: what it matches, if not always as it was written. */
993
- async function tailOf(who, { filter }) {
994
- const parts = [];
995
- if (filter.channelIds?.[0]) parts.push((await channelById(who, filter.channelIds[0])).name);
996
- else if (filter.channelTree !== void 0) parts.push(`${filter.channelTree}/`);
997
- if (filter.threadId !== void 0) parts.push(`--re ${idAt(filter.threadId, 1)}`);
998
- if (filter.authors?.[0]) parts.push(`--by ${filter.authors[0]}`);
999
- if (filter.text !== void 0) parts.push(`--text ${JSON.stringify(filter.text)}`);
1000
- for (const { key, values } of filter.labels ?? []) parts.push(`--label ${values ? `${key}=${values.join("|")}` : key}`);
1001
- return parts.join(" ");
1002
- }
1003
- /** Where a registration is woken, as board shows it: its URL, or a path on its project (and a preview's branch). */
1004
- const whereOf = (found) => found.path ? {
1005
- url: null,
1006
- path: found.path,
1007
- ...found.branch ? { branch: found.branch } : {}
1008
- } : { url: found.url };
1009
- async function registerAs(who, where, watch) {
1010
- const specs = Object.fromEntries(Object.entries(watch).map(([id, spec]) => [id, {
1011
- tail: spec.tail,
1012
- when: spec.when ?? "matches"
1013
- }]));
1014
- const filters = Object.fromEntries(await Promise.all(Object.entries(specs).map(async ([id, spec]) => [id, await filterOf(who, id, spec)])));
1015
- const made = await api(who, "PUT", await onBoard(who, "/watchers"), { body: {
1016
- ...where,
1017
- watch: filters,
1018
- tag: await tagOf(specs)
1019
- } });
1020
- return {
1021
- owner: made.owner,
1022
- ...whereOf(made),
1023
- watch: specs,
1024
- sync: [],
1025
- hash: made.hash
1026
- };
1027
- }
1028
- /** A match as vboard hands it out: its event as `vb tail --json` prints it, with its message as it is now. */
1029
- async function matchOf(who, match, me) {
1030
- const found = await messageById(who, match.event.messageId).catch((error) => {
1031
- if (error instanceof HttpError && error.status === 404) return null;
1032
- throw error;
1033
- });
1034
- const channel = found && await channelById(who, found.thread.channelId);
1035
- const event = found && channel && await eventOf(who, match.event, channel.name, match.id, {}, me, found);
1036
- if (!event?.message) return null;
1037
- return {
1038
- id: match.id,
1039
- watcher: match.watcher,
1040
- thread: event.message.thread,
1041
- lease: match.lease,
1042
- attempt: match.attempt,
1043
- event
1044
- };
1045
- }
1046
- async function pullAs(who, query, signal) {
1047
- const { matches } = await api(who, "GET", await onBoard(who, "/watchers/matches"), {
1048
- query: {
1049
- limit: query.limit?.toString(),
1050
- wait: query.wait?.toString()
1051
- },
1052
- ...signal ? { signal } : {}
1053
- });
1054
- const me = await actorOf(who);
1055
- const shown = await Promise.all(matches.map((match) => matchOf(who, match, me)));
1056
- await Promise.all(matches.map((match, i) => shown[i] ? null : ackAs(who, match.id, {
1057
- lease: match.lease,
1058
- skip: true
1059
- }).catch(() => {})));
1060
- return shown.filter((match) => match !== null);
1061
- }
1062
- async function ackAs(who, id, body) {
1063
- await api(who, "POST", await onBoard(who, `/watchers/matches/${encodeURIComponent(id)}/ack`), { body: {
1064
- lease: body.lease,
1065
- ...body.error !== void 0 ? { error: body.error } : {},
1066
- ...body.skip ? { skip: true } : {}
1067
- } });
1068
- }
1069
- /**
1070
- * The API keeps one registration per principal, and this board reaches it as its own deployment:
1071
- * one a caller registered through it would replace the deployment's, and every other caller's.
1072
- */
1073
- function ownWatchers(caller, what) {
1074
- if ("identity" in caller) throw forbidden(`this board registers watchers as its own deployment, so it can't ${what} for you: run them in its config, or register with Vercel's API as yourself`);
1075
- }
1076
- /** This deployment's own: what its config's watchers run as. */
1077
- const deployment = {
1078
- profile: null,
1079
- session: null
1080
- };
1081
- /** This board's config's watchers, which run here when the API wakes it. */
1082
- let tails = {};
1083
- const bound = () => {
1084
- if (!binding) throw new Error("vercel: used before board() bound it");
1085
- return binding;
1086
- };
1087
- const runner = registrant({
1088
- remote: "Vercel's API",
1089
- registry: {
1090
- register: (where) => registerAs(deployment, where, tails),
1091
- matches: ({ signal, ...query }) => pullAs(deployment, query, signal),
1092
- ack: (id, body) => ackAs(deployment, id, body)
1093
- },
1094
- wakeAt: async (here) => wakePath(here) ?? { url: here },
1095
- binding: bound,
1096
- hash: () => tagOf(tails),
1097
- hasWork: () => Object.keys(tails).length > 0,
1098
- rethrow: (error) => {
1099
- throw error;
1100
- },
1101
- registerFor: async (caller, request) => json(await methods.register(caller, RegisterBody.parse(await request.json()), request.signal))
1102
- });
1103
- const methods = {
1104
- ...Object.fromEntries(METHODS.map((method) => [method, async () => {
1105
- throw notSupported(method === "register" || method === "watchers" || method === "matches" || method === "ack" ? "watchers" : method);
1106
- }])),
1107
- async discovery() {
1108
- const who = {
1109
- profile: null,
1110
- session: null
1111
- };
1112
- const team = await teamId();
1113
- if (options.board) await api(who, "GET", await onBoard(who));
1114
- const id = team?.startsWith("team_") ? team : (await self(who)).teamId;
1115
- return {
1116
- version: VERSION,
1117
- url: `${origin}/v1/messageboard${await onBoard(who)}?teamId=${encodeURIComponent(id)}`,
1118
- audience: origin,
1119
- team_id: id,
1120
- project_id: null,
1121
- sync: [],
1122
- wake_by_path: true
1123
- };
1124
- },
1125
- async me(caller) {
1126
- if ("identity" in caller) return meOf(caller.identity);
1127
- const found = await api(whoOf(caller), "GET", "/me");
1128
- const { view: named } = found;
1129
- const shown = named ? {
1130
- kind: apiKind(named.kind),
1131
- handle: named.handle,
1132
- name: named.name ?? named.handle,
1133
- avatar: named.avatar ?? null
1134
- } : actorView(found.actor);
1135
- return {
1136
- actor: found.actor.id,
1137
- principal: principalId(found.actor.principal),
1138
- kind: shown.kind,
1139
- handle: shown.handle,
1140
- name: shown.name,
1141
- avatar: shown.avatar,
1142
- profile: found.actor.profile?.name ?? null,
1143
- session: found.actor.session ?? null,
1144
- expiresAt: null,
1145
- can: { "*": [
1146
- "read",
1147
- "post",
1148
- "react",
1149
- "label"
1150
- ] }
1151
- };
1152
- },
1153
- async channels(caller) {
1154
- return {
1155
- channels: (await channelsFor(whoOf(caller), void 0, accessOf(caller))).map((channel) => ({ path: channel.name })).sort((a, b) => a.path.localeCompare(b.path)),
1156
- cursor: cursorOf({
1157
- t: Date.now(),
1158
- feeds: {}
1159
- })
1160
- };
1161
- },
1162
- async createChannel(caller, { path }) {
1163
- checkCaller("createChannel", caller);
1164
- const access = accessOf(caller);
1165
- need(access, "read", path);
1166
- need(access, "post", path);
1167
- const { created } = await ensureChannel(whoOf(caller), path);
1168
- return {
1169
- channel: { path },
1170
- created
1171
- };
1172
- },
1173
- async actors(caller, _input, signal) {
1174
- const who = whoOf(caller);
1175
- const listed = (await all(who, await onBoard(who, "/actors"), "actors", {}, signal)).map((actor) => ({
1176
- id: actor.id,
1177
- kind: apiKind(actor.kind),
1178
- handle: actor.handle,
1179
- name: actor.name ?? actor.handle,
1180
- avatar: actor.avatar ?? null
1181
- }));
1182
- const cursor = cursorOf({
1183
- t: Date.now(),
1184
- feeds: {}
1185
- });
1186
- if (!("identity" in caller) || caller.identity.principal.access.readsAll) return {
1187
- actors: listed,
1188
- cursor
1189
- };
1190
- const { actor: self, principal } = caller.identity;
1191
- const seen = await actorsSeen(who, principal.access, signal);
1192
- return {
1193
- actors: [...listed.filter((actor) => seen.has(actor.id) && actor.id !== self.id), {
1194
- id: self.id,
1195
- kind: self.kind,
1196
- handle: self.handle,
1197
- name: self.name,
1198
- avatar: self.avatar
1199
- }],
1200
- cursor
1201
- };
1202
- },
1203
- async messages(caller, query, signal) {
1204
- const who = whoOf(caller);
1205
- const access = accessOf(caller);
1206
- const channel = query.before === void 0 ? await oneChannel(who, access, query) : null;
1207
- if (channel) {
1208
- const page = await channelMessages(who, channel, query, signal);
1209
- return {
1210
- messages: await Promise.all(page.messages.map((message) => view(who, message, channel.name))),
1211
- cursor: page.cursor
1212
- };
1213
- }
1214
- if (query.after !== void 0 && API_CURSOR.test(query.after)) throw new HttpError(400, "invalid_request", `after: ${query.after} is one channel's cursor: read that channel`);
1215
- const { messages, feeds, newest } = await collect(who, access, query, signal);
1216
- const after = query.after !== void 0 ? await timeOf(who, query.after) : void 0;
1217
- const before = query.before !== void 0 ? await timeOf(who, query.before) : void 0;
1218
- const limit = query.limit ?? 50;
1219
- const bounded = messages.filter(({ message }) => (after === void 0 || message.createdAt > after) && (before === void 0 || message.createdAt < before));
1220
- const page = after !== void 0 ? bounded.slice(0, limit) : bounded.slice(-limit);
1221
- return {
1222
- messages: await Promise.all(page.map(({ message, channel }) => view(who, message, channel.name))),
1223
- cursor: cursorOf({
1224
- t: newest,
1225
- feeds
1226
- })
1227
- };
1228
- },
1229
- async threads(caller, query, signal) {
1230
- const who = whoOf(caller);
1231
- const after = query.after !== void 0 ? await timeOf(who, query.after) : void 0;
1232
- const limit = query.limit ?? 50;
1233
- const pick = (found) => {
1234
- const ordered = found.filter(({ at }) => after === void 0 || at > after).sort((a, b) => a.at - b.at);
1235
- return after !== void 0 ? ordered.slice(0, limit) : ordered.slice(-limit);
1236
- };
1237
- if (query.re !== void 0 || query.by !== void 0 || query.mentions !== void 0 || query.text !== void 0 || query.from !== void 0 && query.from !== "board") {
1238
- const { messages, feeds, newest } = await collect(who, accessOf(caller), query, signal);
1239
- const latest = /* @__PURE__ */ new Map();
1240
- for (const { message, thread, channel } of messages) latest.set(thread.id, {
1241
- thread,
1242
- channel,
1243
- at: Math.max(latest.get(thread.id)?.at ?? 0, message.createdAt)
1244
- });
1245
- return {
1246
- threads: await Promise.all(pick([...latest.values()]).map(({ thread, channel }) => summary(who, thread, channel, signal))),
1247
- cursor: cursorOf({
1248
- t: newest,
1249
- feeds
1250
- })
1251
- };
1252
- }
1253
- const listed = await channelsFor(who, query.channel, accessOf(caller));
1254
- const feeds = await heads(who, listed);
1255
- const label = indexed(query);
1256
- const found = (await Promise.all(listed.map(async (channel) => (await latestThreads(who, channel, label, {
1257
- ...after !== void 0 ? { after } : {},
1258
- ...query.label?.length ? {} : { limit }
1259
- }, signal)).map((thread) => ({
1260
- thread,
1261
- channel,
1262
- at: thread.lastActivityAt
1263
- }))))).flat();
1264
- const rooted = found.filter(({ thread }) => (query.label ?? []).every(([key, values]) => thread.labels !== void 0 && Object.hasOwn(thread.labels, key) && (values === null || values.includes(thread.labels[key]))));
1265
- const newest = found.reduce((max, { at }) => Math.max(max, at), 0);
1266
- if (!query.label?.length) return {
1267
- threads: await Promise.all(pick(rooted).map(({ thread, channel }) => summary(who, thread, channel, signal))),
1268
- cursor: cursorOf({
1269
- t: newest,
1270
- feeds
1271
- })
1272
- };
1273
- const candidates = rooted.filter(({ at }) => after === void 0 || at > after).sort((a, b) => a.at - b.at);
1274
- if (after === void 0) candidates.reverse();
1275
- const threads = [];
1276
- for (let next = 0; next < candidates.length && threads.length < limit;) {
1277
- const page = candidates.slice(next, next + limit - threads.length);
1278
- next += page.length;
1279
- for (const shown of await Promise.all(page.map(({ thread, channel }) => summary(who, thread, channel, signal)))) if (!shown.message.deleted) threads.push(shown);
1280
- }
1281
- if (after === void 0) threads.reverse();
1282
- return {
1283
- threads,
1284
- cursor: cursorOf({
1285
- t: newest,
1286
- feeds
1287
- })
1288
- };
1289
- },
1290
- async message(caller, { id }, signal) {
1291
- const who = whoOf(caller);
1292
- const { thread, channel } = await readableMessage(who, accessOf(caller), id, signal);
1293
- const [root, ...replies] = await threadMessages(who, thread.id, signal);
1294
- if (!root) throw notFound(`message not found: ${id}`, "message_not_found");
1295
- return {
1296
- message: await view(who, root, channel.name),
1297
- replies: await Promise.all(replies.map((reply) => view(who, reply, channel.name))),
1298
- cursor: cursorOf({
1299
- t: Math.max(root.createdAt, ...replies.map((reply) => reply.createdAt)),
1300
- feeds: {}
1301
- })
1302
- };
1303
- },
1304
- async upload(caller, { data, name, type }) {
1305
- const who = whoOf(caller);
1306
- await checkUploader(caller, who);
1307
- if (data.byteLength === 0) throw new HttpError(400, "bad_request", "the file is empty");
1308
- if (data.byteLength > 26214400) throw new HttpError(413, "too_large", `attachments are at most ${IMPORT_BYTES_MAX / 1024 / 1024} MB`);
1309
- const bytes = new Uint8Array(data);
1310
- const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
1311
- const started = await api(who, "POST", await onBoard(who, "/attachments"), { body: {
1312
- operationId: operationId(),
1313
- name: fileName(name),
1314
- type: mediaType(type),
1315
- size: data.byteLength,
1316
- sha256: btoa(String.fromCharCode(...digest))
1317
- } });
1318
- const put = await filesFetch(started.upload.url, {
1319
- method: started.upload.method,
1320
- headers: started.upload.headers,
1321
- body: bytes,
1322
- redirect: "error"
1323
- });
1324
- if (!put.ok) throw new HttpError(502, "upload_failed", `the upload to Vercel's storage answered ${put.status}`);
1325
- const { attachment } = await api(who, "POST", await onBoard(who, `/attachments/${encodeURIComponent(started.attachment.id)}/complete`));
1326
- return { attachment: fileOf(attachment) };
1327
- },
1328
- async uploadStart(caller, { name, type, size, sha256 }) {
1329
- const who = whoOf(caller);
1330
- await checkUploader(caller, who);
1331
- if (sha256 === void 0) throw new HttpError(400, "invalid_request", "Vercel's API signs a direct upload for its bytes' SHA-256: send `sha256`, as board's client does");
1332
- const started = await api(who, "POST", await onBoard(who, "/attachments"), { body: {
1333
- operationId: operationId(),
1334
- name: fileName(name ?? null),
1335
- type: mediaType(type ?? null),
1336
- size,
1337
- sha256
1338
- } });
1339
- return {
1340
- id: started.attachment.id,
1341
- url: started.upload.url,
1342
- headers: started.upload.headers,
1343
- expiresAt: iso(started.upload.expiresAt)
1344
- };
1345
- },
1346
- async uploadFinish(caller, { id }) {
1347
- const who = whoOf(caller);
1348
- await checkUploader(caller, who);
1349
- const { attachment } = await api(who, "POST", await onBoard(who, `/attachments/${encodeURIComponent(id)}/complete`));
1350
- return { attachment: fileOf(attachment) };
1351
- },
1352
- async attachment(caller, { id }, signal) {
1353
- const who = whoOf(caller);
1354
- const access = accessOf(caller);
1355
- const found = await api(who, "GET", await onBoard(who, `/attachments/${encodeURIComponent(id)}`), signal ? { signal } : {});
1356
- if (access && !found.attachment.messageId) {
1357
- if (!await isProject(caller, who)) throw notFound(`no attachment: ${id}`, "attachment_not_found");
1358
- } else if (access) {
1359
- const { message } = await readableMessage(who, access, found.attachment.messageId, signal).catch((error) => {
1360
- if (error instanceof HttpError && error.status === 404) throw notFound(`no attachment: ${id}`, "attachment_not_found");
1361
- throw error;
1362
- });
1363
- if (message.deletedAt !== void 0) throw notFound(`no attachment: ${id}`, "attachment_not_found");
1364
- }
1365
- const response = await filesFetch(found.url, {
1366
- redirect: "error",
1367
- ...signal ? { signal } : {}
1368
- });
1369
- if (!response.ok || !response.body) throw new HttpError(502, "download_failed", `Vercel's storage answered ${response.status}`);
1370
- return {
1371
- attachment: fileOf(found.attachment),
1372
- data: response.body
1373
- };
1374
- },
1375
- async post(caller, input, signal) {
1376
- checkCaller("post", caller);
1377
- if (input.sync?.length) throw notSupported("sync");
1378
- const who = whoOf(caller);
1379
- const access = accessOf(caller);
1380
- if (input.attachments?.length) await checkOwner("post files", caller, who);
1381
- const labeled = Object.keys(input.labels ?? {}).length > 0;
1382
- const clientId = input.id !== void 0 ? await postId(caller, input.id) : void 0;
1383
- let made;
1384
- if (input.channel !== void 0) {
1385
- need(access, "post", input.channel);
1386
- if (labeled) need(access, "label", input.channel);
1387
- const channel = await channelToPost(who, input.channel);
1388
- made = await api(who, "POST", await onBoard(who, "/threads"), {
1389
- body: {
1390
- operationId: operationId(),
1391
- channelId: channel.id,
1392
- text: input.text,
1393
- ...input.labels && Object.keys(input.labels).length ? { labels: input.labels } : {},
1394
- ...clientId ? { clientId } : {},
1395
- ...input.attachments?.length ? { attachments: input.attachments } : {}
1396
- },
1397
- signal
1398
- });
1399
- } else {
1400
- const { thread, message: to, channel } = await readableMessage(who, access, input.re, signal);
1401
- need(access, "post", channel.name);
1402
- if (labeled) need(access, "label", channel.name);
1403
- const after = input.after === void 0 ? void 0 : locate(input.after);
1404
- if (after !== void 0 && after?.threadId !== thread.id) {
1405
- const landed = clientId ? await api(who, "GET", await onBoard(who, `/posts/${encodeURIComponent(clientId)}`), { signal }).catch(() => null) : null;
1406
- if (landed?.thread.id === thread.id) return { message: await view(who, landed.message, channel.name) };
1407
- throw badRequest(`after: ${input.after} isn't in ${input.re}'s thread`, "invalid_after");
1408
- }
1409
- made = await api(who, "POST", await onBoard(who, `/threads/${encodeURIComponent(thread.id)}/messages`), {
1410
- body: {
1411
- operationId: operationId(),
1412
- text: input.text,
1413
- ...to.sequence > 1 ? { replyTo: to.sequence } : {},
1414
- ...clientId ? { clientId } : {},
1415
- ...input.attachments?.length ? { attachments: input.attachments } : {},
1416
- ...after ? { after: after.sequence } : {}
1417
- },
1418
- signal
1419
- }).catch((error) => {
1420
- if (error instanceof HttpError && error.code === "newer_message") throw new HttpError(409, "newer_message", `a message came after ${input.after}`);
1421
- throw error;
1422
- });
1423
- if (input.labels && Object.keys(input.labels).length) {
1424
- const labeled = await api(who, "POST", await onBoard(who, `/threads/${encodeURIComponent(thread.id)}/messages/${made.message.sequence}/labels`), {
1425
- body: {
1426
- operationId: operationId(),
1427
- set: input.labels
1428
- },
1429
- signal
1430
- });
1431
- made = {
1432
- ...made,
1433
- message: {
1434
- ...made.message,
1435
- ...labeled.meta.labels ? { labels: labeled.meta.labels } : {},
1436
- version: labeled.meta.version
1437
- }
1438
- };
1439
- }
1440
- }
1441
- const channel = await channelById(who, made.thread.channelId);
1442
- return { message: await view(who, made.message, channel.name) };
1443
- },
1444
- async posted(caller, { id }, signal) {
1445
- checkCaller("posted", caller);
1446
- const who = whoOf(caller);
1447
- const found = await api(who, "GET", await onBoard(who, `/posts/${encodeURIComponent(await postId(caller, id))}`), { signal });
1448
- const channel = await channelById(who, found.thread.channelId);
1449
- const access = accessOf(caller);
1450
- if (access && !access.readable(channel.name)) throw notFound(`no post of yours has id ${id}`, "post_not_found");
1451
- return { message: await view(who, found.message, channel.name) };
1452
- },
1453
- async edit(caller, { id, text, revision }, signal) {
1454
- const who = whoOf(caller);
1455
- await checkOwner("edit", caller, who);
1456
- const at = locate(id);
1457
- if (!at) throw notFound(`message not found: ${id}`, "message_not_found");
1458
- const access = accessOf(caller);
1459
- if (access) need(access, "post", (await readableMessage(who, access, id, signal)).channel.name);
1460
- await api(who, "PATCH", await onBoard(who, `/threads/${encodeURIComponent(at.threadId)}/messages/${at.sequence}`), {
1461
- body: {
1462
- operationId: operationId(),
1463
- text,
1464
- ...revision !== void 0 ? { revision } : {}
1465
- },
1466
- signal
1467
- });
1468
- return { ok: true };
1469
- },
1470
- async delete(caller, { id, revision }, signal) {
1471
- const who = whoOf(caller);
1472
- await checkOwner("delete", caller, who);
1473
- const at = locate(id);
1474
- if (!at) throw notFound(`message not found: ${id}`, "message_not_found");
1475
- const access = accessOf(caller);
1476
- if (access) need(access, "post", (await readableMessage(who, access, id, signal)).channel.name);
1477
- await api(who, "POST", await onBoard(who, `/threads/${encodeURIComponent(at.threadId)}/messages/${at.sequence}/delete`), {
1478
- body: {
1479
- operationId: operationId(),
1480
- ...revision !== void 0 ? { revision } : {}
1481
- },
1482
- signal
1483
- });
1484
- return { ok: true };
1485
- },
1486
- async react(caller, { id, emoji, remove }, signal) {
1487
- checkCaller("react", caller);
1488
- const who = whoOf(caller);
1489
- const at = locate(id);
1490
- if (!at) throw notFound(`message not found: ${id}`, "message_not_found");
1491
- const access = accessOf(caller);
1492
- if (access) need(access, "react", (await readableMessage(who, access, id, signal)).channel.name);
1493
- await api(who, "POST", await onBoard(who, `/threads/${encodeURIComponent(at.threadId)}/messages/${at.sequence}/reactions`), {
1494
- body: {
1495
- operationId: operationId(),
1496
- emoji,
1497
- ...remove ? { remove: true } : {}
1498
- },
1499
- signal
1500
- });
1501
- return { ok: true };
1502
- },
1503
- async label(caller, { id, set, unset, if: expected }, signal) {
1504
- checkCaller("label", caller);
1505
- const who = whoOf(caller);
1506
- const at = locate(id);
1507
- if (!at) throw notFound(`message not found: ${id}`, "message_not_found");
1508
- const access = accessOf(caller);
1509
- if (access) need(access, "label", (await readableMessage(who, access, id, signal)).channel.name);
1510
- await api(who, "POST", await onBoard(who, `/threads/${encodeURIComponent(at.threadId)}/messages/${at.sequence}/labels`), {
1511
- body: {
1512
- operationId: operationId(),
1513
- ...set ? { set } : {},
1514
- ...unset ? { unset } : {},
1515
- ...expected && Object.keys(expected).length ? { if: expected } : {}
1516
- },
1517
- signal
1518
- });
1519
- return { ok: true };
1520
- },
1521
- async grants(caller, _input, signal) {
1522
- checkCaller("grants", caller);
1523
- const who = whoOf(caller);
1524
- return api(who, "GET", await onBoard(who, "/grants"), signal ? { signal } : {});
1525
- },
1526
- async createGrant(caller, input, signal) {
1527
- checkCaller("createGrant", caller);
1528
- const who = whoOf(caller);
1529
- return api(who, "POST", await onBoard(who, "/grants"), {
1530
- body: {
1531
- operationId: operationId(),
1532
- ...input
1533
- },
1534
- ...signal ? { signal } : {}
1535
- });
1536
- },
1537
- async revokeGrant(caller, { id }, signal) {
1538
- checkCaller("revokeGrant", caller);
1539
- const who = whoOf(caller);
1540
- return api(who, "POST", await onBoard(who, `/grants/${encodeURIComponent(id)}/revoke`), {
1541
- body: { operationId: operationId() },
1542
- ...signal ? { signal } : {}
1543
- });
1544
- },
1545
- async tokens(caller, _input, signal) {
1546
- checkCaller("tokens", caller);
1547
- const who = whoOf(caller);
1548
- return api(who, "GET", await onBoard(who, "/tokens"), signal ? { signal } : {});
1549
- },
1550
- async createToken(caller, input, signal) {
1551
- checkCaller("createToken", caller);
1552
- const who = whoOf(caller);
1553
- return api(who, "POST", await onBoard(who, "/tokens"), {
1554
- body: {
1555
- operationId: operationId(),
1556
- ...input
1557
- },
1558
- ...signal ? { signal } : {}
1559
- });
1560
- },
1561
- async revokeToken(caller, { id }, signal) {
1562
- checkCaller("revokeToken", caller);
1563
- const who = whoOf(caller);
1564
- return api(who, "POST", await onBoard(who, `/tokens/${encodeURIComponent(id)}/revoke`), {
1565
- body: { operationId: operationId() },
1566
- ...signal ? { signal } : {}
1567
- });
1568
- },
1569
- async schedule(caller, input, signal) {
1570
- if (input.attachments?.length) throw notSupported("files on scheduled messages");
1571
- const who = whoOf(caller);
1572
- await checkOwner("schedule", caller, who);
1573
- const access = accessOf(caller);
1574
- const labels = input.labels && Object.keys(input.labels).length ? input.labels : void 0;
1575
- let target;
1576
- if (input.channel !== void 0) {
1577
- need(access, "post", input.channel);
1578
- if (labels) need(access, "label", input.channel);
1579
- target = { channelId: (await channelToPost(who, input.channel)).id };
1580
- } else {
1581
- if (labels) throw notSupported("labels on a scheduled reply");
1582
- const { thread, channel } = await readableMessage(who, access, input.re, signal);
1583
- need(access, "post", channel.name);
1584
- target = { threadId: thread.id };
1585
- }
1586
- const ms = (value) => Math.round(duration(value));
1587
- const firstAt = input.at !== void 0 ? Date.parse(input.at) : Date.now() + ms(input.in ?? input.every);
1588
- const until = input.until !== void 0 ? Date.parse(input.until) : input.for !== void 0 ? firstAt + ms(input.for) : void 0;
1589
- const { schedule } = await api(who, "POST", await onBoard(who, "/schedules"), {
1590
- body: {
1591
- operationId: operationId(),
1592
- ...target,
1593
- text: input.text,
1594
- ...labels ? { labels } : {},
1595
- firstAt,
1596
- ...input.every !== void 0 ? { every: ms(input.every) } : {},
1597
- ...until !== void 0 ? { until } : {},
1598
- ...input.times !== void 0 ? { times: input.times } : {}
1599
- },
1600
- signal
1601
- });
1602
- return { schedule: await scheduleView(who, schedule) };
1603
- },
1604
- async schedules(caller, query, signal) {
1605
- const who = whoOf(caller);
1606
- const access = accessOf(caller);
1607
- const filter = { state: query.all ? void 0 : "pending" };
1608
- if (query.re !== void 0) {
1609
- const found = await readableMessage(who, access, query.re, signal).catch((error) => {
1610
- if (error instanceof HttpError && error.status === 404) return null;
1611
- throw error;
1612
- });
1613
- if (!found) return { schedules: [] };
1614
- filter.threadId = found.thread.id;
1615
- }
1616
- if (query.channel !== void 0) {
1617
- const channel = await channelNamed(who, query.channel);
1618
- if (!channel) return { schedules: [] };
1619
- filter.channelId = channel.id;
1620
- }
1621
- const me = query.by === "me" ? await actorOf(who) : void 0;
1622
- const by = me ?? query.by;
1623
- if (by?.startsWith("vercel:")) filter.createdBy = by;
1624
- const created = (actor) => by === void 0 || (me ? actor.id === me : [
1625
- actor.id,
1626
- principalId(actor.principal),
1627
- actor.profile?.name
1628
- ].includes(by));
1629
- const listed = await all(who, await onBoard(who, "/schedules"), "schedules", filter, signal);
1630
- return { schedules: (await Promise.all(listed.filter((schedule) => created(schedule.createdBy)).map((schedule) => scheduleView(who, schedule)))).filter((schedule) => access === null || access.readable(schedule.channel)) };
1631
- },
1632
- async cancelSchedule(caller, { id }, signal) {
1633
- const who = whoOf(caller);
1634
- await checkOwner("cancelSchedule", caller, who);
1635
- const access = accessOf(caller);
1636
- if (access) {
1637
- const found = (await all(who, await onBoard(who, "/schedules"), "schedules", {}, signal)).find((schedule) => schedule.id === id);
1638
- const channel = found && await channelById(who, found.channelId);
1639
- if (!channel || !access.readable(channel.name)) throw notFound(`no schedule: ${id}`, "schedule_not_found");
1640
- need(access, "post", channel.name);
1641
- }
1642
- const { schedule, canceled } = await api(who, "POST", await onBoard(who, `/schedules/${encodeURIComponent(id)}/cancel`), {
1643
- body: { operationId: operationId() },
1644
- signal
1645
- });
1646
- return {
1647
- schedule: await scheduleView(who, schedule),
1648
- canceled
1649
- };
1650
- },
1651
- async events(caller, query, signal) {
1652
- checkCaller("events", caller);
1653
- const who = whoOf(caller);
1654
- const access = accessOf(caller);
1655
- const channel = await oneChannel(who, access, query);
1656
- if (channel) return channelEvents(who, channel, query, signal);
1657
- if (query.after !== void 0 && API_CURSOR.test(query.after)) throw new HttpError(400, "invalid_request", `after: ${query.after} is one channel's cursor: read that channel`);
1658
- const listed = await channelsFor(who, query.channel, access);
1659
- let position = query.after === void 0 ? {
1660
- t: Date.now(),
1661
- feeds: await heads(who, listed)
1662
- } : locate(query.after) ? {
1663
- t: await timeOf(who, query.after),
1664
- feeds: {}
1665
- } : positionOf(query.after);
1666
- const until = Date.now() + (query.wait ?? 0) * 1e3;
1667
- let busy = false;
1668
- for (;;) {
1669
- const started = Date.now();
1670
- const page = await read(who, listed, position, query, signal);
1671
- position = page.position;
1672
- if (page.events.length > 0 || Date.now() >= until || signal.aborted) return {
1673
- events: page.events,
1674
- cursor: cursorOf(position)
1675
- };
1676
- if (!busy) busy = await changed(who, listed, position, until, signal) && Date.now() - started < 1e3;
1677
- await pause(Math.min(started + 1e3, until) - Date.now(), signal);
1678
- }
1679
- },
1680
- async typing() {
1681
- return { targets: [] };
1682
- },
1683
- async readSource(_caller, { key }) {
1684
- throw notFound(`this board doesn't run sync entry ${key}`, "not_synced_here");
1685
- },
1686
- async watchers(caller) {
1687
- ownWatchers(caller, "list watchers");
1688
- const who = whoOf(caller);
1689
- const { watchers } = await api(who, "GET", await onBoard(who, "/watchers"));
1690
- return { watchers: await Promise.all(watchers.map(async (found) => ({
1691
- owner: found.owner,
1692
- ...whereOf(found),
1693
- watch: Object.fromEntries(await Promise.all(Object.entries(found.watch).map(async ([id, spec]) => [id, {
1694
- tail: await tailOf(who, spec),
1695
- when: spec.when
1696
- }]))),
1697
- sync: [],
1698
- hash: found.hash
1699
- }))) };
1700
- },
1701
- async register(caller, body) {
1702
- ownWatchers(caller, "register watchers");
1703
- if ((body.sync?.length ?? 0) > 0) throw notSupported("sync");
1704
- return registerAs(whoOf(caller), typeof body.path === "string" ? {
1705
- path: body.path,
1706
- ...body.branch ? { branch: body.branch } : {}
1707
- } : { url: body.url ?? null }, body.watch);
1708
- },
1709
- async matches(caller, query, signal) {
1710
- ownWatchers(caller, "pull matches");
1711
- return { matches: await pullAs(whoOf(caller), query, signal) };
1712
- },
1713
- async ack(caller, { id, ...body }) {
1714
- ownWatchers(caller, "ack matches");
1715
- await ackAs(whoOf(caller), id, body);
1716
- return { ok: true };
1717
- }
1718
- };
1719
- return {
1720
- ...Object.fromEntries(Object.entries(methods).map(([name, method]) => [name, (...args) => {
1721
- if (binding) runner.start();
1722
- return method(...args);
1723
- }])),
1724
- routes: runner.routes,
1725
- keeps: false,
1726
- sendsSchedulesHere: false,
1727
- bind(next) {
1728
- if (binding) throw new Error("vercel: this backend already serves a board: create one vercel() per board()");
1729
- if (Object.values(next.subscriptions).map((subscription) => subscription.kind).includes("sync")) throw new Error("vercel: Vercel's boards don't run sync yet: leave `sync` out");
1730
- for (const id of Object.keys(next.subscriptions)) own.add(id);
1731
- tails = Object.fromEntries(Object.entries(next.subscriptions).flatMap(([id, subscription]) => subscription.kind === "tail" ? [[id, {
1732
- tail: subscription.tail,
1733
- when: subscription.when
1734
- }]] : []));
1735
- binding = next;
1736
- },
1737
- /** Registers this board's watchers with Vercel's API now, as `POST /watchers` does. */
1738
- registerWatchers: runner.registerNow,
1739
- /** Stops pulling, for a board that pulls on its own. */
1740
- close: runner.close
1741
- };
1742
- }
1743
- //#endregion
1744
- export { isApiMessageId as n, createVercel as t };