@vercel/board 0.39.0 → 0.41.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 (100) hide show
  1. package/README.md +6 -4
  2. package/dist/{access-CVkjSfxj.mjs → access-C5HaO42b.mjs} +2 -2
  3. package/dist/access.d.mts +6 -6
  4. package/dist/access.mjs +5 -5
  5. package/dist/actors-nrOf7Y7z.mjs +160 -0
  6. package/dist/{auth-BXLCkeB0.d.mts → auth-Bn8J_1F2.d.mts} +14 -29
  7. package/dist/{auth-B3bBYOqf.mjs → auth-DAlYi6TN.mjs} +9 -19
  8. package/dist/{backend-HcCCGPG4.d.mts → backend-CYsTLxtP.d.mts} +139 -43
  9. package/dist/backend-local.d.mts +1 -1
  10. package/dist/backend-local.mjs +1 -1
  11. package/dist/blocks-CVoBC7ur.mjs +402 -0
  12. package/dist/blocks-DGvh2alZ.d.mts +33 -0
  13. package/dist/{chat-provider-1WKsLEnM.mjs → chat-provider-CPZg2MQb.mjs} +2 -2
  14. package/dist/{chat-provider-DyNy5xdC.d.mts → chat-provider-Cgkh9xJw.d.mts} +2 -2
  15. package/dist/cli-commands.d.mts +1 -1
  16. package/dist/cli-commands.mjs +1 -1
  17. package/dist/cli-embedded.d.mts +3 -3
  18. package/dist/cli-embedded.mjs +4 -4
  19. package/dist/cli.mjs +8 -13
  20. package/dist/{commands-B5d-lmNN.d.mts → commands-CrEVjASe.d.mts} +14 -26
  21. package/dist/{commands-BLS7erNu.mjs → commands-QRD0U9AQ.mjs} +114 -105
  22. package/dist/{conformance-D59Py2m2.mjs → conformance-ClxEEZ9C.mjs} +378 -101
  23. package/dist/conformance.d.mts +11 -9
  24. package/dist/conformance.mjs +1 -1
  25. package/dist/data-values-C-Cq80hz.mjs +176 -0
  26. package/dist/digest-Dna1CGa_.mjs +4 -0
  27. package/dist/{engine-eUgO5jTM.mjs → engine-8BcNeckB.mjs} +197 -84
  28. package/dist/{errors-rYDxZEuN.mjs → errors-DcQf5WeM.mjs} +123 -42
  29. package/dist/{events-C6HwB046.mjs → events-BT8y_81j.mjs} +2 -2
  30. package/dist/{exports-M5o4PTfO.mjs → exports-B6udRV_E.mjs} +961 -383
  31. package/dist/exports-C8zsIL1A.d.mts +4 -0
  32. package/dist/{external-CHDxWIVf.mjs → external-DymyhUzl.mjs} +1 -1
  33. package/dist/{index-rNqqgkyu.d.mts → index-fcpEFCTR.d.mts} +2 -2
  34. package/dist/index.d.mts +7 -6
  35. package/dist/index.mjs +8 -6
  36. package/dist/index.node.d.mts +7 -6
  37. package/dist/index.node.mjs +5 -4
  38. package/dist/inspect/app.js +110 -109
  39. package/dist/inspect/engine.js +5 -5
  40. package/dist/inspect-BsF3mYMY.mjs +2 -0
  41. package/dist/{inspect-BkXxR2uB.mjs → inspect-DPRoC_Gg.mjs} +6 -6
  42. package/dist/{local-DvkOWf4U.mjs → local-B9y4p6N7.mjs} +463 -512
  43. package/dist/{main-DtV_Po9i.mjs → main-S0A-c_kP.mjs} +549 -178
  44. package/dist/{memory-DkoqhxIH.mjs → memory-DhduVbUu.mjs} +2 -2
  45. package/dist/{mentions-CB6ShY4R.mjs → mentions-DfZGp3B-.mjs} +18 -4
  46. package/dist/{middleware-CPqAuRtp.mjs → middleware-DHdrxmoc.mjs} +71 -3
  47. package/dist/{targets-C1mT3M1N.mjs → origin-B3m2lnZC.mjs} +43 -64
  48. package/dist/{page-64IwoGRu.mjs → page-2jjHZmIW.mjs} +2 -2
  49. package/dist/page-CAUe4GmQ.mjs +2 -0
  50. package/dist/{provider-D5yVFisj.d.mts → provider-dY54GFNz.d.mts} +20 -34
  51. package/dist/{routes-BffuaoTX.d.mts → routes-By9lmvUD.d.mts} +91 -77
  52. package/dist/{schemas-AZkxk06N.mjs → schemas-DAzSsgWk.mjs} +8 -3
  53. package/dist/schemas.d.mts +37 -0
  54. package/dist/schemas.mjs +3 -0
  55. package/dist/{serve-CX1rqDF_.mjs → serve-B15I2Ibf.mjs} +5 -5
  56. package/dist/{server-DkYkyarg.mjs → server-DgpRZ4Nu.mjs} +74 -127
  57. package/dist/{serving-DJMcG0dT.mjs → serving-CALKWs9K.mjs} +1 -1
  58. package/dist/{sql-l3ysn4O5.mjs → sql-P9g-rLIF.mjs} +75 -12
  59. package/dist/{sqlite-CAwNHbQD.mjs → sqlite-B3rCcIof.mjs} +2 -2
  60. package/dist/{sqlite-db-cm5yhrD-.mjs → sqlite-db-D0Fyju-4.mjs} +1 -1
  61. package/dist/sync-chat-sdk.d.mts +2 -2
  62. package/dist/sync-chat-sdk.mjs +2 -2
  63. package/dist/sync-github.d.mts +2 -2
  64. package/dist/sync-github.mjs +2 -2
  65. package/dist/sync-linear.d.mts +3 -3
  66. package/dist/sync-linear.mjs +2 -2
  67. package/dist/sync-slack.d.mts +14 -8
  68. package/dist/sync-slack.mjs +46 -19
  69. package/dist/sync.d.mts +2 -2
  70. package/dist/sync.mjs +2 -2
  71. package/dist/{tokens-DA9ipsZ-.mjs → tokens-D7_ZIWpX.mjs} +4 -4
  72. package/docs/01-board/01-mounting.md +13 -16
  73. package/docs/01-board/03-identity.md +112 -74
  74. package/docs/01-board/04-messages.md +61 -2
  75. package/docs/01-board/05-reading.md +11 -5
  76. package/docs/01-board/06-watchers.md +17 -13
  77. package/docs/01-board/07-schedules.md +8 -6
  78. package/docs/01-board/08-middleware.md +1 -1
  79. package/docs/01-board/09-access.md +80 -132
  80. package/docs/02-sync/01-overview.md +75 -4
  81. package/docs/02-sync/02-functions.md +11 -6
  82. package/docs/02-sync/03-slack.md +43 -19
  83. package/docs/02-sync/06-providers.md +9 -4
  84. package/docs/03-guides/01-coding-agents.md +18 -22
  85. package/docs/03-guides/02-inspector.md +4 -5
  86. package/docs/03-guides/03-ci.md +7 -26
  87. package/docs/03-guides/04-triage.md +2 -2
  88. package/docs/03-guides/05-agent-factory.md +7 -9
  89. package/docs/03-guides/06-sandboxed-agents.md +149 -0
  90. package/docs/04-reference/01-cli.md +161 -104
  91. package/docs/04-reference/02-board.md +89 -37
  92. package/docs/04-reference/03-http.md +176 -71
  93. package/docs/04-reference/05-conformance.md +47 -21
  94. package/docs/index.md +5 -5
  95. package/package.json +5 -1
  96. package/dist/actors-kfMejhaw.mjs +0 -156
  97. package/dist/digest-krhjNAt4.mjs +0 -4
  98. package/dist/exports-vLQ2Y2Nd.d.mts +0 -4
  99. package/dist/inspect-lnv1sLXM.mjs +0 -2
  100. package/dist/page-BUj8_UZv.mjs +0 -2
@@ -1,10 +1,12 @@
1
- import { a as forbidden, c as toErrorResponse, d as createBoardClient, f as duration, g as fileName, h as IMPORT_BYTES_MAX, l as unauthorized, n as RejectedError, o as json, p as ATTACHMENT_BYTES_MAX, r as badRequest, s as notFound, t as HttpError, u as BoardError, v as mediaType } from "./errors-rYDxZEuN.mjs";
2
- import { h as RemoteWatcherId } from "./schemas-AZkxk06N.mjs";
3
- import { A as MatchesQuery, B as SyncBody, C as GrantBody, D as InboxQuery, E as InboxPushBody, F as RegisterBody, G as ThreadsQuery, H as SyncFindQuery, I as ScheduleBody, J as UpdateGrantBody, K as TokenBody, L as SchedulesQuery, M as PostBody, N as ReactBody, O as LabelBody, P as Ref, R as SourceJoinBody, S as ExplainQuery, T as InboxNextQuery, U as SyncImportBody, V as SyncCopiesQuery, W as SyncReceiptBody, Y as UploadStartBody, _ as AckBody, a as runMatch, b as EditBody, d as openapi, f as queryObject, g as VERSION, h as SYNC, i as canonicalWatchers, j as MessagesQuery, k as LinkedQuery, l as METHODS, m as readJson, n as syncTarget, o as compileWatcher, p as readCapped, q as TypingBody, r as withEmailMentions, t as mentionsEmails, u as createRouter, v as CreateChannelBody, w as InboxAckBody, x as EventsQuery, y as DeleteBody, z as SourceReadQuery } from "./targets-C1mT3M1N.mjs";
4
- import { a as waitUntil, r as runMiddleware, s as derivedId, t as DroppedError, u as sha256 } from "./middleware-CPqAuRtp.mjs";
5
- import { a as canText, c as compileAccess, d as parsePattern, r as PERMISSIONS, u as parseCan } from "./access-CVkjSfxj.mjs";
6
- import { S as verifiesTokens, T as explainGrants, a as VERCEL_ISSUER, d as fromTokens, f as grantIssuers, p as hostPrincipal, u as createAuthority, x as verifiedIssuers, y as tokenHash } from "./auth-B3bBYOqf.mjs";
7
- import { i as resolveActor, r as claimsOf, t as KNOWN_AGENTS } from "./actors-kfMejhaw.mjs";
1
+ import { _ as IMPORT_BYTES_MAX, a as forbidden, b as mediaType, c as toErrorResponse, d as createBoardClient, f as duration, h as ATTACHMENT_BYTES_MAX, l as unauthorized, n as RejectedError, o as json, p as formatProfileHeader, r as badRequest, s as notFound, t as HttpError, u as BoardError, v as fileName } from "./errors-DcQf5WeM.mjs";
2
+ import { h as RemoteWatcherId } from "./schemas-DAzSsgWk.mjs";
3
+ import { f as schemaId, n as blocksIn, r as findBlocks } from "./blocks-CVoBC7ur.mjs";
4
+ import { A as MessagesQuery, B as SyncBody, C as InboxAckBody, D as LabelBody, E as InboxQuery, F as ScheduleBody, G as ThreadsQuery, H as SyncFindQuery, I as SchedulesQuery, J as UploadStartBody, K as TypingBody, L as SchemaBody, M as ReactBody, N as Ref, O as LinkedQuery, P as RegisterBody, R as SourceJoinBody, S as GrantBody, T as InboxPushBody, U as SyncImportBody, V as SyncCopiesQuery, W as SyncReceiptBody, Y as routes, _ as CreateChannelBody, a as compileWatcher, b as EventsQuery, c as METHODS, d as queryObject, f as readCapped, g as AckBody, h as VERSION, i as runMatch, j as PostBody, k as MatchesQuery, l as createRouter, m as SYNC, n as syncTarget, p as readJson, q as UpdateGrantBody, r as canonicalWatchers, t as SYNC_ACTOR, u as openapi, v as DeleteBody, w as InboxNextQuery, x as ExplainQuery, y as EditBody, z as SourceReadQuery } from "./origin-B3m2lnZC.mjs";
5
+ import { _ as sha256, a as waitUntil, c as platformProfile, d as userIdOf, m as derivedId, o as actorParts, r as runMiddleware, s as importedHandle, t as DroppedError, u as underPrincipal } from "./middleware-DHdrxmoc.mjs";
6
+ import { a as canText, c as compileAccess, d as parsePattern, n as InvalidCan, r as PERMISSIONS, u as parseCan } from "./access-C5HaO42b.mjs";
7
+ import { C as explainGrants, b as verifiesTokens, d as grantIssuers, f as hostPrincipal, i as VERCEL_ISSUER, l as createAuthority, t as DEFAULT_CAN$1, u as fromTokens, y as verifiedIssuers } from "./auth-DAlYi6TN.mjs";
8
+ import { a as resolveActor, o as viaOf, r as claimsOf, t as KNOWN_AGENTS } from "./actors-nrOf7Y7z.mjs";
9
+ import { t as checkValue } from "./data-values-C-Cq80hz.mjs";
8
10
  //#region src/server/registrant.ts
9
11
  /** Registering again this soon after the same registration only repeats it. */
10
12
  const REGISTER_EVERY_MS = 1e4;
@@ -49,10 +51,15 @@ function registrant(options) {
49
51
  const bound = options.binding;
50
52
  let last = null;
51
53
  let registering = null;
52
- /** Registers this board's watchers with the other board, as itself, replacing its last registration. */
53
- async function register(here) {
54
+ /**
55
+ * Registers this board's watchers with the other board, as itself, replacing its last registration. `fresh`
56
+ * registers again even so soon after the same one: the other board said something changed since (another
57
+ * deployment took a sync key), and only a new answer says what.
58
+ */
59
+ async function register(here, fresh = false) {
54
60
  const current = await options.hash();
55
- if (last && last.url === here && last.result.hash === current && Date.now() - last.at < REGISTER_EVERY_MS) return last.result;
61
+ if (!fresh && last && last.url === here && last.result.hash === current && Date.now() - last.at < REGISTER_EVERY_MS) return last.result;
62
+ if (fresh && registering) await registering.catch(() => {});
56
63
  registering ??= options.wakeAt(here).then((where) => registry.register(where)).then((result) => {
57
64
  last = {
58
65
  url: here,
@@ -180,8 +187,8 @@ function registrant(options) {
180
187
  return json(registration);
181
188
  }
182
189
  }],
183
- /** Registers this board's watchers with the other board now, as `POST /watchers` does. */
184
- registerNow: () => register(wakeable(bound().url())),
190
+ /** Registers this board's watchers with the other board now, as `POST /watchers` does, and with `fresh`, even if it just did. */
191
+ registerNow: (fresh = false) => register(wakeable(bound().url()), fresh),
185
192
  /** Stops pulling, for a board that pulls on its own. */
186
193
  close: () => {
187
194
  polling?.abort();
@@ -194,7 +201,7 @@ function registrant(options) {
194
201
  /** A pull with nothing to hand out holds this long: the same long-poll `vb tail` holds. */
195
202
  const WAIT_S = 25;
196
203
  /** A run that throws waits this long, doubling to `RETRY_MAX_MS`, as on a local board. */
197
- const RETRY_MS = 1e3;
204
+ const RETRY_MS$1 = 1e3;
198
205
  const RETRY_MAX_MS = 3e4;
199
206
  /** A feed that fails is read again after this long, doubling to a minute. */
200
207
  const READ_AGAIN_MS = 1e3;
@@ -241,7 +248,7 @@ function tailWatchers(options) {
241
248
  }
242
249
  after = page.cursor;
243
250
  for (const event of page.events) {
244
- if (event.actor?.id === own) continue;
251
+ if (event.actor?.id === own && !(event.type === "message.posted" && event.message?.schedule)) continue;
245
252
  const thread = event.message?.thread ?? "";
246
253
  const match = {
247
254
  id: `${boot}:${matched++}`,
@@ -260,7 +267,7 @@ function tailWatchers(options) {
260
267
  }
261
268
  async function attempts(id, match, signal) {
262
269
  const trigger = `watch:${id}:${match.id}`;
263
- for (let attempt = 1, wait = RETRY_MS; !signal.aborted; attempt++, wait = Math.min(wait * 2, RETRY_MAX_MS)) try {
270
+ for (let attempt = 1, wait = RETRY_MS$1; !signal.aborted; attempt++, wait = Math.min(wait * 2, RETRY_MAX_MS)) try {
264
271
  await runMatch({
265
272
  watcher: {
266
273
  id,
@@ -299,9 +306,251 @@ const sleep = (ms, signal) => new Promise((resolve) => {
299
306
  signal.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
300
307
  });
301
308
  //#endregion
309
+ //#region src/server/sandbox.ts
310
+ /** Outside Node there's no deployment credential to find: a sandbox's policy needs the one it's given. */
311
+ const withoutToken = (url) => {
312
+ throw new HttpError(400, "no_token", `There's no credential here to hand a sandbox for ${url}: pass one, sandboxPolicy({ token }).`, { origin: "handle" });
313
+ };
314
+ /**
315
+ * `x-board-can` for `can`, read here as the board reads it, so a bad one fails before the sandbox
316
+ * does: any `Can` (`'all'`, a list for every channel, a map from pattern to grant, a grant's `'none'`
317
+ * included), or a header's own text (`dev/=read,post`).
318
+ */
319
+ function canHeader(can) {
320
+ if (typeof can === "string" && can !== "all") {
321
+ parseCan(can);
322
+ return can;
323
+ }
324
+ const given = can === void 0 ? DEFAULT_CAN$1 : can === "all" || Array.isArray(can) ? can : Object.fromEntries(Object.entries(can).map(([pattern, grant]) => [pattern, grant === "none" ? [] : grant]));
325
+ return canText(compileAccess(given));
326
+ }
327
+ /**
328
+ * Routes under a board that the policy never adds the credential to: what hands out what outreaches
329
+ * the policy (a grant, a watcher's registration, sync's records and a platform's events), and what a
330
+ * platform or the board's own deployments call (webhooks, wake-ups), where the credential could speak
331
+ * for them.
332
+ */
333
+ const WITHHELD = [
334
+ "grants",
335
+ "watchers",
336
+ "wake",
337
+ "webhooks",
338
+ "sync",
339
+ "inbox",
340
+ "sources"
341
+ ];
342
+ const escaped = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
343
+ /** `value` in any case, as a router that ignores case reads it: a regular expression without flags, as RE2 and JavaScript both take it. */
344
+ const caseless = (value) => [...value].map((char) => /[a-z]/i.test(char) ? `[${char.toLowerCase()}${char.toUpperCase()}]` : escaped(char)).join("");
345
+ /** A path segment, percent-encoded as clients write them; the first rule refuses a dot segment and an encoded slash or dot. */
346
+ const SEGMENT = "(?:[A-Za-z0-9_.@~:+=,!$&'*-]|%[0-9A-Fa-f]{2})+";
347
+ /**
348
+ * The protocol's routes a sandbox reaches: every route but those under a withheld segment. Each is
349
+ * named whole, because a board mounted without a `basePath` matches a route as the end of a path, and
350
+ * `/api/board/x/grants` would be its `/grants` under `/api/board/x`.
351
+ */
352
+ const PROTOCOL_ROUTES = Object.values(routes).filter(({ path }) => !WITHHELD.includes(path.split("/").filter(Boolean)[0] ?? "")).map(({ method, path }) => ({
353
+ method,
354
+ path: path === "/" ? "" : path
355
+ }));
356
+ /** `routes`' rules: one a method, its paths' shapes in one expression after `prefix`. */
357
+ function routeRules(prefix, routes, scoped, transform) {
358
+ const byMethod = /* @__PURE__ */ new Map();
359
+ for (const { method, path } of routes) {
360
+ const shape = path.split("/").filter(Boolean).map((part) => part.startsWith(":") ? `/${SEGMENT}` : `/${escaped(part)}`).join("");
361
+ byMethod.set(method, [...byMethod.get(method) ?? [], shape]);
362
+ }
363
+ return [...byMethod].map(([method, shapes]) => ({
364
+ match: scoped({
365
+ method: [method],
366
+ path: { regex: `^${prefix}(?:${shapes.join("|")})/?$` }
367
+ }),
368
+ transform
369
+ }));
370
+ }
371
+ const refused = (why) => ({ response: {
372
+ statusCode: 403,
373
+ body: JSON.stringify({ error: {
374
+ code: "forbidden",
375
+ message: why
376
+ } }),
377
+ contentType: "application/json"
378
+ } });
379
+ /**
380
+ * The policy that hands the board `reach` names to a sandbox: its host, and on it only the board's
381
+ * own routes, under its URL's path and with its query (`teamId`), each request carrying `reach`'s
382
+ * headers. Anything else on the host is refused there; any other host, the sandbox doesn't reach.
383
+ */
384
+ function boardPolicy(reach) {
385
+ const url = new URL(reach.url);
386
+ const prefix = escaped(url.pathname.replace(/\/+$/, ""));
387
+ const query = [...url.searchParams].map(([key, value]) => ({
388
+ key: { exact: key },
389
+ value: { exact: value }
390
+ }));
391
+ const scoped = (match) => query.length > 0 ? {
392
+ ...match,
393
+ queryString: query
394
+ } : match;
395
+ const transform = [{ headers: { ...reach.headers } }];
396
+ return { allow: { [url.host]: [
397
+ {
398
+ match: { path: { regex: "(?:^|/)\\.\\.?(?:/|$)|%2[eEfF]|%5[cC]|\\\\" } },
399
+ ...refused("not a board route")
400
+ },
401
+ {
402
+ match: { queryString: [{ key: { regex: `^${caseless("x-vercel-set-bypass-cookie")}$` } }] },
403
+ ...refused("not a board route")
404
+ },
405
+ {
406
+ match: { headers: [{ key: { exact: "x-vercel-set-bypass-cookie" } }] },
407
+ ...refused("not a board route")
408
+ },
409
+ ...routeRules(prefix, reach.routes, scoped, transform),
410
+ ...(reach.reads ?? []).map((path) => ({
411
+ match: scoped({
412
+ path: { exact: path },
413
+ method: ["GET"]
414
+ }),
415
+ transform
416
+ })),
417
+ {
418
+ match: { path: { regex: `^${prefix}/(?:${WITHHELD.map(caseless).join("|")})(?:/|$)` } },
419
+ ...refused("not a route this sandbox's policy hands it")
420
+ },
421
+ refused("not this board's")
422
+ ] } };
423
+ }
424
+ //#endregion
302
425
  //#region src/server/backend-vercel.ts
303
426
  const PROFILE = /^[A-Za-z][A-Za-z0-9-]{0,31}$/;
304
- const SESSION = /^[A-Za-z0-9_.:-]{1,128}$/;
427
+ /**
428
+ * What `vb` on this board calls in Vercel's API for what a sandboxed agent does, by method and path
429
+ * under `/boards/<id>`: reading, posting and replying, editing and deleting its own, reacting and
430
+ * labeling, files, schedules, and finding a platform link's message. A sandbox's policy hands it these
431
+ * and nothing else under the board: not the board itself (`PATCH`, `DELETE`), its members, its
432
+ * grants, watchers, or sync's records, nor a route the API adds later.
433
+ */
434
+ const SANDBOX_ROUTES = [
435
+ {
436
+ method: "GET",
437
+ path: ""
438
+ },
439
+ {
440
+ method: "GET",
441
+ path: "/me"
442
+ },
443
+ {
444
+ method: "GET",
445
+ path: "/channels"
446
+ },
447
+ {
448
+ method: "POST",
449
+ path: "/channels"
450
+ },
451
+ {
452
+ method: "GET",
453
+ path: "/actors"
454
+ },
455
+ {
456
+ method: "GET",
457
+ path: "/messages"
458
+ },
459
+ {
460
+ method: "GET",
461
+ path: "/messages/:id"
462
+ },
463
+ {
464
+ method: "GET",
465
+ path: "/messages/:id/synced"
466
+ },
467
+ {
468
+ method: "GET",
469
+ path: "/changes"
470
+ },
471
+ {
472
+ method: "GET",
473
+ path: "/threads"
474
+ },
475
+ {
476
+ method: "POST",
477
+ path: "/threads"
478
+ },
479
+ {
480
+ method: "GET",
481
+ path: "/threads/:thread/messages"
482
+ },
483
+ {
484
+ method: "POST",
485
+ path: "/threads/:thread/messages"
486
+ },
487
+ {
488
+ method: "PATCH",
489
+ path: "/threads/:thread/messages/:n"
490
+ },
491
+ {
492
+ method: "POST",
493
+ path: "/threads/:thread/messages/:n/delete"
494
+ },
495
+ {
496
+ method: "GET",
497
+ path: "/threads/:thread/messages/:n/reactions"
498
+ },
499
+ {
500
+ method: "POST",
501
+ path: "/threads/:thread/messages/:n/reactions"
502
+ },
503
+ {
504
+ method: "POST",
505
+ path: "/threads/:thread/messages/:n/labels"
506
+ },
507
+ {
508
+ method: "GET",
509
+ path: "/posts/:id"
510
+ },
511
+ {
512
+ method: "POST",
513
+ path: "/attachments"
514
+ },
515
+ {
516
+ method: "GET",
517
+ path: "/attachments/:id"
518
+ },
519
+ {
520
+ method: "POST",
521
+ path: "/attachments/:id/complete"
522
+ },
523
+ {
524
+ method: "GET",
525
+ path: "/schedules"
526
+ },
527
+ {
528
+ method: "POST",
529
+ path: "/schedules"
530
+ },
531
+ {
532
+ method: "POST",
533
+ path: "/schedules/:id/cancel"
534
+ },
535
+ {
536
+ method: "GET",
537
+ path: "/sync/linked"
538
+ }
539
+ ];
540
+ /**
541
+ * Who a request to Vercel's API writes as, as the API reads it today: the profile's name alone in
542
+ * `x-board-profile`, and its avatar in `x-board-avatar`, which board's protocol refuses for the
543
+ * avatar parameter of `x-board-profile` (`formatProfileHeader`). Every request and sandbox policy
544
+ * for the API gets its profile from here, so this is the one place that changes once the API reads
545
+ * the profile header as the protocol has it.
546
+ */
547
+ function apiProfileHeaders(profile) {
548
+ if (!profile) return {};
549
+ return {
550
+ "x-board-profile": profile.name,
551
+ ...profile.avatar?.startsWith("https://") ? { "x-board-avatar": profile.avatar } : {}
552
+ };
553
+ }
305
554
  const CLIENT_ID = /^[A-Za-z0-9_.:-]{1,128}$/;
306
555
  const MESSAGE_ID = /^msg_([0-9a-f-]{36})_([1-9]\d*)$/;
307
556
  /** 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. */
@@ -393,6 +642,25 @@ function expiryOf(at) {
393
642
  /** What a caller board() verified gets: board() serves no requests for a board on Vercel's, so it never sends one. */
394
643
  const servesNone = () => new HttpError(404, "not_found", "this board uses Vercel's, and answers only wake-ups and webhooks");
395
644
  const apiKind = (kind) => kind === "app" ? "workflow" : kind;
645
+ /** How many more times a request goes out after the API puts it off. */
646
+ const RETRIES = 4;
647
+ /** The first wait before sending again, doubling each time. */
648
+ const RETRY_MS = 1e3;
649
+ /**
650
+ * How long to wait before sending a put-off request again: a second, doubling each time, with up to
651
+ * as long again added at random so callers the API put off together don't come back together, and
652
+ * never past what `Retry-After` asks. The API's 429s ask for a whole minute while its limit refills
653
+ * all the time, so that's a ceiling, not the wait.
654
+ */
655
+ function retryWait(attempt, retryAfter) {
656
+ const asked = retryAfter !== null && /^\d+$/.test(retryAfter) && Number(retryAfter) > 0 ? Number(retryAfter) * 1e3 : Infinity;
657
+ return Math.min(asked, RETRY_MS * 2 ** attempt * (1 + Math.random()));
658
+ }
659
+ /** `ms` passing, or `signal` stopping it first. */
660
+ const pause = (ms, signal) => ms <= 0 || signal?.aborted ? Promise.resolve() : new Promise((resolve) => {
661
+ const timer = setTimeout(resolve, ms);
662
+ signal?.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
663
+ });
396
664
  /** A UUIDv7, which the API takes as an operation ID. */
397
665
  function operationId() {
398
666
  const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
@@ -409,11 +677,16 @@ const grantFrom = (grant) => ({
409
677
  ...grant,
410
678
  at: expiryOf(grant.at)
411
679
  });
412
- /** A token as the API answers it, its times in milliseconds, as the protocol has them. */
413
- const tokenFrom = (token) => ({
414
- ...token,
415
- at: expiryOf(token.at) ?? token.at,
416
- expiresAt: expiryOf(token.expiresAt) ?? token.expiresAt
680
+ /** A schema the API keeps, as the protocol shows it. */
681
+ const schemaFrom = (schema) => ({
682
+ id: schema.id,
683
+ name: schema.name,
684
+ version: schema.version,
685
+ description: schema.description ?? null,
686
+ schema: schema.schema,
687
+ builtIn: schema.builtIn,
688
+ by: schema.createdBy?.id ?? null,
689
+ at: schema.builtIn ? null : iso(schema.createdAt)
417
690
  });
418
691
  const idAt = (threadId, sequence) => `msg_${threadId.slice(4)}_${sequence}`;
419
692
  /** Where a message ID points: its thread and its place in it. Null for one that isn't a message's. */
@@ -431,38 +704,182 @@ function principalId(principal) {
431
704
  if (principal.type === "app") return `vercel:app:${principal.clientId}`;
432
705
  return `vercel:project:${principal.projectId}:${principal.environment}`;
433
706
  }
707
+ /** A principal from a board actor ID, `vercel:project:prj_1:preview+slack:user:U1` say, or null for one the API doesn't name. */
708
+ function principalFrom(actor) {
709
+ const id = actorParts(actor).principal;
710
+ const project = /^vercel:project:([^:]+):([^:]+)$/.exec(id);
711
+ if (project) return {
712
+ type: "project",
713
+ projectId: project[1],
714
+ environment: project[2]
715
+ };
716
+ if (id.startsWith("vercel:user:")) return {
717
+ type: "user",
718
+ userId: id.slice(12)
719
+ };
720
+ if (id.startsWith("vercel:app:")) return {
721
+ type: "app",
722
+ clientId: id.slice(11)
723
+ };
724
+ return null;
725
+ }
726
+ /**
727
+ * Who an actor with a profile acts through, as board shows it: a project by its name (`project`, as the
728
+ * actors list names it), or the one the API's view gives it, or its ID, in its environment; a person by
729
+ * their username, which the API puts before an agent's name in its handle (`julian/claude`); anyone
730
+ * else by a short form of their ID.
731
+ */
732
+ function viaFor(principal, view, project) {
733
+ const named = view?.via?.name ?? null;
734
+ if (principal.type === "project") return {
735
+ name: project ?? named ?? principal.projectId,
736
+ environment: view?.via?.environment ?? principal.environment
737
+ };
738
+ if (principal.type === "external") return {
739
+ name: named ?? principal.id,
740
+ environment: null
741
+ };
742
+ const slash = view?.handle.indexOf("/") ?? -1;
743
+ const username = principal.type === "user" && slash > 0 ? view.handle.slice(0, slash) : null;
744
+ return {
745
+ name: named ?? username ?? shortName(principal),
746
+ environment: null
747
+ };
748
+ }
749
+ /**
750
+ * A platform user's handle as a project's sync imported them, `support/malte-ubl`, at most 128
751
+ * characters as the API keeps it: as the API names them, or from an API that names them as their
752
+ * platform does, under their project's name.
753
+ */
754
+ const importedHandleOf = (handle, principal, view, userId, project) => handle.includes("/") ? underPrincipal(handle.slice(0, handle.indexOf("/")), handle.slice(handle.indexOf("/") + 1)) : importedHandle(viaFor(principal, view, project).name, handle, userId);
755
+ /**
756
+ * A deployment as board shows it: by its project's name (`project`) in every environment, and named
757
+ * with its environment outside production (`support (preview)`); or, where that isn't known, by its
758
+ * project's ID, and outside production with its environment (`prj_support@preview`).
759
+ */
760
+ function deploymentNamed(principal, project) {
761
+ const production = principal.environment === "production";
762
+ if (project === void 0) {
763
+ const id = production ? principal.projectId : `${principal.projectId}@${principal.environment}`;
764
+ return {
765
+ handle: id,
766
+ name: id
767
+ };
768
+ }
769
+ return {
770
+ handle: project,
771
+ name: production ? project : `${project} (${principal.environment})`
772
+ };
773
+ }
774
+ /**
775
+ * Projects' names by ID, from what the actors list says: a deployment's handle, which the API makes its project's
776
+ * name, then what comes before the `/` in one of its agents' (`support/sync`, its sync's), then the name the API gives
777
+ * a project on its users (their `via`). An API that names a deployment by its ID (`project:prj_…:production`,
778
+ * `project:prj_…:production/sync`) names its project only there. A platform user's handle names no project: an API
779
+ * may give the one they have on their platform, slash and all.
780
+ */
781
+ function projectNamesOf(views) {
782
+ const byHandle = /* @__PURE__ */ new Map();
783
+ const byProfile = /* @__PURE__ */ new Map();
784
+ const byVia = /* @__PURE__ */ new Map();
785
+ for (const [id, found] of views) {
786
+ const principal = principalFrom(id);
787
+ if (principal?.type !== "project") continue;
788
+ const { profile } = actorParts(id);
789
+ if (profile !== null && found.via?.name) byVia.set(principal.projectId, found.via.name);
790
+ if (found.handle.startsWith("project:")) continue;
791
+ const slash = found.handle.indexOf("/");
792
+ if (profile === null) byHandle.set(principal.projectId, found.handle);
793
+ else if (slash > 0 && platformProfile(profile) === null) byProfile.set(principal.projectId, found.handle.slice(0, slash));
794
+ }
795
+ return new Map([
796
+ ...byVia,
797
+ ...byProfile,
798
+ ...byHandle
799
+ ]);
800
+ }
801
+ /**
802
+ * The handle board shows an actor of the actors list by, with its project named as `names` says: a deployment by
803
+ * its project's (`www`, or by ID `prj_www@preview`), a platform user under it (`www/ada`), and anyone else as the
804
+ * API names them.
805
+ */
806
+ function shownHandle(id, view, names) {
807
+ const principal = principalFrom(id);
808
+ if (principal?.type !== "project") return view.handle;
809
+ const project = names.get(principal.projectId);
810
+ const { profile } = actorParts(id);
811
+ if (profile === null) return deploymentNamed(principal, project).handle;
812
+ const user = platformProfile(profile);
813
+ return user ? importedHandleOf(view.handle, principal, view, user.user, project) : view.handle;
814
+ }
815
+ /** Who goes by `handle` in a read of the actors list: as the API names them, or as board shows them. */
816
+ const goingBy = (views, names, handle) => [...views].filter(([id, view]) => view.handle.toLowerCase() === handle || shownHandle(id, view, names).toLowerCase() === handle).map(([id]) => id);
817
+ /** A short name for a person or an app the API doesn't name: the start of their ID. */
818
+ const shortName = (principal) => principal.type === "user" ? `user-${principal.userId.slice(0, 6).toLowerCase()}` : `app-${principal.clientId.slice(0, 6).toLowerCase()}`;
434
819
  const authorOf = (actor) => ({
435
820
  actor: actor.id,
436
821
  principal: principalId(actor.principal),
437
- profile: actor.profile?.name ?? null,
438
- session: actor.session ?? null
822
+ profile: actor.profile?.name ?? null
439
823
  });
440
824
  /** Who cancels a schedule when no one did: the API, once its creator can no longer post it, as a local board's scheduler. */
441
825
  const SCHEDULER = {
442
826
  actor: "board:schedule",
443
827
  principal: "board:schedule",
444
- profile: null,
445
- session: null
828
+ profile: null
446
829
  };
447
- /** The API names nobody, so an actor's handle is its profile, or a short form of its principal. */
448
- function actorView(actor) {
449
- const { principal } = actor;
830
+ /**
831
+ * An actor where the API doesn't name them: its handle is its profile, or a short form of its
832
+ * principal (a deployment by `project`, its project's name, where it's known), and one with a profile
833
+ * acts through its principal, as `view` names it if there's one.
834
+ */
835
+ function actorView(actor, view, project) {
836
+ const { principal, profile } = actor;
450
837
  if (principal.type === "external") return {
451
838
  id: actor.id,
452
839
  kind: "external",
453
840
  handle: principal.id.slice(principal.id.lastIndexOf(":") + 1),
454
841
  name: principal.id,
455
- avatar: null
842
+ avatar: null,
843
+ verified: true
844
+ };
845
+ if (profile?.platform) {
846
+ const { userId, platform, key } = profile.platform;
847
+ const handle = importedHandleOf(view?.handle ?? "", principal, view, userId, project);
848
+ return {
849
+ id: actor.id,
850
+ kind: "external",
851
+ handle,
852
+ name: profile.name,
853
+ avatar: null,
854
+ via: viaFor(principal, view, project),
855
+ platform: view?.platform ?? platform ?? key,
856
+ verified: true
857
+ };
858
+ }
859
+ if (profile) return {
860
+ id: actor.id,
861
+ kind: "agent",
862
+ handle: profile.name,
863
+ name: profile.name,
864
+ avatar: profile.avatar ?? null,
865
+ via: viaFor(principal, view, project),
866
+ verified: true
456
867
  };
457
- 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}`;
458
- const handle = actor.profile?.name ?? base;
459
- const kind = actor.profile ? "agent" : principal.type === "user" ? "person" : principal.type === "project" ? "deployment" : "workflow";
868
+ if (principal.type === "project") return {
869
+ id: actor.id,
870
+ kind: "deployment",
871
+ ...deploymentNamed(principal, project),
872
+ avatar: null,
873
+ verified: true
874
+ };
875
+ const handle = shortName(principal);
460
876
  return {
461
877
  id: actor.id,
462
- kind,
878
+ kind: principal.type === "user" ? "person" : "workflow",
463
879
  handle,
464
880
  name: handle,
465
- avatar: actor.profile?.avatar ?? null
881
+ avatar: null,
882
+ verified: true
466
883
  };
467
884
  }
468
885
  /** A message's labels just before a change, from what they are after it and what it changed. */
@@ -502,7 +919,11 @@ function createVercel(options, environment) {
502
919
  const given = binding?.team ?? options.team;
503
920
  return team ??= given ? Promise.resolve(given) : environment?.team() ?? Promise.resolve(null);
504
921
  };
505
- /** One request to the API, as `who`. Its errors are the API's own, with its status and code. */
922
+ /**
923
+ * One request to the API, as `who`. Its errors are the API's own, with its status and code. One the
924
+ * API puts off (429, or a 503) waits and goes again as it was, so a write keeps its operation ID
925
+ * and lands once.
926
+ */
506
927
  async function api(who, method, path, init = {}) {
507
928
  const url = new URL(`${origin}/v1/messageboard${path}`);
508
929
  const id = await teamId();
@@ -512,42 +933,46 @@ function createVercel(options, environment) {
512
933
  if (typeof value === "string") url.searchParams.set(name, value);
513
934
  else for (const one of value) url.searchParams.append(name, one);
514
935
  }
515
- const headers = { "content-type": "application/json" };
516
- if (who.profile) headers["x-board-profile"] = who.profile.name;
517
- if (who.profile?.avatar?.startsWith("https://")) headers["x-board-avatar"] = who.profile.avatar;
518
- if (who.session && SESSION.test(who.session)) headers["x-board-session"] = who.session;
519
- let response;
520
- try {
521
- response = await doFetch(url, {
522
- method,
523
- headers,
524
- redirect: "error",
525
- ...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {},
526
- ...init.signal ? { signal: init.signal } : {}
527
- });
528
- } catch (error) {
529
- if (error instanceof HttpError || error instanceof Error && error.name === "AbortError") throw error;
530
- throw new HttpError(502, "unreachable", `Vercel's API didn't answer: ${error instanceof Error ? error.message : String(error)}`);
936
+ const headers = {
937
+ "content-type": "application/json",
938
+ ...apiProfileHeaders(who.profile)
939
+ };
940
+ const repeatable = method !== "POST" && method !== "PATCH" || typeof init.body?.operationId === "string";
941
+ for (let attempt = 0;; attempt++) {
942
+ let response;
943
+ try {
944
+ response = await doFetch(url, {
945
+ method,
946
+ headers,
947
+ redirect: "error",
948
+ ...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {},
949
+ ...init.signal ? { signal: init.signal } : {}
950
+ });
951
+ } catch (error) {
952
+ if (error instanceof HttpError || error instanceof Error && error.name === "AbortError") throw error;
953
+ throw new HttpError(502, "unreachable", `Vercel's API didn't answer: ${error instanceof Error ? error.message : String(error)}`);
954
+ }
955
+ const text = await response.text();
956
+ let body;
957
+ try {
958
+ body = text ? JSON.parse(text) : void 0;
959
+ } catch {}
960
+ if (response.ok) return body;
961
+ if (attempt < RETRIES && !init.signal?.aborted && (response.status === 429 || response.status === 503 && repeatable)) {
962
+ await pause(retryWait(attempt, response.headers.get("retry-after")), init.signal);
963
+ init.signal?.throwIfAborted();
964
+ continue;
965
+ }
966
+ const error = body?.error;
967
+ throw new HttpError(response.status, error?.code ?? "remote_error", error?.message ?? `Vercel's API answered ${response.status}`);
531
968
  }
532
- const text = await response.text();
533
- let body;
534
- try {
535
- body = text ? JSON.parse(text) : void 0;
536
- } catch {}
537
- if (response.ok) return body;
538
- const error = body?.error;
539
- if (error?.code === "board_token_scope") throw new HttpError(403, "board_token_scope", "a board token reaches only its own board, by its ID.", {
540
- hint: "Name its board by URL or ID: BOARD_URL, --url, or vercel({ board }).",
541
- origin: "handle"
542
- });
543
- throw new HttpError(response.status, error?.code ?? "remote_error", error?.message ?? `Vercel's API answered ${response.status}`);
544
969
  }
545
970
  /** A request on sync's routes, whose refusals board()'s sync knows only by the board's codes. */
546
971
  async function syncApi(...args) {
547
972
  try {
548
973
  return await api(...args).catch(async (error) => {
549
974
  if (!(error instanceof HttpError && error.code === "sync_key_not_owned" && (binding?.sync.length ?? 0) > 0)) throw error;
550
- await runner.registerNow();
975
+ await runner.registerNow(true);
551
976
  return api(...args);
552
977
  });
553
978
  } catch (error) {
@@ -789,15 +1214,71 @@ function createVercel(options, environment) {
789
1214
  if (!found && await again.views.then(() => true, () => false)) unlisted.add(actor.id);
790
1215
  }
791
1216
  const kind = found && apiKind(found.kind);
792
- if (!found || !(kind === "person" || kind === "external" || kind === "agent" && actor.principal.type === "user")) return actorView(actor);
1217
+ const project = actor.principal.type === "project" ? await namedProject(who, actor.principal.projectId) : void 0;
1218
+ if (!found || !(kind === "person" || kind === "external" || kind === "agent" && actor.principal.type === "user")) return actorView(actor, found, project);
1219
+ const via = actor.profile && actor.principal.type !== "external" ? { via: viaFor(actor.principal, found, project) } : {};
1220
+ const platform = found.platform ?? actor.profile?.platform?.platform;
1221
+ const user = actor.profile?.platform;
1222
+ const handle = user && actor.principal.type !== "external" ? importedHandleOf(found.handle, actor.principal, found, user.userId, project) : found.handle;
793
1223
  return {
794
1224
  id: actor.id,
795
1225
  kind,
796
- handle: found.handle,
1226
+ handle,
797
1227
  name: found.name ?? found.handle,
798
- avatar: found.avatar ?? null
1228
+ avatar: found.avatar ?? null,
1229
+ ...via,
1230
+ ...platform ? { platform } : {},
1231
+ verified: true
799
1232
  };
800
1233
  }
1234
+ /** Projects' names by ID, as `projectNamesOf` reads them from a read of the actors list. */
1235
+ const namesRead = /* @__PURE__ */ new WeakMap();
1236
+ function namesIn(read) {
1237
+ let names = namesRead.get(read);
1238
+ if (!names) namesRead.set(read, names = read.views.then(projectNamesOf, () => /* @__PURE__ */ new Map()));
1239
+ return names;
1240
+ }
1241
+ /** What a fresh read of the actors still didn't name: it isn't read again for them until names are read anyway. */
1242
+ const unnamed = /* @__PURE__ */ new Set();
1243
+ /**
1244
+ * Projects' names by ID, as the actors list names them, read again at once when `wanted` (one or more projects, by
1245
+ * their IDs) isn't among them, as for someone new since the list was read.
1246
+ */
1247
+ async function projectNames(who, wanted) {
1248
+ const kept = actorNames && Date.now() - actorNames.at <= NAMES_FRESH_MS ? actorNames : null;
1249
+ let names = await namesIn(kept ?? readNames(who));
1250
+ if (!wanted || wanted.found(names) || !kept || unnamed.has(wanted.key)) return names;
1251
+ names = await namesIn(actorNames && actorNames !== kept ? actorNames : readNames(who));
1252
+ if (!wanted.found(names)) {
1253
+ if (unnamed.size >= 1e3) unnamed.clear();
1254
+ unnamed.add(wanted.key);
1255
+ }
1256
+ return names;
1257
+ }
1258
+ /** A project's name, as `projectNames` finds it: undefined where nothing names it. */
1259
+ const namedProject = async (who, project) => (await projectNames(who, {
1260
+ key: project,
1261
+ found: (names) => names.has(project)
1262
+ })).get(project);
1263
+ /** A project's name, or its ID. */
1264
+ const projectName = async (who, project) => await namedProject(who, project) ?? project;
1265
+ /** The project these credentials are, whose sync keys a caller names bare: null for a person's or an app's. */
1266
+ const ownProject = async (who) => {
1267
+ const { principal } = (await self(who)).actor;
1268
+ return principal.type === "project" ? principal.projectId : null;
1269
+ };
1270
+ /** The project whose sync imported a message or a change, as its author says: null for one that says none. */
1271
+ const importerOf = (actor) => actor.principal.type === "project" ? actor.principal.projectId : null;
1272
+ /**
1273
+ * The sync key a message or a change came through, as this caller names it: bare for its own project's, since a
1274
+ * project's keys are its own, and `<project>/<key>` for another's (`www/slack`), by the project's name, or its ID.
1275
+ */
1276
+ async function fromOf(who, from, by) {
1277
+ if (from === void 0) return null;
1278
+ const project = importerOf(by);
1279
+ if (project === null || project === await ownProject(who)) return from;
1280
+ return `${await projectName(who, project)}/${from}`;
1281
+ }
801
1282
  async function view(who, message, channel) {
802
1283
  const root = message.sequence === 1;
803
1284
  return {
@@ -809,11 +1290,10 @@ function createVercel(options, environment) {
809
1290
  thread: message.threadId,
810
1291
  labels: labelsOf(message),
811
1292
  reactions: message.deletedAt === void 0 ? await reactors(who, message) : {},
812
- mentions: [],
813
1293
  by: authorOf(message.createdBy),
814
1294
  noSync: message.noSync ?? false,
815
1295
  origin: originOf(message.origin),
816
- from: message.from ?? null,
1296
+ from: await fromOf(who, message.from, message.createdBy),
817
1297
  createdAt: iso(message.createdAt),
818
1298
  editedAt: message.editedAt === void 0 ? null : iso(message.editedAt),
819
1299
  deleted: message.deletedAt !== void 0,
@@ -831,7 +1311,8 @@ function createVercel(options, environment) {
831
1311
  ...message.schedule ? { schedule: {
832
1312
  id: message.schedule.id,
833
1313
  n: message.schedule.n
834
- } } : {}
1314
+ } } : {},
1315
+ blocks: (message.from ?? null) === null && message.deletedAt === void 0 ? blocksIn(message.text) : []
835
1316
  };
836
1317
  }
837
1318
  /**
@@ -843,8 +1324,7 @@ function createVercel(options, environment) {
843
1324
  const by = {
844
1325
  id: await actorOf(who),
845
1326
  principal: actor.principal,
846
- ...who.profile ? { profile: who.profile } : {},
847
- ...who.session ? { session: who.session } : {}
1327
+ ...who.profile ? { profile: who.profile } : {}
848
1328
  };
849
1329
  const attachments = (await Promise.all((input.attachments ?? []).map(async (id) => api(who, "GET", await onBoard(who, `/attachments/${encodeURIComponent(id)}`)).then(({ attachment }) => fileOf(attachment), () => null)))).filter((file) => file !== null);
850
1330
  return {
@@ -934,7 +1414,7 @@ function createVercel(options, environment) {
934
1414
  const named = /* @__PURE__ */ new Set([by]);
935
1415
  if (!by.startsWith("vercel:")) {
936
1416
  const handle = by.toLowerCase();
937
- const find = async (read) => [...await read.views].filter(([, view]) => view.handle.toLowerCase() === handle).map(([id]) => id);
1417
+ const find = async (read) => goingBy(await read.views, await namesIn(read), handle);
938
1418
  const kept = actorNames && Date.now() - actorNames.at <= NAMES_FRESH_MS ? actorNames : null;
939
1419
  let ids = await find(kept ?? readNames(who));
940
1420
  const missed = unhandled.get(handle);
@@ -945,17 +1425,39 @@ function createVercel(options, environment) {
945
1425
  }
946
1426
  for (const id of ids) named.add(id);
947
1427
  }
948
- return (actor) => named.has(actor.id) || named.has(principalId(actor.principal)) || actor.profile !== void 0 && named.has(actor.profile.name);
1428
+ return (actor) => named.has(actor.id) || named.has(principalId(actor.principal)) || actor.profile !== void 0 && !actor.profile.platform && named.has(actor.profile.name);
949
1429
  }
950
1430
  /**
951
- * Whether a message matches a read's filters. A label matches on the message or its thread's root:
952
- * `thread`'s labels, as `labeledBy` gives them when the read filters on labels.
1431
+ * Which messages `--source` names, as `fromOf` shows where they came from: `board`, a key bare for this caller's own
1432
+ * project's (or an import that names no project), or `<project>/<key>` for any project's, by its name or its ID.
953
1433
  */
954
- function matches(filters, message, thread, by) {
1434
+ async function sourceOf(who, from) {
1435
+ if (from === void 0) return void 0;
1436
+ if (from === "board") return (message) => message.from === void 0;
1437
+ const slash = from.indexOf("/");
1438
+ if (slash === -1) {
1439
+ const own = await ownProject(who);
1440
+ return (message) => message.from === from && [null, own].includes(importerOf(message.createdBy));
1441
+ }
1442
+ const [project, key] = [from.slice(0, slash), from.slice(slash + 1)];
1443
+ return async (message) => {
1444
+ const importer = importerOf(message.createdBy);
1445
+ return message.from === key && importer !== null && (importer === project || await namedProject(who, importer) === project);
1446
+ };
1447
+ }
1448
+ const narrowOf = async (who, filters) => ({
1449
+ by: await byOf(who, filters.by),
1450
+ source: await sourceOf(who, filters.from)
1451
+ });
1452
+ /**
1453
+ * Whether a message matches a read's filters, `narrow` as `narrowOf` gives them for it. A label matches on the
1454
+ * message or its thread's root: `thread`'s labels, as `labeledBy` gives them when the read filters on labels.
1455
+ */
1456
+ async function matches(filters, message, thread, narrow) {
955
1457
  if (filters.re !== void 0 && filters.re !== message.id && filters.re !== idAt(thread.id, 1)) return false;
956
- if (by && !by(message.createdBy)) return false;
1458
+ if (narrow.by && !narrow.by(message.createdBy)) return false;
957
1459
  if (filters.mentions !== void 0) return false;
958
- if (filters.from !== void 0 && (message.from ?? "board") !== filters.from) return false;
1460
+ if (filters.from !== void 0 && !await narrow.source?.(message)) return false;
959
1461
  if (filters.text !== void 0 && !message.text.toLowerCase().includes(filters.text.toLowerCase())) return false;
960
1462
  for (const [key, values] of filters.label ?? []) {
961
1463
  const on = (labels) => labels !== void 0 && Object.hasOwn(labels, key) && (values === null || values.includes(labels[key]));
@@ -1018,7 +1520,7 @@ function createVercel(options, environment) {
1018
1520
  });
1019
1521
  /** The actor `who` writes as: the credentials' principal, and its profile, as the API names it. */
1020
1522
  const actorOf = async (who) => `${principalId((await self(who)).actor.principal)}${who.profile ? `+${who.profile.name.toLowerCase()}` : ""}`;
1021
- /** Who a caller acts as there: its profile and session, beside this deployment's credentials. */
1523
+ /** Who a caller acts as there: its profile, beside this deployment's credentials. */
1022
1524
  function whoOf(caller) {
1023
1525
  if ("identity" in caller) throw servesNone();
1024
1526
  const named = (profile) => {
@@ -1032,23 +1534,9 @@ function createVercel(options, environment) {
1032
1534
  };
1033
1535
  if (caller.origin.via?.kind === "client") {
1034
1536
  const asked = "profile" in caller ? caller.profile : caller.self ?? void 0;
1035
- const found = environment?.profile() ?? {
1036
- profile: null,
1037
- session: null
1038
- };
1039
- if (asked === void 0) return {
1040
- profile: named(found.profile),
1041
- session: found.session
1042
- };
1043
- return {
1044
- profile: named(asked),
1045
- session: asked === null ? null : found.session
1046
- };
1537
+ return { profile: named(asked === void 0 ? environment?.profile() ?? null : asked) };
1047
1538
  }
1048
- return {
1049
- profile: named(caller.self ?? "client"),
1050
- session: null
1051
- };
1539
+ return { profile: named(caller.self ?? "client") };
1052
1540
  }
1053
1541
  /** A post's client ID, as the API takes one: its own when it fits, a hash of it when it doesn't. */
1054
1542
  const clientIdOf = async (id) => CLIENT_ID.test(id) ? id : `h.${(await sha256(id)).slice(0, 64)}`;
@@ -1085,7 +1573,7 @@ function createVercel(options, environment) {
1085
1573
  }))))).flat();
1086
1574
  }
1087
1575
  const feeds = await heads(who, listed);
1088
- const by = await byOf(who, filters.by);
1576
+ const narrow = await narrowOf(who, filters);
1089
1577
  let newest = 0;
1090
1578
  const messages = [];
1091
1579
  for (const { thread, channel } of threads) {
@@ -1093,7 +1581,7 @@ function createVercel(options, environment) {
1093
1581
  const labeled = labeledBy(thread, all.find((message) => message.sequence === 1));
1094
1582
  for (const message of all) {
1095
1583
  newest = Math.max(newest, message.createdAt);
1096
- if (matches(filters, message, labeled, by)) messages.push({
1584
+ if (await matches(filters, message, labeled, narrow)) messages.push({
1097
1585
  message,
1098
1586
  thread,
1099
1587
  channel
@@ -1144,7 +1632,7 @@ function createVercel(options, environment) {
1144
1632
  };
1145
1633
  }
1146
1634
  /** 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. */
1147
- async function eventOf(who, change, channel, cursor, filters, authors, given, threads = threadReader(who)) {
1635
+ async function eventOf(who, change, channel, cursor, filters, narrow, given, threads = threadReader(who)) {
1148
1636
  if (!change.messageId || !change.type.startsWith("message.")) return null;
1149
1637
  let found = given ?? await messageById(who, change.messageId).catch((error) => {
1150
1638
  if (error instanceof HttpError && error.status === 404) return null;
@@ -1154,10 +1642,10 @@ function createVercel(options, environment) {
1154
1642
  ...found,
1155
1643
  thread: found.message.sequence === 1 ? labeledBy(found.thread, found.message) : await threads(found.thread.id)
1156
1644
  };
1157
- if (!found || !matches(filters, found.message, found.thread, authors)) return null;
1645
+ if (!found || !await matches(filters, found.message, found.thread, narrow)) return null;
1158
1646
  const message = await view(who, found.message, channel);
1159
1647
  const by = authorOf(change.actor);
1160
- const from = change.from ?? null;
1648
+ const from = await fromOf(who, change.from, change.actor);
1161
1649
  const base = {
1162
1650
  id: message.id,
1163
1651
  thread: message.thread
@@ -1175,7 +1663,6 @@ function createVercel(options, environment) {
1175
1663
  thread: message.thread,
1176
1664
  labels: message.labels,
1177
1665
  noSync: message.noSync,
1178
- mentions: [],
1179
1666
  by,
1180
1667
  origin: message.origin,
1181
1668
  from: message.from,
@@ -1188,7 +1675,6 @@ function createVercel(options, environment) {
1188
1675
  payload = {
1189
1676
  ...base,
1190
1677
  text: message.text,
1191
- mentions: [],
1192
1678
  by,
1193
1679
  from
1194
1680
  };
@@ -1261,7 +1747,7 @@ function createVercel(options, environment) {
1261
1747
  events
1262
1748
  };
1263
1749
  }));
1264
- const by = await byOf(who, filters.by);
1750
+ const narrow = await narrowOf(who, filters);
1265
1751
  const threads = threadReader(who, signal);
1266
1752
  const running = { ...position.feeds };
1267
1753
  const merged = pages.flatMap((page) => page.events.map((event) => ({
@@ -1277,7 +1763,7 @@ function createVercel(options, environment) {
1277
1763
  const event = await eventOf(who, change, page.channel.name, cursorOf({
1278
1764
  t: change.createdAt,
1279
1765
  feeds: { ...running }
1280
- }), filters, by, void 0, threads);
1766
+ }), filters, narrow, void 0, threads);
1281
1767
  if (event) events.push(event);
1282
1768
  }
1283
1769
  const after = { ...position.feeds };
@@ -1293,11 +1779,6 @@ function createVercel(options, environment) {
1293
1779
  }
1294
1780
  };
1295
1781
  }
1296
- /** `ms` passing, or `signal` stopping it first. */
1297
- const pause = (ms, signal) => ms <= 0 || signal.aborted ? Promise.resolve() : new Promise((resolve) => {
1298
- const timer = setTimeout(resolve, ms);
1299
- signal.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
1300
- });
1301
1782
  /**
1302
1783
  * Until one of `listed`'s feeds has something after `position` (true), or it's `until` (false). The API's feed is
1303
1784
  * one channel's, and only it can wait for what comes next, so this waits on each at once and lets
@@ -1348,8 +1829,8 @@ function createVercel(options, environment) {
1348
1829
  const limit = query.limit ?? 50;
1349
1830
  const thread = threadReader(who, signal);
1350
1831
  const narrowed = filtered(query);
1351
- const by = narrowed ? await byOf(who, query.by) : void 0;
1352
- const keep = async (message) => !narrowed || matches(query, message, query.label?.length ? await thread(message.threadId) : { id: message.threadId }, by);
1832
+ const narrow = narrowed ? await narrowOf(who, query) : {};
1833
+ const keep = async (message) => !narrowed || await matches(query, message, query.label?.length ? await thread(message.threadId) : { id: message.threadId }, narrow);
1353
1834
  const kept = [];
1354
1835
  if (query.after === void 0) {
1355
1836
  const page = await api(who, "GET", path, {
@@ -1388,7 +1869,7 @@ function createVercel(options, environment) {
1388
1869
  async function channelEvents(who, channel, query, signal) {
1389
1870
  const path = await onBoard(who, "/changes");
1390
1871
  const thread = threadReader(who, signal);
1391
- const by = await byOf(who, query.by);
1872
+ const narrow = await narrowOf(who, query);
1392
1873
  const until = Date.now() + (query.wait ?? 0) * 1e3;
1393
1874
  let cursor = query.after;
1394
1875
  for (;;) {
@@ -1411,7 +1892,7 @@ function createVercel(options, environment) {
1411
1892
  thread: query.label?.length ? await thread(change.threadId) : { id: change.threadId }
1412
1893
  } : null;
1413
1894
  if (!found) continue;
1414
- const event = await eventOf(who, change, channel.name, change.cursor ?? page.cursor, query, by, found);
1895
+ const event = await eventOf(who, change, channel.name, change.cursor ?? page.cursor, query, narrow, found);
1415
1896
  if (event) events.push(event);
1416
1897
  }
1417
1898
  if (events.length > 0 || Date.now() >= until || signal.aborted) return {
@@ -1460,7 +1941,10 @@ function createVercel(options, environment) {
1460
1941
  async function authorsOf(who, by) {
1461
1942
  if (by === "me") return [await actorOf(who)];
1462
1943
  if (by.startsWith("vercel:")) return [by];
1463
- const named = (await all(who, await onBoard(who, "/actors"), "actors")).filter((actor) => actor.handle === by || actor.id.endsWith(`+${by.toLowerCase()}`)).map((actor) => actor.id);
1944
+ const listed = await all(who, await onBoard(who, "/actors"), "actors");
1945
+ const views = listed.map((actor) => [actor.id, actor]);
1946
+ const shown = new Set(goingBy(views, projectNamesOf(views), by.toLowerCase()));
1947
+ const named = listed.filter((actor) => shown.has(actor.id) || !by.includes(":") && actor.id.endsWith(`+${by.toLowerCase()}`)).map((actor) => actor.id);
1464
1948
  if (named.length === 0) throw new HttpError(400, "bad_watcher", `--by ${by}: nobody here goes by that yet: name them by their actor ID`);
1465
1949
  return named;
1466
1950
  }
@@ -1531,12 +2015,11 @@ function createVercel(options, environment) {
1531
2015
  ...found.branch ? { branch: found.branch } : {}
1532
2016
  } : { url: null };
1533
2017
  /**
1534
- * Vercel's API takes watchers only from a deployment's own credentials: never a person's, an app's,
1535
- * or a board token's, whoever made it. Anyone else's registration, pull, or ack is its 403
1536
- * `watchers_need_project`.
2018
+ * Vercel's API takes watchers only from a deployment's own credentials: never a person's or an
2019
+ * app's. Anyone else's registration, pull, or ack is its 403 `watchers_need_project`.
1537
2020
  */
1538
2021
  const notADeployment = () => new HttpError(403, "watchers_need_project", "Vercel's API takes watchers only from a deployment's own credentials.", {
1539
- hint: "Register them from the project's deployment, with no board token. Watchers in board()'s config run in this process instead.",
2022
+ hint: "Register them from the project's deployment. Watchers in board()'s config run in this process instead.",
1540
2023
  origin: "handle"
1541
2024
  });
1542
2025
  const needsProject = (error) => error instanceof HttpError && error.code === "watchers_need_project" ? notADeployment() : error;
@@ -1547,7 +2030,7 @@ function createVercel(options, environment) {
1547
2030
  throw needsProject(error);
1548
2031
  }
1549
2032
  }
1550
- async function registerAs(who, where, watch, sync, fromHere) {
2033
+ async function registerAs(who, where, watch, sync, fromHere, registered = async () => {}) {
1551
2034
  const specs = Object.fromEntries(Object.entries(watch).map(([id, spec]) => [id, { tail: spec.tail }]));
1552
2035
  const filters = Object.fromEntries(await Promise.all(Object.entries(specs).map(async ([id, spec]) => [id, await filterOf(who, id, spec, fromHere)])));
1553
2036
  const entries = sync.map(({ key, platform }) => ({
@@ -1565,6 +2048,7 @@ function createVercel(options, environment) {
1565
2048
  } catch (error) {
1566
2049
  throw needsProject(error);
1567
2050
  }
2051
+ await registered(made);
1568
2052
  return {
1569
2053
  owner: made.owner,
1570
2054
  ...whereOf(made),
@@ -1573,6 +2057,54 @@ function createVercel(options, environment) {
1573
2057
  hash: made.hash
1574
2058
  };
1575
2059
  }
2060
+ /** The sync keys this deployment holds, as its last registration said: null before one has. */
2061
+ let held = null;
2062
+ /** Who holds each of its sync's keys that it doesn't, as people read it: `production`, or `support (production)`. */
2063
+ const holders = /* @__PURE__ */ new Map();
2064
+ /**
2065
+ * What this deployment's registration says it holds: the keys in its `sync`. Vercel's API says who holds each of
2066
+ * the rest, another of its project's deployments (production takes a key from a preview), which is said once each.
2067
+ * An API from before each project had its own keys says none, and holds every key it lists.
2068
+ */
2069
+ async function holding(made) {
2070
+ held = new Set((made.sync ?? []).map((entry) => entry.key));
2071
+ const mine = principalFrom(made.owner);
2072
+ for (const { key, owner, environment } of made.elsewhere ?? []) {
2073
+ const holder = principalFrom(owner);
2074
+ let shown = owner;
2075
+ if (holder?.type === "project") {
2076
+ const where = environment ?? holder.environment;
2077
+ shown = mine?.type === "project" && mine.projectId === holder.projectId ? where : `${await projectName(deployment, holder.projectId)} (${where})`;
2078
+ }
2079
+ if (holders.get(key) !== shown) console.info(`[board] ${key} is synced by ${shown}`);
2080
+ holders.set(key, shown);
2081
+ }
2082
+ }
2083
+ /**
2084
+ * Whether this deployment holds its sync's key `key`, as its last registration said: another of its project's
2085
+ * deployments may. Before one has said, it registers as on its first use; until one can, it holds every key, and
2086
+ * the API decides.
2087
+ */
2088
+ async function holds(key) {
2089
+ if (!binding?.sync.some((entry) => entry.key === key)) return true;
2090
+ if (held === null && await isDeployment().catch(() => false)) await runner.start();
2091
+ return held === null || held.has(key);
2092
+ }
2093
+ /** A write through a key another deployment holds: its holder imports and delivers through it. */
2094
+ const notHeld = (key) => notFound(`${key} is synced by ${holders.get(key) ?? "another deployment of this project"}, not this deployment`, "not_synced_here");
2095
+ /**
2096
+ * A sync call through key `key`: `unheld` answers it here, asking the API nothing, once another deployment holds
2097
+ * it. One may have taken it since this one registered: the API refuses the call, and registering again says so.
2098
+ */
2099
+ async function throughKey(key, unheld, call) {
2100
+ if (!await holds(key)) return unheld();
2101
+ try {
2102
+ return await call();
2103
+ } catch (error) {
2104
+ if (error instanceof HttpError && error.status === 403 && !await holds(key)) return unheld();
2105
+ throw error;
2106
+ }
2107
+ }
1576
2108
  /** A match as vboard hands it out: its event as `vb tail --json` prints it, with its message as it is now. */
1577
2109
  async function matchOf(who, match, filters) {
1578
2110
  const found = await messageById(who, match.event.messageId).catch((error) => {
@@ -1581,7 +2113,7 @@ function createVercel(options, environment) {
1581
2113
  });
1582
2114
  const channel = found && await channelById(who, found.thread.channelId);
1583
2115
  if (!found || !channel) return null;
1584
- const event = match.event.type === "thread.synced" ? await syncedOf(who, match, found.message, channel.name) : await eventOf(who, match.event, channel.name, match.id, filters, void 0, found);
2116
+ const event = match.event.type === "thread.synced" ? await syncedOf(who, match, found.message, channel.name) : await eventOf(who, match.event, channel.name, match.id, filters, await narrowOf(who, filters), found);
1585
2117
  if (!event?.message) return null;
1586
2118
  const handed = match.watcher === "@sync" && event.type === "labels.changed" ? {
1587
2119
  ...event,
@@ -1599,10 +2131,13 @@ function createVercel(options, environment) {
1599
2131
  event: handed
1600
2132
  };
1601
2133
  }
1602
- /** A thread bound to a target, as the event that has the sync owning its key backfill a channel: about the thread's root. */
2134
+ /**
2135
+ * A thread bound to a target, as the event that has the sync owning its key backfill a channel: about the thread's
2136
+ * root. Another project's binding is that project's sync's, and one that names no project is this one's.
2137
+ */
1603
2138
  async function syncedOf(who, match, root, channel) {
1604
2139
  const { binding } = match.event;
1605
- if (!binding) return null;
2140
+ if (!binding || binding.projectId !== void 0 && binding.projectId !== await ownProject(who)) return null;
1606
2141
  const message = await view(who, root, channel);
1607
2142
  return boardEvent(who, match.event, match.id, "thread.synced", {
1608
2143
  thread: message.thread,
@@ -1639,10 +2174,7 @@ function createVercel(options, environment) {
1639
2174
  } });
1640
2175
  }
1641
2176
  /** This deployment's own: what its config's watchers run as. */
1642
- const deployment = {
1643
- profile: null,
1644
- session: null
1645
- };
2177
+ const deployment = { profile: null };
1646
2178
  /** This board's config's watchers, which run here when the API wakes it. */
1647
2179
  let tails = {};
1648
2180
  const bound = () => {
@@ -1652,14 +2184,7 @@ function createVercel(options, environment) {
1652
2184
  const runner = registrant({
1653
2185
  remote: "Vercel's API",
1654
2186
  registry: {
1655
- register: (where) => registerAs(deployment, where, tails, bound().sync, true).catch((error) => {
1656
- if (error instanceof HttpError && error.code === "watchers_need_project") {
1657
- refused = true;
1658
- runner.close();
1659
- runHere();
1660
- }
1661
- throw error;
1662
- }),
2187
+ register: (where) => registerAs(deployment, where, tails, bound().sync, true, holding),
1663
2188
  matches: ({ signal, ...query }) => pullAs(deployment, query, signal, tails),
1664
2189
  ack: (id, body) => ackAs(deployment, id, body)
1665
2190
  },
@@ -1673,19 +2198,11 @@ function createVercel(options, environment) {
1673
2198
  registerFor: async (caller, request) => json(await methods.register(caller, RegisterBody.parse(await request.json()), request.signal))
1674
2199
  });
1675
2200
  let deployed = null;
1676
- /** Whether Vercel's API refused to register this board's watchers: its credentials aren't a deployment's own. */
1677
- let refused = false;
1678
- /**
1679
- * Whether this board's own credentials are a deployment's own: a project's, and no board token. A
1680
- * board token you set says so; one in a `fetch` passed in says so when the API refuses it.
1681
- */
1682
- const isDeployment = async () => {
1683
- if (refused || !options.fetch && environment?.boardToken()) return false;
1684
- return (deployed ??= self(deployment).then((found) => found.actor.principal.type === "project")).catch((error) => {
1685
- deployed = null;
1686
- throw error;
1687
- });
1688
- };
2201
+ /** Whether this board's own credentials are a deployment's own: a project's. */
2202
+ const isDeployment = () => (deployed ??= self(deployment).then((found) => found.actor.principal.type === "project")).catch((error) => {
2203
+ deployed = null;
2204
+ throw error;
2205
+ });
1689
2206
  let here = null;
1690
2207
  let deployedElse = false;
1691
2208
  /** Anyone else's watchers run in this process, as tails: nothing wakes a person. */
@@ -1693,7 +2210,7 @@ function createVercel(options, environment) {
1693
2210
  if (here || deployedElse) return;
1694
2211
  if (deployedOnVercel()) {
1695
2212
  deployedElse = true;
1696
- console.error("[board] watchers on a deployment need its own OIDC token: with a board token or another Vercel token, none run here");
2213
+ console.error("[board] watchers on a deployment need its own OIDC token: with another Vercel token, none run here");
1697
2214
  return;
1698
2215
  }
1699
2216
  const { sync, run } = bound();
@@ -1707,10 +2224,7 @@ function createVercel(options, environment) {
1707
2224
  here = tailWatchers({
1708
2225
  watchers,
1709
2226
  events: (query, signal) => eventsAs(deployment, query, signal),
1710
- actorOf: (id) => actorOf({
1711
- profile: { name: id },
1712
- session: null
1713
- }),
2227
+ actorOf: (id) => actorOf({ profile: { name: id } }),
1714
2228
  run
1715
2229
  });
1716
2230
  here.start();
@@ -1749,11 +2263,6 @@ function createVercel(options, environment) {
1749
2263
  });
1750
2264
  /** An import as the API takes it: a channel by its ID, and a reply's `after` as its sequence in the thread. */
1751
2265
  async function importBody(who, body) {
1752
- if (body.op === "seen") return {
1753
- op: "seen",
1754
- operationId: operationId(),
1755
- author: platformUser(body.author)
1756
- };
1757
2266
  const base = {
1758
2267
  op: body.op,
1759
2268
  operationId: operationId(),
@@ -1761,7 +2270,6 @@ function createVercel(options, environment) {
1761
2270
  ...body.from !== void 0 ? { from: body.from } : {}
1762
2271
  };
1763
2272
  if (body.op === "post") {
1764
- if (body.attachments?.length) throw notSupported("files on imports");
1765
2273
  let after;
1766
2274
  if (body.after !== void 0) {
1767
2275
  const at = locate(body.after);
@@ -1778,6 +2286,7 @@ function createVercel(options, environment) {
1778
2286
  text: body.text,
1779
2287
  ...body.labels && Object.keys(body.labels).length ? { labels: body.labels } : {},
1780
2288
  ...body.noSync ? { noSync: true } : {},
2289
+ ...body.attachments?.length ? { attachments: body.attachments } : {},
1781
2290
  ...body.links?.length ? { links: body.links } : {},
1782
2291
  ...body.id !== void 0 ? { id: body.id } : {},
1783
2292
  ...after !== void 0 ? { after } : {}
@@ -1832,23 +2341,12 @@ function createVercel(options, environment) {
1832
2341
  });
1833
2342
  throw error;
1834
2343
  };
1835
- /** A mint Vercel's API won't make: only a deployment mints board tokens there, and a board token mints from itself. */
1836
- const mintRefused = (error) => {
1837
- if (error instanceof HttpError && error.code === "unsupported_principal") throw new HttpError(403, "unsupported_principal", "Vercel's board mints board tokens only for a deployment.", {
1838
- hint: "Mint it from a deployment, with its OIDC token, or from a board token.",
1839
- origin: "handle"
1840
- });
1841
- throw error;
1842
- };
1843
2344
  const methods = {
1844
2345
  ...Object.fromEntries(METHODS.map((method) => [method, async () => {
1845
2346
  throw notSupported(method === "register" || method === "watchers" || method === "matches" || method === "ack" ? "watchers" : method);
1846
2347
  }])),
1847
2348
  async discovery() {
1848
- const who = {
1849
- profile: null,
1850
- session: null
1851
- };
2349
+ const who = { profile: null };
1852
2350
  const team = await teamId();
1853
2351
  if (options.board) await api(who, "GET", await onBoard(who));
1854
2352
  const id = team?.startsWith("team_") ? team : (await self(who)).teamId;
@@ -1866,14 +2364,22 @@ function createVercel(options, environment) {
1866
2364
  };
1867
2365
  },
1868
2366
  async me(caller) {
1869
- const found = await api(whoOf(caller), "GET", "/me");
2367
+ const who = whoOf(caller);
2368
+ const found = await api(who, "GET", await onBoard(who, "/me"));
1870
2369
  const { view: named } = found;
1871
- const shown = named ? {
2370
+ const { principal } = found.actor;
2371
+ const project = principal.type === "project" ? (named ? projectNamesOf([[found.actor.id, named]]).get(principal.projectId) : void 0) ?? await namedProject(who, principal.projectId) : void 0;
2372
+ const shown = principal.type === "project" && !found.actor.profile ? {
2373
+ kind: "deployment",
2374
+ ...deploymentNamed(principal, project),
2375
+ avatar: named?.avatar ?? null
2376
+ } : named ? {
1872
2377
  kind: apiKind(named.kind),
1873
2378
  handle: named.handle,
1874
2379
  name: named.name ?? named.handle,
1875
2380
  avatar: named.avatar ?? null
1876
- } : actorView(found.actor);
2381
+ } : actorView(found.actor, void 0, project);
2382
+ const via = found.actor.profile && principal.type !== "external" ? { via: viaFor(principal, named, project) } : {};
1877
2383
  return {
1878
2384
  actor: found.actor.id,
1879
2385
  principal: principalId(found.actor.principal),
@@ -1882,7 +2388,7 @@ function createVercel(options, environment) {
1882
2388
  name: shown.name,
1883
2389
  avatar: shown.avatar,
1884
2390
  profile: found.actor.profile?.name ?? null,
1885
- session: found.actor.session ?? null,
2391
+ ...via,
1886
2392
  expiresAt: expiryOf(found.expiresAt),
1887
2393
  can: canOf(found.can)
1888
2394
  };
@@ -1905,14 +2411,27 @@ function createVercel(options, environment) {
1905
2411
  },
1906
2412
  async actors(caller, _input, signal) {
1907
2413
  const who = whoOf(caller);
2414
+ const views = await all(who, await onBoard(who, "/actors"), "actors", {}, signal);
2415
+ const names = projectNamesOf(views.map((view) => [view.id, view]));
1908
2416
  return {
1909
- actors: (await all(who, await onBoard(who, "/actors"), "actors", {}, signal)).map((actor) => ({
1910
- id: actor.id,
1911
- kind: apiKind(actor.kind),
1912
- handle: actor.handle,
1913
- name: actor.name ?? actor.handle,
1914
- avatar: actor.avatar ?? null
1915
- })),
2417
+ actors: views.map((actor) => {
2418
+ const { profile } = actorParts(actor.id);
2419
+ const owner = principalFrom(actor.id);
2420
+ const project = owner?.type === "project" ? names.get(owner.projectId) : void 0;
2421
+ const principal = profile === null ? null : owner;
2422
+ const user = platformProfile(profile);
2423
+ const deployment = profile === null && owner?.type === "project" ? deploymentNamed(owner, project) : null;
2424
+ return {
2425
+ id: actor.id,
2426
+ kind: apiKind(actor.kind),
2427
+ handle: deployment?.handle ?? (principal && user ? importedHandleOf(actor.handle, principal, actor, user.user, project) : actor.handle),
2428
+ name: deployment?.name ?? actor.name ?? actor.handle,
2429
+ avatar: actor.avatar ?? null,
2430
+ ...principal ? { via: viaFor(principal, actor, project) } : {},
2431
+ ...actor.platform ? { platform: actor.platform } : {},
2432
+ verified: true
2433
+ };
2434
+ }),
1916
2435
  cursor: cursorOf({
1917
2436
  t: Date.now(),
1918
2437
  feeds: {}
@@ -2031,7 +2550,6 @@ function createVercel(options, environment) {
2031
2550
  },
2032
2551
  async upload(caller, { data, name, type }) {
2033
2552
  const who = whoOf(caller);
2034
- if ("self" in caller && caller.self === "sync") throw new HttpError(501, "no_files", "Vercel's board takes no files from sync yet");
2035
2553
  if (data.byteLength === 0) throw new HttpError(400, "bad_request", "the file is empty");
2036
2554
  if (data.byteLength > 26214400) throw new HttpError(413, "too_large", `attachments are at most ${IMPORT_BYTES_MAX / 1024 / 1024} MB`);
2037
2555
  const bytes = new Uint8Array(data);
@@ -2262,32 +2780,33 @@ function createVercel(options, environment) {
2262
2780
  ...signal ? { signal } : {}
2263
2781
  });
2264
2782
  },
2265
- async tokens(caller, _input, signal) {
2266
- const who = whoOf(caller);
2267
- const { tokens } = await api(who, "GET", await onBoard(who, "/tokens"), signal ? { signal } : {});
2268
- return { tokens: tokens.map(tokenFrom) };
2783
+ async schemas(caller, _input, signal) {
2784
+ const schemas = (await all(whoOf(caller), "/schemas", "schemas", {}, signal)).map(schemaFrom);
2785
+ const order = (schema) => schema.builtIn ? 0 : 1;
2786
+ return { schemas: schemas.sort((a, b) => order(a) - order(b) || (a.builtIn ? 0 : a.name < b.name ? -1 : a.name > b.name ? 1 : a.version - b.version)) };
2269
2787
  },
2270
- async createToken(caller, input, signal) {
2788
+ async schema(caller, { id }, signal) {
2789
+ const { schema } = await api(whoOf(caller), "GET", `/schemas/${encodeURIComponent(id)}`, signal ? { signal } : {});
2790
+ return { schema: schemaFrom(schema) };
2791
+ },
2792
+ async createSchema(caller, input, signal) {
2271
2793
  const who = whoOf(caller);
2272
- const created = await api(who, "POST", await onBoard(who, "/tokens"), {
2794
+ const there = await api(who, "GET", `/schemas/${encodeURIComponent(schemaId(input.name, input.version))}`, signal ? { signal } : {}).then(() => true, (error) => {
2795
+ if (error instanceof HttpError && error.code === "schema_not_found") return false;
2796
+ throw error;
2797
+ });
2798
+ const { schema } = await api(who, "POST", "/schemas", {
2273
2799
  body: {
2274
2800
  operationId: operationId(),
2275
2801
  ...input
2276
2802
  },
2277
2803
  ...signal ? { signal } : {}
2278
- }).catch(mintRefused);
2804
+ });
2279
2805
  return {
2280
- ...created,
2281
- token: tokenFrom(created.token)
2806
+ schema: schemaFrom(schema),
2807
+ created: !there
2282
2808
  };
2283
2809
  },
2284
- async revokeToken(caller, { id }, signal) {
2285
- const who = whoOf(caller);
2286
- return api(who, "POST", await onBoard(who, `/tokens/${encodeURIComponent(id)}/revoke`), {
2287
- body: { operationId: operationId() },
2288
- ...signal ? { signal } : {}
2289
- });
2290
- },
2291
2810
  async schedule(caller, input, signal) {
2292
2811
  if (input.attachments?.length) throw notSupported("files on scheduled messages");
2293
2812
  const who = whoOf(caller);
@@ -2367,20 +2886,26 @@ function createVercel(options, environment) {
2367
2886
  },
2368
2887
  async syncImport(caller, body, signal) {
2369
2888
  const who = whoOf(caller);
2370
- return { message: (await syncApi(who, "POST", await onBoard(who, "/sync/imports"), {
2889
+ const key = body.from ?? body.author.id.split(":")[0];
2890
+ return { message: (await throughKey(key, () => {
2891
+ throw notHeld(key);
2892
+ }, async () => syncApi(who, "POST", await onBoard(who, "/sync/imports"), {
2371
2893
  body: await importBody(who, body),
2372
2894
  signal
2373
- }).catch((error) => {
2895
+ })).catch((error) => {
2374
2896
  if (error instanceof HttpError && error.code === "newer_message" && body.op === "post") throw new HttpError(409, "newer_message", `a message came after ${body.after}`);
2375
2897
  throw error;
2376
2898
  })).message };
2377
2899
  },
2378
2900
  async syncReceipt(caller, body, signal) {
2379
2901
  const who = whoOf(caller);
2380
- return syncApi(who, "POST", await onBoard(who, "/sync/receipts"), {
2902
+ const key = body.target.split(":")[0];
2903
+ return throughKey(key, () => {
2904
+ throw notHeld(key);
2905
+ }, async () => syncApi(who, "POST", await onBoard(who, "/sync/receipts"), {
2381
2906
  body,
2382
2907
  signal
2383
- });
2908
+ }));
2384
2909
  },
2385
2910
  async syncFind(caller, query, signal) {
2386
2911
  const who = whoOf(caller);
@@ -2412,10 +2937,28 @@ function createVercel(options, environment) {
2412
2937
  const who = whoOf(caller);
2413
2938
  if (!locate(id)) throw notFound(`message not found: ${id}`, "message_not_found");
2414
2939
  const { targets } = await syncApi(who, "GET", await onBoard(who, `/messages/${encodeURIComponent(id)}/synced`), { signal });
2415
- return { targets: await Promise.all(targets.map(async (target) => ({
2416
- ...target,
2417
- url: binding && target.thread !== null && target.message !== null ? await binding.linkOf(target.key, target.thread, target.message) : null
2418
- }))) };
2940
+ const own = await ownProject(who);
2941
+ const foreign = (projectId) => projectId !== void 0 && projectId !== own;
2942
+ const others = [...new Set(targets.flatMap(({ projectId }) => foreign(projectId) ? [projectId] : []))];
2943
+ const names = others.length ? await projectNames(who, {
2944
+ key: others.join(" "),
2945
+ found: (names) => others.every((id) => names.has(id))
2946
+ }) : /* @__PURE__ */ new Map();
2947
+ return { targets: await Promise.all(targets.map(async ({ projectId, ...target }) => {
2948
+ if (foreign(projectId)) {
2949
+ const key = `${names.get(projectId) ?? projectId}/${target.key}`;
2950
+ return {
2951
+ ...target,
2952
+ key,
2953
+ target: `${key}${target.target.slice(target.key.length)}`,
2954
+ url: null
2955
+ };
2956
+ }
2957
+ return {
2958
+ ...target,
2959
+ url: binding && target.thread !== null && target.message !== null ? await binding.linkOf(target.key, target.thread, target.message) : null
2960
+ };
2961
+ })) };
2419
2962
  },
2420
2963
  async linked(caller, { url }, signal) {
2421
2964
  const who = whoOf(caller);
@@ -2440,23 +2983,24 @@ function createVercel(options, environment) {
2440
2983
  },
2441
2984
  async inboxPush(caller, { key, events }, signal) {
2442
2985
  const who = whoOf(caller);
2443
- await syncApi(who, "POST", await inboxPath(who, key), {
2444
- body: { events: events.map(({ id, event, raw }) => ({
2445
- id,
2446
- thread: event.thread,
2447
- event,
2448
- ...raw !== void 0 ? { raw } : {}
2449
- })) },
2986
+ const body = { events: events.map(({ id, event, raw }) => ({
2987
+ id,
2988
+ thread: event.thread,
2989
+ event,
2990
+ ...raw !== void 0 ? { raw } : {}
2991
+ })) };
2992
+ await throughKey(key, () => null, async () => syncApi(who, "POST", await inboxPath(who, key), {
2993
+ body,
2450
2994
  signal
2451
- });
2995
+ }));
2452
2996
  return { ok: true };
2453
2997
  },
2454
2998
  async inboxNext(caller, { key, limit }, signal) {
2455
2999
  const who = whoOf(caller);
2456
- const { items } = await syncApi(who, "GET", await inboxPath(who, key, "/next"), {
3000
+ const { items } = await throughKey(key, () => ({ items: [] }), async () => syncApi(who, "GET", await inboxPath(who, key, "/next"), {
2457
3001
  query: { limit: limit?.toString() },
2458
3002
  signal
2459
- });
3003
+ }));
2460
3004
  return { items: items.map(({ raw, ...item }) => ({
2461
3005
  ...item,
2462
3006
  key,
@@ -2465,22 +3009,22 @@ function createVercel(options, environment) {
2465
3009
  },
2466
3010
  async inboxAck(caller, { key, id, lease, error }, signal) {
2467
3011
  const who = whoOf(caller);
2468
- await syncApi(who, "POST", await inboxPath(who, key, `/${encodeURIComponent(id)}/ack`), {
3012
+ await throughKey(key, () => null, async () => syncApi(who, "POST", await inboxPath(who, key, `/${encodeURIComponent(id)}/ack`), {
2469
3013
  body: {
2470
3014
  lease,
2471
3015
  ...error !== void 0 ? { error } : {}
2472
3016
  },
2473
3017
  signal
2474
- });
3018
+ }));
2475
3019
  return { ok: true };
2476
3020
  },
2477
3021
  async inbox(caller, { key, channel, limit }, signal) {
2478
3022
  const who = whoOf(caller);
2479
3023
  const wanted = Math.min(limit ?? 50, INBOX_LIST_MAX);
2480
- const { events } = await syncApi(who, "GET", await inboxPath(who, key), {
3024
+ const { events } = await throughKey(key, () => ({ events: [] }), async () => syncApi(who, "GET", await inboxPath(who, key), {
2481
3025
  query: { limit: String(channel === void 0 ? wanted : INBOX_LIST_MAX) },
2482
3026
  signal
2483
- });
3027
+ }));
2484
3028
  const entries = events.flatMap(({ id, createdAt, event, raw }) => event ? [{
2485
3029
  id,
2486
3030
  channel: typeof event.channel === "string" ? event.channel : "",
@@ -2528,7 +3072,30 @@ function createVercel(options, environment) {
2528
3072
  }])),
2529
3073
  routes,
2530
3074
  keeps: false,
3075
+ /**
3076
+ * A sandbox's way to this board in Vercel's API: its routes, by its ID and team, and `/me`, which a
3077
+ * handle on it asks, held to `can` by `x-board-can` as a board of its own would be. The API reads the
3078
+ * profile as `apiProfileHeaders` sends it.
3079
+ */
3080
+ async sandbox({ profile, can, token }) {
3081
+ if (profile.avatar !== void 0 && !profile.avatar.startsWith("https://")) throw new HttpError(400, "invalid_profile", `${profile.avatar} isn't an avatar Vercel's API takes: one is an https URL.`, { origin: "handle" });
3082
+ const who = { profile: null };
3083
+ const team = await teamId();
3084
+ const id = team?.startsWith("team_") ? team : (await self(who)).teamId;
3085
+ const url = `${origin}/v1/messageboard${await onBoard(who)}?teamId=${encodeURIComponent(id)}`;
3086
+ return {
3087
+ url,
3088
+ headers: {
3089
+ ...environment ? await environment.sandbox(url, token) : token === void 0 ? withoutToken(url) : { authorization: `Bearer ${token}` },
3090
+ ...apiProfileHeaders(profile),
3091
+ "x-board-can": can
3092
+ },
3093
+ routes: SANDBOX_ROUTES,
3094
+ reads: ["/v1/messageboard/me"]
3095
+ };
3096
+ },
2531
3097
  sendsSchedulesHere: false,
3098
+ syncedHere: holds,
2532
3099
  bind(next) {
2533
3100
  if (binding) throw new Error("vercel: this backend already serves a board: create one vercel() per board()");
2534
3101
  if (options.team && next.team && options.team !== next.team) throw new Error(`vercel: board() names team ${next.team}, and vercel() team ${options.team}: name the team once`);
@@ -2608,18 +3175,6 @@ function createPolicy(options, keeps, serving, trust = null) {
2608
3175
  const issuers = verifiedIssuers([], grantIssuers(await grants()));
2609
3176
  if (issuers.join("\n") !== context.issuers.join("\n")) context.issuers = issuers;
2610
3177
  }
2611
- /** Who a board token is: the principal that minted it, narrowed, until it's revoked or expires. */
2612
- async function tokenPrincipal(secret) {
2613
- if (!trust) throw unauthorized("this board issues no tokens: send a board token to the board that minted it");
2614
- const found = await trust.token(await tokenHash(secret));
2615
- if (!found || found.expiresAt.getTime() <= Date.now()) throw unauthorized("invalid token: revoked, expired, or not this board's");
2616
- return {
2617
- ...found.minter,
2618
- expiresAt: found.expiresAt,
2619
- token: found.id,
2620
- pinned: found.pinned
2621
- };
2622
- }
2623
3178
  /** Verified principals by credential, until they expire, so a stream's polls don't verify from scratch. */
2624
3179
  const verified = /* @__PURE__ */ new Map();
2625
3180
  /** And by request, for one with no credential (a session cookie), for as long as it's served. */
@@ -2641,7 +3196,7 @@ function createPolicy(options, keeps, serving, trust = null) {
2641
3196
  const principal = verify(request);
2642
3197
  perRequest.set(request, principal);
2643
3198
  if (key !== null) principal.then((found) => {
2644
- if (found.facts?.issuer === "host" || found.expiresAt === null || found.token !== void 0) return;
3199
+ if (found.facts?.issuer === "host" || found.expiresAt === null) return;
2645
3200
  if (verified.size >= 1e3) verified.delete(verified.keys().next().value);
2646
3201
  verified.set(key, {
2647
3202
  principal,
@@ -2651,7 +3206,6 @@ function createPolicy(options, keeps, serving, trust = null) {
2651
3206
  return principal;
2652
3207
  }
2653
3208
  async function verify(request) {
2654
- if (request.credential?.startsWith("board_")) return tokenPrincipal(request.credential);
2655
3209
  if (request.credential !== null) await learnIssuers(request.credential);
2656
3210
  const authenticate = await verifier();
2657
3211
  let result;
@@ -2718,13 +3272,12 @@ function createPolicy(options, keeps, serving, trust = null) {
2718
3272
  */
2719
3273
  async identify(request) {
2720
3274
  const found = await principalOf(request);
2721
- const claims = found.pinned ? pinnedClaims(found.pinned, request.claims) : request.claims;
2722
- const scope = found.scope === void 0 ? claims.scope ?? void 0 : claims.scope === null ? found.scope : canText(compileAccess(parseCan(found.scope)).narrow(parseCan(claims.scope)));
2723
- const principal = scope === void 0 ? found : {
3275
+ const { claims } = request;
3276
+ const principal = claims.scope === null ? found : {
2724
3277
  ...found,
2725
- scope
3278
+ scope: claims.scope
2726
3279
  };
2727
- const { author, actor } = resolveActor(principal, claims, request.audience);
3280
+ const { author, actor } = resolveActor(principal, claims);
2728
3281
  return {
2729
3282
  principal: {
2730
3283
  ...principal,
@@ -2735,26 +3288,13 @@ function createPolicy(options, keeps, serving, trust = null) {
2735
3288
  };
2736
3289
  },
2737
3290
  explain,
2738
- /** What a stored principal (a schedule's creator, a watcher's registrant) may do now: null once nothing, its board token's revoking included. */
3291
+ /** What a stored principal (a schedule's creator, a watcher's registrant) may do now: null once nothing, or once it was made with a board token. */
2739
3292
  async accessNow(principal, grants) {
2740
- if (principal.token !== void 0 && !await trust?.live(principal.token)) return null;
3293
+ if (principal.token !== void 0) return null;
2741
3294
  return authority.accessNow(principal, grants);
2742
3295
  }
2743
3296
  };
2744
3297
  }
2745
- /** A board token's pins, over what the request says: its profile and session win, and a person's name is the minter's. */
2746
- function pinnedClaims(pinned, claims) {
2747
- return {
2748
- ...claims,
2749
- ...pinned.profile !== null ? {
2750
- profile: pinned.profile,
2751
- avatar: pinned.avatar
2752
- } : {},
2753
- ...pinned.session !== null ? { session: pinned.session } : {},
2754
- handle: pinned.handle,
2755
- name: pinned.name
2756
- };
2757
- }
2758
3298
  /** A JWT's `iss`, read but not verified: which issuer's keys would check it. Null for anything else. */
2759
3299
  function issuerOf(credential) {
2760
3300
  const payload = credential.split(".")[1];
@@ -2805,7 +3345,7 @@ const STYLES = {
2805
3345
  mark: { glyph: "π" }
2806
3346
  }
2807
3347
  };
2808
- /** A built-in avatar for a detected agent; other names get their initial. */
3348
+ /** A known agent's mark, for a caller to pass as its avatar; other names get their initial. */
2809
3349
  function avatarSvg(name) {
2810
3350
  const style = STYLES[name] ?? {
2811
3351
  background: "#666666",
@@ -2823,10 +3363,6 @@ const CREATED = /* @__PURE__ */ new Set([
2823
3363
  "upload",
2824
3364
  "uploadFinish"
2825
3365
  ]);
2826
- /** An email, as `--mentions` names one: sync looks its platform user up. */
2827
- const EMAIL = /^[^\s@]+@[^\s@]+$/;
2828
- /** How long a filter's email lookup holds. */
2829
- const EMAIL_TTL_MS = 3e5;
2830
3366
  /** Shown inline only when a browser can't run it: everything else downloads. */
2831
3367
  const INLINE = /^(image\/(png|jpeg|gif|webp|avif)|video\/(mp4|webm)|text\/plain)$/;
2832
3368
  /**
@@ -2857,13 +3393,13 @@ async function inputOf(name, request, url, params) {
2857
3393
  case "actors":
2858
3394
  case "watchers":
2859
3395
  case "grants":
2860
- case "tokens": return {};
3396
+ case "schemas": return {};
2861
3397
  case "message":
2862
3398
  case "posted":
2863
3399
  case "synced":
2864
3400
  case "cancelSchedule":
2865
3401
  case "revokeGrant":
2866
- case "revokeToken":
3402
+ case "schema":
2867
3403
  case "attachment":
2868
3404
  case "uploadFinish": return { id };
2869
3405
  case "messages": return MessagesQuery.parse(queryObject(url));
@@ -2885,7 +3421,7 @@ async function inputOf(name, request, url, params) {
2885
3421
  ...UpdateGrantBody.parse(await body())
2886
3422
  };
2887
3423
  case "explain": return ExplainQuery.parse(queryObject(url));
2888
- case "createToken": return TokenBody.parse(await body());
3424
+ case "createSchema": return SchemaBody.parse(await body());
2889
3425
  case "register": return RegisterBody.parse(await body());
2890
3426
  case "edit": return {
2891
3427
  id,
@@ -2959,14 +3495,24 @@ async function inputOf(name, request, url, params) {
2959
3495
  case "linked": return LinkedQuery.parse(queryObject(url));
2960
3496
  }
2961
3497
  }
2962
- /** A platform user, as the middleware is told who's writing. */
2963
- const externalActor = (author) => ({
2964
- id: author.id,
2965
- kind: "external",
2966
- handle: author.handle,
2967
- name: author.name,
2968
- avatar: author.avatar
2969
- });
3498
+ /**
3499
+ * A platform user an import by `importer` is by, as the board records them: themselves for the
3500
+ * board's own sync on a board that keeps its log here, which checked them, and a profile of
3501
+ * anyone else's principal, whose word they are, under its name.
3502
+ */
3503
+ const externalActor = (author, importer) => {
3504
+ const own = importer.principal === SYNC_ACTOR;
3505
+ return {
3506
+ id: own ? author.id : `${importer.principal}+${author.id}`,
3507
+ kind: "external",
3508
+ handle: own ? author.handle : importedHandle(viaOf({
3509
+ id: importer.principal,
3510
+ handle: importer.actor.handle
3511
+ }).name, author.handle, userIdOf(author.id)),
3512
+ name: author.name,
3513
+ avatar: author.avatar
3514
+ };
3515
+ };
2970
3516
  /** A write's caller, as the middleware is told: where it came from. The middleware's own handle and sync's lookups skip it. */
2971
3517
  function sourceOf(caller) {
2972
3518
  const via = caller.origin.via;
@@ -3022,54 +3568,6 @@ async function createServe(context) {
3022
3568
  */
3023
3569
  const servesOnly = () => new HttpError(404, "not_found", `${ownUrl() ?? "this board"} answers ${backend.routes.length > 0 || engine ? "only wake-ups and webhooks" : "nothing itself"}`);
3024
3570
  /**
3025
- * `@[ada@vercel.com]`: an email a synced platform knows becomes that user's mention, and the
3026
- * board learns who they are; the rest stay plain text.
3027
- */
3028
- async function withEmails(text) {
3029
- return (await withEmailMentions(text, engine ? learnEmail : void 0)).text;
3030
- }
3031
- /**
3032
- * The synced platform's user with this email, whom the board learns: a post can mention only
3033
- * an actor it knows, and a platform mention of them resolves only once it does.
3034
- */
3035
- async function learnEmail(email) {
3036
- const actor = await engine.findByEmail(email);
3037
- if (actor) await backend.syncImport(engine.caller, {
3038
- op: "seen",
3039
- author: {
3040
- ...actor,
3041
- isBot: false
3042
- }
3043
- }, new AbortController().signal);
3044
- return actor;
3045
- }
3046
- /** Emails filters named, as sync found them, for a few minutes: `tail` and `wait` ask at every page. */
3047
- const mentioned = /* @__PURE__ */ new Map();
3048
- /**
3049
- * `--mentions ada@vercel.com`: the synced platform's user with that email, for a caller that may
3050
- * read somewhere. Anything else, and an email sync doesn't know, goes on as it came.
3051
- */
3052
- async function withMentioned(caller, query) {
3053
- const email = query.mentions?.toLowerCase();
3054
- if (!engine || email === void 0 || !EMAIL.test(email)) return query;
3055
- const access = accessOf(caller);
3056
- if (access !== null && !access.anywhere("read")) return query;
3057
- let found = mentioned.get(email);
3058
- if (!found || Date.now() - found.at > EMAIL_TTL_MS) {
3059
- if (mentioned.size >= 1e3) mentioned.clear();
3060
- found = {
3061
- at: Date.now(),
3062
- actor: learnEmail(email).catch(() => null)
3063
- };
3064
- mentioned.set(email, found);
3065
- }
3066
- const actor = await found.actor;
3067
- return actor ? {
3068
- ...query,
3069
- mentions: actor.id
3070
- } : query;
3071
- }
3072
- /**
3073
3571
  * A sync target as the board that syncs it resolves it. One for an entry this board doesn't
3074
3572
  * have goes on as it is, for the sync that does, unless this board syncs: then it's a mistake.
3075
3573
  */
@@ -3084,9 +3582,9 @@ async function createServe(context) {
3084
3582
  }
3085
3583
  /**
3086
3584
  * What a verified caller may do, as board()'s `access` said when it verified them: board() checks
3087
- * it before it does anything for them past calling the backend (a platform call, an email lookup,
3088
- * sync's own write, reading an upload, the middleware), so a caller it won't let in starts none of
3089
- * it. Null for this deployment's own code, which may do everything.
3585
+ * it before it does anything for them past calling the backend (a platform call, sync's own write,
3586
+ * reading an upload, the middleware), so a caller it won't let in starts none of it. Null for this
3587
+ * deployment's own code, which may do everything.
3090
3588
  */
3091
3589
  const accessOf = (caller) => "identity" in caller ? caller.identity.principal.access : null;
3092
3590
  /**
@@ -3135,6 +3633,47 @@ async function createServe(context) {
3135
3633
  }
3136
3634
  return found;
3137
3635
  }
3636
+ /** The schemas writes have named, as the backend answered them: a version never changes, so each is read once. */
3637
+ const definitions = /* @__PURE__ */ new Map();
3638
+ /**
3639
+ * Checks the blocks `text` carries before it's written, each against the schema its fence names:
3640
+ * a 400 for one that isn't a JSON object, names a schema the board doesn't have, or doesn't match
3641
+ * it. So what a message written on the board shows as its `blocks` always matches. The check is
3642
+ * board()'s, so it reads each schema as board() itself, whoever is writing: every caller's write
3643
+ * is held to the same definition, and gets the same answer.
3644
+ */
3645
+ async function checkBlocks(text) {
3646
+ if (!text.includes("json#")) return;
3647
+ for (const found of findBlocks(text)) {
3648
+ if (found.problem !== void 0) throw badRequest(found.problem, "invalid_block");
3649
+ let definition = definitions.get(found.id);
3650
+ if (!definition) {
3651
+ definition = backend.schema(OWN, { id: found.id }, new AbortController().signal).then(({ schema }) => schema.schema);
3652
+ definitions.set(found.id, definition);
3653
+ definition.catch(() => definitions.delete(found.id));
3654
+ }
3655
+ const schema = await definition.catch((error) => {
3656
+ if (error instanceof HttpError && error.status === 404) throw badRequest(`the ${found.id} block names a schema this board doesn't have`, "schema_not_found");
3657
+ throw error;
3658
+ });
3659
+ const problem = checkValue(schema, found.data);
3660
+ if (problem !== null) throw badRequest(`the ${found.id} block doesn't match its schema: ${problem}`, "invalid_block");
3661
+ }
3662
+ }
3663
+ /**
3664
+ * Checks a write's blocks, unless board() already knows its caller may not post where it lands:
3665
+ * then the backend's refusal is the answer, not what the text says. A message board() can't find
3666
+ * for the caller is still checked, since one written without reading is its author's to edit.
3667
+ */
3668
+ async function checkWrite(caller, text, where, signal) {
3669
+ if (!text.includes("json#")) return;
3670
+ const access = accessOf(caller);
3671
+ if (access !== null) {
3672
+ const channel = "channel" in where ? where.channel : (await lookup(caller, where.message, signal))?.channel;
3673
+ if (channel !== void 0 && !access.can("post", channel)) return;
3674
+ }
3675
+ await checkBlocks(text);
3676
+ }
3138
3677
  let middlewareBoard = null;
3139
3678
  /** Runs the middleware on a write, then `commit`s what it passed on: a `DroppedError` when it drops it. */
3140
3679
  const screen = (write, author, source, commit) => runMiddleware(middleware, {
@@ -3213,11 +3752,14 @@ async function createServe(context) {
3213
3752
  ...labels ? { labels } : {},
3214
3753
  ...noSync !== void 0 ? { noSync } : {},
3215
3754
  ...attachments ? { attachments } : {}
3216
- }, signal, (screened) => backend.schedule(caller, {
3217
- ...input,
3218
- text: screened.text,
3219
- ...screened.labels ? { labels: screened.labels } : {}
3220
- }, signal));
3755
+ }, signal, async (screened) => {
3756
+ if (screened.text !== text) await checkBlocks(screened.text);
3757
+ return backend.schedule(caller, {
3758
+ ...input,
3759
+ text: screened.text,
3760
+ ...screened.labels ? { labels: screened.labels } : {}
3761
+ }, signal);
3762
+ });
3221
3763
  }
3222
3764
  /**
3223
3765
  * The caller's own message, still there, where it may post: what an edit of it changes. One it
@@ -3288,7 +3830,12 @@ async function createServe(context) {
3288
3830
  * the platform. A retry of one that landed stands.
3289
3831
  */
3290
3832
  async function syncImport(caller, body, signal) {
3291
- const send = (patched) => backend.syncImport(caller, patched, signal);
3833
+ const written = (body.op === "post" || body.op === "edit") && body.from === null ? body.text : null;
3834
+ if (written !== null) await checkBlocks(written);
3835
+ const send = async (patched) => {
3836
+ if (written !== null && (patched.op === "post" || patched.op === "edit") && patched.text !== written) await checkBlocks(patched.text);
3837
+ return backend.syncImport(caller, patched, signal);
3838
+ };
3292
3839
  if (middleware.length === 0 || caller.origin.via?.kind === "middleware" || body.op !== "post" && body.op !== "edit") return send(body);
3293
3840
  const access = accessOf(caller);
3294
3841
  if (access && (!access.anywhere("sync") || "identity" in caller && caller.identity.principal.scope !== void 0)) return send(body);
@@ -3317,6 +3864,7 @@ async function createServe(context) {
3317
3864
  const source = await importSource(caller, body, null, signal);
3318
3865
  if (!source) return send(body);
3319
3866
  const attachments = await attachmentsOf(caller, body.attachments, signal);
3867
+ const author = externalActor(body.author, await whoIs(caller, signal));
3320
3868
  return dropped(async () => screen({
3321
3869
  kind: "post",
3322
3870
  channel,
@@ -3324,7 +3872,7 @@ async function createServe(context) {
3324
3872
  text: body.text,
3325
3873
  labels: body.labels ?? {},
3326
3874
  attachments
3327
- }, externalActor(body.author), source, async (write) => send({
3875
+ }, author, source, async (write) => send({
3328
3876
  ...body,
3329
3877
  text: write.text,
3330
3878
  labels: write.labels
@@ -3332,7 +3880,9 @@ async function createServe(context) {
3332
3880
  }
3333
3881
  if (body.origin === void 0 === (body.message === void 0)) return send(body);
3334
3882
  const found = await importTarget(caller, body, signal);
3335
- if (!found || found.deleted || access && !access.can("sync", found.channel) || body.message !== void 0 && found.by.principal !== body.author.id) return send(body);
3883
+ const author = externalActor(body.author, await whoIs(caller, signal));
3884
+ const own = found !== null && (found.by.actor === author.id || found.by.actor === body.author.id);
3885
+ if (!found || found.deleted || access && !access.can("sync", found.channel) || body.message !== void 0 && !own) return send(body);
3336
3886
  const source = await importSource(caller, body, found, signal);
3337
3887
  if (!source) return send(body);
3338
3888
  return dropped(async () => screen({
@@ -3341,7 +3891,7 @@ async function createServe(context) {
3341
3891
  channel: found.channel,
3342
3892
  re: found.re,
3343
3893
  text: body.text
3344
- }, externalActor(body.author), source, async (write) => send({
3894
+ }, author, source, async (write) => send({
3345
3895
  ...body,
3346
3896
  text: write.text
3347
3897
  })));
@@ -3356,35 +3906,24 @@ async function createServe(context) {
3356
3906
  throw error;
3357
3907
  }
3358
3908
  }
3359
- /**
3360
- * A post, with the emails it mentions resolved once the caller may post there (and sync, for
3361
- * targets it names), through the middleware.
3362
- */
3909
+ /** A post, with the targets it names resolved once the caller may post and sync there, through the middleware. */
3363
3910
  async function post(caller, input, signal) {
3364
- const send = (poster, body) => screenPost(poster, body, signal, (patched) => backend.post(poster, patched, signal));
3911
+ await checkWrite(caller, input.text, input.channel !== void 0 ? { channel: input.channel } : { message: input.re }, signal);
3912
+ const send = (poster, body) => screenPost(poster, body, signal, async (patched) => {
3913
+ if (patched.text !== input.text) await checkBlocks(patched.text);
3914
+ return backend.post(poster, patched, signal);
3915
+ });
3365
3916
  if (!engine) return send(caller, input.sync?.length ? {
3366
3917
  ...input,
3367
3918
  sync: await Promise.all(input.sync.map(resolveTarget))
3368
3919
  } : input);
3369
- const allowed = (input.sync?.length ?? 0) > 0 || mentionsEmails(input.text) ? await mayPost(caller, input, signal) : null;
3920
+ const allowed = input.sync?.length ? await mayPost(caller, input, signal) : null;
3370
3921
  if (!allowed) return send(caller, input);
3371
3922
  const { access, channel } = allowed;
3372
- const body = input.re === void 0 && (input.sync?.length ?? 0) > 0 && (access === null || access.can("sync", channel)) ? {
3923
+ return send(caller, input.re === void 0 && (access === null || access.can("sync", channel)) ? {
3373
3924
  ...input,
3374
3925
  sync: await Promise.all(input.sync.map(resolveTarget))
3375
- } : input;
3376
- const text = await withEmails(body.text);
3377
- const answer = await send(caller, {
3378
- ...body,
3379
- text
3380
- });
3381
- return text !== input.text && access !== null && !access.readable(answer.message.channel) ? {
3382
- ...answer,
3383
- message: {
3384
- ...answer.message,
3385
- text: input.text
3386
- }
3387
- } : answer;
3926
+ } : input);
3388
3927
  }
3389
3928
  /**
3390
3929
  * An import's answer, as a sync callback's client gets it: the message it wrote or changed, or the
@@ -3422,7 +3961,7 @@ async function createServe(context) {
3422
3961
  author,
3423
3962
  from: null,
3424
3963
  message: id,
3425
- text: await withEmails(text),
3964
+ text,
3426
3965
  source,
3427
3966
  ...revision !== void 0 ? { revision } : {}
3428
3967
  });
@@ -3489,7 +4028,7 @@ async function createServe(context) {
3489
4028
  thread: via.thread
3490
4029
  },
3491
4030
  ...input.channel !== void 0 ? { channel: input.channel } : { re: input.re },
3492
- text: await withEmails(input.text),
4031
+ text: input.text,
3493
4032
  ...input.labels ? { labels: input.labels } : {},
3494
4033
  ...input.noSync ? { noSync: true } : {},
3495
4034
  ...input.attachments?.length ? { attachments: input.attachments } : {},
@@ -3505,39 +4044,23 @@ async function createServe(context) {
3505
4044
  }, signal);
3506
4045
  return { message: await read(message) };
3507
4046
  }
3508
- /** The protocol method `name`, as board() serves it: what it posts and edits, and the filters it reads by, with their emails resolved. */
4047
+ /** The protocol method `name`, as board() serves it: what it posts, edits, and imports goes through the middleware. */
3509
4048
  async function invoke(name, caller, input, signal) {
3510
- if (name === "messages" || name === "threads" || name === "events") input = await withMentioned(caller, input);
3511
4049
  switch (name) {
3512
4050
  case "post": return post(caller, input, signal);
3513
4051
  case "edit": {
3514
4052
  const edit = input;
3515
- const send = (body) => screenEdit(caller, body, signal, (patched) => backend.edit(caller, patched, signal));
3516
- if (!engine || !mentionsEmails(edit.text) || !await mayPost(caller, { re: edit.id }, signal)) return send(edit);
3517
- return send({
3518
- ...edit,
3519
- text: await withEmails(edit.text)
4053
+ await checkWrite(caller, edit.text, { message: edit.id }, signal);
4054
+ return screenEdit(caller, edit, signal, async (patched) => {
4055
+ if (patched.text !== edit.text) await checkBlocks(patched.text);
4056
+ return backend.edit(caller, patched, signal);
3520
4057
  });
3521
4058
  }
3522
4059
  case "syncImport": return syncImport(caller, input, signal);
3523
4060
  case "schedule": {
3524
4061
  const body = input;
3525
- const schedule = (made) => backend.sendsSchedulesHere === false ? screenSchedule(caller, made, signal) : backend.schedule(caller, made, signal);
3526
- const allowed = engine && mentionsEmails(body.text) ? await mayPost(caller, body, signal) : null;
3527
- if (!allowed) return schedule(body);
3528
- const text = await withEmails(body.text);
3529
- const answer = await schedule({
3530
- ...body,
3531
- text
3532
- });
3533
- const { access } = allowed;
3534
- return text !== body.text && access !== null && !access.readable(answer.schedule.channel) ? {
3535
- ...answer,
3536
- schedule: {
3537
- ...answer.schedule,
3538
- text: body.text
3539
- }
3540
- } : answer;
4062
+ await checkWrite(caller, body.text, body.channel !== void 0 ? { channel: body.channel } : { message: body.re }, signal);
4063
+ return backend.sendsSchedulesHere === false ? screenSchedule(caller, body, signal) : backend.schedule(caller, body, signal);
3541
4064
  }
3542
4065
  case "inbox": {
3543
4066
  const query = input;
@@ -3596,7 +4119,8 @@ async function createServe(context) {
3596
4119
  respond: platform.respond
3597
4120
  },
3598
4121
  origin: { via: platform.via }
3599
- }, trigger)
4122
+ }, trigger),
4123
+ syncedHere: async (key) => backend.syncedHere ? backend.syncedHere(key) : true
3600
4124
  });
3601
4125
  /**
3602
4126
  * Server-sent events, from the backend's long-poll: each event's `id` is its cursor, so
@@ -3712,7 +4236,7 @@ async function createServe(context) {
3712
4236
  const caller = own ?? await callerOf(asked);
3713
4237
  if (target.kind === "board") return await serve(target.name, caller, request, url, match.params);
3714
4238
  const input = await inputOf(target.name, request, url, match.params);
3715
- if (target.name === "events" && (request.headers.get("accept") ?? "").includes("text/event-stream")) return await sse(caller, await withMentioned(caller, input), request, asked ? () => callerOf(asked) : null);
4239
+ if (target.name === "events" && (request.headers.get("accept") ?? "").includes("text/event-stream")) return await sse(caller, input, request, asked ? () => callerOf(asked) : null);
3716
4240
  const output = injected && "platform" in injected ? await asPlatform(target.name, injected, input, request.signal) : await invoke(target.name, caller, input, request.signal);
3717
4241
  if (target.name === "attachment") return attachmentResponse(output);
3718
4242
  const made = CREATED.has(target.name) || target.name === "createChannel" && output.created;
@@ -3774,6 +4298,13 @@ async function createServe(context) {
3774
4298
  //#region src/server/board.ts
3775
4299
  /** How long a handle's live events wait for the next, in seconds, before asking again. */
3776
4300
  const EVENTS_WAIT_S = 25;
4301
+ /** A profile's name, as the board takes one in `x-board-profile`. */
4302
+ const SANDBOX_PROFILE = /^[A-Za-z][A-Za-z0-9-]{0,31}$/;
4303
+ /** An avatar the board takes: an https URL, or http on localhost. */
4304
+ const avatarUrl = (value) => {
4305
+ const url = URL.parse(value);
4306
+ return url !== null && (url.protocol === "https:" || url.protocol === "http:" && ["localhost", "127.0.0.1"].includes(url.hostname));
4307
+ };
3777
4308
  /** A board's name: 1 to 64 characters, no `/`. */
3778
4309
  const BOARD_NAME = /^[^/]{1,64}$/;
3779
4310
  /** A team, by its ID or its slug. */
@@ -3824,12 +4355,59 @@ function createBoard(options, runtime) {
3824
4355
  });
3825
4356
  }
3826
4357
  const serve = async (request) => (await server()).dispatch(request, null);
4358
+ /** How a sandbox reaches this board, where it keeps the board itself: at its own URL, with this deployment's credential. */
4359
+ async function ownReach({ profile, can, token }) {
4360
+ const url = ownUrl();
4361
+ if (url === null) throw new HttpError(400, "no_url", "A sandbox reaches this board at its URL, and it doesn't know it yet.", {
4362
+ hint: "Pass board({ url }).",
4363
+ origin: "handle"
4364
+ });
4365
+ return {
4366
+ url,
4367
+ headers: {
4368
+ ...runtime.sandbox ? await runtime.sandbox(url, token) : token === void 0 ? withoutToken(url) : { authorization: `Bearer ${token}` },
4369
+ "x-board-profile": formatProfileHeader(profile),
4370
+ "x-board-can": can
4371
+ },
4372
+ routes: PROTOCOL_ROUTES
4373
+ };
4374
+ }
4375
+ /** The policy that hands this board to a sandbox, for a handle as `caller`. */
4376
+ async function sandboxPolicy(caller, options = {}) {
4377
+ const own = "profile" in caller ? caller.profile : null;
4378
+ const named = options.profile ?? (own === null || own === void 0 ? null : typeof own === "string" ? { name: own } : own);
4379
+ if (named === null) throw new BoardError("invalid_profile", "A sandbox writes as a profile of this deployment, and this names none: the sandbox could send its own, and write as any.", 400, { hint: "Name one: sandboxPolicy({ profile: { name } }), or team.as('<name>').sandboxPolicy()." });
4380
+ if (!SANDBOX_PROFILE.test(named.name)) throw new BoardError("invalid_profile", `${named.name} isn't a profile's name: one starts with a letter and uses up to 32 letters, numbers, and hyphens.`, 400);
4381
+ if (named.avatar !== void 0 && !avatarUrl(named.avatar)) throw new BoardError("invalid_profile", `${named.avatar} isn't an avatar: one is an https URL, or http on localhost.`, 400);
4382
+ let can;
4383
+ try {
4384
+ can = canHeader(options.can);
4385
+ } catch (error) {
4386
+ if (error instanceof InvalidCan) throw new BoardError("invalid_scope", error.message, 400);
4387
+ throw error;
4388
+ }
4389
+ const input = {
4390
+ profile: named,
4391
+ can,
4392
+ token: options.token
4393
+ };
4394
+ try {
4395
+ return boardPolicy(backend.sandbox ? await backend.sandbox(input) : await ownReach(input));
4396
+ } catch (error) {
4397
+ if (error instanceof HttpError) throw new BoardError(error.code, error.message, error.status, {
4398
+ ...error.hint !== void 0 ? { hint: error.hint } : {},
4399
+ origin: error.origin
4400
+ });
4401
+ throw error;
4402
+ }
4403
+ }
3827
4404
  /** A handle on `client`, which `as` gives other profiles of. */
3828
- function handle(client, url) {
4405
+ function handle(client, url, caller) {
3829
4406
  const made = {
3830
4407
  ...client,
3831
4408
  fetch: serve,
3832
- as
4409
+ as,
4410
+ sandboxPolicy: (options) => sandboxPolicy(caller, options)
3833
4411
  };
3834
4412
  if (url) Object.defineProperty(made, "url", {
3835
4413
  get: url,
@@ -3847,7 +4425,7 @@ function createBoard(options, runtime) {
3847
4425
  if ("identity" in caller) return handle({
3848
4426
  ...client,
3849
4427
  events: (query, opts) => events(client, query, opts)
3850
- }, () => ownUrl() ?? inProcess);
4428
+ }, () => ownUrl() ?? inProcess, caller);
3851
4429
  const via = caller.origin.via?.kind ?? "client";
3852
4430
  const id = (given) => derivedId(`board-${via === "watcher" ? "watch" : via}`, caller.self ?? "", given);
3853
4431
  const owned = async (input) => typeof input === "string" || input.id === void 0 ? input : {
@@ -3864,7 +4442,7 @@ function createBoard(options, runtime) {
3864
4442
  return profile !== void 0 ? as(profile).request(path, rest) : client.request(path, rest);
3865
4443
  },
3866
4444
  events: (query, opts) => events(client, query, opts)
3867
- }, () => ownUrl() ?? inProcess);
4445
+ }, () => ownUrl() ?? inProcess, caller);
3868
4446
  }
3869
4447
  const profileCaller = (profile) => {
3870
4448
  const name = profile === null ? null : typeof profile === "string" ? profile : profile.name;
@@ -3977,4 +4555,4 @@ async function* events(client, query = {}, opts = {}) {
3977
4555
  }
3978
4556
  }
3979
4557
  //#endregion
3980
- export { tailWatchers as a, isApiMessageId as i, isBoardName as n, deployedOnVercel as o, createVercel as r, createBoard as t };
4558
+ export { PROTOCOL_ROUTES as a, deployedOnVercel as c, isApiMessageId as i, isBoardName as n, withoutToken as o, createVercel as r, tailWatchers as s, createBoard as t };