@weatherboard/annotation 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ADOPTING.md +50 -4
- package/COMPATIBILITY.md +14 -0
- package/README.md +51 -2
- package/dist/anchor.cjs +1 -1
- package/dist/anchor.cjs.map +1 -1
- package/dist/anchor.mjs +1 -1
- package/dist/anchor.mjs.map +1 -1
- package/dist/arming.d.cts +17 -18
- package/dist/arming.d.mts +17 -18
- package/dist/arming.d.ts +17 -18
- package/dist/bootstrap.cjs +1 -1
- package/dist/bootstrap.cjs.map +4 -4
- package/dist/bootstrap.d.cts +1 -0
- package/dist/bootstrap.d.mts +1 -0
- package/dist/bootstrap.d.ts +1 -0
- package/dist/bootstrap.mjs +1 -1
- package/dist/bootstrap.mjs.map +4 -4
- package/dist/host.cjs +1 -1
- package/dist/host.cjs.map +2 -2
- package/dist/host.mjs +1 -1
- package/dist/host.mjs.map +2 -2
- package/dist/index.cjs +4 -4
- package/dist/index.cjs.map +4 -4
- package/dist/index.d.cts +9 -3
- package/dist/index.d.mts +9 -3
- package/dist/index.d.ts +9 -3
- package/dist/index.mjs +4 -4
- package/dist/index.mjs.map +4 -4
- package/dist/markers.cjs.map +1 -1
- package/dist/markers.mjs.map +1 -1
- package/dist/page-capture.cjs +2 -0
- package/dist/page-capture.cjs.map +7 -0
- package/dist/page-capture.d.cts +115 -0
- package/dist/page-capture.d.mts +115 -0
- package/dist/page-capture.d.ts +115 -0
- package/dist/page-capture.mjs +2 -0
- package/dist/page-capture.mjs.map +7 -0
- package/dist/protocol.cjs +1 -1
- package/dist/protocol.cjs.map +2 -2
- package/dist/protocol.d.cts +12 -0
- package/dist/protocol.d.mts +12 -0
- package/dist/protocol.d.ts +12 -0
- package/dist/protocol.mjs +1 -1
- package/dist/protocol.mjs.map +2 -2
- package/dist/screenshot.d.cts +56 -7
- package/dist/screenshot.d.mts +56 -7
- package/dist/screenshot.d.ts +56 -7
- package/dist/session.d.cts +7 -0
- package/dist/session.d.mts +7 -0
- package/dist/session.d.ts +7 -0
- package/dist/shortcut.d.cts +52 -0
- package/dist/shortcut.d.mts +52 -0
- package/dist/shortcut.d.ts +52 -0
- package/dist/toolbar.d.cts +13 -0
- package/dist/toolbar.d.mts +13 -0
- package/dist/toolbar.d.ts +13 -0
- package/package.json +13 -3
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A picture of what the reviewer saw: the viewport, rendered in the page (A-2385).
|
|
3
|
+
*
|
|
4
|
+
* ===========================================================================
|
|
5
|
+
* THE ONE RUNTIME DEPENDENCY THIS PACKAGE HAS, AND WHY IT IS ALLOWED
|
|
6
|
+
* ===========================================================================
|
|
7
|
+
*
|
|
8
|
+
* The package states, in `README.md`, `ADOPTING.md` and `build.mjs`, that it
|
|
9
|
+
* has no runtime dependencies. `modern-screenshot` is the single, approved
|
|
10
|
+
* exception (owner decision, 2026-10-17, A-2385): the platform cannot
|
|
11
|
+
* rasterise arbitrary DOM without either prompting the reviewer
|
|
12
|
+
* (`getDisplayMedia`) or re-implementing a DOM-to-SVG cloner, and an issue in
|
|
13
|
+
* Linear without a picture of the page is an issue a human has to reproduce
|
|
14
|
+
* before anyone can start on it.
|
|
15
|
+
*
|
|
16
|
+
* It is loaded with a DYNAMIC `import()` inside `loadPageRenderer`, and only
|
|
17
|
+
* there — and THIS MODULE is itself loaded with a dynamic `import()` from
|
|
18
|
+
* `screenshot.ts`, so a product that mounts the SDK and is never clicked
|
|
19
|
+
* downloads neither the library nor this glue (about 1.4KB gzip, which would
|
|
20
|
+
* otherwise sit in `index`). `build.mjs` emits this file as its own entry
|
|
21
|
+
* point, keeps both imports external, and a consumer's bundler splits each
|
|
22
|
+
* into its own chunk. `page-capture.test.ts` bundles `index.ts` and fails if
|
|
23
|
+
* the library lands in the entry chunk.
|
|
24
|
+
*
|
|
25
|
+
* ===========================================================================
|
|
26
|
+
* WHAT IS HONEST ABOUT THE PICTURE, AND WHAT IS NOT
|
|
27
|
+
* ===========================================================================
|
|
28
|
+
*
|
|
29
|
+
* - Canvases are copied as pixels (`toDataURL`). A WebGL canvas created
|
|
30
|
+
* without `preserveDrawingBuffer` has an EMPTY drawing buffer whenever this
|
|
31
|
+
* code runs, because the browser clears it after compositing each frame. No
|
|
32
|
+
* page script can read those pixels back afterwards, so this module does
|
|
33
|
+
* not pretend to: it reads every canvas in the viewport first and counts the
|
|
34
|
+
* ones that come back blank or unreadable (`canvases` on the screenshot), and
|
|
35
|
+
* the issue body says so, rather than shipping a black rectangle silently.
|
|
36
|
+
* - The package's own UI (the toolbar, the composer, the highlight, the
|
|
37
|
+
* markers) is filtered out of the clone, so the picture is of the product
|
|
38
|
+
* and not of the post-it.
|
|
39
|
+
* - Known limitation, stated rather than hidden: on a scrolled page,
|
|
40
|
+
* `position: fixed` content is drawn relative to the document, so a fixed
|
|
41
|
+
* header can be missing from the picture.
|
|
42
|
+
* - No redaction rules exist in this package. Password inputs render as dots,
|
|
43
|
+
* exactly as on the page, because the clone keeps their `type`.
|
|
44
|
+
*
|
|
45
|
+
* NOTHING HERE MAY BREAK A CAPTURE: every path resolves to a screenshot or to
|
|
46
|
+
* null, and `screenshot.ts` falls back to the element bitmap on null.
|
|
47
|
+
*/
|
|
48
|
+
import type { CanvasLike } from "./screenshot.cjs";
|
|
49
|
+
/** What the render receives. Narrow so tests need no browser and no library. */
|
|
50
|
+
export interface PageRenderOptions {
|
|
51
|
+
width: number;
|
|
52
|
+
height: number;
|
|
53
|
+
scale: number;
|
|
54
|
+
/** False for a node the picture must not contain (the package's own UI). */
|
|
55
|
+
filter: (node: Node) => boolean;
|
|
56
|
+
}
|
|
57
|
+
export type PageRenderer = (root: Element, options: PageRenderOptions) => Promise<CanvasLike>;
|
|
58
|
+
/**
|
|
59
|
+
* The library, loaded on first capture. The ONLY reference to it in the
|
|
60
|
+
* package, and it must stay a dynamic import (see the header).
|
|
61
|
+
*/
|
|
62
|
+
export declare function loadPageRenderer(): Promise<PageRenderer>;
|
|
63
|
+
/** What a canvas in the viewport gave back when read. */
|
|
64
|
+
export type CanvasRead = "painted" | "blank" | "unreadable";
|
|
65
|
+
export interface CanvasReadout {
|
|
66
|
+
/** Canvases in the viewport. */
|
|
67
|
+
total: number;
|
|
68
|
+
/** Read back as empty: almost always WebGL without `preserveDrawingBuffer`. */
|
|
69
|
+
blank: number;
|
|
70
|
+
/** Threw on read: tainted by a cross-origin image. */
|
|
71
|
+
unreadable: number;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Read one canvas the way the render will, at 16x16. Blank means every sample
|
|
75
|
+
* is transparent, or every sample is the same opaque black — what a cleared
|
|
76
|
+
* WebGL buffer reads as with and without `alpha`.
|
|
77
|
+
*/
|
|
78
|
+
export declare function readCanvas(source: unknown, createCanvas: () => CanvasLike | null): CanvasRead;
|
|
79
|
+
/** The package's own nodes, by the id prefix every one of them carries. */
|
|
80
|
+
export declare function isPackageUi(node: {
|
|
81
|
+
id?: unknown;
|
|
82
|
+
}): boolean;
|
|
83
|
+
/** Decoded bytes of a base64 data URL, without decoding it. */
|
|
84
|
+
export declare function dataUrlByteLength(dataUrl: string): number;
|
|
85
|
+
export interface ViewportOptions {
|
|
86
|
+
maxWidth: number;
|
|
87
|
+
maxBytes: number;
|
|
88
|
+
createCanvas: () => CanvasLike | null;
|
|
89
|
+
/** Null for the real library. */
|
|
90
|
+
loadRenderer: (() => Promise<PageRenderer>) | null;
|
|
91
|
+
/** Null for `readCanvas` over `createCanvas`. */
|
|
92
|
+
readCanvas: ((canvas: unknown) => CanvasRead) | null;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Encode the rendered canvas within the width and byte caps, shrinking until
|
|
96
|
+
* it fits. Null when even the smallest attempt is over budget, or the canvas
|
|
97
|
+
* cannot be encoded at all.
|
|
98
|
+
*/
|
|
99
|
+
export declare function encodeViewport(rendered: CanvasLike, options: Pick<ViewportOptions, "maxWidth" | "maxBytes" | "createCanvas">): {
|
|
100
|
+
dataUrl: string;
|
|
101
|
+
w: number;
|
|
102
|
+
h: number;
|
|
103
|
+
} | null;
|
|
104
|
+
export interface ViewportShot {
|
|
105
|
+
dataUrl: string;
|
|
106
|
+
region: "viewport";
|
|
107
|
+
w: number;
|
|
108
|
+
h: number;
|
|
109
|
+
canvases?: CanvasReadout;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Render the viewport. Resolves to the picture or to null; never rejects.
|
|
113
|
+
* `ignore` is the host's `ignoreElement`, so a host's own chrome stays out too.
|
|
114
|
+
*/
|
|
115
|
+
export declare function captureViewport(doc: Document, options: ViewportOptions, ignore: ((el: Element) => boolean) | null): Promise<ViewportShot | null>;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A picture of what the reviewer saw: the viewport, rendered in the page (A-2385).
|
|
3
|
+
*
|
|
4
|
+
* ===========================================================================
|
|
5
|
+
* THE ONE RUNTIME DEPENDENCY THIS PACKAGE HAS, AND WHY IT IS ALLOWED
|
|
6
|
+
* ===========================================================================
|
|
7
|
+
*
|
|
8
|
+
* The package states, in `README.md`, `ADOPTING.md` and `build.mjs`, that it
|
|
9
|
+
* has no runtime dependencies. `modern-screenshot` is the single, approved
|
|
10
|
+
* exception (owner decision, 2026-10-17, A-2385): the platform cannot
|
|
11
|
+
* rasterise arbitrary DOM without either prompting the reviewer
|
|
12
|
+
* (`getDisplayMedia`) or re-implementing a DOM-to-SVG cloner, and an issue in
|
|
13
|
+
* Linear without a picture of the page is an issue a human has to reproduce
|
|
14
|
+
* before anyone can start on it.
|
|
15
|
+
*
|
|
16
|
+
* It is loaded with a DYNAMIC `import()` inside `loadPageRenderer`, and only
|
|
17
|
+
* there — and THIS MODULE is itself loaded with a dynamic `import()` from
|
|
18
|
+
* `screenshot.ts`, so a product that mounts the SDK and is never clicked
|
|
19
|
+
* downloads neither the library nor this glue (about 1.4KB gzip, which would
|
|
20
|
+
* otherwise sit in `index`). `build.mjs` emits this file as its own entry
|
|
21
|
+
* point, keeps both imports external, and a consumer's bundler splits each
|
|
22
|
+
* into its own chunk. `page-capture.test.ts` bundles `index.ts` and fails if
|
|
23
|
+
* the library lands in the entry chunk.
|
|
24
|
+
*
|
|
25
|
+
* ===========================================================================
|
|
26
|
+
* WHAT IS HONEST ABOUT THE PICTURE, AND WHAT IS NOT
|
|
27
|
+
* ===========================================================================
|
|
28
|
+
*
|
|
29
|
+
* - Canvases are copied as pixels (`toDataURL`). A WebGL canvas created
|
|
30
|
+
* without `preserveDrawingBuffer` has an EMPTY drawing buffer whenever this
|
|
31
|
+
* code runs, because the browser clears it after compositing each frame. No
|
|
32
|
+
* page script can read those pixels back afterwards, so this module does
|
|
33
|
+
* not pretend to: it reads every canvas in the viewport first and counts the
|
|
34
|
+
* ones that come back blank or unreadable (`canvases` on the screenshot), and
|
|
35
|
+
* the issue body says so, rather than shipping a black rectangle silently.
|
|
36
|
+
* - The package's own UI (the toolbar, the composer, the highlight, the
|
|
37
|
+
* markers) is filtered out of the clone, so the picture is of the product
|
|
38
|
+
* and not of the post-it.
|
|
39
|
+
* - Known limitation, stated rather than hidden: on a scrolled page,
|
|
40
|
+
* `position: fixed` content is drawn relative to the document, so a fixed
|
|
41
|
+
* header can be missing from the picture.
|
|
42
|
+
* - No redaction rules exist in this package. Password inputs render as dots,
|
|
43
|
+
* exactly as on the page, because the clone keeps their `type`.
|
|
44
|
+
*
|
|
45
|
+
* NOTHING HERE MAY BREAK A CAPTURE: every path resolves to a screenshot or to
|
|
46
|
+
* null, and `screenshot.ts` falls back to the element bitmap on null.
|
|
47
|
+
*/
|
|
48
|
+
import type { CanvasLike } from "./screenshot.mjs";
|
|
49
|
+
/** What the render receives. Narrow so tests need no browser and no library. */
|
|
50
|
+
export interface PageRenderOptions {
|
|
51
|
+
width: number;
|
|
52
|
+
height: number;
|
|
53
|
+
scale: number;
|
|
54
|
+
/** False for a node the picture must not contain (the package's own UI). */
|
|
55
|
+
filter: (node: Node) => boolean;
|
|
56
|
+
}
|
|
57
|
+
export type PageRenderer = (root: Element, options: PageRenderOptions) => Promise<CanvasLike>;
|
|
58
|
+
/**
|
|
59
|
+
* The library, loaded on first capture. The ONLY reference to it in the
|
|
60
|
+
* package, and it must stay a dynamic import (see the header).
|
|
61
|
+
*/
|
|
62
|
+
export declare function loadPageRenderer(): Promise<PageRenderer>;
|
|
63
|
+
/** What a canvas in the viewport gave back when read. */
|
|
64
|
+
export type CanvasRead = "painted" | "blank" | "unreadable";
|
|
65
|
+
export interface CanvasReadout {
|
|
66
|
+
/** Canvases in the viewport. */
|
|
67
|
+
total: number;
|
|
68
|
+
/** Read back as empty: almost always WebGL without `preserveDrawingBuffer`. */
|
|
69
|
+
blank: number;
|
|
70
|
+
/** Threw on read: tainted by a cross-origin image. */
|
|
71
|
+
unreadable: number;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Read one canvas the way the render will, at 16x16. Blank means every sample
|
|
75
|
+
* is transparent, or every sample is the same opaque black — what a cleared
|
|
76
|
+
* WebGL buffer reads as with and without `alpha`.
|
|
77
|
+
*/
|
|
78
|
+
export declare function readCanvas(source: unknown, createCanvas: () => CanvasLike | null): CanvasRead;
|
|
79
|
+
/** The package's own nodes, by the id prefix every one of them carries. */
|
|
80
|
+
export declare function isPackageUi(node: {
|
|
81
|
+
id?: unknown;
|
|
82
|
+
}): boolean;
|
|
83
|
+
/** Decoded bytes of a base64 data URL, without decoding it. */
|
|
84
|
+
export declare function dataUrlByteLength(dataUrl: string): number;
|
|
85
|
+
export interface ViewportOptions {
|
|
86
|
+
maxWidth: number;
|
|
87
|
+
maxBytes: number;
|
|
88
|
+
createCanvas: () => CanvasLike | null;
|
|
89
|
+
/** Null for the real library. */
|
|
90
|
+
loadRenderer: (() => Promise<PageRenderer>) | null;
|
|
91
|
+
/** Null for `readCanvas` over `createCanvas`. */
|
|
92
|
+
readCanvas: ((canvas: unknown) => CanvasRead) | null;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Encode the rendered canvas within the width and byte caps, shrinking until
|
|
96
|
+
* it fits. Null when even the smallest attempt is over budget, or the canvas
|
|
97
|
+
* cannot be encoded at all.
|
|
98
|
+
*/
|
|
99
|
+
export declare function encodeViewport(rendered: CanvasLike, options: Pick<ViewportOptions, "maxWidth" | "maxBytes" | "createCanvas">): {
|
|
100
|
+
dataUrl: string;
|
|
101
|
+
w: number;
|
|
102
|
+
h: number;
|
|
103
|
+
} | null;
|
|
104
|
+
export interface ViewportShot {
|
|
105
|
+
dataUrl: string;
|
|
106
|
+
region: "viewport";
|
|
107
|
+
w: number;
|
|
108
|
+
h: number;
|
|
109
|
+
canvases?: CanvasReadout;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Render the viewport. Resolves to the picture or to null; never rejects.
|
|
113
|
+
* `ignore` is the host's `ignoreElement`, so a host's own chrome stays out too.
|
|
114
|
+
*/
|
|
115
|
+
export declare function captureViewport(doc: Document, options: ViewportOptions, ignore: ((el: Element) => boolean) | null): Promise<ViewportShot | null>;
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A picture of what the reviewer saw: the viewport, rendered in the page (A-2385).
|
|
3
|
+
*
|
|
4
|
+
* ===========================================================================
|
|
5
|
+
* THE ONE RUNTIME DEPENDENCY THIS PACKAGE HAS, AND WHY IT IS ALLOWED
|
|
6
|
+
* ===========================================================================
|
|
7
|
+
*
|
|
8
|
+
* The package states, in `README.md`, `ADOPTING.md` and `build.mjs`, that it
|
|
9
|
+
* has no runtime dependencies. `modern-screenshot` is the single, approved
|
|
10
|
+
* exception (owner decision, 2026-10-17, A-2385): the platform cannot
|
|
11
|
+
* rasterise arbitrary DOM without either prompting the reviewer
|
|
12
|
+
* (`getDisplayMedia`) or re-implementing a DOM-to-SVG cloner, and an issue in
|
|
13
|
+
* Linear without a picture of the page is an issue a human has to reproduce
|
|
14
|
+
* before anyone can start on it.
|
|
15
|
+
*
|
|
16
|
+
* It is loaded with a DYNAMIC `import()` inside `loadPageRenderer`, and only
|
|
17
|
+
* there — and THIS MODULE is itself loaded with a dynamic `import()` from
|
|
18
|
+
* `screenshot.ts`, so a product that mounts the SDK and is never clicked
|
|
19
|
+
* downloads neither the library nor this glue (about 1.4KB gzip, which would
|
|
20
|
+
* otherwise sit in `index`). `build.mjs` emits this file as its own entry
|
|
21
|
+
* point, keeps both imports external, and a consumer's bundler splits each
|
|
22
|
+
* into its own chunk. `page-capture.test.ts` bundles `index.ts` and fails if
|
|
23
|
+
* the library lands in the entry chunk.
|
|
24
|
+
*
|
|
25
|
+
* ===========================================================================
|
|
26
|
+
* WHAT IS HONEST ABOUT THE PICTURE, AND WHAT IS NOT
|
|
27
|
+
* ===========================================================================
|
|
28
|
+
*
|
|
29
|
+
* - Canvases are copied as pixels (`toDataURL`). A WebGL canvas created
|
|
30
|
+
* without `preserveDrawingBuffer` has an EMPTY drawing buffer whenever this
|
|
31
|
+
* code runs, because the browser clears it after compositing each frame. No
|
|
32
|
+
* page script can read those pixels back afterwards, so this module does
|
|
33
|
+
* not pretend to: it reads every canvas in the viewport first and counts the
|
|
34
|
+
* ones that come back blank or unreadable (`canvases` on the screenshot), and
|
|
35
|
+
* the issue body says so, rather than shipping a black rectangle silently.
|
|
36
|
+
* - The package's own UI (the toolbar, the composer, the highlight, the
|
|
37
|
+
* markers) is filtered out of the clone, so the picture is of the product
|
|
38
|
+
* and not of the post-it.
|
|
39
|
+
* - Known limitation, stated rather than hidden: on a scrolled page,
|
|
40
|
+
* `position: fixed` content is drawn relative to the document, so a fixed
|
|
41
|
+
* header can be missing from the picture.
|
|
42
|
+
* - No redaction rules exist in this package. Password inputs render as dots,
|
|
43
|
+
* exactly as on the page, because the clone keeps their `type`.
|
|
44
|
+
*
|
|
45
|
+
* NOTHING HERE MAY BREAK A CAPTURE: every path resolves to a screenshot or to
|
|
46
|
+
* null, and `screenshot.ts` falls back to the element bitmap on null.
|
|
47
|
+
*/
|
|
48
|
+
import type { CanvasLike } from "./screenshot.js";
|
|
49
|
+
/** What the render receives. Narrow so tests need no browser and no library. */
|
|
50
|
+
export interface PageRenderOptions {
|
|
51
|
+
width: number;
|
|
52
|
+
height: number;
|
|
53
|
+
scale: number;
|
|
54
|
+
/** False for a node the picture must not contain (the package's own UI). */
|
|
55
|
+
filter: (node: Node) => boolean;
|
|
56
|
+
}
|
|
57
|
+
export type PageRenderer = (root: Element, options: PageRenderOptions) => Promise<CanvasLike>;
|
|
58
|
+
/**
|
|
59
|
+
* The library, loaded on first capture. The ONLY reference to it in the
|
|
60
|
+
* package, and it must stay a dynamic import (see the header).
|
|
61
|
+
*/
|
|
62
|
+
export declare function loadPageRenderer(): Promise<PageRenderer>;
|
|
63
|
+
/** What a canvas in the viewport gave back when read. */
|
|
64
|
+
export type CanvasRead = "painted" | "blank" | "unreadable";
|
|
65
|
+
export interface CanvasReadout {
|
|
66
|
+
/** Canvases in the viewport. */
|
|
67
|
+
total: number;
|
|
68
|
+
/** Read back as empty: almost always WebGL without `preserveDrawingBuffer`. */
|
|
69
|
+
blank: number;
|
|
70
|
+
/** Threw on read: tainted by a cross-origin image. */
|
|
71
|
+
unreadable: number;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Read one canvas the way the render will, at 16x16. Blank means every sample
|
|
75
|
+
* is transparent, or every sample is the same opaque black — what a cleared
|
|
76
|
+
* WebGL buffer reads as with and without `alpha`.
|
|
77
|
+
*/
|
|
78
|
+
export declare function readCanvas(source: unknown, createCanvas: () => CanvasLike | null): CanvasRead;
|
|
79
|
+
/** The package's own nodes, by the id prefix every one of them carries. */
|
|
80
|
+
export declare function isPackageUi(node: {
|
|
81
|
+
id?: unknown;
|
|
82
|
+
}): boolean;
|
|
83
|
+
/** Decoded bytes of a base64 data URL, without decoding it. */
|
|
84
|
+
export declare function dataUrlByteLength(dataUrl: string): number;
|
|
85
|
+
export interface ViewportOptions {
|
|
86
|
+
maxWidth: number;
|
|
87
|
+
maxBytes: number;
|
|
88
|
+
createCanvas: () => CanvasLike | null;
|
|
89
|
+
/** Null for the real library. */
|
|
90
|
+
loadRenderer: (() => Promise<PageRenderer>) | null;
|
|
91
|
+
/** Null for `readCanvas` over `createCanvas`. */
|
|
92
|
+
readCanvas: ((canvas: unknown) => CanvasRead) | null;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Encode the rendered canvas within the width and byte caps, shrinking until
|
|
96
|
+
* it fits. Null when even the smallest attempt is over budget, or the canvas
|
|
97
|
+
* cannot be encoded at all.
|
|
98
|
+
*/
|
|
99
|
+
export declare function encodeViewport(rendered: CanvasLike, options: Pick<ViewportOptions, "maxWidth" | "maxBytes" | "createCanvas">): {
|
|
100
|
+
dataUrl: string;
|
|
101
|
+
w: number;
|
|
102
|
+
h: number;
|
|
103
|
+
} | null;
|
|
104
|
+
export interface ViewportShot {
|
|
105
|
+
dataUrl: string;
|
|
106
|
+
region: "viewport";
|
|
107
|
+
w: number;
|
|
108
|
+
h: number;
|
|
109
|
+
canvases?: CanvasReadout;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Render the viewport. Resolves to the picture or to null; never rejects.
|
|
113
|
+
* `ignore` is the host's `ignoreElement`, so a host's own chrome stays out too.
|
|
114
|
+
*/
|
|
115
|
+
export declare function captureViewport(doc: Document, options: ViewportOptions, ignore: ((el: Element) => boolean) | null): Promise<ViewportShot | null>;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
async function v(){let{domToCanvas:e}=await import("modern-screenshot");return(n,t)=>e(n,{width:t.width,height:t.height,scale:t.scale,filter:t.filter,backgroundColor:"Canvas",features:{restoreScrollPosition:!0}})}var d=16;function w(e,n){try{let t=n();if(!t)return"unreadable";t.width=d,t.height=d;let a=t.getContext("2d");if(!a||typeof a.getImageData!="function")return"unreadable";a.drawImage(e,0,0,d,d);let o=a.getImageData(0,0,d,d).data,i=!0,l=!0;for(let r=0;r+3<o.length;r+=4){let[u,m,b,h]=[o[r],o[r+1],o[r+2],o[r+3]];if(h!==0&&(i=!1),(u!==0||m!==0||b!==0||h!==255)&&(l=!1),!i&&!l)return"painted"}return"blank"}catch{return"unreadable"}}function x(e){return typeof e.id=="string"&&e.id.startsWith("ai-annotation-")}function C(e){let n=e.indexOf(",");if(n<0)return e.length;let t=e.slice(n+1),a=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.floor(t.length*3/4)-a}var k=[.82,.62],y=.75,p=320;function R(e,n){if(!(e.width>0&&e.height>0))return null;let t=Math.min(e.width,n.maxWidth);for(;;){let a=Math.max(1,Math.round(e.height*t/e.width));for(let o of k){let i=P(e,t,a,o,n.createCanvas);if(i===null)return null;if(C(i)<=n.maxBytes)return{dataUrl:i,w:t,h:a}}if(t<=p)return null;t=Math.max(p,Math.round(t*y))}}function P(e,n,t,a,o){try{let i=e;if(n!==e.width||t!==e.height){let r=o();if(!r)return null;r.width=n,r.height=t;let u=r.getContext("2d");if(!u)return null;u.drawImage(e,0,0,n,t),i=r}let l=i.toDataURL("image/jpeg",a);return typeof l=="string"&&/^data:image\/(jpeg|png);base64,/.test(l)?l:null}catch{return null}}async function L(e,n,t){try{let a=e.defaultView,o=e.documentElement,i=Math.round(a?.innerWidth??o.clientWidth),l=Math.round(a?.innerHeight??o.clientHeight);if(!(i>0&&l>0))return null;let r=s=>x(s)||(t?.(s)??!1),u={total:0,blank:0,unreadable:0};for(let s of Array.from(e.querySelectorAll("canvas"))){if(r(s))continue;let c=s.getBoundingClientRect();if(!(c.width>0&&c.height>0&&c.right>0&&c.bottom>0&&c.left<i&&c.top<l))continue;u.total++;let g=n.readCanvas?n.readCanvas(s):w(s,n.createCanvas);g==="blank"&&u.blank++,g==="unreadable"&&u.unreadable++}let m=await(n.loadRenderer??v)(),b=a?.devicePixelRatio&&a.devicePixelRatio>0?a.devicePixelRatio:1,h=await m(o,{width:i,height:l,scale:Math.min(b,n.maxWidth/i),filter:s=>!(s.nodeType===1&&r(s))}),f=R(h,n);return f?{...f,region:"viewport",...u.total>0?{canvases:u}:{}}:null}catch{return null}}export{L as captureViewport,C as dataUrlByteLength,R as encodeViewport,x as isPackageUi,v as loadPageRenderer,w as readCanvas};
|
|
2
|
+
//# sourceMappingURL=page-capture.mjs.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/page-capture.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * A picture of what the reviewer saw: the viewport, rendered in the page (A-2385).\n *\n * ===========================================================================\n * THE ONE RUNTIME DEPENDENCY THIS PACKAGE HAS, AND WHY IT IS ALLOWED\n * ===========================================================================\n *\n * The package states, in `README.md`, `ADOPTING.md` and `build.mjs`, that it\n * has no runtime dependencies. `modern-screenshot` is the single, approved\n * exception (owner decision, 2026-10-17, A-2385): the platform cannot\n * rasterise arbitrary DOM without either prompting the reviewer\n * (`getDisplayMedia`) or re-implementing a DOM-to-SVG cloner, and an issue in\n * Linear without a picture of the page is an issue a human has to reproduce\n * before anyone can start on it.\n *\n * It is loaded with a DYNAMIC `import()` inside `loadPageRenderer`, and only\n * there \u2014 and THIS MODULE is itself loaded with a dynamic `import()` from\n * `screenshot.ts`, so a product that mounts the SDK and is never clicked\n * downloads neither the library nor this glue (about 1.4KB gzip, which would\n * otherwise sit in `index`). `build.mjs` emits this file as its own entry\n * point, keeps both imports external, and a consumer's bundler splits each\n * into its own chunk. `page-capture.test.ts` bundles `index.ts` and fails if\n * the library lands in the entry chunk.\n *\n * ===========================================================================\n * WHAT IS HONEST ABOUT THE PICTURE, AND WHAT IS NOT\n * ===========================================================================\n *\n * - Canvases are copied as pixels (`toDataURL`). A WebGL canvas created\n * without `preserveDrawingBuffer` has an EMPTY drawing buffer whenever this\n * code runs, because the browser clears it after compositing each frame. No\n * page script can read those pixels back afterwards, so this module does\n * not pretend to: it reads every canvas in the viewport first and counts the\n * ones that come back blank or unreadable (`canvases` on the screenshot), and\n * the issue body says so, rather than shipping a black rectangle silently.\n * - The package's own UI (the toolbar, the composer, the highlight, the\n * markers) is filtered out of the clone, so the picture is of the product\n * and not of the post-it.\n * - Known limitation, stated rather than hidden: on a scrolled page,\n * `position: fixed` content is drawn relative to the document, so a fixed\n * header can be missing from the picture.\n * - No redaction rules exist in this package. Password inputs render as dots,\n * exactly as on the page, because the clone keeps their `type`.\n *\n * NOTHING HERE MAY BREAK A CAPTURE: every path resolves to a screenshot or to\n * null, and `screenshot.ts` falls back to the element bitmap on null.\n */\n\nimport type { CanvasLike } from \"./screenshot\";\n\n/** What the render receives. Narrow so tests need no browser and no library. */\nexport interface PageRenderOptions {\n width: number;\n height: number;\n scale: number;\n /** False for a node the picture must not contain (the package's own UI). */\n filter: (node: Node) => boolean;\n}\n\nexport type PageRenderer = (root: Element, options: PageRenderOptions) => Promise<CanvasLike>;\n\n/**\n * The library, loaded on first capture. The ONLY reference to it in the\n * package, and it must stay a dynamic import (see the header).\n */\nexport async function loadPageRenderer(): Promise<PageRenderer> {\n const { domToCanvas } = await import(\"modern-screenshot\");\n return (root, options) =>\n domToCanvas(root, {\n width: options.width,\n height: options.height,\n scale: options.scale,\n filter: options.filter,\n // JPEG has no alpha. The browser's Canvas colour follows the page's\n // colour scheme, so a transparent page keeps its actual backdrop.\n backgroundColor: \"Canvas\",\n features: { restoreScrollPosition: true },\n });\n}\n\n/** What a canvas in the viewport gave back when read. */\nexport type CanvasRead = \"painted\" | \"blank\" | \"unreadable\";\n\nexport interface CanvasReadout {\n /** Canvases in the viewport. */\n total: number;\n /** Read back as empty: almost always WebGL without `preserveDrawingBuffer`. */\n blank: number;\n /** Threw on read: tainted by a cross-origin image. */\n unreadable: number;\n}\n\ninterface ProbeContext {\n drawImage(source: unknown, dx: number, dy: number, dw: number, dh: number): void;\n getImageData(sx: number, sy: number, sw: number, sh: number): { data: ArrayLike<number> };\n}\n\nconst PROBE_EDGE = 16;\n\n/**\n * Read one canvas the way the render will, at 16x16. Blank means every sample\n * is transparent, or every sample is the same opaque black \u2014 what a cleared\n * WebGL buffer reads as with and without `alpha`.\n */\nexport function readCanvas(source: unknown, createCanvas: () => CanvasLike | null): CanvasRead {\n try {\n const probe = createCanvas();\n if (!probe) return \"unreadable\";\n probe.width = PROBE_EDGE;\n probe.height = PROBE_EDGE;\n const ctx = probe.getContext(\"2d\") as unknown as ProbeContext | null;\n if (!ctx || typeof ctx.getImageData !== \"function\") return \"unreadable\";\n ctx.drawImage(source, 0, 0, PROBE_EDGE, PROBE_EDGE);\n const data = ctx.getImageData(0, 0, PROBE_EDGE, PROBE_EDGE).data;\n let transparent = true;\n let black = true;\n for (let i = 0; i + 3 < data.length; i += 4) {\n const [r, g, b, a] = [data[i], data[i + 1], data[i + 2], data[i + 3]];\n if (a !== 0) transparent = false;\n if (r !== 0 || g !== 0 || b !== 0 || a !== 255) black = false;\n if (!transparent && !black) return \"painted\";\n }\n return \"blank\";\n } catch {\n return \"unreadable\";\n }\n}\n\n/** The package's own nodes, by the id prefix every one of them carries. */\nexport function isPackageUi(node: { id?: unknown }): boolean {\n return typeof node.id === \"string\" && node.id.startsWith(\"ai-annotation-\");\n}\n\n/** Decoded bytes of a base64 data URL, without decoding it. */\nexport function dataUrlByteLength(dataUrl: string): number {\n const comma = dataUrl.indexOf(\",\");\n if (comma < 0) return dataUrl.length;\n const body = dataUrl.slice(comma + 1);\n const padding = body.endsWith(\"==\") ? 2 : body.endsWith(\"=\") ? 1 : 0;\n return Math.floor((body.length * 3) / 4) - padding;\n}\n\nexport interface ViewportOptions {\n maxWidth: number;\n maxBytes: number;\n createCanvas: () => CanvasLike | null;\n /** Null for the real library. */\n loadRenderer: (() => Promise<PageRenderer>) | null;\n /** Null for `readCanvas` over `createCanvas`. */\n readCanvas: ((canvas: unknown) => CanvasRead) | null;\n}\n\n/**\n * Quality first, then size: a 1600px JPEG at 0.6 is still legible, and a\n * smaller picture is only worth having once quality has given what it can.\n */\nconst QUALITIES = [0.82, 0.62] as const;\nconst SHRINK = 0.75;\nconst MIN_WIDTH = 320;\n\n/**\n * Encode the rendered canvas within the width and byte caps, shrinking until\n * it fits. Null when even the smallest attempt is over budget, or the canvas\n * cannot be encoded at all.\n */\nexport function encodeViewport(\n rendered: CanvasLike,\n options: Pick<ViewportOptions, \"maxWidth\" | \"maxBytes\" | \"createCanvas\">,\n): { dataUrl: string; w: number; h: number } | null {\n if (!(rendered.width > 0 && rendered.height > 0)) return null;\n let w = Math.min(rendered.width, options.maxWidth);\n for (;;) {\n const h = Math.max(1, Math.round((rendered.height * w) / rendered.width));\n for (const quality of QUALITIES) {\n const dataUrl = encodeAt(rendered, w, h, quality, options.createCanvas);\n if (dataUrl === null) return null;\n if (dataUrlByteLength(dataUrl) <= options.maxBytes) return { dataUrl, w, h };\n }\n if (w <= MIN_WIDTH) return null;\n w = Math.max(MIN_WIDTH, Math.round(w * SHRINK));\n }\n}\n\nfunction encodeAt(\n rendered: CanvasLike,\n w: number,\n h: number,\n quality: number,\n createCanvas: () => CanvasLike | null,\n): string | null {\n try {\n let target = rendered;\n if (w !== rendered.width || h !== rendered.height) {\n const scaled = createCanvas();\n if (!scaled) return null;\n scaled.width = w;\n scaled.height = h;\n const ctx = scaled.getContext(\"2d\");\n if (!ctx) return null;\n ctx.drawImage(rendered, 0, 0, w, h);\n target = scaled;\n }\n const dataUrl = target.toDataURL(\"image/jpeg\", quality);\n // A canvas that cannot do JPEG returns PNG; that is still an image we accept.\n return typeof dataUrl === \"string\" && /^data:image\\/(jpeg|png);base64,/.test(dataUrl)\n ? dataUrl\n : null;\n } catch {\n return null;\n }\n}\n\nexport interface ViewportShot {\n dataUrl: string;\n region: \"viewport\";\n w: number;\n h: number;\n canvases?: CanvasReadout;\n}\n\n/**\n * Render the viewport. Resolves to the picture or to null; never rejects.\n * `ignore` is the host's `ignoreElement`, so a host's own chrome stays out too.\n */\nexport async function captureViewport(\n doc: Document,\n options: ViewportOptions,\n ignore: ((el: Element) => boolean) | null,\n): Promise<ViewportShot | null> {\n try {\n const win = doc.defaultView;\n const root = doc.documentElement;\n const width = Math.round(win?.innerWidth ?? root.clientWidth);\n const height = Math.round(win?.innerHeight ?? root.clientHeight);\n if (!(width > 0 && height > 0)) return null;\n\n const ours = (el: Element): boolean => isPackageUi(el) || (ignore?.(el) ?? false);\n\n // Read the canvases BEFORE the render, as the render will read them.\n const readout: CanvasReadout = { total: 0, blank: 0, unreadable: 0 };\n for (const canvas of Array.from(doc.querySelectorAll(\"canvas\"))) {\n if (ours(canvas)) continue;\n const box = canvas.getBoundingClientRect();\n const visible =\n box.width > 0 && box.height > 0 && box.right > 0 && box.bottom > 0 && box.left < width && box.top < height;\n if (!visible) continue;\n readout.total++;\n const read = options.readCanvas ? options.readCanvas(canvas) : readCanvas(canvas, options.createCanvas);\n if (read === \"blank\") readout.blank++;\n if (read === \"unreadable\") readout.unreadable++;\n }\n\n const render = await (options.loadRenderer ?? loadPageRenderer)();\n const dpr = win?.devicePixelRatio && win.devicePixelRatio > 0 ? win.devicePixelRatio : 1;\n const rendered = await render(root, {\n width,\n height,\n scale: Math.min(dpr, options.maxWidth / width),\n filter: (node) => !(node.nodeType === 1 && ours(node as Element)),\n });\n const encoded = encodeViewport(rendered, options);\n if (!encoded) return null;\n return { ...encoded, region: \"viewport\", ...(readout.total > 0 ? { canvases: readout } : {}) };\n } catch {\n return null;\n }\n}\n"],
|
|
5
|
+
"mappings": "AAiEA,eAAsBA,GAA0C,CAC9D,GAAM,CAAE,YAAAC,CAAY,EAAI,KAAM,QAAO,mBAAmB,EACxD,MAAO,CAACC,EAAMC,IACZF,EAAYC,EAAM,CAChB,MAAOC,EAAQ,MACf,OAAQA,EAAQ,OAChB,MAAOA,EAAQ,MACf,OAAQA,EAAQ,OAGhB,gBAAiB,SACjB,SAAU,CAAE,sBAAuB,EAAK,CAC1C,CAAC,CACL,CAmBA,IAAMC,EAAa,GAOZ,SAASC,EAAWC,EAAiBC,EAAmD,CAC7F,GAAI,CACF,IAAMC,EAAQD,EAAa,EAC3B,GAAI,CAACC,EAAO,MAAO,aACnBA,EAAM,MAAQJ,EACdI,EAAM,OAASJ,EACf,IAAMK,EAAMD,EAAM,WAAW,IAAI,EACjC,GAAI,CAACC,GAAO,OAAOA,EAAI,cAAiB,WAAY,MAAO,aAC3DA,EAAI,UAAUH,EAAQ,EAAG,EAAGF,EAAYA,CAAU,EAClD,IAAMM,EAAOD,EAAI,aAAa,EAAG,EAAGL,EAAYA,CAAU,EAAE,KACxDO,EAAc,GACdC,EAAQ,GACZ,QAASC,EAAI,EAAGA,EAAI,EAAIH,EAAK,OAAQG,GAAK,EAAG,CAC3C,GAAM,CAACC,EAAGC,EAAG,EAAGC,CAAC,EAAI,CAACN,EAAKG,CAAC,EAAGH,EAAKG,EAAI,CAAC,EAAGH,EAAKG,EAAI,CAAC,EAAGH,EAAKG,EAAI,CAAC,CAAC,EAGpE,GAFIG,IAAM,IAAGL,EAAc,KACvBG,IAAM,GAAKC,IAAM,GAAK,IAAM,GAAKC,IAAM,OAAKJ,EAAQ,IACpD,CAACD,GAAe,CAACC,EAAO,MAAO,SACrC,CACA,MAAO,OACT,MAAQ,CACN,MAAO,YACT,CACF,CAGO,SAASK,EAAYC,EAAiC,CAC3D,OAAO,OAAOA,EAAK,IAAO,UAAYA,EAAK,GAAG,WAAW,gBAAgB,CAC3E,CAGO,SAASC,EAAkBC,EAAyB,CACzD,IAAMC,EAAQD,EAAQ,QAAQ,GAAG,EACjC,GAAIC,EAAQ,EAAG,OAAOD,EAAQ,OAC9B,IAAME,EAAOF,EAAQ,MAAMC,EAAQ,CAAC,EAC9BE,EAAUD,EAAK,SAAS,IAAI,EAAI,EAAIA,EAAK,SAAS,GAAG,EAAI,EAAI,EACnE,OAAO,KAAK,MAAOA,EAAK,OAAS,EAAK,CAAC,EAAIC,CAC7C,CAgBA,IAAMC,EAAY,CAAC,IAAM,GAAI,EACvBC,EAAS,IACTC,EAAY,IAOX,SAASC,EACdC,EACAzB,EACkD,CAClD,GAAI,EAAEyB,EAAS,MAAQ,GAAKA,EAAS,OAAS,GAAI,OAAO,KACzD,IAAIC,EAAI,KAAK,IAAID,EAAS,MAAOzB,EAAQ,QAAQ,EACjD,OAAS,CACP,IAAM2B,EAAI,KAAK,IAAI,EAAG,KAAK,MAAOF,EAAS,OAASC,EAAKD,EAAS,KAAK,CAAC,EACxE,QAAWG,KAAWP,EAAW,CAC/B,IAAMJ,EAAUY,EAASJ,EAAUC,EAAGC,EAAGC,EAAS5B,EAAQ,YAAY,EACtE,GAAIiB,IAAY,KAAM,OAAO,KAC7B,GAAID,EAAkBC,CAAO,GAAKjB,EAAQ,SAAU,MAAO,CAAE,QAAAiB,EAAS,EAAAS,EAAG,EAAAC,CAAE,CAC7E,CACA,GAAID,GAAKH,EAAW,OAAO,KAC3BG,EAAI,KAAK,IAAIH,EAAW,KAAK,MAAMG,EAAIJ,CAAM,CAAC,CAChD,CACF,CAEA,SAASO,EACPJ,EACAC,EACAC,EACAC,EACAxB,EACe,CACf,GAAI,CACF,IAAI0B,EAASL,EACb,GAAIC,IAAMD,EAAS,OAASE,IAAMF,EAAS,OAAQ,CACjD,IAAMM,EAAS3B,EAAa,EAC5B,GAAI,CAAC2B,EAAQ,OAAO,KACpBA,EAAO,MAAQL,EACfK,EAAO,OAASJ,EAChB,IAAMrB,EAAMyB,EAAO,WAAW,IAAI,EAClC,GAAI,CAACzB,EAAK,OAAO,KACjBA,EAAI,UAAUmB,EAAU,EAAG,EAAGC,EAAGC,CAAC,EAClCG,EAASC,CACX,CACA,IAAMd,EAAUa,EAAO,UAAU,aAAcF,CAAO,EAEtD,OAAO,OAAOX,GAAY,UAAY,kCAAkC,KAAKA,CAAO,EAChFA,EACA,IACN,MAAQ,CACN,OAAO,IACT,CACF,CAcA,eAAsBe,EACpBC,EACAjC,EACAkC,EAC8B,CAC9B,GAAI,CACF,IAAMC,EAAMF,EAAI,YACVlC,EAAOkC,EAAI,gBACXG,EAAQ,KAAK,MAAMD,GAAK,YAAcpC,EAAK,WAAW,EACtDsC,EAAS,KAAK,MAAMF,GAAK,aAAepC,EAAK,YAAY,EAC/D,GAAI,EAAEqC,EAAQ,GAAKC,EAAS,GAAI,OAAO,KAEvC,IAAMC,EAAQC,GAAyBzB,EAAYyB,CAAE,IAAML,IAASK,CAAE,GAAK,IAGrEC,EAAyB,CAAE,MAAO,EAAG,MAAO,EAAG,WAAY,CAAE,EACnE,QAAWC,KAAU,MAAM,KAAKR,EAAI,iBAAiB,QAAQ,CAAC,EAAG,CAC/D,GAAIK,EAAKG,CAAM,EAAG,SAClB,IAAMC,EAAMD,EAAO,sBAAsB,EAGzC,GAAI,EADFC,EAAI,MAAQ,GAAKA,EAAI,OAAS,GAAKA,EAAI,MAAQ,GAAKA,EAAI,OAAS,GAAKA,EAAI,KAAON,GAASM,EAAI,IAAML,GACxF,SACdG,EAAQ,QACR,IAAMG,EAAO3C,EAAQ,WAAaA,EAAQ,WAAWyC,CAAM,EAAIvC,EAAWuC,EAAQzC,EAAQ,YAAY,EAClG2C,IAAS,SAASH,EAAQ,QAC1BG,IAAS,cAAcH,EAAQ,YACrC,CAEA,IAAMI,EAAS,MAAO5C,EAAQ,cAAgBH,GAAkB,EAC1DgD,EAAMV,GAAK,kBAAoBA,EAAI,iBAAmB,EAAIA,EAAI,iBAAmB,EACjFV,EAAW,MAAMmB,EAAO7C,EAAM,CAClC,MAAAqC,EACA,OAAAC,EACA,MAAO,KAAK,IAAIQ,EAAK7C,EAAQ,SAAWoC,CAAK,EAC7C,OAASrB,GAAS,EAAEA,EAAK,WAAa,GAAKuB,EAAKvB,CAAe,EACjE,CAAC,EACK+B,EAAUtB,EAAeC,EAAUzB,CAAO,EAChD,OAAK8C,EACE,CAAE,GAAGA,EAAS,OAAQ,WAAY,GAAIN,EAAQ,MAAQ,EAAI,CAAE,SAAUA,CAAQ,EAAI,CAAC,CAAG,EADxE,IAEvB,MAAQ,CACN,OAAO,IACT,CACF",
|
|
6
|
+
"names": ["loadPageRenderer", "domToCanvas", "root", "options", "PROBE_EDGE", "readCanvas", "source", "createCanvas", "probe", "ctx", "data", "transparent", "black", "i", "r", "g", "a", "isPackageUi", "node", "dataUrlByteLength", "dataUrl", "comma", "body", "padding", "QUALITIES", "SHRINK", "MIN_WIDTH", "encodeViewport", "rendered", "w", "h", "quality", "encodeAt", "target", "scaled", "captureViewport", "doc", "ignore", "win", "width", "height", "ours", "el", "readout", "canvas", "box", "read", "render", "dpr", "encoded"]
|
|
7
|
+
}
|
package/dist/protocol.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var a=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var
|
|
1
|
+
"use strict";var a=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var m=Object.getOwnPropertyNames;var d=Object.prototype.hasOwnProperty;var f=(t,e)=>{for(var n in e)a(t,n,{get:e[n],enumerable:!0})},T=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of m(e))!d.call(t,r)&&r!==n&&a(t,r,{get:()=>e[r],enumerable:!(o=A(e,r))||o.enumerable});return t};var N=t=>T(a({},"__esModule",{value:!0}),t);var L={};f(L,{ANNOTATION_ARMED_COOKIE:()=>i,ANNOTATION_ARMED_COOKIES:()=>l,ANNOTATION_ARMED_VALUE:()=>c,ANNOTATION_MODE_HEADER:()=>x,ANNOTATION_TOKEN_PARAM:()=>s,ANNOTATION_TOKEN_PARAMS:()=>g,CAPTURE_TOKEN_PARAM:()=>P,FIRST_PARTY_ANNOTATION_MODE:()=>O,LEGACY_ANNOTATION_ARMED_COOKIE:()=>p,LEGACY_ANNOTATION_TOKEN_PARAM:()=>u,NAME_ATTR:()=>b,READ_TOKEN_PARAM:()=>k,REVIEW_RUN_PARAM:()=>M,SDK_VERSION:()=>_,SRC_ATTR:()=>E,armedCookie:()=>C,assertConcreteOrigin:()=>w,clearedCookie:()=>v,isAnnotationArmed:()=>D,isParentMessage:()=>S,readAnnotationToken:()=>K,selectionOf:()=>R,unhandledMessage:()=>h});module.exports=N(L);var _="1",x="x-weatherboard-annotation-mode",O="first-party",E="data-src",b="data-src-name";function R(t){return t.selection==="region"?"region":"element"}function y(t){try{return JSON.stringify(t)??String(t)}catch{return"[unserialisable]"}}function h(t,e){console.error(`[annotation] ${t}: protocol drift, nothing was acted on: ${y(e)}`)}var I=new Set(["annotate:enable","annotate:disable","annotate:ping"]);function S(t){if(typeof t!="object"||t===null)return!1;let e=t.type;return typeof e=="string"&&I.has(e)}function w(t){if(!t||t==="*")throw new Error("[annotation] a concrete parent origin is required; '*' would broadcast annotation payloads to any embedder.");return t}var s="ai_annotate",i="ai_annotate_armed",P="ai_capture",M="ai_run",k="ai_read",c="1";function C(t=i){return`${t}=${c}; Path=/; SameSite=Lax; Secure`}function v(t){return`${t}=; Path=/; SameSite=Lax; Secure; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT`}var u="pits_annotate",p="pits_annotate_armed",g=[s,u],l=[i,p];function D(t){return t.split(";").some(e=>{let n=e.trimStart();return l.some(o=>n.startsWith(`${o}=`))})}function K(t){for(let e of g){let n=t.get(e);if(n!==null&&n.length>0)return n}return null}
|
|
2
2
|
//# sourceMappingURL=protocol.cjs.map
|
package/dist/protocol.cjs.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/protocol.ts"],
|
|
4
|
-
"sourcesContent": ["/**\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"],
|
|
5
|
-
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,6BAAAE,EAAA,6BAAAC,EAAA,2BAAAC,EAAA,2BAAAC,EAAA,2BAAAC,EAAA,4BAAAC,EAAA,wBAAAC,EAAA,gCAAAC,EAAA,mCAAAC,EAAA,kCAAAC,EAAA,cAAAC,EAAA,qBAAAC,EAAA,qBAAAC,EAAA,gBAAAC,EAAA,aAAAC,EAAA,gBAAAC,EAAA,yBAAAC,EAAA,kBAAAC,EAAA,sBAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,gBAAAC,EAAA,qBAAAC,IAAA,eAAAC,EAAAzB,GASO,IAAMe,EAAc,IAMdV,EAAyB,iCACzBI,EAA8B,cAmB9BO,EAAW,WACXJ,EAAY,gBAoHlB,SAASW,EAAYG,EAA6D,CACvF,OAAOA,EAAO,YAAc,SAAW,SAAW,SACpD,
|
|
4
|
+
"sourcesContent": ["/**\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 /**\n * `w`/`h` and `canvases` arrive with the in-page viewport capture (A-2385);\n * `canvases` counts the canvases in view and how many read back blank or\n * unreadable, so a black rectangle in the picture is explained, not silent.\n */\n screenshot?: {\n dataUrl: string;\n region: \"element\" | \"viewport\";\n w?: number;\n h?: number;\n canvases?: { total: number; blank: number; unreadable: number };\n };\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"],
|
|
5
|
+
"mappings": "yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,6BAAAE,EAAA,6BAAAC,EAAA,2BAAAC,EAAA,2BAAAC,EAAA,2BAAAC,EAAA,4BAAAC,EAAA,wBAAAC,EAAA,gCAAAC,EAAA,mCAAAC,EAAA,kCAAAC,EAAA,cAAAC,EAAA,qBAAAC,EAAA,qBAAAC,EAAA,gBAAAC,EAAA,aAAAC,EAAA,gBAAAC,EAAA,yBAAAC,EAAA,kBAAAC,EAAA,sBAAAC,EAAA,oBAAAC,EAAA,wBAAAC,EAAA,gBAAAC,EAAA,qBAAAC,IAAA,eAAAC,EAAAzB,GASO,IAAMe,EAAc,IAMdV,EAAyB,iCACzBI,EAA8B,cAmB9BO,EAAW,WACXJ,EAAY,gBAoHlB,SAASW,EAAYG,EAA6D,CACvF,OAAOA,EAAO,YAAc,SAAW,SAAW,SACpD,CA2JA,SAASC,EAASC,EAA0B,CAC1C,GAAI,CACF,OAAO,KAAK,UAAUA,CAAO,GAAK,OAAOA,CAAO,CAClD,MAAQ,CACN,MAAO,kBACT,CACF,CAEO,SAASJ,EAAiBK,EAAwBD,EAAwB,CAkB/E,QAAQ,MAAM,gBAAgBC,CAAI,2CAA2CF,EAASC,CAAO,CAAC,EAAE,CAClG,CAEA,IAAME,EAAe,IAAI,IAAI,CAAC,kBAAmB,mBAAoB,eAAe,CAAC,EAQ9E,SAAST,EAAgBU,EAAsC,CACpE,GAAI,OAAOA,GAAS,UAAYA,IAAS,KAAM,MAAO,GACtD,IAAMC,EAAQD,EAA4B,KAC1C,OAAO,OAAOC,GAAS,UAAYF,EAAa,IAAIE,CAAI,CAC1D,CAUO,SAASd,EAAqBe,EAAwB,CAC3D,GAAI,CAACA,GAAUA,IAAW,IACxB,MAAM,IAAI,MACR,6GAEF,EAEF,OAAOA,CACT,CAkBO,IAAM3B,EAAyB,cACzBJ,EAA0B,oBA0B1BM,EAAsB,aAetBM,EAAmB,SA8BnBD,EAAmB,UAkDnBT,EAAyB,IAE/B,SAASa,EAAYiB,EAAehC,EAAiC,CAC1E,MAAO,GAAGgC,CAAI,IAAI9B,CAAsB,gCAC1C,CAUO,SAASe,EAAce,EAAsB,CAClD,MAAO,GAAGA,CAAI,mFAChB,CAwCO,IAAMvB,EAAgC,gBAChCD,EAAiC,sBA2CjCH,EAA0B,CACrCD,EACAK,CACF,EAGaR,EAA2B,CACtCD,EACAQ,CACF,EAUO,SAASU,EAAkBe,EAAyB,CACzD,OAAOA,EACJ,MAAM,GAAG,EACT,KAAMC,GAAU,CACf,IAAMC,EAAUD,EAAM,UAAU,EAChC,OAAOjC,EAAyB,KAAM+B,GAASG,EAAQ,WAAW,GAAGH,CAAI,GAAG,CAAC,CAC/E,CAAC,CACL,CASO,SAASZ,EAAoBgB,EAAwC,CAC1E,QAAWJ,KAAQ3B,EAAyB,CAC1C,IAAMgC,EAAQD,EAAO,IAAIJ,CAAI,EAC7B,GAAIK,IAAU,MAAQA,EAAM,OAAS,EAAG,OAAOA,CACjD,CACA,OAAO,IACT",
|
|
6
6
|
"names": ["protocol_exports", "__export", "ANNOTATION_ARMED_COOKIE", "ANNOTATION_ARMED_COOKIES", "ANNOTATION_ARMED_VALUE", "ANNOTATION_MODE_HEADER", "ANNOTATION_TOKEN_PARAM", "ANNOTATION_TOKEN_PARAMS", "CAPTURE_TOKEN_PARAM", "FIRST_PARTY_ANNOTATION_MODE", "LEGACY_ANNOTATION_ARMED_COOKIE", "LEGACY_ANNOTATION_TOKEN_PARAM", "NAME_ATTR", "READ_TOKEN_PARAM", "REVIEW_RUN_PARAM", "SDK_VERSION", "SRC_ATTR", "armedCookie", "assertConcreteOrigin", "clearedCookie", "isAnnotationArmed", "isParentMessage", "readAnnotationToken", "selectionOf", "unhandledMessage", "__toCommonJS", "target", "safeJson", "message", "half", "PARENT_TYPES", "data", "type", "origin", "name", "cookie", "entry", "trimmed", "params", "value"]
|
|
7
7
|
}
|
package/dist/protocol.d.cts
CHANGED
|
@@ -168,9 +168,21 @@ export interface AnnotationPayload {
|
|
|
168
168
|
failedRequests: NetworkEntry[];
|
|
169
169
|
featureFlags: Record<string, unknown>;
|
|
170
170
|
};
|
|
171
|
+
/**
|
|
172
|
+
* `w`/`h` and `canvases` arrive with the in-page viewport capture (A-2385);
|
|
173
|
+
* `canvases` counts the canvases in view and how many read back blank or
|
|
174
|
+
* unreadable, so a black rectangle in the picture is explained, not silent.
|
|
175
|
+
*/
|
|
171
176
|
screenshot?: {
|
|
172
177
|
dataUrl: string;
|
|
173
178
|
region: "element" | "viewport";
|
|
179
|
+
w?: number;
|
|
180
|
+
h?: number;
|
|
181
|
+
canvases?: {
|
|
182
|
+
total: number;
|
|
183
|
+
blank: number;
|
|
184
|
+
unreadable: number;
|
|
185
|
+
};
|
|
174
186
|
};
|
|
175
187
|
/** The human's words, verbatim. The parent frame fills this in; we never rewrite it. */
|
|
176
188
|
comment: string;
|
package/dist/protocol.d.mts
CHANGED
|
@@ -168,9 +168,21 @@ export interface AnnotationPayload {
|
|
|
168
168
|
failedRequests: NetworkEntry[];
|
|
169
169
|
featureFlags: Record<string, unknown>;
|
|
170
170
|
};
|
|
171
|
+
/**
|
|
172
|
+
* `w`/`h` and `canvases` arrive with the in-page viewport capture (A-2385);
|
|
173
|
+
* `canvases` counts the canvases in view and how many read back blank or
|
|
174
|
+
* unreadable, so a black rectangle in the picture is explained, not silent.
|
|
175
|
+
*/
|
|
171
176
|
screenshot?: {
|
|
172
177
|
dataUrl: string;
|
|
173
178
|
region: "element" | "viewport";
|
|
179
|
+
w?: number;
|
|
180
|
+
h?: number;
|
|
181
|
+
canvases?: {
|
|
182
|
+
total: number;
|
|
183
|
+
blank: number;
|
|
184
|
+
unreadable: number;
|
|
185
|
+
};
|
|
174
186
|
};
|
|
175
187
|
/** The human's words, verbatim. The parent frame fills this in; we never rewrite it. */
|
|
176
188
|
comment: string;
|