@vercel/board 0.50.0 → 0.51.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 (88) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +128 -118
  3. package/dist/{access-BbgmsAFF.mjs → access-DdojoPZm.mjs} +1 -1
  4. package/dist/access.d.mts +2 -2
  5. package/dist/access.mjs +4 -4
  6. package/dist/{actors-CX2D22hL.mjs → actors-CDkNgWUL.mjs} +3 -3
  7. package/dist/{auth-Z9-Khvvw.d.mts → auth-C4VxPLYz.d.mts} +1 -1
  8. package/dist/{auth-DJDTfgAL.mjs → auth-zPqFJocD.mjs} +10 -3
  9. package/dist/{backend-CcaaS9Xl.d.mts → backend-Da_YEltI.d.mts} +16 -13
  10. package/dist/backend-local.d.mts +1 -1
  11. package/dist/backend-local.mjs +1 -1
  12. package/dist/{chat-provider-DQ1GHm4o.d.mts → chat-provider-BHyX6H8H.d.mts} +2 -2
  13. package/dist/{chat-provider-HJ7y_ipp.mjs → chat-provider-Br2RXgLV.mjs} +4 -3
  14. package/dist/cli-commands.d.mts +1 -1
  15. package/dist/cli-commands.mjs +1 -1
  16. package/dist/cli-embedded.d.mts +15 -7
  17. package/dist/cli-embedded.mjs +9 -6
  18. package/dist/cli.mjs +6 -6
  19. package/dist/{client-C2T4eaXd.d.mts → client-C4-r10SA.d.mts} +25 -4
  20. package/dist/{commands-Cm4sODIu.d.mts → commands-B6pgzwTI.d.mts} +10 -0
  21. package/dist/{commands-nN8WpvCe.mjs → commands-DB1T8vT9.mjs} +37 -10
  22. package/dist/{conformance-Cr-umDl0.mjs → conformance-DW4-9Dwf.mjs} +176 -64
  23. package/dist/conformance.d.mts +4 -3
  24. package/dist/conformance.mjs +1 -1
  25. package/dist/{engine-DJZ8Xy_g.mjs → engine-D8YAsQS_.mjs} +17 -9
  26. package/dist/{errors-DYF4hhIc.mjs → errors-DbCKqGXp.mjs} +35 -7
  27. package/dist/{events-BdOCmnZh.mjs → events-mWKc1uvZ.mjs} +1 -1
  28. package/dist/{exports-CuD-Mxkw.mjs → exports-BDE3eV7B.mjs} +593 -261
  29. package/dist/{exports-lmr6UHHc.d.mts → exports-BUtR_AHa.d.mts} +4 -4
  30. package/dist/{external-D2jq_DEQ.mjs → external-DkWafjn-.mjs} +5 -1
  31. package/dist/{index-_KxJu15n.d.mts → index-BTuTaBaK.d.mts} +2 -2
  32. package/dist/index.d.mts +6 -6
  33. package/dist/index.mjs +4 -4
  34. package/dist/index.node.d.mts +7 -7
  35. package/dist/index.node.mjs +4 -4
  36. package/dist/inspect/app.js +41 -41
  37. package/dist/inspect/engine.js +4 -4
  38. package/dist/inspect-BXvdLMET.mjs +2 -0
  39. package/dist/{inspect-CZeoSm7E.mjs → inspect-Nd_TlU1s.mjs} +3 -3
  40. package/dist/inspect.d.mts +1 -1
  41. package/dist/inspect.mjs +2 -2
  42. package/dist/{local-BVSFSSYf.mjs → local-BsYjQrl_.mjs} +113 -35
  43. package/dist/{main-B016auoG.mjs → main-CSIXhZ_b.mjs} +117 -36
  44. package/dist/{memory-C2lzMV_t.mjs → memory-wmUDblhm.mjs} +2 -2
  45. package/dist/{middleware-DUKIITFZ.mjs → middleware-iVTNf5Su.mjs} +1 -1
  46. package/dist/{profile-header-Cj0Cb1cf.mjs → profile-header-O8wC8yk8.mjs} +12 -1
  47. package/dist/{provider-Dwb_9mnu.d.mts → provider-CGicSMdu.d.mts} +4 -2
  48. package/dist/{routes-BE0y6wCk.mjs → routes-C85Sbhtm.mjs} +44 -11
  49. package/dist/{routes-B6SEA9yw.d.mts → routes-ChGBn0K3.d.mts} +60 -23
  50. package/dist/{serve-B10e7QaY.mjs → serve-Cp0qM4jk.mjs} +9 -8
  51. package/dist/{server-ViWNvg5q.mjs → server-HPq6MO3_.mjs} +50 -33
  52. package/dist/{serving-SbqeWqlA.mjs → serving-aOQsBok0.mjs} +1 -1
  53. package/dist/{shell-DmpmgOPC.mjs → shell-CUR5woOP.mjs} +1 -1
  54. package/dist/{sql-iABdyCiz.mjs → sql-D0MqINA6.mjs} +1 -1
  55. package/dist/{sqlite-28EMrmk7.mjs → sqlite-Dj2ZEtgy.mjs} +2 -2
  56. package/dist/{sqlite-db-Ckd-ceNe.mjs → sqlite-db-DjbTlUwN.mjs} +1 -1
  57. package/dist/sync-chat-sdk.d.mts +2 -2
  58. package/dist/sync-chat-sdk.mjs +2 -2
  59. package/dist/sync-github.d.mts +2 -2
  60. package/dist/sync-github.mjs +3 -3
  61. package/dist/sync-linear.d.mts +3 -3
  62. package/dist/sync-linear.mjs +3 -3
  63. package/dist/sync-slack.d.mts +21 -4
  64. package/dist/sync-slack.mjs +35 -11
  65. package/dist/sync.d.mts +2 -2
  66. package/dist/sync.mjs +2 -2
  67. package/dist/{tags-D0qra0Qy.mjs → tags-CxDCF_tt.mjs} +1 -1
  68. package/dist/{task-batch-9lVDG3d-.mjs → task-batch-D3ASL5_-.mjs} +53 -9
  69. package/dist/{tokens-C-iK0Cku.mjs → tokens-C-T0B1uF.mjs} +31 -7
  70. package/dist/{version-C70RLVEK.mjs → version-BJH1vWR0.mjs} +1 -1
  71. package/docs/01-board/01-mounting.md +20 -7
  72. package/docs/01-board/03-identity.md +1 -1
  73. package/docs/01-board/04-messages.md +5 -0
  74. package/docs/01-board/05-reading.md +71 -16
  75. package/docs/01-board/07-schedules.md +1 -1
  76. package/docs/01-board/10-local.md +1 -1
  77. package/docs/02-sync/01-overview.md +3 -3
  78. package/docs/02-sync/03-slack.md +4 -3
  79. package/docs/03-guides/01-coding-agents.md +1 -1
  80. package/docs/03-guides/02-inspector.md +13 -5
  81. package/docs/03-guides/07-build-a-ui.md +15 -11
  82. package/docs/04-reference/01-cli.md +64 -25
  83. package/docs/04-reference/02-board.md +48 -23
  84. package/docs/04-reference/03-http.md +33 -14
  85. package/docs/04-reference/05-conformance.md +11 -10
  86. package/docs/index.md +1 -1
  87. package/package.json +14 -2
  88. package/dist/inspect-UCcPViyA.mjs +0 -2
@@ -1,15 +1,15 @@
1
- import { i as ATTACHMENT_BYTES_MAX, l as mediaType, n as formatProfileHeader, o as IMPORT_BYTES_MAX, s as fileName } from "./profile-header-Cj0Cb1cf.mjs";
1
+ import { d as mediaType, i as ATTACHMENT_BYTES_MAX, n as formatProfileHeader, o as IMPORT_BYTES_MAX } from "./profile-header-O8wC8yk8.mjs";
2
2
  import { T as TASK_LABEL, b as RemoteWatcherId, y as RESERVED_LABEL_PREFIX } from "./schemas-CUSTEFIy.mjs";
3
- import { A as Ref, B as SyncBody, C as InboxQuery, D as MessagesQuery, E as MatchesQuery, F as ScheduleBody, G as TaskNeedsBody, H as SyncFindQuery, I as SchedulesQuery, J as TypingBody, K as TasksQuery, L as SchemaBody, M as ReleaseTaskBody, N as RenewTaskBody, O as PostBody, P as RevokeGrantBody, R as SourceJoinBody, S as InboxPushBody, T as LinkedQuery, U as SyncImportBody, V as SyncCopiesQuery, W as SyncReceiptBody, X as UploadStartBody, Y as UpdateGrantBody, Z as routes, _ as FailTaskBody, a as ClaimReadyTaskBody, b as InboxAckBody, c as CreateChannelBody, d as CreateTasksBody, f as CreatedTasksQuery, g as ExplainQuery, h as EventsQuery, i as CancelTaskBody, j as RegisterBody, k as ReactBody, l as CreateGrantsBody, m as EditBody, n as AssignTaskBody, o as ClaimTaskBody, p as DeleteBody, q as ThreadsQuery, r as BlockTaskBody, s as CompleteTaskBody, t as AckBody, u as CreateTaskBody, w as LabelBody, x as InboxNextQuery, y as GrantBody, z as SourceReadQuery } from "./routes-BE0y6wCk.mjs";
4
- import { a as duplicateId, c as notFound, d as unauthorized, f as BoardError, h as eventsState, i as batchTooLarge, m as duration, n as RejectedError, o as forbidden, p as createBoardClient, r as badRequest, s as json, t as HttpError, u as toErrorResponse } from "./errors-DYF4hhIc.mjs";
5
- import { _ as sha256, a as waitUntil, c as platformProfile, d as userIdOf, m as derivedId, o as actorParts, r as runMiddleware, s as importedHandle, t as DroppedError, u as underPrincipal } from "./middleware-DUKIITFZ.mjs";
3
+ import { $ as routes, A as ReactBody, B as SourceReadQuery, C as InboxNextQuery, D as LinkedQuery, E as LabelBody, F as RevokeGrantBody, G as SyncReceiptBody, H as SyncCopiesQuery, I as ScheduleBody, J as ThreadQuery, K as TaskNeedsBody, L as SchedulesQuery, M as RegisterBody, N as ReleaseTaskBody, O as MatchesQuery, P as RenewTaskBody, Q as UploadStartBody, R as SchemaBody, S as InboxAckBody, T as InboxQuery, U as SyncFindQuery, V as SyncBody, W as SyncImportBody, X as TypingBody, Y as ThreadsQuery, Z as UpdateGrantBody, _ as EventsQuery, a as ChannelMessagesQuery, c as ClaimTaskBody, d as CreateGrantsBody, f as CreateTaskBody, g as EditBody, h as DeleteBody, i as CancelTaskBody, j as Ref, k as PostBody, l as CompleteTaskBody, m as CreatedTasksQuery, n as AssignTaskBody, o as ChannelsQuery, p as CreateTasksBody, q as TasksQuery, r as BlockTaskBody, s as ClaimReadyTaskBody, t as AckBody, u as CreateChannelBody, v as ExplainQuery, w as InboxPushBody, x as GrantBody, y as FailTaskBody, z as SourceJoinBody } from "./routes-C85Sbhtm.mjs";
4
+ import { a as duplicateId, c as notFound, d as unauthorized, f as BoardError, h as eventsState, i as batchTooLarge, m as duration, n as RejectedError, o as forbidden, p as createBoardClient, r as badRequest, s as json, t as HttpError, u as toErrorResponse } from "./errors-DbCKqGXp.mjs";
5
+ import { _ as sha256, a as waitUntil, c as platformProfile, d as userIdOf, m as derivedId, o as actorParts, r as runMiddleware, s as importedHandle, t as DroppedError, u as underPrincipal } from "./middleware-iVTNf5Su.mjs";
6
6
  import { n as blocksIn, r as findBlocks } from "./blocks-CVoBC7ur.mjs";
7
7
  import { a as replaceMentions, i as mentionTerms, o as settleMentions, r as mentionTerm, t as extractMentions } from "./mentions-CnWt9Z5b.mjs";
8
- import { t as VERSION } from "./version-C70RLVEK.mjs";
9
- import { a as canText, c as compileAccess, d as parsePattern, n as InvalidCan, r as PERMISSIONS, t as FULL_ACCESS, u as parseCan } from "./access-BbgmsAFF.mjs";
10
- import { a as runMatch, d as openapi, f as queryObject, h as SYNC, i as canonicalWatchers, l as METHODS, m as readJson, n as SYNC_ACTOR, o as compileWatcher, p as readCapped, r as syncTarget, t as batchPlan, u as createRouter } from "./task-batch-9lVDG3d-.mjs";
11
- import { C as verifiesTokens, E as explainGrants, S as verifiedIssuers, d as createAuthority, f as fromTokens, m as hostPrincipal, o as VERCEL_ISSUER, p as grantIssuers, t as DEFAULT_CAN$1, v as namesByLogin } from "./auth-DJDTfgAL.mjs";
12
- import { a as resolveActor, o as viaOf, r as claimsOf, t as KNOWN_AGENTS } from "./actors-CX2D22hL.mjs";
8
+ import { t as VERSION } from "./version-BJH1vWR0.mjs";
9
+ import { a as canText, c as compileAccess, d as parsePattern, n as InvalidCan, r as PERMISSIONS, t as FULL_ACCESS, u as parseCan } from "./access-DdojoPZm.mjs";
10
+ import { _ as SYNC, a as runMatch, d as openapi, f as queryObject, g as uploadName, h as carried, i as canonicalWatchers, l as METHODS, m as readJson, n as SYNC_ACTOR, o as compileWatcher, p as readCapped, r as syncTarget, t as batchPlan, u as createRouter } from "./task-batch-D3ASL5_-.mjs";
11
+ import { C as verifiedIssuers, D as explainGrants, d as createAuthority, f as fromTokens, m as hostPrincipal, o as VERCEL_ISSUER, p as grantIssuers, t as DEFAULT_CAN$1, v as namesByLogin, w as verifiesTokens } from "./auth-zPqFJocD.mjs";
12
+ import { a as resolveActor, o as viaOf, r as claimsOf, t as KNOWN_AGENTS } from "./actors-CDkNgWUL.mjs";
13
13
  import { t as checkValue } from "./data-values-CoTP0SQG.mjs";
14
14
  //#region src/server/registrant.ts
15
15
  /** Registering again this soon after the same registration only repeats it. */
@@ -615,6 +615,15 @@ const isApiMessageId = (value) => MESSAGE_ID.test(value);
615
615
  const CURSOR = /^([0-9a-z]+)(?:\.([0-9a-z]+))?$/;
616
616
  /** The API's own cursor for one channel, which its message list and feed share, and any process resumes. */
617
617
  const API_CURSOR = /^c1\./;
618
+ /**
619
+ * In a position, the feed the API reads across channels in one: the whole board's, or a tree's
620
+ * (`dev/`), in place of a channel's ID. Its cursor says where it is by itself (`x1.<time>.<skip>.<the
621
+ * API's cursor>`), so any process reads on from it.
622
+ */
623
+ const ACROSS = "*";
624
+ const ACROSS_CURSOR = /^x1\.([0-9a-z]+)\.(\d+)\.(c1\..+)$/;
625
+ /** The longest cursor the protocol takes. */
626
+ const CURSOR_MAX = 128;
618
627
  /** The API's longest page of a channel's messages, and longest long-poll, in seconds. */
619
628
  const PAGE_MAX = 100;
620
629
  const WAIT_MAX_S = 25;
@@ -647,8 +656,8 @@ const BOARD_CODES = {
647
656
  409: "conflict",
648
657
  413: "too_large"
649
658
  };
650
- /** Pages a filtered read of one channel scans for matches before it answers with what it found. */
651
- const SCAN_PAGES = 10;
659
+ /** Pages a read of one channel after a cursor takes before it answers with what it has: 500 messages, and a few its caller's access left short. */
660
+ const AFTER_PAGES = 10;
652
661
  /** How long after it couldn't tell who its credentials are a board waits to ask again. */
653
662
  const WHO_AGAIN_MS = 1e4;
654
663
  /** A file as the board names it. */
@@ -658,7 +667,12 @@ const fileOf = ({ id, name, type, size }) => ({
658
667
  type,
659
668
  size
660
669
  });
661
- const notSupported = (what) => new HttpError(501, "not_supported", `Vercel's boards don't support ${what} yet`);
670
+ /** The reads the API answers with an `ETag` and, sent it back unchanged, a 304: a board's channels, one channel, and its actors. */
671
+ const TAGGED = /^\/boards\/[^/]+\/(channels(\/[^/]+)?|actors)$/;
672
+ /** How many of their answers are kept. */
673
+ const TAGGED_MAX = 200;
674
+ /** What Vercel's boards don't do, and with `instead`, what to do there. */
675
+ const notSupported = (what, instead) => new HttpError(501, "not_supported", `Vercel's boards don't support ${what} yet${instead ? `: ${instead}` : ""}`);
662
676
  /** What credentials may do when the API doesn't say: read, post, react, and label everywhere, as any it lets in. */
663
677
  const DEFAULT_CAN = { "*": [
664
678
  "read",
@@ -1038,6 +1052,8 @@ function createVercel(options, environment) {
1038
1052
  };
1039
1053
  /** What the API said of an error beside its code: a lost claim's `reason`. */
1040
1054
  const reasons = /* @__PURE__ */ new WeakMap();
1055
+ /** The last answer to a read of channels or actors with its `ETag`, by its URL and who asked: sent back, a 304 says it holds. The newest few. */
1056
+ const tagged = /* @__PURE__ */ new Map();
1041
1057
  /**
1042
1058
  * One request to the API, as `who`. Its errors are the API's own, with its status and code. One the
1043
1059
  * API puts off (429, or a 503) waits and goes again as it was, so a write keeps its operation ID
@@ -1057,6 +1073,9 @@ function createVercel(options, environment) {
1057
1073
  ...apiProfileHeaders(who.profile),
1058
1074
  ...who.can !== void 0 ? { "x-board-can": who.can } : {}
1059
1075
  };
1076
+ const tag = method === "GET" && TAGGED.test(path) ? JSON.stringify([url.href, headers]) : null;
1077
+ const kept = tag === null ? void 0 : tagged.get(tag);
1078
+ if (kept) headers["if-none-match"] = kept.etag;
1060
1079
  const repeatable = method !== "POST" && method !== "PATCH" || typeof init.body?.operationId === "string";
1061
1080
  const started = Date.now();
1062
1081
  for (let attempt = 0;; attempt++) {
@@ -1073,12 +1092,29 @@ function createVercel(options, environment) {
1073
1092
  if (error instanceof HttpError || error instanceof Error && error.name === "AbortError") throw error;
1074
1093
  throw new HttpError(502, "unreachable", `Vercel's API didn't answer: ${error instanceof Error ? error.message : String(error)}`);
1075
1094
  }
1095
+ if (response.status === 304 && kept) {
1096
+ await response.body?.cancel();
1097
+ tagged.delete(tag);
1098
+ tagged.set(tag, kept);
1099
+ return JSON.parse(kept.text);
1100
+ }
1076
1101
  const text = await response.text();
1077
1102
  let body;
1078
1103
  try {
1079
1104
  body = text ? JSON.parse(text) : void 0;
1080
1105
  } catch {}
1081
- if (response.ok) return body;
1106
+ if (response.ok) {
1107
+ if (tag !== null) {
1108
+ const etag = response.headers.get("etag");
1109
+ tagged.delete(tag);
1110
+ if (etag && text) tagged.set(tag, {
1111
+ etag,
1112
+ text
1113
+ });
1114
+ if (tagged.size > TAGGED_MAX) tagged.delete(tagged.keys().next().value);
1115
+ }
1116
+ return body;
1117
+ }
1082
1118
  if (attempt < RETRIES && !init.signal?.aborted && (response.status === 429 || response.status === 503 && repeatable)) {
1083
1119
  await pause(retryWait(attempt, response.headers.get("retry-after")), init.signal);
1084
1120
  init.signal?.throwIfAborted();
@@ -1104,22 +1140,28 @@ function createVercel(options, environment) {
1104
1140
  throw error;
1105
1141
  }
1106
1142
  }
1107
- /** Every page of a list, in order. */
1143
+ /** Every page of a list, in order. A cursor the API says expired (410 `cursor_expired`) starts the list again, once. */
1108
1144
  async function all(who, path, key, query = {}, signal) {
1109
- const out = [];
1110
- let cursor;
1111
- do {
1112
- const page = await api(who, "GET", path, {
1113
- query: {
1114
- ...query,
1115
- cursor
1116
- },
1117
- ...signal ? { signal } : {}
1118
- });
1119
- out.push(...page[key]);
1120
- cursor = page.cursor ?? void 0;
1121
- } while (cursor);
1122
- return out;
1145
+ for (let again = false;; again = true) {
1146
+ const out = [];
1147
+ let cursor;
1148
+ try {
1149
+ do {
1150
+ const page = await api(who, "GET", path, {
1151
+ query: {
1152
+ ...query,
1153
+ cursor
1154
+ },
1155
+ ...signal ? { signal } : {}
1156
+ });
1157
+ out.push(...page[key]);
1158
+ cursor = page.cursor ?? void 0;
1159
+ } while (cursor);
1160
+ return out;
1161
+ } catch (error) {
1162
+ if (again || cursor === void 0 || !(error instanceof HttpError && error.status === 410 && error.code === "cursor_expired")) throw error;
1163
+ }
1164
+ }
1123
1165
  }
1124
1166
  /**
1125
1167
  * The board named `name` in the team: the one the API lists for it. Where it lists none, the
@@ -1127,8 +1169,9 @@ function createVercel(options, environment) {
1127
1169
  * not to (`ensure: false`) and is told there's none it can see. Names are unique across the
1128
1170
  * team's boards, the ones you can't see included.
1129
1171
  */
1130
- async function boardNamed(who, name) {
1131
- if (!/^[^/]{1,64}$/.test(name)) throw new HttpError(400, "invalid_board_name", `${JSON.stringify(name)} isn't a board's name: one is 1 to 64 characters with no /.`, { origin: "handle" });
1172
+ async function boardNamed(who, given) {
1173
+ const name = given.trim().normalize("NFC");
1174
+ if (!/^[^/]{1,64}$/.test(name)) throw new HttpError(400, "invalid_board_name", `${JSON.stringify(given)} isn't a board's name: one is 1 to 64 characters with no /.`, { origin: "handle" });
1132
1175
  const { boards } = await api(who, "GET", "/boards", { query: { name } });
1133
1176
  if (boards[0]) return boards[0].id;
1134
1177
  const { principal } = (await self(who)).actor;
@@ -1195,9 +1238,24 @@ function createVercel(options, environment) {
1195
1238
  throw error;
1196
1239
  });
1197
1240
  };
1241
+ /**
1242
+ * The channels callers have been shown, by name, for the callers one `can` narrows alike. The API finds a name
1243
+ * only for a caller that reads its channel, so what one caller was shown is never another's answer: one narrowed
1244
+ * otherwise asks the API, which decides. The credential is this backend's, so `can` is all that tells callers apart.
1245
+ */
1246
+ const namedBy = /* @__PURE__ */ new Map();
1247
+ const namedTo = (who) => {
1248
+ const key = who.can ?? "";
1249
+ let named = namedBy.get(key);
1250
+ if (!named) {
1251
+ if (namedBy.size >= 200) namedBy.delete(namedBy.keys().next().value);
1252
+ namedBy.set(key, named = /* @__PURE__ */ new Map());
1253
+ }
1254
+ return named;
1255
+ };
1198
1256
  /** The channel by `name`, which the API finds without listing the board's. */
1199
- const named = /* @__PURE__ */ new Map();
1200
1257
  async function channelNamed(who, name) {
1258
+ const named = namedTo(who);
1201
1259
  const known = named.get(name);
1202
1260
  if (known) return known;
1203
1261
  const { channels: [found] } = await api(who, "GET", await onBoard(who, "/channels"), { query: { name } });
@@ -1219,7 +1277,7 @@ function createVercel(options, environment) {
1219
1277
  * read's own by its ID.
1220
1278
  */
1221
1279
  async function inNamed(who, name, read) {
1222
- if (readsByName && !named.has(name)) try {
1280
+ if (readsByName && !namedTo(who).has(name)) try {
1223
1281
  return await read({ name });
1224
1282
  } catch (error) {
1225
1283
  if (unknownParameter(error, "channel")) readsByName = false;
@@ -1236,9 +1294,9 @@ function createVercel(options, environment) {
1236
1294
  * already read answers first, and one the API won't show by ID is looked for in the list, as before.
1237
1295
  */
1238
1296
  const byChannelId = /* @__PURE__ */ new Map();
1239
- /** A channel an answer named by both its ID and its name: nothing in this process asks for it again. */
1240
- const learn = ({ id, name }) => {
1241
- named.set(name, {
1297
+ /** A channel an answer to `who` named by both its ID and its name: no caller narrowed as it is asks for it again, by name, and none by ID. */
1298
+ const learn = (who, { id, name }) => {
1299
+ namedTo(who).set(name, {
1242
1300
  id,
1243
1301
  name
1244
1302
  });
@@ -1265,6 +1323,15 @@ function createVercel(options, environment) {
1265
1323
  if (!found) throw new HttpError(502, "remote_error", `Vercel's API names a channel it doesn't list: ${id}`);
1266
1324
  return found;
1267
1325
  }
1326
+ /**
1327
+ * The channel a change of the board's feed, or a tree's, is in, which the API says by name on each: no channel is
1328
+ * asked for to name an event. An API whose events say none is from before that feed could be read here.
1329
+ */
1330
+ function channelOf(change) {
1331
+ const { channel } = change;
1332
+ if (typeof channel !== "string") throw new HttpError(502, "remote_error", "Vercel's API names no channel on this feed's events: it's from before the board's feed could be read here, and too old for this read");
1333
+ return channel;
1334
+ }
1268
1335
  /** The channel by `name`, made if it isn't there: `created` says whether this made it. */
1269
1336
  async function ensureChannel(who, name) {
1270
1337
  const found = await channelNamed(who, name);
@@ -1278,7 +1345,7 @@ function createVercel(options, environment) {
1278
1345
  name
1279
1346
  } });
1280
1347
  channels = null;
1281
- named.set(name, channel);
1348
+ namedTo(who).set(name, channel);
1282
1349
  return {
1283
1350
  channel,
1284
1351
  created: true
@@ -1296,17 +1363,83 @@ function createVercel(options, environment) {
1296
1363
  }
1297
1364
  /** A channel to post in, made the first time something posts to it, as on any board. */
1298
1365
  const channelToPost = async (who, name) => (await ensureChannel(who, name)).channel;
1366
+ /** Whether the channel `name` is the one a filter names, or for a pattern (`dev/`), it or one under it. */
1367
+ const inPattern = (name, filter) => filter.endsWith("/") ? name === filter.slice(0, -1) || name.startsWith(filter) : name === filter;
1299
1368
  /** The channels a filter names: one, a channel and those under it (`dev/`), or every one. */
1300
1369
  async function channelsFor(who, filter) {
1301
1370
  if (filter !== void 0 && !filter.endsWith("/")) {
1302
1371
  const found = await channelNamed(who, filter);
1303
1372
  return found ? [found] : [];
1304
1373
  }
1374
+ if (filter !== void 0 && channelPages) {
1375
+ const under = [];
1376
+ let next;
1377
+ do {
1378
+ const page = await channelsPage(who, {
1379
+ prefix: filter,
1380
+ after: next,
1381
+ limit: 500
1382
+ });
1383
+ under.push(...page.channels);
1384
+ next = page.next ?? void 0;
1385
+ } while (next && channelPages);
1386
+ if (channelPages) {
1387
+ const own = await channelNamed(who, filter.slice(0, -1));
1388
+ return [...own ? [own] : [], ...under];
1389
+ }
1390
+ }
1305
1391
  const listed = await loadChannels(who, true);
1306
1392
  if (filter === void 0) return listed;
1307
1393
  const path = filter.slice(0, -1);
1308
1394
  return listed.filter((channel) => channel.name === path || channel.name.startsWith(filter));
1309
1395
  }
1396
+ /** Whether the API pages its channel list by `limit` and lists it by a name's `prefix`: until it refuses one, it's asked. */
1397
+ let channelPages = true;
1398
+ /**
1399
+ * A page of the board's channels: `limit` of them whose names start with `prefix`, after a page's `next`. The API
1400
+ * pages them, 100 a request at most, by name under a prefix and in its own order without one. One from before
1401
+ * that lists them all, 50 a request, and they're cut here, by name: its pages' `next` is the last name, and the
1402
+ * API's is its own cursor, so neither reads on the other's.
1403
+ */
1404
+ async function channelsPage(who, { prefix, after, limit }, signal) {
1405
+ const refused = () => new HttpError(400, "invalid_cursor", `after: ${after} isn't a page of this board's channels: pass a page's next as it came`);
1406
+ if (channelPages && !after?.startsWith("n.")) {
1407
+ if (after !== void 0 && !after.startsWith("c.")) throw refused();
1408
+ const path = await onBoard(who, "/channels");
1409
+ const found = [];
1410
+ let cursor = after?.slice(2);
1411
+ try {
1412
+ do {
1413
+ const page = await api(who, "GET", path, {
1414
+ query: {
1415
+ prefix,
1416
+ limit: String(Math.min(PAGE_MAX, limit - found.length)),
1417
+ cursor
1418
+ },
1419
+ ...signal ? { signal } : {}
1420
+ });
1421
+ found.push(...page.channels);
1422
+ cursor = page.cursor ?? void 0;
1423
+ } while (cursor && found.length < limit);
1424
+ for (const channel of found) learn(who, channel);
1425
+ return {
1426
+ channels: found,
1427
+ next: cursor ? `c.${cursor}` : null
1428
+ };
1429
+ } catch (error) {
1430
+ if (!unknownParameter(error, "prefix") && !unknownParameter(error, "limit")) throw error;
1431
+ channelPages = false;
1432
+ }
1433
+ }
1434
+ if (after !== void 0 && !after.startsWith("n.")) throw refused();
1435
+ const last = after === void 0 ? void 0 : decodeURIComponent(after.slice(2));
1436
+ const listed = (await loadChannels(who, true)).filter((channel) => (prefix === void 0 || channel.name.startsWith(prefix)) && (last === void 0 || channel.name > last)).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
1437
+ const channels = listed.slice(0, limit);
1438
+ return {
1439
+ channels,
1440
+ next: listed.length > limit ? `n.${encodeURIComponent(channels.at(-1).name)}` : null
1441
+ };
1442
+ }
1310
1443
  async function messageById(who, id, signal, include) {
1311
1444
  if (!locate(id)) throw notFound(`message not found: ${id}`, "message_not_found");
1312
1445
  try {
@@ -1330,7 +1463,7 @@ function createVercel(options, environment) {
1330
1463
  async function messageIn(who, id, signal) {
1331
1464
  if (messagesWithChannel) try {
1332
1465
  const { channel, ...found } = await messageById(who, id, signal, "channel");
1333
- if (channel) learn(channel);
1466
+ if (channel) learn(who, channel);
1334
1467
  return {
1335
1468
  ...found,
1336
1469
  channel: channel ? {
@@ -1383,6 +1516,49 @@ function createVercel(options, environment) {
1383
1516
  } while (cursor);
1384
1517
  return messages;
1385
1518
  };
1519
+ /** Whether the API reads a thread's messages in a range (`after`, `limit`, `order`): until it refuses one, it's asked. */
1520
+ let threadRanges = true;
1521
+ /**
1522
+ * A thread's root, and its replies in a range: after the message at `after`, the first `limit` of them, or with no
1523
+ * `after`, the newest. The API reads the range itself, a page of 100 at most, and the root apart when the range
1524
+ * leaves it out; one from before ranges answers 400 for the parameter, and the whole thread is read and cut here.
1525
+ */
1526
+ async function threadRange(who, threadId, range, signal) {
1527
+ const cut = ([root, ...replies]) => {
1528
+ const rest = range.after === void 0 ? replies : replies.filter((reply) => reply.sequence > range.after);
1529
+ return root ? [root, ...range.limit === void 0 ? rest : range.after === void 0 ? rest.slice(-range.limit) : rest.slice(0, range.limit)] : [];
1530
+ };
1531
+ if (!threadRanges) return cut(await threadMessages(who, threadId, signal));
1532
+ const path = await onBoard(who, `/threads/${encodeURIComponent(threadId)}/messages`);
1533
+ const wanted = range.limit === void 0 ? Infinity : range.after === void 0 ? range.limit + 1 : range.limit;
1534
+ const order = range.after === void 0 ? { order: "desc" } : { after: String(range.after) };
1535
+ const read = [];
1536
+ try {
1537
+ let cursor;
1538
+ do {
1539
+ const page = await reading(who, path, {
1540
+ query: {
1541
+ ...order,
1542
+ limit: String(Math.min(PAGE_MAX, wanted - read.length)),
1543
+ cursor
1544
+ },
1545
+ ...signal ? { signal } : {}
1546
+ });
1547
+ read.push(...page.messages);
1548
+ cursor = page.cursor ?? void 0;
1549
+ } while (cursor && read.length < wanted);
1550
+ } catch (error) {
1551
+ if (![
1552
+ "after",
1553
+ "limit",
1554
+ "order"
1555
+ ].some((name) => unknownParameter(error, name))) throw error;
1556
+ threadRanges = false;
1557
+ return cut(await threadMessages(who, threadId, signal));
1558
+ }
1559
+ const replies = read.filter((message) => message.sequence > 1).sort((a, b) => a.sequence - b.sequence);
1560
+ return [read.find((message) => message.sequence === 1) ?? (await messageById(who, idAt(threadId, 1), signal)).message, ...range.limit === void 0 ? replies : range.after === void 0 ? replies.slice(-range.limit) : replies.slice(0, range.limit)];
1561
+ }
1386
1562
  /** Who reacted with each emoji. The API counts them on the message and lists them apart. */
1387
1563
  async function reactors(who, message) {
1388
1564
  if (!message.reactions || Object.keys(message.reactions).length === 0) return {};
@@ -1543,13 +1719,14 @@ function createVercel(options, environment) {
1543
1719
  /**
1544
1720
  * An actor as the API names them, asked for by ID with everyone else named in the same turn: the
1545
1721
  * authors on a page cost one request however many actors the board has. Undefined for one the API
1546
- * doesn't have or a read that failed, which isn't kept; null when the API doesn't answer by ID.
1722
+ * doesn't have or a read that failed, which isn't kept; null when the API doesn't answer by ID. `strict` rejects
1723
+ * where the read failed, for a caller that must tell that from an actor the API doesn't have.
1547
1724
  */
1548
- function byId(who, id) {
1725
+ function byId(who, id, strict = false) {
1549
1726
  const names = namesOf(who);
1550
1727
  const { asked } = names;
1551
1728
  const kept = asked.get(id);
1552
- if (kept && Date.now() - kept.at <= NAMES_FRESH_MS) return kept.view;
1729
+ if (kept && Date.now() - kept.at <= NAMES_FRESH_MS) return strict && kept.failing || kept.view;
1553
1730
  let batch = names.asking;
1554
1731
  if (!batch || batch.ids.length >= NAMED_AT_ONCE) {
1555
1732
  const ids = [];
@@ -1563,15 +1740,17 @@ function createVercel(options, environment) {
1563
1740
  batch = names.asking = next;
1564
1741
  }
1565
1742
  batch.ids.push(id);
1566
- const view = batch.views.then((views) => views === null ? null : views.get(id), () => {
1743
+ const failing = batch.views.then((views) => views === null ? null : views.get(id));
1744
+ const view = failing.catch(() => {
1567
1745
  if (asked.get(id)?.view === view) asked.delete(id);
1568
1746
  });
1569
1747
  if (asked.size >= 1e4) asked.clear();
1570
1748
  asked.set(id, {
1571
1749
  at: Date.now(),
1572
- view
1750
+ view,
1751
+ failing
1573
1752
  });
1574
- return view;
1753
+ return strict ? failing : view;
1575
1754
  }
1576
1755
  /**
1577
1756
  * The name of the project `actor` is of, one of its deployments or their agents: as its own actor names it,
@@ -1780,6 +1959,11 @@ function createVercel(options, environment) {
1780
1959
  }
1781
1960
  const positions = /* @__PURE__ */ new Map();
1782
1961
  function cursorOf(position) {
1962
+ const across = position.feeds[ACROSS];
1963
+ if (across?.at && Object.keys(position.feeds).length === 1 && position.past === void 0 && position.floor === void 0) {
1964
+ const exact = `x1.${position.t.toString(36)}.${across.skip}.${across.at}`;
1965
+ if (exact.length <= CURSOR_MAX) return exact;
1966
+ }
1783
1967
  const key = `${position.t.toString(36)}.${Math.floor(Math.random() * 36 ** 8).toString(36)}`;
1784
1968
  positions.set(key, position);
1785
1969
  if (positions.size > 1e4) positions.delete(positions.keys().next().value);
@@ -1788,6 +1972,14 @@ function createVercel(options, environment) {
1788
1972
  function positionOf(cursor) {
1789
1973
  const kept = positions.get(cursor);
1790
1974
  if (kept) return kept;
1975
+ const exact = ACROSS_CURSOR.exec(cursor);
1976
+ if (exact) return {
1977
+ t: parseInt(exact[1], 36),
1978
+ feeds: { [ACROSS]: {
1979
+ at: exact[3],
1980
+ skip: Number(exact[2])
1981
+ } }
1982
+ };
1791
1983
  const found = CURSOR.exec(cursor);
1792
1984
  if (!found) throw new HttpError(400, "invalid_cursor", `after: ${cursor} isn't a cursor here or a message's ID`);
1793
1985
  const t = parseInt(found[1], 36);
@@ -1816,10 +2008,10 @@ function createVercel(options, environment) {
1816
2008
  const found = await Promise.all(listed.map((channel) => head(who, channel)));
1817
2009
  return Object.fromEntries(listed.map((channel, i) => [channel.id, found[i]]));
1818
2010
  }
1819
- /** One channel's feed now. */
2011
+ /** One channel's feed now, or the board's. */
1820
2012
  async function head(who, channel) {
1821
2013
  const { cursor } = await api(who, "GET", await onBoard(who, "/changes"), { query: {
1822
- ...inChannel(channel),
2014
+ ...feedOf(channel),
1823
2015
  from: "latest"
1824
2016
  } });
1825
2017
  return {
@@ -1827,6 +2019,35 @@ function createVercel(options, environment) {
1827
2019
  skip: 0
1828
2020
  };
1829
2021
  }
2022
+ /** How a read of a feed names it to the API: a channel as any read does, a tree by its name (`dev/`), and the whole board by nothing. */
2023
+ const feedOf = (channel) => channel.id === ACROSS ? channel.name ? { channel: channel.name } : {} : inChannel(channel);
2024
+ /** The board's feed as a read's one source: a tree's when `channel` names one. */
2025
+ const across = (channel) => ({
2026
+ id: ACROSS,
2027
+ name: channel ?? ""
2028
+ });
2029
+ /** Whether the API reads the board's feed in one for a caller narrowed as `can` says: asked once each. */
2030
+ const acrossFeeds = /* @__PURE__ */ new Map();
2031
+ /** The API's refusal of the board's feed to a caller that doesn't read every channel, by its code: its cursors would count the rest. */
2032
+ const readsSome = (error) => error instanceof HttpError && error.status === 403 && error.code === "feed_needs_every_channel";
2033
+ /**
2034
+ * Whether these credentials read the board's feed in one request: not on an API from before it, which
2035
+ * takes no read of changes without a channel, and not when they read only some channels. Either way
2036
+ * the read follows each channel's feed, as before.
2037
+ */
2038
+ function acrossFeed(who) {
2039
+ const key = who.can ?? "";
2040
+ let asked = acrossFeeds.get(key);
2041
+ if (!asked) {
2042
+ asked = onBoard(who, "/changes").then((path) => api(who, "GET", path, { query: { from: "latest" } })).then(() => true, (error) => {
2043
+ if (readsSome(error) || error instanceof HttpError && error.status === 400 && /missing required property\W*channelId\b/i.test(error.message)) return false;
2044
+ acrossFeeds.delete(key);
2045
+ throw error;
2046
+ });
2047
+ acrossFeeds.set(key, asked);
2048
+ }
2049
+ return asked;
2050
+ }
1830
2051
  /**
1831
2052
  * Who `--by` names: `me`, the actor itself; or an actor, a principal and its agents, a profile, or
1832
2053
  * a handle as the board shows it (`julian`, `julian/claude`), a person's covering their agents.
@@ -1875,8 +2096,10 @@ function createVercel(options, environment) {
1875
2096
  /**
1876
2097
  * What `--mentions` matches, in a message's text, as on any board: `me` is the caller's handle and
1877
2098
  * actor ID, as the API names them. Anyone else is the name as written and what's under it: a
1878
- * person's agents (`@julian/claude`), a project's imports. The API keeps no mentions, so this reads
1879
- * them from the text of each message a read covers.
2099
+ * person's agents (`@julian/claude`), a project's imports. A mention board() settled to an actor's
2100
+ * ID (`@[vercel:user:u_jb+claude]`) matches by that actor's handle, as the API names them, asked
2101
+ * for by ID; one the API doesn't name matches by its ID alone. The API keeps no mentions, so this
2102
+ * reads them from the text of each message a read covers.
1880
2103
  */
1881
2104
  async function mentionsOf(who, value) {
1882
2105
  if (value === void 0) return void 0;
@@ -1889,7 +2112,26 @@ function createVercel(options, environment) {
1889
2112
  terms = [mentionTerm(value)];
1890
2113
  prefixes = [value.includes(":") ? `${value}+` : `${mentionTerm(value)}/`];
1891
2114
  }
1892
- return (text) => mentionTerms(text).some((term) => terms.includes(term) || prefixes.some((prefix) => term.startsWith(prefix)));
2115
+ const named = (term) => terms.includes(term) || prefixes.some((prefix) => term.startsWith(prefix));
2116
+ const ids = (text) => value === "me" || value.includes(":") ? [] : mentionTerms(text).filter((term) => principalFrom(term) !== null);
2117
+ /**
2118
+ * The handle an ID goes by as the actors list shows it, which is what a `@handle` settles from: the API's own
2119
+ * (`pong/claude`), a deployment by its project's name. None for an ID the API names no one by: a handle made up
2120
+ * from it (an agent by its profile alone) would name another's. A read of the actors that fails fails this, so
2121
+ * a wait reads the same change again rather than going on past a mention it couldn't check.
2122
+ */
2123
+ const handleOf = async (id) => {
2124
+ const view = namesById ? await byId(who, id, true) : null;
2125
+ const found = view === null ? await listed(who, id) : view;
2126
+ return found ? shownHandle(id, found, projectNamesOf([[id, found]])) : null;
2127
+ };
2128
+ const mentioned = async (text) => {
2129
+ if (mentionTerms(text).some(named)) return true;
2130
+ return (await Promise.all(ids(text).map(handleOf))).some((handle) => handle !== null && named(mentionTerm(handle)));
2131
+ };
2132
+ return Object.assign(mentioned, { ahead: (texts) => {
2133
+ if (namesById) for (const text of texts) for (const id of ids(text)) byId(who, id);
2134
+ } });
1893
2135
  }
1894
2136
  const narrowOf = async (who, filters) => ({
1895
2137
  by: await byOf(who, filters.by),
@@ -1903,7 +2145,7 @@ function createVercel(options, environment) {
1903
2145
  async function matches(filters, message, thread, narrow) {
1904
2146
  if (filters.re !== void 0 && filters.re !== message.id && filters.re !== idAt(thread.id, 1)) return false;
1905
2147
  if (narrow.by && !narrow.by(message.createdBy)) return false;
1906
- if (filters.mentions !== void 0 && !narrow.mentions?.(message.text)) return false;
2148
+ if (filters.mentions !== void 0 && !await narrow.mentions?.(message.text)) return false;
1907
2149
  if (filters.from !== void 0 && !await narrow.source?.(message)) return false;
1908
2150
  if (filters.text !== void 0 && !message.text.toLowerCase().includes(filters.text.toLowerCase())) return false;
1909
2151
  for (const [key, values] of filters.label ?? []) {
@@ -1917,36 +2159,6 @@ function createVercel(options, environment) {
1917
2159
  const first = filters.label?.find(([, values]) => values === null || values.length === 1);
1918
2160
  return first && (first[1] === null ? first[0] : `${first[0]}=${first[1][0]}`);
1919
2161
  }
1920
- /** Every thread of a channel, each with its first and newest message where the API sends them (`threadPage`). */
1921
- async function threadsOf(who, channel, filters, signal) {
1922
- const label = indexed(filters);
1923
- const path = await onBoard(who, "/threads");
1924
- const out = [];
1925
- let cursor;
1926
- do {
1927
- const page = await threadPage(who, path, {
1928
- channelId: channel.id,
1929
- label,
1930
- cursor,
1931
- limit: THREAD_PAGE_MAX
1932
- }, signal);
1933
- out.push(...page.threads);
1934
- cursor = page.cursor ?? void 0;
1935
- } while (cursor);
1936
- return out;
1937
- }
1938
- /**
1939
- * A thread's messages when its list brought them all: its first, and its newest when that's its
1940
- * second. Most threads are a post or a post and a reply, and reading one of those costs nothing
1941
- * more. Null for a longer one, or from an API that lists threads without their messages.
1942
- */
1943
- function whole(thread) {
1944
- const root = thread.rootMessage;
1945
- if (!root || root.sequence !== 1) return null;
1946
- if (thread.messageCount === 1) return [root];
1947
- const latest = thread.latestMessage;
1948
- return thread.messageCount === 2 && latest?.sequence === 2 ? [root, latest] : null;
1949
- }
1950
2162
  /** Whether the API lists threads with their first and newest messages (`include=messages`): until it refuses the parameter, it's asked. */
1951
2163
  let threadsWithMessages = true;
1952
2164
  /** Whether the API takes how many threads a page holds (`limit`): until it refuses the parameter, it's asked. */
@@ -2155,99 +2367,45 @@ function createVercel(options, environment) {
2155
2367
  }
2156
2368
  /** A post's client ID, as the API takes one: its own when it fits, a hash of it when it doesn't. */
2157
2369
  const clientIdOf = async (id) => CLIENT_ID.test(id) ? id : `h.${(await sha256(id)).slice(0, 64)}`;
2158
- /** Messages a read covers, newest last: every thread's in the channels it names, or one thread's. */
2159
- async function collect(who, filters, signal) {
2160
- let listed;
2161
- let threads;
2162
- let feeds;
2163
- if (filters.re !== void 0) {
2164
- const found = await messageIn(who, filters.re, signal).catch((error) => {
2165
- if (error instanceof HttpError && error.status === 404) return null;
2166
- throw error;
2167
- });
2168
- if (!found) return {
2169
- messages: [],
2170
- feeds: {},
2171
- newest: 0
2172
- };
2173
- const { channel } = found;
2174
- if (filters.channel !== void 0 && !(await channelsFor(who, filters.channel)).some((c) => c.id === channel.id)) return {
2175
- messages: [],
2176
- feeds: {},
2177
- newest: 0
2178
- };
2179
- listed = [channel];
2180
- threads = [{
2181
- thread: found.thread,
2182
- channel
2183
- }];
2184
- feeds = await heads(who, listed);
2185
- } else {
2186
- listed = await channelsFor(who, filters.channel);
2187
- feeds = await heads(who, listed);
2188
- threads = (await Promise.all(listed.map(async (channel) => (await threadsOf(who, channel, filters, signal)).map((thread) => ({
2189
- thread,
2190
- channel
2191
- }))))).flat();
2192
- }
2193
- const narrow = await narrowOf(who, filters);
2370
+ /**
2371
+ * The messages of the thread `re` names, by any of its messages, that match a read's filters, oldest first, with its
2372
+ * channel's feed now. None for a thread that isn't here, or isn't in the channel the read names.
2373
+ */
2374
+ async function threadMatching(who, re, filters, signal) {
2375
+ const none = {
2376
+ messages: [],
2377
+ feeds: {},
2378
+ newest: 0
2379
+ };
2380
+ const found = await messageIn(who, re, signal).catch((error) => {
2381
+ if (error instanceof HttpError && error.status === 404) return null;
2382
+ throw error;
2383
+ });
2384
+ if (!found) return none;
2385
+ const { thread, channel } = found;
2386
+ if (filters.channel !== void 0 && !inPattern(channel.name, filters.channel)) return none;
2387
+ const feeds = await heads(who, [channel]);
2388
+ const all = await threadMessages(who, thread.id, signal);
2389
+ const labeled = labeledBy(thread, all.find((message) => message.sequence === 1));
2194
2390
  let newest = 0;
2195
2391
  const messages = [];
2196
- for (const { thread, channel } of threads) {
2197
- const all = whole(thread) ?? await threadMessages(who, thread.id, signal);
2198
- const labeled = labeledBy(thread, all.find((message) => message.sequence === 1));
2199
- for (const message of all) {
2200
- newest = Math.max(newest, message.createdAt);
2201
- if (await matches(filters, message, labeled, narrow)) messages.push({
2202
- message,
2203
- thread,
2204
- channel
2205
- });
2206
- }
2392
+ for (const message of all) {
2393
+ newest = Math.max(newest, message.createdAt);
2394
+ if (await matches({
2395
+ ...filters,
2396
+ re
2397
+ }, message, labeled, {})) messages.push({
2398
+ message,
2399
+ thread,
2400
+ channel
2401
+ });
2207
2402
  }
2208
- messages.sort(byTime);
2209
2403
  return {
2210
2404
  messages,
2211
2405
  feeds,
2212
2406
  newest
2213
2407
  };
2214
2408
  }
2215
- /** A thread's messages in order; across threads, by time, as a person reads a channel. */
2216
- const byTime = (a, b) => a.message.createdAt - b.message.createdAt || a.message.threadId.localeCompare(b.message.threadId) || a.message.sequence - b.message.sequence;
2217
- /**
2218
- * The latest `limit` in `listed`, unfiltered: each channel's latest page from the API's message
2219
- * list, all at once, never a thread at a time. The list goes back one page, so a full page cuts the
2220
- * answer off at its oldest message: every message newer than the oldest it answers with is in it,
2221
- * even when that's fewer than `limit`. Each page's cursor is its channel's feed then, which the
2222
- * read's cursor goes on from.
2223
- */
2224
- async function latest(who, listed, limit, signal) {
2225
- const path = await onBoard(who, "/messages");
2226
- const asked = Math.min(limit, PAGE_MAX);
2227
- const pages = await Promise.all(listed.map(async (channel) => ({
2228
- channel,
2229
- ...await reading(who, path, {
2230
- query: {
2231
- channelId: channel.id,
2232
- limit: String(asked)
2233
- },
2234
- signal
2235
- })
2236
- })));
2237
- const full = pages.filter((page) => page.messages.length === asked);
2238
- const cutoff = Math.max(-Infinity, ...full.map((page) => Math.min(...page.messages.map((message) => message.createdAt))));
2239
- return {
2240
- messages: pages.flatMap(({ channel, messages }) => messages.map((message) => ({
2241
- message,
2242
- channel
2243
- }))).filter(({ message }) => message.createdAt >= cutoff).sort(byTime).slice(-limit),
2244
- feeds: Object.fromEntries(pages.map((page) => [page.channel.id, {
2245
- at: page.cursor,
2246
- skip: 0
2247
- }])),
2248
- newest: Math.max(0, ...pages.flatMap((page) => page.messages.map((message) => message.createdAt)))
2249
- };
2250
- }
2251
2409
  /** A change in the API's feed as a board event, with the message as it is now. Null for what's neither a message's nor a task's. */
2252
2410
  async function eventOf(who, change, channel, cursor, filters, narrow, given, threads = threadReader(who)) {
2253
2411
  if (change.type.startsWith("task.")) return taskEventOf(who, change, channel, cursor, filters, narrow, given);
@@ -2348,7 +2506,7 @@ function createVercel(options, environment) {
2348
2506
  const from = position.feeds[channel.id];
2349
2507
  const page = await reading(who, path, {
2350
2508
  query: {
2351
- channelId: channel.id,
2509
+ ...feedOf(channel),
2352
2510
  include: "message",
2353
2511
  ...from?.at ? { cursor: from.at } : {}
2354
2512
  },
@@ -2363,7 +2521,8 @@ function createVercel(options, environment) {
2363
2521
  channel,
2364
2522
  at: from?.at ?? null,
2365
2523
  next: page.cursor,
2366
- events
2524
+ events,
2525
+ behind: channel.id === ACROSS && page.caughtUp === false && page.cursor !== from?.at
2367
2526
  };
2368
2527
  }));
2369
2528
  const narrow = await narrowOf(who, filters);
@@ -2375,6 +2534,7 @@ function createVercel(options, environment) {
2375
2534
  }))).sort((a, b) => a.change.createdAt - b.change.createdAt);
2376
2535
  const events = [];
2377
2536
  naming(who, merged.flatMap(({ change }) => [change.actor, ...change.currentMessage ? [change.currentMessage.createdBy] : []]));
2537
+ narrow.mentions?.ahead(merged.flatMap(({ change }) => change.currentMessage ? [change.currentMessage.text] : []));
2378
2538
  const start = {
2379
2539
  ...position.past !== void 0 ? { past: position.past } : {},
2380
2540
  ...position.floor !== void 0 ? { floor: position.floor } : {}
@@ -2389,7 +2549,7 @@ function createVercel(options, environment) {
2389
2549
  message,
2390
2550
  thread: filters.label?.length ? await threads(change.threadId) : { id: change.threadId }
2391
2551
  } : void 0;
2392
- const event = await eventOf(who, change, page.channel.name, cursorOf({
2552
+ const event = await eventOf(who, change, page.channel.id === ACROSS ? channelOf(change) : page.channel.name, cursorOf({
2393
2553
  t: change.createdAt,
2394
2554
  feeds: { ...running },
2395
2555
  ...start
@@ -2403,6 +2563,7 @@ function createVercel(options, environment) {
2403
2563
  };
2404
2564
  return {
2405
2565
  events,
2566
+ behind: pages.some((page) => page.behind),
2406
2567
  position: {
2407
2568
  t: Math.max(position.t, ...merged.map(({ change }) => change.createdAt)),
2408
2569
  feeds: after,
@@ -2433,13 +2594,13 @@ function createVercel(options, environment) {
2433
2594
  const at = position.feeds[channel.id]?.at;
2434
2595
  api(who, "GET", path, {
2435
2596
  query: {
2436
- channelId: channel.id,
2597
+ ...feedOf(channel),
2437
2598
  ...at ? { cursor: at } : { from: "latest" },
2438
2599
  wait: String(wait)
2439
2600
  },
2440
2601
  signal: either
2441
2602
  }).then((page) => {
2442
- if (page.events.length > 0) resolve(true);
2603
+ if (page.events.length > 0 || channel.id === ACROSS && page.caughtUp === false) resolve(true);
2443
2604
  else if (--pending === 0) resolve(false);
2444
2605
  }).catch((error) => stop.signal.aborted && !signal.aborted ? void 0 : reject(error));
2445
2606
  }
@@ -2448,51 +2609,78 @@ function createVercel(options, environment) {
2448
2609
  stop.abort();
2449
2610
  }
2450
2611
  }
2451
- /** Whether a read filters on what messages say, who wrote them, or their labels: what the API can't narrow by. */
2452
- const filtered = (filters) => filters.by !== void 0 || filters.mentions !== void 0 || filters.text !== void 0 || filters.from !== void 0 || (filters.label?.length ?? 0) > 0;
2453
2612
  /**
2454
- * One channel's messages, from the API's message list: the latest `limit`, or those after one of
2455
- * its cursors. A filtered read checks each page here, and asks only for as many as it still needs,
2456
- * so the cursor it answers with never passes a match it left out.
2613
+ * One channel's messages, from the API's message list: the latest `limit`, of which the API lists 100 at most, or
2614
+ * those after one of its cursors, a page of the API's at a time until it has `limit` or the channel has no more.
2457
2615
  */
2458
2616
  async function channelMessages(who, channel, query, signal) {
2459
2617
  const path = await onBoard(who, "/messages");
2460
2618
  const limit = query.limit ?? 50;
2461
- const thread = threadReader(who, signal);
2462
- const narrowed = filtered(query);
2463
- const narrow = narrowed ? await narrowOf(who, query) : {};
2464
- const keep = async (message) => !narrowed || await matches(query, message, query.label?.length ? await thread(message.threadId) : { id: message.threadId }, narrow);
2465
- const kept = [];
2466
2619
  if (query.after === void 0) {
2467
2620
  const page = await reading(who, path, {
2468
2621
  query: {
2469
2622
  ...inChannel(channel),
2470
- limit: String(narrowed ? PAGE_MAX : Math.min(limit, PAGE_MAX))
2623
+ limit: String(Math.min(limit, PAGE_MAX))
2471
2624
  },
2472
2625
  signal
2473
2626
  });
2474
- for (const message of page.messages) if (await keep(message)) kept.push(message);
2475
2627
  return {
2476
- messages: kept.slice(-limit),
2628
+ messages: page.messages,
2477
2629
  cursor: page.cursor
2478
2630
  };
2479
2631
  }
2632
+ const read = [];
2480
2633
  let cursor = query.after;
2481
- for (let pages = 0; pages < SCAN_PAGES && kept.length < limit; pages++) {
2634
+ for (let pages = 0; pages < AFTER_PAGES && read.length < limit; pages++) {
2482
2635
  const page = await reading(who, path, {
2483
2636
  query: {
2484
2637
  ...inChannel(channel),
2485
- after: cursor,
2486
- limit: String(Math.min(limit - kept.length, PAGE_MAX))
2638
+ cursor,
2639
+ limit: String(Math.min(limit - read.length, PAGE_MAX))
2487
2640
  },
2488
2641
  signal
2489
2642
  });
2490
2643
  cursor = page.cursor;
2491
- for (const message of page.messages) if (await keep(message)) kept.push(message);
2492
- if (page.messages.length === 0) break;
2644
+ read.push(...page.messages);
2645
+ if (page.caughtUp ?? page.messages.length === 0) break;
2493
2646
  }
2494
2647
  return {
2495
- messages: kept,
2648
+ messages: read,
2649
+ cursor
2650
+ };
2651
+ }
2652
+ /**
2653
+ * One channel's messages from the first its feed still keeps, for a read that goes on from before the channel had
2654
+ * any. The API's message list reads on from one of the channel's cursors and from nowhere else, and its feed, read
2655
+ * from its oldest change, hands out the cursor after each post: so the posts are read from there, up to `limit`, and
2656
+ * the cursor answered is the feed's right after the last, which the message list goes on from.
2657
+ */
2658
+ async function channelMessagesFromStart(who, channel, limit, signal) {
2659
+ const path = await onBoard(who, "/changes");
2660
+ const read = [];
2661
+ let cursor;
2662
+ for (let pages = 0; pages < AFTER_PAGES; pages++) {
2663
+ const page = await reading(who, path, {
2664
+ query: {
2665
+ ...inChannel(channel),
2666
+ include: "message",
2667
+ ...cursor !== void 0 ? { cursor } : {}
2668
+ },
2669
+ signal
2670
+ });
2671
+ for (const change of page.events) {
2672
+ if (change.type !== "message.posted" || !change.currentMessage) continue;
2673
+ read.push(change.currentMessage);
2674
+ if (read.length >= limit && change.cursor !== void 0) return {
2675
+ messages: read,
2676
+ cursor: change.cursor
2677
+ };
2678
+ }
2679
+ cursor = page.cursor;
2680
+ if (read.length >= limit || (page.caughtUp ?? page.events.length === 0)) break;
2681
+ }
2682
+ return cursor === void 0 ? null : {
2683
+ messages: read,
2496
2684
  cursor
2497
2685
  };
2498
2686
  }
@@ -2517,6 +2705,7 @@ function createVercel(options, environment) {
2517
2705
  cursor = page.cursor;
2518
2706
  const events = [];
2519
2707
  naming(who, page.events.flatMap((change) => [change.actor, ...change.currentMessage ? [change.currentMessage.createdBy] : []]));
2708
+ narrow.mentions?.ahead(page.events.flatMap((change) => change.currentMessage ? [change.currentMessage.text] : []));
2520
2709
  for (const change of page.events) {
2521
2710
  const message = change.currentMessage;
2522
2711
  const found = message && change.threadId ? {
@@ -2533,17 +2722,114 @@ function createVercel(options, environment) {
2533
2722
  };
2534
2723
  }
2535
2724
  }
2725
+ /** Whether the API reads a feed's newest events (`last`): until it refuses the parameter, it's asked. */
2726
+ let readsLast = true;
2727
+ const noLast = () => notSupported("reading a feed's newest events", "follow it from now, without `last`");
2728
+ const noLastAcross = () => notSupported("reading the newest events of several channels at once here", "read one channel's, with `channel`");
2729
+ /**
2730
+ * The newest events of one feed, oldest first, in one read: the API's `last`, on a channel's feed, a tree's or
2731
+ * the board's, with the feed's end as the cursor. Several channels' are only ever the board's feed: where the
2732
+ * API keeps none for the caller, or takes no `last`, the read is refused, not made a channel at a time.
2733
+ */
2734
+ async function newest(who, query, signal) {
2735
+ if (!readsLast) throw noLast();
2736
+ const { last: _last, ...rest } = query;
2737
+ const none = () => followed(who, [], void 0, rest, signal);
2738
+ try {
2739
+ const name = oneChannel(query);
2740
+ const found = name === null ? null : await inNamed(who, name, (channel) => newestOf(who, channel, query, signal));
2741
+ if (found) return found;
2742
+ if (name !== null) return await none();
2743
+ if (query.re !== void 0) {
2744
+ const [channel] = await channelOfThread(who, query.re, query.channel, signal);
2745
+ return channel ? await newestOf(who, channel, query, signal) : await none();
2746
+ }
2747
+ if (!await acrossFeed(who)) throw noLastAcross();
2748
+ return await newestOf(who, across(query.channel), query, signal);
2749
+ } catch (error) {
2750
+ if (unknownParameter(error, "last")) {
2751
+ readsLast = false;
2752
+ throw noLast();
2753
+ }
2754
+ if (!readsSome(error)) throw error;
2755
+ acrossFeeds.set(who.can ?? "", Promise.resolve(false));
2756
+ throw noLastAcross();
2757
+ }
2758
+ }
2759
+ async function newestOf(who, feed, query, signal) {
2760
+ const page = await reading(who, await onBoard(who, "/changes"), {
2761
+ query: {
2762
+ ...feedOf(feed),
2763
+ include: "message",
2764
+ last: String(query.last)
2765
+ },
2766
+ signal
2767
+ });
2768
+ const narrow = await narrowOf(who, query);
2769
+ const threads = threadReader(who, signal);
2770
+ naming(who, page.events.flatMap((change) => [change.actor, ...change.currentMessage ? [change.currentMessage.createdBy] : []]));
2771
+ narrow.mentions?.ahead(page.events.flatMap((change) => change.currentMessage ? [change.currentMessage.text] : []));
2772
+ const one = feed.id !== ACROSS;
2773
+ const events = [];
2774
+ for (const change of page.events) {
2775
+ const message = change.currentMessage;
2776
+ const given = message && change.threadId ? {
2777
+ message,
2778
+ thread: query.label?.length ? await threads(change.threadId) : { id: change.threadId }
2779
+ } : void 0;
2780
+ if (one && !given) continue;
2781
+ const event = one ? await eventOf(who, change, feed.name, change.cursor ?? page.cursor, query, narrow, given) : await eventOf(who, change, channelOf(change), cursorOf({
2782
+ t: change.createdAt,
2783
+ feeds: { [ACROSS]: {
2784
+ at: change.cursor ?? page.cursor,
2785
+ skip: 0
2786
+ } }
2787
+ }), query, narrow, given, threads);
2788
+ const settled = event && carried(event);
2789
+ if (settled) events.push(settled);
2790
+ }
2791
+ if (one) return {
2792
+ events,
2793
+ cursor: page.cursor
2794
+ };
2795
+ return {
2796
+ events,
2797
+ cursor: cursorOf({
2798
+ t: page.events.length > 0 ? Math.max(...page.events.map((change) => change.createdAt)) : Date.now(),
2799
+ feeds: { [ACROSS]: {
2800
+ at: page.cursor,
2801
+ skip: 0
2802
+ } }
2803
+ })
2804
+ };
2805
+ }
2536
2806
  /** A read of the feed, as `vb tail` makes it: one channel's feed when it names one, or every channel's. */
2537
2807
  async function eventsAs(who, query, signal) {
2808
+ if (query.last !== void 0) return newest(who, query, signal);
2538
2809
  const name = oneChannel(query);
2539
2810
  const found = name === null ? null : await inNamed(who, name, (channel) => channelEvents(who, channel, query, signal));
2540
2811
  if (found) return found;
2541
2812
  if (query.after !== void 0 && API_CURSOR.test(query.after)) throw new HttpError(400, "invalid_request", `after: ${query.after} is one channel's cursor: read that channel`);
2542
- const listed = query.re === void 0 ? await channelsFor(who, query.channel) : await channelOfThread(who, query.re, query.channel, signal);
2543
- let position = query.after === void 0 ? {
2813
+ const from = query.after === void 0 ? void 0 : locate(query.after) ? await afterMessage(who, query.after) : positionOf(query.after);
2814
+ const one = (query.channel === void 0 || query.channel.endsWith("/")) && query.re === void 0 && !(from && Object.keys(from.feeds).some((key) => key !== ACROSS)) && await acrossFeed(who);
2815
+ try {
2816
+ return await followed(who, one ? [across(query.channel)] : query.re === void 0 ? await channelsFor(who, query.channel) : await channelOfThread(who, query.re, query.channel, signal), from, query, signal);
2817
+ } catch (error) {
2818
+ if (!one || !readsSome(error)) throw error;
2819
+ acrossFeeds.set(who.can ?? "", Promise.resolve(false));
2820
+ const { [ACROSS]: _left, ...feeds } = from?.feeds ?? {};
2821
+ return followed(who, await channelsFor(who, query.channel), from && {
2822
+ ...from,
2823
+ feeds
2824
+ }, query, signal);
2825
+ }
2826
+ }
2827
+ /** The events of `listed` feeds after `from`, or from now, waiting for the first when the read waits. */
2828
+ async function followed(who, listed, from, query, signal) {
2829
+ let position = from ?? {
2544
2830
  t: Date.now(),
2545
2831
  feeds: await heads(who, listed)
2546
- } : locate(query.after) ? await afterMessage(who, query.after) : positionOf(query.after);
2832
+ };
2547
2833
  const until = Date.now() + (query.wait ?? 0) * 1e3;
2548
2834
  let busy = false;
2549
2835
  for (;;) {
@@ -2554,6 +2840,7 @@ function createVercel(options, environment) {
2554
2840
  events: page.events,
2555
2841
  cursor: cursorOf(position)
2556
2842
  };
2843
+ if (page.behind) continue;
2557
2844
  if (!busy) busy = await changed(who, listed, position, until, signal) && Date.now() - started < 1e3;
2558
2845
  await pause(Math.min(started + 1e3, until) - Date.now(), signal);
2559
2846
  }
@@ -2750,11 +3037,19 @@ function createVercel(options, environment) {
2750
3037
  }
2751
3038
  /** A match as vboard hands it out: its event as `vb tail --json` prints it, with its message as it is now. */
2752
3039
  async function matchOf(who, match, filters) {
2753
- const found = await messageIn(who, match.event.messageId).catch((error) => {
3040
+ const current = match.event.currentMessage;
3041
+ const found = current && !filters.label?.length ? {
3042
+ message: current,
3043
+ thread: {
3044
+ id: match.threadId,
3045
+ channelId: match.event.channelId
3046
+ },
3047
+ channel: await channelById(who, match.event.channelId)
3048
+ } : await messageIn(who, match.event.messageId).catch((error) => {
2754
3049
  if (error instanceof HttpError && error.status === 404) return null;
2755
3050
  throw error;
2756
3051
  });
2757
- if (!found) return null;
3052
+ if (!found?.channel) return null;
2758
3053
  const { channel } = found;
2759
3054
  const event = match.event.type === "thread.synced" ? await syncedOf(who, match, found.message, channel.name) : await eventOf(who, match.event, channel.name, match.id, filters, await narrowOf(who, filters), found);
2760
3055
  if (!event?.message) return null;
@@ -3012,7 +3307,7 @@ function createVercel(options, environment) {
3012
3307
  if (code === "thread_not_found") return notFound(`message not found: ${about.id ?? "that task"}`, "message_not_found");
3013
3308
  if (code === "not_a_task") return notFound(message, "not_a_task");
3014
3309
  if (code === "message_deleted") return badRequest(message, "message_deleted");
3015
- if (code === "bad_request" || code === "invalid_for") return badRequest(message);
3310
+ if (code === "invalid_request" || code === "invalid_for") return badRequest(message);
3016
3311
  if (code === "invalid_needs" || code === "reserved_label") return badRequest(message, code);
3017
3312
  if (code === "task_not_owned") return new HttpError(403, code, message);
3018
3313
  if (code === "claim_lost") {
@@ -3336,13 +3631,19 @@ function createVercel(options, environment) {
3336
3631
  can: canOf(found.can)
3337
3632
  };
3338
3633
  },
3339
- async channels(caller) {
3634
+ async channels(caller, { prefix, after, limit = 100 }, signal) {
3635
+ const page = await channelsPage(whoOf(caller), {
3636
+ prefix,
3637
+ after,
3638
+ limit
3639
+ }, signal);
3340
3640
  return {
3341
- channels: (await channelsFor(whoOf(caller), void 0)).map((channel) => ({ path: channel.name })).sort((a, b) => a.path.localeCompare(b.path)),
3641
+ channels: page.channels.map((channel) => ({ path: channel.name })),
3342
3642
  cursor: cursorOf({
3343
3643
  t: Date.now(),
3344
3644
  feeds: {}
3345
- })
3645
+ }),
3646
+ next: page.next
3346
3647
  };
3347
3648
  },
3348
3649
  async createChannel(caller, { path }) {
@@ -3381,49 +3682,42 @@ function createVercel(options, environment) {
3381
3682
  })
3382
3683
  };
3383
3684
  },
3384
- async messages(caller, query, signal) {
3685
+ async channelMessages(caller, query, signal) {
3385
3686
  const who = whoOf(caller);
3386
- const name = query.before === void 0 ? oneChannel(query) : null;
3387
- const direct = name === null ? null : await inNamed(who, name, (channel) => channelMessages(who, channel, query, signal));
3388
- if (name !== null && direct) return {
3389
- messages: await Promise.all(direct.messages.map((message) => view(who, message, name))),
3390
- cursor: direct.cursor
3391
- };
3392
- if (query.after !== void 0 && API_CURSOR.test(query.after)) throw new HttpError(400, "invalid_request", `after: ${query.after} is one channel's cursor: read that channel`);
3393
- const limit = query.limit ?? 50;
3394
- if (query.re === void 0 && query.after === void 0 && query.before === void 0 && !filtered(query)) {
3395
- const { messages, feeds, newest } = await latest(who, await channelsFor(who, query.channel), limit, signal);
3396
- return {
3397
- messages: await Promise.all(messages.map(({ message, channel }) => view(who, message, channel.name))),
3398
- cursor: cursorOf({
3399
- t: newest,
3400
- feeds
3401
- })
3402
- };
3403
- }
3404
- const { messages, feeds, newest } = await collect(who, query, signal);
3405
- const after = query.after !== void 0 ? await timeOf(who, query.after) : void 0;
3406
- const before = query.before !== void 0 ? await timeOf(who, query.before) : void 0;
3407
- const bounded = messages.filter(({ message }) => (after === void 0 || message.createdAt > after) && (before === void 0 || message.createdAt < before));
3408
- const page = after !== void 0 ? bounded.slice(0, limit) : bounded.slice(-limit);
3409
- return {
3410
- messages: await Promise.all(page.map(({ message, channel }) => view(who, message, channel.name))),
3687
+ const name = query.channel;
3688
+ const fromStart = query.after !== void 0 && !API_CURSOR.test(query.after);
3689
+ if (fromStart && (locate(query.after) || positionOf(query.after).t !== 0)) throw new HttpError(400, "invalid_cursor", `after: ${query.after} isn't a cursor of #${name}'s messages: pass the cursor a read of this channel's messages answered`);
3690
+ const page = await inNamed(who, name, (channel) => fromStart ? channelMessagesFromStart(who, channel, query.limit ?? 50, signal) : channelMessages(who, channel, query, signal));
3691
+ if (!page && query.after !== void 0 && !fromStart) throw new HttpError(400, "invalid_cursor", `after: ${query.after} isn't a cursor of #${name}'s messages: pass the cursor a read of this channel's messages answered`);
3692
+ if (!page) return {
3693
+ messages: [],
3411
3694
  cursor: cursorOf({
3412
- t: newest,
3413
- feeds
3695
+ t: 0,
3696
+ feeds: {}
3414
3697
  })
3415
3698
  };
3699
+ return {
3700
+ messages: await Promise.all(page.messages.map((message) => view(who, message, name))),
3701
+ cursor: page.cursor
3702
+ };
3416
3703
  },
3417
3704
  async threads(caller, query, signal) {
3418
3705
  const who = whoOf(caller);
3706
+ const unindexed = [
3707
+ query.by !== void 0 && "author",
3708
+ query.mentions !== void 0 && "mention",
3709
+ query.text !== void 0 && "text",
3710
+ query.from !== void 0 && "source"
3711
+ ].filter((name) => name !== false);
3712
+ if (unindexed.length > 0) throw notSupported(`reading threads by ${unindexed.join(", ")}`, "they keep no search index. Read one channel's threads, or one thread, and look through what it answers");
3713
+ if (query.re === void 0 && (query.channel === void 0 || query.channel.endsWith("/"))) throw notSupported(query.channel === void 0 ? "reading every channel at once" : `reading every channel under ${query.channel} at once`, "name one channel, and read the others one at a time. The channel list has their names");
3419
3714
  const after = query.after !== void 0 ? await timeOf(who, query.after) : void 0;
3420
3715
  const limit = query.limit ?? 50;
3421
3716
  const pick = (found) => {
3422
3717
  const ordered = found.filter(({ at }) => after === void 0 || at > after).sort((a, b) => a.at - b.at);
3423
3718
  return after !== void 0 ? ordered.slice(0, limit) : ordered.slice(-limit);
3424
3719
  };
3425
- const byMessage = query.re !== void 0 || query.by !== void 0 || query.mentions !== void 0 || query.text !== void 0 || query.from !== void 0;
3426
- if (query.channel !== void 0 && !query.channel.endsWith("/") && !byMessage && !query.label?.length && after === void 0) {
3720
+ if (query.re === void 0 && !query.label?.length && after === void 0) {
3427
3721
  const name = query.channel;
3428
3722
  const read = await inNamed(who, name, async (channel) => {
3429
3723
  const feed = await head(who, channel);
@@ -3442,7 +3736,7 @@ function createVercel(options, environment) {
3442
3736
  }),
3443
3737
  older: null
3444
3738
  };
3445
- if (read.id !== void 0) learn({
3739
+ if (read.id !== void 0) learn(who, {
3446
3740
  id: read.id,
3447
3741
  name
3448
3742
  });
@@ -3462,16 +3756,15 @@ function createVercel(options, environment) {
3462
3756
  };
3463
3757
  }
3464
3758
  if (query.before !== void 0) throw new HttpError(400, "invalid_request", "before: this board pages one channel's threads, with no filters");
3465
- if (byMessage) {
3466
- const { messages, feeds, newest } = await collect(who, query, signal);
3467
- const latest = /* @__PURE__ */ new Map();
3468
- for (const { message, thread, channel } of messages) latest.set(thread.id, {
3469
- thread,
3470
- channel,
3471
- at: Math.max(latest.get(thread.id)?.at ?? 0, message.createdAt)
3472
- });
3759
+ if (query.re !== void 0) {
3760
+ const { messages, feeds, newest } = await threadMatching(who, query.re, query, signal);
3761
+ const latest = messages.at(-1);
3473
3762
  return {
3474
- threads: await summaries(who, pick([...latest.values()]), signal),
3763
+ threads: latest ? await summaries(who, pick([{
3764
+ thread: latest.thread,
3765
+ channel: latest.channel,
3766
+ at: Math.max(...messages.map(({ message }) => message.createdAt))
3767
+ }]), signal) : [],
3475
3768
  cursor: cursorOf({
3476
3769
  t: newest,
3477
3770
  feeds
@@ -3515,10 +3808,15 @@ function createVercel(options, environment) {
3515
3808
  })
3516
3809
  };
3517
3810
  },
3518
- async message(caller, { id }, signal) {
3811
+ async message(caller, { id, after, limit }, signal) {
3519
3812
  const who = whoOf(caller);
3520
3813
  const { thread, channel } = await messageIn(who, id, signal);
3521
- const [root, ...replies] = await threadMessages(who, thread.id, signal);
3814
+ const from = after === void 0 ? void 0 : locate(after);
3815
+ if (after !== void 0 && from?.threadId !== thread.id) throw new HttpError(400, "invalid_request", `after: ${after} isn't a message of this thread`);
3816
+ const [root, ...replies] = from !== void 0 || limit !== void 0 ? await threadRange(who, thread.id, {
3817
+ ...from ? { after: from.sequence } : {},
3818
+ ...limit !== void 0 ? { limit } : {}
3819
+ }, signal) : await threadMessages(who, thread.id, signal);
3522
3820
  if (!root) throw notFound(`message not found: ${id}`, "message_not_found");
3523
3821
  const [message, ...shown] = await Promise.all([root, ...replies].map((each) => view(who, each, channel.name)));
3524
3822
  return {
@@ -3532,13 +3830,13 @@ function createVercel(options, environment) {
3532
3830
  },
3533
3831
  async upload(caller, { data, name, type }) {
3534
3832
  const who = whoOf(caller);
3535
- if (data.byteLength === 0) throw new HttpError(400, "bad_request", "the file is empty");
3833
+ if (data.byteLength === 0) throw new HttpError(400, "invalid_request", "the file is empty");
3536
3834
  if (data.byteLength > 26214400) throw new HttpError(413, "too_large", `attachments are at most ${IMPORT_BYTES_MAX / 1024 / 1024} MB`);
3537
3835
  const bytes = new Uint8Array(data);
3538
3836
  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
3539
3837
  const started = await api(who, "POST", await onBoard(who, "/attachments"), { body: {
3540
3838
  operationId: operationId(),
3541
- name: fileName(name),
3839
+ name: uploadName(name),
3542
3840
  type: mediaType(type),
3543
3841
  size: data.byteLength,
3544
3842
  sha256: btoa(String.fromCharCode(...digest))
@@ -3558,7 +3856,7 @@ function createVercel(options, environment) {
3558
3856
  if (sha256 === void 0) throw new HttpError(400, "invalid_request", "Vercel's API signs a direct upload for its bytes' SHA-256: send `sha256`, as board's client does");
3559
3857
  const started = await api(who, "POST", await onBoard(who, "/attachments"), { body: {
3560
3858
  operationId: operationId(),
3561
- name: fileName(name ?? null),
3859
+ name: uploadName(name ?? null),
3562
3860
  type: mediaType(type ?? null),
3563
3861
  size,
3564
3862
  sha256
@@ -3847,7 +4145,7 @@ function createVercel(options, environment) {
3847
4145
  ...filter,
3848
4146
  ...inChannel(channel)
3849
4147
  }, signal);
3850
- if (found[0]) learn({
4148
+ if (found[0]) learn(who, {
3851
4149
  id: found[0].channelId,
3852
4150
  name
3853
4151
  });
@@ -4408,10 +4706,10 @@ function createVercel(options, environment) {
4408
4706
  query: { limit: String(channel === void 0 ? wanted : INBOX_LIST_MAX) },
4409
4707
  signal
4410
4708
  }));
4411
- const entries = events.flatMap(({ id, createdAt, event, raw }) => event ? [{
4709
+ const entries = events.flatMap(({ id, pushedAt, event, raw }) => event ? [{
4412
4710
  id,
4413
4711
  channel: typeof event.channel === "string" ? event.channel : "",
4414
- createdAt,
4712
+ createdAt: iso(pushedAt),
4415
4713
  sync: key,
4416
4714
  event,
4417
4715
  raw: raw ?? null
@@ -4789,12 +5087,15 @@ async function inputOf(name, request, url, params) {
4789
5087
  switch (name) {
4790
5088
  case "discovery":
4791
5089
  case "me":
4792
- case "channels":
5090
+ case "channels": return ChannelsQuery.parse(queryObject(url));
4793
5091
  case "actors":
4794
5092
  case "watchers":
4795
5093
  case "grants":
4796
5094
  case "schemas": return {};
4797
- case "message":
5095
+ case "message": return {
5096
+ id,
5097
+ ...ThreadQuery.parse(queryObject(url))
5098
+ };
4798
5099
  case "posted":
4799
5100
  case "synced":
4800
5101
  case "cancelSchedule":
@@ -4803,14 +5104,17 @@ async function inputOf(name, request, url, params) {
4803
5104
  case "schema":
4804
5105
  case "attachment":
4805
5106
  case "uploadFinish": return { id };
4806
- case "messages": return MessagesQuery.parse(queryObject(url));
5107
+ case "channelMessages": return ChannelMessagesQuery.parse(queryObject(url));
4807
5108
  case "threads": return ThreadsQuery.parse(queryObject(url));
4808
5109
  case "schedules": return SchedulesQuery.parse(queryObject(url));
4809
5110
  case "matches": return MatchesQuery.parse(queryObject(url));
4810
5111
  case "events": {
4811
5112
  const query = EventsQuery.parse(queryObject(url));
4812
5113
  const last = request.headers.get("last-event-id");
4813
- if (query.after === void 0 && last && Ref.safeParse(last).success) query.after = last;
5114
+ if (query.after === void 0 && last && Ref.safeParse(last).success) {
5115
+ query.after = last;
5116
+ delete query.last;
5117
+ }
4814
5118
  return query;
4815
5119
  }
4816
5120
  case "post": return PostBody.parse(await body());
@@ -5002,9 +5306,11 @@ async function createServe(context) {
5002
5306
  const watch = options.watch ?? {};
5003
5307
  const middleware = options.middleware ?? [];
5004
5308
  /** What a request says about who it is, none of it verified yet: its bearer token, its claims, and the board's URL. */
5005
- function requestOf(request, audience) {
5309
+ function requestOf(request, at) {
5310
+ const credential = (request.headers.get("authorization") ?? "").match(/^Bearer\s+(.+)$/i)?.[1] ?? null;
5311
+ const audience = credential === null ? options.url?.replace(/\/+$/, "") ?? at : audienceOf(at);
5006
5312
  return {
5007
- credential: (request.headers.get("authorization") ?? "").match(/^Bearer\s+(.+)$/i)?.[1] ?? null,
5313
+ credential,
5008
5314
  claims: claimsOf(request.headers),
5009
5315
  audience,
5010
5316
  headers: request.headers
@@ -5017,6 +5323,19 @@ async function createServe(context) {
5017
5323
  origin: { via: { kind: "api" } }
5018
5324
  };
5019
5325
  }
5326
+ let warned = false;
5327
+ /**
5328
+ * The URL a token's audience must be: `url`, or the one `at` reaches where something checks a request's
5329
+ * Host first. Anywhere else its sender chooses it, so a production board without `url` verifies no tokens.
5330
+ */
5331
+ function audienceOf(at) {
5332
+ if (options.url) return options.url.replace(/\/+$/, "");
5333
+ if (hostTrusted(options)) return at;
5334
+ if (typeof process !== "undefined" && process.env.NODE_ENV === "production") throw new HttpError(500, "no_board_url", "this board has no URL to check a token's audience against, and outside Vercel a request's Host is its sender's to choose", { hint: "Pass board({ url: 'https://<host>/api/board' }), the URL people reach it at." });
5335
+ if (!warned) console.warn(`[board] no url: verifying tokens for ${at}, the host requests name. Pass board({ url }) before this serves in production.`);
5336
+ warned = true;
5337
+ return at;
5338
+ }
5020
5339
  /**
5021
5340
  * What a board that serves no requests answers them: one that uses another board's. One on
5022
5341
  * Vercel's still takes wake-ups and webhooks; one at `BOARD_URL` has neither.
@@ -5819,7 +6138,8 @@ async function createServe(context) {
5819
6138
  * `access` says now holds, and a token that runs out ends it.
5820
6139
  */
5821
6140
  async function sse(caller, query, request, identify) {
5822
- const first = await backend.events(caller, {
6141
+ const { last, ...following } = query;
6142
+ const first = await backend.events(caller, last !== void 0 ? query : {
5823
6143
  ...query,
5824
6144
  wait: 0
5825
6145
  }, request.signal);
@@ -5850,7 +6170,7 @@ async function createServe(context) {
5850
6170
  const left = deadline - Date.now();
5851
6171
  if (signal.aborted || left <= 0) break;
5852
6172
  page = await backend.events(identify ? await identify() : caller, {
5853
- ...query,
6173
+ ...following,
5854
6174
  after,
5855
6175
  wait: Math.min(300, left / 1e3)
5856
6176
  }, signal);
@@ -5901,7 +6221,7 @@ async function createServe(context) {
5901
6221
  if (!match) throw notFound(`no route: ${request.method} ${url.pathname}`);
5902
6222
  const { target } = match;
5903
6223
  if (!injected && !match.root && (state.learned === null || state.learned.startsWith(`${match.base}/`))) state.learned = match.base;
5904
- const boardUrl = (options.url ?? `${url.origin}${match.base}`).replace(/\/+$/, "");
6224
+ const at = `${url.origin}${match.base}`.replace(/\/+$/, "");
5905
6225
  if (target.kind === "board" && target.name === "webhook") {
5906
6226
  if (!engine || !entries[match.params.key ?? ""]) throw notFound(`no sync entry named ${match.params.key}`);
5907
6227
  return await engine.handleWebhook(match.params.key, request);
@@ -5920,10 +6240,10 @@ async function createServe(context) {
5920
6240
  param: match.param
5921
6241
  });
5922
6242
  if (!injected && !policy.open) throw servesOnly();
5923
- if (!injected && target.kind === "protocol" && target.name === "discovery") return json(await discovery(request, boardUrl, request.signal));
6243
+ if (!injected && target.kind === "protocol" && target.name === "discovery") return json(await discovery(request, audienceOf(at), request.signal));
5924
6244
  if (target.kind === "protocol" && typeof backend[target.name] !== "function") throw notFound(`no route: ${request.method} ${url.pathname}`);
5925
6245
  const own = injected && "platform" in injected ? engine.caller : injected;
5926
- const asked = own ? null : requestOf(request, boardUrl);
6246
+ const asked = own ? null : requestOf(request, at);
5927
6247
  const caller = own ?? await callerOf(asked);
5928
6248
  if (target.kind === "board") return await serve(target.name, caller, request, url, match.params);
5929
6249
  const input = await inputOf(target.name, request, url, match.params);
@@ -5988,6 +6308,14 @@ async function createServe(context) {
5988
6308
  }
5989
6309
  //#endregion
5990
6310
  //#region src/server/board.ts
6311
+ const hostChecked = /* @__PURE__ */ new WeakSet();
6312
+ /** `options`, for a board behind a server that lets a request name only hosts it allows, as `vb serve` does. */
6313
+ function hostCheckedBy(options) {
6314
+ hostChecked.add(options);
6315
+ return options;
6316
+ }
6317
+ /** Whether a board without `url` can take it from a request's Host: on Vercel, or behind a server that checks Host. */
6318
+ const hostTrusted = (options) => hostChecked.has(options) || typeof process !== "undefined" && process.env.VERCEL === "1";
5991
6319
  /** A handle's own, with every request it makes ended by a signal: what `vb()` runs a command on. Global, so another copy of board finds it. */
5992
6320
  const STOPPED_BY = Symbol.for("@vercel/board/stopped-by");
5993
6321
  /**
@@ -6054,8 +6382,8 @@ const avatarUrl = (value) => {
6054
6382
  const BOARD_NAME = /^[^/]{1,64}$/;
6055
6383
  /** A team, by its ID or its slug. */
6056
6384
  const TEAM = /^[^\s/]+$/;
6057
- /** Whether `name` is a board's name, such as `security`. */
6058
- const isBoardName = (name) => BOARD_NAME.test(name);
6385
+ /** Whether `name` is a board's name, such as `security`, counted as Vercel's API counts it: trimmed and NFC-normalized. */
6386
+ const isBoardName = (name) => BOARD_NAME.test(name.trim().normalize("NFC"));
6059
6387
  /**
6060
6388
  * A board for this project, on `backend`: Vercel's board for the team by default, `local()` in this
6061
6389
  * process, or one of your own. What it returns is the handle: its
@@ -6310,6 +6638,7 @@ function createBoard(options, runtime) {
6310
6638
  * quiet board's whole wait later.
6311
6639
  */
6312
6640
  async function* events(client, query = {}, opts = {}) {
6641
+ const { last, ...rest } = query;
6313
6642
  let after = query.after;
6314
6643
  let failures = 0;
6315
6644
  /** Whether the board has answered since the feed started, or since it last failed. */
@@ -6318,14 +6647,17 @@ async function* events(client, query = {}, opts = {}) {
6318
6647
  while (!opts.signal?.aborted) {
6319
6648
  let page;
6320
6649
  try {
6321
- page = await client.poll({
6322
- ...query,
6650
+ page = await client.poll(after === void 0 && last !== void 0 ? {
6651
+ ...rest,
6652
+ last
6653
+ } : {
6654
+ ...rest,
6323
6655
  ...after !== void 0 ? { after } : {},
6324
6656
  wait: answered ? EVENTS_WAIT_S : 0
6325
6657
  }, opts.signal);
6326
6658
  } catch (error) {
6327
6659
  if (opts.signal?.aborted) return;
6328
- if (error instanceof BoardError && error.status >= 400 && error.status < 500) throw error;
6660
+ if (error instanceof BoardError && (error.status === 501 || error.status >= 400 && error.status < 500)) throw error;
6329
6661
  answered = false;
6330
6662
  state.failed();
6331
6663
  await new Promise((resolve) => setTimeout(resolve, Math.min(3e4, 500 * 2 ** failures++)));
@@ -6411,4 +6743,4 @@ async function createTasksInChunks(board, channel, tasks, options = {}) {
6411
6743
  return created;
6412
6744
  }
6413
6745
  //#endregion
6414
- export { stoppedBy as a, PROTOCOL_ROUTES as c, deployedOnVercel as d, isBoardName as i, withoutToken as l, createTasksInChunks as n, createVercel as o, createBoard as r, isApiMessageId as s, TasksInChunksError as t, tailWatchers as u };
6746
+ export { isBoardName as a, isApiMessageId as c, tailWatchers as d, deployedOnVercel as f, hostCheckedBy as i, PROTOCOL_ROUTES as l, createTasksInChunks as n, stoppedBy as o, createBoard as r, createVercel as s, TasksInChunksError as t, withoutToken as u };