@vercel/board 0.38.0 → 0.39.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 (38) hide show
  1. package/dist/{backend-BkQlF1LQ.d.mts → backend-HcCCGPG4.d.mts} +1 -1
  2. package/dist/backend-local.d.mts +1 -1
  3. package/dist/backend-local.mjs +1 -1
  4. package/dist/cli-embedded.d.mts +2 -2
  5. package/dist/cli-embedded.mjs +3 -3
  6. package/dist/cli.mjs +4 -4
  7. package/dist/{conformance-qJF96jZI.mjs → conformance-D59Py2m2.mjs} +4 -8
  8. package/dist/conformance.d.mts +1 -1
  9. package/dist/conformance.mjs +1 -1
  10. package/dist/digest-krhjNAt4.mjs +4 -0
  11. package/dist/{exports-BsfcChdp.mjs → exports-M5o4PTfO.mjs} +21 -16
  12. package/dist/exports-vLQ2Y2Nd.d.mts +4 -0
  13. package/dist/{index-DpVyZa9b.d.mts → index-rNqqgkyu.d.mts} +2 -2
  14. package/dist/index.d.mts +2 -2
  15. package/dist/index.mjs +1 -1
  16. package/dist/index.node.d.mts +2 -2
  17. package/dist/index.node.mjs +1 -1
  18. package/dist/inspect/app.js +5 -5
  19. package/dist/{inspect-DtCbBtOW.mjs → inspect-BkXxR2uB.mjs} +3 -3
  20. package/dist/inspect-lnv1sLXM.mjs +2 -0
  21. package/dist/{local-Bo3XzEKB.mjs → local-DvkOWf4U.mjs} +227 -511
  22. package/dist/{main-0nvLgajF.mjs → main-DtV_Po9i.mjs} +5 -5
  23. package/dist/{page-UsfvSIWc.mjs → page-64IwoGRu.mjs} +2 -2
  24. package/dist/page-BUj8_UZv.mjs +2 -0
  25. package/dist/{serve-D7I3KisQ.mjs → serve-CX1rqDF_.mjs} +2 -2
  26. package/dist/{server-Cc3nYq3H.mjs → server-DkYkyarg.mjs} +41 -96
  27. package/dist/{targets-B4Uikw0J.mjs → targets-C1mT3M1N.mjs} +1 -1
  28. package/docs/01-board/01-mounting.md +2 -2
  29. package/docs/01-board/03-identity.md +1 -1
  30. package/docs/01-board/06-watchers.md +8 -11
  31. package/docs/01-board/09-access.md +1 -1
  32. package/docs/02-sync/01-overview.md +2 -5
  33. package/docs/04-reference/03-http.md +3 -3
  34. package/package.json +1 -1
  35. package/dist/digest-DAxy9Ula.mjs +0 -4
  36. package/dist/exports-BJ3wmEMY.d.mts +0 -4
  37. package/dist/inspect-5mkjJYMS.mjs +0 -2
  38. package/dist/page-R0RoE_gM.mjs +0 -2
@@ -1,7 +1,7 @@
1
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";
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";
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-C1mT3M1N.mjs";
5
5
  import { a as waitUntil, c as isKeyIdOf, n as MIDDLEWARE_ACTOR, s as derivedId, t as DroppedError } from "./middleware-CPqAuRtp.mjs";
6
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
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";
@@ -16,9 +16,6 @@ import { createHash, randomBytes } from "node:crypto";
16
16
  import { mkdir, readFile, writeFile } from "node:fs/promises";
17
17
  import { dirname, join, resolve } from "node:path";
18
18
  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
19
  //#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
20
  /**
24
21
  * Run a Standard Schema validator, requiring a synchronous result.
@@ -6909,24 +6906,223 @@ function createSchedules(options) {
6909
6906
  }
6910
6907
  };
6911
6908
  }
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));
6909
+ //#endregion
6910
+ //#region src/server/watch.ts
6911
+ const ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
6912
+ /** The events a tail shows, receipts included for `--all`: each concerns a message, and carries its thread for the lane. */
6913
+ const WATCHED = [
6914
+ "message.posted",
6915
+ "message.edited",
6916
+ "message.deleted",
6917
+ "reaction.added",
6918
+ "reaction.removed",
6919
+ "labels.changed",
6920
+ "message.sync_failed",
6921
+ "message.synced",
6922
+ "message.files_synced",
6923
+ "thread.synced"
6924
+ ];
6925
+ /** Receipts: only a `--all` tail shows them. */
6926
+ const RECEIPTS = /* @__PURE__ */ new Set(["message.synced", "message.files_synced"]);
6916
6927
  /**
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.
6928
+ * What a registrant's sync gets, in every channel where it may sync: what it delivers to platforms,
6929
+ * and a thread's new targets. A tail never shows `thread.synced`, so no watcher gets it.
6919
6930
  */
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;
6931
+ const SYNCED = /* @__PURE__ */ new Set([
6932
+ "message.posted",
6933
+ "message.edited",
6934
+ "message.deleted",
6935
+ "reaction.added",
6936
+ "reaction.removed",
6937
+ "labels.changed",
6938
+ "thread.synced"
6939
+ ]);
6940
+ /** A watcher writes as `board:watch:<id>`, and its own writes never wake it. */
6941
+ const actorOf = (id) => `board:watch:${id}`;
6942
+ /** `watch:@<principal>`: everything one registrant's watchers matched, queued for it to pull. */
6943
+ const registrantSession = (owner) => watchSession(`@${owner}`);
6925
6944
  /**
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.
6945
+ * Watchers: a board-contract consumer matches each event against every
6946
+ * watcher's filters, the way a tail does, and appends what matched to that
6947
+ * watcher's session, where `run` happens on the thread's lane.
6928
6948
  */
6929
- const wakeBackoff = (failures) => Math.min(WAKE_BACKOFF_MAX_MS, SWEEP_MS * 2 ** (failures - 1));
6949
+ function createWatchers(options) {
6950
+ const watchers = Object.entries(options.watch).map(([id, watcher]) => {
6951
+ if (!ID.test(id)) throw new Error(`watch: ids use lowercase letters, numbers, - and _, got: ${id}`);
6952
+ return {
6953
+ id,
6954
+ ...compileWatcher(id, watcher)
6955
+ };
6956
+ });
6957
+ const byId = new Map(watchers.map((watcher) => [watcher.id, watcher]));
6958
+ let reads = null;
6959
+ /** Runs a watcher on a board event it matched, one thread at a time. */
6960
+ const runner = consumer({
6961
+ contract: watchContract,
6962
+ name: "board-watch",
6963
+ types: ["watch.matched"],
6964
+ lane: ({ event }) => `thread:${event.payload.thread}`
6965
+ }).run(async (ctx) => {
6966
+ const watcher = byId.get(ctx.session.id.slice(6));
6967
+ if (!watcher) return;
6968
+ await runMatch({
6969
+ watcher: {
6970
+ id: watcher.id,
6971
+ run: (event) => options.run(watcher.id, event, ctx.event.id, ctx.attempt)
6972
+ },
6973
+ match: ctx.event,
6974
+ attempt: ctx.attempt,
6975
+ record: (payload) => ctx.session.append(`failed:${ctx.event.id}`, {
6976
+ type: "watch.failed",
6977
+ payload
6978
+ })
6979
+ });
6980
+ });
6981
+ const server = createServer({
6982
+ contract: watchContract,
6983
+ ...options.store ? { store: options.store } : {},
6984
+ ...options.scheduler ? { scheduler: options.scheduler } : {},
6985
+ consumers: [runner]
6986
+ });
6987
+ const configured = watchers.map((watcher) => ({
6988
+ ...watcher,
6989
+ actor: actorOf(watcher.id)
6990
+ }));
6991
+ const compiled = /* @__PURE__ */ new Map();
6992
+ function compiledFor(registration) {
6993
+ const version = `${registration.hash}\u001f${JSON.stringify(registration.principal)}`;
6994
+ const hit = compiled.get(registration.owner);
6995
+ if (hit?.version === version) return hit.candidates;
6996
+ const candidates = [];
6997
+ for (const [id, spec] of Object.entries(registration.watch)) try {
6998
+ candidates.push({
6999
+ ...compileWatcher(id, spec),
7000
+ id,
7001
+ actor: `${registration.owner}+${id.toLowerCase()}`,
7002
+ registration
7003
+ });
7004
+ } catch (error) {
7005
+ console.error(`[board] skipping a watcher ${registration.owner} registered:`, error.message);
7006
+ }
7007
+ compiled.set(registration.owner, {
7008
+ version,
7009
+ candidates
7010
+ });
7011
+ return candidates;
7012
+ }
7013
+ async function registrations() {
7014
+ return options.registered ? Object.values((await options.registered.state()).byOwner) : [];
7015
+ }
7016
+ /** Matches one board event; the message before or after it must match, as in a tail. */
7017
+ async function dispatch(ctx) {
7018
+ const event = ctx.event;
7019
+ const through = event.index - 1;
7020
+ const [messages, { state: actors }] = await Promise.all([messagesBefore(event, ctx.signal), ctx.session.state(actorsReducer, { through })]);
7021
+ const { id, before, after } = foldEvent(messages, actors, event);
7022
+ const by = event.payload.by?.actor;
7023
+ const message = after ?? before;
7024
+ const thread = event.payload.thread;
7025
+ let view$1;
7026
+ /** Each session's matches, appended together: one append per watcher in config, one per registrant. */
7027
+ const appends = /* @__PURE__ */ new Map();
7028
+ const add = (session, matched) => (appends.get(session) ?? appends.set(session, []).get(session)).push(matched);
7029
+ const registered = await registrations();
7030
+ const targets = [...configured, ...registered.flatMap(compiledFor)];
7031
+ const registrants = /* @__PURE__ */ new Map();
7032
+ const accessOf = (registration) => {
7033
+ let found = registrants.get(registration.owner);
7034
+ if (!found) registrants.set(registration.owner, found = options.registered.accessNow(registration.principal));
7035
+ return found;
7036
+ };
7037
+ for (const watcher of targets) {
7038
+ if (event.type === "thread.synced") break;
7039
+ if (by === watcher.actor) continue;
7040
+ if (RECEIPTS.has(event.type) && !watcher.all) continue;
7041
+ const { registration } = watcher;
7042
+ let access = FULL_ACCESS;
7043
+ if (registration) {
7044
+ const now = await accessOf(registration);
7045
+ if (!now || (id === null ? !now.readsAll : !message || !now.readable(message.channel))) continue;
7046
+ access = now;
7047
+ }
7048
+ const match = compileFilter(watcher.filters, {
7049
+ me: null,
7050
+ actors,
7051
+ messages,
7052
+ access
7053
+ });
7054
+ if (!(watcher.criteria ? match(before) || match(after) : id !== null)) continue;
7055
+ const key = registration ? `@${registration.owner}/${watcher.id}` : watcher.id;
7056
+ const shown = registration ? eventView(event, after, actors, await reads.reader(access, after ? [after] : [])) : view$1 ??= eventView(event, after, actors, OWN_CODE);
7057
+ add(registration ? registrantSession(registration.owner) : watchSession(watcher.id), {
7058
+ type: "watch.matched",
7059
+ id: await idempotentId("board-watch", key, event.id),
7060
+ payload: {
7061
+ thread,
7062
+ event: shown,
7063
+ ...registration ? { watcher: watcher.id } : {}
7064
+ }
7065
+ });
7066
+ }
7067
+ const syncing = SYNCED.has(event.type) ? registered.filter((registration) => registration.sync.length > 0) : [];
7068
+ if (syncing.length > 0) {
7069
+ const about = event.type === "thread.synced" ? await rootOf(event.payload.thread, event.index, ctx.signal) : message;
7070
+ for (const registration of syncing) {
7071
+ const now = await accessOf(registration);
7072
+ if (!now || !about || !now.can("sync", about.channel)) continue;
7073
+ const reader = await reads.reader(now, [about, ...before ? [before] : []]);
7074
+ const shown = {
7075
+ ...eventView(event, about, actors, reader),
7076
+ ...event.type === "labels.changed" && before ? { before: view(before, actors, reader) } : {}
7077
+ };
7078
+ add(registrantSession(registration.owner), {
7079
+ type: "watch.matched",
7080
+ id: await idempotentId("board-watch", `@${registration.owner}/@sync`, event.id),
7081
+ payload: {
7082
+ thread,
7083
+ event: shown,
7084
+ sync: true
7085
+ }
7086
+ });
7087
+ }
7088
+ }
7089
+ await Promise.all([...appends].map(async ([session, events]) => {
7090
+ try {
7091
+ await server.session(session).append(...events);
7092
+ } catch (error) {
7093
+ if (!(error instanceof A2Error && error.code === "PARTIAL_DUPLICATE_BATCH")) throw error;
7094
+ for (const matched of events) await server.session(session).append(matched);
7095
+ }
7096
+ }));
7097
+ }
7098
+ /** A thread's root, as the board has it once the tables reach `index`: the event that synced it comes after it. */
7099
+ async function rootOf(thread, index, signal) {
7100
+ if (!reads) throw new Error("watchers used before the board bound them");
7101
+ await reads.ensure(index - 1, signal);
7102
+ return await reads.tables.byEventId(thread) ?? void 0;
7103
+ }
7104
+ /** The message `event` concerns, and its thread's root, as they were just before it. */
7105
+ async function messagesBefore(event, signal) {
7106
+ if (!reads) throw new Error("watchers used before the board bound them");
7107
+ return loadBefore(reads, event, signal);
7108
+ }
7109
+ return {
7110
+ server,
7111
+ boardConsumer: consumer({
7112
+ contract: boardContract,
7113
+ name: "board-watchers",
7114
+ types: WATCHED,
7115
+ lane: ({ event }) => `thread:${event.payload.thread}`
7116
+ }).run(dispatch),
7117
+ bind: (binding) => {
7118
+ reads = binding.reads;
7119
+ }
7120
+ };
7121
+ }
7122
+ /** How long a pulled match is its puller's before someone may pull it again. */
7123
+ const LEASE_MS = 3e5;
7124
+ /** After an error, a match waits 1 second, doubling to 30. */
7125
+ const retryDelay = (attempts) => Math.min(3e4, 1e3 * 2 ** (attempts - 1));
6930
7126
  /** The queue of platform events a registrant pushed for sync key `key`. */
6931
7127
  const inboxQueue = (key) => `@inbox:${key}`;
6932
7128
  const queueKey = (queue, thread) => `${queue}\u001f${thread}`;
@@ -6989,38 +7185,19 @@ function foldQueue(state, event) {
6989
7185
  if (found) found.retryAt = null;
6990
7186
  return state;
6991
7187
  }
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;
6999
- }
7000
7188
  case "watch.failed":
7001
7189
  case "watch.skipped":
7002
7190
  remove(state, event.payload.matched);
7003
7191
  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
7192
  default: return state;
7014
7193
  }
7015
7194
  }
7016
7195
  const queueReducer = reducer({
7017
7196
  contract: watchContract,
7018
- name: "board.watch-queue.v4",
7197
+ name: "board.watch-queue.v5",
7019
7198
  initialState: {
7020
7199
  queues: {},
7021
- pending: {},
7022
- sweeps: [],
7023
- unreachable: null
7200
+ pending: {}
7024
7201
  }
7025
7202
  }).fold(foldQueue);
7026
7203
  const describe = (error) => ((error instanceof Error ? error.message : String(error)) || "unknown error").slice(0, 500);
@@ -7037,8 +7214,6 @@ function readable(access, event, queue) {
7037
7214
  const taken = (error) => error instanceof A2Error && error.code === "PARTIAL_DUPLICATE_BATCH";
7038
7215
  /** 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
7216
  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
7217
  /**
7043
7218
  * Hands out what the registrant's watchers and sync may run now: each queue's oldest match, if it's
7044
7219
  * free, leased to this pull. The inbox's queues are `pullInbox`'s.
@@ -7077,10 +7252,7 @@ function pullInbox(session, key, options) {
7077
7252
  */
7078
7253
  async function lease(session, options) {
7079
7254
  const { state } = await session.state(queueReducer);
7080
- const events = state.unreachable ? [{
7081
- type: "watch.reachable",
7082
- payload: { by: "pull" }
7083
- }] : [];
7255
+ const events = [];
7084
7256
  const offered = [];
7085
7257
  for (const ids of Object.values(state.queues)) {
7086
7258
  if (offered.length >= options.limit) break;
@@ -7136,9 +7308,7 @@ async function lease(session, options) {
7136
7308
  });
7137
7309
  if (offered.length === 0) return [];
7138
7310
  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 }) => ({
7311
+ return offered.filter(({ head, lease }) => after.pending[head.id]?.lease?.id === lease).map(({ head, lease, attempt }) => ({
7142
7312
  id: head.id,
7143
7313
  queue: head.queue,
7144
7314
  thread: head.thread,
@@ -7195,47 +7365,8 @@ async function ack(session, id, body, options) {
7195
7365
  retryAt
7196
7366
  }
7197
7367
  });
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
7368
  return "acked";
7206
7369
  }
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
7370
  /** Gives up on a match: `watch.failed`, said in the logs too. */
7240
7371
  function failure(found, error) {
7241
7372
  console.error(`[board] a registrant's ${found.queue} gave up on an item after 5 tries:`, error);
@@ -7249,377 +7380,6 @@ function failure(found, error) {
7249
7380
  };
7250
7381
  }
7251
7382
  //#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
7383
  //#region src/server/a2.ts
7624
7384
  /** Sync's own lookups and receipts, from board() in this deployment. */
7625
7385
  const SYNC_ACTOR = "board:sync";
@@ -7653,8 +7413,6 @@ function scheduleAt(value) {
7653
7413
  return index;
7654
7414
  }
7655
7415
  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
7416
  /**
7659
7417
  * `idempotentId`'s shape, a UUIDv8: the IDs the board derives for its own writes (schedule
7660
7418
  * sends, watchers, sync). They're guessable, so an API caller can't post with one and take it first.
@@ -7766,7 +7524,6 @@ function build(options, binding) {
7766
7524
  const identityOf = async (caller) => "identity" in caller ? caller.identity : selfIdentity(caller);
7767
7525
  /** Its own code's handle, which reaches it in process. */
7768
7526
  let ownHandle = null;
7769
- const post = options.transport?.post ?? publicPost;
7770
7527
  const watchers = createWatchers({
7771
7528
  watch: Object.fromEntries(Object.entries(binding.subscriptions).flatMap(([id, subscription]) => subscription.kind === "tail" ? [[id, { tail: subscription.tail }]] : [])),
7772
7529
  run: (id, event, trigger, attempt) => binding.run(id, event, {
@@ -7777,8 +7534,7 @@ function build(options, binding) {
7777
7534
  scheduler: options.scheduler,
7778
7535
  registered: {
7779
7536
  state: registry.state,
7780
- accessNow: (principal) => binding.accessNow(principal),
7781
- wake
7537
+ accessNow: (principal) => binding.accessNow(principal)
7782
7538
  }
7783
7539
  });
7784
7540
  const schedules = createSchedules({
@@ -7915,33 +7671,6 @@ function build(options, binding) {
7915
7671
  if (!await attachmentReadable(principal, id, uploader)) throw attachmentNotFound(id);
7916
7672
  return attachment;
7917
7673
  }));
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
7674
  /** A registrant's queue, in the watch contract: its watchers' and sync's matches, and its inbox. */
7946
7675
  const queueOf = (owner) => watchers.server.session(registrantSession(owner));
7947
7676
  /**
@@ -8254,7 +7983,8 @@ function build(options, binding) {
8254
7983
  return { watchers: principal.access.everywhere("manage") ? all : all.filter((found) => found.owner === principal.id) };
8255
7984
  },
8256
7985
  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");
7986
+ if (body.path) throw new HttpError(501, "no_wake_by_path", "this board wakes nothing: register no path, and pull your matches");
7987
+ if (body.url) throw new HttpError(501, "no_wake_by_url", "this board wakes nothing: register no url, and pull your matches");
8258
7988
  const { principal } = await identityOf(caller);
8259
7989
  ownWatchers(principal);
8260
7990
  if (!principal.access.anywhere("read")) throw forbidden$1("this token can't read anywhere, so a watcher it registers would see nothing");
@@ -8270,17 +8000,11 @@ function build(options, binding) {
8270
8000
  throw badRequest(error.message, "bad_watcher");
8271
8001
  }
8272
8002
  }
8273
- const registered = await registry.register(storedPrincipal(principal), {
8274
- url: body.url ?? null,
8003
+ return registry.register(storedPrincipal(principal), {
8004
+ url: null,
8275
8005
  watch: body.watch,
8276
8006
  sync: body.sync ?? []
8277
8007
  });
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
8008
  },
8285
8009
  async matches(caller, query, signal) {
8286
8010
  const { principal } = await identityOf(caller);
@@ -8289,8 +8013,7 @@ function build(options, binding) {
8289
8013
  const queue = queueOf(principal.id);
8290
8014
  const pulling = {
8291
8015
  access: principal.access,
8292
- limit: query.limit ?? 10,
8293
- timers: options.scheduler !== void 0
8016
+ limit: query.limit ?? 10
8294
8017
  };
8295
8018
  const deadline = Date.now() + (query.wait ?? 0) * 1e3;
8296
8019
  for (let pause = 100;; pause = Math.min(pause * 2, 1e3)) {
@@ -8312,10 +8035,7 @@ function build(options, binding) {
8312
8035
  async ack(caller, { id, ...body }) {
8313
8036
  const { principal } = await identityOf(caller);
8314
8037
  ownWatchers(principal);
8315
- const result = await ack(queueOf(principal.id), id, body, {
8316
- now: Date.now(),
8317
- timers: options.scheduler !== void 0
8318
- });
8038
+ const result = await ack(queueOf(principal.id), id, body, { now: Date.now() });
8319
8039
  if (result === "gone") throw notFound(`no match ${id} is waiting for this token`, "no_match");
8320
8040
  if (result === "stale") throw new HttpError(409, "stale_lease", "that lease ran out, and the match was pulled again");
8321
8041
  return { ok: true };
@@ -8686,8 +8406,7 @@ function build(options, binding) {
8686
8406
  return { items: (await pullInbox(queueOf(principal.id), key, {
8687
8407
  access: principal.access,
8688
8408
  limit: limit ?? 10,
8689
- now: Date.now(),
8690
- timers: options.scheduler !== void 0
8409
+ now: Date.now()
8691
8410
  })).map(({ id, thread, lease, attempt, event }) => {
8692
8411
  const item = event;
8693
8412
  return {
@@ -8706,10 +8425,7 @@ function build(options, binding) {
8706
8425
  const result = await ack(queueOf(principal.id), id, {
8707
8426
  lease,
8708
8427
  error
8709
- }, {
8710
- now: Date.now(),
8711
- timers: options.scheduler !== void 0
8712
- });
8428
+ }, { now: Date.now() });
8713
8429
  if (result === "gone") throw notFound(`no inbox event ${id} is waiting for this token`, "no_item");
8714
8430
  if (result === "stale") throw new HttpError(409, "stale_lease", "that lease ran out, and the event was pulled again");
8715
8431
  return { ok: true };