@qaiddev/thumbs-embed 1.3.0 → 1.5.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/dist/auto.d.ts +24 -0
- package/dist/auto.js +2 -0
- package/dist/auto.js.map +1 -0
- package/dist/bootstrap.d.ts +15 -0
- package/dist/chunks/annotate-BNibaDg3.js +367 -0
- package/dist/chunks/annotate-BNibaDg3.js.map +1 -0
- package/dist/chunks/bootstrap-U4yiPm5-.js +1099 -0
- package/dist/chunks/bootstrap-U4yiPm5-.js.map +1 -0
- package/dist/chunks/modal-BX5wqy4s.js +119 -0
- package/dist/chunks/modal-BX5wqy4s.js.map +1 -0
- package/dist/chunks/network-capture-DMbMwwwR.js +63 -0
- package/dist/chunks/network-capture-DMbMwwwR.js.map +1 -0
- package/dist/chunks/recording--IwOtRL2.js +256 -0
- package/dist/chunks/recording--IwOtRL2.js.map +1 -0
- package/dist/chunks/screenshot-BkOCLuS2.js +33 -0
- package/dist/chunks/screenshot-BkOCLuS2.js.map +1 -0
- package/dist/chunks/screenshot-dom-CME7tYRE.js +63 -0
- package/dist/chunks/screenshot-dom-CME7tYRE.js.map +1 -0
- package/dist/chunks/targeting-DwdDr9Cm.js +295 -0
- package/dist/chunks/targeting-DwdDr9Cm.js.map +1 -0
- package/dist/chunks/video-BOYqf2Im.js +209 -0
- package/dist/chunks/video-BOYqf2Im.js.map +1 -0
- package/dist/dom.d.ts +36 -0
- package/dist/embed.d.ts +53 -68
- package/dist/index.d.ts +10 -12
- package/dist/index.js +22 -0
- package/dist/index.js.map +1 -0
- package/dist/loader.d.ts +18 -0
- package/dist/loader.js +7 -0
- package/dist/loader.js.map +1 -0
- package/dist/modal.d.ts +49 -0
- package/dist/qaid.umd.cjs +23 -23
- package/dist/qaid.umd.cjs.map +1 -1
- package/dist/recording.d.ts +74 -0
- package/dist/targeting.d.ts +72 -0
- package/dist/types.d.ts +7 -1
- package/dist/video-capture.d.ts +7 -0
- package/dist/video-orientation.d.ts +2 -0
- package/dist/video-redaction.d.ts +58 -0
- package/package.json +12 -5
- package/dist/qaid.js +0 -2013
- package/dist/qaid.js.map +0 -1
package/dist/qaid.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"qaid.js","sources":["../src/icons.ts","../src/styles.ts","../src/element-selector.ts","../src/a11y.ts","../src/modal-positioning.ts","../src/console-capture.ts","../src/network-capture.ts","../src/video-orientation.ts","../src/video-capture.ts","../src/dom-utils.ts","../src/screenshot.ts","../src/screenshot-dom.ts","../src/annotate.ts","../src/quest-launcher.ts","../src/embed.ts","../src/index.ts"],"sourcesContent":["/**\n * SVG icon strings for thumbs up/down buttons\n */\n\nexport const THUMBS_UP_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905 0 .714-.211 1.412-.608 2.006L7 11v9m7-10h-2M7 20H5a2 2 0 01-2-2v-6a2 2 0 012-2h2.5\"/>\n</svg>`;\n\nexport const THUMBS_DOWN_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M10 14H5.236a2 2 0 01-1.789-2.894l3.5-7A2 2 0 018.737 3h4.018a2 2 0 01.485.06l3.76.94m-7 10v5a2 2 0 002 2h.095c.5 0 .905-.405.905-.905 0-.714.211-1.412.608-2.006L17 13V4m-7 10h2m5-10h2a2 2 0 012 2v6a2 2 0 01-2 2h-2.5\"/>\n</svg>`;\n\nexport const RECORD_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M15.75 10.5l4.72-4.72a.75.75 0 011.28.53v11.38a.75.75 0 01-1.28.53l-4.72-4.72M4.5 18.75h9a2.25 2.25 0 002.25-2.25v-9a2.25 2.25 0 00-2.25-2.25h-9A2.25 2.25 0 002.25 7.5v9a2.25 2.25 0 002.25 2.25z\"/>\n</svg>`;\n\n/* ---------------------------------------------------------------------------\n * Screenshot annotation toolbar icons. Same 24×24 stroked style as the thumbs\n * icons above so they inherit `.qaid-icon` sizing and `currentColor`.\n * ------------------------------------------------------------------------- */\n\nexport const RECTANGLE_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <rect x=\"4\" y=\"6\" width=\"16\" height=\"12\" rx=\"1\" stroke-linejoin=\"round\"/>\n</svg>`;\n\nexport const ARROW_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M5 19L19 5m0 0h-8m8 0v8\"/>\n</svg>`;\n\nexport const PENCIL_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M12 20h9M16.5 3.5a2.121 2.121 0 013 3L7 19l-4 1 1-4L16.5 3.5z\"/>\n</svg>`;\n\nexport const BLUR_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M12 3s6 6.4 6 10a6 6 0 01-12 0c0-3.6 6-10 6-10z\"/>\n</svg>`;\n\nexport const UNDO_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 14L4 9l5-5M4 9h11a5 5 0 010 10h-4\"/>\n</svg>`;\n\nexport const DONE_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M20 6L9 17l-5-5\"/>\n</svg>`;\n\nexport const SKIP_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M6 6l12 12M18 6L6 18\"/>\n</svg>`;\n","/**\n * CSS styles for the feedback embed\n * Uses .qaid- prefix to avoid conflicts\n */\n\n// Import CSS as strings (vite handles minification in production)\nimport shadowStyles from \"./styles-shadow.css?inline\";\nimport lightStyles from \"./styles-light.css?inline\";\n\nlet instanceCount = 0;\n\n/** Default button styles included in shadow root */\nconst DEFAULT_BUTTON_STYLES = `button.qaid-btn{width:var(--qaid-btn-size);height:var(--qaid-btn-size);border-radius:50%;border:none;background:#f3f4f6;color:#374151;display:flex;align-items:center;justify-content:center;cursor:pointer;box-shadow:0 4px 6px -1px rgba(0,0,0,.1),0 2px 4px -1px rgba(0,0,0,.06);transition:background-color .2s,color .2s,transform .2s;-webkit-appearance:none;appearance:none;--qaid-hover-up-bg:var(--qaid-positive);--qaid-hover-up-color:#fff;--qaid-hover-down-bg:var(--qaid-negative);--qaid-hover-down-color:#fff}button.qaid-btn:hover{transform:scale(1.05)}button.qaid-btn-up:hover{background:var(--qaid-hover-up-bg);color:var(--qaid-hover-up-color)}button.qaid-btn-down:hover{background:var(--qaid-hover-down-bg);color:var(--qaid-hover-down-color)}button.qaid-btn svg{width:var(--qaid-icon-size);height:var(--qaid-icon-size)}`;\n\nexport interface BuildCssVarsOptions {\n positiveColor?: string;\n negativeColor?: string;\n /** Color for selected element marker */\n markerColor?: string;\n /** Button size: small (36px), medium (48px), large (64px) */\n buttonSize?: \"small\" | \"medium\" | \"large\";\n /** Modal width in pixels */\n modalWidth?: number;\n /** Backdrop opacity (0-1) */\n backdropOpacity?: number;\n /** Font family */\n fontFamily?: string;\n /** Base font size in pixels */\n fontSize?: number;\n}\n\nconst BUTTON_SIZES = {\n small: 36,\n medium: 48,\n large: 64,\n} as const;\n\nconst ICON_SIZES = {\n small: 18,\n medium: 24,\n large: 32,\n} as const;\n\n/**\n * Calculate relative luminance of a color\n * Returns value between 0 (black) and 1 (white)\n */\nfunction getLuminance(r: number, g: number, b: number): number {\n const [rs, gs, bs] = [r, g, b].map((c) => {\n c = c / 255;\n return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);\n });\n return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;\n}\n\n/**\n * Parse a color string (hex or rgb) and return RGB values\n */\nfunction parseColor(color: string): { r: number; g: number; b: number } | null {\n // Hex format\n if (color.startsWith(\"#\")) {\n const hex = color.slice(1);\n const fullHex = hex.length === 3\n ? hex.split(\"\").map((c) => c + c).join(\"\")\n : hex;\n const num = parseInt(fullHex, 16);\n return {\n r: (num >> 16) & 255,\n g: (num >> 8) & 255,\n b: num & 255,\n };\n }\n // RGB format\n const match = color.match(/rgb\\((\\d+),\\s*(\\d+),\\s*(\\d+)\\)/);\n if (match) {\n return {\n r: parseInt(match[1]),\n g: parseInt(match[2]),\n b: parseInt(match[3]),\n };\n }\n return null;\n}\n\n/**\n * Get the best contrasting text color (black or white) for a background\n */\nfunction getContrastTextColor(bgColor: string): string {\n const rgb = parseColor(bgColor);\n if (!rgb) return \"white\";\n const luminance = getLuminance(rgb.r, rgb.g, rgb.b);\n // Use white text on dark backgrounds, black on light\n return luminance > 0.4 ? \"black\" : \"white\";\n}\n\n/**\n * Build a map of CSS variable names to values for per-instance scoping\n */\nexport function buildCssVars(options: BuildCssVarsOptions = {}): Record<string, string> {\n const {\n positiveColor = \"rgb(0, 200, 83)\",\n negativeColor = \"rgb(255, 0, 0)\",\n markerColor = \"#6366f1\",\n buttonSize = \"medium\",\n modalWidth = 400,\n backdropOpacity = 0.3,\n fontFamily = \"system-ui, -apple-system, sans-serif\",\n fontSize = 16,\n } = options;\n\n const btnSize = BUTTON_SIZES[buttonSize];\n const iconSize = ICON_SIZES[buttonSize];\n const markerTextColor = getContrastTextColor(markerColor);\n\n return {\n \"--qaid-positive\": positiveColor,\n \"--qaid-negative\": negativeColor,\n \"--qaid-marker\": markerColor,\n \"--qaid-marker-text\": markerTextColor,\n \"--qaid-btn-size\": `${btnSize}px`,\n \"--qaid-icon-size\": `${iconSize}px`,\n \"--qaid-modal-width\": `${modalWidth}px`,\n \"--qaid-backdrop-opacity\": String(backdropOpacity),\n \"--qaid-font-family\": fontFamily,\n \"--qaid-font-size\": `${fontSize}px`,\n };\n}\n\n/**\n * Apply CSS variables to an element via inline style properties\n */\nexport function applyCssVars(el: HTMLElement, vars: Record<string, string>): void {\n for (const [name, value] of Object.entries(vars)) {\n el.style.setProperty(name, value);\n }\n}\n\n/**\n * Get the CSS string to inject into a shadow root\n * Includes base shadow styles + default button styles\n */\nexport function getEmbedStyles(): string {\n return shadowStyles + DEFAULT_BUTTON_STYLES;\n}\n\n/**\n * Inject light DOM styles (cursor override + highlight)\n * Reference-counted across instances\n */\nexport function injectStyles(): void {\n instanceCount++;\n if (instanceCount > 1) return;\n\n const style = document.createElement(\"style\");\n style.id = \"qaid-styles\";\n style.textContent = lightStyles;\n document.head.appendChild(style);\n}\n\n/**\n * Remove light DOM styles when last instance is destroyed\n */\nexport function removeStyles(): void {\n if (instanceCount <= 0) return;\n instanceCount--;\n if (instanceCount === 0) {\n document.getElementById(\"qaid-styles\")!.remove();\n }\n}\n\n/** Reset internal state — for tests only */\nexport function _resetStylesState(): void {\n instanceCount = 0;\n const style = document.getElementById(\"qaid-styles\");\n if (style) {\n style.remove();\n }\n}\n","/**\n * Element selector generation utilities\n */\n\n/** Data attributes to look for (in priority order) */\nexport const DATA_ATTRS = [\"data-comp\", \"data-qa\", \"data-testid\", \"data-id\"];\n\nexport interface ElementInfo {\n selector: string;\n text: string;\n dataAttr: string | null;\n}\n\n/**\n * Find the first matching data attribute on an element or its ancestors\n */\nexport function findDataAttribute(\n element: Element,\n stopAt: Element = document.body\n): string | null {\n let current: Element | null = element;\n\n while (current && current !== stopAt) {\n for (const attr of DATA_ATTRS) {\n const value = current.getAttribute(attr);\n if (value) {\n return `${attr}=\"${value}\"`;\n }\n }\n current = current.parentElement;\n }\n\n return null;\n}\n\n/**\n * Get truncated text content from an element\n */\nexport function getTruncatedText(element: Element, maxLength = 100): string {\n const textContent = element.textContent?.trim().slice(0, maxLength) || \"\";\n return textContent.length === maxLength ? textContent + \"...\" : textContent;\n}\n\n/**\n * Get the nth-child index of an element among its siblings\n */\nfunction getNthChildIndex(element: Element): number {\n let index = 1;\n let sibling = element.previousElementSibling;\n while (sibling) {\n index++;\n sibling = sibling.previousElementSibling;\n }\n return index;\n}\n\n/**\n * Generate an nth-child path from body to the element\n * This is always a valid CSS selector and uniquely identifies the element\n * Exported for testing\n */\nexport function generateNthChildPath(element: Element): string {\n const path: string[] = [];\n let current: Element | null = element;\n\n while (current && current !== document.body && current !== document.documentElement) {\n const tag = current.tagName.toLowerCase();\n const index = getNthChildIndex(current);\n path.unshift(`${tag}:nth-child(${index})`);\n current = current.parentElement;\n }\n\n return path.length > 0 ? `body > ${path.join(\" > \")}` : \"body\";\n}\n\n/**\n * Escape special CSS characters in a string (for IDs with special chars)\n */\nfunction escapeCSSIdentifier(str: string): string {\n return str.replace(/([!\"#$%&'()*+,./:;<=>?@[\\\\\\]^`{|}~])/g, \"\\\\$1\");\n}\n\n/**\n * Generate a selector string for an element\n * Priority: data attribute > ID > nth-child path\n */\nexport function generateSelector(element: Element): string {\n // Try data attribute first (on element or ancestors) - most stable\n const dataAttr = findDataAttribute(element);\n if (dataAttr) {\n return `[${dataAttr}]`;\n }\n\n // Try ID (escaped for special characters)\n if (element.id) {\n return `#${escapeCSSIdentifier(element.id)}`;\n }\n\n // Fall back to nth-child path - always valid and unique\n return generateNthChildPath(element);\n}\n\n/**\n * Generate complete element info for feedback\n */\nexport function generateElementInfo(element: Element): ElementInfo {\n const text = getTruncatedText(element);\n const dataAttr = findDataAttribute(element);\n const selector = generateSelector(element);\n\n return { selector, text, dataAttr };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Keyboard element targeting */\n/* */\n/* The mouse targeting path in embed.ts resolves the target with */\n/* elementFromPoint(clientX, clientY). A keyboard-activated thumb produces a */\n/* synthetic click at (0, 0), so a keyboard-only user can never point at a */\n/* real element. This controller provides a coordinate-free alternative: */\n/* Tab / arrow keys move a highlight between candidate elements (seeded from */\n/* document.activeElement), Enter / Space selects, Escape cancels. It never */\n/* hides the cursor — it drives the *native* focus ring instead, so both */\n/* sighted keyboard users and screen readers can follow the highlight. */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Default set of \"targetable\" elements for keyboard navigation: focusable\n * controls, ARIA-role'd nodes, common semantic content, and anything already\n * carrying one of the stable data attributes we key selectors off of.\n */\nexport const TARGETABLE_SELECTOR: string = [\n \"a[href]\",\n \"button\",\n \"input:not([type=hidden])\",\n \"select\",\n \"textarea\",\n \"summary\",\n \"[tabindex]\",\n \"[role]\",\n \"img\",\n \"h1\",\n \"h2\",\n \"h3\",\n \"h4\",\n \"h5\",\n \"h6\",\n \"p\",\n \"li\",\n \"label\",\n ...DATA_ATTRS.map((attr) => `[${attr}]`),\n].join(\",\");\n\n/** Tag names that already take keyboard focus without an added tabindex. */\nconst NATIVELY_FOCUSABLE = /^(?:A|BUTTON|INPUT|SELECT|TEXTAREA|SUMMARY)$/;\n\n/**\n * Best-effort visibility test used to keep invisible nodes out of the keyboard\n * candidate list. Deliberately layout-free (no getBoundingClientRect) so it is\n * stable in headless/test environments: it only rejects nodes that are\n * explicitly hidden via the `hidden` attribute, `aria-hidden`, or a computed\n * `display:none` / `visibility:hidden`.\n */\nexport function isElementVisible(element: Element): boolean {\n if (element.hasAttribute(\"hidden\")) return false;\n if (element.getAttribute(\"aria-hidden\") === \"true\") return false;\n const view = element.ownerDocument?.defaultView;\n if (view && typeof view.getComputedStyle === \"function\") {\n const style = view.getComputedStyle(element);\n if (style.display === \"none\" || style.visibility === \"hidden\") return false;\n }\n return true;\n}\n\nexport interface CollectTargetableOptions {\n /** Where to search for candidates (default `document.body`). */\n root?: ParentNode;\n /** CSS selector for candidate elements (default {@link TARGETABLE_SELECTOR}). */\n selector?: string;\n /** Return true to drop an element (e.g. the embed's own shadow hosts). */\n isExcluded?: (element: Element) => boolean;\n /** Visibility predicate (default {@link isElementVisible}). */\n isVisible?: (element: Element) => boolean;\n}\n\n/**\n * Collect the ordered list of elements a keyboard user can target. Document\n * order matches the natural Tab order closely enough for feedback targeting.\n */\nexport function collectTargetableElements(\n options: CollectTargetableOptions = {}\n): Element[] {\n const root = options.root ?? document.body;\n const selector = options.selector ?? TARGETABLE_SELECTOR;\n const isExcluded = options.isExcluded ?? (() => false);\n const isVisible = options.isVisible ?? isElementVisible;\n\n return Array.from(root.querySelectorAll(selector)).filter(\n (element) => !isExcluded(element) && isVisible(element)\n );\n}\n\nexport interface KeyboardTargetingOptions {\n /**\n * Explicit candidate list. When omitted, candidates are collected via\n * {@link collectTargetableElements} using `root` / `selector` / `isExcluded`\n * / `isVisible`.\n */\n candidates?: Element[];\n /** Passed through to {@link collectTargetableElements} when `candidates` is omitted. */\n root?: ParentNode;\n /** Passed through to {@link collectTargetableElements} when `candidates` is omitted. */\n selector?: string;\n /** Passed through to {@link collectTargetableElements} when `candidates` is omitted. */\n isExcluded?: (element: Element) => boolean;\n /** Passed through to {@link collectTargetableElements} when `candidates` is omitted. */\n isVisible?: (element: Element) => boolean;\n /**\n * Element to start the highlight on. Defaults to `document.activeElement`\n * when it is one of the candidates, otherwise the first candidate.\n */\n initial?: Element | null;\n /**\n * Move native focus to the highlighted element (default true). This is what\n * keeps a screen reader / focus ring on the highlight; non-focusable nodes\n * get a temporary `tabindex=\"-1\"` that is removed on {@link stop}. The cursor\n * is never hidden.\n */\n moveFocus?: boolean;\n /** Where the keydown listener is attached (default `document`). */\n eventTarget?: Document | HTMLElement;\n /** Fired whenever the highlighted candidate changes (and once on start). */\n onHighlight?: (element: Element, index: number) => void;\n /** Fired when the user commits a selection (Enter / Space). Auto-stops first. */\n onSelect: (element: Element) => void;\n /** Fired when the user cancels (Escape). Auto-stops first. */\n onCancel?: () => void;\n}\n\nexport interface KeyboardTargetingController {\n /** The (frozen) candidate list being navigated. */\n readonly candidates: readonly Element[];\n /** Index of the highlighted candidate, or -1 when there are none. */\n getIndex(): number;\n /** The highlighted candidate, or null when there are none. */\n getCurrent(): Element | null;\n /** Highlight the next candidate (wraps to the first). */\n next(): void;\n /** Highlight the previous candidate (wraps to the last). */\n prev(): void;\n /** Highlight a specific index (wraps out-of-range values). */\n moveTo(index: number): void;\n /** Commit the current candidate (fires onSelect) and stop. */\n select(): void;\n /** Cancel (fires onCancel) and stop. */\n cancel(): void;\n /**\n * Handle a keydown. Wired automatically to `eventTarget`; exposed so a host\n * can forward events from another surface (e.g. the embed's shadow root).\n */\n handleKey(event: KeyboardEvent): void;\n /** Remove the listener and restore any temporary tabindex. Idempotent. */\n stop(): void;\n}\n\n/**\n * Start a keyboard element-targeting session. The returned controller wires its\n * own capture-phase keydown listener on `eventTarget` and emits the initial\n * highlight synchronously before returning.\n */\nexport function startKeyboardTargeting(\n options: KeyboardTargetingOptions\n): KeyboardTargetingController {\n const candidates =\n options.candidates ??\n collectTargetableElements({\n root: options.root,\n selector: options.selector,\n isExcluded: options.isExcluded,\n isVisible: options.isVisible,\n });\n\n const moveFocus = options.moveFocus ?? true;\n const target: EventTarget = options.eventTarget ?? document;\n const addedTabindex = new Set<Element>();\n\n let index = -1;\n let stopped = false;\n\n // Seed the highlight from the currently focused element when it is a\n // candidate; this makes \"Tab to a control, then hit the thumb\" land on that\n // control rather than the top of the page.\n const seed =\n options.initial !== undefined\n ? options.initial\n : typeof document !== \"undefined\"\n ? document.activeElement\n : null;\n if (seed) {\n const seedIndex = candidates.indexOf(seed);\n if (seedIndex >= 0) index = seedIndex;\n }\n if (index < 0 && candidates.length > 0) index = 0;\n\n function focusCurrent(element: Element): void {\n if (!moveFocus) return;\n const focusable = element as HTMLElement;\n if (typeof focusable.focus !== \"function\") return;\n // Make non-focusable content (p, img, li, …) programmatically focusable so\n // the native focus ring and AT follow the highlight. Never hide the cursor.\n if (\n element.getAttribute(\"tabindex\") === null &&\n !NATIVELY_FOCUSABLE.test(element.tagName)\n ) {\n element.setAttribute(\"tabindex\", \"-1\");\n addedTabindex.add(element);\n }\n try {\n focusable.focus();\n } catch {\n /* focus can throw in detached/headless cases — highlight still works */\n }\n }\n\n function emitHighlight(): void {\n const element = candidates[index];\n if (!element) return;\n focusCurrent(element);\n options.onHighlight?.(element, index);\n }\n\n function moveTo(nextIndex: number): void {\n if (stopped || candidates.length === 0) return;\n const len = candidates.length;\n index = ((nextIndex % len) + len) % len; // wrap in both directions\n emitHighlight();\n }\n\n function next(): void {\n moveTo(index + 1);\n }\n\n function prev(): void {\n moveTo(index - 1);\n }\n\n function getCurrent(): Element | null {\n return candidates[index] ?? null;\n }\n\n function stop(): void {\n if (stopped) return;\n stopped = true;\n target.removeEventListener(\"keydown\", handleKey as EventListener, true);\n addedTabindex.forEach((element) => element.removeAttribute(\"tabindex\"));\n addedTabindex.clear();\n }\n\n function select(): void {\n if (stopped) return;\n const element = getCurrent();\n stop();\n if (element) options.onSelect(element);\n }\n\n function cancel(): void {\n if (stopped) return;\n stop();\n options.onCancel?.();\n }\n\n function handleKey(event: KeyboardEvent): void {\n if (stopped) return;\n switch (event.key) {\n case \"Tab\":\n event.preventDefault();\n event.stopPropagation();\n if (event.shiftKey) prev();\n else next();\n break;\n case \"ArrowDown\":\n case \"ArrowRight\":\n event.preventDefault();\n event.stopPropagation();\n next();\n break;\n case \"ArrowUp\":\n case \"ArrowLeft\":\n event.preventDefault();\n event.stopPropagation();\n prev();\n break;\n case \"Enter\":\n case \" \":\n case \"Spacebar\": // legacy key value\n event.preventDefault();\n event.stopPropagation();\n select();\n break;\n case \"Escape\":\n case \"Esc\": // legacy key value\n event.preventDefault();\n event.stopPropagation();\n cancel();\n break;\n default:\n break;\n }\n }\n\n target.addEventListener(\"keydown\", handleKey as EventListener, true);\n\n // Emit the initial highlight so the caller can position its highlight box.\n if (index >= 0) emitHighlight();\n\n return {\n candidates,\n getIndex: () => index,\n getCurrent,\n next,\n prev,\n moveTo,\n select,\n cancel,\n handleKey,\n stop,\n };\n}\n","/**\n * Shared accessibility primitives for the qaid embeds.\n *\n * These helpers are intentionally framework-free and self-contained (no CSS\n * dependency) so they can be dropped into any open shadow root. They cover the\n * cross-cutting WCAG 2.2 AA infrastructure called for in the embed\n * accessibility plan: live-region announcements, focus management (trap,\n * save/restore), dialog semantics, and background isolation.\n */\n\n/** Host for the live regions: either a shadow root or a plain element. */\nexport type AnnounceRoot = ShadowRoot | HTMLElement;\n\n/** Options accepted by {@link announce}. */\nexport interface AnnounceOptions {\n /** Route the message through the assertive (role=\"alert\") region. */\n assertive?: boolean;\n}\n\n/** Options accepted by {@link applyDialog}. */\nexport interface ApplyDialogOptions {\n /** id of the element that labels the dialog (wired via aria-labelledby). */\n labelledbyId?: string;\n /** id of the element that describes the dialog (wired via aria-describedby). */\n describedbyId?: string;\n /** Fallback accessible name when no labelling element exists. */\n label?: string;\n}\n\n/** Handle returned by {@link createFocusTrap}. */\nexport interface FocusTrap {\n /** Remove the trap's key handler and clean up any tabindex it added. */\n release(): void;\n}\n\nconst POLITE_ATTR = \"data-qaid-a11y-live\";\n\nconst VISUALLY_HIDDEN_CSS =\n \"position:absolute;width:1px;height:1px;margin:-1px;padding:0;\" +\n \"border:0;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);\" +\n \"white-space:nowrap;\";\n\n/**\n * Selector for natively focusable / author-focusable elements. Elements that\n * opt out with tabindex=\"-1\" are excluded below in {@link getFocusable}.\n */\nconst FOCUSABLE_SELECTOR = [\n \"a[href]\",\n \"button\",\n \"input\",\n \"textarea\",\n \"select\",\n \"[tabindex]\",\n].join(\",\");\n\nfunction ownerDoc(root: AnnounceRoot): Document {\n return root.ownerDocument || document;\n}\n\nfunction getLiveRegion(root: AnnounceRoot, assertive: boolean): HTMLElement {\n const kind = assertive ? \"assertive\" : \"polite\";\n const existing = root.querySelector<HTMLElement>(\n `[${POLITE_ATTR}=\"${kind}\"]`\n );\n if (existing) return existing;\n\n const doc = ownerDoc(root);\n const region = doc.createElement(\"div\");\n region.setAttribute(POLITE_ATTR, kind);\n region.setAttribute(\"role\", assertive ? \"alert\" : \"status\");\n region.setAttribute(\"aria-live\", assertive ? \"assertive\" : \"polite\");\n region.setAttribute(\"aria-atomic\", \"true\");\n region.style.cssText = VISUALLY_HIDDEN_CSS;\n root.appendChild(region);\n return region;\n}\n\n/**\n * Announce a message to assistive technology via a visually-hidden live region\n * mounted inside `root`. The two regions (polite role=\"status\" and assertive\n * role=\"alert\") are created lazily on first use and reused thereafter.\n *\n * The target region is cleared before the new text is written so that repeated\n * identical messages are re-announced rather than coalesced.\n */\nexport function announce(\n root: AnnounceRoot,\n message: string,\n opts: AnnounceOptions = {}\n): void {\n const region = getLiveRegion(root, !!opts.assertive);\n // Clear-then-set so an identical repeat is still perceived as a change.\n region.textContent = \"\";\n region.textContent = message;\n}\n\nfunction isDisabled(el: HTMLElement): boolean {\n if (el.hasAttribute(\"disabled\")) return true;\n const asInput = el as HTMLElement & { disabled?: boolean };\n return asInput.disabled === true;\n}\n\nfunction isHidden(el: HTMLElement): boolean {\n let node: HTMLElement | null = el;\n while (node) {\n if (node.hasAttribute(\"hidden\")) return true;\n const style = node.style;\n if (\n style &&\n (style.display === \"none\" ||\n style.visibility === \"hidden\" ||\n style.visibility === \"collapse\")\n ) {\n return true;\n }\n node = node.parentElement;\n }\n return false;\n}\n\n/**\n * Collect the focusable descendants of `container` in DOM order, excluding\n * disabled controls, elements opted out with tabindex=\"-1\", and elements that\n * are hidden (via the hidden attribute or an inline display/visibility rule on\n * themselves or an ancestor up to the document root).\n */\nexport function getFocusable(container: HTMLElement): HTMLElement[] {\n const nodes = Array.from(\n container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)\n );\n return nodes.filter((el) => {\n if (el.getAttribute(\"tabindex\") === \"-1\") return false;\n if (el instanceof HTMLInputElement && el.type === \"hidden\") return false;\n if (el instanceof HTMLAnchorElement && !el.getAttribute(\"href\")) return false;\n if (isDisabled(el)) return false;\n if (isHidden(el)) return false;\n return true;\n });\n}\n\n/** Resolve the deepest active element, drilling through open shadow roots. */\nfunction getDeepActiveElement(doc: Document): HTMLElement | null {\n let active: Element | null = doc.activeElement;\n while (active && active.shadowRoot && active.shadowRoot.activeElement) {\n active = active.shadowRoot.activeElement;\n }\n return active instanceof HTMLElement ? active : null;\n}\n\n/**\n * Trap keyboard focus inside `container`: Tab / Shift+Tab cycle between the\n * first and last focusable descendants and can never leave the container. On\n * creation focus moves to the first focusable element, or to the container\n * itself (made programmatically focusable) when it has no focusable children.\n *\n * Call {@link FocusTrap.release} to remove the handler; pair it with\n * {@link restoreFocus} to return focus to the invoking control.\n */\nexport function createFocusTrap(container: HTMLElement): FocusTrap {\n const doc = container.ownerDocument || document;\n let addedTabindex = false;\n\n const onKeydown = (event: KeyboardEvent): void => {\n if (event.key !== \"Tab\") return;\n\n const focusable = getFocusable(container);\n if (focusable.length === 0) {\n // Nothing to move to — keep focus pinned on the container.\n event.preventDefault();\n container.focus();\n return;\n }\n\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n const active = getDeepActiveElement(doc);\n const withinTrap = active ? focusable.indexOf(active) !== -1 : false;\n\n if (event.shiftKey) {\n if (!withinTrap || active === first) {\n event.preventDefault();\n last.focus();\n }\n } else {\n if (!withinTrap || active === last) {\n event.preventDefault();\n first.focus();\n }\n }\n };\n\n container.addEventListener(\"keydown\", onKeydown);\n\n const initial = getFocusable(container);\n if (initial.length > 0) {\n initial[0].focus();\n } else {\n if (!container.hasAttribute(\"tabindex\")) {\n container.setAttribute(\"tabindex\", \"-1\");\n addedTabindex = true;\n }\n container.focus();\n }\n\n return {\n release(): void {\n container.removeEventListener(\"keydown\", onKeydown);\n if (addedTabindex) {\n container.removeAttribute(\"tabindex\");\n addedTabindex = false;\n }\n },\n };\n}\n\n/**\n * Capture the currently focused element (drilling through shadow roots) so it\n * can be restored later with {@link restoreFocus}. Returns null when focus is\n * on nothing focusable.\n */\nexport function saveFocus(): HTMLElement | null {\n return getDeepActiveElement(document);\n}\n\n/**\n * Restore focus to a previously saved element. Safe to call with null or an\n * element that has since been detached (a missing/throwing focus is ignored).\n */\nexport function restoreFocus(el: HTMLElement | null): void {\n if (!el || typeof el.focus !== \"function\") return;\n try {\n el.focus();\n } catch {\n // The element may have been removed; nothing more to do.\n }\n}\n\n/**\n * Apply dialog semantics to `el`: role=\"dialog\", aria-modal=\"true\", and the\n * naming/description wiring described by `opts`. Prefer aria-labelledby /\n * aria-describedby pointing at visible title/subtitle elements; fall back to\n * aria-label when no visible label element exists.\n */\nexport function applyDialog(el: HTMLElement, opts: ApplyDialogOptions = {}): void {\n el.setAttribute(\"role\", \"dialog\");\n el.setAttribute(\"aria-modal\", \"true\");\n if (opts.labelledbyId) {\n el.setAttribute(\"aria-labelledby\", opts.labelledbyId);\n }\n if (opts.describedbyId) {\n el.setAttribute(\"aria-describedby\", opts.describedbyId);\n }\n if (opts.label) {\n el.setAttribute(\"aria-label\", opts.label);\n }\n}\n\n/** Walk up to the body-level ancestor of `el`, crossing shadow boundaries. */\nfunction topLevelAncestor(el: HTMLElement, body: HTMLElement): HTMLElement | null {\n let node: Node | null = el;\n while (node && node !== body) {\n const parent: Node | null = node.parentNode;\n if (parent === body) return node as HTMLElement;\n if (parent && (parent as ShadowRoot).host) {\n node = (parent as ShadowRoot).host;\n continue;\n }\n if (!parent) return null;\n node = parent;\n }\n return null;\n}\n\n/**\n * Isolate the background from assistive technology while a dialog is open by\n * marking every top-level sibling of the dialog inert (with an aria-hidden\n * fallback). `except` is the open dialog (or any element inside it); the\n * top-level element that contains it is left interactive.\n *\n * Returns a restore function that reverts every attribute this call changed,\n * leaving elements that were already inert/hidden untouched.\n */\nexport function setBackgroundInert(except: HTMLElement): () => void {\n const doc = except.ownerDocument || document;\n const body = doc.body;\n if (!body) return () => {};\n\n const keep = topLevelAncestor(except, body);\n const changed: Array<{\n el: HTMLElement;\n prevInert: boolean;\n prevAriaHidden: string | null;\n }> = [];\n\n Array.from(body.children).forEach((child) => {\n if (!(child instanceof HTMLElement)) return;\n if (keep && child === keep) return;\n\n const prevInert = child.inert === true;\n const prevAriaHidden = child.getAttribute(\"aria-hidden\");\n // Only record (and later revert) elements we actually change.\n if (prevInert && prevAriaHidden === \"true\") return;\n\n child.inert = true;\n child.setAttribute(\"aria-hidden\", \"true\");\n changed.push({ el: child, prevInert, prevAriaHidden });\n });\n\n return function restore(): void {\n while (changed.length) {\n // The loop guard guarantees pop() returns an entry.\n const entry = changed.pop()!;\n entry.el.inert = entry.prevInert;\n if (entry.prevAriaHidden === null) {\n entry.el.removeAttribute(\"aria-hidden\");\n } else {\n entry.el.setAttribute(\"aria-hidden\", entry.prevAriaHidden);\n }\n }\n };\n}\n","/**\n * Modal positioning utilities\n */\n\nimport type { SelectedBounds } from \"./types\";\n\nexport interface ModalPosition {\n top: number;\n left: number;\n position: \"above\" | \"below\";\n}\n\nexport interface ArrowPosition {\n left: number;\n}\n\nexport interface ModalDimensions {\n width: number;\n height: number;\n arrowHeight: number;\n gap: number;\n viewportPadding: number;\n}\n\nconst DEFAULT_DIMENSIONS: ModalDimensions = {\n width: 400,\n height: 280,\n arrowHeight: 12,\n gap: 8,\n viewportPadding: 16,\n};\n\n/**\n * Calculate whether modal should go above or below the target element\n */\nexport function calculateVerticalPosition(\n bounds: SelectedBounds,\n viewportHeight: number,\n totalHeight: number,\n gap: number,\n viewportPadding: number\n): { top: number; position: \"above\" | \"below\" } {\n const spaceAbove = bounds.y;\n const spaceBelow = viewportHeight - (bounds.y + bounds.height);\n\n // Prefer below if there's enough space\n if (spaceBelow >= totalHeight + gap) {\n return {\n top: bounds.y + bounds.height + gap,\n position: \"below\",\n };\n }\n\n // Try above if there's enough space\n if (spaceAbove >= totalHeight + gap) {\n return {\n top: bounds.y - totalHeight - gap,\n position: \"above\",\n };\n }\n\n // Neither fits perfectly - clamp to viewport\n const position = spaceBelow > spaceAbove ? \"below\" : \"above\";\n let top: number;\n\n if (position === \"below\") {\n top = Math.min(\n bounds.y + bounds.height + gap,\n viewportHeight - totalHeight - viewportPadding\n );\n } else {\n top = Math.max(viewportPadding, bounds.y - totalHeight - gap);\n }\n\n return { top, position };\n}\n\n/**\n * Calculate horizontal position of modal, clamped to viewport\n */\nexport function calculateHorizontalPosition(\n bounds: SelectedBounds,\n viewportWidth: number,\n modalWidth: number,\n viewportPadding: number\n): number {\n const centerX = bounds.x + bounds.width / 2;\n let left = centerX - modalWidth / 2;\n\n // Clamp to viewport\n left = Math.max(viewportPadding, Math.min(left, viewportWidth - modalWidth - viewportPadding));\n\n return left;\n}\n\n/**\n * Calculate arrow position relative to modal\n * Points at the click position, not the element center\n */\nexport function calculateArrowPosition(\n bounds: SelectedBounds,\n modalLeft: number,\n modalWidth: number,\n minOffset = 24,\n arrowWidth = 24\n): number {\n // Use click position for arrow, not element center\n const targetX = bounds.clickX;\n // Subtract half the arrow width to center it on the target\n const arrowLeft = targetX - modalLeft - arrowWidth / 2;\n\n // Clamp arrow to stay within modal bounds\n return Math.max(minOffset, Math.min(arrowLeft, modalWidth - minOffset - arrowWidth / 2));\n}\n\n/**\n * Calculate complete modal position based on selected element bounds\n */\nexport function calculateModalPosition(\n bounds: SelectedBounds,\n viewportWidth: number,\n viewportHeight: number,\n dimensions: ModalDimensions = DEFAULT_DIMENSIONS\n): ModalPosition {\n const totalHeight = dimensions.height + dimensions.arrowHeight;\n\n const vertical = calculateVerticalPosition(\n bounds,\n viewportHeight,\n totalHeight,\n dimensions.gap,\n dimensions.viewportPadding\n );\n\n const left = calculateHorizontalPosition(\n bounds,\n viewportWidth,\n dimensions.width,\n dimensions.viewportPadding\n );\n\n return {\n top: vertical.top,\n left,\n position: vertical.position,\n };\n}\n\nexport interface TooltipPositionOptions {\n /** Gap in pixels between anchor and tooltip, and from viewport edges */\n gap?: number;\n}\n\n/**\n * Calculate tooltip position relative to an anchor, clamped to the viewport.\n * Pure function: no DOM access — caller passes measured rects and viewport size.\n *\n * Strategy:\n * - Place below the anchor by default\n * - Flip above if below would overflow vertically\n * - Clamp horizontally to viewport, then vertically to viewport\n */\nexport function calculateTooltipPosition(\n anchor: { top: number; bottom: number; left: number },\n tooltip: { width: number; height: number },\n viewport: { width: number; height: number },\n options: TooltipPositionOptions = {}\n): { top: number; left: number } {\n const gap = options.gap ?? 8;\n\n let top = anchor.bottom + gap;\n\n // Flip above if below overflows\n if (top + tooltip.height > viewport.height - gap) {\n top = anchor.top - tooltip.height - gap;\n }\n\n // Clamp horizontally\n let left = anchor.left;\n if (left < gap) {\n left = gap;\n } else if (left + tooltip.width > viewport.width - gap) {\n left = viewport.width - tooltip.width - gap;\n }\n\n // Clamp vertically\n if (top < gap) {\n top = gap;\n } else if (top + tooltip.height > viewport.height - gap) {\n top = viewport.height - tooltip.height - gap;\n }\n\n return { top, left };\n}\n\n/**\n * Calculate both modal and arrow positions\n */\nexport function calculateModalAndArrowPosition(\n bounds: SelectedBounds,\n viewportWidth: number,\n viewportHeight: number,\n dimensions: ModalDimensions = DEFAULT_DIMENSIONS\n): { modal: ModalPosition; arrow: ArrowPosition } {\n const modal = calculateModalPosition(bounds, viewportWidth, viewportHeight, dimensions);\n\n const arrowLeft = calculateArrowPosition(\n bounds,\n modal.left,\n dimensions.width\n );\n\n return {\n modal,\n arrow: { left: arrowLeft },\n };\n}\n","/**\n * Console capture utilities\n */\n\nimport type { ConsoleError } from \"./types\";\n\nconst MAX_MESSAGES = 20;\n\nexport interface ConsoleCapture {\n errors: ConsoleError[];\n restore: () => void;\n}\n\ntype ConsoleLevel = \"error\" | \"warn\" | \"log\";\n\n/**\n * Wrap console methods to capture messages\n */\nexport function captureConsoleErrors(\n onError?: (error: ConsoleError) => void\n): ConsoleCapture {\n const errors: ConsoleError[] = [];\n const originalError = console.error;\n const originalWarn = console.warn;\n const originalLog = console.log;\n\n const capture = (level: ConsoleLevel, args: unknown[]) => {\n const error: ConsoleError = {\n message: args.map((arg) => String(arg)).join(\" \"),\n timestamp: Date.now(),\n level,\n };\n\n // Keep max messages\n if (errors.length >= MAX_MESSAGES) {\n errors.shift();\n }\n errors.push(error);\n\n // Call callback if provided\n if (onError) {\n onError(error);\n }\n };\n\n console.error = function (...args: unknown[]) {\n capture(\"error\", args);\n originalError.apply(console, args);\n };\n\n console.warn = function (...args: unknown[]) {\n capture(\"warn\", args);\n originalWarn.apply(console, args);\n };\n\n console.log = function (...args: unknown[]) {\n capture(\"log\", args);\n originalLog.apply(console, args);\n };\n\n return {\n errors,\n restore: () => {\n console.error = originalError;\n console.warn = originalWarn;\n console.log = originalLog;\n },\n };\n}\n\n/**\n * Add an error to the captured errors array\n */\nexport function addError(errors: ConsoleError[], error: ConsoleError): void {\n if (errors.length >= MAX_MESSAGES) {\n errors.shift();\n }\n errors.push(error);\n}\n\n/**\n * Format console error for display\n */\nexport function formatError(error: ConsoleError): string {\n const date = new Date(error.timestamp);\n const time = date.toLocaleTimeString();\n const levelPrefix = error.level === \"error\" ? \"ERR\" : error.level === \"warn\" ? \"WRN\" : \"LOG\";\n return `[${time}] [${levelPrefix}] ${error.message}`;\n}\n","/**\n * Network capture utilities\n * Intercepts fetch() and XMLHttpRequest to capture 4xx/5xx errors\n */\n\nimport type { NetworkError } from \"./types\";\n\nconst MAX_ENTRIES = 20;\nconst MAX_BODY_SIZE = 4096; // 4KB\n\nexport interface NetworkCapture {\n errors: NetworkError[];\n restore: () => void;\n}\n\n/**\n * Truncate a body to max size. Callers must guard against null/undefined.\n */\nexport function truncateBody(body: unknown): string {\n const str = typeof body === \"string\" ? body : JSON.stringify(body);\n if (str.length > MAX_BODY_SIZE) {\n return str.slice(0, MAX_BODY_SIZE) + \"…[truncated]\";\n }\n return str;\n}\n\n/**\n * Add an error to the buffer, evicting oldest if at capacity\n */\nexport function addEntry(errors: NetworkError[], entry: NetworkError): void {\n if (errors.length >= MAX_ENTRIES) {\n errors.shift();\n }\n errors.push(entry);\n}\n\n/**\n * Read response body as text, with size limit\n */\nasync function safeReadBody(response: Response): Promise<string | undefined> {\n try {\n const text = await response.clone().text();\n return truncateBody(text);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Intercept fetch() and XMLHttpRequest to capture network errors (4xx/5xx)\n */\nexport function captureNetworkErrors(): NetworkCapture {\n const errors: NetworkError[] = [];\n const originalFetch = window.fetch;\n\n // Monkey-patch fetch\n window.fetch = async function (input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.toString() : input.url;\n const method = init?.method ?? (typeof input === \"object\" && \"method\" in input ? input.method : \"GET\");\n let requestBody: string | undefined;\n if (init?.body) {\n requestBody = truncateBody(init.body);\n }\n\n const response = await originalFetch.apply(window, [input, init]);\n\n if (response.status >= 400) {\n const responseBody = await safeReadBody(response);\n addEntry(errors, {\n url,\n method: method.toUpperCase(),\n status: response.status,\n statusText: response.statusText,\n requestBody,\n responseBody,\n timestamp: Date.now(),\n });\n }\n\n return response;\n };\n\n // Monkey-patch XMLHttpRequest\n const originalXHROpen = XMLHttpRequest.prototype.open;\n const originalXHRSend = XMLHttpRequest.prototype.send;\n\n XMLHttpRequest.prototype.open = function (method: string, url: string | URL, ...rest: unknown[]) {\n (this as XMLHttpRequest & { _qaid_method: string; _qaid_url: string })._qaid_method = method;\n (this as XMLHttpRequest & { _qaid_url: string })._qaid_url = typeof url === \"string\" ? url : url.toString();\n return originalXHROpen.apply(this, [method, url, ...rest] as Parameters<typeof originalXHROpen>);\n };\n\n XMLHttpRequest.prototype.send = function (body?: Document | XMLHttpRequestBodyInit | null) {\n const xhr = this as XMLHttpRequest & { _qaid_method: string; _qaid_url: string };\n const requestBody = body ? truncateBody(body) : undefined;\n\n xhr.addEventListener(\"load\", function () {\n if (xhr.status >= 400) {\n addEntry(errors, {\n url: xhr._qaid_url,\n method: xhr._qaid_method.toUpperCase(),\n status: xhr.status,\n statusText: xhr.statusText,\n requestBody,\n responseBody: truncateBody(xhr.responseText),\n timestamp: Date.now(),\n });\n }\n });\n\n return originalXHRSend.apply(this, [body]);\n };\n\n return {\n errors,\n restore: () => {\n window.fetch = originalFetch;\n XMLHttpRequest.prototype.open = originalXHROpen;\n XMLHttpRequest.prototype.send = originalXHRSend;\n },\n };\n}\n","/**\n * iOS/iPadOS screen-recording orientation fix.\n *\n * On iOS/iPadOS, `getDisplayMedia` + `MediaRecorder` writes a device-orientation\n * rotation into the recorded file (even for screen captures). Players disagree\n * on whether to honour it — the widget's own preview `<video>` renders it\n * sideways, and so does the dashboard. Re-encoding the *live* decoded frames\n * (which carry no container rotation) through a canvas produces a file whose\n * pixels are already upright with no rotation metadata, so it renders the same\n * everywhere.\n *\n * If the live frames themselves come back with swapped dimensions (portrait\n * frame while the viewport is landscape, or vice versa), we additionally rotate\n * the canvas 90° to match the viewport. That branch only triggers on a clear\n * orientation mismatch, so a correctly-oriented recording is never rotated.\n */\n\nexport interface OrientationTransform {\n /** Output canvas width in px. */\n width: number;\n /** Output canvas height in px. */\n height: number;\n /** Clockwise rotation to apply while drawing: 0, 90, or -90. */\n rotate: 0 | 90 | -90;\n}\n\nexport interface OrientationCorrectedStream {\n /** Canvas-sourced stream to hand to MediaRecorder. */\n stream: MediaStream;\n /** Stop drawing and release the canvas stream + source video. */\n stop: () => void;\n}\n\n/** True on iPhone/iPad/iPod, including iPadOS 13+ which reports as desktop Mac. */\nexport function isIOSDevice(): boolean {\n const ua = navigator.userAgent || \"\";\n return (\n /iP(hone|ad|od)/.test(ua) ||\n // iPadOS 13+ masquerades as \"MacIntel\" but is a multi-touch device.\n (navigator.platform === \"MacIntel\" && (navigator.maxTouchPoints || 0) > 1)\n );\n}\n\n/**\n * Decide the output canvas size and rotation needed to render a `frameW×frameH`\n * capture upright for a `viewportW×viewportH` viewport. When the frame and\n * viewport share an orientation, no rotation is applied (a straight re-encode,\n * which still strips the bad container rotation). Otherwise rotate 90°, its\n * direction chosen from the screen orientation angle.\n */\nexport function computeOrientationTransform(\n frameW: number,\n frameH: number,\n viewportW: number,\n viewportH: number,\n screenAngle: number\n): OrientationTransform {\n const frameLandscape = frameW >= frameH;\n const viewportLandscape = viewportW >= viewportH;\n\n if (frameLandscape === viewportLandscape) {\n return { width: frameW, height: frameH, rotate: 0 };\n }\n\n // Landscape-secondary (angle 270) is turned the opposite way to primary (90).\n const rotate: 90 | -90 = screenAngle === 270 ? -90 : 90;\n return { width: frameH, height: frameW, rotate };\n}\n\n/** Draw one video frame onto the canvas context, applying the transform. */\nexport function drawRotatedFrame(\n ctx: CanvasRenderingContext2D,\n source: CanvasImageSource,\n t: OrientationTransform\n): void {\n if (t.rotate === 0) {\n ctx.drawImage(source, 0, 0, t.width, t.height);\n return;\n }\n\n ctx.save();\n if (t.rotate === 90) {\n ctx.translate(t.width, 0);\n ctx.rotate(Math.PI / 2);\n } else {\n ctx.translate(0, t.height);\n ctx.rotate(-Math.PI / 2);\n }\n // The source is drawn at its natural (unrotated) extents, which are the\n // output dimensions swapped back.\n ctx.drawImage(source, 0, 0, t.height, t.width);\n ctx.restore();\n}\n\nfunction getScreenAngle(): number {\n const orientation =\n typeof screen !== \"undefined\" ? screen.orientation : undefined;\n return orientation && typeof orientation.angle === \"number\"\n ? orientation.angle\n : 0;\n}\n\nfunction waitForVideoDimensions(video: HTMLVideoElement): Promise<void> {\n return new Promise<void>((resolve) => {\n if (video.videoWidth > 0) {\n resolve();\n return;\n }\n video.addEventListener(\"loadedmetadata\", () => resolve(), { once: true });\n });\n}\n\nasync function playSilently(video: HTMLVideoElement): Promise<void> {\n try {\n await video.play();\n } catch {\n // Autoplay can reject without a gesture; the element still produces frames\n // for the canvas, so this is non-fatal.\n }\n}\n\n/**\n * Build a canvas-backed, orientation-normalised copy of a display-capture\n * stream. Returns null when the browser can't support the canvas pipeline, in\n * which case the caller should record the original stream directly.\n */\nexport async function buildOrientationCorrectedStream(\n displayStream: MediaStream,\n frameRate = 15\n): Promise<OrientationCorrectedStream | null> {\n const canvas = document.createElement(\"canvas\");\n if (typeof canvas.captureStream !== \"function\") return null;\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) return null;\n\n const video = document.createElement(\"video\");\n video.muted = true;\n video.playsInline = true;\n video.srcObject = displayStream;\n\n await waitForVideoDimensions(video);\n\n const transform = computeOrientationTransform(\n video.videoWidth,\n video.videoHeight,\n window.innerWidth,\n window.innerHeight,\n getScreenAngle()\n );\n canvas.width = transform.width;\n canvas.height = transform.height;\n\n await playSilently(video);\n\n let rafId = 0;\n const draw = (): void => {\n drawRotatedFrame(ctx, video, transform);\n rafId = requestAnimationFrame(draw);\n };\n draw();\n\n const stream = canvas.captureStream(frameRate);\n\n return {\n stream,\n stop: (): void => {\n if (rafId) cancelAnimationFrame(rafId);\n rafId = 0;\n stream.getTracks().forEach((t) => t.stop());\n video.pause();\n video.srcObject = null;\n },\n };\n}\n","/**\n * Video capture utilities\n * Uses getDisplayMedia + MediaRecorder for screen recording\n */\n\nimport {\n isIOSDevice,\n buildOrientationCorrectedStream,\n type OrientationCorrectedStream,\n} from \"./video-orientation\";\n\nexport interface VideoRecorderOptions {\n /** Max recording duration in seconds. Default: 15 */\n maxDuration?: number;\n /** Video bitrate in bps. Default: 800000 (800kbps) */\n videoBitsPerSecond?: number;\n}\n\nexport interface VideoRecorder {\n /** Start recording. Requests getDisplayMedia if not already started. */\n start(): Promise<void>;\n /** Stop recording and return the video blob. */\n stop(): Promise<Blob>;\n /** Register a callback for each second tick (receives seconds elapsed). */\n onTick(callback: (elapsed: number) => void): void;\n /** Register a callback for when recording stops (e.g., browser stop button, max duration). */\n onStop(callback: (blob: Blob | null) => void): void;\n /** Clean up all resources. */\n destroy(): void;\n}\n\n/**\n * Check if video recording is supported in this browser\n */\nexport function isVideoRecordingSupported(): boolean {\n return (\n typeof navigator !== \"undefined\" &&\n !!navigator.mediaDevices &&\n typeof navigator.mediaDevices.getDisplayMedia === \"function\" &&\n typeof MediaRecorder !== \"undefined\"\n );\n}\n\n/**\n * Detect the best supported MIME type for recording\n */\nexport function getSupportedMimeType(): string {\n if (typeof MediaRecorder === \"undefined\") return \"\";\n\n const candidates = [\n \"video/webm;codecs=vp9\",\n \"video/webm;codecs=vp8\",\n \"video/webm\",\n \"video/mp4\",\n ];\n\n for (const type of candidates) {\n if (MediaRecorder.isTypeSupported(type)) {\n return type;\n }\n }\n\n return \"\";\n}\n\n/**\n * Create a video recorder that captures the screen\n */\nexport function createVideoRecorder(options: VideoRecorderOptions = {}): VideoRecorder {\n const maxDuration = options.maxDuration ?? 15;\n const videoBitsPerSecond = options.videoBitsPerSecond ?? 800_000;\n\n let stream: MediaStream | null = null;\n let orientationCorrection: OrientationCorrectedStream | null = null;\n let recorder: MediaRecorder | null = null;\n let chunks: Blob[] = [];\n let tickCallback: ((elapsed: number) => void) | null = null;\n let stopCallback: ((blob: Blob | null) => void) | null = null;\n let tickInterval: ReturnType<typeof setInterval> | null = null;\n let startTime = 0;\n let resolveStop: ((blob: Blob) => void) | null = null;\n let rejectStop: ((err: Error) => void) | null = null;\n let stopped = false;\n let autoStopTimeout: ReturnType<typeof setTimeout> | null = null;\n\n function cleanup(): void {\n if (tickInterval !== null) {\n clearInterval(tickInterval);\n tickInterval = null;\n }\n if (autoStopTimeout !== null) {\n clearTimeout(autoStopTimeout);\n autoStopTimeout = null;\n }\n if (orientationCorrection) {\n orientationCorrection.stop();\n orientationCorrection = null;\n }\n if (stream) {\n stream.getTracks().forEach((t) => t.stop());\n stream = null;\n }\n recorder = null;\n chunks = [];\n tickCallback = null;\n stopCallback = null;\n resolveStop = null;\n rejectStop = null;\n }\n\n function finishRecording(): void {\n if (stopped) return;\n stopped = true;\n\n if (recorder && recorder.state !== \"inactive\") {\n recorder.stop();\n }\n }\n\n return {\n async start(): Promise<void> {\n stopped = false;\n chunks = [];\n\n const mimeType = getSupportedMimeType();\n if (!mimeType) {\n throw new Error(\"No supported video MIME type found\");\n }\n\n // Request screen capture\n stream = await navigator.mediaDevices.getDisplayMedia({\n video: {\n frameRate: 15,\n },\n audio: false,\n // @ts-expect-error preferCurrentTab is not in the TS types yet\n preferCurrentTab: true,\n });\n\n // Handle browser \"Stop sharing\" button\n const videoTrack = stream.getVideoTracks()[0];\n if (videoTrack) {\n videoTrack.addEventListener(\"ended\", () => {\n finishRecording();\n });\n }\n\n // On iOS/iPadOS the captured file is rotated by the OS; re-encode the live\n // frames through a canvas so the recording is upright everywhere. Falls\n // back to the raw stream if the canvas pipeline isn't available.\n let recordStream: MediaStream = stream;\n if (isIOSDevice()) {\n const corrected = await buildOrientationCorrectedStream(stream);\n if (corrected) {\n orientationCorrection = corrected;\n recordStream = corrected.stream;\n }\n }\n\n recorder = new MediaRecorder(recordStream, {\n mimeType,\n videoBitsPerSecond,\n });\n\n recorder.ondataavailable = (e: BlobEvent) => {\n if (e.data.size > 0) {\n chunks.push(e.data);\n }\n };\n\n recorder.onstop = () => {\n const blob = new Blob(chunks, { type: mimeType });\n if (resolveStop) {\n resolveStop(blob);\n }\n // Notify via callback (for unexpected stops like browser stop button)\n if (stopCallback) {\n stopCallback(blob);\n }\n // Stop the canvas pipeline (iOS) and the display stream tracks\n if (orientationCorrection) {\n orientationCorrection.stop();\n orientationCorrection = null;\n }\n if (stream) {\n stream.getTracks().forEach((t) => t.stop());\n }\n };\n\n recorder.onerror = () => {\n if (rejectStop) {\n rejectStop(new Error(\"MediaRecorder error\"));\n }\n };\n\n recorder.start(1000); // collect data every second\n startTime = Date.now();\n\n // Start tick interval\n tickInterval = setInterval(() => {\n const elapsed = Math.floor((Date.now() - startTime) / 1000);\n if (tickCallback) {\n tickCallback(elapsed);\n }\n }, 1000);\n\n // Auto-stop at max duration\n autoStopTimeout = setTimeout(() => {\n finishRecording();\n }, maxDuration * 1000);\n },\n\n stop(): Promise<Blob> {\n return new Promise<Blob>((resolve, reject) => {\n resolveStop = resolve;\n rejectStop = reject;\n finishRecording();\n });\n },\n\n onTick(callback: (elapsed: number) => void): void {\n tickCallback = callback;\n },\n\n onStop(callback: (blob: Blob | null) => void): void {\n stopCallback = callback;\n },\n\n destroy(): void {\n finishRecording();\n cleanup();\n },\n };\n}\n","/**\n * DOM utility functions\n */\n\n/**\n * Create an element with attributes and optional children\n */\nexport function createElement<K extends keyof HTMLElementTagNameMap>(\n tag: K,\n attrs?: Record<string, string>,\n children?: (Node | string)[]\n): HTMLElementTagNameMap[K] {\n const el = document.createElement(tag);\n\n if (attrs) {\n for (const [key, value] of Object.entries(attrs)) {\n if (key === \"className\") {\n el.className = value;\n } else {\n el.setAttribute(key, value);\n }\n }\n }\n\n if (children) {\n for (const child of children) {\n if (typeof child === \"string\") {\n el.appendChild(document.createTextNode(child));\n } else {\n el.appendChild(child);\n }\n }\n }\n\n return el;\n}\n\n/**\n * Check if viewport width indicates mobile device\n */\nexport function isMobileViewport(breakpoint = 640): boolean {\n return typeof window !== \"undefined\" && window.innerWidth < breakpoint;\n}\n\n/**\n * Get element at point, temporarily hiding shadow hosts so elementFromPoint\n * sees through to the page elements underneath.\n * Uses visibility:hidden which skips the element in elementFromPoint without\n * triggering reflow.\n */\nexport function getElementAtPointUnderOverlay(\n x: number,\n y: number,\n hosts: HTMLElement[]\n): Element | null {\n const saved = hosts.map((h) => h.style.visibility);\n hosts.forEach((h) => (h.style.visibility = \"hidden\"));\n const element = document.elementFromPoint(x, y);\n hosts.forEach((h, i) => (h.style.visibility = saved[i]));\n return element;\n}\n\n/**\n * Check if an element is part of the feedback embed\n * With shadow DOM, embed elements are inside shadow hosts marked with\n * data-qaid-embed or data-qaid-embed-overlay\n */\nexport function isEmbedElement(element: Element | null): boolean {\n if (!element) return false;\n // Check if the element itself is a shadow host\n if (element.hasAttribute(\"data-qaid-embed\") || element.hasAttribute(\"data-qaid-embed-overlay\")) return true;\n // Check ancestors for shadow host\n return !!element.closest(\"[data-qaid-embed], [data-qaid-embed-overlay]\");\n}\n\n/**\n * Get element bounds with optional padding\n */\nexport function getElementBounds(\n element: Element,\n padding = 0\n): { x: number; y: number; width: number; height: number } {\n const rect = element.getBoundingClientRect();\n return {\n x: rect.left - padding,\n y: rect.top - padding,\n width: rect.width + padding * 2,\n height: rect.height + padding * 2,\n };\n}\n\n/**\n * Remove all elements with a specific class\n */\nexport function removeAllByClass(className: string): void {\n document.querySelectorAll(`.${className}`).forEach((el) => {\n el.classList.remove(className);\n });\n}\n","/**\n * Screenshot capture utility using native Screen Capture API\n */\n\nexport interface ScreenshotOptions {\n /** Quality of WebP compression (0-1). Default: 1.0 */\n quality?: number;\n /** Max width of the screenshot. Default: 1280 */\n maxWidth?: number;\n /** Max height of the screenshot. Default: 800 */\n maxHeight?: number;\n}\n\n/**\n * Captures a screenshot using the native Screen Capture API\n * Requires user permission but produces accurate results\n * Returns a base64-encoded WebP data URL\n */\nexport async function captureScreenshot(\n options: ScreenshotOptions = {}\n): Promise<string | null> {\n const { quality = 1.0, maxWidth = 1280, maxHeight = 800 } = options;\n\n try {\n // Check if API is available\n if (!navigator.mediaDevices?.getDisplayMedia) {\n console.warn('Screen Capture API not available');\n return null;\n }\n\n // Request screen capture - preferCurrentTab auto-selects current tab in supported browsers\n const stream = await navigator.mediaDevices.getDisplayMedia({\n preferCurrentTab: true,\n video: {\n displaySurface: 'browser',\n },\n } as DisplayMediaStreamOptions);\n\n // Get video track\n const track = stream.getVideoTracks()[0];\n const settings = track.getSettings();\n\n // Create video element\n const video = document.createElement('video');\n video.srcObject = stream;\n video.muted = true;\n\n await new Promise<void>((resolve) => {\n video.onloadedmetadata = () => {\n video.play();\n resolve();\n };\n });\n\n // Wait for video to have actual frame data\n await new Promise<void>((resolve) => {\n const checkFrame = () => {\n if (video.readyState >= 2) {\n resolve();\n } else {\n requestAnimationFrame(checkFrame);\n }\n };\n checkFrame();\n });\n\n // Extra delay to ensure frame is rendered\n await new Promise((resolve) => setTimeout(resolve, 100));\n\n // Calculate dimensions\n const srcWidth = settings.width || video.videoWidth;\n const srcHeight = settings.height || video.videoHeight;\n const scale = Math.min(maxWidth / srcWidth, maxHeight / srcHeight, 1);\n const width = Math.round(srcWidth * scale);\n const height = Math.round(srcHeight * scale);\n\n // Draw to canvas\n const canvas = document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n\n const ctx = canvas.getContext('2d');\n if (!ctx) {\n track.stop();\n return null;\n }\n\n ctx.drawImage(video, 0, 0, width, height);\n\n // Stop the stream\n track.stop();\n\n return canvas.toDataURL('image/webp', quality);\n } catch (error) {\n console.warn('Screenshot capture failed:', error);\n return null;\n }\n}\n","/**\n * DOM-based screenshot capture using html2canvas\n * No browser permission dialog required - reconstructs the page from the DOM\n */\n\nexport interface DomScreenshotOptions {\n /** Quality of WebP compression (0-1). Default: 0.8 */\n quality?: number;\n /** Max width of the screenshot. Default: 1280 */\n maxWidth?: number;\n /** Max height of the screenshot. Default: 800 */\n maxHeight?: number;\n}\n\ndeclare global {\n interface Window {\n html2canvas?: (\n element: HTMLElement,\n options?: Record<string, unknown>\n ) => Promise<HTMLCanvasElement>;\n }\n}\n\nconst SCRIPT_URL = \"https://qaid.dev/lib/html2canvas.min.js\";\nconst LOAD_TIMEOUT = 10_000;\nconst POLL_INTERVAL = 50;\n\nlet loadPromise: Promise<boolean> | null = null;\n\n/**\n * Check if DOM screenshot capture is supported\n * Requires canvas and basic DOM APIs\n */\nexport function isDomScreenshotSupported(): boolean {\n if (typeof document === \"undefined\" || typeof window === \"undefined\") {\n return false;\n }\n // Check canvas support\n const canvas = document.createElement(\"canvas\");\n return typeof canvas.getContext === \"function\" && !!canvas.getContext(\"2d\");\n}\n\n/**\n * Load html2canvas script if not already loaded\n */\nfunction loadHtml2Canvas(): Promise<boolean> {\n if (window.html2canvas) return Promise.resolve(true);\n\n if (loadPromise) return loadPromise;\n\n loadPromise = new Promise<boolean>((resolve) => {\n // Check if script tag already exists\n const existing = document.querySelector(\n `script[src=\"${SCRIPT_URL}\"]`\n ) as HTMLScriptElement | null;\n\n if (!existing) {\n const script = document.createElement(\"script\");\n script.src = SCRIPT_URL;\n script.async = true;\n document.head.appendChild(script);\n }\n\n // Poll for window.html2canvas availability\n const start = Date.now();\n const poll = () => {\n if (window.html2canvas) {\n resolve(true);\n return;\n }\n if (Date.now() - start > LOAD_TIMEOUT) {\n loadPromise = null;\n resolve(false);\n return;\n }\n setTimeout(poll, POLL_INTERVAL);\n };\n poll();\n });\n\n return loadPromise;\n}\n\n/**\n * Capture a screenshot of the current page using html2canvas\n * Returns a base64-encoded WebP data URL, or null on failure\n */\nexport async function captureDomScreenshot(\n options: DomScreenshotOptions = {}\n): Promise<string | null> {\n const { quality = 0.8, maxWidth = 1280, maxHeight = 800 } = options;\n\n try {\n const loaded = await loadHtml2Canvas();\n if (!loaded || !window.html2canvas) {\n console.warn(\"html2canvas failed to load\");\n return null;\n }\n\n const canvas = await window.html2canvas(document.body, {\n useCORS: true,\n allowTaint: false,\n logging: false,\n windowWidth: document.documentElement.clientWidth,\n windowHeight: document.documentElement.clientHeight,\n width: document.documentElement.clientWidth,\n height: document.documentElement.clientHeight,\n x: window.scrollX,\n y: window.scrollY,\n ignoreElements: (el: Element) => {\n // Hide all qaid elements from the screenshot\n if (el instanceof HTMLElement) {\n return (\n el.classList.contains(\"qaid-buttons\") ||\n el.classList.contains(\"qaid-targeting-overlay\") ||\n el.classList.contains(\"qaid-modal-container\") ||\n el.classList.contains(\"qaid-bottom-sheet\") ||\n el.classList.contains(\"qaid-backdrop\") ||\n el.classList.contains(\"qaid-selected-marker\") ||\n el.classList.contains(\"qaid-tooltip-text\") ||\n el.classList.contains(\"qaid-recording-indicator\") ||\n el.classList.contains(\"qaid-video-preview\") ||\n el.className?.toString().startsWith?.(\"qaid-\")\n );\n }\n return false;\n },\n });\n\n // Scale down if needed\n const srcWidth = canvas.width;\n const srcHeight = canvas.height;\n const scale = Math.min(maxWidth / srcWidth, maxHeight / srcHeight, 1);\n\n if (scale < 1) {\n const scaledWidth = Math.round(srcWidth * scale);\n const scaledHeight = Math.round(srcHeight * scale);\n\n const scaledCanvas = document.createElement(\"canvas\");\n scaledCanvas.width = scaledWidth;\n scaledCanvas.height = scaledHeight;\n\n const ctx = scaledCanvas.getContext(\"2d\");\n if (!ctx) return null;\n\n ctx.drawImage(canvas, 0, 0, scaledWidth, scaledHeight);\n return scaledCanvas.toDataURL(\"image/webp\", quality);\n }\n\n return canvas.toDataURL(\"image/webp\", quality);\n } catch (error) {\n console.warn(\"DOM screenshot capture failed:\", error);\n return null;\n }\n}\n","/**\n * Screenshot annotation / markup editor for the thumbs embed.\n *\n * After a screenshot is captured the user can draw on it — rectangles, arrows,\n * a freehand pen, and a blur/redact box — in a full-screen, focus-trapped,\n * WCAG 2.2 AA dialog rendered inside the embed's overlay shadow root. On \"Done\"\n * the base image and the vector shapes are composited into a fresh WebP data\n * URL (so downstream code is unchanged); on \"Skip\"/Escape the original is kept.\n *\n * The geometry and compositing are kept as pure-ish exported functions\n * (`drawShape`, `rectFromPoints`, `compositeAnnotations`) so they can be tested\n * without a real rendering engine — happy-dom has no raster, so tests assert on\n * spied canvas-context calls rather than pixels. The {@link AnnotationEditor}\n * controller keeps the DOM wiring thin and its interactive methods are public\n * so they can be driven directly in tests.\n */\n\nimport { createElement } from \"./dom-utils\";\nimport {\n RECTANGLE_ICON,\n ARROW_ICON,\n PENCIL_ICON,\n BLUR_ICON,\n UNDO_ICON,\n DONE_ICON,\n SKIP_ICON,\n} from \"./icons\";\n\n/** The four drawing tools. */\nexport type ShapeType = \"rect\" | \"arrow\" | \"pen\" | \"blur\";\n\n/** A point in the screenshot's natural-pixel coordinate space. */\nexport interface Point {\n x: number;\n y: number;\n}\n\n/**\n * A single vector annotation. `rect`, `arrow` and `blur` use `points[0]` as the\n * drag start and `points[1]` as the drag end; `pen` uses every point in order.\n */\nexport interface Shape {\n type: ShapeType;\n color: string;\n strokeWidth: number;\n points: Point[];\n}\n\n/** Tile size (natural px) for the mosaic drawn by the blur/redact tool. */\nconst BLUR_TILE = 12;\n\n/** Default stroke colour: a high-visibility red that reads on most screenshots. */\nconst DEFAULT_STROKE = \"#ef4444\";\n/** Default stroke width in natural pixels. */\nconst DEFAULT_STROKE_WIDTH = 4;\n/** Default WebP quality for the re-encoded composite. */\nconst DEFAULT_QUALITY = 0.8;\n\n/** Human-readable labels for the toolbar / announcements (all overridable). */\nexport interface AnnotationLabels {\n title: string;\n instructions: string;\n rectangle: string;\n arrow: string;\n pen: string;\n blur: string;\n undo: string;\n skip: string;\n done: string;\n}\n\nconst DEFAULT_LABELS: AnnotationLabels = {\n title: \"Annotate screenshot\",\n instructions:\n \"Draw on the screenshot to highlight or hide details, then choose Done to attach it or Skip to send the original.\",\n rectangle: \"Rectangle\",\n arrow: \"Arrow\",\n pen: \"Pen\",\n blur: \"Blur or redact\",\n undo: \"Undo last\",\n skip: \"Skip annotation\",\n done: \"Done\",\n};\n\n/**\n * Normalise two drag corners into a top-left origin plus positive width/height,\n * regardless of the direction the user dragged.\n */\nexport function rectFromPoints(\n a: Point,\n b: Point\n): { x: number; y: number; w: number; h: number } {\n return {\n x: Math.min(a.x, b.x),\n y: Math.min(a.y, b.y),\n w: Math.abs(a.x - b.x),\n h: Math.abs(a.y - b.y),\n };\n}\n\n/** A drag/shape too small to be a deliberate mark (a click, not a drag). */\nfunction isDegenerate(shape: Shape): boolean {\n if (shape.type === \"pen\") return shape.points.length < 2;\n const r = rectFromPoints(shape.points[0], shape.points[1]);\n return r.w < 3 && r.h < 3;\n}\n\nfunction drawArrow(\n ctx: CanvasRenderingContext2D,\n from: Point,\n to: Point,\n width: number\n): void {\n ctx.beginPath();\n ctx.moveTo(from.x, from.y);\n ctx.lineTo(to.x, to.y);\n ctx.stroke();\n\n const angle = Math.atan2(to.y - from.y, to.x - from.x);\n const head = Math.max(10, width * 3);\n ctx.beginPath();\n ctx.moveTo(to.x, to.y);\n ctx.lineTo(\n to.x - head * Math.cos(angle - Math.PI / 6),\n to.y - head * Math.sin(angle - Math.PI / 6)\n );\n ctx.moveTo(to.x, to.y);\n ctx.lineTo(\n to.x - head * Math.cos(angle + Math.PI / 6),\n to.y - head * Math.sin(angle + Math.PI / 6)\n );\n ctx.stroke();\n}\n\nfunction drawPen(ctx: CanvasRenderingContext2D, points: Point[]): void {\n if (points.length === 0) return;\n ctx.beginPath();\n ctx.moveTo(points[0].x, points[0].y);\n for (let i = 1; i < points.length; i++) {\n ctx.lineTo(points[i].x, points[i].y);\n }\n ctx.stroke();\n}\n\n/**\n * Redact a region so the underlying content is GONE from the composite — not\n * merely dimmed. Both fills are fully opaque (no alpha), so nothing bleeds\n * through; the two-tone mosaic just gives it a recognisable \"redacted\" texture.\n * There is no real Gaussian blur (it can't be verified without a raster), and a\n * translucent wash would leave sensitive text faintly legible — so this paints\n * solid.\n */\nfunction drawBlur(\n ctx: CanvasRenderingContext2D,\n x: number,\n y: number,\n w: number,\n h: number\n): void {\n ctx.fillStyle = \"rgb(15, 23, 42)\";\n ctx.fillRect(x, y, w, h);\n ctx.fillStyle = \"rgb(37, 47, 63)\";\n for (let ty = y; ty < y + h; ty += BLUR_TILE) {\n for (let tx = x; tx < x + w; tx += BLUR_TILE) {\n const checker =\n (Math.floor((tx - x) / BLUR_TILE) + Math.floor((ty - y) / BLUR_TILE)) %\n 2 ===\n 0;\n if (checker) {\n ctx.fillRect(\n tx,\n ty,\n Math.min(BLUR_TILE, x + w - tx),\n Math.min(BLUR_TILE, y + h - ty)\n );\n }\n }\n }\n}\n\n/**\n * Draw a single shape onto a 2D context in the shape's own (natural-pixel)\n * coordinates. Used both for the live editing preview and for the final\n * composite, so what the user sees is exactly what is submitted.\n */\nexport function drawShape(ctx: CanvasRenderingContext2D, shape: Shape): void {\n ctx.save();\n ctx.strokeStyle = shape.color;\n ctx.fillStyle = shape.color;\n ctx.lineWidth = shape.strokeWidth;\n ctx.lineJoin = \"round\";\n ctx.lineCap = \"round\";\n\n switch (shape.type) {\n case \"rect\": {\n const r = rectFromPoints(shape.points[0], shape.points[1]);\n ctx.strokeRect(r.x, r.y, r.w, r.h);\n break;\n }\n case \"arrow\":\n drawArrow(ctx, shape.points[0], shape.points[1], shape.strokeWidth);\n break;\n case \"pen\":\n drawPen(ctx, shape.points);\n break;\n case \"blur\": {\n const r = rectFromPoints(shape.points[0], shape.points[1]);\n drawBlur(ctx, r.x, r.y, r.w, r.h);\n break;\n }\n }\n\n ctx.restore();\n}\n\n/** Load an image from a data URL. Resolves with the element once decoded. */\nfunction loadImage(src: string): Promise<HTMLImageElement> {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = (): void => resolve(img);\n img.onerror = (): void => reject(new Error(\"Failed to load screenshot\"));\n img.src = src;\n });\n}\n\n/**\n * Composite the base screenshot and the drawn shapes into a new WebP data URL\n * at the image's natural size. Falls back to the original data URL if the image\n * can't be loaded or a 2D context isn't available (so a submission is never\n * lost). This is intentionally standalone so it can be unit-tested in isolation.\n */\nexport async function compositeAnnotations(\n dataUrl: string,\n shapes: Shape[],\n opts: { quality?: number } = {}\n): Promise<string> {\n const quality = opts.quality ?? DEFAULT_QUALITY;\n\n let img: HTMLImageElement;\n try {\n img = await loadImage(dataUrl);\n } catch {\n return dataUrl;\n }\n\n const canvas = document.createElement(\"canvas\");\n canvas.width = img.naturalWidth || img.width || 1;\n canvas.height = img.naturalHeight || img.height || 1;\n\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) return dataUrl;\n\n ctx.drawImage(img, 0, 0, canvas.width, canvas.height);\n for (const shape of shapes) {\n drawShape(ctx, shape);\n }\n\n return canvas.toDataURL(\"image/webp\", quality);\n}\n\n/** Options for {@link AnnotationEditor} / {@link openAnnotationEditor}. */\nexport interface AnnotationEditorOptions {\n /** The captured screenshot as a WebP data URL. */\n dataUrl: string;\n /** Shadow root (or element) the editor is mounted into. */\n root: ShadowRoot | HTMLElement;\n /** WebP quality for the re-encoded composite. */\n quality?: number;\n /** Default stroke colour for rectangle/arrow/pen. */\n color?: string;\n /** Default stroke width. */\n strokeWidth?: number;\n /** Label overrides. */\n labels?: Partial<AnnotationLabels>;\n /** Apply the embed's per-instance `--qaid-*` CSS variables to the container. */\n applyVars?: (el: HTMLElement) => void;\n /** Announce a message via the embed's live regions. */\n announce?: (message: string, assertive?: boolean) => void;\n /** Turn the container into an accessible modal dialog (focus trap + inert). */\n openDialog?: (\n container: HTMLElement,\n opts: { labelledbyId?: string; describedbyId?: string }\n ) => void;\n /** Tear down the dialog semantics and restore focus. */\n closeDialog?: () => void;\n}\n\nlet editorSeq = 0;\n\n/**\n * Full-screen screenshot annotation editor. Construct it, call {@link open}\n * (which returns a promise resolving to the composited WebP, or `null` when the\n * user skips), and the controller manages its own DOM and teardown.\n */\nexport class AnnotationEditor {\n readonly shapes: Shape[] = [];\n tool: ShapeType = \"rect\";\n\n private readonly opts: AnnotationEditorOptions;\n private readonly labels: AnnotationLabels;\n private readonly color: string;\n private readonly strokeWidth: number;\n private readonly uid = `qaid-annotate-${++editorSeq}`;\n\n private container!: HTMLDivElement;\n private canvas!: HTMLCanvasElement;\n private ctx: CanvasRenderingContext2D | null = null;\n private toolbar!: HTMLDivElement;\n private undoBtn!: HTMLButtonElement;\n private img: HTMLImageElement | null = null;\n\n private drawing = false;\n private current: Shape | null = null;\n private settled = false;\n // Assigned in open() before any settle() is reachable (done/skip only fire\n // after the editor is mounted).\n private resolveResult!: (value: string | null) => void;\n\n constructor(opts: AnnotationEditorOptions) {\n this.opts = opts;\n this.labels = { ...DEFAULT_LABELS, ...(opts.labels ?? {}) };\n this.color = opts.color ?? DEFAULT_STROKE;\n this.strokeWidth = opts.strokeWidth ?? DEFAULT_STROKE_WIDTH;\n }\n\n /** Mount the editor and resolve when the user commits (Done) or skips. */\n open(): Promise<string | null> {\n const promise = new Promise<string | null>((resolve) => {\n this.resolveResult = resolve;\n });\n this.mount();\n return promise;\n }\n\n private toolButton(tool: ShapeType, icon: string, label: string): HTMLButtonElement {\n const btn = createElement(\"button\", {\n type: \"button\",\n class: \"qaid-annotate-tool\",\n \"data-qaid-tool\": tool,\n \"aria-pressed\": tool === this.tool ? \"true\" : \"false\",\n \"aria-label\": `${label} tool`,\n title: label,\n });\n btn.innerHTML = icon;\n return btn;\n }\n\n private actionButton(\n action: string,\n icon: string,\n label: string,\n extraClass: string\n ): HTMLButtonElement {\n const btn = createElement(\"button\", {\n type: \"button\",\n class: `qaid-annotate-action ${extraClass}`,\n \"data-qaid-action\": action,\n \"aria-label\": label,\n title: label,\n });\n btn.innerHTML = `${icon}<span class=\"qaid-annotate-btn-text\">${label}</span>`;\n return btn;\n }\n\n private mount(): void {\n const titleId = `${this.uid}-title`;\n const descId = `${this.uid}-desc`;\n\n this.container = createElement(\"div\", { class: \"qaid-annotate\" });\n this.opts.applyVars?.(this.container);\n\n const title = createElement(\"h2\", {\n id: titleId,\n class: \"qaid-annotate-title\",\n });\n title.textContent = this.labels.title;\n\n const desc = createElement(\"p\", {\n id: descId,\n class: \"qaid-annotate-desc\",\n });\n desc.textContent = this.labels.instructions;\n\n const stage = createElement(\"div\", { class: \"qaid-annotate-stage\" });\n this.canvas = document.createElement(\"canvas\");\n this.canvas.className = \"qaid-annotate-canvas\";\n this.canvas.width = 1;\n this.canvas.height = 1;\n this.canvas.setAttribute(\"role\", \"img\");\n this.canvas.setAttribute(\"aria-label\", this.labels.title);\n this.ctx = this.canvas.getContext(\"2d\");\n stage.appendChild(this.canvas);\n\n this.toolbar = createElement(\"div\", {\n class: \"qaid-annotate-toolbar\",\n role: \"toolbar\",\n \"aria-label\": this.labels.title,\n });\n\n const tools = createElement(\"div\", { class: \"qaid-annotate-tools\" });\n tools.appendChild(this.toolButton(\"rect\", RECTANGLE_ICON, this.labels.rectangle));\n tools.appendChild(this.toolButton(\"arrow\", ARROW_ICON, this.labels.arrow));\n tools.appendChild(this.toolButton(\"pen\", PENCIL_ICON, this.labels.pen));\n tools.appendChild(this.toolButton(\"blur\", BLUR_ICON, this.labels.blur));\n\n this.undoBtn = this.actionButton(\"undo\", UNDO_ICON, this.labels.undo, \"qaid-annotate-undo\");\n this.undoBtn.disabled = true;\n\n const skipBtn = this.actionButton(\"skip\", SKIP_ICON, this.labels.skip, \"qaid-annotate-skip\");\n const doneBtn = this.actionButton(\"done\", DONE_ICON, this.labels.done, \"qaid-annotate-done\");\n\n const actions = createElement(\"div\", { class: \"qaid-annotate-actions\" });\n actions.appendChild(this.undoBtn);\n actions.appendChild(skipBtn);\n actions.appendChild(doneBtn);\n\n this.toolbar.appendChild(tools);\n this.toolbar.appendChild(actions);\n\n this.container.appendChild(title);\n this.container.appendChild(desc);\n this.container.appendChild(stage);\n this.container.appendChild(this.toolbar);\n this.opts.root.appendChild(this.container);\n\n this.toolbar.addEventListener(\"click\", this.onToolbarClick);\n this.canvas.addEventListener(\"pointerdown\", this.onPointerDown);\n this.container.addEventListener(\"pointermove\", this.onPointerMove);\n this.container.addEventListener(\"pointerup\", this.onPointerUp);\n this.container.addEventListener(\"keydown\", this.onKeyDown);\n\n this.opts.openDialog?.(this.container, {\n labelledbyId: titleId,\n describedbyId: descId,\n });\n this.opts.announce?.(this.labels.instructions);\n\n loadImage(this.opts.dataUrl)\n .then((img) => {\n this.img = img;\n this.canvas.width = img.naturalWidth || img.width || 1;\n this.canvas.height = img.naturalHeight || img.height || 1;\n this.redraw();\n })\n .catch(() => {\n this.img = null;\n this.redraw();\n });\n }\n\n /** Convert a pointer event's client coordinates into natural image pixels. */\n private toImageCoords(e: { clientX: number; clientY: number }): Point {\n const rect = this.canvas.getBoundingClientRect();\n const scaleX = this.canvas.width / (rect.width || this.canvas.width);\n const scaleY = this.canvas.height / (rect.height || this.canvas.height);\n return {\n x: (e.clientX - rect.left) * scaleX,\n y: (e.clientY - rect.top) * scaleY,\n };\n }\n\n /** Repaint the display canvas: base image (if loaded) then every shape. */\n redraw(): void {\n const ctx = this.ctx;\n if (!ctx) return;\n ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);\n if (this.img) {\n ctx.drawImage(this.img, 0, 0, this.canvas.width, this.canvas.height);\n }\n for (const shape of this.shapes) {\n drawShape(ctx, shape);\n }\n if (this.current) {\n drawShape(ctx, this.current);\n }\n }\n\n /** Select the active drawing tool and reflect it on the toolbar. */\n selectTool(tool: ShapeType): void {\n this.tool = tool;\n const buttons = this.toolbar.querySelectorAll<HTMLButtonElement>(\"[data-qaid-tool]\");\n buttons.forEach((btn) => {\n btn.setAttribute(\n \"aria-pressed\",\n btn.getAttribute(\"data-qaid-tool\") === tool ? \"true\" : \"false\"\n );\n });\n const label = this.labels[LABEL_KEY[tool]];\n this.opts.announce?.(`${label} tool selected`);\n }\n\n private onToolbarClick = (e: Event): void => {\n const target = e.target as HTMLElement | null;\n const btn = target?.closest<HTMLElement>(\"[data-qaid-tool],[data-qaid-action]\");\n if (!btn) return;\n const tool = btn.getAttribute(\"data-qaid-tool\");\n if (tool) {\n this.selectTool(tool as ShapeType);\n return;\n }\n const action = btn.getAttribute(\"data-qaid-action\");\n if (action === \"undo\") this.undo();\n else if (action === \"skip\") this.skip();\n else if (action === \"done\") void this.done();\n };\n\n onPointerDown = (e: PointerEvent): void => {\n e.preventDefault?.();\n this.drawing = true;\n const p = this.toImageCoords(e);\n this.current = {\n type: this.tool,\n color: this.color,\n strokeWidth: this.strokeWidth,\n points: this.tool === \"pen\" ? [p] : [p, { ...p }],\n };\n this.redraw();\n };\n\n onPointerMove = (e: PointerEvent): void => {\n if (!this.drawing || !this.current) return;\n const p = this.toImageCoords(e);\n if (this.current.type === \"pen\") {\n this.current.points.push(p);\n } else {\n this.current.points[1] = p;\n }\n this.redraw();\n };\n\n onPointerUp = (): void => {\n if (!this.drawing || !this.current) return;\n this.drawing = false;\n const shape = this.current;\n this.current = null;\n if (isDegenerate(shape)) {\n this.redraw();\n return;\n }\n this.shapes.push(shape);\n this.undoBtn.disabled = false;\n this.opts.announce?.(\"Annotation added\");\n this.redraw();\n };\n\n onKeyDown = (e: KeyboardEvent): void => {\n if (e.key === \"Escape\") {\n e.preventDefault();\n this.skip();\n return;\n }\n if (e.key === \"Enter\") {\n const target = e.target as HTMLElement | null;\n // Let Enter activate a focused tool/action button natively.\n if (target?.getAttribute(\"data-qaid-tool\") || target?.getAttribute(\"data-qaid-action\")) {\n return;\n }\n e.preventDefault();\n void this.done();\n }\n };\n\n /** Remove the most recently added shape. */\n undo(): void {\n if (this.shapes.length === 0) {\n this.opts.announce?.(\"Nothing to undo\");\n return;\n }\n this.shapes.pop();\n this.undoBtn.disabled = this.shapes.length === 0;\n this.opts.announce?.(\"Removed last annotation\");\n this.redraw();\n }\n\n /** Composite the annotations and resolve with the new WebP data URL. */\n async done(): Promise<void> {\n if (this.settled) return;\n const out = await compositeAnnotations(this.opts.dataUrl, this.shapes, {\n quality: this.opts.quality,\n });\n this.opts.announce?.(\"Annotated screenshot attached\");\n this.settle(out);\n }\n\n /** Discard annotations and resolve with `null` (caller keeps the original). */\n skip(): void {\n if (this.settled) return;\n this.opts.announce?.(\"Annotation skipped\");\n this.settle(null);\n }\n\n private settle(value: string | null): void {\n this.settled = true;\n this.teardown();\n this.resolveResult(value);\n }\n\n private teardown(): void {\n this.toolbar.removeEventListener(\"click\", this.onToolbarClick);\n this.canvas.removeEventListener(\"pointerdown\", this.onPointerDown);\n this.container.removeEventListener(\"pointermove\", this.onPointerMove);\n this.container.removeEventListener(\"pointerup\", this.onPointerUp);\n this.container.removeEventListener(\"keydown\", this.onKeyDown);\n this.opts.closeDialog?.();\n this.container.remove();\n }\n}\n\n/** Maps a tool id to its label key, for announcements. */\nconst LABEL_KEY: Record<ShapeType, keyof AnnotationLabels> = {\n rect: \"rectangle\",\n arrow: \"arrow\",\n pen: \"pen\",\n blur: \"blur\",\n};\n\n/**\n * Open the annotation editor and resolve with the composited WebP data URL, or\n * `null` if the user skipped. Thin entry point used by the embed.\n */\nexport function openAnnotationEditor(\n opts: AnnotationEditorOptions\n): Promise<string | null> {\n return new AnnotationEditor(opts).open();\n}\n","/**\n * Lazy loader + launcher for `@qaiddev/quests-embed`.\n *\n * `thumbs-embed` links a button to a quest but owns no questionnaire code\n * and takes no build-time dependency on the quests package. Instead the\n * quests widget is imported from a CDN the first time a quest is triggered,\n * so the shipped bundle stays zero-dependency and small.\n *\n * Only the tiny slice of the quests public API that we actually use is\n * modelled here structurally, so a version bump of the quests package that\n * keeps this surface stable needs no change in thumbs-embed.\n */\n\n/** Default ES-module URL, pinned to a compatible major on unpkg. */\nexport const DEFAULT_QUESTS_MODULE_URL =\n \"https://unpkg.com/@qaiddev/quests-embed@1/dist/qaid-quests.js\";\n\n/** The bit of a QaidQuests instance we hold onto. */\nexport interface QuestInstance {\n destroy(): void;\n}\n\n/** The bit of QaidQuests config we pass. Mirrors QuestsConfig loosely. */\nexport interface LaunchedQuestConfig {\n endpoint: string;\n configUrl: string;\n apiKey?: string;\n metadata?: Record<string, unknown>;\n onComplete?: (answers: Record<string, unknown>) => void;\n onClose?: () => void;\n}\n\ntype QuestsConstructor = new (config: LaunchedQuestConfig) => QuestInstance;\n\n/** Shape of the quests module's default/entry exports. */\nexport interface QuestsModule {\n QaidQuests: QuestsConstructor;\n}\n\ntype Importer = (url: string) => Promise<unknown>;\n\nconst defaultImporter: Importer = (url) =>\n // The URL is a runtime value, not a static specifier — keep Vite from\n // trying to analyze/bundle it.\n import(/* @vite-ignore */ url);\n\nlet importer: Importer = defaultImporter;\nlet modulePromise: Promise<QuestsModule> | null = null;\nlet cachedUrl: string | null = null;\n\n/**\n * @internal Test seam: swap the dynamic importer and clear the cache.\n * Pass `null` to restore the real dynamic `import()`. Not re-exported\n * from the package entry, so it isn't public API.\n */\nexport function _setQuestsImporter(fn: Importer | null): void {\n importer = fn ?? defaultImporter;\n modulePromise = null;\n cachedUrl = null;\n}\n\n/**\n * Import the quests module, caching the promise per URL. A failed load\n * clears the cache so a later trigger can retry (e.g. after a transient\n * network error) rather than being stuck with a rejected promise.\n */\nexport function loadQuestsModule(moduleUrl: string): Promise<QuestsModule> {\n if (modulePromise && cachedUrl === moduleUrl) return modulePromise;\n cachedUrl = moduleUrl;\n modulePromise = Promise.resolve(importer(moduleUrl))\n .then((mod) => {\n const m = mod as Partial<QuestsModule>;\n if (!m || typeof m.QaidQuests !== \"function\") {\n throw new Error(\"quests module has no QaidQuests export\");\n }\n return m as QuestsModule;\n })\n .catch((err) => {\n modulePromise = null;\n cachedUrl = null;\n throw err;\n });\n return modulePromise;\n}\n\nexport interface LaunchQuestOptions {\n /** Quest id to launch (the `[id]` in `{base}/{id}/definition`). */\n questId: string;\n /** Quest-service base URL, e.g. \"https://qaid.dev/api/quests\". */\n base: string;\n /** API key for the quest service (optional). */\n apiKey?: string;\n /** ES-module URL to load the quests widget from. */\n moduleUrl: string;\n /** Feedback record id to correlate the response with (optional). */\n feedbackId?: string | number | null;\n /** Called when the quest embed is torn down. */\n onClose?: () => void;\n}\n\n/**\n * Load the quests widget (if not already loaded) and open the given quest\n * as its own centered modal. Rejects if the module can't be loaded — the\n * caller should fall back to its normal UI.\n */\nexport async function launchQuest(opts: LaunchQuestOptions): Promise<QuestInstance> {\n const mod = await loadQuestsModule(opts.moduleUrl);\n const base = opts.base.replace(/\\/+$/, \"\");\n const metadata =\n opts.feedbackId != null ? { feedbackId: opts.feedbackId } : undefined;\n return new mod.QaidQuests({\n endpoint: `${base}/responses`,\n configUrl: `${base}/${encodeURIComponent(opts.questId)}/definition`,\n apiKey: opts.apiKey || undefined,\n metadata,\n onClose: opts.onClose,\n });\n}\n","import type {\n FeedbackConfig,\n ResolvedFeedbackConfig,\n FeedbackData,\n SelectedBounds,\n EmbedState,\n FeedbackPayload,\n FeedbackResponse,\n} from \"./types\";\nimport { THUMBS_UP_ICON, THUMBS_DOWN_ICON, RECORD_ICON } from \"./icons\";\nimport { injectStyles, removeStyles, buildCssVars, applyCssVars, getEmbedStyles } from \"./styles\";\nimport {\n generateElementInfo,\n startKeyboardTargeting,\n type KeyboardTargetingController,\n} from \"./element-selector\";\nimport {\n announce,\n createFocusTrap,\n saveFocus,\n restoreFocus,\n applyDialog,\n setBackgroundInert,\n type FocusTrap,\n} from \"./a11y\";\nimport { calculateModalAndArrowPosition, calculateTooltipPosition } from \"./modal-positioning\";\nimport { captureConsoleErrors, type ConsoleCapture } from \"./console-capture\";\nimport { captureNetworkErrors, type NetworkCapture } from \"./network-capture\";\nimport {\n createVideoRecorder,\n isVideoRecordingSupported,\n type VideoRecorder,\n} from \"./video-capture\";\nimport {\n getElementAtPointUnderOverlay,\n isEmbedElement,\n getElementBounds,\n isMobileViewport,\n} from \"./dom-utils\";\nimport { captureScreenshot } from \"./screenshot\";\nimport { captureDomScreenshot } from \"./screenshot-dom\";\nimport { openAnnotationEditor } from \"./annotate\";\nimport {\n launchQuest,\n DEFAULT_QUESTS_MODULE_URL,\n type QuestInstance,\n} from \"./quest-launcher\";\n\nconst VISITOR_ID_KEY = \"qaid_visitor_id\";\nconst HIDE_FEEDBACK_KEY = \"qaid_hide_feedback\";\n\n// Max finger travel (px) for a touch to still count as a tap (vs a scroll)\n// when selecting a target element.\nconst TOUCH_TAP_SLOP = 12;\n\n// True when the primary pointer is touch (phone/tablet). On these devices the\n// Screen Capture API (getDisplayMedia) shows an intrusive \"start capturing\"\n// system prompt, dims the screen, and on iOS returns a rotated frame — so the\n// permission-free DOM/canvas screenshot is the right default there.\nfunction isTouchPrimaryDevice(): boolean {\n return (\n typeof window.matchMedia === \"function\" &&\n window.matchMedia(\"(pointer: coarse)\").matches\n );\n}\n\nfunction getHideKey(apiKey?: string): string {\n return apiKey ? `${HIDE_FEEDBACK_KEY}_${apiKey}` : HIDE_FEEDBACK_KEY;\n}\n\nexport function isHiddenByUser(apiKey?: string): boolean {\n try {\n return localStorage.getItem(getHideKey(apiKey)) === \"1\";\n } catch {\n return false;\n }\n}\n\nexport function setHiddenByUser(apiKey?: string, hidden = true): void {\n try {\n if (hidden) {\n localStorage.setItem(getHideKey(apiKey), \"1\");\n } else {\n localStorage.removeItem(getHideKey(apiKey));\n }\n } catch {\n // localStorage not available\n }\n}\n\n/**\n * Get or create a visitor ID stored in localStorage\n */\nexport function getOrCreateVisitorId(): string {\n try {\n let visitorId = localStorage.getItem(VISITOR_ID_KEY);\n if (!visitorId) {\n visitorId = crypto.randomUUID();\n localStorage.setItem(VISITOR_ID_KEY, visitorId);\n }\n return visitorId;\n } catch {\n // localStorage not available, generate a session-only ID\n return crypto.randomUUID();\n }\n}\n\n/**\n * QaidFeedback - Standalone feedback collection embed\n */\nexport class QaidFeedback {\n private config: ResolvedFeedbackConfig;\n private state: EmbedState = \"IDLE\";\n private feedbackData: FeedbackData = {\n feedbackType: null,\n elementSelector: null,\n elementText: null,\n consoleErrors: [],\n };\n private selectedBounds: SelectedBounds = {\n x: 0,\n y: 0,\n width: 0,\n height: 0,\n clickX: 0,\n clickY: 0,\n visible: false,\n };\n private feedbackId: number | null = null;\n // A quest launched from a button (in place of the message box), if any.\n private activeQuest: QuestInstance | null = null;\n private mousePos = { x: 0, y: 0 };\n private isMobile = false;\n private visitorId: string;\n\n // Console capture\n private consoleCapture: ConsoleCapture | null = null;\n\n // Video recording\n private videoRecorder: VideoRecorder | null = null;\n private networkCapture: NetworkCapture | null = null;\n private recordedBlob: Blob | null = null;\n private recordingIndicator: HTMLDivElement | null = null;\n private videoPreview: HTMLDivElement | null = null;\n private isRecording = false;\n private isSendingVideo = false;\n\n // Shadow DOM\n private shadowHost: HTMLDivElement | null = null;\n private shadowRoot: ShadowRoot | null = null;\n\n // Overlay shadow DOM (always on document.body for full-page coverage)\n private overlayShadowHost: HTMLDivElement | null = null;\n private overlayShadowRoot: ShadowRoot | null = null;\n\n // DOM elements (inside shadow root)\n private buttonsContainer: HTMLDivElement | null = null;\n private isUserProvidedContainer = false;\n private overlayContainer: HTMLDivElement | null = null;\n private captureLayer: HTMLDivElement | null = null;\n private crosshairH: HTMLDivElement | null = null;\n private crosshairV: HTMLDivElement | null = null;\n private scope: HTMLDivElement | null = null;\n private highlightBox: HTMLDivElement | null = null;\n private marker: HTMLDivElement | null = null;\n private modalContainer: HTMLDivElement | null = null;\n private backdrop: HTMLDivElement | null = null;\n private dismissBtn: HTMLButtonElement | null = null;\n\n // Per-instance CSS variables\n private cssVars: Record<string, string> = {};\n\n // Keyboard element-targeting\n private keyboardController: KeyboardTargetingController | null = null;\n private activeThumbBtn: HTMLElement | null = null;\n // Tracks whether the pending activation came from the keyboard (Enter/Space)\n // rather than a pointer, so targeting can avoid elementFromPoint(0,0).\n private keyboardActivation = false;\n\n // Accessibility: dialog focus management\n private dialogTrigger: HTMLElement | null = null;\n private dialogTrap: FocusTrap | null = null;\n private dialogRestoreInert: (() => void) | null = null;\n\n // Unique id suffix for aria-labelledby/describedby references\n private readonly uid = Math.random().toString(36).slice(2, 9);\n\n // Bound event handlers\n private boundKeyDown: (e: KeyboardEvent) => void;\n private boundMouseMove: (e: MouseEvent) => void;\n private boundClick: (e: MouseEvent) => void;\n // Touch equivalents for targeting. iOS/iPadOS does not synthesise `click`\n // (or `mousemove`) for taps on non-interactive page elements, so targeting\n // must be driven by touch events there.\n private boundTouchStart: (e: TouchEvent) => void;\n private boundTouchEnd: (e: TouchEvent) => void;\n // Where the current targeting touch began, to tell a tap from a scroll.\n private touchStartPos: { x: number; y: number } | null = null;\n private boundResize: () => void;\n\n // Start with buttons slid off-screen (localStorage dismiss, no animation)\n private _startDismissed = false;\n\n // DOM persistence (survives framework client-side navigation)\n private destroyed = false;\n private domObserver: MutationObserver | null = null;\n private boundBeforeSwap: ((e: Event) => void) | null = null;\n\n constructor(config: FeedbackConfig) {\n this.config = {\n endpoint: config.endpoint,\n apiKey: config.apiKey ?? \"\",\n container: config.container ?? \"\",\n buttonClass: config.buttonClass ?? \"\",\n direction: config.direction ?? \"horizontal\",\n position: config.position ?? \"bottom-right\",\n offset: {\n x: config.offset?.x ?? 16,\n y: config.offset?.y ?? 16,\n },\n zIndex: config.zIndex ?? 50,\n skipTargeting: config.skipTargeting ?? false,\n colors: {\n positive: config.colors?.positive ?? \"rgb(0, 200, 83)\",\n negative: config.colors?.negative ?? \"rgb(255, 0, 0)\",\n marker: config.colors?.marker ?? \"#6366f1\",\n },\n buttonSize: config.buttonSize ?? \"medium\",\n text: {\n tooltip: config.text?.tooltip ?? \"\",\n modalTitle: config.text?.modalTitle ?? \"Thank you for your feedback!\",\n modalSubtitle: config.text?.modalSubtitle ?? \"Would you like to add a message to help us understand your feedback better?\",\n placeholder: config.text?.placeholder ?? \"Optional: Tell us more about your experience...\",\n submitButton: config.text?.submitButton ?? \"Submit\",\n skipButton: config.text?.skipButton ?? \"Skip\",\n positiveLabel: config.text?.positiveLabel ?? \"Send positive feedback\",\n negativeLabel: config.text?.negativeLabel ?? \"Send negative feedback\",\n recordLabel: config.text?.recordLabel ?? \"Record a screen recording\",\n dismissLabel: config.text?.dismissLabel ?? \"Hide Feedback\",\n },\n modalWidth: config.modalWidth ?? 400,\n backdropOpacity: config.backdropOpacity ?? 0.3,\n fontFamily: config.fontFamily ?? \"system-ui, -apple-system, sans-serif\",\n fontSize: config.fontSize ?? 16,\n captureScreenshot: config.captureScreenshot ?? false,\n annotate: config.annotate ?? true,\n screenshotMethod: config.screenshotMethod ?? \"permission\",\n screenshotOptions: {\n quality: config.screenshotOptions?.quality ?? 0.8,\n maxWidth: config.screenshotOptions?.maxWidth ?? 1280,\n maxHeight: config.screenshotOptions?.maxHeight ?? 800,\n },\n incognito: config.incognito ?? false,\n hideDismiss: config.hideDismiss ?? false,\n positiveIcon: config.positiveIcon ?? \"\",\n negativeIcon: config.negativeIcon ?? \"\",\n hideThumbs: config.hideThumbs ?? false,\n css: config.css ?? \"\",\n captureVideo: config.captureVideo ?? false,\n videoOptions: {\n maxDuration: config.videoOptions?.maxDuration ?? 15,\n },\n recordIcon: config.recordIcon ?? \"\",\n quests: {\n base: config.quests?.base ?? \"\",\n up: config.quests?.up ?? \"\",\n down: config.quests?.down ?? \"\",\n video: config.quests?.video ?? \"\",\n // Quest service reuses the feedback API key unless overridden.\n apiKey: config.quests?.apiKey ?? config.apiKey ?? \"\",\n moduleUrl: config.quests?.moduleUrl ?? DEFAULT_QUESTS_MODULE_URL,\n },\n };\n\n // Bind event handlers\n this.boundKeyDown = this.handleKeyDown.bind(this);\n this.boundMouseMove = this.handleMouseMove.bind(this);\n this.boundClick = this.handleClick.bind(this);\n this.boundTouchStart = this.handleTouchStart.bind(this);\n this.boundTouchEnd = this.handleTouchEnd.bind(this);\n this.boundResize = this.handleResize.bind(this);\n\n // Get or create visitor ID for anonymous feedback tracking\n this.visitorId = getOrCreateVisitorId();\n\n this.init();\n }\n\n private applyVars(el: HTMLElement): void {\n applyCssVars(el, this.cssVars);\n }\n\n /**\n * Announce a message via the shared visually-hidden live regions.\n * Prefer the overlay shadow root (which hosts every transient surface and\n * is never inerted by its own dialogs) so announcements are not suppressed\n * while a dialog aria-hides the main button host.\n */\n private announceMsg(message: string, assertive = false): void {\n const root = this.overlayShadowRoot ?? this.shadowRoot;\n if (root) announce(root, message, { assertive });\n }\n\n /**\n * Turn a transient surface into an accessible modal dialog: save the\n * invoking control, apply dialog semantics, trap focus, and inert the\n * background. Paired with closeDialogA11y() on every close path.\n */\n private openDialogA11y(\n container: HTMLElement,\n opts: { labelledbyId?: string; describedbyId?: string; label?: string }\n ): void {\n this.dialogTrigger = saveFocus();\n applyDialog(container, opts);\n this.dialogTrap = createFocusTrap(container);\n this.dialogRestoreInert = setBackgroundInert(container);\n }\n\n private closeDialogA11y(): void {\n this.dialogTrap?.release();\n this.dialogTrap = null;\n if (this.dialogRestoreInert) {\n this.dialogRestoreInert();\n this.dialogRestoreInert = null;\n }\n restoreFocus(this.dialogTrigger);\n this.dialogTrigger = null;\n }\n\n private clearActiveThumb(): void {\n if (this.activeThumbBtn) {\n this.activeThumbBtn.setAttribute(\"aria-pressed\", \"false\");\n this.activeThumbBtn = null;\n }\n }\n\n private init(): void {\n // Inject shared light DOM styles (cursor + highlight, reference counted)\n injectStyles();\n\n // Build per-instance CSS variables\n this.cssVars = buildCssVars({\n positiveColor: this.config.colors.positive,\n negativeColor: this.config.colors.negative,\n markerColor: this.config.colors.marker,\n buttonSize: this.config.buttonSize,\n modalWidth: this.config.modalWidth,\n backdropOpacity: this.config.backdropOpacity,\n fontFamily: this.config.fontFamily,\n fontSize: this.config.fontSize,\n });\n\n // Restore dismiss preference from localStorage (skip if hideDismiss)\n if (!this.config.hideDismiss && isHiddenByUser(this.config.apiKey)) {\n this._startDismissed = true;\n }\n\n // Check mobile\n this.checkMobile();\n window.addEventListener(\"resize\", this.boundResize);\n\n // Create shadow host and embed\n this.createEmbed();\n\n // Capture console errors\n this.consoleCapture = captureConsoleErrors((_error) => {\n this.feedbackData.consoleErrors = this.consoleCapture?.errors ?? [];\n });\n this.feedbackData.consoleErrors = this.consoleCapture.errors;\n\n // Persist across client-side navigations (Astro View Transitions, etc.)\n this.observeDom();\n }\n\n /**\n * Watch for the shadow hosts being removed from the DOM by framework\n * client-side navigation (e.g. Astro View Transitions swapping <body>\n * contents, or any SPA router that replaces DOM subtrees). If the host\n * is disconnected and destroy() wasn't called, re-append it.\n *\n * Also hooks into Astro's `astro:before-swap` when available, which\n * lets us carry elements into the new document before the swap happens\n * (avoids a flash of the widget disappearing and reappearing).\n */\n private observeDom(): void {\n // Astro View Transitions: carry hosts into the new document pre-swap\n this.boundBeforeSwap = (e: Event) => {\n const newDoc = (e as any).newDocument as Document | undefined;\n if (!newDoc || this.destroyed) return;\n if (this.shadowHost) newDoc.body.appendChild(this.shadowHost);\n if (this.overlayShadowHost) newDoc.body.appendChild(this.overlayShadowHost);\n };\n document.addEventListener(\"astro:before-swap\", this.boundBeforeSwap);\n\n // Generic fallback: MutationObserver to catch any framework removing our hosts\n this.domObserver = new MutationObserver(() => {\n if (this.destroyed) return;\n if (this.shadowHost && !this.shadowHost.isConnected) {\n document.body.appendChild(this.shadowHost);\n }\n if (this.overlayShadowHost && !this.overlayShadowHost.isConnected) {\n document.body.appendChild(this.overlayShadowHost);\n }\n });\n this.domObserver.observe(document.body, { childList: true });\n }\n\n private checkMobile(): void {\n this.isMobile = isMobileViewport();\n }\n\n private handleResize(): void {\n this.checkMobile();\n }\n\n private createEmbed(): void {\n // Create the shadow host element\n this.shadowHost = document.createElement(\"div\");\n this.shadowHost.setAttribute(\"data-qaid-embed\", \"\");\n this.shadowHost.style.position = \"static\";\n this.shadowHost.style.display = \"contents\";\n\n // Check if user provided a container selector\n let userContainer: HTMLElement | null = null;\n if (this.config.container) {\n userContainer = document.querySelector(this.config.container);\n }\n\n if (userContainer) {\n userContainer.appendChild(this.shadowHost);\n this.isUserProvidedContainer = true;\n // Container mode never needs a dismiss button\n this.config.hideDismiss = true;\n } else {\n // Set shadow host to fixed positioning for auto-created containers\n this.shadowHost.style.position = \"fixed\";\n this.shadowHost.style.display = \"block\";\n this.shadowHost.style.inset = \"0\";\n this.shadowHost.style.pointerEvents = \"none\";\n this.shadowHost.style.zIndex = String(this.config.zIndex);\n document.body.appendChild(this.shadowHost);\n }\n\n // Attach shadow root\n this.shadowRoot = this.shadowHost.attachShadow({ mode: \"open\" });\n\n // Inject base styles into shadow root\n const baseStyle = document.createElement(\"style\");\n baseStyle.textContent = getEmbedStyles();\n this.shadowRoot.appendChild(baseStyle);\n\n // Inject theme CSS if provided\n if (this.config.css) {\n const themeStyle = document.createElement(\"style\");\n themeStyle.textContent = this.config.css;\n this.shadowRoot.appendChild(themeStyle);\n }\n\n // Create buttons container inside shadow root\n const dirClass = this.config.direction === \"vertical\" ? \"qaid-vertical\" : \"\";\n if (this.isUserProvidedContainer) {\n this.buttonsContainer = document.createElement(\"div\");\n this.buttonsContainer.className = `qaid-buttons qaid-${this.config.position} ${dirClass}`.trim();\n if (this.config.incognito) {\n this.buttonsContainer.classList.add(\"qaid-incognito\");\n }\n } else {\n this.buttonsContainer = document.createElement(\"div\");\n this.buttonsContainer.className = `qaid-buttons qaid-auto-container qaid-${this.config.position} ${dirClass}${this.config.incognito ? \" qaid-incognito\" : \"\"}`.trim();\n this.buttonsContainer.style.pointerEvents = \"auto\";\n // Apply custom offset\n const { x: offsetX, y: offsetY } = this.config.offset;\n if (this.config.position.includes(\"right\")) {\n this.buttonsContainer.style.right = `${offsetX}px`;\n } else {\n this.buttonsContainer.style.left = `${offsetX}px`;\n }\n if (this.config.position.includes(\"bottom\")) {\n this.buttonsContainer.style.bottom = `${offsetY}px`;\n } else {\n this.buttonsContainer.style.top = `${offsetY}px`;\n }\n }\n\n // Apply per-instance CSS variables to buttons container\n this.applyVars(this.buttonsContainer);\n this.shadowRoot.appendChild(this.buttonsContainer);\n\n // Track input modality so a keyboard-activated control (Enter/Space) can be\n // distinguished from a pointer click. A keyboard-fired synthetic click has\n // clientX/clientY===0, which would break elementFromPoint targeting.\n this.buttonsContainer.addEventListener(\"keydown\", (ev) => {\n if (ev.key === \"Enter\" || ev.key === \" \" || ev.key === \"Spacebar\") {\n this.keyboardActivation = true;\n }\n });\n this.buttonsContainer.addEventListener(\"mousedown\", () => {\n this.keyboardActivation = false;\n });\n this.buttonsContainer.addEventListener(\"pointerdown\", () => {\n this.keyboardActivation = false;\n });\n\n // Determine button classes\n const useCustomClass = !!this.config.buttonClass;\n const btnBaseClass = useCustomClass\n ? `qaid-btn-structural ${this.config.buttonClass}`\n : \"qaid-btn\";\n\n // Determine tooltip text\n const defaultTooltip = \"Feedback for us?\";\n const tooltipText = this.config.text.tooltip || defaultTooltip;\n\n // Create shared tooltip element (inside shadow root)\n const tooltip = document.createElement(\"div\");\n tooltip.className = \"qaid-tooltip-text\";\n tooltip.textContent = tooltipText;\n this.applyVars(tooltip);\n this.shadowRoot.appendChild(tooltip);\n this.tooltipElement = tooltip;\n\n // Thumbs up/down buttons (unless hidden)\n if (!this.config.hideThumbs) {\n // Thumbs up button\n const upWrapper = document.createElement(\"div\");\n upWrapper.className = \"qaid-tooltip-wrapper\";\n\n const upBtn = document.createElement(\"button\");\n upBtn.type = \"button\";\n upBtn.className = useCustomClass ? `${btnBaseClass} qaid-btn-up` : \"qaid-btn qaid-btn-up\";\n upBtn.setAttribute(\"aria-label\", this.config.text.positiveLabel);\n upBtn.innerHTML = this.config.positiveIcon || THUMBS_UP_ICON;\n upBtn.addEventListener(\"click\", (e) => this.handleThumbClick(\"up\", e.currentTarget as HTMLElement, e));\n upBtn.addEventListener(\"mouseenter\", () => this.showTooltip(upBtn));\n upBtn.addEventListener(\"mouseleave\", () => this.hideTooltip());\n upWrapper.appendChild(upBtn);\n\n // Thumbs down button\n const downWrapper = document.createElement(\"div\");\n downWrapper.className = \"qaid-tooltip-wrapper\";\n\n const downBtn = document.createElement(\"button\");\n downBtn.type = \"button\";\n downBtn.className = useCustomClass ? `${btnBaseClass} qaid-btn-down` : \"qaid-btn qaid-btn-down\";\n downBtn.setAttribute(\"aria-label\", this.config.text.negativeLabel);\n downBtn.innerHTML = this.config.negativeIcon || THUMBS_DOWN_ICON;\n downBtn.addEventListener(\"click\", (e) => this.handleThumbClick(\"down\", e.currentTarget as HTMLElement, e));\n downBtn.addEventListener(\"mouseenter\", () => this.showTooltip(downBtn));\n downBtn.addEventListener(\"mouseleave\", () => this.hideTooltip());\n downWrapper.appendChild(downBtn);\n\n this.buttonsContainer.appendChild(upWrapper);\n this.buttonsContainer.appendChild(downWrapper);\n }\n\n // Record button (only when captureVideo is true and browser supports it)\n if (this.config.captureVideo && isVideoRecordingSupported()) {\n const recordWrapper = document.createElement(\"div\");\n recordWrapper.className = \"qaid-tooltip-wrapper\";\n\n const recordBtn = document.createElement(\"button\");\n recordBtn.type = \"button\";\n recordBtn.className = useCustomClass ? `${btnBaseClass} qaid-btn-record` : \"qaid-btn qaid-btn-record\";\n recordBtn.setAttribute(\"aria-label\", this.config.text.recordLabel);\n recordBtn.innerHTML = this.config.recordIcon || RECORD_ICON;\n recordBtn.addEventListener(\"click\", () => this.startRecording());\n recordBtn.addEventListener(\"mouseenter\", () => this.showTooltip(recordBtn));\n recordBtn.addEventListener(\"mouseleave\", () => this.hideTooltip());\n recordWrapper.appendChild(recordBtn);\n\n this.buttonsContainer.appendChild(recordWrapper);\n }\n\n // Dismiss (X) button — only in body/fixed mode (hidden for container embeds)\n if (!this.config.hideDismiss) {\n this.dismissBtn = document.createElement(\"button\");\n this.dismissBtn.type = \"button\";\n this.dismissBtn.className = \"qaid-dismiss-btn\";\n this.dismissBtn.setAttribute(\"aria-label\", this.config.text.dismissLabel);\n this.dismissBtn.title = this.config.text.dismissLabel;\n this.dismissBtn.innerHTML = `<svg width=\"12\" height=\"12\" viewBox=\"0 0 12 12\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M2 2l8 8M10 2l-8 8\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\"/></svg>`;\n this.dismissBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n this.handleDismiss();\n });\n // Insert as first child so it sits to the left of thumb buttons\n this.buttonsContainer.insertBefore(this.dismissBtn, this.buttonsContainer.firstChild);\n\n // If previously dismissed via localStorage, start fully hidden so it\n // doesn't flash back on hover — matching the dismiss behavior.\n if (this._startDismissed) {\n this.buttonsContainer.classList.add(\"qaid-dismissed\");\n }\n }\n }\n\n /**\n * Lazily create a separate overlay shadow host on document.body.\n * This host contains all full-page elements (targeting overlay, marker,\n * backdrop, modal, recording indicator, video preview) so they escape\n * clip-path / transform containing blocks in user containers.\n */\n private ensureOverlayHost(): ShadowRoot {\n if (this.overlayShadowRoot) return this.overlayShadowRoot;\n\n this.overlayShadowHost = document.createElement(\"div\");\n this.overlayShadowHost.setAttribute(\"data-qaid-embed-overlay\", \"\");\n this.overlayShadowHost.style.position = \"fixed\";\n this.overlayShadowHost.style.inset = \"0\";\n this.overlayShadowHost.style.pointerEvents = \"none\";\n this.overlayShadowHost.style.zIndex = String(this.config.zIndex);\n document.body.appendChild(this.overlayShadowHost);\n\n this.overlayShadowRoot = this.overlayShadowHost.attachShadow({ mode: \"open\" });\n\n // Inject base styles into overlay shadow root\n const baseStyle = document.createElement(\"style\");\n baseStyle.textContent = getEmbedStyles();\n this.overlayShadowRoot.appendChild(baseStyle);\n\n // Inject theme CSS if provided\n if (this.config.css) {\n const themeStyle = document.createElement(\"style\");\n themeStyle.textContent = this.config.css;\n this.overlayShadowRoot.appendChild(themeStyle);\n }\n\n return this.overlayShadowRoot;\n }\n\n private tooltipElement: HTMLElement | null = null;\n\n private showTooltip(anchor: HTMLElement): void {\n const tooltip = this.tooltipElement!;\n\n // Make visible to measure\n tooltip.style.visibility = \"hidden\";\n tooltip.classList.add(\"qaid-tooltip-visible\");\n\n const anchorRect = anchor.getBoundingClientRect();\n const tooltipRect = tooltip.getBoundingClientRect();\n const { top, left } = calculateTooltipPosition(\n anchorRect,\n tooltipRect,\n { width: window.innerWidth, height: window.innerHeight }\n );\n\n tooltip.style.top = `${top}px`;\n tooltip.style.left = `${left}px`;\n tooltip.style.visibility = \"visible\";\n }\n\n private hideTooltip(): void {\n this.tooltipElement!.classList.remove(\"qaid-tooltip-visible\");\n }\n\n private handleDismiss(): void {\n // Fully remove the widget. It does not linger as a hover-reveal ghost\n // (that's `qaid-incognito`); once dismissed it stays gone until the\n // visitor clears the stored preference.\n this.buttonsContainer!.classList.add(\"qaid-dismissed\");\n setHiddenByUser(this.config.apiKey, true);\n }\n\n private handleThumbClick(type: \"up\" | \"down\", buttonEl: HTMLElement, e: MouseEvent): void {\n // If user clicks a thumb while in incognito mode, they want it back.\n // (Dismissed widgets are `display:none`, so this can't fire for them.)\n if (this.buttonsContainer?.classList.contains(\"qaid-incognito\")) {\n this.buttonsContainer.classList.remove(\"qaid-incognito\");\n setHiddenByUser(this.config.apiKey, false);\n }\n if (this.config.skipTargeting) {\n this.submitDirectFeedback(type, buttonEl);\n } else {\n // Expose targeting on/off state on the trigger\n this.activeThumbBtn = buttonEl;\n buttonEl.setAttribute(\"aria-pressed\", \"true\");\n // A keyboard-activated <button> fires a synthetic click whose clientX/\n // clientY are (0,0). Route those through the keyboard path instead of\n // elementFromPoint(0,0). `keyboardActivation` is set by a preceding\n // Enter/Space keydown and cleared by any pointerdown/mousedown.\n const keyboard = this.keyboardActivation;\n this.keyboardActivation = false;\n if (keyboard) {\n this.startKeyboardTargetingFlow(type);\n } else {\n this.startTargeting(type, e);\n }\n }\n }\n\n private submitDirectFeedback(type: \"up\" | \"down\", buttonEl: HTMLElement): void {\n this.feedbackData.feedbackType = type;\n this.feedbackData.elementSelector = null;\n this.feedbackData.elementText = null;\n\n // Use the button's position for modal placement\n const rect = buttonEl.getBoundingClientRect();\n this.selectedBounds = {\n x: rect.left,\n y: rect.top,\n width: rect.width,\n height: rect.height,\n clickX: rect.left + rect.width / 2,\n clickY: rect.top + rect.height / 2,\n visible: false,\n };\n this.submitFeedback();\n }\n\n private startTargeting(type: \"up\" | \"down\", e: MouseEvent): void {\n this.state = \"TARGETING\";\n this.feedbackData.feedbackType = type;\n this.feedbackData.elementSelector = null;\n this.feedbackData.elementText = null;\n this.selectedBounds.visible = false;\n\n // Track initial mouse position from the click event\n this.mousePos.x = e.clientX;\n this.mousePos.y = e.clientY;\n\n // Add class to body (light DOM — for cursor override)\n document.body.classList.add(\"qaid-targeting\");\n if (type === \"up\") {\n document.body.classList.add(\"qaid-type-up\");\n } else {\n document.body.classList.remove(\"qaid-type-up\");\n }\n\n // Set targeting colors on body so .qaid-highlight rules can resolve them\n document.body.style.setProperty(\"--qaid-positive\", this.cssVars[\"--qaid-positive\"]);\n document.body.style.setProperty(\"--qaid-negative\", this.cssVars[\"--qaid-negative\"]);\n\n // Create targeting overlay (in overlay shadow host)\n this.createTargetingOverlay();\n\n // Add event listeners on document — overlay is pointer-events:none so scroll works naturally\n document.addEventListener(\"keydown\", this.boundKeyDown);\n document.addEventListener(\"mousemove\", this.boundMouseMove);\n document.addEventListener(\"click\", this.boundClick, true);\n // Touch: tap to select (scrolling stays enabled). touchstart is passive\n // (we only read the point); touchend is non-passive so a tap can\n // preventDefault the synthesised click that would otherwise activate the\n // targeted element.\n document.addEventListener(\"touchstart\", this.boundTouchStart, { passive: true });\n document.addEventListener(\"touchend\", this.boundTouchEnd, { passive: false });\n }\n\n /**\n * Keyboard-driven targeting. Mirrors startTargeting minus the mouse\n * plumbing: no `qaid-targeting` body class (keeps the cursor visible for\n * keyboard users), no mouse reticle, and no document mouse/click listeners.\n * The KeyboardTargetingController owns Tab/Arrow/Enter/Space/Escape.\n */\n private startKeyboardTargetingFlow(type: \"up\" | \"down\"): void {\n this.state = \"TARGETING\";\n this.feedbackData.feedbackType = type;\n this.feedbackData.elementSelector = null;\n this.feedbackData.elementText = null;\n this.selectedBounds.visible = false;\n\n // Set overlay theming colors (NOT the cursor-hiding qaid-targeting class)\n document.body.style.setProperty(\"--qaid-positive\", this.cssVars[\"--qaid-positive\"]);\n document.body.style.setProperty(\"--qaid-negative\", this.cssVars[\"--qaid-negative\"]);\n\n // Build the highlight box, then hide the mouse reticle (meaningless here)\n this.createTargetingOverlay();\n if (this.crosshairH) this.crosshairH.style.display = \"none\";\n if (this.crosshairV) this.crosshairV.style.display = \"none\";\n if (this.scope) this.scope.style.display = \"none\";\n\n this.keyboardController = startKeyboardTargeting({\n isExcluded: (el) => isEmbedElement(el),\n onHighlight: (el) => {\n const rect = el.getBoundingClientRect();\n const b = this.highlightBox;\n if (b) {\n b.style.transform = `translate(${rect.left}px, ${rect.top}px)`;\n b.style.width = `${rect.width}px`;\n b.style.height = `${rect.height}px`;\n b.style.display = \"block\";\n }\n const { text } = generateElementInfo(el);\n this.announceMsg(`Targeting ${text || el.tagName.toLowerCase()}`);\n },\n onSelect: (el) => this.selectKeyboardTarget(el),\n onCancel: () => this.cancelTargeting(),\n });\n }\n\n private selectKeyboardTarget(el: Element): void {\n const bounds = getElementBounds(el, 8);\n this.selectedBounds = {\n ...bounds,\n clickX: bounds.x + bounds.width / 2,\n clickY: bounds.y + bounds.height / 2,\n visible: true,\n };\n\n const { selector, text } = generateElementInfo(el);\n this.feedbackData.elementSelector = selector;\n this.feedbackData.elementText = text;\n\n // Teardown (controller has already auto-stopped before onSelect fired)\n this.removeTargetingOverlay();\n document.body.classList.remove(\"qaid-targeting\", \"qaid-type-up\");\n document.body.style.removeProperty(\"--qaid-positive\");\n document.body.style.removeProperty(\"--qaid-negative\");\n this.keyboardController = null;\n this.clearActiveThumb();\n\n this.state = \"SELECTED\";\n this.showSelectedMarker();\n this.submitFeedback();\n }\n\n private createTargetingOverlay(): void {\n const root = this.ensureOverlayHost();\n\n this.overlayContainer = document.createElement(\"div\");\n this.overlayContainer.className = `qaid-targeting-overlay qaid-type-${this.feedbackData.feedbackType}`;\n\n // Capture layer (pointer-events:none — scroll passes through naturally)\n this.captureLayer = document.createElement(\"div\");\n this.captureLayer.className = \"qaid-capture-layer\";\n\n // Vignette\n const vignette = document.createElement(\"div\");\n vignette.className = \"qaid-vignette\";\n\n // Crosshairs\n this.crosshairH = document.createElement(\"div\");\n this.crosshairH.className = \"qaid-crosshair-h\";\n\n this.crosshairV = document.createElement(\"div\");\n this.crosshairV.className = \"qaid-crosshair-v\";\n\n // Scope\n this.scope = document.createElement(\"div\");\n this.scope.className = \"qaid-scope\";\n this.scope.innerHTML = `\n <div class=\"qaid-scope-ring\"></div>\n <div class=\"qaid-scope-ring-inner\"></div>\n <div class=\"qaid-scope-dot\"></div>\n `;\n\n // Highlight box overlay (positioned over hovered elements)\n this.highlightBox = document.createElement(\"div\");\n this.highlightBox.className = \"qaid-highlight-box\";\n\n this.overlayContainer.appendChild(this.captureLayer);\n this.overlayContainer.appendChild(vignette);\n this.overlayContainer.appendChild(this.highlightBox);\n this.overlayContainer.appendChild(this.crosshairH);\n this.overlayContainer.appendChild(this.crosshairV);\n this.overlayContainer.appendChild(this.scope);\n\n // Position crosshairs immediately at current mouse position\n this.crosshairH.style.top = `${this.mousePos.y}px`;\n this.crosshairV.style.left = `${this.mousePos.x}px`;\n this.scope.style.left = `${this.mousePos.x}px`;\n this.scope.style.top = `${this.mousePos.y}px`;\n\n this.applyVars(this.overlayContainer);\n root.appendChild(this.overlayContainer);\n }\n\n private handleKeyDown(e: KeyboardEvent): void {\n if (e.key === \"Escape\") {\n if (this.isRecording) {\n this.stopRecording();\n } else if (this.videoPreview) {\n this.cancelRecordingPreview();\n } else if (this.state === \"TARGETING\") {\n this.cancelTargeting();\n } else if (this.state === \"MODAL_OPEN\") {\n this.closeModal();\n }\n }\n }\n\n private handleMouseMove(e: MouseEvent): void {\n this.updateReticleAt(e.clientX, e.clientY);\n }\n\n /** Move the crosshair/scope reticle and highlight the element under (x, y).\n * Shared by the mouse (hover) and touch (drag) targeting paths. */\n private updateReticleAt(x: number, y: number): void {\n this.mousePos.x = x;\n this.mousePos.y = y;\n\n // Update crosshairs and scope\n if (this.crosshairH) {\n this.crosshairH.style.top = `${y}px`;\n }\n if (this.crosshairV) {\n this.crosshairV.style.left = `${x}px`;\n }\n if (this.scope) {\n this.scope.style.left = `${x}px`;\n this.scope.style.top = `${y}px`;\n }\n\n // Find element underneath — hide both shadow hosts\n if (this.captureLayer && this.shadowHost) {\n const hosts = [this.shadowHost, this.overlayShadowHost].filter(Boolean) as HTMLElement[];\n const elementUnder = getElementAtPointUnderOverlay(x, y, hosts);\n\n if (elementUnder && !isEmbedElement(elementUnder)) {\n if (this.highlightBox) {\n const rect = elementUnder.getBoundingClientRect();\n this.highlightBox.style.transform = `translate(${rect.left}px, ${rect.top}px)`;\n this.highlightBox.style.width = `${rect.width}px`;\n this.highlightBox.style.height = `${rect.height}px`;\n this.highlightBox.style.display = \"block\";\n }\n } else {\n if (this.highlightBox) {\n this.highlightBox.style.display = \"none\";\n }\n }\n }\n }\n\n private handleClick(e: MouseEvent): void {\n e.preventDefault();\n e.stopPropagation();\n this.selectAt(e.clientX, e.clientY);\n }\n\n // ---- Touch targeting (iOS/iPadOS) ----\n // iOS/iPadOS taps on non-interactive elements don't fire click, so touch\n // drives targeting here. Scrolling stays enabled (the page may need to scroll\n // to bring the target into view); a low-movement touch is treated as a tap\n // that selects, distinguishing it from a scroll/drag.\n\n private handleTouchStart(e: TouchEvent): void {\n const t = e.touches[0];\n if (!t) return;\n this.touchStartPos = { x: t.clientX, y: t.clientY };\n // Preview what's under the finger; don't preventDefault so scrolling works.\n this.updateReticleAt(t.clientX, t.clientY);\n }\n\n private handleTouchEnd(e: TouchEvent): void {\n // touches is empty on touchend; the lifted point is in changedTouches.\n const t = e.changedTouches[0];\n const start = this.touchStartPos;\n this.touchStartPos = null;\n if (!t || !start) return;\n // A drag beyond the slop threshold is a scroll, not a selection — ignore it.\n const moved = Math.hypot(t.clientX - start.x, t.clientY - start.y);\n if (moved > TOUCH_TAP_SLOP) return;\n e.preventDefault(); // suppress the tap's synthesised click\n this.selectAt(t.clientX, t.clientY);\n }\n\n /** Select the element under (x, y) and tear down targeting.\n * Shared by the mouse (click) and touch (touchend) targeting paths. */\n private selectAt(x: number, y: number): void {\n // Find element underneath — hide both shadow hosts\n const hosts = [this.shadowHost, this.overlayShadowHost].filter(Boolean) as HTMLElement[];\n const target = getElementAtPointUnderOverlay(x, y, hosts);\n\n if (!target || isEmbedElement(target)) {\n return;\n }\n\n // Get element bounds\n const bounds = getElementBounds(target, 8);\n this.selectedBounds = {\n ...bounds,\n clickX: x,\n clickY: y,\n visible: true,\n };\n\n const { selector, text } = generateElementInfo(target);\n this.feedbackData.elementSelector = selector;\n this.feedbackData.elementText = text;\n\n // Remove targeting overlay and document listeners\n this.stopTargetingListeners();\n document.body.classList.remove(\"qaid-targeting\", \"qaid-type-up\");\n document.body.style.removeProperty(\"--qaid-positive\");\n document.body.style.removeProperty(\"--qaid-negative\");\n\n this.state = \"SELECTED\";\n this.clearActiveThumb();\n\n // Show marker and submit feedback\n this.showSelectedMarker();\n this.submitFeedback();\n }\n\n /** Remove the targeting overlay and every mouse/touch/keyboard listener the\n * pointer-targeting flow attaches to the document. */\n private stopTargetingListeners(): void {\n this.removeTargetingOverlay();\n this.touchStartPos = null;\n document.removeEventListener(\"mousemove\", this.boundMouseMove);\n document.removeEventListener(\"click\", this.boundClick, true);\n document.removeEventListener(\"touchstart\", this.boundTouchStart);\n document.removeEventListener(\"touchend\", this.boundTouchEnd);\n document.removeEventListener(\"keydown\", this.boundKeyDown);\n }\n\n private cancelTargeting(): void {\n this.keyboardController?.stop();\n this.keyboardController = null;\n this.stopTargetingListeners();\n document.body.classList.remove(\"qaid-targeting\", \"qaid-type-up\");\n document.body.style.removeProperty(\"--qaid-positive\");\n document.body.style.removeProperty(\"--qaid-negative\");\n this.clearActiveThumb();\n\n this.state = \"IDLE\";\n this.feedbackData.feedbackType = null;\n this.feedbackData.elementSelector = null;\n this.feedbackData.elementText = null;\n this.selectedBounds.visible = false;\n }\n\n private removeTargetingOverlay(): void {\n if (this.overlayContainer) {\n this.overlayContainer.remove();\n this.overlayContainer = null;\n }\n this.captureLayer = null;\n this.crosshairH = null;\n this.crosshairV = null;\n this.scope = null;\n }\n\n private showSelectedMarker(): void {\n const root = this.ensureOverlayHost();\n\n this.marker = document.createElement(\"div\");\n this.marker.className = \"qaid-selected-marker\";\n this.marker.style.left = `${this.selectedBounds.x}px`;\n this.marker.style.top = `${this.selectedBounds.y}px`;\n this.marker.style.width = `${this.selectedBounds.width}px`;\n this.marker.style.height = `${this.selectedBounds.height}px`;\n this.marker.style.zIndex = String(this.config.zIndex + 1);\n\n this.applyVars(this.marker);\n root.appendChild(this.marker);\n }\n\n private hideSelectedMarker(): void {\n if (this.marker) {\n this.marker.remove();\n this.marker = null;\n }\n }\n\n /** Whether to capture the screenshot with the DOM/canvas method (html2canvas)\n * instead of the permission-based Screen Capture API. Explicit \"dom\" wins;\n * otherwise DOM is used on touch devices to avoid the getDisplayMedia prompt. */\n private shouldCaptureViaDom(): boolean {\n return this.config.screenshotMethod === \"dom\" || isTouchPrimaryDevice();\n }\n\n /**\n * Open the full-screen annotation editor over the captured screenshot,\n * reusing the overlay shadow host and the shared dialog a11y helpers.\n * Resolves with the composited WebP data URL, or null when the user skips\n * (caller keeps the original). Pointer events on the overlay host are\n * enabled while the editor is open and restored on close.\n */\n private async openAnnotationEditor(screenshot: string): Promise<string | null> {\n const root = this.ensureOverlayHost();\n const host = this.overlayShadowHost!;\n const prevPointerEvents = host.style.pointerEvents;\n host.style.pointerEvents = \"auto\";\n try {\n return await openAnnotationEditor({\n dataUrl: screenshot,\n root,\n quality: this.config.screenshotOptions.quality,\n color: this.config.colors.marker,\n applyVars: (el) => this.applyVars(el),\n announce: (msg, assertive) => this.announceMsg(msg, assertive),\n openDialog: (container, opts) => this.openDialogA11y(container, opts),\n closeDialog: () => this.closeDialogA11y(),\n });\n } finally {\n host.style.pointerEvents = prevPointerEvents;\n }\n }\n\n private async submitFeedback(): Promise<void> {\n // Capture screenshot if enabled (server will gate by plan)\n let screenshot: string | null = null;\n if (this.config.captureScreenshot) {\n screenshot = this.shouldCaptureViaDom()\n ? await captureDomScreenshot(this.config.screenshotOptions)\n : await captureScreenshot(this.config.screenshotOptions);\n if (screenshot) this.announceMsg(\"Screenshot captured\");\n }\n\n // Let the user mark up / redact the screenshot before it is submitted.\n // The message modal only opens after the POST below, so the composited\n // result lands in the same request — no backend change needed. On skip\n // the editor resolves null and the original screenshot is kept.\n if (screenshot && this.config.annotate) {\n screenshot = (await this.openAnnotationEditor(screenshot)) ?? screenshot;\n }\n\n // Include element bounds for server-side screenshot fallback\n // Only include if we have an element selector (element was targeted)\n const elementBounds = this.feedbackData.elementSelector\n ? {\n x: this.selectedBounds.x,\n y: this.selectedBounds.y,\n width: this.selectedBounds.width,\n height: this.selectedBounds.height,\n }\n : null;\n\n const payload: FeedbackPayload = {\n feedbackType: this.feedbackData.feedbackType!,\n pageUrl: window.location.href,\n apiKey: this.config.apiKey || undefined,\n elementSelector: this.feedbackData.elementSelector,\n elementText: this.feedbackData.elementText,\n consoleErrors: [...this.feedbackData.consoleErrors],\n screenWidth: window.innerWidth,\n screenHeight: window.innerHeight,\n clickX: this.selectedBounds.clickX,\n clickY: this.selectedBounds.clickY,\n scrollX: window.scrollX,\n scrollY: window.scrollY,\n screenshot,\n visitorId: this.visitorId,\n // Include element bounds and user agent for server-side screenshot fallback\n elementBounds,\n userAgent: navigator.userAgent,\n };\n\n try {\n const response = await fetch(this.config.endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(payload),\n });\n\n if (response.ok) {\n const data: FeedbackResponse = await response.json();\n this.feedbackId = data.id;\n this.announceMsg(\"Feedback sent\");\n }\n } catch (error) {\n console.error(\"Failed to submit feedback:\", error);\n this.announceMsg(\"Failed to send feedback\", true);\n }\n\n // If this button is linked to a quest, launch it in place of the\n // message box. The feedback record already exists, so on success we\n // just tear down the targeting UI and hand off. On any load failure we\n // fall through to the classic message box so the user can still leave\n // an optional message.\n const type = this.feedbackData.feedbackType;\n if (type && (await this.tryLaunchQuest(type, this.feedbackId))) {\n this.resetFeedbackUi();\n return;\n }\n\n // Always show modal (even if API failed - useful for demos)\n this.state = \"MODAL_OPEN\";\n\n this.showModal();\n\n // Enable pointer events on overlay host for modal\n if (this.overlayShadowHost) {\n this.overlayShadowHost.style.pointerEvents = \"auto\";\n }\n }\n\n /**\n * Quest id linked to `type`, or \"\" when quest launching is disabled\n * (no `base`) or this button has no quest configured.\n */\n private questIdFor(type: \"up\" | \"down\" | \"video\"): string {\n const q = this.config.quests;\n return q.base ? q[type] || \"\" : \"\";\n }\n\n /**\n * Launch the quest linked to `type`, if any. Resolves `true` when a quest\n * was configured and the widget launched; `false` when no quest is\n * configured or the widget failed to load (caller falls back to its\n * normal UI). The created feedback record id is passed through so the\n * quest response can be joined back to it server-side.\n */\n private async tryLaunchQuest(\n type: \"up\" | \"down\" | \"video\",\n feedbackId: number | string | null,\n ): Promise<boolean> {\n const questId = this.questIdFor(type);\n if (!questId) return false;\n try {\n this.activeQuest?.destroy();\n this.activeQuest = await launchQuest({\n questId,\n base: this.config.quests.base,\n apiKey: this.config.quests.apiKey || undefined,\n moduleUrl: this.config.quests.moduleUrl,\n feedbackId,\n onClose: () => {\n this.activeQuest = null;\n },\n });\n return true;\n } catch (error) {\n console.error(\"Failed to launch quest:\", error);\n this.activeQuest = null;\n return false;\n }\n }\n\n /**\n * Reset the thumbs targeting/marker UI back to idle without opening or\n * closing the message modal. Shared by closeModal() and the quest-launch\n * path (which bypasses the modal entirely).\n */\n private resetFeedbackUi(): void {\n this.hideSelectedMarker();\n if (this.overlayShadowHost) {\n this.overlayShadowHost.style.pointerEvents = \"none\";\n }\n this.state = \"IDLE\";\n this.feedbackId = null;\n this.feedbackData.feedbackType = null;\n this.feedbackData.elementSelector = null;\n this.feedbackData.elementText = null;\n this.selectedBounds.visible = false;\n }\n\n private showModal(): void {\n const root = this.ensureOverlayHost();\n\n // Create backdrop\n this.backdrop = document.createElement(\"div\");\n this.backdrop.className = \"qaid-backdrop\";\n this.backdrop.style.zIndex = String(this.config.zIndex + 2);\n this.backdrop.style.background = `rgba(0, 0, 0, ${this.config.backdropOpacity})`;\n this.backdrop.addEventListener(\"click\", () => this.closeModal());\n this.applyVars(this.backdrop);\n\n if (this.isMobile) {\n this.showBottomSheet();\n } else {\n this.showPositionedModal();\n }\n\n root.appendChild(this.backdrop);\n document.addEventListener(\"keydown\", this.boundKeyDown);\n }\n\n private showBottomSheet(): void {\n const root = this.ensureOverlayHost();\n\n const sheet = document.createElement(\"div\");\n sheet.className = \"qaid-bottom-sheet\";\n sheet.style.zIndex = String(this.config.zIndex + 3);\n\n sheet.innerHTML = `\n <div class=\"qaid-bottom-sheet-content\">\n <div class=\"qaid-bottom-sheet-handle\"></div>\n ${this.getModalContent()}\n </div>\n `;\n\n this.applyVars(sheet);\n root.appendChild(sheet);\n this.modalContainer = sheet;\n\n this.setupModalInteractions();\n }\n\n private showPositionedModal(): void {\n const root = this.ensureOverlayHost();\n\n const { modal, arrow } = calculateModalAndArrowPosition(\n this.selectedBounds,\n window.innerWidth,\n window.innerHeight,\n {\n width: this.config.modalWidth,\n height: 280,\n arrowHeight: 12,\n gap: 8,\n viewportPadding: 16,\n }\n );\n\n this.modalContainer = document.createElement(\"div\");\n this.modalContainer.className = `qaid-modal-container qaid-${modal.position}`;\n this.modalContainer.style.top = `${modal.top}px`;\n this.modalContainer.style.left = `${modal.left}px`;\n this.modalContainer.style.zIndex = String(this.config.zIndex + 3);\n\n const arrowEl = document.createElement(\"div\");\n arrowEl.className = \"qaid-modal-arrow\";\n arrowEl.style.left = `${arrow.left}px`;\n\n const box = document.createElement(\"div\");\n box.className = \"qaid-modal-box\";\n box.innerHTML = this.getModalContent();\n\n this.modalContainer.appendChild(arrowEl);\n this.modalContainer.appendChild(box);\n this.applyVars(this.modalContainer);\n root.appendChild(this.modalContainer);\n\n this.setupModalInteractions();\n }\n\n private getModalContent(): string {\n const isUp = this.feedbackData.feedbackType === \"up\";\n const positiveIcon = this.config.positiveIcon || THUMBS_UP_ICON;\n const negativeIcon = this.config.negativeIcon || THUMBS_DOWN_ICON;\n const toggleClass = this.config.buttonClass\n ? `qaid-type-toggle qaid-type-toggle-custom ${this.config.buttonClass} ${isUp ? \"qaid-btn-up\" : \"qaid-btn-down\"}`\n : `qaid-type-toggle ${isUp ? \"qaid-type-up\" : \"qaid-type-down\"}`;\n const toggleLabel = isUp ? \"Feedback type: positive\" : \"Feedback type: negative\";\n return `\n <div class=\"qaid-modal-header\">\n <button type=\"button\" class=\"${toggleClass}\" title=\"Click to switch\" aria-pressed=\"${isUp}\" aria-label=\"${toggleLabel}\">\n ${isUp ? positiveIcon : negativeIcon}\n </button>\n <div class=\"qaid-modal-header-text\">\n <h3 class=\"qaid-modal-title\" id=\"qaid-modal-title-${this.uid}\">${this.config.text.modalTitle}</h3>\n <p class=\"qaid-modal-subtitle\" id=\"qaid-modal-subtitle-${this.uid}\">${this.config.text.modalSubtitle}</p>\n </div>\n </div>\n <textarea class=\"qaid-textarea\" aria-label=\"${this.config.text.modalSubtitle}\" placeholder=\"${this.config.text.placeholder}\"></textarea>\n <div class=\"qaid-btn-row\">\n <button type=\"button\" class=\"qaid-btn-submit\">${this.config.text.skipButton}</button>\n </div>\n `;\n }\n\n private setupModalInteractions(): void {\n // Dialog semantics + focus trap + background inert\n this.openDialogA11y(this.modalContainer!, {\n labelledbyId: `qaid-modal-title-${this.uid}`,\n describedbyId: `qaid-modal-subtitle-${this.uid}`,\n });\n\n const textarea =\n this.modalContainer!.querySelector<HTMLTextAreaElement>(\".qaid-textarea\");\n const submitBtn =\n this.modalContainer!.querySelector<HTMLButtonElement>(\".qaid-btn-submit\");\n if (textarea) {\n // Auto-focus\n setTimeout(() => textarea.focus(), 100);\n\n // Update button text based on content\n textarea.addEventListener(\"input\", () => {\n if (submitBtn) {\n submitBtn.textContent = textarea.value.trim() ? this.config.text.submitButton : this.config.text.skipButton;\n }\n });\n }\n\n if (submitBtn) {\n submitBtn.addEventListener(\"click\", () => {\n const message = textarea?.value.trim() || null;\n this.submitMessage(message);\n });\n }\n\n // Handle feedback type toggle\n const typeToggle = this.modalContainer!.querySelector<HTMLButtonElement>(\".qaid-type-toggle\");\n if (typeToggle) {\n typeToggle.addEventListener(\"click\", () => {\n const newType = this.feedbackData.feedbackType === \"up\" ? \"down\" : \"up\";\n this.feedbackData.feedbackType = newType;\n\n // Update UI - use different classes depending on custom buttonClass\n if (this.config.buttonClass) {\n typeToggle.classList.toggle(\"qaid-btn-up\", newType === \"up\");\n typeToggle.classList.toggle(\"qaid-btn-down\", newType === \"down\");\n } else {\n typeToggle.classList.toggle(\"qaid-type-up\", newType === \"up\");\n typeToggle.classList.toggle(\"qaid-type-down\", newType === \"down\");\n }\n const positiveIcon = this.config.positiveIcon || THUMBS_UP_ICON;\n const negativeIcon = this.config.negativeIcon || THUMBS_DOWN_ICON;\n typeToggle.innerHTML = newType === \"up\" ? positiveIcon : negativeIcon;\n\n // Update accessible state and announce the change\n const toggleLabel = newType === \"up\" ? \"Feedback type: positive\" : \"Feedback type: negative\";\n typeToggle.setAttribute(\"aria-pressed\", String(newType === \"up\"));\n typeToggle.setAttribute(\"aria-label\", toggleLabel);\n this.announceMsg(toggleLabel);\n\n // Update feedback on server\n if (this.feedbackId) {\n fetch(`${this.config.endpoint}/${this.feedbackId}`, {\n method: \"PATCH\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ feedbackType: newType }),\n }).catch((err) => console.error(\"Failed to update feedback type:\", err));\n }\n });\n }\n }\n\n private async submitMessage(message: string | null): Promise<void> {\n if (this.feedbackId) {\n try {\n await fetch(`${this.config.endpoint}/${this.feedbackId}`, {\n method: \"PATCH\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ message }),\n });\n } catch (error) {\n console.error(\"Failed to submit feedback message:\", error);\n }\n // Clear feedbackId so closeModal doesn't send another PATCH\n this.feedbackId = null;\n }\n\n this.closeModal();\n }\n\n private closeModal(): void {\n // If modal is open and we're closing without submitting, still finalize\n if (this.state === \"MODAL_OPEN\" && this.feedbackId) {\n fetch(`${this.config.endpoint}/${this.feedbackId}`, {\n method: \"PATCH\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ message: null }),\n }).catch((err) => console.error(\"Failed to finalize feedback:\", err));\n }\n\n // Release focus trap / inert and restore focus before removing the DOM\n this.closeDialogA11y();\n\n if (this.modalContainer) {\n this.modalContainer.remove();\n this.modalContainer = null;\n }\n if (this.backdrop) {\n this.backdrop.remove();\n this.backdrop = null;\n }\n\n document.removeEventListener(\"keydown\", this.boundKeyDown);\n\n this.resetFeedbackUi();\n }\n\n // ==================== Video Recording ====================\n\n private async startRecording(): Promise<void> {\n // Don't start if already recording or in targeting/modal flow\n if (this.isRecording || this.state !== \"IDLE\") return;\n\n try {\n // Start network capture\n this.networkCapture = captureNetworkErrors();\n\n // Create video recorder\n this.videoRecorder = createVideoRecorder({\n maxDuration: this.config.videoOptions.maxDuration,\n });\n\n this.videoRecorder.onTick((elapsed) => {\n this.updateRecordingTimer(elapsed);\n });\n\n // Handle unexpected stops (browser stop button, max duration)\n this.videoRecorder.onStop((blob) => {\n if (this.isRecording) {\n this.recordedBlob = blob;\n this.isRecording = false;\n this.announceMsg(\"Recording stopped\");\n this.removeRecordingIndicator();\n document.removeEventListener(\"keydown\", this.boundKeyDown);\n this.setButtonsDisabled(false);\n\n if (blob && blob.size > 0) {\n this.showRecordingPreview();\n } else {\n this.cleanupRecording();\n }\n }\n });\n\n await this.videoRecorder.start();\n this.isRecording = true;\n this.announceMsg(\"Recording started\");\n\n // Disable thumb buttons while recording\n this.setButtonsDisabled(true);\n\n // Show recording indicator\n this.showRecordingIndicator();\n\n // Listen for escape key\n document.addEventListener(\"keydown\", this.boundKeyDown);\n } catch (error) {\n // User denied screen share or error occurred\n this.cleanupRecording();\n }\n }\n\n private async stopRecording(): Promise<void> {\n try {\n this.recordedBlob = await this.videoRecorder!.stop();\n } catch {\n this.recordedBlob = null;\n }\n\n this.isRecording = false;\n this.announceMsg(\"Recording stopped\");\n this.removeRecordingIndicator();\n document.removeEventListener(\"keydown\", this.boundKeyDown);\n\n if (this.recordedBlob && this.recordedBlob.size > 0) {\n this.showRecordingPreview();\n } else {\n this.cleanupRecording();\n }\n }\n\n private showRecordingIndicator(): void {\n const root = this.ensureOverlayHost();\n\n this.recordingIndicator = document.createElement(\"div\");\n this.recordingIndicator.className = \"qaid-recording-indicator\";\n this.recordingIndicator.style.zIndex = String(this.config.zIndex + 100);\n\n const dot = document.createElement(\"div\");\n dot.className = \"qaid-recording-dot\";\n\n const timer = document.createElement(\"span\");\n timer.className = \"qaid-recording-time\";\n timer.textContent = this.formatTime(this.config.videoOptions.maxDuration);\n\n const stopBtn = document.createElement(\"button\");\n stopBtn.type = \"button\";\n stopBtn.className = \"qaid-recording-stop\";\n stopBtn.textContent = \"Stop\";\n stopBtn.addEventListener(\"click\", () => this.stopRecording());\n\n this.recordingIndicator.appendChild(dot);\n this.recordingIndicator.appendChild(timer);\n this.recordingIndicator.appendChild(stopBtn);\n\n this.applyVars(this.recordingIndicator);\n\n // Enable pointer events on overlay host for recording indicator\n if (this.overlayShadowHost) {\n this.overlayShadowHost.style.pointerEvents = \"auto\";\n }\n\n root.appendChild(this.recordingIndicator);\n }\n\n private updateRecordingTimer(elapsed: number): void {\n if (!this.recordingIndicator) return;\n const timer = this.recordingIndicator.querySelector<HTMLSpanElement>(\".qaid-recording-time\");\n if (timer) {\n const remaining = Math.max(0, this.config.videoOptions.maxDuration - elapsed);\n timer.textContent = this.formatTime(remaining);\n // Announce the final countdown so it is perceivable non-visually\n if (remaining > 0 && remaining <= 5) {\n this.announceMsg(`${remaining} second${remaining === 1 ? \"\" : \"s\"} remaining`);\n }\n }\n }\n\n private formatTime(seconds: number): string {\n const m = Math.floor(seconds / 60);\n const s = seconds % 60;\n return `${m}:${s.toString().padStart(2, \"0\")}`;\n }\n\n private removeRecordingIndicator(): void {\n if (this.recordingIndicator) {\n this.recordingIndicator.remove();\n this.recordingIndicator = null;\n }\n }\n\n private showRecordingPreview(): void {\n const root = this.ensureOverlayHost();\n\n const videoUrl = URL.createObjectURL(this.recordedBlob!);\n\n this.videoPreview = document.createElement(\"div\");\n this.videoPreview.className = \"qaid-video-preview\";\n this.videoPreview.style.zIndex = String(this.config.zIndex + 100);\n\n const box = document.createElement(\"div\");\n box.className = \"qaid-video-preview-box\";\n\n const title = document.createElement(\"h3\");\n title.textContent = \"Review your recording\";\n title.id = `qaid-video-title-${this.uid}`;\n\n const videoEl = document.createElement(\"video\");\n videoEl.src = videoUrl;\n videoEl.controls = true;\n videoEl.autoplay = true;\n videoEl.muted = true;\n\n const textarea = document.createElement(\"textarea\");\n textarea.placeholder = \"Optional: Describe the issue you recorded...\";\n textarea.setAttribute(\"aria-label\", \"Describe the issue you recorded\");\n\n const actions = document.createElement(\"div\");\n actions.className = \"qaid-video-preview-actions\";\n\n const cancelBtn = document.createElement(\"button\");\n cancelBtn.type = \"button\";\n cancelBtn.className = \"qaid-video-btn qaid-video-btn-cancel\";\n cancelBtn.textContent = \"Cancel\";\n cancelBtn.addEventListener(\"click\", () => this.cancelRecordingPreview());\n\n const rerecordBtn = document.createElement(\"button\");\n rerecordBtn.type = \"button\";\n rerecordBtn.className = \"qaid-video-btn qaid-video-btn-rerecord\";\n rerecordBtn.textContent = \"Re-record\";\n rerecordBtn.addEventListener(\"click\", () => {\n this.cancelRecordingPreview();\n this.startRecording();\n });\n\n const sendBtn = document.createElement(\"button\");\n sendBtn.type = \"button\";\n sendBtn.className = \"qaid-video-btn qaid-video-btn-send\";\n sendBtn.textContent = \"Send\";\n sendBtn.addEventListener(\"click\", () => {\n const message = textarea.value.trim() || null;\n this.submitVideoFeedback(message, sendBtn);\n });\n\n actions.appendChild(cancelBtn);\n actions.appendChild(rerecordBtn);\n actions.appendChild(sendBtn);\n\n box.appendChild(title);\n box.appendChild(videoEl);\n box.appendChild(textarea);\n box.appendChild(actions);\n\n this.videoPreview.appendChild(box);\n this.applyVars(this.videoPreview);\n\n // Enable pointer events on overlay host for video preview\n if (this.overlayShadowHost) {\n this.overlayShadowHost.style.pointerEvents = \"auto\";\n }\n\n root.appendChild(this.videoPreview);\n\n // Dialog semantics + focus trap + background inert\n this.openDialogA11y(box, { labelledbyId: title.id });\n\n // Listen for escape key\n document.addEventListener(\"keydown\", this.boundKeyDown);\n }\n\n private cancelRecordingPreview(): void {\n this.removeVideoPreview();\n this.cleanupRecording();\n }\n\n private removeVideoPreview(): void {\n // Release focus trap / inert and restore focus before removing the DOM\n this.closeDialogA11y();\n if (this.videoPreview) {\n // Revoke object URLs\n const videoEl = this.videoPreview.querySelector<HTMLVideoElement>(\"video\");\n if (videoEl?.src) {\n URL.revokeObjectURL(videoEl.src);\n }\n this.videoPreview.remove();\n this.videoPreview = null;\n }\n document.removeEventListener(\"keydown\", this.boundKeyDown);\n }\n\n private async submitVideoFeedback(message: string | null, sendBtn: HTMLButtonElement): Promise<void> {\n if (!this.recordedBlob || this.isSendingVideo) return;\n\n this.isSendingVideo = true;\n sendBtn.disabled = true;\n sendBtn.textContent = \"Sending...\";\n\n const formData = new FormData();\n formData.append(\"video\", this.recordedBlob, `recording.${this.recordedBlob.type.includes(\"mp4\") ? \"mp4\" : \"webm\"}`);\n formData.append(\"pageUrl\", window.location.href);\n formData.append(\"visitorId\", this.visitorId);\n\n if (this.config.apiKey) {\n formData.append(\"apiKey\", this.config.apiKey);\n }\n if (message) {\n formData.append(\"message\", message);\n }\n if (this.consoleCapture) {\n formData.append(\"consoleErrors\", JSON.stringify(this.consoleCapture.errors));\n }\n if (this.networkCapture) {\n formData.append(\"networkErrors\", JSON.stringify(this.networkCapture.errors));\n }\n\n let videoFeedbackId: string | number | null = null;\n try {\n const response = await fetch(`${this.config.endpoint}/video`, {\n method: \"POST\",\n body: formData,\n });\n\n if (response.ok) {\n this.announceMsg(\"Recording sent\");\n try {\n const data = (await response.json()) as { id?: string | number };\n videoFeedbackId = data?.id ?? null;\n } catch {\n // Non-JSON / no id — the quest can still launch, just unlinked.\n }\n } else {\n console.error(\"Failed to submit video feedback:\", await response.text());\n this.announceMsg(\"Failed to send recording\", true);\n }\n } catch (error) {\n console.error(\"Failed to submit video feedback:\", error);\n this.announceMsg(\"Failed to send recording\", true);\n }\n\n this.isSendingVideo = false;\n this.removeVideoPreview();\n this.cleanupRecording();\n\n // Once the recording is safely sent, launch the linked quest (if any),\n // passing the new feedback record id so its response is joinable.\n // tryLaunchQuest is a no-op when no video quest is configured.\n await this.tryLaunchQuest(\"video\", videoFeedbackId);\n }\n\n private cleanupRecording(): void {\n this.isRecording = false;\n this.removeRecordingIndicator();\n\n if (this.videoRecorder) {\n this.videoRecorder.destroy();\n this.videoRecorder = null;\n }\n if (this.networkCapture) {\n this.networkCapture.restore();\n this.networkCapture = null;\n }\n if (this.recordedBlob) {\n this.recordedBlob = null;\n }\n\n // Re-enable buttons\n this.setButtonsDisabled(false);\n\n // Reset overlay host pointer events if nothing else needs them\n if (this.overlayShadowHost && this.state === \"IDLE\") {\n this.overlayShadowHost.style.pointerEvents = \"none\";\n }\n }\n\n private setButtonsDisabled(disabled: boolean): void {\n if (!this.buttonsContainer) return;\n const buttons = this.buttonsContainer.querySelectorAll<HTMLButtonElement>(\"button.qaid-btn, button.qaid-btn-structural\");\n buttons.forEach((btn) => {\n if (disabled) {\n // Don't disable the record button itself (it has its own state)\n if (!btn.classList.contains(\"qaid-btn-record\")) {\n btn.disabled = true;\n btn.style.opacity = \"0.5\";\n }\n } else {\n btn.disabled = false;\n btn.style.opacity = \"\";\n }\n });\n }\n\n /**\n * Destroy the embed and clean up all resources\n */\n public destroy(): void {\n // Flag as destroyed so the DOM observer doesn't re-attach hosts\n this.destroyed = true;\n\n // Disconnect DOM persistence observers\n if (this.domObserver) {\n this.domObserver.disconnect();\n this.domObserver = null;\n }\n if (this.boundBeforeSwap) {\n document.removeEventListener(\"astro:before-swap\", this.boundBeforeSwap);\n this.boundBeforeSwap = null;\n }\n\n // Stop keyboard targeting and release any open dialog focus state\n this.keyboardController?.stop();\n this.keyboardController = null;\n this.clearActiveThumb();\n this.closeDialogA11y();\n\n // Clean up video recording\n this.cleanupRecording();\n this.removeVideoPreview();\n\n // Tear down any quest launched from a button\n this.activeQuest?.destroy();\n this.activeQuest = null;\n\n // Restore console.error\n if (this.consoleCapture) {\n this.consoleCapture.restore();\n this.consoleCapture = null;\n }\n\n // Remove event listeners\n window.removeEventListener(\"resize\", this.boundResize);\n document.removeEventListener(\"keydown\", this.boundKeyDown);\n document.removeEventListener(\"mousemove\", this.boundMouseMove);\n document.removeEventListener(\"click\", this.boundClick, true);\n document.removeEventListener(\"touchstart\", this.boundTouchStart);\n document.removeEventListener(\"touchend\", this.boundTouchEnd);\n\n document.body.classList.remove(\"qaid-targeting\", \"qaid-type-up\");\n document.body.style.removeProperty(\"--qaid-positive\");\n document.body.style.removeProperty(\"--qaid-negative\");\n\n // Remove shadow hosts from DOM (this removes shadow roots and all their contents)\n if (this.shadowHost) {\n this.shadowHost.remove();\n this.shadowHost = null;\n this.shadowRoot = null;\n }\n if (this.overlayShadowHost) {\n this.overlayShadowHost.remove();\n this.overlayShadowHost = null;\n this.overlayShadowRoot = null;\n }\n this.buttonsContainer = null;\n this.overlayContainer = null;\n this.captureLayer = null;\n this.crosshairH = null;\n this.crosshairV = null;\n this.scope = null;\n this.marker = null;\n this.modalContainer = null;\n this.backdrop = null;\n this.dismissBtn = null;\n this.tooltipElement = null;\n\n // Remove light DOM styles (reference counted)\n removeStyles();\n }\n}\n","/**\n * @qaiddev/thumbs-embed - Standalone Feedback Embed\n *\n * A zero-dependency feedback embed with element targeting.\n *\n * Usage via ES module:\n * ```typescript\n * import { QaidFeedback } from '@qaiddev/thumbs-embed';\n *\n * const embed = new QaidFeedback({\n * endpoint: '/api/feedback'\n * });\n * ```\n *\n * Usage via script tag:\n * ```html\n * <script src=\"feedback.umd.cjs\" data-endpoint=\"/api/feedback\"></script>\n * ```\n *\n * Or manually initialize:\n * ```html\n * <script src=\"feedback.umd.cjs\"></script>\n * <script>\n * const embed = new QaidFeedback.QaidFeedback({\n * endpoint: '/api/feedback'\n * });\n * </script>\n * ```\n */\n\nimport { QaidFeedback } from \"./embed\";\n\nexport { QaidFeedback };\nexport type {\n FeedbackConfig,\n QuestsLaunchConfig,\n ResolvedFeedbackConfig,\n ConsoleError,\n NetworkError,\n FeedbackData,\n SelectedBounds,\n FeedbackPayload,\n FeedbackResponse,\n FeedbackMessagePayload,\n} from \"./types\";\nexport { captureNetworkErrors } from \"./network-capture\";\nexport type { NetworkCapture } from \"./network-capture\";\nexport { createVideoRecorder, isVideoRecordingSupported, getSupportedMimeType } from \"./video-capture\";\nexport type { VideoRecorder, VideoRecorderOptions } from \"./video-capture\";\nexport { captureDomScreenshot, isDomScreenshotSupported } from \"./screenshot-dom\";\nexport type { DomScreenshotOptions } from \"./screenshot-dom\";\nexport {\n openAnnotationEditor,\n compositeAnnotations,\n drawShape,\n rectFromPoints,\n AnnotationEditor,\n} from \"./annotate\";\nexport type {\n Shape,\n ShapeType,\n Point,\n AnnotationLabels,\n AnnotationEditorOptions,\n} from \"./annotate\";\n\nimport type { FeedbackConfig } from \"./types\";\n\n/**\n * Find theme CSS from an element matched by a CSS selector.\n * Used by data-css-selector attribute and JSON cssSelector property.\n */\nfunction findCssFromSelector(selector: string): string {\n const el = document.querySelector(selector);\n return el?.textContent?.trim() ?? \"\";\n}\n\n/**\n * Parse JSON config from a separate script tag with type=\"application/json\"\n * Looks for: <script type=\"application/json\" data-feedback-config>{ ... }</script>\n */\nfunction parseJsonConfig(): Partial<FeedbackConfig> | null {\n const configScript = document.querySelector(\n 'script[type=\"application/json\"][data-feedback-config]'\n );\n if (!configScript) return null;\n\n const textContent = configScript.textContent?.trim();\n if (!textContent) return null;\n\n try {\n const parsed = JSON.parse(textContent);\n // Resolve cssSelector → css\n if (parsed.cssSelector && !parsed.css) {\n parsed.css = findCssFromSelector(parsed.cssSelector);\n delete parsed.cssSelector;\n }\n return parsed;\n } catch {\n return null;\n }\n}\n\n/**\n * Parse config from data-* attributes (backward compatibility)\n */\nfunction parseDataAttributes(script: HTMLScriptElement): Partial<FeedbackConfig> | null {\n const endpoint = script.getAttribute(\"data-endpoint\");\n if (!endpoint) return null;\n\n const position = script.getAttribute(\"data-position\") as\n | \"bottom-right\"\n | \"bottom-left\"\n | \"top-right\"\n | \"top-left\"\n | null;\n const zIndex = script.getAttribute(\"data-zindex\");\n const positiveColor = script.getAttribute(\"data-positive-color\");\n const negativeColor = script.getAttribute(\"data-negative-color\");\n const markerColor = script.getAttribute(\"data-marker-color\");\n const container = script.getAttribute(\"data-container\");\n const buttonClass = script.getAttribute(\"data-button-class\");\n const skipTargeting = script.getAttribute(\"data-skip-targeting\");\n const incognito = script.getAttribute(\"data-incognito\");\n const buttonSize = script.getAttribute(\"data-button-size\") as\n | \"small\"\n | \"medium\"\n | \"large\"\n | null;\n const offsetX = script.getAttribute(\"data-offset-x\");\n const offsetY = script.getAttribute(\"data-offset-y\");\n const modalWidth = script.getAttribute(\"data-modal-width\");\n const backdropOpacity = script.getAttribute(\"data-backdrop-opacity\");\n const fontFamily = script.getAttribute(\"data-font-family\");\n const fontSize = script.getAttribute(\"data-font-size\");\n const tooltip = script.getAttribute(\"data-tooltip\");\n const modalTitle = script.getAttribute(\"data-modal-title\");\n const modalSubtitle = script.getAttribute(\"data-modal-subtitle\");\n const placeholder = script.getAttribute(\"data-placeholder\");\n const submitButton = script.getAttribute(\"data-submit-button\");\n const skipButton = script.getAttribute(\"data-skip-button\");\n const positiveIcon = script.getAttribute(\"data-positive-icon\");\n const negativeIcon = script.getAttribute(\"data-negative-icon\");\n const apiKey = script.getAttribute(\"data-api-key\");\n const captureScreenshot = script.getAttribute(\"data-capture-screenshot\");\n const annotate = script.getAttribute(\"data-annotate\");\n const screenshotQuality = script.getAttribute(\"data-screenshot-quality\");\n const screenshotMaxWidth = script.getAttribute(\"data-screenshot-max-width\");\n const screenshotMaxHeight = script.getAttribute(\"data-screenshot-max-height\");\n const captureVideo = script.getAttribute(\"data-capture-video\");\n const hideThumbs = script.getAttribute(\"data-hide-thumbs\");\n const hideDismiss = script.getAttribute(\"data-hide-dismiss\");\n const videoMaxDuration = script.getAttribute(\"data-video-max-duration\");\n const screenshotMethod = script.getAttribute(\"data-screenshot-method\") as \"dom\" | \"permission\" | null;\n const direction = script.getAttribute(\"data-direction\") as \"horizontal\" | \"vertical\" | null;\n const cssSelector = script.getAttribute(\"data-css-selector\");\n const questBase = script.getAttribute(\"data-quest-base\");\n const questUp = script.getAttribute(\"data-quest-up\");\n const questDown = script.getAttribute(\"data-quest-down\");\n const questVideo = script.getAttribute(\"data-quest-video\");\n const questApiKey = script.getAttribute(\"data-quest-api-key\");\n const questModuleUrl = script.getAttribute(\"data-quest-module-url\");\n\n return {\n endpoint,\n css: cssSelector ? findCssFromSelector(cssSelector) : undefined,\n apiKey: apiKey ?? undefined,\n captureScreenshot: captureScreenshot === \"true\" ? true : undefined,\n // Annotation is on by default; only an explicit \"false\" disables it.\n annotate: annotate === \"false\" ? false : undefined,\n screenshotOptions: (screenshotQuality || screenshotMaxWidth || screenshotMaxHeight) ? {\n quality: screenshotQuality ? parseFloat(screenshotQuality) : undefined,\n maxWidth: screenshotMaxWidth ? parseInt(screenshotMaxWidth, 10) : undefined,\n maxHeight: screenshotMaxHeight ? parseInt(screenshotMaxHeight, 10) : undefined,\n } : undefined,\n container: container ?? undefined,\n buttonClass: buttonClass ?? undefined,\n direction: direction ?? undefined,\n position: position ?? undefined,\n zIndex: zIndex ? parseInt(zIndex, 10) : undefined,\n skipTargeting: skipTargeting === \"true\" ? true : undefined,\n incognito: incognito === \"true\" ? true : undefined,\n buttonSize: buttonSize ?? undefined,\n offset: (offsetX || offsetY) ? {\n x: offsetX ? parseInt(offsetX, 10) : undefined,\n y: offsetY ? parseInt(offsetY, 10) : undefined,\n } : undefined,\n modalWidth: modalWidth ? parseInt(modalWidth, 10) : undefined,\n backdropOpacity: backdropOpacity ? parseFloat(backdropOpacity) : undefined,\n fontFamily: fontFamily ?? undefined,\n fontSize: fontSize ? parseInt(fontSize, 10) : undefined,\n colors: {\n positive: positiveColor ?? undefined,\n negative: negativeColor ?? undefined,\n marker: markerColor ?? undefined,\n },\n text: (tooltip || modalTitle || modalSubtitle || placeholder || submitButton || skipButton) ? {\n tooltip: tooltip ?? undefined,\n modalTitle: modalTitle ?? undefined,\n modalSubtitle: modalSubtitle ?? undefined,\n placeholder: placeholder ?? undefined,\n submitButton: submitButton ?? undefined,\n skipButton: skipButton ?? undefined,\n } : undefined,\n positiveIcon: positiveIcon ?? undefined,\n negativeIcon: negativeIcon ?? undefined,\n screenshotMethod: screenshotMethod ?? undefined,\n captureVideo: captureVideo === \"true\" ? true : undefined,\n hideThumbs: hideThumbs === \"true\" ? true : undefined,\n hideDismiss: hideDismiss === \"true\" ? true : undefined,\n videoOptions: videoMaxDuration ? {\n maxDuration: parseInt(videoMaxDuration, 10),\n } : undefined,\n quests: questBase ? {\n base: questBase,\n up: questUp ?? undefined,\n down: questDown ?? undefined,\n video: questVideo ?? undefined,\n apiKey: questApiKey ?? undefined,\n moduleUrl: questModuleUrl ?? undefined,\n } : undefined,\n };\n}\n\n// Auto-initialize from script tag\nif (typeof document !== \"undefined\") {\n const initFromScript = (): void => {\n const script = document.currentScript as HTMLScriptElement | null;\n\n // Try JSON config from separate script tag first, fall back to data-* attributes\n const jsonConfig = parseJsonConfig();\n const dataConfig = script ? parseDataAttributes(script) : null;\n const config = jsonConfig ?? dataConfig;\n\n if (config?.endpoint) {\n new QaidFeedback(config as FeedbackConfig);\n }\n };\n\n // Run immediately if DOM is ready, otherwise wait\n if (document.readyState === \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", initFromScript);\n } else {\n initFromScript();\n }\n}\n"],"names":["THUMBS_UP_ICON","THUMBS_DOWN_ICON","RECORD_ICON","RECTANGLE_ICON","ARROW_ICON","PENCIL_ICON","BLUR_ICON","UNDO_ICON","DONE_ICON","SKIP_ICON","instanceCount","DEFAULT_BUTTON_STYLES","BUTTON_SIZES","ICON_SIZES","getLuminance","r","g","b","rs","gs","bs","c","parseColor","color","hex","fullHex","num","match","getContrastTextColor","bgColor","rgb","buildCssVars","options","positiveColor","negativeColor","markerColor","buttonSize","modalWidth","backdropOpacity","fontFamily","fontSize","btnSize","iconSize","markerTextColor","applyCssVars","el","vars","name","value","getEmbedStyles","shadowStyles","injectStyles","style","lightStyles","removeStyles","DATA_ATTRS","findDataAttribute","element","stopAt","current","attr","getTruncatedText","maxLength","textContent","getNthChildIndex","index","sibling","generateNthChildPath","path","tag","escapeCSSIdentifier","str","generateSelector","dataAttr","generateElementInfo","text","TARGETABLE_SELECTOR","NATIVELY_FOCUSABLE","isElementVisible","view","collectTargetableElements","root","selector","isExcluded","isVisible","startKeyboardTargeting","candidates","moveFocus","target","addedTabindex","stopped","seed","seedIndex","focusCurrent","focusable","emitHighlight","moveTo","nextIndex","len","next","prev","getCurrent","stop","handleKey","select","cancel","event","POLITE_ATTR","VISUALLY_HIDDEN_CSS","FOCUSABLE_SELECTOR","ownerDoc","getLiveRegion","assertive","kind","existing","region","announce","message","opts","isDisabled","isHidden","node","getFocusable","container","getDeepActiveElement","doc","active","createFocusTrap","onKeydown","first","last","withinTrap","initial","saveFocus","restoreFocus","applyDialog","topLevelAncestor","body","parent","setBackgroundInert","except","keep","changed","child","prevInert","prevAriaHidden","entry","DEFAULT_DIMENSIONS","calculateVerticalPosition","bounds","viewportHeight","totalHeight","gap","viewportPadding","spaceAbove","spaceBelow","position","top","calculateHorizontalPosition","viewportWidth","left","calculateArrowPosition","modalLeft","minOffset","arrowWidth","arrowLeft","calculateModalPosition","dimensions","vertical","calculateTooltipPosition","anchor","tooltip","viewport","calculateModalAndArrowPosition","modal","MAX_MESSAGES","captureConsoleErrors","onError","errors","originalError","originalWarn","originalLog","capture","level","args","error","arg","MAX_ENTRIES","MAX_BODY_SIZE","truncateBody","addEntry","safeReadBody","response","captureNetworkErrors","originalFetch","input","init","url","method","requestBody","responseBody","originalXHROpen","originalXHRSend","rest","xhr","isIOSDevice","ua","computeOrientationTransform","frameW","frameH","viewportW","viewportH","screenAngle","frameLandscape","viewportLandscape","drawRotatedFrame","ctx","source","t","getScreenAngle","orientation","waitForVideoDimensions","video","resolve","playSilently","buildOrientationCorrectedStream","displayStream","frameRate","canvas","transform","rafId","draw","stream","isVideoRecordingSupported","getSupportedMimeType","type","createVideoRecorder","maxDuration","videoBitsPerSecond","orientationCorrection","recorder","chunks","tickCallback","stopCallback","tickInterval","startTime","resolveStop","rejectStop","autoStopTimeout","cleanup","finishRecording","mimeType","videoTrack","recordStream","corrected","e","blob","elapsed","reject","callback","createElement","attrs","children","key","isMobileViewport","breakpoint","getElementAtPointUnderOverlay","x","y","hosts","saved","h","i","isEmbedElement","getElementBounds","padding","rect","captureScreenshot","quality","maxWidth","maxHeight","track","settings","checkFrame","srcWidth","srcHeight","scale","width","height","SCRIPT_URL","LOAD_TIMEOUT","POLL_INTERVAL","loadPromise","isDomScreenshotSupported","loadHtml2Canvas","script","start","poll","captureDomScreenshot","scaledWidth","scaledHeight","scaledCanvas","BLUR_TILE","DEFAULT_STROKE","DEFAULT_STROKE_WIDTH","DEFAULT_QUALITY","DEFAULT_LABELS","rectFromPoints","a","isDegenerate","shape","drawArrow","from","to","angle","head","drawPen","points","drawBlur","w","ty","tx","drawShape","loadImage","src","img","compositeAnnotations","dataUrl","shapes","editorSeq","AnnotationEditor","promise","tool","icon","label","btn","action","extraClass","titleId","descId","title","desc","stage","tools","skipBtn","doneBtn","actions","scaleX","scaleY","LABEL_KEY","p","out","openAnnotationEditor","DEFAULT_QUESTS_MODULE_URL","defaultImporter","importer","modulePromise","cachedUrl","loadQuestsModule","moduleUrl","mod","m","err","launchQuest","base","metadata","VISITOR_ID_KEY","HIDE_FEEDBACK_KEY","TOUCH_TAP_SLOP","isTouchPrimaryDevice","getHideKey","apiKey","isHiddenByUser","setHiddenByUser","hidden","getOrCreateVisitorId","visitorId","QaidFeedback","config","_error","newDoc","userContainer","baseStyle","themeStyle","dirClass","offsetX","offsetY","ev","useCustomClass","btnBaseClass","tooltipText","upWrapper","upBtn","downWrapper","downBtn","recordWrapper","recordBtn","anchorRect","tooltipRect","buttonEl","keyboard","vignette","elementUnder","screenshot","host","prevPointerEvents","msg","elementBounds","payload","data","q","feedbackId","questId","sheet","arrow","arrowEl","box","isUp","positiveIcon","negativeIcon","textarea","submitBtn","typeToggle","newType","toggleLabel","dot","timer","stopBtn","remaining","seconds","s","videoUrl","videoEl","cancelBtn","rerecordBtn","sendBtn","formData","videoFeedbackId","disabled","findCssFromSelector","parseJsonConfig","configScript","parsed","parseDataAttributes","endpoint","zIndex","buttonClass","skipTargeting","incognito","modalTitle","modalSubtitle","placeholder","submitButton","skipButton","annotate","screenshotQuality","screenshotMaxWidth","screenshotMaxHeight","captureVideo","hideThumbs","hideDismiss","videoMaxDuration","screenshotMethod","direction","cssSelector","questBase","questUp","questDown","questVideo","questApiKey","questModuleUrl","initFromScript","jsonConfig","dataConfig"],"mappings":"AAIO,MAAMA,IAAiB;AAAA;AAAA,SAIjBC,IAAmB;AAAA;AAAA,SAInBC,KAAc;AAAA;AAAA,SASdC,KAAiB;AAAA;AAAA,SAIjBC,KAAa;AAAA;AAAA,SAIbC,KAAc;AAAA;AAAA,SAIdC,KAAY;AAAA;AAAA,SAIZC,KAAY;AAAA;AAAA,SAIZC,KAAY;AAAA;AAAA,SAIZC,KAAY;AAAA;AAAA;ACpCzB,IAAIC,IAAgB;AAGpB,MAAMC,KAAwB,2zBAmBxBC,KAAe;AAAA,EACnB,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,OAAO;AACT,GAEMC,KAAa;AAAA,EACjB,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,OAAO;AACT;AAMA,SAASC,GAAaC,GAAWC,GAAWC,GAAmB;AAC7D,QAAM,CAACC,GAAIC,GAAIC,CAAE,IAAI,CAACL,GAAGC,GAAGC,CAAC,EAAE,IAAI,CAACI,OAClCA,IAAIA,IAAI,KACDA,KAAK,UAAUA,IAAI,QAAQ,KAAK,KAAKA,IAAI,SAAS,OAAO,GAAG,EACpE;AACD,SAAO,SAASH,IAAK,SAASC,IAAK,SAASC;AAC9C;AAKA,SAASE,GAAWC,GAA2D;AAE7E,MAAIA,EAAM,WAAW,GAAG,GAAG;AACzB,UAAMC,IAAMD,EAAM,MAAM,CAAC,GACnBE,IAAUD,EAAI,WAAW,IAC3BA,EAAI,MAAM,EAAE,EAAE,IAAI,CAACH,MAAMA,IAAIA,CAAC,EAAE,KAAK,EAAE,IACvCG,GACEE,IAAM,SAASD,GAAS,EAAE;AAChC,WAAO;AAAA,MACL,GAAIC,KAAO,KAAM;AAAA,MACjB,GAAIA,KAAO,IAAK;AAAA,MAChB,GAAGA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