@qaiddev/thumbs-embed 1.10.1 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/a11y-dialog.d.ts +77 -0
  2. package/dist/a11y.d.ts +6 -65
  3. package/dist/annotate.d.ts +2 -0
  4. package/dist/chunks/annotate-DGyRcgPt.js +2 -0
  5. package/dist/chunks/annotate-DGyRcgPt.js.map +1 -0
  6. package/dist/chunks/core-BsR7oV99.js +26 -0
  7. package/dist/chunks/core-BsR7oV99.js.map +1 -0
  8. package/dist/chunks/dom-scpOS8nl.js +2 -0
  9. package/dist/chunks/{dom-DvdtcUS8.js.map → dom-scpOS8nl.js.map} +1 -1
  10. package/dist/chunks/modal-DYxcs1Gm.js +2 -0
  11. package/dist/chunks/modal-DYxcs1Gm.js.map +1 -0
  12. package/dist/chunks/recording-BUw5-5Rf.js +2 -0
  13. package/dist/chunks/recording-BUw5-5Rf.js.map +1 -0
  14. package/dist/chunks/screenshot-CNe1irEz.js +2 -0
  15. package/dist/chunks/{screenshot-DYOKg2bS.js.map → screenshot-CNe1irEz.js.map} +1 -1
  16. package/dist/chunks/screenshot-dom-ZYP2w2h0.js +2 -0
  17. package/dist/chunks/{screenshot-dom-CME7tYRE.js.map → screenshot-dom-ZYP2w2h0.js.map} +1 -1
  18. package/dist/chunks/send-C26DRoYc.js +2 -0
  19. package/dist/chunks/send-C26DRoYc.js.map +1 -0
  20. package/dist/chunks/targeting-CMUEe-7C.js +6 -0
  21. package/dist/chunks/targeting-CMUEe-7C.js.map +1 -0
  22. package/dist/chunks/video-BSP4s2te.js +2 -0
  23. package/dist/chunks/{video-Bd_29-rK.js.map → video-BSP4s2te.js.map} +1 -1
  24. package/dist/embed.d.ts +35 -34
  25. package/dist/index.js +1515 -1382
  26. package/dist/index.js.map +1 -1
  27. package/dist/loader.d.ts +6 -4
  28. package/dist/loader.js +1 -6
  29. package/dist/loader.js.map +1 -1
  30. package/dist/modal-positioning.d.ts +0 -27
  31. package/dist/modal.d.ts +2 -0
  32. package/dist/qaid.umd.cjs +14 -14
  33. package/dist/qaid.umd.cjs.map +1 -1
  34. package/dist/quest-config.d.ts +2 -0
  35. package/dist/quest-launcher.d.ts +1 -3
  36. package/dist/recording.d.ts +2 -0
  37. package/dist/send.d.ts +60 -0
  38. package/dist/targeting.d.ts +2 -0
  39. package/dist/tooltip-positioning.d.ts +31 -0
  40. package/package.json +1 -1
  41. package/dist/chunks/annotate-BTLeFQa0.js +0 -355
  42. package/dist/chunks/annotate-BTLeFQa0.js.map +0 -1
  43. package/dist/chunks/core-2nGsCcZq.js +0 -1319
  44. package/dist/chunks/core-2nGsCcZq.js.map +0 -1
  45. package/dist/chunks/dom-DvdtcUS8.js +0 -17
  46. package/dist/chunks/modal-zwBhxWO0.js +0 -219
  47. package/dist/chunks/modal-zwBhxWO0.js.map +0 -1
  48. package/dist/chunks/recording-DNngIGr2.js +0 -321
  49. package/dist/chunks/recording-DNngIGr2.js.map +0 -1
  50. package/dist/chunks/screenshot-DYOKg2bS.js +0 -33
  51. package/dist/chunks/screenshot-dom-CME7tYRE.js +0 -63
  52. package/dist/chunks/targeting-DaBmGVk5.js +0 -296
  53. package/dist/chunks/targeting-DaBmGVk5.js.map +0 -1
  54. package/dist/chunks/video-Bd_29-rK.js +0 -214
@@ -1 +1 @@
1
- {"version":3,"file":"screenshot-DYOKg2bS.js","sources":["../../src/screenshot.ts"],"sourcesContent":["/**\n * Screenshot capture utility using native Screen Capture API\n */\n\nexport interface ScreenshotOptions {\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\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 = 0.8, 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"],"names":["captureScreenshot","options","quality","maxWidth","maxHeight","stream","track","settings","video","resolve","checkFrame","srcWidth","srcHeight","scale","width","height","canvas","ctx","error"],"mappings":"AAkBA,eAAsBA,EACpBC,IAA6B,IACL;AACxB,QAAM,EAAE,SAAAC,IAAU,KAAK,UAAAC,IAAW,MAAM,WAAAC,IAAY,QAAQH;AAE5D,MAAI;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Q,KAAK,8BAA8BA,CAAK,GACzC;AAAA,EACT;AACF;"}
1
+ {"version":3,"file":"screenshot-CNe1irEz.js","sources":["../../src/screenshot.ts"],"sourcesContent":["/**\n * Screenshot capture utility using native Screen Capture API\n */\n\nexport interface ScreenshotOptions {\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\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 = 0.8, 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"],"names":["captureScreenshot","options","quality","maxWidth","maxHeight","stream","track","settings","video","resolve","checkFrame","srcWidth","srcHeight","scale","width","height","canvas","ctx","error"],"mappings":"AAkBA,eAAsBA,EACpBC,EAA6B,GACL,CACxB,KAAM,CAAE,QAAAC,EAAU,GAAK,SAAAC,EAAW,KAAM,UAAAC,EAAY,KAAQH,EAE5D,GAAI,CAEF,GAAI,CAAC,UAAU,cAAc,gBAC3B,eAAQ,KAAK,kCAAkC,EACxC,KAIT,MAAMI,EAAS,MAAM,UAAU,aAAa,gBAAgB,CAC1D,iBAAkB,GAClB,MAAO,CACL,eAAgB,SAAA,CAClB,CAC4B,EAGxBC,EAAQD,EAAO,eAAA,EAAiB,CAAC,EACjCE,EAAWD,EAAM,YAAA,EAGjBE,EAAQ,SAAS,cAAc,OAAO,EAC5CA,EAAM,UAAYH,EAClBG,EAAM,MAAQ,GAEd,MAAM,IAAI,QAAeC,GAAY,CACnCD,EAAM,iBAAmB,IAAM,CAC7BA,EAAM,KAAA,EACNC,EAAA,CACF,CACF,CAAC,EAGD,MAAM,IAAI,QAAeA,GAAY,CACnC,MAAMC,EAAa,IAAM,CACnBF,EAAM,YAAc,EACtBC,EAAA,EAEA,sBAAsBC,CAAU,CAEpC,EACAA,EAAA,CACF,CAAC,EAGD,MAAM,IAAI,QAASD,GAAY,WAAWA,EAAS,GAAG,CAAC,EAGvD,MAAME,EAAWJ,EAAS,OAASC,EAAM,WACnCI,EAAYL,EAAS,QAAUC,EAAM,YACrCK,EAAQ,KAAK,IAAIV,EAAWQ,EAAUP,EAAYQ,EAAW,CAAC,EAC9DE,EAAQ,KAAK,MAAMH,EAAWE,CAAK,EACnCE,EAAS,KAAK,MAAMH,EAAYC,CAAK,EAGrCG,EAAS,SAAS,cAAc,QAAQ,EAC9CA,EAAO,MAAQF,EACfE,EAAO,OAASD,EAEhB,MAAME,EAAMD,EAAO,WAAW,IAAI,EAClC,OAAKC,GAKLA,EAAI,UAAUT,EAAO,EAAG,EAAGM,EAAOC,CAAM,EAGxCT,EAAM,KAAA,EAECU,EAAO,UAAU,aAAcd,CAAO,IAT3CI,EAAM,KAAA,EACC,KASX,OAASY,EAAO,CACd,eAAQ,KAAK,6BAA8BA,CAAK,EACzC,IACT,CACF"}
@@ -0,0 +1,2 @@
1
+ const w="https://qaid.dev/lib/html2canvas.min.js",p=1e4,v=50;let a=null;function f(){if(typeof document>"u"||typeof window>"u")return!1;const n=document.createElement("canvas");return typeof n.getContext=="function"&&!!n.getContext("2d")}function g(){return window.html2canvas?Promise.resolve(!0):a||(a=new Promise(n=>{if(!document.querySelector(`script[src="${w}"]`)){const e=document.createElement("script");e.src=w,e.async=!0,document.head.appendChild(e)}const r=Date.now(),i=()=>{if(window.html2canvas){n(!0);return}if(Date.now()-r>1e4){a=null,n(!1);return}setTimeout(i,50)};i()}),a)}async function L(n={}){const{quality:c=.8,maxWidth:r=1280,maxHeight:i=800}=n;try{if(!await g()||!window.html2canvas)return console.warn("html2canvas failed to load"),null;const s=await window.html2canvas(document.body,{useCORS:!0,allowTaint:!1,logging:!1,windowWidth:document.documentElement.clientWidth,windowHeight:document.documentElement.clientHeight,width:document.documentElement.clientWidth,height:document.documentElement.clientHeight,x:window.scrollX,y:window.scrollY,ignoreElements:t=>t instanceof HTMLElement?t.classList.contains("qaid-buttons")||t.classList.contains("qaid-targeting-overlay")||t.classList.contains("qaid-modal-container")||t.classList.contains("qaid-bottom-sheet")||t.classList.contains("qaid-backdrop")||t.classList.contains("qaid-selected-marker")||t.classList.contains("qaid-tooltip-text")||t.classList.contains("qaid-recording-indicator")||t.classList.contains("qaid-video-preview")||t.className?.toString().startsWith?.("qaid-"):!1}),l=s.width,u=s.height,d=Math.min(r/l,i/u,1);if(d<1){const t=Math.round(l*d),m=Math.round(u*d),o=document.createElement("canvas");o.width=t,o.height=m;const h=o.getContext("2d");return h?(h.drawImage(s,0,0,t,m),o.toDataURL("image/webp",c)):null}return s.toDataURL("image/webp",c)}catch(e){return console.warn("DOM screenshot capture failed:",e),null}}export{L as captureDomScreenshot,f as isDomScreenshotSupported};
2
+ //# sourceMappingURL=screenshot-dom-ZYP2w2h0.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"screenshot-dom-CME7tYRE.js","sources":["../../src/screenshot-dom.ts"],"sourcesContent":["/**\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"],"names":["SCRIPT_URL","loadPromise","isDomScreenshotSupported","canvas","loadHtml2Canvas","resolve","script","start","poll","captureDomScreenshot","options","quality","maxWidth","maxHeight","el","srcWidth","srcHeight","scale","scaledWidth","scaledHeight","scaledCanvas","ctx","error"],"mappings":"AAuBA,MAAMA,IAAa;AAInB,IAAIC,IAAuC;AAMpC,SAASC,IAAoC;AAClD,MAAI,OAAO,WAAa,OAAe,OAAO,SAAW;AACvD,WAAO;AAGT,QAAMC,IAAS,SAAS,cAAc,QAAQ;AAC9C,SAAO,OAAOA,EAAO,cAAe,cAAc,CAAC,CAACA,EAAO,WAAW,IAAI;AAC5E;AAKA,SAASC,IAAoC;AAC3C,SAAI,OAAO,cAAoB,QAAQ,QAAQ,EAAI,IAE/CH,MAEJA,IAAc,IAAI,QAAiB,CAACI,MAAY;AAM9C,QAAI,CAJa,SAAS;AAAA,MACxB,eAAeL,CAAU;AAAA,IAAA,GAGZ;AACb,YAAMM,IAAS,SAAS,cAAc,QAAQ;AAC9C,MAAAA,EAAO,MAAMN,GACbM,EAAO,QAAQ,IACf,SAAS,KAAK,YAAYA,CAAM;AAAA,IAClC;AAGA,UAAMC,IAAQ,KAAK,IAAA,GACbC,IAAO,MAAM;AACjB,UAAI,OAAO,aAAa;AACtB,QAAAH,EAAQ,EAAI;AACZ;AAAA,MACF;AACA,UAAI,KAAK,QAAQE,IAAQ,KAAc;AACrC,QAAAN,IAAc,MACdI,EAAQ,EAAK;A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c,QAAQ;AACpD,MAAAA,EAAa,QAAQF,GACrBE,EAAa,SAASD;AAEtB,YAAME,IAAMD,EAAa,WAAW,IAAI;AACxC,aAAKC,KAELA,EAAI,UAAUlB,GAAQ,GAAG,GAAGe,GAAaC,CAAY,GAC9CC,EAAa,UAAU,cAAcT,CAAO,KAHlC;AAAA,IAInB;AAEA,WAAOR,EAAO,UAAU,cAAcQ,CAAO;AAAA,EAC/C,SAASW,GAAO;AACd,mBAAQ,KAAK,kCAAkCA,CAAK,GAC7C;AAAA,EACT;AACF;"}
1
+ {"version":3,"file":"screenshot-dom-ZYP2w2h0.js","sources":["../../src/screenshot-dom.ts"],"sourcesContent":["/**\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"],"names":["SCRIPT_URL","LOAD_TIMEOUT","POLL_INTERVAL","loadPromise","isDomScreenshotSupported","canvas","loadHtml2Canvas","resolve","script","start","poll","captureDomScreenshot","options","quality","maxWidth","maxHeight","el","srcWidth","srcHeight","scale","scaledWidth","scaledHeight","scaledCanvas","ctx","error"],"mappings":"AAuBA,MAAMA,EAAa,0CACbC,EAAe,IACfC,EAAgB,GAEtB,IAAIC,EAAuC,KAMpC,SAASC,GAAoC,CAClD,GAAI,OAAO,SAAa,KAAe,OAAO,OAAW,IACvD,MAAO,GAGT,MAAMC,EAAS,SAAS,cAAc,QAAQ,EAC9C,OAAO,OAAOA,EAAO,YAAe,YAAc,CAAC,CAACA,EAAO,WAAW,IAAI,CAC5E,CAKA,SAASC,GAAoC,CAC3C,OAAI,OAAO,YAAoB,QAAQ,QAAQ,EAAI,EAE/CH,IAEJA,EAAc,IAAI,QAAkBI,GAAY,CAM9C,GAAI,CAJa,SAAS,cACxB,eAAeP,CAAU,IAAA,EAGZ,CACb,MAAMQ,EAAS,SAAS,cAAc,QAAQ,EAC9CA,EAAO,IAAMR,EACbQ,EAAO,MAAQ,GACf,SAAS,KAAK,YAAYA,CAAM,CAClC,CAGA,MAAMC,EAAQ,KAAK,IAAA,EACbC,EAAO,IAAM,CACjB,GAAI,OAAO,YAAa,CACtBH,EAAQ,EAAI,EACZ,MACF,CACA,GAAI,KAAK,MAA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,EAEtB,MAAME,EAAMD,EAAa,WAAW,IAAI,EACxC,OAAKC,GAELA,EAAI,UAAUlB,EAAQ,EAAG,EAAGe,EAAaC,CAAY,EAC9CC,EAAa,UAAU,aAAcT,CAAO,GAHlC,IAInB,CAEA,OAAOR,EAAO,UAAU,aAAcQ,CAAO,CAC/C,OAASW,EAAO,CACd,eAAQ,KAAK,iCAAkCA,CAAK,EAC7C,IACT,CACF"}
@@ -0,0 +1,2 @@
1
+ import{D as O}from"./core-BsR7oV99.js";const Q=["a[href]","button","input","textarea","select","[tabindex]"].join(",");function _(e){return e.hasAttribute("disabled")?!0:e.disabled===!0}function F(e){let t=e;for(;t;){if(t.hasAttribute("hidden"))return!0;const n=t.style;if(n&&(n.display==="none"||n.visibility==="hidden"||n.visibility==="collapse"))return!0;t=t.parentElement}return!1}function b(e){return Array.from(e.querySelectorAll(Q)).filter(n=>!(n.getAttribute("tabindex")==="-1"||n instanceof HTMLInputElement&&n.type==="hidden"||n instanceof HTMLAnchorElement&&!n.getAttribute("href")||_(n)||F(n)))}function m(e){let t=e.activeElement;for(;t&&t.shadowRoot&&t.shadowRoot.activeElement;)t=t.shadowRoot.activeElement;return t instanceof HTMLElement?t:null}function h(e){const t=e.ownerDocument||document;let n=!1;const r=i=>{if(i.key!=="Tab")return;const a=b(e);if(a.length===0){i.preventDefault(),e.focus();return}const s=a[0],l=a[a.length-1],u=m(t),c=u?a.indexOf(u)!==-1:!1;i.shiftKey?(!c||u===s)&&(i.preventDefault(),l.focus()):(!c||u===l)&&(i.preventDefault(),s.focus())};e.addEventListener("keydown",r);const o=b(e);return o.length>0?o[0].focus():(e.hasAttribute("tabindex")||(e.setAttribute("tabindex","-1"),n=!0),e.focus()),{release(){e.removeEventListener("keydown",r),n&&(e.removeAttribute("tabindex"),n=!1)}}}function g(){return m(document)}function w(e){if(!(!e||typeof e.focus!="function"))try{e.focus()}catch{}}function v(e,t={}){e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),t.labelledbyId&&e.setAttribute("aria-labelledby",t.labelledbyId),t.describedbyId&&e.setAttribute("aria-describedby",t.describedbyId),t.label&&e.setAttribute("aria-label",t.label)}function L(e,t){let n=e;for(;n&&n!==t;){const r=n.parentNode;if(r===t)return n;if(r&&r.host){n=r.host;continue}if(!r)return null;n=r}return null}function A(e){const n=(e.ownerDocument||document).body;if(!n)return()=>{};const r=L(e,n),o=[];return Array.from(n.children).forEach(i=>{if(!(i instanceof HTMLElement)||r&&i===r)return;const a=i.inert===!0,s=i.getAttribute("aria-hidden");a&&s==="true"||(i.inert=!0,i.setAttribute("aria-hidden","true"),o.push({el:i,prevInert:a,prevAriaHidden:s}))}),function(){for(;o.length;){const a=o.pop();a.el.inert=a.prevInert,a.prevAriaHidden===null?a.el.removeAttribute("aria-hidden"):a.el.setAttribute("aria-hidden",a.prevAriaHidden)}}}function H(e,t){const n=g();v(e,t);const r=h(e),o=A(e);return()=>{r.release(),o(),w(n)}}const U=Object.freeze(Object.defineProperty({__proto__:null,applyDialog:v,createFocusTrap:h,getFocusable:b,openDialog:H,restoreFocus:w,saveFocus:g,setBackgroundInert:A},Symbol.toStringTag,{value:"Module"})),k=e=>import(e);let E=k,d=null,f=null;const p=new Map,y=new Map;function q(e){E=e??k,d=null,f=null,p.clear(),y.clear()}function S(e,t){return`${e.replace(/\/+$/,"")}/${encodeURIComponent(t)}/definition`}function x(e){if(p.has(e))return Promise.resolve();const t=y.get(e);if(t)return t;const n=fetch(e,{headers:{Accept:"application/json"}}).then(r=>r.ok?r.json():null).then(r=>{r&&p.set(e,r)}).catch(()=>{}).finally(()=>{y.delete(e)});return y.set(e,n),n}function D(e){return d&&f===e||(f=e,d=Promise.resolve(E(e)).then(t=>{const n=t;if(!n||typeof n.QaidQuests!="function")throw new Error("quests module has no QaidQuests export");return n}).catch(t=>{throw d=null,f=null,t})),d}async function I(e){const t=await D(e.moduleUrl),n=e.base.replace(/\/+$/,""),r=S(n,e.questId),o=s=>s!=null?{feedbackId:s}:void 0;let i;const a=e.feedbackId;return a instanceof Promise?i=t.QaidQuests.supports?.asyncMetadata?a.then(o,()=>{}):o(await a.catch(()=>null)):i=o(a??null),new t.QaidQuests({endpoint:`${n}/responses`,configUrl:r,questionnaire:p.get(r),apiKey:e.apiKey||void 0,metadata:i,onClose:e.onClose})}const j=Object.freeze(Object.defineProperty({__proto__:null,DEFAULT_QUESTS_MODULE_URL:O,_setQuestsImporter:q,launchQuest:I,loadQuestsModule:D,prefetchQuestDefinition:x,questDefinitionUrl:S},Symbol.toStringTag,{value:"Module"}));async function T(e,t){const n=e.ensureOverlayHost(),r=e.overlayShadowHost,o=r.style.pointerEvents;r.style.pointerEvents="auto";try{const{openAnnotationEditor:i,styles:a}=await import("./annotate-DGyRcgPt.js");return e.addFeatureStyles(a),await i({dataUrl:t,root:n,quality:e.config.screenshotOptions.quality,color:e.config.annotationColor,palette:e.config.annotationPalette,applyVars:s=>e.applyVars(s),announce:(s,l)=>e.announceMsg(s,l),openDialog:(s,l)=>e.openDialogA11y(s,l),closeDialog:()=>e.closeDialogA11y()})}catch(i){return console.error("Annotation editor failed to open:",i),null}finally{r.style.pointerEvents=o}}async function P(e){const{config:t,feedbackData:n,selectedBounds:r}=e;let o=null;if(t.captureScreenshot||t.feedbackMode==="annotate")try{if(e.shouldCaptureViaDom()){const{captureDomScreenshot:c}=await import("./screenshot-dom-ZYP2w2h0.js");o=await c(t.screenshotOptions)}else{const{captureScreenshot:c}=await import("./screenshot-CNe1irEz.js");o=await c(t.screenshotOptions)}o&&e.announceMsg("Screenshot captured")}catch(c){console.error("Screenshot capture failed:",c),o=null}o&&t.annotate&&(o=await T(e,o)??o);const a=n.elementSelector?{x:r.x,y:r.y,width:r.width,height:r.height}:null,s={feedbackType:n.feedbackType,pageUrl:window.location.href,apiKey:t.apiKey||void 0,elementSelector:n.elementSelector,elementText:n.elementText,consoleErrors:[...n.consoleErrors],screenWidth:window.innerWidth,screenHeight:window.innerHeight,clickX:r.clickX,clickY:r.clickY,scrollX:window.scrollX,scrollY:window.scrollY,screenshot:o,visitorId:e.visitorId,elementBounds:a,userAgent:navigator.userAgent},l=C(e,s);e.setFeedbackId(l);const u=n.feedbackType;if(u&&u!=="neutral"&&await M(e,u,l)){e.resetFeedbackUi();return}e.setState("MODAL_OPEN");try{const c=await e.ensureModal();if(e.destroyed)return;c.open(),e.overlayShadowHost&&(e.overlayShadowHost.style.pointerEvents="auto")}catch(c){console.error("Failed to open the feedback modal:",c),e.announceMsg("Thank you for your feedback!",!0),e.resetFeedbackUi()}}async function C(e,t){try{const n=await fetch(e.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(n.ok){const r=await n.json();return e.announceMsg("Feedback sent"),r.id}}catch(n){console.error("Failed to submit feedback:",n),e.announceMsg("Failed to send feedback",!0)}return null}async function M(e,t,n){const r=e.config.quests,o=r.base&&r[t]||"";if(!o)return!1;try{return e.activeQuest?.destroy(),e.activeQuest=await I({questId:o,base:r.base,apiKey:r.apiKey||void 0,moduleUrl:r.moduleUrl,feedbackId:n,onClose:()=>{e.activeQuest=null}}),!0}catch(i){return console.error("Failed to launch quest:",i),e.activeQuest=null,!1}}const K=Object.freeze(Object.defineProperty({__proto__:null,openAnnotationEditor:T,submitFeedback:P,tryLaunchQuest:M},Symbol.toStringTag,{value:"Module"}));export{U as a,j as q,K as s};
2
+ //# sourceMappingURL=send-C26DRoYc.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"send-C26DRoYc.js","sources":["../../src/a11y-dialog.ts","../../src/quest-launcher.ts","../../src/send.ts"],"sourcesContent":["/**\n * Dialog accessibility for the qaid embeds: focus management (trap,\n * save/restore), dialog semantics, and background isolation. Split from\n * a11y.ts so the startup chunk ships only `announce`; this module loads with\n * the click path (the message box, the markup editor, the video preview).\n *\n * Framework-free and self-contained (no CSS dependency), so it can be dropped\n * into any open shadow root.\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\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 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/** What {@link openDialog} needs to name the dialog. */\nexport type DialogOptions = ApplyDialogOptions;\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. Returns the matching close: release the trap, restore the\n * background, and return focus to the saved control.\n */\nexport function openDialog(container: HTMLElement, opts: DialogOptions): () => void {\n const trigger = saveFocus();\n applyDialog(container, opts);\n const trap = createFocusTrap(container);\n const restoreInert = setBackgroundInert(container);\n return () => {\n trap.release();\n restoreInert();\n restoreFocus(trigger);\n };\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// The default module URL lives apart so the startup chunk can fill in the\n// config default without carrying this loader.\nexport { DEFAULT_QUESTS_MODULE_URL } from \"./quest-config\";\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 /** The definition, when it was fetched ahead of time (wins over configUrl). */\n questionnaire?: unknown;\n apiKey?: string;\n /** A promise only when the loaded module says it accepts one. */\n metadata?: Record<string, unknown> | Promise<Record<string, unknown> | undefined>;\n onComplete?: (answers: Record<string, unknown>) => void;\n onClose?: () => void;\n}\n\ninterface QuestsConstructor {\n new (config: LaunchedQuestConfig): QuestInstance;\n /** quests-embed 1.7+: `asyncMetadata` means `metadata` may be a promise. */\n supports?: { asyncMetadata?: boolean };\n}\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/** Quest definitions fetched ahead of a click, by definition URL. */\nconst definitions = new Map<string, unknown>();\nconst definitionLoads = new Map<string, Promise<void>>();\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 definitions.clear();\n definitionLoads.clear();\n}\n\n/** Where the quest service serves a quest's live definition. */\nexport function questDefinitionUrl(base: string, questId: string): string {\n return `${base.replace(/\\/+$/, \"\")}/${encodeURIComponent(questId)}/definition`;\n}\n\n/**\n * Fetch a quest's definition before anyone clicks, so the quest opens from\n * memory. Never rejects: a failed fetch is forgotten, and the quests widget\n * then loads the definition itself, the way it did before this existed.\n */\nexport function prefetchQuestDefinition(url: string): Promise<void> {\n if (definitions.has(url)) return Promise.resolve();\n const pending = definitionLoads.get(url);\n if (pending) return pending;\n const load = fetch(url, { headers: { Accept: \"application/json\" } })\n .then((res) => (res.ok ? res.json() : null))\n .then((def: unknown) => {\n if (def) definitions.set(url, def);\n })\n .catch(() => {})\n .finally(() => {\n definitionLoads.delete(url);\n });\n definitionLoads.set(url, load);\n return load;\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 /**\n * Feedback record id to correlate the response with (optional). A promise\n * lets the quest open before the feedback POST has answered.\n */\n feedbackId?: string | number | null | Promise<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 configUrl = questDefinitionUrl(base, opts.questId);\n const toMetadata = (id: string | number | null): Record<string, unknown> | undefined =>\n id != null ? { feedbackId: id } : undefined;\n\n let metadata: LaunchedQuestConfig[\"metadata\"];\n const id = opts.feedbackId;\n if (id instanceof Promise) {\n // A quests build that takes a promise opens now and sends the id when it\n // lands. An older one (a pinned moduleUrl) would serialise the promise as\n // {} and lose the id, so for it we wait, as before.\n metadata = mod.QaidQuests.supports?.asyncMetadata\n ? id.then(toMetadata, () => undefined)\n : toMetadata(await id.catch(() => null));\n } else {\n metadata = toMetadata(id ?? null);\n }\n\n return new mod.QaidQuests({\n endpoint: `${base}/responses`,\n configUrl,\n // Only a definition already in hand. One still loading is left to the\n // widget, which shows its own loading state instead of nothing.\n questionnaire: definitions.get(configUrl),\n apiKey: opts.apiKey || undefined,\n metadata,\n onClose: opts.onClose,\n });\n}\n","/**\n * The feedback send flow — extracted from embed.ts into its own lazily-loaded\n * chunk. It runs only after a thumb click (or a targeted element), so it is\n * pre-warmed when the pointer or focus reaches the buttons, or on idle,\n * whichever comes first.\n *\n * It captures (and lets the visitor mark up) a screenshot when configured,\n * POSTs the feedback, then opens the linked quest or the message box. It talks\n * back to the embed through the narrow `SendHost` interface.\n */\n\nimport { launchQuest, type QuestInstance } from \"./quest-launcher\";\nimport type { ModalController } from \"./modal\";\nimport type {\n ResolvedFeedbackConfig,\n EmbedState,\n FeedbackData,\n SelectedBounds,\n FeedbackPayload,\n FeedbackResponse,\n} from \"./types\";\n\n/** The slice of the embed the send flow needs. */\nexport interface SendHost {\n readonly config: ResolvedFeedbackConfig;\n readonly visitorId: string;\n /** Live references, filled in by the click or the targeting controller. */\n readonly feedbackData: FeedbackData;\n readonly selectedBounds: SelectedBounds;\n readonly destroyed: boolean;\n readonly overlayShadowHost: HTMLDivElement | null;\n /** A quest launched from a button, so destroy() can tear it down. */\n activeQuest: QuestInstance | null;\n setState(state: EmbedState): void;\n /** Record the pending POST, which the message box's PATCHes wait on. */\n setFeedbackId(id: Promise<number | null>): void;\n shouldCaptureViaDom(): boolean;\n ensureOverlayHost(): ShadowRoot;\n ensureModal(): Promise<ModalController>;\n addFeatureStyles(css: string): void;\n applyVars(el: HTMLElement): void;\n announceMsg(message: string, assertive?: boolean): void;\n openDialogA11y(\n container: HTMLElement,\n opts: { labelledbyId?: string; describedbyId?: string; label?: string }\n ): void;\n closeDialogA11y(): void;\n resetFeedbackUi(): void;\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 */\nexport async function openAnnotationEditor(\n host: SendHost,\n screenshot: string\n): Promise<string | null> {\n const root = host.ensureOverlayHost();\n const overlay = host.overlayShadowHost!;\n const prevPointerEvents = overlay.style.pointerEvents;\n overlay.style.pointerEvents = \"auto\";\n try {\n const { openAnnotationEditor, styles } = await import(\"./annotate\");\n host.addFeatureStyles(styles);\n return await openAnnotationEditor({\n dataUrl: screenshot,\n root,\n quality: host.config.screenshotOptions.quality,\n color: host.config.annotationColor,\n palette: host.config.annotationPalette,\n applyVars: (el) => host.applyVars(el),\n announce: (msg, assertive) => host.announceMsg(msg, assertive),\n openDialog: (container, opts) => host.openDialogA11y(container, opts),\n closeDialog: () => host.closeDialogA11y(),\n });\n } catch (err) {\n // The annotate chunk failed to load / the editor threw — keep the\n // original screenshot rather than aborting the whole submission.\n console.error(\"Annotation editor failed to open:\", err);\n return null;\n } finally {\n overlay.style.pointerEvents = prevPointerEvents;\n }\n}\n\n/** Capture, POST, then hand off to a linked quest or the message box. */\nexport async function submitFeedback(host: SendHost): Promise<void> {\n const { config, feedbackData, selectedBounds } = host;\n // Capture screenshot if enabled (server will gate by plan). \"annotate\" mode\n // always captures one to mark up, even without captureScreenshot set.\n let screenshot: string | null = null;\n const wantScreenshot = config.captureScreenshot || config.feedbackMode === \"annotate\";\n if (wantScreenshot) {\n // Loaded on demand so visitors who never submit a screenshot never\n // download the capture + annotation code. A capture failure (denied\n // permission, chunk load error) must never abort the feedback — we just\n // submit without a screenshot so the user still reaches the modal.\n try {\n if (host.shouldCaptureViaDom()) {\n const { captureDomScreenshot } = await import(\"./screenshot-dom\");\n screenshot = await captureDomScreenshot(config.screenshotOptions);\n } else {\n const { captureScreenshot } = await import(\"./screenshot\");\n screenshot = await captureScreenshot(config.screenshotOptions);\n }\n if (screenshot) host.announceMsg(\"Screenshot captured\");\n } catch (err) {\n console.error(\"Screenshot capture failed:\", err);\n screenshot = null;\n }\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 && config.annotate) {\n screenshot = (await openAnnotationEditor(host, 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 = feedbackData.elementSelector\n ? {\n x: selectedBounds.x,\n y: selectedBounds.y,\n width: selectedBounds.width,\n height: selectedBounds.height,\n }\n : null;\n\n const payload: FeedbackPayload = {\n feedbackType: feedbackData.feedbackType!,\n pageUrl: window.location.href,\n apiKey: config.apiKey || undefined,\n elementSelector: feedbackData.elementSelector,\n elementText: feedbackData.elementText,\n consoleErrors: [...feedbackData.consoleErrors],\n screenWidth: window.innerWidth,\n screenHeight: window.innerHeight,\n clickX: selectedBounds.clickX,\n clickY: selectedBounds.clickY,\n scrollX: window.scrollX,\n scrollY: window.scrollY,\n screenshot,\n visitorId: host.visitorId,\n // Include element bounds and user agent for server-side screenshot fallback\n elementBounds,\n userAgent: navigator.userAgent,\n };\n\n // The POST goes out in the background. The message box or linked quest\n // opens now instead of a server round trip later; what needs the new\n // record's id (the message PATCH, the quest's link back) waits on this.\n const feedbackId = postFeedback(host, payload);\n host.setFeedbackId(feedbackId);\n\n // If this button is linked to a quest, launch it in place of the\n // message box, handing it the pending id. On success we just tear down\n // the targeting UI and hand off. On any load failure we fall through to\n // the classic message box so the user can still leave an optional message.\n const type = feedbackData.feedbackType;\n // Quest links are keyed by up/down/video; neutral single-button feedback\n // has no quest mapping, so it always falls through to the message box.\n if (type && type !== \"neutral\" && (await tryLaunchQuest(host, type, feedbackId))) {\n host.resetFeedbackUi();\n return;\n }\n\n // Always show the message modal as the terminal state (even if the API\n // failed — useful for demos).\n host.setState(\"MODAL_OPEN\");\n try {\n // The modal chunk loads async; bail if the embed was destroyed meanwhile,\n // so a raced modal never opens (and never leaks a listener) post-destroy.\n const modal = await host.ensureModal();\n if (host.destroyed) return;\n modal.open();\n\n // Enable pointer events on overlay host for modal\n if (host.overlayShadowHost) {\n host.overlayShadowHost.style.pointerEvents = \"auto\";\n }\n } catch (err) {\n // The modal chunk failed to load/open. Never leave the user stuck in a\n // re-targetable limbo: thank them and reset to IDLE so a fresh click\n // starts a clean flow (the feedback itself was already POSTed above).\n console.error(\"Failed to open the feedback modal:\", err);\n host.announceMsg(\"Thank you for your feedback!\", true);\n host.resetFeedbackUi();\n }\n}\n\n/** POST the feedback. Resolves to the new record's id, or null if it failed. */\nasync function postFeedback(host: SendHost, payload: FeedbackPayload): Promise<number | null> {\n try {\n const response = await fetch(host.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 host.announceMsg(\"Feedback sent\");\n return data.id;\n }\n } catch (error) {\n console.error(\"Failed to submit feedback:\", error);\n host.announceMsg(\"Failed to send feedback\", true);\n }\n return null;\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 (quest launching off: no `base`, or this button has no quest)\n * or the widget failed to load (caller falls back to its normal UI). The\n * created feedback record id is passed through so the quest response can be\n * joined back to it server-side.\n */\nexport async function tryLaunchQuest(\n host: SendHost,\n type: \"up\" | \"down\" | \"video\",\n feedbackId: number | string | null | Promise<number | string | null>,\n): Promise<boolean> {\n const q = host.config.quests;\n const questId = q.base ? q[type] || \"\" : \"\";\n if (!questId) return false;\n try {\n host.activeQuest?.destroy();\n host.activeQuest = await launchQuest({\n questId,\n base: q.base,\n apiKey: q.apiKey || undefined,\n moduleUrl: q.moduleUrl,\n feedbackId,\n onClose: () => {\n host.activeQuest = null;\n },\n });\n return true;\n } catch (error) {\n console.error(\"Failed to launch quest:\", error);\n host.activeQuest = null;\n return false;\n }\n}\n"],"names":["FOCUSABLE_SELECTOR","isDisabled","el","isHidden","node","style","getFocusable","container","getDeepActiveElement","doc","active","createFocusTrap","addedTabindex","onKeydown","event","focusable","first","last","withinTrap","initial","saveFocus","restoreFocus","applyDialog","opts","topLevelAncestor","body","parent","setBackgroundInert","except","keep","changed","child","prevInert","prevAriaHidden","entry","openDialog","trigger","trap","restoreInert","defaultImporter","url","importer","modulePromise","cachedUrl","definitions","definitionLoads","_setQuestsImporter","fn","questDefinitionUrl","base","questId","prefetchQuestDefinition","pending","load","res","def","loadQuestsModule","moduleUrl","mod","m","err","launchQuest","configUrl","toMetadata","id","metadata","openAnnotationEditor","host","screenshot","root","overlay","prevPointerEvents","styles","msg","assertive","submitFeedback","config","feedbackData","selectedBounds","captureDomScreenshot","captureScreenshot","elementBounds","payload","feedbackId","postFeedback","type","tryLaunchQuest","modal","response","data","error","q"],"mappings":"uCA8BA,MAAMA,EAAqB,CACzB,UACA,SACA,QACA,WACA,SACA,YACF,EAAE,KAAK,GAAG,EAEV,SAASC,EAAWC,EAA0B,CAC5C,OAAIA,EAAG,aAAa,UAAU,EAAU,GACxBA,EACD,WAAa,EAC9B,CAEA,SAASC,EAASD,EAA0B,CAC1C,IAAIE,EAA2BF,EAC/B,KAAOE,GAAM,CACX,GAAIA,EAAK,aAAa,QAAQ,EAAG,MAAO,GACxC,MAAMC,EAAQD,EAAK,MACnB,GACEC,IACCA,EAAM,UAAY,QACjBA,EAAM,aAAe,UACrBA,EAAM,aAAe,YAEvB,MAAO,GAETD,EAAOA,EAAK,aACd,CACA,MAAO,EACT,CAQO,SAASE,EAAaC,EAAuC,CAIlE,OAHc,MAAM,KAClBA,EAAU,iBAA8BP,CAAkB,CAAA,EAE/C,OAAQE,GACf,EAAAA,EAAG,aAAa,UAAU,IAAM,MAChCA,aAAc,kBAAoBA,EAAG,OAAS,UAC9CA,aAAc,mBAAqB,CAACA,EAAG,aAAa,MAAM,GAC1DD,EAAWC,CAAE,GACbC,EAASD,CAAE,EAEhB,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ClB,MAAMQ,EAAIxB,EAAK,OAAO,OAChBjB,EAAUyC,EAAE,MAAOA,EAAEN,CAAI,GAAK,GACpC,GAAI,CAACnC,EAAS,MAAO,GACrB,GAAI,CACF,OAAAiB,EAAK,aAAa,QAAA,EAClBA,EAAK,YAAc,MAAMN,EAAY,CACnC,QAAAX,EACA,KAAMyC,EAAE,KACR,OAAQA,EAAE,QAAU,OACpB,UAAWA,EAAE,UACb,WAAAR,EACA,QAAS,IAAM,CACbhB,EAAK,YAAc,IACrB,CAAA,CACD,EACM,EACT,OAASuB,EAAO,CACd,eAAQ,MAAM,0BAA2BA,CAAK,EAC9CvB,EAAK,YAAc,KACZ,EACT,CACF"}
@@ -0,0 +1,6 @@
1
+ import{g as k,e as q,i as m}from"./core-BsR7oV99.js";const T=["data-comp","data-qa","data-testid","data-id"];function E(i,t=document.body){let e=i;for(;e&&e!==t;){for(const r of T){const o=e.getAttribute(r);if(o)return`${r}="${o}"`}e=e.parentElement}return null}function S(i,t=100){const e=i.textContent?.trim().slice(0,t)||"";return e.length===t?e+"...":e}function w(i){let t=1,e=i.previousElementSibling;for(;e;)t++,e=e.previousElementSibling;return t}function L(i){const t=[];let e=i;for(;e&&e!==document.body&&e!==document.documentElement;){const r=e.tagName.toLowerCase(),o=w(e);t.unshift(`${r}:nth-child(${o})`),e=e.parentElement}return t.length>0?`body > ${t.join(" > ")}`:"body"}function A(i){return i.replace(/([!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g,"\\$1")}function P(i){const t=E(i);return t?`[${t}]`:i.id?`#${A(i.id)}`:L(i)}function y(i){const t=S(i),e=E(i);return{selector:P(i),text:t,dataAttr:e}}const $=["a[href]","button","input:not([type=hidden])","select","textarea","summary","[tabindex]","[role]","img","h1","h2","h3","h4","h5","h6","p","li","label",...T.map(i=>`[${i}]`)].join(","),D=/^(?:A|BUTTON|INPUT|SELECT|TEXTAREA|SUMMARY)$/;function B(i){if(i.hasAttribute("hidden")||i.getAttribute("aria-hidden")==="true")return!1;const t=i.ownerDocument?.defaultView;if(t&&typeof t.getComputedStyle=="function"){const e=t.getComputedStyle(i);if(e.display==="none"||e.visibility==="hidden")return!1}return!0}function H(i={}){const t=i.root??document.body,e=i.selector??$,r=i.isExcluded??(()=>!1),o=i.isVisible??B;return Array.from(t.querySelectorAll(e)).filter(a=>!r(a)&&o(a))}function V(i){const t=i.candidates??H({root:i.root,selector:i.selector,isExcluded:i.isExcluded,isVisible:i.isVisible}),e=i.moveFocus??!0,r=i.eventTarget??document,o=new Set;let a=-1,n=!1;const h=i.initial!==void 0?i.initial:typeof document<"u"?document.activeElement:null;if(h){const s=t.indexOf(h);s>=0&&(a=s)}a<0&&t.length>0&&(a=0);function C(s){if(!e)return;const d=s;if(typeof d.focus=="function"){s.getAttribute("tabindex")===null&&!D.test(s.tagName)&&(s.setAttribute("tabindex","-1"),o.add(s));try{d.focus()}catch{}}}function v(){const s=t[a];s&&(C(s),i.onHighlight?.(s,a))}function l(s){if(n||t.length===0)return;const d=t.length;a=(s%d+d)%d,v()}function c(){l(a+1)}function u(){l(a-1)}function b(){return t[a]??null}function p(){n||(n=!0,r.removeEventListener("keydown",g,!0),o.forEach(s=>s.removeAttribute("tabindex")),o.clear())}function f(){if(n)return;const s=b();p(),s&&i.onSelect(s)}function x(){n||(p(),i.onCancel?.())}function g(s){if(!n)switch(s.key){case"Tab":s.preventDefault(),s.stopPropagation(),s.shiftKey?u():c();break;case"ArrowDown":case"ArrowRight":s.preventDefault(),s.stopPropagation(),c();break;case"ArrowUp":case"ArrowLeft":s.preventDefault(),s.stopPropagation(),u();break;case"Enter":case" ":case"Spacebar":s.preventDefault(),s.stopPropagation(),f();break;case"Escape":case"Esc":s.preventDefault(),s.stopPropagation(),x();break}}return r.addEventListener("keydown",g,!0),a>=0&&v(),{candidates:t,getIndex:()=>a,getCurrent:b,next:c,prev:u,moveTo:l,select:f,cancel:x,handleKey:g,stop:p}}const M=".qaid-targeting-overlay{position:fixed;inset:0;z-index:40;pointer-events:none}.qaid-capture-layer{position:fixed;inset:0;pointer-events:none;z-index:9999}.qaid-vignette{position:fixed;inset:0;pointer-events:none;background:radial-gradient(ellipse at center,transparent 30%,rgba(0,0,0,.3) 70%,rgba(0,0,0,.6) 100%);z-index:41}.qaid-crosshair-h,.qaid-crosshair-v{position:fixed;pointer-events:none;z-index:42}.qaid-crosshair-h{left:0;right:0;height:1px;background:color-mix(in srgb,var(--qaid-negative) 60%,transparent)}.qaid-crosshair-v{top:0;bottom:0;width:1px;background:color-mix(in srgb,var(--qaid-negative) 60%,transparent)}.qaid-type-up .qaid-crosshair-h,.qaid-type-up .qaid-crosshair-v{background:color-mix(in srgb,var(--qaid-positive) 60%,transparent)}.qaid-highlight-box{position:fixed;top:0;left:0;pointer-events:none;z-index:41;display:none;border:3px solid color-mix(in srgb,var(--qaid-negative) 80%,transparent);border-radius:2px;background:color-mix(in srgb,var(--qaid-negative) 8%,transparent);will-change:transform,width,height}.qaid-type-up .qaid-highlight-box{border-color:color-mix(in srgb,var(--qaid-positive) 80%,transparent);background:color-mix(in srgb,var(--qaid-positive) 8%,transparent)}.qaid-scope{position:fixed;width:80px;height:80px;pointer-events:none;z-index:43;transform:translate(-50%,-50%)}.qaid-scope-ring{position:absolute;inset:10px;border:2px solid color-mix(in srgb,var(--qaid-negative) 80%,transparent);border-radius:50%}.qaid-type-up .qaid-scope-ring{border-color:color-mix(in srgb,var(--qaid-positive) 80%,transparent)}.qaid-scope-ring-inner{position:absolute;inset:20px;border:1px solid color-mix(in srgb,var(--qaid-negative) 50%,transparent);border-radius:50%}.qaid-type-up .qaid-scope-ring-inner{border-color:color-mix(in srgb,var(--qaid-positive) 50%,transparent)}.qaid-scope-dot{position:absolute;top:50%;left:50%;width:4px;height:4px;background:var(--qaid-negative);border-radius:50%;transform:translate(-50%,-50%)}.qaid-type-up .qaid-scope-dot{background:var(--qaid-positive)}.qaid-selected-marker{position:fixed;border:3px solid var(--qaid-marker, #6365f1);border-radius:50%;pointer-events:none;z-index:44;animation:qaid-markerPulse 1.5s ease-in-out infinite}@keyframes qaid-markerPulse{0%,to{opacity:1;transform:scale(1)}50%{opacity:.7;transform:scale(1.05)}}@media(forced-colors:active){.qaid-selected-marker,.qaid-highlight-box{border-color:Highlight}}",N=12;class O{constructor(t){this.host=t}host;mousePos={x:0,y:0};touchStartPos=null;overlayContainer=null;captureLayer=null;crosshairH=null;crosshairV=null;scope=null;highlightBox=null;marker=null;keyboardController=null;boundMouseMove=t=>this.handleMouseMove(t);boundClick=t=>this.handleClick(t);boundTouchStart=t=>this.handleTouchStart(t);boundTouchEnd=t=>this.handleTouchEnd(t);startPointer(t,e){this.host.setState("TARGETING"),this.host.feedbackData.feedbackType=t,this.host.feedbackData.elementSelector=null,this.host.feedbackData.elementText=null,this.host.selectedBounds.visible=!1,this.mousePos.x=e.clientX,this.mousePos.y=e.clientY,document.body.classList.add("qaid-targeting"),t==="up"?document.body.classList.add("qaid-type-up"):document.body.classList.remove("qaid-type-up"),document.body.style.setProperty("--qaid-positive",this.host.cssVars["--qaid-positive"]),document.body.style.setProperty("--qaid-negative",this.host.cssVars["--qaid-negative"]),this.createTargetingOverlay(),document.addEventListener("keydown",this.host.boundKeyDown),document.addEventListener("mousemove",this.boundMouseMove),document.addEventListener("click",this.boundClick,!0),document.addEventListener("touchstart",this.boundTouchStart,{passive:!0}),document.addEventListener("touchend",this.boundTouchEnd,{passive:!1})}startKeyboard(t){this.host.setState("TARGETING"),this.host.feedbackData.feedbackType=t,this.host.feedbackData.elementSelector=null,this.host.feedbackData.elementText=null,this.host.selectedBounds.visible=!1,document.body.style.setProperty("--qaid-positive",this.host.cssVars["--qaid-positive"]),document.body.style.setProperty("--qaid-negative",this.host.cssVars["--qaid-negative"]),this.createTargetingOverlay(),this.crosshairH&&(this.crosshairH.style.display="none"),this.crosshairV&&(this.crosshairV.style.display="none"),this.scope&&(this.scope.style.display="none"),this.keyboardController=V({isExcluded:e=>m(e),onHighlight:e=>{const r=e.getBoundingClientRect(),o=this.highlightBox;o&&(o.style.transform=`translate(${r.left}px, ${r.top}px)`,o.style.width=`${r.width}px`,o.style.height=`${r.height}px`,o.style.display="block");const{text:a}=y(e);this.host.announceMsg(`Targeting ${a||e.tagName.toLowerCase()}`)},onSelect:e=>this.selectKeyboardTarget(e),onCancel:()=>this.cancel()})}selectKeyboardTarget(t){const e=k(t,8);Object.assign(this.host.selectedBounds,e,{clickX:e.x+e.width/2,clickY:e.y+e.height/2,visible:!0});const{selector:r,text:o}=y(t);this.host.feedbackData.elementSelector=r,this.host.feedbackData.elementText=o,this.removeTargetingOverlay(),document.body.classList.remove("qaid-targeting","qaid-type-up"),document.body.style.removeProperty("--qaid-positive"),document.body.style.removeProperty("--qaid-negative"),this.keyboardController=null,this.host.clearActiveThumb(),this.host.setState("SELECTED"),this.showSelectedMarker(),this.host.submitFeedback()}createTargetingOverlay(){const t=this.host.ensureOverlayHost();this.overlayContainer=document.createElement("div"),this.overlayContainer.className=`qaid-targeting-overlay qaid-type-${this.host.feedbackData.feedbackType}`,this.captureLayer=document.createElement("div"),this.captureLayer.className="qaid-capture-layer";const e=document.createElement("div");e.className="qaid-vignette",this.crosshairH=document.createElement("div"),this.crosshairH.className="qaid-crosshair-h",this.crosshairV=document.createElement("div"),this.crosshairV.className="qaid-crosshair-v",this.scope=document.createElement("div"),this.scope.className="qaid-scope",this.scope.innerHTML=`
2
+ <div class="qaid-scope-ring"></div>
3
+ <div class="qaid-scope-ring-inner"></div>
4
+ <div class="qaid-scope-dot"></div>
5
+ `,this.highlightBox=document.createElement("div"),this.highlightBox.className="qaid-highlight-box",this.overlayContainer.appendChild(this.captureLayer),this.overlayContainer.appendChild(e),this.overlayContainer.appendChild(this.highlightBox),this.overlayContainer.appendChild(this.crosshairH),this.overlayContainer.appendChild(this.crosshairV),this.overlayContainer.appendChild(this.scope),this.crosshairH.style.top=`${this.mousePos.y}px`,this.crosshairV.style.left=`${this.mousePos.x}px`,this.scope.style.left=`${this.mousePos.x}px`,this.scope.style.top=`${this.mousePos.y}px`,this.host.applyVars(this.overlayContainer),t.appendChild(this.overlayContainer)}handleMouseMove(t){this.updateReticleAt(t.clientX,t.clientY)}updateReticleAt(t,e){if(this.mousePos.x=t,this.mousePos.y=e,this.crosshairH&&(this.crosshairH.style.top=`${e}px`),this.crosshairV&&(this.crosshairV.style.left=`${t}px`),this.scope&&(this.scope.style.left=`${t}px`,this.scope.style.top=`${e}px`),this.captureLayer&&this.host.shadowHost){const r=[this.host.shadowHost,this.host.overlayShadowHost].filter(Boolean),o=q(t,e,r);if(o&&!m(o)){if(this.highlightBox){const a=o.getBoundingClientRect();this.highlightBox.style.transform=`translate(${a.left}px, ${a.top}px)`,this.highlightBox.style.width=`${a.width}px`,this.highlightBox.style.height=`${a.height}px`,this.highlightBox.style.display="block"}}else this.highlightBox&&(this.highlightBox.style.display="none")}}handleClick(t){t.preventDefault(),t.stopPropagation(),this.selectAt(t.clientX,t.clientY)}handleTouchStart(t){const e=t.touches[0];e&&(this.touchStartPos={x:e.clientX,y:e.clientY},this.updateReticleAt(e.clientX,e.clientY))}handleTouchEnd(t){const e=t.changedTouches[0],r=this.touchStartPos;this.touchStartPos=null,!(!e||!r||Math.hypot(e.clientX-r.x,e.clientY-r.y)>N)&&(t.preventDefault(),this.selectAt(e.clientX,e.clientY))}selectAt(t,e){const r=[this.host.shadowHost,this.host.overlayShadowHost].filter(Boolean),o=q(t,e,r);if(!o||m(o))return;const a=k(o,8);Object.assign(this.host.selectedBounds,a,{clickX:t,clickY:e,visible:!0});const{selector:n,text:h}=y(o);this.host.feedbackData.elementSelector=n,this.host.feedbackData.elementText=h,this.stopTargetingListeners(),document.body.classList.remove("qaid-targeting","qaid-type-up"),document.body.style.removeProperty("--qaid-positive"),document.body.style.removeProperty("--qaid-negative"),this.host.setState("SELECTED"),this.host.clearActiveThumb(),this.showSelectedMarker(),this.host.submitFeedback()}stopTargetingListeners(){this.removeTargetingOverlay(),this.touchStartPos=null,document.removeEventListener("mousemove",this.boundMouseMove),document.removeEventListener("click",this.boundClick,!0),document.removeEventListener("touchstart",this.boundTouchStart),document.removeEventListener("touchend",this.boundTouchEnd),document.removeEventListener("keydown",this.host.boundKeyDown)}cancel(){this.keyboardController?.stop(),this.keyboardController=null,this.stopTargetingListeners(),document.body.classList.remove("qaid-targeting","qaid-type-up"),document.body.style.removeProperty("--qaid-positive"),document.body.style.removeProperty("--qaid-negative"),this.host.clearActiveThumb(),this.host.setState("IDLE"),this.host.feedbackData.feedbackType=null,this.host.feedbackData.elementSelector=null,this.host.feedbackData.elementText=null,this.host.selectedBounds.visible=!1}removeTargetingOverlay(){this.overlayContainer&&(this.overlayContainer.remove(),this.overlayContainer=null),this.captureLayer=null,this.crosshairH=null,this.crosshairV=null,this.scope=null}showSelectedMarker(){const t=this.host.ensureOverlayHost();this.marker=document.createElement("div"),this.marker.className="qaid-selected-marker",this.marker.style.left=`${this.host.selectedBounds.x}px`,this.marker.style.top=`${this.host.selectedBounds.y}px`,this.marker.style.width=`${this.host.selectedBounds.width}px`,this.marker.style.height=`${this.host.selectedBounds.height}px`,this.marker.style.zIndex=String(this.host.config.zIndex+1),this.host.applyVars(this.marker),t.appendChild(this.marker)}hideMarker(){this.marker&&(this.marker.remove(),this.marker=null)}destroy(){this.keyboardController?.stop(),this.keyboardController=null,this.stopTargetingListeners(),this.hideMarker()}}const R=M;export{O as TargetingController,R as styles};
6
+ //# sourceMappingURL=targeting-CMUEe-7C.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"targeting-CMUEe-7C.js","sources":["../../src/element-selector.ts","../../src/targeting.ts"],"sourcesContent":["/**\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 * Element-targeting subsystem — extracted from embed.ts into its own lazily\n * loaded chunk (it also carries `element-selector`, ~14 KB). It's fetched the\n * first time the user starts targeting (and pre-warmed on thumb-button hover,\n * so the reticle appears without a perceptible wait).\n *\n * The controller owns the reticle/overlay, the mouse/touch/keyboard targeting\n * flows, and the selected-element marker; it talks back to the embed through\n * the narrow `TargetingHost` interface.\n */\n\nimport {\n generateElementInfo,\n startKeyboardTargeting,\n type KeyboardTargetingController,\n} from \"./element-selector\";\nimport {\n getElementAtPointUnderOverlay,\n isEmbedElement,\n getElementBounds,\n} from \"./dom-utils\";\nimport type {\n ResolvedFeedbackConfig,\n EmbedState,\n FeedbackData,\n FeedbackType,\n SelectedBounds,\n} from \"./types\";\nimport featureStyles from \"./styles-targeting.css?inline\";\n\n/** A touch that moves more than this (px) is a scroll, not a tap-to-select. */\nconst TOUCH_TAP_SLOP = 12;\n\n/** The slice of the embed the targeting subsystem needs. */\nexport interface TargetingHost {\n readonly config: ResolvedFeedbackConfig;\n readonly cssVars: Record<string, string>;\n readonly state: EmbedState;\n readonly shadowHost: HTMLDivElement | null;\n readonly overlayShadowHost: HTMLDivElement | null;\n readonly boundKeyDown: (e: KeyboardEvent) => void;\n /** Live references, mutated in place. */\n readonly feedbackData: FeedbackData;\n readonly selectedBounds: SelectedBounds;\n setState(state: EmbedState): void;\n ensureOverlayHost(): ShadowRoot;\n applyVars(el: HTMLElement): void;\n announceMsg(message: string, assertive?: boolean): void;\n clearActiveThumb(): void;\n submitFeedback(): Promise<void>;\n}\n\nexport class TargetingController {\n private mousePos = { x: 0, y: 0 };\n private touchStartPos: { x: number; y: number } | null = null;\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 keyboardController: KeyboardTargetingController | null = null;\n\n private boundMouseMove = (e: MouseEvent): void => this.handleMouseMove(e);\n private boundClick = (e: MouseEvent): void => this.handleClick(e);\n private boundTouchStart = (e: TouchEvent): void => this.handleTouchStart(e);\n private boundTouchEnd = (e: TouchEvent): void => this.handleTouchEnd(e);\n\n constructor(private host: TargetingHost) {}\n\n startPointer(type: FeedbackType, e: MouseEvent): void {\n this.host.setState(\"TARGETING\");\n this.host.feedbackData.feedbackType = type;\n this.host.feedbackData.elementSelector = null;\n this.host.feedbackData.elementText = null;\n this.host.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.host.cssVars[\"--qaid-positive\"]);\n document.body.style.setProperty(\"--qaid-negative\", this.host.cssVars[\"--qaid-negative\"]);\n\n this.createTargetingOverlay();\n\n // Add event listeners on document — overlay is pointer-events:none so scroll works naturally\n document.addEventListener(\"keydown\", this.host.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 startPointer minus the mouse plumbing:\n * no `qaid-targeting` body class (keeps the cursor visible for keyboard\n * users), no mouse reticle, and no document mouse/click listeners. The\n * KeyboardTargetingController owns Tab/Arrow/Enter/Space/Escape.\n */\n startKeyboard(type: FeedbackType): void {\n this.host.setState(\"TARGETING\");\n this.host.feedbackData.feedbackType = type;\n this.host.feedbackData.elementSelector = null;\n this.host.feedbackData.elementText = null;\n this.host.selectedBounds.visible = false;\n\n document.body.style.setProperty(\"--qaid-positive\", this.host.cssVars[\"--qaid-positive\"]);\n document.body.style.setProperty(\"--qaid-negative\", this.host.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.host.announceMsg(`Targeting ${text || el.tagName.toLowerCase()}`);\n },\n onSelect: (el) => this.selectKeyboardTarget(el),\n onCancel: () => this.cancel(),\n });\n }\n\n private selectKeyboardTarget(el: Element): void {\n const bounds = getElementBounds(el, 8);\n Object.assign(this.host.selectedBounds, 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.host.feedbackData.elementSelector = selector;\n this.host.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.host.clearActiveThumb();\n\n this.host.setState(\"SELECTED\");\n this.showSelectedMarker();\n void this.host.submitFeedback();\n }\n\n private createTargetingOverlay(): void {\n const root = this.host.ensureOverlayHost();\n\n this.overlayContainer = document.createElement(\"div\");\n this.overlayContainer.className = `qaid-targeting-overlay qaid-type-${this.host.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.host.applyVars(this.overlayContainer);\n root.appendChild(this.overlayContainer);\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 private updateReticleAt(x: number, y: number): void {\n this.mousePos.x = x;\n this.mousePos.y = y;\n\n if (this.crosshairH) this.crosshairH.style.top = `${y}px`;\n if (this.crosshairV) this.crosshairV.style.left = `${x}px`;\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.host.shadowHost) {\n const hosts = [this.host.shadowHost, this.host.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 if (this.highlightBox) {\n this.highlightBox.style.display = \"none\";\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 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 private selectAt(x: number, y: number): void {\n const hosts = [this.host.shadowHost, this.host.overlayShadowHost].filter(Boolean) as HTMLElement[];\n const target = getElementAtPointUnderOverlay(x, y, hosts);\n\n if (!target || isEmbedElement(target)) {\n return;\n }\n\n const bounds = getElementBounds(target, 8);\n Object.assign(this.host.selectedBounds, bounds, { clickX: x, clickY: y, visible: true });\n\n const { selector, text } = generateElementInfo(target);\n this.host.feedbackData.elementSelector = selector;\n this.host.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.host.setState(\"SELECTED\");\n this.host.clearActiveThumb();\n\n this.showSelectedMarker();\n void this.host.submitFeedback();\n }\n\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.host.boundKeyDown);\n }\n\n cancel(): 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.host.clearActiveThumb();\n\n this.host.setState(\"IDLE\");\n this.host.feedbackData.feedbackType = null;\n this.host.feedbackData.elementSelector = null;\n this.host.feedbackData.elementText = null;\n this.host.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.host.ensureOverlayHost();\n\n this.marker = document.createElement(\"div\");\n this.marker.className = \"qaid-selected-marker\";\n this.marker.style.left = `${this.host.selectedBounds.x}px`;\n this.marker.style.top = `${this.host.selectedBounds.y}px`;\n this.marker.style.width = `${this.host.selectedBounds.width}px`;\n this.marker.style.height = `${this.host.selectedBounds.height}px`;\n this.marker.style.zIndex = String(this.host.config.zIndex + 1);\n\n this.host.applyVars(this.marker);\n root.appendChild(this.marker);\n }\n\n hideMarker(): void {\n if (this.marker) {\n this.marker.remove();\n this.marker = null;\n }\n }\n\n /** Full teardown for embed.destroy(). */\n destroy(): void {\n this.keyboardController?.stop();\n this.keyboardController = null;\n this.stopTargetingListeners();\n this.hideMarker();\n }\n}\n\n/** This feature's shadow-DOM styles; the embed adds them when it loads the chunk. */\nexport const styles = featureStyles;\n"],"names":["DATA_ATTRS","findDataAttribute","element","stopAt","current","attr","value","getTruncatedText","maxLength","textContent","getNthChildIndex","index","sibling","generateNthChildPath","path","tag","escapeCSSIdentifier","str","generateSelector","dataAttr","generateElementInfo","text","TARGETABLE_SELECTOR","NATIVELY_FOCUSABLE","isElementVisible","view","style","collectTargetableElements","options","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","TOUCH_TAP_SLOP","TargetingController","host","e","type","el","isEmbedElement","rect","b","bounds","getElementBounds","vignette","x","y","hosts","elementUnder","getElementAtPointUnderOverlay","t","start","styles","featureStyles"],"mappings":"qDAKO,MAAMA,EAAa,CAAC,YAAa,UAAW,cAAe,SAAS,EAWpE,SAASC,EACdC,EACAC,EAAkB,SAAS,KACZ,CACf,IAAIC,EAA0BF,EAE9B,KAAOE,GAAWA,IAAYD,GAAQ,CACpC,UAAWE,KAAQL,EAAY,CAC7B,MAAMM,EAAQF,EAAQ,aAAaC,CAAI,EACvC,GAAIC,EACF,MAAO,GAAGD,CAAI,KAAKC,CAAK,GAE5B,CACAF,EAAUA,EAAQ,aACpB,CAEA,OAAO,IACT,CAKO,SAASG,EAAiBL,EAAkBM,EAAY,IAAa,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mB,MAE1B,KAAK,aAAe,KACpB,KAAK,WAAa,KAClB,KAAK,WAAa,KAClB,KAAK,MAAQ,IACf,CAEQ,oBAA2B,CACjC,MAAMQ,EAAO,KAAK,KAAK,kBAAA,EAEvB,KAAK,OAAS,SAAS,cAAc,KAAK,EAC1C,KAAK,OAAO,UAAY,uBACxB,KAAK,OAAO,MAAM,KAAO,GAAG,KAAK,KAAK,eAAe,CAAC,KACtD,KAAK,OAAO,MAAM,IAAM,GAAG,KAAK,KAAK,eAAe,CAAC,KACrD,KAAK,OAAO,MAAM,MAAQ,GAAG,KAAK,KAAK,eAAe,KAAK,KAC3D,KAAK,OAAO,MAAM,OAAS,GAAG,KAAK,KAAK,eAAe,MAAM,KAC7D,KAAK,OAAO,MAAM,OAAS,OAAO,KAAK,KAAK,OAAO,OAAS,CAAC,EAE7D,KAAK,KAAK,UAAU,KAAK,MAAM,EAC/BA,EAAK,YAAY,KAAK,MAAM,CAC9B,CAEA,YAAmB,CACb,KAAK,SACP,KAAK,OAAO,OAAA,EACZ,KAAK,OAAS,KAElB,CAGA,SAAgB,CACd,KAAK,oBAAoB,KAAA,EACzB,KAAK,mBAAqB,KAC1B,KAAK,uBAAA,EACL,KAAK,WAAA,CACP,CACF,CAGO,MAAM6C,EAASC"}
@@ -0,0 +1,2 @@
1
+ function x(){const e=navigator.userAgent||"";return/iP(hone|ad|od)/.test(e)||navigator.platform==="MacIntel"&&(navigator.maxTouchPoints||0)>1}function C(e,a,r,d,s){const t=e>=a,o=r>=d;return t===o?{width:e,height:a,rotate:0}:{width:a,height:e,rotate:s===270?-90:90}}function F(e,a,r){if(r.rotate===0){e.drawImage(a,0,0,r.width,r.height);return}e.save(),r.rotate===90?(e.translate(r.width,0),e.rotate(Math.PI/2)):(e.translate(0,r.height),e.rotate(-Math.PI/2)),e.drawImage(a,0,0,r.height,r.width),e.restore()}function B(){const e=typeof screen<"u"?screen.orientation:void 0;return e&&typeof e.angle=="number"?e.angle:0}function E(e){return new Promise(a=>{if(e.videoWidth>0){a();return}e.addEventListener("loadedmetadata",()=>a(),{once:!0})})}async function I(e){try{await e.play()}catch{}}async function O(e,a=15){const r=document.createElement("canvas");if(typeof r.captureStream!="function")return null;const d=r.getContext("2d");if(!d)return null;const s=document.createElement("video");s.muted=!0,s.playsInline=!0,s.srcObject=e,await E(s);const t=C(s.videoWidth,s.videoHeight,window.innerWidth,window.innerHeight,B());r.width=t.width,r.height=t.height,await I(s);let o=0;const c=()=>{F(d,s,t),o=requestAnimationFrame(c)};c();const n=r.captureStream(a);return{stream:n,stop:()=>{o&&cancelAnimationFrame(o),o=0,n.getTracks().forEach(u=>u.stop()),s.pause(),s.srcObject=null}}}function P(e,a,r,d,s){const t=Math.max(0,Math.min(d,e.left*a)),o=Math.max(0,Math.min(s,e.top*r)),c=Math.max(0,Math.min(d,(e.left+e.width)*a)),n=Math.max(0,Math.min(s,(e.top+e.height)*r)),u=c-t,i=n-o;return u<=0||i<=0?null:{x:t,y:o,w:u,h:i}}function L(e,a,r,d,s,t,o){e.drawImage(a,0,0,d,s);const c=d/Math.max(1,window.innerWidth),n=s/Math.max(1,window.innerHeight);for(const u of r){const i=P(u.getBoundingClientRect(),c,n,d,s);i&&(e.save(),o?(e.filter=`blur(${t}px)`,e.drawImage(a,i.x,i.y,i.w,i.h,i.x,i.y,i.w,i.h)):(e.fillStyle="#0b0b0b",e.fillRect(i.x,i.y,i.w,i.h)),e.restore())}}async function j(e,a,r={}){const d=r.frameRate??15,s=r.blurRadius??12,t=document.createElement("canvas");if(typeof t.captureStream!="function")return null;const o=t.getContext("2d");if(!o)return null;const c="filter"in o,n=document.createElement("video");n.muted=!0,n.playsInline=!0,n.srcObject=e,await E(n),t.width=n.videoWidth,t.height=n.videoHeight,await I(n);let u=0;const i=()=>{L(o,n,a,t.width,t.height,s,c),u=requestAnimationFrame(i)};i();const h=t.captureStream(d);return{stream:h,stop:()=>{u&&cancelAnimationFrame(u),u=0,h.getTracks().forEach(p=>p.stop()),n.pause(),n.srcObject=null}}}const k="This browser cannot blur the areas you picked, so the recording was not started.";function V(){return typeof navigator<"u"&&!!navigator.mediaDevices&&typeof navigator.mediaDevices.getDisplayMedia=="function"&&typeof MediaRecorder<"u"}function D(){if(typeof MediaRecorder>"u")return"";const e=["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"];for(const a of e)if(MediaRecorder.isTypeSupported(a))return a;return""}function q(e={}){const a=e.maxDuration??15,r=e.videoBitsPerSecond??8e5,d=e.redactionElements??[],s=e.redactionBlurRadius;let t=null,o=null,c=null,n=null,u=[],i=null,h=null,p=null,R=0,w=null,g=null,S=!1,v=null;function A(){p!==null&&(clearInterval(p),p=null),v!==null&&(clearTimeout(v),v=null),o&&(o.stop(),o=null),c&&(c.stop(),c=null),t&&(t.getTracks().forEach(f=>f.stop()),t=null),n=null,u=[],i=null,h=null,w=null,g=null}function y(){S||(S=!0,n&&n.state!=="inactive"&&n.stop())}return{async start(){S=!1,u=[];const f=D();if(!f)throw new Error("No supported video MIME type found");t=await navigator.mediaDevices.getDisplayMedia({video:{frameRate:15,displaySurface:"browser"},audio:!1,preferCurrentTab:!0,selfBrowserSurface:"include",monitorTypeSurfaces:"exclude",surfaceSwitching:"exclude"});const m=t.getVideoTracks()[0],T=m?.getSettings?.()?.displaySurface;if(T==="monitor"||T==="window")throw t.getTracks().forEach(l=>l.stop()),t=null,new Error("qaid records only the current tab \u2014 please share this tab, not a window or your whole screen.");m&&m.addEventListener("ended",()=>{y()});let b=t;if(x()){const l=await O(t);l&&(o=l,b=l.stream)}if(d.length>0){const l=await j(b,d,{blurRadius:s});if(!l)throw o&&(o.stop(),o=null),t.getTracks().forEach(M=>M.stop()),t=null,new Error(k);c=l,b=l.stream}n=new MediaRecorder(b,{mimeType:f,videoBitsPerSecond:r}),n.ondataavailable=l=>{l.data.size>0&&u.push(l.data)},n.onstop=()=>{const l=new Blob(u,{type:f});w&&w(l),h&&h(l),o&&(o.stop(),o=null),c&&(c.stop(),c=null),t&&t.getTracks().forEach(M=>M.stop())},n.onerror=()=>{g&&g(new Error("MediaRecorder error"))},n.start(1e3),R=Date.now(),p=setInterval(()=>{const l=Math.floor((Date.now()-R)/1e3);i&&i(l)},1e3),v=setTimeout(()=>{y()},a*1e3)},stop(){return new Promise((f,m)=>{w=f,g=m,y()})},onTick(f){i=f},onStop(f){h=f},destroy(){y(),A()}}}export{k as REDACTION_UNAVAILABLE,q as createVideoRecorder,D as getSupportedMimeType,V as isVideoRecordingSupported};
2
+ //# sourceMappingURL=video-BSP4s2te.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"video-Bd_29-rK.js","sources":["../../src/video-orientation.ts","../../src/video-redaction.ts","../../src/video-capture.ts"],"sourcesContent":["/**\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\nexport function 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\nexport async 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 * Live video redaction.\n *\n * Blurs the on-screen bounding boxes of chosen elements while the current tab\n * is recorded. Every frame re-reads each element's `getBoundingClientRect()`,\n * so the blur tracks the content as the page scrolls or reflows — no pixel\n * tracking and no post-recording re-encode. The captured frame is the tab's\n * viewport (video-capture restricts capture to the current tab), so viewport\n * CSS coordinates map onto the frame with a single scale factor.\n *\n * The display stream is drawn to a canvas, the tracked regions are blurred on\n * top, and MediaRecorder records the canvas stream instead of the raw capture —\n * mirroring the iOS orientation pipeline in `video-orientation.ts`.\n */\n\nimport { waitForVideoDimensions, playSilently } from \"./video-orientation\";\n\nexport interface RedactedStream {\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\nexport interface RedactionOptions {\n /** Output frame rate of the redacted stream. Default: 15. */\n frameRate?: number;\n /** Gaussian blur radius in px applied to each region. Default: 12. */\n blurRadius?: number;\n}\n\ninterface Box {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/**\n * Map a viewport rect (CSS px, from `getBoundingClientRect()`) onto the\n * captured frame, clamped to the frame bounds. Returns null when the rect is\n * fully outside the viewport (the element scrolled away) or has no area.\n */\nexport function mapRectToFrame(\n rect: { left: number; top: number; width: number; height: number },\n scaleX: number,\n scaleY: number,\n frameW: number,\n frameH: number\n): Box | null {\n const x = Math.max(0, Math.min(frameW, rect.left * scaleX));\n const y = Math.max(0, Math.min(frameH, rect.top * scaleY));\n const right = Math.max(0, Math.min(frameW, (rect.left + rect.width) * scaleX));\n const bottom = Math.max(0, Math.min(frameH, (rect.top + rect.height) * scaleY));\n const w = right - x;\n const h = bottom - y;\n if (w <= 0 || h <= 0) return null;\n return { x, y, w, h };\n}\n\n/**\n * Draw one frame: the full capture, then each element's live bounding box\n * blurred on top. Exported for unit testing the per-frame logic without a real\n * capture stream. When the 2D context can't apply a blur filter, the region is\n * filled solid instead so sensitive content is still hidden.\n */\nexport function drawRedactedFrame(\n ctx: CanvasRenderingContext2D,\n video: CanvasImageSource,\n elements: Element[],\n frameW: number,\n frameH: number,\n blurRadius: number,\n supportsFilter: boolean\n): void {\n ctx.drawImage(video, 0, 0, frameW, frameH);\n\n // The current-tab capture is the viewport, so this scale is ~devicePixelRatio;\n // deriving it live also absorbs viewport resizes mid-recording.\n const scaleX = frameW / Math.max(1, window.innerWidth);\n const scaleY = frameH / Math.max(1, window.innerHeight);\n\n for (const el of elements) {\n const box = mapRectToFrame(\n el.getBoundingClientRect(),\n scaleX,\n scaleY,\n frameW,\n frameH\n );\n if (!box) continue; // scrolled out of view\n\n ctx.save();\n if (supportsFilter) {\n ctx.filter = `blur(${blurRadius}px)`;\n // Re-sample just this region from the live frame so the blur source is\n // the region itself.\n ctx.drawImage(video, box.x, box.y, box.w, box.h, box.x, box.y, box.w, box.h);\n } else {\n // No canvas filter support — hide the region with a solid fill.\n ctx.fillStyle = \"#0b0b0b\";\n ctx.fillRect(box.x, box.y, box.w, box.h);\n }\n ctx.restore();\n }\n}\n\n/**\n * Build a canvas-backed copy of a display-capture stream that blurs the live\n * bounding boxes of `elements`. Returns null when the browser can't support the\n * canvas pipeline (no `captureStream` / 2D context), in which case the caller\n * should record the original stream unredacted.\n */\nexport async function buildRedactedStream(\n displayStream: MediaStream,\n elements: Element[],\n options: RedactionOptions = {}\n): Promise<RedactedStream | null> {\n const frameRate = options.frameRate ?? 15;\n const blurRadius = options.blurRadius ?? 12;\n\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 // Feature-detect canvas blur; fall back to solid fill where unsupported.\n const supportsFilter = \"filter\" in ctx;\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 canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n\n await playSilently(video);\n\n let rafId = 0;\n const draw = (): void => {\n drawRedactedFrame(\n ctx,\n video,\n elements,\n canvas.width,\n canvas.height,\n blurRadius,\n supportsFilter\n );\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\";\nimport { buildRedactedStream, type RedactedStream } from \"./video-redaction\";\n\n/**\n * Thrown by `start()` when areas were picked for redaction but this browser\n * cannot run the canvas pipeline that blurs them. The recording is refused\n * rather than made without the blur.\n */\nexport const REDACTION_UNAVAILABLE =\n \"This browser cannot blur the areas you picked, so the recording was not started.\";\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 * Elements whose live bounding boxes are blurred out of the recording. The\n * blur tracks each element as the page scrolls. Empty/omitted = no redaction.\n */\n redactionElements?: Element[];\n /** Blur radius in px for redacted regions. Default: 12. */\n redactionBlurRadius?: 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 const redactionElements = options.redactionElements ?? [];\n const redactionBlurRadius = options.redactionBlurRadius;\n\n let stream: MediaStream | null = null;\n let orientationCorrection: OrientationCorrectedStream | null = null;\n let redaction: RedactedStream | 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 (redaction) {\n redaction.stop();\n redaction = 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, restricted to the current tab (the page the\n // embed is running on). `preferCurrentTab` collapses the Chromium picker\n // to a single \"share this tab\" choice; the other hints drop window and\n // whole-screen options where the browser honours them. These keys are\n // not in the DOM types yet.\n stream = await navigator.mediaDevices.getDisplayMedia({\n video: {\n frameRate: 15,\n displaySurface: \"browser\",\n },\n audio: false,\n // @ts-expect-error preferCurrentTab is not in the TS types yet\n preferCurrentTab: true,\n selfBrowserSurface: \"include\",\n monitorTypeSurfaces: \"exclude\",\n surfaceSwitching: \"exclude\",\n });\n\n // Enforce tab-only capture. In browsers that ignore the hints above and\n // still let the user share a window or the whole screen, reject it — qaid\n // records only the tab it is embedded in, never other windows or the\n // desktop.\n const videoTrack = stream.getVideoTracks()[0];\n const surface = videoTrack?.getSettings?.()?.displaySurface;\n if (surface === \"monitor\" || surface === \"window\") {\n stream.getTracks().forEach((t) => t.stop());\n stream = null;\n throw new Error(\n \"qaid records only the current tab — please share this tab, not a window or your whole screen.\",\n );\n }\n\n // Handle browser \"Stop sharing\" button\n if (videoTrack) {\n videoTrack.addEventListener(\"ended\", () => {\n finishRecording();\n });\n }\n\n // Route the raw capture through canvas pipelines when needed. On\n // iOS/iPadOS the captured file is rotated by the OS, so first re-encode\n // the live frames upright (falling back to the raw stream if the canvas\n // pipeline isn't available). Then, if the user marked regions to redact,\n // blur their live bounding boxes into whatever the first step produced.\n //\n // Redaction used to sit in an `else` of the iOS branch, so on an iPhone\n // or iPad the picker drew its outlines and the recording went out\n // unblurred. The upright frame matches the viewport, which is what the\n // redaction mapping assumes, so the two chain cleanly.\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 if (redactionElements.length > 0) {\n const redacted = await buildRedactedStream(recordStream, redactionElements, {\n blurRadius: redactionBlurRadius,\n });\n if (!redacted) {\n // The visitor was promised a blur. Recording the areas in the clear\n // would break that promise, so refuse to record instead.\n if (orientationCorrection) {\n orientationCorrection.stop();\n orientationCorrection = null;\n }\n stream.getTracks().forEach((t) => t.stop());\n stream = null;\n throw new Error(REDACTION_UNAVAILABLE);\n }\n redaction = redacted;\n recordStream = redacted.stream;\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 orientation / redaction) and the\n // display stream tracks.\n if (orientationCorrection) {\n orientationCorrection.stop();\n orientationCorrection = null;\n }\n if (redaction) {\n redaction.stop();\n redaction = 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"],"names":["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","mapRectToFrame","rect","scaleX","scaleY","x","y","right","bottom","w","h","drawRedactedFrame","elements","blurRadius","supportsFilter","el","box","buildRedactedStream","options","REDACTION_UNAVAILABLE","isVideoRecordingSupported","getSupportedMimeType","candidates","type","createVideoRecorder","maxDuration","videoBitsPerSecond","redactionElements","redactionBlurRadius","orientationCorrection","redaction","recorder","chunks","tickCallback","stopCallback","tickInterval","startTime","resolveStop","rejectStop","stopped","autoStopTimeout","cleanup","finishRecording","mimeType","videoTrack","surface","recordStream","corrected","redacted","e","blob","elapsed","reject","callback"],"mappings":"AAkCO,SAASA,IAAuB;AACrC,QAAMC,IAAK,UAAU,aAAa;AAClC,SACE,iBAAiB,KAAKA,CAAE;AAAA,EAEvB,UAAU,aAAa,eAAe,UAAU,kBAAkB,KAAK;AAE5E;AASO,SAASC,EACdC,GACAC,GACAC,GACAC,GACAC,GACsB;AACtB,QAAMC,IAAiBL,KAAUC,GAC3BK,IAAoBJ,KAAaC;AAEvC,SAAIE,MAAmBC,IACd,EAAE,OAAON,GAAQ,QAAQC,GAAQ,QAAQ,EAAA,IAK3C,EAAE,OAAOA,GAAQ,QAAQD,GAAQ,QADfI,MAAgB,MAAM,MAAM,GACb;AAC1C;AAGO,SAASG,EACdC,GACAC,GACAC,GACM;AACN,MAAIA,EAAE,WAAW,GAAG;AAClB,IAAAF,EAAI,UAAUC,GAAQ,GAAG,GAAGC,EAAE,OAAOA,EAAE,MAAM;AAC7C;AAAA,EACF;AAEA,EAAAF,EAAI,KAAA,GACAE,EAAE,WAAW,MACfF,EAAI,UAAUE,EAAE,OAAO,CAAC,GACxBF,EAAI,OAAO,KAAK,KAAK,CAAC,MAEtBA,EAAI,UAAU,GAAGE,EAAE,MAAM,GACzBF,EAAI,OAAO,CAAC,KAAK,KAAK,CAAC,IAIzBA,EAAI,UAAUC,GAAQ,GAAG,GAAGC,EAAE,QAAQA,EAAE,KAAK,GAC7CF,EAAI,QAAA;AACN;AAEA,SAASG,IAAyB;AAChC,QAAMC,IACJ,OAAO,SAAW,MAAc,OAAO,cAAc;AACvD,SAAOA,KAAe,OAAOA,EAAY,SAAU,WAC/CA,EAAY,QACZ;AACN;AAEO,SAASC,EAAuBC,GAAwC;AAC7E,SAAO,IAAI,QAAc,CAACC,MAAY;AACpC,QAAID,EAAM,aAAa,GAAG;AACxB,MAAAC,EAAA;AACA;AAAA,IACF;AACA,IAAAD,EAAM,iBAAiB,kBAAkB,MAAMC,EAAA,GAAW,EAAE,MAAM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U,KAAA,GACVA,IAAY,OAEV9B,KACFA,EAAO,YAAY,QAAQ,CAACd,MAAMA,EAAE,MAAM;AAAA,MAE9C,GAEA6C,EAAS,UAAU,MAAM;AACvB,QAAIO,KACFA,EAAW,IAAI,MAAM,qBAAqB,CAAC;AAAA,MAE/C,GAEAP,EAAS,MAAM,GAAI,GACnBK,IAAY,KAAK,IAAA,GAGjBD,IAAe,YAAY,MAAM;AAC/B,cAAMgB,IAAU,KAAK,OAAO,KAAK,IAAA,IAAQf,KAAa,GAAI;AAC1D,QAAIH,KACFA,EAAakB,CAAO;AAAA,MAExB,GAAG,GAAI,GAGPX,IAAkB,WAAW,MAAM;AACjC,QAAAE,EAAA;AAAA,MACF,GAAGjB,IAAc,GAAI;AAAA,IACvB;AAAA,IAEA,OAAsB;AACpB,aAAO,IAAI,QAAc,CAAClC,GAAS6D,MAAW;AAC5C,QAAAf,IAAc9C,GACd+C,IAAac,GACbV,EAAA;AAAA,MACF,CAAC;AAAA,IACH;AAAA,IAEA,OAAOW,GAA2C;AAChD,MAAApB,IAAeoB;AAAA,IACjB;AAAA,IAEA,OAAOA,GAA6C;AAClD,MAAAnB,IAAemB;AAAA,IACjB;AAAA,IAEA,UAAgB;AACd,MAAAX,EAAA,GACAD,EAAA;AAAA,IACF;AAAA,EAAA;AAEJ;"}
1
+ {"version":3,"file":"video-BSP4s2te.js","sources":["../../src/video-orientation.ts","../../src/video-redaction.ts","../../src/video-capture.ts"],"sourcesContent":["/**\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\nexport function 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\nexport async 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 * Live video redaction.\n *\n * Blurs the on-screen bounding boxes of chosen elements while the current tab\n * is recorded. Every frame re-reads each element's `getBoundingClientRect()`,\n * so the blur tracks the content as the page scrolls or reflows — no pixel\n * tracking and no post-recording re-encode. The captured frame is the tab's\n * viewport (video-capture restricts capture to the current tab), so viewport\n * CSS coordinates map onto the frame with a single scale factor.\n *\n * The display stream is drawn to a canvas, the tracked regions are blurred on\n * top, and MediaRecorder records the canvas stream instead of the raw capture —\n * mirroring the iOS orientation pipeline in `video-orientation.ts`.\n */\n\nimport { waitForVideoDimensions, playSilently } from \"./video-orientation\";\n\nexport interface RedactedStream {\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\nexport interface RedactionOptions {\n /** Output frame rate of the redacted stream. Default: 15. */\n frameRate?: number;\n /** Gaussian blur radius in px applied to each region. Default: 12. */\n blurRadius?: number;\n}\n\ninterface Box {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/**\n * Map a viewport rect (CSS px, from `getBoundingClientRect()`) onto the\n * captured frame, clamped to the frame bounds. Returns null when the rect is\n * fully outside the viewport (the element scrolled away) or has no area.\n */\nexport function mapRectToFrame(\n rect: { left: number; top: number; width: number; height: number },\n scaleX: number,\n scaleY: number,\n frameW: number,\n frameH: number\n): Box | null {\n const x = Math.max(0, Math.min(frameW, rect.left * scaleX));\n const y = Math.max(0, Math.min(frameH, rect.top * scaleY));\n const right = Math.max(0, Math.min(frameW, (rect.left + rect.width) * scaleX));\n const bottom = Math.max(0, Math.min(frameH, (rect.top + rect.height) * scaleY));\n const w = right - x;\n const h = bottom - y;\n if (w <= 0 || h <= 0) return null;\n return { x, y, w, h };\n}\n\n/**\n * Draw one frame: the full capture, then each element's live bounding box\n * blurred on top. Exported for unit testing the per-frame logic without a real\n * capture stream. When the 2D context can't apply a blur filter, the region is\n * filled solid instead so sensitive content is still hidden.\n */\nexport function drawRedactedFrame(\n ctx: CanvasRenderingContext2D,\n video: CanvasImageSource,\n elements: Element[],\n frameW: number,\n frameH: number,\n blurRadius: number,\n supportsFilter: boolean\n): void {\n ctx.drawImage(video, 0, 0, frameW, frameH);\n\n // The current-tab capture is the viewport, so this scale is ~devicePixelRatio;\n // deriving it live also absorbs viewport resizes mid-recording.\n const scaleX = frameW / Math.max(1, window.innerWidth);\n const scaleY = frameH / Math.max(1, window.innerHeight);\n\n for (const el of elements) {\n const box = mapRectToFrame(\n el.getBoundingClientRect(),\n scaleX,\n scaleY,\n frameW,\n frameH\n );\n if (!box) continue; // scrolled out of view\n\n ctx.save();\n if (supportsFilter) {\n ctx.filter = `blur(${blurRadius}px)`;\n // Re-sample just this region from the live frame so the blur source is\n // the region itself.\n ctx.drawImage(video, box.x, box.y, box.w, box.h, box.x, box.y, box.w, box.h);\n } else {\n // No canvas filter support — hide the region with a solid fill.\n ctx.fillStyle = \"#0b0b0b\";\n ctx.fillRect(box.x, box.y, box.w, box.h);\n }\n ctx.restore();\n }\n}\n\n/**\n * Build a canvas-backed copy of a display-capture stream that blurs the live\n * bounding boxes of `elements`. Returns null when the browser can't support the\n * canvas pipeline (no `captureStream` / 2D context), in which case the caller\n * should record the original stream unredacted.\n */\nexport async function buildRedactedStream(\n displayStream: MediaStream,\n elements: Element[],\n options: RedactionOptions = {}\n): Promise<RedactedStream | null> {\n const frameRate = options.frameRate ?? 15;\n const blurRadius = options.blurRadius ?? 12;\n\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 // Feature-detect canvas blur; fall back to solid fill where unsupported.\n const supportsFilter = \"filter\" in ctx;\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 canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n\n await playSilently(video);\n\n let rafId = 0;\n const draw = (): void => {\n drawRedactedFrame(\n ctx,\n video,\n elements,\n canvas.width,\n canvas.height,\n blurRadius,\n supportsFilter\n );\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\";\nimport { buildRedactedStream, type RedactedStream } from \"./video-redaction\";\n\n/**\n * Thrown by `start()` when areas were picked for redaction but this browser\n * cannot run the canvas pipeline that blurs them. The recording is refused\n * rather than made without the blur.\n */\nexport const REDACTION_UNAVAILABLE =\n \"This browser cannot blur the areas you picked, so the recording was not started.\";\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 * Elements whose live bounding boxes are blurred out of the recording. The\n * blur tracks each element as the page scrolls. Empty/omitted = no redaction.\n */\n redactionElements?: Element[];\n /** Blur radius in px for redacted regions. Default: 12. */\n redactionBlurRadius?: 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 const redactionElements = options.redactionElements ?? [];\n const redactionBlurRadius = options.redactionBlurRadius;\n\n let stream: MediaStream | null = null;\n let orientationCorrection: OrientationCorrectedStream | null = null;\n let redaction: RedactedStream | 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 (redaction) {\n redaction.stop();\n redaction = 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, restricted to the current tab (the page the\n // embed is running on). `preferCurrentTab` collapses the Chromium picker\n // to a single \"share this tab\" choice; the other hints drop window and\n // whole-screen options where the browser honours them. These keys are\n // not in the DOM types yet.\n stream = await navigator.mediaDevices.getDisplayMedia({\n video: {\n frameRate: 15,\n displaySurface: \"browser\",\n },\n audio: false,\n // @ts-expect-error preferCurrentTab is not in the TS types yet\n preferCurrentTab: true,\n selfBrowserSurface: \"include\",\n monitorTypeSurfaces: \"exclude\",\n surfaceSwitching: \"exclude\",\n });\n\n // Enforce tab-only capture. In browsers that ignore the hints above and\n // still let the user share a window or the whole screen, reject it — qaid\n // records only the tab it is embedded in, never other windows or the\n // desktop.\n const videoTrack = stream.getVideoTracks()[0];\n const surface = videoTrack?.getSettings?.()?.displaySurface;\n if (surface === \"monitor\" || surface === \"window\") {\n stream.getTracks().forEach((t) => t.stop());\n stream = null;\n throw new Error(\n \"qaid records only the current tab — please share this tab, not a window or your whole screen.\",\n );\n }\n\n // Handle browser \"Stop sharing\" button\n if (videoTrack) {\n videoTrack.addEventListener(\"ended\", () => {\n finishRecording();\n });\n }\n\n // Route the raw capture through canvas pipelines when needed. On\n // iOS/iPadOS the captured file is rotated by the OS, so first re-encode\n // the live frames upright (falling back to the raw stream if the canvas\n // pipeline isn't available). Then, if the user marked regions to redact,\n // blur their live bounding boxes into whatever the first step produced.\n //\n // Redaction used to sit in an `else` of the iOS branch, so on an iPhone\n // or iPad the picker drew its outlines and the recording went out\n // unblurred. The upright frame matches the viewport, which is what the\n // redaction mapping assumes, so the two chain cleanly.\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 if (redactionElements.length > 0) {\n const redacted = await buildRedactedStream(recordStream, redactionElements, {\n blurRadius: redactionBlurRadius,\n });\n if (!redacted) {\n // The visitor was promised a blur. Recording the areas in the clear\n // would break that promise, so refuse to record instead.\n if (orientationCorrection) {\n orientationCorrection.stop();\n orientationCorrection = null;\n }\n stream.getTracks().forEach((t) => t.stop());\n stream = null;\n throw new Error(REDACTION_UNAVAILABLE);\n }\n redaction = redacted;\n recordStream = redacted.stream;\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 orientation / redaction) and the\n // display stream tracks.\n if (orientationCorrection) {\n orientationCorrection.stop();\n orientationCorrection = null;\n }\n if (redaction) {\n redaction.stop();\n redaction = 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"],"names":["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","mapRectToFrame","rect","scaleX","scaleY","x","y","right","bottom","w","h","drawRedactedFrame","elements","blurRadius","supportsFilter","el","box","buildRedactedStream","options","REDACTION_UNAVAILABLE","isVideoRecordingSupported","getSupportedMimeType","candidates","type","createVideoRecorder","maxDuration","videoBitsPerSecond","redactionElements","redactionBlurRadius","orientationCorrection","redaction","recorder","chunks","tickCallback","stopCallback","tickInterval","startTime","resolveStop","rejectStop","stopped","autoStopTimeout","cleanup","finishRecording","mimeType","videoTrack","surface","recordStream","corrected","redacted","e","blob","elapsed","reject","callback"],"mappings":"AAkCO,SAASA,GAAuB,CACrC,MAAMC,EAAK,UAAU,WAAa,GAClC,MACE,iBAAiB,KAAKA,CAAE,GAEvB,UAAU,WAAa,aAAe,UAAU,gBAAkB,GAAK,CAE5E,CASO,SAASC,EACdC,EACAC,EACAC,EACAC,EACAC,EACsB,CACtB,MAAMC,EAAiBL,GAAUC,EAC3BK,EAAoBJ,GAAaC,EAEvC,OAAIE,IAAmBC,EACd,CAAE,MAAON,EAAQ,OAAQC,EAAQ,OAAQ,CAAA,EAK3C,CAAE,MAAOA,EAAQ,OAAQD,EAAQ,OADfI,IAAgB,IAAM,IAAM,EACb,CAC1C,CAGO,SAASG,EACdC,EACAC,EACAC,EACM,CACN,GAAIA,EAAE,SAAW,EAAG,CAClBF,EAAI,UAAUC,EAAQ,EAAG,EAAGC,EAAE,MAAOA,EAAE,MAAM,EAC7C,MACF,CAEAF,EAAI,KAAA,EACAE,EAAE,SAAW,IACfF,EAAI,UAAUE,EAAE,MAAO,CAAC,EACxBF,EAAI,OAAO,KAAK,GAAK,CAAC,IAEtBA,EAAI,UAAU,EAAGE,EAAE,MAAM,EACzBF,EAAI,OAAO,CA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