@weatherboard/annotation 0.4.0 → 0.6.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 (60) hide show
  1. package/ADOPTING.md +97 -6
  2. package/COMPATIBILITY.md +15 -0
  3. package/README.md +33 -8
  4. package/dist/anchor.cjs +1 -1
  5. package/dist/anchor.cjs.map +2 -2
  6. package/dist/anchor.mjs +1 -1
  7. package/dist/anchor.mjs.map +2 -2
  8. package/dist/arming.d.cts +1 -3
  9. package/dist/arming.d.mts +1 -3
  10. package/dist/arming.d.ts +1 -3
  11. package/dist/bootstrap-runtime.d.cts +30 -0
  12. package/dist/bootstrap-runtime.d.mts +30 -0
  13. package/dist/bootstrap-runtime.d.ts +30 -0
  14. package/dist/bootstrap.cjs +2 -0
  15. package/dist/bootstrap.cjs.map +7 -0
  16. package/dist/bootstrap.d.cts +7 -0
  17. package/dist/bootstrap.d.mts +7 -0
  18. package/dist/bootstrap.d.ts +7 -0
  19. package/dist/bootstrap.mjs +2 -0
  20. package/dist/bootstrap.mjs.map +7 -0
  21. package/dist/host.cjs +1 -1
  22. package/dist/host.cjs.map +3 -3
  23. package/dist/host.mjs +1 -1
  24. package/dist/host.mjs.map +3 -3
  25. package/dist/index.cjs +4 -4
  26. package/dist/index.cjs.map +4 -4
  27. package/dist/index.d.cts +1 -1
  28. package/dist/index.d.mts +1 -1
  29. package/dist/index.d.ts +1 -1
  30. package/dist/index.mjs +4 -4
  31. package/dist/index.mjs.map +4 -4
  32. package/dist/markers.cjs +2 -2
  33. package/dist/markers.cjs.map +2 -2
  34. package/dist/markers.mjs +2 -2
  35. package/dist/markers.mjs.map +2 -2
  36. package/dist/protocol.cjs +1 -1
  37. package/dist/protocol.cjs.map +3 -3
  38. package/dist/protocol.d.cts +7 -0
  39. package/dist/protocol.d.mts +7 -0
  40. package/dist/protocol.d.ts +7 -0
  41. package/dist/protocol.mjs +1 -1
  42. package/dist/protocol.mjs.map +3 -3
  43. package/dist/read.cjs +1 -1
  44. package/dist/read.cjs.map +2 -2
  45. package/dist/read.mjs +1 -1
  46. package/dist/read.mjs.map +2 -2
  47. package/dist/selection.cjs +5 -0
  48. package/dist/selection.cjs.map +7 -0
  49. package/dist/selection.d.cts +27 -0
  50. package/dist/selection.d.mts +27 -0
  51. package/dist/selection.d.ts +27 -0
  52. package/dist/selection.mjs +5 -0
  53. package/dist/selection.mjs.map +7 -0
  54. package/dist/session.d.cts +10 -0
  55. package/dist/session.d.mts +10 -0
  56. package/dist/session.d.ts +10 -0
  57. package/dist/transport.d.cts +10 -0
  58. package/dist/transport.d.mts +10 -0
  59. package/dist/transport.d.ts +10 -0
  60. package/package.json +35 -10
package/ADOPTING.md CHANGED
@@ -98,23 +98,40 @@ pointed at production anyway.
98
98
 
99
99
  ```ts
100
100
  // middleware.ts
101
- import { ANNOTATION_ARMED_COOKIE, readAnnotationToken } from "@weatherboard/annotation/protocol";
101
+ import {
102
+ ANNOTATION_ARMED_COOKIE,
103
+ ANNOTATION_ARMED_COOKIES,
104
+ ANNOTATION_TOKEN_PARAMS,
105
+ readAnnotationToken,
106
+ } from "@weatherboard/annotation/protocol";
102
107
 
103
108
  const presented = readAnnotationToken(request.nextUrl.searchParams);
104
109
  const expected = process.env.ANNOTATION_TOKEN;
110
+ const attempted = ANNOTATION_TOKEN_PARAMS.some((name) => request.nextUrl.searchParams.has(name));
111
+ const overHttps = request.nextUrl.protocol === "https:";
105
112
 
106
113
  if (expected && presented && presented.length === expected.length && presented === expected) {
107
- const overHttps = request.nextUrl.protocol === "https:";
108
114
  response.cookies.set(ANNOTATION_ARMED_COOKIE, "1", {
109
115
  httpOnly: false, // the client bundle is what reads it
110
116
  sameSite: overHttps ? "none" : "lax",
111
117
  secure: overHttps,
112
118
  path: "/",
113
119
  });
120
+ } else if (attempted) {
121
+ for (const name of ANNOTATION_ARMED_COOKIES) {
122
+ response.cookies.set(name, "", {
123
+ httpOnly: false,
124
+ sameSite: overHttps ? "none" : "lax",
125
+ secure: overHttps,
126
+ path: "/",
127
+ maxAge: 0,
128
+ expires: new Date(0),
129
+ });
130
+ }
114
131
  }
115
132
  ```
116
133
 
117
- Four details, each of which has cost somebody a day:
134
+ Five details, each of which has cost somebody a day:
118
135
 
119
136
  - **The cookie holds `1`, never the token.** It records that the token was
120
137
  presented once, so navigation inside the frame stays armed without the secret
@@ -127,6 +144,10 @@ Four details, each of which has cost somebody a day:
127
144
  - **…but `None` is only honoured with `Secure`**, and `Secure` is dropped over
128
145
  plain http — so a local `next dev` would set a cookie the browser silently
129
146
  discards. Fall back to `Lax`, which is same-origin anyway.
147
+ - **A fresh rejected token expires both cookie spellings.** A browser may still
148
+ carry a valid cookie from an earlier link. Leaving it in place turns the new
149
+ rejection into an accepted launch and lets the old capture/read/run context
150
+ survive under a different review link.
130
151
 
131
152
  ### First-party, the cookie is an ordinary one — use `armedCookie()` (A-241)
132
153
 
@@ -140,12 +161,63 @@ Do not re-derive the attributes. `@weatherboard/annotation/protocol` exports the
140
161
  cookie itself, so the two halves cannot disagree:
141
162
 
142
163
  ```ts
143
- import { armedCookie, clearedCookie, ANNOTATION_ARMED_COOKIE } from "@weatherboard/annotation/protocol";
164
+ import {
165
+ armedCookie,
166
+ clearedCookie,
167
+ ANNOTATION_ARMED_COOKIES,
168
+ ANNOTATION_TOKEN_PARAMS,
169
+ readAnnotationToken,
170
+ } from "@weatherboard/annotation/protocol";
144
171
 
145
- // after YOUR comparison against YOUR secret has succeeded, and only then:
146
- response.headers.append("set-cookie", armedCookie());
172
+ const presented = readAnnotationToken(request.nextUrl.searchParams);
173
+ const attempted = ANNOTATION_TOKEN_PARAMS.some((name) => request.nextUrl.searchParams.has(name));
174
+ if (presented && presented === process.env.ANNOTATION_TOKEN) {
175
+ response.headers.append("set-cookie", armedCookie());
176
+ } else if (attempted) {
177
+ for (const name of ANNOTATION_ARMED_COOKIES) {
178
+ response.headers.append("set-cookie", clearedCookie(name));
179
+ }
180
+ }
181
+ ```
182
+
183
+ Put the package bootstrap in the first raw script in `<head>`, before styles,
184
+ analytics and hydration:
185
+
186
+ ```tsx
187
+ import { annotationBootstrapScript } from "@weatherboard/annotation/bootstrap";
188
+
189
+ <script dangerouslySetInnerHTML={{ __html: annotationBootstrapScript() }} />
190
+ ```
191
+
192
+ The script synchronously strips `ai_annotate`, its legacy spelling,
193
+ `ai_capture`, `ai_read` and `ai_run`. When middleware accepted the arming link,
194
+ it keeps capture/read/run in this tab's `sessionStorage`, so same-tab routing
195
+ and a hard reload remain armed after the URL is clean. When middleware rejected
196
+ the link, it persists only `{ status: "rejected", capture: "present" | "missing" }`.
197
+ No credential from an unarmed link is stored.
198
+
199
+ The client mount can consume that signal once and report a generic failure:
200
+
201
+ ```ts
202
+ import {
203
+ consumeAnnotationAttempt,
204
+ reportAnnotationStartupFailure,
205
+ } from "@weatherboard/annotation/bootstrap";
206
+
207
+ const attempt = consumeAnnotationAttempt();
208
+ if (attempt?.status === "rejected") {
209
+ return reportAnnotationStartupFailure("rejected-arming");
210
+ }
211
+ if (attempt?.capture === "missing") {
212
+ return reportAnnotationStartupFailure("missing-capture");
213
+ }
147
214
  ```
148
215
 
216
+ The reporter owns one host, `#ai-annotation-startup-status`, and returns a
217
+ cleanup function. Import and mount failures use `"import-failed"` and
218
+ `"mount-failed"`. All copy is package-owned and contains no token or product
219
+ name.
220
+
149
221
  It takes no value argument on purpose — the cookie holds a marker, never the
150
222
  token, and the first bullet above is the reason. The page half calls
151
223
  `readArming()`, which reads that cookie, strips the tokens out of the URL with
@@ -490,3 +562,22 @@ misattributed.
490
562
  Every step above is a thing that, when absent, produces no error, no warning and
491
563
  no log line — only an absence. When you are debugging, prefer the check that
492
564
  distinguishes causes over the check that confirms your guess.
565
+
566
+ ## Host-owned contextual feedback
567
+
568
+ `@weatherboard/annotation/selection` exposes `relativePoint`,
569
+ `captureTextSelection`, `resolveTextSelection` and `prepareTextSelections` without
570
+ arming the developer SDK, mounting UI or sending network requests. Production
571
+ hosts such as Pitch own authentication, capture intent, target persistence and
572
+ permission-scoped reads. Import this subpath directly; importing the root SDK
573
+ still observes its existing production restrictions.
574
+
575
+ Mark authored text containers with `data-annotation-text="host-field-path"`.
576
+ Capture returns UTF-16 offsets, exact quote and bounded prefix/suffix using CRLF
577
+ normalisation only. A field path is evidence qualified by a host content revision,
578
+ not a permanent identity. Pass whether content is unchanged when resolving;
579
+ edited content requires a unique quote/context match. Missing or ambiguous
580
+ locations must remain reviewable as unplaced feedback. `prepareTextSelections`
581
+ shares one bounded text-map snapshot across annotations in a layout frame; discard
582
+ it after content or layout changes. Neither helper reads application controls as
583
+ authored text or persists DOM nodes.
package/COMPATIBILITY.md CHANGED
@@ -95,3 +95,18 @@ whoever drops it, in the same change, and not by whoever finds out.
95
95
 
96
96
  `0.x` while the wire protocol is still moving. **1.0 is the statement that a
97
97
  hundred consumers can rely on it**, not a way to look finished.
98
+
99
+ ### Additive selection subpath (A-391)
100
+
101
+ The workspace adds `./selection` with ESM, CommonJS and TypeScript exports.
102
+ Existing SDK wire versions and production arming rules are unchanged. Pitch uses
103
+ the workspace source; external consumers need a subsequently published package
104
+ version containing this entry point. The tarball smoke test verifies its exports;
105
+ this feature does not itself publish an npm release.
106
+
107
+ ### Additive bootstrap subpath and hosted-mode metadata (A-1375)
108
+
109
+ Version 0.6.0 adds `./bootstrap` for synchronous credential stripping,
110
+ per-tab continuation and token-free startup status. It also adds the exact
111
+ `x-weatherboard-annotation-mode: first-party` constants to `./protocol`. The
112
+ wire payload version and all existing names remain unchanged.
package/README.md CHANGED
@@ -20,23 +20,37 @@ adding to your supply chain.
20
20
  npm i @weatherboard/annotation
21
21
  ```
22
22
 
23
- ## Six entry points
23
+ ## Eight entry points
24
24
 
25
25
  They are split by **who imports them**, not by topic.
26
26
 
27
27
  | Import | Runs where | For |
28
28
  |---|---|---|
29
29
  | `@weatherboard/annotation` | The browser | The page SDK — overlay, target resolution, state collection, screenshots |
30
+ | `@weatherboard/annotation/bootstrap` | The browser, before hydration | Immediate URL stripping, arming reads and token-free startup status |
30
31
  | `@weatherboard/annotation/protocol` | Anywhere, no DOM | The wire names and the two readers. This is what a middleware imports |
31
32
  | `@weatherboard/annotation/host` | The reviewing console | The parent half of the channel |
32
33
  | `@weatherboard/annotation/anchor` | The browser | `resolveAnchor` — where a capture's marker goes, or why it goes nowhere |
33
34
  | `@weatherboard/annotation/read` | The browser | `createAnnotationReader` — the captures already made on this page |
34
35
  | `@weatherboard/annotation/markers` | The browser | The marker layer and its panel |
36
+ | `@weatherboard/annotation/selection` | The browser | Authored-content text/point selection and placement helpers |
35
37
 
36
- The last three are separate for one reason: they run only in a product that
37
- RENDERS markers, and a product that merely captures should not pay for them. They
38
- are subpaths rather than a tree-shaking promise for the same reason `/protocol`
39
- is.
38
+ The final four remain separate because products can choose capture, marker
39
+ rendering and authored-content selection independently. A product that merely
40
+ captures should not pay for readers, marker UI or selection helpers. They are
41
+ subpaths rather than a tree-shaking promise for the same reason `/protocol` is.
42
+
43
+ `/bootstrap` is also a subpath rather than a tree-shaking promise. Put
44
+ `annotationBootstrapScript()` in the first raw script in `<head>`, then keep the
45
+ root entry behind a dynamic import. A normal visitor pays for URL and cookie
46
+ reads without downloading the toolbar or state collector.
47
+
48
+ Package-authored browser UI keeps its styles zero-dependency too. Declare
49
+ colour, spacing and radius literals once as local `--ai-*` custom properties,
50
+ then consume them with `var()` in the same style string. Do not import a
51
+ product's design tokens: a toolbar or startup notice runs inside somebody
52
+ else's page, where those names and values are not ours. New runtime surfaces
53
+ must pass `pnpm gyde:check`; do not add their findings to the allowance ledger.
40
54
 
41
55
  `/protocol` is a subpath rather than a tree-shaking promise on purpose: an edge
42
56
  middleware is often bundled as CJS, and CJS does not shake. Importing the root
@@ -63,11 +77,21 @@ right is yours, because only you hold the secret.
63
77
 
64
78
  ```ts
65
79
  // middleware.ts
66
- import { ANNOTATION_ARMED_COOKIE, readAnnotationToken } from "@weatherboard/annotation/protocol";
80
+ import {
81
+ ANNOTATION_ARMED_COOKIE,
82
+ ANNOTATION_ARMED_COOKIES,
83
+ ANNOTATION_TOKEN_PARAMS,
84
+ readAnnotationToken,
85
+ } from "@weatherboard/annotation/protocol";
67
86
 
68
87
  const token = readAnnotationToken(request.nextUrl.searchParams);
69
- if (token !== undefined && token === process.env.ANNOTATION_TOKEN) {
88
+ const attempted = ANNOTATION_TOKEN_PARAMS.some((name) => request.nextUrl.searchParams.has(name));
89
+ if (token !== null && token === process.env.ANNOTATION_TOKEN) {
70
90
  response.cookies.set(ANNOTATION_ARMED_COOKIE, "1", { httpOnly: false, sameSite: "lax" });
91
+ } else if (attempted) {
92
+ for (const name of ANNOTATION_ARMED_COOKIES) {
93
+ response.cookies.set(name, "", { path: "/", maxAge: 0, expires: new Date(0) });
94
+ }
71
95
  }
72
96
  ```
73
97
 
@@ -75,7 +99,8 @@ if (token !== undefined && token === process.env.ANNOTATION_TOKEN) {
75
99
  for an absent *or empty* parameter. An empty token compared with `===` against
76
100
  your secret is a rejection; an empty token treated as present is an app armed
77
101
  with the empty string, which fails later and reads like a bad secret rather than
78
- a missing one.
102
+ a missing one. A fresh rejected attempt must expire **both** supported cookie
103
+ spellings so an already-armed browser cannot reuse its previous session.
79
104
 
80
105
  ## Source refs
81
106
 
package/dist/anchor.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var f=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var R=(e,n)=>{for(var t in n)f(e,t,{get:n[t],enumerable:!0})},b=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of E(n))!T.call(e,r)&&r!==t&&f(e,r,{get:()=>n[r],enumerable:!(o=x(n,r))||o.enumerable});return e};var y=e=>b(f({},"__esModule",{value:!0}),e);var L={};R(L,{anchorFromTarget:()=>S,resolveAnchor:()=>A,tallyAnchors:()=>_});module.exports=y(L);var u="data-src";function g(e){return e.selection==="region"?"region":"element"}var m=8;function s(e){if(!e)return null;let n=e.lastIndexOf(":");if(n<=0)return null;let t=e.lastIndexOf(":",n-1);if(t<=0)return null;let o=e.slice(0,t),r=Number(e.slice(t+1,n)),i=Number(e.slice(n+1));return!o||!Number.isFinite(r)||!Number.isFinite(i)?null:{file:o,line:r,column:i}}function d(e,n=m){let t=[],o=e;for(;o&&t.length<n;){let r=s(o.getAttribute(u));if(r){let i=t[t.length-1];i&&i.file===r.file&&i.line===r.line||t.push(r)}o=o.parentElement}return t}function h(e){let n=e;for(;n;){if(s(n.getAttribute(u)))return n;n=n.parentElement}return null}function l(e,n){return e.file!==n.file||e.line!==n.line?!1:e.column===void 0||n.column===void 0?!0:e.column===n.column}function k(e,n){if(e.length===0)return!1;if(e.length<m){if(n.length!==e.length)return!1}else if(n.length<e.length)return!1;return e.every((t,o)=>{let r=n[o];return r!==void 0&&l(t,r)})}function N(e,n){let t={file:e.file,line:e.line};e.column!==void 0&&(t.column=e.column);let o=n.querySelectorAll(`[${u}]`),r=[];for(let i=0;i<o.length;i++){let a=o[i],c=s(a.getAttribute(u));if(!c||!l(t,c))continue;let p=s(h(a.parentElement)?.getAttribute(u)??null);p&&l(p,c)||r.push(a)}return r}function A(e,n){switch(e.kind){case"route":{if(!e.path)return"none";let t=n.location?.pathname;return!t||t!==e.path?"none":n.body??"none"}case"dom-path":{if(!e.path)return"none";let t;try{t=n.querySelectorAll(e.path)}catch{return"none"}return t.length===0?"none":t.length>1?"ambiguous":t[0]}case"source-ref":{if(e.chain.length===0)return"none";let t=N(e,n).filter(o=>k(e.chain,d(o)));return t.length===0?"none":t.length>1?"ambiguous":t[0]}default:return"none"}}function S(e,n={}){let t=()=>n.path===void 0?{kind:"route"}:{kind:"route",path:n.path};if(g(e)==="region")return t();let o=e.sourceChain??[],r=o[0],i=e.source??r;if(i&&r&&l(i,r)){let a={kind:"source-ref",file:i.file,line:i.line,chain:o};return i.column!==void 0&&(a.column=i.column),n.ordinal!==void 0&&(a.ordinal=n.ordinal),a}return e.domPath?{kind:"dom-path",path:e.domPath}:t()}function _(e,n){let t={total:e.length,placed:0,ambiguous:0,unresolved:0};for(let o of e){let r=A(o,n);r==="ambiguous"?t.ambiguous+=1:r==="none"?t.unresolved+=1:t.placed+=1}return t}
1
+ "use strict";var f=Object.defineProperty;var x=Object.getOwnPropertyDescriptor;var E=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var R=(e,n)=>{for(var t in n)f(e,t,{get:n[t],enumerable:!0})},b=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of E(n))!T.call(e,r)&&r!==t&&f(e,r,{get:()=>n[r],enumerable:!(o=x(n,r))||o.enumerable});return e};var y=e=>b(f({},"__esModule",{value:!0}),e);var O={};R(O,{anchorFromTarget:()=>S,resolveAnchor:()=>A,tallyAnchors:()=>_});module.exports=y(O);var s="data-src";function g(e){return e.selection==="region"?"region":"element"}var m=8;function u(e){if(!e)return null;let n=e.lastIndexOf(":");if(n<=0)return null;let t=e.lastIndexOf(":",n-1);if(t<=0)return null;let o=e.slice(0,t),r=Number(e.slice(t+1,n)),i=Number(e.slice(n+1));return!o||!Number.isFinite(r)||!Number.isFinite(i)?null:{file:o,line:r,column:i}}function d(e,n=m){let t=[],o=e;for(;o&&t.length<n;){let r=u(o.getAttribute(s));if(r){let i=t[t.length-1];i&&i.file===r.file&&i.line===r.line||t.push(r)}o=o.parentElement}return t}function h(e){let n=e;for(;n;){if(u(n.getAttribute(s)))return n;n=n.parentElement}return null}function l(e,n){return e.file!==n.file||e.line!==n.line?!1:e.column===void 0||n.column===void 0?!0:e.column===n.column}function k(e,n){if(e.length===0)return!1;if(e.length<m){if(n.length!==e.length)return!1}else if(n.length<e.length)return!1;return e.every((t,o)=>{let r=n[o];return r!==void 0&&l(t,r)})}function N(e,n){let t={file:e.file,line:e.line};e.column!==void 0&&(t.column=e.column);let o=n.querySelectorAll(`[${s}]`),r=[];for(let i=0;i<o.length;i++){let a=o[i],c=u(a.getAttribute(s));if(!c||!l(t,c))continue;let p=u(h(a.parentElement)?.getAttribute(s)??null);p&&l(p,c)||r.push(a)}return r}function A(e,n){switch(e.kind){case"route":{if(!e.path)return"none";let t=n.location?.pathname;return!t||t!==e.path?"none":n.body??"none"}case"dom-path":{if(!e.path)return"none";let t;try{t=n.querySelectorAll(e.path)}catch{return"none"}return t.length===0?"none":t.length>1?"ambiguous":t[0]}case"source-ref":{if(e.chain.length===0)return"none";let t=N(e,n).filter(o=>k(e.chain,d(o)));return t.length===0?"none":t.length>1?"ambiguous":t[0]}default:return"none"}}function S(e,n={}){let t=()=>n.path===void 0?{kind:"route"}:{kind:"route",path:n.path};if(g(e)==="region")return t();let o=e.sourceChain??[],r=o[0],i=e.source??r;if(i&&r&&l(i,r)){let a={kind:"source-ref",file:i.file,line:i.line,chain:o};return i.column!==void 0&&(a.column=i.column),n.ordinal!==void 0&&(a.ordinal=n.ordinal),a}return e.domPath?{kind:"dom-path",path:e.domPath}:t()}function _(e,n){let t={total:e.length,placed:0,ambiguous:0,unresolved:0};for(let o of e){let r=A(o,n);r==="ambiguous"?t.ambiguous+=1:r==="none"?t.unresolved+=1:t.placed+=1}return t}
2
2
  //# sourceMappingURL=anchor.cjs.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/anchor.ts", "../src/protocol.ts", "../src/target.ts"],
4
- "sourcesContent": ["/**\n * Putting a capture back on the element it came from (A-275).\n *\n * ===========================================================================\n * WHY THIS IS A PACKAGE EXPORT AND NOT A MEASUREMENT HARNESS\n * ===========================================================================\n *\n * The slice that produced this file was originally scoped as \"measure whether\n * anchoring can work\", with rendering explicitly out of scope. That was wrong,\n * and the reason is A-268's shape: resolving an anchor against a live DOM **is**\n * the marker-placement code. Measuring with one implementation and shipping\n * another later gives two implementations of one primitive, and two\n * implementations of one primitive is a way for them to disagree \u2014 which is the\n * principle `capture-token.ts` already names, and the defect A-268 already was.\n *\n * So `resolveAnchor` is the export the marker layer (A-277) imports, and the\n * measurement in A-275 is that same function called on staging pages.\n *\n * **The measurement and the decision it produced are in\n * `docs/decisions/a-275-anchor-placement.md`**, and `anchor-measure.mjs` runs it\n * again. Read the decision before changing anything here.\n *\n * Every figure in this file is quoted from that document with its denominator,\n * or is a property of the code rather than a measurement and says so. That rule\n * exists because it was broken here: two comments claimed `MEASURED: 105 of 200`\n * \u2014 a stale figure, from a SAMPLE the decision document explicitly retires, for a\n * branch it was not even a statistic about. **A number labelled MEASURED that no\n * checked-in artifact can reproduce is worse than no number**, which this\n * package's own size-budget note already says about a different number.\n *\n * The headline, so it is not paraphrased loosely elsewhere: **139 of 546\n * annotated elements on the staging home page resolve to exactly one element,\n * and 0 of 546 resolve to the wrong one.** Every plausible improvement to the\n * first figure is a way of trading the second one away.\n *\n * ===========================================================================\n * WHY `source_file:source_line` IS NOT AN ANCHOR\n * ===========================================================================\n *\n * A source ref identifies a **component**, not an **instance**. Six cards\n * rendered from one `<PubCard/>` all carry the same `data-src`, and the file and\n * line say nothing about which one a reviewer clicked.\n *\n * The first draft of this scheme fixed that with an ordinal \u2014 the element's\n * index among the matches, in document order. A reviewer showed that this is\n * **wrong rather than merely incomplete**, and the argument is worth keeping\n * because it is not obvious:\n *\n * An ordinal is POSITIONAL. Delete the second card, and a capture anchored to\n * ordinal 3 resolves to what used to be card 4. Exactly one match. A marker is\n * drawn, on the wrong element, and NOTHING ANYWHERE HAS A COMPLAINT \u2014 a\n * \"cannot be confidently placed\" rule never fires, because the failure IS a\n * confident single match.\n *\n * A marker on the wrong element does not degrade this feature, it inverts it:\n * the entire value of putting the conversation on the component is that\n * *\"this one, here\"* stops being ambiguous.\n *\n * ===========================================================================\n * SO: A DISCONFIRMING SIGNAL, NOT A UNIQUENESS TEST\n * ===========================================================================\n *\n * Uniqueness is satisfied by every silent failure above, so uniqueness cannot be\n * the test. What the anchor stores instead is the **whole source chain** \u2014\n * `TargetInfo.sourceChain`, every `data-src` from the clicked element up to the\n * root, innermost first, which the capture has carried since A-33 and which the\n * ingest has persisted since A-287 \u2014 and a candidate must match the chain, not\n * just the leaf.\n *\n * A reordered sibling still matches (its ancestors did not change). An element\n * that MOVED does not (its ancestors did). The chain is a claim the DOM can\n * contradict, and that is the only kind of claim worth storing.\n *\n * It does not make repeated siblings distinguishable, and it is not supposed to:\n * two identical cards in one list have identical chains, so an anchor to either\n * resolves `\"ambiguous\"`. That is the SAFE failure \u2014 the marker is withheld and\n * the count says so \u2014 and it is the one an ordinal would have converted into a\n * confident wrong answer.\n *\n * ===========================================================================\n * A TAGGED UNION FROM DAY ONE\n * ===========================================================================\n *\n * Not speculative generality: two capture kinds that cannot carry a usable\n * source ref ALREADY SHIP. `TargetInfo.domPath` is the documented fallback for a\n * page whose elements have no refs, and region captures (A-179) exist, where\n * `sourceChain` is the siblings a rectangle crossed rather than ancestors \u2014\n * a chain that contains nothing of itself and would be silently read as an\n * ancestor chain by anything that assumed one shape.\n *\n * Retrofitting a union onto flat columns after a year of rows is the expensive\n * version of this, and the read response (A-276) is additive-only forever, so\n * `kind` is what lets an older SDK skip a marker it does not understand rather\n * than misplace it.\n */\n\nimport {\n collectSourceChain,\n findAnnotatedAncestor,\n parseSourceRef,\n MAX_CHAIN,\n SRC_ATTR,\n type ElementLike,\n} from \"./target\";\nimport { selectionOf, type SourceRef, type TargetInfo } from \"./protocol\";\n\n/**\n * An element identified by the source location that rendered it, plus the chain\n * of source locations above it.\n *\n * `chain` is innermost-first and INCLUDES the leaf, exactly as\n * `collectSourceChain` produces it \u2014 one array, not a leaf plus a tail, because\n * two representations of one list is a way for them to disagree about whether\n * entry zero is the element or its parent.\n */\nexport interface SourceRefAnchor {\n kind: \"source-ref\";\n file: string;\n line: number;\n column?: number;\n chain: SourceRef[];\n /**\n * The element's index among the leaf-matching candidates at capture time.\n *\n * **Recorded, and deliberately never used to select.** It is here because\n * knowing \"this was the 3rd of 6\" is genuinely useful when a human is looking\n * at an unresolved anchor and asking what happened \u2014 and it is *not* here as a\n * tie-break, for the reason set out at length in this file's header. If you\n * are about to reach for it to turn an `\"ambiguous\"` into an element, that is\n * the bug this whole scheme was rewritten to avoid; `anchor.test.ts` has a\n * test that fails if you do.\n */\n ordinal?: number;\n}\n\n/** A CSS-ish path, for elements no build transform gave a ref. */\nexport interface DomPathAnchor {\n kind: \"dom-path\";\n path: string;\n}\n\n/**\n * \"Something on THIS page.\"\n *\n * First-class rather than a fallback of last resort: it is the honest home for a\n * region capture, for a canvas, for a PDF, and for any product that is not a JSX\n * tree.\n *\n * ===========================================================================\n * `path` IS NOT OPTIONAL DECORATION \u2014 IT IS WHAT MAKES \"THIS PAGE\" MEAN ANYTHING\n * ===========================================================================\n *\n * The first version of this interface had no fields at all and `resolveAnchor`\n * returned `doc.body` unconditionally, with a comment calling it *\"always\n * placeable\"*. A reviewer pointed out that this reintroduces, through the route\n * branch, exactly the failure the source-ref scheme was rewritten to prevent:\n *\n * A capture taken on `/guides/a` resolves CONFIDENTLY on `/guides/b`. One\n * match, marker drawn, wrong page, counted as `placed`. No signal anywhere.\n *\n * That is not a rate to be estimated. `return doc.body` has no input but the\n * document, so under it **every** route anchor placed on **every** page it was\n * shown \u2014 100%, by construction, and there is nothing to measure. The reason it\n * matters is `payload.page.route`: it is the matched PATTERN rather than the\n * URL, so \"the page this came from\" was never pinned in the first place. And\n * `anchorFromTarget` sends every region capture down this branch, so it is the\n * common case rather than the edge.\n *\n * The measured neighbour is the SOURCE-REF branch meeting the same problem:\n * 414 anchors captured on one guide page resolve **identically** after a real\n * navigation to another guide page \u2014 161 placed, 253 ambiguous, 0 refused, the\n * same three numbers on both \u2014 recorded with its method and denominator in\n * `docs/decisions/a-275-anchor-placement.md` \u00A7 *The limit this does not fix*.\n * It is a different branch and a different number, cited here as evidence that\n * the pattern-not-URL problem is real, not as a figure for this one.\n *\n * So a route anchor carries the RESOLVED path it was captured on, and\n * `resolveAnchor` refuses when the document is somewhere else.\n *\n * ===========================================================================\n * AND ABSENT MEANS \"CANNOT PLACE\", NEVER \"PLACE ANYWAY\"\n * ===========================================================================\n *\n * `path` is optional because the field is newer than the wire, and the read-back\n * plan's versioning rule for exactly this case is that a new anchor field is\n * optional and **absent means cannot place** \u2014 the precedent `selection?:` set.\n * A route anchor with no `path`, or a document that cannot say where it is,\n * therefore resolves to `\"none\"`.\n *\n * That is a deliberate choice to under-place rather than mis-place, and it costs\n * nothing today because no route anchor has ever been stored: markers have not\n * shipped. It would be a real cost if this were retrofitted a year from now,\n * which is the argument for doing it here.\n *\n * WHAT IT DOES NOT FIX: a SOURCE-REF anchor still resolves happily on a\n * different `[id]` of the same route pattern \u2014 the markup is identical, so there\n * is nothing for the chain to disagree with, and no amount of anchor design\n * closes it. That one is the read endpoint's (A-276): scope the query on the\n * resolved path, not on `route`. Stated here because an unstated limit gets read\n * as a covered one.\n */\nexport interface RouteAnchor {\n kind: \"route\";\n /** `location.pathname` at capture time. Absent means the anchor cannot be placed. */\n path?: string;\n}\n\nexport type Anchor = SourceRefAnchor | DomPathAnchor | RouteAnchor;\n\n/**\n * Where a marker goes, or why it does not go anywhere.\n *\n * Three outcomes and not two, because `\"none\"` and `\"ambiguous\"` are different\n * facts about the page and a caller counting them together loses the one that\n * says the markup moved.\n */\nexport type AnchorResolution<E extends ElementLike = ElementLike> = E | \"none\" | \"ambiguous\";\n\n/**\n * The narrowest slice of `Document` this module reads. A real `Document`\n * satisfies it, which `anchor.test.ts` asserts at compile time.\n *\n * `location` is here for the route branch above. It is optional because a parsed\n * fixture has no location, and a document that cannot say where it is makes a\n * route anchor unplaceable rather than placeable-by-default.\n */\nexport interface DocumentLike<E extends ElementLike = ElementLike> {\n querySelectorAll(selectors: string): ArrayLike<E>;\n body?: E | null;\n location?: { pathname: string } | null;\n}\n\nfunction sameRef(a: SourceRef, b: SourceRef): boolean {\n if (a.file !== b.file || a.line !== b.line) return false;\n /**\n * Column is compared only when BOTH sides have one.\n *\n * It is optional in `SourceRef` and the ingest drops a malformed one rather\n * than defaulting it (A-287), so an absent column means \"not recorded\" and\n * never \"column zero\". Treating a missing column as a mismatch would make\n * every capture from a build that omits it permanently unplaceable.\n */\n if (a.column === undefined || b.column === undefined) return true;\n return a.column === b.column;\n}\n\n/**\n * Does this candidate's live chain still match the one recorded at capture time?\n *\n * The length rule is the half that does the work, and it is asymmetric on\n * purpose:\n *\n * - A recorded chain SHORTER than `MAX_CHAIN` is complete \u2014 it ran out of\n * ancestors, not out of budget \u2014 so the live chain must be exactly as long.\n * An element that gained an annotated ancestor (a conditional wrapper, a\n * portal boundary, a new layout) is a moved element and must not match.\n * - A recorded chain AT `MAX_CHAIN` was truncated by `collectSourceChain`, so\n * all that can honestly be required is that the recorded frames are a prefix\n * of the live ones.\n *\n * THE SECOND CASE IS NOT WHERE THE REAL WEAKNESS LIVES, and an earlier version\n * of this comment said it was. An ancestor inserted above the eighth frame is\n * invisible because `collectSourceChain` never walked that far \u2014 the frame is\n * missing from the recorded chain AND from the live one, so no comparison here\n * can see it. MEASURED: making this length rule strict for truncated chains too\n * changes no test; raising `MAX_CHAIN` changes four.\n *\n * `anchor.test.ts` pins that ceiling under the name\n * *\"MAX_CHAIN truncation hides an ancestor added above the eighth frame\"*, so it\n * is an executable fact rather than a paragraph.\n */\nfunction chainMatches(recorded: SourceRef[], live: SourceRef[]): boolean {\n if (recorded.length === 0) return false;\n if (recorded.length < MAX_CHAIN) {\n if (live.length !== recorded.length) return false;\n } else if (live.length < recorded.length) {\n return false;\n }\n return recorded.every((ref, i) => { const other = live[i]; return other !== undefined && sameRef(ref, other); });\n}\n\n/**\n * Candidates for a source-ref anchor: every element whose OWN `data-src` is the\n * anchor's leaf, minus the nested repeats.\n *\n * One JSX element frequently produces several nested DOM nodes carrying the same\n * ref. `collectSourceChain` already collapses those when it builds a chain; not\n * collapsing them here would make a perfectly unambiguous element report\n * `\"ambiguous\"` against copies of itself \u2014 a false unplaceable, which is the\n * quiet way a scheme gets abandoned for being useless rather than for being\n * wrong. The outermost node of a repeat group is kept, because that is the one\n * whose box covers the component.\n */\nfunction leafCandidates<E extends ElementLike>(anchor: SourceRefAnchor, doc: DocumentLike<E>): E[] {\n const leaf: SourceRef = { file: anchor.file, line: anchor.line };\n if (anchor.column !== undefined) leaf.column = anchor.column;\n\n const all = doc.querySelectorAll(`[${SRC_ATTR}]`);\n const matched: E[] = [];\n for (let i = 0; i < all.length; i++) {\n const el = all[i] as E;\n const own = parseSourceRef(el.getAttribute(SRC_ATTR));\n if (!own || !sameRef(leaf, own)) continue;\n\n const parentRef = parseSourceRef(\n findAnnotatedAncestor(el.parentElement)?.getAttribute(SRC_ATTR) ?? null,\n );\n if (parentRef && sameRef(parentRef, own)) continue; // a nested repeat of the same ref\n\n matched.push(el);\n }\n return matched;\n}\n\n/**\n * Resolve an anchor against a document.\n *\n * Pure: it reads the document and returns an element or a refusal, and it never\n * mutates, measures layout, or draws anything. That is what lets the same\n * function be a unit test over a checked-in HTML fixture, a number in a\n * measurement run, and the marker layer's placement call.\n *\n * A `kind` this version does not recognise resolves to `\"none\"` \u2014 the read\n * response is additive-only forever (A-276), so an SDK meeting a newer console\n * must SKIP a marker it cannot place rather than guess at one.\n */\nexport function resolveAnchor<E extends ElementLike>(\n anchor: Anchor,\n doc: DocumentLike<E>,\n): AnchorResolution<E> {\n switch (anchor.kind) {\n case \"route\": {\n /**\n * Both sides must say where they are, and they must agree. See\n * `RouteAnchor` for why this is a refusal rather than a default.\n */\n if (!anchor.path) return \"none\";\n const here = doc.location?.pathname;\n if (!here || here !== anchor.path) return \"none\";\n return doc.body ?? \"none\";\n }\n\n case \"dom-path\": {\n if (!anchor.path) return \"none\";\n let found: ArrayLike<E>;\n try {\n found = doc.querySelectorAll(anchor.path);\n } catch {\n /**\n * `domPath` is documented as a hint for a human and explicitly not a\n * selector we promise to re-resolve \u2014 hashed class names can contain\n * characters that make it an invalid selector, and an invalid selector\n * THROWS rather than matching nothing. Refusing is right; letting a\n * `SyntaxError` out of a placement call would take the whole marker\n * layer down over one bad capture.\n */\n return \"none\";\n }\n if (found.length === 0) return \"none\";\n if (found.length > 1) return \"ambiguous\";\n return found[0] as E;\n }\n\n case \"source-ref\": {\n if (anchor.chain.length === 0) return \"none\";\n const matched = leafCandidates(anchor, doc).filter((el) =>\n chainMatches(anchor.chain, collectSourceChain(el)),\n );\n if (matched.length === 0) return \"none\";\n if (matched.length > 1) return \"ambiguous\";\n return matched[0] as E;\n }\n\n default:\n return \"none\";\n }\n}\n\nexport interface AnchorFromTargetOptions {\n /** Document order index among leaf-matching candidates, when the caller has a document. */\n ordinal?: number;\n /**\n * `location.pathname` at capture time \u2014 the RESOLVED path, not the route\n * pattern.\n *\n * Pass it. A route anchor built without it can never be placed, by design; see\n * `RouteAnchor`. It is optional here rather than required because\n * `anchorFromTarget` is also called for element captures, where it is unused.\n */\n path?: string;\n}\n\n/**\n * Build the anchor for a capture.\n *\n * The capture side of the same primitive, here rather than in `target.ts` so the\n * union and the function that produces it cannot drift apart.\n *\n * **A region capture becomes a `route` anchor.** Its `sourceChain` is the\n * siblings a rectangle crossed, which contain nothing of each other; handing\n * that to `chainMatches` would compare a sibling list against an ancestor list\n * and refuse \u2014 the right answer for the wrong reason, and one that would report\n * every region capture as \"the markup moved\". Route-level is what a region\n * capture actually means: something on this page, in that area.\n */\nexport function anchorFromTarget(\n target: Pick<TargetInfo, \"selection\" | \"source\" | \"sourceChain\" | \"domPath\">,\n options: AnchorFromTargetOptions = {},\n): Anchor {\n const routeAnchor = (): RouteAnchor =>\n options.path === undefined ? { kind: \"route\" } : { kind: \"route\", path: options.path };\n\n if (selectionOf(target) === \"region\") return routeAnchor();\n\n const chain = target.sourceChain ?? [];\n const head = chain[0];\n const leaf = target.source ?? head;\n if (leaf && head && sameRef(leaf, head)) {\n const anchor: SourceRefAnchor = {\n kind: \"source-ref\",\n file: leaf.file,\n line: leaf.line,\n chain,\n };\n if (leaf.column !== undefined) anchor.column = leaf.column;\n if (options.ordinal !== undefined) anchor.ordinal = options.ordinal;\n return anchor;\n }\n\n if (target.domPath) return { kind: \"dom-path\", path: target.domPath };\n return routeAnchor();\n}\n\n/**\n * The counts a caller reports, so that \"0 markers\" is never the same string as\n * \"working, nothing here\" (rule 1 of the read-back plan).\n *\n * ===========================================================================\n * `wrong` IS NOT IN HERE AND CANNOT BE, AND THAT IS A GAP RATHER THAN A DESIGN\n * ===========================================================================\n *\n * Whether a resolved element is the RIGHT element is not knowable from the live\n * page alone \u2014 it takes a before/after comparison, which is what A-275's\n * mutation battery does and what no runtime caller can do.\n *\n * So `placed` means \"resolved to exactly one element\", NOT \"resolved\n * correctly\", and there is one measured channel where those differ: a\n * source-ref anchor captured on one `[id]` resolves on another `[id]` of the\n * same route pattern, because the two pages are structurally identical.\n *\n * MEASURED at **161 of 414 anchors** placing on a different `[id]` of the same\n * route pattern, with zero refusals \u2014 indistinguishable, count for count, from\n * resolving against the page they were captured on. The method, the denominator\n * and the pages are in `docs/decisions/a-275-anchor-placement.md` \u00A7 *The limit\n * this does not fix*, and `node anchor-measure.mjs --url \u2026 --compare-url \u2026`\n * re-runs it in one command. Nothing in this module can detect it; the\n * fix is for the read endpoint to scope on the resolved path (A-276), so a\n * caller must not read `placed` as a correctness figure until it does.\n *\n * The route branch closes its own half of that (`RouteAnchor.path`). This\n * comment is the record that the source-ref half is still open.\n */\nexport interface AnchorTally {\n total: number;\n placed: number;\n ambiguous: number;\n unresolved: number;\n}\n\nexport function tallyAnchors<E extends ElementLike>(\n anchors: readonly Anchor[],\n doc: DocumentLike<E>,\n): AnchorTally {\n const tally: AnchorTally = { total: anchors.length, placed: 0, ambiguous: 0, unresolved: 0 };\n for (const anchor of anchors) {\n const result = resolveAnchor(anchor, doc);\n if (result === \"ambiguous\") tally.ambiguous += 1;\n else if (result === \"none\") tally.unresolved += 1;\n else tally.placed += 1;\n }\n return tally;\n}\n", "/**\n * The annotation postMessage protocol (A-36).\n *\n * Mirrors `docs/contracts/types.ts`. That file is the\n * cross-component contract; this is the runtime copy the product bundle ships,\n * because the product cannot import from a docs directory. Changing a shape\n * here is a change to both \u2014 say so in the PR.\n */\n\nexport const SDK_VERSION = \"1\";\n\n/**\n * ===========================================================================\n * THE ATTRIBUTES \u2014 THE OTHER WIRE (A-186)\n * ===========================================================================\n *\n * These live in `protocol.ts`, not in `target.ts` where they are read, because\n * they are a contract between TWO PACKAGES that a consumer installs separately:\n * `@weatherboard/annotation-next` WRITES them at build time and this package\n * READS them at runtime. Two spellings of `data-src` is not a bug anybody\n * catches \u2014 the transform runs, the attributes appear, and every capture comes\n * back with no source ref at all, which is indistinguishable from the transform\n * not running.\n *\n * `annotation-next` imports these from `@weatherboard/annotation/protocol`\n * rather than declaring its own, which is why the subpath has no DOM in it: a\n * build tool importing the page SDK to learn two strings would be absurd.\n */\nexport const SRC_ATTR = \"data-src\";\nexport const NAME_ATTR = \"data-src-name\";\n\nexport interface SourceRef {\n file: string;\n line: number;\n column?: number;\n}\n\nexport interface BuildInfo {\n /** Mandatory. Feedback not pinned to a revision is ambiguous the moment someone merges. */\n gitSha: string;\n /**\n * Where this build came from.\n *\n * `\"development\"` was added in A-37, when the SDK was first mounted in a\n * real app and the two halves turned out not to agree: `resolveBuildInfo` in\n * `resolveBuildInfo` in the product's own Next config package \u2014 the module\n * that stamps the build-env variable, and the only producer of this field \u2014\n * emits\n * `production | preview | development`, mirroring `VERCEL_ENV`. This union\n * instead offered `\"staging\"`, which nothing produces: a staging deploy IS a\n * Vercel preview and reports itself as one. Widening rather than forcing the\n * mount to lie: a locally-annotated build calling itself a preview would put\n * someone's laptop in the corpus as though it were a deployment.\n */\n env: \"production\" | \"preview\" | \"staging\" | \"development\";\n branch?: string;\n /** Set when reviewing an agent's preview deploy, so feedback routes to that run's session. */\n previewRunId?: string;\n}\n\nexport interface ConsoleEntry {\n level: \"error\" | \"warn\";\n message: string;\n stack?: string;\n at: string;\n}\n\nexport interface NetworkEntry {\n url: string;\n method: string;\n status: number;\n at: string;\n}\n\nexport interface TargetInfo {\n /**\n * What the reviewer selected \u2014 one element, or an area (A-179).\n *\n * -------------------------------------------------------------------------\n * WHY THIS EXISTS RATHER THAN BEING INFERRED\n * -------------------------------------------------------------------------\n *\n * A region capture and an element capture are the same SHAPE: a bounding box,\n * a chain of source refs, a DOM path. Nothing in the values distinguishes\n * them, and the two mean opposite things about the chain \u2014 for an element it\n * is ANCESTORS, innermost first, so entry two contains entry one; for a\n * region it is SIBLINGS the rectangle happened to cross, which contain\n * nothing of each other.\n *\n * A reader that guesses will describe a region's siblings as a call-site\n * chain, which is a confident false statement about the page. `describeCapture`\n * hands that description to a model that writes acceptance criteria from it.\n *\n * -------------------------------------------------------------------------\n * WHY IT IS OPTIONAL, AND WHY ABSENT MEANS `element`\n * -------------------------------------------------------------------------\n *\n * The two halves of this protocol live in different repositories and deploy\n * independently (see the note on the legacy parameter names below). Every\n * capture in the store today, and every capture from a product bundle that\n * predates region selection, has no such field \u2014 and all of them are element\n * captures. Absent therefore has to mean `element`, or this field would\n * retroactively make the entire history ambiguous.\n *\n * Required-with-a-default would have the same effect and a worse failure: an\n * older bundle omits it, the type says it is there, and every reader believes\n * a value nobody sent.\n */\n selection?: \"element\" | \"region\";\n source?: SourceRef;\n /**\n * Every `data-src` from the clicked element up to the document root, innermost\n * first \u2014 an addition to the contract, and the reason is structural.\n *\n * Only host elements carry a ref (A-33), so `source` names the file that\n * *writes the markup*. For a composed design-system component that is\n * `MediaCard.tsx`, not the `GuideDetailCard.tsx` a human would say they\n * clicked. The chain is what lets the PM agent and the coding agent see both,\n * and pick the call site over the leaf when the feedback is about content\n * rather than the component itself.\n */\n sourceChain?: SourceRef[];\n componentName?: string;\n /** CSS selector fallback, for when no ancestor carries a ref at all. */\n domPath: string;\n boundingBox: { x: number; y: number; w: number; h: number };\n /** Truncated to 200 characters. */\n textContent?: string;\n}\n\n/**\n * What kind of capture this is, with the default applied once (A-189).\n *\n * `selection` is optional and **absent means `element`** \u2014 every capture taken\n * before A-179, and everything the managed product's live bundle emits today,\n * has no such field. Any other default would retroactively reclassify the whole\n * history as regions, silently.\n *\n * A function rather than a documented convention because the default is the\n * kind of thing two readers implement slightly differently and neither notices:\n * one writes `=== \"region\"`, another writes `?? \"element\"`, a third forgets and\n * treats `undefined` as falsy in a branch that meant something else. This is\n * the protocol's answer, and `compatibility.test.ts` replays every recorded\n * payload through it.\n */\nexport function selectionOf(target: Pick<TargetInfo, \"selection\">): \"element\" | \"region\" {\n return target.selection === \"region\" ? \"region\" : \"element\";\n}\n\nexport interface AnnotationPayload {\n schemaVersion: 1;\n capturedAt: string;\n build: BuildInfo;\n page: {\n url: string;\n /** The matched route pattern, not the resolved URL. */\n route: string;\n viewport: { w: number; h: number; dpr: number };\n userAgent: string;\n };\n target: TargetInfo;\n state: {\n consoleErrors: ConsoleEntry[];\n failedRequests: NetworkEntry[];\n featureFlags: Record<string, unknown>;\n };\n screenshot?: { dataUrl: string; region: \"element\" | \"viewport\" };\n /** The human's words, verbatim. The parent frame fills this in; we never rewrite it. */\n comment: string;\n}\n\nexport type ParentToFrame =\n | { type: \"annotate:enable\" }\n | { type: \"annotate:disable\" }\n | { type: \"annotate:ping\" };\n\nexport type FrameToParent =\n | { type: \"annotate:ready\"; sdkVersion: string; build: BuildInfo }\n | { type: \"annotate:hover\"; target: TargetInfo }\n | { type: \"annotate:capture\"; payload: AnnotationPayload }\n | { type: \"annotate:cancel\" };\n\nconst PARENT_TYPES = new Set([\"annotate:enable\", \"annotate:disable\", \"annotate:ping\"]);\n\n/**\n * Is this a message we recognise?\n *\n * Origin is checked separately and first \u2014 a well-formed message from the wrong\n * origin is the case this guard must not be trusted to catch.\n */\nexport function isParentMessage(data: unknown): data is ParentToFrame {\n if (typeof data !== \"object\" || data === null) return false;\n const type = (data as { type?: unknown }).type;\n return typeof type === \"string\" && PARENT_TYPES.has(type);\n}\n\n/**\n * Reject wildcards outright rather than treating them as \"any origin\".\n *\n * `postMessage(msg, \"*\")` broadcasts the payload to whatever happens to be\n * framing us, and an annotation payload carries page content, console errors and\n * failed request URLs. The spec's rule is no wildcards in either direction; this\n * makes it impossible to configure one by accident.\n */\nexport function assertConcreteOrigin(origin: string): string {\n if (!origin || origin === \"*\") {\n throw new Error(\n \"[annotation] a concrete parent origin is required; '*' would broadcast \" +\n \"annotation payloads to any embedder.\",\n );\n }\n return origin;\n}\n\n/**\n * The query parameter that arms the SDK in a managed product, and the cookie\n * that records it.\n *\n * THESE LIVE IN THE PROTOCOL BECAUSE THE TWO HALVES ARE NOW IN DIFFERENT\n * REPOSITORIES. The managed product's middleware looks for the parameter and\n * sets the cookie; the management app appends the parameter and the SDK reads\n * the cookie. While both halves were one monorepo, a test could read the other\n * side's source and assert the strings matched \u2014 that gate does not survive a\n * repository split, and a mismatch produces no error at all: the frame loads,\n * the cookie is never set, the SDK never boots, and the reviewer sees \"waiting\n * for the page to announce itself\" with nothing to go on.\n *\n * So they stop being two spellings that agree and become one exported\n * constant. A managed product that imports this package cannot drift from it.\n */\nexport const ANNOTATION_TOKEN_PARAM = \"ai_annotate\";\nexport const ANNOTATION_ARMED_COOKIE = \"ai_annotate_armed\";\n\n/**\n * The CAPTURE token's query parameter (A-240).\n *\n * -------------------------------------------------------------------------\n * WHY IT IS HERE AND NOT WHERE IT IS WRITTEN\n * -------------------------------------------------------------------------\n *\n * A second name on the same wire, and a second credential \u2014 see\n * `docs/plans/first-party-annotation.md` \u00A7 *Authentication*. `ai_annotate`\n * answers *should this page offer an annotation UI at all*; this one answers\n * *may this capture become an issue*. Different secrets, different lifetimes,\n * different blast radii, and deliberately not folded into one token.\n *\n * It lives beside `ANNOTATION_TOKEN_PARAM` for that constant's own reason,\n * stated at length above: the console WRITES it into a deep link and the\n * product's bundle READS it, the two halves ship from different repositories,\n * and a mismatch produces no error anywhere \u2014 the reviewer writes a post-it,\n * clicks send, and the ingest rejects an unsigned capture. One exported\n * constant is the only thing that makes those two spellings unable to drift.\n *\n * It has no legacy spelling because it has never had another one: nothing has\n * shipped it yet. It is exported here BEFORE its writer needs it precisely so\n * the writer never has a reason to spell it itself.\n */\nexport const CAPTURE_TOKEN_PARAM = \"ai_capture\";\n\n/**\n * The run under review, when the console knows of one (A-241).\n *\n * Third name on the same wire, here for the reason the two above are: the\n * console writes it and the product's bundle reads it, from two repositories.\n * `apps/manager/src/lib/request-changes.ts` spells it itself today and its own\n * comment asks for exactly this \u2014 the constant to move into the package so the\n * writer has no reason to spell it. **That deletion is not this slice's**\n * (A-243/A-244 are merged and settled), so for now there are two definitions of\n * one string, and `protocol.test.ts` is the only thing standing between them\n * and a silent divergence. Nothing about it is signed: the ingest already\n * treats it as attacker-supplied text and files on it rather than routing on it.\n */\nexport const REVIEW_RUN_PARAM = \"ai_run\";\n\n/**\n * The READ token's query parameter (A-277).\n *\n * ===========================================================================\n * WHY THE MARKER LAYER GETS ITS OWN CREDENTIAL AND NOT `ai_capture`\n * ===========================================================================\n *\n * Fourth name on the same wire, and the reason it is a fourth is A-276's\n * disclosure decision rather than tidiness. The capture token is minted for\n * WRITING and lives four hours so a reviewer can work through a session; reusing\n * it for the read would make one leaked deep link a write capability AND a read\n * capability over every reviewer's comments on that origin for the same window.\n * The scope is a signed field, `verifyCaptureToken` requires an expectation at\n * every call site, and the read endpoint refuses a write claim \u2014 so handing\n * `ai_capture` to the reader does not degrade to a read, it fails.\n *\n * The read claim's TTL is ONE hour rather than four (`READ_TOKEN_TTL_S`), which\n * is the practical consequence a reader of this constant should know: the\n * toolbar outlives the markers, so a reviewer who leaves a tab open all\n * afternoon will find the count line saying it cannot read before they find the\n * Send button broken. That is the intended ordering \u2014 the shorter credential is\n * the one that discloses other people's words.\n *\n * Exported here for the reason the three above are: the console writes it into a\n * deep link and the product's bundle reads it, from two repositories, and a\n * mismatch produces no error anywhere \u2014 just a page with no markers, which is\n * indistinguishable from nine other causes.\n */\nexport const READ_TOKEN_PARAM = \"ai_read\";\n\n/**\n * The arming cookie, as a `Set-Cookie` value (A-241).\n *\n * ===========================================================================\n * IT GOT SIMPLER BY MOVING FIRST-PARTY, AND THAT IS THE WHOLE POINT\n * ===========================================================================\n *\n * Framed, this had to be `SameSite=None; Secure` with no `Partitioned` \u2014 a\n * genuine cross-site cookie, which A-211 records would have broken on its own\n * under Chrome's third-party cookie work, independently of the auth problem\n * that killed the frame. Top-level at the product's own origin it is an\n * ordinary cookie and none of that applies.\n *\n * Each attribute, and why:\n *\n * - **`SameSite=Lax`.** The reviewer arrives by clicking *Request changes* in\n * the console, which is a top-level cross-site GET navigation \u2014 the one case\n * `Lax` still sends on. `Strict` would withhold the cookie on that very first\n * render, so the toolbar would be missing on the page the link opened and\n * appear only after an internal click; that reads as a broken deploy.\n * - **`Secure`.** It is a marker rather than a credential, but a marker that\n * travels in clear is a marker an attacker on the path can set.\n * - **`Path=/`.** Arming survives the reviewer navigating the whole app, which\n * is the point of a cookie rather than a URL parameter.\n * - **No `Max-Age` / `Expires`.** Session-scoped: closing the tab disarms.\n *\n * ===========================================================================\n * WHAT IS *NOT* HERE: `HttpOnly`, AND THE TOKEN\n * ===========================================================================\n *\n * No `HttpOnly`, deliberately. Page script both READS this (`isAnnotationArmed`\n * decides whether a toolbar exists) and CLEARS it (*Done* disarms). An\n * `HttpOnly` arming cookie makes *Done* impossible from the page, which is the\n * one control the reviewer has.\n *\n * That is affordable only because THE VALUE IS A MARKER AND NEVER THE TOKEN.\n * The value is a constant and there is no argument that supplies one: the\n * middleware compares the URL parameter against its secret and then calls this,\n * and what it stores is *yes*, not *what was presented*. The single parameter\n * is the cookie's NAME, and it exists only so a product mid-migration can write\n * the legacy spelling \u2014 it is not a value slot wearing a different label, and\n * `arming.test.ts` pins which side of the `=` it lands on.\n *\n * This is a shape argument, not a guarantee about callers. Nothing stops a\n * determined caller passing a secret as the name; what the signature removes is\n * the ACCIDENT \u2014 the middleware author with a verified token in hand and one\n * parameter available, reaching for the obvious.\n */\nexport const ANNOTATION_ARMED_VALUE = \"1\";\n\nexport function armedCookie(name: string = ANNOTATION_ARMED_COOKIE): string {\n return `${name}=${ANNOTATION_ARMED_VALUE}; Path=/; SameSite=Lax; Secure`;\n}\n\n/**\n * The same cookie, expired \u2014 what *Done* and a disarm write.\n *\n * `Max-Age=0` AND an `Expires` in the past, because they are read by different\n * things and the pair is what every browser honours. The path must match the\n * one set above or the browser stores a second cookie and the first survives \u2014\n * a *Done* button that does nothing and reports success.\n */\nexport function clearedCookie(name: string): string {\n return `${name}=; Path=/; SameSite=Lax; Secure; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT`;\n}\n\n/**\n * The names these used to have (A-98).\n *\n * -------------------------------------------------------------------------\n * WHY THE RENAME, AND WHY IT COULD NOT JUST BE DONE\n * -------------------------------------------------------------------------\n *\n * They were `pits_annotate` and `pits_annotate_armed` \u2014 one managed product's\n * initialism, in a contract every managed product's bundle has to implement.\n * Onboarding a second product meant asking an unrelated codebase to adopt the\n * first product's name in its cookies and its query strings. That is the bug\n * A-98 is about, and it is a bug in a wire protocol rather than in a variable\n * name, which is what makes it expensive.\n *\n * The two halves live in DIFFERENT REPOSITORIES and deploy independently. A\n * clean rename is therefore a breaking change to every product bundle\n * simultaneously, and its failure mode is silence: the frame loads, the cookie\n * is never set, the SDK never boots, and the reviewer sees \"waiting for the\n * page to announce itself\" with nothing to go on. Nothing throws, nothing logs,\n * and the natural reading is that the agent broke the site.\n *\n * -------------------------------------------------------------------------\n * THE MIGRATION: READ BOTH, WRITE BOTH, THEN STOP WRITING THE OLD ONE\n * -------------------------------------------------------------------------\n *\n * 1. **Now.** Every reader accepts either name. Every writer emits BOTH, so a\n * product still running the old bundle arms on the legacy name and one\n * running the new bundle arms on the new one. Deploy order stops mattering,\n * which is the whole point \u2014 there is no window in which a reviewer sees the\n * silent failure above.\n * 2. **After every managed product's bundle is on this version** (A-102). Drop\n * the legacy names from the writers, then from the readers. Two steps, not\n * one: a reader that stops accepting the old name before the writers stop\n * emitting it re-creates the outage in the other direction.\n *\n * The legacy names are exported rather than inlined so the deletion in step 2\n * is `git grep LEGACY_` rather than an archaeology exercise.\n */\nexport const LEGACY_ANNOTATION_TOKEN_PARAM = \"pits_annotate\";\nexport const LEGACY_ANNOTATION_ARMED_COOKIE = \"pits_annotate_armed\";\n\n/**\n * ===========================================================================\n * AND THE NAMES ARE NOT CHANGING AGAIN FOR THE PUBLISHED PACKAGE (A-184)\n * ===========================================================================\n *\n * When this becomes `@weatherboard/annotation` the obvious next thought is that\n * the wire names should match the package \u2014 `weatherboard_annotate`. They\n * should not, and the reason is the migration described above rather than\n * taste.\n *\n * That migration is STILL IN FLIGHT. Readers accept both spellings; writers\n * emit both; step 2 waits on every managed product's bundle being current.\n * A third spelling introduced now does not replace the second, it joins it:\n * every reader accepts three names, every writer emits three, and the window in\n * which a product can be on any of them widens instead of closing.\n *\n * The cost is not the code. It is that each rename buys another instance of the\n * failure this file exists to prevent \u2014 the frame loads, the cookie is never\n * set, the SDK never boots, and the reviewer sees \"waiting for the page to\n * announce itself\" with nothing to go on. Twice is a migration. Three times is\n * a habit, and the third one would be paid by consumers who never asked for\n * either.\n *\n * `ai_annotate` is already product-neutral, which was the entire point of A-98.\n * A published package needs names that name no product; it does not need names\n * that name the package. Nobody reading a query string cares which npm scope\n * the library came from.\n *\n * The one real objection is collision: `ai_` is a common prefix and some other\n * tool could plausibly use it. That is survivable by construction \u2014 arming\n * requires the parameter to carry a token the product compares exactly, so a\n * coincidental `?ai_annotate=` from an unrelated tool arms nothing. A colliding\n * COOKIE cannot false-positive either; `isAnnotationArmed` matches on the\n * delimiter rather than by substring, for exactly this reason.\n *\n * If a rename is ever genuinely warranted, it happens ONCE, after step 2 has\n * landed and the reader accepts one name again \u2014 not layered on top of an\n * unfinished one.\n */\n\n/** Both spellings of the query parameter, current first. */\nexport const ANNOTATION_TOKEN_PARAMS = [\n ANNOTATION_TOKEN_PARAM,\n LEGACY_ANNOTATION_TOKEN_PARAM,\n] as const;\n\n/** Both spellings of the cookie, current first. */\nexport const ANNOTATION_ARMED_COOKIES = [\n ANNOTATION_ARMED_COOKIE,\n LEGACY_ANNOTATION_ARMED_COOKIE,\n] as const;\n\n/**\n * Whether a cookie jar carries the armed cookie, under either name.\n *\n * Delimiter-aware rather than a substring test: a cookie named\n * `not_ai_annotate_armed`, or another cookie whose VALUE contains the name,\n * satisfies `includes` \u2014 and arming an annotation channel on a coincidence is\n * not a failure anyone would think to look for.\n */\nexport function isAnnotationArmed(cookie: string): boolean {\n return cookie\n .split(\";\")\n .some((entry) => {\n const trimmed = entry.trimStart();\n return ANNOTATION_ARMED_COOKIES.some((name) => trimmed.startsWith(`${name}=`));\n });\n}\n\n/**\n * The arming token from a URL's query string, under either name.\n *\n * Current name wins when both are present. They should never disagree \u2014 the\n * management app writes both from one value \u2014 but if they ever do, the one this\n * version of the protocol owns is the one to believe.\n */\nexport function readAnnotationToken(params: URLSearchParams): string | null {\n for (const name of ANNOTATION_TOKEN_PARAMS) {\n const value = params.get(name);\n if (value !== null && value.length > 0) return value;\n }\n return null;\n}\n", "import { NAME_ATTR, SRC_ATTR, type SourceRef, type TargetInfo } from \"./protocol\";\n\n/**\n * Turning a clicked DOM element into something a coding agent can act on.\n *\n * Everything here is written against the narrowest possible slice of the DOM so\n * it can be tested without a browser \u2014 see `ElementLike`. The parts that need a\n * real browser (hit-testing, layout) live in `sdk.ts`.\n */\n\n/**\n * Re-exported, not declared. They moved to `protocol.ts` (A-186) because the\n * build transform in `@weatherboard/annotation-next` writes what this file\n * reads, and the two packages install separately. Kept exported from here so\n * every existing importer is unaffected.\n */\nexport { NAME_ATTR, SRC_ATTR };\n\nexport const MAX_TEXT = 200;\n/** Deep trees are common; a chain long enough to be useless is not worth sending. */\nexport const MAX_CHAIN = 8;\n\n/** The subset of `Element` this module reads. */\nexport interface ElementLike {\n tagName: string;\n id?: string;\n getAttribute(name: string): string | null;\n parentElement: ElementLike | null;\n classList?: { value?: string } | ArrayLike<string>;\n textContent?: string | null;\n}\n\n/**\n * Parse `path/to/File.tsx:42:7` into its parts.\n *\n * Split from the right: the line and column never contain a colon, and a path\n * conceivably might. Returns null rather than a half-parsed ref \u2014 a ref we\n * cannot read is worse than no ref, because downstream will believe it.\n */\nexport function parseSourceRef(value: string | null): SourceRef | null {\n if (!value) return null;\n\n const colIdx = value.lastIndexOf(\":\");\n if (colIdx <= 0) return null;\n const lineIdx = value.lastIndexOf(\":\", colIdx - 1);\n if (lineIdx <= 0) return null;\n\n const file = value.slice(0, lineIdx);\n const line = Number(value.slice(lineIdx + 1, colIdx));\n const column = Number(value.slice(colIdx + 1));\n\n if (!file || !Number.isFinite(line) || !Number.isFinite(column)) return null;\n return { file, line, column };\n}\n\n/**\n * Every source ref from `el` upwards, innermost first.\n *\n * Consecutive duplicates are collapsed: one JSX element often produces several\n * nested DOM nodes carrying the same ref, and repeating it says nothing.\n */\nexport function collectSourceChain(el: ElementLike | null, max = MAX_CHAIN): SourceRef[] {\n const chain: SourceRef[] = [];\n let node: ElementLike | null = el;\n\n while (node && chain.length < max) {\n const ref = parseSourceRef(node.getAttribute(SRC_ATTR));\n if (ref) {\n const prev = chain[chain.length - 1];\n const isRepeat = prev && prev.file === ref.file && prev.line === ref.line;\n if (!isRepeat) chain.push(ref);\n }\n node = node.parentElement;\n }\n\n return chain;\n}\n\n/** The nearest ancestor (or self) carrying a ref, which is the element a human means. */\nexport function findAnnotatedAncestor(el: ElementLike | null): ElementLike | null {\n let node: ElementLike | null = el;\n while (node) {\n if (parseSourceRef(node.getAttribute(SRC_ATTR))) return node;\n node = node.parentElement;\n }\n return null;\n}\n\nfunction classTokens(el: ElementLike): string[] {\n const list = el.classList as { value?: string } | undefined;\n const raw = typeof list?.value === \"string\" ? list.value : \"\";\n return raw.split(/\\s+/).filter(Boolean);\n}\n\n/**\n * A CSS-ish path to the element, used only when no ancestor carries a ref.\n *\n * Deliberately not guaranteed unique. It is a hint for a human reading the\n * payload, not a selector we promise to re-resolve \u2014 StyleX class names are\n * hashed and change between builds, so a path that looks precise would be\n * quietly wrong on the next deploy. IDs are kept because they survive; classes\n * are capped at two for readability.\n */\nexport function domPath(el: ElementLike | null, maxDepth = 6): string {\n const parts: string[] = [];\n let node: ElementLike | null = el;\n\n while (node && parts.length < maxDepth) {\n const tag = (node.tagName || \"\").toLowerCase();\n if (!tag || tag === \"html\") break;\n\n let part = tag;\n if (node.id) {\n // An id is unique on the page, so nothing above it adds information.\n parts.unshift(`${tag}#${node.id}`);\n return parts.join(\" > \");\n }\n const classes = classTokens(node).slice(0, 2);\n if (classes.length > 0) part += `.${classes.join(\".\")}`;\n parts.unshift(part);\n\n if (tag === \"body\") break;\n node = node.parentElement;\n }\n\n return parts.join(\" > \");\n}\n\n/** Collapse whitespace and truncate, so the payload carries a label rather than a page. */\nexport function summariseText(text: string | null | undefined): string | undefined {\n if (!text) return undefined;\n const collapsed = text.replace(/\\s+/g, \" \").trim();\n if (!collapsed) return undefined;\n return collapsed.length > MAX_TEXT ? `${collapsed.slice(0, MAX_TEXT - 1)}\u2026` : collapsed;\n}\n\nexport interface ResolveTargetOptions {\n boundingBox: { x: number; y: number; w: number; h: number };\n}\n\n/**\n * Build the `TargetInfo` for a clicked or hovered element.\n *\n * `source` is the nearest ref, which names the file that writes the markup \u2014\n * for a composed design-system component that is the design-system file, not\n * the call site. `sourceChain` carries the rest so the agent can choose.\n */\nexport function resolveTarget(el: ElementLike, options: ResolveTargetOptions): TargetInfo {\n const annotated = findAnnotatedAncestor(el);\n const chain = collectSourceChain(el);\n const source = chain[0];\n\n const target: TargetInfo = {\n domPath: domPath(el),\n boundingBox: options.boundingBox,\n };\n\n if (source) target.source = source;\n if (chain.length > 0) target.sourceChain = chain;\n\n const componentName = annotated?.getAttribute(NAME_ATTR);\n if (componentName) target.componentName = componentName;\n\n const text = summariseText(el.textContent);\n if (text) target.textContent = text;\n\n return target;\n}\n"],
5
- "mappings": "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",
4
+ "sourcesContent": ["/**\n * Putting a capture back on the element it came from (A-275).\n *\n * ===========================================================================\n * WHY THIS IS A PACKAGE EXPORT AND NOT A MEASUREMENT HARNESS\n * ===========================================================================\n *\n * The slice that produced this file was originally scoped as \"measure whether\n * anchoring can work\", with rendering explicitly out of scope. That was wrong,\n * and the reason is A-268's shape: resolving an anchor against a live DOM **is**\n * the marker-placement code. Measuring with one implementation and shipping\n * another later gives two implementations of one primitive, and two\n * implementations of one primitive is a way for them to disagree \u2014 which is the\n * principle `capture-token.ts` already names, and the defect A-268 already was.\n *\n * So `resolveAnchor` is the export the marker layer (A-277) imports, and the\n * measurement in A-275 is that same function called on staging pages.\n *\n * **The measurement and the decision it produced are in\n * `docs/decisions/a-275-anchor-placement.md`**, and `anchor-measure.mjs` runs it\n * again. Read the decision before changing anything here.\n *\n * Every figure in this file is quoted from that document with its denominator,\n * or is a property of the code rather than a measurement and says so. That rule\n * exists because it was broken here: two comments claimed `MEASURED: 105 of 200`\n * \u2014 a stale figure, from a SAMPLE the decision document explicitly retires, for a\n * branch it was not even a statistic about. **A number labelled MEASURED that no\n * checked-in artifact can reproduce is worse than no number**, which this\n * package's own size-budget note already says about a different number.\n *\n * The headline, so it is not paraphrased loosely elsewhere: **139 of 546\n * annotated elements on the staging home page resolve to exactly one element,\n * and 0 of 546 resolve to the wrong one.** Every plausible improvement to the\n * first figure is a way of trading the second one away.\n *\n * ===========================================================================\n * WHY `source_file:source_line` IS NOT AN ANCHOR\n * ===========================================================================\n *\n * A source ref identifies a **component**, not an **instance**. Six cards\n * rendered from one `<PubCard/>` all carry the same `data-src`, and the file and\n * line say nothing about which one a reviewer clicked.\n *\n * The first draft of this scheme fixed that with an ordinal \u2014 the element's\n * index among the matches, in document order. A reviewer showed that this is\n * **wrong rather than merely incomplete**, and the argument is worth keeping\n * because it is not obvious:\n *\n * An ordinal is POSITIONAL. Delete the second card, and a capture anchored to\n * ordinal 3 resolves to what used to be card 4. Exactly one match. A marker is\n * drawn, on the wrong element, and NOTHING ANYWHERE HAS A COMPLAINT \u2014 a\n * \"cannot be confidently placed\" rule never fires, because the failure IS a\n * confident single match.\n *\n * A marker on the wrong element does not degrade this feature, it inverts it:\n * the entire value of putting the conversation on the component is that\n * *\"this one, here\"* stops being ambiguous.\n *\n * ===========================================================================\n * SO: A DISCONFIRMING SIGNAL, NOT A UNIQUENESS TEST\n * ===========================================================================\n *\n * Uniqueness is satisfied by every silent failure above, so uniqueness cannot be\n * the test. What the anchor stores instead is the **whole source chain** \u2014\n * `TargetInfo.sourceChain`, every `data-src` from the clicked element up to the\n * root, innermost first, which the capture has carried since A-33 and which the\n * ingest has persisted since A-287 \u2014 and a candidate must match the chain, not\n * just the leaf.\n *\n * A reordered sibling still matches (its ancestors did not change). An element\n * that MOVED does not (its ancestors did). The chain is a claim the DOM can\n * contradict, and that is the only kind of claim worth storing.\n *\n * It does not make repeated siblings distinguishable, and it is not supposed to:\n * two identical cards in one list have identical chains, so an anchor to either\n * resolves `\"ambiguous\"`. That is the SAFE failure \u2014 the marker is withheld and\n * the count says so \u2014 and it is the one an ordinal would have converted into a\n * confident wrong answer.\n *\n * ===========================================================================\n * A TAGGED UNION FROM DAY ONE\n * ===========================================================================\n *\n * Not speculative generality: two capture kinds that cannot carry a usable\n * source ref ALREADY SHIP. `TargetInfo.domPath` is the documented fallback for a\n * page whose elements have no refs, and region captures (A-179) exist, where\n * `sourceChain` is the siblings a rectangle crossed rather than ancestors \u2014\n * a chain that contains nothing of itself and would be silently read as an\n * ancestor chain by anything that assumed one shape.\n *\n * Retrofitting a union onto flat columns after a year of rows is the expensive\n * version of this, and the read response (A-276) is additive-only forever, so\n * `kind` is what lets an older SDK skip a marker it does not understand rather\n * than misplace it.\n */\n\nimport {\n collectSourceChain,\n findAnnotatedAncestor,\n parseSourceRef,\n MAX_CHAIN,\n SRC_ATTR,\n type ElementLike,\n} from \"./target\";\nimport { selectionOf, type SourceRef, type TargetInfo } from \"./protocol\";\n\n/**\n * An element identified by the source location that rendered it, plus the chain\n * of source locations above it.\n *\n * `chain` is innermost-first and INCLUDES the leaf, exactly as\n * `collectSourceChain` produces it \u2014 one array, not a leaf plus a tail, because\n * two representations of one list is a way for them to disagree about whether\n * entry zero is the element or its parent.\n */\nexport interface SourceRefAnchor {\n kind: \"source-ref\";\n file: string;\n line: number;\n column?: number;\n chain: SourceRef[];\n /**\n * The element's index among the leaf-matching candidates at capture time.\n *\n * **Recorded, and deliberately never used to select.** It is here because\n * knowing \"this was the 3rd of 6\" is genuinely useful when a human is looking\n * at an unresolved anchor and asking what happened \u2014 and it is *not* here as a\n * tie-break, for the reason set out at length in this file's header. If you\n * are about to reach for it to turn an `\"ambiguous\"` into an element, that is\n * the bug this whole scheme was rewritten to avoid; `anchor.test.ts` has a\n * test that fails if you do.\n */\n ordinal?: number;\n}\n\n/** A CSS-ish path, for elements no build transform gave a ref. */\nexport interface DomPathAnchor {\n kind: \"dom-path\";\n path: string;\n}\n\n/**\n * \"Something on THIS page.\"\n *\n * First-class rather than a fallback of last resort: it is the honest home for a\n * region capture, for a canvas, for a PDF, and for any product that is not a JSX\n * tree.\n *\n * ===========================================================================\n * `path` IS NOT OPTIONAL DECORATION \u2014 IT IS WHAT MAKES \"THIS PAGE\" MEAN ANYTHING\n * ===========================================================================\n *\n * The first version of this interface had no fields at all and `resolveAnchor`\n * returned `doc.body` unconditionally, with a comment calling it *\"always\n * placeable\"*. A reviewer pointed out that this reintroduces, through the route\n * branch, exactly the failure the source-ref scheme was rewritten to prevent:\n *\n * A capture taken on `/guides/a` resolves CONFIDENTLY on `/guides/b`. One\n * match, marker drawn, wrong page, counted as `placed`. No signal anywhere.\n *\n * That is not a rate to be estimated. `return doc.body` has no input but the\n * document, so under it **every** route anchor placed on **every** page it was\n * shown \u2014 100%, by construction, and there is nothing to measure. The reason it\n * matters is `payload.page.route`: it is the matched PATTERN rather than the\n * URL, so \"the page this came from\" was never pinned in the first place. And\n * `anchorFromTarget` sends every region capture down this branch, so it is the\n * common case rather than the edge.\n *\n * The measured neighbour is the SOURCE-REF branch meeting the same problem:\n * 414 anchors captured on one guide page resolve **identically** after a real\n * navigation to another guide page \u2014 161 placed, 253 ambiguous, 0 refused, the\n * same three numbers on both \u2014 recorded with its method and denominator in\n * `docs/decisions/a-275-anchor-placement.md` \u00A7 *The limit this does not fix*.\n * It is a different branch and a different number, cited here as evidence that\n * the pattern-not-URL problem is real, not as a figure for this one.\n *\n * So a route anchor carries the RESOLVED path it was captured on, and\n * `resolveAnchor` refuses when the document is somewhere else.\n *\n * ===========================================================================\n * AND ABSENT MEANS \"CANNOT PLACE\", NEVER \"PLACE ANYWAY\"\n * ===========================================================================\n *\n * `path` is optional because the field is newer than the wire, and the read-back\n * plan's versioning rule for exactly this case is that a new anchor field is\n * optional and **absent means cannot place** \u2014 the precedent `selection?:` set.\n * A route anchor with no `path`, or a document that cannot say where it is,\n * therefore resolves to `\"none\"`.\n *\n * That is a deliberate choice to under-place rather than mis-place, and it costs\n * nothing today because no route anchor has ever been stored: markers have not\n * shipped. It would be a real cost if this were retrofitted a year from now,\n * which is the argument for doing it here.\n *\n * WHAT IT DOES NOT FIX: a SOURCE-REF anchor still resolves happily on a\n * different `[id]` of the same route pattern \u2014 the markup is identical, so there\n * is nothing for the chain to disagree with, and no amount of anchor design\n * closes it. That one is the read endpoint's (A-276): scope the query on the\n * resolved path, not on `route`. Stated here because an unstated limit gets read\n * as a covered one.\n */\nexport interface RouteAnchor {\n kind: \"route\";\n /** `location.pathname` at capture time. Absent means the anchor cannot be placed. */\n path?: string;\n}\n\nexport type Anchor = SourceRefAnchor | DomPathAnchor | RouteAnchor;\n\n/**\n * Where a marker goes, or why it does not go anywhere.\n *\n * Three outcomes and not two, because `\"none\"` and `\"ambiguous\"` are different\n * facts about the page and a caller counting them together loses the one that\n * says the markup moved.\n */\nexport type AnchorResolution<E extends ElementLike = ElementLike> = E | \"none\" | \"ambiguous\";\n\n/**\n * The narrowest slice of `Document` this module reads. A real `Document`\n * satisfies it, which `anchor.test.ts` asserts at compile time.\n *\n * `location` is here for the route branch above. It is optional because a parsed\n * fixture has no location, and a document that cannot say where it is makes a\n * route anchor unplaceable rather than placeable-by-default.\n */\nexport interface DocumentLike<E extends ElementLike = ElementLike> {\n querySelectorAll(selectors: string): ArrayLike<E>;\n body?: E | null;\n location?: { pathname: string } | null;\n}\n\nfunction sameRef(a: SourceRef, b: SourceRef): boolean {\n if (a.file !== b.file || a.line !== b.line) return false;\n /**\n * Column is compared only when BOTH sides have one.\n *\n * It is optional in `SourceRef` and the ingest drops a malformed one rather\n * than defaulting it (A-287), so an absent column means \"not recorded\" and\n * never \"column zero\". Treating a missing column as a mismatch would make\n * every capture from a build that omits it permanently unplaceable.\n */\n if (a.column === undefined || b.column === undefined) return true;\n return a.column === b.column;\n}\n\n/**\n * Does this candidate's live chain still match the one recorded at capture time?\n *\n * The length rule is the half that does the work, and it is asymmetric on\n * purpose:\n *\n * - A recorded chain SHORTER than `MAX_CHAIN` is complete \u2014 it ran out of\n * ancestors, not out of budget \u2014 so the live chain must be exactly as long.\n * An element that gained an annotated ancestor (a conditional wrapper, a\n * portal boundary, a new layout) is a moved element and must not match.\n * - A recorded chain AT `MAX_CHAIN` was truncated by `collectSourceChain`, so\n * all that can honestly be required is that the recorded frames are a prefix\n * of the live ones.\n *\n * THE SECOND CASE IS NOT WHERE THE REAL WEAKNESS LIVES, and an earlier version\n * of this comment said it was. An ancestor inserted above the eighth frame is\n * invisible because `collectSourceChain` never walked that far \u2014 the frame is\n * missing from the recorded chain AND from the live one, so no comparison here\n * can see it. MEASURED: making this length rule strict for truncated chains too\n * changes no test; raising `MAX_CHAIN` changes four.\n *\n * `anchor.test.ts` pins that ceiling under the name\n * *\"MAX_CHAIN truncation hides an ancestor added above the eighth frame\"*, so it\n * is an executable fact rather than a paragraph.\n */\nfunction chainMatches(recorded: SourceRef[], live: SourceRef[]): boolean {\n if (recorded.length === 0) return false;\n if (recorded.length < MAX_CHAIN) {\n if (live.length !== recorded.length) return false;\n } else if (live.length < recorded.length) {\n return false;\n }\n return recorded.every((ref, i) => { const other = live[i]; return other !== undefined && sameRef(ref, other); });\n}\n\n/**\n * Candidates for a source-ref anchor: every element whose OWN `data-src` is the\n * anchor's leaf, minus the nested repeats.\n *\n * One JSX element frequently produces several nested DOM nodes carrying the same\n * ref. `collectSourceChain` already collapses those when it builds a chain; not\n * collapsing them here would make a perfectly unambiguous element report\n * `\"ambiguous\"` against copies of itself \u2014 a false unplaceable, which is the\n * quiet way a scheme gets abandoned for being useless rather than for being\n * wrong. The outermost node of a repeat group is kept, because that is the one\n * whose box covers the component.\n */\nfunction leafCandidates<E extends ElementLike>(anchor: SourceRefAnchor, doc: DocumentLike<E>): E[] {\n const leaf: SourceRef = { file: anchor.file, line: anchor.line };\n if (anchor.column !== undefined) leaf.column = anchor.column;\n\n const all = doc.querySelectorAll(`[${SRC_ATTR}]`);\n const matched: E[] = [];\n for (let i = 0; i < all.length; i++) {\n const el = all[i] as E;\n const own = parseSourceRef(el.getAttribute(SRC_ATTR));\n if (!own || !sameRef(leaf, own)) continue;\n\n const parentRef = parseSourceRef(\n findAnnotatedAncestor(el.parentElement)?.getAttribute(SRC_ATTR) ?? null,\n );\n if (parentRef && sameRef(parentRef, own)) continue; // a nested repeat of the same ref\n\n matched.push(el);\n }\n return matched;\n}\n\n/**\n * Resolve an anchor against a document.\n *\n * Pure: it reads the document and returns an element or a refusal, and it never\n * mutates, measures layout, or draws anything. That is what lets the same\n * function be a unit test over a checked-in HTML fixture, a number in a\n * measurement run, and the marker layer's placement call.\n *\n * A `kind` this version does not recognise resolves to `\"none\"` \u2014 the read\n * response is additive-only forever (A-276), so an SDK meeting a newer console\n * must SKIP a marker it cannot place rather than guess at one.\n */\nexport function resolveAnchor<E extends ElementLike>(\n anchor: Anchor,\n doc: DocumentLike<E>,\n): AnchorResolution<E> {\n switch (anchor.kind) {\n case \"route\": {\n /**\n * Both sides must say where they are, and they must agree. See\n * `RouteAnchor` for why this is a refusal rather than a default.\n */\n if (!anchor.path) return \"none\";\n const here = doc.location?.pathname;\n if (!here || here !== anchor.path) return \"none\";\n return doc.body ?? \"none\";\n }\n\n case \"dom-path\": {\n if (!anchor.path) return \"none\";\n let found: ArrayLike<E>;\n try {\n found = doc.querySelectorAll(anchor.path);\n } catch {\n /**\n * `domPath` is documented as a hint for a human and explicitly not a\n * selector we promise to re-resolve \u2014 hashed class names can contain\n * characters that make it an invalid selector, and an invalid selector\n * THROWS rather than matching nothing. Refusing is right; letting a\n * `SyntaxError` out of a placement call would take the whole marker\n * layer down over one bad capture.\n */\n return \"none\";\n }\n if (found.length === 0) return \"none\";\n if (found.length > 1) return \"ambiguous\";\n return found[0] as E;\n }\n\n case \"source-ref\": {\n if (anchor.chain.length === 0) return \"none\";\n const matched = leafCandidates(anchor, doc).filter((el) =>\n chainMatches(anchor.chain, collectSourceChain(el)),\n );\n if (matched.length === 0) return \"none\";\n if (matched.length > 1) return \"ambiguous\";\n return matched[0] as E;\n }\n\n default:\n return \"none\";\n }\n}\n\nexport interface AnchorFromTargetOptions {\n /** Document order index among leaf-matching candidates, when the caller has a document. */\n ordinal?: number;\n /**\n * `location.pathname` at capture time \u2014 the RESOLVED path, not the route\n * pattern.\n *\n * Pass it. A route anchor built without it can never be placed, by design; see\n * `RouteAnchor`. It is optional here rather than required because\n * `anchorFromTarget` is also called for element captures, where it is unused.\n */\n path?: string;\n}\n\n/**\n * Build the anchor for a capture.\n *\n * The capture side of the same primitive, here rather than in `target.ts` so the\n * union and the function that produces it cannot drift apart.\n *\n * **A region capture becomes a `route` anchor.** Its `sourceChain` is the\n * siblings a rectangle crossed, which contain nothing of each other; handing\n * that to `chainMatches` would compare a sibling list against an ancestor list\n * and refuse \u2014 the right answer for the wrong reason, and one that would report\n * every region capture as \"the markup moved\". Route-level is what a region\n * capture actually means: something on this page, in that area.\n */\nexport function anchorFromTarget(\n target: Pick<TargetInfo, \"selection\" | \"source\" | \"sourceChain\" | \"domPath\">,\n options: AnchorFromTargetOptions = {},\n): Anchor {\n const routeAnchor = (): RouteAnchor =>\n options.path === undefined ? { kind: \"route\" } : { kind: \"route\", path: options.path };\n\n if (selectionOf(target) === \"region\") return routeAnchor();\n\n const chain = target.sourceChain ?? [];\n const head = chain[0];\n const leaf = target.source ?? head;\n if (leaf && head && sameRef(leaf, head)) {\n const anchor: SourceRefAnchor = {\n kind: \"source-ref\",\n file: leaf.file,\n line: leaf.line,\n chain,\n };\n if (leaf.column !== undefined) anchor.column = leaf.column;\n if (options.ordinal !== undefined) anchor.ordinal = options.ordinal;\n return anchor;\n }\n\n if (target.domPath) return { kind: \"dom-path\", path: target.domPath };\n return routeAnchor();\n}\n\n/**\n * The counts a caller reports, so that \"0 markers\" is never the same string as\n * \"working, nothing here\" (rule 1 of the read-back plan).\n *\n * ===========================================================================\n * `wrong` IS NOT IN HERE AND CANNOT BE, AND THAT IS A GAP RATHER THAN A DESIGN\n * ===========================================================================\n *\n * Whether a resolved element is the RIGHT element is not knowable from the live\n * page alone \u2014 it takes a before/after comparison, which is what A-275's\n * mutation battery does and what no runtime caller can do.\n *\n * So `placed` means \"resolved to exactly one element\", NOT \"resolved\n * correctly\", and there is one measured channel where those differ: a\n * source-ref anchor captured on one `[id]` resolves on another `[id]` of the\n * same route pattern, because the two pages are structurally identical.\n *\n * MEASURED at **161 of 414 anchors** placing on a different `[id]` of the same\n * route pattern, with zero refusals \u2014 indistinguishable, count for count, from\n * resolving against the page they were captured on. The method, the denominator\n * and the pages are in `docs/decisions/a-275-anchor-placement.md` \u00A7 *The limit\n * this does not fix*, and `node anchor-measure.mjs --url \u2026 --compare-url \u2026`\n * re-runs it in one command. Nothing in this module can detect it; the\n * fix is for the read endpoint to scope on the resolved path (A-276), so a\n * caller must not read `placed` as a correctness figure until it does.\n *\n * The route branch closes its own half of that (`RouteAnchor.path`). This\n * comment is the record that the source-ref half is still open.\n */\nexport interface AnchorTally {\n total: number;\n placed: number;\n ambiguous: number;\n unresolved: number;\n}\n\nexport function tallyAnchors<E extends ElementLike>(\n anchors: readonly Anchor[],\n doc: DocumentLike<E>,\n): AnchorTally {\n const tally: AnchorTally = { total: anchors.length, placed: 0, ambiguous: 0, unresolved: 0 };\n for (const anchor of anchors) {\n const result = resolveAnchor(anchor, doc);\n if (result === \"ambiguous\") tally.ambiguous += 1;\n else if (result === \"none\") tally.unresolved += 1;\n else tally.placed += 1;\n }\n return tally;\n}\n", "/**\n * The annotation postMessage protocol (A-36).\n *\n * Mirrors `docs/contracts/types.ts`. That file is the\n * cross-component contract; this is the runtime copy the product bundle ships,\n * because the product cannot import from a docs directory. Changing a shape\n * here is a change to both \u2014 say so in the PR.\n */\n\nexport const SDK_VERSION = \"1\";\n\n/**\n * A hosted document declares first-party annotation support with this exact\n * response header. It describes the BUILD, never a token, cookie or attempt.\n */\nexport const ANNOTATION_MODE_HEADER = \"x-weatherboard-annotation-mode\";\nexport const FIRST_PARTY_ANNOTATION_MODE = \"first-party\";\n\n/**\n * ===========================================================================\n * THE ATTRIBUTES \u2014 THE OTHER WIRE (A-186)\n * ===========================================================================\n *\n * These live in `protocol.ts`, not in `target.ts` where they are read, because\n * they are a contract between TWO PACKAGES that a consumer installs separately:\n * `@weatherboard/annotation-next` WRITES them at build time and this package\n * READS them at runtime. Two spellings of `data-src` is not a bug anybody\n * catches \u2014 the transform runs, the attributes appear, and every capture comes\n * back with no source ref at all, which is indistinguishable from the transform\n * not running.\n *\n * `annotation-next` imports these from `@weatherboard/annotation/protocol`\n * rather than declaring its own, which is why the subpath has no DOM in it: a\n * build tool importing the page SDK to learn two strings would be absurd.\n */\nexport const SRC_ATTR = \"data-src\";\nexport const NAME_ATTR = \"data-src-name\";\n\nexport interface SourceRef {\n file: string;\n line: number;\n column?: number;\n}\n\nexport interface BuildInfo {\n /** Mandatory. Feedback not pinned to a revision is ambiguous the moment someone merges. */\n gitSha: string;\n /**\n * Where this build came from.\n *\n * `\"development\"` was added in A-37, when the SDK was first mounted in a\n * real app and the two halves turned out not to agree: `resolveBuildInfo` in\n * `resolveBuildInfo` in the product's own Next config package \u2014 the module\n * that stamps the build-env variable, and the only producer of this field \u2014\n * emits\n * `production | preview | development`, mirroring `VERCEL_ENV`. This union\n * instead offered `\"staging\"`, which nothing produces: a staging deploy IS a\n * Vercel preview and reports itself as one. Widening rather than forcing the\n * mount to lie: a locally-annotated build calling itself a preview would put\n * someone's laptop in the corpus as though it were a deployment.\n */\n env: \"production\" | \"preview\" | \"staging\" | \"development\";\n branch?: string;\n /** Set when reviewing an agent's preview deploy, so feedback routes to that run's session. */\n previewRunId?: string;\n}\n\nexport interface ConsoleEntry {\n level: \"error\" | \"warn\";\n message: string;\n stack?: string;\n at: string;\n}\n\nexport interface NetworkEntry {\n url: string;\n method: string;\n status: number;\n at: string;\n}\n\nexport interface TargetInfo {\n /**\n * What the reviewer selected \u2014 one element, or an area (A-179).\n *\n * -------------------------------------------------------------------------\n * WHY THIS EXISTS RATHER THAN BEING INFERRED\n * -------------------------------------------------------------------------\n *\n * A region capture and an element capture are the same SHAPE: a bounding box,\n * a chain of source refs, a DOM path. Nothing in the values distinguishes\n * them, and the two mean opposite things about the chain \u2014 for an element it\n * is ANCESTORS, innermost first, so entry two contains entry one; for a\n * region it is SIBLINGS the rectangle happened to cross, which contain\n * nothing of each other.\n *\n * A reader that guesses will describe a region's siblings as a call-site\n * chain, which is a confident false statement about the page. `describeCapture`\n * hands that description to a model that writes acceptance criteria from it.\n *\n * -------------------------------------------------------------------------\n * WHY IT IS OPTIONAL, AND WHY ABSENT MEANS `element`\n * -------------------------------------------------------------------------\n *\n * The two halves of this protocol live in different repositories and deploy\n * independently (see the note on the legacy parameter names below). Every\n * capture in the store today, and every capture from a product bundle that\n * predates region selection, has no such field \u2014 and all of them are element\n * captures. Absent therefore has to mean `element`, or this field would\n * retroactively make the entire history ambiguous.\n *\n * Required-with-a-default would have the same effect and a worse failure: an\n * older bundle omits it, the type says it is there, and every reader believes\n * a value nobody sent.\n */\n selection?: \"element\" | \"region\";\n source?: SourceRef;\n /**\n * Every `data-src` from the clicked element up to the document root, innermost\n * first \u2014 an addition to the contract, and the reason is structural.\n *\n * Only host elements carry a ref (A-33), so `source` names the file that\n * *writes the markup*. For a composed design-system component that is\n * `MediaCard.tsx`, not the `GuideDetailCard.tsx` a human would say they\n * clicked. The chain is what lets the PM agent and the coding agent see both,\n * and pick the call site over the leaf when the feedback is about content\n * rather than the component itself.\n */\n sourceChain?: SourceRef[];\n componentName?: string;\n /** CSS selector fallback, for when no ancestor carries a ref at all. */\n domPath: string;\n boundingBox: { x: number; y: number; w: number; h: number };\n /** Truncated to 200 characters. */\n textContent?: string;\n}\n\n/**\n * What kind of capture this is, with the default applied once (A-189).\n *\n * `selection` is optional and **absent means `element`** \u2014 every capture taken\n * before A-179, and everything the managed product's live bundle emits today,\n * has no such field. Any other default would retroactively reclassify the whole\n * history as regions, silently.\n *\n * A function rather than a documented convention because the default is the\n * kind of thing two readers implement slightly differently and neither notices:\n * one writes `=== \"region\"`, another writes `?? \"element\"`, a third forgets and\n * treats `undefined` as falsy in a branch that meant something else. This is\n * the protocol's answer, and `compatibility.test.ts` replays every recorded\n * payload through it.\n */\nexport function selectionOf(target: Pick<TargetInfo, \"selection\">): \"element\" | \"region\" {\n return target.selection === \"region\" ? \"region\" : \"element\";\n}\n\nexport interface AnnotationPayload {\n schemaVersion: 1;\n capturedAt: string;\n build: BuildInfo;\n page: {\n url: string;\n /** The matched route pattern, not the resolved URL. */\n route: string;\n viewport: { w: number; h: number; dpr: number };\n userAgent: string;\n };\n target: TargetInfo;\n state: {\n consoleErrors: ConsoleEntry[];\n failedRequests: NetworkEntry[];\n featureFlags: Record<string, unknown>;\n };\n screenshot?: { dataUrl: string; region: \"element\" | \"viewport\" };\n /** The human's words, verbatim. The parent frame fills this in; we never rewrite it. */\n comment: string;\n}\n\nexport type ParentToFrame =\n | { type: \"annotate:enable\" }\n | { type: \"annotate:disable\" }\n | { type: \"annotate:ping\" };\n\nexport type FrameToParent =\n | { type: \"annotate:ready\"; sdkVersion: string; build: BuildInfo }\n | { type: \"annotate:hover\"; target: TargetInfo }\n | { type: \"annotate:capture\"; payload: AnnotationPayload }\n | { type: \"annotate:cancel\" };\n\n/**\n * A message that got past both guards and matched no `case` (A-359).\n *\n * ===========================================================================\n * THE DEFECT\n * ===========================================================================\n *\n * `host.ts` and `sdk.ts` hold the two halves of this protocol, one `switch`\n * each, and neither had a `default`. Measured before the fix: adding\n * `| { type: \"annotate:probe\" }` to `ParentToFrame` and\n * `| { type: \"annotate:pong\" }` to `FrameToParent`, then running\n * `tsc --noEmit` in this package, gave exit 0 and zero errors. A message type\n * added to the union is dropped on the floor by whichever half was not\n * updated, and the two halves are the only things in the world that can\n * disagree about what a message means.\n *\n * ===========================================================================\n * WHY IT DOES NOT THROW, WHERE THE MANAGER'S TWO EQUIVALENTS DO\n * ===========================================================================\n *\n * This is the house pattern with one deliberate departure, and the departure is\n * the boundary rather than taste.\n *\n * Both switches run inside a `message` listener, reached from `postMessage`.\n * The host's listener runs in the management console over a frame that may be\n * serving anything; the SDK's runs in a product page we do not own. A throw\n * there does not propagate to a caller \u2014 there is no caller \u2014 it becomes an\n * uncaught error on somebody else's page, once per message. Any party that can\n * reach this branch can therefore reach it repeatedly, and the loudest\n * available answer would be handing them a way to fill a product's error\n * reporting with our noise.\n *\n * The narrower reason the throw would buy little: `isFrameMessage` and\n * `isParentMessage` gate on fixed sets of type strings, so a message an\n * outsider invents never reaches the switch at all. What DOES reach it is a\n * type in the guard's set with no `case` \u2014 which is our own two lists having\n * drifted apart, in this repository, in the commit that widened one of them.\n *\n * So the answer is: act on nothing, and say so. Acting on nothing is what a\n * trust boundary owes an input it does not understand; saying so is what makes\n * this different from the silent drop that was there before, which is\n * indistinguishable from the message never having been sent.\n *\n * `console.error` rather than a callback, because both call sites are inside\n * listeners with no error channel of their own, and because in the frame the\n * SDK's own `StateCollector` patches `console.error` \u2014 so the drift is\n * collected into the very next annotation payload, where somebody debugging\n * exactly this will already be looking.\n *\n * The type-level half of the guard is NOT here. It is `const unhandled: never`\n * in each `default` branch, which is what makes a widened union a compile\n * error; this function only makes the runtime half observable, and it is\n * exported so `exhaustive.test.ts` can call it. Both halves are pinned\n * separately, because deleting either leaves the other looking correct.\n */\n/**\n * `JSON.stringify` that cannot throw, for any input at all (A-359 cycle 2).\n *\n * ===========================================================================\n * WHY THIS IS NEEDED \u2014 THE DEFECT IT REPLACES\n * ===========================================================================\n *\n * `unhandledMessage` interpolated `JSON.stringify(message)` unguarded, and so\n * became the thing it was written to prevent. `postMessage` serialises with\n * the STRUCTURED CLONE algorithm, and structured clone PRESERVES CYCLES where\n * JSON cannot represent them \u2014 so `{a: {b: a}}` survives a `postMessage`\n * intact, arrives at that branch, and `JSON.stringify` throws `Converting\n * circular structure to JSON` from inside a `message` listener on a page this\n * SDK is a guest on, once per message, at the sender's discretion.\n *\n * Every word of the argument on `unhandledMessage` was correct, and the\n * implementation defeated it on its own terms. Both cases are pinned in\n * `exhaustive.test.ts` and both were confirmed RED before this existed.\n *\n * ===========================================================================\n * WHY NOT `describeArg`, WHICH DOES THIS ALREADY \u2014 TWO REASONS, ONE MEASURED\n * ===========================================================================\n *\n * `describeArg` in `state.ts` solves the same problem and its comment names\n * the same hazard, so reusing it was the first thing tried rather than a road\n * not taken. It was reverted for two reasons, and the second is the one that\n * decided it:\n *\n * 1. MEASURED, by running `node build.mjs` on both: reuse costs protocol\n * 869 -> 1008 (+139) and host 649 -> 793 (+144). This local version costs\n * +39 and +37. `describeArg` is built for console ARGUMENTS \u2014 strings,\n * Errors, a prototype walk for named objects \u2014 and almost none of that is\n * reachable for a wire message, so the extra 100 bytes per entry point buy\n * nothing here. In a package with a per-entry gzip budget that is not a\n * rounding error.\n * 2. THIS MODULE HAS NO IMPORTS AND THAT IS A PROPERTY WORTH KEEPING.\n * `protocol.ts` is the pure wire contract \u2014 it mirrors\n * `docs/contracts/types.ts`, `annotation-next` imports it so a build tool\n * can learn two strings without pulling in a DOM, and `state.ts` already\n * imports FROM it. Importing back the other way makes the contract depend\n * on the console-patching state collector and closes a module cycle that\n * is only invisible because `state.ts`'s side of it is `import type`.\n *\n * The cost of the choice, stated rather than left for somebody to find: there\n * are now two safe-stringify helpers in this package. They cannot drift in a\n * way that matters \u2014 each is a total function with one behaviour and its own\n * test \u2014 but if a third appears, that is the moment to put one in a module\n * both can depend on, rather than making the contract depend on the collector.\n *\n * The fallback is a constant, deliberately. Reaching for `String(message)` or\n * a constructor name in the `catch` is the obvious way to say something more\n * useful, and it is how this function would learn to throw again: the input\n * that got us here is one whose property access already threw.\n */\nfunction safeJson(message: unknown): string {\n try {\n return JSON.stringify(message) ?? String(message);\n } catch {\n return \"[unserialisable]\";\n }\n}\n\nexport function unhandledMessage(half: \"host\" | \"frame\", message: unknown): void {\n /**\n * `safeJson` RATHER THAN A BARE `JSON.stringify`, AND THAT IS THE WHOLE\n * DIFFERENCE BETWEEN THIS FUNCTION AND ITS FIRST DRAFT (A-359 cycle 2).\n *\n * The first draft interpolated `JSON.stringify(message)` unguarded, which\n * made this function do the thing it exists to avoid. The full argument, the\n * measurement, and why `describeArg` was tried and reverted are on\n * `safeJson` above rather than repeated here.\n *\n * Short on purpose too, and the shortness is measured rather than stylistic.\n * This package ships inside a product's bundle and this package's own\n * `build.mjs` enforces a gzip budget per entry point; the first draft of this\n * sentence was 230 characters and put `protocol`, `host` and `index` over\n * theirs at once. What it must still carry is which half, what arrived, and\n * that nothing was done with it \u2014 the last being the only thing that\n * distinguishes this from the silent drop it replaced.\n */\n console.error(`[annotation] ${half}: protocol drift, nothing was acted on: ${safeJson(message)}`);\n}\n\nconst PARENT_TYPES = new Set([\"annotate:enable\", \"annotate:disable\", \"annotate:ping\"]);\n\n/**\n * Is this a message we recognise?\n *\n * Origin is checked separately and first \u2014 a well-formed message from the wrong\n * origin is the case this guard must not be trusted to catch.\n */\nexport function isParentMessage(data: unknown): data is ParentToFrame {\n if (typeof data !== \"object\" || data === null) return false;\n const type = (data as { type?: unknown }).type;\n return typeof type === \"string\" && PARENT_TYPES.has(type);\n}\n\n/**\n * Reject wildcards outright rather than treating them as \"any origin\".\n *\n * `postMessage(msg, \"*\")` broadcasts the payload to whatever happens to be\n * framing us, and an annotation payload carries page content, console errors and\n * failed request URLs. The spec's rule is no wildcards in either direction; this\n * makes it impossible to configure one by accident.\n */\nexport function assertConcreteOrigin(origin: string): string {\n if (!origin || origin === \"*\") {\n throw new Error(\n \"[annotation] a concrete parent origin is required; '*' would broadcast \" +\n \"annotation payloads to any embedder.\",\n );\n }\n return origin;\n}\n\n/**\n * The query parameter that arms the SDK in a managed product, and the cookie\n * that records it.\n *\n * THESE LIVE IN THE PROTOCOL BECAUSE THE TWO HALVES ARE NOW IN DIFFERENT\n * REPOSITORIES. The managed product's middleware looks for the parameter and\n * sets the cookie; the management app appends the parameter and the SDK reads\n * the cookie. While both halves were one monorepo, a test could read the other\n * side's source and assert the strings matched \u2014 that gate does not survive a\n * repository split, and a mismatch produces no error at all: the frame loads,\n * the cookie is never set, the SDK never boots, and the reviewer sees \"waiting\n * for the page to announce itself\" with nothing to go on.\n *\n * So they stop being two spellings that agree and become one exported\n * constant. A managed product that imports this package cannot drift from it.\n */\nexport const ANNOTATION_TOKEN_PARAM = \"ai_annotate\";\nexport const ANNOTATION_ARMED_COOKIE = \"ai_annotate_armed\";\n\n/**\n * The CAPTURE token's query parameter (A-240).\n *\n * -------------------------------------------------------------------------\n * WHY IT IS HERE AND NOT WHERE IT IS WRITTEN\n * -------------------------------------------------------------------------\n *\n * A second name on the same wire, and a second credential \u2014 see\n * `docs/plans/first-party-annotation.md` \u00A7 *Authentication*. `ai_annotate`\n * answers *should this page offer an annotation UI at all*; this one answers\n * *may this capture become an issue*. Different secrets, different lifetimes,\n * different blast radii, and deliberately not folded into one token.\n *\n * It lives beside `ANNOTATION_TOKEN_PARAM` for that constant's own reason,\n * stated at length above: the console WRITES it into a deep link and the\n * product's bundle READS it, the two halves ship from different repositories,\n * and a mismatch produces no error anywhere \u2014 the reviewer writes a post-it,\n * clicks send, and the ingest rejects an unsigned capture. One exported\n * constant is the only thing that makes those two spellings unable to drift.\n *\n * It has no legacy spelling because it has never had another one: nothing has\n * shipped it yet. It is exported here BEFORE its writer needs it precisely so\n * the writer never has a reason to spell it itself.\n */\nexport const CAPTURE_TOKEN_PARAM = \"ai_capture\";\n\n/**\n * The run under review, when the console knows of one (A-241).\n *\n * Third name on the same wire, here for the reason the two above are: the\n * console writes it and the product's bundle reads it, from two repositories.\n * `apps/manager/src/lib/request-changes.ts` spells it itself today and its own\n * comment asks for exactly this \u2014 the constant to move into the package so the\n * writer has no reason to spell it. **That deletion is not this slice's**\n * (A-243/A-244 are merged and settled), so for now there are two definitions of\n * one string, and `protocol.test.ts` is the only thing standing between them\n * and a silent divergence. Nothing about it is signed: the ingest already\n * treats it as attacker-supplied text and files on it rather than routing on it.\n */\nexport const REVIEW_RUN_PARAM = \"ai_run\";\n\n/**\n * The READ token's query parameter (A-277).\n *\n * ===========================================================================\n * WHY THE MARKER LAYER GETS ITS OWN CREDENTIAL AND NOT `ai_capture`\n * ===========================================================================\n *\n * Fourth name on the same wire, and the reason it is a fourth is A-276's\n * disclosure decision rather than tidiness. The capture token is minted for\n * WRITING and lives four hours so a reviewer can work through a session; reusing\n * it for the read would make one leaked deep link a write capability AND a read\n * capability over every reviewer's comments on that origin for the same window.\n * The scope is a signed field, `verifyCaptureToken` requires an expectation at\n * every call site, and the read endpoint refuses a write claim \u2014 so handing\n * `ai_capture` to the reader does not degrade to a read, it fails.\n *\n * The read claim's TTL is ONE hour rather than four (`READ_TOKEN_TTL_S`), which\n * is the practical consequence a reader of this constant should know: the\n * toolbar outlives the markers, so a reviewer who leaves a tab open all\n * afternoon will find the count line saying it cannot read before they find the\n * Send button broken. That is the intended ordering \u2014 the shorter credential is\n * the one that discloses other people's words.\n *\n * Exported here for the reason the three above are: the console writes it into a\n * deep link and the product's bundle reads it, from two repositories, and a\n * mismatch produces no error anywhere \u2014 just a page with no markers, which is\n * indistinguishable from nine other causes.\n */\nexport const READ_TOKEN_PARAM = \"ai_read\";\n\n/**\n * The arming cookie, as a `Set-Cookie` value (A-241).\n *\n * ===========================================================================\n * IT GOT SIMPLER BY MOVING FIRST-PARTY, AND THAT IS THE WHOLE POINT\n * ===========================================================================\n *\n * Framed, this had to be `SameSite=None; Secure` with no `Partitioned` \u2014 a\n * genuine cross-site cookie, which A-211 records would have broken on its own\n * under Chrome's third-party cookie work, independently of the auth problem\n * that killed the frame. Top-level at the product's own origin it is an\n * ordinary cookie and none of that applies.\n *\n * Each attribute, and why:\n *\n * - **`SameSite=Lax`.** The reviewer arrives by clicking *Request changes* in\n * the console, which is a top-level cross-site GET navigation \u2014 the one case\n * `Lax` still sends on. `Strict` would withhold the cookie on that very first\n * render, so the toolbar would be missing on the page the link opened and\n * appear only after an internal click; that reads as a broken deploy.\n * - **`Secure`.** It is a marker rather than a credential, but a marker that\n * travels in clear is a marker an attacker on the path can set.\n * - **`Path=/`.** Arming survives the reviewer navigating the whole app, which\n * is the point of a cookie rather than a URL parameter.\n * - **No `Max-Age` / `Expires`.** Session-scoped: closing the tab disarms.\n *\n * ===========================================================================\n * WHAT IS *NOT* HERE: `HttpOnly`, AND THE TOKEN\n * ===========================================================================\n *\n * No `HttpOnly`, deliberately. Page script both READS this (`isAnnotationArmed`\n * decides whether a toolbar exists) and CLEARS it (*Done* disarms). An\n * `HttpOnly` arming cookie makes *Done* impossible from the page, which is the\n * one control the reviewer has.\n *\n * That is affordable only because THE VALUE IS A MARKER AND NEVER THE TOKEN.\n * The value is a constant and there is no argument that supplies one: the\n * middleware compares the URL parameter against its secret and then calls this,\n * and what it stores is *yes*, not *what was presented*. The single parameter\n * is the cookie's NAME, and it exists only so a product mid-migration can write\n * the legacy spelling \u2014 it is not a value slot wearing a different label, and\n * `arming.test.ts` pins which side of the `=` it lands on.\n *\n * This is a shape argument, not a guarantee about callers. Nothing stops a\n * determined caller passing a secret as the name; what the signature removes is\n * the ACCIDENT \u2014 the middleware author with a verified token in hand and one\n * parameter available, reaching for the obvious.\n */\nexport const ANNOTATION_ARMED_VALUE = \"1\";\n\nexport function armedCookie(name: string = ANNOTATION_ARMED_COOKIE): string {\n return `${name}=${ANNOTATION_ARMED_VALUE}; Path=/; SameSite=Lax; Secure`;\n}\n\n/**\n * The same cookie, expired \u2014 what *Done* and a disarm write.\n *\n * `Max-Age=0` AND an `Expires` in the past, because they are read by different\n * things and the pair is what every browser honours. The path must match the\n * one set above or the browser stores a second cookie and the first survives \u2014\n * a *Done* button that does nothing and reports success.\n */\nexport function clearedCookie(name: string): string {\n return `${name}=; Path=/; SameSite=Lax; Secure; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT`;\n}\n\n/**\n * The names these used to have (A-98).\n *\n * -------------------------------------------------------------------------\n * WHY THE RENAME, AND WHY IT COULD NOT JUST BE DONE\n * -------------------------------------------------------------------------\n *\n * They were `pits_annotate` and `pits_annotate_armed` \u2014 one managed product's\n * initialism, in a contract every managed product's bundle has to implement.\n * Onboarding a second product meant asking an unrelated codebase to adopt the\n * first product's name in its cookies and its query strings. That is the bug\n * A-98 is about, and it is a bug in a wire protocol rather than in a variable\n * name, which is what makes it expensive.\n *\n * The two halves live in DIFFERENT REPOSITORIES and deploy independently. A\n * clean rename is therefore a breaking change to every product bundle\n * simultaneously, and its failure mode is silence: the frame loads, the cookie\n * is never set, the SDK never boots, and the reviewer sees \"waiting for the\n * page to announce itself\" with nothing to go on. Nothing throws, nothing logs,\n * and the natural reading is that the agent broke the site.\n *\n * -------------------------------------------------------------------------\n * THE MIGRATION: READ BOTH, WRITE BOTH, THEN STOP WRITING THE OLD ONE\n * -------------------------------------------------------------------------\n *\n * 1. **Now.** Every reader accepts either name. Every writer emits BOTH, so a\n * product still running the old bundle arms on the legacy name and one\n * running the new bundle arms on the new one. Deploy order stops mattering,\n * which is the whole point \u2014 there is no window in which a reviewer sees the\n * silent failure above.\n * 2. **After every managed product's bundle is on this version** (A-102). Drop\n * the legacy names from the writers, then from the readers. Two steps, not\n * one: a reader that stops accepting the old name before the writers stop\n * emitting it re-creates the outage in the other direction.\n *\n * The legacy names are exported rather than inlined so the deletion in step 2\n * is `git grep LEGACY_` rather than an archaeology exercise.\n */\nexport const LEGACY_ANNOTATION_TOKEN_PARAM = \"pits_annotate\";\nexport const LEGACY_ANNOTATION_ARMED_COOKIE = \"pits_annotate_armed\";\n\n/**\n * ===========================================================================\n * AND THE NAMES ARE NOT CHANGING AGAIN FOR THE PUBLISHED PACKAGE (A-184)\n * ===========================================================================\n *\n * When this becomes `@weatherboard/annotation` the obvious next thought is that\n * the wire names should match the package \u2014 `weatherboard_annotate`. They\n * should not, and the reason is the migration described above rather than\n * taste.\n *\n * That migration is STILL IN FLIGHT. Readers accept both spellings; writers\n * emit both; step 2 waits on every managed product's bundle being current.\n * A third spelling introduced now does not replace the second, it joins it:\n * every reader accepts three names, every writer emits three, and the window in\n * which a product can be on any of them widens instead of closing.\n *\n * The cost is not the code. It is that each rename buys another instance of the\n * failure this file exists to prevent \u2014 the frame loads, the cookie is never\n * set, the SDK never boots, and the reviewer sees \"waiting for the page to\n * announce itself\" with nothing to go on. Twice is a migration. Three times is\n * a habit, and the third one would be paid by consumers who never asked for\n * either.\n *\n * `ai_annotate` is already product-neutral, which was the entire point of A-98.\n * A published package needs names that name no product; it does not need names\n * that name the package. Nobody reading a query string cares which npm scope\n * the library came from.\n *\n * The one real objection is collision: `ai_` is a common prefix and some other\n * tool could plausibly use it. That is survivable by construction \u2014 arming\n * requires the parameter to carry a token the product compares exactly, so a\n * coincidental `?ai_annotate=` from an unrelated tool arms nothing. A colliding\n * COOKIE cannot false-positive either; `isAnnotationArmed` matches on the\n * delimiter rather than by substring, for exactly this reason.\n *\n * If a rename is ever genuinely warranted, it happens ONCE, after step 2 has\n * landed and the reader accepts one name again \u2014 not layered on top of an\n * unfinished one.\n */\n\n/** Both spellings of the query parameter, current first. */\nexport const ANNOTATION_TOKEN_PARAMS = [\n ANNOTATION_TOKEN_PARAM,\n LEGACY_ANNOTATION_TOKEN_PARAM,\n] as const;\n\n/** Both spellings of the cookie, current first. */\nexport const ANNOTATION_ARMED_COOKIES = [\n ANNOTATION_ARMED_COOKIE,\n LEGACY_ANNOTATION_ARMED_COOKIE,\n] as const;\n\n/**\n * Whether a cookie jar carries the armed cookie, under either name.\n *\n * Delimiter-aware rather than a substring test: a cookie named\n * `not_ai_annotate_armed`, or another cookie whose VALUE contains the name,\n * satisfies `includes` \u2014 and arming an annotation channel on a coincidence is\n * not a failure anyone would think to look for.\n */\nexport function isAnnotationArmed(cookie: string): boolean {\n return cookie\n .split(\";\")\n .some((entry) => {\n const trimmed = entry.trimStart();\n return ANNOTATION_ARMED_COOKIES.some((name) => trimmed.startsWith(`${name}=`));\n });\n}\n\n/**\n * The arming token from a URL's query string, under either name.\n *\n * Current name wins when both are present. They should never disagree \u2014 the\n * management app writes both from one value \u2014 but if they ever do, the one this\n * version of the protocol owns is the one to believe.\n */\nexport function readAnnotationToken(params: URLSearchParams): string | null {\n for (const name of ANNOTATION_TOKEN_PARAMS) {\n const value = params.get(name);\n if (value !== null && value.length > 0) return value;\n }\n return null;\n}\n", "import { NAME_ATTR, SRC_ATTR, type SourceRef, type TargetInfo } from \"./protocol\";\n\n/**\n * Turning a clicked DOM element into something a coding agent can act on.\n *\n * Everything here is written against the narrowest possible slice of the DOM so\n * it can be tested without a browser \u2014 see `ElementLike`. The parts that need a\n * real browser (hit-testing, layout) live in `sdk.ts`.\n */\n\n/**\n * Re-exported, not declared. They moved to `protocol.ts` (A-186) because the\n * build transform in `@weatherboard/annotation-next` writes what this file\n * reads, and the two packages install separately. Kept exported from here so\n * every existing importer is unaffected.\n */\nexport { NAME_ATTR, SRC_ATTR };\n\nexport const MAX_TEXT = 200;\n/** Deep trees are common; a chain long enough to be useless is not worth sending. */\nexport const MAX_CHAIN = 8;\n\n/** The subset of `Element` this module reads. */\nexport interface ElementLike {\n tagName: string;\n id?: string;\n getAttribute(name: string): string | null;\n parentElement: ElementLike | null;\n classList?: { value?: string } | ArrayLike<string>;\n textContent?: string | null;\n}\n\n/**\n * Parse `path/to/File.tsx:42:7` into its parts.\n *\n * Split from the right: the line and column never contain a colon, and a path\n * conceivably might. Returns null rather than a half-parsed ref \u2014 a ref we\n * cannot read is worse than no ref, because downstream will believe it.\n */\nexport function parseSourceRef(value: string | null): SourceRef | null {\n if (!value) return null;\n\n const colIdx = value.lastIndexOf(\":\");\n if (colIdx <= 0) return null;\n const lineIdx = value.lastIndexOf(\":\", colIdx - 1);\n if (lineIdx <= 0) return null;\n\n const file = value.slice(0, lineIdx);\n const line = Number(value.slice(lineIdx + 1, colIdx));\n const column = Number(value.slice(colIdx + 1));\n\n if (!file || !Number.isFinite(line) || !Number.isFinite(column)) return null;\n return { file, line, column };\n}\n\n/**\n * Every source ref from `el` upwards, innermost first.\n *\n * Consecutive duplicates are collapsed: one JSX element often produces several\n * nested DOM nodes carrying the same ref, and repeating it says nothing.\n */\nexport function collectSourceChain(el: ElementLike | null, max = MAX_CHAIN): SourceRef[] {\n const chain: SourceRef[] = [];\n let node: ElementLike | null = el;\n\n while (node && chain.length < max) {\n const ref = parseSourceRef(node.getAttribute(SRC_ATTR));\n if (ref) {\n const prev = chain[chain.length - 1];\n const isRepeat = prev && prev.file === ref.file && prev.line === ref.line;\n if (!isRepeat) chain.push(ref);\n }\n node = node.parentElement;\n }\n\n return chain;\n}\n\n/** The nearest ancestor (or self) carrying a ref, which is the element a human means. */\nexport function findAnnotatedAncestor(el: ElementLike | null): ElementLike | null {\n let node: ElementLike | null = el;\n while (node) {\n if (parseSourceRef(node.getAttribute(SRC_ATTR))) return node;\n node = node.parentElement;\n }\n return null;\n}\n\nfunction classTokens(el: ElementLike): string[] {\n const list = el.classList as { value?: string } | undefined;\n const raw = typeof list?.value === \"string\" ? list.value : \"\";\n return raw.split(/\\s+/).filter(Boolean);\n}\n\n/**\n * A CSS-ish path to the element, used only when no ancestor carries a ref.\n *\n * Deliberately not guaranteed unique. It is a hint for a human reading the\n * payload, not a selector we promise to re-resolve \u2014 StyleX class names are\n * hashed and change between builds, so a path that looks precise would be\n * quietly wrong on the next deploy. IDs are kept because they survive; classes\n * are capped at two for readability.\n */\nexport function domPath(el: ElementLike | null, maxDepth = 6): string {\n const parts: string[] = [];\n let node: ElementLike | null = el;\n\n while (node && parts.length < maxDepth) {\n const tag = (node.tagName || \"\").toLowerCase();\n if (!tag || tag === \"html\") break;\n\n let part = tag;\n if (node.id) {\n // An id is unique on the page, so nothing above it adds information.\n parts.unshift(`${tag}#${node.id}`);\n return parts.join(\" > \");\n }\n const classes = classTokens(node).slice(0, 2);\n if (classes.length > 0) part += `.${classes.join(\".\")}`;\n parts.unshift(part);\n\n if (tag === \"body\") break;\n node = node.parentElement;\n }\n\n return parts.join(\" > \");\n}\n\n/** Collapse whitespace and truncate, so the payload carries a label rather than a page. */\nexport function summariseText(text: string | null | undefined): string | undefined {\n if (!text) return undefined;\n const collapsed = text.replace(/\\s+/g, \" \").trim();\n if (!collapsed) return undefined;\n return collapsed.length > MAX_TEXT ? `${collapsed.slice(0, MAX_TEXT - 1)}\u2026` : collapsed;\n}\n\nexport interface ResolveTargetOptions {\n boundingBox: { x: number; y: number; w: number; h: number };\n}\n\n/**\n * Build the `TargetInfo` for a clicked or hovered element.\n *\n * `source` is the nearest ref, which names the file that writes the markup \u2014\n * for a composed design-system component that is the design-system file, not\n * the call site. `sourceChain` carries the rest so the agent can choose.\n */\nexport function resolveTarget(el: ElementLike, options: ResolveTargetOptions): TargetInfo {\n const annotated = findAnnotatedAncestor(el);\n const chain = collectSourceChain(el);\n const source = chain[0];\n\n const target: TargetInfo = {\n domPath: domPath(el),\n boundingBox: options.boundingBox,\n };\n\n if (source) target.source = source;\n if (chain.length > 0) target.sourceChain = chain;\n\n const componentName = annotated?.getAttribute(NAME_ATTR);\n if (componentName) target.componentName = componentName;\n\n const text = summariseText(el.textContent);\n if (text) target.textContent = text;\n\n return target;\n}\n"],
5
+ "mappings": "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",
6
6
  "names": ["anchor_exports", "__export", "anchorFromTarget", "resolveAnchor", "tallyAnchors", "__toCommonJS", "SRC_ATTR", "selectionOf", "target", "MAX_CHAIN", "parseSourceRef", "value", "colIdx", "lineIdx", "file", "line", "column", "collectSourceChain", "el", "max", "chain", "node", "ref", "SRC_ATTR", "prev", "findAnnotatedAncestor", "sameRef", "a", "b", "chainMatches", "recorded", "live", "MAX_CHAIN", "ref", "i", "other", "leafCandidates", "anchor", "doc", "leaf", "all", "SRC_ATTR", "matched", "el", "own", "parseSourceRef", "parentRef", "findAnnotatedAncestor", "resolveAnchor", "here", "found", "collectSourceChain", "anchorFromTarget", "target", "options", "routeAnchor", "selectionOf", "chain", "head", "tallyAnchors", "anchors", "tally", "result"]
7
7
  }
package/dist/anchor.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var u="data-src";function p(e){return e.selection==="region"?"region":"element"}var f=8;function s(e){if(!e)return null;let n=e.lastIndexOf(":");if(n<=0)return null;let t=e.lastIndexOf(":",n-1);if(t<=0)return null;let o=e.slice(0,t),r=Number(e.slice(t+1,n)),i=Number(e.slice(n+1));return!o||!Number.isFinite(r)||!Number.isFinite(i)?null:{file:o,line:r,column:i}}function g(e,n=f){let t=[],o=e;for(;o&&t.length<n;){let r=s(o.getAttribute(u));if(r){let i=t[t.length-1];i&&i.file===r.file&&i.line===r.line||t.push(r)}o=o.parentElement}return t}function d(e){let n=e;for(;n;){if(s(n.getAttribute(u)))return n;n=n.parentElement}return null}function l(e,n){return e.file!==n.file||e.line!==n.line?!1:e.column===void 0||n.column===void 0?!0:e.column===n.column}function h(e,n){if(e.length===0)return!1;if(e.length<f){if(n.length!==e.length)return!1}else if(n.length<e.length)return!1;return e.every((t,o)=>{let r=n[o];return r!==void 0&&l(t,r)})}function A(e,n){let t={file:e.file,line:e.line};e.column!==void 0&&(t.column=e.column);let o=n.querySelectorAll(`[${u}]`),r=[];for(let i=0;i<o.length;i++){let a=o[i],c=s(a.getAttribute(u));if(!c||!l(t,c))continue;let m=s(d(a.parentElement)?.getAttribute(u)??null);m&&l(m,c)||r.push(a)}return r}function x(e,n){switch(e.kind){case"route":{if(!e.path)return"none";let t=n.location?.pathname;return!t||t!==e.path?"none":n.body??"none"}case"dom-path":{if(!e.path)return"none";let t;try{t=n.querySelectorAll(e.path)}catch{return"none"}return t.length===0?"none":t.length>1?"ambiguous":t[0]}case"source-ref":{if(e.chain.length===0)return"none";let t=A(e,n).filter(o=>h(e.chain,g(o)));return t.length===0?"none":t.length>1?"ambiguous":t[0]}default:return"none"}}function N(e,n={}){let t=()=>n.path===void 0?{kind:"route"}:{kind:"route",path:n.path};if(p(e)==="region")return t();let o=e.sourceChain??[],r=o[0],i=e.source??r;if(i&&r&&l(i,r)){let a={kind:"source-ref",file:i.file,line:i.line,chain:o};return i.column!==void 0&&(a.column=i.column),n.ordinal!==void 0&&(a.ordinal=n.ordinal),a}return e.domPath?{kind:"dom-path",path:e.domPath}:t()}function S(e,n){let t={total:e.length,placed:0,ambiguous:0,unresolved:0};for(let o of e){let r=x(o,n);r==="ambiguous"?t.ambiguous+=1:r==="none"?t.unresolved+=1:t.placed+=1}return t}export{N as anchorFromTarget,x as resolveAnchor,S as tallyAnchors};
1
+ var s="data-src";function p(e){return e.selection==="region"?"region":"element"}var f=8;function u(e){if(!e)return null;let n=e.lastIndexOf(":");if(n<=0)return null;let t=e.lastIndexOf(":",n-1);if(t<=0)return null;let o=e.slice(0,t),r=Number(e.slice(t+1,n)),i=Number(e.slice(n+1));return!o||!Number.isFinite(r)||!Number.isFinite(i)?null:{file:o,line:r,column:i}}function g(e,n=f){let t=[],o=e;for(;o&&t.length<n;){let r=u(o.getAttribute(s));if(r){let i=t[t.length-1];i&&i.file===r.file&&i.line===r.line||t.push(r)}o=o.parentElement}return t}function d(e){let n=e;for(;n;){if(u(n.getAttribute(s)))return n;n=n.parentElement}return null}function l(e,n){return e.file!==n.file||e.line!==n.line?!1:e.column===void 0||n.column===void 0?!0:e.column===n.column}function h(e,n){if(e.length===0)return!1;if(e.length<f){if(n.length!==e.length)return!1}else if(n.length<e.length)return!1;return e.every((t,o)=>{let r=n[o];return r!==void 0&&l(t,r)})}function A(e,n){let t={file:e.file,line:e.line};e.column!==void 0&&(t.column=e.column);let o=n.querySelectorAll(`[${s}]`),r=[];for(let i=0;i<o.length;i++){let a=o[i],c=u(a.getAttribute(s));if(!c||!l(t,c))continue;let m=u(d(a.parentElement)?.getAttribute(s)??null);m&&l(m,c)||r.push(a)}return r}function x(e,n){switch(e.kind){case"route":{if(!e.path)return"none";let t=n.location?.pathname;return!t||t!==e.path?"none":n.body??"none"}case"dom-path":{if(!e.path)return"none";let t;try{t=n.querySelectorAll(e.path)}catch{return"none"}return t.length===0?"none":t.length>1?"ambiguous":t[0]}case"source-ref":{if(e.chain.length===0)return"none";let t=A(e,n).filter(o=>h(e.chain,g(o)));return t.length===0?"none":t.length>1?"ambiguous":t[0]}default:return"none"}}function N(e,n={}){let t=()=>n.path===void 0?{kind:"route"}:{kind:"route",path:n.path};if(p(e)==="region")return t();let o=e.sourceChain??[],r=o[0],i=e.source??r;if(i&&r&&l(i,r)){let a={kind:"source-ref",file:i.file,line:i.line,chain:o};return i.column!==void 0&&(a.column=i.column),n.ordinal!==void 0&&(a.ordinal=n.ordinal),a}return e.domPath?{kind:"dom-path",path:e.domPath}:t()}function S(e,n){let t={total:e.length,placed:0,ambiguous:0,unresolved:0};for(let o of e){let r=x(o,n);r==="ambiguous"?t.ambiguous+=1:r==="none"?t.unresolved+=1:t.placed+=1}return t}export{N as anchorFromTarget,x as resolveAnchor,S as tallyAnchors};
2
2
  //# sourceMappingURL=anchor.mjs.map