@vercel/board 0.39.0 → 0.40.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 (85) hide show
  1. package/README.md +5 -3
  2. package/dist/{access-CVkjSfxj.mjs → access-Bl_k_Hpa.mjs} +1 -1
  3. package/dist/access.d.mts +2 -2
  4. package/dist/access.mjs +4 -4
  5. package/dist/{actors-kfMejhaw.mjs → actors-yBRWTpt5.mjs} +38 -53
  6. package/dist/{auth-B3bBYOqf.mjs → auth-C8URZHLx.mjs} +2 -2
  7. package/dist/{auth-BXLCkeB0.d.mts → auth-DtmZzlHm.d.mts} +5 -2
  8. package/dist/{backend-HcCCGPG4.d.mts → backend-BW5NbBsp.d.mts} +36 -10
  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-DyNy5xdC.d.mts → chat-provider-Bbb9JguG.d.mts} +2 -2
  14. package/dist/cli-commands.d.mts +1 -1
  15. package/dist/cli-commands.mjs +1 -1
  16. package/dist/cli-embedded.d.mts +2 -2
  17. package/dist/cli-embedded.mjs +3 -3
  18. package/dist/cli.mjs +5 -5
  19. package/dist/{commands-B5d-lmNN.d.mts → commands-BJLocuXj.d.mts} +10 -0
  20. package/dist/{commands-BLS7erNu.mjs → commands-D6VWegVY.mjs} +88 -8
  21. package/dist/{conformance-D59Py2m2.mjs → conformance-BWhZ0k8T.mjs} +252 -5
  22. package/dist/conformance.d.mts +4 -3
  23. package/dist/conformance.mjs +1 -1
  24. package/dist/data-values-C-Cq80hz.mjs +176 -0
  25. package/dist/digest-D32GV_mX.mjs +4 -0
  26. package/dist/{engine-eUgO5jTM.mjs → engine-Djif8XVk.mjs} +191 -77
  27. package/dist/{errors-rYDxZEuN.mjs → errors-CNRJqUuL.mjs} +16 -14
  28. package/dist/{exports-M5o4PTfO.mjs → exports-C2OWIbLU.mjs} +621 -245
  29. package/dist/exports-FyRBIAMs.d.mts +4 -0
  30. package/dist/{index-rNqqgkyu.d.mts → index-Cuxbz_E0.d.mts} +2 -2
  31. package/dist/index.d.mts +7 -6
  32. package/dist/index.mjs +6 -5
  33. package/dist/index.node.d.mts +7 -6
  34. package/dist/index.node.mjs +5 -4
  35. package/dist/inspect/app.js +110 -109
  36. package/dist/inspect/engine.js +5 -5
  37. package/dist/inspect-CLy6FrOZ.mjs +2 -0
  38. package/dist/{inspect-BkXxR2uB.mjs → inspect-cGcP8ZO9.mjs} +4 -4
  39. package/dist/{local-DvkOWf4U.mjs → local-CsleYuyM.mjs} +373 -177
  40. package/dist/{main-DtV_Po9i.mjs → main-D97xuqWZ.mjs} +177 -59
  41. package/dist/{memory-DkoqhxIH.mjs → memory-BvVoglGv.mjs} +2 -2
  42. package/dist/{mentions-CB6ShY4R.mjs → mentions-CT2bN5eP.mjs} +17 -3
  43. package/dist/{middleware-CPqAuRtp.mjs → middleware-BF9vnPPS.mjs} +70 -2
  44. package/dist/{targets-C1mT3M1N.mjs → origin-DLCmrwmE.mjs} +47 -39
  45. package/dist/{page-64IwoGRu.mjs → page-6BTCZWGY.mjs} +2 -2
  46. package/dist/page-BnY8FhPn.mjs +2 -0
  47. package/dist/{provider-D5yVFisj.d.mts → provider-YqkF1E2k.d.mts} +23 -13
  48. package/dist/{routes-BffuaoTX.d.mts → routes-CAjd5ARa.d.mts} +101 -25
  49. package/dist/schemas.d.mts +37 -0
  50. package/dist/schemas.mjs +3 -0
  51. package/dist/{serve-CX1rqDF_.mjs → serve-Cs-e0Jke.mjs} +4 -4
  52. package/dist/{server-DkYkyarg.mjs → server-CIfMdIt3.mjs} +6 -6
  53. package/dist/{serving-DJMcG0dT.mjs → serving-B4l0nLng.mjs} +1 -1
  54. package/dist/{sql-l3ysn4O5.mjs → sql-Bv-RQu8n.mjs} +73 -10
  55. package/dist/{sqlite-CAwNHbQD.mjs → sqlite-D4mkYihG.mjs} +2 -2
  56. package/dist/{sqlite-db-cm5yhrD-.mjs → sqlite-db-BraLvHtf.mjs} +1 -1
  57. package/dist/sync-chat-sdk.d.mts +2 -2
  58. package/dist/sync-github.d.mts +2 -2
  59. package/dist/sync-linear.d.mts +3 -3
  60. package/dist/sync-slack.d.mts +14 -8
  61. package/dist/sync-slack.mjs +42 -15
  62. package/dist/sync.d.mts +2 -2
  63. package/dist/{tokens-DA9ipsZ-.mjs → tokens-CrrXAVGz.mjs} +2 -2
  64. package/docs/01-board/01-mounting.md +5 -3
  65. package/docs/01-board/03-identity.md +70 -38
  66. package/docs/01-board/04-messages.md +58 -1
  67. package/docs/01-board/05-reading.md +3 -3
  68. package/docs/01-board/06-watchers.md +2 -3
  69. package/docs/01-board/07-schedules.md +2 -4
  70. package/docs/01-board/08-middleware.md +1 -1
  71. package/docs/01-board/09-access.md +24 -21
  72. package/docs/02-sync/01-overview.md +70 -2
  73. package/docs/02-sync/02-functions.md +11 -6
  74. package/docs/02-sync/03-slack.md +40 -16
  75. package/docs/02-sync/06-providers.md +9 -4
  76. package/docs/04-reference/01-cli.md +110 -18
  77. package/docs/04-reference/02-board.md +63 -10
  78. package/docs/04-reference/03-http.md +154 -28
  79. package/docs/04-reference/05-conformance.md +13 -6
  80. package/docs/index.md +1 -1
  81. package/package.json +5 -1
  82. package/dist/digest-krhjNAt4.mjs +0 -4
  83. package/dist/exports-vLQ2Y2Nd.d.mts +0 -4
  84. package/dist/inspect-lnv1sLXM.mjs +0 -2
  85. 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";
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-CNRJqUuL.mjs";
2
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";
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 UpdateGrantBody, K as TokenBody, 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 UploadStartBody, _ 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 TypingBody, 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-DLCmrwmE.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-BF9vnPPS.mjs";
6
+ import { a as canText, c as compileAccess, d as parsePattern, r as PERMISSIONS, u as parseCan } from "./access-Bl_k_Hpa.mjs";
7
+ 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-C8URZHLx.mjs";
8
+ import { a as viaOf, i as resolveActor, r as claimsOf, t as KNOWN_AGENTS } from "./actors-yBRWTpt5.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;
@@ -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,
@@ -393,6 +400,25 @@ function expiryOf(at) {
393
400
  /** What a caller board() verified gets: board() serves no requests for a board on Vercel's, so it never sends one. */
394
401
  const servesNone = () => new HttpError(404, "not_found", "this board uses Vercel's, and answers only wake-ups and webhooks");
395
402
  const apiKind = (kind) => kind === "app" ? "workflow" : kind;
403
+ /** How many more times a request goes out after the API puts it off. */
404
+ const RETRIES = 4;
405
+ /** The first wait before sending again, doubling each time. */
406
+ const RETRY_MS = 1e3;
407
+ /**
408
+ * How long to wait before sending a put-off request again: a second, doubling each time, with up to
409
+ * as long again added at random so callers the API put off together don't come back together, and
410
+ * never past what `Retry-After` asks. The API's 429s ask for a whole minute while its limit refills
411
+ * all the time, so that's a ceiling, not the wait.
412
+ */
413
+ function retryWait(attempt, retryAfter) {
414
+ const asked = retryAfter !== null && /^\d+$/.test(retryAfter) && Number(retryAfter) > 0 ? Number(retryAfter) * 1e3 : Infinity;
415
+ return Math.min(asked, RETRY_MS * 2 ** attempt * (1 + Math.random()));
416
+ }
417
+ /** `ms` passing, or `signal` stopping it first. */
418
+ const pause = (ms, signal) => ms <= 0 || signal?.aborted ? Promise.resolve() : new Promise((resolve) => {
419
+ const timer = setTimeout(resolve, ms);
420
+ signal?.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
421
+ });
396
422
  /** A UUIDv7, which the API takes as an operation ID. */
397
423
  function operationId() {
398
424
  const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
@@ -415,6 +441,17 @@ const tokenFrom = (token) => ({
415
441
  at: expiryOf(token.at) ?? token.at,
416
442
  expiresAt: expiryOf(token.expiresAt) ?? token.expiresAt
417
443
  });
444
+ /** A schema the API keeps, as the protocol shows it. */
445
+ const schemaFrom = (schema) => ({
446
+ id: schema.id,
447
+ name: schema.name,
448
+ version: schema.version,
449
+ description: schema.description ?? null,
450
+ schema: schema.schema,
451
+ builtIn: schema.builtIn,
452
+ by: schema.createdBy?.id ?? null,
453
+ at: schema.builtIn ? null : iso(schema.createdAt)
454
+ });
418
455
  const idAt = (threadId, sequence) => `msg_${threadId.slice(4)}_${sequence}`;
419
456
  /** Where a message ID points: its thread and its place in it. Null for one that isn't a message's. */
420
457
  function locate(id) {
@@ -431,6 +468,118 @@ function principalId(principal) {
431
468
  if (principal.type === "app") return `vercel:app:${principal.clientId}`;
432
469
  return `vercel:project:${principal.projectId}:${principal.environment}`;
433
470
  }
471
+ /** 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. */
472
+ function principalFrom(actor) {
473
+ const id = actorParts(actor).principal;
474
+ const project = /^vercel:project:([^:]+):([^:]+)$/.exec(id);
475
+ if (project) return {
476
+ type: "project",
477
+ projectId: project[1],
478
+ environment: project[2]
479
+ };
480
+ if (id.startsWith("vercel:user:")) return {
481
+ type: "user",
482
+ userId: id.slice(12)
483
+ };
484
+ if (id.startsWith("vercel:app:")) return {
485
+ type: "app",
486
+ clientId: id.slice(11)
487
+ };
488
+ return null;
489
+ }
490
+ /**
491
+ * Who an actor with a profile acts through, as board shows it: a project by its name (`project`, as the
492
+ * actors list names it), or the one the API's view gives it, or its ID, in its environment; a person by
493
+ * their username, which the API puts before an agent's name in its handle (`julian/claude`); anyone
494
+ * else by a short form of their ID.
495
+ */
496
+ function viaFor(principal, view, project) {
497
+ const named = view?.via?.name ?? null;
498
+ if (principal.type === "project") return {
499
+ name: project ?? named ?? principal.projectId,
500
+ environment: view?.via?.environment ?? principal.environment
501
+ };
502
+ if (principal.type === "external") return {
503
+ name: named ?? principal.id,
504
+ environment: null
505
+ };
506
+ const slash = view?.handle.indexOf("/") ?? -1;
507
+ const username = principal.type === "user" && slash > 0 ? view.handle.slice(0, slash) : null;
508
+ return {
509
+ name: named ?? username ?? shortName(principal),
510
+ environment: null
511
+ };
512
+ }
513
+ /**
514
+ * A platform user's handle as a project's sync imported them, `support/malte-ubl`, at most 128
515
+ * characters as the API keeps it: as the API names them, or from an API that names them as their
516
+ * platform does, under their project's name.
517
+ */
518
+ 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);
519
+ /**
520
+ * A deployment as board shows it: by its project's name (`project`) in every environment, and named
521
+ * with its environment outside production (`support (preview)`); or, where that isn't known, by its
522
+ * project's ID, and outside production with its environment (`prj_support@preview`).
523
+ */
524
+ function deploymentNamed(principal, project) {
525
+ const production = principal.environment === "production";
526
+ if (project === void 0) {
527
+ const id = production ? principal.projectId : `${principal.projectId}@${principal.environment}`;
528
+ return {
529
+ handle: id,
530
+ name: id
531
+ };
532
+ }
533
+ return {
534
+ handle: project,
535
+ name: production ? project : `${project} (${principal.environment})`
536
+ };
537
+ }
538
+ /**
539
+ * Projects' names by ID, from what the actors list says: a deployment's handle, which the API makes its project's
540
+ * name, then what comes before the `/` in one of its agents' (`support/sync`, its sync's), then the name the API gives
541
+ * a project on its users (their `via`). An API that names a deployment by its ID (`project:prj_…:production`,
542
+ * `project:prj_…:production/sync`) names its project only there. A platform user's handle names no project: an API
543
+ * may give the one they have on their platform, slash and all.
544
+ */
545
+ function projectNamesOf(views) {
546
+ const byHandle = /* @__PURE__ */ new Map();
547
+ const byProfile = /* @__PURE__ */ new Map();
548
+ const byVia = /* @__PURE__ */ new Map();
549
+ for (const [id, found] of views) {
550
+ const principal = principalFrom(id);
551
+ if (principal?.type !== "project") continue;
552
+ const { profile } = actorParts(id);
553
+ if (profile !== null && found.via?.name) byVia.set(principal.projectId, found.via.name);
554
+ if (found.handle.startsWith("project:")) continue;
555
+ const slash = found.handle.indexOf("/");
556
+ if (profile === null) byHandle.set(principal.projectId, found.handle);
557
+ else if (slash > 0 && platformProfile(profile) === null) byProfile.set(principal.projectId, found.handle.slice(0, slash));
558
+ }
559
+ return new Map([
560
+ ...byVia,
561
+ ...byProfile,
562
+ ...byHandle
563
+ ]);
564
+ }
565
+ /**
566
+ * The handle board shows an actor of the actors list by, with its project named as `names` says: a deployment by
567
+ * its project's (`www`, or by ID `prj_www@preview`), a platform user under it (`www/ada`), and anyone else as the
568
+ * API names them.
569
+ */
570
+ function shownHandle(id, view, names) {
571
+ const principal = principalFrom(id);
572
+ if (principal?.type !== "project") return view.handle;
573
+ const project = names.get(principal.projectId);
574
+ const { profile } = actorParts(id);
575
+ if (profile === null) return deploymentNamed(principal, project).handle;
576
+ const user = platformProfile(profile);
577
+ return user ? importedHandleOf(view.handle, principal, view, user.user, project) : view.handle;
578
+ }
579
+ /** Who goes by `handle` in a read of the actors list: as the API names them, or as board shows them. */
580
+ const goingBy = (views, names, handle) => [...views].filter(([id, view]) => view.handle.toLowerCase() === handle || shownHandle(id, view, names).toLowerCase() === handle).map(([id]) => id);
581
+ /** A short name for a person or an app the API doesn't name: the start of their ID. */
582
+ const shortName = (principal) => principal.type === "user" ? `user-${principal.userId.slice(0, 6).toLowerCase()}` : `app-${principal.clientId.slice(0, 6).toLowerCase()}`;
434
583
  const authorOf = (actor) => ({
435
584
  actor: actor.id,
436
585
  principal: principalId(actor.principal),
@@ -444,25 +593,59 @@ const SCHEDULER = {
444
593
  profile: null,
445
594
  session: null
446
595
  };
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;
596
+ /**
597
+ * An actor where the API doesn't name them: its handle is its profile, or a short form of its
598
+ * principal (a deployment by `project`, its project's name, where it's known), and one with a profile
599
+ * acts through its principal, as `view` names it if there's one.
600
+ */
601
+ function actorView(actor, view, project) {
602
+ const { principal, profile } = actor;
450
603
  if (principal.type === "external") return {
451
604
  id: actor.id,
452
605
  kind: "external",
453
606
  handle: principal.id.slice(principal.id.lastIndexOf(":") + 1),
454
607
  name: principal.id,
455
- avatar: null
608
+ avatar: null,
609
+ verified: true
456
610
  };
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";
611
+ if (profile?.platform) {
612
+ const { userId, platform, key } = profile.platform;
613
+ const handle = importedHandleOf(view?.handle ?? "", principal, view, userId, project);
614
+ return {
615
+ id: actor.id,
616
+ kind: "external",
617
+ handle,
618
+ name: profile.name,
619
+ avatar: null,
620
+ via: viaFor(principal, view, project),
621
+ platform: view?.platform ?? platform ?? key,
622
+ verified: true
623
+ };
624
+ }
625
+ if (profile) return {
626
+ id: actor.id,
627
+ kind: "agent",
628
+ handle: profile.name,
629
+ name: profile.name,
630
+ avatar: profile.avatar ?? null,
631
+ via: viaFor(principal, view, project),
632
+ verified: true
633
+ };
634
+ if (principal.type === "project") return {
635
+ id: actor.id,
636
+ kind: "deployment",
637
+ ...deploymentNamed(principal, project),
638
+ avatar: null,
639
+ verified: true
640
+ };
641
+ const handle = shortName(principal);
460
642
  return {
461
643
  id: actor.id,
462
- kind,
644
+ kind: principal.type === "user" ? "person" : "workflow",
463
645
  handle,
464
646
  name: handle,
465
- avatar: actor.profile?.avatar ?? null
647
+ avatar: null,
648
+ verified: true
466
649
  };
467
650
  }
468
651
  /** A message's labels just before a change, from what they are after it and what it changed. */
@@ -502,7 +685,11 @@ function createVercel(options, environment) {
502
685
  const given = binding?.team ?? options.team;
503
686
  return team ??= given ? Promise.resolve(given) : environment?.team() ?? Promise.resolve(null);
504
687
  };
505
- /** One request to the API, as `who`. Its errors are the API's own, with its status and code. */
688
+ /**
689
+ * One request to the API, as `who`. Its errors are the API's own, with its status and code. One the
690
+ * API puts off (429, or a 503) waits and goes again as it was, so a write keeps its operation ID
691
+ * and lands once.
692
+ */
506
693
  async function api(who, method, path, init = {}) {
507
694
  const url = new URL(`${origin}/v1/messageboard${path}`);
508
695
  const id = await teamId();
@@ -516,38 +703,46 @@ function createVercel(options, environment) {
516
703
  if (who.profile) headers["x-board-profile"] = who.profile.name;
517
704
  if (who.profile?.avatar?.startsWith("https://")) headers["x-board-avatar"] = who.profile.avatar;
518
705
  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 } : {}
706
+ const repeatable = method !== "POST" && method !== "PATCH" || typeof init.body?.operationId === "string";
707
+ for (let attempt = 0;; attempt++) {
708
+ let response;
709
+ try {
710
+ response = await doFetch(url, {
711
+ method,
712
+ headers,
713
+ redirect: "error",
714
+ ...init.body !== void 0 ? { body: JSON.stringify(init.body) } : {},
715
+ ...init.signal ? { signal: init.signal } : {}
716
+ });
717
+ } catch (error) {
718
+ if (error instanceof HttpError || error instanceof Error && error.name === "AbortError") throw error;
719
+ throw new HttpError(502, "unreachable", `Vercel's API didn't answer: ${error instanceof Error ? error.message : String(error)}`);
720
+ }
721
+ const text = await response.text();
722
+ let body;
723
+ try {
724
+ body = text ? JSON.parse(text) : void 0;
725
+ } catch {}
726
+ if (response.ok) return body;
727
+ if (attempt < RETRIES && !init.signal?.aborted && (response.status === 429 || response.status === 503 && repeatable)) {
728
+ await pause(retryWait(attempt, response.headers.get("retry-after")), init.signal);
729
+ init.signal?.throwIfAborted();
730
+ continue;
731
+ }
732
+ const error = body?.error;
733
+ if (error?.code === "board_token_scope") throw new HttpError(403, "board_token_scope", "a board token reaches only its own board, by its ID.", {
734
+ hint: "Name its board by URL or ID: BOARD_URL, --url, or vercel({ board }).",
735
+ origin: "handle"
527
736
  });
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)}`);
737
+ throw new HttpError(response.status, error?.code ?? "remote_error", error?.message ?? `Vercel's API answered ${response.status}`);
531
738
  }
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
739
  }
545
740
  /** A request on sync's routes, whose refusals board()'s sync knows only by the board's codes. */
546
741
  async function syncApi(...args) {
547
742
  try {
548
743
  return await api(...args).catch(async (error) => {
549
744
  if (!(error instanceof HttpError && error.code === "sync_key_not_owned" && (binding?.sync.length ?? 0) > 0)) throw error;
550
- await runner.registerNow();
745
+ await runner.registerNow(true);
551
746
  return api(...args);
552
747
  });
553
748
  } catch (error) {
@@ -789,15 +984,71 @@ function createVercel(options, environment) {
789
984
  if (!found && await again.views.then(() => true, () => false)) unlisted.add(actor.id);
790
985
  }
791
986
  const kind = found && apiKind(found.kind);
792
- if (!found || !(kind === "person" || kind === "external" || kind === "agent" && actor.principal.type === "user")) return actorView(actor);
987
+ const project = actor.principal.type === "project" ? await namedProject(who, actor.principal.projectId) : void 0;
988
+ if (!found || !(kind === "person" || kind === "external" || kind === "agent" && actor.principal.type === "user")) return actorView(actor, found, project);
989
+ const via = actor.profile && actor.principal.type !== "external" ? { via: viaFor(actor.principal, found, project) } : {};
990
+ const platform = found.platform ?? actor.profile?.platform?.platform;
991
+ const user = actor.profile?.platform;
992
+ const handle = user && actor.principal.type !== "external" ? importedHandleOf(found.handle, actor.principal, found, user.userId, project) : found.handle;
793
993
  return {
794
994
  id: actor.id,
795
995
  kind,
796
- handle: found.handle,
996
+ handle,
797
997
  name: found.name ?? found.handle,
798
- avatar: found.avatar ?? null
998
+ avatar: found.avatar ?? null,
999
+ ...via,
1000
+ ...platform ? { platform } : {},
1001
+ verified: true
799
1002
  };
800
1003
  }
1004
+ /** Projects' names by ID, as `projectNamesOf` reads them from a read of the actors list. */
1005
+ const namesRead = /* @__PURE__ */ new WeakMap();
1006
+ function namesIn(read) {
1007
+ let names = namesRead.get(read);
1008
+ if (!names) namesRead.set(read, names = read.views.then(projectNamesOf, () => /* @__PURE__ */ new Map()));
1009
+ return names;
1010
+ }
1011
+ /** What a fresh read of the actors still didn't name: it isn't read again for them until names are read anyway. */
1012
+ const unnamed = /* @__PURE__ */ new Set();
1013
+ /**
1014
+ * Projects' names by ID, as the actors list names them, read again at once when `wanted` (one or more projects, by
1015
+ * their IDs) isn't among them, as for someone new since the list was read.
1016
+ */
1017
+ async function projectNames(who, wanted) {
1018
+ const kept = actorNames && Date.now() - actorNames.at <= NAMES_FRESH_MS ? actorNames : null;
1019
+ let names = await namesIn(kept ?? readNames(who));
1020
+ if (!wanted || wanted.found(names) || !kept || unnamed.has(wanted.key)) return names;
1021
+ names = await namesIn(actorNames && actorNames !== kept ? actorNames : readNames(who));
1022
+ if (!wanted.found(names)) {
1023
+ if (unnamed.size >= 1e3) unnamed.clear();
1024
+ unnamed.add(wanted.key);
1025
+ }
1026
+ return names;
1027
+ }
1028
+ /** A project's name, as `projectNames` finds it: undefined where nothing names it. */
1029
+ const namedProject = async (who, project) => (await projectNames(who, {
1030
+ key: project,
1031
+ found: (names) => names.has(project)
1032
+ })).get(project);
1033
+ /** A project's name, or its ID. */
1034
+ const projectName = async (who, project) => await namedProject(who, project) ?? project;
1035
+ /** The project these credentials are, whose sync keys a caller names bare: null for a person's or an app's. */
1036
+ const ownProject = async (who) => {
1037
+ const { principal } = (await self(who)).actor;
1038
+ return principal.type === "project" ? principal.projectId : null;
1039
+ };
1040
+ /** The project whose sync imported a message or a change, as its author says: null for one that says none. */
1041
+ const importerOf = (actor) => actor.principal.type === "project" ? actor.principal.projectId : null;
1042
+ /**
1043
+ * The sync key a message or a change came through, as this caller names it: bare for its own project's, since a
1044
+ * project's keys are its own, and `<project>/<key>` for another's (`www/slack`), by the project's name, or its ID.
1045
+ */
1046
+ async function fromOf(who, from, by) {
1047
+ if (from === void 0) return null;
1048
+ const project = importerOf(by);
1049
+ if (project === null || project === await ownProject(who)) return from;
1050
+ return `${await projectName(who, project)}/${from}`;
1051
+ }
801
1052
  async function view(who, message, channel) {
802
1053
  const root = message.sequence === 1;
803
1054
  return {
@@ -809,11 +1060,10 @@ function createVercel(options, environment) {
809
1060
  thread: message.threadId,
810
1061
  labels: labelsOf(message),
811
1062
  reactions: message.deletedAt === void 0 ? await reactors(who, message) : {},
812
- mentions: [],
813
1063
  by: authorOf(message.createdBy),
814
1064
  noSync: message.noSync ?? false,
815
1065
  origin: originOf(message.origin),
816
- from: message.from ?? null,
1066
+ from: await fromOf(who, message.from, message.createdBy),
817
1067
  createdAt: iso(message.createdAt),
818
1068
  editedAt: message.editedAt === void 0 ? null : iso(message.editedAt),
819
1069
  deleted: message.deletedAt !== void 0,
@@ -831,7 +1081,8 @@ function createVercel(options, environment) {
831
1081
  ...message.schedule ? { schedule: {
832
1082
  id: message.schedule.id,
833
1083
  n: message.schedule.n
834
- } } : {}
1084
+ } } : {},
1085
+ blocks: (message.from ?? null) === null && message.deletedAt === void 0 ? blocksIn(message.text) : []
835
1086
  };
836
1087
  }
837
1088
  /**
@@ -934,7 +1185,7 @@ function createVercel(options, environment) {
934
1185
  const named = /* @__PURE__ */ new Set([by]);
935
1186
  if (!by.startsWith("vercel:")) {
936
1187
  const handle = by.toLowerCase();
937
- const find = async (read) => [...await read.views].filter(([, view]) => view.handle.toLowerCase() === handle).map(([id]) => id);
1188
+ const find = async (read) => goingBy(await read.views, await namesIn(read), handle);
938
1189
  const kept = actorNames && Date.now() - actorNames.at <= NAMES_FRESH_MS ? actorNames : null;
939
1190
  let ids = await find(kept ?? readNames(who));
940
1191
  const missed = unhandled.get(handle);
@@ -945,17 +1196,39 @@ function createVercel(options, environment) {
945
1196
  }
946
1197
  for (const id of ids) named.add(id);
947
1198
  }
948
- return (actor) => named.has(actor.id) || named.has(principalId(actor.principal)) || actor.profile !== void 0 && named.has(actor.profile.name);
1199
+ return (actor) => named.has(actor.id) || named.has(principalId(actor.principal)) || actor.profile !== void 0 && !actor.profile.platform && named.has(actor.profile.name);
949
1200
  }
950
1201
  /**
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.
1202
+ * Which messages `--source` names, as `fromOf` shows where they came from: `board`, a key bare for this caller's own
1203
+ * project's (or an import that names no project), or `<project>/<key>` for any project's, by its name or its ID.
1204
+ */
1205
+ async function sourceOf(who, from) {
1206
+ if (from === void 0) return void 0;
1207
+ if (from === "board") return (message) => message.from === void 0;
1208
+ const slash = from.indexOf("/");
1209
+ if (slash === -1) {
1210
+ const own = await ownProject(who);
1211
+ return (message) => message.from === from && [null, own].includes(importerOf(message.createdBy));
1212
+ }
1213
+ const [project, key] = [from.slice(0, slash), from.slice(slash + 1)];
1214
+ return async (message) => {
1215
+ const importer = importerOf(message.createdBy);
1216
+ return message.from === key && importer !== null && (importer === project || await namedProject(who, importer) === project);
1217
+ };
1218
+ }
1219
+ const narrowOf = async (who, filters) => ({
1220
+ by: await byOf(who, filters.by),
1221
+ source: await sourceOf(who, filters.from)
1222
+ });
1223
+ /**
1224
+ * Whether a message matches a read's filters, `narrow` as `narrowOf` gives them for it. A label matches on the
1225
+ * message or its thread's root: `thread`'s labels, as `labeledBy` gives them when the read filters on labels.
953
1226
  */
954
- function matches(filters, message, thread, by) {
1227
+ async function matches(filters, message, thread, narrow) {
955
1228
  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;
1229
+ if (narrow.by && !narrow.by(message.createdBy)) return false;
957
1230
  if (filters.mentions !== void 0) return false;
958
- if (filters.from !== void 0 && (message.from ?? "board") !== filters.from) return false;
1231
+ if (filters.from !== void 0 && !await narrow.source?.(message)) return false;
959
1232
  if (filters.text !== void 0 && !message.text.toLowerCase().includes(filters.text.toLowerCase())) return false;
960
1233
  for (const [key, values] of filters.label ?? []) {
961
1234
  const on = (labels) => labels !== void 0 && Object.hasOwn(labels, key) && (values === null || values.includes(labels[key]));
@@ -1085,7 +1358,7 @@ function createVercel(options, environment) {
1085
1358
  }))))).flat();
1086
1359
  }
1087
1360
  const feeds = await heads(who, listed);
1088
- const by = await byOf(who, filters.by);
1361
+ const narrow = await narrowOf(who, filters);
1089
1362
  let newest = 0;
1090
1363
  const messages = [];
1091
1364
  for (const { thread, channel } of threads) {
@@ -1093,7 +1366,7 @@ function createVercel(options, environment) {
1093
1366
  const labeled = labeledBy(thread, all.find((message) => message.sequence === 1));
1094
1367
  for (const message of all) {
1095
1368
  newest = Math.max(newest, message.createdAt);
1096
- if (matches(filters, message, labeled, by)) messages.push({
1369
+ if (await matches(filters, message, labeled, narrow)) messages.push({
1097
1370
  message,
1098
1371
  thread,
1099
1372
  channel
@@ -1144,7 +1417,7 @@ function createVercel(options, environment) {
1144
1417
  };
1145
1418
  }
1146
1419
  /** 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)) {
1420
+ async function eventOf(who, change, channel, cursor, filters, narrow, given, threads = threadReader(who)) {
1148
1421
  if (!change.messageId || !change.type.startsWith("message.")) return null;
1149
1422
  let found = given ?? await messageById(who, change.messageId).catch((error) => {
1150
1423
  if (error instanceof HttpError && error.status === 404) return null;
@@ -1154,10 +1427,10 @@ function createVercel(options, environment) {
1154
1427
  ...found,
1155
1428
  thread: found.message.sequence === 1 ? labeledBy(found.thread, found.message) : await threads(found.thread.id)
1156
1429
  };
1157
- if (!found || !matches(filters, found.message, found.thread, authors)) return null;
1430
+ if (!found || !await matches(filters, found.message, found.thread, narrow)) return null;
1158
1431
  const message = await view(who, found.message, channel);
1159
1432
  const by = authorOf(change.actor);
1160
- const from = change.from ?? null;
1433
+ const from = await fromOf(who, change.from, change.actor);
1161
1434
  const base = {
1162
1435
  id: message.id,
1163
1436
  thread: message.thread
@@ -1175,7 +1448,6 @@ function createVercel(options, environment) {
1175
1448
  thread: message.thread,
1176
1449
  labels: message.labels,
1177
1450
  noSync: message.noSync,
1178
- mentions: [],
1179
1451
  by,
1180
1452
  origin: message.origin,
1181
1453
  from: message.from,
@@ -1188,7 +1460,6 @@ function createVercel(options, environment) {
1188
1460
  payload = {
1189
1461
  ...base,
1190
1462
  text: message.text,
1191
- mentions: [],
1192
1463
  by,
1193
1464
  from
1194
1465
  };
@@ -1261,7 +1532,7 @@ function createVercel(options, environment) {
1261
1532
  events
1262
1533
  };
1263
1534
  }));
1264
- const by = await byOf(who, filters.by);
1535
+ const narrow = await narrowOf(who, filters);
1265
1536
  const threads = threadReader(who, signal);
1266
1537
  const running = { ...position.feeds };
1267
1538
  const merged = pages.flatMap((page) => page.events.map((event) => ({
@@ -1277,7 +1548,7 @@ function createVercel(options, environment) {
1277
1548
  const event = await eventOf(who, change, page.channel.name, cursorOf({
1278
1549
  t: change.createdAt,
1279
1550
  feeds: { ...running }
1280
- }), filters, by, void 0, threads);
1551
+ }), filters, narrow, void 0, threads);
1281
1552
  if (event) events.push(event);
1282
1553
  }
1283
1554
  const after = { ...position.feeds };
@@ -1293,11 +1564,6 @@ function createVercel(options, environment) {
1293
1564
  }
1294
1565
  };
1295
1566
  }
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
1567
  /**
1302
1568
  * Until one of `listed`'s feeds has something after `position` (true), or it's `until` (false). The API's feed is
1303
1569
  * one channel's, and only it can wait for what comes next, so this waits on each at once and lets
@@ -1348,8 +1614,8 @@ function createVercel(options, environment) {
1348
1614
  const limit = query.limit ?? 50;
1349
1615
  const thread = threadReader(who, signal);
1350
1616
  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);
1617
+ const narrow = narrowed ? await narrowOf(who, query) : {};
1618
+ const keep = async (message) => !narrowed || await matches(query, message, query.label?.length ? await thread(message.threadId) : { id: message.threadId }, narrow);
1353
1619
  const kept = [];
1354
1620
  if (query.after === void 0) {
1355
1621
  const page = await api(who, "GET", path, {
@@ -1388,7 +1654,7 @@ function createVercel(options, environment) {
1388
1654
  async function channelEvents(who, channel, query, signal) {
1389
1655
  const path = await onBoard(who, "/changes");
1390
1656
  const thread = threadReader(who, signal);
1391
- const by = await byOf(who, query.by);
1657
+ const narrow = await narrowOf(who, query);
1392
1658
  const until = Date.now() + (query.wait ?? 0) * 1e3;
1393
1659
  let cursor = query.after;
1394
1660
  for (;;) {
@@ -1411,7 +1677,7 @@ function createVercel(options, environment) {
1411
1677
  thread: query.label?.length ? await thread(change.threadId) : { id: change.threadId }
1412
1678
  } : null;
1413
1679
  if (!found) continue;
1414
- const event = await eventOf(who, change, channel.name, change.cursor ?? page.cursor, query, by, found);
1680
+ const event = await eventOf(who, change, channel.name, change.cursor ?? page.cursor, query, narrow, found);
1415
1681
  if (event) events.push(event);
1416
1682
  }
1417
1683
  if (events.length > 0 || Date.now() >= until || signal.aborted) return {
@@ -1460,7 +1726,10 @@ function createVercel(options, environment) {
1460
1726
  async function authorsOf(who, by) {
1461
1727
  if (by === "me") return [await actorOf(who)];
1462
1728
  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);
1729
+ const listed = await all(who, await onBoard(who, "/actors"), "actors");
1730
+ const views = listed.map((actor) => [actor.id, actor]);
1731
+ const shown = new Set(goingBy(views, projectNamesOf(views), by.toLowerCase()));
1732
+ const named = listed.filter((actor) => shown.has(actor.id) || !by.includes(":") && actor.id.endsWith(`+${by.toLowerCase()}`)).map((actor) => actor.id);
1464
1733
  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
1734
  return named;
1466
1735
  }
@@ -1547,7 +1816,7 @@ function createVercel(options, environment) {
1547
1816
  throw needsProject(error);
1548
1817
  }
1549
1818
  }
1550
- async function registerAs(who, where, watch, sync, fromHere) {
1819
+ async function registerAs(who, where, watch, sync, fromHere, registered = async () => {}) {
1551
1820
  const specs = Object.fromEntries(Object.entries(watch).map(([id, spec]) => [id, { tail: spec.tail }]));
1552
1821
  const filters = Object.fromEntries(await Promise.all(Object.entries(specs).map(async ([id, spec]) => [id, await filterOf(who, id, spec, fromHere)])));
1553
1822
  const entries = sync.map(({ key, platform }) => ({
@@ -1565,6 +1834,7 @@ function createVercel(options, environment) {
1565
1834
  } catch (error) {
1566
1835
  throw needsProject(error);
1567
1836
  }
1837
+ await registered(made);
1568
1838
  return {
1569
1839
  owner: made.owner,
1570
1840
  ...whereOf(made),
@@ -1573,6 +1843,54 @@ function createVercel(options, environment) {
1573
1843
  hash: made.hash
1574
1844
  };
1575
1845
  }
1846
+ /** The sync keys this deployment holds, as its last registration said: null before one has. */
1847
+ let held = null;
1848
+ /** Who holds each of its sync's keys that it doesn't, as people read it: `production`, or `support (production)`. */
1849
+ const holders = /* @__PURE__ */ new Map();
1850
+ /**
1851
+ * What this deployment's registration says it holds: the keys in its `sync`. Vercel's API says who holds each of
1852
+ * the rest, another of its project's deployments (production takes a key from a preview), which is said once each.
1853
+ * An API from before each project had its own keys says none, and holds every key it lists.
1854
+ */
1855
+ async function holding(made) {
1856
+ held = new Set((made.sync ?? []).map((entry) => entry.key));
1857
+ const mine = principalFrom(made.owner);
1858
+ for (const { key, owner, environment } of made.elsewhere ?? []) {
1859
+ const holder = principalFrom(owner);
1860
+ let shown = owner;
1861
+ if (holder?.type === "project") {
1862
+ const where = environment ?? holder.environment;
1863
+ shown = mine?.type === "project" && mine.projectId === holder.projectId ? where : `${await projectName(deployment, holder.projectId)} (${where})`;
1864
+ }
1865
+ if (holders.get(key) !== shown) console.info(`[board] ${key} is synced by ${shown}`);
1866
+ holders.set(key, shown);
1867
+ }
1868
+ }
1869
+ /**
1870
+ * Whether this deployment holds its sync's key `key`, as its last registration said: another of its project's
1871
+ * deployments may. Before one has said, it registers as on its first use; until one can, it holds every key, and
1872
+ * the API decides.
1873
+ */
1874
+ async function holds(key) {
1875
+ if (!binding?.sync.some((entry) => entry.key === key)) return true;
1876
+ if (held === null && await isDeployment().catch(() => false)) await runner.start();
1877
+ return held === null || held.has(key);
1878
+ }
1879
+ /** A write through a key another deployment holds: its holder imports and delivers through it. */
1880
+ const notHeld = (key) => notFound(`${key} is synced by ${holders.get(key) ?? "another deployment of this project"}, not this deployment`, "not_synced_here");
1881
+ /**
1882
+ * A sync call through key `key`: `unheld` answers it here, asking the API nothing, once another deployment holds
1883
+ * it. One may have taken it since this one registered: the API refuses the call, and registering again says so.
1884
+ */
1885
+ async function throughKey(key, unheld, call) {
1886
+ if (!await holds(key)) return unheld();
1887
+ try {
1888
+ return await call();
1889
+ } catch (error) {
1890
+ if (error instanceof HttpError && error.status === 403 && !await holds(key)) return unheld();
1891
+ throw error;
1892
+ }
1893
+ }
1576
1894
  /** A match as vboard hands it out: its event as `vb tail --json` prints it, with its message as it is now. */
1577
1895
  async function matchOf(who, match, filters) {
1578
1896
  const found = await messageById(who, match.event.messageId).catch((error) => {
@@ -1581,7 +1899,7 @@ function createVercel(options, environment) {
1581
1899
  });
1582
1900
  const channel = found && await channelById(who, found.thread.channelId);
1583
1901
  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);
1902
+ 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
1903
  if (!event?.message) return null;
1586
1904
  const handed = match.watcher === "@sync" && event.type === "labels.changed" ? {
1587
1905
  ...event,
@@ -1599,10 +1917,13 @@ function createVercel(options, environment) {
1599
1917
  event: handed
1600
1918
  };
1601
1919
  }
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. */
1920
+ /**
1921
+ * A thread bound to a target, as the event that has the sync owning its key backfill a channel: about the thread's
1922
+ * root. Another project's binding is that project's sync's, and one that names no project is this one's.
1923
+ */
1603
1924
  async function syncedOf(who, match, root, channel) {
1604
1925
  const { binding } = match.event;
1605
- if (!binding) return null;
1926
+ if (!binding || binding.projectId !== void 0 && binding.projectId !== await ownProject(who)) return null;
1606
1927
  const message = await view(who, root, channel);
1607
1928
  return boardEvent(who, match.event, match.id, "thread.synced", {
1608
1929
  thread: message.thread,
@@ -1652,7 +1973,7 @@ function createVercel(options, environment) {
1652
1973
  const runner = registrant({
1653
1974
  remote: "Vercel's API",
1654
1975
  registry: {
1655
- register: (where) => registerAs(deployment, where, tails, bound().sync, true).catch((error) => {
1976
+ register: (where) => registerAs(deployment, where, tails, bound().sync, true, holding).catch((error) => {
1656
1977
  if (error instanceof HttpError && error.code === "watchers_need_project") {
1657
1978
  refused = true;
1658
1979
  runner.close();
@@ -1749,11 +2070,6 @@ function createVercel(options, environment) {
1749
2070
  });
1750
2071
  /** An import as the API takes it: a channel by its ID, and a reply's `after` as its sequence in the thread. */
1751
2072
  async function importBody(who, body) {
1752
- if (body.op === "seen") return {
1753
- op: "seen",
1754
- operationId: operationId(),
1755
- author: platformUser(body.author)
1756
- };
1757
2073
  const base = {
1758
2074
  op: body.op,
1759
2075
  operationId: operationId(),
@@ -1761,7 +2077,6 @@ function createVercel(options, environment) {
1761
2077
  ...body.from !== void 0 ? { from: body.from } : {}
1762
2078
  };
1763
2079
  if (body.op === "post") {
1764
- if (body.attachments?.length) throw notSupported("files on imports");
1765
2080
  let after;
1766
2081
  if (body.after !== void 0) {
1767
2082
  const at = locate(body.after);
@@ -1778,6 +2093,7 @@ function createVercel(options, environment) {
1778
2093
  text: body.text,
1779
2094
  ...body.labels && Object.keys(body.labels).length ? { labels: body.labels } : {},
1780
2095
  ...body.noSync ? { noSync: true } : {},
2096
+ ...body.attachments?.length ? { attachments: body.attachments } : {},
1781
2097
  ...body.links?.length ? { links: body.links } : {},
1782
2098
  ...body.id !== void 0 ? { id: body.id } : {},
1783
2099
  ...after !== void 0 ? { after } : {}
@@ -1866,14 +2182,22 @@ function createVercel(options, environment) {
1866
2182
  };
1867
2183
  },
1868
2184
  async me(caller) {
1869
- const found = await api(whoOf(caller), "GET", "/me");
2185
+ const who = whoOf(caller);
2186
+ const found = await api(who, "GET", await onBoard(who, "/me"));
1870
2187
  const { view: named } = found;
1871
- const shown = named ? {
2188
+ const { principal } = found.actor;
2189
+ const project = principal.type === "project" ? (named ? projectNamesOf([[found.actor.id, named]]).get(principal.projectId) : void 0) ?? await namedProject(who, principal.projectId) : void 0;
2190
+ const shown = principal.type === "project" && !found.actor.profile ? {
2191
+ kind: "deployment",
2192
+ ...deploymentNamed(principal, project),
2193
+ avatar: named?.avatar ?? null
2194
+ } : named ? {
1872
2195
  kind: apiKind(named.kind),
1873
2196
  handle: named.handle,
1874
2197
  name: named.name ?? named.handle,
1875
2198
  avatar: named.avatar ?? null
1876
- } : actorView(found.actor);
2199
+ } : actorView(found.actor, void 0, project);
2200
+ const via = found.actor.profile && principal.type !== "external" ? { via: viaFor(principal, named, project) } : {};
1877
2201
  return {
1878
2202
  actor: found.actor.id,
1879
2203
  principal: principalId(found.actor.principal),
@@ -1882,6 +2206,7 @@ function createVercel(options, environment) {
1882
2206
  name: shown.name,
1883
2207
  avatar: shown.avatar,
1884
2208
  profile: found.actor.profile?.name ?? null,
2209
+ ...via,
1885
2210
  session: found.actor.session ?? null,
1886
2211
  expiresAt: expiryOf(found.expiresAt),
1887
2212
  can: canOf(found.can)
@@ -1905,14 +2230,27 @@ function createVercel(options, environment) {
1905
2230
  },
1906
2231
  async actors(caller, _input, signal) {
1907
2232
  const who = whoOf(caller);
2233
+ const views = await all(who, await onBoard(who, "/actors"), "actors", {}, signal);
2234
+ const names = projectNamesOf(views.map((view) => [view.id, view]));
1908
2235
  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
- })),
2236
+ actors: views.map((actor) => {
2237
+ const { profile } = actorParts(actor.id);
2238
+ const owner = principalFrom(actor.id);
2239
+ const project = owner?.type === "project" ? names.get(owner.projectId) : void 0;
2240
+ const principal = profile === null ? null : owner;
2241
+ const user = platformProfile(profile);
2242
+ const deployment = profile === null && owner?.type === "project" ? deploymentNamed(owner, project) : null;
2243
+ return {
2244
+ id: actor.id,
2245
+ kind: apiKind(actor.kind),
2246
+ handle: deployment?.handle ?? (principal && user ? importedHandleOf(actor.handle, principal, actor, user.user, project) : actor.handle),
2247
+ name: deployment?.name ?? actor.name ?? actor.handle,
2248
+ avatar: actor.avatar ?? null,
2249
+ ...principal ? { via: viaFor(principal, actor, project) } : {},
2250
+ ...actor.platform ? { platform: actor.platform } : {},
2251
+ verified: true
2252
+ };
2253
+ }),
1916
2254
  cursor: cursorOf({
1917
2255
  t: Date.now(),
1918
2256
  feeds: {}
@@ -2031,7 +2369,6 @@ function createVercel(options, environment) {
2031
2369
  },
2032
2370
  async upload(caller, { data, name, type }) {
2033
2371
  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
2372
  if (data.byteLength === 0) throw new HttpError(400, "bad_request", "the file is empty");
2036
2373
  if (data.byteLength > 26214400) throw new HttpError(413, "too_large", `attachments are at most ${IMPORT_BYTES_MAX / 1024 / 1024} MB`);
2037
2374
  const bytes = new Uint8Array(data);
@@ -2264,8 +2601,7 @@ function createVercel(options, environment) {
2264
2601
  },
2265
2602
  async tokens(caller, _input, signal) {
2266
2603
  const who = whoOf(caller);
2267
- const { tokens } = await api(who, "GET", await onBoard(who, "/tokens"), signal ? { signal } : {});
2268
- return { tokens: tokens.map(tokenFrom) };
2604
+ return { tokens: (await all(who, await onBoard(who, "/tokens"), "tokens", {}, signal)).map(tokenFrom) };
2269
2605
  },
2270
2606
  async createToken(caller, input, signal) {
2271
2607
  const who = whoOf(caller);
@@ -2288,6 +2624,33 @@ function createVercel(options, environment) {
2288
2624
  ...signal ? { signal } : {}
2289
2625
  });
2290
2626
  },
2627
+ async schemas(caller, _input, signal) {
2628
+ const schemas = (await all(whoOf(caller), "/schemas", "schemas", {}, signal)).map(schemaFrom);
2629
+ const order = (schema) => schema.builtIn ? 0 : 1;
2630
+ 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)) };
2631
+ },
2632
+ async schema(caller, { id }, signal) {
2633
+ const { schema } = await api(whoOf(caller), "GET", `/schemas/${encodeURIComponent(id)}`, signal ? { signal } : {});
2634
+ return { schema: schemaFrom(schema) };
2635
+ },
2636
+ async createSchema(caller, input, signal) {
2637
+ const who = whoOf(caller);
2638
+ const there = await api(who, "GET", `/schemas/${encodeURIComponent(schemaId(input.name, input.version))}`, signal ? { signal } : {}).then(() => true, (error) => {
2639
+ if (error instanceof HttpError && error.code === "schema_not_found") return false;
2640
+ throw error;
2641
+ });
2642
+ const { schema } = await api(who, "POST", "/schemas", {
2643
+ body: {
2644
+ operationId: operationId(),
2645
+ ...input
2646
+ },
2647
+ ...signal ? { signal } : {}
2648
+ });
2649
+ return {
2650
+ schema: schemaFrom(schema),
2651
+ created: !there
2652
+ };
2653
+ },
2291
2654
  async schedule(caller, input, signal) {
2292
2655
  if (input.attachments?.length) throw notSupported("files on scheduled messages");
2293
2656
  const who = whoOf(caller);
@@ -2367,20 +2730,26 @@ function createVercel(options, environment) {
2367
2730
  },
2368
2731
  async syncImport(caller, body, signal) {
2369
2732
  const who = whoOf(caller);
2370
- return { message: (await syncApi(who, "POST", await onBoard(who, "/sync/imports"), {
2733
+ const key = body.from ?? body.author.id.split(":")[0];
2734
+ return { message: (await throughKey(key, () => {
2735
+ throw notHeld(key);
2736
+ }, async () => syncApi(who, "POST", await onBoard(who, "/sync/imports"), {
2371
2737
  body: await importBody(who, body),
2372
2738
  signal
2373
- }).catch((error) => {
2739
+ })).catch((error) => {
2374
2740
  if (error instanceof HttpError && error.code === "newer_message" && body.op === "post") throw new HttpError(409, "newer_message", `a message came after ${body.after}`);
2375
2741
  throw error;
2376
2742
  })).message };
2377
2743
  },
2378
2744
  async syncReceipt(caller, body, signal) {
2379
2745
  const who = whoOf(caller);
2380
- return syncApi(who, "POST", await onBoard(who, "/sync/receipts"), {
2746
+ const key = body.target.split(":")[0];
2747
+ return throughKey(key, () => {
2748
+ throw notHeld(key);
2749
+ }, async () => syncApi(who, "POST", await onBoard(who, "/sync/receipts"), {
2381
2750
  body,
2382
2751
  signal
2383
- });
2752
+ }));
2384
2753
  },
2385
2754
  async syncFind(caller, query, signal) {
2386
2755
  const who = whoOf(caller);
@@ -2412,10 +2781,28 @@ function createVercel(options, environment) {
2412
2781
  const who = whoOf(caller);
2413
2782
  if (!locate(id)) throw notFound(`message not found: ${id}`, "message_not_found");
2414
2783
  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
- }))) };
2784
+ const own = await ownProject(who);
2785
+ const foreign = (projectId) => projectId !== void 0 && projectId !== own;
2786
+ const others = [...new Set(targets.flatMap(({ projectId }) => foreign(projectId) ? [projectId] : []))];
2787
+ const names = others.length ? await projectNames(who, {
2788
+ key: others.join(" "),
2789
+ found: (names) => others.every((id) => names.has(id))
2790
+ }) : /* @__PURE__ */ new Map();
2791
+ return { targets: await Promise.all(targets.map(async ({ projectId, ...target }) => {
2792
+ if (foreign(projectId)) {
2793
+ const key = `${names.get(projectId) ?? projectId}/${target.key}`;
2794
+ return {
2795
+ ...target,
2796
+ key,
2797
+ target: `${key}${target.target.slice(target.key.length)}`,
2798
+ url: null
2799
+ };
2800
+ }
2801
+ return {
2802
+ ...target,
2803
+ url: binding && target.thread !== null && target.message !== null ? await binding.linkOf(target.key, target.thread, target.message) : null
2804
+ };
2805
+ })) };
2419
2806
  },
2420
2807
  async linked(caller, { url }, signal) {
2421
2808
  const who = whoOf(caller);
@@ -2440,23 +2827,24 @@ function createVercel(options, environment) {
2440
2827
  },
2441
2828
  async inboxPush(caller, { key, events }, signal) {
2442
2829
  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
- })) },
2830
+ const body = { events: events.map(({ id, event, raw }) => ({
2831
+ id,
2832
+ thread: event.thread,
2833
+ event,
2834
+ ...raw !== void 0 ? { raw } : {}
2835
+ })) };
2836
+ await throughKey(key, () => null, async () => syncApi(who, "POST", await inboxPath(who, key), {
2837
+ body,
2450
2838
  signal
2451
- });
2839
+ }));
2452
2840
  return { ok: true };
2453
2841
  },
2454
2842
  async inboxNext(caller, { key, limit }, signal) {
2455
2843
  const who = whoOf(caller);
2456
- const { items } = await syncApi(who, "GET", await inboxPath(who, key, "/next"), {
2844
+ const { items } = await throughKey(key, () => ({ items: [] }), async () => syncApi(who, "GET", await inboxPath(who, key, "/next"), {
2457
2845
  query: { limit: limit?.toString() },
2458
2846
  signal
2459
- });
2847
+ }));
2460
2848
  return { items: items.map(({ raw, ...item }) => ({
2461
2849
  ...item,
2462
2850
  key,
@@ -2465,22 +2853,22 @@ function createVercel(options, environment) {
2465
2853
  },
2466
2854
  async inboxAck(caller, { key, id, lease, error }, signal) {
2467
2855
  const who = whoOf(caller);
2468
- await syncApi(who, "POST", await inboxPath(who, key, `/${encodeURIComponent(id)}/ack`), {
2856
+ await throughKey(key, () => null, async () => syncApi(who, "POST", await inboxPath(who, key, `/${encodeURIComponent(id)}/ack`), {
2469
2857
  body: {
2470
2858
  lease,
2471
2859
  ...error !== void 0 ? { error } : {}
2472
2860
  },
2473
2861
  signal
2474
- });
2862
+ }));
2475
2863
  return { ok: true };
2476
2864
  },
2477
2865
  async inbox(caller, { key, channel, limit }, signal) {
2478
2866
  const who = whoOf(caller);
2479
2867
  const wanted = Math.min(limit ?? 50, INBOX_LIST_MAX);
2480
- const { events } = await syncApi(who, "GET", await inboxPath(who, key), {
2868
+ const { events } = await throughKey(key, () => ({ events: [] }), async () => syncApi(who, "GET", await inboxPath(who, key), {
2481
2869
  query: { limit: String(channel === void 0 ? wanted : INBOX_LIST_MAX) },
2482
2870
  signal
2483
- });
2871
+ }));
2484
2872
  const entries = events.flatMap(({ id, createdAt, event, raw }) => event ? [{
2485
2873
  id,
2486
2874
  channel: typeof event.channel === "string" ? event.channel : "",
@@ -2529,6 +2917,7 @@ function createVercel(options, environment) {
2529
2917
  routes,
2530
2918
  keeps: false,
2531
2919
  sendsSchedulesHere: false,
2920
+ syncedHere: holds,
2532
2921
  bind(next) {
2533
2922
  if (binding) throw new Error("vercel: this backend already serves a board: create one vercel() per board()");
2534
2923
  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`);
@@ -2823,10 +3212,6 @@ const CREATED = /* @__PURE__ */ new Set([
2823
3212
  "upload",
2824
3213
  "uploadFinish"
2825
3214
  ]);
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
3215
  /** Shown inline only when a browser can't run it: everything else downloads. */
2831
3216
  const INLINE = /^(image\/(png|jpeg|gif|webp|avif)|video\/(mp4|webm)|text\/plain)$/;
2832
3217
  /**
@@ -2857,13 +3242,15 @@ async function inputOf(name, request, url, params) {
2857
3242
  case "actors":
2858
3243
  case "watchers":
2859
3244
  case "grants":
2860
- case "tokens": return {};
3245
+ case "tokens":
3246
+ case "schemas": return {};
2861
3247
  case "message":
2862
3248
  case "posted":
2863
3249
  case "synced":
2864
3250
  case "cancelSchedule":
2865
3251
  case "revokeGrant":
2866
3252
  case "revokeToken":
3253
+ case "schema":
2867
3254
  case "attachment":
2868
3255
  case "uploadFinish": return { id };
2869
3256
  case "messages": return MessagesQuery.parse(queryObject(url));
@@ -2886,6 +3273,7 @@ async function inputOf(name, request, url, params) {
2886
3273
  };
2887
3274
  case "explain": return ExplainQuery.parse(queryObject(url));
2888
3275
  case "createToken": return TokenBody.parse(await body());
3276
+ case "createSchema": return SchemaBody.parse(await body());
2889
3277
  case "register": return RegisterBody.parse(await body());
2890
3278
  case "edit": return {
2891
3279
  id,
@@ -2959,14 +3347,24 @@ async function inputOf(name, request, url, params) {
2959
3347
  case "linked": return LinkedQuery.parse(queryObject(url));
2960
3348
  }
2961
3349
  }
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
- });
3350
+ /**
3351
+ * A platform user an import by `importer` is by, as the board records them: themselves for the
3352
+ * board's own sync on a board that keeps its log here, which checked them, and a profile of
3353
+ * anyone else's principal, whose word they are, under its name.
3354
+ */
3355
+ const externalActor = (author, importer) => {
3356
+ const own = importer.principal === SYNC_ACTOR;
3357
+ return {
3358
+ id: own ? author.id : `${importer.principal}+${author.id}`,
3359
+ kind: "external",
3360
+ handle: own ? author.handle : importedHandle(viaOf({
3361
+ id: importer.principal,
3362
+ handle: importer.actor.handle
3363
+ }).name, author.handle, userIdOf(author.id)),
3364
+ name: author.name,
3365
+ avatar: author.avatar
3366
+ };
3367
+ };
2970
3368
  /** 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
3369
  function sourceOf(caller) {
2972
3370
  const via = caller.origin.via;
@@ -3022,54 +3420,6 @@ async function createServe(context) {
3022
3420
  */
3023
3421
  const servesOnly = () => new HttpError(404, "not_found", `${ownUrl() ?? "this board"} answers ${backend.routes.length > 0 || engine ? "only wake-ups and webhooks" : "nothing itself"}`);
3024
3422
  /**
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
3423
  * A sync target as the board that syncs it resolves it. One for an entry this board doesn't
3074
3424
  * have goes on as it is, for the sync that does, unless this board syncs: then it's a mistake.
3075
3425
  */
@@ -3084,9 +3434,9 @@ async function createServe(context) {
3084
3434
  }
3085
3435
  /**
3086
3436
  * 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.
3437
+ * it before it does anything for them past calling the backend (a platform call, sync's own write,
3438
+ * reading an upload, the middleware), so a caller it won't let in starts none of it. Null for this
3439
+ * deployment's own code, which may do everything.
3090
3440
  */
3091
3441
  const accessOf = (caller) => "identity" in caller ? caller.identity.principal.access : null;
3092
3442
  /**
@@ -3135,6 +3485,47 @@ async function createServe(context) {
3135
3485
  }
3136
3486
  return found;
3137
3487
  }
3488
+ /** The schemas writes have named, as the backend answered them: a version never changes, so each is read once. */
3489
+ const definitions = /* @__PURE__ */ new Map();
3490
+ /**
3491
+ * Checks the blocks `text` carries before it's written, each against the schema its fence names:
3492
+ * a 400 for one that isn't a JSON object, names a schema the board doesn't have, or doesn't match
3493
+ * it. So what a message written on the board shows as its `blocks` always matches. The check is
3494
+ * board()'s, so it reads each schema as board() itself, whoever is writing: every caller's write
3495
+ * is held to the same definition, and gets the same answer.
3496
+ */
3497
+ async function checkBlocks(text) {
3498
+ if (!text.includes("json#")) return;
3499
+ for (const found of findBlocks(text)) {
3500
+ if (found.problem !== void 0) throw badRequest(found.problem, "invalid_block");
3501
+ let definition = definitions.get(found.id);
3502
+ if (!definition) {
3503
+ definition = backend.schema(OWN, { id: found.id }, new AbortController().signal).then(({ schema }) => schema.schema);
3504
+ definitions.set(found.id, definition);
3505
+ definition.catch(() => definitions.delete(found.id));
3506
+ }
3507
+ const schema = await definition.catch((error) => {
3508
+ if (error instanceof HttpError && error.status === 404) throw badRequest(`the ${found.id} block names a schema this board doesn't have`, "schema_not_found");
3509
+ throw error;
3510
+ });
3511
+ const problem = checkValue(schema, found.data);
3512
+ if (problem !== null) throw badRequest(`the ${found.id} block doesn't match its schema: ${problem}`, "invalid_block");
3513
+ }
3514
+ }
3515
+ /**
3516
+ * Checks a write's blocks, unless board() already knows its caller may not post where it lands:
3517
+ * then the backend's refusal is the answer, not what the text says. A message board() can't find
3518
+ * for the caller is still checked, since one written without reading is its author's to edit.
3519
+ */
3520
+ async function checkWrite(caller, text, where, signal) {
3521
+ if (!text.includes("json#")) return;
3522
+ const access = accessOf(caller);
3523
+ if (access !== null) {
3524
+ const channel = "channel" in where ? where.channel : (await lookup(caller, where.message, signal))?.channel;
3525
+ if (channel !== void 0 && !access.can("post", channel)) return;
3526
+ }
3527
+ await checkBlocks(text);
3528
+ }
3138
3529
  let middlewareBoard = null;
3139
3530
  /** Runs the middleware on a write, then `commit`s what it passed on: a `DroppedError` when it drops it. */
3140
3531
  const screen = (write, author, source, commit) => runMiddleware(middleware, {
@@ -3213,11 +3604,14 @@ async function createServe(context) {
3213
3604
  ...labels ? { labels } : {},
3214
3605
  ...noSync !== void 0 ? { noSync } : {},
3215
3606
  ...attachments ? { attachments } : {}
3216
- }, signal, (screened) => backend.schedule(caller, {
3217
- ...input,
3218
- text: screened.text,
3219
- ...screened.labels ? { labels: screened.labels } : {}
3220
- }, signal));
3607
+ }, signal, async (screened) => {
3608
+ if (screened.text !== text) await checkBlocks(screened.text);
3609
+ return backend.schedule(caller, {
3610
+ ...input,
3611
+ text: screened.text,
3612
+ ...screened.labels ? { labels: screened.labels } : {}
3613
+ }, signal);
3614
+ });
3221
3615
  }
3222
3616
  /**
3223
3617
  * The caller's own message, still there, where it may post: what an edit of it changes. One it
@@ -3288,7 +3682,12 @@ async function createServe(context) {
3288
3682
  * the platform. A retry of one that landed stands.
3289
3683
  */
3290
3684
  async function syncImport(caller, body, signal) {
3291
- const send = (patched) => backend.syncImport(caller, patched, signal);
3685
+ const written = (body.op === "post" || body.op === "edit") && body.from === null ? body.text : null;
3686
+ if (written !== null) await checkBlocks(written);
3687
+ const send = async (patched) => {
3688
+ if (written !== null && (patched.op === "post" || patched.op === "edit") && patched.text !== written) await checkBlocks(patched.text);
3689
+ return backend.syncImport(caller, patched, signal);
3690
+ };
3292
3691
  if (middleware.length === 0 || caller.origin.via?.kind === "middleware" || body.op !== "post" && body.op !== "edit") return send(body);
3293
3692
  const access = accessOf(caller);
3294
3693
  if (access && (!access.anywhere("sync") || "identity" in caller && caller.identity.principal.scope !== void 0)) return send(body);
@@ -3317,6 +3716,7 @@ async function createServe(context) {
3317
3716
  const source = await importSource(caller, body, null, signal);
3318
3717
  if (!source) return send(body);
3319
3718
  const attachments = await attachmentsOf(caller, body.attachments, signal);
3719
+ const author = externalActor(body.author, await whoIs(caller, signal));
3320
3720
  return dropped(async () => screen({
3321
3721
  kind: "post",
3322
3722
  channel,
@@ -3324,7 +3724,7 @@ async function createServe(context) {
3324
3724
  text: body.text,
3325
3725
  labels: body.labels ?? {},
3326
3726
  attachments
3327
- }, externalActor(body.author), source, async (write) => send({
3727
+ }, author, source, async (write) => send({
3328
3728
  ...body,
3329
3729
  text: write.text,
3330
3730
  labels: write.labels
@@ -3332,7 +3732,9 @@ async function createServe(context) {
3332
3732
  }
3333
3733
  if (body.origin === void 0 === (body.message === void 0)) return send(body);
3334
3734
  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);
3735
+ const author = externalActor(body.author, await whoIs(caller, signal));
3736
+ const own = found !== null && (found.by.actor === author.id || found.by.actor === body.author.id);
3737
+ if (!found || found.deleted || access && !access.can("sync", found.channel) || body.message !== void 0 && !own) return send(body);
3336
3738
  const source = await importSource(caller, body, found, signal);
3337
3739
  if (!source) return send(body);
3338
3740
  return dropped(async () => screen({
@@ -3341,7 +3743,7 @@ async function createServe(context) {
3341
3743
  channel: found.channel,
3342
3744
  re: found.re,
3343
3745
  text: body.text
3344
- }, externalActor(body.author), source, async (write) => send({
3746
+ }, author, source, async (write) => send({
3345
3747
  ...body,
3346
3748
  text: write.text
3347
3749
  })));
@@ -3356,35 +3758,24 @@ async function createServe(context) {
3356
3758
  throw error;
3357
3759
  }
3358
3760
  }
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
- */
3761
+ /** A post, with the targets it names resolved once the caller may post and sync there, through the middleware. */
3363
3762
  async function post(caller, input, signal) {
3364
- const send = (poster, body) => screenPost(poster, body, signal, (patched) => backend.post(poster, patched, signal));
3763
+ await checkWrite(caller, input.text, input.channel !== void 0 ? { channel: input.channel } : { message: input.re }, signal);
3764
+ const send = (poster, body) => screenPost(poster, body, signal, async (patched) => {
3765
+ if (patched.text !== input.text) await checkBlocks(patched.text);
3766
+ return backend.post(poster, patched, signal);
3767
+ });
3365
3768
  if (!engine) return send(caller, input.sync?.length ? {
3366
3769
  ...input,
3367
3770
  sync: await Promise.all(input.sync.map(resolveTarget))
3368
3771
  } : input);
3369
- const allowed = (input.sync?.length ?? 0) > 0 || mentionsEmails(input.text) ? await mayPost(caller, input, signal) : null;
3772
+ const allowed = input.sync?.length ? await mayPost(caller, input, signal) : null;
3370
3773
  if (!allowed) return send(caller, input);
3371
3774
  const { access, channel } = allowed;
3372
- const body = input.re === void 0 && (input.sync?.length ?? 0) > 0 && (access === null || access.can("sync", channel)) ? {
3775
+ return send(caller, input.re === void 0 && (access === null || access.can("sync", channel)) ? {
3373
3776
  ...input,
3374
3777
  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;
3778
+ } : input);
3388
3779
  }
3389
3780
  /**
3390
3781
  * An import's answer, as a sync callback's client gets it: the message it wrote or changed, or the
@@ -3422,7 +3813,7 @@ async function createServe(context) {
3422
3813
  author,
3423
3814
  from: null,
3424
3815
  message: id,
3425
- text: await withEmails(text),
3816
+ text,
3426
3817
  source,
3427
3818
  ...revision !== void 0 ? { revision } : {}
3428
3819
  });
@@ -3489,7 +3880,7 @@ async function createServe(context) {
3489
3880
  thread: via.thread
3490
3881
  },
3491
3882
  ...input.channel !== void 0 ? { channel: input.channel } : { re: input.re },
3492
- text: await withEmails(input.text),
3883
+ text: input.text,
3493
3884
  ...input.labels ? { labels: input.labels } : {},
3494
3885
  ...input.noSync ? { noSync: true } : {},
3495
3886
  ...input.attachments?.length ? { attachments: input.attachments } : {},
@@ -3505,39 +3896,23 @@ async function createServe(context) {
3505
3896
  }, signal);
3506
3897
  return { message: await read(message) };
3507
3898
  }
3508
- /** The protocol method `name`, as board() serves it: what it posts and edits, and the filters it reads by, with their emails resolved. */
3899
+ /** The protocol method `name`, as board() serves it: what it posts, edits, and imports goes through the middleware. */
3509
3900
  async function invoke(name, caller, input, signal) {
3510
- if (name === "messages" || name === "threads" || name === "events") input = await withMentioned(caller, input);
3511
3901
  switch (name) {
3512
3902
  case "post": return post(caller, input, signal);
3513
3903
  case "edit": {
3514
3904
  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)
3905
+ await checkWrite(caller, edit.text, { message: edit.id }, signal);
3906
+ return screenEdit(caller, edit, signal, async (patched) => {
3907
+ if (patched.text !== edit.text) await checkBlocks(patched.text);
3908
+ return backend.edit(caller, patched, signal);
3520
3909
  });
3521
3910
  }
3522
3911
  case "syncImport": return syncImport(caller, input, signal);
3523
3912
  case "schedule": {
3524
3913
  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;
3914
+ await checkWrite(caller, body.text, body.channel !== void 0 ? { channel: body.channel } : { message: body.re }, signal);
3915
+ return backend.sendsSchedulesHere === false ? screenSchedule(caller, body, signal) : backend.schedule(caller, body, signal);
3541
3916
  }
3542
3917
  case "inbox": {
3543
3918
  const query = input;
@@ -3596,7 +3971,8 @@ async function createServe(context) {
3596
3971
  respond: platform.respond
3597
3972
  },
3598
3973
  origin: { via: platform.via }
3599
- }, trigger)
3974
+ }, trigger),
3975
+ syncedHere: async (key) => backend.syncedHere ? backend.syncedHere(key) : true
3600
3976
  });
3601
3977
  /**
3602
3978
  * Server-sent events, from the backend's long-poll: each event's `id` is its cursor, so
@@ -3712,7 +4088,7 @@ async function createServe(context) {
3712
4088
  const caller = own ?? await callerOf(asked);
3713
4089
  if (target.kind === "board") return await serve(target.name, caller, request, url, match.params);
3714
4090
  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);
4091
+ if (target.name === "events" && (request.headers.get("accept") ?? "").includes("text/event-stream")) return await sse(caller, input, request, asked ? () => callerOf(asked) : null);
3716
4092
  const output = injected && "platform" in injected ? await asPlatform(target.name, injected, input, request.signal) : await invoke(target.name, caller, input, request.signal);
3717
4093
  if (target.name === "attachment") return attachmentResponse(output);
3718
4094
  const made = CREATED.has(target.name) || target.name === "createChannel" && output.created;