@botiverse/porthole 0.14.8 → 0.14.10

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 (60) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/dist/annotate/types.d.ts +33 -2
  3. package/dist/annotate/validate.d.ts +6 -1
  4. package/dist/annotate/validate.js +31 -3
  5. package/dist/bridge/bridge.d.ts +6 -0
  6. package/dist/bridge/bridge.js +5 -0
  7. package/dist/check/page-source.js +1 -1
  8. package/dist/config/capabilities.d.ts +16 -2
  9. package/dist/config/capabilities.js +8 -0
  10. package/dist/conformance/harness-source.js +1 -1
  11. package/dist/find/types.d.ts +83 -0
  12. package/dist/find/types.js +29 -0
  13. package/dist/find/validate.d.ts +17 -0
  14. package/dist/find/validate.js +82 -0
  15. package/dist/guide/guide.js +2 -1
  16. package/dist/host/create-host.js +219 -3
  17. package/dist/host/pass-on.js +3 -2
  18. package/dist/host/types.d.ts +54 -1
  19. package/dist/index.d.ts +5 -3
  20. package/dist/index.js +4 -1
  21. package/dist/react/frame.d.ts +45 -1
  22. package/dist/react/frame.js +107 -3
  23. package/dist/react/view.js +2 -0
  24. package/dist/runtime/contract.d.ts +1 -1
  25. package/dist/runtime/contract.js +1 -1
  26. package/dist/shell/annotate.d.ts +5 -1
  27. package/dist/shell/annotate.js +41 -107
  28. package/dist/shell/document.d.ts +3 -3
  29. package/dist/shell/document.js +5 -3
  30. package/dist/shell/find.d.ts +82 -0
  31. package/dist/shell/find.js +725 -0
  32. package/dist/shell/runtime.js +4 -1
  33. package/dist/shell/text.d.ts +17 -0
  34. package/dist/shell/text.js +140 -0
  35. package/docs/ADOPTING.md +112 -0
  36. package/docs/ARCHITECTURE.md +10 -3
  37. package/docs/DECISIONS.md +284 -1
  38. package/docs/DESIGN.md +48 -2
  39. package/docs/THREAT_MODEL.md +61 -5
  40. package/docs/insertion-entry-points.md +17 -0
  41. package/package.json +1 -1
  42. package/src/annotate/types.ts +43 -4
  43. package/src/annotate/validate.ts +34 -3
  44. package/src/bridge/bridge.ts +7 -0
  45. package/src/config/capabilities.ts +13 -1
  46. package/src/find/types.ts +86 -0
  47. package/src/find/validate.ts +101 -0
  48. package/src/guide/guide.ts +3 -1
  49. package/src/host/create-host.ts +235 -3
  50. package/src/host/pass-on.ts +3 -2
  51. package/src/host/types.ts +55 -1
  52. package/src/index.ts +14 -1
  53. package/src/react/frame.tsx +162 -2
  54. package/src/react/view.tsx +3 -0
  55. package/src/runtime/contract.ts +1 -1
  56. package/src/shell/annotate.ts +42 -107
  57. package/src/shell/document.ts +5 -3
  58. package/src/shell/find.ts +731 -0
  59. package/src/shell/runtime.ts +4 -1
  60. package/src/shell/text.ts +140 -0
@@ -0,0 +1,83 @@
1
+ import type { AnnotationRect } from "../annotate/types.ts";
2
+ /**
3
+ * Find in page (P131): the host draws its own find bar (a query box, previous and next, "3/12")
4
+ * and the shell finds the query in the content's text and highlights it, the current match apart,
5
+ * in a layer of its own. The host drives it with Porthole's own messages (`porthole/find.*`); the
6
+ * shell answers how many matches there are and which is current.
7
+ *
8
+ * Everything the frame says is the content's word: the shell shares its realm with the content,
9
+ * which can read the query, change the count or hide the highlights. Use what it says for the
10
+ * find bar (a count, where the current match is), never as a fact about the content.
11
+ */
12
+ /** Which match becomes the current one: the next, the previous, or the same (a new query: the first in view). */
13
+ export type FindDirection = "next" | "prev" | "none";
14
+ export interface FindOptions {
15
+ /** Default `"none"`: a new query's first match at or after where the person is reading. */
16
+ readonly direction?: FindDirection;
17
+ /** Default false: case-insensitive, as a browser's own find is. */
18
+ readonly caseSensitive?: boolean;
19
+ }
20
+ /**
21
+ * Where the matches stand. The content's word: a count for the find bar, nothing more.
22
+ */
23
+ export interface FindResult {
24
+ /** How many matches, at most `FIND_LIMITS.matches`. */
25
+ readonly total: number;
26
+ /** The current match, from 1; 0 when there is none. */
27
+ readonly active: number;
28
+ /** There may be more than `total`: the shell stopped at `FIND_LIMITS.matches` ("1000+"). */
29
+ readonly capped?: true;
30
+ /**
31
+ * The current match's box in the frame's viewport, once it was scrolled into view, clamped to
32
+ * the frame's viewport as an annotation's box is (P104): for a host whose frame doesn't scroll
33
+ * itself (a display that grows with its content) to scroll its own page to it. A hint only.
34
+ */
35
+ readonly rect?: AnnotationRect;
36
+ }
37
+ /** What the frame says unasked, once the host has checked it. */
38
+ export type FindReport =
39
+ /**
40
+ * The person pressed Cmd+F (Apple) or Ctrl+F (elsewhere) with the keyboard in the frame, and the
41
+ * page didn't take the key itself. Sent only while the host takes the shortcut
42
+ * (`find.takeShortcut(true)`), which also stops the browser's own find. The page's word too: it
43
+ * can send it, or keep the key from the shell. Open the host's find bar, nothing more.
44
+ */
45
+ {
46
+ readonly type: "requested";
47
+ }
48
+ /**
49
+ * The matches changed while a query is shown, without the host asking: the content changed
50
+ * (more of it, or the page's own changes). At most once a second.
51
+ */
52
+ | ({
53
+ readonly type: "updated";
54
+ } & FindResult);
55
+ /** Porthole's own messages for find in page (own-prefixed, P002). */
56
+ export declare const FIND_METHODS: {
57
+ /**
58
+ * Host → frame, a request: `{ query, direction?, caseSensitive? }`, answered with a
59
+ * `FindResult`. An empty query (or only spaces) clears, and answers no matches. One that a later
60
+ * query or a clear superseded before the shell ran it is answered with an error (code -32800,
61
+ * "superseded by a later query"; the host's `"unsupported"`): only the latest is searched.
62
+ */
63
+ readonly query: "porthole/find.query";
64
+ /** Host → frame: remove the highlights and forget the query. */
65
+ readonly clear: "porthole/find.clear";
66
+ /**
67
+ * Host → frame: `{ handled: boolean }`, whether the host draws its own find bar: while it does,
68
+ * the shell stops the browser's own find on Cmd+F or Ctrl+F in the frame and says `requested`.
69
+ */
70
+ readonly handled: "porthole/find.handled";
71
+ /** Frame → host. */
72
+ readonly requested: "porthole/find.requested";
73
+ readonly updated: "porthole/find.updated";
74
+ };
75
+ /** The most of each part of a query or an answer. */
76
+ export declare const FIND_LIMITS: {
77
+ /** The longest query, in UTF-16 code units. */
78
+ readonly query: 256;
79
+ /** The most matches the shell finds and highlights; past it the answer says `capped`. */
80
+ readonly matches: 1000;
81
+ /** How long the host waits for an answer before it calls the display's find unsupported, ms. */
82
+ readonly timeoutMs: 3000;
83
+ };
@@ -0,0 +1,29 @@
1
+ /** Porthole's own messages for find in page (own-prefixed, P002). */
2
+ export const FIND_METHODS = {
3
+ /**
4
+ * Host → frame, a request: `{ query, direction?, caseSensitive? }`, answered with a
5
+ * `FindResult`. An empty query (or only spaces) clears, and answers no matches. One that a later
6
+ * query or a clear superseded before the shell ran it is answered with an error (code -32800,
7
+ * "superseded by a later query"; the host's `"unsupported"`): only the latest is searched.
8
+ */
9
+ query: "porthole/find.query",
10
+ /** Host → frame: remove the highlights and forget the query. */
11
+ clear: "porthole/find.clear",
12
+ /**
13
+ * Host → frame: `{ handled: boolean }`, whether the host draws its own find bar: while it does,
14
+ * the shell stops the browser's own find on Cmd+F or Ctrl+F in the frame and says `requested`.
15
+ */
16
+ handled: "porthole/find.handled",
17
+ /** Frame → host. */
18
+ requested: "porthole/find.requested",
19
+ updated: "porthole/find.updated",
20
+ };
21
+ /** The most of each part of a query or an answer. */
22
+ export const FIND_LIMITS = {
23
+ /** The longest query, in UTF-16 code units. */
24
+ query: 256,
25
+ /** The most matches the shell finds and highlights; past it the answer says `capped`. */
26
+ matches: 1_000,
27
+ /** How long the host waits for an answer before it calls the display's find unsupported, ms. */
28
+ timeoutMs: 3_000,
29
+ };
@@ -0,0 +1,17 @@
1
+ import { type FindDirection, type FindOptions, type FindReport, type FindResult } from "./types.ts";
2
+ /** An answer to `porthole/find.query`, or an `updated`'s numbers; null if malformed. */
3
+ export declare function parseFindResult(value: unknown): FindResult | null;
4
+ /** A report from the frame, checked; null if malformed (it is then dropped). */
5
+ export declare function parseFindReport(value: unknown): FindReport | null;
6
+ /**
7
+ * A query and its options as the host gives them, checked before they go to the frame; throws a
8
+ * `TypeError` for a query that isn't text, is longer than `FIND_LIMITS.query`, or options that
9
+ * aren't these. The query goes as it is (the shell trims it and loosens its spacing).
10
+ */
11
+ export declare function checkFindQuery(query: unknown, options: FindOptions | undefined): {
12
+ query: string;
13
+ direction: FindDirection;
14
+ caseSensitive: boolean;
15
+ };
16
+ /** Whether a query finds nothing by its words alone: empty, or only spaces (it clears). */
17
+ export declare const blankQuery: (query: string) => boolean;
@@ -0,0 +1,82 @@
1
+ import { parseRect } from "../annotate/validate.js";
2
+ import { FIND_LIMITS as LIMITS, } from "./types.js";
3
+ /**
4
+ * The host's checks on find in page (P131): what it sends (a query and its options) and what a
5
+ * frame says back. A frame's word is rebuilt from known fields only, within `FIND_LIMITS`, and is
6
+ * null for anything else: dropped whole, never repaired.
7
+ */
8
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
9
+ const whole = (value, max) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= max;
10
+ /** An answer to `porthole/find.query`, or an `updated`'s numbers; null if malformed. */
11
+ export function parseFindResult(value) {
12
+ if (!isRecord(value)) {
13
+ return null;
14
+ }
15
+ const { total, active, capped, rect } = value;
16
+ if (!whole(total, LIMITS.matches) || !whole(active, total)) {
17
+ return null;
18
+ }
19
+ if ((total === 0) !== (active === 0)) {
20
+ return null;
21
+ }
22
+ if (capped !== undefined && capped !== true && capped !== false) {
23
+ return null;
24
+ }
25
+ // Capped only at the limit: fewer matches were all of them.
26
+ if (capped === true && total !== LIMITS.matches) {
27
+ return null;
28
+ }
29
+ const box = rect === undefined || active === 0 ? undefined : parseRect(rect);
30
+ if (box === null) {
31
+ return null;
32
+ }
33
+ return {
34
+ total,
35
+ active,
36
+ ...(capped === true ? { capped: true } : {}),
37
+ ...(box === undefined ? {} : { rect: box }),
38
+ };
39
+ }
40
+ /** A report from the frame, checked; null if malformed (it is then dropped). */
41
+ export function parseFindReport(value) {
42
+ if (!isRecord(value)) {
43
+ return null;
44
+ }
45
+ switch (value.type) {
46
+ case "requested":
47
+ return { type: "requested" };
48
+ case "updated": {
49
+ // No box: where the current match is goes only with an answer to the host's own query.
50
+ const { rect: _rect, ...numbers } = value;
51
+ const result = parseFindResult(numbers);
52
+ return result === null ? null : { type: "updated", ...result };
53
+ }
54
+ default:
55
+ return null;
56
+ }
57
+ }
58
+ const DIRECTIONS = ["next", "prev", "none"];
59
+ /**
60
+ * A query and its options as the host gives them, checked before they go to the frame; throws a
61
+ * `TypeError` for a query that isn't text, is longer than `FIND_LIMITS.query`, or options that
62
+ * aren't these. The query goes as it is (the shell trims it and loosens its spacing).
63
+ */
64
+ export function checkFindQuery(query, options) {
65
+ if (typeof query !== "string" || query.length > LIMITS.query) {
66
+ throw new TypeError(`find.query: the query is text, at most ${LIMITS.query} characters`);
67
+ }
68
+ if (options !== undefined && !isRecord(options)) {
69
+ throw new TypeError("find.query: options are { direction?, caseSensitive? }");
70
+ }
71
+ const direction = options?.direction ?? "none";
72
+ if (!DIRECTIONS.includes(direction)) {
73
+ throw new TypeError('find.query: direction is "next", "prev" or "none"');
74
+ }
75
+ const caseSensitive = options?.caseSensitive ?? false;
76
+ if (typeof caseSensitive !== "boolean") {
77
+ throw new TypeError("find.query: caseSensitive is true or false");
78
+ }
79
+ return { query, direction: direction, caseSensitive };
80
+ }
81
+ /** Whether a query finds nothing by its words alone: empty, or only spaces (it clears). */
82
+ export const blankQuery = (query) => query.trim() === "";
@@ -256,6 +256,7 @@ const ENTRIES = {
256
256
  ? `- copyText(text): copies text to the person's clipboard (at most ${MAX_COPY_CHARS.toLocaleString("en-US")} characters), and the app shows them what was copied. Use it for every copy button: nothing else in the ${c.noun} can write the clipboard. ${gateWords(gates, "the text")} It returns a promise: true if it was copied.`
257
257
  : `- Copying: the request porthole/copy-text with { text } (at most ${MAX_COPY_CHARS.toLocaleString("en-US")} characters) copies text to the person's clipboard, and the app shows them what was copied; nothing else in the ${c.noun} can write the clipboard. ${gateWords(gates, "the text")}`,
258
258
  annotate: (c) => `- Comments: the person may point at parts of the ${c.noun} to comment on them. Give headings and the parts that matter stable ids (id="revenue"), so comments stay on them when the ${c.noun} is written again.`,
259
+ find: (c) => `- Find: the person may search the ${c.noun}'s words with the app's own find bar (Cmd+F or Ctrl+F), which highlights them where they are. Keep the words they would look for as text (not in images or a canvas). A ${c.noun} that handles Cmd+F or Ctrl+F itself (preventDefault) keeps the key.`,
259
260
  reportError: (c) => `- ${manualLimits(c.config, "").find((limit) => limit.id === "errors")?.text ?? ""}`,
260
261
  resize: () => "",
261
262
  // The runtime's own: taught as porthole.use's methods (runtimeEntries), never alone.
@@ -266,7 +267,7 @@ const ENTRIES = {
266
267
  db: () => "",
267
268
  };
268
269
  /** The shell's own capabilities, which content never calls by name: taught as they are. */
269
- const SHELL_OWN = ["annotate", "reportError", "resize"];
270
+ const SHELL_OWN = ["annotate", "find", "reportError", "resize"];
270
271
  function interactive(c) {
271
272
  const { config, noun } = c;
272
273
  // Under the capability runtime (P085), what content calls is porthole.use's methods.
@@ -1,5 +1,7 @@
1
1
  import { ANNOTATE_METHODS, } from "../annotate/types.js";
2
2
  import { annotateMode, checkMarks, clampRect, hasMarker, parseReport, } from "../annotate/validate.js";
3
+ import { FIND_LIMITS, FIND_METHODS } from "../find/types.js";
4
+ import { blankQuery, checkFindQuery, parseFindReport, parseFindResult } from "../find/validate.js";
3
5
  import { createBridge, onceConsent, } from "../bridge/bridge.js";
4
6
  import { compile } from "../compile/compile.js";
5
7
  import { servesFiles } from "../files/paths.js";
@@ -44,6 +46,11 @@ const REPORTS = {
44
46
  [ANNOTATE_METHODS.activated]: "activated",
45
47
  [ANNOTATE_METHODS.tracked]: "tracked",
46
48
  };
49
+ /** What the frame says of find in page unasked (P131), by method. */
50
+ const FIND_REPORTS = {
51
+ [FIND_METHODS.requested]: "requested",
52
+ [FIND_METHODS.updated]: "updated",
53
+ };
47
54
  /** The most `tracked` reports a second the host takes (P112): one per animation frame at 60 Hz. */
48
55
  export const TRACKED_PER_SECOND = 60;
49
56
  const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
@@ -160,6 +167,14 @@ export function createHost(config, options = {}) {
160
167
  // The mark the host follows (P112), and when it took each `tracked` in the last second.
161
168
  let tracking = null;
162
169
  const trackedTimes = [];
170
+ // Find in page (P131): the query shown (for the content it was asked of only: a new run or
171
+ // other content forgets it), whether the host takes the shortcut (kept for every frame the
172
+ // display runs), and the queries asked and not yet answered.
173
+ const finds = config.capabilities.find !== undefined;
174
+ let findShown = null;
175
+ let takesShortcut = false;
176
+ let nextFind = 1;
177
+ const findsAsked = new Map();
163
178
  let handshaken = false;
164
179
  let storageTold = false;
165
180
  const toFrame = (method, params) => {
@@ -167,6 +182,86 @@ export function createHost(config, options = {}) {
167
182
  surface.transport.send({ jsonrpc: "2.0", method, params });
168
183
  }
169
184
  };
185
+ /** A query asked of the frame running now (once it finished its handshake). */
186
+ const sendFind = (id, params) => {
187
+ if (handshaken && surface !== null) {
188
+ surface.transport.send({ jsonrpc: "2.0", id, method: FIND_METHODS.query, params });
189
+ }
190
+ };
191
+ /** Answers a query asked, once; a later answer for it is dropped. */
192
+ const settleFind = (id, result) => {
193
+ const asked = findsAsked.get(id);
194
+ if (asked !== undefined) {
195
+ findsAsked.delete(id);
196
+ clearTimeout(asked.timer);
197
+ asked.resolve(result);
198
+ }
199
+ };
200
+ /**
201
+ * Asks the frame a query: at once where one finished its handshake, else when one does
202
+ * (its load's time and the answer's). No answer in time, an error (an older shell's "isn't
203
+ * offered here"), or one malformed: `"unsupported"`.
204
+ */
205
+ const askFind = (params) => new Promise((resolve) => {
206
+ const id = `porthole-find-${nextFind++}`;
207
+ const wait = handshaken ? FIND_LIMITS.timeoutMs : timeoutMs + FIND_LIMITS.timeoutMs;
208
+ findsAsked.set(id, {
209
+ params,
210
+ resolve,
211
+ timer: setTimeout(() => settleFind(id, "unsupported"), wait),
212
+ });
213
+ sendFind(id, params);
214
+ });
215
+ /**
216
+ * A new frame's find (after its handshake): the shortcut, and the latest of the queries
217
+ * asked while it loaded (those it superseded answered `"unsupported"`, never sent). A query
218
+ * cleared since it was asked is answered as nothing found, unasked. The query shown before
219
+ * this run is never given again: a run's frame may show other content (forgetFind).
220
+ */
221
+ const giveFind = () => {
222
+ if (!finds) {
223
+ return;
224
+ }
225
+ if (takesShortcut) {
226
+ toFrame(FIND_METHODS.handled, { handled: true });
227
+ }
228
+ if (findShown === null) {
229
+ for (const id of findsAsked.keys()) {
230
+ settleFind(id, { total: 0, active: 0 });
231
+ }
232
+ return;
233
+ }
234
+ const waiting = [...findsAsked];
235
+ for (const [id] of waiting.slice(0, -1)) {
236
+ settleFind(id, "unsupported");
237
+ }
238
+ const last = waiting.at(-1);
239
+ if (last !== undefined) {
240
+ const [id, asked] = last;
241
+ clearTimeout(asked.timer);
242
+ asked.timer = setTimeout(() => settleFind(id, "unsupported"), FIND_LIMITS.timeoutMs);
243
+ sendFind(id, asked.params);
244
+ }
245
+ };
246
+ /**
247
+ * The content the query was asked of is gone (P131): a new run (a reload, a restart after
248
+ * the content navigated away, a new location) or other content. The query is forgotten and
249
+ * what waits is answered `"unsupported"`, so a new page is never searched with the last
250
+ * one's query unless the host asks it again; `clearFrame` also clears the frame running now.
251
+ */
252
+ const forgetFind = (clearFrame) => {
253
+ if (!finds) {
254
+ return;
255
+ }
256
+ const had = findShown !== null || findsAsked.size > 0;
257
+ findShown = null;
258
+ for (const id of findsAsked.keys()) {
259
+ settleFind(id, "unsupported");
260
+ }
261
+ if (clearFrame && had) {
262
+ toFrame(FIND_METHODS.clear, {});
263
+ }
264
+ };
170
265
  const giveAnnotations = () => {
171
266
  if (marks.length > 0) {
172
267
  toFrame(ANNOTATE_METHODS.show, {
@@ -218,7 +313,9 @@ export function createHost(config, options = {}) {
218
313
  };
219
314
  /**
220
315
  * Every box a report carries, clamped to the frame's viewport as it is now (P104): the page
221
- * places the host's own UI nowhere outside its frame.
316
+ * places the host's own UI nowhere outside its frame. A mark's `documentRect` and the
317
+ * document's `scroll` (P132) pass as they were checked: where a mark is in the document,
318
+ * offscreen too, which a clamp would erase; the host clips what it draws from them.
222
319
  */
223
320
  const withinFrame = (report) => {
224
321
  const viewport = frameViewport();
@@ -229,7 +326,7 @@ export function createHost(config, options = {}) {
229
326
  return { ...report, rect: clampRect(report.rect, viewport) };
230
327
  case "anchored":
231
328
  return {
232
- type: "anchored",
329
+ ...report,
233
330
  results: report.results.map((result) => result.rect === undefined
234
331
  ? result
235
332
  : { ...result, rect: clampRect(result.rect, viewport) }),
@@ -313,7 +410,7 @@ export function createHost(config, options = {}) {
313
410
  if (results.length === 0) {
314
411
  return;
315
412
  }
316
- report = { type: "anchored", results };
413
+ report = { ...report, results };
317
414
  break;
318
415
  }
319
416
  case "activated": {
@@ -333,6 +430,94 @@ export function createHost(config, options = {}) {
333
430
  }
334
431
  void through.call("annotate", withinFrame(report));
335
432
  };
433
+ /**
434
+ * What the frame says of find (P131): an answer to a query asked (its own id only, checked,
435
+ * its box clamped to the frame), or a report unasked, taken only while the host asked for it
436
+ * (the shortcut while the host takes it and the page's focus is in the frame; a changed count
437
+ * while a query is shown), then through the bridge's gates.
438
+ */
439
+ const onFind = (raw, through, focused) => {
440
+ if (!isRecord(raw) || raw.jsonrpc !== "2.0") {
441
+ return;
442
+ }
443
+ if (typeof raw.method !== "string") {
444
+ // Its own entries only: an id the host never asked is no answer.
445
+ const id = raw.id;
446
+ if (typeof id !== "string" || !findsAsked.has(id)) {
447
+ return;
448
+ }
449
+ const result = "error" in raw || !("result" in raw) ? null : parseFindResult(raw.result);
450
+ settleFind(id, result === null
451
+ ? "unsupported"
452
+ : result.rect === undefined
453
+ ? result
454
+ : { ...result, rect: clampRect(result.rect, frameViewport()) });
455
+ return;
456
+ }
457
+ if ("id" in raw) {
458
+ return;
459
+ }
460
+ const type = Object.hasOwn(FIND_REPORTS, raw.method) ? FIND_REPORTS[raw.method] : undefined;
461
+ if (type === undefined) {
462
+ return;
463
+ }
464
+ const report = parseFindReport({ ...(isRecord(raw.params) ? raw.params : {}), type });
465
+ if (report === null) {
466
+ void through.call("find", null);
467
+ return;
468
+ }
469
+ if (report.type === "requested") {
470
+ // The person's key in the frame: the page's focus is there (where the platform can tell),
471
+ // so a page can't bring the host's find bar up while the person types beside it.
472
+ let inFrame;
473
+ try {
474
+ inFrame = focused();
475
+ }
476
+ catch {
477
+ inFrame = false;
478
+ }
479
+ if (!takesShortcut || inFrame === false) {
480
+ return;
481
+ }
482
+ }
483
+ else if (findShown === null) {
484
+ return;
485
+ }
486
+ void through.call("find", report);
487
+ };
488
+ const find = {
489
+ query(query, given) {
490
+ if (!finds) {
491
+ return Promise.resolve("unsupported");
492
+ }
493
+ let checked;
494
+ try {
495
+ checked = checkFindQuery(query, given);
496
+ }
497
+ catch (error) {
498
+ return Promise.reject(error);
499
+ }
500
+ if (blankQuery(checked.query)) {
501
+ findShown = null;
502
+ toFrame(FIND_METHODS.clear, {});
503
+ return Promise.resolve({ total: 0, active: 0 });
504
+ }
505
+ findShown = { query: checked.query, caseSensitive: checked.caseSensitive };
506
+ return askFind({ ...checked });
507
+ },
508
+ clear() {
509
+ if (finds) {
510
+ findShown = null;
511
+ toFrame(FIND_METHODS.clear, {});
512
+ }
513
+ },
514
+ takeShortcut(take) {
515
+ if (finds) {
516
+ takesShortcut = take;
517
+ toFrame(FIND_METHODS.handled, { handled: takesShortcut });
518
+ }
519
+ },
520
+ };
336
521
  const needsAnnotate = (operation) => {
337
522
  if (!annotates) {
338
523
  throw new TypeError(`annotations.${operation}: the config doesn't declare annotate`);
@@ -471,6 +656,15 @@ export function createHost(config, options = {}) {
471
656
  case "annotation":
472
657
  emit("annotation", event.report);
473
658
  return;
659
+ case "find":
660
+ if (event.report.type === "requested") {
661
+ emit("findRequested", undefined);
662
+ }
663
+ else {
664
+ const { type: _type, ...result } = event.report;
665
+ emit("findUpdated", result);
666
+ }
667
+ return;
474
668
  }
475
669
  };
476
670
  const closeDoor = () => {
@@ -658,6 +852,9 @@ export function createHost(config, options = {}) {
658
852
  if (annotates) {
659
853
  created.transport.listen((raw) => onAnnotation(raw, opening));
660
854
  }
855
+ if (finds) {
856
+ created.transport.listen((raw) => onFind(raw, opening, () => created.focused?.()));
857
+ }
661
858
  // Whether the page used storage (P111): once per run, the page's word (a count, no more).
662
859
  created.transport.listen((raw) => {
663
860
  if (!storageTold &&
@@ -688,6 +885,7 @@ export function createHost(config, options = {}) {
688
885
  if (!handshaken) {
689
886
  handshaken = true;
690
887
  giveAnnotations();
888
+ giveFind();
691
889
  }
692
890
  emit("initialized", undefined);
693
891
  }
@@ -701,6 +899,8 @@ export function createHost(config, options = {}) {
701
899
  };
702
900
  const run = () => {
703
901
  stop();
902
+ // Each run is a new frame, maybe of other content: it starts with no query (P131).
903
+ forgetFind(false);
704
904
  if (destroyed) {
705
905
  return;
706
906
  }
@@ -781,6 +981,7 @@ export function createHost(config, options = {}) {
781
981
  const controls = {
782
982
  displayId: mount.displayId,
783
983
  annotations,
984
+ find,
784
985
  setTheme(next) {
785
986
  if (themeless) {
786
987
  return;
@@ -824,6 +1025,9 @@ export function createHost(config, options = {}) {
824
1025
  destroyed = true;
825
1026
  stop();
826
1027
  listeners.clear();
1028
+ for (const id of findsAsked.keys()) {
1029
+ settleFind(id, "unsupported");
1030
+ }
827
1031
  },
828
1032
  };
829
1033
  // The adapter's own operations (`setContent` for the shell adapter): forwarded to the frame
@@ -832,6 +1036,10 @@ export function createHost(config, options = {}) {
832
1036
  get(target, key, receiver) {
833
1037
  if (typeof key === "string" && !(key in target) && !BASE_KEYS.has(key)) {
834
1038
  return (...args) => {
1039
+ // Other content (not the content so far, continued): the query was the last one's.
1040
+ if (key === "setContent" && !continues(replay.get(key)?.[0], args[0])) {
1041
+ forgetFind(true);
1042
+ }
835
1043
  replay.delete(key);
836
1044
  replay.set(key, args);
837
1045
  const operation = connection?.[key];
@@ -846,6 +1054,14 @@ export function createHost(config, options = {}) {
846
1054
  },
847
1055
  };
848
1056
  }
1057
+ /**
1058
+ * Whether `next` is the content `before` was, continued (P131): the same, or more of it (the next
1059
+ * part of a streamed page). Nothing given before: anything continues it.
1060
+ */
1061
+ function continues(before, next) {
1062
+ return (before === undefined ||
1063
+ (typeof before === "string" && typeof next === "string" && next.startsWith(before)));
1064
+ }
849
1065
  /** The host's nonce option, read now (`HostOptions.nonce`). */
850
1066
  function nonceOf(nonce) {
851
1067
  const value = typeof nonce === "function" ? nonce() : nonce;
@@ -10,8 +10,9 @@ const KINDS = ["connect", "script", "style", "img", "font", "media"];
10
10
  * conversation and context (`sendPrompt`, `setModelContext`), and the host's data services, which
11
11
  * may be someone else's (`callTool`, `readData`, `subscribeData`: their arguments are the page's).
12
12
  * Not here: the person's own clipboard and disk (`copyText`, `downloadFile`), the host's own UI
13
- * (`annotate`, `resize`, `comments`: the composer is the person's, under the host's duties), and
14
- * what only reads (`user`). `reportError` is one where the config sends errors to the agent.
13
+ * (`annotate`, `find`, `resize`, `comments`: the composer is the person's, under the host's
14
+ * duties), and what only reads (`user`). `reportError` is one where the config sends errors to the
15
+ * agent.
15
16
  */
16
17
  const CARRIERS = [
17
18
  "db",
@@ -1,4 +1,5 @@
1
1
  import type { AnnotateMode, AnnotationMark, AnnotationReport } from "../annotate/types.ts";
2
+ import type { FindOptions, FindResult } from "../find/types.ts";
2
3
  import type { Refused } from "../bridge/refusal.ts";
3
4
  import type { Confirm, CapabilityHandlers, Consent, DataCache, Refusal, Show } from "../bridge/types.ts";
4
5
  import type { CompiledConfig } from "../compile/compile.ts";
@@ -118,6 +119,8 @@ export type HostErrorKind =
118
119
  | "mount"
119
120
  /** An annotation call was refused (an invalid mark, an unknown id). */
120
121
  | "annotations"
122
+ /** A find call was refused (a query too long, options that aren't these: P131). */
123
+ | "find"
121
124
  /**
122
125
  * A frame status (`porthole/notifications/frame-status`) the host didn't take, since it came
123
126
  * from the frame's content, not from a page of Porthole's server (P124): never shown, never an
@@ -246,6 +249,52 @@ export interface DisplayEvents {
246
249
  * content's word: UI hints, never permissions.
247
250
  */
248
251
  readonly annotation: AnnotationReport;
252
+ /**
253
+ * The person pressed Cmd+F (Apple) or Ctrl+F (elsewhere) with the keyboard in the frame (`find`,
254
+ * P131): open the host's find bar. Only while the host takes the shortcut
255
+ * (`find.takeShortcut(true)`, which stops the browser's own find there) and the page's focus is
256
+ * in the frame (where the platform can tell). The content's word: it can say it without the key,
257
+ * or keep the key; open the bar, nothing more.
258
+ */
259
+ readonly findRequested: undefined;
260
+ /**
261
+ * The matches of the query shown changed without the host asking (`find`, P131): the content
262
+ * changed (more of it, or the page's own changes). At most once a second, from an honest shell.
263
+ * The content's word: a find bar's numbers.
264
+ */
265
+ readonly findUpdated: FindResult;
266
+ }
267
+ /**
268
+ * Find in page on a display whose config declares `find` (P131): the host draws the find bar,
269
+ * the frame finds and highlights. The query is posted into the frame, where the content can read
270
+ * it. Where the config doesn't declare `find`, `query` answers `"unsupported"` and the rest do
271
+ * nothing. The shortcut is kept and given to every frame the display runs. The query holds only for
272
+ * the content it was asked of: a new run (`reload()`, a restart after the content navigated away,
273
+ * a new location) or other content (`setContent` with content that doesn't continue what was
274
+ * given) forgets it and answers what waits `"unsupported"`, and nothing is found there until the
275
+ * host asks again: clear your find bar then.
276
+ */
277
+ export interface FindControls {
278
+ /**
279
+ * Finds `query` in the content's text (case-insensitive by default, any spacing), highlights
280
+ * every match, makes one current (the first in view for a new query; the next or previous one
281
+ * with `direction`), scrolls it into view, and answers where they stand. An empty query (or
282
+ * only spaces) clears, and answers no matches. `"unsupported"` where the frame can't find: the
283
+ * config doesn't declare `find`, the frame's shell is older (it answered that it doesn't know
284
+ * the request), it failed, it didn't answer in `FIND_LIMITS.timeoutMs` once it ran, a later
285
+ * query superseded it before it ran (only the latest is searched: show the answer to your latest
286
+ * query only), or the content it was asked of is gone (a new run, other content). Rejects
287
+ * with a `TypeError` for a query longer than `FIND_LIMITS.query`, or options that aren't these.
288
+ */
289
+ query(query: string, options?: FindOptions): Promise<FindResult | "unsupported">;
290
+ /** Removes the highlights and forgets the query (the find bar closed). */
291
+ clear(): void;
292
+ /**
293
+ * Whether the host draws its own find bar for this display (default no): while it does, Cmd+F
294
+ * or Ctrl+F in the frame doesn't open the browser's own find, and the display says
295
+ * `findRequested` instead. A page that handles the key itself keeps it.
296
+ */
297
+ takeShortcut(take: boolean): void;
249
298
  }
250
299
  /**
251
300
  * Annotations on a display whose config declares `annotate` (P053). The host's state is kept and
@@ -263,7 +312,9 @@ export interface AnnotationControls {
263
312
  * Follows one shown mark (P112): while it moves (a scroll, a layout change) the display reports
264
313
  * `{ type: "tracked", id, rect }` at most once per animation frame (60 a second), its box clamped
265
314
  * to the frame, for that mark only; `null` stops. One at a time: a new id replaces the last.
266
- * Throws for an id no shown mark has; a `show` without it, or `clear`, stops it.
315
+ * Throws for an id no shown mark has; a `show` without it, or `clear`, stops it. From a newer
316
+ * shell (P132) each also carries the mark's `documentRect` and the document's `scroll`, so
317
+ * following one mark tells how far the document scrolled, for every mark placed by `documentRect`.
267
318
  */
268
319
  track(id: string | null): void;
269
320
  /** Removes every mark. */
@@ -288,6 +339,8 @@ export interface DisplayControls {
288
339
  on<E extends keyof DisplayEvents>(event: E, listener: (detail: DisplayEvents[E]) => void): () => void;
289
340
  /** Annotations (`annotate`): throws on use where the config doesn't declare it. */
290
341
  readonly annotations: AnnotationControls;
342
+ /** Find in page (`find`, P131): `"unsupported"` where the config doesn't declare it. */
343
+ readonly find: FindControls;
291
344
  /** Runs the content again from the start, in a new frame. */
292
345
  reload(): void;
293
346
  /**