nowity 1.8.0 → 1.9.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.
@@ -6,6 +6,7 @@ const mobx_1 = require("mobx");
6
6
  const derived_1 = require("../core/derived");
7
7
  const protocol_1 = require("../core/protocol");
8
8
  const confirmed_store_1 = require("./confirmed-store");
9
+ const devtools_1 = require("./devtools");
9
10
  const live_query_1 = require("./live-query");
10
11
  const overlay_1 = require("./overlay");
11
12
  /** Thrown in strict mode by a mutation the client has no answer for. */
@@ -114,6 +115,8 @@ class NowityClient {
114
115
  this.everWelcomed = false;
115
116
  /** What this connection says it is looking at; resent after every reconnect. */
116
117
  this.context = null;
118
+ /** See {@link enableDevtools}. `null` = nothing is measured. */
119
+ this.recorder = null;
117
120
  /** Rebuild the overlay from confirmed state plus pending mutations. */
118
121
  this.rebase = (0, mobx_1.action)(() => {
119
122
  this.pendingBox.set(this.pending.length > 0);
@@ -165,6 +168,30 @@ class NowityClient {
165
168
  }
166
169
  this.mutators.set(mutator.name, mutator);
167
170
  }
171
+ if (opts.devtools)
172
+ this.enableDevtools(opts.devtools === true ? {} : opts.devtools);
173
+ }
174
+ // -------------------------------------------------------------------- devtools
175
+ /**
176
+ * Start recording subscribes, mutations and connection events for a
177
+ * developer panel (`nowity/devtools`). Idempotent: a second call returns the
178
+ * recorder already running, whatever its options.
179
+ *
180
+ * Turned on before the client connects (the `devtools` option), it sees the
181
+ * page's startup; turned on later, it sees what happens from then on —
182
+ * subscriptions already open are not in it.
183
+ */
184
+ enableDevtools(options = {}) {
185
+ this.recorder ?? (this.recorder = new devtools_1.NowityDevtools(options));
186
+ return this.recorder;
187
+ }
188
+ /** Stop recording and drop what was recorded. */
189
+ disableDevtools() {
190
+ this.recorder = null;
191
+ }
192
+ /** The running recorder, or `null` when devtools are off. */
193
+ get devtools() {
194
+ return this.recorder;
168
195
  }
169
196
  // ------------------------------------------------------------------ connection
170
197
  connect() {
@@ -176,11 +203,15 @@ class NowityClient {
176
203
  return;
177
204
  this.intentionalClose = false;
178
205
  (0, mobx_1.runInAction)(() => this.status.set("connecting"));
206
+ this.recorder?.onConnect();
179
207
  this.opts.transport.connect({
180
208
  onOpen: () => this.handleOpen(),
181
- onMessage: (message) => this.handleMessage(message),
209
+ onMessage: (message, raw) => this.handleMessage(message, raw),
182
210
  onClose: () => this.handleClose(),
183
- onError: (err) => this.onError(err),
211
+ onError: (err) => {
212
+ this.recorder?.onTransportError(err.message);
213
+ this.onError(err);
214
+ },
184
215
  });
185
216
  }
186
217
  close() {
@@ -199,6 +230,7 @@ class NowityClient {
199
230
  handleOpen() {
200
231
  this.connected = true;
201
232
  this.reconnectAttempt = 0;
233
+ this.recorder?.onOpen();
202
234
  (0, mobx_1.runInAction)(() => this.status.set("connected"));
203
235
  // The context rides on the hello: the server forgets it with the old
204
236
  // socket, and a new socket has to be told before it is recorded.
@@ -228,6 +260,7 @@ class NowityClient {
228
260
  this.send({ t: "context", context });
229
261
  }
230
262
  handleClose() {
263
+ this.recorder?.onClose(this.intentionalClose);
231
264
  this.connected = false;
232
265
  this.welcomed = false;
233
266
  (0, mobx_1.runInAction)(() => this.status.set(this.intentionalClose ? "idle" : "disconnected"));
@@ -248,6 +281,7 @@ class NowityClient {
248
281
  const max = this.opts.reconnect?.maxDelayMs ?? 5000;
249
282
  const delay = Math.min(max, min * 2 ** this.reconnectAttempt);
250
283
  this.reconnectAttempt += 1;
284
+ this.recorder?.onReconnectScheduled(delay);
251
285
  this.reconnectTimer = setTimeout(() => {
252
286
  this.reconnectTimer = null;
253
287
  this.connect();
@@ -255,6 +289,8 @@ class NowityClient {
255
289
  }
256
290
  send(message) {
257
291
  this.opts.transport.send(message);
292
+ if (this.recorder && message.t === "hello")
293
+ this.recorder.onHello((0, devtools_1.jsonBytes)(message));
258
294
  }
259
295
  /**
260
296
  * Forget every unconfirmed mutation: the connection they were bound to is
@@ -264,6 +300,8 @@ class NowityClient {
264
300
  dropPending() {
265
301
  const callers = [...this.callers];
266
302
  this.callers.clear();
303
+ for (const [mutationId] of callers)
304
+ this.recorder?.onMutationLost(mutationId);
267
305
  (0, mobx_1.runInAction)(() => {
268
306
  this.pending = [];
269
307
  this.rebase();
@@ -313,6 +351,7 @@ class NowityClient {
313
351
  });
314
352
  const hydrationKey = subscriptionKey(query, args);
315
353
  const payload = this.hydrationByKey.get(hydrationKey);
354
+ this.recorder?.onSubscribe(subId, query, args, payload !== undefined);
316
355
  if (payload) {
317
356
  // Server-rendered data is used once. Keeping it would resurrect stale
318
357
  // rows on a later subscription to the same query.
@@ -336,6 +375,7 @@ class NowityClient {
336
375
  return;
337
376
  this.subs.delete(subId);
338
377
  this.derivedBySub.delete(subId);
378
+ this.recorder?.onUnsubscribe(subId);
339
379
  this.send({ t: "unsubscribe", subId });
340
380
  this.resolveResync(subId);
341
381
  (0, mobx_1.runInAction)(() => {
@@ -393,8 +433,12 @@ class NowityClient {
393
433
  caller.promise = promise;
394
434
  this.callers.set(mutationId, caller);
395
435
  this.pending.push({ mutationId, name, args });
436
+ const recorder = this.recorder;
437
+ const startedAt = recorder ? now() : 0;
396
438
  (0, mobx_1.runInAction)(() => this.rebase());
397
- this.send({ t: "mutate", mutationId, name, args });
439
+ const message = { t: "mutate", mutationId, name, args };
440
+ recorder?.onMutate(mutationId, name, args, (0, devtools_1.jsonBytes)(message), now() - startedAt);
441
+ this.send(message);
398
442
  return promise;
399
443
  }
400
444
  /** See {@link NowityClientOptions.optimistic}. Takes effect immediately. */
@@ -419,9 +463,11 @@ class NowityClient {
419
463
  return [...(this.derivedBySub.get(subId)?.values() ?? [])];
420
464
  }
421
465
  // -------------------------------------------------------------------- messages
422
- handleMessage(message) {
466
+ handleMessage(message, raw) {
423
467
  try {
424
468
  this.opts.onServerMessage?.(message);
469
+ if (this.recorder)
470
+ this.record(this.recorder, message, raw);
425
471
  switch (message.t) {
426
472
  case "welcome":
427
473
  this.handleWelcome(message);
@@ -463,6 +509,41 @@ class NowityClient {
463
509
  this.onError(err);
464
510
  }
465
511
  }
512
+ /**
513
+ * Note a message for the devtools recorder, before it is applied.
514
+ *
515
+ * Sizes come from the raw frame when the transport has it; a transaction
516
+ * spread over several subscriptions is measured per subscription, by its
517
+ * own part of the message.
518
+ */
519
+ record(recorder, message, raw) {
520
+ const size = () => (raw !== undefined ? (0, devtools_1.byteSize)(raw) : (0, devtools_1.jsonBytes)(message));
521
+ switch (message.t) {
522
+ case "welcome":
523
+ recorder.onWelcome(size());
524
+ break;
525
+ case "snapshot":
526
+ recorder.onSnapshot(message.subId, size(), message.reason === "permission-change");
527
+ break;
528
+ case "tx":
529
+ for (const revoked of message.revoked ?? []) {
530
+ recorder.onSubscriptionRefused(revoked.subId, "rejected", revoked.reason);
531
+ }
532
+ for (const snapshot of message.snapshots ?? []) {
533
+ recorder.onSnapshot(snapshot.subId, (0, devtools_1.jsonBytes)(snapshot), snapshot.reason === "permission-change");
534
+ }
535
+ for (const patch of message.patches)
536
+ recorder.onPatch(patch.subId, (0, devtools_1.jsonBytes)(patch));
537
+ break;
538
+ case "mutation-result":
539
+ recorder.onMutationResult(message.mutationId, message.ok, message.error);
540
+ break;
541
+ case "error":
542
+ if (message.subId)
543
+ recorder.onSubscriptionRefused(message.subId, "error", message.code);
544
+ break;
545
+ }
546
+ }
466
547
  handleWelcome(message) {
467
548
  const serverLastMutationId = message.lastMutationId;
468
549
  this.welcomed = true;
@@ -496,6 +577,7 @@ class NowityClient {
496
577
  if (queued.has(mutationId))
497
578
  continue;
498
579
  this.callers.delete(mutationId);
580
+ this.recorder?.onMutationSettled(mutationId);
499
581
  caller.resolve(undefined);
500
582
  }
501
583
  // Re-send everything the server has not seen, then re-establish the
@@ -503,6 +585,7 @@ class NowityClient {
503
585
  // contain these mutations; whichever way, the reported lastMutationId says
504
586
  // which of them may leave the pending queue.
505
587
  for (const mutation of this.pending) {
588
+ this.recorder?.onMutationResent(mutation.mutationId);
506
589
  this.send({
507
590
  t: "mutate",
508
591
  mutationId: mutation.mutationId,
@@ -515,6 +598,7 @@ class NowityClient {
515
598
  // already sent (queued by the transport if the socket was not open yet),
516
599
  // and re-sending them would cost a second snapshot of everything.
517
600
  for (const sub of this.subs.values()) {
601
+ this.recorder?.onResubscribe(sub.subId);
518
602
  this.send({ t: "subscribe", subId: sub.subId, query: sub.query, args: sub.args });
519
603
  }
520
604
  }
@@ -840,7 +924,7 @@ class NowityClient {
840
924
  }
841
925
  /** Test seam: feed a server message in as if it arrived over the wire. */
842
926
  injectMessage(message) {
843
- this.handleMessage(message);
927
+ this.handleMessage(message, undefined);
844
928
  }
845
929
  }
846
930
  exports.NowityClient = NowityClient;
@@ -868,3 +952,7 @@ function strictFromEnv() {
868
952
  const env = globalThis.process?.env;
869
953
  return env?.NOWITY_STRICT_OPTIMISTIC === "1";
870
954
  }
955
+ function now() {
956
+ const perf = globalThis.performance;
957
+ return perf ? perf.now() : Date.now();
958
+ }
@@ -1,7 +1,8 @@
1
1
  import type { ClientMessage, ServerMessage } from "../core/protocol";
2
2
  export interface TransportHandlers {
3
3
  onOpen(): void;
4
- onMessage(message: ServerMessage): void;
4
+ /** `raw` = the frame as received, when the transport has it (for sizes in devtools). */
5
+ onMessage(message: ServerMessage, raw?: string): void;
5
6
  onClose(): void;
6
7
  onError(error: Error): void;
7
8
  }
@@ -1 +1 @@
1
- {"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../src/client/transport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAErE,MAAM,WAAW,iBAAiB;IAC9B,MAAM,IAAI,IAAI,CAAC;IACf,SAAS,CAAC,OAAO,EAAE,aAAa,GAAG,IAAI,CAAC;IACxC,OAAO,IAAI,IAAI,CAAC;IAChB,OAAO,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;CAC/B;AAED;;;;;GAKG;AACH,MAAM,WAAW,SAAS;IACtB,OAAO,CAAC,QAAQ,EAAE,iBAAiB,GAAG,IAAI,CAAC;IAC3C,IAAI,CAAC,OAAO,EAAE,aAAa,GAAG,IAAI,CAAC;IACnC,KAAK,IAAI,IAAI,CAAC;CACjB"}
1
+ {"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../src/client/transport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAErE,MAAM,WAAW,iBAAiB;IAC9B,MAAM,IAAI,IAAI,CAAC;IACf,wFAAwF;IACxF,SAAS,CAAC,OAAO,EAAE,aAAa,EAAE,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtD,OAAO,IAAI,IAAI,CAAC;IAChB,OAAO,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAAC;CAC/B;AAED;;;;;GAKG;AACH,MAAM,WAAW,SAAS;IACtB,OAAO,CAAC,QAAQ,EAAE,iBAAiB,GAAG,IAAI,CAAC;IAC3C,IAAI,CAAC,OAAO,EAAE,aAAa,GAAG,IAAI,CAAC;IACnC,KAAK,IAAI,IAAI,CAAC;CACjB"}
@@ -1 +1 @@
1
- {"version":3,"file":"ws-transport.d.ts","sourceRoot":"","sources":["../../src/client/ws-transport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAiB,MAAM,kBAAkB,CAAC;AACrE,OAAO,KAAK,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAUhE,MAAM,WAAW,yBAAyB;IACtC,GAAG,EAAE,MAAM,CAAC;IACZ;;;OAGG;IACH,aAAa,CAAC,EAAE,GAAG,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;CACjC;AAED;;;;;;;GAOG;AACH,qBAAa,kBAAmB,YAAW,SAAS;IAKpC,OAAO,CAAC,QAAQ,CAAC,IAAI;IAJjC,OAAO,CAAC,MAAM,CAA2B;IACzC,OAAO,CAAC,QAAQ,CAAkC;IAClD,OAAO,CAAC,KAAK,CAAuB;gBAEP,IAAI,EAAE,yBAAyB;IAE5D,OAAO,CAAC,QAAQ,EAAE,iBAAiB,GAAG,IAAI;IAmD1C,IAAI,CAAC,OAAO,EAAE,aAAa,GAAG,IAAI;IAUlC,KAAK,IAAI,IAAI;CAShB"}
1
+ {"version":3,"file":"ws-transport.d.ts","sourceRoot":"","sources":["../../src/client/ws-transport.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAiB,MAAM,kBAAkB,CAAC;AACrE,OAAO,KAAK,EAAE,SAAS,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAUhE,MAAM,WAAW,yBAAyB;IACtC,GAAG,EAAE,MAAM,CAAC;IACZ;;;OAGG;IACH,aAAa,CAAC,EAAE,GAAG,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;CACjC;AAED;;;;;;;GAOG;AACH,qBAAa,kBAAmB,YAAW,SAAS;IAKpC,OAAO,CAAC,QAAQ,CAAC,IAAI;IAJjC,OAAO,CAAC,MAAM,CAA2B;IACzC,OAAO,CAAC,QAAQ,CAAkC;IAClD,OAAO,CAAC,KAAK,CAAuB;gBAEP,IAAI,EAAE,yBAAyB;IAE5D,OAAO,CAAC,QAAQ,EAAE,iBAAiB,GAAG,IAAI;IAoD1C,IAAI,CAAC,OAAO,EAAE,aAAa,GAAG,IAAI;IAUlC,KAAK,IAAI,IAAI;CAShB"}
@@ -49,7 +49,8 @@ class WebSocketTransport {
49
49
  return;
50
50
  const raw = typeof payload === "string" ? payload : (payload?.data ?? payload);
51
51
  try {
52
- handlers.onMessage(JSON.parse(String(raw)));
52
+ const text = String(raw);
53
+ handlers.onMessage(JSON.parse(text), text);
53
54
  }
54
55
  catch (err) {
55
56
  handlers.onError(err);
package/dist/client.d.ts CHANGED
@@ -40,6 +40,11 @@ export type { QueryEntry, QueryError, QuerySource } from "./client/query-source"
40
40
  export { ConnectionLostError, StrictOptimisticError, type ClientMutatorDef, type OptimisticMutatorDef, type PessimisticMutatorDef, } from "./client/nowity-client";
41
41
  export type { Draft, EntityTx, LocalEntities, LocalTx } from "./client/overlay";
42
42
  export { WebSocketTransport, type WebSocketTransportOptions } from "./client/ws-transport";
43
+ /**
44
+ * The recorder behind `client.enableDevtools()`; the panel that shows it is a
45
+ * separate entry, `nowity/devtools`, loaded only where it is wanted.
46
+ */
47
+ export type { NowityDevtools, DevtoolsOptions, DevtoolsRecord, DevtoolsSummary } from "./client/devtools";
43
48
  export { configureNowityClient, type NowityClientContainerConfig } from "./ironbean/client";
44
49
  export { NowityClientToken } from "./ironbean/tokens";
45
50
  export type { EntityId, Row } from "./core/types";
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAGH,OAAO,EACH,GAAG,EACH,QAAQ,EACR,KAAK,EACL,IAAI,EACJ,QAAQ,EACR,cAAc,EACd,UAAU,EACV,gBAAgB,EAChB,cAAc,EACd,YAAY,EACZ,SAAS,EACT,UAAU,EACV,aAAa,EACb,KAAK,WAAW,EAChB,KAAK,YAAY,EACjB,KAAK,YAAY,EACjB,KAAK,YAAY,EACjB,KAAK,WAAW,EAChB,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,KAAK,YAAY,GACpB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAQ5E,OAAO,EACH,QAAQ,EACR,gBAAgB,EAChB,OAAO,EACP,QAAQ,EACR,IAAI,EACJ,QAAQ,EACR,iBAAiB,EACjB,UAAU,EACV,cAAc,EACd,WAAW,EACX,cAAc;AACd;;;;;GAKG;AACH,UAAU,EACV,KAAK,WAAW,EAChB,KAAK,SAAS,EACd,KAAK,MAAM,EACX,KAAK,cAAc,EACnB,KA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EAAE,MAAM,mBAAmB,CAAC;AAGtD,YAAY,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,cAAc,CAAC;AAClD,YAAY,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACxD,YAAY,EAAE,cAAc,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC"}
@@ -0,0 +1,25 @@
1
+ import type { DevtoolsRecord, DevtoolsRecordType, NowityDevtools } from "./client/devtools";
2
+ export { NowityDevtools, maskArgs, byteSize, MASKED, DEFAULT_ALLOWED_KEYS, type DevtoolsMeta, type DevtoolsOptions, type DevtoolsRecord, type DevtoolsRecordType, type DevtoolsStatus, type DevtoolsSummary, type DevtoolsUpdate, type DevtoolsUpdateCause, } from "./client/devtools";
3
+ export interface NowityDevtoolsPanelProps {
4
+ /** The client's recorder: `connection.client.devtools`. */
5
+ recorder: NowityDevtools;
6
+ /** Shows a close button when given. */
7
+ onClose?: () => void;
8
+ /** Fixed to the bottom of the viewport instead of inline. */
9
+ floating?: boolean;
10
+ /** Height of the floating panel (CSS). Default `40vh`. */
11
+ height?: string;
12
+ title?: string;
13
+ }
14
+ type Filter = "all" | DevtoolsRecordType;
15
+ type SortKey = "start" | "name" | "status" | "latency" | "size" | "updates";
16
+ export declare function formatMs(ms: number | null | undefined): string;
17
+ export declare function formatBytes(bytes: number | null | undefined): string;
18
+ /** Rows for the table: filtered, searched and sorted. Pure, for tests. */
19
+ export declare function visibleRecords(records: readonly DevtoolsRecord[], filter: Filter, search: string, sort: SortKey, desc: boolean): DevtoolsRecord[];
20
+ /**
21
+ * The panel: page-startup summary, a table of every subscribe / mutation / socket
22
+ * event with a waterfall, filter, search, sort, details, copy as JSON and clear.
23
+ */
24
+ export declare function NowityDevtoolsPanel({ recorder, onClose, floating, height, title }: NowityDevtoolsPanelProps): import("react").JSX.Element;
25
+ //# sourceMappingURL=devtools.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"devtools.d.ts","sourceRoot":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QAAQ,EAAE,MAAe,EAAE,KAAgB,EAAE,EAAE,wBAAwB,+BA+L/H"}
@@ -0,0 +1,228 @@
1
+ "use strict";
2
+ "use client";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.DEFAULT_ALLOWED_KEYS = exports.MASKED = exports.byteSize = exports.maskArgs = exports.NowityDevtools = void 0;
5
+ exports.formatMs = formatMs;
6
+ exports.formatBytes = formatBytes;
7
+ exports.visibleRecords = visibleRecords;
8
+ exports.NowityDevtoolsPanel = NowityDevtoolsPanel;
9
+ const jsx_runtime_1 = require("react/jsx-runtime");
10
+ /**
11
+ * `nowity/devtools` — a Network tab for the socket.
12
+ *
13
+ * A separate entry on purpose: the panel is for developers, so an application
14
+ * loads it with a dynamic `import("nowity/devtools")` behind its own access check
15
+ * and the code never reaches anyone else's bundle. Neither `nowity` nor
16
+ * `nowity/client` imports this module.
17
+ *
18
+ * The panel only reads a recorder ({@link NowityDevtools}) the client was asked
19
+ * to keep — `client.enableDevtools()` or the `devtools` option. Everything it
20
+ * shows is in the browser's memory already, masked; it sends nothing anywhere.
21
+ */
22
+ const react_1 = require("react");
23
+ var devtools_1 = require("./client/devtools");
24
+ Object.defineProperty(exports, "NowityDevtools", { enumerable: true, get: function () { return devtools_1.NowityDevtools; } });
25
+ Object.defineProperty(exports, "maskArgs", { enumerable: true, get: function () { return devtools_1.maskArgs; } });
26
+ Object.defineProperty(exports, "byteSize", { enumerable: true, get: function () { return devtools_1.byteSize; } });
27
+ Object.defineProperty(exports, "MASKED", { enumerable: true, get: function () { return devtools_1.MASKED; } });
28
+ Object.defineProperty(exports, "DEFAULT_ALLOWED_KEYS", { enumerable: true, get: function () { return devtools_1.DEFAULT_ALLOWED_KEYS; } });
29
+ const COLORS = {
30
+ subscribe: "#4f9cf9",
31
+ mutation: "#f5a524",
32
+ ws: "#9b8afb",
33
+ };
34
+ const STATUS_COLORS = {
35
+ pending: "#a1a1aa",
36
+ rejected: "#f87171",
37
+ error: "#f87171",
38
+ lost: "#f87171",
39
+ closed: "#71717a",
40
+ };
41
+ function formatMs(ms) {
42
+ if (ms === null || ms === undefined)
43
+ return "—";
44
+ if (ms >= 10000)
45
+ return `${(ms / 1000).toFixed(1)} s`;
46
+ if (ms >= 1000)
47
+ return `${(ms / 1000).toFixed(2)} s`;
48
+ return `${ms.toFixed(ms < 10 ? 1 : 0)} ms`;
49
+ }
50
+ function formatBytes(bytes) {
51
+ if (bytes === null || bytes === undefined)
52
+ return "—";
53
+ if (bytes >= 1024 * 1024)
54
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
55
+ if (bytes >= 1024)
56
+ return `${(bytes / 1024).toFixed(1)} kB`;
57
+ return `${bytes} B`;
58
+ }
59
+ /** Rows for the table: filtered, searched and sorted. Pure, for tests. */
60
+ function visibleRecords(records, filter, search, sort, desc) {
61
+ const needle = search.trim().toLowerCase();
62
+ const rows = records.filter((record) => (filter === "all" || record.type === filter) &&
63
+ (needle === "" || record.name.toLowerCase().includes(needle) || record.status.includes(needle)));
64
+ const key = (record) => {
65
+ switch (sort) {
66
+ case "name":
67
+ return record.name;
68
+ case "status":
69
+ return record.status;
70
+ case "latency":
71
+ return record.durationMs ?? Number.POSITIVE_INFINITY;
72
+ case "size":
73
+ return record.bytes ?? -1;
74
+ case "updates":
75
+ return record.meta.updateCount ?? 0;
76
+ default:
77
+ return record.ts;
78
+ }
79
+ };
80
+ rows.sort((a, b) => {
81
+ const ka = key(a);
82
+ const kb = key(b);
83
+ const order = ka < kb ? -1 : ka > kb ? 1 : a.id - b.id;
84
+ return desc ? -order : order;
85
+ });
86
+ return rows;
87
+ }
88
+ function useRecorder(recorder) {
89
+ const version = (0, react_1.useSyncExternalStore)((listener) => recorder.subscribe(listener), () => recorder.version, () => recorder.version);
90
+ return (0, react_1.useMemo)(() => ({ records: recorder.records, summary: recorder.summary() }), [recorder, version]);
91
+ }
92
+ const font = 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace';
93
+ const styles = {
94
+ root: {
95
+ fontFamily: font,
96
+ fontSize: 12,
97
+ color: "#e4e4e7",
98
+ background: "#18181b",
99
+ border: "1px solid #3f3f46",
100
+ display: "flex",
101
+ flexDirection: "column",
102
+ minHeight: 0,
103
+ boxSizing: "border-box",
104
+ },
105
+ floating: {
106
+ position: "fixed",
107
+ left: 0,
108
+ right: 0,
109
+ bottom: 0,
110
+ zIndex: 2147483000,
111
+ boxShadow: "0 -4px 16px rgba(0,0,0,.4)",
112
+ },
113
+ bar: {
114
+ display: "flex",
115
+ flexWrap: "wrap",
116
+ alignItems: "center",
117
+ gap: 6,
118
+ padding: "4px 8px",
119
+ borderBottom: "1px solid #3f3f46",
120
+ background: "#27272a",
121
+ },
122
+ button: {
123
+ font: "inherit",
124
+ color: "inherit",
125
+ background: "#3f3f46",
126
+ border: "1px solid #52525b",
127
+ borderRadius: 4,
128
+ padding: "2px 8px",
129
+ cursor: "pointer",
130
+ },
131
+ input: {
132
+ font: "inherit",
133
+ color: "inherit",
134
+ background: "#09090b",
135
+ border: "1px solid #52525b",
136
+ borderRadius: 4,
137
+ padding: "2px 6px",
138
+ minWidth: 120,
139
+ },
140
+ th: {
141
+ position: "sticky",
142
+ top: 0,
143
+ background: "#27272a",
144
+ textAlign: "left",
145
+ fontWeight: 600,
146
+ padding: "3px 6px",
147
+ borderBottom: "1px solid #3f3f46",
148
+ cursor: "pointer",
149
+ whiteSpace: "nowrap",
150
+ userSelect: "none",
151
+ },
152
+ td: {
153
+ padding: "2px 6px",
154
+ borderBottom: "1px solid #27272a",
155
+ whiteSpace: "nowrap",
156
+ overflow: "hidden",
157
+ textOverflow: "ellipsis",
158
+ maxWidth: 320,
159
+ },
160
+ };
161
+ function SummaryItem({ label, value, testId }) {
162
+ return ((0, jsx_runtime_1.jsxs)("span", { "data-testid": testId, style: { whiteSpace: "nowrap" }, children: [(0, jsx_runtime_1.jsx)("span", { style: { color: "#a1a1aa" }, children: label }), " ", value] }));
163
+ }
164
+ /**
165
+ * The panel: page-startup summary, a table of every subscribe / mutation / socket
166
+ * event with a waterfall, filter, search, sort, details, copy as JSON and clear.
167
+ */
168
+ function NowityDevtoolsPanel({ recorder, onClose, floating, height = "40vh", title = "Nowity" }) {
169
+ const { records, summary } = useRecorder(recorder);
170
+ const [filter, setFilter] = (0, react_1.useState)("all");
171
+ const [search, setSearch] = (0, react_1.useState)("");
172
+ const [sort, setSort] = (0, react_1.useState)("start");
173
+ const [desc, setDesc] = (0, react_1.useState)(false);
174
+ const [selected, setSelected] = (0, react_1.useState)(null);
175
+ const [copied, setCopied] = (0, react_1.useState)(false);
176
+ const rows = (0, react_1.useMemo)(() => visibleRecords(records, filter, search, sort, desc), [records, filter, search, sort, desc]);
177
+ const range = (0, react_1.useMemo)(() => {
178
+ let start = Number.POSITIVE_INFINITY;
179
+ let end = 0;
180
+ for (const record of rows) {
181
+ start = Math.min(start, record.ts);
182
+ end = Math.max(end, record.ts + (record.durationMs ?? 0));
183
+ }
184
+ return rows.length === 0 ? { start: 0, span: 1 } : { start, span: Math.max(1, end - start) };
185
+ }, [rows]);
186
+ const detail = selected === null ? undefined : records.find((record) => record.id === selected);
187
+ const sortBy = (key) => {
188
+ if (sort === key)
189
+ setDesc(!desc);
190
+ else {
191
+ setSort(key);
192
+ setDesc(false);
193
+ }
194
+ };
195
+ const header = (key, label, style) => ((0, jsx_runtime_1.jsxs)("th", { style: { ...styles.th, ...style }, onClick: () => sortBy(key), "data-testid": `nowity-devtools-sort-${key}`, children: [label, sort === key ? (desc ? " ▼" : " ▲") : ""] }));
196
+ const copy = () => {
197
+ const json = recorder.export();
198
+ const clipboard = globalThis.navigator?.clipboard;
199
+ void clipboard?.writeText(json).then(() => setCopied(true), () => setCopied(false));
200
+ };
201
+ return ((0, jsx_runtime_1.jsxs)("section", { "data-testid": "nowity-devtools", "aria-label": title, style: { ...styles.root, ...(floating ? { ...styles.floating, height } : { height: "100%" }) }, children: [(0, jsx_runtime_1.jsxs)("div", { style: styles.bar, children: [(0, jsx_runtime_1.jsx)("strong", { children: title }), ["all", "subscribe", "mutation", "ws"].map((value) => ((0, jsx_runtime_1.jsx)("button", { type: "button", "data-testid": `nowity-devtools-filter-${value}`, "aria-pressed": filter === value, style: { ...styles.button, ...(filter === value ? { background: "#52525b" } : {}) }, onClick: () => setFilter(value), children: value }, value))), (0, jsx_runtime_1.jsx)("input", { type: "search", placeholder: "filter", "aria-label": "filter", "data-testid": "nowity-devtools-search", style: styles.input, value: search, onChange: (event) => setSearch(event.target.value) }), (0, jsx_runtime_1.jsx)("span", { style: { flex: 1 } }), (0, jsx_runtime_1.jsx)("button", { type: "button", style: styles.button, "data-testid": "nowity-devtools-copy", onClick: copy, children: copied ? "copied" : "copy JSON" }), (0, jsx_runtime_1.jsx)("button", { type: "button", style: styles.button, "data-testid": "nowity-devtools-clear", onClick: () => {
202
+ recorder.clear();
203
+ setSelected(null);
204
+ }, children: "clear" }), onClose && ((0, jsx_runtime_1.jsx)("button", { type: "button", style: styles.button, "data-testid": "nowity-devtools-close", "aria-label": "close", onClick: onClose, children: "\u00D7" }))] }), (0, jsx_runtime_1.jsxs)("div", { style: { ...styles.bar, background: "#1f1f23", gap: 14 }, "data-testid": "nowity-devtools-summary", children: [(0, jsx_runtime_1.jsx)(SummaryItem, { testId: "nowity-devtools-summary-open", label: "ws open", value: formatMs(summary.openAt) }), (0, jsx_runtime_1.jsx)(SummaryItem, { testId: "nowity-devtools-summary-welcome", label: "welcome", value: formatMs(summary.welcomeAt) }), (0, jsx_runtime_1.jsx)(SummaryItem, { testId: "nowity-devtools-summary-subscribe", label: "1st subscribe", value: formatMs(summary.firstSubscribeAt) }), (0, jsx_runtime_1.jsx)(SummaryItem, { testId: "nowity-devtools-summary-data", label: "1st data", value: formatMs(summary.firstDataAt) }), (0, jsx_runtime_1.jsx)(SummaryItem, { testId: "nowity-devtools-summary-connections", label: "sockets", value: summary.connections }), (0, jsx_runtime_1.jsx)(SummaryItem, { label: "reconnects", testId: "nowity-devtools-summary-reconnects", value: summary.reconnects }), (0, jsx_runtime_1.jsx)(SummaryItem, { label: "live", testId: "nowity-devtools-summary-live", value: `${summary.openSubscriptions} (${summary.pendingSubscriptions} pending)` }), (0, jsx_runtime_1.jsx)(SummaryItem, { label: "mutations pending", testId: "nowity-devtools-summary-mutations", value: summary.pendingMutations })] }), (0, jsx_runtime_1.jsxs)("div", { style: { display: "flex", flex: 1, minHeight: 0 }, children: [(0, jsx_runtime_1.jsxs)("div", { style: { flex: 1, overflow: "auto", minWidth: 0 }, children: [(0, jsx_runtime_1.jsxs)("table", { style: { borderCollapse: "collapse", width: "100%", tableLayout: "auto" }, children: [(0, jsx_runtime_1.jsx)("thead", { children: (0, jsx_runtime_1.jsxs)("tr", { children: [header("name", "name"), header("status", "status"), header("start", "start"), header("latency", "latency"), header("size", "size"), header("updates", "updates"), (0, jsx_runtime_1.jsx)("th", { style: { ...styles.th, width: "30%", cursor: "default" }, children: "waterfall" })] }) }), (0, jsx_runtime_1.jsx)("tbody", { children: rows.map((record) => {
205
+ const left = ((record.ts - range.start) / range.span) * 100;
206
+ const width = Math.max(0.5, ((record.durationMs ?? 0) / range.span) * 100);
207
+ return ((0, jsx_runtime_1.jsxs)("tr", { "data-testid": "nowity-devtools-row", "data-type": record.type, "data-name": record.name, "data-status": record.status, onClick: () => setSelected(record.id === selected ? null : record.id), style: { cursor: "pointer", background: record.id === selected ? "#27272a" : undefined }, children: [(0, jsx_runtime_1.jsxs)("td", { style: styles.td, title: record.name, children: [(0, jsx_runtime_1.jsx)("span", { style: { color: COLORS[record.type], marginRight: 4 }, children: "\u25CF" }), record.name] }), (0, jsx_runtime_1.jsxs)("td", { style: { ...styles.td, color: STATUS_COLORS[record.status] }, "data-testid": "nowity-devtools-row-status", children: [record.status, record.meta.code ? ` (${record.meta.code})` : ""] }), (0, jsx_runtime_1.jsx)("td", { style: styles.td, children: formatMs(record.ts) }), (0, jsx_runtime_1.jsx)("td", { style: styles.td, "data-testid": "nowity-devtools-row-latency", children: formatMs(record.durationMs) }), (0, jsx_runtime_1.jsx)("td", { style: styles.td, children: formatBytes(record.bytes) }), (0, jsx_runtime_1.jsx)("td", { style: styles.td, children: record.meta.updateCount ?? "" }), (0, jsx_runtime_1.jsx)("td", { style: { ...styles.td, position: "relative", maxWidth: "none" }, children: (0, jsx_runtime_1.jsx)("div", { style: {
208
+ position: "absolute",
209
+ top: 4,
210
+ bottom: 4,
211
+ left: `${left}%`,
212
+ width: `${Math.min(width, 100 - left)}%`,
213
+ minWidth: 2,
214
+ background: COLORS[record.type],
215
+ opacity: record.status === "pending" ? 0.4 : 0.85,
216
+ borderRadius: 2,
217
+ } }) })] }, record.id));
218
+ }) })] }), rows.length === 0 && ((0, jsx_runtime_1.jsx)("div", { style: { padding: 12, color: "#a1a1aa" }, "data-testid": "nowity-devtools-empty", children: "nothing recorded" }))] }), detail && ((0, jsx_runtime_1.jsx)("pre", { "data-testid": "nowity-devtools-detail", style: {
219
+ margin: 0,
220
+ width: "34%",
221
+ overflow: "auto",
222
+ padding: 8,
223
+ borderLeft: "1px solid #3f3f46",
224
+ background: "#09090b",
225
+ whiteSpace: "pre-wrap",
226
+ wordBreak: "break-word",
227
+ }, children: JSON.stringify(detail, null, 2) }))] })] }));
228
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nowity",
3
- "version": "1.8.0",
3
+ "version": "1.9.0",
4
4
  "description": "Realtime object model over PostgreSQL: logical change stream, query-scoped subscriptions, MobX identity map",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
@@ -60,6 +60,10 @@
60
60
  "./client": {
61
61
  "types": "./dist/client.d.ts",
62
62
  "default": "./dist/client.js"
63
+ },
64
+ "./devtools": {
65
+ "types": "./dist/devtools.d.ts",
66
+ "default": "./dist/devtools.js"
63
67
  }
64
68
  },
65
69
  "peerDependenciesMeta": {