@daybook/feedback 1.2.0 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/feedback.js +7 -7
- package/dist/screenshot.d.ts +15 -0
- package/dist/screenshot.js +63 -7
- package/package.json +1 -1
package/dist/feedback.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
"use strict";var DaybookFeedback=(()=>{var C=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var ge=Object.prototype.hasOwnProperty;var be=(n,e)=>{for(var t in e)C(n,t,{get:e[t],enumerable:!0})},ye=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of me(e))!ge.call(n,r)&&r!==t&&C(n,r,{get:()=>e[r],enumerable:!(o=fe(e,r))||o.enumerable});return n};var we=n=>ye(C({},"__esModule",{value:!0}),n);var qe={};be(qe,{DEFAULT_API_URL:()=>ue,DaybookFeedback:()=>A,captureAnchor:()=>_,init:()=>Oe,resolveAnchor:()=>se});function v(n){var e;try{let t=new URL(n,location.href);return t.origin===location.origin?t.pathname:`${t.origin}${t.pathname}`}catch{return(e=n.split("?")[0])!=null?e:n}}function P(n){var o,r,i,s,a,c;let e=n.tagName.toLowerCase();if(!n.getAttribute("aria-label")&&!n.getAttribute("data-testid")&&!((o=n.textContent)!=null?o:"").trim()){let d=n.closest("button, a, [role=button], [data-testid], label");if(d&&d!==n)return P(d)}if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement){let d=(i=(r=n.getAttribute("name"))!=null?r:n.id)!=null?i:"",u=n instanceof HTMLInputElement?n.type:e;return`${e}[${u}]${d?` name=${d}`:""}`}let t=(c=(s=n.getAttribute("aria-label"))!=null?s:n.getAttribute("data-testid"))!=null?c:((a=n.textContent)!=null?a:"").replace(/\s+/g," ").trim().slice(0,40);return t?`${e} "${t}"`:e}function Q(n){return n.replace(/[\w.+-]+@[\w-]+\.[\w.]+/g,"[email]").replace(/\b[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g,"[jwt]").replace(/\bBearer\s+[\w.-]+/gi,"Bearer [redacted]").replace(/\b\d{12,19}\b/g,"[number]").slice(0,500)}var Z="data-daybook-private";var k=class{constructor(e=40,t=!0){this.limit=e;this.redact=t;this.entries=[];this.detach=[]}list(){return[...this.entries]}add(e,t){for(this.entries.push({at:new Date().toISOString(),type:e,message:this.redact?Q(t):t.slice(0,500)});this.entries.length>this.limit;)this.entries.shift()}start(){let e=a=>{let c=a.target;c instanceof Element&&(c.closest("[data-daybook-feedback]")||this.add("click",P(c)))};document.addEventListener("click",e,{capture:!0,passive:!0}),this.detach.push(()=>document.removeEventListener("click",e,{capture:!0}));let t=history.pushState,o=history.replaceState,r=()=>this.add("nav",v(location.href));history.pushState=(...a)=>{t.apply(history,a),r()},history.replaceState=(...a)=>{o.apply(history,a),r()},window.addEventListener("popstate",r),this.detach.push(()=>{history.pushState=t,history.replaceState=o,window.removeEventListener("popstate",r)});for(let a of["error","warn"]){let c=console[a];console[a]=(...d)=>{this.add("console",`${a}: ${d.map(F).join(" ")}`),c.apply(console,d)},this.detach.push(()=>{console[a]=c})}let i=a=>this.add("console",`uncaught: ${a.message}`),s=a=>this.add("console",`unhandled rejection: ${F(a.reason)}`);window.addEventListener("error",i),window.addEventListener("unhandledrejection",s),this.detach.push(()=>{window.removeEventListener("error",i),window.removeEventListener("unhandledrejection",s)}),this.watchFetch()}stop(){for(let e of this.detach.splice(0))e()}watchFetch(){if(typeof window.fetch!="function")return;let e=window.fetch;window.fetch=async(...t)=>{let o=performance.now();try{let r=await e.apply(window,t),i=Math.round(performance.now()-o);return(!r.ok||i>3e3)&&this.add("network",`${r.status} ${v(G(t[0]))} ${i}ms`),r}catch(r){throw this.add("network",`failed ${v(G(t[0]))}: ${F(r)}`),r}},this.detach.push(()=>{window.fetch=e})}};function G(n){return typeof n=="string"?n:n instanceof URL?n.href:n.url}function F(n){var e,t;if(typeof n=="string")return n;if(n instanceof Error)return`${n.name}: ${n.message}`;try{return(t=(e=JSON.stringify(n))==null?void 0:e.slice(0,200))!=null?t:String(n)}catch{return String(n)}}var j="pm.feedback.queue";var T=class{constructor(e,t){this.apiUrl=e;this.ingestKey=t;this.session=null;this.identityToken=null}setSession(e){this.session=e}async send(e,t=[],o){var c,d,u;let r={idempotencyKey:(c=e.idempotencyKey)!=null?c:ee(),...e,attachments:[...(d=e.attachments)!=null?d:[],...t.map(p=>({filename:p.filename,contentType:p.contentType,size:p.blob.size}))]},i=await this.post("/ingest/v1",r);if(!i.ok)throw await E(i);let s=await i.json(),a=((u=e.attachments)!=null?u:[]).length;return await Promise.all(t.map(async(p,m)=>{let g=ve(s,a+m);if(!g){o==null||o(p,new Error("The server would not accept that file."));return}try{await this.upload(g,p)}catch(y){o==null||o(p,y)}})),s}async flush(){let e=ne();if(e.length!==0){oe([]);for(let t of e)try{let o=await this.post("/ingest/v1",t);!o.ok&&(o.status===429||o.status>=500)&&O(t)}catch{O(t)}}}queue(e){var t;O({...e,idempotencyKey:(t=e.idempotencyKey)!=null?t:ee(),attachments:void 0})}async signIn(){let e=te(64),t=await xe(e),o=te(16),r=`${this.base()}/ingest/v1/authorize?key=${encodeURIComponent(this.ingestKey)}&origin=${encodeURIComponent(location.origin)}&code_challenge=${encodeURIComponent(t)}&state=${encodeURIComponent(o)}`,i=window.open(r,"daybook-feedback","width=460,height=640");if(!i)throw Object.assign(new Error("Popup blocked"),{code:"popup_blocked"});let s=await new Promise((d,u)=>{let p=setInterval(()=>{i.closed&&(g(),u(Object.assign(new Error("Sign-in cancelled"),{code:"cancelled"})))},400),m=y=>{if(y.origin!==new URL(this.base()).origin)return;let f=y.data;if((f==null?void 0:f.source)==="daybook-feedback"&&f.state===o){if(g(),f.error||!f.code){u(Object.assign(new Error("Sign-in was refused"),{code:f.error||"refused"}));return}d(f.code)}},g=()=>{clearInterval(p),window.removeEventListener("message",m)};window.addEventListener("message",m)}),a=await this.post("/ingest/v1/token",{code:s,codeVerifier:e});if(!a.ok)throw await E(a);let{identityToken:c}=await a.json();return this.identityToken=c,c}base(){return this.apiUrl.replace(/\/$/,"")}resolve(e){try{let t=new URL(this.base()),o=new URL(e,t);return o.hostname===t.hostname?new URL(o.pathname+o.search,t).toString():o.toString()}catch{return e}}async handshake(e){var r,i;let t=await this.post("/ingest/v1/session",{...e,identityToken:(r=this.identityToken)!=null?r:void 0});if(!t.ok)throw await E(t);let o=await t.json();return this.session=(i=o.sessionToken)!=null?i:null,o}post(e,t){let o={"Content-Type":"application/json","X-Ingest-Key":this.ingestKey};return this.session&&(o["X-Feedback-Session"]=this.session),fetch(`${this.base()}${e}`,{method:"POST",headers:o,body:JSON.stringify(t),credentials:"omit"})}async upload(e,t){let o=await fetch(this.resolve(e.uploadUrl),{method:e.method,headers:{"Content-Type":e.contentType,"X-Ingest-Key":this.ingestKey},body:t.blob,credentials:"omit"});if(!o.ok)throw await E(o);await this.post(`/ingest/v1/attachments/${e.id}/confirm`,{})}};function ve(n,e){let t=n.attachments.find(o=>o.index===e);return t!=null?t:n.attachments.some(o=>typeof o.index=="number")?void 0:n.attachments[e]}function O(n){let e=ne();e.push(n),oe(e.slice(-20))}function ne(){try{let n=localStorage.getItem(j);return n?JSON.parse(n):[]}catch{return[]}}function oe(n){try{n.length===0?localStorage.removeItem(j):localStorage.setItem(j,JSON.stringify(n))}catch{}}async function E(n){let e=`http_${n.status}`;try{let t=await n.json();if(t.code&&(e=t.code),t.message)return Object.assign(new Error(t.message),{code:e})}catch{}return Object.assign(new Error(`Ingest failed (${n.status})`),{code:e})}function ee(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function te(n){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=new Uint8Array(n);return crypto.getRandomValues(t),Array.from(t,o=>e[o%e.length]).join("")}async function xe(n){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function q(n){var t;let e={platform:"web",route:location.pathname,title:document.title.slice(0,200),locale:navigator.language,timezone:Ee(),viewport:{width:window.innerWidth,height:window.innerHeight,dpr:(t=window.devicePixelRatio)!=null?t:1},device:ke()};return document.referrer&&(e.referrer=v(document.referrer)),n.app&&(e.app=n.app),n.anchor&&(e.anchor=n.anchor),n.breadcrumbs&&n.breadcrumbs.length>0&&(e.breadcrumbs=n.breadcrumbs),e}function ke(){var r;let n=navigator.userAgent,e=/Edg\//.test(n)?"Edge":/OPR\//.test(n)?"Opera":/Firefox\//.test(n)?"Firefox":/Chrome\//.test(n)?"Chrome":/Safari\//.test(n)?"Safari":"Unknown",t=/Windows NT/.test(n)?"Windows":/iPhone|iPad|iPod/.test(n)?"iOS":/Mac OS X/.test(n)?"macOS":/Android/.test(n)?"Android":/Linux/.test(n)?"Linux":"Unknown",o=(r=n.match(/(?:Edg|OPR|Firefox|Chrome|Version)\/(\d+)/))==null?void 0:r[1];return{browser:o?`${e} ${o}`:e,os:t,touch:navigator.maxTouchPoints>0,userAgent:n.slice(0,300)}}function Ee(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return`UTC${-new Date().getTimezoneOffset()/60}`}}async function re(n,e=()=>()=>{}){var i;if(typeof((i=navigator.mediaDevices)==null?void 0:i.getDisplayMedia)!="function")return null;let t=n?Le():()=>{},o=e(),r=null;try{if(r=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0,selfBrowserSurface:"include",surfaceSwitching:"exclude",monitorTypeSurfaces:"exclude"}),!r.getVideoTracks()[0])return null;await new Promise(c=>setTimeout(c,250));let a=await Te(r);return a?{blob:a,filename:"screenshot.png",contentType:"image/png"}:null}catch{return null}finally{r==null||r.getTracks().forEach(s=>s.stop()),o(),t()}}async function Te(n){let e=document.createElement("video");e.srcObject=n,e.muted=!0,await e.play().catch(()=>{});let t=document.createElement("canvas");t.width=e.videoWidth||window.innerWidth,t.height=e.videoHeight||window.innerHeight;let o=t.getContext("2d");return o?(o.drawImage(e,0,0,t.width,t.height),e.pause(),e.srcObject=null,new Promise(r=>t.toBlob(i=>r(i),"image/png"))):null}function Le(){let n=[...document.querySelectorAll(`[${Z}]`),...document.querySelectorAll('input[type="password"]')],e=n.map(t=>t.style.filter);return n.forEach(t=>{t.style.filter="blur(12px)"}),()=>{n.forEach((t,o)=>{var r;t.style.filter=(r=e[o])!=null?r:""})}}function _(n,e){let t=document.elementFromPoint(n,e);if(!(t instanceof HTMLElement))return{selector:null,offsetX:S(n/window.innerWidth),offsetY:S(e/window.innerHeight),elementText:null};let o=t.getBoundingClientRect();return{selector:Se(t),offsetX:o.width>0?S((n-o.left)/o.width):0,offsetY:o.height>0?S((e-o.top)/o.height):0,elementText:_e(t)}}function se(n){if(!n.selector)return{x:n.offsetX*window.innerWidth,y:n.offsetY*window.innerHeight};let e=null;try{e=document.querySelector(n.selector)}catch{return null}if(!e)return null;let t=e.getBoundingClientRect();return{x:t.left+n.offsetX*t.width,y:t.top+n.offsetY*t.height}}function Se(n){if(n===document.body)return"body";for(let r of["data-testid","data-test","data-daybook-id","data-cy"]){let i=n.getAttribute(r);if(i){let s=`[${r}="${U(i)}"]`;if(L(s))return s}}if(n.id&&!ie(n.id)){let r=`#${U(n.id)}`;if(L(r))return r}let e=[],t=n;for(;t&&t!==document.body&&e.length<8;){let r=t.tagName.toLowerCase(),i=Array.from(t.classList).filter(c=>!ie(c)).slice(0,2);i.length>0&&(r+=i.map(c=>`.${U(c)}`).join(""));let s=t.parentElement;if(s){let c=Array.from(s.children).filter(d=>d.tagName===t.tagName);c.length>1&&(r+=`:nth-of-type(${c.indexOf(t)+1})`)}e.unshift(r);let a=e.join(" > ");if(L(a))return a;t=s}let o=e.length>0?`body > ${e.join(" > ")}`:null;return o&&L(o)?o:null}function L(n){try{return document.querySelectorAll(n).length===1}catch{return!1}}function ie(n){return/^[a-z]{1,3}[0-9a-f]{5,}$/i.test(n)||/--[0-9a-f]{5,}$/i.test(n)||/^_[0-9a-z]{5,}/i.test(n)||/^v-[0-9a-f]{6,}$/i.test(n)||/^ng-/.test(n)||/[0-9a-f]{8,}/i.test(n)}function _e(n){var o,r,i;let t=((r=(o=n.innerText)!=null?o:n.textContent)!=null?r:"").replace(/\s+/g," ").trim();if(!t){let s=(i=n.getAttribute("aria-label"))!=null?i:n.getAttribute("title");return(s==null?void 0:s.trim())||null}return t.length>80?`${t.slice(0,77)}\u2026`:t}function S(n){return Number.isFinite(n)?Math.max(0,Math.min(1,n)):0}function U(n){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(n):n.replace(/([^\w-])/g,"\\$1")}var Re=/^(image\/(png|jpeg|gif|webp)|video\/(mp4|quicktime|webm))$/;function ae(n,e){let t=[];for(let o of n){if(e+t.length>=5)break;let r=Re.test(o.type)?o.size>26214400?`Too large (${(o.size/1048576).toFixed(1)} MB, max 25).`:null:"Only images and short videos.";t.push({blob:o,filename:o.name||`pasted-${t.length+1}.${$e(o.type)}`,contentType:o.type,preview:r?null:URL.createObjectURL(o),error:r})}return t}function ce(n){var o;let e=(o=n.clipboardData)==null?void 0:o.items;if(!e)return[];let t=[];for(let r of e){if(r.kind!=="file")continue;let i=r.getAsFile();i&&t.push(i)}return t}function R(n){for(let e of n)e.preview&&URL.revokeObjectURL(e.preview)}function $e(n){var e,t;return(t=(e=n.split("/")[1])==null?void 0:e.replace("quicktime","mov"))!=null?t:"bin"}function le(n){var o;let t=(o=(typeof n.composedPath=="function"?n.composedPath():[])[0])!=null?o:n.target;return!t||t.nodeType!==1?!1:/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)?!0:typeof t.closest=="function"&&t.closest('[contenteditable=""], [contenteditable="true"]')!==null}var M=class{constructor(e,t){this.options=e;this.onSubmit=t;this.mode="idle";this.anchor=null;this.detach=[];this.state="ready";this.policy=null;this.placement=Ie();this.reference=null;this.uploadsFailed=0;this.host=document.createElement("div"),this.host.setAttribute("data-daybook-feedback",""),this.host.style.cssText="position:fixed;inset:0;z-index:2147483000;pointer-events:none",this.root=this.host.attachShadow({mode:"open"}),this.root.innerHTML=`<style>${Fe}</style><style id="theme"></style><div id="layer"></div>`}setTheme(e){var s,a;let t=this.root.getElementById("theme");if(!t)return;if(!e){t.textContent="";return}let o=[];Pe(e.accent)&&o.push(`--pm-accent: ${e.accent}`);let r={none:"0",sm:"6px",md:"12px",lg:"18px"}[(s=e.cornerRadius)!=null?s:"md"];r&&o.push(`--pm-radius: ${r}`);let i=Ce[(a=e.position)!=null?a:"bottom-right"];i&&o.push(i),t.textContent=o.length>0?`:host { ${o.join("; ")} }`:"",this.launcherLabel=typeof e.launcherLabel=="string"&&e.launcherLabel.length>0?e.launcherLabel.slice(0,24):void 0}setState(e){this.state=e,this.host.isConnected&&this.render()}mount(){var e;if(document.body.appendChild(this.host),this.render(),this.options.hotkey!==null){let t=((e=this.options.hotkey)!=null?e:"f").toLowerCase(),o=r=>{if(r.key==="Escape"){this.mode==="picking"&&(this.mode="idle",this.anchor=null,this.render());return}r.metaKey||r.ctrlKey||r.altKey||le(r)||this.mode!=="composing"&&r.key.toLowerCase()===t&&(this.mode=this.mode==="picking"?"idle":"picking",this.render())};window.addEventListener("keydown",o),this.detach.push(()=>window.removeEventListener("keydown",o))}}unmount(){for(let e of this.detach.splice(0))e();this.host.remove()}open(){this.mode="picking",this.render()}setReporter(e){this.reporter=e}setPolicy(e){this.policy=e}capture(){var t,o;let e=(t=this.options.screenshots)!=null?t:!0;return e===!1||((o=this.policy)==null?void 0:o.screenshots)===!1?{offered:!1,checked:!1}:{offered:!0,checked:e!=="optional"}}conceal(){let e=this.host.style.visibility;return this.host.style.visibility="hidden",()=>{this.host.style.visibility=e}}movable(e,t){this.place(e),t.classList.add("drag"),t.title="Drag to move \xB7 double-click to reset",t.addEventListener("dblclick",()=>{this.placement=null,pe(null),this.place(e)}),t.addEventListener("pointerdown",o=>{if(o.target.closest("button")||o.button!==0)return;o.preventDefault();let r=e.getBoundingClientRect(),i=o.clientX-r.left,s=o.clientY-r.top;t.setPointerCapture(o.pointerId),e.classList.add("panel--dragging");let a=d=>{let u=$(d.clientX-i,w-r.width+z,window.innerWidth-z),p=$(d.clientY-s,0,window.innerHeight-z);e.style.left=`${u}px`,e.style.top=`${p}px`,e.style.right="auto",e.style.bottom="auto"},c=()=>{t.releasePointerCapture(o.pointerId),t.removeEventListener("pointermove",a),t.removeEventListener("pointerup",c),t.removeEventListener("pointercancel",c),e.classList.remove("panel--dragging"),this.placement=He(e.getBoundingClientRect()),pe(this.placement),this.place(e)};t.addEventListener("pointermove",a),t.addEventListener("pointerup",c),t.addEventListener("pointercancel",c)})}place(e){let t=this.placement;if(!t){e.style.left=e.style.right=e.style.top=e.style.bottom="";return}let o=e.offsetWidth||380,r=e.offsetHeight||240,i=$(t.dx,w,Math.max(w,window.innerWidth-o-w)),s=$(t.dy,w,Math.max(w,window.innerHeight-r-w));e.style.left=t.h==="left"?`${i}px`:"auto",e.style.right=t.h==="right"?`${i}px`:"auto",e.style.top=t.v==="top"?`${s}px`:"auto",e.style.bottom=t.v==="bottom"?`${s}px`:"auto"}render(){let e=this.root.getElementById("layer");if(e.innerHTML="",this.mode==="idle"){e.appendChild(this.state==="pending"?this.pending():this.launcher());return}if(this.mode==="sent"){let o=this.sent();e.appendChild(o),this.place(o);return}if(this.mode==="picking"){e.appendChild(this.picker());return}let t=this.composer();e.appendChild(t),this.place(t)}pending(){let e=document.createElement("div");return e.className="launcher launcher--pending",e.setAttribute("role","status"),e.textContent="Feedback access pending approval",e}sent(){var c;let e=document.createElement("div");e.className="panel panel--sent",e.setAttribute("role","status");let t=this.reference,o=this.uploadsFailed;e.innerHTML=`
|
|
1
|
+
"use strict";var DaybookFeedback=(()=>{var C=Object.defineProperty;var ge=Object.getOwnPropertyDescriptor;var be=Object.getOwnPropertyNames;var ye=Object.prototype.hasOwnProperty;var we=(n,e)=>{for(var t in e)C(n,t,{get:e[t],enumerable:!0})},ve=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of be(e))!ye.call(n,r)&&r!==t&&C(n,r,{get:()=>e[r],enumerable:!(o=ge(e,r))||o.enumerable});return n};var xe=n=>ve(C({},"__esModule",{value:!0}),n);var Ne={};we(Ne,{DEFAULT_API_URL:()=>me,DaybookFeedback:()=>A,captureAnchor:()=>_,init:()=>ze,resolveAnchor:()=>ce});function v(n){var e;try{let t=new URL(n,location.href);return t.origin===location.origin?t.pathname:`${t.origin}${t.pathname}`}catch{return(e=n.split("?")[0])!=null?e:n}}function P(n){var o,r,i,s,a,c;let e=n.tagName.toLowerCase();if(!n.getAttribute("aria-label")&&!n.getAttribute("data-testid")&&!((o=n.textContent)!=null?o:"").trim()){let l=n.closest("button, a, [role=button], [data-testid], label");if(l&&l!==n)return P(l)}if(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement||n instanceof HTMLSelectElement){let l=(i=(r=n.getAttribute("name"))!=null?r:n.id)!=null?i:"",u=n instanceof HTMLInputElement?n.type:e;return`${e}[${u}]${l?` name=${l}`:""}`}let t=(c=(s=n.getAttribute("aria-label"))!=null?s:n.getAttribute("data-testid"))!=null?c:((a=n.textContent)!=null?a:"").replace(/\s+/g," ").trim().slice(0,40);return t?`${e} "${t}"`:e}function Q(n){return n.replace(/[\w.+-]+@[\w-]+\.[\w.]+/g,"[email]").replace(/\b[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g,"[jwt]").replace(/\bBearer\s+[\w.-]+/gi,"Bearer [redacted]").replace(/\b\d{12,19}\b/g,"[number]").slice(0,500)}var Z="data-daybook-private";var k=class{constructor(e=40,t=!0){this.limit=e;this.redact=t;this.entries=[];this.detach=[]}list(){return[...this.entries]}add(e,t){for(this.entries.push({at:new Date().toISOString(),type:e,message:this.redact?Q(t):t.slice(0,500)});this.entries.length>this.limit;)this.entries.shift()}start(){let e=a=>{let c=a.target;c instanceof Element&&(c.closest("[data-daybook-feedback]")||this.add("click",P(c)))};document.addEventListener("click",e,{capture:!0,passive:!0}),this.detach.push(()=>document.removeEventListener("click",e,{capture:!0}));let t=history.pushState,o=history.replaceState,r=()=>this.add("nav",v(location.href));history.pushState=(...a)=>{t.apply(history,a),r()},history.replaceState=(...a)=>{o.apply(history,a),r()},window.addEventListener("popstate",r),this.detach.push(()=>{history.pushState=t,history.replaceState=o,window.removeEventListener("popstate",r)});for(let a of["error","warn"]){let c=console[a];console[a]=(...l)=>{this.add("console",`${a}: ${l.map(F).join(" ")}`),c.apply(console,l)},this.detach.push(()=>{console[a]=c})}let i=a=>this.add("console",`uncaught: ${a.message}`),s=a=>this.add("console",`unhandled rejection: ${F(a.reason)}`);window.addEventListener("error",i),window.addEventListener("unhandledrejection",s),this.detach.push(()=>{window.removeEventListener("error",i),window.removeEventListener("unhandledrejection",s)}),this.watchFetch()}stop(){for(let e of this.detach.splice(0))e()}watchFetch(){if(typeof window.fetch!="function")return;let e=window.fetch;window.fetch=async(...t)=>{let o=performance.now();try{let r=await e.apply(window,t),i=Math.round(performance.now()-o);return(!r.ok||i>3e3)&&this.add("network",`${r.status} ${v(G(t[0]))} ${i}ms`),r}catch(r){throw this.add("network",`failed ${v(G(t[0]))}: ${F(r)}`),r}},this.detach.push(()=>{window.fetch=e})}};function G(n){return typeof n=="string"?n:n instanceof URL?n.href:n.url}function F(n){var e,t;if(typeof n=="string")return n;if(n instanceof Error)return`${n.name}: ${n.message}`;try{return(t=(e=JSON.stringify(n))==null?void 0:e.slice(0,200))!=null?t:String(n)}catch{return String(n)}}var j="pm.feedback.queue";var T=class{constructor(e,t){this.apiUrl=e;this.ingestKey=t;this.session=null;this.identityToken=null}setSession(e){this.session=e}async send(e,t=[],o){var c,l,u;let r={idempotencyKey:(c=e.idempotencyKey)!=null?c:ee(),...e,attachments:[...(l=e.attachments)!=null?l:[],...t.map(p=>({filename:p.filename,contentType:p.contentType,size:p.blob.size}))]},i=await this.post("/ingest/v1",r);if(!i.ok)throw await E(i);let s=await i.json(),a=((u=e.attachments)!=null?u:[]).length;return await Promise.all(t.map(async(p,m)=>{let g=ke(s,a+m);if(!g){o==null||o(p,new Error("The server would not accept that file."));return}try{await this.upload(g,p)}catch(y){o==null||o(p,y)}})),s}async flush(){let e=ne();if(e.length!==0){oe([]);for(let t of e)try{let o=await this.post("/ingest/v1",t);!o.ok&&(o.status===429||o.status>=500)&&O(t)}catch{O(t)}}}queue(e){var t;O({...e,idempotencyKey:(t=e.idempotencyKey)!=null?t:ee(),attachments:void 0})}async signIn(){let e=te(64),t=await Ee(e),o=te(16),r=`${this.base()}/ingest/v1/authorize?key=${encodeURIComponent(this.ingestKey)}&origin=${encodeURIComponent(location.origin)}&code_challenge=${encodeURIComponent(t)}&state=${encodeURIComponent(o)}`,i=window.open(r,"daybook-feedback","width=460,height=640");if(!i)throw Object.assign(new Error("Popup blocked"),{code:"popup_blocked"});let s=await new Promise((l,u)=>{let p=setInterval(()=>{i.closed&&(g(),u(Object.assign(new Error("Sign-in cancelled"),{code:"cancelled"})))},400),m=y=>{if(y.origin!==new URL(this.base()).origin)return;let f=y.data;if((f==null?void 0:f.source)==="daybook-feedback"&&f.state===o){if(g(),f.error||!f.code){u(Object.assign(new Error("Sign-in was refused"),{code:f.error||"refused"}));return}l(f.code)}},g=()=>{clearInterval(p),window.removeEventListener("message",m)};window.addEventListener("message",m)}),a=await this.post("/ingest/v1/token",{code:s,codeVerifier:e});if(!a.ok)throw await E(a);let{identityToken:c}=await a.json();return this.identityToken=c,c}base(){return this.apiUrl.replace(/\/$/,"")}resolve(e){try{let t=new URL(this.base()),o=new URL(e,t);return o.hostname===t.hostname?new URL(o.pathname+o.search,t).toString():o.toString()}catch{return e}}async handshake(e){var r,i;let t=await this.post("/ingest/v1/session",{...e,identityToken:(r=this.identityToken)!=null?r:void 0});if(!t.ok)throw await E(t);let o=await t.json();return this.session=(i=o.sessionToken)!=null?i:null,o}post(e,t){let o={"Content-Type":"application/json","X-Ingest-Key":this.ingestKey};return this.session&&(o["X-Feedback-Session"]=this.session),fetch(`${this.base()}${e}`,{method:"POST",headers:o,body:JSON.stringify(t),credentials:"omit"})}async upload(e,t){let o=await fetch(this.resolve(e.uploadUrl),{method:e.method,headers:{"Content-Type":e.contentType,"X-Ingest-Key":this.ingestKey},body:t.blob,credentials:"omit"});if(!o.ok)throw await E(o);await this.post(`/ingest/v1/attachments/${e.id}/confirm`,{})}};function ke(n,e){let t=n.attachments.find(o=>o.index===e);return t!=null?t:n.attachments.some(o=>typeof o.index=="number")?void 0:n.attachments[e]}function O(n){let e=ne();e.push(n),oe(e.slice(-20))}function ne(){try{let n=localStorage.getItem(j);return n?JSON.parse(n):[]}catch{return[]}}function oe(n){try{n.length===0?localStorage.removeItem(j):localStorage.setItem(j,JSON.stringify(n))}catch{}}async function E(n){let e=`http_${n.status}`;try{let t=await n.json();if(t.code&&(e=t.code),t.message)return Object.assign(new Error(t.message),{code:e})}catch{}return Object.assign(new Error(`Ingest failed (${n.status})`),{code:e})}function ee(){return typeof crypto!="undefined"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function te(n){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=new Uint8Array(n);return crypto.getRandomValues(t),Array.from(t,o=>e[o%e.length]).join("")}async function Ee(n){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function q(n){var t;let e={platform:"web",route:location.pathname,title:document.title.slice(0,200),locale:navigator.language,timezone:Le(),viewport:{width:window.innerWidth,height:window.innerHeight,dpr:(t=window.devicePixelRatio)!=null?t:1},device:Te()};return document.referrer&&(e.referrer=v(document.referrer)),n.app&&(e.app=n.app),n.anchor&&(e.anchor=n.anchor),n.breadcrumbs&&n.breadcrumbs.length>0&&(e.breadcrumbs=n.breadcrumbs),e}function Te(){var r;let n=navigator.userAgent,e=/Edg\//.test(n)?"Edge":/OPR\//.test(n)?"Opera":/Firefox\//.test(n)?"Firefox":/Chrome\//.test(n)?"Chrome":/Safari\//.test(n)?"Safari":"Unknown",t=/Windows NT/.test(n)?"Windows":/iPhone|iPad|iPod/.test(n)?"iOS":/Mac OS X/.test(n)?"macOS":/Android/.test(n)?"Android":/Linux/.test(n)?"Linux":"Unknown",o=(r=n.match(/(?:Edg|OPR|Firefox|Chrome|Version)\/(\d+)/))==null?void 0:r[1];return{browser:o?`${e} ${o}`:e,os:t,touch:navigator.maxTouchPoints>0,userAgent:n.slice(0,300)}}function Le(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return`UTC${-new Date().getTimezoneOffset()/60}`}}async function se(n,e=()=>()=>{}){var i;if(typeof((i=navigator.mediaDevices)==null?void 0:i.getDisplayMedia)!="function")return null;let t=n?Re():()=>{},o=e(),r=null;try{return r=await navigator.mediaDevices.getDisplayMedia({video:!0,audio:!1,preferCurrentTab:!0,selfBrowserSurface:"include",surfaceSwitching:"exclude",monitorTypeSurfaces:"exclude"}),r.getVideoTracks()[0]?(await new Promise(a=>setTimeout(a,250)),await _e(r)):null}catch{return null}finally{r==null||r.getTracks().forEach(s=>s.stop()),o(),t()}}var re=1920,Se=.82;async function _e(n){let e=document.createElement("video");e.srcObject=n,e.muted=!0,await e.play().catch(()=>{});let t=e.videoWidth||window.innerWidth,o=e.videoHeight||window.innerHeight,r=t>re?re/t:1,i=document.createElement("canvas");i.width=Math.round(t*r),i.height=Math.round(o*r);let s=i.getContext("2d");if(!s)return null;s.imageSmoothingQuality="high",s.drawImage(e,0,0,i.width,i.height),e.pause(),e.srcObject=null;let a=await $e(i);if(!a)return null;let c=a.type||"image/png";return{blob:a,filename:`screenshot.${c==="image/webp"?"webp":c==="image/jpeg"?"jpg":"png"}`,contentType:c}}async function $e(n){for(let e of["image/webp","image/jpeg"]){let t=await ie(n,e,Se);if((t==null?void 0:t.type)===e)return t}return ie(n,"image/png")}function ie(n,e,t){return new Promise(o=>n.toBlob(r=>o(r),e,t))}function Re(){let n=[...document.querySelectorAll(`[${Z}]`),...document.querySelectorAll('input[type="password"]')],e=n.map(t=>t.style.filter);return n.forEach(t=>{t.style.filter="blur(12px)"}),()=>{n.forEach((t,o)=>{var r;t.style.filter=(r=e[o])!=null?r:""})}}function _(n,e){let t=document.elementFromPoint(n,e);if(!(t instanceof HTMLElement))return{selector:null,offsetX:S(n/window.innerWidth),offsetY:S(e/window.innerHeight),elementText:null};let o=t.getBoundingClientRect();return{selector:Me(t),offsetX:o.width>0?S((n-o.left)/o.width):0,offsetY:o.height>0?S((e-o.top)/o.height):0,elementText:Ae(t)}}function ce(n){if(!n.selector)return{x:n.offsetX*window.innerWidth,y:n.offsetY*window.innerHeight};let e=null;try{e=document.querySelector(n.selector)}catch{return null}if(!e)return null;let t=e.getBoundingClientRect();return{x:t.left+n.offsetX*t.width,y:t.top+n.offsetY*t.height}}function Me(n){if(n===document.body)return"body";for(let r of["data-testid","data-test","data-daybook-id","data-cy"]){let i=n.getAttribute(r);if(i){let s=`[${r}="${U(i)}"]`;if(L(s))return s}}if(n.id&&!ae(n.id)){let r=`#${U(n.id)}`;if(L(r))return r}let e=[],t=n;for(;t&&t!==document.body&&e.length<8;){let r=t.tagName.toLowerCase(),i=Array.from(t.classList).filter(c=>!ae(c)).slice(0,2);i.length>0&&(r+=i.map(c=>`.${U(c)}`).join(""));let s=t.parentElement;if(s){let c=Array.from(s.children).filter(l=>l.tagName===t.tagName);c.length>1&&(r+=`:nth-of-type(${c.indexOf(t)+1})`)}e.unshift(r);let a=e.join(" > ");if(L(a))return a;t=s}let o=e.length>0?`body > ${e.join(" > ")}`:null;return o&&L(o)?o:null}function L(n){try{return document.querySelectorAll(n).length===1}catch{return!1}}function ae(n){return/^[a-z]{1,3}[0-9a-f]{5,}$/i.test(n)||/--[0-9a-f]{5,}$/i.test(n)||/^_[0-9a-z]{5,}/i.test(n)||/^v-[0-9a-f]{6,}$/i.test(n)||/^ng-/.test(n)||/[0-9a-f]{8,}/i.test(n)}function Ae(n){var o,r,i;let t=((r=(o=n.innerText)!=null?o:n.textContent)!=null?r:"").replace(/\s+/g," ").trim();if(!t){let s=(i=n.getAttribute("aria-label"))!=null?i:n.getAttribute("title");return(s==null?void 0:s.trim())||null}return t.length>80?`${t.slice(0,77)}\u2026`:t}function S(n){return Number.isFinite(n)?Math.max(0,Math.min(1,n)):0}function U(n){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(n):n.replace(/([^\w-])/g,"\\$1")}var He=/^(image\/(png|jpeg|gif|webp)|video\/(mp4|quicktime|webm))$/;function le(n,e){let t=[];for(let o of n){if(e+t.length>=5)break;let r=He.test(o.type)?o.size>26214400?`Too large (${(o.size/1048576).toFixed(1)} MB, max 25).`:null:"Only images and short videos.";t.push({blob:o,filename:o.name||`pasted-${t.length+1}.${Ie(o.type)}`,contentType:o.type,preview:r?null:URL.createObjectURL(o),error:r})}return t}function de(n){var o;let e=(o=n.clipboardData)==null?void 0:o.items;if(!e)return[];let t=[];for(let r of e){if(r.kind!=="file")continue;let i=r.getAsFile();i&&t.push(i)}return t}function $(n){for(let e of n)e.preview&&URL.revokeObjectURL(e.preview)}function Ie(n){var e,t;return(t=(e=n.split("/")[1])==null?void 0:e.replace("quicktime","mov"))!=null?t:"bin"}function pe(n){var o;let t=(o=(typeof n.composedPath=="function"?n.composedPath():[])[0])!=null?o:n.target;return!t||t.nodeType!==1?!1:/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)?!0:typeof t.closest=="function"&&t.closest('[contenteditable=""], [contenteditable="true"]')!==null}var M=class{constructor(e,t){this.options=e;this.onSubmit=t;this.mode="idle";this.anchor=null;this.detach=[];this.state="ready";this.policy=null;this.placement=Oe();this.reference=null;this.uploadsFailed=0;this.host=document.createElement("div"),this.host.setAttribute("data-daybook-feedback",""),this.host.style.cssText="position:fixed;inset:0;z-index:2147483000;pointer-events:none",this.root=this.host.attachShadow({mode:"open"}),this.root.innerHTML=`<style>${Ue}</style><style id="theme"></style><div id="layer"></div>`}setTheme(e){var s,a;let t=this.root.getElementById("theme");if(!t)return;if(!e){t.textContent="";return}let o=[];qe(e.accent)&&o.push(`--pm-accent: ${e.accent}`);let r={none:"0",sm:"6px",md:"12px",lg:"18px"}[(s=e.cornerRadius)!=null?s:"md"];r&&o.push(`--pm-radius: ${r}`);let i=je[(a=e.position)!=null?a:"bottom-right"];i&&o.push(i),t.textContent=o.length>0?`:host { ${o.join("; ")} }`:"",this.launcherLabel=typeof e.launcherLabel=="string"&&e.launcherLabel.length>0?e.launcherLabel.slice(0,24):void 0}setState(e){this.state=e,this.host.isConnected&&this.render()}mount(){var e;if(document.body.appendChild(this.host),this.render(),this.options.hotkey!==null){let t=((e=this.options.hotkey)!=null?e:"f").toLowerCase(),o=r=>{if(r.key==="Escape"){this.mode==="picking"&&(this.mode="idle",this.anchor=null,this.render());return}r.metaKey||r.ctrlKey||r.altKey||pe(r)||this.mode!=="composing"&&r.key.toLowerCase()===t&&(this.mode=this.mode==="picking"?"idle":"picking",this.render())};window.addEventListener("keydown",o),this.detach.push(()=>window.removeEventListener("keydown",o))}}unmount(){for(let e of this.detach.splice(0))e();this.host.remove()}open(){this.mode="picking",this.render()}setReporter(e){this.reporter=e}setPolicy(e){this.policy=e}capture(){var t,o;let e=(t=this.options.screenshots)!=null?t:!0;return e===!1||((o=this.policy)==null?void 0:o.screenshots)===!1?{offered:!1,checked:!1}:{offered:!0,checked:e!=="optional"}}conceal(){let e=this.host.style.visibility;return this.host.style.visibility="hidden",()=>{this.host.style.visibility=e}}movable(e,t){this.place(e),t.classList.add("drag"),t.title="Drag to move \xB7 double-click to reset",t.addEventListener("dblclick",()=>{this.placement=null,ue(null),this.place(e)}),t.addEventListener("pointerdown",o=>{if(o.target.closest("button")||o.button!==0)return;o.preventDefault();let r=e.getBoundingClientRect(),i=o.clientX-r.left,s=o.clientY-r.top;t.setPointerCapture(o.pointerId),e.classList.add("panel--dragging");let a=l=>{let u=R(l.clientX-i,w-r.width+z,window.innerWidth-z),p=R(l.clientY-s,0,window.innerHeight-z);e.style.left=`${u}px`,e.style.top=`${p}px`,e.style.right="auto",e.style.bottom="auto"},c=()=>{t.releasePointerCapture(o.pointerId),t.removeEventListener("pointermove",a),t.removeEventListener("pointerup",c),t.removeEventListener("pointercancel",c),e.classList.remove("panel--dragging"),this.placement=Fe(e.getBoundingClientRect()),ue(this.placement),this.place(e)};t.addEventListener("pointermove",a),t.addEventListener("pointerup",c),t.addEventListener("pointercancel",c)})}place(e){let t=this.placement;if(!t){e.style.left=e.style.right=e.style.top=e.style.bottom="";return}let o=e.offsetWidth||380,r=e.offsetHeight||240,i=R(t.dx,w,Math.max(w,window.innerWidth-o-w)),s=R(t.dy,w,Math.max(w,window.innerHeight-r-w));e.style.left=t.h==="left"?`${i}px`:"auto",e.style.right=t.h==="right"?`${i}px`:"auto",e.style.top=t.v==="top"?`${s}px`:"auto",e.style.bottom=t.v==="bottom"?`${s}px`:"auto"}render(){let e=this.root.getElementById("layer");if(e.innerHTML="",this.mode==="idle"){e.appendChild(this.state==="pending"?this.pending():this.launcher());return}if(this.mode==="sent"){let o=this.sent();e.appendChild(o),this.place(o);return}if(this.mode==="picking"){e.appendChild(this.picker());return}let t=this.composer();e.appendChild(t),this.place(t)}pending(){let e=document.createElement("div");return e.className="launcher launcher--pending",e.setAttribute("role","status"),e.textContent="Feedback access pending approval",e}sent(){var c;let e=document.createElement("div");e.className="panel panel--sent",e.setAttribute("role","status");let t=this.reference,o=this.uploadsFailed;e.innerHTML=`
|
|
2
2
|
<div class="sent__tick" aria-hidden="true">✓</div>
|
|
3
3
|
<div class="sent__body">
|
|
4
4
|
<div class="panel__title">Thank you \u2014 that is on its way.</div>
|
|
5
5
|
${t?`<div class="sent__ref">
|
|
6
|
-
<code class="sent__id">${
|
|
6
|
+
<code class="sent__id">${fe(t)}</code>
|
|
7
7
|
<button type="button" class="sent__copy" data-copy>Copy</button>
|
|
8
8
|
</div>
|
|
9
9
|
<div class="panel__anchor">Quote it if you follow it up.</div>`:""}
|
|
10
10
|
${o>0?`<div class="sent__warn">${o===1?"One attachment could not be uploaded.":`${o} attachments could not be uploaded.`} The report was filed without it.</div>`:""}
|
|
11
11
|
</div>
|
|
12
|
-
${t?'<button type="button" class="panel__close" data-dismiss aria-label="Dismiss">×</button>':""}`;let r=()=>{this.mode==="sent"&&(this.mode="idle",this.render())},i=window.setTimeout(r,o>0?2e4:t?12e3:6e3),s=()=>window.clearTimeout(i);if(this.detach.push(()=>window.clearTimeout(i)),this.contain(e),this.place(e),!t)return e;e.addEventListener("pointerenter",s),e.addEventListener("focusin",s),(c=e.querySelector("[data-dismiss]"))==null||c.addEventListener("click",r);let a=e.querySelector("[data-copy]");return a&&(a.onclick=async()=>{s();let
|
|
12
|
+
${t?'<button type="button" class="panel__close" data-dismiss aria-label="Dismiss">×</button>':""}`;let r=()=>{this.mode==="sent"&&(this.mode="idle",this.render())},i=window.setTimeout(r,o>0?2e4:t?12e3:6e3),s=()=>window.clearTimeout(i);if(this.detach.push(()=>window.clearTimeout(i)),this.contain(e),this.place(e),!t)return e;e.addEventListener("pointerenter",s),e.addEventListener("focusin",s),(c=e.querySelector("[data-dismiss]"))==null||c.addEventListener("click",r);let a=e.querySelector("[data-copy]");return a&&(a.onclick=async()=>{s();let l=await Pe(t);a.textContent=l?"Copied":"Copy failed",a.classList.toggle("sent__copy--done",l)}),e}launcher(){var t,o;let e=document.createElement("button");return e.className="launcher",e.textContent=(t=this.launcherLabel)!=null?t:"Feedback",e.title=this.options.hotkey===null?"Report a problem":`Report a problem (${((o=this.options.hotkey)!=null?o:"f").toUpperCase()})`,e.onclick=()=>{this.mode="picking",this.render()},e}picker(){let e=document.createElement("div");return e.className="mask",e.innerHTML='<div class="hint">Click the thing that is wrong \xB7 <kbd>Esc</kbd> to cancel</div>',e.onclick=t=>{e.style.pointerEvents="none",this.anchor=_(t.clientX,t.clientY),e.style.pointerEvents="",this.mode="composing",this.render()},e}composer(){var K,X,W,Y,V;let e=document.createElement("div");e.className="panel";let t=(K=this.anchor)!=null&&K.elementText?`on \u201C${this.anchor.elementText}\u201D`:(X=this.anchor)!=null&&X.selector?`on ${this.anchor.selector}`:"on this page",o=this.capture();e.innerHTML=`
|
|
13
13
|
<div class="panel__head" id="head">
|
|
14
14
|
<span class="panel__grip" aria-hidden="true">\u283F</span>
|
|
15
15
|
<div class="panel__heading">
|
|
16
|
-
<div class="panel__anchor">${
|
|
16
|
+
<div class="panel__anchor">${fe(t)}</div>
|
|
17
17
|
<div class="panel__title">Report a problem</div>
|
|
18
18
|
</div>
|
|
19
19
|
<button id="close" class="panel__close" aria-label="Close">×</button>
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
what somebody came here to do is type.
|
|
28
28
|
-->
|
|
29
29
|
<div class="panel__kinds">
|
|
30
|
-
${["bug","idea","praise","question"].map((
|
|
30
|
+
${["bug","idea","praise","question"].map((d,h)=>`<button class="kind${h===0?" kind--on":""}" data-kind="${d}">${d}</button>`).join("")}
|
|
31
31
|
</div>
|
|
32
32
|
|
|
33
33
|
<input id="email" type="email" placeholder="Email (optional, so we can reply)" autocomplete="email" />
|
|
@@ -53,7 +53,7 @@
|
|
|
53
53
|
<span class="panel__note">Sends the page, your browser, and recent errors.</span>
|
|
54
54
|
<button id="cancel" class="ghost">Cancel</button>
|
|
55
55
|
<button id="send" class="primary">Send</button>
|
|
56
|
-
</div>`;let r=[],i=e.querySelector("#files"),s=e.querySelector("#drop"),a=e.querySelector("#file"),c=()=>{i.innerHTML="",r.forEach((
|
|
56
|
+
</div>`;let r=[],i=e.querySelector("#files"),s=e.querySelector("#drop"),a=e.querySelector("#file"),c=()=>{i.innerHTML="",r.forEach((d,h)=>{var J;let b=document.createElement("div");b.className=d.error?"file file--bad":"file",b.innerHTML=d.preview?`<img src="${d.preview}" alt="" />`:'<span class="file__icon">\u25A6</span>';let I=document.createElement("span");I.className="file__name",I.textContent=(J=d.error)!=null?J:d.filename,b.appendChild(I);let x=document.createElement("button");x.className="link",x.textContent="\xD7",x.onclick=()=>{$([d]),r.splice(h,1),c()},b.appendChild(x),i.appendChild(b)}),s.style.display=r.length>=5?"none":""},l=d=>{r.push(...le(d,r.length)),c()};a.onchange=()=>{a.files&&l(a.files)},e.querySelector("#browse").onclick=()=>a.click(),e.addEventListener("paste",d=>{let h=de(d);h.length>0&&(d.preventDefault(),l(h))}),s.addEventListener("dragover",d=>{d.preventDefault(),s.classList.add("drop--over")}),s.addEventListener("dragleave",()=>s.classList.remove("drop--over")),s.addEventListener("drop",d=>{var h,b;d.preventDefault(),s.classList.remove("drop--over"),l(Array.from((b=(h=d.dataTransfer)==null?void 0:h.files)!=null?b:[]))});let u="bug";e.querySelectorAll(".kind").forEach(d=>{d.onclick=()=>{var h;u=(h=d.dataset.kind)!=null?h:"bug",e.querySelectorAll(".kind").forEach(b=>b.classList.remove("kind--on")),d.classList.add("kind--on")}});let p=e.querySelector("#message"),m=e.querySelector("#email"),g=(V=(W=this.reporter)==null?void 0:W.email)!=null?V:(Y=this.options.reporter)==null?void 0:Y.email;g&&!m.value&&(m.value=g);let y=e.querySelector("#shot"),f=e.querySelector("#status"),H=e.querySelector("#send"),N=()=>{$(r),this.mode="idle",this.anchor=null,this.render()};e.querySelector("#cancel").onclick=N,e.querySelector("#close").onclick=N;let D=async()=>{var d;if(!p.value.trim()){f.textContent="Say what happened first.";return}H.disabled=!0,f.textContent="Sending\u2026";try{let h=await this.onSubmit({message:p.value.trim(),kind:u,email:m.value.trim()||void 0,anchor:this.anchor,withScreenshot:(d=y==null?void 0:y.checked)!=null?d:!1,files:r.filter(b=>!b.error)});this.reference=h.reference,this.uploadsFailed=h.uploadsFailed,$(r),this.mode="sent",this.anchor=null,this.render()}catch(h){H.disabled=!1,f.textContent=h instanceof Error?`${h.message} \u2014 saved, will retry.`:"Failed, saved and will retry."}};return H.onclick=D,p.onkeydown=d=>{(d.metaKey||d.ctrlKey)&&d.key==="Enter"&&D()},setTimeout(()=>p.focus(),0),this.contain(e),this.movable(e,e.querySelector("#head")),e}contain(e){for(let t of["pointerdown","mousedown","click"])e.addEventListener(t,o=>o.stopPropagation())}};async function Pe(n){var t;try{if((t=navigator.clipboard)!=null&&t.writeText)return await navigator.clipboard.writeText(n),!0}catch{}let e=document.createElement("textarea");e.value=n,e.setAttribute("readonly",""),e.style.cssText="position:fixed;top:0;left:0;width:1px;height:1px;opacity:0",document.body.appendChild(e);try{return e.select(),document.execCommand("copy")}catch{return!1}finally{e.remove()}}var he=72,w=16,z=56,B="pm.feedback.placement";function Fe(n){let e=n.left+n.width/2<window.innerWidth/2?"left":"right",t=n.top+n.height/2<window.innerHeight/2?"top":"bottom",o=e==="left"?n.left:window.innerWidth-n.right,r=t==="top"?n.top:window.innerHeight-n.bottom;return{h:e,v:t,dx:o<he?w:Math.round(o),dy:r<he?w:Math.round(r)}}function Oe(){try{let n=localStorage.getItem(B);if(!n)return null;let e=JSON.parse(n);return(e.h==="left"||e.h==="right")&&(e.v==="top"||e.v==="bottom")&&Number.isFinite(e.dx)&&Number.isFinite(e.dy)?e:null}catch{return null}}function ue(n){try{n?localStorage.setItem(B,JSON.stringify(n)):localStorage.removeItem(B)}catch{}}function R(n,e,t){return Math.min(Math.max(n,e),t)}function fe(n){return n.replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}var je={"bottom-right":"--pm-left: auto; --pm-right: 16px; --pm-top: auto; --pm-bottom: 16px","bottom-left":"--pm-left: 16px; --pm-right: auto; --pm-top: auto; --pm-bottom: 16px","top-right":"--pm-left: auto; --pm-right: 16px; --pm-top: 16px; --pm-bottom: auto","top-left":"--pm-left: 16px; --pm-right: auto; --pm-top: 16px; --pm-bottom: auto"};function qe(n){return typeof n=="string"&&/^(#[0-9a-f]{3,8}|rgba?\([\d\s.,%/]+\)|hsla?\([\d\s.,%/deg]+\)|[a-z]{3,20})$/i.test(n.trim())}var Ue=`
|
|
57
57
|
:host {
|
|
58
58
|
all: initial;
|
|
59
59
|
|
|
@@ -211,4 +211,4 @@ textarea:focus, input:focus { outline: 2px solid #171717; outline-offset: -1px }
|
|
|
211
211
|
.file__icon { width: 28px; text-align: center }
|
|
212
212
|
.file__name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap }
|
|
213
213
|
.link { border: 0; background: transparent; color: #525252; cursor: pointer; font-size: 11px; text-decoration: underline }
|
|
214
|
-
`;var
|
|
214
|
+
`;var me="https://api.daybook.team",A=class{constructor(e){this.options=e;this.widget=null;this.started=!1;this.inFlight=null;this.epoch=0;this.ready=null;this.stopped=!1;var t;if(!e.ingestKey)throw new Error("ingestKey is required");this.client=new T((t=e.apiUrl)!=null?t:me,e.ingestKey),this.trail=e.breadcrumbs===!1?null:new k(40,e.redact!==!1)}start(){var e;return this.stopped=!1,(e=this.trail)==null||e.start(),this.mount(),this.started||(this.started=!0,this.client.flush()),this.handshake(),this}mount(){this.widget||this.stopped||(this.widget=new M(this.options,e=>this.submit(e)),this.widget.setReporter(this.options.reporter),this.widget.mount())}handshake(){var o,r,i;let e=JSON.stringify([(o=this.options.reporter)!=null?o:null,(r=this.options.signature)!=null?r:null,this.epoch]);if(((i=this.inFlight)==null?void 0:i.key)===e)return this.inFlight.promise;let t=this.runHandshake().finally(()=>{var s;((s=this.inFlight)==null?void 0:s.promise)===t&&(this.inFlight=null)});return this.inFlight={key:e,promise:t},t}async runHandshake(){var e,t,o,r,i,s,a;try{let c=await this.client.handshake({identity:this.options.reporter,signature:this.options.signature,locale:typeof navigator!="undefined"?navigator.language:void 0});if(this.ready=c,(t=(e=this.options).onReady)==null||t.call(e,c),c.reporterStatus==="Blocked"){(o=this.widget)==null||o.unmount(),this.widget=null;return}this.mount(),this.widget.setTheme(Be(c.theme)),this.widget.setPolicy((r=c.policy)!=null?r:null),this.widget.setState(c.reporterStatus==="Pending"?"pending":"ready")}catch(c){(s=(i=this.options).onError)==null||s.call(i,c),console.warn("[feedback] handshake failed; the widget will not appear",c),(a=this.widget)==null||a.unmount(),this.widget=null}}identify(e){var t;this.options={...this.options,reporter:e?{...this.options.reporter,...e}:void 0},(t=this.widget)==null||t.setReporter(this.options.reporter),this.widget&&this.handshake()}async signIn(){await this.client.signIn(),this.epoch++,await this.handshake()}authenticate(e){this.options={...this.options,signature:e!=null?e:void 0},this.widget&&this.handshake()}stop(){var e,t;this.started=!1,this.stopped=!0,(e=this.trail)==null||e.stop(),(t=this.widget)==null||t.unmount(),this.widget=null}open(){var e;(e=this.widget)==null||e.open()}async report(e,t={}){var o,r,i;return this.client.send({message:e,surface:this.options.surface,...t,context:{...q({breadcrumbs:(o=this.trail)==null?void 0:o.list(),app:this.options.app}),...(r=t.context)!=null?r:{}},reporter:(i=t.reporter)!=null?i:this.options.reporter})}async submit(e){var s,a,c,l,u;let t=e.withScreenshot?await se(this.options.redact!==!1,()=>{var p,m;return(m=(p=this.widget)==null?void 0:p.conceal())!=null?m:(()=>{})}):null,o=[...e.files,...t?[t]:[]],r={message:e.message,kind:e.kind,app:this.options.app,surface:this.options.surface,reporter:e.email?{...this.options.reporter,email:e.email}:this.options.reporter,context:q({anchor:e.anchor,breadcrumbs:(s=this.trail)==null?void 0:s.list(),app:this.options.app})},i=[];try{let p=await this.client.send(r,o,(m,g)=>{var y,f;i.push(g),console.warn(`[feedback] "${m.filename}" did not upload`,g),(f=(y=this.options).onError)==null||f.call(y,g)});return p.uploadsFailed=i.length,(c=(a=this.options).onSent)==null||c.call(a,p),{reference:p.reference,uploadsFailed:i.length}}catch(p){throw this.client.queue(r),(u=(l=this.options).onError)==null||u.call(l,p),p}}};function ze(n){return new A(n).start()}function Be(n){if(!n)return null;try{let e=JSON.parse(n);return e&&typeof e=="object"?e:null}catch{return null}}return xe(Ne);})();
|
package/dist/screenshot.d.ts
CHANGED
|
@@ -23,3 +23,18 @@ export interface Screenshot {
|
|
|
23
23
|
* the form they just filled in, covering the thing they were reporting.
|
|
24
24
|
*/
|
|
25
25
|
export declare function captureScreenshot(redact: boolean, conceal?: () => () => void): Promise<Screenshot | null>;
|
|
26
|
+
/**
|
|
27
|
+
* Encodes the frame as small as the browser can manage.
|
|
28
|
+
*
|
|
29
|
+
* WebP first, JPEG second, and whatever comes back last. The order is by size on this kind of
|
|
30
|
+
* image: a 2880-wide screenshot is several megabytes as PNG and a couple of hundred kilobytes as
|
|
31
|
+
* WebP, and that difference is a report that uploads in a second rather than in a minute.
|
|
32
|
+
*
|
|
33
|
+
* Each step checks what came back rather than trusting the request. toBlob falls back to PNG
|
|
34
|
+
* silently for a format it does not support, so asking for WebP and believing the answer is how a
|
|
35
|
+
* fix like this quietly does nothing on Safari.
|
|
36
|
+
*
|
|
37
|
+
* Exported so that behaviour can be tested — it is the only part of the capture path that does not
|
|
38
|
+
* need a browser, and it is the part with the trap in it.
|
|
39
|
+
*/
|
|
40
|
+
export declare function encode(canvas: HTMLCanvasElement): Promise<Blob | null>;
|
package/dist/screenshot.js
CHANGED
|
@@ -38,10 +38,7 @@ export async function captureScreenshot(redact, conceal = () => () => { }) {
|
|
|
38
38
|
return null;
|
|
39
39
|
// A frame arrives a moment after the track opens; without this the capture is often blank.
|
|
40
40
|
await new Promise(resolve => setTimeout(resolve, 250));
|
|
41
|
-
|
|
42
|
-
return blob
|
|
43
|
-
? { blob, filename: 'screenshot.png', contentType: 'image/png' }
|
|
44
|
-
: null;
|
|
41
|
+
return await grabFrame(stream);
|
|
45
42
|
}
|
|
46
43
|
catch {
|
|
47
44
|
// Declining the share prompt is a normal outcome, not an error worth surfacing — the report
|
|
@@ -54,21 +51,80 @@ export async function captureScreenshot(redact, conceal = () => () => { }) {
|
|
|
54
51
|
restore();
|
|
55
52
|
}
|
|
56
53
|
}
|
|
54
|
+
/**
|
|
55
|
+
* The widest a screenshot is allowed to be, in pixels.
|
|
56
|
+
*
|
|
57
|
+
* A screen capture arrives at the display's PHYSICAL resolution — 2880 or 3840 across on the
|
|
58
|
+
* laptops this is reported from — and none of that detail survives being read by a person triaging
|
|
59
|
+
* a bug. Halving the width quarters the pixels, and 1920 is still wider than most people's browser
|
|
60
|
+
* window.
|
|
61
|
+
*/
|
|
62
|
+
const MAX_WIDTH = 1920;
|
|
63
|
+
/**
|
|
64
|
+
* WebP quality. Lossy, deliberately.
|
|
65
|
+
*
|
|
66
|
+
* A screenshot is a photograph of text, which is the worst case for PNG: lossless compression finds
|
|
67
|
+
* almost nothing to remove and the file comes out in megabytes. At 0.82 the text is still crisp and
|
|
68
|
+
* the file is a fraction of the size.
|
|
69
|
+
*/
|
|
70
|
+
const QUALITY = 0.82;
|
|
57
71
|
async function grabFrame(stream) {
|
|
58
72
|
const video = document.createElement('video');
|
|
59
73
|
video.srcObject = stream;
|
|
60
74
|
video.muted = true;
|
|
61
75
|
await video.play().catch(() => { });
|
|
76
|
+
const width = video.videoWidth || window.innerWidth;
|
|
77
|
+
const height = video.videoHeight || window.innerHeight;
|
|
78
|
+
// Scaled on the way into the canvas rather than afterwards, so the full-resolution bitmap is
|
|
79
|
+
// never held at all.
|
|
80
|
+
const scale = width > MAX_WIDTH ? MAX_WIDTH / width : 1;
|
|
62
81
|
const canvas = document.createElement('canvas');
|
|
63
|
-
canvas.width =
|
|
64
|
-
canvas.height =
|
|
82
|
+
canvas.width = Math.round(width * scale);
|
|
83
|
+
canvas.height = Math.round(height * scale);
|
|
65
84
|
const context = canvas.getContext('2d');
|
|
66
85
|
if (!context)
|
|
67
86
|
return null;
|
|
87
|
+
// Text is what a screenshot is mostly made of, and the default resampler smears it when
|
|
88
|
+
// downscaling. This is the one place the quality hint earns its cost.
|
|
89
|
+
context.imageSmoothingQuality = 'high';
|
|
68
90
|
context.drawImage(video, 0, 0, canvas.width, canvas.height);
|
|
69
91
|
video.pause();
|
|
70
92
|
video.srcObject = null;
|
|
71
|
-
|
|
93
|
+
const blob = await encode(canvas);
|
|
94
|
+
if (!blob)
|
|
95
|
+
return null;
|
|
96
|
+
// Named from what the browser ACTUALLY produced, not from what was asked for. A browser that
|
|
97
|
+
// cannot encode WebP does not fail — it silently returns a PNG — and a PNG called .webp is
|
|
98
|
+
// rejected by the server's magic-number check, which would turn a slow screenshot into a missing
|
|
99
|
+
// one.
|
|
100
|
+
const type = blob.type || 'image/png';
|
|
101
|
+
const extension = type === 'image/webp' ? 'webp' : type === 'image/jpeg' ? 'jpg' : 'png';
|
|
102
|
+
return { blob, filename: `screenshot.${extension}`, contentType: type };
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Encodes the frame as small as the browser can manage.
|
|
106
|
+
*
|
|
107
|
+
* WebP first, JPEG second, and whatever comes back last. The order is by size on this kind of
|
|
108
|
+
* image: a 2880-wide screenshot is several megabytes as PNG and a couple of hundred kilobytes as
|
|
109
|
+
* WebP, and that difference is a report that uploads in a second rather than in a minute.
|
|
110
|
+
*
|
|
111
|
+
* Each step checks what came back rather than trusting the request. toBlob falls back to PNG
|
|
112
|
+
* silently for a format it does not support, so asking for WebP and believing the answer is how a
|
|
113
|
+
* fix like this quietly does nothing on Safari.
|
|
114
|
+
*
|
|
115
|
+
* Exported so that behaviour can be tested — it is the only part of the capture path that does not
|
|
116
|
+
* need a browser, and it is the part with the trap in it.
|
|
117
|
+
*/
|
|
118
|
+
export async function encode(canvas) {
|
|
119
|
+
for (const type of ['image/webp', 'image/jpeg']) {
|
|
120
|
+
const blob = await toBlob(canvas, type, QUALITY);
|
|
121
|
+
if (blob?.type === type)
|
|
122
|
+
return blob;
|
|
123
|
+
}
|
|
124
|
+
return toBlob(canvas, 'image/png');
|
|
125
|
+
}
|
|
126
|
+
function toBlob(canvas, type, quality) {
|
|
127
|
+
return new Promise(resolve => canvas.toBlob(blob => resolve(blob), type, quality));
|
|
72
128
|
}
|
|
73
129
|
/**
|
|
74
130
|
* Blurs anything the host app marked private, and every password field whether it was marked or not.
|
package/package.json
CHANGED