@steve31415/baselib 3.59.0 → 3.60.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.
package/README.md CHANGED
@@ -10,8 +10,11 @@ Server subpath exports: `config`, `log`, `auth`, `oauth-resource`, `connector`,
10
10
  `client-version`. Browser exports: `log-browser`, `rum`, `slow-fetch`, `sync-browser`, `app-update-browser`, and
11
11
  `extension-self-update`.
12
12
 
13
- `sync` provides the Postgres event-log and server protocol primitives;
14
- `sync-browser` provides the IndexedDB outbox and offline-first client.
13
+ `sync` provides the Postgres event-log and server protocol primitives, and
14
+ `handleSyncEventsRequest`, the one handler for every app's
15
+ `POST /api/sync/events`; `sync-browser` provides the IndexedDB outbox and
16
+ offline-first client, whose live socket is either the app's own (default) or
17
+ the connection hub's (`hubUrl`, hub mode).
15
18
  `app-update` renders build-aware shells, matches their ETags, and fetches
16
19
  retained assets for consumer-owned routes;
17
20
  `app-update-browser` detects a new traffic build and reloads when the app's
package/dist/email.js CHANGED
@@ -28,6 +28,27 @@
28
28
  import { serializeError, truncate } from './log-core.js';
29
29
  export const RESEND_API_URL = 'https://api.resend.com/emails';
30
30
  export const DEFAULT_EMAIL_TIMEOUT_MS = 30_000;
31
+ /** The JSON body of Resend's `POST /emails`: optional fields are omitted
32
+ * rather than sent empty. */
33
+ function resendRequestBody(msg) {
34
+ return {
35
+ from: msg.from,
36
+ to: [msg.to],
37
+ subject: msg.subject,
38
+ ...(msg.text !== undefined ? { text: msg.text } : {}),
39
+ ...(msg.html !== undefined ? { html: msg.html } : {}),
40
+ ...(msg.headers && Object.keys(msg.headers).length ? { headers: msg.headers } : {}),
41
+ ...(msg.attachments?.length
42
+ ? {
43
+ attachments: msg.attachments.map((attachment) => ({
44
+ filename: attachment.filename,
45
+ content: attachment.content,
46
+ ...(attachment.contentType ? { content_type: attachment.contentType } : {}),
47
+ })),
48
+ }
49
+ : {}),
50
+ };
51
+ }
31
52
  /**
32
53
  * Send one email through Resend. Never throws: every failure is an ERROR
33
54
  * log (with enough of the message to redo the send by hand) and an
@@ -69,30 +90,14 @@ export async function sendEmail(msg, deps) {
69
90
  ...(deps.idempotencyKey !== undefined ? { 'Idempotency-Key': deps.idempotencyKey } : {}),
70
91
  },
71
92
  signal: AbortSignal.timeout(timeoutMs),
72
- body: JSON.stringify({
73
- from: msg.from,
74
- to: [msg.to],
75
- subject: msg.subject,
76
- ...(msg.text !== undefined ? { text: msg.text } : {}),
77
- ...(msg.html !== undefined ? { html: msg.html } : {}),
78
- ...(msg.headers && Object.keys(msg.headers).length ? { headers: msg.headers } : {}),
79
- ...(msg.attachments?.length
80
- ? {
81
- attachments: msg.attachments.map((attachment) => ({
82
- filename: attachment.filename,
83
- content: attachment.content,
84
- ...(attachment.contentType ? { content_type: attachment.contentType } : {}),
85
- })),
86
- }
87
- : {}),
88
- }),
93
+ body: JSON.stringify(resendRequestBody(msg)),
89
94
  });
90
95
  const elapsedMs = Date.now() - start;
91
96
  const body = await res.text().catch(() => '');
92
97
  if (!res.ok) {
93
- const error = `Resend API ${res.status}: ${truncate(body, 500)}`;
94
- logger.error('email_send_failed', { ...base, status: res.status, body: truncate(body, 500), elapsedMs, ...preview });
95
- return { ok: false, error };
98
+ const bodyPreview = truncate(body, 500);
99
+ logger.error('email_send_failed', { ...base, status: res.status, body: bodyPreview, elapsedMs, ...preview });
100
+ return { ok: false, error: `Resend API ${res.status}: ${bodyPreview}` };
96
101
  }
97
102
  let emailId;
98
103
  try {
@@ -1,6 +1,6 @@
1
1
  import { ScopeBroadcaster } from './broadcaster.js';
2
2
  import { EventLogEngine } from './engine.js';
3
- import { type ClientEvent, type EventBody, type HttpEventOutcome, type WsServerMessage } from './types.js';
3
+ import { type ClientEvent, type EventBody, type HttpEventOutcome, type HttpEventsResponse, type SyncEvent, type WsServerMessage } from './types.js';
4
4
  export interface SyncSocketSessionOptions<C extends EventBody, S extends EventBody> {
5
5
  scopeKey: string;
6
6
  engine: EventLogEngine<C, S>;
@@ -26,4 +26,38 @@ export declare class SyncSocketSession<C extends EventBody, S extends EventBody>
26
26
  private reject;
27
27
  private sendToSocket;
28
28
  }
29
+ /** The old-shape `POST /api/sync/events` loop: per-event outcomes, a
30
+ * duplicate reported as `applied`, nothing else. Kept for apps not yet on
31
+ * `handleSyncEventsRequest`; a `lastSeq` in the request is ignored. */
29
32
  export declare function applyHttpEventBatch<C extends EventBody, S extends EventBody>(engine: EventLogEngine<C, S>, scopeKey: string, request: unknown, parseClientEvent: (value: unknown) => ClientEvent<C>): Promise<HttpEventOutcome[]>;
33
+ /** What one request committed, for `afterCommit`: the events it appended,
34
+ * and the stored event of each retried event that had already committed. */
35
+ export interface SyncEventsCommitted<S extends EventBody> {
36
+ applied: SyncEvent<S>[];
37
+ duplicates: SyncEvent<S>[];
38
+ }
39
+ export interface SyncEventsRequestOptions<C extends EventBody, S extends EventBody> {
40
+ engine: EventLogEngine<C, S>;
41
+ /** Chosen by the app's authenticated, authorized route. */
42
+ scopeKey: string;
43
+ /** The request body as parsed JSON (untrusted). */
44
+ body: unknown;
45
+ parseClientEvent(value: unknown): ClientEvent<C>;
46
+ /** Runs once per request, after every event has been applied and before
47
+ * the catch-up is read, when at least one event was applied or was a
48
+ * duplicate: where the app publishes `applied` to its in-process
49
+ * broadcaster and notifies the hub (whose notify must fire on duplicates
50
+ * too, design §5.3). Awaited; it should not throw (a throw fails the
51
+ * request after the commit, and the client's retry is deduplicated). */
52
+ afterCommit?(committed: SyncEventsCommitted<S>): void | Promise<void>;
53
+ }
54
+ /** One handler for every app's `POST /api/sync/events` (connection hub
55
+ * design §5.5). Applies each event of `{clientGuid, events, lastSeq?}`
56
+ * through the engine in order. A request without `lastSeq` (sendBeacon, and
57
+ * clients before hub mode) gets the old shape, `{ outcomes }` with
58
+ * duplicates reported as `applied`. A request with it gets frame outcomes
59
+ * (`applied` + committed events, `duplicate` + the stored event, `rejected`
60
+ * + error) and a contiguous catch-up from `lastSeq`, read after the commits:
61
+ * `events` + `currentSeq`, or `reload: true` when too far behind. Throws
62
+ * `SyncError('bad_request')` for a malformed batch (answer 400). */
63
+ export declare function handleSyncEventsRequest<C extends EventBody, S extends EventBody>(options: SyncEventsRequestOptions<C, S>): Promise<HttpEventsResponse<S>>;
@@ -158,7 +158,37 @@ export class SyncSocketSession {
158
158
  }
159
159
  }
160
160
  }
161
+ /** The old-shape `POST /api/sync/events` loop: per-event outcomes, a
162
+ * duplicate reported as `applied`, nothing else. Kept for apps not yet on
163
+ * `handleSyncEventsRequest`; a `lastSeq` in the request is ignored. */
161
164
  export async function applyHttpEventBatch(engine, scopeKey, request, parseClientEvent) {
165
+ const batch = parseBatch(request, false);
166
+ const { outcomes } = await applyBatch(engine, scopeKey, batch, parseClientEvent);
167
+ return outcomes.map(oldShape);
168
+ }
169
+ /** One handler for every app's `POST /api/sync/events` (connection hub
170
+ * design §5.5). Applies each event of `{clientGuid, events, lastSeq?}`
171
+ * through the engine in order. A request without `lastSeq` (sendBeacon, and
172
+ * clients before hub mode) gets the old shape, `{ outcomes }` with
173
+ * duplicates reported as `applied`. A request with it gets frame outcomes
174
+ * (`applied` + committed events, `duplicate` + the stored event, `rejected`
175
+ * + error) and a contiguous catch-up from `lastSeq`, read after the commits:
176
+ * `events` + `currentSeq`, or `reload: true` when too far behind. Throws
177
+ * `SyncError('bad_request')` for a malformed batch (answer 400). */
178
+ export async function handleSyncEventsRequest(options) {
179
+ const batch = parseBatch(options.body, true);
180
+ const { outcomes, committed } = await applyBatch(options.engine, options.scopeKey, batch, options.parseClientEvent);
181
+ if (options.afterCommit && (committed.applied.length > 0 || committed.duplicates.length > 0)) {
182
+ await options.afterCommit(committed);
183
+ }
184
+ if (batch.lastSeq === undefined)
185
+ return { outcomes: outcomes.map(oldShape) };
186
+ const catchup = await options.engine.catchup(options.scopeKey, batch.lastSeq);
187
+ if (catchup.kind === 'reload')
188
+ return { outcomes, reload: true };
189
+ return { outcomes, events: catchup.events, currentSeq: catchup.currentSeq };
190
+ }
191
+ function parseBatch(request, withLastSeq) {
162
192
  const envelope = record(request);
163
193
  if (!envelope ||
164
194
  typeof envelope.clientGuid !== 'string' ||
@@ -166,8 +196,19 @@ export async function applyHttpEventBatch(engine, scopeKey, request, parseClient
166
196
  !Array.isArray(envelope.events)) {
167
197
  throw new SyncError('bad_request', 'invalid event batch');
168
198
  }
199
+ const batch = { clientGuid: envelope.clientGuid, events: envelope.events };
200
+ if (withLastSeq && envelope.lastSeq !== undefined) {
201
+ if (!Number.isSafeInteger(envelope.lastSeq) || envelope.lastSeq < 0) {
202
+ throw new SyncError('bad_request', 'invalid lastSeq');
203
+ }
204
+ batch.lastSeq = envelope.lastSeq;
205
+ }
206
+ return batch;
207
+ }
208
+ async function applyBatch(engine, scopeKey, batch, parseClientEvent) {
169
209
  const outcomes = [];
170
- for (const value of envelope.events) {
210
+ const committed = { applied: [], duplicates: [] };
211
+ for (const value of batch.events) {
171
212
  const guid = eventGuid(value);
172
213
  let event;
173
214
  try {
@@ -177,13 +218,24 @@ export async function applyHttpEventBatch(engine, scopeKey, request, parseClient
177
218
  outcomes.push({ eventGuid: guid, status: 'rejected', error: parserError(error) });
178
219
  continue;
179
220
  }
180
- const outcome = await engine.apply(scopeKey, envelope.clientGuid, event);
221
+ const outcome = await engine.apply(scopeKey, batch.clientGuid, event);
181
222
  if (outcome.kind === 'rejected') {
182
223
  outcomes.push({ eventGuid: event.eventGuid, status: 'rejected', error: outcome.error });
183
224
  }
225
+ else if (outcome.kind === 'duplicate') {
226
+ committed.duplicates.push(outcome.event);
227
+ outcomes.push({ eventGuid: event.eventGuid, status: 'duplicate', events: [outcome.event] });
228
+ }
184
229
  else {
185
- outcomes.push({ eventGuid: event.eventGuid, status: 'applied' });
230
+ committed.applied.push(...outcome.events);
231
+ outcomes.push({ eventGuid: event.eventGuid, status: 'applied', events: outcome.events });
186
232
  }
187
233
  }
188
- return outcomes;
234
+ return { outcomes, committed };
235
+ }
236
+ function oldShape(outcome) {
237
+ if (outcome.status === 'rejected') {
238
+ return { eventGuid: outcome.eventGuid, status: 'rejected', error: outcome.error };
239
+ }
240
+ return { eventGuid: outcome.eventGuid, status: 'applied' };
189
241
  }
@@ -68,7 +68,13 @@ export type WsServerMessage<T extends EventBody> = WsEventBroadcast<T> | WsCatch
68
68
  export interface HttpEventsRequest<T extends EventBody> {
69
69
  clientGuid: string;
70
70
  events: ClientEvent<T>[];
71
+ /** The tab's current sequence (hub-mode clients). A request that carries it
72
+ * is answered with outcome frames and a catch-up from it
73
+ * (`handleSyncEventsRequest`); one without it, the old shape. */
74
+ lastSeq?: number;
71
75
  }
76
+ /** One event's outcome in the old response shape: what clients that send no
77
+ * `lastSeq` get, and all they read (anything but `rejected` is applied). */
72
78
  export interface HttpEventOutcome {
73
79
  eventGuid: string;
74
80
  status: 'applied' | 'rejected';
@@ -77,3 +83,26 @@ export interface HttpEventOutcome {
77
83
  message: string;
78
84
  };
79
85
  }
86
+ /** One event's outcome with its frames (a request that carried `lastSeq`):
87
+ * `applied` with the committed events, `duplicate` with the stored event (a
88
+ * retry whose first attempt committed), `rejected` with the error. A superset
89
+ * of `HttpEventOutcome`: old readers see `duplicate` as applied. */
90
+ export interface HttpEventFrameOutcome<T extends EventBody> {
91
+ eventGuid: string;
92
+ status: 'applied' | 'duplicate' | 'rejected';
93
+ error?: {
94
+ code: string;
95
+ message: string;
96
+ };
97
+ events?: SyncEvent<T>[];
98
+ }
99
+ /** The response of `POST /api/sync/events`. Without `lastSeq` in the request
100
+ * it is `{ outcomes }` in the old shape; with it, frame outcomes plus either a
101
+ * contiguous catch-up from `lastSeq` (`events`, `currentSeq`) or `reload`
102
+ * when the tab is too far behind (connection hub design §5.5). */
103
+ export interface HttpEventsResponse<T extends EventBody> {
104
+ outcomes: Array<HttpEventOutcome | HttpEventFrameOutcome<T>>;
105
+ events?: SyncEvent<T>[];
106
+ currentSeq?: number;
107
+ reload?: boolean;
108
+ }
@@ -1,5 +1,5 @@
1
1
  import type { Logger as BrowserLogger } from '../log-browser.js';
2
- import type { ClientEvent, EventBody, HttpEventOutcome, SyncEvent } from '../sync/index.js';
2
+ import type { ClientEvent, EventBody, HttpEventsResponse, SyncEvent } from '../sync/index.js';
3
3
  import type { IndexedDbOutbox } from './outbox.js';
4
4
  export interface PendingEntry<C extends EventBody, Summary = unknown> {
5
5
  event: ClientEvent<C>;
@@ -110,14 +110,24 @@ export interface SyncClientOptions<B, C extends EventBody, S extends EventBody,
110
110
  * (default 5 min). */
111
111
  backgroundCatchupMs?: number;
112
112
  /** POSTs events to the app's batch endpoint (the beacon URL) and returns
113
- * the per-event outcomes. Lets a hidden, disconnected page deliver pending
114
- * edits and learn about rejections; without it the page beacons once. */
113
+ * its response. Lets a hidden, disconnected page deliver pending edits and
114
+ * learn about rejections; without it the page beacons once. Hub mode
115
+ * requires it: every mutation travels here, with `lastSeq`, and the
116
+ * response's frames and catch-up (`handleSyncEventsRequest`) settle it. */
115
117
  postEvents?(body: {
116
118
  clientGuid: string;
117
119
  events: ClientEvent<C>[];
118
- }, signal: AbortSignal): Promise<{
119
- outcomes: HttpEventOutcome[];
120
- }>;
120
+ lastSeq?: number;
121
+ }, signal: AbortSignal): Promise<HttpEventsResponse<S>>;
122
+ /** Hub mode (connection hub design §5.4–§5.5): the hub's base URL, e.g.
123
+ * `https://hub.apps.snewman.net`. The live socket goes to
124
+ * `wss://<hub>/api/ws?app=<app>` and carries hints only; mutations go over
125
+ * `postEvents` and catch-ups over `fetchCatchup`, against the app.
126
+ * Unset or empty: the same-origin socket (`socketUrl`), exactly as before.
127
+ * Requires `app` and `postEvents`. */
128
+ hubUrl?: string;
129
+ /** This app's name on the hub socket (hub mode). */
130
+ app?: string;
121
131
  }
122
132
  export declare class SyncClient<B, C extends EventBody, S extends EventBody, Summary = unknown> {
123
133
  private readonly options;
@@ -187,6 +197,29 @@ export declare class SyncClient<B, C extends EventBody, S extends EventBody, Sum
187
197
  private stallCoveredUntil;
188
198
  private visibleSinceMono;
189
199
  private readonly counters;
200
+ private readonly hub;
201
+ /** The live hub socket answered our `connect`. */
202
+ private hubAcked;
203
+ private hubLastHeardAt;
204
+ private hubAwaitingPong;
205
+ /** The last app request (POST or catch-up) succeeded; the bootstrap counts. */
206
+ private appOk;
207
+ /** The app-request ladder's step, reset by any app success and on return. */
208
+ private appAttempts;
209
+ /** Visible app-request failures in this outage and spell, for its logs. */
210
+ private appFailuresInOutage;
211
+ private appRetryTimer;
212
+ private appRetryAt;
213
+ /** When the hub socket's ladder retries (its countdown, for the state). */
214
+ private hubRetryAt;
215
+ private floorTimer;
216
+ private hintWindowTimer;
217
+ private hintTrailing;
218
+ /** One catch-up may wait behind the one in flight. */
219
+ private catchupQueued;
220
+ private postInFlight;
221
+ /** An edit was submitted while a POST was in flight: post again after it. */
222
+ private postAgain;
190
223
  constructor(options: SyncClientOptions<B, C, S, Summary>);
191
224
  init(): Promise<void>;
192
225
  private initialize;
@@ -266,12 +299,16 @@ export declare class SyncClient<B, C extends EventBody, S extends EventBody, Sum
266
299
  /** Hidden and disconnected: no WebSocket retries; HTTP catch-ups on a slow
267
300
  * cadence instead (docs/SYNC-BACKGROUND-PLAN.md). */
268
301
  private enterDormant;
302
+ private armBackgroundTick;
269
303
  private cancelBackgroundTick;
270
304
  private backgroundTick;
271
305
  private unsettledPending;
272
306
  private postPendingOverHttp;
273
- /** The background/return catch-up (review S5): one slot, a return aborts
274
- * a background fetch in flight, both give up after 15 s. */
307
+ /** The HTTP catch-up (review S5): one slot, a return aborts any other
308
+ * kind in flight, every kind gives up after 15 s. Hub mode: a request that
309
+ * finds the slot busy queues one more catch-up to start when it frees (one
310
+ * in flight, at most one queued), and the outcome feeds the app-request
311
+ * ladder. */
275
312
  private runCatchup;
276
313
  private withTimeout;
277
314
  private openReturnWindow;
@@ -296,6 +333,7 @@ export declare class SyncClient<B, C extends EventBody, S extends EventBody, Sum
296
333
  /** ERROR only after OUTAGE_ESCALATE_MS of visible, on-time outage; re-armed
297
334
  * on each return so an outage that began hidden still escalates (S3). */
298
335
  private armEscalation;
336
+ private dispatchMessage;
299
337
  private handleMessage;
300
338
  private handleSocketCatchup;
301
339
  /** Returns false when a forward gap prevented application. */
@@ -330,6 +368,7 @@ export declare class SyncClient<B, C extends EventBody, S extends EventBody, Sum
330
368
  private cancelResyncFailureRetry;
331
369
  private sendConnect;
332
370
  private connectMessage;
371
+ private socketUrl;
333
372
  private sendRaw;
334
373
  private trySend;
335
374
  private flushViaBeacon;
@@ -341,6 +380,58 @@ export declare class SyncClient<B, C extends EventBody, S extends EventBody, Sum
341
380
  private halt;
342
381
  private clearConnectionTimers;
343
382
  private clearAllTimers;
383
+ /** Live: the socket is open and, in hub mode, the hub answered our
384
+ * `connect` and the last app request succeeded (a pong overdue replaces
385
+ * the socket, so an open one has been heard from recently). */
386
+ private isLive;
387
+ private isQuietHubClose;
388
+ /** Hub mode's state: live as `connected`/`syncing`; otherwise a countdown
389
+ * to whichever ladder (hub socket or app request) retries first; otherwise
390
+ * `connecting`, or `disconnected` once something has failed. */
391
+ private refreshHubState;
392
+ private handleHubMessage;
393
+ /** The hub routes hints to this socket from now on. Established still
394
+ * needs a catch-up that began after this (design §5.4); one queues behind
395
+ * a catch-up already in flight. */
396
+ private onHubAck;
397
+ /** Two missed pongs replace the socket like a rollover (no outage); hints
398
+ * sent to it meanwhile are lost, and the new socket's ack catches up. */
399
+ private hubPingTick;
400
+ /** `sync_available`: leading-edge debounce. The first hint catches up at
401
+ * once; hints in the next 500 ms fold into one trailing catch-up. */
402
+ private onSyncHint;
403
+ private openHintWindow;
404
+ /** While visible, a catch-up at least every 2 minutes whatever the hub
405
+ * socket's state; any successful app request restarts the wait. */
406
+ private armFloor;
407
+ private cancelFloor;
408
+ private appSucceeded;
409
+ /** A POST or catch-up got no usable answer: the outage starts (if it had
410
+ * not), and a visible page retries on the app-request ladder whatever the
411
+ * hub socket's state. An expired session halts instead. */
412
+ private appFailed;
413
+ /** The 1-2-4-8-16-30 s ladder (a return's first failure: 250 ms); a retry
414
+ * already scheduled stands. */
415
+ private scheduleAppRetry;
416
+ private cancelAppRetry;
417
+ /** A POST when edits are unsettled (its response carries the catch-up),
418
+ * else a catch-up. */
419
+ private retryAppRequest;
420
+ /** Re-send paths (established, resync, return): post the unsettled edits
421
+ * unless a POST is already in flight. */
422
+ private kickPost;
423
+ /** Hub mode's mutation path: every unsettled edit in one POST, one POST in
424
+ * flight per tab. An edit submitted meanwhile posts after it succeeds; a
425
+ * failure leaves the retry to the app-request ladder. */
426
+ private runPost;
427
+ private postOnce;
428
+ /** The catch-up slice first: contiguous from the request's `lastSeq`, it
429
+ * carries the own events in order with any writer that interleaved, so no
430
+ * forward gap trips a resync. Then the outcomes: frames confirm their
431
+ * pending entry by GUID even at or below the tab's sequence (a resync may
432
+ * have moved it past them, review round 2 B1); rejections settle as on
433
+ * the socket. */
434
+ private applyPostResponse;
344
435
  private detachSocket;
345
436
  private abortable;
346
437
  private abortFetches;