@terpjs/react-core 0.24.0 → 0.27.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/src/realtime.ts CHANGED
@@ -36,7 +36,23 @@ interface RealtimePaths {
36
36
  export interface RealtimeChannelOptions<Message> {
37
37
  channel: string;
38
38
  transport?: RealtimeTransport;
39
- /** Runtime validation for the channel's Pydantic JSON wire payload. */
39
+ /**
40
+ * Runtime validation for the channel's Pydantic JSON wire payload.
41
+ *
42
+ * THIS FUNCTION IS THE DRIFT BOUNDARY. The authoritative shape is the server's
43
+ * `RealtimeChannel.outbound_model`, which the backend validates every publish against;
44
+ * this guard is hand-written client-side code asserting the same thing. Nothing checks
45
+ * the two against each other, so the realistic way this guard fails is not an attack —
46
+ * the payload's only author is the same deployment's own backend, behind a one-use
47
+ * ticket — but a field added or an enum member widened on the server while the guard
48
+ * still describes the old shape.
49
+ *
50
+ * Because that is the realistic cause, a payload this guard rejects is treated as a
51
+ * MESSAGE failure and not a transport failure: the message is dropped, the rejection is
52
+ * surfaced once on `error` naming this channel, and the transport stays open and keeps
53
+ * delivering. Write the guard narrowly enough to be worth having and wide enough that a
54
+ * server-side addition does not silently blank a screen.
55
+ */
40
56
  validate(value: unknown): value is Message;
41
57
  /** Receive every validated message (lastMessage is also retained). */
42
58
  onMessage?(message: Message): void;
@@ -45,8 +61,19 @@ export interface RealtimeChannelOptions<Message> {
45
61
  }
46
62
 
47
63
  export interface RealtimeChannelState<Message> {
64
+ /**
65
+ * The transport's state. `"error"` means the transport itself failed and a reconnect is
66
+ * scheduled; a message the guard rejected does NOT move this away from `"open"`.
67
+ */
48
68
  status: RealtimeStatus;
49
69
  lastMessage: Message | null;
70
+ /**
71
+ * The most recent failure, which is not the same question as `status`. A rejected
72
+ * payload sets this while `status` stays `"open"`: the channel is still delivering, and
73
+ * something it was sent did not match the declared type. Read the pair, not either half
74
+ * — `status === "error"` is the connection's verdict, `error !== null` is the last
75
+ * reason of any kind.
76
+ */
50
77
  error: Error | null;
51
78
  /** WebSocket only; throws unless the socket is open. */
52
79
  send(message: unknown): void;
@@ -81,15 +108,20 @@ function transportUrl(
81
108
  function parseMessage<Message>(
82
109
  raw: string,
83
110
  validate: (value: unknown) => value is Message,
111
+ channel?: string,
84
112
  ): Message {
113
+ // The channel is named in the message because the reader of this error is debugging
114
+ // drift between one server-side model and one hand-written guard, and an app may hold
115
+ // several channels at once. Optional so the predicate stays callable on its own.
116
+ const named = channel === undefined ? "Realtime channel" : `Realtime channel "${channel}"`;
85
117
  let value: unknown;
86
118
  try {
87
119
  value = JSON.parse(raw);
88
120
  } catch {
89
- throw new Error("Realtime channel received invalid JSON");
121
+ throw new Error(`${named} received invalid JSON`);
90
122
  }
91
123
  if (!validate(value)) {
92
- throw new Error("Realtime channel received a payload outside its declared type");
124
+ throw new Error(`${named} received a payload outside its declared type`);
93
125
  }
94
126
  return value;
95
127
  }
@@ -116,7 +148,7 @@ export function useRealtimeChannel<Message>({
116
148
  const validateRef = useRef(validate);
117
149
  const onMessageRef = useRef(onMessage);
118
150
  const closeRef = useRef<() => void>(() => {});
119
- const terminalFailureRef = useRef<(cause: unknown) => void>(() => {});
151
+ const messageFailureRef = useRef<(cause: unknown) => void>(() => {});
120
152
  validateRef.current = validate;
121
153
  onMessageRef.current = onMessage;
122
154
  const [status, setStatus] = useState<RealtimeStatus>(
@@ -128,17 +160,23 @@ export function useRealtimeChannel<Message>({
128
160
  const receiveRef = useRef((raw: string) => {});
129
161
  receiveRef.current = (raw: string) => {
130
162
  try {
131
- const message = parseMessage(raw, validateRef.current);
163
+ const message = parseMessage(raw, validateRef.current, channel);
132
164
  setLastMessage(message);
133
165
  onMessageRef.current?.(message);
134
166
  } catch (cause) {
135
- terminalFailureRef.current(cause);
167
+ // One message, one failure. The transport is fine — see `messageFailure`.
168
+ messageFailureRef.current(cause);
136
169
  }
137
170
  };
138
171
 
172
+ const reportRef = useRef((cause: unknown) => {});
173
+ reportRef.current = (cause: unknown) => {
174
+ setError(cause instanceof Error ? cause : new Error("Realtime channel failed"));
175
+ };
176
+
139
177
  const failRef = useRef((cause: unknown) => {});
140
178
  failRef.current = (cause: unknown) => {
141
- setError(cause instanceof Error ? cause : new Error("Realtime connection failed"));
179
+ reportRef.current(cause);
142
180
  setStatus("error");
143
181
  };
144
182
 
@@ -174,14 +212,29 @@ export function useRealtimeChannel<Message>({
174
212
  };
175
213
  closeRef.current = stop;
176
214
 
177
- const terminalFailure = (cause: unknown) => {
215
+ // A payload the guard rejects is a MESSAGE failure, not a transport failure.
216
+ //
217
+ // This used to tear the transport down: `stopped = true`, cancel the retry timer and
218
+ // release the socket, which left the channel dead for the life of the mount — the
219
+ // effect's deps never change on a bad message and the returned state exposes no reopen,
220
+ // so neither shipped subscriber could recover. That is a self-inflicted outage in the
221
+ // one case that actually happens: the payload's only author is the same deployment's
222
+ // own backend behind a one-use ticket, so a guard miss means the hand-written guard has
223
+ // fallen behind the server's model, and every LATER message — including the ones the
224
+ // guard still accepts — was being discarded along with it.
225
+ //
226
+ // So: drop the message, say so once on `error` with the channel named, and keep
227
+ // delivering. Once per connection, because a server whose shape has moved sends the
228
+ // same wrong shape repeatedly and one re-render per message is a second failure on top
229
+ // of the first; a reconnect clears the latch along with the error (`onopen`).
230
+ let rejectedPayloadReported = false;
231
+ const messageFailure = (cause: unknown) => {
178
232
  if (!active()) return;
179
- stopped = true;
180
- cancelRetry();
181
- releaseTransport("invalid message payload");
182
- failRef.current(cause);
233
+ if (rejectedPayloadReported) return;
234
+ rejectedPayloadReported = true;
235
+ reportRef.current(cause);
183
236
  };
184
- terminalFailureRef.current = terminalFailure;
237
+ messageFailureRef.current = messageFailure;
185
238
 
186
239
  if (!enabled) {
187
240
  stopped = true;
@@ -189,8 +242,8 @@ export function useRealtimeChannel<Message>({
189
242
  return () => {
190
243
  cancelled = true;
191
244
  if (closeRef.current === stop) closeRef.current = () => {};
192
- if (terminalFailureRef.current === terminalFailure) {
193
- terminalFailureRef.current = () => {};
245
+ if (messageFailureRef.current === messageFailure) {
246
+ messageFailureRef.current = () => {};
194
247
  }
195
248
  };
196
249
  }
@@ -218,6 +271,7 @@ export function useRealtimeChannel<Message>({
218
271
  source.onopen = () => {
219
272
  if (!active() || source !== connectedSource) return;
220
273
  retryAttempt = 0;
274
+ rejectedPayloadReported = false;
221
275
  setError(null);
222
276
  setStatus("open");
223
277
  };
@@ -236,6 +290,7 @@ export function useRealtimeChannel<Message>({
236
290
  socket.onopen = () => {
237
291
  if (!active() || socket !== connectedSocket) return;
238
292
  retryAttempt = 0;
293
+ rejectedPayloadReported = false;
239
294
  setError(null);
240
295
  setStatus("open");
241
296
  };
@@ -281,8 +336,8 @@ export function useRealtimeChannel<Message>({
281
336
  cancelRetry();
282
337
  releaseTransport("component unmounted");
283
338
  if (closeRef.current === stop) closeRef.current = () => {};
284
- if (terminalFailureRef.current === terminalFailure) {
285
- terminalFailureRef.current = () => {};
339
+ if (messageFailureRef.current === messageFailure) {
340
+ messageFailureRef.current = () => {};
286
341
  }
287
342
  };
288
343
  }, [baseUrl, channel, client, enabled, transport]);
@@ -1,7 +1,7 @@
1
1
  // @vitest-environment jsdom
2
2
  import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
3
3
  import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
4
- import { useEffect, useState } from "react";
4
+ import { Suspense, lazy, useEffect, useState } from "react";
5
5
  import { afterEach, describe, expect, it, vi } from "vitest";
6
6
  import type { ModuleManifest } from "@terpjs/contract";
7
7
 
@@ -657,9 +657,12 @@ describe("buildAppRouter", () => {
657
657
  </TerpProvider>,
658
658
  );
659
659
 
660
- // The bare view mounts, the post-mount check bites, and the screen is torn down.
661
- await waitFor(() =>
662
- expect(screen.queryByRole("heading", { name: "Bare view" })).not.toBeInTheDocument(),
660
+ // The bare view mounts, the post-mount check bites, and the screen is torn down. The
661
+ // timeout clears the guard's grace budget: this is the one test that waits out the whole
662
+ // window, because it is the one asserting the refusal actually arrives.
663
+ await waitFor(
664
+ () => expect(screen.queryByRole("heading", { name: "Bare view" })).not.toBeInTheDocument(),
665
+ { timeout: 4000 },
663
666
  );
664
667
  });
665
668
 
@@ -702,6 +705,86 @@ describe("buildAppRouter", () => {
702
705
  );
703
706
  });
704
707
 
708
+ it("accepts a view whose page archetype lands a timer later, not merely a commit later", async () => {
709
+ // The case above frames on the very next commit, which the old one-macrotask window
710
+ // happened to cover on an idle machine and lost on a busy one — this suite's flakiest
711
+ // failure. A view that frames after a *timer* is the same thing without the coin toss:
712
+ // it was refused every time, and it is the ordinary shape of a screen waiting on
713
+ // anything at all before it can draw its frame.
714
+ vi.stubGlobal("fetch", sessionFetch());
715
+
716
+ function TimerFramedView() {
717
+ const [ready, setReady] = useState(false);
718
+ useEffect(() => {
719
+ const timer = setTimeout(() => setReady(true), 25);
720
+ return () => clearTimeout(timer);
721
+ }, []);
722
+ return ready ? <Page title="Late view">late body</Page> : null;
723
+ }
724
+
725
+ const router = buildAppRouter(
726
+ [{ name: "late", routes: [{ path: "/late", view: "LateView" }], nav: [] }],
727
+ {
728
+ views: { LateView: TimerFramedView },
729
+ title: "Terp",
730
+ history: createMemoryHistory({ initialEntries: ["/late"] }),
731
+ },
732
+ );
733
+
734
+ render(
735
+ <TerpProvider baseUrl="https://api.test">
736
+ <LogInOnMount />
737
+ <RouterProvider router={router} />
738
+ </TerpProvider>,
739
+ );
740
+
741
+ await waitFor(() =>
742
+ expect(screen.getByRole("heading", { name: "Late view" })).toBeInTheDocument(),
743
+ );
744
+ });
745
+
746
+ it("accepts a view whose page archetype arrives with a lazily loaded chunk", async () => {
747
+ // The literal case the grace window's own comment named and did not cover: a code-split
748
+ // screen. `lazy()` resolves over a chunk fetch, so the frame is unreachable within one
749
+ // macrotask by construction — the guard refused every such view, deterministically, and
750
+ // hardest on the slow connections code splitting exists to serve.
751
+ vi.stubGlobal("fetch", sessionFetch());
752
+
753
+ const LazyFramed = lazy(
754
+ () =>
755
+ new Promise<{ default: typeof Page }>((resolve) =>
756
+ setTimeout(() => resolve({ default: Page }), 25),
757
+ ),
758
+ );
759
+ function ChunkedView() {
760
+ return (
761
+ <Suspense fallback={null}>
762
+ <LazyFramed title="Late view">late body</LazyFramed>
763
+ </Suspense>
764
+ );
765
+ }
766
+
767
+ const router = buildAppRouter(
768
+ [{ name: "late", routes: [{ path: "/late", view: "LateView" }], nav: [] }],
769
+ {
770
+ views: { LateView: ChunkedView },
771
+ title: "Terp",
772
+ history: createMemoryHistory({ initialEntries: ["/late"] }),
773
+ },
774
+ );
775
+
776
+ render(
777
+ <TerpProvider baseUrl="https://api.test">
778
+ <LogInOnMount />
779
+ <RouterProvider router={router} />
780
+ </TerpProvider>,
781
+ );
782
+
783
+ await waitFor(() =>
784
+ expect(screen.getByRole("heading", { name: "Late view" })).toBeInTheDocument(),
785
+ );
786
+ });
787
+
705
788
  it("mounts the built-in profile page; the user menu's Settings opens it", async () => {
706
789
  const fetchMock = vi.fn<typeof fetch>(async (input) => {
707
790
  const url = (input as Request).url;
package/src/router.tsx CHANGED
@@ -55,6 +55,32 @@ export const DEFAULT_ROLE_RANKS: Record<string, number> = {
55
55
  /** The built-in profile / settings route (an app manifest claiming the path wins). */
56
56
  export const PROFILE_PATH = "/profile";
57
57
 
58
+ /**
59
+ * How long a routed view may go unframed before the page-archetype guard refuses it.
60
+ *
61
+ * The window used to be one macrotask, and one macrotask does not mean what the guard said it
62
+ * meant. The case the grace exists for — an inner component resolving lazily — is a dynamic
63
+ * `import()`, so the frame lands a *chunk fetch* later and never on the next tick; a view
64
+ * framing on a plain `useEffect` → `setState` → commit can lose the race too, because that
65
+ * commit goes through React's scheduler while the deadline is a timer, and on a loaded machine
66
+ * the timer wins. Both shapes were refused: a correct code-split screen replaced by an error
67
+ * boundary on exactly the slow devices that can least afford it, and a test suite that failed
68
+ * on whichever file the CI runner happened to be busy with.
69
+ *
70
+ * The asymmetry sets the number. Refusing early destroys a working screen in front of a user;
71
+ * refusing late only delays a message a developer reads, and delays it by less than the time it
72
+ * takes to look at what they just broke. So the budget is deliberately generous.
73
+ *
74
+ * It is still a deadline, and the honest limit is that a chunk slower than this is refused. The
75
+ * guard cannot be both fail-closed on an *absent* frame and patient without bound — absence
76
+ * only becomes a fact once something declares the waiting over. Worth knowing while reading
77
+ * that trade: unlike the layout contract, which pairs a lint rule with its runtime check, this
78
+ * control has no build-time half — no lint rule reads the source for it and the Terp Standard
79
+ * catalogs no entry — so this budget is the whole of the judgement, with no second control
80
+ * behind it.
81
+ */
82
+ const ARCHETYPE_GRACE_MS = 2_000;
83
+
58
84
  /**
59
85
  * Translate a manifest path into TanStack Router's dialect.
60
86
  *
@@ -561,8 +587,9 @@ export function buildAppRouter(
561
587
  // The runtime half of the "every routed view is a page archetype" control: Page
562
588
  // (composed by OverviewPage / DetailPage / HubPage) marks the render; a routed view
563
589
  // that mounted without any archetype in its tree is refused, fail closed. The check
564
- // waits one macrotask so a view whose archetype lands on a follow-up commit (e.g. a
565
- // lazy inner component resolving) is not refused spuriously.
590
+ // waits `ARCHETYPE_GRACE_MS` so a view whose archetype lands on a follow-up commit —
591
+ // a lazy inner component resolving, a frame behind one render of state — is not
592
+ // refused spuriously; see that constant for why the budget is as generous as it is.
566
593
  const marked = useRef(false);
567
594
  const [unframed, setUnframed] = useState(false);
568
595
  useEffect(() => {
@@ -573,7 +600,7 @@ export function buildAppRouter(
573
600
  if (!marked.current) {
574
601
  setUnframed(true);
575
602
  }
576
- }, 0);
603
+ }, ARCHETYPE_GRACE_MS);
577
604
  return () => clearTimeout(timer);
578
605
  }, [allowed]);
579
606
  if (unframed && !marked.current) {
@@ -1,7 +1,7 @@
1
1
  // @vitest-environment jsdom
2
2
  import { afterEach, describe, expect, it } from "vitest";
3
3
 
4
- import { ROOMY_VIEWPORT_QUERY } from "./breakpoints";
4
+ import { NARROW_VIEWPORT, ROOMY_VIEWPORT_QUERY, WIDE_VIEWPORT_QUERY } from "./breakpoints";
5
5
  import { TERP_STYLES_ID, TERP_STYLES_CSS, injectTerpStyles } from "./styles";
6
6
 
7
7
  /** The sheet with comments removed — prose must not satisfy a structural assertion. */
@@ -39,6 +39,40 @@ function layerBody(name: string): string {
39
39
  throw new Error(`@layer ${name} is not brace-balanced`);
40
40
  }
41
41
 
42
+ /**
43
+ * Every `@media <query>` block inside `body`, brace-balanced and joined.
44
+ *
45
+ * ALL of them, not the first: a cutover half is declared in more than one place — the stack's
46
+ * direction props and the page band's two-row form both sit above the same one — and reading
47
+ * only the first would assert against whichever block happens to be written earlier. Joining
48
+ * asserts what the sheet declares for that HALF of the cutover, which is the property worth
49
+ * holding; where a rule physically sits inside the half is not.
50
+ *
51
+ * Reaching inside the query at all is the point. A substring search across the flat layer
52
+ * passes just as happily when a rule has landed in the wrong half, which is the one mistake
53
+ * this pair of blocks can make.
54
+ */
55
+ function mediaBodies(body: string, query: string): string {
56
+ const opener = `@media ${query} {`;
57
+ const found: string[] = [];
58
+ for (let at = body.indexOf(opener); at !== -1; at = body.indexOf(opener, at + 1)) {
59
+ const first = body.indexOf("{", at);
60
+ let depth = 0;
61
+ for (let i = first; i < body.length; i += 1) {
62
+ if (body[i] === "{") depth += 1;
63
+ else if (body[i] === "}") {
64
+ depth -= 1;
65
+ if (depth === 0) {
66
+ found.push(body.slice(first + 1, i));
67
+ break;
68
+ }
69
+ }
70
+ }
71
+ }
72
+ if (found.length === 0) throw new Error(`the sheet declares no @media ${query} block`);
73
+ return found.join("\n");
74
+ }
75
+
42
76
  /**
43
77
  * Whether `body` declares a rule whose selector list contains EXACTLY `selector` — not
44
78
  * merely a selector containing it as a substring.
@@ -1033,29 +1067,52 @@ describe("cascade structure", () => {
1033
1067
  expect(header, "with nothing else to show, the band is one row").toContain(
1034
1068
  'grid-template-areas: "trail actions"',
1035
1069
  );
1036
- // The second row, and the reason it is conditional. A page with badges or a lead line
1037
- // already spends a row on them, so the cluster joining them costs no height at all -- and
1038
- // it buys the trail the whole first row, which is what stops a deep trail truncating. A
1039
- // page with neither keeps the single row, and with it the measurement the chrome is held
1040
- // to further down this file: the band matches the app header above it.
1070
+ // The second row. It used to carry the cluster as well -- "a page with badges already
1071
+ // spends a row, so the cluster joining them costs no height, and it buys the trail the
1072
+ // whole first row" -- and the second clause was false for as long as it was written. The
1073
+ // rule meant to hand the trail that row is a child selector against a display: contents
1074
+ // wrapper (pinned below), so it never matched; the trail was auto-placed into column one
1075
+ // and truncated exactly as early as before. The cluster paid and the trail never
1076
+ // collected. Measured at 1280px on two crumbs, one badge and one button: the button on
1077
+ // line two with 1028px of free room beside the trail on line one, unchanged at 1440.
1078
+ //
1079
+ // So the cluster stays beside the trail and the meta group takes the row under it, which
1080
+ // is the one-row band's arrangement with a row added rather than a second arrangement.
1041
1081
  const metaAt = base.indexOf('[data-terp="page-header"][data-has-meta] {');
1042
1082
  expect(metaAt, "the two-row band should have a rule of its own").toBeGreaterThan(-1);
1043
1083
  const withMeta = base.slice(metaAt, base.indexOf("}", metaAt));
1044
- expect(withMeta, "the trail owns the first row outright once there is a second").toContain(
1045
- '"trail trail"',
1084
+ // auto, not 1fr. Equal-height lines were the point of 1fr, and in an indefinite container
1085
+ // fr rows resolve to the LARGEST row's content -- so the taller line's item filled its
1086
+ // track exactly and, with the chrome row spending no block padding, sat flush on the
1087
+ // band's border. Measured 9px above the content and 0px below it on every two-row page.
1088
+ // Content-sized rows plus the multi-row band's own padding measure 4px and 4px.
1089
+ expect(withMeta, "rows sized to their content, so neither sits on the border").toContain(
1090
+ "grid-auto-rows: auto",
1091
+ );
1092
+ // The areas move per cutover, so they are pinned in their own queries rather than here.
1093
+ const wideMeta = mediaBodies(base, WIDE_VIEWPORT_QUERY);
1094
+ expect(wideMeta, "above the cutover the cluster keeps its place beside the trail").toContain(
1095
+ '"trail actions"',
1096
+ );
1097
+ expect(wideMeta, "meta takes the row under them, spanning both columns").toContain(
1098
+ '"meta meta"',
1099
+ );
1100
+ const narrowBand = mediaBodies(base, NARROW_VIEWPORT);
1101
+ expect(narrowBand, "below the cutover the band is a single column").toContain(
1102
+ "grid-template-columns: minmax(0, 1fr)",
1046
1103
  );
1047
- expect(withMeta, "meta sits left of the cluster on the second row").toContain(
1048
- '"meta actions"',
1104
+ // The trail sheds its ancestors rather than its characters. Every crumb carries
1105
+ // min-width: 0 and an ellipsis while the separators are flex: 0 0 auto, so a trail with no
1106
+ // room degrades to bare chevrons -- measured at 360px on six crumbs: six labels under 8px
1107
+ // and no h1 on screen at all. Dropping the ancestors takes their separators with them.
1108
+ expect(narrowBand, "the narrow trail keeps the leaf and one ancestor").toContain(
1109
+ "li:not(:last-child):not(:nth-last-child(2))",
1049
1110
  );
1050
- // Same-height lines. 1fr rather than auto, and in a box whose height nobody declared that
1051
- // is not a share of anything: fr rows in an indefinite container resolve to the LARGEST
1052
- // row's content, so both lines come out at the taller one. Two content-sized rows would be
1053
- // a short trail line above a tall control line, which reads as two bands rather than one
1054
- // of two lines. The computed half is next door in the workbench, which measures the
1055
- // resolved tracks rather than the box: a total carries the gap and the border too, so only
1056
- // the tracks can say whether the two lines actually agree.
1057
- expect(withMeta, "a band of two lines gives them the same height").toContain(
1058
- "grid-auto-rows: 1fr",
1111
+ // The actions row is declared only where there is a cluster to put in it: a named row with
1112
+ // nothing in it is still a row, and the band's gap under it is 8px wedged beneath the
1113
+ // trail on every page with no actions.
1114
+ expect(narrowBand, "an actions row with no cluster is 8px of nothing").toContain(
1115
+ '[data-terp="page-header"]:has(> [data-terp="page-actions"])',
1059
1116
  );
1060
1117
  // The left group generates no box, which is what lets its two children be grid items of
1061
1118
  // the BAND and therefore sit on different rows. The marker survives for the scanner.