@botiverse/porthole 0.14.8 → 0.14.9

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 (54) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/bridge/bridge.d.ts +6 -0
  3. package/dist/bridge/bridge.js +5 -0
  4. package/dist/check/page-source.js +1 -1
  5. package/dist/config/capabilities.d.ts +16 -2
  6. package/dist/config/capabilities.js +8 -0
  7. package/dist/conformance/harness-source.js +1 -1
  8. package/dist/find/types.d.ts +83 -0
  9. package/dist/find/types.js +29 -0
  10. package/dist/find/validate.d.ts +17 -0
  11. package/dist/find/validate.js +82 -0
  12. package/dist/guide/guide.js +2 -1
  13. package/dist/host/create-host.js +214 -0
  14. package/dist/host/pass-on.js +3 -2
  15. package/dist/host/types.d.ts +51 -0
  16. package/dist/index.d.ts +3 -1
  17. package/dist/index.js +3 -0
  18. package/dist/react/frame.d.ts +43 -0
  19. package/dist/react/frame.js +107 -3
  20. package/dist/react/view.js +2 -0
  21. package/dist/runtime/contract.d.ts +1 -1
  22. package/dist/runtime/contract.js +1 -1
  23. package/dist/shell/annotate.js +2 -95
  24. package/dist/shell/document.d.ts +3 -3
  25. package/dist/shell/document.js +5 -3
  26. package/dist/shell/find.d.ts +82 -0
  27. package/dist/shell/find.js +725 -0
  28. package/dist/shell/runtime.js +4 -1
  29. package/dist/shell/text.d.ts +17 -0
  30. package/dist/shell/text.js +140 -0
  31. package/docs/ADOPTING.md +83 -0
  32. package/docs/ARCHITECTURE.md +10 -3
  33. package/docs/DECISIONS.md +219 -1
  34. package/docs/DESIGN.md +33 -0
  35. package/docs/THREAT_MODEL.md +48 -4
  36. package/docs/insertion-entry-points.md +17 -0
  37. package/package.json +1 -1
  38. package/src/bridge/bridge.ts +7 -0
  39. package/src/config/capabilities.ts +13 -1
  40. package/src/find/types.ts +86 -0
  41. package/src/find/validate.ts +101 -0
  42. package/src/guide/guide.ts +3 -1
  43. package/src/host/create-host.ts +230 -0
  44. package/src/host/pass-on.ts +3 -2
  45. package/src/host/types.ts +52 -0
  46. package/src/index.ts +12 -0
  47. package/src/react/frame.tsx +160 -1
  48. package/src/react/view.tsx +3 -0
  49. package/src/runtime/contract.ts +1 -1
  50. package/src/shell/annotate.ts +3 -95
  51. package/src/shell/document.ts +5 -3
  52. package/src/shell/find.ts +731 -0
  53. package/src/shell/runtime.ts +4 -1
  54. 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, {
@@ -333,6 +428,94 @@ export function createHost(config, options = {}) {
333
428
  }
334
429
  void through.call("annotate", withinFrame(report));
335
430
  };
431
+ /**
432
+ * What the frame says of find (P131): an answer to a query asked (its own id only, checked,
433
+ * its box clamped to the frame), or a report unasked, taken only while the host asked for it
434
+ * (the shortcut while the host takes it and the page's focus is in the frame; a changed count
435
+ * while a query is shown), then through the bridge's gates.
436
+ */
437
+ const onFind = (raw, through, focused) => {
438
+ if (!isRecord(raw) || raw.jsonrpc !== "2.0") {
439
+ return;
440
+ }
441
+ if (typeof raw.method !== "string") {
442
+ // Its own entries only: an id the host never asked is no answer.
443
+ const id = raw.id;
444
+ if (typeof id !== "string" || !findsAsked.has(id)) {
445
+ return;
446
+ }
447
+ const result = "error" in raw || !("result" in raw) ? null : parseFindResult(raw.result);
448
+ settleFind(id, result === null
449
+ ? "unsupported"
450
+ : result.rect === undefined
451
+ ? result
452
+ : { ...result, rect: clampRect(result.rect, frameViewport()) });
453
+ return;
454
+ }
455
+ if ("id" in raw) {
456
+ return;
457
+ }
458
+ const type = Object.hasOwn(FIND_REPORTS, raw.method) ? FIND_REPORTS[raw.method] : undefined;
459
+ if (type === undefined) {
460
+ return;
461
+ }
462
+ const report = parseFindReport({ ...(isRecord(raw.params) ? raw.params : {}), type });
463
+ if (report === null) {
464
+ void through.call("find", null);
465
+ return;
466
+ }
467
+ if (report.type === "requested") {
468
+ // The person's key in the frame: the page's focus is there (where the platform can tell),
469
+ // so a page can't bring the host's find bar up while the person types beside it.
470
+ let inFrame;
471
+ try {
472
+ inFrame = focused();
473
+ }
474
+ catch {
475
+ inFrame = false;
476
+ }
477
+ if (!takesShortcut || inFrame === false) {
478
+ return;
479
+ }
480
+ }
481
+ else if (findShown === null) {
482
+ return;
483
+ }
484
+ void through.call("find", report);
485
+ };
486
+ const find = {
487
+ query(query, given) {
488
+ if (!finds) {
489
+ return Promise.resolve("unsupported");
490
+ }
491
+ let checked;
492
+ try {
493
+ checked = checkFindQuery(query, given);
494
+ }
495
+ catch (error) {
496
+ return Promise.reject(error);
497
+ }
498
+ if (blankQuery(checked.query)) {
499
+ findShown = null;
500
+ toFrame(FIND_METHODS.clear, {});
501
+ return Promise.resolve({ total: 0, active: 0 });
502
+ }
503
+ findShown = { query: checked.query, caseSensitive: checked.caseSensitive };
504
+ return askFind({ ...checked });
505
+ },
506
+ clear() {
507
+ if (finds) {
508
+ findShown = null;
509
+ toFrame(FIND_METHODS.clear, {});
510
+ }
511
+ },
512
+ takeShortcut(take) {
513
+ if (finds) {
514
+ takesShortcut = take;
515
+ toFrame(FIND_METHODS.handled, { handled: takesShortcut });
516
+ }
517
+ },
518
+ };
336
519
  const needsAnnotate = (operation) => {
337
520
  if (!annotates) {
338
521
  throw new TypeError(`annotations.${operation}: the config doesn't declare annotate`);
@@ -471,6 +654,15 @@ export function createHost(config, options = {}) {
471
654
  case "annotation":
472
655
  emit("annotation", event.report);
473
656
  return;
657
+ case "find":
658
+ if (event.report.type === "requested") {
659
+ emit("findRequested", undefined);
660
+ }
661
+ else {
662
+ const { type: _type, ...result } = event.report;
663
+ emit("findUpdated", result);
664
+ }
665
+ return;
474
666
  }
475
667
  };
476
668
  const closeDoor = () => {
@@ -658,6 +850,9 @@ export function createHost(config, options = {}) {
658
850
  if (annotates) {
659
851
  created.transport.listen((raw) => onAnnotation(raw, opening));
660
852
  }
853
+ if (finds) {
854
+ created.transport.listen((raw) => onFind(raw, opening, () => created.focused?.()));
855
+ }
661
856
  // Whether the page used storage (P111): once per run, the page's word (a count, no more).
662
857
  created.transport.listen((raw) => {
663
858
  if (!storageTold &&
@@ -688,6 +883,7 @@ export function createHost(config, options = {}) {
688
883
  if (!handshaken) {
689
884
  handshaken = true;
690
885
  giveAnnotations();
886
+ giveFind();
691
887
  }
692
888
  emit("initialized", undefined);
693
889
  }
@@ -701,6 +897,8 @@ export function createHost(config, options = {}) {
701
897
  };
702
898
  const run = () => {
703
899
  stop();
900
+ // Each run is a new frame, maybe of other content: it starts with no query (P131).
901
+ forgetFind(false);
704
902
  if (destroyed) {
705
903
  return;
706
904
  }
@@ -781,6 +979,7 @@ export function createHost(config, options = {}) {
781
979
  const controls = {
782
980
  displayId: mount.displayId,
783
981
  annotations,
982
+ find,
784
983
  setTheme(next) {
785
984
  if (themeless) {
786
985
  return;
@@ -824,6 +1023,9 @@ export function createHost(config, options = {}) {
824
1023
  destroyed = true;
825
1024
  stop();
826
1025
  listeners.clear();
1026
+ for (const id of findsAsked.keys()) {
1027
+ settleFind(id, "unsupported");
1028
+ }
827
1029
  },
828
1030
  };
829
1031
  // The adapter's own operations (`setContent` for the shell adapter): forwarded to the frame
@@ -832,6 +1034,10 @@ export function createHost(config, options = {}) {
832
1034
  get(target, key, receiver) {
833
1035
  if (typeof key === "string" && !(key in target) && !BASE_KEYS.has(key)) {
834
1036
  return (...args) => {
1037
+ // Other content (not the content so far, continued): the query was the last one's.
1038
+ if (key === "setContent" && !continues(replay.get(key)?.[0], args[0])) {
1039
+ forgetFind(true);
1040
+ }
835
1041
  replay.delete(key);
836
1042
  replay.set(key, args);
837
1043
  const operation = connection?.[key];
@@ -846,6 +1052,14 @@ export function createHost(config, options = {}) {
846
1052
  },
847
1053
  };
848
1054
  }
1055
+ /**
1056
+ * Whether `next` is the content `before` was, continued (P131): the same, or more of it (the next
1057
+ * part of a streamed page). Nothing given before: anything continues it.
1058
+ */
1059
+ function continues(before, next) {
1060
+ return (before === undefined ||
1061
+ (typeof before === "string" && typeof next === "string" && next.startsWith(before)));
1062
+ }
849
1063
  /** The host's nonce option, read now (`HostOptions.nonce`). */
850
1064
  function nonceOf(nonce) {
851
1065
  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
@@ -288,6 +337,8 @@ export interface DisplayControls {
288
337
  on<E extends keyof DisplayEvents>(event: E, listener: (detail: DisplayEvents[E]) => void): () => void;
289
338
  /** Annotations (`annotate`): throws on use where the config doesn't declare it. */
290
339
  readonly annotations: AnnotationControls;
340
+ /** Find in page (`find`, P131): `"unsupported"` where the config doesn't declare it. */
341
+ readonly find: FindControls;
291
342
  /** Runs the content again from the start, in a new frame. */
292
343
  reload(): void;
293
344
  /**
package/dist/index.d.ts CHANGED
@@ -46,6 +46,8 @@ export { lintFiles, type FileContents, type FileFinding } from "./check/files.ts
46
46
  export { admitContent, admitFiles, type AdmitFilesResult, answerGuide, checkTool, guideChanges, guideTool, guideTopics, showTool, type AdmitResult, type JsonSchema, type ToolDefinition, } from "./check/tools.ts";
47
47
  export { writeClipboard } from "./host/clipboard.ts";
48
48
  export { httpLocator, LocateError, servedOrOpaque, type HttpLocatorOptions, type ServedMeta, } from "./host/locator.ts";
49
- export type { AnnotationControls, DisplayControls, DisplayEvents, FrameBlock, FrameOutcome, DisplayHandle, HostOptions, MountOptions, PortholeHost, } from "./host/types.ts";
49
+ export type { AnnotationControls, FindControls, DisplayControls, DisplayEvents, FrameBlock, FrameOutcome, DisplayHandle, HostOptions, MountOptions, PortholeHost, } from "./host/types.ts";
50
50
  export { ANNOTATE_METHODS, ANNOTATION_LIMITS, type AnchorResult, type AnchorState, type AnnotateMode, type AnnotationAnchor, type AnnotationMark, type AnnotationMarkKind, type AnnotationRect, type AnnotationReport, type AnnotationSelector, type CssSelector, type TextPositionSelector, type TextQuoteSelector, } from "./annotate/types.ts";
51
51
  export { parseAnchor, parseRect, parseReport } from "./annotate/validate.ts";
52
+ export { FIND_LIMITS, FIND_METHODS, type FindDirection, type FindOptions, type FindReport, type FindResult, } from "./find/types.ts";
53
+ export { parseFindReport, parseFindResult } from "./find/validate.ts";
package/dist/index.js CHANGED
@@ -53,3 +53,6 @@ export { httpLocator, LocateError, servedOrOpaque, } from "./host/locator.js";
53
53
  // Annotations (P053): anchors, what a frame reports, and the host's checks on both.
54
54
  export { ANNOTATE_METHODS, ANNOTATION_LIMITS, } from "./annotate/types.js";
55
55
  export { parseAnchor, parseRect, parseReport } from "./annotate/validate.js";
56
+ // Find in page (P131): the host's find bar, the frame's matches, and the host's checks on both.
57
+ export { FIND_LIMITS, FIND_METHODS, } from "./find/types.js";
58
+ export { parseFindReport, parseFindResult } from "./find/validate.js";