@vercel/board 0.38.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-BkQlF1LQ.d.mts → backend-BW5NbBsp.d.mts} +37 -11
  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-qJF96jZI.mjs → conformance-BWhZ0k8T.mjs} +256 -13
  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-BsfcChdp.mjs → exports-C2OWIbLU.mjs} +639 -258
  29. package/dist/exports-FyRBIAMs.d.mts +4 -0
  30. package/dist/{index-DpVyZa9b.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-DtCbBtOW.mjs → inspect-cGcP8ZO9.mjs} +4 -4
  39. package/dist/{local-Bo3XzEKB.mjs → local-CsleYuyM.mjs} +664 -752
  40. package/dist/{main-0nvLgajF.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-B4Uikw0J.mjs → origin-DLCmrwmE.mjs} +47 -39
  45. package/dist/{page-UsfvSIWc.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-D7I3KisQ.mjs → serve-Cs-e0Jke.mjs} +4 -4
  52. package/dist/{server-Cc3nYq3H.mjs → server-CIfMdIt3.mjs} +43 -98
  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 +7 -5
  65. package/docs/01-board/03-identity.md +71 -39
  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 +10 -14
  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 +25 -22
  72. package/docs/02-sync/01-overview.md +72 -7
  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 +157 -31
  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-DAxy9Ula.mjs +0 -4
  83. package/dist/exports-BJ3wmEMY.d.mts +0 -4
  84. package/dist/inspect-5mkjJYMS.mjs +0 -2
  85. package/dist/page-R0RoE_gM.mjs +0 -2
@@ -1,24 +1,22 @@
1
- import { a as forbidden$1, c as toErrorResponse, f as duration, g as fileName, h as IMPORT_BYTES_MAX, i as duplicateId, l as unauthorized, m as DIRECT_UPLOAD_BYTES_MAX, 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$1, c as toErrorResponse, f as duration, g as fileName, h as IMPORT_BYTES_MAX, i as duplicateId, l as unauthorized, m as DIRECT_UPLOAD_BYTES_MAX, 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 { _ as actorKind, a as CAN_MAX, c as Handle, d as Labels, g as SeenActorKind, h as RemoteWatcherId, i as Author, l as LabelKey, m as MessageText, n as Attachment, o as ChannelPath, p as MessageId, s as Emoji, t as ActorId, v as platformAvatar, y as storable } from "./schemas-AZkxk06N.mjs";
3
3
  import { a as Link, i as ExternalTarget, n as ExternalEvent, o as Origin } from "./external-CHDxWIVf.mjs";
4
- import { a as runMatch, g as VERSION, h as SYNC, i as canonicalWatchers, l as METHODS, n as syncTarget, o as compileWatcher, r as withEmailMentions, s as hasCriteria } from "./targets-B4Uikw0J.mjs";
5
- import { a as waitUntil, c as isKeyIdOf, n as MIDDLEWARE_ACTOR, s as derivedId, t as DroppedError } from "./middleware-CPqAuRtp.mjs";
6
- import { a as canText, c as compileAccess, i as authorize, o as checkGrantChange, t as FULL_ACCESS, u as parseCan } from "./access-CVkjSfxj.mjs";
7
- import { C as workflowPath, c as checkGrant, f as grantIssuers, h as joined, l as checkPrincipal, m as issuerName, n as DEFAULT_CAN, o as authenticates, r as GITHUB_ISSUER, s as checkCan, t as BOARD_TOKEN_PREFIX, v as removes, w as wroteAs, y as tokenHash } from "./auth-B3bBYOqf.mjs";
4
+ import { a as SCHEMA_DESCRIPTION_MAX, c as canonical, d as parseSchemaId, f as schemaId, i as BUILT_IN_SCHEMAS, l as checkDefinition, n as blocksIn, o as SCHEMA_NAME, s as SCHEMA_VERSION_MAX, u as isBuiltInName } from "./blocks-CVoBC7ur.mjs";
5
+ import { a as compileWatcher, c as METHODS, h as VERSION, i as runMatch, m as SYNC, n as syncTarget, o as hasCriteria, r as canonicalWatchers, t as SYNC_ACTOR } from "./origin-DLCmrwmE.mjs";
6
+ import { a as waitUntil, c as platformProfile, d as userIdOf, h as isKeyIdOf, l as shownName, m as derivedId, n as MIDDLEWARE_ACTOR, o as actorParts, s as importedHandle, t as DroppedError } from "./middleware-BF9vnPPS.mjs";
7
+ import { a as canText, c as compileAccess, i as authorize, o as checkGrantChange, t as FULL_ACCESS, u as parseCan } from "./access-Bl_k_Hpa.mjs";
8
+ import { C as workflowPath, c as checkGrant, f as grantIssuers, h as joined, l as checkPrincipal, m as issuerName, n as DEFAULT_CAN, o as authenticates, r as GITHUB_ISSUER, s as checkCan, t as BOARD_TOKEN_PREFIX, v as removes, w as wroteAs, y as tokenHash } from "./auth-C8URZHLx.mjs";
8
9
  import { n as setOwn, t as own } from "./own-OwgPWdmh.mjs";
9
- import { n as replaceMentions } from "./mentions-CB6ShY4R.mjs";
10
- import { a as resolveMentions, n as actorSeen } from "./actors-kfMejhaw.mjs";
10
+ import { a as viaOf, n as actorSeen } from "./actors-yBRWTpt5.mjs";
11
11
  import { C as sessionClearedError, a as SOCKET_TIMINGS, c as drainSettledHooks, d as nullProtoRecord, f as runtimeConsumerFactory, g as A2Error, h as stateTailReaders, i as RESERVED_PARTICIPANT_IDS, l as failedPreviousAttempt, m as serverInternals, n as POLL_TIMINGS, o as STATE_CACHE, p as runtimeConsumers, r as PRESENCE_TIMINGS, s as STREAM_TIMINGS, t as DRAIN_TIMINGS, u as markSchedulerSendFailure, v as NonRetriableError, x as isSessionCleared, y as asStoreUnavailable } from "./internal-CvsrprnU-CEPOUpAv.mjs";
12
12
  import { i as streamActivities, n as defaultSleep, t as createStreamActivity } from "./store-polling-BZt2Rf3D-oh3aU_An.mjs";
13
- import { a as foldActors, i as concernedMessageId, o as foldMessages, s as iso, t as TABLES_CONSUMER } from "./sql-l3ysn4O5.mjs";
13
+ import { a as foldActors, i as concernedMessageId, o as foldMessages, s as iso, t as TABLES_CONSUMER } from "./sql-Bv-RQu8n.mjs";
14
+ import { a as replaceMentions, i as mentionTerms, n as isEmail, r as mentionTerm, t as extractMentions } from "./mentions-CT2bN5eP.mjs";
14
15
  import { z } from "zod";
15
16
  import { createHash, randomBytes } from "node:crypto";
16
17
  import { mkdir, readFile, writeFile } from "node:fs/promises";
17
18
  import { dirname, join, resolve } from "node:path";
18
19
  import { AsyncLocalStorage } from "node:async_hooks";
19
- import { lookup } from "node:dns";
20
- import { request } from "node:https";
21
- import { BlockList, isIP } from "node:net";
22
20
  //#region ../../node_modules/.pnpm/experimental-a2@0.24.0_@upstash+qstash@2.12.0_@vercel+queue@0.7.0_ai@7.0.130_zod@4.6.5__b1e2c243a963f2620a5d202817417c26/node_modules/experimental-a2/dist/reducer-Bswr11ar.js
23
21
  /**
24
22
  * Run a Standard Schema validator, requiring a synchronous result.
@@ -3846,7 +3844,6 @@ const boardEvents = {
3846
3844
  thread: ThreadKey,
3847
3845
  labels: Labels,
3848
3846
  noSync: z.boolean(),
3849
- mentions: z.array(ActorId),
3850
3847
  by: Author,
3851
3848
  origin: Origin.nullable(),
3852
3849
  from: From,
@@ -3891,7 +3888,6 @@ const boardEvents = {
3891
3888
  id: MessageId,
3892
3889
  thread: ThreadKey,
3893
3890
  text: MessageText,
3894
- mentions: z.array(ActorId),
3895
3891
  by: Author,
3896
3892
  from: From
3897
3893
  }),
@@ -3972,10 +3968,26 @@ const boardEvents = {
3972
3968
  name: z.string().min(1).max(128).refine(storable, "name has a NUL character or a lone surrogate"),
3973
3969
  avatar: z.string().url().nullable(),
3974
3970
  /**
3971
+ * (server) Who an actor with a profile acts through, as the board shows it: its principal's name
3972
+ * (a deployment's project, anyone else's handle), and a deployment's environment.
3973
+ */
3974
+ via: z.object({
3975
+ name: Handle,
3976
+ environment: z.string().min(1).max(128).nullable()
3977
+ }).optional(),
3978
+ /** (server) A platform user's platform (`slack`), as their sync key was registered with: for display. */
3979
+ platform: z.string().min(1).max(64).optional(),
3980
+ /**
3975
3981
  * (server) A principal a host's `authenticate` made, or one of its profiles: someone the board
3976
3982
  * signs in, whatever its ID or kind, so sync never writes as it. Others have none.
3977
3983
  */
3978
- host: z.literal(true).optional()
3984
+ host: z.literal(true).optional(),
3985
+ /**
3986
+ * (server) Whether this write's credential named the actor as shown, rather than taking it from what
3987
+ * the caller sent: under the handle it gave the principal, as itself or after `via`. Unlike `host`,
3988
+ * each `actor.seen` says it anew. Others, and events from before, have none.
3989
+ */
3990
+ verified: z.literal(true).optional()
3979
3991
  })
3980
3992
  };
3981
3993
  const BOARD_SESSION = "board";
@@ -4159,7 +4171,11 @@ const ScheduleIdentity = z.object({
4159
4171
  kind: SeenActorKind,
4160
4172
  handle: Handle,
4161
4173
  name: z.string().min(1).max(128),
4162
- avatar: z.string().nullable()
4174
+ avatar: z.string().nullable(),
4175
+ via: z.object({
4176
+ name: Handle,
4177
+ environment: z.string().min(1).max(128).nullable()
4178
+ }).optional()
4163
4179
  })
4164
4180
  });
4165
4181
  /**
@@ -4335,6 +4351,23 @@ const accessContract = contract({
4335
4351
  }
4336
4352
  });
4337
4353
  const ACCESS_SESSION = "access";
4354
+ /**
4355
+ * The board's schema registry, outside the board log: one session, `schemas`. A version is
4356
+ * registered once and never changes, so its event is all there is of it.
4357
+ */
4358
+ const schemasContract = contract({
4359
+ name: "board-schemas",
4360
+ events: {
4361
+ /** A schema version, for good: `name@version` is its ID, and `schema` the JSON Schema the board checked. */
4362
+ "schema.created": z.object({
4363
+ name: z.string().regex(SCHEMA_NAME),
4364
+ version: z.number().int().min(1).max(SCHEMA_VERSION_MAX),
4365
+ description: z.string().min(1).max(SCHEMA_DESCRIPTION_MAX).nullable(),
4366
+ schema: z.record(z.string(), z.unknown()),
4367
+ by: ActorId
4368
+ }) }
4369
+ });
4370
+ const SCHEMAS_SESSION = "schemas";
4338
4371
  reducer({
4339
4372
  contract: boardContract,
4340
4373
  name: "board.messages.v5",
@@ -4390,16 +4423,34 @@ const HIDDEN = /* @__PURE__ */ new Set([
4390
4423
  "message.synced",
4391
4424
  "message.files_synced"
4392
4425
  ]);
4426
+ /** Whether the board checked who an actor is, as people see them, at their last write (`actor.seen`'s `verified`). */
4427
+ const verifiedRecord = (actor) => actor.verified === true;
4393
4428
  function actorView(actors, id) {
4394
4429
  const author = own(actors.byId, id);
4395
4430
  if (!author) return null;
4431
+ const via = viaOfRecord(author);
4396
4432
  return {
4397
4433
  kind: author.kind,
4398
4434
  handle: author.handle,
4399
4435
  name: author.name,
4400
- avatar: author.avatar
4436
+ avatar: author.avatar,
4437
+ ...via ? { via } : {},
4438
+ ...author.platform ? { platform: author.platform } : {},
4439
+ ...verifiedRecord(author) ? { verified: true } : {}
4401
4440
  };
4402
4441
  }
4442
+ /**
4443
+ * Who an actor with a profile acts through, as its record says. An agent recorded before records
4444
+ * said, whose handle is `<person>/<profile>`, acts through the person its handle names.
4445
+ */
4446
+ function viaOfRecord(actor) {
4447
+ if (actor.via) return { ...actor.via };
4448
+ const slash = actor.handle.indexOf("/");
4449
+ return actorParts(actor.id).profile !== null && slash > 0 ? {
4450
+ name: actor.handle.slice(0, slash),
4451
+ environment: null
4452
+ } : void 0;
4453
+ }
4403
4454
  /** The board's own code, which reads every channel: it needs no messages to say so. */
4404
4455
  const OWN_CODE = {
4405
4456
  access: FULL_ACCESS,
@@ -4465,8 +4516,8 @@ const scheduleRef = (index) => `s${index}`;
4465
4516
  /** The log index a ref names on this board, or null for a string that names nothing here. */
4466
4517
  const indexOf$1 = (value) => /^(0|[1-9]\d{0,15})$/.test(value) ? Number(value) : null;
4467
4518
  /** A message as `reader` sees it. Every view names its reader, so none shows a link's snapshot by default. */
4468
- function view(message, actors, reader) {
4469
- const { blind, version, revision, schedule, ...shown } = message;
4519
+ function view$1(message, actors, reader) {
4520
+ const { blind, version, revision, schedule, platformText, mentions: _mentions, ...shown } = message;
4470
4521
  return {
4471
4522
  ...shown,
4472
4523
  ...blind ? { blind } : {},
@@ -4482,14 +4533,14 @@ function view(message, actors, reader) {
4482
4533
  links: readableLinks(message.links, reader),
4483
4534
  labels: { ...message.labels },
4484
4535
  reactions: Object.fromEntries(Object.entries(message.reactions).map(([emoji, ids]) => [emoji, [...ids]])),
4485
- author: actorView(actors, message.by.actor)
4536
+ author: actorView(actors, message.by.actor),
4537
+ blocks: message.from === null && !platformText ? blocksIn(message.text) : []
4486
4538
  };
4487
4539
  }
4488
4540
  const actorSet = (value, actors) => own(actors.byId, value) ? /* @__PURE__ */ new Set([value]) : new Set(own(actors.byHandle, value.toLowerCase()) ?? []);
4489
4541
  /**
4490
- * Who a `--by` or `--mentions` value covers. A person (`julian`) is everyone they
4491
- * are: their own actor, and their agents (`julian/claude`). An agent or a platform
4492
- * actor is just itself.
4542
+ * Who a `--by` value covers. A person (`julian`) is everyone they are: their own
4543
+ * actor, and their agents (`julian/claude`). An agent or a platform actor is just itself.
4493
4544
  */
4494
4545
  function whoIs(value, actors) {
4495
4546
  const ids = actorSet(value, actors);
@@ -4498,6 +4549,37 @@ function whoIs(value, actors) {
4498
4549
  principals: new Set([...ids].filter((id) => own(actors.byId, id)?.kind === "person"))
4499
4550
  };
4500
4551
  }
4552
+ /**
4553
+ * What a `--mentions` value matches in a message's text (`mentionTerms`): `me` is the caller's handle
4554
+ * and ID. Anyone else is the value as written, and what's under it: a person's agents
4555
+ * (`@julian/claude`), a project's imports (`@support/malte`), and their IDs. A reader of every
4556
+ * channel also gets each actor the value names, by ID or by handle, through their other name: their
4557
+ * handle and ID. Anyone else doesn't, since that would say who goes by what where it can't read.
4558
+ */
4559
+ function mentionFilter(value, context) {
4560
+ if (value === "me") return {
4561
+ terms: context.me === null ? [] : [mentionTerm(context.me.handle), context.me.id],
4562
+ prefixes: []
4563
+ };
4564
+ const under = (name) => name.includes(":") ? `${name}+` : `${mentionTerm(name)}/`;
4565
+ const terms = /* @__PURE__ */ new Set([mentionTerm(value)]);
4566
+ const prefixes = /* @__PURE__ */ new Set([under(value)]);
4567
+ if (!context.access.readsAll) return {
4568
+ terms: [...terms],
4569
+ prefixes: [...prefixes]
4570
+ };
4571
+ for (const id of actorSet(value, context.actors)) {
4572
+ const actor = own(context.actors.byId, id);
4573
+ terms.add(id).add(mentionTerm(actor.handle));
4574
+ prefixes.add(under(actor.handle)).add(under(id));
4575
+ }
4576
+ return {
4577
+ terms: [...terms],
4578
+ prefixes: [...prefixes]
4579
+ };
4580
+ }
4581
+ /** Whether `text` mentions what a `--mentions` filter matches. */
4582
+ const mentionsIn = (text, filter) => mentionTerms(text).some((term) => filter.terms.includes(term) || filter.prefixes.some((prefix) => term.startsWith(prefix)));
4501
4583
  /** Whether `author` is one of `who`: its actor, or an agent of one of its people. */
4502
4584
  const covers = (who, actor, principal) => who.actors.has(actor) || principal !== void 0 && who.principals.has(principal);
4503
4585
  const hasLabel = (labels, [key, values]) => Object.hasOwn(labels, key) && (values === null || values.includes(labels[key]));
@@ -4516,7 +4598,7 @@ function compileFilter(filters, context) {
4516
4598
  const subtree = channel?.endsWith("/") ? channel.slice(0, -1) : null;
4517
4599
  const by = filters.by === void 0 ? null : whoIs(filters.by, context.actors);
4518
4600
  const re = filters.re === void 0 ? void 0 : indexOf$1(filters.re) ?? -1;
4519
- const mentions = filters.mentions === void 0 ? null : filters.mentions === "me" ? new Set(context.me === null ? [] : [context.me]) : whoIs(filters.mentions, context.actors).actors;
4601
+ const mentions = filters.mentions === void 0 ? null : mentionFilter(filters.mentions, context);
4520
4602
  return (message) => {
4521
4603
  if (!message || !access.readable(message.channel)) return false;
4522
4604
  if (channel !== void 0) {
@@ -4526,7 +4608,7 @@ function compileFilter(filters, context) {
4526
4608
  }
4527
4609
  if (re !== void 0 && message.id !== re && message.re !== re) return false;
4528
4610
  if (by !== null && !covers(by, message.by.actor, message.by.principal)) return false;
4529
- if (mentions !== null && !message.mentions.some((id) => mentions.has(id))) return false;
4611
+ if (mentions !== null && !mentionsIn(message.text, mentions)) return false;
4530
4612
  if (filters.from !== void 0 && (message.from ?? "board") !== filters.from) return false;
4531
4613
  if (text !== void 0 && !message.text.toLowerCase().includes(text)) return false;
4532
4614
  if (labels.length > 0) {
@@ -4550,7 +4632,7 @@ function readableFilter(filter, known, access) {
4550
4632
  channels: [...known].filter((path) => within(path) && access.readable(path))
4551
4633
  };
4552
4634
  }
4553
- /** The filters as the tables take them: handles resolved to who they cover, `me` to the caller. */
4635
+ /** The filters as the tables take them: handles resolved to who they cover, mentions to the terms they match. */
4554
4636
  function toMessageFilter(filters, context) {
4555
4637
  const out = {};
4556
4638
  const channel = filters.channel;
@@ -4569,7 +4651,7 @@ function toMessageFilter(filters, context) {
4569
4651
  principals: [...who.principals]
4570
4652
  };
4571
4653
  }
4572
- if (filters.mentions !== void 0) out.mentions = filters.mentions === "me" ? context.me === null ? [] : [context.me] : [...whoIs(filters.mentions, context.actors).actors];
4654
+ if (filters.mentions !== void 0) out.mentions = mentionFilter(filters.mentions, context);
4573
4655
  if (filters.from !== void 0) out.from = filters.from;
4574
4656
  if (filters.text !== void 0) out.text = filters.text.toLowerCase();
4575
4657
  if (filters.label?.length) out.labels = filters.label.map(([key, values]) => ({
@@ -4633,7 +4715,7 @@ function eventView(event, after, actors, reader) {
4633
4715
  type: event.type,
4634
4716
  createdAt: iso(event.createdAt),
4635
4717
  payload: payloadView(event.payload, links ? readableLinks(links, reader) : void 0),
4636
- ...after ? { message: view(after, actors, reader) } : {},
4718
+ ...after ? { message: view$1(after, actors, reader) } : {},
4637
4719
  ...actor ? { actor: {
4638
4720
  id: actor.id,
4639
4721
  ...actorView(actors, actor.id)
@@ -4642,7 +4724,7 @@ function eventView(event, after, actors, reader) {
4642
4724
  }
4643
4725
  /** An event's payload as clients see it: the message IDs in it are refs. */
4644
4726
  function payloadView(payload, links) {
4645
- const shown = { ...payload };
4727
+ const { mentions: _mentions, ...shown } = payload;
4646
4728
  for (const key of [
4647
4729
  "id",
4648
4730
  "re",
@@ -4843,22 +4925,34 @@ function deploymentIdentity(actor, handle) {
4843
4925
  }
4844
4926
  /**
4845
4927
  * The `actor.seen` a write carries, or null: who its author is, as the board's record of them
4846
- * says, unless the board knows that already. A platform user's record is board-wide, so a write
4847
- * whose identity doesn't keep it (`records: false`) leaves it as it is. A host's principal and its
4848
- * profiles are recorded as the host's, which sync never writes as.
4928
+ * says, unless the board knows that already. A host's principal and its profiles are recorded as
4929
+ * the host's, which sync never writes as.
4849
4930
  */
4850
4931
  function seenFor(identity, actors) {
4851
- if (identity.records === false) return null;
4852
- return actorSeen(identity.actor, actors, identity.principal.facts?.issuer === "host");
4853
- }
4854
- /** The actors a write can mention: the ones the board knows, plus the ones an email named. */
4855
- const knownWith = (actors, found) => found.length === 0 ? actors : {
4856
- ...actors,
4857
- byId: {
4858
- ...actors.byId,
4859
- ...Object.fromEntries(found.map((a) => [a.id, a]))
4860
- }
4861
- };
4932
+ const { verified: _verified, ...actor } = identity.actor;
4933
+ return actorSeen(verifiedAs(identity) ? {
4934
+ ...actor,
4935
+ verified: true
4936
+ } : actor, actors, identity.principal.facts?.issuer === "host");
4937
+ }
4938
+ /**
4939
+ * Whether the board checked who a write is by, as it shows them: a principal a credential named
4940
+ * (an OIDC token it trusts, a board token, or a host's verifier; never the board's own code), under
4941
+ * the handle that credential gave it. An agent shows that principal after `via`, and its profile
4942
+ * name is the principal's to choose; a person, deployment, or workflow writing as itself shows the
4943
+ * handle as its name, which a display name its client sends replaces. An import says for itself.
4944
+ */
4945
+ function verifiedAs({ principal, author, actor }) {
4946
+ if (principal.kind === "external") return actor.verified === true;
4947
+ if (principal.id.startsWith("board:")) return false;
4948
+ if (author.profile !== null) return actor.via !== void 0 && actor.via.name === viaOf(principal).name;
4949
+ return actor.name === principal.handle && actor.handle === principal.handle;
4950
+ }
4951
+ /**
4952
+ * Whether `identity` wrote `message`, to change it as its author: its principal did, as itself or
4953
+ * any of its agents, and a platform user a sync speaks for only as that same user.
4954
+ */
4955
+ const authored = (message, identity) => message.by.principal === identity.principal.id && (platformProfile(identity.author.profile) === null || message.by.actor === identity.author.actor);
4862
4956
  const messageNotFound = (id) => () => notFound(`message not found: #${id}`, "message_not_found");
4863
4957
  /**
4864
4958
  * A message the board looked up and the caller may act on with `permission`,
@@ -4992,7 +5086,7 @@ async function landedFor(ctx, identity, landed) {
4992
5086
  if (!sameAuthor(landed.by, identity.author)) return null;
4993
5087
  const { access } = identity.principal;
4994
5088
  const { state: actors } = await ctx.session.state(actorsReducer);
4995
- if (access.readable(landed.channel)) return view(landed, actors, await readerFor(ctx, access, landed));
5089
+ if (access.readable(landed.channel)) return view$1(landed, actors, await readerFor(ctx, access, landed));
4996
5090
  if (!landed.blind) return null;
4997
5091
  const [event] = await ctx.session.history({
4998
5092
  gte: landed.id,
@@ -5003,15 +5097,14 @@ async function landedFor(ctx, identity, landed) {
5003
5097
  replies: {}
5004
5098
  }, event).byId[landed.id];
5005
5099
  return {
5006
- ...view(posted, actors, await readerFor(ctx, access, posted)),
5007
- text: blindText(posted.text, identity.actor.id),
5008
- mentions: []
5100
+ ...view$1(posted, actors, await readerFor(ctx, access, posted)),
5101
+ text: blindText(posted.text, identity.actor.id)
5009
5102
  };
5010
5103
  }
5011
5104
  /**
5012
5105
  * A message's text for its writer where it can't read: each exact mention but of itself shows as
5013
- * `@…`. The board may have turned an email it wrote into an actor ID, and who that is, `/actors`
5014
- * doesn't show it either.
5106
+ * `@…`. The board turned an email it wrote into an actor ID before mentions were text, and a sync's
5107
+ * import names its own profiles: who those are, `/actors` doesn't show it either.
5015
5108
  */
5016
5109
  const blindText = (text, own) => replaceMentions(text, (token) => token.kind === "actor" && token.actor !== own ? "@…" : null);
5017
5110
  const sameAuthor = (a, b) => a.actor === b.actor && a.principal === b.principal && a.profile === b.profile && a.session === b.session;
@@ -5029,9 +5122,6 @@ async function commitPost(ctx, input, placed) {
5029
5122
  });
5030
5123
  }
5031
5124
  const seen = seenFor(identity, actors);
5032
- const { text, found } = await withEmailMentions(input.text);
5033
- const named = found.map((actor) => actorSeen(actor, actors)).filter((event) => event !== null);
5034
- const { mentions, unknown } = resolveMentions(text, knownWith(actors, found), seen ? identity.actor : void 0, input.lenientMentions ?? false, identity.principal.access.readsAll);
5035
5125
  const synced = await Promise.all(targets.map(async ({ target, kind, cause }) => ({
5036
5126
  type: "thread.synced",
5037
5127
  id: await derivedId("board", thread, "sync", target),
@@ -5045,19 +5135,17 @@ async function commitPost(ctx, input, placed) {
5045
5135
  })));
5046
5136
  const events = [
5047
5137
  ...seen ? [seen] : [],
5048
- ...named,
5049
5138
  {
5050
5139
  type: "message.posted",
5051
5140
  ...id ? { id } : {},
5052
5141
  payload: {
5053
5142
  channel,
5054
- text,
5143
+ text: input.text,
5055
5144
  re,
5056
5145
  replyTo,
5057
5146
  thread,
5058
5147
  labels: input.labels ?? {},
5059
5148
  noSync: input.noSync ?? false,
5060
- mentions,
5061
5149
  by: identity.author,
5062
5150
  origin: input.origin ?? null,
5063
5151
  from: input.from ?? null,
@@ -5092,25 +5180,22 @@ async function commitPost(ctx, input, placed) {
5092
5180
  ...actors,
5093
5181
  byId: {
5094
5182
  ...actors.byId,
5095
- [identity.actor.id]: identity.actor
5183
+ [identity.actor.id]: {
5184
+ ...identity.actor,
5185
+ ...seen.payload.host ? { host: true } : {},
5186
+ ...seen.payload.verified ? { verified: true } : {}
5187
+ }
5096
5188
  }
5097
5189
  } : actors;
5098
- return shownTo(view(message, known, await readerFor(ctx, identity.principal.access, message)), identity.principal.access, sent, unknown);
5190
+ return shownTo(view$1(message, known, await readerFor(ctx, identity.principal.access, message)), identity.principal.access, sent);
5099
5191
  }
5100
5192
  /**
5101
5193
  * A post's view for its writer. One that can't read the channel gets back the
5102
- * text it sent, no mentions, and no `unknownMentions`: the board resolved its
5103
- * handles and emails to actor IDs, which `/actors` doesn't show it, and which
5104
- * handles matched no one would say which ones exist. The board keeps the
5105
- * mentions, so they still notify.
5194
+ * text it sent: what the board made of it (the middleware's changes) is for its readers.
5106
5195
  */
5107
- const shownTo = (shown, access, sent, unknown = []) => !access.readable(shown.channel) ? {
5196
+ const shownTo = (shown, access, sent) => !access.readable(shown.channel) ? {
5108
5197
  ...shown,
5109
- text: sent,
5110
- mentions: []
5111
- } : unknown.length ? {
5112
- ...shown,
5113
- unknownMentions: unknown
5198
+ text: sent
5114
5199
  } : shown;
5115
5200
  /** The writer, as the reader of the view its write returns. Only a link to a board message needs a lookup. */
5116
5201
  const readerFor = (ctx, access, message) => ctx.reads.reader(access, [message]);
@@ -5193,7 +5278,7 @@ function spent(authorized, permission) {
5193
5278
  }
5194
5279
  async function writeEdit(ctx, input) {
5195
5280
  const message = spent(input.authorized, "post");
5196
- if (input.asAuthor !== false && message.by.principal !== input.identity.principal.id) throw forbidden$1("only the author can edit a message");
5281
+ if (input.asAuthor !== false && !authored(message, input.identity)) throw forbidden$1("only the author can edit a message");
5197
5282
  if (message.deleted) {
5198
5283
  if (input.revision !== void 0 && input.revision !== (message.revision ?? message.id)) throw new HttpError(409, "revision_conflict", `#${message.id} was deleted since revision ${input.revision}`);
5199
5284
  throw badRequest("message was deleted", "message_deleted");
@@ -5203,26 +5288,17 @@ async function writeEdit(ctx, input) {
5203
5288
  async function commitEdit(ctx, input, message) {
5204
5289
  const { state: actors } = await ctx.session.state(actorsReducer);
5205
5290
  const seen = seenFor(input.identity, actors);
5206
- const { text, found } = await withEmailMentions(input.text);
5207
- const named = found.map((actor) => actorSeen(actor, actors)).filter((event) => event !== null);
5208
- const { mentions, unknown } = resolveMentions(text, knownWith(actors, found), seen ? input.identity.actor : void 0, input.from != null, input.identity.principal.access.readsAll);
5209
- const events = [
5210
- ...seen ? [seen] : [],
5211
- ...named,
5212
- {
5213
- type: "message.edited",
5214
- payload: {
5215
- id: message.id,
5216
- thread: message.thread,
5217
- text,
5218
- mentions,
5219
- by: input.identity.author,
5220
- from: input.from ?? null
5221
- }
5291
+ const events = [...seen ? [seen] : [], {
5292
+ type: "message.edited",
5293
+ payload: {
5294
+ id: message.id,
5295
+ thread: message.thread,
5296
+ text: input.text,
5297
+ by: input.identity.author,
5298
+ from: input.from ?? null
5222
5299
  }
5223
- ];
5300
+ }];
5224
5301
  await untilApplied(ctx, input.revision === void 0 ? await ctx.session.append(...events) : await appendWhile(ctx, revisionIs(ctx, message.id, input.revision), events));
5225
- return unknown.length && input.identity.principal.access.readable(message.channel) ? { unknownMentions: unknown } : {};
5226
5302
  }
5227
5303
  /** A message's links, replaced: a platform edit or unfurl changed what it links to. */
5228
5304
  async function writeLinks(ctx, input) {
@@ -5241,7 +5317,7 @@ async function writeLinks(ctx, input) {
5241
5317
  }
5242
5318
  async function writeDelete(ctx, input) {
5243
5319
  const message = spent(input.authorized, "post");
5244
- if (input.asAuthor !== false && message.by.principal !== input.identity.principal.id) throw forbidden$1("only the author can delete a message");
5320
+ if (input.asAuthor !== false && !authored(message, input.identity)) throw forbidden$1("only the author can delete a message");
5245
5321
  if (message.deleted) {
5246
5322
  if (input.revision !== void 0 && input.revision !== (message.revision ?? message.id)) throw new HttpError(409, "revision_conflict", `#${message.id} was deleted since revision ${input.revision}`);
5247
5323
  return;
@@ -5383,9 +5459,9 @@ const TOKEN_DEPTH_MAX = 8;
5383
5459
  /**
5384
5460
  * The grants a board starts with, as a team's board in Vercel's API does: g1, every person may do
5385
5461
  * everything (no team roles cap it here), g2, every project on the board's team, in every
5386
- * environment, reads, posts, reacts, and labels everywhere, and g3, every app on the team, the
5387
- * same. A local board has no apps, so g3 names no one here, but the defaults are the same
5388
- * everywhere. Revoke or change them like any other.
5462
+ * environment, reads, posts, reacts, labels, and syncs everywhere, and g3, every app on the team,
5463
+ * reads, posts, reacts, and labels. A local board has no apps, so g3 names no one here, but the
5464
+ * defaults are the same everywhere. Revoke or change them like any other.
5389
5465
  */
5390
5466
  const STARTING_GRANTS = {
5391
5467
  1: {
@@ -5411,7 +5487,8 @@ const STARTING_GRANTS = {
5411
5487
  "read",
5412
5488
  "post",
5413
5489
  "react",
5414
- "label"
5490
+ "label",
5491
+ "sync"
5415
5492
  ] },
5416
5493
  by: null,
5417
5494
  at: null
@@ -5529,7 +5606,7 @@ function foldAccess(state, event) {
5529
5606
  }
5530
5607
  const accessReducer = reducer({
5531
5608
  contract: accessContract,
5532
- name: "board.access.v2",
5609
+ name: "board.access.v3",
5533
5610
  initialState: startingAccess()
5534
5611
  }).fold(foldAccess);
5535
5612
  const grantId = (id) => `g${id}`;
@@ -6059,6 +6136,108 @@ function createTrust(options) {
6059
6136
  };
6060
6137
  }
6061
6138
  //#endregion
6139
+ //#region src/server/schemas.ts
6140
+ /** The schemas session's fold: a version is its first event, and nothing changes it after. */
6141
+ function foldSchemas(state, event) {
6142
+ const { name, version, description, schema, by } = event.payload;
6143
+ state.byId[schemaId(name, version)] ??= {
6144
+ name,
6145
+ version,
6146
+ description,
6147
+ schema,
6148
+ by,
6149
+ at: new Date(event.createdAt).getTime()
6150
+ };
6151
+ return state;
6152
+ }
6153
+ const schemasReducer = reducer({
6154
+ contract: schemasContract,
6155
+ name: "board.schemas.v1",
6156
+ initialState: { byId: {} }
6157
+ }).fold(foldSchemas);
6158
+ const builtIns = BUILT_IN_SCHEMAS.map((schema) => ({
6159
+ id: schemaId(schema.name, schema.version),
6160
+ ...schema,
6161
+ builtIn: true,
6162
+ by: null,
6163
+ at: null
6164
+ }));
6165
+ const view = (row) => ({
6166
+ id: schemaId(row.name, row.version),
6167
+ name: row.name,
6168
+ version: row.version,
6169
+ description: row.description,
6170
+ schema: row.schema,
6171
+ builtIn: false,
6172
+ by: row.by,
6173
+ at: new Date(row.at).toISOString()
6174
+ });
6175
+ /**
6176
+ * The board's schema registry, in session `schemas` of its log: what a local board answers for
6177
+ * them. Anyone the board let in reads it, and registering takes `manage` at `*`, since a schema is
6178
+ * the whole board's.
6179
+ */
6180
+ function createSchemas(options) {
6181
+ const session = createServer({
6182
+ contract: schemasContract,
6183
+ store: options.store
6184
+ }).session(SCHEMAS_SESSION);
6185
+ const read = async () => (await session.state(schemasReducer)).state;
6186
+ /** The registry as it is now, and the index a conditional write holds it at. */
6187
+ const latest = () => session.state(schemasReducer, { through: "latest" });
6188
+ return {
6189
+ async schemas() {
6190
+ const own = Object.values((await read()).byId).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : a.version - b.version);
6191
+ return { schemas: [...builtIns, ...own.map(view)] };
6192
+ },
6193
+ async schema({ id }) {
6194
+ if (!parseSchemaId(id)) throw badRequest(`${id} doesn't name a schema: one is name@version, like sandbox@1`, "invalid_schema_id");
6195
+ const builtIn = builtIns.find((schema) => schema.id === id);
6196
+ if (builtIn) return { schema: builtIn };
6197
+ const row = (await read()).byId[id];
6198
+ if (!row) throw notFound(`schema not found: ${id}`, "schema_not_found");
6199
+ return { schema: view(row) };
6200
+ },
6201
+ async createSchema({ principal, actor }, body) {
6202
+ if (!principal.access.at("manage", "*")) throw forbidden$1("this token can't register schemas: it needs manage at *");
6203
+ const id = schemaId(body.name, body.version);
6204
+ if (isBuiltInName(body.name)) throw new HttpError(409, "reserved_schema", `${body.name} is a built-in schema: register yours under another name`);
6205
+ const problem = checkDefinition(body.schema);
6206
+ if (problem !== null) throw badRequest(problem, "invalid_schema");
6207
+ const description = body.description ?? null;
6208
+ return whileHeadMoves(async () => {
6209
+ const { state, index } = await latest();
6210
+ const existing = state.byId[id];
6211
+ if (existing) {
6212
+ const differs = canonical(existing.schema) !== canonical(body.schema) ? "definition" : existing.description !== description ? "description" : null;
6213
+ if (differs !== null) throw new HttpError(409, "schema_immutable", `${id} is registered with another ${differs}, and a version never changes: register a new version`);
6214
+ return {
6215
+ schema: view(existing),
6216
+ created: false
6217
+ };
6218
+ }
6219
+ if (Object.keys(state.byId).length >= 500) throw badRequest(`a board registers at most 500 schema versions`, "too_many_schemas");
6220
+ await session.append.ifLastIndex(index, {
6221
+ type: "schema.created",
6222
+ payload: {
6223
+ name: body.name,
6224
+ version: body.version,
6225
+ description,
6226
+ schema: body.schema,
6227
+ by: actor.id
6228
+ }
6229
+ });
6230
+ const made = (await read()).byId[id];
6231
+ if (!made) throw new Error("a schema was registered but its log has no record of it");
6232
+ return {
6233
+ schema: view(made),
6234
+ created: true
6235
+ };
6236
+ });
6237
+ }
6238
+ };
6239
+ }
6240
+ //#endregion
6062
6241
  //#region src/server/blob.ts
6063
6242
  /** Files in memory, for tests: forgets everything when the process ends. */
6064
6243
  function memoryBlob() {
@@ -6559,6 +6738,11 @@ const createdBy = (schedule, identity) => wroteAs(identity, {
6559
6738
  }) && identity.principal.access.can("post", schedule.channel) && (schedule.blind || identity.principal.access.readable(schedule.channel));
6560
6739
  const scheduleView = (schedule, actors) => {
6561
6740
  const author = actors.byId[schedule.as.actor.id] ?? schedule.as.actor;
6741
+ const via = viaOfRecord({
6742
+ id: schedule.as.actor.id,
6743
+ handle: author.handle,
6744
+ via: "via" in author ? author.via : void 0
6745
+ });
6562
6746
  return {
6563
6747
  id: scheduleRef(schedule.id),
6564
6748
  channel: schedule.channel,
@@ -6581,7 +6765,8 @@ const scheduleView = (schedule, actors) => {
6581
6765
  kind: author.kind,
6582
6766
  handle: author.handle,
6583
6767
  name: author.name,
6584
- avatar: author.avatar
6768
+ avatar: author.avatar,
6769
+ ...via ? { via } : {}
6585
6770
  },
6586
6771
  createdAt: schedule.createdAt
6587
6772
  };
@@ -6837,9 +7022,6 @@ function createSchedules(options) {
6837
7022
  const until = expires !== null && (asked === null || asked > expires) ? expires : asked;
6838
7023
  if (until !== null && until < first) throw badRequest("the schedule stops before its first send");
6839
7024
  if (first > now + 316224e5 || until !== null && until > now + 316224e5) throw badRequest("a schedule reaches at most a year out: its first send and its stop");
6840
- const { state: known } = await writes.session.state(actorsReducer);
6841
- const withoutEmails = replaceMentions(body.text, (t) => t.kind === "actor" && t.actor.includes("@") ? t.actor : null);
6842
- const { unknown } = resolveMentions(withoutEmails, known, identity.actor, false, identity.principal.access.readsAll);
6843
7025
  let channel = body.channel;
6844
7026
  let re = null;
6845
7027
  if (body.re !== void 0) {
@@ -6873,11 +7055,7 @@ function createSchedules(options) {
6873
7055
  const created = state.byId[row.index];
6874
7056
  if (created.next !== null) await arm("first", created.id, created.sent, created.next);
6875
7057
  const { state: actors } = await writes.session.state(actorsReducer);
6876
- const schedule = scheduleView(created, actors);
6877
- return unknown.length && identity.principal.access.readable(channel) ? {
6878
- schedule,
6879
- unknownMentions: unknown
6880
- } : { schedule };
7058
+ return { schedule: scheduleView(created, actors) };
6881
7059
  },
6882
7060
  /**
6883
7061
  * Its creator may cancel it while they can post there, and so may `manage`
@@ -6909,118 +7087,298 @@ function createSchedules(options) {
6909
7087
  }
6910
7088
  };
6911
7089
  }
6912
- /** How long a pulled match is its puller's before someone may pull it again. */
6913
- const LEASE_MS = 3e5;
6914
- /** After an error, a match waits 1 second, doubling to 30. */
6915
- const retryDelay = (attempts) => Math.min(3e4, 1e3 * 2 ** (attempts - 1));
7090
+ //#endregion
7091
+ //#region src/server/watch.ts
7092
+ const ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
7093
+ /** The events a tail shows, receipts included for `--all`: each concerns a message, and carries its thread for the lane. */
7094
+ const WATCHED = [
7095
+ "message.posted",
7096
+ "message.edited",
7097
+ "message.deleted",
7098
+ "reaction.added",
7099
+ "reaction.removed",
7100
+ "labels.changed",
7101
+ "message.sync_failed",
7102
+ "message.synced",
7103
+ "message.files_synced",
7104
+ "thread.synced"
7105
+ ];
7106
+ /** Receipts: only a `--all` tail shows them. */
7107
+ const RECEIPTS = /* @__PURE__ */ new Set(["message.synced", "message.files_synced"]);
6916
7108
  /**
6917
- * Sweeps fall on the minute: a registrant has at most one timer a minute, however many matches it
6918
- * pulls. A sweep wakes it for leases that ran out, and for a wake-up that didn't arrive.
7109
+ * What a registrant's sync gets, in every channel where it may sync: what it delivers to platforms,
7110
+ * and a thread's new targets. A tail never shows `thread.synced`, so no watcher gets it.
6919
7111
  */
6920
- const SWEEP_MS = 6e4;
6921
- /** The sweep that covers `at`: the next minute at least a second after it, since a timer may land up to a second early. */
6922
- const sweepFor = (at) => Math.ceil((at + 1e3) / SWEEP_MS) * SWEEP_MS;
6923
- /** The longest a registrant whose wake-ups don't get there waits for the next one. */
6924
- const WAKE_BACKOFF_MAX_MS = 36e5;
7112
+ const SYNCED = /* @__PURE__ */ new Set([
7113
+ "message.posted",
7114
+ "message.edited",
7115
+ "message.deleted",
7116
+ "reaction.added",
7117
+ "reaction.removed",
7118
+ "labels.changed",
7119
+ "thread.synced"
7120
+ ]);
7121
+ /** A watcher writes as `board:watch:<id>`, and its own writes never wake it. */
7122
+ const actorOf = (id) => `board:watch:${id}`;
7123
+ /** `watch:@<principal>`: everything one registrant's watchers matched, queued for it to pull. */
7124
+ const registrantSession = (owner) => watchSession(`@${owner}`);
6925
7125
  /**
6926
- * After `failures` wake-ups in a row that didn't get there, how long until the next: a minute,
6927
- * doubling to an hour. Until then a match only queues.
7126
+ * Watchers: a board-contract consumer matches each event against every
7127
+ * watcher's filters, the way a tail does, and appends what matched to that
7128
+ * watcher's session, where `run` happens on the thread's lane.
6928
7129
  */
6929
- const wakeBackoff = (failures) => Math.min(WAKE_BACKOFF_MAX_MS, SWEEP_MS * 2 ** (failures - 1));
6930
- /** The queue of platform events a registrant pushed for sync key `key`. */
6931
- const inboxQueue = (key) => `@inbox:${key}`;
6932
- const queueKey = (queue, thread) => `${queue}\u001f${thread}`;
6933
- function remove(state, id) {
6934
- const found = state.pending[id];
6935
- if (!found) return;
6936
- delete state.pending[id];
6937
- const key = queueKey(found.queue, found.thread);
6938
- const rest = (state.queues[key] ?? []).filter((queued) => queued !== id);
6939
- if (rest.length > 0) state.queues[key] = rest;
6940
- else delete state.queues[key];
6941
- }
6942
- function foldQueue(state, event) {
6943
- switch (event.type) {
6944
- case "watch.matched": {
6945
- const { watcher, sync, inbox, thread } = event.payload;
6946
- const queue = watcher ?? (sync ? "@sync" : inbox !== void 0 ? inboxQueue(inbox) : void 0);
6947
- if (queue === void 0 || state.pending[event.id]) return state;
6948
- state.pending[event.id] = {
6949
- id: event.id,
6950
- queue,
6951
- thread,
6952
- event: event.payload.event,
6953
- attempts: 0,
6954
- lease: null,
6955
- retryAt: null
6956
- };
6957
- (state.queues[queueKey(queue, thread)] ??= []).push(event.id);
6958
- return state;
6959
- }
6960
- case "watch.leased": {
6961
- const found = state.pending[event.payload.matched];
6962
- if (found && !found.lease) found.lease = {
6963
- id: event.payload.lease,
6964
- until: event.payload.until
6965
- };
6966
- return state;
6967
- }
6968
- case "watch.acked": {
6969
- const found = state.pending[event.payload.matched];
6970
- if (!found || found.lease?.id !== event.payload.lease) return state;
6971
- if (event.payload.error === void 0) {
6972
- remove(state, found.id);
6973
- return state;
6974
- }
6975
- found.attempts += 1;
6976
- found.lease = null;
6977
- found.retryAt = event.payload.retryAt ?? null;
6978
- return state;
6979
- }
6980
- case "watch.expired": {
6981
- const found = state.pending[event.payload.matched];
6982
- if (!found || found.lease?.id !== event.payload.lease) return state;
6983
- found.attempts += 1;
6984
- found.lease = null;
6985
- return state;
6986
- }
6987
- case "watch.retry": {
6988
- const found = state.pending[event.payload.matched];
6989
- if (found) found.retryAt = null;
6990
- return state;
6991
- }
6992
- case "watch.armed":
6993
- if (!state.sweeps.includes(event.payload.at)) state.sweeps.push(event.payload.at);
6994
- return state;
6995
- case "watch.due": {
6996
- const { sweep } = event.payload;
6997
- if (sweep !== void 0) state.sweeps = state.sweeps.filter((at) => at !== sweep);
6998
- return state;
7130
+ function createWatchers(options) {
7131
+ const watchers = Object.entries(options.watch).map(([id, watcher]) => {
7132
+ if (!ID.test(id)) throw new Error(`watch: ids use lowercase letters, numbers, - and _, got: ${id}`);
7133
+ return {
7134
+ id,
7135
+ ...compileWatcher(id, watcher)
7136
+ };
7137
+ });
7138
+ const byId = new Map(watchers.map((watcher) => [watcher.id, watcher]));
7139
+ let reads = null;
7140
+ /** Runs a watcher on a board event it matched, one thread at a time. */
7141
+ const runner = consumer({
7142
+ contract: watchContract,
7143
+ name: "board-watch",
7144
+ types: ["watch.matched"],
7145
+ lane: ({ event }) => `thread:${event.payload.thread}`
7146
+ }).run(async (ctx) => {
7147
+ const watcher = byId.get(ctx.session.id.slice(6));
7148
+ if (!watcher) return;
7149
+ await runMatch({
7150
+ watcher: {
7151
+ id: watcher.id,
7152
+ run: (event) => options.run(watcher.id, event, ctx.event.id, ctx.attempt)
7153
+ },
7154
+ match: ctx.event,
7155
+ attempt: ctx.attempt,
7156
+ record: (payload) => ctx.session.append(`failed:${ctx.event.id}`, {
7157
+ type: "watch.failed",
7158
+ payload
7159
+ })
7160
+ });
7161
+ });
7162
+ const server = createServer({
7163
+ contract: watchContract,
7164
+ ...options.store ? { store: options.store } : {},
7165
+ ...options.scheduler ? { scheduler: options.scheduler } : {},
7166
+ consumers: [runner]
7167
+ });
7168
+ const configured = watchers.map((watcher) => ({
7169
+ ...watcher,
7170
+ actor: actorOf(watcher.id)
7171
+ }));
7172
+ const compiled = /* @__PURE__ */ new Map();
7173
+ function compiledFor(registration) {
7174
+ const version = `${registration.hash}\u001f${JSON.stringify(registration.principal)}`;
7175
+ const hit = compiled.get(registration.owner);
7176
+ if (hit?.version === version) return hit.candidates;
7177
+ const candidates = [];
7178
+ for (const [id, spec] of Object.entries(registration.watch)) try {
7179
+ candidates.push({
7180
+ ...compileWatcher(id, spec),
7181
+ id,
7182
+ actor: `${registration.owner}+${id.toLowerCase()}`,
7183
+ registration
7184
+ });
7185
+ } catch (error) {
7186
+ console.error(`[board] skipping a watcher ${registration.owner} registered:`, error.message);
6999
7187
  }
7000
- case "watch.failed":
7001
- case "watch.skipped":
7002
- remove(state, event.payload.matched);
7003
- return state;
7004
- case "watch.unreachable":
7005
- state.unreachable = {
7006
- failures: event.payload.failures,
7007
- until: event.payload.until
7008
- };
7009
- return state;
7010
- case "watch.reachable":
7011
- state.unreachable = null;
7012
- return state;
7013
- default: return state;
7188
+ compiled.set(registration.owner, {
7189
+ version,
7190
+ candidates
7191
+ });
7192
+ return candidates;
7014
7193
  }
7015
- }
7016
- const queueReducer = reducer({
7194
+ async function registrations() {
7195
+ return options.registered ? Object.values((await options.registered.state()).byOwner) : [];
7196
+ }
7197
+ /** Matches one board event; the message before or after it must match, as in a tail. */
7198
+ async function dispatch(ctx) {
7199
+ const event = ctx.event;
7200
+ const through = event.index - 1;
7201
+ const [messages, { state: actors }] = await Promise.all([messagesBefore(event, ctx.signal), ctx.session.state(actorsReducer, { through })]);
7202
+ const { id, before, after } = foldEvent(messages, actors, event);
7203
+ const by = event.payload.by?.actor;
7204
+ const message = after ?? before;
7205
+ const thread = event.payload.thread;
7206
+ let view;
7207
+ /** Each session's matches, appended together: one append per watcher in config, one per registrant. */
7208
+ const appends = /* @__PURE__ */ new Map();
7209
+ const add = (session, matched) => (appends.get(session) ?? appends.set(session, []).get(session)).push(matched);
7210
+ const registered = await registrations();
7211
+ const targets = [...configured, ...registered.flatMap(compiledFor)];
7212
+ const registrants = /* @__PURE__ */ new Map();
7213
+ const accessOf = (registration) => {
7214
+ let found = registrants.get(registration.owner);
7215
+ if (!found) registrants.set(registration.owner, found = options.registered.accessNow(registration.principal));
7216
+ return found;
7217
+ };
7218
+ for (const watcher of targets) {
7219
+ if (event.type === "thread.synced") break;
7220
+ if (by === watcher.actor) continue;
7221
+ if (RECEIPTS.has(event.type) && !watcher.all) continue;
7222
+ const { registration } = watcher;
7223
+ let access = FULL_ACCESS;
7224
+ if (registration) {
7225
+ const now = await accessOf(registration);
7226
+ if (!now || (id === null ? !now.readsAll : !message || !now.readable(message.channel))) continue;
7227
+ access = now;
7228
+ }
7229
+ const match = compileFilter(watcher.filters, {
7230
+ me: null,
7231
+ actors,
7232
+ messages,
7233
+ access
7234
+ });
7235
+ if (!(watcher.criteria ? match(before) || match(after) : id !== null)) continue;
7236
+ const key = registration ? `@${registration.owner}/${watcher.id}` : watcher.id;
7237
+ const shown = registration ? eventView(event, after, actors, await reads.reader(access, after ? [after] : [])) : view ??= eventView(event, after, actors, OWN_CODE);
7238
+ add(registration ? registrantSession(registration.owner) : watchSession(watcher.id), {
7239
+ type: "watch.matched",
7240
+ id: await idempotentId("board-watch", key, event.id),
7241
+ payload: {
7242
+ thread,
7243
+ event: shown,
7244
+ ...registration ? { watcher: watcher.id } : {}
7245
+ }
7246
+ });
7247
+ }
7248
+ const syncing = SYNCED.has(event.type) ? registered.filter((registration) => registration.sync.length > 0) : [];
7249
+ if (syncing.length > 0) {
7250
+ const about = event.type === "thread.synced" ? await rootOf(event.payload.thread, event.index, ctx.signal) : message;
7251
+ for (const registration of syncing) {
7252
+ const now = await accessOf(registration);
7253
+ if (!now || !about || !now.can("sync", about.channel)) continue;
7254
+ const reader = await reads.reader(now, [about, ...before ? [before] : []]);
7255
+ const shown = {
7256
+ ...eventView(event, about, actors, reader),
7257
+ ...event.type === "labels.changed" && before ? { before: view$1(before, actors, reader) } : {}
7258
+ };
7259
+ add(registrantSession(registration.owner), {
7260
+ type: "watch.matched",
7261
+ id: await idempotentId("board-watch", `@${registration.owner}/@sync`, event.id),
7262
+ payload: {
7263
+ thread,
7264
+ event: shown,
7265
+ sync: true
7266
+ }
7267
+ });
7268
+ }
7269
+ }
7270
+ await Promise.all([...appends].map(async ([session, events]) => {
7271
+ try {
7272
+ await server.session(session).append(...events);
7273
+ } catch (error) {
7274
+ if (!(error instanceof A2Error && error.code === "PARTIAL_DUPLICATE_BATCH")) throw error;
7275
+ for (const matched of events) await server.session(session).append(matched);
7276
+ }
7277
+ }));
7278
+ }
7279
+ /** A thread's root, as the board has it once the tables reach `index`: the event that synced it comes after it. */
7280
+ async function rootOf(thread, index, signal) {
7281
+ if (!reads) throw new Error("watchers used before the board bound them");
7282
+ await reads.ensure(index - 1, signal);
7283
+ return await reads.tables.byEventId(thread) ?? void 0;
7284
+ }
7285
+ /** The message `event` concerns, and its thread's root, as they were just before it. */
7286
+ async function messagesBefore(event, signal) {
7287
+ if (!reads) throw new Error("watchers used before the board bound them");
7288
+ return loadBefore(reads, event, signal);
7289
+ }
7290
+ return {
7291
+ server,
7292
+ boardConsumer: consumer({
7293
+ contract: boardContract,
7294
+ name: "board-watchers",
7295
+ types: WATCHED,
7296
+ lane: ({ event }) => `thread:${event.payload.thread}`
7297
+ }).run(dispatch),
7298
+ bind: (binding) => {
7299
+ reads = binding.reads;
7300
+ }
7301
+ };
7302
+ }
7303
+ /** How long a pulled match is its puller's before someone may pull it again. */
7304
+ const LEASE_MS = 3e5;
7305
+ /** After an error, a match waits 1 second, doubling to 30. */
7306
+ const retryDelay = (attempts) => Math.min(3e4, 1e3 * 2 ** (attempts - 1));
7307
+ /** The queue of platform events a registrant pushed for sync key `key`. */
7308
+ const inboxQueue = (key) => `@inbox:${key}`;
7309
+ const queueKey = (queue, thread) => `${queue}\u001f${thread}`;
7310
+ function remove(state, id) {
7311
+ const found = state.pending[id];
7312
+ if (!found) return;
7313
+ delete state.pending[id];
7314
+ const key = queueKey(found.queue, found.thread);
7315
+ const rest = (state.queues[key] ?? []).filter((queued) => queued !== id);
7316
+ if (rest.length > 0) state.queues[key] = rest;
7317
+ else delete state.queues[key];
7318
+ }
7319
+ function foldQueue(state, event) {
7320
+ switch (event.type) {
7321
+ case "watch.matched": {
7322
+ const { watcher, sync, inbox, thread } = event.payload;
7323
+ const queue = watcher ?? (sync ? "@sync" : inbox !== void 0 ? inboxQueue(inbox) : void 0);
7324
+ if (queue === void 0 || state.pending[event.id]) return state;
7325
+ state.pending[event.id] = {
7326
+ id: event.id,
7327
+ queue,
7328
+ thread,
7329
+ event: event.payload.event,
7330
+ attempts: 0,
7331
+ lease: null,
7332
+ retryAt: null
7333
+ };
7334
+ (state.queues[queueKey(queue, thread)] ??= []).push(event.id);
7335
+ return state;
7336
+ }
7337
+ case "watch.leased": {
7338
+ const found = state.pending[event.payload.matched];
7339
+ if (found && !found.lease) found.lease = {
7340
+ id: event.payload.lease,
7341
+ until: event.payload.until
7342
+ };
7343
+ return state;
7344
+ }
7345
+ case "watch.acked": {
7346
+ const found = state.pending[event.payload.matched];
7347
+ if (!found || found.lease?.id !== event.payload.lease) return state;
7348
+ if (event.payload.error === void 0) {
7349
+ remove(state, found.id);
7350
+ return state;
7351
+ }
7352
+ found.attempts += 1;
7353
+ found.lease = null;
7354
+ found.retryAt = event.payload.retryAt ?? null;
7355
+ return state;
7356
+ }
7357
+ case "watch.expired": {
7358
+ const found = state.pending[event.payload.matched];
7359
+ if (!found || found.lease?.id !== event.payload.lease) return state;
7360
+ found.attempts += 1;
7361
+ found.lease = null;
7362
+ return state;
7363
+ }
7364
+ case "watch.retry": {
7365
+ const found = state.pending[event.payload.matched];
7366
+ if (found) found.retryAt = null;
7367
+ return state;
7368
+ }
7369
+ case "watch.failed":
7370
+ case "watch.skipped":
7371
+ remove(state, event.payload.matched);
7372
+ return state;
7373
+ default: return state;
7374
+ }
7375
+ }
7376
+ const queueReducer = reducer({
7017
7377
  contract: watchContract,
7018
- name: "board.watch-queue.v4",
7378
+ name: "board.watch-queue.v5",
7019
7379
  initialState: {
7020
7380
  queues: {},
7021
- pending: {},
7022
- sweeps: [],
7023
- unreachable: null
7381
+ pending: {}
7024
7382
  }
7025
7383
  }).fold(foldQueue);
7026
7384
  const describe = (error) => ((error instanceof Error ? error.message : String(error)) || "unknown error").slice(0, 500);
@@ -7037,8 +7395,6 @@ function readable(access, event, queue) {
7037
7395
  const taken = (error) => error instanceof A2Error && error.code === "PARTIAL_DUPLICATE_BATCH";
7038
7396
  /** Whether a match is free to pull now: no one holds it, and its wait after an error is over. A lease or wait whose time has passed counts as over. */
7039
7397
  const free = (found, now) => !(found.lease && found.lease.until > now) && !(found.retryAt !== null && found.retryAt > now);
7040
- /** Whether the registrant has anything to pull now. */
7041
- const hasWork = (state, now) => Object.values(state.queues).some((ids) => free(state.pending[ids[0]], now));
7042
7398
  /**
7043
7399
  * Hands out what the registrant's watchers and sync may run now: each queue's oldest match, if it's
7044
7400
  * free, leased to this pull. The inbox's queues are `pullInbox`'s.
@@ -7077,10 +7433,7 @@ function pullInbox(session, key, options) {
7077
7433
  */
7078
7434
  async function lease(session, options) {
7079
7435
  const { state } = await session.state(queueReducer);
7080
- const events = state.unreachable ? [{
7081
- type: "watch.reachable",
7082
- payload: { by: "pull" }
7083
- }] : [];
7436
+ const events = [];
7084
7437
  const offered = [];
7085
7438
  for (const ids of Object.values(state.queues)) {
7086
7439
  if (offered.length >= options.limit) break;
@@ -7136,9 +7489,7 @@ async function lease(session, options) {
7136
7489
  });
7137
7490
  if (offered.length === 0) return [];
7138
7491
  const { state: after } = await session.state(queueReducer);
7139
- const handed = offered.filter(({ head, lease }) => after.pending[head.id]?.lease?.id === lease);
7140
- if (handed.length > 0 && options.timers) await arm(session, after, options.now + LEASE_MS);
7141
- return handed.map(({ head, lease, attempt }) => ({
7492
+ return offered.filter(({ head, lease }) => after.pending[head.id]?.lease?.id === lease).map(({ head, lease, attempt }) => ({
7142
7493
  id: head.id,
7143
7494
  queue: head.queue,
7144
7495
  thread: head.thread,
@@ -7195,47 +7546,8 @@ async function ack(session, id, body, options) {
7195
7546
  retryAt
7196
7547
  }
7197
7548
  });
7198
- if (options.timers) await session.schedule(`retry:${id}:${attempts}`, { at: new Date(retryAt) }, {
7199
- type: "watch.due",
7200
- payload: {
7201
- matched: id,
7202
- retry: true
7203
- }
7204
- });
7205
7549
  return "acked";
7206
7550
  }
7207
- /**
7208
- * Sets a sweep for `at`, unless one is set already. The sweep runs on the minute after it, so the
7209
- * leases of a minute share one timer. Its timer goes first: a sweep recorded without one would
7210
- * never run, and a timer set twice under one name lands once.
7211
- */
7212
- async function arm(session, state, at) {
7213
- const sweep = sweepFor(at);
7214
- if (state.sweeps.includes(sweep)) return;
7215
- await session.schedule(`sweep:${sweep}`, { at: new Date(sweep) }, {
7216
- type: "watch.due",
7217
- payload: { sweep }
7218
- });
7219
- await session.append({
7220
- type: "watch.armed",
7221
- id: await idempotentId("board-sweep", String(sweep)),
7222
- payload: { at: sweep }
7223
- });
7224
- }
7225
- /**
7226
- * A timer came due: an error's wait is over, or a sweep. Returns the queue after it, for its
7227
- * consumer to tell whether the registrant has something to pull.
7228
- */
7229
- async function due(session, payload) {
7230
- const { state } = await session.state(queueReducer);
7231
- const found = payload.matched === void 0 ? void 0 : state.pending[payload.matched];
7232
- if (!payload.retry || !found || found.retryAt === null) return state;
7233
- await session.append({
7234
- type: "watch.retry",
7235
- payload: { matched: found.id }
7236
- });
7237
- return (await session.state(queueReducer)).state;
7238
- }
7239
7551
  /** Gives up on a match: `watch.failed`, said in the logs too. */
7240
7552
  function failure(found, error) {
7241
7553
  console.error(`[board] a registrant's ${found.queue} gave up on an item after 5 tries:`, error);
@@ -7249,380 +7561,7 @@ function failure(found, error) {
7249
7561
  };
7250
7562
  }
7251
7563
  //#endregion
7252
- //#region src/server/watch.ts
7253
- const ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
7254
- /** The events a tail shows, receipts included for `--all`: each concerns a message, and carries its thread for the lane. */
7255
- const WATCHED = [
7256
- "message.posted",
7257
- "message.edited",
7258
- "message.deleted",
7259
- "reaction.added",
7260
- "reaction.removed",
7261
- "labels.changed",
7262
- "message.sync_failed",
7263
- "message.synced",
7264
- "message.files_synced",
7265
- "thread.synced"
7266
- ];
7267
- /** Receipts: only a `--all` tail shows them. */
7268
- const RECEIPTS = /* @__PURE__ */ new Set(["message.synced", "message.files_synced"]);
7269
- /**
7270
- * What a registrant's sync gets, in every channel where it may sync: what it delivers to platforms,
7271
- * and a thread's new targets. A tail never shows `thread.synced`, so no watcher gets it.
7272
- */
7273
- const SYNCED = /* @__PURE__ */ new Set([
7274
- "message.posted",
7275
- "message.edited",
7276
- "message.deleted",
7277
- "reaction.added",
7278
- "reaction.removed",
7279
- "labels.changed",
7280
- "thread.synced"
7281
- ]);
7282
- /** Whether a match waits in a registrant's queue for it to pull, as opposed to a config watcher's, which runs here. */
7283
- const queued = (payload) => payload.watcher !== void 0 || payload.sync === true || payload.inbox !== void 0;
7284
- /** Tries at a wake-up before it's left to the next match or sweep, well short of A2's dead letter. */
7285
- const WAKE_TRIES = 3;
7286
- /** A watcher writes as `board:watch:<id>`, and its own writes never wake it. */
7287
- const actorOf = (id) => `board:watch:${id}`;
7288
- /** `watch:@<principal>`: everything one registrant's watchers matched, queued for it to pull. */
7289
- const registrantSession = (owner) => watchSession(`@${owner}`);
7290
- /**
7291
- * Watchers: a board-contract consumer matches each event against every
7292
- * watcher's filters, the way a tail does, and appends what matched to that
7293
- * watcher's session, where `run` happens on the thread's lane.
7294
- */
7295
- function createWatchers(options) {
7296
- const watchers = Object.entries(options.watch).map(([id, watcher]) => {
7297
- if (!ID.test(id)) throw new Error(`watch: ids use lowercase letters, numbers, - and _, got: ${id}`);
7298
- return {
7299
- id,
7300
- ...compileWatcher(id, watcher)
7301
- };
7302
- });
7303
- const byId = new Map(watchers.map((watcher) => [watcher.id, watcher]));
7304
- let reads = null;
7305
- /** Runs a watcher on a board event it matched, one thread at a time. */
7306
- const runner = consumer({
7307
- contract: watchContract,
7308
- name: "board-watch",
7309
- types: ["watch.matched"],
7310
- lane: ({ event }) => `thread:${event.payload.thread}`
7311
- }).run(async (ctx) => {
7312
- const watcher = byId.get(ctx.session.id.slice(6));
7313
- if (!watcher) return;
7314
- await runMatch({
7315
- watcher: {
7316
- id: watcher.id,
7317
- run: (event) => options.run(watcher.id, event, ctx.event.id, ctx.attempt)
7318
- },
7319
- match: ctx.event,
7320
- attempt: ctx.attempt,
7321
- record: (payload) => ctx.session.append(`failed:${ctx.event.id}`, {
7322
- type: "watch.failed",
7323
- payload
7324
- })
7325
- });
7326
- });
7327
- /**
7328
- * Wakes a registrant's board when it has something to pull: a new match, a wait after an error
7329
- * that's over, or a sweep that finds a lease ran out. A registrant's wake-ups go one at a time,
7330
- * and only when there's something to pull: its board pulls until nothing's left, so a burst of
7331
- * matches wakes it once. One that doesn't get there waits a minute for the next, doubling to an
7332
- * hour while they keep failing, until its board answers one, pulls, or registers.
7333
- */
7334
- const waker = consumer({
7335
- contract: watchContract,
7336
- name: "board-wake",
7337
- types: ["watch.matched", "watch.due"],
7338
- lane: ({ event }) => "thread" in event.payload && (!queued(event.payload) || event.payload.inbox !== void 0) ? null : "wake"
7339
- }).run(async (ctx) => {
7340
- const key = ctx.session.id.slice(6);
7341
- const registered = options.registered;
7342
- if (!key.startsWith("@") || !registered) return;
7343
- if (ctx.event.type === "watch.matched" && (!queued(ctx.event.payload) || ctx.event.payload.inbox !== void 0)) return;
7344
- const queue = server.session(ctx.session.id);
7345
- try {
7346
- const state = ctx.event.type === "watch.due" ? await due(queue, ctx.event.payload) : (await queue.state(queueReducer)).state;
7347
- if (!hasWork(state, Date.now())) return;
7348
- const registration = (await registered.state()).byOwner[key.slice(1)];
7349
- if (!registration || registration.url === null) return;
7350
- const { url } = registration;
7351
- const now = Date.now();
7352
- if (state.unreachable && state.unreachable.until > now) return;
7353
- const woken = await registered.wake({
7354
- ...registration,
7355
- url
7356
- });
7357
- if (woken.reached) {
7358
- if (state.unreachable) await queue.append({
7359
- type: "watch.reachable",
7360
- payload: { by: "wake" }
7361
- });
7362
- return;
7363
- }
7364
- const failures = (state.unreachable?.failures ?? 0) + 1;
7365
- const until = now + wakeBackoff(failures);
7366
- if (failures === 1) console.error(`[board] couldn't wake ${url}: ${woken.why}`);
7367
- if (failures === 2) console.error(`[board] couldn't wake ${url} again (${woken.why}): trying less often, up to once an hour, until it answers, pulls, or registers`);
7368
- if (options.scheduler) await arm(queue, state, until);
7369
- await queue.append({
7370
- type: "watch.unreachable",
7371
- payload: {
7372
- failures,
7373
- until,
7374
- why: woken.why.slice(0, 200) || "unknown error"
7375
- }
7376
- });
7377
- } catch (error) {
7378
- if (ctx.attempt < WAKE_TRIES) throw error;
7379
- console.error(`[board] couldn't wake the board of ${key.slice(1)}:`, error.message);
7380
- }
7381
- });
7382
- const server = createServer({
7383
- contract: watchContract,
7384
- ...options.store ? { store: options.store } : {},
7385
- ...options.scheduler ? { scheduler: options.scheduler } : {},
7386
- consumers: [runner, waker]
7387
- });
7388
- const configured = watchers.map((watcher) => ({
7389
- ...watcher,
7390
- actor: actorOf(watcher.id)
7391
- }));
7392
- const compiled = /* @__PURE__ */ new Map();
7393
- function compiledFor(registration) {
7394
- const version = `${registration.hash}\u001f${JSON.stringify(registration.principal)}`;
7395
- const hit = compiled.get(registration.owner);
7396
- if (hit?.version === version) return hit.candidates;
7397
- const candidates = [];
7398
- for (const [id, spec] of Object.entries(registration.watch)) try {
7399
- candidates.push({
7400
- ...compileWatcher(id, spec),
7401
- id,
7402
- actor: `${registration.owner}+${id.toLowerCase()}`,
7403
- registration
7404
- });
7405
- } catch (error) {
7406
- console.error(`[board] skipping a watcher ${registration.owner} registered:`, error.message);
7407
- }
7408
- compiled.set(registration.owner, {
7409
- version,
7410
- candidates
7411
- });
7412
- return candidates;
7413
- }
7414
- async function registrations() {
7415
- return options.registered ? Object.values((await options.registered.state()).byOwner) : [];
7416
- }
7417
- /** Matches one board event; the message before or after it must match, as in a tail. */
7418
- async function dispatch(ctx) {
7419
- const event = ctx.event;
7420
- const through = event.index - 1;
7421
- const [messages, { state: actors }] = await Promise.all([messagesBefore(event, ctx.signal), ctx.session.state(actorsReducer, { through })]);
7422
- const { id, before, after } = foldEvent(messages, actors, event);
7423
- const by = event.payload.by?.actor;
7424
- const message = after ?? before;
7425
- const thread = event.payload.thread;
7426
- let view$1;
7427
- /** Each session's matches, appended together: one append per watcher in config, one per registrant. */
7428
- const appends = /* @__PURE__ */ new Map();
7429
- const add = (session, matched) => (appends.get(session) ?? appends.set(session, []).get(session)).push(matched);
7430
- const registered = await registrations();
7431
- const targets = [...configured, ...registered.flatMap(compiledFor)];
7432
- const registrants = /* @__PURE__ */ new Map();
7433
- const accessOf = (registration) => {
7434
- let found = registrants.get(registration.owner);
7435
- if (!found) registrants.set(registration.owner, found = options.registered.accessNow(registration.principal));
7436
- return found;
7437
- };
7438
- for (const watcher of targets) {
7439
- if (event.type === "thread.synced") break;
7440
- if (by === watcher.actor) continue;
7441
- if (RECEIPTS.has(event.type) && !watcher.all) continue;
7442
- const { registration } = watcher;
7443
- let access = FULL_ACCESS;
7444
- if (registration) {
7445
- const now = await accessOf(registration);
7446
- if (!now || (id === null ? !now.readsAll : !message || !now.readable(message.channel))) continue;
7447
- access = now;
7448
- }
7449
- const match = compileFilter(watcher.filters, {
7450
- me: null,
7451
- actors,
7452
- messages,
7453
- access
7454
- });
7455
- if (!(watcher.criteria ? match(before) || match(after) : id !== null)) continue;
7456
- const key = registration ? `@${registration.owner}/${watcher.id}` : watcher.id;
7457
- const shown = registration ? eventView(event, after, actors, await reads.reader(access, after ? [after] : [])) : view$1 ??= eventView(event, after, actors, OWN_CODE);
7458
- add(registration ? registrantSession(registration.owner) : watchSession(watcher.id), {
7459
- type: "watch.matched",
7460
- id: await idempotentId("board-watch", key, event.id),
7461
- payload: {
7462
- thread,
7463
- event: shown,
7464
- ...registration ? { watcher: watcher.id } : {}
7465
- }
7466
- });
7467
- }
7468
- const syncing = SYNCED.has(event.type) ? registered.filter((registration) => registration.sync.length > 0) : [];
7469
- if (syncing.length > 0) {
7470
- const about = event.type === "thread.synced" ? await rootOf(event.payload.thread, event.index, ctx.signal) : message;
7471
- for (const registration of syncing) {
7472
- const now = await accessOf(registration);
7473
- if (!now || !about || !now.can("sync", about.channel)) continue;
7474
- const reader = await reads.reader(now, [about, ...before ? [before] : []]);
7475
- const shown = {
7476
- ...eventView(event, about, actors, reader),
7477
- ...event.type === "labels.changed" && before ? { before: view(before, actors, reader) } : {}
7478
- };
7479
- add(registrantSession(registration.owner), {
7480
- type: "watch.matched",
7481
- id: await idempotentId("board-watch", `@${registration.owner}/@sync`, event.id),
7482
- payload: {
7483
- thread,
7484
- event: shown,
7485
- sync: true
7486
- }
7487
- });
7488
- }
7489
- }
7490
- await Promise.all([...appends].map(async ([session, events]) => {
7491
- try {
7492
- await server.session(session).append(...events);
7493
- } catch (error) {
7494
- if (!(error instanceof A2Error && error.code === "PARTIAL_DUPLICATE_BATCH")) throw error;
7495
- for (const matched of events) await server.session(session).append(matched);
7496
- }
7497
- }));
7498
- }
7499
- /** A thread's root, as the board has it once the tables reach `index`: the event that synced it comes after it. */
7500
- async function rootOf(thread, index, signal) {
7501
- if (!reads) throw new Error("watchers used before the board bound them");
7502
- await reads.ensure(index - 1, signal);
7503
- return await reads.tables.byEventId(thread) ?? void 0;
7504
- }
7505
- /** The message `event` concerns, and its thread's root, as they were just before it. */
7506
- async function messagesBefore(event, signal) {
7507
- if (!reads) throw new Error("watchers used before the board bound them");
7508
- return loadBefore(reads, event, signal);
7509
- }
7510
- return {
7511
- server,
7512
- boardConsumer: consumer({
7513
- contract: boardContract,
7514
- name: "board-watchers",
7515
- types: WATCHED,
7516
- lane: ({ event }) => `thread:${event.payload.thread}`
7517
- }).run(dispatch),
7518
- bind: (binding) => {
7519
- reads = binding.reads;
7520
- }
7521
- };
7522
- }
7523
- //#endregion
7524
- //#region src/server/transport.ts
7525
- /** Addresses a wake-up never reaches: this machine, private networks, link-local, and the rest that aren't the internet. */
7526
- const NOT_PUBLIC = new BlockList();
7527
- for (const [network, prefix] of [
7528
- ["0.0.0.0", 8],
7529
- ["10.0.0.0", 8],
7530
- ["100.64.0.0", 10],
7531
- ["127.0.0.0", 8],
7532
- ["169.254.0.0", 16],
7533
- ["172.16.0.0", 12],
7534
- ["192.0.0.0", 24],
7535
- ["192.168.0.0", 16],
7536
- ["198.18.0.0", 15],
7537
- ["224.0.0.0", 4],
7538
- ["240.0.0.0", 4]
7539
- ]) NOT_PUBLIC.addSubnet(network, prefix, "ipv4");
7540
- for (const [network, prefix] of [
7541
- ["::", 127],
7542
- ["64:ff9b::", 96],
7543
- ["64:ff9b:1::", 48],
7544
- ["100::", 64],
7545
- ["2001::", 32],
7546
- ["2002::", 16],
7547
- ["fc00::", 7],
7548
- ["fe80::", 10],
7549
- ["fec0::", 10],
7550
- ["ff00::", 8]
7551
- ]) NOT_PUBLIC.addSubnet(network, prefix, "ipv6");
7552
- /** Whether `address` is one a wake-up may connect to. */
7553
- const isPublicAddress = (address) => {
7554
- const family = isIP(address);
7555
- return family !== 0 && !NOT_PUBLIC.check(address, family === 4 ? "ipv4" : "ipv6");
7556
- };
7557
- /** Resolves as the system does, and refuses a name that resolves to any address that isn't public. */
7558
- const publicLookup = (hostname, options, callback) => {
7559
- lookup(hostname, {
7560
- ...options,
7561
- all: true
7562
- }, (error, found) => {
7563
- if (error) return callback(error, "", 0);
7564
- const addresses = found;
7565
- const bad = addresses.find((entry) => !isPublicAddress(entry.address));
7566
- if (bad || addresses.length === 0) return callback(Object.assign(/* @__PURE__ */ new Error(`${hostname} resolves to ${bad?.address ?? "nothing"}, which isn't a public address`), { code: "ENOTPUBLIC" }), "", 0);
7567
- if (options.all) return callback(null, addresses);
7568
- callback(null, addresses[0].address, addresses[0].family);
7569
- });
7570
- };
7571
- /** A response body is read only as far as an error message needs. */
7572
- const ERROR_BYTES = 4096;
7573
- /** Statuses a `Response` has no body with. */
7574
- const NULL_BODY = /* @__PURE__ */ new Set([
7575
- 204,
7576
- 205,
7577
- 304
7578
- ]);
7579
- /**
7580
- * A wake-up's answer as a `Response`, whatever status the other end chose: one with no body has
7581
- * none, and one a `Response` can't have (outside 200 to 599) is a 502.
7582
- */
7583
- function responseOf(status, body) {
7584
- if (status === void 0 || !Number.isInteger(status) || status < 200 || status > 599) return new Response(null, { status: 502 });
7585
- return new Response(NULL_BODY.has(status) ? null : body, { status });
7586
- }
7587
- /** POSTs to a public `https` URL: the default `Post`. */
7588
- async function publicPost(url, init) {
7589
- const target = new URL(url);
7590
- if (target.protocol !== "https:") throw new Error(`wake-ups go over https, not to ${url}`);
7591
- const host = target.hostname.replace(/^\[|\]$/g, "");
7592
- if (isIP(host) && !isPublicAddress(host)) throw new Error(`${host} isn't a public address`);
7593
- return new Promise((resolve, reject) => {
7594
- const sent = request(target, {
7595
- method: "POST",
7596
- headers: {
7597
- ...init.headers,
7598
- "content-length": String(Buffer.byteLength(init.body))
7599
- },
7600
- lookup: publicLookup,
7601
- signal: init.signal
7602
- }, (response) => {
7603
- const chunks = [];
7604
- let size = 0;
7605
- response.on("data", (chunk) => {
7606
- if (size < ERROR_BYTES) chunks.push(chunk);
7607
- size += chunk.length;
7608
- });
7609
- response.on("end", () => {
7610
- try {
7611
- resolve(responseOf(response.statusCode, Buffer.concat(chunks).subarray(0, ERROR_BYTES)));
7612
- } catch (error) {
7613
- reject(error);
7614
- }
7615
- });
7616
- response.on("error", reject);
7617
- });
7618
- sent.on("error", reject);
7619
- sent.end(init.body);
7620
- });
7621
- }
7622
- //#endregion
7623
7564
  //#region src/server/a2.ts
7624
- /** Sync's own lookups and receipts, from board() in this deployment. */
7625
- const SYNC_ACTOR = "board:sync";
7626
7565
  /** The board's own code, through its handle: `team.post(…)`. With `as(profile)`, `board:client:<profile>`. */
7627
7566
  const CLIENT_ACTOR = "board:client";
7628
7567
  /** A cursor or message ref in a request, as this board's log index: decimals, from 0. */
@@ -7653,8 +7592,6 @@ function scheduleAt(value) {
7653
7592
  return index;
7654
7593
  }
7655
7594
  new AbortController().signal;
7656
- /** A wake-up only has to arrive: the board it wakes answers once what it pulls has run, or after 2 seconds while it keeps going. */
7657
- const WAKE_TIMEOUT_MS = 5e3;
7658
7595
  /**
7659
7596
  * `idempotentId`'s shape, a UUIDv8: the IDs the board derives for its own writes (schedule
7660
7597
  * sends, watchers, sync). They're guessable, so an API caller can't post with one and take it first.
@@ -7687,6 +7624,11 @@ function selfIdentity(caller) {
7687
7624
  if (!ID.test(self)) throw badRequest(`as: profiles use lowercase letters, numbers, - and _, got: ${self}`);
7688
7625
  return deploymentIdentity(`${CLIENT_ACTOR}:${self}`, self);
7689
7626
  }
7627
+ /** An actor's name as people see it, with who it acts through: `Malte via www (preview)`. */
7628
+ const shownOf = (actor) => actor ? shownName({
7629
+ name: actor.name,
7630
+ via: viaOfRecord(actor)
7631
+ }) : void 0;
7690
7632
  /** A schedule as its creator sees it where it can't read: its text as a blind writer's message's is. */
7691
7633
  const blindSchedule = (schedule, access, own) => access.readable(schedule.channel) ? schedule : {
7692
7634
  ...schedule,
@@ -7694,32 +7636,40 @@ const blindSchedule = (schedule, access, own) => access.readable(schedule.channe
7694
7636
  };
7695
7637
  /**
7696
7638
  * A platform user, writing through sync: full access, and each write still proved against the
7697
- * channel it lands in. Their avatar is an https URL or none. `records`: the write keeps the
7698
- * board's record of who they are, which only a sync that may sync everywhere does.
7639
+ * channel it lands in. Their avatar is an https URL or none. This board's own sync checked the
7640
+ * platform said so, so its platform users are themselves (`slack:user:U0456`); a sync elsewhere's
7641
+ * are its word, a profile of its principal (`vercel:project:prj_1:production+slack:user:U0456`),
7642
+ * whose record only its own imports change.
7699
7643
  */
7700
- function externalIdentity(author, records) {
7644
+ function externalIdentity(author, through, platform) {
7645
+ const id = through === null ? author.id : `${through.id}+${author.id}`;
7646
+ const host = through?.facts?.issuer === "host" ? { facts: through.facts } : {};
7647
+ const principal = {
7648
+ id: through?.id ?? author.id,
7649
+ kind: "external",
7650
+ handle: author.handle,
7651
+ access: FULL_ACCESS,
7652
+ expiresAt: null,
7653
+ ...host
7654
+ };
7701
7655
  return {
7702
- principal: {
7703
- id: author.id,
7704
- kind: "external",
7705
- handle: author.handle,
7706
- access: FULL_ACCESS,
7707
- expiresAt: null
7708
- },
7656
+ principal,
7709
7657
  author: {
7710
- actor: author.id,
7711
- principal: author.id,
7712
- profile: null,
7658
+ actor: id,
7659
+ principal: principal.id,
7660
+ profile: through === null ? null : author.id,
7713
7661
  session: null
7714
7662
  },
7715
7663
  actor: {
7716
- id: author.id,
7664
+ id,
7717
7665
  kind: "external",
7718
- handle: author.handle,
7666
+ handle: through === null ? author.handle : importedHandle(viaOf(through).name, author.handle, userIdOf(author.id)),
7719
7667
  name: author.name,
7720
- avatar: platformAvatar(author.avatar)
7721
- },
7722
- ...records ? {} : { records: false }
7668
+ avatar: platformAvatar(author.avatar),
7669
+ ...through === null ? {} : { via: viaOf(through) },
7670
+ platform,
7671
+ ...through !== null && !through.id.startsWith("board:") ? { verified: true } : {}
7672
+ }
7723
7673
  };
7724
7674
  }
7725
7675
  /** The board events sync delivers: what a platform shows, and a thread's new targets. */
@@ -7766,7 +7716,6 @@ function build(options, binding) {
7766
7716
  const identityOf = async (caller) => "identity" in caller ? caller.identity : selfIdentity(caller);
7767
7717
  /** Its own code's handle, which reaches it in process. */
7768
7718
  let ownHandle = null;
7769
- const post = options.transport?.post ?? publicPost;
7770
7719
  const watchers = createWatchers({
7771
7720
  watch: Object.fromEntries(Object.entries(binding.subscriptions).flatMap(([id, subscription]) => subscription.kind === "tail" ? [[id, { tail: subscription.tail }]] : [])),
7772
7721
  run: (id, event, trigger, attempt) => binding.run(id, event, {
@@ -7777,8 +7726,7 @@ function build(options, binding) {
7777
7726
  scheduler: options.scheduler,
7778
7727
  registered: {
7779
7728
  state: registry.state,
7780
- accessNow: (principal) => binding.accessNow(principal),
7781
- wake
7729
+ accessNow: (principal) => binding.accessNow(principal)
7782
7730
  }
7783
7731
  });
7784
7732
  const schedules = createSchedules({
@@ -7803,7 +7751,7 @@ function build(options, binding) {
7803
7751
  const { before, after } = foldEvent(messages, actors, event);
7804
7752
  const shown = {
7805
7753
  ...eventView(event, event.type === "thread.synced" ? (await reads.ensure(event.index - 1, ctx.signal), await store.tables.byEventId(event.payload.thread)) ?? void 0 : after, actors, OWN_CODE),
7806
- ...event.type === "labels.changed" && before ? { before: view(before, actors, OWN_CODE) } : {}
7754
+ ...event.type === "labels.changed" && before ? { before: view$1(before, actors, OWN_CODE) } : {}
7807
7755
  };
7808
7756
  await delivering.run(ctx, () => binding.run(SYNC, shown, {
7809
7757
  trigger: ctx.event.id,
@@ -7856,6 +7804,7 @@ function build(options, binding) {
7856
7804
  explain: (principal, channel) => binding.explain(principal, channel),
7857
7805
  team: async () => (await binding.project()).teamId
7858
7806
  });
7807
+ const schemaRegistry = createSchemas({ store: log });
7859
7808
  const inboxes = inboxServer.session(INBOXES_SESSION);
7860
7809
  /** The inboxes this instance knows have an `inbox.opened`, so most pushes write nothing more. */
7861
7810
  const opened = /* @__PURE__ */ new Set();
@@ -7891,7 +7840,7 @@ function build(options, binding) {
7891
7840
  through: index
7892
7841
  };
7893
7842
  }
7894
- /** Who wrote, was mentioned, or reacted in the channels `access` reads, a page at a time. */
7843
+ /** Who wrote, was mentioned by actor ID (`@[actor-id]`), or reacted in the channels `access` reads, a page at a time. */
7895
7844
  async function actorsIn(access) {
7896
7845
  const ids = /* @__PURE__ */ new Set();
7897
7846
  const { filter } = await readable({}, access);
@@ -7902,7 +7851,7 @@ function build(options, binding) {
7902
7851
  });
7903
7852
  for (const message of messages) {
7904
7853
  ids.add(message.by.actor);
7905
- for (const id of message.mentions) ids.add(id);
7854
+ for (const token of extractMentions(message.text)) if (token.kind === "actor" && !isEmail(token.actor)) ids.add(token.actor);
7906
7855
  for (const reactors of Object.values(message.reactions)) for (const id of reactors) ids.add(id);
7907
7856
  }
7908
7857
  if (messages.length < 500) return ids;
@@ -7915,33 +7864,6 @@ function build(options, binding) {
7915
7864
  if (!await attachmentReadable(principal, id, uploader)) throw attachmentNotFound(id);
7916
7865
  return attachment;
7917
7866
  }));
7918
- /**
7919
- * Tells a registrant's board it has matches to pull, with no event and no credential in it: its
7920
- * board pulls them with its own credentials, and lets this POST through its own protection. The hash says whether its registration is stale. Says whether the
7921
- * wake-up got there: an answer, or still pulling when the wait ran out.
7922
- */
7923
- async function wake(registration) {
7924
- try {
7925
- const response = await post(`${registration.url}/wake`, {
7926
- headers: {
7927
- "content-type": "application/json",
7928
- "x-board-watchers": registration.hash
7929
- },
7930
- body: "{}",
7931
- signal: AbortSignal.timeout(WAKE_TIMEOUT_MS)
7932
- });
7933
- return response.ok ? { reached: true } : {
7934
- reached: false,
7935
- why: String(response.status)
7936
- };
7937
- } catch (error) {
7938
- if (error.name === "TimeoutError") return { reached: true };
7939
- return {
7940
- reached: false,
7941
- why: error.message
7942
- };
7943
- }
7944
- }
7945
7867
  /** A registrant's queue, in the watch contract: its watchers' and sync's matches, and its inbox. */
7946
7868
  const queueOf = (owner) => watchers.server.session(registrantSession(owner));
7947
7869
  /**
@@ -7974,7 +7896,7 @@ function build(options, binding) {
7974
7896
  if (fromRequest(caller) && body.id?.startsWith("sync:")) throw badRequest("id: sync:… IDs are what sync imports, under the principal that imports them");
7975
7897
  const attachments = await attachmentsFor(principal, body.attachments);
7976
7898
  const { schedule } = caller.origin;
7977
- const { unknownMentions, ...message } = await writePost(writes, {
7899
+ return { message: await writePost(writes, {
7978
7900
  attachments,
7979
7901
  identity,
7980
7902
  proofs,
@@ -7986,15 +7908,8 @@ function build(options, binding) {
7986
7908
  id: body.id,
7987
7909
  sync: body.sync,
7988
7910
  after: afterAt(body.after),
7989
- ...schedule && !fromRequest(caller) ? {
7990
- schedule,
7991
- lenientMentions: true
7992
- } : {}
7993
- });
7994
- return {
7995
- message,
7996
- ...unknownMentions ? { unknownMentions } : {}
7997
- };
7911
+ ...schedule && !fromRequest(caller) ? { schedule } : {}
7912
+ }) };
7998
7913
  }
7999
7914
  /**
8000
7915
  * The sync entry an import says it came through, when it names one: one its caller syncs, or a
@@ -8026,6 +7941,7 @@ function build(options, binding) {
8026
7941
  name: actor.name,
8027
7942
  avatar: actor.avatar,
8028
7943
  profile: author.profile,
7944
+ ...actor.via ? { via: { ...actor.via } } : {},
8029
7945
  session: author.session,
8030
7946
  expiresAt: principal.expiresAt?.toISOString() ?? null,
8031
7947
  can: principal.access.summary()
@@ -8055,7 +7971,15 @@ function build(options, binding) {
8055
7971
  seen = (id) => ids.has(id);
8056
7972
  }
8057
7973
  return {
8058
- actors: Object.values(state.byId).filter((a) => seen === null || seen(a.id)).sort((a, b) => a.handle.localeCompare(b.handle)).map(({ host: _host, ...a }) => a),
7974
+ actors: Object.values(state.byId).filter((a) => seen === null || seen(a.id)).sort((a, b) => a.handle.localeCompare(b.handle)).map((found) => {
7975
+ const { host: _host, via: _via, ...a } = found;
7976
+ const via = viaOfRecord(found);
7977
+ return {
7978
+ ...a,
7979
+ ...via ? { via } : {},
7980
+ ...verifiedRecord(found) ? { verified: true } : {}
7981
+ };
7982
+ }),
8059
7983
  cursor: ref(index)
8060
7984
  };
8061
7985
  },
@@ -8063,8 +7987,12 @@ function build(options, binding) {
8063
7987
  const { principal, actor } = await identityOf(caller);
8064
7988
  const { state: actors } = await session.state(actorsReducer);
8065
7989
  const { filter, through } = await readable(toMessageFilter(query, {
8066
- me: actor.id,
8067
- actors
7990
+ me: {
7991
+ id: actor.id,
7992
+ handle: actor.handle
7993
+ },
7994
+ actors,
7995
+ access: principal.access
8068
7996
  }), principal.access);
8069
7997
  const { messages, position } = await reads.messages(filter, {
8070
7998
  ...query.before !== void 0 ? { before: cursorAt(query.before) } : {},
@@ -8073,7 +8001,7 @@ function build(options, binding) {
8073
8001
  });
8074
8002
  const reader = await reads.reader(principal.access, messages);
8075
8003
  return {
8076
- messages: messages.map((m) => view(m, actors, reader)),
8004
+ messages: messages.map((m) => view$1(m, actors, reader)),
8077
8005
  cursor: ref(Math.min(position, through))
8078
8006
  };
8079
8007
  },
@@ -8081,8 +8009,12 @@ function build(options, binding) {
8081
8009
  const { principal, actor } = await identityOf(caller);
8082
8010
  const { state: actors } = await session.state(actorsReducer);
8083
8011
  const { filter, through } = await readable(toMessageFilter(query, {
8084
- me: actor.id,
8085
- actors
8012
+ me: {
8013
+ id: actor.id,
8014
+ handle: actor.handle
8015
+ },
8016
+ actors,
8017
+ access: principal.access
8086
8018
  }), principal.access);
8087
8019
  const { threads, position } = await reads.threads(filter, {
8088
8020
  ...query.after !== void 0 ? { after: cursorAt(query.after) } : {},
@@ -8091,9 +8023,9 @@ function build(options, binding) {
8091
8023
  const reader = await reads.reader(principal.access, threads.flatMap((t) => t.last ? [t.root, t.last] : [t.root]));
8092
8024
  return {
8093
8025
  threads: threads.map((t) => ({
8094
- message: view(t.root, actors, reader),
8026
+ message: view$1(t.root, actors, reader),
8095
8027
  replies: t.replies,
8096
- last: t.last && view(t.last, actors, reader)
8028
+ last: t.last && view$1(t.last, actors, reader)
8097
8029
  })),
8098
8030
  cursor: ref(Math.min(position, through))
8099
8031
  };
@@ -8107,8 +8039,8 @@ function build(options, binding) {
8107
8039
  const [root, ...replies] = messages;
8108
8040
  const reader = await reads.reader(principal.access, messages);
8109
8041
  return {
8110
- message: view(root, actors, reader),
8111
- replies: replies.map((reply) => view(reply, actors, reader)),
8042
+ message: view$1(root, actors, reader),
8043
+ replies: replies.map((reply) => view$1(reply, actors, reader)),
8112
8044
  cursor: ref(cursor),
8113
8045
  schedules: await schedules.forThread(root.id)
8114
8046
  };
@@ -8126,16 +8058,13 @@ function build(options, binding) {
8126
8058
  async edit(caller, { id, text, revision }) {
8127
8059
  const identity = await identityOf(caller);
8128
8060
  const authorized = await authorizeOwn(writes, identity, messageAt(id), "edit");
8129
- const { unknownMentions } = await writeEdit(writes, {
8061
+ await writeEdit(writes, {
8130
8062
  identity,
8131
8063
  authorized,
8132
8064
  text,
8133
8065
  revision
8134
8066
  });
8135
- return {
8136
- ok: true,
8137
- ...unknownMentions ? { unknownMentions } : {}
8138
- };
8067
+ return { ok: true };
8139
8068
  },
8140
8069
  async delete(caller, { id, revision }) {
8141
8070
  const identity = await identityOf(caller);
@@ -8212,6 +8141,9 @@ function build(options, binding) {
8212
8141
  tokens: async (caller) => access.tokens(await identityOf(caller)),
8213
8142
  createToken: async (caller, body) => access.createToken(await identityOf(caller), body),
8214
8143
  revokeToken: async (caller, input) => access.revokeToken(await identityOf(caller), input),
8144
+ schemas: async () => schemaRegistry.schemas(),
8145
+ schema: async (_caller, input) => schemaRegistry.schema(input),
8146
+ createSchema: async (caller, body) => schemaRegistry.createSchema(await identityOf(caller), body),
8215
8147
  async upload(caller, { data, name, type }) {
8216
8148
  const { principal } = await identityOf(caller);
8217
8149
  if (!principal.access.anywhere("post") && !principal.access.anywhere("sync")) throw forbidden$1("this token can't post anywhere, so it can't upload");
@@ -8254,7 +8186,8 @@ function build(options, binding) {
8254
8186
  return { watchers: principal.access.everywhere("manage") ? all : all.filter((found) => found.owner === principal.id) };
8255
8187
  },
8256
8188
  async register(caller, body) {
8257
- if (body.path) throw new HttpError(501, "no_wake_by_path", "this board wakes a url, not a path: register `url` instead");
8189
+ if (body.path) throw new HttpError(501, "no_wake_by_path", "this board wakes nothing: register no path, and pull your matches");
8190
+ if (body.url) throw new HttpError(501, "no_wake_by_url", "this board wakes nothing: register no url, and pull your matches");
8258
8191
  const { principal } = await identityOf(caller);
8259
8192
  ownWatchers(principal);
8260
8193
  if (!principal.access.anywhere("read")) throw forbidden$1("this token can't read anywhere, so a watcher it registers would see nothing");
@@ -8270,17 +8203,11 @@ function build(options, binding) {
8270
8203
  throw badRequest(error.message, "bad_watcher");
8271
8204
  }
8272
8205
  }
8273
- const registered = await registry.register(storedPrincipal(principal), {
8274
- url: body.url ?? null,
8206
+ return registry.register(storedPrincipal(principal), {
8207
+ url: null,
8275
8208
  watch: body.watch,
8276
8209
  sync: body.sync ?? []
8277
8210
  });
8278
- const queue = queueOf(principal.id);
8279
- if ((await queue.state(queueReducer)).state.unreachable) await queue.append({
8280
- type: "watch.reachable",
8281
- payload: { by: "registration" }
8282
- });
8283
- return registered;
8284
8211
  },
8285
8212
  async matches(caller, query, signal) {
8286
8213
  const { principal } = await identityOf(caller);
@@ -8289,8 +8216,7 @@ function build(options, binding) {
8289
8216
  const queue = queueOf(principal.id);
8290
8217
  const pulling = {
8291
8218
  access: principal.access,
8292
- limit: query.limit ?? 10,
8293
- timers: options.scheduler !== void 0
8219
+ limit: query.limit ?? 10
8294
8220
  };
8295
8221
  const deadline = Date.now() + (query.wait ?? 0) * 1e3;
8296
8222
  for (let pause = 100;; pause = Math.min(pause * 2, 1e3)) {
@@ -8312,10 +8238,7 @@ function build(options, binding) {
8312
8238
  async ack(caller, { id, ...body }) {
8313
8239
  const { principal } = await identityOf(caller);
8314
8240
  ownWatchers(principal);
8315
- const result = await ack(queueOf(principal.id), id, body, {
8316
- now: Date.now(),
8317
- timers: options.scheduler !== void 0
8318
- });
8241
+ const result = await ack(queueOf(principal.id), id, body, { now: Date.now() });
8319
8242
  if (result === "gone") throw notFound(`no match ${id} is waiting for this token`, "no_match");
8320
8243
  if (result === "stale") throw new HttpError(409, "stale_lease", "that lease ran out, and the match was pulled again");
8321
8244
  return { ok: true };
@@ -8330,7 +8253,10 @@ function build(options, binding) {
8330
8253
  after,
8331
8254
  filters: query,
8332
8255
  all: query.all ?? false,
8333
- me: actor.id,
8256
+ me: {
8257
+ id: actor.id,
8258
+ handle: actor.handle
8259
+ },
8334
8260
  actors,
8335
8261
  access: principal.access
8336
8262
  }, (query.wait ?? 0) * 1e3, signal);
@@ -8412,15 +8338,11 @@ function build(options, binding) {
8412
8338
  },
8413
8339
  async syncImport(caller, body, signal) {
8414
8340
  const { principal } = await needSync(caller, "import", true);
8415
- await speaksFor(caller, principal.id, body.author, body.op === "seen" ? null : body.from);
8416
- const author = externalIdentity(body.author, recordsActors(caller, principal));
8417
- if (body.op === "seen") {
8418
- const { state: actors } = await session.state(actorsReducer);
8419
- const seen = author.records === false ? null : actorSeen(author.actor, actors);
8420
- if (seen) await session.append(seen);
8421
- return { message: null };
8422
- }
8341
+ const platform = await speaksFor(caller, principal.id, body.author, body.from);
8342
+ const author = externalIdentity(body.author, ownSync(caller) ? null : principal, platform);
8423
8343
  const may = (channel) => principal.access.can("sync", channel);
8344
+ const keys = ownSync(caller) ? [] : (await entriesOf(caller, principal.id)).map(({ key }) => key);
8345
+ const asNamed = (text) => keys.length === 0 ? text : replaceMentions(text, (token) => token.kind === "actor" && keys.some((key) => token.actor.startsWith(`${key}:`)) ? `@[${principal.id}+${token.actor}]` : null);
8424
8346
  if (body.op === "post") {
8425
8347
  if (body.channel === void 0 === (body.re === void 0)) throw badRequest("an import needs `channel`; a reply needs `re`");
8426
8348
  let re;
@@ -8446,7 +8368,7 @@ function build(options, binding) {
8446
8368
  proofs,
8447
8369
  channel: body.channel,
8448
8370
  re,
8449
- text,
8371
+ text: asNamed(text),
8450
8372
  labels,
8451
8373
  noSync: body.noSync,
8452
8374
  id,
@@ -8454,7 +8376,6 @@ function build(options, binding) {
8454
8376
  from: body.from,
8455
8377
  ...body.origin && !ownSync(caller) ? { importedBy: principal.id } : {},
8456
8378
  after: afterAt(body.after),
8457
- lenientMentions: true,
8458
8379
  attachments,
8459
8380
  links: await linksOf(principal, body.links)
8460
8381
  })).id;
@@ -8480,7 +8401,7 @@ function build(options, binding) {
8480
8401
  await writeEdit(writes, {
8481
8402
  identity: author,
8482
8403
  authorized: proof,
8483
- text,
8404
+ text: asNamed(text),
8484
8405
  from: body.from,
8485
8406
  asAuthor,
8486
8407
  revision: body.revision
@@ -8494,7 +8415,7 @@ function build(options, binding) {
8494
8415
  re: found.re === null ? null : ref(found.re),
8495
8416
  text: body.text
8496
8417
  };
8497
- if (!found.deleted && !(asAuthor && found.by.principal !== body.author.id)) await checkSource(caller, principal.id, body.source);
8418
+ if (!found.deleted && !(asAuthor && found.by.actor !== author.author.actor)) await checkSource(caller, principal.id, body.source);
8498
8419
  return { message: await commit(write) };
8499
8420
  }
8500
8421
  if (body.op === "delete") await writeDelete(writes, {
@@ -8686,8 +8607,7 @@ function build(options, binding) {
8686
8607
  return { items: (await pullInbox(queueOf(principal.id), key, {
8687
8608
  access: principal.access,
8688
8609
  limit: limit ?? 10,
8689
- now: Date.now(),
8690
- timers: options.scheduler !== void 0
8610
+ now: Date.now()
8691
8611
  })).map(({ id, thread, lease, attempt, event }) => {
8692
8612
  const item = event;
8693
8613
  return {
@@ -8706,10 +8626,7 @@ function build(options, binding) {
8706
8626
  const result = await ack(queueOf(principal.id), id, {
8707
8627
  lease,
8708
8628
  error
8709
- }, {
8710
- now: Date.now(),
8711
- timers: options.scheduler !== void 0
8712
- });
8629
+ }, { now: Date.now() });
8713
8630
  if (result === "gone") throw notFound(`no inbox event ${id} is waiting for this token`, "no_item");
8714
8631
  if (result === "stale") throw new HttpError(409, "stale_lease", "that lease ran out, and the event was pulled again");
8715
8632
  return { ok: true };
@@ -8779,15 +8696,18 @@ function build(options, binding) {
8779
8696
  return [...found.values()];
8780
8697
  }
8781
8698
  /**
8782
- * Whether a caller may write as `author`: a platform user, never anyone this board
8783
- * signs in, on a platform it syncs: the one of entry `from`, when it names one.
8699
+ * Whether a caller may write as `author`, and the platform of the sync key they're a user of: a
8700
+ * platform user, never anyone this board signs in, named under a key it syncs (`slack-eu:…`):
8701
+ * entry `from`, when it names one.
8784
8702
  */
8785
8703
  async function speaksFor(caller, principal, author, from) {
8786
8704
  if (authenticates(author.id) || await signedIn(author.id)) throw forbidden$1(`${author.id} is someone this board signs in, not a platform user: sync can't write as them`);
8787
8705
  const entries = await entriesOf(caller, principal);
8788
- const platforms = (from === null ? entries : entries.filter((entry) => entry.key === from)).map((entry) => entry.platform);
8789
- if (from !== null && platforms.length === 0) throw forbidden$1(`this token doesn't sync ${from} here: its board registers its sync entries`);
8790
- if (!platforms.some((platform) => author.id.startsWith(`${platform}:`))) throw forbidden$1(`${author.id} isn't a user of ${platforms.length ? platforms.join(" or ") : "a platform this token syncs"}`);
8706
+ const keys = from === null ? entries : entries.filter((entry) => entry.key === from);
8707
+ if (from !== null && keys.length === 0) throw forbidden$1(`this token doesn't sync ${from} here: its board registers its sync entries`);
8708
+ const entry = keys.find(({ key }) => author.id.startsWith(`${key}:`));
8709
+ if (!entry) throw forbidden$1(`${author.id} isn't a user of ${keys.length ? keys.map(({ key }) => key).join(" or ") : "a sync key this token has"}: their ID starts with its key`);
8710
+ return entry.platform;
8791
8711
  }
8792
8712
  /**
8793
8713
  * Whether `id` is someone this board signs in that `authenticates` can't tell by its shape: a
@@ -8815,14 +8735,6 @@ function build(options, binding) {
8815
8735
  if (principal.scope !== void 0) throw forbidden$1("this token is narrowed with x-board-can: registering and running watchers is its project's job");
8816
8736
  }
8817
8737
  /**
8818
- * Whether a sync's writes keep the board's record of the platform users they're by (name and
8819
- * avatar), which every channel shows: this board's own sync's, and those of one that may sync in every
8820
- * channel. Anyone else's still carry their author, and leave the record as it is.
8821
- */
8822
- function recordsActors(caller, principal) {
8823
- return ownSync(caller) || principal.access.everywhere("sync");
8824
- }
8825
- /**
8826
8738
  * The caller, when it may sync somewhere: what every sync route needs. `records`: what it does
8827
8739
  * keeps sync's records (imports, receipts, its inbox, links), which only an integration does,
8828
8740
  * never a caller narrowed with `x-board-can`.
@@ -8904,7 +8816,7 @@ function build(options, binding) {
8904
8816
  message: null
8905
8817
  };
8906
8818
  const snapshot = {
8907
- author: actors.byId[found.by.actor]?.name ?? found.by.actor,
8819
+ author: shownOf(actors.byId[found.by.actor]) ?? found.by.actor,
8908
8820
  text: found.text,
8909
8821
  createdAt: found.createdAt,
8910
8822
  files: found.attachments.map((file) => ({
@@ -9113,10 +9025,10 @@ function local(options = {}) {
9113
9025
  opening ??= (async () => {
9114
9026
  const file = localFile(bound.name);
9115
9027
  let store;
9116
- if (options.memory) store = (await import("./memory-DkoqhxIH.mjs")).memory();
9028
+ if (options.memory) store = (await import("./memory-BvVoglGv.mjs")).memory();
9117
9029
  else {
9118
9030
  const { mkdir } = await import("node:fs/promises");
9119
- const { sqlite } = await import("./sqlite-CAwNHbQD.mjs");
9031
+ const { sqlite } = await import("./sqlite-D4mkYihG.mjs");
9120
9032
  const path = join(dir, `${file}.db`);
9121
9033
  try {
9122
9034
  await mkdir(dir, {