@tristan2828/ui-foundation 4.124.2 → 4.126.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 (69) hide show
  1. package/README.md +1 -1
  2. package/conventions/docs/add-an-entity.md +42 -21
  3. package/conventions/docs/cell-patterns.md +80 -39
  4. package/dist/api/transport/index.js +10 -1
  5. package/dist/components/app/edit-caret.d.ts +25 -0
  6. package/dist/components/app/edit-caret.js +118 -0
  7. package/dist/components/app/edit-in-place-store.d.ts +43 -4
  8. package/dist/components/app/edit-in-place-store.js +169 -19
  9. package/dist/components/app/editable-value.js +164 -22
  10. package/dist/components/app/entity-form.js +4 -0
  11. package/dist/components/app/entity-view.js +1 -1
  12. package/dist/components/app/form-leave-guard.js +7 -1
  13. package/dist/components/app/milkdown-editor.d.ts +1 -0
  14. package/dist/components/app/milkdown-editor.js +224 -63
  15. package/dist/components/app/prose-look.d.ts +1 -1
  16. package/dist/components/app/prose-look.js +3 -1
  17. package/dist/components/app/rich-text-autolink.d.ts +6 -0
  18. package/dist/components/app/rich-text-autolink.js +79 -0
  19. package/dist/components/app/rich-text-edges.d.ts +8 -0
  20. package/dist/components/app/rich-text-edges.js +144 -0
  21. package/dist/components/app/rich-text-editor.d.ts +15 -2
  22. package/dist/components/app/rich-text-editor.js +16 -4
  23. package/dist/components/app/rich-text-empty-paragraph.d.ts +14 -6
  24. package/dist/components/app/rich-text-empty-paragraph.js +19 -8
  25. package/dist/components/app/rich-text-formats.js +88 -15
  26. package/dist/components/app/rich-text-full-screen.d.ts +2 -0
  27. package/dist/components/app/rich-text-full-screen.js +78 -0
  28. package/dist/components/app/rich-text-highlight-menu.d.ts +3 -1
  29. package/dist/components/app/rich-text-highlight-menu.js +3 -2
  30. package/dist/components/app/rich-text-input-rules.d.ts +7 -0
  31. package/dist/components/app/rich-text-input-rules.js +83 -0
  32. package/dist/components/app/rich-text-keyboard-bar.d.ts +24 -0
  33. package/dist/components/app/rich-text-keyboard-bar.js +214 -0
  34. package/dist/components/app/rich-text-node-views.js +2 -1
  35. package/dist/components/app/rich-text-paste.d.ts +43 -0
  36. package/dist/components/app/rich-text-paste.js +355 -0
  37. package/dist/components/app/rich-text-shortcuts.d.ts +5 -1
  38. package/dist/components/app/rich-text-shortcuts.js +132 -2
  39. package/dist/components/app/rich-text-slash-menu.js +47 -9
  40. package/dist/components/app/rich-text-slash.d.ts +7 -0
  41. package/dist/components/app/rich-text-slash.js +27 -14
  42. package/dist/components/app/rich-text-table-grips.d.ts +8 -6
  43. package/dist/components/app/rich-text-table-grips.js +11 -12
  44. package/dist/components/app/rich-text-tasks.d.ts +8 -0
  45. package/dist/components/app/rich-text-tasks.js +20 -0
  46. package/dist/components/app/rich-text-toolbar.d.ts +5 -1
  47. package/dist/components/app/rich-text-toolbar.js +13 -5
  48. package/dist/components/app/rich-text-touch.d.ts +2 -0
  49. package/dist/components/app/rich-text-touch.js +18 -0
  50. package/dist/components/app/rich-text-widgets.js +1 -1
  51. package/dist/hooks/table-url-changes.d.ts +4 -0
  52. package/dist/hooks/table-url-changes.js +13 -0
  53. package/dist/hooks/use-table-url-state.js +14 -8
  54. package/dist/index.d.ts +1 -0
  55. package/dist/index.js +3 -0
  56. package/dist/lib/markdown-merge.d.ts +26 -0
  57. package/dist/lib/markdown-merge.js +112 -17
  58. package/dist/lib/page-leaving.d.ts +8 -0
  59. package/dist/lib/page-leaving.js +30 -0
  60. package/dist/lib/pending-edits.d.ts +14 -0
  61. package/dist/lib/pending-edits.js +51 -0
  62. package/dist/mocks/e2e-hooks.js +10 -0
  63. package/dist/mocks/override.d.ts +8 -0
  64. package/dist/mocks/start-worker.d.ts +24 -0
  65. package/dist/mocks/start-worker.js +120 -3
  66. package/dist/testing/index.d.ts +84 -5
  67. package/dist/testing/index.js +177 -10
  68. package/package.json +1 -1
  69. package/styles/index.css +7 -0
@@ -28,6 +28,16 @@
28
28
  // - A table and the comment after it that keeps its column widths
29
29
  // (markdown-table-widths.ts) are one block: a width changed in the editor
30
30
  // is an edit to the table, and an unchanged one keeps the comment as written.
31
+ // - A code fence's info string after the language (`title="app.js"`,
32
+ // `{1,3}`) is something the editor can't hold: it loads only the
33
+ // language. `meaning` leaves it out, so an untouched fence still matches
34
+ // and is kept as written; `content` counts it, so a fence is never
35
+ // swapped for the editor's copy that lost it.
36
+ // - Line endings: a Windows (CRLF) note compares as if it were LF, and what
37
+ // the editor writes goes back in the document's own ending.
38
+ // - A link definition goes once nothing in the text uses it any more (no
39
+ // reference to it and no link to its address): select all and delete
40
+ // leaves an empty text, not an invisible definition.
31
41
  import remarkGfm from 'remark-gfm';
32
42
  import remarkParse from 'remark-parse';
33
43
  import { unified } from 'unified';
@@ -38,6 +48,10 @@ function parse(markdown) {
38
48
  }
39
49
  // Fields that are about how a node was written, not what it means.
40
50
  const STYLE_ONLY = new Set(['position', 'data', 'spread', 'label', 'referenceType']);
51
+ // Fields the editor can't hold, so it loads a node without them: left out
52
+ // of `meaning` (the block the editor shows still matches its original) but
53
+ // counted by `content` (nothing is lost by writing the editor's copy).
54
+ const EDITOR_DROPS = new Set(['meta']);
41
55
  // Nodes whose children are inline text: compared as runs of marked text.
42
56
  const INLINE_PARENTS = new Set(['paragraph', 'heading', 'tableCell']);
43
57
  // A reference link (or image) as the link it stands for, when its
@@ -99,9 +113,14 @@ function meaning(node, definitions) {
99
113
  const md = resolved(node, definitions);
100
114
  const out = {};
101
115
  for (const key of Object.keys(md).sort()) {
102
- if (STYLE_ONLY.has(key))
116
+ if (STYLE_ONLY.has(key) || EDITOR_DROPS.has(key))
103
117
  continue;
104
- out[key] = key === 'children' && INLINE_PARENTS.has(md.type) ? runs(md.children ?? [], definitions) : meaning(md[key], definitions);
118
+ const value = md[key];
119
+ // CRLF and LF text mean the same.
120
+ if (typeof value === 'string')
121
+ out[key] = value.replace(/\r\n?/g, '\n');
122
+ else
123
+ out[key] = key === 'children' && INLINE_PARENTS.has(md.type) ? runs(md.children ?? [], definitions) : meaning(value, definitions);
105
124
  }
106
125
  if ((md.type === 'link' || md.type === 'image') && out.title === undefined)
107
126
  out.title = null;
@@ -118,26 +137,68 @@ function meaning(node, definitions) {
118
137
  return out;
119
138
  }
120
139
  // Everything in a block a reader could lose: its text (spacing aside),
121
- // code, raw HTML, link and image addresses, image alt text, rules and
122
- // task boxes. Not how any of it is marked or laid out.
140
+ // code, raw HTML, rules, and every other field `meaning` compares
141
+ // (addresses, alt text, a code block's language, a heading's level, task
142
+ // boxes), plus what the editor can't hold (`EDITOR_DROPS`). Taken from the
143
+ // node's own fields, so a field `meaning` compares can't be missed here.
144
+ // Not how any of it is marked or nested (a node's type), nor laid out.
123
145
  function content(node, definitions) {
124
146
  const md = resolved(node, definitions);
125
147
  let out = '';
126
- if (typeof md.value === 'string')
127
- out += md.value.replace(/\s+/g, '');
128
- if (md.type === 'link' || md.type === 'image')
129
- out += `<${String(md.url)}>`;
130
- if (md.type === 'image' || md.type === 'imageReference')
131
- out += `![${String(md.alt ?? '')}]`;
132
148
  if (md.type === 'thematicBreak')
133
149
  out += '<hr>';
134
- if (md.type === 'listItem' && typeof md.checked === 'boolean')
135
- out += md.checked ? '[x]' : '[ ]';
150
+ for (const key of Object.keys(md).sort()) {
151
+ if (key === 'type' || key === 'children' || STYLE_ONLY.has(key))
152
+ continue;
153
+ const value = md[key];
154
+ if (value === null || value === undefined)
155
+ continue;
156
+ // Text runs on across marks: `a *b*` and `**a b**` hold the same text.
157
+ if (key === 'value' && typeof value === 'string')
158
+ out += value.replace(/\s+/g, '');
159
+ else
160
+ out += `<${key}=${JSON.stringify(value)}>`;
161
+ }
136
162
  for (const child of md.children ?? [])
137
163
  out += content(child, definitions);
138
164
  return out;
139
165
  }
166
+ // For tests/markdown-merge.test.ts: every field `meaning` compares must be
167
+ // one `content` counts. Not part of the package's exports.
168
+ export const mergeParts = { parse, meaning, content };
169
+ // References and addresses a block uses (see `Block`).
170
+ function uses(node, references = new Set(), urls = new Set()) {
171
+ if (node.type === 'linkReference' || node.type === 'imageReference' || node.type === 'definition') {
172
+ references.add(String(node.identifier));
173
+ }
174
+ if (typeof node.url === 'string')
175
+ urls.add(node.url);
176
+ for (const child of node.children ?? [])
177
+ uses(child, references, urls);
178
+ return { references, urls };
179
+ }
180
+ // The blocks of the texts merged lately, by text: an editor merges the
181
+ // same original and baseline against each edit, so each is parsed once
182
+ // per mount, not once per merge (F6). A few, most recent last.
183
+ const PARSED = 8;
184
+ const parsed = new Map();
140
185
  function blocks(markdown) {
186
+ const known = parsed.get(markdown);
187
+ if (known) {
188
+ parsed.delete(markdown);
189
+ parsed.set(markdown, known);
190
+ return known;
191
+ }
192
+ const out = parseBlocks(markdown);
193
+ parsed.set(markdown, out);
194
+ if (parsed.size > PARSED)
195
+ parsed.delete(parsed.keys().next().value);
196
+ return out;
197
+ }
198
+ /** How many texts mergeMarkdown has parsed, for tests/markdown-merge-budget.test.ts. */
199
+ export const mergeStats = { parses: 0 };
200
+ function parseBlocks(markdown) {
201
+ mergeStats.parses += 1;
141
202
  const tree = parse(markdown);
142
203
  const children = tree.children ?? [];
143
204
  const definitions = new Map();
@@ -161,6 +222,7 @@ function blocks(markdown) {
161
222
  // Tables with no width set read as they always have.
162
223
  key: JSON.stringify(widths?.some((width) => width !== null) ? [key, widths] : key),
163
224
  content: content(child, definitions),
225
+ ...uses(child),
164
226
  });
165
227
  }
166
228
  return out;
@@ -217,6 +279,19 @@ function shownOwnWay(originals, loaded, loadedToOriginal) {
217
279
  }
218
280
  return shown;
219
281
  }
282
+ const loadedPairs = new WeakMap();
283
+ function loadedAgainst(originals, loaded) {
284
+ let byLoaded = loadedPairs.get(originals);
285
+ if (!byLoaded)
286
+ loadedPairs.set(originals, (byLoaded = new WeakMap()));
287
+ let pair = byLoaded.get(loaded);
288
+ if (!pair) {
289
+ const loadedToOriginal = match(originals, loaded);
290
+ pair = { loadedToOriginal, shown: shownOwnWay(originals, loaded, loadedToOriginal) };
291
+ byLoaded.set(loaded, pair);
292
+ }
293
+ return pair;
294
+ }
220
295
  export class MarkdownMergeError extends Error {
221
296
  constructor() {
222
297
  super("This text can't be saved without changing parts you didn't edit. Undo the last change, or edit it in the form.");
@@ -233,10 +308,14 @@ export class MarkdownMergeError extends Error {
233
308
  export function mergeMarkdown(original, baseline, current) {
234
309
  if (current === baseline)
235
310
  return original;
311
+ // The document's own line ending (its first), for what the editor
312
+ // writes, which is always LF.
313
+ const eol = original[original.indexOf('\n') - 1] === '\r' ? '\r\n' : '\n';
314
+ const ownEnding = (text) => (eol === '\n' ? text : text.replace(/\r?\n/g, eol));
236
315
  const originals = blocks(original);
237
316
  const loaded = blocks(baseline);
238
317
  const edited = blocks(current);
239
- const loadedToOriginal = match(originals, loaded);
318
+ const { loadedToOriginal, shown } = loadedAgainst(originals, loaded);
240
319
  const editedToLoaded = match(loaded, edited);
241
320
  // Each edited block's original, if it is one unchanged.
242
321
  const sources = edited.map((_block, index) => {
@@ -254,7 +333,6 @@ export function mergeMarkdown(original, baseline, current) {
254
333
  });
255
334
  // Blocks the editor never showed (definitions, and any block it dropped
256
335
  // part of): after whatever came before them in the original.
257
- const shown = shownOwnWay(originals, loaded, loadedToOriginal);
258
336
  originals.forEach((_block, index) => {
259
337
  if (shown.has(index))
260
338
  return;
@@ -267,6 +345,23 @@ export function mergeMarkdown(original, baseline, current) {
267
345
  }
268
346
  items.splice(position, 0, { original: index, at: index });
269
347
  });
348
+ // A definition the original used and nothing uses now (no reference to
349
+ // it, no link to its address: the editor writes a reference link inline)
350
+ // goes with the text that used it.
351
+ const inText = (list) => list.filter((block) => block.type !== 'definition');
352
+ const usedBefore = new Set(inText(originals).flatMap((block) => [...block.references]));
353
+ const kept = items.map((item) => ('original' in item ? originals[item.original] : item.written));
354
+ const referencesNow = new Set(inText(kept).flatMap((block) => [...block.references]));
355
+ const urlsNow = new Set(inText(kept).flatMap((block) => [...block.urls]));
356
+ for (let k = items.length - 1; k >= 0; k--) {
357
+ const block = kept[k];
358
+ if (block.type !== 'definition')
359
+ continue;
360
+ const [identifier] = block.references;
361
+ const [url] = block.urls;
362
+ if (usedBefore.has(identifier) && !referencesNow.has(identifier) && !urlsNow.has(url))
363
+ items.splice(k, 1);
364
+ }
270
365
  let out = '';
271
366
  items.forEach((item, k) => {
272
367
  const previous = items[k - 1];
@@ -278,16 +373,16 @@ export function mergeMarkdown(original, baseline, current) {
278
373
  out += original.slice(originals[previous.original].end, originals[item.original].start);
279
374
  }
280
375
  else {
281
- out += '\n\n';
376
+ out += eol + eol;
282
377
  }
283
- out += 'original' in item ? originals[item.original].source : item.written.source;
378
+ out += 'original' in item ? originals[item.original].source : ownEnding(item.written.source);
284
379
  });
285
380
  // The document ends the way the original ended, whichever block is last
286
381
  // now: an edit to the last block adds no newline the person didn't type.
287
382
  // Text written from nothing ends the way the editor ends it.
288
383
  const ending = originals.length > 0
289
384
  ? original.slice(originals[originals.length - 1].end)
290
- : current.slice(edited.at(-1)?.end ?? current.length);
385
+ : ownEnding(current.slice(edited.at(-1)?.end ?? current.length));
291
386
  if (items.length > 0)
292
387
  out += ending;
293
388
  const saved = blocks(out)
@@ -0,0 +1,8 @@
1
+ /** Under the browser's 64 KB keepalive budget, with room for a second save. */
2
+ export declare const KEEPALIVE_MAX_BYTES = 30000;
3
+ /** The page is closing or hidden: requests started in the next moment use `keepalive`. */
4
+ export declare function markPageLeaving(now?: number): void;
5
+ /** The page is back (visible again): requests are ordinary again. */
6
+ export declare function clearPageLeaving(): void;
7
+ /** Whether a request with this body, started now, should be sent with `keepalive`. */
8
+ export declare function keepaliveFor(body: unknown, now?: number): boolean;
@@ -0,0 +1,30 @@
1
+ // The page is going away (closing the tab, hidden on a phone): requests
2
+ // started now ask the browser to finish them after the page is gone
3
+ // (`keepalive`), so the last autosave still arrives (F13). LeaveGuard
4
+ // marks it; the transport reads it. Only a body that fits the browser's
5
+ // keepalive budget (64 KB across the page's keepalive requests) goes
6
+ // that way: a longer note's save goes as an ordinary request, which the
7
+ // leave prompt (`beforeunload`) gives time to finish.
8
+ /** Under the browser's 64 KB keepalive budget, with room for a second save. */
9
+ export const KEEPALIVE_MAX_BYTES = 30_000;
10
+ // How long after the mark a request still counts as made while leaving:
11
+ // the save goes through the mutation queue first.
12
+ const LEAVING_FOR_MS = 2_000;
13
+ let leavingUntil = 0;
14
+ /** The page is closing or hidden: requests started in the next moment use `keepalive`. */
15
+ export function markPageLeaving(now = Date.now()) {
16
+ leavingUntil = now + LEAVING_FOR_MS;
17
+ }
18
+ /** The page is back (visible again): requests are ordinary again. */
19
+ export function clearPageLeaving() {
20
+ leavingUntil = 0;
21
+ }
22
+ /** Whether a request with this body, started now, should be sent with `keepalive`. */
23
+ export function keepaliveFor(body, now = Date.now()) {
24
+ if (now >= leavingUntil)
25
+ return false;
26
+ // A save's JSON; nothing else (a GET, an upload's form) needs it.
27
+ if (typeof body !== 'string')
28
+ return false;
29
+ return new TextEncoder().encode(body).length <= KEEPALIVE_MAX_BYTES;
30
+ }
@@ -0,0 +1,14 @@
1
+ type Flush = () => void;
2
+ /**
3
+ * A control has typing it hasn't reported yet: `flush` reports it now.
4
+ * Returns the release, called once it has reported (by itself, after its
5
+ * pause, or through `flush`).
6
+ */
7
+ export declare function holdPendingEdit(flush: Flush): () => void;
8
+ /** Every control with typing held back reports it now (before a save reads the value). */
9
+ export declare function flushPendingEdits(): void;
10
+ /** Whether any control holds typing it hasn't reported yet. */
11
+ export declare function hasPendingEdits(): boolean;
12
+ /** Called when `hasPendingEdits()` changes (for `useSyncExternalStore`). */
13
+ export declare function subscribePendingEdits(listener: () => void): () => void;
14
+ export {};
@@ -0,0 +1,51 @@
1
+ // Edits a control holds back until they're needed (RichTextEditor, F6 of
2
+ // the 2026-11-17 review). Turning a long note back into Markdown that
3
+ // keeps every untouched block as written (mergeMarkdown) costs time in
4
+ // proportion to the note, so the editor does it a short pause after
5
+ // typing stops, not on every key. Anything about to read a control's
6
+ // value to save it calls `flushPendingEdits()` first: each editor with
7
+ // typing not yet reported reports it, synchronously, through its
8
+ // `onChange` (or `onProblem`).
9
+ //
10
+ // The edit-in-place store does (before each save, commit, refresh and
11
+ // when a field leaves), EntityForm does before its submit, and the leave
12
+ // guards do before they decide whether leaving loses something.
13
+ // `hasPendingEdits()` (with `subscribePendingEdits`) says whether any is
14
+ // waiting, for a leave guard that must ask the browser to hold a tab
15
+ // open before the pause is over.
16
+ const pending = new Set();
17
+ const listeners = new Set();
18
+ function changed() {
19
+ for (const listener of listeners)
20
+ listener();
21
+ }
22
+ /**
23
+ * A control has typing it hasn't reported yet: `flush` reports it now.
24
+ * Returns the release, called once it has reported (by itself, after its
25
+ * pause, or through `flush`).
26
+ */
27
+ export function holdPendingEdit(flush) {
28
+ pending.add(flush);
29
+ if (pending.size === 1)
30
+ changed();
31
+ return () => {
32
+ if (pending.delete(flush) && pending.size === 0)
33
+ changed();
34
+ };
35
+ }
36
+ /** Every control with typing held back reports it now (before a save reads the value). */
37
+ export function flushPendingEdits() {
38
+ for (const flush of [...pending])
39
+ flush();
40
+ }
41
+ /** Whether any control holds typing it hasn't reported yet. */
42
+ export function hasPendingEdits() {
43
+ return pending.size > 0;
44
+ }
45
+ /** Called when `hasPendingEdits()` changes (for `useSyncExternalStore`). */
46
+ export function subscribePendingEdits(listener) {
47
+ listeners.add(listener);
48
+ return () => {
49
+ listeners.delete(listener);
50
+ };
51
+ }
@@ -12,7 +12,17 @@ export function exposeMswForE2E(worker) {
12
12
  window.__msw = { worker, http, HttpResponse, delay };
13
13
  const override = window.__E2E_MSW_OVERRIDE__;
14
14
  if (override) {
15
+ // A held override answers once the test releases it: requests made
16
+ // before then wait, any made after go straight through.
17
+ const held = [];
18
+ window.__E2E_MSW_RELEASE__ = () => {
19
+ window.__E2E_MSW_RELEASED__ = true;
20
+ for (const go of held.splice(0))
21
+ go();
22
+ };
15
23
  worker.use(http[override.method](override.path, async () => {
24
+ if (override.hold && !window.__E2E_MSW_RELEASED__)
25
+ await new Promise((go) => held.push(go));
16
26
  if (override.delayMs)
17
27
  await delay(override.delayMs);
18
28
  if (override.bodyBase64 !== undefined) {
@@ -6,6 +6,12 @@ export type MswOverride = {
6
6
  status?: number;
7
7
  body?: unknown;
8
8
  delayMs?: number;
9
+ /**
10
+ * Holds every matching request until the test releases it
11
+ * (`forceMswOverride(page, override, { hold: true })` and its
12
+ * `release()`, or `releaseMswOverride(page)`). Set by `forceMswOverride`.
13
+ */
14
+ hold?: boolean;
9
15
  bodyBase64?: string;
10
16
  contentType?: string;
11
17
  /** Response headers, e.g. a 429's `Retry-After`. */
@@ -21,5 +27,7 @@ declare global {
21
27
  interface Window {
22
28
  __msw: MswHandle;
23
29
  __E2E_MSW_OVERRIDE__?: MswOverride;
30
+ __E2E_MSW_RELEASED__?: boolean;
31
+ __E2E_MSW_RELEASE__?: () => void;
24
32
  }
25
33
  }
@@ -8,3 +8,27 @@ export declare const MOCK_PROBE_PATH = "/__ui-foundation-msw-probe";
8
8
  * unhandled requests are bypassed unless they say otherwise.
9
9
  */
10
10
  export declare function startMockWorker(worker: SetupWorker, options?: StartOptions): Promise<void>;
11
+ type RequestStarts = {
12
+ on(event: 'request:start', listener: (args: {
13
+ request: Request;
14
+ }) => void): void;
15
+ };
16
+ export type FetchGuardOptions = {
17
+ /** The page's own fetch, which the guard calls. */
18
+ fetch: typeof fetch;
19
+ /** MSW's lifecycle events (`worker.events`): `request:start` for each request the worker hands the page. */
20
+ events: RequestStarts;
21
+ /** Whether a service worker controls the page; an uncontrolled page (a hard reload) has nothing to rejoin. */
22
+ controlled: () => boolean;
23
+ /** Joins the worker's client list again; true once requests are mocked. */
24
+ rejoin: () => Promise<boolean>;
25
+ /** What relative request URLs resolve against (`document.baseURI`). */
26
+ baseUrl: string;
27
+ };
28
+ /**
29
+ * A `fetch` that notices a request the mock worker passed to the network
30
+ * without handing it to MSW, joins the worker again and makes it once
31
+ * more. Exported for its unit test; `startMockWorker` installs it.
32
+ */
33
+ export declare function guardFetch({ fetch: pageFetch, events, controlled, rejoin, baseUrl }: FetchGuardOptions): typeof fetch;
34
+ export {};
@@ -15,6 +15,20 @@
15
15
  // from the network (no `main`, "data is undefined"). So one request that
16
16
  // only a runtime handler answers is made first; until it comes back
17
17
  // mocked, the page joins the list again.
18
+ //
19
+ // After boot the same restart can happen mid-session (#367: requests from a
20
+ // booted page went to the network, five at once from one page). Nothing in
21
+ // the page hears it: a restarted worker is the same `controller`, so no
22
+ // `controllerchange` fires. What the page can see is a request the worker
23
+ // never handed it: MSW's client emits `request:start` for every request the
24
+ // worker forwards (passthroughs included), before the response, and a
25
+ // worker that has forgotten the page forwards none. So, after boot,
26
+ // `window.fetch` is guarded: a response (or network error) whose request
27
+ // was never handed over means the page joins the list again, probes until
28
+ // it's mocked, and makes the request once more. Bounded: one rejoin at a
29
+ // time, shared by every request that saw the bypass, and if a rejoin fails
30
+ // the guard stands down (the boot's message says why). A healthy page
31
+ // pays one map lookup per request and never probes.
18
32
  import { http, HttpResponse } from 'msw';
19
33
  import { exposeMswForE2E } from './e2e-hooks.js';
20
34
  /** Answered only by the handler startMockWorker adds for the probe. */
@@ -35,6 +49,14 @@ export async function startMockWorker(worker, options = {}) {
35
49
  // After the probe's resetHandlers(), so a spec's pre-navigation override
36
50
  // (applied here) stays in place.
37
51
  exposeMswForE2E(worker);
52
+ const pageFetch = window.fetch.bind(window);
53
+ window.fetch = guardFetch({
54
+ fetch: pageFetch,
55
+ events: worker.events,
56
+ controlled: () => navigator.serviceWorker.controller !== null,
57
+ rejoin: () => rejoin(worker, pageFetch),
58
+ baseUrl: document.baseURI,
59
+ });
38
60
  }
39
61
  // Bounded: a hard reload leaves the page uncontrolled for its whole life,
40
62
  // and then the probe below says so instead of the boot hanging.
@@ -68,10 +90,105 @@ async function untilMocked(worker) {
68
90
  worker.resetHandlers();
69
91
  }
70
92
  }
71
- function probe() {
93
+ // After boot: the worker forgot this page. Join again first, then probe. The
94
+ // probe's handler is a `once` handler and stays put, never reset: a spec's
95
+ // runtime handlers (worker.use) are in the same list and must survive.
96
+ async function rejoin(worker, pageFetch) {
97
+ worker.use(http.get(MOCK_PROBE_PATH, () => HttpResponse.text(PROBE_ANSWER), { once: true }));
98
+ for (let attempt = 0; attempt < PROBE_TRIES; attempt += 1) {
99
+ navigator.serviceWorker.controller?.postMessage('MOCK_ACTIVATE');
100
+ await new Promise((resolve) => setTimeout(resolve, PROBE_PAUSE_MS));
101
+ if ((await probe(pageFetch)) === PROBE_ANSWER)
102
+ return true;
103
+ }
104
+ console.error(`[ui-foundation] The mock service worker stopped answering this page and still passes its requests to the network after ${PROBE_TRIES} tries. ` +
105
+ 'API calls may not be mocked; reload the page.');
106
+ return false;
107
+ }
108
+ // One request's identity as both sides see it: the method (upper case: a
109
+ // Request keeps `patch` as given) and the absolute URL without a fragment.
110
+ const requestKey = (method, url) => `${method.toUpperCase()} ${url.split('#')[0]}`;
111
+ function keyOf(input, init, baseUrl) {
112
+ const url = input instanceof Request ? input.url : new URL(input instanceof URL ? input.href : input, baseUrl).href;
113
+ return requestKey(init?.method ?? (input instanceof Request ? input.method : 'GET'), url);
114
+ }
115
+ const aborted = (input, init) => Boolean(init?.signal?.aborted || (input instanceof Request && input.signal.aborted));
116
+ /**
117
+ * A `fetch` that notices a request the mock worker passed to the network
118
+ * without handing it to MSW, joins the worker again and makes it once
119
+ * more. Exported for its unit test; `startMockWorker` installs it.
120
+ */
121
+ export function guardFetch({ fetch: pageFetch, events, controlled, rejoin, baseUrl }) {
122
+ // Per request key: guarded requests in flight, and how many of them the
123
+ // worker has handed over. Only keys in flight are counted, so the
124
+ // worker's other traffic (scripts, images) leaves nothing behind.
125
+ const inFlight = new Map();
126
+ const handed = new Map();
127
+ const bump = (map, key, by) => {
128
+ const next = (map.get(key) ?? 0) + by;
129
+ if (next > 0)
130
+ map.set(key, next);
131
+ else
132
+ map.delete(key);
133
+ };
134
+ events.on('request:start', ({ request }) => {
135
+ const key = requestKey(request.method, request.url);
136
+ if (inFlight.has(key))
137
+ bump(handed, key, 1);
138
+ });
139
+ let rejoining = null;
140
+ let standDown = false;
141
+ const rejoinOnce = () => {
142
+ rejoining ??= rejoin().then((joined) => {
143
+ rejoining = null;
144
+ if (!joined)
145
+ standDown = true;
146
+ return joined;
147
+ });
148
+ return rejoining;
149
+ };
150
+ return async function guardedFetch(input, init) {
151
+ if (standDown || !controlled())
152
+ return pageFetch(input, init);
153
+ const key = keyOf(input, init, baseUrl);
154
+ if (key.endsWith(MOCK_PROBE_PATH))
155
+ return pageFetch(input, init);
156
+ // A Request's body can be read once: keep a copy for the second try.
157
+ // A streamed init body can't be replayed at all.
158
+ const again = input instanceof Request && input.body ? input.clone() : input;
159
+ const replayable = !(init?.body instanceof ReadableStream);
160
+ bump(inFlight, key, 1);
161
+ let outcome;
162
+ try {
163
+ outcome = { response: await pageFetch(input, init) };
164
+ }
165
+ catch (error) {
166
+ outcome = { error };
167
+ }
168
+ const mocked = handed.has(key);
169
+ bump(handed, key, -1);
170
+ bump(inFlight, key, -1);
171
+ if (!inFlight.has(key))
172
+ handed.delete(key);
173
+ const settle = () => {
174
+ if ('error' in outcome)
175
+ throw outcome.error;
176
+ return outcome.response;
177
+ };
178
+ if (mocked || aborted(input, init) || !replayable)
179
+ return settle();
180
+ if (!(await rejoinOnce()))
181
+ return settle();
182
+ if ('response' in outcome)
183
+ void outcome.response.body?.cancel().catch(() => { });
184
+ return pageFetch(again, init);
185
+ };
186
+ }
187
+ function probe(pageFetch = fetch) {
72
188
  // The one bare fetch in mocks (eslint.config.js): it tests the worker
73
- // itself, before any app code runs, and never reaches a server.
74
- return fetch(MOCK_PROBE_PATH, { cache: 'no-store' })
189
+ // itself, before any app code runs, and never reaches a server. After
190
+ // boot it's given the page's own fetch, never the guarded one.
191
+ return pageFetch(MOCK_PROBE_PATH, { cache: 'no-store' })
75
192
  .then((response) => (response.ok ? response.text() : ''))
76
193
  .catch(() => '');
77
194
  }
@@ -5,7 +5,11 @@ import type { MswOverride } from '../mocks/override.js';
5
5
  export type { MswHandle, MswOverride } from '../mocks/override.js';
6
6
  export { expect };
7
7
  /**
8
- * Makes the page's `goto()` and `reload()` return once the app has
8
+ * Makes the page's `goto()` and `reload()` wait first until none of the
9
+ * page's own `/api/` requests has been in flight for 150 ms (at most 3 s,
10
+ * and reaching that never fails the test), so a save's follow-up refresh
11
+ * is answered by the page that sent it, on the mocks, not sent by the
12
+ * unloading page past them. They then return once the app has
9
13
  * booted (its first render into `#root`), not at the load event, and load
10
14
  * the page once more when one of the app's own files is refused before
11
15
  * then; a second refusal fails naming the file. The wait is bounded by
@@ -14,18 +18,93 @@ export { expect };
14
18
  * test's `page`; this is for a page an app's own fixture opens.
15
19
  */
16
20
  export declare function withBootWait(page: Page): Page;
21
+ export type MswBypassOptions = {
22
+ /**
23
+ * Whether this run's app is MSW-backed. Defaults to
24
+ * `process.env.VITE_API !== 'real'`; against a real API every response
25
+ * comes from the network and nothing is checked.
26
+ */
27
+ mockMode?: boolean;
28
+ };
29
+ export type MswBypassWatch = {
30
+ /** What went past MSW and was never answered by it, one line per request. */
31
+ bypassed: () => string[];
32
+ /** Whether the test answers requests itself (`page.route`, `context.route`, or from a HAR). */
33
+ routed: () => boolean;
34
+ /** Throws naming every bypassed request, unless the test routes requests itself or the app isn't on MSW. */
35
+ check: () => void;
36
+ };
37
+ /**
38
+ * Watches the page's own `/api/` responses for any that didn't come from
39
+ * the mock service worker (`response.fromServiceWorker()` false), which
40
+ * means the request went to the network: to the preview server's proxy,
41
+ * and from there to whatever listens on its port. A test that passed on
42
+ * data from there didn't test the mocks (#367).
43
+ *
44
+ * A bypass the app healed doesn't count: since the rejoin in
45
+ * `startMockWorker`, a page whose worker forgot it makes the request again
46
+ * once the worker knows it, so a later answer from the worker to the same
47
+ * method and URL settles it. A test that routes requests itself is left
48
+ * alone: its routed answers aren't the worker's either.
49
+ *
50
+ * The `test` exported here runs it on every test's `page`; this is for a
51
+ * page an app's own fixture opens. Call `check()` after the test.
52
+ */
53
+ export declare function watchMswBypass(page: Page, { mockMode }?: MswBypassOptions): MswBypassWatch;
17
54
  /**
18
55
  * Playwright's `test`, with a `page` whose `goto()` and `reload()` wait
19
- * for the app's boot (`withBootWait`). Import `test` and `expect` from
20
- * here instead of '@playwright/test'; the suites below use it too.
56
+ * for the app's boot (`withBootWait`), and which fails a test whose page
57
+ * got an `/api/` answer from anywhere but the mock service worker
58
+ * (`watchMswBypass`). Import `test` and `expect` from here instead of
59
+ * '@playwright/test'; the suites below use it too.
60
+ *
61
+ * `test.use({ mswBypass: 'allow' })` turns the check off for a file or a
62
+ * describe; a test that routes requests itself (`page.route`) and a run
63
+ * against the real API (`VITE_API=real`) are never checked.
21
64
  */
22
- export declare const test: import("playwright/test").TestType<import("playwright/test").PlaywrightTestArgs & import("playwright/test").PlaywrightTestOptions, import("playwright/test").PlaywrightWorkerArgs & import("playwright/test").PlaywrightWorkerOptions>;
65
+ export declare const test: import("playwright/test").TestType<import("playwright/test").PlaywrightTestArgs & import("playwright/test").PlaywrightTestOptions & {
66
+ mswBypass: "fail" | "allow";
67
+ }, import("playwright/test").PlaywrightWorkerArgs & import("playwright/test").PlaywrightWorkerOptions>;
68
+ export type MswOverrideOptions = {
69
+ /**
70
+ * Holds every matching request until the test calls `release()` (or
71
+ * `releaseMswOverride(page)`): the way to test a loading state. The
72
+ * skeleton is there for as long as the test needs, however slow the run,
73
+ * with no time to tune. `delayMs`, if set too, starts counting at the
74
+ * release.
75
+ */
76
+ hold?: boolean;
77
+ };
78
+ export type MswOverrideControl = {
79
+ /** Lets the held requests answer, and every later one answer at once (this page and any it loads next). */
80
+ release: () => Promise<void>;
81
+ };
23
82
  /**
24
83
  * Forces a response for the page's *first* load: set before navigation, so
25
84
  * it wins the race against the app's own first fetch. For states forced
26
85
  * after load, use `waitForMswReady` and then `window.__msw.worker.use(...)`.
86
+ * The override applies to every page the test loads after, reloads included.
87
+ *
88
+ * `{ hold: true }` holds the requests until the test releases them, for a
89
+ * loading state (`tasksList` here is the list's `MswOverride`):
90
+ *
91
+ * const list = await forceMswOverride(page, tasksList, { hold: true })
92
+ * await page.goto('/tasks')
93
+ * await expect(page.locator('[data-state="loading"]')).toBeVisible()
94
+ * await list.release()
95
+ * await expect(page.getByText('Water the ferns')).toBeVisible()
96
+ *
97
+ * Release before the test navigates again: `goto()` and `reload()` first
98
+ * wait for the page's `/api/` requests to settle, and a held one doesn't.
99
+ */
100
+ export declare function forceMswOverride(page: Page, override: MswOverride, { hold }?: MswOverrideOptions): Promise<MswOverrideControl>;
101
+ /**
102
+ * Releases a held override (`forceMswOverride(page, ..., { hold: true })`):
103
+ * the requests held so far answer, and later ones answer at once, on this
104
+ * page and every page the test loads after. Releasing twice, or an
105
+ * override that wasn't held, does nothing.
27
106
  */
28
- export declare function forceMswOverride(page: Page, override: MswOverride): Promise<void>;
107
+ export declare function releaseMswOverride(page: Page): Promise<void>;
29
108
  /** `window.__msw` is set only once the app's mocking has started — page.goto's load event doesn't wait for it. */
30
109
  export declare function waitForMswReady(page: Page): Promise<void>;
31
110
  /** Starts the page logged out: GET /auth/me answers 401 on first load. */