@nuniapp/widget 0.1.6 → 0.1.8
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/index.d.ts +11 -5
- package/dist/index.js +650 -255
- package/dist/nuni.global.js +260 -66
- package/package.json +1 -1
package/dist/nuni.global.js
CHANGED
|
@@ -3,10 +3,10 @@
|
|
|
3
3
|
`)}function p(e){let t=e.replace(/\s+/g,` `).trim();return t.includes("`")?`"${t}"`:`\`${t}\``}function m(e,t={}){let n=t.includeContext??!0,{anchor:i,page:a}=e,o=[];if(o.push(`Fix this piece of feedback that was left on the live site with Nuni.`,``,`## Comment`,``,f(e.body),``,`From ${e.authorName} on ${new Date(e.createdAt).toISOString().slice(0,10)}`+(e.status===`resolved`?` (already resolved)`:``)),e.replies?.length){o.push(``,`## Replies (${e.replies.length})`,``);for(let t of e.replies)o.push(`${t.authorName}${t.isOwner?` (owner)`:``}:`,f(t.body),``);o.pop()}if(o.push(``,`## Where`,``),o.push(`- Page: ${a.title?`${a.title} `:``}(${a.path})`),o.push(`- Open it: ${r(a,e._id)}`),o.push(`- Viewport: ${e.viewport.w}×${e.viewport.h} at ${e.viewport.dpr}x`),n&&e.userAgent&&o.push(`- Browser: ${e.userAgent}`),o.push(``,`## Element`,``),o.push(`- Tag: <${i.tag}>`),i.text&&o.push(`- Text: ${p(i.text)}`),i.quote&&o.push(`- Selected text: ${p(i.quote.exact)}`),i.region){let e=e=>`${Math.round(e*100)}%`,t=i.region;o.push(`- Area: ${e(t.w)} × ${e(t.h)} of the element, from ${e(t.x)} left and ${e(t.y)} top`)}i.componentName&&o.push(`- React component: ${i.componentName}`),i.selectors.testId&&o.push(`- Test ID: ${p(i.selectors.testId)}`),i.selectors.id&&o.push(`- ID: ${p(i.selectors.id)}`),i.selectors.css&&o.push(`- CSS selector: ${p(i.selectors.css)}`),o.push(`- DOM path: ${p(i.selectors.path)}`);let s=Object.entries(i.attrs).filter(([e])=>e!==`class`&&e!==`style`).map(([e,t])=>`${e}="${t}"`);s.length&&o.push(`- Attributes: ${p(s.join(` `))}`);let c=n?e.context:void 0;c?.dom?.html&&o.push(``,d(c.dom.html,`html`));let l=Object.entries(c?.dom?.styles??{});if(l.length&&o.push(``,`Computed styles:`,``,d(l.map(([e,t])=>`${e}: ${t};`).join(`
|
|
4
4
|
`),`css`)),c?.console?.length&&(o.push(``,`## Console (${c.console.length})`,``),o.push(d(c.console.map(e=>`[${e.level}] ${e.message}`).join(`
|
|
5
5
|
`),`text`))),c?.network?.length){o.push(``,`## Failed requests (${c.network.length})`,``);for(let e of c.network)o.push(`- ${e.method} ${e.url} → ${e.status===0?`network error`:e.status}`)}return n&&e.screenshotUrl&&o.push(``,`## Screenshot`,``,e.screenshotUrl),o.push(``,`## Steps`,``,`1. Find the code that renders this element. Search for the text, the component name, the test ID or the selector.`,`2. Make the change the comment asks for, and keep the fix focused on it.`,`3. Tell me what you changed, so the comment can be resolved in Nuni.`,` If the Nuni CLI is signed in to this project (\`npx ${u.cli}@latest login\`), resolve it with \`npx ${u.cli}@latest resolve ${e._id}\` or the \`resolve_comment\` MCP tool.`),o.join(`
|
|
6
|
-
`)}let h=`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`,ee=RegExp(`^nuni_[${h}]{22}$`);function te(e){let t=new Uint8Array(e);crypto.getRandomValues(t);let n=``;for(let e of t){let t=e;for(;t>=232;){let e=/* @__PURE__ */ new Uint8Array(1);crypto.getRandomValues(e),t=e[0]}n+=h[t%58]}return n}function ne(e){return typeof e==`string`&&ee.test(e)}function g(){return te(32)}let _={bodyMaxLength:2e3,nameMaxLength:50,unclaimedCommentCap:500,maxOriginsPerProject:20,sessionTtlMs:2592e6,cliSessionTtlMs:7776e6,transferTtlMs:6048e5,bulkMax:100,cliLoginTtlMs:6e5,anchorTextMaxLength:120,quoteMaxLength:500,quoteContextLength:32,pageOpenLimit:1e3,pageResolvedLimit:200,contextEntryMax:20,contextMessageMaxLength:500,domSnippetMaxLength:4e3,screenshotMaxBytes:6e5,repliesPerComment:200,reactionsPerComment:2e3,screenshotUploadWindowMs:3e5},re=[`👍`,`❤️`,`🎉`,`👀`,`✅`,`😄`],ie=`data-nuni-mask`,v=`[${ie}]`;function y(e){return{project:e.project,convexUrl:e.convexUrl??`https://greedy-giraffe-33.convex.cloud`,convexSiteUrl:e.convexSiteUrl??`https://greedy-giraffe-33.convex.site`,appUrl:(e.appUrl??`https://nuni.praveenjuge.com`).replace(/\/$/,``),getPageKey:e.getPageKey??le(e.pageKey),position:se(e.position,ae,`bottom-right`),accentColor:e.accentColor?.trim()||null,theme:se(e.theme,oe,`auto`),label:e.label?.trim()||null,hotkey:e.hotkey===!1?null:e.hotkey?.trim().slice(0,1).toLowerCase()||`c`,zIndex:typeof e.zIndex==`number`&&Number.isFinite(e.zIndex)?Math.round(e.zIndex):null,locale:e.locale?.trim()||void 0,messages:e.messages??{},capture:{console:e.capture?.console??!0,network:e.capture?.network??!0,dom:e.capture?.dom??!0,screenshot:e.capture?.screenshot??!0}}}let ae=[`bottom-right`,`bottom-left`,`top-right`,`top-left`],oe=[`auto`,`light`,`dark`];function se(e,t,n){return t.includes(e)?e:n}let ce=/^(nuni|utm_.*|fbclid|gclid|msclkid|ref)$/i;function le(t=`path`){return n=>{let r=e(n);if(t===`path+search`){let e=[...n.searchParams].filter(([e])=>!ce.test(e)).sort(([e],[t])=>e<t?-1:+(e>t));return e.length?`${r}?${new URLSearchParams(e).toString()}`:r}return t===`path+hash`&&n.hash.length>1&&!r.includes(`#`)&&!/^#!?\//.test(n.hash)?`${r}${n.hash}`:r}}let ue=Symbol.for(`nuni.capture`);function de(e){"@babel/helpers - typeof";return de=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},de(e)}function fe(e,t){if(de(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(de(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function pe(e){var t=fe(e,`string`);return de(t)==`symbol`?t:t+``}function b(e,t,n){return(t=pe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}let me=_.contextMessageMaxLength;function he(e){if(typeof e==`string`)return e;if(e instanceof Error){let t=e.stack?.split(`
|
|
7
|
-
`).find(e=>e.trim().startsWith(`at `));return`${e.name}: ${e.message}${t?` (${t.trim()})`:``}`}try{let t=200;return JSON.stringify(e,(e,n)=>t-->0?n:void 0)??String(e)}catch{return String(e)}}function ge(e){return e.length>me?`${e.slice(0,me-1)}…`:e}function _e(e){return ge(i(e,location.href))}var ve=class{constructor(){b(this,`items`,[])}push(e){this.items.push(e),this.items.length>_.contextEntryMax&&this.items.shift()}};function ye(e,t){let n=new ve,r=new ve,i=[],a=(e,t)=>{n.push({level:e,message:ge(o(t.map(he).join(` `))),at:Date.now()})},s=(e,n,i)=>{t(n)||r.push({method:e.toUpperCase(),url:_e(n),status:i,at:Date.now()})};if(e.console){for(let e of[`error`,`warn`]){let t=console[e],n=(...n)=>{a(e,n),t.apply(console,n)};console[e]=n,i.push(()=>{console[e]===n&&(console[e]=t)})}let e=e=>{e.error?a(`error`,[e.error]):a(`error`,[`${e.message}${e.filename?` (${_e(e.filename)}:${e.lineno})`:``}`])},t=e=>a(`error`,[`Unhandled rejection:`,e.reason]);window.addEventListener(`error`,e),window.addEventListener(`unhandledrejection`,t),i.push(()=>{window.removeEventListener(`error`,e),window.removeEventListener(`unhandledrejection`,t)})}if(e.network){let e=window.fetch;if(typeof e==`function`){let t=async(t,n)=>{if(n&&n[ue])return e.call(window,t,n);let r=typeof t==`string`?t:t instanceof URL?t.href:t.url,i=n?.method??(typeof t==`object`&&`method`in t?t.method:`GET`);try{let a=await e.call(window,t,n);return!a.ok&&a.type!==`opaque`&&s(i,r,a.status),a}catch(e){throw e instanceof DOMException&&e.name===`AbortError`||s(i,r,0),e}};window.fetch=t,i.push(()=>{window.fetch===t&&(window.fetch=e)})}let t=window.XMLHttpRequest?.prototype;if(t){let e=t.open,n=t.send,r=/* @__PURE__ */ new WeakMap,a=function(t,n,...i){return r.set(this,{method:t,url:String(n)}),e.call(this,t,n,...i)};t.open=a;let o=function(e){let t=r.get(this);if(t){let e=!1,n=()=>e=!0,r=()=>{this.removeEventListener(`abort`,n),this.removeEventListener(`loadend`,r),!e&&(this.status===0||this.status>=400)&&s(t.method,t.url,this.status)};this.addEventListener(`abort`,n),this.addEventListener(`loadend`,r)}return n.call(this,e)};t.send=o,i.push(()=>{t.open===a&&(t.open=e),t.send===o&&(t.send=n)})}}return{console:()=>[...n.items],network:()=>[...r.items],stop(){for(let e of i.splice(0))e()}}}let be=[`display`,`position`,`width`,`height`,`margin`,`padding`,`gap`,`font-family`,`font-size`,`font-weight`,`line-height`,`letter-spacing`,`text-align`,`color`,`background-color`,`border`,`border-radius`,`box-shadow`,`opacity`];function xe(e,t){e.replaceChildren(e.ownerDocument.createComment(` ${t} `))}function Se(e){let t=e.ownerDocument.createTreeWalker(e,5),n=[];for(let r=e;r;r=t.nextNode()){if(r.nodeType===3){let e=r.textContent??``;e.length>200&&(r.textContent=`${e.slice(0,200)}…`);continue}let e=r,t=e.tagName;if(t===`SCRIPT`||t===`STYLE`||t===`NOSCRIPT`){n.push(e);continue}if(e.hasAttribute(`data-nuni-mask`)){for(let t of Array.from(e.attributes))t.name!==`id`&&t.name!==`class`&&t.name!==`data-nuni-mask`&&e.removeAttribute(t.name);xe(e,`masked`);continue}if((t===`INPUT`||t===`TEXTAREA`)&&(e.removeAttribute(`value`),t===`TEXTAREA`&&(e.textContent=``)),t===`SELECT`||t===`DATALIST`){let t=e.getElementsByTagName(`option`).length;xe(e,`${t} options`)}for(let t of Array.from(e.attributes))t.value.length>200&&e.setAttribute(t.name,`${t.value.slice(0,200)}…`)}for(let e of n)e.parentNode?.removeChild(e)}function Ce(e,t){let n=e.cloneNode(!1);if(t>0)for(let r of Array.from(e.childNodes))n.appendChild(r.nodeType===1?Ce(r,t-1):r.cloneNode(!1));else e.childElementCount&&n.appendChild(e.ownerDocument.createComment(` ${e.childElementCount} more `));return n}function we(e){let t=_.domSnippetMaxLength,n=``,r=!!e.parentElement?.closest(`[${ie}]`);for(let i of r?[-1]:[1/0,3,1,0]){let r=i===1/0?e.cloneNode(!0):Ce(e,Math.max(0,i));if(i<0&&r.setAttribute(ie,``),Se(r),n=l(r.outerHTML),n.length<=t)break}n.length>t&&(n=`${n.slice(0,t-1)}…`);let i={},a=e.ownerDocument.defaultView?.getComputedStyle(e);for(let e of be){let t=a?.getPropertyValue(e).trim();t&&(i[e]=t)}return{html:n,styles:i}}function Te(e){let t=Object.keys(e).find(e=>e.startsWith(`__reactFiber$`)||e.startsWith(`__reactInternalInstance$`));if(!t)return;let n=e[t]??null;for(let e=0;n&&e<30;e++){let e=n.type;if(e&&typeof e!=`string`){let t=e.displayName||e.name||e.render?.name;if(t&&t.length>2&&/^[A-Z]/.test(t))return t}n=n.return??null}}function Ee(e){let t=e.getBoundingClientRect(),n=e.ownerDocument.defaultView,r=n?.scrollX??0,i=n?.scrollY??0;return{x:t.left+r,y:t.top+i,w:t.width,h:t.height}}function De(e){let t=e.defaultView;return{w:t?.innerWidth??0,h:t?.innerHeight??0,dpr:t?.devicePixelRatio??1,scrollX:t?.scrollX??0,scrollY:t?.scrollY??0}}function Oe(e){let t=e.documentElement;return{w:t.scrollWidth,h:t.scrollHeight}}function ke(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):.5}function Ae(e){if(!e.isConnected)return!1;let t=e.ownerDocument.defaultView,n=e.getBoundingClientRect();if(n.width===0&&n.height===0)return!1;let r=t?.getComputedStyle(e);return!r||r.visibility!==`hidden`&&r.display!==`none`}function je(e,t){let n=t.ignoreAttributePrefixes;return!n||!n.some(t=>e.startsWith(t))}let Me=/* @__PURE__ */ new Set([`SCRIPT`,`STYLE`,`NOSCRIPT`,`TEMPLATE`,`SVG`]);function Ne(e){return e.replace(/\s+/g,` `).trim()}function x(e,t=120){if(e.closest(v))return``;if(e.tagName===`INPUT`||e.tagName===`TEXTAREA`)return Ne(e.placeholder||e.getAttribute(`aria-label`)||``).slice(0,t);let n=``,r=e=>{if(n.length>t*2)return;if(e.nodeType===3){n+=e.nodeValue??``;return}if(e.nodeType!==1)return;let i=e.tagName.toUpperCase();if(Me.has(i)||e.hasAttribute(`data-nuni-mask`)||e.hasAttribute(`data-nuni`))return;if(i===`IMG`){n+=` `+(e.getAttribute(`alt`)??``)+` `;return}let a=e.shadowRoot;if(a){for(let e of Array.from(a.childNodes))r(e);return}if(i===`SLOT`){let t=e.assignedNodes?.({flatten:!0});if(t?.length){for(let e of t)r(e);return}}for(let t of Array.from(e.childNodes))r(t);(i===`BR`||i===`P`||i===`DIV`||i===`LI`)&&(n+=` `)};return r(e),Ne(n).slice(0,t)}function Pe(e){let t=e.toLowerCase(),n=/* @__PURE__ */ new Map;for(let e=0;e<t.length-1;e++){let r=t.slice(e,e+2);n.set(r,(n.get(r)??0)+1)}return n}function
|
|
8
|
-
`||t===` `||t===`\r`||t===`\f`?(r||i(` `,o,e),r=!0):(i(t,o,e),r=!1)}return}if(e.nodeType!==1)return;let s=e,c=s.tagName.toUpperCase();if(Fe.has(c)||s.hasAttribute(`data-nuni-mask`)||s.hasAttribute(`data-nuni`))return;let l=Ie.has(c);l&&a();for(let e of Array.from(s.childNodes))o(e);l&&a()};for(o(e);n.length&&n[n.length-1]===` `;)n.pop(),t.node.pop(),t.offset.pop();return t.text=n.join(``),t}function Ve(e,t,n){if(!e.text.length)return 0;let r=(t.ownerDocument??t).createRange();r.setStart(t,n),r.collapse(!0);let i=0,a=e.text.length;try{for(;i<a;){let t=i+a>>1,n=e.nodes[e.node[t]];r.comparePoint(n,e.offset[t])<0?i=t+1:a=t}}catch{return-1}return i}function He(e,t,n){let r=e.nodes[e.node[t]],i=e.nodes[e.node[n-1]],a=r.ownerDocument.createRange();return a.setStart(r,e.offset[t]),a.setEnd(i,Math.min(i.length,e.offset[n-1]+1)),a}function Ue(e){let t=e.commonAncestorContainer;if(t.nodeType!==1&&(t=t.parentNode),!t||t.nodeType!==1)return null;let n=t,r=n.ownerDocument.body;for(;Le.has(n.tagName.toUpperCase())&&n.parentElement&&n.parentElement!==r;)n=n.parentElement;return n}function We(e,t){let n=Be(t),r=Ve(n,e.startContainer,e.startOffset),i=Ve(n,e.endContainer,e.endOffset);if(r<0||i<0)return null;let{text:a}=n;for(;r<i&&a[r]===` `;)r++;for(;i>r&&a[i-1]===` `;)i--;if(i<=r)return null;let o=a.slice(r,Math.min(i,r+_.quoteMaxLength)),s=r+o.length;return{exact:o,prefix:a.slice(Math.max(0,r-_.quoteContextLength),r),suffix:a.slice(s,s+_.quoteContextLength)}}function Ge(e,t){let n=Je(e,t,0);if(n)return n;let r=e.parentElement,i=e.ownerDocument.body;for(let e=0;r&&r!==i&&e<2;e++){let e=Je(r,t,.6);if(e)return e;r=r.parentElement}return null}function Ke(e,t){return t?S(e,t):e?.8:1}function qe(e,t,n,r){let i=e.slice(Math.max(0,t-r.prefix.length),t),a=e.slice(n,n+r.suffix.length);return(Ke(i.trimStart(),r.prefix.trimStart())+Ke(a.trimEnd(),r.suffix.trimEnd()))/2}function Je(e,t,n){let{exact:r}=t;if(!r)return null;let i=Be(e),{text:a}=i;if(!a)return null;let o=-1,s=-1;for(let e=a.indexOf(r);e>=0;e=a.indexOf(r,e+1)){let n=qe(a,e,e+r.length,t);n>s&&(o=e,s=n)}if(o>=0&&s>=n)return{range:He(i,o,o+r.length),exact:!0};if(r.length<8||a.length>6e3)return null;let c=Ye(a,t);if(!c)return null;let l=qe(a,c.start,c.end,t);return c.score<.75||l<Math.max(n,.3)?null:{range:He(i,c.start,c.end),exact:!1}}function Ye(e,t){let n=e=>e!==void 0&&ze.test(e),r=[],i=[];for(let t=0;t<e.length;t++){let a=e[t];if(a===` `)continue;let o=e[t-1],s=e[t+1];(o===void 0||o===` `||n(a)&&!n(o))&&r.push(t),(s===void 0||s===` `||n(a)&&!n(s))&&i.push(t+1)}let a=t.exact.length,o=null,s=0;for(let n of r){for(;s<i.length&&i[s]<=n;)s++;for(let r=s;r<i.length;r++){let s=i[r]-n;if(s<a*.7)continue;if(s>a*1.3)break;let c=S(e.slice(n,i[r]),t.exact);(!o||c>o.score)&&(o={start:n,end:i[r],score:c})}}return o}function C(e){return!!(e&&e.nodeType===11&&`host`in e)}function Xe(e){let t=e.getRootNode();return C(t)?t:e.ownerDocument}function Ze(e){return C(e)?e.ownerDocument:e}function Qe(e){try{return e.defaultView?.frameElement??null}catch{return null}}function $e(e){if(e.tagName!==`IFRAME`&&e.tagName!==`FRAME`)return null;try{return e.contentDocument}catch{return null}}function et(e,t){let n=[],r=e;for(let e=0;e<8;e++){let e=r.getRootNode();if(C(e)){n.unshift({kind:`shadow`,host:e.host}),r=e.host;continue}if(r.ownerDocument===t)break;let i=Qe(r.ownerDocument);if(!i)break;n.unshift({kind:`frame`,host:i}),r=i}return n}function tt(e,t){let n=e.getBoundingClientRect(),r=n.left,i=n.top,a=!1,o=e.ownerDocument;for(let e=0;e<8&&o!==t;e++){let e=Qe(o);if(!e)break;let t=o.defaultView;t&&(r+n.width<0||i+n.height<0||r>t.innerWidth||i>t.innerHeight)&&(a=!0);let s=e.getBoundingClientRect();r+=s.left+e.clientLeft,i+=s.top+e.clientTop,o=e.ownerDocument}return{left:r,top:i,width:n.width,height:n.height,clipped:a}}let nt=/^-?(m|p|mx|my|mt|mb|ml|mr|ms|me|px|py|pt|pb|pl|pr|ps|pe|w|h|min-w|max-w|min-h|max-h|size|gap|gap-x|gap-y|space-x|space-y|text|font|bg|border|border-[trblxy]|rounded|rounded-[trbl]{1,2}|shadow|flex|grid|grid-cols|grid-rows|col|col-span|row|row-span|items|justify|self|place|content|inset|inset-x|inset-y|top|left|right|bottom|start|end|z|opacity|leading|tracking|ring|ring-offset|outline|overflow|overflow-x|overflow-y|order|basis|grow|shrink|translate-x|translate-y|scale|rotate|skew|transition|duration|ease|delay|animate|cursor|select|fill|stroke|object|aspect|line-clamp|decoration|indent|align|whitespace|break|hyphens|list|columns|backdrop|blur|brightness|contrast|drop-shadow|grayscale|invert|saturate|sepia|divide|divide-x|divide-y|from|to|via|accent|caret|scroll|snap|touch|will-change|pointer-events|underline-offset|auto-cols|auto-rows|origin|mix-blend|bg-blend|box|float|clear|appearance|resize|table|sr|not-sr)(-|$)/,rt=/* @__PURE__ */ new Set(/* @__PURE__ */ `flex.grid.block.inline.inline-block.inline-flex.inline-grid.hidden.contents.table.static.fixed.absolute.relative.sticky.visible.invisible.container.truncate.underline.uppercase.lowercase.capitalize.italic.antialiased.sr-only.grow.shrink.isolate.transform.filter.group.peer.prose.dark.light`.split(`.`)),it=[/_{1,3}(?=[a-zA-Z-]*[0-9])[a-zA-Z0-9-]{5,}$/,/_{1,3}(?=[a-zA-Z0-9-]*[A-Z][a-zA-Z0-9-]*[A-Z])(?=[a-zA-Z0-9-]*[a-z])[a-zA-Z0-9-]{5,8}$/,/^_[a-zA-Z0-9]/,/^(css|sc|jsx|svelte|astro|emotion|e|tw|vanilla|chakra-[a-z]+-)[-_][a-zA-Z0-9]{4,}$/,/^[a-z]{1,3}-(?=[a-zA-Z]*[0-9])[a-zA-Z0-9]{5,}$/,/^(is|has)-(active|open|selected|focused|hover|hovered|visible|hidden|expanded|collapsed|loading|disabled|checked|current)$/,/^(active|open|selected|focus|focused|hover|current|show|showing|in|fade|collapse|collapsing)$/];function at(e){if(e.length<5)return!1;let t=e.replace(/[^0-9]/g,``).length;return t===0?/^[a-zA-Z]{6,}$/.test(e)&&/[A-Z].*[A-Z]/.test(e)&&/[a-z]/.test(e)&&!/^[A-Z][a-z]+([A-Z][a-z]+)+$/.test(e):e.replace(/[^a-zA-Z]/g,``).length===0||!/^[a-zA-Z]+[-_]?\d{1,3}$/.test(e)&&t/e.length>.2}function ot(e){return/[[\]:/()%!#@&*,.>+~=]/.test(e)||rt.has(e)?!0:nt.test(e)}function st(e){return!e||e.length>40||e.startsWith(`nuni-`)||ot(e)||it.some(t=>t.test(e))?!1:!at(e)}function w(e){let t=[];for(let n of Array.from(e.classList))if(st(n)&&t.push(n),t.length>=4)break;return t}let ct=[/^:[a-zA-Z0-9]+:$/,/^«[a-zA-Z0-9]+»$/,/^(radix|headlessui|mui|react-aria|rc|base-ui|mantine|chakra|reach|downshift|ember|ext|yui|ui-id|aria|mat|cdk|ng|v|vue|svelte|el|id|uid|field|input)[-_:]/i,/[0-9a-f]{8}-[0-9a-f]{4}-/i,/\d{3,}/];function lt(e){return!e||e.length>80||ct.some(t=>t.test(e))?!1:!at(e)}let ut=[`data-nuni`,`data-testid`,`data-test-id`,`data-test`,`data-cy`,`data-qa`],dt=[`aria-label`,`name`,`href`,`src`,`alt`,`placeholder`,`title`,`type`,`role`,`for`,`value`];function T(e){return typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/([^\w-])/g,`\\$1`).replace(/^(\d)/,`\\3$1 `)}function ft(e,t){return`[${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"]`}function pt(e,t){for(let n of ut){if(!je(n,t))continue;let r=e.getAttribute(n);if(r&&r.length<=100)return{attr:n,value:r}}return null}function mt(e){let t=e.getAttribute(`id`);return t&<(t)?t:null}function ht(e){return e.tagName.toLowerCase()}function gt(e){let t=1,n=e.previousElementSibling;for(;n;)n.tagName===e.tagName&&t++,n=n.previousElementSibling;return t}function _t(e){let t=e.parentNode;if(!t)return 1;let n=0;for(let r of Array.from(t.children))r.tagName===e.tagName&&n++;return n}function vt(e,t){try{return e.querySelectorAll(t).length}catch{return 1/0}}function yt(e,t){return vt(e,`#${T(t)}`)===1}function bt(e){let t=Xe(e),n=e.ownerDocument,r=[],i=e;for(;i&&i!==n.documentElement;){let n=mt(i);if(n&&i!==e&&yt(t,n))return r.unshift(`#${T(n)}`),r.join(` > `);let a=ht(i);r.unshift(_t(i)>1?`${a}:nth-of-type(${gt(i)})`:a),i=i.parentElement}return C(t)?r.join(` > `):r.length?`html > ${r.join(` > `)}`:`html`}function xt(e,t){let n;try{n=Array.from(e.querySelectorAll(t)).slice(0,50)}catch{return null}if(!C(e)||t.startsWith(`#`))return n[0]??null;let r=t.split(` > `).length;return n.find(t=>{let n=t;for(let e=1;e<r&&n;e++)n=n.parentElement;return n?.parentNode===e})??null}function St(e,t){let n=ht(e),r=pt(e,t);if(r)return n+ft(r.attr,r.value);let i=n;for(let t of w(e).slice(0,2))i+=`.${T(t)}`;for(let r of[`name`,`type`,`role`]){let a=e.getAttribute(r);if(a&&a.length<=40&&je(r,t)){if(r===`type`&&n!==`input`&&n!==`button`)continue;i+=ft(r,a)}}let a=e.getAttribute(`aria-label`);return a&&a.length<=60&&!e.closest(v)&&(i+=ft(`aria-label`,a)),i}function Ct(e,t={}){let n=e.ownerDocument,r=Xe(e),i=mt(e);if(i&&yt(r,i))return`#${T(i)}`;let a=[],o=e;for(let e=0;o&&e<6;e++){if(o===n.documentElement||o===n.body){a.unshift(ht(o));break}let i=mt(o);if(e>0&&i&&yt(r,i)){a.unshift(`#${T(i)}`);let e=a.join(` > `);if(vt(r,e)===1)return e;break}a.unshift(St(o,t));let s=a.join(` > `);if(vt(r,s)===1)return s;let c=o.parentElement;if(c&&vt(c,`:scope > ${a[0]}`)>1&&(a[0]=`${a[0]}:nth-of-type(${gt(o)})`,s=a.join(` > `),vt(r,s)===1))return s;o=o.parentElement}let s=a.join(` > `);return vt(r,s)===1?s:void 0}function wt(e,t){let n={};if(e.closest(v))return n;for(let r of dt){if(!je(r,t)||r===`value`&&e.tagName!==`BUTTON`&&e.getAttribute(`type`)!==`submit`)continue;let i=e.getAttribute(r);i&&(n[r]=i.slice(0,200))}return n}function Tt(e){let t=[],n=e.parentElement;for(;n&&t.length<5&&n!==n.ownerDocument.documentElement;){let e=mt(n),r={tag:n.tagName.toLowerCase(),classes:w(n).slice(0,3)};if(e&&(r.id=e),t.length<3&&n!==n.ownerDocument.body){let e=x(n,80);e&&(r.text=e)}t.push(r),n=n.parentElement}return t}function Et(e,t,n={}){let r=Dt(e,t,n),i=et(e,n.document??(typeof document>`u`?e.ownerDocument:document));return i.length&&(r.scope=i.map(({kind:e,host:t})=>({kind:e,host:Dt(t,void 0,n)}))),r}function Dt(e,t,n){let r=e.ownerDocument,i=Ee(e),a=De(r),o=e.getBoundingClientRect(),s=t?{x:ke(o.width?(t.x-o.left)/o.width:.5),y:ke(o.height?(t.y-o.top)/o.height:.5)}:{x:.5,y:.5},c=mt(e),l=pt(e,n),u=Ct(e,n),d=e.getAttribute(`role`)??void 0,f=e.parentNode,p=f?Array.from(f.children):[e],m={v:1,selectors:{path:bt(e),...c?{id:c}:{},...l?{testId:`${l.attr}=${l.value}`}:{},...u?{css:u}:{}},tag:e.tagName.toLowerCase(),classes:w(e),text:x(e,_.anchorTextMaxLength),attrs:wt(e,n),ancestors:Tt(e),siblingIndex:p.indexOf(e),siblingCount:p.length,rect:i,offset:s,viewport:a,docSize:Oe(r)};d&&(m.role=d);let h=Te(e);return h&&(m.componentName=h),m}function Ot(e,t={}){let n=Ue(e);if(!n)return null;let r=We(e,n);if(!r)return null;let i=e.getClientRects()[0]??e.getBoundingClientRect(),a=Et(n,{x:i.left,y:i.top+i.height/2},t);return a.quote=r,{element:n,anchor:a}}function kt(e,t,n=()=>!1){let r=t.left+t.width,i=t.top+t.height,a=[[t.left+1,t.top+1],[r-1,t.top+1],[t.left+1,i-1],[r-1,i-1]],o=e=>n(e)||e.closest(`[data-nuni]`)!==null,s=null;for(let[t,n]of a){let r=e.elementsFromPoint(t,n).find(e=>!o(e));r&&(s=s?At(s,r):r)}let c=s??e.body;for(;c.parentElement&&c!==e.body;){let e=c.getBoundingClientRect();if(e.left<=t.left+1&&e.top<=t.top+1&&e.right>=r-1&&e.bottom>=i-1)break;c=c.parentElement}return c}function At(e,t){let n=/* @__PURE__ */ new Set;for(let t=e;t;t=t.parentElement)n.add(t);for(let e=t;e;e=e.parentElement)if(n.has(e))return e;return e.ownerDocument.body}function jt(e,t,n={}){let r=Et(e,{x:t.left+t.width,y:t.top},n),i=e.getBoundingClientRect(),a=i.width?ke((t.left-i.left)/i.width):0,o=i.height?ke((t.top-i.top)/i.height):0;return r.region={x:a,y:o,w:i.width?Math.min(1-a,t.width/i.width):1,h:i.height?Math.min(1-o,t.height/i.height):1},r}function Mt(){return{byTag:/* @__PURE__ */ new Map,elements:/* @__PURE__ */ new Map,text:/* @__PURE__ */ new WeakMap,content:/* @__PURE__ */ new WeakMap,words:/* @__PURE__ */ new WeakMap}}function Nt(e,t,n){if(!n)return x(e,t);let r=n.text.get(e);r||n.text.set(e,r=/* @__PURE__ */ new Map);let i=r.get(t);return i===void 0&&r.set(t,i=x(e,t)),i}function Pt(e,t){if(!t)return e.textContent??``;let n=t.content.get(e);return n===void 0&&t.content.set(e,n=e.textContent??``),n}function Ft(e,t){let n=t?.words.get(e);return n===void 0&&(n=Ne(Pt(e,t)),t?.words.set(e,n)),n}function It(e,t,n){let r=()=>C(e)?e.querySelectorAll(t):e.getElementsByTagName(t);if(!n)return r();let i=n.byTag.get(e);i||n.byTag.set(e,i=/* @__PURE__ */ new Map);let a=i.get(t);return a||i.set(t,a=Array.from(r())),a}function Lt(e,t,n){let r=n?.elements.get(e);if(r)return r;let i=Ze(e),a=C(e)?e:i.body??i.documentElement,o=i.createTreeWalker(a,1),s=[];for(let e=o.nextNode();e&&s.length<t;e=o.nextNode())s.push(e);return n?.elements.set(e,s),s}let Rt={exact:.9,high:.72,low:.55},zt=3e3;function Bt(e,t,n=20){if(!t)return[];try{return Array.from(e.querySelectorAll(t)).slice(0,n)}catch{return[]}}function Vt(e,t){if(!t)return!1;try{return e.matches(t)}catch{return!1}}function Ht(e,t){if(!e.length&&!t.length)return 1;let n=new Set(e),r=0;for(let e of new Set(t))n.has(e)&&r++;return r/(n.size+new Set(t).size-r)}function Ut(e){let t=e.indexOf(`=`);return t>0?[e.slice(0,t),e.slice(t+1)]:null}function Wt(e,t){return`[${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"]`}function Gt(e,t){try{let n=new URL(e,t.baseURI);return n.pathname.replace(/\/$/,``)+n.search}catch{return e}}function Kt(e){let t=e.parentElement;if(!t)return 0;let n=w(e).join(` `),r=0;for(let i of Array.from(t.children))i!==e&&i.tagName===e.tagName&&w(i).join(` `)===n&&r++;return r}let qt=/* @__PURE__ */ new Set([`href`,`name`,`aria-label`,`src`,`for`,`placeholder`,`alt`,`title`]);function Jt(e,t,n,r,i,a){let o=0,s=0,c=(e,t)=>{o+=e*t,s+=e};c(1,+(t.tagName.toLowerCase()===e.tag));let l=!1;if(e.selectors.id){let n=t.getAttribute(`id`)===e.selectors.id;l||(l=n),c(3,+!!n)}if(e.selectors.testId){let n=Ut(e.selectors.testId),r=!!(n&&t.getAttribute(n[0])===n[1]);l||(l=r),c(4,+!!r)}let u=Vt(t,e.selectors.css);e.selectors.css&&c(1.5,+!!u);let d=r.pathMatch===t;c(1,+!!d),e.classes&&e.classes.length&&c(1.5,Ht(w(t),e.classes));let f=Object.keys(e.attrs).filter(e=>je(e,i)),p=!1;if(f.length){let r=0,i=0,a=0;for(let o of f){let s=qt.has(o);s&&i++;let c=t.getAttribute(o);if(c==null)continue;let l=e.attrs[o];(o===`href`||o===`src`?Gt(c,n)===Gt(l,n):c===l)?(r++,s&&a++):r+=S(c,l)*.5}c(2,r/f.length),p=i>0&&a===i}e.role&&c(.5,+(t.getAttribute(`role`)===e.role)),e.componentName&&c(.5,+(Te(t)===e.componentName));let m=Nt(t,120,a),h=e.text?S(m,e.text):m?.3:1;c(e.text?3:1,h);let ee=e.quote?Ft(t,a).includes(e.quote.exact):null;ee!==null&&c(3,+!!ee);let te=0,ne=0,g=null,_=t.parentElement;e.ancestors.forEach((t,n)=>{let r=1-n*.15;if(ne+=r,!_)return;let i=_.tagName.toLowerCase()===t.tag?.4:0,o=_.getAttribute(`id`);t.id?i+=o===t.id?.35:0:i+=.35*(o?.5:1),i+=.25*Ht(w(_),t.classes),te+=r*i,g===null&&t.text&&t.text!==e.text&&(g=S(Nt(_,80,a),t.text)),_=_.parentElement}),ne&&c(1.5,te/ne),g!==null&&c(2,g);let re=t.parentNode,ie=re?Array.prototype.indexOf.call(re.children,t):0;c(.5,Math.max(0,1-Math.abs(ie-e.siblingIndex)/3));let v=Math.max(0,1-Math.abs(r.viewportRatio-1)*2),y=t.getBoundingClientRect(),ae=y.width+y.height>0;if(v>0&&e.rect.w+e.rect.h>0&&ae){let t=n.defaultView,i=y.left+(t?.scrollX??0)+y.width/2,a=y.top+(t?.scrollY??0)+y.height/2,o=(e.rect.x+e.rect.w/2)*r.viewportRatio,s=e.rect.y+e.rect.h/2,l=Math.hypot(i-o,a-s);c(1.5*v,Math.exp(-l/250));let u=Math.min(y.width,e.rect.w)/Math.max(y.width,e.rect.w,1),d=Math.min(y.height,e.rect.h)/Math.max(y.height,e.rect.h,1);c(.5*v,u*d)}let oe=s?o/s:0,se=(u||!e.selectors.css)&&d&&p,ce=r.quoteOnly===t?Math.max(h,.9):h;if(e.text.length>=2&&ce<.999){let e=Kt(t)>0?.2+.8*ce*ce:.7+.3*ce;oe*=l||se?Math.max(e,.92):e}return ee===!1&&(oe*=.85),{el:t,score:oe,text:h,context:g,strong:l||se,rendered:ae}}function Yt(e,t,n,r){let i=Ze(t),a=/* @__PURE__ */ new Set,o=e=>e===i.documentElement||(n.isIgnored?.(e)??!1),s=e=>{e&&!o(e)&&a.add(e)};if(e.selectors.id&&s(C(t)?Bt(t,`#${T(e.selectors.id)}`,1)[0]:t.getElementById(e.selectors.id)),e.selectors.testId){let n=Ut(e.selectors.testId);n&&Bt(t,Wt(n[0],n[1])).forEach(s)}Bt(t,e.selectors.css).forEach(s);let c=xt(t,e.selectors.path);s(c);let l=e.text.slice(0,24).toLowerCase(),u=It(t,e.tag,r),d=u.length<=zt;for(let e=0;e<u.length&&e<zt*2;e++){let t=u[e];if(d){s(t);continue}let n=Pt(t,r).toLowerCase();l&&n.includes(l)&&s(t)}if(e.text.length>=3){let n=e.text.toLowerCase();for(let i of Lt(t,zt*3,r)){if(i.tagName.toLowerCase()===e.tag)continue;let t=Pt(i,r);!t||t.length>n.length*3+20||Nt(i,120,r).toLowerCase()===n&&s(i)}}return{candidates:a,pathMatch:c}}let E={lost:0,low:1,high:2,exact:3};function Xt(e,t=document,n={},r){let i=t,a=`exact`,o={element:null,confidence:`lost`,score:0};for(let t of e.scope??[]){let e=Zt(t.host,i,n,r);if(!e.element)return o;let s=e.confidence;if(t.host.text){if(e.text<.9&&E[s]<E.high)return o;e.text>=.999&&e.margin>=.1&&s===`low`&&(s=`high`)}let c=t.kind===`shadow`?e.element.shadowRoot:$e(e.element);if(!c)return o;E[s]<E[a]&&(a=s),i=c}let{text:s,margin:c,...l}=Zt(e,i,n,r);if(l.element&&E[a]<E[l.confidence]&&(l.confidence=a),l.element&&e.quote){let t=Ge(l.element,e.quote);t&&(l.range=t.range),(!t||!t.exact)&&E[l.confidence]>E.low&&(l.confidence=`low`)}return l}function Zt(e,t,n,r){let i=Ze(t);if(!C(t)&&(e.tag===`body`||e.tag===`html`))return{element:i.body,confidence:`exact`,score:1,text:1,margin:1};let{candidates:a,pathMatch:o}=Yt(e,t,n,r);if(!a.size)return{element:null,confidence:`lost`,score:0,text:0,margin:0};let s=i.defaultView,c=e.viewport.w&&s?.innerWidth?s.innerWidth/e.viewport.w:1,l=null;if(e.quote){let t=e.quote.exact,n=[...a].filter(e=>Ft(e,r).includes(t)),i=n.filter(e=>!n.some(t=>t!==e&&e.contains(t)));i.length===1&&(l=i[0])}let u=[];for(let t of a)u.push(Jt(e,t,i,{pathMatch:o,viewportRatio:c,quoteOnly:l},n,r));let d=e.rect.w+e.rect.h>0&&u.some(e=>e.rendered),f=e=>!d||e.rendered;if(u.filter(t=>t.text>=.999&&t.el.tagName.toLowerCase()===e.tag&&f(t)).length>1)for(let e of u)e.context===null||e.strong||(e.score*=.2+.8*e.context*e.context);u.sort((e,t)=>t.score-e.score);let p=u[0],m=u.find(e=>e.el!==p.el&&!p.el.contains(e.el)&&!e.el.contains(p.el)&&(!p.rendered||f(e)));if(p.score<Rt.low)return{element:null,confidence:`lost`,score:p.score,text:p.text,margin:0};let h=p.score>=Rt.exact&&p.text>=.999?`exact`:p.score>=Rt.high?`high`:`low`,ee=m?p.score-m.score:1;return ee<.03&&(h=`low`),{element:p.el,confidence:h,score:p.score,text:p.text,margin:ee}}let Qt=/* @__PURE__ */ new Set([`SPAN`,`STRONG`,`EM`,`B`,`I`,`SMALL`,`MARK`,`SUB`,`SUP`,`ABBR`,`CODE`,`KBD`,`TIME`,`U`,`S`]);function $t(e){let t=e,n=t.closest(`svg`);n&&(t=n.parentElement??n);let r=t.closest(`a[href], button, label, summary, select, textarea, input, [role=button], [role=link], [role=tab], [role=menuitem], [role=checkbox], [role=switch], [role=option]`);if(r)return r;for(;Qt.has(t.tagName)&&t.parentElement&&t.parentElement!==t.ownerDocument.body&&!t.id;)t=t.parentElement;return t}for(var D=[],O=[],en=Uint8Array,tn=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,k=0,nn=tn.length;k<nn;++k)D[k]=tn[k],O[tn.charCodeAt(k)]=k;O[45]=62,O[95]=63;function rn(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function an(e,t,n){return(t+n)*3/4-n}function on(e){for(var t,n=rn(e),r=n[0],i=n[1],a=new en(an(e,r,i)),o=0,s=i>0?r-4:r,c=0;c<s;c+=4)t=O[e.charCodeAt(c)]<<18|O[e.charCodeAt(c+1)]<<12|O[e.charCodeAt(c+2)]<<6|O[e.charCodeAt(c+3)],a[o++]=t>>16&255,a[o++]=t>>8&255,a[o++]=t&255;return i===2&&(t=O[e.charCodeAt(c)]<<2|O[e.charCodeAt(c+1)]>>4,a[o++]=t&255),i===1&&(t=O[e.charCodeAt(c)]<<10|O[e.charCodeAt(c+1)]<<4|O[e.charCodeAt(c+2)]>>2,a[o++]=t>>8&255,a[o++]=t&255),a}function sn(e){return D[e>>18&63]+D[e>>12&63]+D[e>>6&63]+D[e&63]}function cn(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(sn(r));return i.join(``)}function ln(e){for(var t,n=e.length,r=n%3,i=[],a=16383,o=0,s=n-r;o<s;o+=a)i.push(cn(e,o,o+a>s?s:o+a));return r===1?(t=e[n-1],i.push(D[t>>2]+D[t<<4&63]+`==`)):r===2&&(t=(e[n-2]<<8)+e[n-1],i.push(D[t>>10]+D[t>>4&63]+D[t<<2&63]+`=`)),i.join(``)}function A(e){if(e===void 0)return{};if(!dn(e))throw Error(`The arguments to a Convex function must be an object. Received: ${e}`);return e}function un(e){if(e===void 0)throw Error(`Client created with undefined deployment address. If you used an environment variable, check that it's set.`);if(typeof e!=`string`)throw Error(`Invalid deployment address: found ${e}".`);if(!(e.startsWith(`http:`)||e.startsWith(`https:`)))throw Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${e}".`);try{new URL(e)}catch{throw Error(`Invalid deployment address: "${e}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(e.endsWith(`.convex.site`))throw Error(`Invalid deployment address: "${e}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}function dn(e){let t=typeof e==`object`,n=Object.getPrototypeOf(e),r=n===null||n===Object.prototype||n?.constructor?.name===`Object`;return t&&r}let j=BigInt(`-9223372036854775808`),fn=BigInt(`9223372036854775807`),pn=BigInt(`0`),mn=BigInt(`8`),hn=BigInt(`256`),gn=`This commit timestamp is unresolved: its value is assigned when the mutation commits. Read the document after the mutation completes to get its value.`;var _n=class{[Symbol.toPrimitive](e){if(e===`string`)return this.toString();throw Error(gn)}valueOf(){throw Error(gn)}toJSON(){throw Error(gn)}toString(){return`[unresolved commit timestamp]`}};let vn=new _n;function yn(e){return Number.isNaN(e)||!Number.isFinite(e)||Object.is(e,-0)}function bn(e){e<pn&&(e-=j+j);let t=e.toString(16);t.length%2==1&&(t=`0`+t);let n=new Uint8Array(/* @__PURE__ */ new ArrayBuffer(8)),r=0;for(let i of t.match(/.{2}/g).reverse())n.set([parseInt(i,16)],r++),e>>=mn;return ln(n)}function xn(e){let t=on(e);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);let n=pn,r=pn;for(let e of t)n+=BigInt(e)*hn**r,r++;return n>fn&&(n+=j+j),n}function Sn(e){if(e<j||fn<e)throw Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);let t=/* @__PURE__ */ new ArrayBuffer(8);return new DataView(t).setBigInt64(0,e,!0),ln(new Uint8Array(t))}function Cn(e){let t=on(e);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);return new DataView(t.buffer).getBigInt64(0,!0)}let wn=DataView.prototype.setBigInt64?Sn:bn,Tn=DataView.prototype.getBigInt64?Cn:xn,En=1024;function Dn(e){if(e.length>En)throw Error(`Field name ${e} exceeds maximum field name length ${En}.`);if(e.startsWith(`$`))throw Error(`Field name ${e} starts with a '$', which is reserved.`);for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n<32||n>=127)throw Error(`Field name ${e} has invalid character '${e[t]}': Field names can only contain non-control ASCII characters`)}}function M(e){if(e===null||typeof e==`boolean`||typeof e==`number`||typeof e==`string`)return e;if(Array.isArray(e))return e.map(e=>M(e));if(typeof e!=`object`)throw Error(`Unexpected type of ${e}`);let t=Object.entries(e);if(t.length===1){let n=t[0][0];if(n===`$bytes`){if(typeof e.$bytes!=`string`)throw Error(`Malformed $bytes field on ${e}`);return on(e.$bytes).buffer}if(n===`$integer`){if(typeof e.$integer!=`string`)throw Error(`Malformed $integer field on ${e}`);return Tn(e.$integer)}if(n===`$float`){if(typeof e.$float!=`string`)throw Error(`Malformed $float field on ${e}`);let t=on(e.$float);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $float`);let n=new DataView(t.buffer).getFloat64(0,!0);if(!yn(n))throw Error(`Float ${n} should be encoded as a number`);return n}if(n===`$commitTs`){if(e.$commitTs!==null)throw Error(`Malformed $commitTs field on ${e}`);return vn}if(n===`$set`)throw Error(`Received a Set which is no longer supported as a Convex type.`);if(n===`$map`)throw Error(`Received a Map which is no longer supported as a Convex type.`)}let n={};for(let[t,r]of Object.entries(e))Dn(t),n[t]=M(r);return n}function N(e){let t=JSON.stringify(e,(e,t)=>t===void 0?`undefined`:typeof t==`bigint`?`${t.toString()}n`:t);if(t.length>16384){let e=16370,n=t.codePointAt(e-1);return n!==void 0&&n>65535&&--e,t.substring(0,e)+`[...truncated]`}return t}function On(e,t,n,r){if(e===void 0){let e=n&&` (present at path ${n} in original object ${N(t)})`;throw Error(`undefined is not a valid Convex value${e}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(e===null)return e;if(typeof e==`bigint`){if(e<j||fn<e)throw Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);return{$integer:wn(e)}}if(typeof e==`number`){if(yn(e)){let t=/* @__PURE__ */ new ArrayBuffer(8);return new DataView(t).setFloat64(0,e,!0),{$float:ln(new Uint8Array(t))}}return e}if(typeof e==`boolean`||typeof e==`string`)return e;if(e instanceof ArrayBuffer)return{$bytes:ln(new Uint8Array(e))};if(e instanceof _n)return{$commitTs:null};if(Array.isArray(e))return e.map((e,r)=>On(e,t,n+`[${r}]`,!1));if(e instanceof Set)throw Error(kn(n,`Set`,[...e],t));if(e instanceof Map)throw Error(kn(n,`Map`,[...e],t));if(!dn(e)){let r=e?.constructor?.name,i=r?`${r} `:``;throw Error(kn(n,i,e,t))}let i={},a=Object.entries(e);a.sort(([e,t],[n,r])=>e===n?0:e<n?-1:1);for(let[e,o]of a)o===void 0?r&&(Dn(e),i[e]=An(o,t,n+`.${e}`)):(Dn(e),i[e]=On(o,t,n+`.${e}`,!1));return i}function kn(e,t,n,r){return e?`${t}${N(n)} is not a supported Convex type (present at path ${e} in original object ${N(r)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${t}${N(n)} is not a supported Convex type.`}function An(e,t,n){if(e===void 0)return{$undefined:null};if(t===void 0)throw Error(`Programming error. Current value is ${N(e)} but original value is undefined`);return On(e,t,n,!1)}function P(e){return On(e,e,``,!1)}var jn=Object.defineProperty,Mn=(e,t,n)=>t in e?jn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Nn=(e,t,n)=>Mn(e,typeof t==`symbol`?t:t+``,n),Pn,Fn;let In=Symbol.for(`ConvexError`);var Ln=class extends (Fn=Error,Pn=In,Fn){constructor(e){super(typeof e==`string`?e:N(e)),Nn(this,`name`,`ConvexError`),Nn(this,`data`),Nn(this,Pn,!0),this.data=e}};let Rn=`1.46.0`,zn=Symbol.for(`functionName`),Bn=Symbol.for(`toReferencePath`);function Vn(e){return e[Bn]??null}function Hn(e){return e.startsWith(`function://`)}function Un(e){let t;if(typeof e==`string`)t=Hn(e)?{functionHandle:e}:{name:e};else if(e[zn])t={name:e[zn]};else{let n=Vn(e);if(!n)throw Error(`${e} is not a functionReference`);t={reference:n}}return t}function F(e){let t=Un(e);if(t.name===void 0)throw t.functionHandle===void 0?t.reference===void 0?Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(t)}`):Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${t.reference}`):Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${t.functionHandle}`);if(typeof e==`string`)return e;let n=e[zn];if(!n)throw Error(`${e} is not a functionReference`);return n}function Wn(e=[]){return new Proxy({},{get(t,n){if(typeof n==`string`)return Wn([...e,n]);if(n===zn){if(e.length<2){let t=[`api`,...e].join(`.`);throw Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${t}\``)}let t=e.slice(0,-1).join(`/`),n=e[e.length-1];return n==="default"?t:t+`:`+n}if(n===Symbol.toStringTag)return`FunctionReference`}})}let Gn=Wn();function Kn(e,t){return new Proxy({},{get(n,r){if(typeof r==`string`)return Kn(e,[...t,r]);if(r===Bn){if(t.length<1){let n=[e,...t].join(`.`);throw Error(`API path is expected to be of the form \`${e}.childComponent.functionName\`. Found: \`${n}\``)}return`_reference/childComponent/`+t.join(`/`)}}})}let qn=()=>Kn(`components`,[]),I=Gn;qn();var Jn=Object.defineProperty,Yn=(e,t,n)=>t in e?Jn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Xn=(e,t,n)=>Yn(e,typeof t==`symbol`?t:t+``,n);function Zn(e){switch(e){case`query`:return`Q`;case`mutation`:return`M`;case`action`:return`A`;case`any`:return`?`}}var Qn=class{constructor(e){Xn(this,`_onLogLineFuncs`),Xn(this,`_verbose`),this._onLogLineFuncs={},this._verbose=e.verbose}addLogLineListener(e){let t=Math.random().toString(36).substring(2,15);for(let e=0;e<10&&this._onLogLineFuncs[t]!==void 0;e++)t=Math.random().toString(36).substring(2,15);return this._onLogLineFuncs[t]=e,()=>{delete this._onLogLineFuncs[t]}}logVerbose(...e){if(this._verbose)for(let t of Object.values(this._onLogLineFuncs))t(`debug`,`${(/* @__PURE__ */ new Date()).toISOString()}`,...e)}log(...e){for(let t of Object.values(this._onLogLineFuncs))t(`info`,...e)}warn(...e){for(let t of Object.values(this._onLogLineFuncs))t(`warn`,...e)}error(...e){for(let t of Object.values(this._onLogLineFuncs))t(`error`,...e)}};function $n(e){let t=new Qn(e);return t.addLogLineListener((e,...t)=>{switch(e){case`debug`:console.debug(...t);break;case`info`:console.log(...t);break;case`warn`:console.warn(...t);break;case`error`:console.error(...t);break;default:console.log(...t)}}),t}function er(e){return new Qn(e)}function tr(e,t,n,r,i){let a=Zn(n);if(typeof i==`object`&&(i=`ConvexError ${JSON.stringify(i.errorData,null,2)}`),t===`info`){let t=i.match(/^\[.*?\] /);if(t===null){e.error(`[CONVEX ${a}(${r})] Could not parse console.log`);return}let n=i.slice(1,t[0].length-2),o=i.slice(t[0].length);e.log(`%c[CONVEX ${a}(${r})] [${n}]`,`color:rgb(0, 145, 255)`,o)}else e.error(`[CONVEX ${a}(${r})] ${i}`)}function nr(e,t){let n=`[CONVEX FATAL ERROR] ${t}`;return e.error(n),Error(n)}function L(e,t,n){return`[CONVEX ${Zn(e)}(${t})] ${n.errorMessage}
|
|
9
|
-
Called by client`}function rr(e,t){return t.data=e.errorData,t}function R(e){let t=e.split(`:`),n,r;return t.length===1?(n=t[0],r=`default`):(n=t.slice(0,t.length-1).join(`:`),r=t[t.length-1]),n.endsWith(`.js`)&&(n=n.slice(0,-3)),`${n}:${r}`}function z(e,t){return JSON.stringify({udfPath:R(e),args:P(t)})}function ir(e,t,n){let{initialNumItems:r,id:i}=n;return JSON.stringify({type:`paginated`,udfPath:R(e),args:P(t),options:P({initialNumItems:r,id:i})})}function ar(e){return JSON.parse(e).type===`paginated`}var or=Object.defineProperty,sr=(e,t,n)=>t in e?or(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,B=(e,t,n)=>sr(e,typeof t==`symbol`?t:t+``,n),cr=class{constructor(){B(this,`nextQueryId`),B(this,`querySetVersion`),B(this,`querySet`),B(this,`queryIdToToken`),B(this,`identityVersion`),B(this,`auth`),B(this,`outstandingQueriesOlderThanRestart`),B(this,`outstandingAuthOlderThanRestart`),B(this,`paused`),B(this,`pendingQuerySetModifications`),this.nextQueryId=0,this.querySetVersion=0,this.identityVersion=0,this.querySet=/* @__PURE__ */ new Map,this.queryIdToToken=/* @__PURE__ */ new Map,this.outstandingQueriesOlderThanRestart=/* @__PURE__ */ new Set,this.outstandingAuthOlderThanRestart=!1,this.paused=!1,this.pendingQuerySetModifications=/* @__PURE__ */ new Map}hasSyncedPastLastReconnect(){return this.outstandingQueriesOlderThanRestart.size===0&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(e,t,n,r){let i=R(e),a=z(i,t),o=this.querySet.get(a);if(o!==void 0)return o.numSubscribers+=1,{queryToken:a,modification:null,unsubscribe:()=>this.removeSubscriber(a)};{let e=this.nextQueryId++,o={id:e,canonicalizedUdfPath:i,args:t,numSubscribers:1,journal:n,componentPath:r};this.querySet.set(a,o),this.queryIdToToken.set(e,a);let s=this.querySetVersion,c=this.querySetVersion+1,l={type:`Add`,queryId:e,udfPath:i,args:[P(t)],journal:n,componentPath:r};return this.paused?this.pendingQuerySetModifications.set(e,l):this.querySetVersion=c,{queryToken:a,modification:{type:`ModifyQuerySet`,baseVersion:s,newVersion:c,modifications:[l]},unsubscribe:()=>this.removeSubscriber(a)}}}transition(e){for(let t of e.modifications)switch(t.type){case`QueryUpdated`:case`QueryFailed`:{this.outstandingQueriesOlderThanRestart.delete(t.queryId);let e=t.journal;if(e!==void 0){let n=this.queryIdToToken.get(t.queryId);n!==void 0&&(this.querySet.get(n).journal=e)}break}case`QueryRemoved`:this.outstandingQueriesOlderThanRestart.delete(t.queryId);break;default:throw Error(`Invalid modification ${t.type}`)}}queryId(e,t){let n=z(R(e),t),r=this.querySet.get(n);return r===void 0?null:r.id}isCurrentOrNewerAuthVersion(e){return e>=this.identityVersion}getAuth(){return this.auth}setAuth(e){this.auth={tokenType:`User`,value:e};let t=this.identityVersion;return this.paused||(this.identityVersion=t+1),{type:`Authenticate`,baseVersion:t,...this.auth}}setAdminAuth(e,t){let n={tokenType:`Admin`,value:e,impersonating:t};this.auth=n;let r=this.identityVersion;return this.paused||(this.identityVersion=r+1),{type:`Authenticate`,baseVersion:r,...n}}clearAuth(){this.auth=void 0,this.markAuthCompletion();let e=this.identityVersion;return this.paused||(this.identityVersion=e+1),{type:`Authenticate`,tokenType:`None`,baseVersion:e}}hasAuth(){return!!this.auth}isNewAuth(e){return this.auth?.value!==e}queryPath(e){let t=this.queryIdToToken.get(e);return t?this.querySet.get(t).canonicalizedUdfPath:null}queryArgs(e){let t=this.queryIdToToken.get(e);return t?this.querySet.get(t).args:null}queryToken(e){return this.queryIdToToken.get(e)??null}queryJournal(e){return this.querySet.get(e)?.journal}restart(){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();let e=[];for(let t of this.querySet.values()){let n={type:`Add`,queryId:t.id,udfPath:t.canonicalizedUdfPath,args:[P(t.args)],journal:t.journal,componentPath:t.componentPath};e.push(n),this.outstandingQueriesOlderThanRestart.add(t.id)}this.querySetVersion=1;let t={type:`ModifyQuerySet`,baseVersion:0,newVersion:1,modifications:e};if(!this.auth)return this.identityVersion=0,[t,void 0];this.outstandingAuthOlderThanRestart=!0;let n={type:`Authenticate`,baseVersion:0,...this.auth};return this.identityVersion=1,[t,n]}pause(){this.paused=!0}resume(){let e=this.pendingQuerySetModifications.size>0?{type:`ModifyQuerySet`,baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,t=this.auth===void 0?void 0:{type:`Authenticate`,baseVersion:this.identityVersion++,...this.auth};return this.unpause(),[e,t]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(e){let t=this.querySet.get(e);if(t.numSubscribers>1)return--t.numSubscribers,null;{this.querySet.delete(e),this.queryIdToToken.delete(t.id),this.outstandingQueriesOlderThanRestart.delete(t.id);let n=this.querySetVersion,r=this.querySetVersion+1,i={type:`Remove`,queryId:t.id};return this.paused?this.pendingQuerySetModifications.has(t.id)?this.pendingQuerySetModifications.delete(t.id):this.pendingQuerySetModifications.set(t.id,i):this.querySetVersion=r,{type:`ModifyQuerySet`,baseVersion:n,newVersion:r,modifications:[i]}}}},lr=Object.defineProperty,ur=(e,t,n)=>t in e?lr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,dr=(e,t,n)=>ur(e,typeof t==`symbol`?t:t+``,n),fr=class{constructor(e,t){this.logger=e,this.markConnectionStateDirty=t,dr(this,`inflightRequests`),dr(this,`requestsOlderThanRestart`),dr(this,`inflightMutationsCount`,0),dr(this,`inflightActionsCount`,0),this.inflightRequests=/* @__PURE__ */ new Map,this.requestsOlderThanRestart=/* @__PURE__ */ new Set}request(e,t){let n=new Promise(n=>{let r=t?`Requested`:`NotSent`;this.inflightRequests.set(e.requestId,{message:e,status:{status:r,requestedAt:/* @__PURE__ */ new Date,onResult:n}}),e.type===`Mutation`?this.inflightMutationsCount++:e.type===`Action`&&this.inflightActionsCount++});return this.markConnectionStateDirty(),n}onResponse(e){let t=this.inflightRequests.get(e.requestId);if(t===void 0||t.status.status===`Completed`)return null;let n=t.message.type===`Mutation`?`mutation`:`action`,r=t.message.udfPath;for(let t of e.logLines)tr(this.logger,`info`,n,r,t);let i=t.status,a,o;if(e.success)a={success:!0,logLines:e.logLines,value:M(e.result)},o=()=>i.onResult(a);else{let t=e.result,{errorData:s}=e;tr(this.logger,`error`,n,r,t),a={success:!1,errorMessage:t,errorData:s===void 0?void 0:M(s),logLines:e.logLines},o=()=>i.onResult(a)}return e.type===`ActionResponse`||!e.success?(o(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),t.message.type===`Action`?this.inflightActionsCount--:t.message.type===`Mutation`&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:a}):(t.status={status:`Completed`,result:a,ts:e.ts,onResolve:o},null)}removeCompleted(e){let t=/* @__PURE__ */ new Map;for(let[n,r]of this.inflightRequests.entries()){let i=r.status;i.status===`Completed`&&i.ts.lessThanOrEqual(e)&&(i.onResolve(),t.set(n,i.result),r.message.type===`Mutation`?this.inflightMutationsCount--:r.message.type===`Action`&&this.inflightActionsCount--,this.inflightRequests.delete(n),this.requestsOlderThanRestart.delete(n))}return t.size>0&&this.markConnectionStateDirty(),t}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());let e=[];for(let[t,n]of this.inflightRequests){if(n.status.status===`NotSent`){n.status.status=`Requested`,e.push(n.message);continue}if(n.message.type===`Mutation`)e.push(n.message);else if(n.message.type===`Action`){if(this.inflightRequests.delete(t),this.requestsOlderThanRestart.delete(t),this.inflightActionsCount--,n.status.status===`Completed`)throw Error(`Action should never be in 'Completed' state`);n.status.onResult({success:!1,errorMessage:`Connection lost while action was in flight`,logLines:[]})}}return this.markConnectionStateDirty(),e}resume(){let e=[];for(let[,t]of this.inflightRequests)if(t.status.status===`NotSent`){t.status.status=`Requested`,e.push(t.message);continue}return e}hasIncompleteRequests(){for(let e of this.inflightRequests.values())if(e.status.status===`Requested`)return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return this.requestsOlderThanRestart.size===0}timeOfOldestInflightRequest(){if(this.inflightRequests.size===0)return null;let e=Date.now();for(let t of this.inflightRequests.values())t.status.status!==`Completed`&&t.status.requestedAt.getTime()<e&&(e=t.status.requestedAt.getTime());return new Date(e)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}},pr=Object.defineProperty,mr=(e,t,n)=>t in e?pr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,hr=(e,t,n)=>mr(e,typeof t==`symbol`?t:t+``,n),gr=class e{constructor(e){hr(this,`queryResults`),hr(this,`modifiedQueries`),this.queryResults=e,this.modifiedQueries=[]}getQuery(t,...n){let r=A(n[0]),i=F(t),a=this.queryResults.get(z(i,r));if(a!==void 0)return e.queryValue(a.result)}getAllQueries(t){let n=[],r=F(t);for(let t of this.queryResults.values())t.udfPath===R(r)&&n.push({args:t.args,value:e.queryValue(t.result)});return n}setQuery(e,t,n){let r=A(t),i=F(e),a=z(i,r),o;o=n===void 0?void 0:{success:!0,value:n,logLines:[]};let s={udfPath:i,args:r,result:o};this.queryResults.set(a,s),this.modifiedQueries.push(a)}static queryValue(e){if(e!==void 0&&e.success)return e.value}},_r=class{constructor(){hr(this,`queryResults`),hr(this,`optimisticUpdates`),this.queryResults=/* @__PURE__ */ new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,t){this.optimisticUpdates=this.optimisticUpdates.filter(e=>!t.has(e.mutationId));let n=this.queryResults;this.queryResults=new Map(e);let r=new gr(this.queryResults);for(let e of this.optimisticUpdates)e.update(r);let i=[];for(let[e,t]of this.queryResults){let r=n.get(e);(r===void 0||r.result!==t.result)&&i.push(e)}return i}applyOptimisticUpdate(e,t){this.optimisticUpdates.push({update:e,mutationId:t});let n=new gr(this.queryResults);return e(n),n.modifiedQueries}rawQueryResult(e){let t=this.queryResults.get(e);if(t!==void 0)return t.result}queryResult(e){let t=this.queryResults.get(e);if(t===void 0)return;let n=t.result;if(n!==void 0){if(n.success)return n.value;throw n.errorData===void 0?Error(L(`query`,t.udfPath,n)):rr(n,new Ln(L(`query`,t.udfPath,n)))}}hasQueryResult(e){return this.queryResults.get(e)!==void 0}queryLogs(e){return this.queryResults.get(e)?.result?.logLines}},vr=Object.defineProperty,yr=(e,t,n)=>t in e?vr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,br=(e,t,n)=>yr(e,typeof t==`symbol`?t:t+``,n),xr=class e{constructor(e,t){br(this,`low`),br(this,`high`),br(this,`__isUnsignedLong__`),this.low=e|0,this.high=t|0,this.__isUnsignedLong__=!0}static isLong(e){return(e&&e.__isUnsignedLong__)===!0}static fromBytesLE(t){return new e(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24)}toBytesLE(){let e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]}static fromNumber(t){return isNaN(t)||t<0?Sr:t>=Tr?Er:new e(t%wr|0,t/wr|0)}toString(){return(BigInt(this.high)*BigInt(wr)+BigInt(this.low)).toString()}equals(t){return e.isLong(t)||(t=e.fromValue(t)),this.high>>>31==1&&t.high>>>31==1?!1:this.high===t.high&&this.low===t.low}notEquals(e){return!this.equals(e)}comp(t){return e.isLong(t)||(t=e.fromValue(t)),this.equals(t)?0:t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(e){return this.comp(e)<=0}static fromValue(t){return typeof t==`number`?e.fromNumber(t):new e(t.low,t.high)}};let Sr=new xr(0,0),Cr=65536,wr=Cr*Cr,Tr=wr*wr,Er=new xr(-1,-1);var Dr=Object.defineProperty,Or=(e,t,n)=>t in e?Dr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,kr=(e,t,n)=>Or(e,typeof t==`symbol`?t:t+``,n),Ar=class{constructor(e,t){kr(this,`version`),kr(this,`remoteQuerySet`),kr(this,`queryPath`),kr(this,`logger`),this.version={querySet:0,ts:xr.fromNumber(0),identity:0},this.remoteQuerySet=/* @__PURE__ */ new Map,this.queryPath=e,this.logger=t}transition(e){let t=e.startVersion;if(this.version.querySet!==t.querySet||this.version.ts.notEquals(t.ts)||this.version.identity!==t.identity)throw Error(`Invalid start version: ${t.ts.toString()}:${t.querySet}:${t.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(let t of e.modifications)switch(t.type){case`QueryUpdated`:{let e=this.queryPath(t.queryId);if(e)for(let n of t.logLines)tr(this.logger,`info`,`query`,e,n);let n=M(t.value??null);this.remoteQuerySet.set(t.queryId,{success:!0,value:n,logLines:t.logLines});break}case`QueryFailed`:{let e=this.queryPath(t.queryId);if(e)for(let n of t.logLines)tr(this.logger,`info`,`query`,e,n);let{errorData:n}=t;this.remoteQuerySet.set(t.queryId,{success:!1,errorMessage:t.errorMessage,errorData:n===void 0?void 0:M(n),logLines:t.logLines});break}case`QueryRemoved`:this.remoteQuerySet.delete(t.queryId);break;default:throw Error(`Invalid modification ${t.type}`)}this.version=e.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}};function jr(e){let t=on(e);return xr.fromBytesLE(Array.from(t))}function Mr(e){return ln(new Uint8Array(e.toBytesLE()))}function Nr(e){switch(e.type){case`FatalError`:case`AuthError`:case`ActionResponse`:case`TransitionChunk`:case`Ping`:return{...e};case`MutationResponse`:return e.success?{...e,ts:jr(e.ts)}:{...e};case`Transition`:return{...e,startVersion:{...e.startVersion,ts:jr(e.startVersion.ts)},endVersion:{...e.endVersion,ts:jr(e.endVersion.ts)}}}}function Pr(e){switch(e.type){case`Authenticate`:case`ModifyQuerySet`:case`Mutation`:case`Action`:case`Event`:return{...e};case`Connect`:return e.maxObservedTimestamp===void 0?{...e,maxObservedTimestamp:void 0}:{...e,maxObservedTimestamp:Mr(e.maxObservedTimestamp)}}}var Fr=Object.defineProperty,Ir=(e,t,n)=>t in e?Fr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,V=(e,t,n)=>Ir(e,typeof t==`symbol`?t:t+``,n);let Lr;function H(){return Lr===void 0&&(Lr=Date.now()),typeof performance>`u`||!performance.now?Date.now():Math.round(Lr+performance.now())}function Rr(){return`t=${Math.round((H()-Lr)/100)/10}s`}let zr={InternalServerError:{timeout:1e3},SubscriptionsWorkerFullError:{timeout:3e3},TooManyConcurrentRequests:{timeout:3e3},CommitterFullError:{timeout:3e3},AwsTooManyRequestsException:{timeout:3e3},ExecuteFullError:{timeout:3e3},SystemTimeoutError:{timeout:3e3},ExpiredInQueue:{timeout:3e3},VectorIndexesUnavailable:{timeout:1e3},SearchIndexesUnavailable:{timeout:1e3},TableSummariesUnavailable:{timeout:1e3},VectorIndexTooLarge:{timeout:3e3},SearchIndexTooLarge:{timeout:3e3},TooManyWritesInTimePeriod:{timeout:3e3}};function Br(e){if(e===void 0)return`Unknown`;for(let t of Object.keys(zr))if(e.startsWith(t))return t;return`Unknown`}var Vr=class{constructor(e,t,n,r,i,a){this.markConnectionStateDirty=i,this.debug=a,V(this,`socket`),V(this,`connectionCount`),V(this,`_hasEverConnected`,!1),V(this,`lastCloseReason`),V(this,`transitionChunkBuffer`,null),V(this,`defaultInitialBackoff`),V(this,`maxBackoff`),V(this,`retries`),V(this,`serverInactivityThreshold`),V(this,`reconnectDueToServerInactivityTimeout`),V(this,`scheduledReconnect`,null),V(this,`networkOnlineHandler`,null),V(this,`pendingNetworkRecoveryInfo`,null),V(this,`uri`),V(this,`onOpen`),V(this,`onResume`),V(this,`onMessage`),V(this,`webSocketConstructor`),V(this,`logger`),V(this,`onServerDisconnectError`),this.webSocketConstructor=n,this.socket={state:`disconnected`},this.connectionCount=0,this.lastCloseReason=`InitialConnect`,this.defaultInitialBackoff=1e3,this.maxBackoff=16e3,this.retries=0,this.serverInactivityThreshold=6e4,this.reconnectDueToServerInactivityTimeout=null,this.uri=e,this.onOpen=t.onOpen,this.onResume=t.onResume,this.onMessage=t.onMessage,this.onServerDisconnectError=t.onServerDisconnectError,this.logger=r,this.setupNetworkListener(),this.connect()}setSocketState(e){this.socket=e,this._logVerbose(`socket state changed: ${this.socket.state}, paused: ${`paused`in this.socket?this.socket.paused:void 0}`),this.markConnectionStateDirty()}setupNetworkListener(){typeof window<`u`&&typeof window.addEventListener==`function`&&this.networkOnlineHandler===null&&(this.networkOnlineHandler=()=>{this._logVerbose(`network online event detected`),this.tryReconnectImmediately()},window.addEventListener(`online`,this.networkOnlineHandler),this._logVerbose(`network online event listener registered`))}cleanupNetworkListener(){this.networkOnlineHandler&&typeof window<`u`&&typeof window.removeEventListener==`function`&&(window.removeEventListener(`online`,this.networkOnlineHandler),this.networkOnlineHandler=null,this._logVerbose(`network online event listener removed`))}assembleTransition(e){if(e.partNumber<0||e.partNumber>=e.totalParts||e.totalParts===0||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==e.totalParts||this.transitionChunkBuffer.transitionId!==e.transitionId))throw this.transitionChunkBuffer=null,Error(`Invalid TransitionChunk`);if(this.transitionChunkBuffer===null&&(this.transitionChunkBuffer={chunks:[],totalParts:e.totalParts,transitionId:e.transitionId}),e.partNumber!==this.transitionChunkBuffer.chunks.length){let t=this.transitionChunkBuffer.chunks.length;throw this.transitionChunkBuffer=null,Error(`TransitionChunk received out of order: expected part ${t}, got ${e.partNumber}`)}if(this.transitionChunkBuffer.chunks.push(e.chunk),this.transitionChunkBuffer.chunks.length===e.totalParts){let e=this.transitionChunkBuffer.chunks.join(``);this.transitionChunkBuffer=null;let t=Nr(JSON.parse(e));if(t.type!==`Transition`)throw Error(`Expected Transition, got ${t.type} after assembling chunks`);return t}return null}connect(){if(this.socket.state===`terminated`)return;if(this.socket.state!==`disconnected`&&this.socket.state!==`stopped`)throw Error(`Didn't start connection from disconnected state: `+this.socket.state);let e=new this.webSocketConstructor(this.uri);this._logVerbose(`constructed WebSocket`),this.setSocketState({state:`connecting`,ws:e,paused:`no`}),this.resetServerInactivityTimeout(),e.onopen=()=>{if(this.logger.logVerbose(`begin ws.onopen`),this.socket.state!==`connecting`)throw Error(`onopen called with socket not in connecting state`);if(this.setSocketState({state:`ready`,ws:e,paused:this.socket.paused===`yes`?`uninitialized`:`no`}),this.resetServerInactivityTimeout(),this.socket.paused===`no`&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:H()})),this.lastCloseReason!==`InitialConnect`&&(this.lastCloseReason?this.logger.log(`WebSocket reconnected at`,Rr(),`after disconnect due to`,this.lastCloseReason):this.logger.log(`WebSocket reconnected at`,Rr())),this.connectionCount+=1,this.lastCloseReason=null,this.pendingNetworkRecoveryInfo!==null){let{timeSavedMs:e}=this.pendingNetworkRecoveryInfo;this.pendingNetworkRecoveryInfo=null,this.sendMessage({type:`Event`,eventType:`NetworkRecoveryReconnect`,event:{timeSavedMs:e}}),this.logger.log(`Network recovery reconnect saved ~${Math.round(e/1e3)}s of waiting`)}},e.onerror=e=>{this.transitionChunkBuffer=null;let t=e.message;t&&this.logger.log(`WebSocket error message: ${t}`)},e.onmessage=e=>{this.resetServerInactivityTimeout();let t=e.data.length,n=Nr(JSON.parse(e.data));if(this._logVerbose(`received ws message with type ${n.type}`),n.type!==`Ping`){if(n.type===`TransitionChunk`){let e=this.assembleTransition(n);if(!e)return;n=e,this._logVerbose(`assembled full ws message of type ${n.type}`)}this.transitionChunkBuffer!==null&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${n.type} while buffering TransitionChunks`)),n.type===`Transition`&&this.reportLargeTransition({messageLength:t,transition:n}),this.onMessage(n).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())}},e.onclose=e=>{if(this._logVerbose(`begin ws.onclose`),this.transitionChunkBuffer=null,this.lastCloseReason===null&&(this.lastCloseReason=e.reason||`closed with code ${e.code}`),e.code!==1e3&&e.code!==1001&&e.code!==1005&&e.code!==4040){let t=`WebSocket closed with code ${e.code}`;e.reason&&(t+=`: ${e.reason}`),this.logger.log(t),this.onServerDisconnectError&&e.reason&&this.onServerDisconnectError(t)}let t=Br(e.reason);this.scheduleReconnect(t)}}socketState(){return this.socket.state}sendMessage(e){let t={type:e.type,...e.type===`Authenticate`&&e.tokenType===`User`?{value:`...${e.value.slice(-7)}`}:{}};if(this.socket.state===`ready`&&this.socket.paused===`no`){let n=Pr(e),r=JSON.stringify(n),i=!1;try{this.socket.ws.send(r),i=!0}catch(e){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${e}`),this.closeAndReconnect(`FailedToSendMessage`)}return this._logVerbose(`${i?`sent`:`failed to send`} message with type ${e.type}: ${JSON.stringify(t)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${`paused`in this.socket?this.socket.paused:void 0}): ${JSON.stringify(t)}`),!1}resetServerInactivityTimeout(){this.socket.state!==`terminated`&&(this.reconnectDueToServerInactivityTimeout!==null&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect(`InactiveServer`)},this.serverInactivityThreshold))}scheduleReconnect(e){this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.socket={state:`disconnected`};let t=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(t)}ms`);let n=H(),r=setTimeout(()=>{this.scheduledReconnect?.timeout===r&&(this.scheduledReconnect=null,this.connect())},t);this.scheduledReconnect={timeout:r,scheduledAt:n,backoffMs:t}}closeAndReconnect(e){switch(this._logVerbose(`begin closeAndReconnect with reason ${e}`),this.socket.state){case`disconnected`:case`terminated`:case`stopped`:return;case`connecting`:case`ready`:this.lastCloseReason=e,this.close(),this.scheduleReconnect(`client`);return;default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case`disconnected`:case`terminated`:case`stopped`:return Promise.resolve();case`connecting`:{let e=this.socket.ws;return e.onmessage=e=>{this._logVerbose(`Ignoring message received after close`)},new Promise(t=>{e.onclose=()=>{this._logVerbose(`Closed after connecting`),t()},e.onopen=()=>{this._logVerbose(`Opened after connecting`),e.close()}})}case`ready`:{this._logVerbose(`ws.close called`);let e=this.socket.ws;e.onmessage=e=>{this._logVerbose(`Ignoring message received after close`)};let t=new Promise(t=>{e.onclose=()=>{t()}});return e.close(),t}default:return this.socket,Promise.resolve()}}terminate(){switch(this.reconnectDueToServerInactivityTimeout&&clearTimeout(this.reconnectDueToServerInactivityTimeout),this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.cleanupNetworkListener(),this.socket.state){case`terminated`:case`stopped`:case`disconnected`:case`connecting`:case`ready`:{let e=this.close();return this.setSocketState({state:`terminated`}),e}default:throw this.socket,Error(`Invalid websocket state: ${this.socket.state}`)}}stop(){switch(this.socket.state){case`terminated`:return Promise.resolve();case`connecting`:case`stopped`:case`disconnected`:case`ready`:{this.cleanupNetworkListener();let e=this.close();return this.socket={state:`stopped`},e}default:return this.socket,Promise.resolve()}}tryRestart(){switch(this.socket.state){case`stopped`:break;case`terminated`:case`connecting`:case`ready`:case`disconnected`:this.logger.logVerbose(`Restart called without stopping first`);return;default:this.socket}this.setupNetworkListener(),this.connect()}pause(){switch(this.socket.state){case`disconnected`:case`stopped`:case`terminated`:return;case`connecting`:case`ready`:this.socket={...this.socket,paused:`yes`};return;default:this.socket;return}}tryReconnectImmediately(){if(this._logVerbose(`tryReconnectImmediately called`),this.socket.state!==`disconnected`){this._logVerbose(`tryReconnectImmediately called but socket state is ${this.socket.state}, no action taken`);return}let e=null;if(this.scheduledReconnect){let t=H()-this.scheduledReconnect.scheduledAt;e=Math.max(0,this.scheduledReconnect.backoffMs-t),this._logVerbose(`would have waited ${Math.round(e)}ms more (backoff was ${Math.round(this.scheduledReconnect.backoffMs)}ms, elapsed ${Math.round(t)}ms)`),clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null,this._logVerbose(`canceled scheduled reconnect`)}this.logger.log(`Network recovery detected, reconnecting immediately`),this.pendingNetworkRecoveryInfo=e===null?null:{timeSavedMs:e},this.connect()}resume(){switch(this.socket.state){case`connecting`:this.socket={...this.socket,paused:`no`};return;case`ready`:this.socket.paused===`uninitialized`?(this.socket={...this.socket,paused:`no`},this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:H()})):this.socket.paused===`yes`&&(this.socket={...this.socket,paused:`no`},this.onResume());return;case`terminated`:case`stopped`:case`disconnected`:return;default:this.socket}this.connect()}connectionState(){return{isConnected:this.socket.state===`ready`,hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(e){this.logger.logVerbose(e)}nextBackoff(e){let t=(e===`client`?100:e===`Unknown`?this.defaultInitialBackoff:zr[e].timeout)*2**this.retries;this.retries+=1;let n=Math.min(t,this.maxBackoff);return n+n*(Math.random()-.5)}reportLargeTransition({transition:e,messageLength:t}){if(e.clientClockSkew===void 0||e.serverTs===void 0)return;let n=H()-e.clientClockSkew-e.serverTs/1e6,r=`${Math.round(n)}ms`,i=`${Math.round(t/1e4)/100}MB`,a=t/(n/1e3),o=`${Math.round(a/1e4)/100}MB per second`;this._logVerbose(`received ${i} transition in ${r} at ${o}`),t>2e7?this.logger.log(`received query results totaling more that 20MB (${i}) which will take a long time to download on slower connections`):n>2e4&&this.logger.log(`received query results totaling ${i} which took more than 20s to arrive (${r})`),this.debug&&this.sendMessage({type:`Event`,eventType:`ClientReceivedTransition`,event:{transitionTransitTime:n,messageLength:t}})}};function Hr(){return Ur()}function Ur(){return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}var Wr=class extends Error{};Wr.prototype.name=`InvalidTokenError`;function Gr(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n=`0`+n),`%`+n}))}function Kr(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);switch(t.length%4){case 0:break;case 2:t+=`==`;break;case 3:t+=`=`;break;default:throw Error(`base64 string is not of the correct length`)}try{return Gr(t)}catch{return atob(t)}}function qr(e,t){if(typeof e!=`string`)throw new Wr(`Invalid token specified: must be a string`);t||(t={});let n=t.header===!0?0:1,r=e.split(`.`)[n];if(typeof r!=`string`)throw new Wr(`Invalid token specified: missing part #${n+1}`);let i;try{i=Kr(r)}catch(e){throw new Wr(`Invalid token specified: invalid base64 for part #${n+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new Wr(`Invalid token specified: invalid json for part #${n+1} (${e.message})`)}}var Jr=Object.defineProperty,Yr=(e,t,n)=>t in e?Jr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,U=(e,t,n)=>Yr(e,typeof t==`symbol`?t:t+``,n),Xr=class{constructor(e,t,n){U(this,`authState`,{state:`noAuth`}),U(this,`configVersion`,0),U(this,`syncState`),U(this,`authenticate`),U(this,`stopSocket`),U(this,`tryRestartSocket`),U(this,`pauseSocket`),U(this,`resumeSocket`),U(this,`clearAuth`),U(this,`logger`),U(this,`refreshTokenLeewaySeconds`),U(this,`initialAuthTokenReuse`),U(this,`lastRefreshChange`),U(this,`tokenConfirmationAttempts`,0),this.syncState=e,this.authenticate=t.authenticate,this.stopSocket=t.stopSocket,this.tryRestartSocket=t.tryRestartSocket,this.pauseSocket=t.pauseSocket,this.resumeSocket=t.resumeSocket,this.clearAuth=t.clearAuth,this.logger=n.logger,this.refreshTokenLeewaySeconds=n.refreshTokenLeewaySeconds,this.initialAuthTokenReuse=n.initialAuthTokenReuse,this.lastRefreshChange=!1}notifyRefreshChange(e){this.authState.state!==`noAuth`&&this.authState.state!==`initialRefetch`&&this.authState.config.onRefreshChange&&this.lastRefreshChange!==e&&(this.lastRefreshChange=e,this.authState.config.onRefreshChange(e))}async setConfig(e,t,n){this.resetAuthState(),this._logVerbose(`pausing WS for auth token fetch`),this.pauseSocket();let r=await this.fetchTokenAndGuardAgainstRace(e,{forceRefreshToken:!1});if(r.isFromOutdatedConfig)return;let i={fetchToken:e,onAuthChange:t,onRefreshChange:n};r.value?(this.setAuthState({state:`waitingForServerConfirmationOfCachedToken`,config:i,hasRetried:!1}),this.authenticate(r.value)):(this.setAuthState({state:`initialRefetch`,config:i}),await this.refetchToken()),this._logVerbose(`resuming WS after auth token fetch`),this.resumeSocket()}onTransition(e){if(this.syncState.isCurrentOrNewerAuthVersion(e.endVersion.identity)&&!(e.endVersion.identity<=e.startVersion.identity)){if(this._logVerbose(`auth state is ${this.authState.state} when handling transition`),this.syncState.markAuthCompletion(),this.authState.state===`waitingForServerConfirmationOfCachedToken`){this._logVerbose(`server confirmed auth token is valid`);let t=this.syncState.getAuth()?.value;this.initialAuthTokenReuse&&t?this.scheduleTokenRefetch(t,e.clientClockSkew):this.refetchToken(),this.authState.config.onAuthChange(!0);return}this.authState.state===`waitingForServerConfirmationOfFreshToken`&&(this._logVerbose(`server confirmed new auth token is valid`),this.notifyRefreshChange(!1),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(e){if(e.authUpdateAttempted===!1&&(this.authState.state===`waitingForServerConfirmationOfFreshToken`||this.authState.state===`waitingForServerConfirmationOfCachedToken`)){this._logVerbose(`ignoring non-auth token expired error`);return}let{baseVersion:t}=e;if(!this.syncState.isCurrentOrNewerAuthVersion(t+1)){this._logVerbose(`ignoring auth error for previous auth attempt`);return}this.tryToReauthenticate(e)}async tryToReauthenticate(e){if(this._logVerbose(`attempting to reauthenticate: ${e.error}`),this.authState.state===`noAuth`||this.authState.state===`waitingForServerConfirmationOfFreshToken`&&this.tokenConfirmationAttempts>=2){this.logger.error(`Failed to authenticate: "${e.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.authState.state!==`noAuth`&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}if(this.authState.state===`waitingForServerConfirmationOfFreshToken`&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${2-this.tokenConfirmationAttempts} attempts remaining`)),this.notifyRefreshChange(!0),await this.stopSocket(),this.authState.state===`noAuth`)return;let t=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});t.isFromOutdatedConfig||(t.value&&this.syncState.isNewAuth(t.value)?(this.authenticate(t.value),this.setAuthState({state:`waitingForServerConfirmationOfFreshToken`,config:this.authState.config,token:t.value,hadAuth:this.authState.state===`notRefetching`||this.authState.state===`waitingForScheduledRefetch`})):(this._logVerbose(`reauthentication failed, could not fetch a new token`),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this.tryRestartSocket())}async refetchToken(){if(this.authState.state===`noAuth`)return;this._logVerbose(`refetching auth token`);let e=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});e.isFromOutdatedConfig||(e.value?this.syncState.isNewAuth(e.value)?(this.setAuthState({state:`waitingForServerConfirmationOfFreshToken`,hadAuth:this.syncState.hasAuth(),token:e.value,config:this.authState.config}),this.authenticate(e.value)):this.setAuthState({state:`notRefetching`,config:this.authState.config}):(this._logVerbose(`refetching token failed`),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose(`restarting WS after auth token fetch (if currently stopped)`),this.tryRestartSocket())}scheduleTokenRefetch(e,t){if(this.authState.state===`noAuth`)return;let n=this.decodeToken(e);if(!n){this.logger.error(`Auth token is not a valid JWT, cannot refetch the token`);return}let{iat:r,exp:i}=n;if(!r||!i){this.logger.error(`Auth token does not have required fields, cannot refetch the token`);return}let a=i-r;if(a<=2){this.logger.error(`Auth token does not live long enough, cannot refetch the token`);return}let o;t===void 0?o=a:(o=i-(Date.now()-t)/1e3,o<=0&&(o=0));let s=Math.min(1728e6,(o-this.refreshTokenLeewaySeconds)*1e3);s<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${o}s`),s=0);let c=setTimeout(()=>{this._logVerbose(`running scheduled token refetch`),this.refetchToken()},s);this.setAuthState({state:`waitingForScheduledRefetch`,refetchTokenTimeoutId:c,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${s}ms`)}async fetchTokenAndGuardAgainstRace(e,t){let n=++this.configVersion;this._logVerbose(`fetching token with config version ${n}`);let r=await e(t);return this.configVersion===n?{isFromOutdatedConfig:!1,value:r}:(this._logVerbose(`stale config version, expected ${n}, got ${this.configVersion}`),{isFromOutdatedConfig:!0})}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(e){e(!1),this.resetAuthState()}resetAuthState(){this.notifyRefreshChange(!1),this.setAuthState({state:`noAuth`})}setAuthState(e){let t=e.state===`waitingForServerConfirmationOfFreshToken`?{hadAuth:e.hadAuth,state:e.state,token:`...${e.token.slice(-7)}`}:{state:e.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(t)}`),e.state){case`waitingForScheduledRefetch`:case`notRefetching`:case`noAuth`:this.tokenConfirmationAttempts=0}this.authState.state===`waitingForScheduledRefetch`&&clearTimeout(this.authState.refetchTokenTimeoutId),this.authState=e}decodeToken(e){try{return qr(e)}catch(e){return this._logVerbose(`Error decoding token: ${e instanceof Error?e.message:`Unknown error`}`),null}}_logVerbose(e){this.logger.logVerbose(`${e} [v${this.configVersion}]`)}};let Zr=[`convexClientConstructed`,`convexWebSocketOpen`,`convexFirstMessageReceived`];function Qr(e,t){let n={sessionId:t};typeof performance<`u`&&performance.mark&&performance.mark(e,{detail:n})}function $r(e){let t=e.name.slice(6);return t=t.charAt(0).toLowerCase()+t.slice(1),{name:t,startTime:e.startTime}}function ei(e){if(typeof performance>`u`||!performance.getEntriesByName)return[];let t=[];for(let n of Zr){let r=performance.getEntriesByName(n).filter(e=>e.entryType===`mark`).filter(t=>t.detail.sessionId===e);t.push(...r)}return t.map($r)}var ti=Object.defineProperty,ni=(e,t,n)=>t in e?ti(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,W=(e,t,n)=>ni(e,typeof t==`symbol`?t:t+``,n),ri=class{constructor(e,t,n){if(W(this,`address`),W(this,`state`),W(this,`requestManager`),W(this,`webSocketManager`),W(this,`authenticationManager`),W(this,`remoteQuerySet`),W(this,`optimisticQueryResults`),W(this,`_transitionHandlerCounter`,0),W(this,`_nextRequestId`),W(this,`_onTransitionFns`,/* @__PURE__ */ new Map),W(this,`_sessionId`),W(this,`firstMessageReceived`,!1),W(this,`debug`),W(this,`logger`),W(this,`maxObservedTimestamp`),W(this,`connectionStateSubscribers`,/* @__PURE__ */ new Map),W(this,`nextConnectionStateSubscriberId`,0),W(this,`_lastPublishedConnectionState`),W(this,`markConnectionStateDirty`,()=>{Promise.resolve().then(()=>{let e=this.connectionState();if(JSON.stringify(e)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=e;for(let t of this.connectionStateSubscribers.values())t(e)}})}),W(this,`mark`,e=>{this.debug&&Qr(e,this.sessionId)}),typeof e==`object`)throw Error(`Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.`);n?.skipConvexDeploymentUrlCheck!==!0&&un(e),n={...n};let r=n.authRefreshTokenLeewaySeconds??10,i=n.webSocketConstructor;if(!i&&typeof WebSocket>`u`)throw Error(`No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient`);i=i||WebSocket,this.debug=n.reportDebugInfoToConvex??!1,this.address=e,this.logger=n.logger===!1?er({verbose:n.verbose??!1}):n.logger!==!0&&n.logger?n.logger:$n({verbose:n.verbose??!1});let a=e.search(`://`);if(a===-1)throw Error(`Provided address was not an absolute URL.`);let o=e.substring(a+3),s=e.substring(0,a),c;if(s===`http`)c=`ws`;else if(s===`https`)c=`wss`;else throw Error(`Unknown parent protocol ${s}`);let l=`${c}://${o}/api/${Rn}/sync`;this.state=new cr,this.remoteQuerySet=new Ar(e=>this.state.queryPath(e),this.logger),this.requestManager=new fr(this.logger,this.markConnectionStateDirty);let u=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new Xr(this.state,{authenticate:e=>{let t=this.state.setAuth(e);return this.webSocketManager.sendMessage(t),t.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:u,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:r,initialAuthTokenReuse:n.initialAuthTokenReuse??!1}),this.optimisticQueryResults=new _r,this.addOnTransitionHandler(e=>{t(e.queries.map(e=>e.token))}),this._nextRequestId=0,this._sessionId=Hr();let{unsavedChangesWarning:d}=n;if(typeof window>`u`||window.addEventListener===void 0){if(d===!0)throw Error(`unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.`)}else d!==!1&&window.addEventListener(`beforeunload`,e=>{if(this.requestManager.hasIncompleteRequests()){e.preventDefault();let t=`Are you sure you want to leave? Your changes may not be saved.`;return(e||window.event).returnValue=t,t}});this.webSocketManager=new Vr(l,{onOpen:e=>{this.mark(`convexWebSocketOpen`),this.webSocketManager.sendMessage({...e,type:`Connect`,sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new Ar(e=>this.state.queryPath(e),this.logger);let[t,n]=this.state.restart();n&&this.webSocketManager.sendMessage(n),this.webSocketManager.sendMessage(t);for(let e of this.requestManager.restart())this.webSocketManager.sendMessage(e)},onResume:()=>{let[e,t]=this.state.resume();t&&this.webSocketManager.sendMessage(t),e&&this.webSocketManager.sendMessage(e);for(let e of this.requestManager.resume())this.webSocketManager.sendMessage(e)},onMessage:e=>{switch(this.firstMessageReceived||(this.firstMessageReceived=!0,this.mark(`convexFirstMessageReceived`),this.reportMarks()),e.type){case`Transition`:{this.observedTimestamp(e.endVersion.ts),this.authenticationManager.onTransition(e),this.remoteQuerySet.transition(e),this.state.transition(e);let t=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(t);break}case`MutationResponse`:{e.success&&this.observedTimestamp(e.ts);let t=this.requestManager.onResponse(e);t!==null&&this.notifyOnQueryResultChanges(/* @__PURE__ */ new Map([[t.requestId,t.result]]));break}case`ActionResponse`:this.requestManager.onResponse(e);break;case`AuthError`:this.authenticationManager.onAuthError(e);break;case`FatalError`:{let t=nr(this.logger,e.error);throw this.webSocketManager.terminate(),t}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:n.onServerDisconnectError},i,this.logger,this.markConnectionStateDirty,this.debug),this.mark(`convexClientConstructed`),n.expectAuth&&u()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()&&this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(this.maxObservedTimestamp===void 0||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){let t=this.remoteQuerySet.remoteQueryResults(),n=/* @__PURE__ */ new Map;for(let[e,r]of t){let t=this.state.queryToken(e);if(t!==null){let i={result:r,udfPath:this.state.queryPath(e),args:this.state.queryArgs(e)};n.set(t,i)}}let r=this.optimisticQueryResults.ingestQueryResultsFromServer(n,new Set(e.keys()));this.handleTransition({queries:r.map(e=>({token:e,modification:{kind:`Updated`,result:this.optimisticQueryResults.rawQueryResult(e)}})),reflectedMutations:Array.from(e).map(([e,t])=>({requestId:e,result:t})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(e){for(let t of this._onTransitionFns.values())t(e)}addOnTransitionHandler(e){let t=this._transitionHandlerCounter++;return this._onTransitionFns.set(t,e),()=>this._onTransitionFns.delete(t)}getCurrentAuthClaims(){let e=this.state.getAuth(),t={};if(e&&e.tokenType===`User`)try{t=e?qr(e.value):{}}catch{t={}}else return;return{token:e.value,decoded:t}}setAuth(e,t,n){this.authenticationManager.setConfig(e,t,n)}hasAuth(){return this.state.hasAuth()}setAdminAuth(e,t){let n=this.state.setAdminAuth(e,t);this.webSocketManager.sendMessage(n)}clearAuth(){let e=this.state.clearAuth();this.webSocketManager.sendMessage(e)}subscribe(e,t,n){let r=A(t),{modification:i,queryToken:a,unsubscribe:o}=this.state.subscribe(e,r,n?.journal,n?.componentPath);return i!==null&&this.webSocketManager.sendMessage(i),{queryToken:a,unsubscribe:()=>{let e=o();e&&this.webSocketManager.sendMessage(e)}}}localQueryResult(e,t){let n=z(e,A(t));return this.optimisticQueryResults.queryResult(n)}localQueryResultByToken(e){return this.optimisticQueryResults.queryResult(e)}hasLocalQueryResultByToken(e){return this.optimisticQueryResults.hasQueryResult(e)}localQueryLogs(e,t){let n=z(e,A(t));return this.optimisticQueryResults.queryLogs(n)}queryJournal(e,t){let n=z(e,A(t));return this.state.queryJournal(n)}connectionState(){let e=this.webSocketManager.connectionState();return{hasInflightRequests:this.requestManager.hasInflightRequests(),isWebSocketConnected:e.isConnected,hasEverConnected:e.hasEverConnected,connectionCount:e.connectionCount,connectionRetries:e.connectionRetries,timeOfOldestInflightRequest:this.requestManager.timeOfOldestInflightRequest(),inflightMutations:this.requestManager.inflightMutations(),inflightActions:this.requestManager.inflightActions()}}subscribeToConnectionState(e){let t=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(t,e),()=>{this.connectionStateSubscribers.delete(t)}}async mutation(e,t,n){let r=await this.mutationInternal(e,t,n);if(!r.success)throw r.errorData===void 0?Error(L(`mutation`,e,r)):rr(r,new Ln(L(`mutation`,e,r)));return r.value}async mutationInternal(e,t,n,r){let{mutationPromise:i}=this.enqueueMutation(e,t,n,r);return i}enqueueMutation(e,t,n,r){let i=A(t);this.tryReportLongDisconnect();let a=this.nextRequestId;if(this._nextRequestId++,n!==void 0){let e=n.optimisticUpdate;if(e!==void 0){let t=this.optimisticQueryResults.applyOptimisticUpdate(t=>{e(t,i)instanceof Promise&&this.logger.warn(`Optimistic update handler returned a Promise. Optimistic updates should be synchronous.`)},a).map(e=>{let t=this.localQueryResultByToken(e);return{token:e,modification:{kind:`Updated`,result:t===void 0?void 0:{success:!0,value:t,logLines:[]}}}});this.handleTransition({queries:t,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}let o={type:`Mutation`,requestId:a,udfPath:e,componentPath:r,args:[P(i)]},s=this.webSocketManager.sendMessage(o);return{requestId:a,mutationPromise:this.requestManager.request(o,s)}}async action(e,t){let n=await this.actionInternal(e,t);if(!n.success)throw n.errorData===void 0?Error(L(`action`,e,n)):rr(n,new Ln(L(`action`,e,n)));return n.value}async actionInternal(e,t,n){let r=A(t),i=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();let a={type:`Action`,requestId:i,udfPath:e,componentPath:n,args:[P(r)]},o=this.webSocketManager.sendMessage(a);return this.requestManager.request(a,o)}async close(){return this.authenticationManager.stop(),this.webSocketManager.terminate()}get url(){return this.address}get nextRequestId(){return this._nextRequestId}get sessionId(){return this._sessionId}reportMarks(){if(this.debug){let e=ei(this.sessionId);this.webSocketManager.sendMessage({type:`Event`,eventType:`ClientConnect`,event:e})}}tryReportLongDisconnect(){if(!this.debug)return;let e=this.connectionState().timeOfOldestInflightRequest;if(e===null||Date.now()-e.getTime()<=6e4)return;let t=`${this.address}/api/debug_event`;fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,"Convex-Client":`npm-${Rn}`},body:JSON.stringify({event:`LongWebsocketDisconnect`})}).then(e=>{e.ok||this.logger.warn(`Analytics request failed with response:`,e.body)}).catch(e=>{this.logger.warn(`Analytics response failed with error:`,e)})}};function ii(e){if(typeof e!=`object`||!e||!Array.isArray(e.page)||typeof e.isDone!=`boolean`||typeof e.continueCursor!=`string`)throw Error(`Not a valid paginated query result: ${e?.toString()}`);return e}var ai=Object.defineProperty,oi=(e,t,n)=>t in e?ai(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,si=(e,t,n)=>oi(e,typeof t==`symbol`?t:t+``,n),ci=class{constructor(e,t){this.client=e,this.onTransition=t,si(this,`paginatedQuerySet`,/* @__PURE__ */ new Map),si(this,`lastTransitionTs`),this.lastTransitionTs=xr.fromNumber(0),this.client.addOnTransitionHandler(e=>this.onBaseTransition(e))}subscribe(e,t,n){let r=R(e),i=ir(r,t,n),a=()=>this.removePaginatedQuerySubscriber(i),o=this.paginatedQuerySet.get(i);return o?(o.numSubscribers+=1,{paginatedQueryToken:i,unsubscribe:a}):(this.paginatedQuerySet.set(i,{token:i,canonicalizedUdfPath:r,args:t,numSubscribers:1,options:{initialNumItems:n.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:/* @__PURE__ */ new Map,ongoingSplits:/* @__PURE__ */ new Map,skip:!1,id:n.id}),this.addPageToPaginatedQuery(i,null,n.initialNumItems),{paginatedQueryToken:i,unsubscribe:a})}localQueryResult(e,t,n){let r=ir(R(e),t,n);return this.localQueryResultByToken(r)}localQueryResultByToken(e){let t=this.paginatedQuerySet.get(e);if(!t)return;let n=this.activePageQueryTokens(t);if(n.length===0)return{results:[],status:`LoadingFirstPage`,loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)};let r=[],i=!1,a=!1;for(let e of n){let t=this.client.localQueryResultByToken(e);if(t===void 0){i=!0,a=!1;continue}let n=ii(t);r=r.concat(n.page),a=!!n.isDone}let o;return o=i?r.length===0?`LoadingFirstPage`:`LoadingMore`:a?`Exhausted`:`CanLoadMore`,{results:r,status:o,loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)}}onBaseTransition(e){let t=e.queries.map(e=>e.token),n=this.queriesContainingTokens(t),r=[];n.length>0&&(this.processPaginatedQuerySplits(n,e=>this.client.localQueryResultByToken(e)),r=n.map(e=>({token:e,modification:{kind:`Updated`,result:this.localQueryResultByToken(e)}})));let i={...e,paginatedQueries:r};this.onTransition(i)}loadMoreOfPaginatedQuery(e,t){this.mustGetPaginatedQuery(e);let n=this.queryTokenForLastPageOfPaginatedQuery(e),r=this.client.localQueryResultByToken(n);if(!r)return!1;let i=ii(r);if(i.isDone)return!1;this.addPageToPaginatedQuery(e,i.continueCursor,t);let a={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token:e,modification:{kind:`Updated`,result:this.localQueryResultByToken(e)}}]};return this.onTransition(a),!0}queriesContainingTokens(e){if(e.length===0)return[];let t=[],n=new Set(e);for(let[e,r]of this.paginatedQuerySet)for(let i of this.allQueryTokens(r))if(n.has(i)){t.push(e);break}return t}processPaginatedQuerySplits(e,t){for(let n of e){let e=this.mustGetPaginatedQuery(n),{ongoingSplits:r,pageKeyToQuery:i,pageKeys:a}=e;for(let[n,[a,o]]of r)t(i.get(a).queryToken)!==void 0&&t(i.get(o).queryToken)!==void 0&&this.completePaginatedQuerySplit(e,n,a,o);for(let n of a){if(r.has(n))continue;let a=i.get(n);if(!a)throw Error(`No page query for active pageKey ${n}`);let o=t(a.queryToken);if(!o)continue;let s=ii(o);s.splitCursor&&(s.pageStatus===`SplitRecommended`||s.pageStatus===`SplitRequired`||s.page.length>e.options.initialNumItems*2)&&this.splitPaginatedQueryPage(e,n,a.cursor,s.splitCursor,s.continueCursor)}}}splitPaginatedQueryPage(e,t,n,r,i){let a=e.nextPageKey++,o=e.nextPageKey++,s={numItems:e.options.initialNumItems,id:e.id},c=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...s,cursor:n,endCursor:r}});e.pageKeyToQuery.set(a,{...c,cursor:n});let l=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...s,cursor:r,endCursor:i}});e.pageKeyToQuery.set(o,{...l,cursor:r}),e.ongoingSplits.set(t,[a,o])}addPageToPaginatedQuery(e,t,n){let r=this.mustGetPaginatedQuery(e),i=r.nextPageKey++,a={cursor:t,numItems:n,id:r.id},o={...r.args,paginationOpts:a},s=this.client.subscribe(r.canonicalizedUdfPath,o);return r.pageKeys.push(i),r.pageKeyToQuery.set(i,{...s,cursor:t}),s}removePaginatedQuerySubscriber(e){let t=this.paginatedQuerySet.get(e);if(t&&(--t.numSubscribers,!(t.numSubscribers>0))){for(let e of t.pageKeyToQuery.values())e.unsubscribe();this.paginatedQuerySet.delete(e)}}completePaginatedQuerySplit(e,t,n,r){let i=e.pageKeyToQuery.get(t);e.pageKeyToQuery.delete(t);let a=e.pageKeys.indexOf(t);e.pageKeys.splice(a,1,n,r),e.ongoingSplits.delete(t),i.unsubscribe()}activePageQueryTokens(e){return e.pageKeys.map(t=>e.pageKeyToQuery.get(t).queryToken)}allQueryTokens(e){return Array.from(e.pageKeyToQuery.values()).map(e=>e.queryToken)}queryTokenForLastPageOfPaginatedQuery(e){let t=this.mustGetPaginatedQuery(e),n=t.pageKeys[t.pageKeys.length-1];if(n===void 0)throw Error(`No pages for paginated query ${e}`);return t.pageKeyToQuery.get(n).queryToken}mustGetPaginatedQuery(e){let t=this.paginatedQuerySet.get(e);if(!t)throw Error(`paginated query no longer exists for token `+e);return t}},li=Object.defineProperty,ui=(e,t,n)=>t in e?li(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,di=(e,t,n)=>ui(e,typeof t==`symbol`?t:t+``,n),fi=class{constructor(e,t={}){di(this,`listeners`),di(this,`_client`),di(this,`_paginatedClient`),di(this,`callNewListenersWithCurrentValuesTimer`),di(this,`_closed`),di(this,`_disabled`),t.skipConvexDeploymentUrlCheck!==!0&&un(e);let{disabled:n,...r}=t;this._closed=!1,this._disabled=!!n,typeof window>`u`&&!(`unsavedChangesWarning`in r)&&(r.unsavedChangesWarning=!1),this.disabled||(this._client=new ri(e,()=>{},r),this._paginatedClient=new ci(this._client,e=>this._transition(e))),this.listeners=/* @__PURE__ */ new Set}get closed(){return this._closed}get client(){if(this._client)return this._client;throw Error(`ConvexClient is disabled`)}get paginatedClient(){if(this._paginatedClient)return this._paginatedClient;throw Error(`ConvexClient is disabled`)}get disabled(){return this._disabled}onUpdate(e,t,n,r){if(this.disabled)return this.createDisabledUnsubscribe();let{queryToken:i,unsubscribe:a}=this.client.subscribe(F(e),t),o={queryToken:i,callback:n,onError:r,unsubscribe:a,hasEverRun:!1,query:e,args:t,paginationOptions:void 0};this.listeners.add(o),this.queryResultReady(i)&&this.callNewListenersWithCurrentValuesTimer===void 0&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));let s={unsubscribe:()=>{this.closed||(this.listeners.delete(o),a())},getCurrentValue:()=>this.client.localQueryResultByToken(i),getQueryLogs:()=>this.client.localQueryLogs(i)},c=s.unsubscribe;return Object.assign(c,s),c}onPaginatedUpdate_experimental(e,t,n,r,i){if(this.disabled)return this.createDisabledUnsubscribe();let a={initialNumItems:n.initialNumItems,id:-1},{paginatedQueryToken:o,unsubscribe:s}=this.paginatedClient.subscribe(F(e),t,a),c={queryToken:o,callback:r,onError:i,unsubscribe:s,hasEverRun:!1,query:e,args:t,paginationOptions:a};this.listeners.add(c),this.paginatedClient.localQueryResultByToken(o)&&this.callNewListenersWithCurrentValuesTimer===void 0&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));let l={unsubscribe:()=>{this.closed||(this.listeners.delete(c),s())},getCurrentValue:()=>this.paginatedClient.localQueryResult(F(e),t,a),getQueryLogs:()=>[]},u=l.unsubscribe;return Object.assign(u,l),u}callNewListenersWithCurrentValues(){this.callNewListenersWithCurrentValuesTimer=void 0,this._transition({queries:[],paginatedQueries:[]},!0)}queryResultReady(e){return this.client.hasLocalQueryResultByToken(e)}createDisabledUnsubscribe(){let e=(()=>{});return Object.assign(e,{unsubscribe:e,getCurrentValue:()=>void 0,getQueryLogs:()=>void 0}),e}async close(){if(!this.disabled)return this.listeners.clear(),this._closed=!0,this._paginatedClient&&(this._paginatedClient=void 0),this.client.close()}getAuth(){if(!this.disabled)return this.client.getCurrentAuthClaims()}setAuth(e,t){this.disabled||this.client.setAuth(e,t??(()=>{}))}setAdminAuth(e,t){if(this.closed)throw Error(`ConvexClient has already been closed.`);this.disabled||this.client.setAdminAuth(e,t)}_transition({queries:e,paginatedQueries:t},n=!1){let r=[...e.map(e=>e.token),...t.map(e=>e.token)];for(let e of this.listeners){let{callback:t,queryToken:i,onError:a,hasEverRun:o}=e,s=ar(i),c=s?!!this.paginatedClient.localQueryResultByToken(i):this.client.hasLocalQueryResultByToken(i);if(r.includes(i)||n&&!o&&c){e.hasEverRun=!0;let n;try{n=s?this.paginatedClient.localQueryResultByToken(i):this.client.localQueryResultByToken(i)}catch(e){if(!(e instanceof Error))throw e;a?a(e,`Second argument to onUpdate onError is reserved for later use`):Promise.reject(e);continue}t(n,`Second argument to onUpdate callback is reserved for later use`)}}}async mutation(e,t,n){if(this.disabled)throw Error(`ConvexClient is disabled`);return await this.client.mutation(F(e),t,n)}async action(e,t){if(this.disabled)throw Error(`ConvexClient is disabled`);return await this.client.action(F(e),t)}async query(e,t){if(this.disabled)throw Error(`ConvexClient is disabled`);let n=this.client.localQueryResult(F(e),t);return n===void 0?new Promise((n,r)=>{let{unsubscribe:i}=this.onUpdate(e,t,e=>{i(),n(e)},e=>{i(),r(e)})}):Promise.resolve(n)}connectionState(){if(this.disabled)throw Error(`ConvexClient is disabled`);return this.client.connectionState()}subscribeToConnectionState(e){return this.disabled?()=>{}:this.client.subscribeToConnectionState(e)}},G=class extends Error{constructor(e,t){super(e),this.code=t}};function pi(e){let t=e?.data;return t?.message?t.message:e instanceof Error?e.message:`Something went wrong`}var mi=class{constructor(e){this.config=e,b(this,`client`,void 0),this.client=new fi(e.convexUrl,{unsavedChangesWarning:!1,skipConvexDeploymentUrlCheck:!/\.convex\.cloud\/?$/.test(e.convexUrl)})}close(){return this.client.close()}touch(e){return this.client.mutation(I.projects.touch,{publicId:this.config.project,origin:e}).catch(()=>null)}onStatus(e){return this.client.onUpdate(I.projects.status,{publicId:this.config.project},e,()=>{})}onPage(e,t,n){return this.client.onUpdate(I.comments.listForPage,{publicId:this.config.project,path:e},e=>t(e),n)}onPages(e){return this.client.onUpdate(I.comments.pagesWithComments,{publicId:this.config.project},e,()=>{})}onSession(e,t){return this.client.onUpdate(I.sessions.validate,{publicId:this.config.project,sessionToken:e},t,()=>{})}onOwnerComment(e,t,n){return this.client.onUpdate(I.comments.getForOwner,{publicId:this.config.project,id:e,sessionToken:t},e=>n(e),()=>{})}onThread(e,t){return this.client.onUpdate(I.replies.listForComment,{publicId:this.config.project,commentId:e},e=>t(e),()=>{})}getComment(e){return this.client.query(I.comments.getById,{publicId:this.config.project,id:e}).then(e=>e).catch(()=>null)}async createComment(e){let t;try{t=await fetch(`${this.config.convexSiteUrl}/widget/comments`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({publicId:this.config.project,...e})})}catch{throw new G(`Couldn't reach Nuni. Check your connection.`,`network`)}let n=await t.json().catch(()=>({}));if(!t.ok||!n.id)throw new G(n.message??`Couldn't post the comment`,n.code??`error`);return n.id}async createReply(e){let t;try{t=await fetch(`${this.config.convexSiteUrl}/widget/replies`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({publicId:this.config.project,...e})})}catch{throw new G(`Couldn't reach Nuni. Check your connection.`,`network`)}let n=await t.json().catch(()=>({}));if(!t.ok||!n.id)throw new G(n.message??`Couldn't post the reply`,n.code??`error`);return n.id}async uploadScreenshot(e,t,n){let r=await fetch(`${this.config.convexSiteUrl}/widget/screenshot`,{method:`POST`,headers:{"Content-Type":n.type,"X-Nuni-Project":this.config.project,"X-Nuni-Comment":e,"X-Nuni-Author":t},body:n});if(!r.ok){let e=await r.json().catch(()=>({}));throw new G(e.message??`Couldn't attach the screenshot`,e.code??`error`)}}async run(e){try{return await e}catch(e){throw new G(pi(e),`error`)}}editOwn(e,t,n){return this.run(this.client.mutation(I.comments.editOwn,{id:e,authorSecret:t,body:n}))}deleteOwn(e,t){return this.run(this.client.mutation(I.comments.deleteOwn,{id:e,authorSecret:t}))}resolve(e,t){return this.run(this.client.mutation(I.comments.resolve,{id:e,sessionToken:t}))}reopen(e,t){return this.run(this.client.mutation(I.comments.reopen,{id:e,sessionToken:t}))}editReply(e,t,n){return this.run(this.client.mutation(I.replies.editOwn,{id:e,authorSecret:t,body:n}))}deleteReply(e,t){return this.run(this.client.mutation(I.replies.deleteOwn,{id:e,authorSecret:t}))}removeReply(e,t){return this.run(this.client.mutation(I.replies.remove,{id:e,sessionToken:t}))}toggleReaction(e,t,n,r){return this.run(this.client.mutation(I.reactions.toggle,{publicId:this.config.project,commentId:e,targetId:t,emoji:n,authorSecret:r}))}remove(e,t){return this.run(this.client.mutation(I.comments.remove,{id:e,sessionToken:t}))}};function K(e,t={},...n){let r=document.createElement(e);for(let[e,n]of Object.entries(t))n!=null&&n!==!1&&(e.startsWith(`on`)&&typeof n==`function`?r.addEventListener(e.slice(2).toLowerCase(),n):e===`class`?r.className=String(n):n===!0?r.setAttribute(e,``):r.setAttribute(e,String(n)));for(let e of n.flat())e!=null&&e!==!1&&r.append(typeof e==`string`?document.createTextNode(e):e);return r}function q(e){let t=document.createElement(`span`);t.className=`icon`,t.setAttribute(`aria-hidden`,`true`);let n=new DOMParser().parseFromString(e,`image/svg+xml`);return t.append(document.importNode(n.documentElement,!0)),t}function J(e){let t=e.trim().split(/\s+/).filter(Boolean);return(t.length>1?t[0][0]+t[t.length-1][0]:(t[0]??`?`).slice(0,2)).toUpperCase()}function hi(e){let t=0;for(let n of e)t=t*31+n.charCodeAt(0)>>>0;return`oklch(0.5 0.17 ${t%360})`}async function gi(e){try{return await navigator.clipboard.writeText(e),!0}catch{}let t=document.createElement(`textarea`);t.value=e,t.setAttribute(`readonly`,``),t.style.cssText=`position:fixed;top:0;left:0;opacity:0`,document.body.appendChild(t),t.select();try{return document.execCommand(`copy`)}catch{return!1}finally{t.remove()}}function _i(e){let t=document.createElement(`span`);if(t.style.color=e,!t.style.color)return null;t.style.display=`none`,document.documentElement.appendChild(t);let n=getComputedStyle(t).color;if(t.remove(),/^rgba?\(/.test(n)){let e=n.match(/[\d.]+/g)?.map(Number);if(e&&e.length>=3)return[e[0],e[1],e[2]]}try{let t=document.createElement(`canvas`);t.width=t.height=1;let n=t.getContext(`2d`);if(!n)return null;n.fillStyle=e,n.fillRect(0,0,1,1);let[r,i,a]=n.getImageData(0,0,1,1).data;return[r,i,a]}catch{return null}}function vi([e,t,n]){let r=e=>{let t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4},i=.2126*r(e)+.7152*r(t)+.0722*r(n);return 1.05/(i+.05)>=(i+.05)/.05?`#ffffff`:`#111111`}let yi={toolbar:`Nuni comments`,comment:`Comment`,addComment:`Add a comment`,addCommentKey:`Add a comment ({key})`,cancelAdding:`Cancel adding a comment`,pickElement:`Pick an element`,allComments:`All comments`,openCount:`Comments on this page: {count} open`,commentSelection:`Comment on the selected text`,commentSelectionKey:`Comment on the selected text ({key})`,pickHint:`Click anything to comment, or drag to mark an area`,pickHintMobile:`Tap anything to comment`,pickHintKeys:`Arrow keys move, Enter comments, Esc cancels`,picked:`Selected {element}`,comments:`Comments`,close:`Close`,tabOpen:`Open ({count})`,tabResolved:`Resolved ({count})`,loading:`Loading…`,noOpen:`No open comments on this page.`,noOpenKey:`No open comments on this page. Press {key} to add one.`,noResolved:`Nothing resolved yet.`,notFoundHere:`Couldn't find on this page`,otherPages:`Other pages`,openOnPage:`{count} open`,replyCount:{one:`{count} reply`,other:`{count} replies`},edited:`edited`,ownSite:`Own this website?`,claim:`Claim Nuni`,yourName:`Your name`,leaveComment:`Leave a comment`,notYou:`Not you?`,screenshotAlt:`Screenshot that will be attached`,screenshotNote:`Screenshot attached. Only the site owner sees it.`,remove:`Remove`,cancel:`Cancel`,post:`Post`,posting:`Posting…`,save:`Save`,send:`{key} + Enter`,pinLabel:`Comment by {name}: {body}`,commentBy:`Comment by {name}`,openScreenshot:`Open the screenshot`,screenshotTaken:`Screenshot taken when the comment was left`,resolved:`Resolved`,leftOn:`Left on {origin}`,approximate:`Approximate`,approximateHint:`The page changed; this pin is a best guess`,notFound:`Element not found`,originallyOn:`Originally on: {text}`,resolve:`Resolve`,reopen:`Reopen`,copyForAgent:`Copy for agent`,copyForAgentHint:`Copy for your coding agent`,loadingContext:`Loading page context…`,edit:`Edit`,delete:`Delete`,owner:`Owner`,addReaction:`Add a reaction`,reactions:`Reactions`,reactWith:`React with {emoji}`,reply:`Reply`,replyFirst:`Reply to start a thread`,sendReply:`Send reply`,editReply:`Edit reply`,deleteReply:`Delete reply`,confirmDeleteComment:`Delete this comment? This can't be undone.`,confirmDeleteReply:`Delete this reply?`,added:`Comment added`,saved:`Saved`,deleted:`Deleted`,replyDeleted:`Reply deleted`,reopened:`Reopened`,copied:`Copied for your coding agent`,copyFailed:`Couldn't copy`,signedIn:`You're signed in as the owner`,linkGone:`That comment was deleted or is on another page`,enterName:`Enter your name`,writeFirst:`Write a comment first`,commentTooLong:`Comments are limited to {count} characters`,replyTooLong:`Replies are limited to {count} characters`,postFailed:`Couldn't post the comment`,replyFailed:`Couldn't post the reply`,reactFailed:`Couldn't react`,failed:`Something went wrong`,justNow:`just now`};function bi(){if(typeof navigator>`u`)return!1;let e=navigator.userAgentData?.platform??navigator.platform??``;return/mac|iphone|ipad|ipod/i.test(e||navigator.userAgent)}function xi(e,t={}){let n={...yi,...t},r=null,i=null;try{r=new Intl.PluralRules(e),i=new Intl.RelativeTimeFormat(e,{numeric:`auto`,style:`narrow`})}catch{r=new Intl.PluralRules,i=new Intl.RelativeTimeFormat(void 0,{numeric:`auto`,style:`narrow`})}let a=(e,t={})=>{let i=n[e]??yi[e];return(typeof i==`string`?i:i[r.select(Number(t.count??0))]??i.other).replace(/\{(\w+)\}/g,(e,n)=>n in t?String(t[n]):e)};return{locale:e,t:a,timeAgo:(t,n=Date.now())=>{let r=Math.max(0,Math.round((n-t)/1e3));if(r<45)return a(`justNow`);let o=Math.round(r/60);if(o<60)return i.format(-o,`minute`);let s=Math.round(o/60);if(s<24)return i.format(-s,`hour`);let c=Math.round(s/24);if(c<30)return i.format(-c,`day`);try{return new Date(t).toLocaleDateString(e)}catch{return new Date(t).toLocaleDateString()}},mod:bi()?`⌘`:`Ctrl`}}let Y=e=>`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${e}</svg>`,X={comment:Y(`<path d="M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.6A8 8 0 1 1 21 12z"/>`),list:Y(`<path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/>`),close:Y(`<path d="M18 6 6 18M6 6l12 12"/>`),check:Y(`<path d="M20 6 9 17l-5-5"/>`),undo:Y(`<path d="M3 7v6h6"/><path d="M21 17a9 9 0 0 0-15-6.7L3 13"/>`),trash:Y(`<path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6"/>`),edit:Y(`<path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"/>`),send:Y(`<path d="m22 2-7 20-4-9-9-4z"/><path d="M22 2 11 13"/>`),bot:Y(`<path d="M12 8V4H8"/><rect width="16" height="12" x="4" y="8" rx="2"/><path d="M2 14h2M20 14h2M15 13v2M9 13v2"/>`),smile:Y(`<circle cx="12" cy="12" r="9"/><path d="M8 14s1.5 2 4 2 4-2 4-2M9 9h.01M15 9h.01"/>`),target:Y(`<circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="3"/>`),github:`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M12 .5a11.5 11.5 0 0 0-3.6 22.4c.6.1.8-.3.8-.6v-2c-3.2.7-3.9-1.5-3.9-1.5-.5-1.3-1.3-1.7-1.3-1.7-1-.7.1-.7.1-.7 1.2.1 1.8 1.2 1.8 1.2 1 1.8 2.8 1.3 3.5 1 .1-.8.4-1.3.7-1.6-2.6-.3-5.3-1.3-5.3-5.7 0-1.3.5-2.3 1.2-3.1-.1-.3-.5-1.5.1-3.1 0 0 1-.3 3.2 1.2a11 11 0 0 1 5.8 0c2.2-1.5 3.2-1.2 3.2-1.2.6 1.6.2 2.8.1 3.1.8.8 1.2 1.9 1.2 3.1 0 4.4-2.7 5.4-5.3 5.7.4.4.8 1.1.8 2.2v3.3c0 .3.2.7.8.6A11.5 11.5 0 0 0 12 .5z"/></svg>`,link:Y(`<path d="M15 3h6v6M10 14 21 3M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>`)},Si=`nuni:locationchange`,Ci=!1;function wi(e){if(!Ci){Ci=!0;for(let e of[`pushState`,`replaceState`]){let t=history[e];history[e]=function(...e){let n=t.apply(this,e);return window.dispatchEvent(new Event(Si)),n}}}let t=location.href,n=()=>{location.href!==t&&(t=location.href,e())};window.addEventListener(Si,n),window.addEventListener(`popstate`,n),window.addEventListener(`hashchange`,n);let r=window.navigation,i=()=>setTimeout(n,0);return r?.addEventListener(`navigatesuccess`,i),()=>{window.removeEventListener(Si,n),window.removeEventListener(`popstate`,n),window.removeEventListener(`hashchange`,n),r?.removeEventListener(`navigatesuccess`,i)}}async function Ti(e){let t=new TextEncoder().encode(e);if(typeof crypto<`u`&&crypto.subtle){let e=await crypto.subtle.digest(`SHA-256`,t);return Ei(new Uint8Array(e))}return Ei(Oi(t))}function Ei(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}let Di=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function Oi(e){let t=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),n=e.length*8,r=new Uint8Array(e.length+9+63>>6<<6);r.set(e),r[e.length]=128;let i=new DataView(r.buffer);i.setUint32(r.length-4,n>>>0),i.setUint32(r.length-8,Math.floor(n/2**32));let a=/* @__PURE__ */ new Uint32Array(64),o=(e,t)=>e>>>t|e<<32-t;for(let e=0;e<r.length;e+=64){for(let t=0;t<16;t++)a[t]=i.getUint32(e+t*4);for(let e=16;e<64;e++){let t=a[e-15],n=a[e-2],r=o(t,7)^o(t,18)^t>>>3,i=o(n,17)^o(n,19)^n>>>10;a[e]=a[e-16]+r+a[e-7]+i>>>0}let[n,r,s,c,l,u,d,f]=t;for(let e=0;e<64;e++){let t=o(l,6)^o(l,11)^o(l,25),i=l&u^~l&d,p=f+t+i+Di[e]+a[e]>>>0,m=(o(n,2)^o(n,13)^o(n,22))+(n&r^n&s^r&s)>>>0;f=d,d=u,u=l,l=c+p>>>0,c=s,s=r,r=n,n=p+m>>>0}t[0]=t[0]+n>>>0,t[1]=t[1]+r>>>0,t[2]=t[2]+s>>>0,t[3]=t[3]+c>>>0,t[4]=t[4]+l>>>0,t[5]=t[5]+u>>>0,t[6]=t[6]+d>>>0,t[7]=t[7]+f>>>0}let s=/* @__PURE__ */ new Uint8Array(32),c=new DataView(s.buffer);return t.forEach((e,t)=>c.setUint32(t*4,e)),s}function ki(e,t){e.scrollIntoView({block:`center`,inline:`center`,behavior:`instant`});let n=e;for(;n;){let e=n.parentElement;if(e){let r=e.ownerDocument.defaultView?.getComputedStyle(e),i=r&&/auto|scroll|hidden/.test(r.overflowX),a=r&&/auto|scroll|hidden/.test(r.overflowY);if(e!==e.ownerDocument.scrollingElement&&(i||a)){let n=tt(e,document),r=t();e.scrollBy({left:i?r.x-n.left-e.clientLeft-e.clientWidth/2:0,top:a?r.y-n.top-e.clientTop-e.clientHeight/2:0,behavior:`instant`})}n=e;continue}let r=n.getRootNode();if(C(r)){n=r.host;continue}let i=n.ownerDocument,a=i.defaultView,o=Qe(i);if(a){let e=t(),n=o?tt(o,document):{left:0,top:0};a.scrollBy({left:e.x-n.left-(o?.clientLeft??0)-a.innerWidth/2,top:e.y-n.top-(o?.clientTop??0)-a.innerHeight/2,behavior:`instant`})}n=o}}let Ai=/* @__PURE__ */ new Map;function ji(e){try{return window.localStorage.getItem(e)}catch{return Ai.get(e)??null}}function Mi(e,t){try{t===null?window.localStorage.removeItem(e):window.localStorage.setItem(e,t)}catch{t===null?Ai.delete(e):Ai.set(e,t)}}let Z={name:`nuni:name`,secret:`nuni:author-secret`,session:e=>`nuni:session:${e}`},Ni=`nuni-picking`,Pi=[`pointerdown`,`mousedown`,`pointerup`,`mouseup`];function Fi(e){return Array.from(e.getClientRects()).filter(e=>e.width>0&&e.height>0)}function Ii(e,t){let n=e.region;if(!n)return null;let r=tt(t,document);return{left:r.left+n.x*r.width,top:r.top+n.y*r.height,width:n.w*r.width,height:n.h*r.height}}let Li=e=>e.replace(/\s+/g,` `).trim();function Ri(e){typeof requestIdleCallback==`function`?requestIdleCallback(e,{timeout:100}):setTimeout(e,0)}function zi(e,t=0){if(t>3)return[];let n=[];for(let r of Array.from(e.querySelectorAll(`iframe`))){let e=$e(r);e?.documentElement&&n.push(e,...zi(e,t+1))}return n}let Bi=`(max-width: 640px)`;function Vi(e){if(!e||e.nodeType!==1)return!1;let t=e;return t.isContentEditable||t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.tagName===`SELECT`}function Hi(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>t(String(r.result)),r.onerror=()=>n(r.error),r.readAsDataURL(e)})}function Ui(e){let t=e.tagName.toLowerCase(),n=e.id?`#${e.id}`:``,r=Array.from(e.classList).slice(0,2).map(e=>`.${e}`).join(``),i=x(e,40);return`${t}${n}${r}${i?` "${i}"`:``}`}function Wi(e,t){let n=/[?#]/.test(e)?t.origin+e:t.origin+e+t.search;try{return new URL(n).origin===t.origin?n:null}catch{return null}}var Gi=class{constructor(e,t){this.config=e,this.runtime=t,b(this,`host`,void 0),b(this,`root`,void 0),b(this,`markLayer`,void 0),b(this,`pinLayer`,void 0),b(this,`overlayLayer`,void 0),b(this,`selectButton`,void 0),b(this,`uiLayer`,void 0),b(this,`api`,void 0),b(this,`cleanups`,[]),b(this,`pageUnsub`,null),b(this,`sessionUnsub`,null),b(this,`pageKey`,``),b(this,`comments`,[]),b(this,`loaded`,!1),b(this,`placements`,/* @__PURE__ */ new Map),b(this,`pins`,/* @__PURE__ */ new Map),b(this,`status`,null),b(this,`pages`,[]),b(this,`picking`,!1),b(this,`panelOpen`,!1),b(this,`tab`,`open`),b(this,`card`,null),b(this,`activeId`,null),b(this,`hoverEl`,null),b(this,`toastTimer`,0),b(this,`toast`,null),b(this,`name`,ji(Z.name)??``),b(this,`secret`,void 0),b(this,`secretHash`,``),b(this,`ownerToken`,void 0),b(this,`ownerName`,null),b(this,`deepLinkId`,null),b(this,`extraComment`,null),b(this,`ownerDetail`,null),b(this,`ownerDetailId`,null),b(this,`ownerDetailLoaded`,!1),b(this,`ownerDetailUnsub`,null),b(this,`thread`,null),b(this,`threadId`,null),b(this,`threadUnsub`,null),b(this,`resolveRun`,0),b(this,`scopeWatchers`,/* @__PURE__ */ new Map),b(this,`pickDocs`,[]),b(this,`dragStart`,null),b(this,`dragBox`,null),b(this,`dragEnded`,!1),b(this,`selection`,null),b(this,`pointerDown`,!1),b(this,`selectionFrame`,0),b(this,`returnFocus`,null),b(this,`focusNext`,null),b(this,`confirming`,null),b(this,`live`,void 0),b(this,`layoutFrame`,0),b(this,`pinPositions`,/* @__PURE__ */ new Map),b(this,`resolveTimer`,0),b(this,`i18n`,void 0),b(this,`isIgnored`,e=>e===this.host||this.host.contains(e)),b(this,`onFrameKey`,e=>this.onKeyDown(e)),b(this,`swallow`,e=>{if(this.fromPage(e)){if(e.type===`pointerdown`&&e instanceof PointerEvent){let t=this.fromPage(e);t&&(this.hoverEl=$t(t),this.renderHighlight()),this.dragEnded=!1,this.dragStart=e.pointerType!==`touch`&&e.button===0&&(t?.ownerDocument??null)===document?{x:e.clientX,y:e.clientY}:null}if(e.type===`pointerup`&&this.dragBox){let e=this.dragBox;this.dragStart=null,this.dragBox=null,this.dragEnded=!0,setTimeout(()=>{this.dragEnded=!1,this.picking&&this.commentOnArea(e)},0)}else e.type===`pointerup`&&(this.dragStart=null);e.preventDefault(),e.stopPropagation()}}),b(this,`onPickMove`,e=>{let t=this.dragStart;if(t){let n=e.clientX-t.x,r=e.clientY-t.y;if(this.dragBox||Math.hypot(n,r)>6){this.dragBox={left:Math.min(t.x,e.clientX),top:Math.min(t.y,e.clientY),width:Math.abs(n),height:Math.abs(r)},this.renderHighlight();return}}let n=this.fromPage(e),r=n?$t(n):null;r!==this.hoverEl&&(this.hoverEl=r,this.renderHighlight())}),b(this,`onPickClick`,e=>{let t=this.fromPage(e);if(!t||(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),this.dragEnded))return;let n=$t(t),r=Et(n,{x:e.clientX,y:e.clientY},{ignoreAttributePrefixes:[],document});this.openComposer({anchor:r,element:n})}),this.i18n=xi(e.locale,e.messages);let n=ji(Z.secret);n||(n=g(),Mi(Z.secret,n)),this.secret=n,this.ownerToken=ji(Z.session(e.project)),this.host=document.createElement(`div`),this.host.id=`nuni-root`,this.host.setAttribute(`data-nuni`,``),this.applyAppearance(),this.root=this.host.attachShadow({mode:`open`});let r=document.createElement(`style`);r.textContent=`
|
|
6
|
+
`)}let h=`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`,ee=RegExp(`^nuni_[${h}]{22}$`);function te(e){let t=new Uint8Array(e);crypto.getRandomValues(t);let n=``;for(let e of t){let t=e;for(;t>=232;){let e=/* @__PURE__ */ new Uint8Array(1);crypto.getRandomValues(e),t=e[0]}n+=h[t%58]}return n}function ne(e){return typeof e==`string`&&ee.test(e)}function g(){return te(32)}let _={bodyMaxLength:2e3,nameMaxLength:50,unclaimedCommentCap:500,maxOriginsPerProject:20,sessionTtlMs:2592e6,cliSessionTtlMs:7776e6,transferTtlMs:6048e5,bulkMax:100,cliLoginTtlMs:6e5,anchorTextMaxLength:120,quoteMaxLength:500,quoteContextLength:32,pageOpenLimit:1e3,pageResolvedLimit:200,contextEntryMax:20,contextMessageMaxLength:500,domSnippetMaxLength:4e3,screenshotMaxBytes:6e5,repliesPerComment:200,reactionsPerComment:2e3,screenshotUploadWindowMs:3e5},re=[`👍`,`❤️`,`🎉`,`👀`,`✅`,`😄`],ie=`data-nuni-mask`,v=`[${ie}]`;function y(e){return{project:e.project,convexUrl:e.convexUrl??`https://greedy-giraffe-33.convex.cloud`,convexSiteUrl:e.convexSiteUrl??`https://greedy-giraffe-33.convex.site`,appUrl:(e.appUrl??`https://nuni.praveenjuge.com`).replace(/\/$/,``),getPageKey:e.getPageKey??le(e.pageKey),position:se(e.position,ae,`bottom-right`),accentColor:e.accentColor?.trim()||null,theme:se(e.theme,oe,`auto`),label:e.label?.trim()||null,hotkey:e.hotkey===!1?null:e.hotkey?.trim().slice(0,1).toLowerCase()||`c`,zIndex:typeof e.zIndex==`number`&&Number.isFinite(e.zIndex)?Math.round(e.zIndex):null,locale:e.locale?.trim()||void 0,messages:e.messages??{},capture:{console:e.capture?.console??!0,network:e.capture?.network??!0,dom:e.capture?.dom??!0,screenshot:e.capture?.screenshot??!0}}}let ae=[`bottom-right`,`bottom-center`,`bottom-left`,`top-right`,`top-center`,`top-left`],oe=[`auto`,`light`,`dark`];function se(e,t,n){return t.includes(e)?e:n}let ce=/^(nuni|utm_.*|fbclid|gclid|msclkid|ref)$/i;function le(t=`path`){return n=>{let r=e(n);if(t===`path+search`){let e=[...n.searchParams].filter(([e])=>!ce.test(e)).sort(([e],[t])=>e<t?-1:+(e>t));return e.length?`${r}?${new URLSearchParams(e).toString()}`:r}return t===`path+hash`&&n.hash.length>1&&!r.includes(`#`)&&!/^#!?\//.test(n.hash)?`${r}${n.hash}`:r}}let ue=Symbol.for(`nuni.capture`);function de(e){"@babel/helpers - typeof";return de=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},de(e)}function fe(e,t){if(de(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(de(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function pe(e){var t=fe(e,`string`);return de(t)==`symbol`?t:t+``}function b(e,t,n){return(t=pe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}let me=_.contextMessageMaxLength;function he(e){if(typeof e==`string`)return e;if(e instanceof Error){let t=e.stack?.split(`
|
|
7
|
+
`).find(e=>e.trim().startsWith(`at `));return`${e.name}: ${e.message}${t?` (${t.trim()})`:``}`}try{let t=200;return JSON.stringify(e,(e,n)=>t-->0?n:void 0)??String(e)}catch{return String(e)}}function ge(e){return e.length>me?`${e.slice(0,me-1)}…`:e}function _e(e){return ge(i(e,location.href))}var ve=class{constructor(){b(this,`items`,[])}push(e){this.items.push(e),this.items.length>_.contextEntryMax&&this.items.shift()}};function ye(e,t){let n=new ve,r=new ve,i=[],a=(e,t)=>{n.push({level:e,message:ge(o(t.map(he).join(` `))),at:Date.now()})},s=(e,n,i)=>{t(n)||r.push({method:e.toUpperCase(),url:_e(n),status:i,at:Date.now()})};if(e.console){for(let e of[`error`,`warn`]){let t=console[e],n=(...n)=>{a(e,n),t.apply(console,n)};console[e]=n,i.push(()=>{console[e]===n&&(console[e]=t)})}let e=e=>{e.error?a(`error`,[e.error]):a(`error`,[`${e.message}${e.filename?` (${_e(e.filename)}:${e.lineno})`:``}`])},t=e=>a(`error`,[`Unhandled rejection:`,e.reason]);window.addEventListener(`error`,e),window.addEventListener(`unhandledrejection`,t),i.push(()=>{window.removeEventListener(`error`,e),window.removeEventListener(`unhandledrejection`,t)})}if(e.network){let e=window.fetch;if(typeof e==`function`){let t=async(t,n)=>{if(n&&n[ue])return e.call(window,t,n);let r=typeof t==`string`?t:t instanceof URL?t.href:t.url,i=n?.method??(typeof t==`object`&&`method`in t?t.method:`GET`);try{let a=await e.call(window,t,n);return!a.ok&&a.type!==`opaque`&&s(i,r,a.status),a}catch(e){throw e instanceof DOMException&&e.name===`AbortError`||s(i,r,0),e}};window.fetch=t,i.push(()=>{window.fetch===t&&(window.fetch=e)})}let t=window.XMLHttpRequest?.prototype;if(t){let e=t.open,n=t.send,r=/* @__PURE__ */ new WeakMap,a=function(t,n,...i){return r.set(this,{method:t,url:String(n)}),e.call(this,t,n,...i)};t.open=a;let o=function(e){let t=r.get(this);if(t){let e=!1,n=()=>e=!0,r=()=>{this.removeEventListener(`abort`,n),this.removeEventListener(`loadend`,r),!e&&(this.status===0||this.status>=400)&&s(t.method,t.url,this.status)};this.addEventListener(`abort`,n),this.addEventListener(`loadend`,r)}return n.call(this,e)};t.send=o,i.push(()=>{t.open===a&&(t.open=e),t.send===o&&(t.send=n)})}}return{console:()=>[...n.items],network:()=>[...r.items],stop(){for(let e of i.splice(0))e()}}}let be=[`display`,`position`,`width`,`height`,`margin`,`padding`,`gap`,`font-family`,`font-size`,`font-weight`,`line-height`,`letter-spacing`,`text-align`,`color`,`background-color`,`border`,`border-radius`,`box-shadow`,`opacity`];function xe(e,t){e.replaceChildren(e.ownerDocument.createComment(` ${t} `))}function Se(e){let t=e.ownerDocument.createTreeWalker(e,5),n=[];for(let r=e;r;r=t.nextNode()){if(r.nodeType===3){let e=r.textContent??``;e.length>200&&(r.textContent=`${e.slice(0,200)}…`);continue}let e=r,t=e.tagName;if(t===`SCRIPT`||t===`STYLE`||t===`NOSCRIPT`){n.push(e);continue}if(e.hasAttribute(`data-nuni-mask`)){for(let t of Array.from(e.attributes))t.name!==`id`&&t.name!==`class`&&t.name!==`data-nuni-mask`&&e.removeAttribute(t.name);xe(e,`masked`);continue}if((t===`INPUT`||t===`TEXTAREA`)&&(e.removeAttribute(`value`),t===`TEXTAREA`&&(e.textContent=``)),t===`SELECT`||t===`DATALIST`){let t=e.getElementsByTagName(`option`).length;xe(e,`${t} options`)}for(let t of Array.from(e.attributes))t.value.length>200&&e.setAttribute(t.name,`${t.value.slice(0,200)}…`)}for(let e of n)e.parentNode?.removeChild(e)}function Ce(e,t){let n=e.cloneNode(!1);if(t>0)for(let r of Array.from(e.childNodes))n.appendChild(r.nodeType===1?Ce(r,t-1):r.cloneNode(!1));else e.childElementCount&&n.appendChild(e.ownerDocument.createComment(` ${e.childElementCount} more `));return n}function we(e){let t=_.domSnippetMaxLength,n=``,r=!!e.parentElement?.closest(`[${ie}]`);for(let i of r?[-1]:[1/0,3,1,0]){let r=i===1/0?e.cloneNode(!0):Ce(e,Math.max(0,i));if(i<0&&r.setAttribute(ie,``),Se(r),n=l(r.outerHTML),n.length<=t)break}n.length>t&&(n=`${n.slice(0,t-1)}…`);let i={},a=e.ownerDocument.defaultView?.getComputedStyle(e);for(let e of be){let t=a?.getPropertyValue(e).trim();t&&(i[e]=t)}return{html:n,styles:i}}function Te(e){let t=Object.keys(e).find(e=>e.startsWith(`__reactFiber$`)||e.startsWith(`__reactInternalInstance$`));if(!t)return;let n=e[t]??null;for(let e=0;n&&e<30;e++){let e=n.type;if(e&&typeof e!=`string`){let t=e.displayName||e.name||e.render?.name;if(t&&t.length>2&&/^[A-Z]/.test(t))return t}n=n.return??null}}function Ee(e){let t=e.getBoundingClientRect(),n=e.ownerDocument.defaultView,r=n?.scrollX??0,i=n?.scrollY??0;return{x:t.left+r,y:t.top+i,w:t.width,h:t.height}}function De(e){let t=e.defaultView;return{w:t?.innerWidth??0,h:t?.innerHeight??0,dpr:t?.devicePixelRatio??1,scrollX:t?.scrollX??0,scrollY:t?.scrollY??0}}function Oe(e){let t=e.documentElement;return{w:t.scrollWidth,h:t.scrollHeight}}function ke(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):.5}function Ae(e){if(!e.isConnected)return!1;let t=e.ownerDocument.defaultView,n=e.getBoundingClientRect();if(n.width===0&&n.height===0)return!1;let r=t?.getComputedStyle(e);return!r||r.visibility!==`hidden`&&r.display!==`none`}function je(e,t){let n=t.ignoreAttributePrefixes;return!n||!n.some(t=>e.startsWith(t))}let Me=/* @__PURE__ */ new Set([`SCRIPT`,`STYLE`,`NOSCRIPT`,`TEMPLATE`,`SVG`]);function Ne(e){return e.replace(/\s+/g,` `).trim()}function x(e,t=120){if(e.closest(v))return``;if(e.tagName===`INPUT`||e.tagName===`TEXTAREA`)return Ne(e.placeholder||e.getAttribute(`aria-label`)||``).slice(0,t);let n=``,r=e=>{if(n.length>t*2)return;if(e.nodeType===3){n+=e.nodeValue??``;return}if(e.nodeType!==1)return;let i=e.tagName.toUpperCase();if(Me.has(i)||e.hasAttribute(`data-nuni-mask`)||e.hasAttribute(`data-nuni`))return;if(i===`IMG`){n+=` `+(e.getAttribute(`alt`)??``)+` `;return}let a=e.shadowRoot;if(a){for(let e of Array.from(a.childNodes))r(e);return}if(i===`SLOT`){let t=e.assignedNodes?.({flatten:!0});if(t?.length){for(let e of t)r(e);return}}for(let t of Array.from(e.childNodes))r(t);(i===`BR`||i===`P`||i===`DIV`||i===`LI`)&&(n+=` `)};return r(e),Ne(n).slice(0,t)}function Pe(e){let t=e.toLowerCase(),n=/* @__PURE__ */ new Map;for(let e=0;e<t.length-1;e++){let r=t.slice(e,e+2);n.set(r,(n.get(r)??0)+1)}return n}function Fe(e,t){if(e===t)return 1;let n=e.toLowerCase(),r=t.toLowerCase();if(n===r)return 1;if(n.length<2||r.length<2)return 0;let i=Pe(n),a=Pe(r),o=0;for(let[e,t]of i){let n=a.get(e);n&&(o+=Math.min(t,n))}return 2*o/(n.length-1+(r.length-1))}let Ie=/* @__PURE__ */ new Set([`SCRIPT`,`STYLE`,`NOSCRIPT`,`TEMPLATE`,`SVG`]),Le=/* @__PURE__ */ new Set(/* @__PURE__ */ `ADDRESS.ARTICLE.ASIDE.BLOCKQUOTE.BR.DD.DIV.DL.DT.FIGCAPTION.FIGURE.FOOTER.FORM.H1.H2.H3.H4.H5.H6.HEADER.HR.LI.MAIN.NAV.OL.P.PRE.SECTION.TABLE.TD.TH.TR.UL`.split(`.`)),Re=/* @__PURE__ */ new Set(/* @__PURE__ */ `A.ABBR.B.BDI.BDO.CITE.CODE.DATA.DEL.DFN.EM.I.INS.KBD.LABEL.MARK.Q.S.SAMP.SMALL.SPAN.STRONG.SUB.SUP.TIME.U.VAR`.split(`.`)),ze=2e4,Be=/[\p{L}\p{N}]/u;function Ve(e){let t={text:``,nodes:[],node:[],offset:[]};if(e.closest(v))return t;let n=[],r=!0,i=(e,r,i)=>{n.push(e),t.node.push(r),t.offset.push(i)},a=()=>{if(r||!t.nodes.length)return;let e=t.nodes.length-1;i(` `,e,t.nodes[e].length),r=!0},o=e=>{if(n.length>=ze)return;if(e.nodeType===3){let a=e.nodeValue??``;if(!a)return;let o=t.nodes.push(e)-1;for(let e=0;e<a.length&&n.length<ze;e++){let t=a[e];t===` `||t===`
|
|
8
|
+
`||t===` `||t===`\r`||t===`\f`?(r||i(` `,o,e),r=!0):(i(t,o,e),r=!1)}return}if(e.nodeType!==1)return;let s=e,c=s.tagName.toUpperCase();if(Ie.has(c)||s.hasAttribute(`data-nuni-mask`)||s.hasAttribute(`data-nuni`))return;let l=Le.has(c);l&&a();for(let e of Array.from(s.childNodes))o(e);l&&a()};for(o(e);n.length&&n[n.length-1]===` `;)n.pop(),t.node.pop(),t.offset.pop();return t.text=n.join(``),t}function He(e,t,n){if(!e.text.length)return 0;let r=(t.ownerDocument??t).createRange();r.setStart(t,n),r.collapse(!0);let i=0,a=e.text.length;try{for(;i<a;){let t=i+a>>1,n=e.nodes[e.node[t]];r.comparePoint(n,e.offset[t])<0?i=t+1:a=t}}catch{return-1}return i}function Ue(e,t,n){let r=e.nodes[e.node[t]],i=e.nodes[e.node[n-1]],a=r.ownerDocument.createRange();return a.setStart(r,e.offset[t]),a.setEnd(i,Math.min(i.length,e.offset[n-1]+1)),a}function We(e){let t=e.commonAncestorContainer;if(t.nodeType!==1&&(t=t.parentNode),!t||t.nodeType!==1)return null;let n=t,r=n.ownerDocument.body;for(;Re.has(n.tagName.toUpperCase())&&n.parentElement&&n.parentElement!==r;)n=n.parentElement;return n}function Ge(e,t){let n=Ve(t),r=He(n,e.startContainer,e.startOffset),i=He(n,e.endContainer,e.endOffset);if(r<0||i<0)return null;let{text:a}=n;for(;r<i&&a[r]===` `;)r++;for(;i>r&&a[i-1]===` `;)i--;if(i<=r)return null;let o=a.slice(r,Math.min(i,r+_.quoteMaxLength)),s=r+o.length;return{exact:o,prefix:a.slice(Math.max(0,r-_.quoteContextLength),r),suffix:a.slice(s,s+_.quoteContextLength)}}function Ke(e,t){let n=Ye(e,t,0);if(n)return n;let r=e.parentElement,i=e.ownerDocument.body;for(let e=0;r&&r!==i&&e<2;e++){let e=Ye(r,t,.6);if(e)return e;r=r.parentElement}return null}function qe(e,t){return t?Fe(e,t):e?.8:1}function Je(e,t,n,r){let i=e.slice(Math.max(0,t-r.prefix.length),t),a=e.slice(n,n+r.suffix.length);return(qe(i.trimStart(),r.prefix.trimStart())+qe(a.trimEnd(),r.suffix.trimEnd()))/2}function Ye(e,t,n){let{exact:r}=t;if(!r)return null;let i=Ve(e),{text:a}=i;if(!a)return null;let o=-1,s=-1;for(let e=a.indexOf(r);e>=0;e=a.indexOf(r,e+1)){let n=Je(a,e,e+r.length,t);n>s&&(o=e,s=n)}if(o>=0&&s>=n)return{range:Ue(i,o,o+r.length),exact:!0};if(r.length<8||a.length>6e3)return null;let c=Xe(a,t);if(!c)return null;let l=Je(a,c.start,c.end,t);return c.score<.75||l<Math.max(n,.3)?null:{range:Ue(i,c.start,c.end),exact:!1}}function Xe(e,t){let n=e=>e!==void 0&&Be.test(e),r=[],i=[];for(let t=0;t<e.length;t++){let a=e[t];if(a===` `)continue;let o=e[t-1],s=e[t+1];(o===void 0||o===` `||n(a)&&!n(o))&&r.push(t),(s===void 0||s===` `||n(a)&&!n(s))&&i.push(t+1)}let a=t.exact.length,o=null,s=0;for(let n of r){for(;s<i.length&&i[s]<=n;)s++;for(let r=s;r<i.length;r++){let s=i[r]-n;if(s<a*.7)continue;if(s>a*1.3)break;let c=Fe(e.slice(n,i[r]),t.exact);(!o||c>o.score)&&(o={start:n,end:i[r],score:c})}}return o}function S(e){return!!(e&&e.nodeType===11&&`host`in e)}function Ze(e){let t=e.getRootNode();return S(t)?t:e.ownerDocument}function Qe(e){return S(e)?e.ownerDocument:e}function $e(e){try{return e.defaultView?.frameElement??null}catch{return null}}function et(e){if(e.tagName!==`IFRAME`&&e.tagName!==`FRAME`)return null;try{return e.contentDocument}catch{return null}}function tt(e,t){let n=[],r=e;for(let e=0;e<8;e++){let e=r.getRootNode();if(S(e)){n.unshift({kind:`shadow`,host:e.host}),r=e.host;continue}if(r.ownerDocument===t)break;let i=$e(r.ownerDocument);if(!i)break;n.unshift({kind:`frame`,host:i}),r=i}return n}function nt(e,t){let n=e.getBoundingClientRect(),r=n.left,i=n.top,a=!1,o=e.ownerDocument;for(let e=0;e<8&&o!==t;e++){let e=$e(o);if(!e)break;let t=o.defaultView;t&&(r+n.width<0||i+n.height<0||r>t.innerWidth||i>t.innerHeight)&&(a=!0);let s=e.getBoundingClientRect();r+=s.left+e.clientLeft,i+=s.top+e.clientTop,o=e.ownerDocument}return{left:r,top:i,width:n.width,height:n.height,clipped:a}}let rt=/^-?(m|p|mx|my|mt|mb|ml|mr|ms|me|px|py|pt|pb|pl|pr|ps|pe|w|h|min-w|max-w|min-h|max-h|size|gap|gap-x|gap-y|space-x|space-y|text|font|bg|border|border-[trblxy]|rounded|rounded-[trbl]{1,2}|shadow|flex|grid|grid-cols|grid-rows|col|col-span|row|row-span|items|justify|self|place|content|inset|inset-x|inset-y|top|left|right|bottom|start|end|z|opacity|leading|tracking|ring|ring-offset|outline|overflow|overflow-x|overflow-y|order|basis|grow|shrink|translate-x|translate-y|scale|rotate|skew|transition|duration|ease|delay|animate|cursor|select|fill|stroke|object|aspect|line-clamp|decoration|indent|align|whitespace|break|hyphens|list|columns|backdrop|blur|brightness|contrast|drop-shadow|grayscale|invert|saturate|sepia|divide|divide-x|divide-y|from|to|via|accent|caret|scroll|snap|touch|will-change|pointer-events|underline-offset|auto-cols|auto-rows|origin|mix-blend|bg-blend|box|float|clear|appearance|resize|table|sr|not-sr)(-|$)/,it=/* @__PURE__ */ new Set(/* @__PURE__ */ `flex.grid.block.inline.inline-block.inline-flex.inline-grid.hidden.contents.table.static.fixed.absolute.relative.sticky.visible.invisible.container.truncate.underline.uppercase.lowercase.capitalize.italic.antialiased.sr-only.grow.shrink.isolate.transform.filter.group.peer.prose.dark.light`.split(`.`)),at=[/_{1,3}(?=[a-zA-Z-]*[0-9])[a-zA-Z0-9-]{5,}$/,/_{1,3}(?=[a-zA-Z0-9-]*[A-Z][a-zA-Z0-9-]*[A-Z])(?=[a-zA-Z0-9-]*[a-z])[a-zA-Z0-9-]{5,8}$/,/^_[a-zA-Z0-9]/,/^(css|sc|jsx|svelte|astro|emotion|e|tw|vanilla|chakra-[a-z]+-)[-_][a-zA-Z0-9]{4,}$/,/^[a-z]{1,3}-(?=[a-zA-Z]*[0-9])[a-zA-Z0-9]{5,}$/,/^(is|has)-(active|open|selected|focused|hover|hovered|visible|hidden|expanded|collapsed|loading|disabled|checked|current)$/,/^(active|open|selected|focus|focused|hover|current|show|showing|in|fade|collapse|collapsing)$/];function ot(e){if(e.length<5)return!1;let t=e.replace(/[^0-9]/g,``).length;return t===0?/^[a-zA-Z]{6,}$/.test(e)&&/[A-Z].*[A-Z]/.test(e)&&/[a-z]/.test(e)&&!/^[A-Z][a-z]+([A-Z][a-z]+)+$/.test(e):e.replace(/[^a-zA-Z]/g,``).length===0||!/^[a-zA-Z]+[-_]?\d{1,3}$/.test(e)&&t/e.length>.2}function st(e){return/[[\]:/()%!#@&*,.>+~=]/.test(e)||it.has(e)?!0:rt.test(e)}function ct(e){return!e||e.length>40||e.startsWith(`nuni-`)||st(e)||at.some(t=>t.test(e))?!1:!ot(e)}function C(e){let t=[];for(let n of Array.from(e.classList))if(ct(n)&&t.push(n),t.length>=4)break;return t}let lt=[/^:[a-zA-Z0-9]+:$/,/^«[a-zA-Z0-9]+»$/,/^(radix|headlessui|mui|react-aria|rc|base-ui|mantine|chakra|reach|downshift|ember|ext|yui|ui-id|aria|mat|cdk|ng|v|vue|svelte|el|id|uid|field|input)[-_:]/i,/[0-9a-f]{8}-[0-9a-f]{4}-/i,/\d{3,}/];function ut(e){return!e||e.length>80||lt.some(t=>t.test(e))?!1:!ot(e)}let dt=[`data-nuni`,`data-testid`,`data-test-id`,`data-test`,`data-cy`,`data-qa`],ft=[`aria-label`,`name`,`href`,`src`,`alt`,`placeholder`,`title`,`type`,`role`,`for`,`value`];function pt(e){return typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/([^\w-])/g,`\\$1`).replace(/^(\d)/,`\\3$1 `)}function mt(e,t){return`[${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"]`}function ht(e,t){for(let n of dt){if(!je(n,t))continue;let r=e.getAttribute(n);if(r&&r.length<=100)return{attr:n,value:r}}return null}function gt(e){let t=e.getAttribute(`id`);return t&&ut(t)?t:null}function _t(e){return e.tagName.toLowerCase()}function vt(e){let t=1,n=e.previousElementSibling;for(;n;)n.tagName===e.tagName&&t++,n=n.previousElementSibling;return t}function yt(e){let t=e.parentNode;if(!t)return 1;let n=0;for(let r of Array.from(t.children))r.tagName===e.tagName&&n++;return n}function w(e,t){try{return e.querySelectorAll(t).length}catch{return 1/0}}function bt(e,t){return w(e,`#${pt(t)}`)===1}function xt(e){let t=Ze(e),n=e.ownerDocument,r=[],i=e;for(;i&&i!==n.documentElement;){let n=gt(i);if(n&&i!==e&&bt(t,n))return r.unshift(`#${pt(n)}`),r.join(` > `);let a=_t(i);r.unshift(yt(i)>1?`${a}:nth-of-type(${vt(i)})`:a),i=i.parentElement}return S(t)?r.join(` > `):r.length?`html > ${r.join(` > `)}`:`html`}function St(e,t){let n;try{n=Array.from(e.querySelectorAll(t)).slice(0,50)}catch{return null}if(!S(e)||t.startsWith(`#`))return n[0]??null;let r=t.split(` > `).length;return n.find(t=>{let n=t;for(let e=1;e<r&&n;e++)n=n.parentElement;return n?.parentNode===e})??null}function Ct(e,t){let n=_t(e),r=ht(e,t);if(r)return n+mt(r.attr,r.value);let i=n;for(let t of C(e).slice(0,2))i+=`.${pt(t)}`;for(let r of[`name`,`type`,`role`]){let a=e.getAttribute(r);if(a&&a.length<=40&&je(r,t)){if(r===`type`&&n!==`input`&&n!==`button`)continue;i+=mt(r,a)}}let a=e.getAttribute(`aria-label`);return a&&a.length<=60&&!e.closest(v)&&(i+=mt(`aria-label`,a)),i}function wt(e,t={}){let n=e.ownerDocument,r=Ze(e),i=gt(e);if(i&&bt(r,i))return`#${pt(i)}`;let a=[],o=e;for(let e=0;o&&e<6;e++){if(o===n.documentElement||o===n.body){a.unshift(_t(o));break}let i=gt(o);if(e>0&&i&&bt(r,i)){a.unshift(`#${pt(i)}`);let e=a.join(` > `);if(w(r,e)===1)return e;break}a.unshift(Ct(o,t));let s=a.join(` > `);if(w(r,s)===1)return s;let c=o.parentElement;if(c&&w(c,`:scope > ${a[0]}`)>1&&(a[0]=`${a[0]}:nth-of-type(${vt(o)})`,s=a.join(` > `),w(r,s)===1))return s;o=o.parentElement}let s=a.join(` > `);return w(r,s)===1?s:void 0}function Tt(e,t){let n={};if(e.closest(v))return n;for(let r of ft){if(!je(r,t)||r===`value`&&e.tagName!==`BUTTON`&&e.getAttribute(`type`)!==`submit`)continue;let i=e.getAttribute(r);i&&(n[r]=i.slice(0,200))}return n}function Et(e){let t=[],n=e.parentElement;for(;n&&t.length<5&&n!==n.ownerDocument.documentElement;){let e=gt(n),r={tag:n.tagName.toLowerCase(),classes:C(n).slice(0,3)};if(e&&(r.id=e),t.length<3&&n!==n.ownerDocument.body){let e=x(n,80);e&&(r.text=e)}t.push(r),n=n.parentElement}return t}function Dt(e,t,n={}){let r=Ot(e,t,n),i=tt(e,n.document??(typeof document>`u`?e.ownerDocument:document));return i.length&&(r.scope=i.map(({kind:e,host:t})=>({kind:e,host:Ot(t,void 0,n)}))),r}function Ot(e,t,n){let r=e.ownerDocument,i=Ee(e),a=De(r),o=e.getBoundingClientRect(),s=t?{x:ke(o.width?(t.x-o.left)/o.width:.5),y:ke(o.height?(t.y-o.top)/o.height:.5)}:{x:.5,y:.5},c=gt(e),l=ht(e,n),u=wt(e,n),d=e.getAttribute(`role`)??void 0,f=e.parentNode,p=f?Array.from(f.children):[e],m={v:1,selectors:{path:xt(e),...c?{id:c}:{},...l?{testId:`${l.attr}=${l.value}`}:{},...u?{css:u}:{}},tag:e.tagName.toLowerCase(),classes:C(e),text:x(e,_.anchorTextMaxLength),attrs:Tt(e,n),ancestors:Et(e),siblingIndex:p.indexOf(e),siblingCount:p.length,rect:i,offset:s,viewport:a,docSize:Oe(r)};d&&(m.role=d);let h=Te(e);return h&&(m.componentName=h),m}function kt(e,t={}){let n=We(e);if(!n)return null;let r=Ge(e,n);if(!r)return null;let i=e.getClientRects()[0]??e.getBoundingClientRect(),a=Dt(n,{x:i.left,y:i.top+i.height/2},t);return a.quote=r,{element:n,anchor:a}}function At(e,t,n=()=>!1){let r=t.left+t.width,i=t.top+t.height,a=[[t.left+1,t.top+1],[r-1,t.top+1],[t.left+1,i-1],[r-1,i-1]],o=e=>n(e)||e.closest(`[data-nuni]`)!==null,s=null;for(let[t,n]of a){let r=e.elementsFromPoint(t,n).find(e=>!o(e));r&&(s=s?jt(s,r):r)}let c=s??e.body;for(;c.parentElement&&c!==e.body;){let e=c.getBoundingClientRect();if(e.left<=t.left+1&&e.top<=t.top+1&&e.right>=r-1&&e.bottom>=i-1)break;c=c.parentElement}return c}function jt(e,t){let n=/* @__PURE__ */ new Set;for(let t=e;t;t=t.parentElement)n.add(t);for(let e=t;e;e=e.parentElement)if(n.has(e))return e;return e.ownerDocument.body}function Mt(e,t,n={}){let r=Dt(e,{x:t.left+t.width,y:t.top},n),i=e.getBoundingClientRect(),a=i.width?ke((t.left-i.left)/i.width):0,o=i.height?ke((t.top-i.top)/i.height):0;return r.region={x:a,y:o,w:i.width?Math.min(1-a,t.width/i.width):1,h:i.height?Math.min(1-o,t.height/i.height):1},r}function Nt(){return{byTag:/* @__PURE__ */ new Map,elements:/* @__PURE__ */ new Map,text:/* @__PURE__ */ new WeakMap,content:/* @__PURE__ */ new WeakMap,words:/* @__PURE__ */ new WeakMap}}function Pt(e,t,n){if(!n)return x(e,t);let r=n.text.get(e);r||n.text.set(e,r=/* @__PURE__ */ new Map);let i=r.get(t);return i===void 0&&r.set(t,i=x(e,t)),i}function Ft(e,t){if(!t)return e.textContent??``;let n=t.content.get(e);return n===void 0&&t.content.set(e,n=e.textContent??``),n}function It(e,t){let n=t?.words.get(e);return n===void 0&&(n=Ne(Ft(e,t)),t?.words.set(e,n)),n}function Lt(e,t,n){let r=()=>S(e)?e.querySelectorAll(t):e.getElementsByTagName(t);if(!n)return r();let i=n.byTag.get(e);i||n.byTag.set(e,i=/* @__PURE__ */ new Map);let a=i.get(t);return a||i.set(t,a=Array.from(r())),a}function Rt(e,t,n){let r=n?.elements.get(e);if(r)return r;let i=Qe(e),a=S(e)?e:i.body??i.documentElement,o=i.createTreeWalker(a,1),s=[];for(let e=o.nextNode();e&&s.length<t;e=o.nextNode())s.push(e);return n?.elements.set(e,s),s}let zt={exact:.9,high:.72,low:.55},Bt=3e3;function Vt(e,t,n=20){if(!t)return[];try{return Array.from(e.querySelectorAll(t)).slice(0,n)}catch{return[]}}function Ht(e,t){if(!t)return!1;try{return e.matches(t)}catch{return!1}}function Ut(e,t){if(!e.length&&!t.length)return 1;let n=new Set(e),r=0;for(let e of new Set(t))n.has(e)&&r++;return r/(n.size+new Set(t).size-r)}function Wt(e){let t=e.indexOf(`=`);return t>0?[e.slice(0,t),e.slice(t+1)]:null}function Gt(e,t){return`[${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"]`}function Kt(e,t){try{let n=new URL(e,t.baseURI);return n.pathname.replace(/\/$/,``)+n.search}catch{return e}}function qt(e){let t=e.parentElement;if(!t)return 0;let n=C(e).join(` `),r=0;for(let i of Array.from(t.children))i!==e&&i.tagName===e.tagName&&C(i).join(` `)===n&&r++;return r}let Jt=/* @__PURE__ */ new Set([`href`,`name`,`aria-label`,`src`,`for`,`placeholder`,`alt`,`title`]);function Yt(e,t,n,r,i,a){let o=0,s=0,c=(e,t)=>{o+=e*t,s+=e};c(1,+(t.tagName.toLowerCase()===e.tag));let l=!1;if(e.selectors.id){let n=t.getAttribute(`id`)===e.selectors.id;l||(l=n),c(3,+!!n)}if(e.selectors.testId){let n=Wt(e.selectors.testId),r=!!(n&&t.getAttribute(n[0])===n[1]);l||(l=r),c(4,+!!r)}let u=Ht(t,e.selectors.css);e.selectors.css&&c(1.5,+!!u);let d=r.pathMatch===t;c(1,+!!d),e.classes&&e.classes.length&&c(1.5,Ut(C(t),e.classes));let f=Object.keys(e.attrs).filter(e=>je(e,i)),p=!1;if(f.length){let r=0,i=0,a=0;for(let o of f){let s=Jt.has(o);s&&i++;let c=t.getAttribute(o);if(c==null)continue;let l=e.attrs[o];(o===`href`||o===`src`?Kt(c,n)===Kt(l,n):c===l)?(r++,s&&a++):r+=Fe(c,l)*.5}c(2,r/f.length),p=i>0&&a===i}e.role&&c(.5,+(t.getAttribute(`role`)===e.role)),e.componentName&&c(.5,+(Te(t)===e.componentName));let m=Pt(t,120,a),h=e.text?Fe(m,e.text):m?.3:1;c(e.text?3:1,h);let ee=e.quote?It(t,a).includes(e.quote.exact):null;ee!==null&&c(3,+!!ee);let te=0,ne=0,g=null,_=t.parentElement;e.ancestors.forEach((t,n)=>{let r=1-n*.15;if(ne+=r,!_)return;let i=_.tagName.toLowerCase()===t.tag?.4:0,o=_.getAttribute(`id`);t.id?i+=o===t.id?.35:0:i+=.35*(o?.5:1),i+=.25*Ut(C(_),t.classes),te+=r*i,g===null&&t.text&&t.text!==e.text&&(g=Fe(Pt(_,80,a),t.text)),_=_.parentElement}),ne&&c(1.5,te/ne),g!==null&&c(2,g);let re=t.parentNode,ie=re?Array.prototype.indexOf.call(re.children,t):0;c(.5,Math.max(0,1-Math.abs(ie-e.siblingIndex)/3));let v=Math.max(0,1-Math.abs(r.viewportRatio-1)*2),y=t.getBoundingClientRect(),ae=y.width+y.height>0;if(v>0&&e.rect.w+e.rect.h>0&&ae){let t=n.defaultView,i=y.left+(t?.scrollX??0)+y.width/2,a=y.top+(t?.scrollY??0)+y.height/2,o=(e.rect.x+e.rect.w/2)*r.viewportRatio,s=e.rect.y+e.rect.h/2,l=Math.hypot(i-o,a-s);c(1.5*v,Math.exp(-l/250));let u=Math.min(y.width,e.rect.w)/Math.max(y.width,e.rect.w,1),d=Math.min(y.height,e.rect.h)/Math.max(y.height,e.rect.h,1);c(.5*v,u*d)}let oe=s?o/s:0,se=(u||!e.selectors.css)&&d&&p,ce=r.quoteOnly===t?Math.max(h,.9):h;if(e.text.length>=2&&ce<.999){let e=qt(t)>0?.2+.8*ce*ce:.7+.3*ce;oe*=l||se?Math.max(e,.92):e}return ee===!1&&(oe*=.85),{el:t,score:oe,text:h,context:g,strong:l||se,rendered:ae}}function Xt(e,t,n,r){let i=Qe(t),a=/* @__PURE__ */ new Set,o=e=>e===i.documentElement||(n.isIgnored?.(e)??!1),s=e=>{e&&!o(e)&&a.add(e)};if(e.selectors.id&&s(S(t)?Vt(t,`#${pt(e.selectors.id)}`,1)[0]:t.getElementById(e.selectors.id)),e.selectors.testId){let n=Wt(e.selectors.testId);n&&Vt(t,Gt(n[0],n[1])).forEach(s)}Vt(t,e.selectors.css).forEach(s);let c=St(t,e.selectors.path);s(c);let l=e.text.slice(0,24).toLowerCase(),u=Lt(t,e.tag,r),d=u.length<=Bt;for(let e=0;e<u.length&&e<Bt*2;e++){let t=u[e];if(d){s(t);continue}let n=Ft(t,r).toLowerCase();l&&n.includes(l)&&s(t)}if(e.text.length>=3){let n=e.text.toLowerCase();for(let i of Rt(t,Bt*3,r)){if(i.tagName.toLowerCase()===e.tag)continue;let t=Ft(i,r);!t||t.length>n.length*3+20||Pt(i,120,r).toLowerCase()===n&&s(i)}}return{candidates:a,pathMatch:c}}let T={lost:0,low:1,high:2,exact:3};function Zt(e,t=document,n={},r){let i=t,a=`exact`,o={element:null,confidence:`lost`,score:0};for(let t of e.scope??[]){let e=Qt(t.host,i,n,r);if(!e.element)return o;let s=e.confidence;if(t.host.text){if(e.text<.9&&T[s]<T.high)return o;e.text>=.999&&e.margin>=.1&&s===`low`&&(s=`high`)}let c=t.kind===`shadow`?e.element.shadowRoot:et(e.element);if(!c)return o;T[s]<T[a]&&(a=s),i=c}let{text:s,margin:c,...l}=Qt(e,i,n,r);if(l.element&&T[a]<T[l.confidence]&&(l.confidence=a),l.element&&e.quote){let t=Ke(l.element,e.quote);t&&(l.range=t.range),(!t||!t.exact)&&T[l.confidence]>T.low&&(l.confidence=`low`)}return l}function Qt(e,t,n,r){let i=Qe(t);if(!S(t)&&(e.tag===`body`||e.tag===`html`))return{element:i.body,confidence:`exact`,score:1,text:1,margin:1};let{candidates:a,pathMatch:o}=Xt(e,t,n,r);if(!a.size)return{element:null,confidence:`lost`,score:0,text:0,margin:0};let s=i.defaultView,c=e.viewport.w&&s?.innerWidth?s.innerWidth/e.viewport.w:1,l=null;if(e.quote){let t=e.quote.exact,n=[...a].filter(e=>It(e,r).includes(t)),i=n.filter(e=>!n.some(t=>t!==e&&e.contains(t)));i.length===1&&(l=i[0])}let u=[];for(let t of a)u.push(Yt(e,t,i,{pathMatch:o,viewportRatio:c,quoteOnly:l},n,r));let d=e.rect.w+e.rect.h>0&&u.some(e=>e.rendered),f=e=>!d||e.rendered;if(u.filter(t=>t.text>=.999&&t.el.tagName.toLowerCase()===e.tag&&f(t)).length>1)for(let e of u)e.context===null||e.strong||(e.score*=.2+.8*e.context*e.context);u.sort((e,t)=>t.score-e.score);let p=u[0],m=u.find(e=>e.el!==p.el&&!p.el.contains(e.el)&&!e.el.contains(p.el)&&(!p.rendered||f(e)));if(p.score<zt.low)return{element:null,confidence:`lost`,score:p.score,text:p.text,margin:0};let h=p.score>=zt.exact&&p.text>=.999?`exact`:p.score>=zt.high?`high`:`low`,ee=m?p.score-m.score:1;return ee<.03&&(h=`low`),{element:p.el,confidence:h,score:p.score,text:p.text,margin:ee}}let $t=/* @__PURE__ */ new Set([`SPAN`,`STRONG`,`EM`,`B`,`I`,`SMALL`,`MARK`,`SUB`,`SUP`,`ABBR`,`CODE`,`KBD`,`TIME`,`U`,`S`]);function en(e){let t=e,n=t.closest(`svg`);n&&(t=n.parentElement??n);let r=t.closest(`a[href], button, label, summary, select, textarea, input, [role=button], [role=link], [role=tab], [role=menuitem], [role=checkbox], [role=switch], [role=option]`);if(r)return r;for(;$t.has(t.tagName)&&t.parentElement&&t.parentElement!==t.ownerDocument.body&&!t.id;)t=t.parentElement;return t}for(var E=[],D=[],tn=Uint8Array,nn=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,O=0,rn=nn.length;O<rn;++O)E[O]=nn[O],D[nn.charCodeAt(O)]=O;D[45]=62,D[95]=63;function an(e){var t=e.length;if(t%4>0)throw Error(`Invalid string. Length must be a multiple of 4`);var n=e.indexOf(`=`);n===-1&&(n=t);var r=n===t?0:4-n%4;return[n,r]}function on(e,t,n){return(t+n)*3/4-n}function sn(e){for(var t,n=an(e),r=n[0],i=n[1],a=new tn(on(e,r,i)),o=0,s=i>0?r-4:r,c=0;c<s;c+=4)t=D[e.charCodeAt(c)]<<18|D[e.charCodeAt(c+1)]<<12|D[e.charCodeAt(c+2)]<<6|D[e.charCodeAt(c+3)],a[o++]=t>>16&255,a[o++]=t>>8&255,a[o++]=t&255;return i===2&&(t=D[e.charCodeAt(c)]<<2|D[e.charCodeAt(c+1)]>>4,a[o++]=t&255),i===1&&(t=D[e.charCodeAt(c)]<<10|D[e.charCodeAt(c+1)]<<4|D[e.charCodeAt(c+2)]>>2,a[o++]=t>>8&255,a[o++]=t&255),a}function cn(e){return E[e>>18&63]+E[e>>12&63]+E[e>>6&63]+E[e&63]}function ln(e,t,n){for(var r,i=[],a=t;a<n;a+=3)r=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(e[a+2]&255),i.push(cn(r));return i.join(``)}function un(e){for(var t,n=e.length,r=n%3,i=[],a=16383,o=0,s=n-r;o<s;o+=a)i.push(ln(e,o,o+a>s?s:o+a));return r===1?(t=e[n-1],i.push(E[t>>2]+E[t<<4&63]+`==`)):r===2&&(t=(e[n-2]<<8)+e[n-1],i.push(E[t>>10]+E[t>>4&63]+E[t<<2&63]+`=`)),i.join(``)}function k(e){if(e===void 0)return{};if(!fn(e))throw Error(`The arguments to a Convex function must be an object. Received: ${e}`);return e}function dn(e){if(e===void 0)throw Error(`Client created with undefined deployment address. If you used an environment variable, check that it's set.`);if(typeof e!=`string`)throw Error(`Invalid deployment address: found ${e}".`);if(!(e.startsWith(`http:`)||e.startsWith(`https:`)))throw Error(`Invalid deployment address: Must start with "https://" or "http://". Found "${e}".`);try{new URL(e)}catch{throw Error(`Invalid deployment address: "${e}" is not a valid URL. If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}if(e.endsWith(`.convex.site`))throw Error(`Invalid deployment address: "${e}" ends with .convex.site, which is used for HTTP Actions. Convex deployment URLs typically end with .convex.cloud? If you believe this URL is correct, use the \`skipConvexDeploymentUrlCheck\` option to bypass this.`)}function fn(e){let t=typeof e==`object`,n=Object.getPrototypeOf(e),r=n===null||n===Object.prototype||n?.constructor?.name===`Object`;return t&&r}let A=BigInt(`-9223372036854775808`),pn=BigInt(`9223372036854775807`),mn=BigInt(`0`),hn=BigInt(`8`),gn=BigInt(`256`),_n=`This commit timestamp is unresolved: its value is assigned when the mutation commits. Read the document after the mutation completes to get its value.`;var vn=class{[Symbol.toPrimitive](e){if(e===`string`)return this.toString();throw Error(_n)}valueOf(){throw Error(_n)}toJSON(){throw Error(_n)}toString(){return`[unresolved commit timestamp]`}};let yn=new vn;function bn(e){return Number.isNaN(e)||!Number.isFinite(e)||Object.is(e,-0)}function xn(e){e<mn&&(e-=A+A);let t=e.toString(16);t.length%2==1&&(t=`0`+t);let n=new Uint8Array(/* @__PURE__ */ new ArrayBuffer(8)),r=0;for(let i of t.match(/.{2}/g).reverse())n.set([parseInt(i,16)],r++),e>>=hn;return un(n)}function Sn(e){let t=sn(e);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);let n=mn,r=mn;for(let e of t)n+=BigInt(e)*gn**r,r++;return n>pn&&(n+=A+A),n}function Cn(e){if(e<A||pn<e)throw Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);let t=/* @__PURE__ */ new ArrayBuffer(8);return new DataView(t).setBigInt64(0,e,!0),un(new Uint8Array(t))}function wn(e){let t=sn(e);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);return new DataView(t.buffer).getBigInt64(0,!0)}let Tn=DataView.prototype.setBigInt64?Cn:xn,En=DataView.prototype.getBigInt64?wn:Sn,Dn=1024;function On(e){if(e.length>Dn)throw Error(`Field name ${e} exceeds maximum field name length ${Dn}.`);if(e.startsWith(`$`))throw Error(`Field name ${e} starts with a '$', which is reserved.`);for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n<32||n>=127)throw Error(`Field name ${e} has invalid character '${e[t]}': Field names can only contain non-control ASCII characters`)}}function j(e){if(e===null||typeof e==`boolean`||typeof e==`number`||typeof e==`string`)return e;if(Array.isArray(e))return e.map(e=>j(e));if(typeof e!=`object`)throw Error(`Unexpected type of ${e}`);let t=Object.entries(e);if(t.length===1){let n=t[0][0];if(n===`$bytes`){if(typeof e.$bytes!=`string`)throw Error(`Malformed $bytes field on ${e}`);return sn(e.$bytes).buffer}if(n===`$integer`){if(typeof e.$integer!=`string`)throw Error(`Malformed $integer field on ${e}`);return En(e.$integer)}if(n===`$float`){if(typeof e.$float!=`string`)throw Error(`Malformed $float field on ${e}`);let t=sn(e.$float);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $float`);let n=new DataView(t.buffer).getFloat64(0,!0);if(!bn(n))throw Error(`Float ${n} should be encoded as a number`);return n}if(n===`$commitTs`){if(e.$commitTs!==null)throw Error(`Malformed $commitTs field on ${e}`);return yn}if(n===`$set`)throw Error(`Received a Set which is no longer supported as a Convex type.`);if(n===`$map`)throw Error(`Received a Map which is no longer supported as a Convex type.`)}let n={};for(let[t,r]of Object.entries(e))On(t),n[t]=j(r);return n}function M(e){let t=JSON.stringify(e,(e,t)=>t===void 0?`undefined`:typeof t==`bigint`?`${t.toString()}n`:t);if(t.length>16384){let e=16370,n=t.codePointAt(e-1);return n!==void 0&&n>65535&&--e,t.substring(0,e)+`[...truncated]`}return t}function kn(e,t,n,r){if(e===void 0){let e=n&&` (present at path ${n} in original object ${M(t)})`;throw Error(`undefined is not a valid Convex value${e}. To learn about Convex's supported types, see https://docs.convex.dev/using/types.`)}if(e===null)return e;if(typeof e==`bigint`){if(e<A||pn<e)throw Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);return{$integer:Tn(e)}}if(typeof e==`number`){if(bn(e)){let t=/* @__PURE__ */ new ArrayBuffer(8);return new DataView(t).setFloat64(0,e,!0),{$float:un(new Uint8Array(t))}}return e}if(typeof e==`boolean`||typeof e==`string`)return e;if(e instanceof ArrayBuffer)return{$bytes:un(new Uint8Array(e))};if(e instanceof vn)return{$commitTs:null};if(Array.isArray(e))return e.map((e,r)=>kn(e,t,n+`[${r}]`,!1));if(e instanceof Set)throw Error(An(n,`Set`,[...e],t));if(e instanceof Map)throw Error(An(n,`Map`,[...e],t));if(!fn(e)){let r=e?.constructor?.name,i=r?`${r} `:``;throw Error(An(n,i,e,t))}let i={},a=Object.entries(e);a.sort(([e,t],[n,r])=>e===n?0:e<n?-1:1);for(let[e,o]of a)o===void 0?r&&(On(e),i[e]=jn(o,t,n+`.${e}`)):(On(e),i[e]=kn(o,t,n+`.${e}`,!1));return i}function An(e,t,n,r){return e?`${t}${M(n)} is not a supported Convex type (present at path ${e} in original object ${M(r)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${t}${M(n)} is not a supported Convex type.`}function jn(e,t,n){if(e===void 0)return{$undefined:null};if(t===void 0)throw Error(`Programming error. Current value is ${M(e)} but original value is undefined`);return kn(e,t,n,!1)}function N(e){return kn(e,e,``,!1)}var Mn=Object.defineProperty,Nn=(e,t,n)=>t in e?Mn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Pn=(e,t,n)=>Nn(e,typeof t==`symbol`?t:t+``,n),Fn,In;let Ln=Symbol.for(`ConvexError`);var Rn=class extends (In=Error,Fn=Ln,In){constructor(e){super(typeof e==`string`?e:M(e)),Pn(this,`name`,`ConvexError`),Pn(this,`data`),Pn(this,Fn,!0),this.data=e}};let zn=`1.46.0`,Bn=Symbol.for(`functionName`),Vn=Symbol.for(`toReferencePath`);function Hn(e){return e[Vn]??null}function Un(e){return e.startsWith(`function://`)}function Wn(e){let t;if(typeof e==`string`)t=Un(e)?{functionHandle:e}:{name:e};else if(e[Bn])t={name:e[Bn]};else{let n=Hn(e);if(!n)throw Error(`${e} is not a functionReference`);t={reference:n}}return t}function P(e){let t=Wn(e);if(t.name===void 0)throw t.functionHandle===void 0?t.reference===void 0?Error(`Expected function reference like "api.file.func" or "internal.file.func", but received ${JSON.stringify(t)}`):Error(`Expected function reference in the current component like "api.file.func" or "internal.file.func", but received reference ${t.reference}`):Error(`Expected function reference like "api.file.func" or "internal.file.func", but received function handle ${t.functionHandle}`);if(typeof e==`string`)return e;let n=e[Bn];if(!n)throw Error(`${e} is not a functionReference`);return n}function Gn(e=[]){return new Proxy({},{get(t,n){if(typeof n==`string`)return Gn([...e,n]);if(n===Bn){if(e.length<2){let t=[`api`,...e].join(`.`);throw Error(`API path is expected to be of the form \`api.moduleName.functionName\`. Found: \`${t}\``)}let t=e.slice(0,-1).join(`/`),n=e[e.length-1];return n==="default"?t:t+`:`+n}if(n===Symbol.toStringTag)return`FunctionReference`}})}let Kn=Gn();function qn(e,t){return new Proxy({},{get(n,r){if(typeof r==`string`)return qn(e,[...t,r]);if(r===Vn){if(t.length<1){let n=[e,...t].join(`.`);throw Error(`API path is expected to be of the form \`${e}.childComponent.functionName\`. Found: \`${n}\``)}return`_reference/childComponent/`+t.join(`/`)}}})}let Jn=()=>qn(`components`,[]),F=Kn;Jn();var Yn=Object.defineProperty,Xn=(e,t,n)=>t in e?Yn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Zn=(e,t,n)=>Xn(e,typeof t==`symbol`?t:t+``,n);function Qn(e){switch(e){case`query`:return`Q`;case`mutation`:return`M`;case`action`:return`A`;case`any`:return`?`}}var $n=class{constructor(e){Zn(this,`_onLogLineFuncs`),Zn(this,`_verbose`),this._onLogLineFuncs={},this._verbose=e.verbose}addLogLineListener(e){let t=Math.random().toString(36).substring(2,15);for(let e=0;e<10&&this._onLogLineFuncs[t]!==void 0;e++)t=Math.random().toString(36).substring(2,15);return this._onLogLineFuncs[t]=e,()=>{delete this._onLogLineFuncs[t]}}logVerbose(...e){if(this._verbose)for(let t of Object.values(this._onLogLineFuncs))t(`debug`,`${(/* @__PURE__ */ new Date()).toISOString()}`,...e)}log(...e){for(let t of Object.values(this._onLogLineFuncs))t(`info`,...e)}warn(...e){for(let t of Object.values(this._onLogLineFuncs))t(`warn`,...e)}error(...e){for(let t of Object.values(this._onLogLineFuncs))t(`error`,...e)}};function er(e){let t=new $n(e);return t.addLogLineListener((e,...t)=>{switch(e){case`debug`:console.debug(...t);break;case`info`:console.log(...t);break;case`warn`:console.warn(...t);break;case`error`:console.error(...t);break;default:console.log(...t)}}),t}function tr(e){return new $n(e)}function nr(e,t,n,r,i){let a=Qn(n);if(typeof i==`object`&&(i=`ConvexError ${JSON.stringify(i.errorData,null,2)}`),t===`info`){let t=i.match(/^\[.*?\] /);if(t===null){e.error(`[CONVEX ${a}(${r})] Could not parse console.log`);return}let n=i.slice(1,t[0].length-2),o=i.slice(t[0].length);e.log(`%c[CONVEX ${a}(${r})] [${n}]`,`color:rgb(0, 145, 255)`,o)}else e.error(`[CONVEX ${a}(${r})] ${i}`)}function rr(e,t){let n=`[CONVEX FATAL ERROR] ${t}`;return e.error(n),Error(n)}function I(e,t,n){return`[CONVEX ${Qn(e)}(${t})] ${n.errorMessage}
|
|
9
|
+
Called by client`}function ir(e,t){return t.data=e.errorData,t}function L(e){let t=e.split(`:`),n,r;return t.length===1?(n=t[0],r=`default`):(n=t.slice(0,t.length-1).join(`:`),r=t[t.length-1]),n.endsWith(`.js`)&&(n=n.slice(0,-3)),`${n}:${r}`}function R(e,t){return JSON.stringify({udfPath:L(e),args:N(t)})}function ar(e,t,n){let{initialNumItems:r,id:i}=n;return JSON.stringify({type:`paginated`,udfPath:L(e),args:N(t),options:N({initialNumItems:r,id:i})})}function or(e){return JSON.parse(e).type===`paginated`}var sr=Object.defineProperty,cr=(e,t,n)=>t in e?sr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,z=(e,t,n)=>cr(e,typeof t==`symbol`?t:t+``,n),lr=class{constructor(){z(this,`nextQueryId`),z(this,`querySetVersion`),z(this,`querySet`),z(this,`queryIdToToken`),z(this,`identityVersion`),z(this,`auth`),z(this,`outstandingQueriesOlderThanRestart`),z(this,`outstandingAuthOlderThanRestart`),z(this,`paused`),z(this,`pendingQuerySetModifications`),this.nextQueryId=0,this.querySetVersion=0,this.identityVersion=0,this.querySet=/* @__PURE__ */ new Map,this.queryIdToToken=/* @__PURE__ */ new Map,this.outstandingQueriesOlderThanRestart=/* @__PURE__ */ new Set,this.outstandingAuthOlderThanRestart=!1,this.paused=!1,this.pendingQuerySetModifications=/* @__PURE__ */ new Map}hasSyncedPastLastReconnect(){return this.outstandingQueriesOlderThanRestart.size===0&&!this.outstandingAuthOlderThanRestart}markAuthCompletion(){this.outstandingAuthOlderThanRestart=!1}subscribe(e,t,n,r){let i=L(e),a=R(i,t),o=this.querySet.get(a);if(o!==void 0)return o.numSubscribers+=1,{queryToken:a,modification:null,unsubscribe:()=>this.removeSubscriber(a)};{let e=this.nextQueryId++,o={id:e,canonicalizedUdfPath:i,args:t,numSubscribers:1,journal:n,componentPath:r};this.querySet.set(a,o),this.queryIdToToken.set(e,a);let s=this.querySetVersion,c=this.querySetVersion+1,l={type:`Add`,queryId:e,udfPath:i,args:[N(t)],journal:n,componentPath:r};return this.paused?this.pendingQuerySetModifications.set(e,l):this.querySetVersion=c,{queryToken:a,modification:{type:`ModifyQuerySet`,baseVersion:s,newVersion:c,modifications:[l]},unsubscribe:()=>this.removeSubscriber(a)}}}transition(e){for(let t of e.modifications)switch(t.type){case`QueryUpdated`:case`QueryFailed`:{this.outstandingQueriesOlderThanRestart.delete(t.queryId);let e=t.journal;if(e!==void 0){let n=this.queryIdToToken.get(t.queryId);n!==void 0&&(this.querySet.get(n).journal=e)}break}case`QueryRemoved`:this.outstandingQueriesOlderThanRestart.delete(t.queryId);break;default:throw Error(`Invalid modification ${t.type}`)}}queryId(e,t){let n=R(L(e),t),r=this.querySet.get(n);return r===void 0?null:r.id}isCurrentOrNewerAuthVersion(e){return e>=this.identityVersion}getAuth(){return this.auth}setAuth(e){this.auth={tokenType:`User`,value:e};let t=this.identityVersion;return this.paused||(this.identityVersion=t+1),{type:`Authenticate`,baseVersion:t,...this.auth}}setAdminAuth(e,t){let n={tokenType:`Admin`,value:e,impersonating:t};this.auth=n;let r=this.identityVersion;return this.paused||(this.identityVersion=r+1),{type:`Authenticate`,baseVersion:r,...n}}clearAuth(){this.auth=void 0,this.markAuthCompletion();let e=this.identityVersion;return this.paused||(this.identityVersion=e+1),{type:`Authenticate`,tokenType:`None`,baseVersion:e}}hasAuth(){return!!this.auth}isNewAuth(e){return this.auth?.value!==e}queryPath(e){let t=this.queryIdToToken.get(e);return t?this.querySet.get(t).canonicalizedUdfPath:null}queryArgs(e){let t=this.queryIdToToken.get(e);return t?this.querySet.get(t).args:null}queryToken(e){return this.queryIdToToken.get(e)??null}queryJournal(e){return this.querySet.get(e)?.journal}restart(){this.unpause(),this.outstandingQueriesOlderThanRestart.clear();let e=[];for(let t of this.querySet.values()){let n={type:`Add`,queryId:t.id,udfPath:t.canonicalizedUdfPath,args:[N(t.args)],journal:t.journal,componentPath:t.componentPath};e.push(n),this.outstandingQueriesOlderThanRestart.add(t.id)}this.querySetVersion=1;let t={type:`ModifyQuerySet`,baseVersion:0,newVersion:1,modifications:e};if(!this.auth)return this.identityVersion=0,[t,void 0];this.outstandingAuthOlderThanRestart=!0;let n={type:`Authenticate`,baseVersion:0,...this.auth};return this.identityVersion=1,[t,n]}pause(){this.paused=!0}resume(){let e=this.pendingQuerySetModifications.size>0?{type:`ModifyQuerySet`,baseVersion:this.querySetVersion,newVersion:++this.querySetVersion,modifications:Array.from(this.pendingQuerySetModifications.values())}:void 0,t=this.auth===void 0?void 0:{type:`Authenticate`,baseVersion:this.identityVersion++,...this.auth};return this.unpause(),[e,t]}unpause(){this.paused=!1,this.pendingQuerySetModifications.clear()}removeSubscriber(e){let t=this.querySet.get(e);if(t.numSubscribers>1)return--t.numSubscribers,null;{this.querySet.delete(e),this.queryIdToToken.delete(t.id),this.outstandingQueriesOlderThanRestart.delete(t.id);let n=this.querySetVersion,r=this.querySetVersion+1,i={type:`Remove`,queryId:t.id};return this.paused?this.pendingQuerySetModifications.has(t.id)?this.pendingQuerySetModifications.delete(t.id):this.pendingQuerySetModifications.set(t.id,i):this.querySetVersion=r,{type:`ModifyQuerySet`,baseVersion:n,newVersion:r,modifications:[i]}}}},ur=Object.defineProperty,dr=(e,t,n)=>t in e?ur(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,fr=(e,t,n)=>dr(e,typeof t==`symbol`?t:t+``,n),pr=class{constructor(e,t){this.logger=e,this.markConnectionStateDirty=t,fr(this,`inflightRequests`),fr(this,`requestsOlderThanRestart`),fr(this,`inflightMutationsCount`,0),fr(this,`inflightActionsCount`,0),this.inflightRequests=/* @__PURE__ */ new Map,this.requestsOlderThanRestart=/* @__PURE__ */ new Set}request(e,t){let n=new Promise(n=>{let r=t?`Requested`:`NotSent`;this.inflightRequests.set(e.requestId,{message:e,status:{status:r,requestedAt:/* @__PURE__ */ new Date,onResult:n}}),e.type===`Mutation`?this.inflightMutationsCount++:e.type===`Action`&&this.inflightActionsCount++});return this.markConnectionStateDirty(),n}onResponse(e){let t=this.inflightRequests.get(e.requestId);if(t===void 0||t.status.status===`Completed`)return null;let n=t.message.type===`Mutation`?`mutation`:`action`,r=t.message.udfPath;for(let t of e.logLines)nr(this.logger,`info`,n,r,t);let i=t.status,a,o;if(e.success)a={success:!0,logLines:e.logLines,value:j(e.result)},o=()=>i.onResult(a);else{let t=e.result,{errorData:s}=e;nr(this.logger,`error`,n,r,t),a={success:!1,errorMessage:t,errorData:s===void 0?void 0:j(s),logLines:e.logLines},o=()=>i.onResult(a)}return e.type===`ActionResponse`||!e.success?(o(),this.inflightRequests.delete(e.requestId),this.requestsOlderThanRestart.delete(e.requestId),t.message.type===`Action`?this.inflightActionsCount--:t.message.type===`Mutation`&&this.inflightMutationsCount--,this.markConnectionStateDirty(),{requestId:e.requestId,result:a}):(t.status={status:`Completed`,result:a,ts:e.ts,onResolve:o},null)}removeCompleted(e){let t=/* @__PURE__ */ new Map;for(let[n,r]of this.inflightRequests.entries()){let i=r.status;i.status===`Completed`&&i.ts.lessThanOrEqual(e)&&(i.onResolve(),t.set(n,i.result),r.message.type===`Mutation`?this.inflightMutationsCount--:r.message.type===`Action`&&this.inflightActionsCount--,this.inflightRequests.delete(n),this.requestsOlderThanRestart.delete(n))}return t.size>0&&this.markConnectionStateDirty(),t}restart(){this.requestsOlderThanRestart=new Set(this.inflightRequests.keys());let e=[];for(let[t,n]of this.inflightRequests){if(n.status.status===`NotSent`){n.status.status=`Requested`,e.push(n.message);continue}if(n.message.type===`Mutation`)e.push(n.message);else if(n.message.type===`Action`){if(this.inflightRequests.delete(t),this.requestsOlderThanRestart.delete(t),this.inflightActionsCount--,n.status.status===`Completed`)throw Error(`Action should never be in 'Completed' state`);n.status.onResult({success:!1,errorMessage:`Connection lost while action was in flight`,logLines:[]})}}return this.markConnectionStateDirty(),e}resume(){let e=[];for(let[,t]of this.inflightRequests)if(t.status.status===`NotSent`){t.status.status=`Requested`,e.push(t.message);continue}return e}hasIncompleteRequests(){for(let e of this.inflightRequests.values())if(e.status.status===`Requested`)return!0;return!1}hasInflightRequests(){return this.inflightRequests.size>0}hasSyncedPastLastReconnect(){return this.requestsOlderThanRestart.size===0}timeOfOldestInflightRequest(){if(this.inflightRequests.size===0)return null;let e=Date.now();for(let t of this.inflightRequests.values())t.status.status!==`Completed`&&t.status.requestedAt.getTime()<e&&(e=t.status.requestedAt.getTime());return new Date(e)}inflightMutations(){return this.inflightMutationsCount}inflightActions(){return this.inflightActionsCount}},mr=Object.defineProperty,hr=(e,t,n)=>t in e?mr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,gr=(e,t,n)=>hr(e,typeof t==`symbol`?t:t+``,n),_r=class e{constructor(e){gr(this,`queryResults`),gr(this,`modifiedQueries`),this.queryResults=e,this.modifiedQueries=[]}getQuery(t,...n){let r=k(n[0]),i=P(t),a=this.queryResults.get(R(i,r));if(a!==void 0)return e.queryValue(a.result)}getAllQueries(t){let n=[],r=P(t);for(let t of this.queryResults.values())t.udfPath===L(r)&&n.push({args:t.args,value:e.queryValue(t.result)});return n}setQuery(e,t,n){let r=k(t),i=P(e),a=R(i,r),o;o=n===void 0?void 0:{success:!0,value:n,logLines:[]};let s={udfPath:i,args:r,result:o};this.queryResults.set(a,s),this.modifiedQueries.push(a)}static queryValue(e){if(e!==void 0&&e.success)return e.value}},vr=class{constructor(){gr(this,`queryResults`),gr(this,`optimisticUpdates`),this.queryResults=/* @__PURE__ */ new Map,this.optimisticUpdates=[]}ingestQueryResultsFromServer(e,t){this.optimisticUpdates=this.optimisticUpdates.filter(e=>!t.has(e.mutationId));let n=this.queryResults;this.queryResults=new Map(e);let r=new _r(this.queryResults);for(let e of this.optimisticUpdates)e.update(r);let i=[];for(let[e,t]of this.queryResults){let r=n.get(e);(r===void 0||r.result!==t.result)&&i.push(e)}return i}applyOptimisticUpdate(e,t){this.optimisticUpdates.push({update:e,mutationId:t});let n=new _r(this.queryResults);return e(n),n.modifiedQueries}rawQueryResult(e){let t=this.queryResults.get(e);if(t!==void 0)return t.result}queryResult(e){let t=this.queryResults.get(e);if(t===void 0)return;let n=t.result;if(n!==void 0){if(n.success)return n.value;throw n.errorData===void 0?Error(I(`query`,t.udfPath,n)):ir(n,new Rn(I(`query`,t.udfPath,n)))}}hasQueryResult(e){return this.queryResults.get(e)!==void 0}queryLogs(e){return this.queryResults.get(e)?.result?.logLines}},yr=Object.defineProperty,br=(e,t,n)=>t in e?yr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,xr=(e,t,n)=>br(e,typeof t==`symbol`?t:t+``,n),Sr=class e{constructor(e,t){xr(this,`low`),xr(this,`high`),xr(this,`__isUnsignedLong__`),this.low=e|0,this.high=t|0,this.__isUnsignedLong__=!0}static isLong(e){return(e&&e.__isUnsignedLong__)===!0}static fromBytesLE(t){return new e(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24)}toBytesLE(){let e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]}static fromNumber(t){return isNaN(t)||t<0?Cr:t>=Er?Dr:new e(t%Tr|0,t/Tr|0)}toString(){return(BigInt(this.high)*BigInt(Tr)+BigInt(this.low)).toString()}equals(t){return e.isLong(t)||(t=e.fromValue(t)),this.high>>>31==1&&t.high>>>31==1?!1:this.high===t.high&&this.low===t.low}notEquals(e){return!this.equals(e)}comp(t){return e.isLong(t)||(t=e.fromValue(t)),this.equals(t)?0:t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1}lessThanOrEqual(e){return this.comp(e)<=0}static fromValue(t){return typeof t==`number`?e.fromNumber(t):new e(t.low,t.high)}};let Cr=new Sr(0,0),wr=65536,Tr=wr*wr,Er=Tr*Tr,Dr=new Sr(-1,-1);var Or=Object.defineProperty,kr=(e,t,n)=>t in e?Or(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Ar=(e,t,n)=>kr(e,typeof t==`symbol`?t:t+``,n),jr=class{constructor(e,t){Ar(this,`version`),Ar(this,`remoteQuerySet`),Ar(this,`queryPath`),Ar(this,`logger`),this.version={querySet:0,ts:Sr.fromNumber(0),identity:0},this.remoteQuerySet=/* @__PURE__ */ new Map,this.queryPath=e,this.logger=t}transition(e){let t=e.startVersion;if(this.version.querySet!==t.querySet||this.version.ts.notEquals(t.ts)||this.version.identity!==t.identity)throw Error(`Invalid start version: ${t.ts.toString()}:${t.querySet}:${t.identity}, transitioning from ${this.version.ts.toString()}:${this.version.querySet}:${this.version.identity}`);for(let t of e.modifications)switch(t.type){case`QueryUpdated`:{let e=this.queryPath(t.queryId);if(e)for(let n of t.logLines)nr(this.logger,`info`,`query`,e,n);let n=j(t.value??null);this.remoteQuerySet.set(t.queryId,{success:!0,value:n,logLines:t.logLines});break}case`QueryFailed`:{let e=this.queryPath(t.queryId);if(e)for(let n of t.logLines)nr(this.logger,`info`,`query`,e,n);let{errorData:n}=t;this.remoteQuerySet.set(t.queryId,{success:!1,errorMessage:t.errorMessage,errorData:n===void 0?void 0:j(n),logLines:t.logLines});break}case`QueryRemoved`:this.remoteQuerySet.delete(t.queryId);break;default:throw Error(`Invalid modification ${t.type}`)}this.version=e.endVersion}remoteQueryResults(){return this.remoteQuerySet}timestamp(){return this.version.ts}};function Mr(e){let t=sn(e);return Sr.fromBytesLE(Array.from(t))}function Nr(e){return un(new Uint8Array(e.toBytesLE()))}function Pr(e){switch(e.type){case`FatalError`:case`AuthError`:case`ActionResponse`:case`TransitionChunk`:case`Ping`:return{...e};case`MutationResponse`:return e.success?{...e,ts:Mr(e.ts)}:{...e};case`Transition`:return{...e,startVersion:{...e.startVersion,ts:Mr(e.startVersion.ts)},endVersion:{...e.endVersion,ts:Mr(e.endVersion.ts)}}}}function Fr(e){switch(e.type){case`Authenticate`:case`ModifyQuerySet`:case`Mutation`:case`Action`:case`Event`:return{...e};case`Connect`:return e.maxObservedTimestamp===void 0?{...e,maxObservedTimestamp:void 0}:{...e,maxObservedTimestamp:Nr(e.maxObservedTimestamp)}}}var Ir=Object.defineProperty,Lr=(e,t,n)=>t in e?Ir(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,B=(e,t,n)=>Lr(e,typeof t==`symbol`?t:t+``,n);let Rr;function V(){return Rr===void 0&&(Rr=Date.now()),typeof performance>`u`||!performance.now?Date.now():Math.round(Rr+performance.now())}function zr(){return`t=${Math.round((V()-Rr)/100)/10}s`}let Br={InternalServerError:{timeout:1e3},SubscriptionsWorkerFullError:{timeout:3e3},TooManyConcurrentRequests:{timeout:3e3},CommitterFullError:{timeout:3e3},AwsTooManyRequestsException:{timeout:3e3},ExecuteFullError:{timeout:3e3},SystemTimeoutError:{timeout:3e3},ExpiredInQueue:{timeout:3e3},VectorIndexesUnavailable:{timeout:1e3},SearchIndexesUnavailable:{timeout:1e3},TableSummariesUnavailable:{timeout:1e3},VectorIndexTooLarge:{timeout:3e3},SearchIndexTooLarge:{timeout:3e3},TooManyWritesInTimePeriod:{timeout:3e3}};function Vr(e){if(e===void 0)return`Unknown`;for(let t of Object.keys(Br))if(e.startsWith(t))return t;return`Unknown`}var Hr=class{constructor(e,t,n,r,i,a){this.markConnectionStateDirty=i,this.debug=a,B(this,`socket`),B(this,`connectionCount`),B(this,`_hasEverConnected`,!1),B(this,`lastCloseReason`),B(this,`transitionChunkBuffer`,null),B(this,`defaultInitialBackoff`),B(this,`maxBackoff`),B(this,`retries`),B(this,`serverInactivityThreshold`),B(this,`reconnectDueToServerInactivityTimeout`),B(this,`scheduledReconnect`,null),B(this,`networkOnlineHandler`,null),B(this,`pendingNetworkRecoveryInfo`,null),B(this,`uri`),B(this,`onOpen`),B(this,`onResume`),B(this,`onMessage`),B(this,`webSocketConstructor`),B(this,`logger`),B(this,`onServerDisconnectError`),this.webSocketConstructor=n,this.socket={state:`disconnected`},this.connectionCount=0,this.lastCloseReason=`InitialConnect`,this.defaultInitialBackoff=1e3,this.maxBackoff=16e3,this.retries=0,this.serverInactivityThreshold=6e4,this.reconnectDueToServerInactivityTimeout=null,this.uri=e,this.onOpen=t.onOpen,this.onResume=t.onResume,this.onMessage=t.onMessage,this.onServerDisconnectError=t.onServerDisconnectError,this.logger=r,this.setupNetworkListener(),this.connect()}setSocketState(e){this.socket=e,this._logVerbose(`socket state changed: ${this.socket.state}, paused: ${`paused`in this.socket?this.socket.paused:void 0}`),this.markConnectionStateDirty()}setupNetworkListener(){typeof window<`u`&&typeof window.addEventListener==`function`&&this.networkOnlineHandler===null&&(this.networkOnlineHandler=()=>{this._logVerbose(`network online event detected`),this.tryReconnectImmediately()},window.addEventListener(`online`,this.networkOnlineHandler),this._logVerbose(`network online event listener registered`))}cleanupNetworkListener(){this.networkOnlineHandler&&typeof window<`u`&&typeof window.removeEventListener==`function`&&(window.removeEventListener(`online`,this.networkOnlineHandler),this.networkOnlineHandler=null,this._logVerbose(`network online event listener removed`))}assembleTransition(e){if(e.partNumber<0||e.partNumber>=e.totalParts||e.totalParts===0||this.transitionChunkBuffer&&(this.transitionChunkBuffer.totalParts!==e.totalParts||this.transitionChunkBuffer.transitionId!==e.transitionId))throw this.transitionChunkBuffer=null,Error(`Invalid TransitionChunk`);if(this.transitionChunkBuffer===null&&(this.transitionChunkBuffer={chunks:[],totalParts:e.totalParts,transitionId:e.transitionId}),e.partNumber!==this.transitionChunkBuffer.chunks.length){let t=this.transitionChunkBuffer.chunks.length;throw this.transitionChunkBuffer=null,Error(`TransitionChunk received out of order: expected part ${t}, got ${e.partNumber}`)}if(this.transitionChunkBuffer.chunks.push(e.chunk),this.transitionChunkBuffer.chunks.length===e.totalParts){let e=this.transitionChunkBuffer.chunks.join(``);this.transitionChunkBuffer=null;let t=Pr(JSON.parse(e));if(t.type!==`Transition`)throw Error(`Expected Transition, got ${t.type} after assembling chunks`);return t}return null}connect(){if(this.socket.state===`terminated`)return;if(this.socket.state!==`disconnected`&&this.socket.state!==`stopped`)throw Error(`Didn't start connection from disconnected state: `+this.socket.state);let e=new this.webSocketConstructor(this.uri);this._logVerbose(`constructed WebSocket`),this.setSocketState({state:`connecting`,ws:e,paused:`no`}),this.resetServerInactivityTimeout(),e.onopen=()=>{if(this.logger.logVerbose(`begin ws.onopen`),this.socket.state!==`connecting`)throw Error(`onopen called with socket not in connecting state`);if(this.setSocketState({state:`ready`,ws:e,paused:this.socket.paused===`yes`?`uninitialized`:`no`}),this.resetServerInactivityTimeout(),this.socket.paused===`no`&&(this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:V()})),this.lastCloseReason!==`InitialConnect`&&(this.lastCloseReason?this.logger.log(`WebSocket reconnected at`,zr(),`after disconnect due to`,this.lastCloseReason):this.logger.log(`WebSocket reconnected at`,zr())),this.connectionCount+=1,this.lastCloseReason=null,this.pendingNetworkRecoveryInfo!==null){let{timeSavedMs:e}=this.pendingNetworkRecoveryInfo;this.pendingNetworkRecoveryInfo=null,this.sendMessage({type:`Event`,eventType:`NetworkRecoveryReconnect`,event:{timeSavedMs:e}}),this.logger.log(`Network recovery reconnect saved ~${Math.round(e/1e3)}s of waiting`)}},e.onerror=e=>{this.transitionChunkBuffer=null;let t=e.message;t&&this.logger.log(`WebSocket error message: ${t}`)},e.onmessage=e=>{this.resetServerInactivityTimeout();let t=e.data.length,n=Pr(JSON.parse(e.data));if(this._logVerbose(`received ws message with type ${n.type}`),n.type!==`Ping`){if(n.type===`TransitionChunk`){let e=this.assembleTransition(n);if(!e)return;n=e,this._logVerbose(`assembled full ws message of type ${n.type}`)}this.transitionChunkBuffer!==null&&(this.transitionChunkBuffer=null,this.logger.log(`Received unexpected ${n.type} while buffering TransitionChunks`)),n.type===`Transition`&&this.reportLargeTransition({messageLength:t,transition:n}),this.onMessage(n).hasSyncedPastLastReconnect&&(this.retries=0,this.markConnectionStateDirty())}},e.onclose=e=>{if(this._logVerbose(`begin ws.onclose`),this.transitionChunkBuffer=null,this.lastCloseReason===null&&(this.lastCloseReason=e.reason||`closed with code ${e.code}`),e.code!==1e3&&e.code!==1001&&e.code!==1005&&e.code!==4040){let t=`WebSocket closed with code ${e.code}`;e.reason&&(t+=`: ${e.reason}`),this.logger.log(t),this.onServerDisconnectError&&e.reason&&this.onServerDisconnectError(t)}let t=Vr(e.reason);this.scheduleReconnect(t)}}socketState(){return this.socket.state}sendMessage(e){let t={type:e.type,...e.type===`Authenticate`&&e.tokenType===`User`?{value:`...${e.value.slice(-7)}`}:{}};if(this.socket.state===`ready`&&this.socket.paused===`no`){let n=Fr(e),r=JSON.stringify(n),i=!1;try{this.socket.ws.send(r),i=!0}catch(e){this.logger.log(`Failed to send message on WebSocket, reconnecting: ${e}`),this.closeAndReconnect(`FailedToSendMessage`)}return this._logVerbose(`${i?`sent`:`failed to send`} message with type ${e.type}: ${JSON.stringify(t)}`),!0}return this._logVerbose(`message not sent (socket state: ${this.socket.state}, paused: ${`paused`in this.socket?this.socket.paused:void 0}): ${JSON.stringify(t)}`),!1}resetServerInactivityTimeout(){this.socket.state!==`terminated`&&(this.reconnectDueToServerInactivityTimeout!==null&&(clearTimeout(this.reconnectDueToServerInactivityTimeout),this.reconnectDueToServerInactivityTimeout=null),this.reconnectDueToServerInactivityTimeout=setTimeout(()=>{this.closeAndReconnect(`InactiveServer`)},this.serverInactivityThreshold))}scheduleReconnect(e){this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.socket={state:`disconnected`};let t=this.nextBackoff(e);this.markConnectionStateDirty(),this.logger.log(`Attempting reconnect in ${Math.round(t)}ms`);let n=V(),r=setTimeout(()=>{this.scheduledReconnect?.timeout===r&&(this.scheduledReconnect=null,this.connect())},t);this.scheduledReconnect={timeout:r,scheduledAt:n,backoffMs:t}}closeAndReconnect(e){switch(this._logVerbose(`begin closeAndReconnect with reason ${e}`),this.socket.state){case`disconnected`:case`terminated`:case`stopped`:return;case`connecting`:case`ready`:this.lastCloseReason=e,this.close(),this.scheduleReconnect(`client`);return;default:this.socket}}close(){switch(this.transitionChunkBuffer=null,this.socket.state){case`disconnected`:case`terminated`:case`stopped`:return Promise.resolve();case`connecting`:{let e=this.socket.ws;return e.onmessage=e=>{this._logVerbose(`Ignoring message received after close`)},new Promise(t=>{e.onclose=()=>{this._logVerbose(`Closed after connecting`),t()},e.onopen=()=>{this._logVerbose(`Opened after connecting`),e.close()}})}case`ready`:{this._logVerbose(`ws.close called`);let e=this.socket.ws;e.onmessage=e=>{this._logVerbose(`Ignoring message received after close`)};let t=new Promise(t=>{e.onclose=()=>{t()}});return e.close(),t}default:return this.socket,Promise.resolve()}}terminate(){switch(this.reconnectDueToServerInactivityTimeout&&clearTimeout(this.reconnectDueToServerInactivityTimeout),this.scheduledReconnect&&(clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null),this.cleanupNetworkListener(),this.socket.state){case`terminated`:case`stopped`:case`disconnected`:case`connecting`:case`ready`:{let e=this.close();return this.setSocketState({state:`terminated`}),e}default:throw this.socket,Error(`Invalid websocket state: ${this.socket.state}`)}}stop(){switch(this.socket.state){case`terminated`:return Promise.resolve();case`connecting`:case`stopped`:case`disconnected`:case`ready`:{this.cleanupNetworkListener();let e=this.close();return this.socket={state:`stopped`},e}default:return this.socket,Promise.resolve()}}tryRestart(){switch(this.socket.state){case`stopped`:break;case`terminated`:case`connecting`:case`ready`:case`disconnected`:this.logger.logVerbose(`Restart called without stopping first`);return;default:this.socket}this.setupNetworkListener(),this.connect()}pause(){switch(this.socket.state){case`disconnected`:case`stopped`:case`terminated`:return;case`connecting`:case`ready`:this.socket={...this.socket,paused:`yes`};return;default:this.socket;return}}tryReconnectImmediately(){if(this._logVerbose(`tryReconnectImmediately called`),this.socket.state!==`disconnected`){this._logVerbose(`tryReconnectImmediately called but socket state is ${this.socket.state}, no action taken`);return}let e=null;if(this.scheduledReconnect){let t=V()-this.scheduledReconnect.scheduledAt;e=Math.max(0,this.scheduledReconnect.backoffMs-t),this._logVerbose(`would have waited ${Math.round(e)}ms more (backoff was ${Math.round(this.scheduledReconnect.backoffMs)}ms, elapsed ${Math.round(t)}ms)`),clearTimeout(this.scheduledReconnect.timeout),this.scheduledReconnect=null,this._logVerbose(`canceled scheduled reconnect`)}this.logger.log(`Network recovery detected, reconnecting immediately`),this.pendingNetworkRecoveryInfo=e===null?null:{timeSavedMs:e},this.connect()}resume(){switch(this.socket.state){case`connecting`:this.socket={...this.socket,paused:`no`};return;case`ready`:this.socket.paused===`uninitialized`?(this.socket={...this.socket,paused:`no`},this._hasEverConnected=!0,this.onOpen({connectionCount:this.connectionCount,lastCloseReason:this.lastCloseReason,clientTs:V()})):this.socket.paused===`yes`&&(this.socket={...this.socket,paused:`no`},this.onResume());return;case`terminated`:case`stopped`:case`disconnected`:return;default:this.socket}this.connect()}connectionState(){return{isConnected:this.socket.state===`ready`,hasEverConnected:this._hasEverConnected,connectionCount:this.connectionCount,connectionRetries:this.retries}}_logVerbose(e){this.logger.logVerbose(e)}nextBackoff(e){let t=(e===`client`?100:e===`Unknown`?this.defaultInitialBackoff:Br[e].timeout)*2**this.retries;this.retries+=1;let n=Math.min(t,this.maxBackoff);return n+n*(Math.random()-.5)}reportLargeTransition({transition:e,messageLength:t}){if(e.clientClockSkew===void 0||e.serverTs===void 0)return;let n=V()-e.clientClockSkew-e.serverTs/1e6,r=`${Math.round(n)}ms`,i=`${Math.round(t/1e4)/100}MB`,a=t/(n/1e3),o=`${Math.round(a/1e4)/100}MB per second`;this._logVerbose(`received ${i} transition in ${r} at ${o}`),t>2e7?this.logger.log(`received query results totaling more that 20MB (${i}) which will take a long time to download on slower connections`):n>2e4&&this.logger.log(`received query results totaling ${i} which took more than 20s to arrive (${r})`),this.debug&&this.sendMessage({type:`Event`,eventType:`ClientReceivedTransition`,event:{transitionTransitTime:n,messageLength:t}})}};function Ur(){return Wr()}function Wr(){return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}var Gr=class extends Error{};Gr.prototype.name=`InvalidTokenError`;function Kr(e){return decodeURIComponent(atob(e).replace(/(.)/g,(e,t)=>{let n=t.charCodeAt(0).toString(16).toUpperCase();return n.length<2&&(n=`0`+n),`%`+n}))}function qr(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);switch(t.length%4){case 0:break;case 2:t+=`==`;break;case 3:t+=`=`;break;default:throw Error(`base64 string is not of the correct length`)}try{return Kr(t)}catch{return atob(t)}}function Jr(e,t){if(typeof e!=`string`)throw new Gr(`Invalid token specified: must be a string`);t||(t={});let n=t.header===!0?0:1,r=e.split(`.`)[n];if(typeof r!=`string`)throw new Gr(`Invalid token specified: missing part #${n+1}`);let i;try{i=qr(r)}catch(e){throw new Gr(`Invalid token specified: invalid base64 for part #${n+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new Gr(`Invalid token specified: invalid json for part #${n+1} (${e.message})`)}}var Yr=Object.defineProperty,Xr=(e,t,n)=>t in e?Yr(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,H=(e,t,n)=>Xr(e,typeof t==`symbol`?t:t+``,n),Zr=class{constructor(e,t,n){H(this,`authState`,{state:`noAuth`}),H(this,`configVersion`,0),H(this,`syncState`),H(this,`authenticate`),H(this,`stopSocket`),H(this,`tryRestartSocket`),H(this,`pauseSocket`),H(this,`resumeSocket`),H(this,`clearAuth`),H(this,`logger`),H(this,`refreshTokenLeewaySeconds`),H(this,`initialAuthTokenReuse`),H(this,`lastRefreshChange`),H(this,`tokenConfirmationAttempts`,0),this.syncState=e,this.authenticate=t.authenticate,this.stopSocket=t.stopSocket,this.tryRestartSocket=t.tryRestartSocket,this.pauseSocket=t.pauseSocket,this.resumeSocket=t.resumeSocket,this.clearAuth=t.clearAuth,this.logger=n.logger,this.refreshTokenLeewaySeconds=n.refreshTokenLeewaySeconds,this.initialAuthTokenReuse=n.initialAuthTokenReuse,this.lastRefreshChange=!1}notifyRefreshChange(e){this.authState.state!==`noAuth`&&this.authState.state!==`initialRefetch`&&this.authState.config.onRefreshChange&&this.lastRefreshChange!==e&&(this.lastRefreshChange=e,this.authState.config.onRefreshChange(e))}async setConfig(e,t,n){this.resetAuthState(),this._logVerbose(`pausing WS for auth token fetch`),this.pauseSocket();let r=await this.fetchTokenAndGuardAgainstRace(e,{forceRefreshToken:!1});if(r.isFromOutdatedConfig)return;let i={fetchToken:e,onAuthChange:t,onRefreshChange:n};r.value?(this.setAuthState({state:`waitingForServerConfirmationOfCachedToken`,config:i,hasRetried:!1}),this.authenticate(r.value)):(this.setAuthState({state:`initialRefetch`,config:i}),await this.refetchToken()),this._logVerbose(`resuming WS after auth token fetch`),this.resumeSocket()}onTransition(e){if(this.syncState.isCurrentOrNewerAuthVersion(e.endVersion.identity)&&!(e.endVersion.identity<=e.startVersion.identity)){if(this._logVerbose(`auth state is ${this.authState.state} when handling transition`),this.syncState.markAuthCompletion(),this.authState.state===`waitingForServerConfirmationOfCachedToken`){this._logVerbose(`server confirmed auth token is valid`);let t=this.syncState.getAuth()?.value;this.initialAuthTokenReuse&&t?this.scheduleTokenRefetch(t,e.clientClockSkew):this.refetchToken(),this.authState.config.onAuthChange(!0);return}this.authState.state===`waitingForServerConfirmationOfFreshToken`&&(this._logVerbose(`server confirmed new auth token is valid`),this.notifyRefreshChange(!1),this.scheduleTokenRefetch(this.authState.token),this.tokenConfirmationAttempts=0,this.authState.hadAuth||this.authState.config.onAuthChange(!0))}}onAuthError(e){if(e.authUpdateAttempted===!1&&(this.authState.state===`waitingForServerConfirmationOfFreshToken`||this.authState.state===`waitingForServerConfirmationOfCachedToken`)){this._logVerbose(`ignoring non-auth token expired error`);return}let{baseVersion:t}=e;if(!this.syncState.isCurrentOrNewerAuthVersion(t+1)){this._logVerbose(`ignoring auth error for previous auth attempt`);return}this.tryToReauthenticate(e)}async tryToReauthenticate(e){if(this._logVerbose(`attempting to reauthenticate: ${e.error}`),this.authState.state===`noAuth`||this.authState.state===`waitingForServerConfirmationOfFreshToken`&&this.tokenConfirmationAttempts>=2){this.logger.error(`Failed to authenticate: "${e.error}", check your server auth config`),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.authState.state!==`noAuth`&&this.setAndReportAuthFailed(this.authState.config.onAuthChange);return}if(this.authState.state===`waitingForServerConfirmationOfFreshToken`&&(this.tokenConfirmationAttempts++,this._logVerbose(`retrying reauthentication, ${2-this.tokenConfirmationAttempts} attempts remaining`)),this.notifyRefreshChange(!0),await this.stopSocket(),this.authState.state===`noAuth`)return;let t=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});t.isFromOutdatedConfig||(t.value&&this.syncState.isNewAuth(t.value)?(this.authenticate(t.value),this.setAuthState({state:`waitingForServerConfirmationOfFreshToken`,config:this.authState.config,token:t.value,hadAuth:this.authState.state===`notRefetching`||this.authState.state===`waitingForScheduledRefetch`})):(this._logVerbose(`reauthentication failed, could not fetch a new token`),this.syncState.hasAuth()&&this.syncState.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this.tryRestartSocket())}async refetchToken(){if(this.authState.state===`noAuth`)return;this._logVerbose(`refetching auth token`);let e=await this.fetchTokenAndGuardAgainstRace(this.authState.config.fetchToken,{forceRefreshToken:!0});e.isFromOutdatedConfig||(e.value?this.syncState.isNewAuth(e.value)?(this.setAuthState({state:`waitingForServerConfirmationOfFreshToken`,hadAuth:this.syncState.hasAuth(),token:e.value,config:this.authState.config}),this.authenticate(e.value)):this.setAuthState({state:`notRefetching`,config:this.authState.config}):(this._logVerbose(`refetching token failed`),this.syncState.hasAuth()&&this.clearAuth(),this.setAndReportAuthFailed(this.authState.config.onAuthChange)),this._logVerbose(`restarting WS after auth token fetch (if currently stopped)`),this.tryRestartSocket())}scheduleTokenRefetch(e,t){if(this.authState.state===`noAuth`)return;let n=this.decodeToken(e);if(!n){this.logger.error(`Auth token is not a valid JWT, cannot refetch the token`);return}let{iat:r,exp:i}=n;if(!r||!i){this.logger.error(`Auth token does not have required fields, cannot refetch the token`);return}let a=i-r;if(a<=2){this.logger.error(`Auth token does not live long enough, cannot refetch the token`);return}let o;t===void 0?o=a:(o=i-(Date.now()-t)/1e3,o<=0&&(o=0));let s=Math.min(1728e6,(o-this.refreshTokenLeewaySeconds)*1e3);s<=0&&(this.logger.warn(`Refetching auth token immediately, configured leeway ${this.refreshTokenLeewaySeconds}s is larger than the token's lifetime ${o}s`),s=0);let c=setTimeout(()=>{this._logVerbose(`running scheduled token refetch`),this.refetchToken()},s);this.setAuthState({state:`waitingForScheduledRefetch`,refetchTokenTimeoutId:c,config:this.authState.config}),this._logVerbose(`scheduled preemptive auth token refetching in ${s}ms`)}async fetchTokenAndGuardAgainstRace(e,t){let n=++this.configVersion;this._logVerbose(`fetching token with config version ${n}`);let r=await e(t);return this.configVersion===n?{isFromOutdatedConfig:!1,value:r}:(this._logVerbose(`stale config version, expected ${n}, got ${this.configVersion}`),{isFromOutdatedConfig:!0})}stop(){this.resetAuthState(),this.configVersion++,this._logVerbose(`config version bumped to ${this.configVersion}`)}setAndReportAuthFailed(e){e(!1),this.resetAuthState()}resetAuthState(){this.notifyRefreshChange(!1),this.setAuthState({state:`noAuth`})}setAuthState(e){let t=e.state===`waitingForServerConfirmationOfFreshToken`?{hadAuth:e.hadAuth,state:e.state,token:`...${e.token.slice(-7)}`}:{state:e.state};switch(this._logVerbose(`setting auth state to ${JSON.stringify(t)}`),e.state){case`waitingForScheduledRefetch`:case`notRefetching`:case`noAuth`:this.tokenConfirmationAttempts=0}this.authState.state===`waitingForScheduledRefetch`&&clearTimeout(this.authState.refetchTokenTimeoutId),this.authState=e}decodeToken(e){try{return Jr(e)}catch(e){return this._logVerbose(`Error decoding token: ${e instanceof Error?e.message:`Unknown error`}`),null}}_logVerbose(e){this.logger.logVerbose(`${e} [v${this.configVersion}]`)}};let Qr=[`convexClientConstructed`,`convexWebSocketOpen`,`convexFirstMessageReceived`];function $r(e,t){let n={sessionId:t};typeof performance<`u`&&performance.mark&&performance.mark(e,{detail:n})}function ei(e){let t=e.name.slice(6);return t=t.charAt(0).toLowerCase()+t.slice(1),{name:t,startTime:e.startTime}}function ti(e){if(typeof performance>`u`||!performance.getEntriesByName)return[];let t=[];for(let n of Qr){let r=performance.getEntriesByName(n).filter(e=>e.entryType===`mark`).filter(t=>t.detail.sessionId===e);t.push(...r)}return t.map(ei)}var ni=Object.defineProperty,ri=(e,t,n)=>t in e?ni(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,U=(e,t,n)=>ri(e,typeof t==`symbol`?t:t+``,n),ii=class{constructor(e,t,n){if(U(this,`address`),U(this,`state`),U(this,`requestManager`),U(this,`webSocketManager`),U(this,`authenticationManager`),U(this,`remoteQuerySet`),U(this,`optimisticQueryResults`),U(this,`_transitionHandlerCounter`,0),U(this,`_nextRequestId`),U(this,`_onTransitionFns`,/* @__PURE__ */ new Map),U(this,`_sessionId`),U(this,`firstMessageReceived`,!1),U(this,`debug`),U(this,`logger`),U(this,`maxObservedTimestamp`),U(this,`connectionStateSubscribers`,/* @__PURE__ */ new Map),U(this,`nextConnectionStateSubscriberId`,0),U(this,`_lastPublishedConnectionState`),U(this,`markConnectionStateDirty`,()=>{Promise.resolve().then(()=>{let e=this.connectionState();if(JSON.stringify(e)!==JSON.stringify(this._lastPublishedConnectionState)){this._lastPublishedConnectionState=e;for(let t of this.connectionStateSubscribers.values())t(e)}})}),U(this,`mark`,e=>{this.debug&&$r(e,this.sessionId)}),typeof e==`object`)throw Error(`Passing a ClientConfig object is no longer supported. Pass the URL of the Convex deployment as a string directly.`);n?.skipConvexDeploymentUrlCheck!==!0&&dn(e),n={...n};let r=n.authRefreshTokenLeewaySeconds??10,i=n.webSocketConstructor;if(!i&&typeof WebSocket>`u`)throw Error(`No WebSocket global variable defined! To use Convex in an environment without WebSocket try the HTTP client: https://docs.convex.dev/api/classes/browser.ConvexHttpClient`);i=i||WebSocket,this.debug=n.reportDebugInfoToConvex??!1,this.address=e,this.logger=n.logger===!1?tr({verbose:n.verbose??!1}):n.logger!==!0&&n.logger?n.logger:er({verbose:n.verbose??!1});let a=e.search(`://`);if(a===-1)throw Error(`Provided address was not an absolute URL.`);let o=e.substring(a+3),s=e.substring(0,a),c;if(s===`http`)c=`ws`;else if(s===`https`)c=`wss`;else throw Error(`Unknown parent protocol ${s}`);let l=`${c}://${o}/api/${zn}/sync`;this.state=new lr,this.remoteQuerySet=new jr(e=>this.state.queryPath(e),this.logger),this.requestManager=new pr(this.logger,this.markConnectionStateDirty);let u=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new Zr(this.state,{authenticate:e=>{let t=this.state.setAuth(e);return this.webSocketManager.sendMessage(t),t.baseVersion},stopSocket:()=>this.webSocketManager.stop(),tryRestartSocket:()=>this.webSocketManager.tryRestart(),pauseSocket:u,resumeSocket:()=>this.webSocketManager.resume(),clearAuth:()=>{this.clearAuth()}},{logger:this.logger,refreshTokenLeewaySeconds:r,initialAuthTokenReuse:n.initialAuthTokenReuse??!1}),this.optimisticQueryResults=new vr,this.addOnTransitionHandler(e=>{t(e.queries.map(e=>e.token))}),this._nextRequestId=0,this._sessionId=Ur();let{unsavedChangesWarning:d}=n;if(typeof window>`u`||window.addEventListener===void 0){if(d===!0)throw Error(`unsavedChangesWarning requested, but window.addEventListener not found! Remove {unsavedChangesWarning: true} from Convex client options.`)}else d!==!1&&window.addEventListener(`beforeunload`,e=>{if(this.requestManager.hasIncompleteRequests()){e.preventDefault();let t=`Are you sure you want to leave? Your changes may not be saved.`;return(e||window.event).returnValue=t,t}});this.webSocketManager=new Hr(l,{onOpen:e=>{this.mark(`convexWebSocketOpen`),this.webSocketManager.sendMessage({...e,type:`Connect`,sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new jr(e=>this.state.queryPath(e),this.logger);let[t,n]=this.state.restart();n&&this.webSocketManager.sendMessage(n),this.webSocketManager.sendMessage(t);for(let e of this.requestManager.restart())this.webSocketManager.sendMessage(e)},onResume:()=>{let[e,t]=this.state.resume();t&&this.webSocketManager.sendMessage(t),e&&this.webSocketManager.sendMessage(e);for(let e of this.requestManager.resume())this.webSocketManager.sendMessage(e)},onMessage:e=>{switch(this.firstMessageReceived||(this.firstMessageReceived=!0,this.mark(`convexFirstMessageReceived`),this.reportMarks()),e.type){case`Transition`:{this.observedTimestamp(e.endVersion.ts),this.authenticationManager.onTransition(e),this.remoteQuerySet.transition(e),this.state.transition(e);let t=this.requestManager.removeCompleted(this.remoteQuerySet.timestamp());this.notifyOnQueryResultChanges(t);break}case`MutationResponse`:{e.success&&this.observedTimestamp(e.ts);let t=this.requestManager.onResponse(e);t!==null&&this.notifyOnQueryResultChanges(/* @__PURE__ */ new Map([[t.requestId,t.result]]));break}case`ActionResponse`:this.requestManager.onResponse(e);break;case`AuthError`:this.authenticationManager.onAuthError(e);break;case`FatalError`:{let t=rr(this.logger,e.error);throw this.webSocketManager.terminate(),t}}return{hasSyncedPastLastReconnect:this.hasSyncedPastLastReconnect()}},onServerDisconnectError:n.onServerDisconnectError},i,this.logger,this.markConnectionStateDirty,this.debug),this.mark(`convexClientConstructed`),n.expectAuth&&u()}hasSyncedPastLastReconnect(){return this.requestManager.hasSyncedPastLastReconnect()&&this.state.hasSyncedPastLastReconnect()}observedTimestamp(e){(this.maxObservedTimestamp===void 0||this.maxObservedTimestamp.lessThanOrEqual(e))&&(this.maxObservedTimestamp=e)}getMaxObservedTimestamp(){return this.maxObservedTimestamp}notifyOnQueryResultChanges(e){let t=this.remoteQuerySet.remoteQueryResults(),n=/* @__PURE__ */ new Map;for(let[e,r]of t){let t=this.state.queryToken(e);if(t!==null){let i={result:r,udfPath:this.state.queryPath(e),args:this.state.queryArgs(e)};n.set(t,i)}}let r=this.optimisticQueryResults.ingestQueryResultsFromServer(n,new Set(e.keys()));this.handleTransition({queries:r.map(e=>({token:e,modification:{kind:`Updated`,result:this.optimisticQueryResults.rawQueryResult(e)}})),reflectedMutations:Array.from(e).map(([e,t])=>({requestId:e,result:t})),timestamp:this.remoteQuerySet.timestamp()})}handleTransition(e){for(let t of this._onTransitionFns.values())t(e)}addOnTransitionHandler(e){let t=this._transitionHandlerCounter++;return this._onTransitionFns.set(t,e),()=>this._onTransitionFns.delete(t)}getCurrentAuthClaims(){let e=this.state.getAuth(),t={};if(e&&e.tokenType===`User`)try{t=e?Jr(e.value):{}}catch{t={}}else return;return{token:e.value,decoded:t}}setAuth(e,t,n){this.authenticationManager.setConfig(e,t,n)}hasAuth(){return this.state.hasAuth()}setAdminAuth(e,t){let n=this.state.setAdminAuth(e,t);this.webSocketManager.sendMessage(n)}clearAuth(){let e=this.state.clearAuth();this.webSocketManager.sendMessage(e)}subscribe(e,t,n){let r=k(t),{modification:i,queryToken:a,unsubscribe:o}=this.state.subscribe(e,r,n?.journal,n?.componentPath);return i!==null&&this.webSocketManager.sendMessage(i),{queryToken:a,unsubscribe:()=>{let e=o();e&&this.webSocketManager.sendMessage(e)}}}localQueryResult(e,t){let n=R(e,k(t));return this.optimisticQueryResults.queryResult(n)}localQueryResultByToken(e){return this.optimisticQueryResults.queryResult(e)}hasLocalQueryResultByToken(e){return this.optimisticQueryResults.hasQueryResult(e)}localQueryLogs(e,t){let n=R(e,k(t));return this.optimisticQueryResults.queryLogs(n)}queryJournal(e,t){let n=R(e,k(t));return this.state.queryJournal(n)}connectionState(){let e=this.webSocketManager.connectionState();return{hasInflightRequests:this.requestManager.hasInflightRequests(),isWebSocketConnected:e.isConnected,hasEverConnected:e.hasEverConnected,connectionCount:e.connectionCount,connectionRetries:e.connectionRetries,timeOfOldestInflightRequest:this.requestManager.timeOfOldestInflightRequest(),inflightMutations:this.requestManager.inflightMutations(),inflightActions:this.requestManager.inflightActions()}}subscribeToConnectionState(e){let t=this.nextConnectionStateSubscriberId++;return this.connectionStateSubscribers.set(t,e),()=>{this.connectionStateSubscribers.delete(t)}}async mutation(e,t,n){let r=await this.mutationInternal(e,t,n);if(!r.success)throw r.errorData===void 0?Error(I(`mutation`,e,r)):ir(r,new Rn(I(`mutation`,e,r)));return r.value}async mutationInternal(e,t,n,r){let{mutationPromise:i}=this.enqueueMutation(e,t,n,r);return i}enqueueMutation(e,t,n,r){let i=k(t);this.tryReportLongDisconnect();let a=this.nextRequestId;if(this._nextRequestId++,n!==void 0){let e=n.optimisticUpdate;if(e!==void 0){let t=this.optimisticQueryResults.applyOptimisticUpdate(t=>{e(t,i)instanceof Promise&&this.logger.warn(`Optimistic update handler returned a Promise. Optimistic updates should be synchronous.`)},a).map(e=>{let t=this.localQueryResultByToken(e);return{token:e,modification:{kind:`Updated`,result:t===void 0?void 0:{success:!0,value:t,logLines:[]}}}});this.handleTransition({queries:t,reflectedMutations:[],timestamp:this.remoteQuerySet.timestamp()})}}let o={type:`Mutation`,requestId:a,udfPath:e,componentPath:r,args:[N(i)]},s=this.webSocketManager.sendMessage(o);return{requestId:a,mutationPromise:this.requestManager.request(o,s)}}async action(e,t){let n=await this.actionInternal(e,t);if(!n.success)throw n.errorData===void 0?Error(I(`action`,e,n)):ir(n,new Rn(I(`action`,e,n)));return n.value}async actionInternal(e,t,n){let r=k(t),i=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();let a={type:`Action`,requestId:i,udfPath:e,componentPath:n,args:[N(r)]},o=this.webSocketManager.sendMessage(a);return this.requestManager.request(a,o)}async close(){return this.authenticationManager.stop(),this.webSocketManager.terminate()}get url(){return this.address}get nextRequestId(){return this._nextRequestId}get sessionId(){return this._sessionId}reportMarks(){if(this.debug){let e=ti(this.sessionId);this.webSocketManager.sendMessage({type:`Event`,eventType:`ClientConnect`,event:e})}}tryReportLongDisconnect(){if(!this.debug)return;let e=this.connectionState().timeOfOldestInflightRequest;if(e===null||Date.now()-e.getTime()<=6e4)return;let t=`${this.address}/api/debug_event`;fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,"Convex-Client":`npm-${zn}`},body:JSON.stringify({event:`LongWebsocketDisconnect`})}).then(e=>{e.ok||this.logger.warn(`Analytics request failed with response:`,e.body)}).catch(e=>{this.logger.warn(`Analytics response failed with error:`,e)})}};function ai(e){if(typeof e!=`object`||!e||!Array.isArray(e.page)||typeof e.isDone!=`boolean`||typeof e.continueCursor!=`string`)throw Error(`Not a valid paginated query result: ${e?.toString()}`);return e}var oi=Object.defineProperty,si=(e,t,n)=>t in e?oi(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ci=(e,t,n)=>si(e,typeof t==`symbol`?t:t+``,n),li=class{constructor(e,t){this.client=e,this.onTransition=t,ci(this,`paginatedQuerySet`,/* @__PURE__ */ new Map),ci(this,`lastTransitionTs`),this.lastTransitionTs=Sr.fromNumber(0),this.client.addOnTransitionHandler(e=>this.onBaseTransition(e))}subscribe(e,t,n){let r=L(e),i=ar(r,t,n),a=()=>this.removePaginatedQuerySubscriber(i),o=this.paginatedQuerySet.get(i);return o?(o.numSubscribers+=1,{paginatedQueryToken:i,unsubscribe:a}):(this.paginatedQuerySet.set(i,{token:i,canonicalizedUdfPath:r,args:t,numSubscribers:1,options:{initialNumItems:n.initialNumItems},nextPageKey:0,pageKeys:[],pageKeyToQuery:/* @__PURE__ */ new Map,ongoingSplits:/* @__PURE__ */ new Map,skip:!1,id:n.id}),this.addPageToPaginatedQuery(i,null,n.initialNumItems),{paginatedQueryToken:i,unsubscribe:a})}localQueryResult(e,t,n){let r=ar(L(e),t,n);return this.localQueryResultByToken(r)}localQueryResultByToken(e){let t=this.paginatedQuerySet.get(e);if(!t)return;let n=this.activePageQueryTokens(t);if(n.length===0)return{results:[],status:`LoadingFirstPage`,loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)};let r=[],i=!1,a=!1;for(let e of n){let t=this.client.localQueryResultByToken(e);if(t===void 0){i=!0,a=!1;continue}let n=ai(t);r=r.concat(n.page),a=!!n.isDone}let o;return o=i?r.length===0?`LoadingFirstPage`:`LoadingMore`:a?`Exhausted`:`CanLoadMore`,{results:r,status:o,loadMore:t=>this.loadMoreOfPaginatedQuery(e,t)}}onBaseTransition(e){let t=e.queries.map(e=>e.token),n=this.queriesContainingTokens(t),r=[];n.length>0&&(this.processPaginatedQuerySplits(n,e=>this.client.localQueryResultByToken(e)),r=n.map(e=>({token:e,modification:{kind:`Updated`,result:this.localQueryResultByToken(e)}})));let i={...e,paginatedQueries:r};this.onTransition(i)}loadMoreOfPaginatedQuery(e,t){this.mustGetPaginatedQuery(e);let n=this.queryTokenForLastPageOfPaginatedQuery(e),r=this.client.localQueryResultByToken(n);if(!r)return!1;let i=ai(r);if(i.isDone)return!1;this.addPageToPaginatedQuery(e,i.continueCursor,t);let a={timestamp:this.lastTransitionTs,reflectedMutations:[],queries:[],paginatedQueries:[{token:e,modification:{kind:`Updated`,result:this.localQueryResultByToken(e)}}]};return this.onTransition(a),!0}queriesContainingTokens(e){if(e.length===0)return[];let t=[],n=new Set(e);for(let[e,r]of this.paginatedQuerySet)for(let i of this.allQueryTokens(r))if(n.has(i)){t.push(e);break}return t}processPaginatedQuerySplits(e,t){for(let n of e){let e=this.mustGetPaginatedQuery(n),{ongoingSplits:r,pageKeyToQuery:i,pageKeys:a}=e;for(let[n,[a,o]]of r)t(i.get(a).queryToken)!==void 0&&t(i.get(o).queryToken)!==void 0&&this.completePaginatedQuerySplit(e,n,a,o);for(let n of a){if(r.has(n))continue;let a=i.get(n);if(!a)throw Error(`No page query for active pageKey ${n}`);let o=t(a.queryToken);if(!o)continue;let s=ai(o);s.splitCursor&&(s.pageStatus===`SplitRecommended`||s.pageStatus===`SplitRequired`||s.page.length>e.options.initialNumItems*2)&&this.splitPaginatedQueryPage(e,n,a.cursor,s.splitCursor,s.continueCursor)}}}splitPaginatedQueryPage(e,t,n,r,i){let a=e.nextPageKey++,o=e.nextPageKey++,s={numItems:e.options.initialNumItems,id:e.id},c=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...s,cursor:n,endCursor:r}});e.pageKeyToQuery.set(a,{...c,cursor:n});let l=this.client.subscribe(e.canonicalizedUdfPath,{...e.args,paginationOpts:{...s,cursor:r,endCursor:i}});e.pageKeyToQuery.set(o,{...l,cursor:r}),e.ongoingSplits.set(t,[a,o])}addPageToPaginatedQuery(e,t,n){let r=this.mustGetPaginatedQuery(e),i=r.nextPageKey++,a={cursor:t,numItems:n,id:r.id},o={...r.args,paginationOpts:a},s=this.client.subscribe(r.canonicalizedUdfPath,o);return r.pageKeys.push(i),r.pageKeyToQuery.set(i,{...s,cursor:t}),s}removePaginatedQuerySubscriber(e){let t=this.paginatedQuerySet.get(e);if(t&&(--t.numSubscribers,!(t.numSubscribers>0))){for(let e of t.pageKeyToQuery.values())e.unsubscribe();this.paginatedQuerySet.delete(e)}}completePaginatedQuerySplit(e,t,n,r){let i=e.pageKeyToQuery.get(t);e.pageKeyToQuery.delete(t);let a=e.pageKeys.indexOf(t);e.pageKeys.splice(a,1,n,r),e.ongoingSplits.delete(t),i.unsubscribe()}activePageQueryTokens(e){return e.pageKeys.map(t=>e.pageKeyToQuery.get(t).queryToken)}allQueryTokens(e){return Array.from(e.pageKeyToQuery.values()).map(e=>e.queryToken)}queryTokenForLastPageOfPaginatedQuery(e){let t=this.mustGetPaginatedQuery(e),n=t.pageKeys[t.pageKeys.length-1];if(n===void 0)throw Error(`No pages for paginated query ${e}`);return t.pageKeyToQuery.get(n).queryToken}mustGetPaginatedQuery(e){let t=this.paginatedQuerySet.get(e);if(!t)throw Error(`paginated query no longer exists for token `+e);return t}},ui=Object.defineProperty,di=(e,t,n)=>t in e?ui(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,W=(e,t,n)=>di(e,typeof t==`symbol`?t:t+``,n),fi=class{constructor(e,t={}){W(this,`listeners`),W(this,`_client`),W(this,`_paginatedClient`),W(this,`callNewListenersWithCurrentValuesTimer`),W(this,`_closed`),W(this,`_disabled`),t.skipConvexDeploymentUrlCheck!==!0&&dn(e);let{disabled:n,...r}=t;this._closed=!1,this._disabled=!!n,typeof window>`u`&&!(`unsavedChangesWarning`in r)&&(r.unsavedChangesWarning=!1),this.disabled||(this._client=new ii(e,()=>{},r),this._paginatedClient=new li(this._client,e=>this._transition(e))),this.listeners=/* @__PURE__ */ new Set}get closed(){return this._closed}get client(){if(this._client)return this._client;throw Error(`ConvexClient is disabled`)}get paginatedClient(){if(this._paginatedClient)return this._paginatedClient;throw Error(`ConvexClient is disabled`)}get disabled(){return this._disabled}onUpdate(e,t,n,r){if(this.disabled)return this.createDisabledUnsubscribe();let{queryToken:i,unsubscribe:a}=this.client.subscribe(P(e),t),o={queryToken:i,callback:n,onError:r,unsubscribe:a,hasEverRun:!1,query:e,args:t,paginationOptions:void 0};this.listeners.add(o),this.queryResultReady(i)&&this.callNewListenersWithCurrentValuesTimer===void 0&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));let s={unsubscribe:()=>{this.closed||(this.listeners.delete(o),a())},getCurrentValue:()=>this.client.localQueryResultByToken(i),getQueryLogs:()=>this.client.localQueryLogs(i)},c=s.unsubscribe;return Object.assign(c,s),c}onPaginatedUpdate_experimental(e,t,n,r,i){if(this.disabled)return this.createDisabledUnsubscribe();let a={initialNumItems:n.initialNumItems,id:-1},{paginatedQueryToken:o,unsubscribe:s}=this.paginatedClient.subscribe(P(e),t,a),c={queryToken:o,callback:r,onError:i,unsubscribe:s,hasEverRun:!1,query:e,args:t,paginationOptions:a};this.listeners.add(c),this.paginatedClient.localQueryResultByToken(o)&&this.callNewListenersWithCurrentValuesTimer===void 0&&(this.callNewListenersWithCurrentValuesTimer=setTimeout(()=>this.callNewListenersWithCurrentValues(),0));let l={unsubscribe:()=>{this.closed||(this.listeners.delete(c),s())},getCurrentValue:()=>this.paginatedClient.localQueryResult(P(e),t,a),getQueryLogs:()=>[]},u=l.unsubscribe;return Object.assign(u,l),u}callNewListenersWithCurrentValues(){this.callNewListenersWithCurrentValuesTimer=void 0,this._transition({queries:[],paginatedQueries:[]},!0)}queryResultReady(e){return this.client.hasLocalQueryResultByToken(e)}createDisabledUnsubscribe(){let e=(()=>{});return Object.assign(e,{unsubscribe:e,getCurrentValue:()=>void 0,getQueryLogs:()=>void 0}),e}async close(){if(!this.disabled)return this.listeners.clear(),this._closed=!0,this._paginatedClient&&(this._paginatedClient=void 0),this.client.close()}getAuth(){if(!this.disabled)return this.client.getCurrentAuthClaims()}setAuth(e,t){this.disabled||this.client.setAuth(e,t??(()=>{}))}setAdminAuth(e,t){if(this.closed)throw Error(`ConvexClient has already been closed.`);this.disabled||this.client.setAdminAuth(e,t)}_transition({queries:e,paginatedQueries:t},n=!1){let r=[...e.map(e=>e.token),...t.map(e=>e.token)];for(let e of this.listeners){let{callback:t,queryToken:i,onError:a,hasEverRun:o}=e,s=or(i),c=s?!!this.paginatedClient.localQueryResultByToken(i):this.client.hasLocalQueryResultByToken(i);if(r.includes(i)||n&&!o&&c){e.hasEverRun=!0;let n;try{n=s?this.paginatedClient.localQueryResultByToken(i):this.client.localQueryResultByToken(i)}catch(e){if(!(e instanceof Error))throw e;a?a(e,`Second argument to onUpdate onError is reserved for later use`):Promise.reject(e);continue}t(n,`Second argument to onUpdate callback is reserved for later use`)}}}async mutation(e,t,n){if(this.disabled)throw Error(`ConvexClient is disabled`);return await this.client.mutation(P(e),t,n)}async action(e,t){if(this.disabled)throw Error(`ConvexClient is disabled`);return await this.client.action(P(e),t)}async query(e,t){if(this.disabled)throw Error(`ConvexClient is disabled`);let n=this.client.localQueryResult(P(e),t);return n===void 0?new Promise((n,r)=>{let{unsubscribe:i}=this.onUpdate(e,t,e=>{i(),n(e)},e=>{i(),r(e)})}):Promise.resolve(n)}connectionState(){if(this.disabled)throw Error(`ConvexClient is disabled`);return this.client.connectionState()}subscribeToConnectionState(e){return this.disabled?()=>{}:this.client.subscribeToConnectionState(e)}},G=class extends Error{constructor(e,t){super(e),this.code=t}};function pi(e){let t=e?.data;return t?.message?t.message:e instanceof Error?e.message:`Something went wrong`}var mi=class{constructor(e){this.config=e,b(this,`client`,void 0),this.client=new fi(e.convexUrl,{unsavedChangesWarning:!1,skipConvexDeploymentUrlCheck:!/\.convex\.cloud\/?$/.test(e.convexUrl)})}close(){return this.client.close()}touch(e){return this.client.mutation(F.projects.touch,{publicId:this.config.project,origin:e}).catch(()=>null)}onStatus(e){return this.client.onUpdate(F.projects.status,{publicId:this.config.project},e,()=>{})}onPage(e,t,n){return this.client.onUpdate(F.comments.listForPage,{publicId:this.config.project,path:e},e=>t(e),n)}onPages(e){return this.client.onUpdate(F.comments.pagesWithComments,{publicId:this.config.project},e,()=>{})}onSession(e,t){return this.client.onUpdate(F.sessions.validate,{publicId:this.config.project,sessionToken:e},t,()=>{})}onOwnerComment(e,t,n){return this.client.onUpdate(F.comments.getForOwner,{publicId:this.config.project,id:e,sessionToken:t},e=>n(e),()=>{})}onThread(e,t){return this.client.onUpdate(F.replies.listForComment,{publicId:this.config.project,commentId:e},e=>t(e),()=>{})}getComment(e){return this.client.query(F.comments.getById,{publicId:this.config.project,id:e}).then(e=>e).catch(()=>null)}async createComment(e){let t;try{t=await fetch(`${this.config.convexSiteUrl}/widget/comments`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({publicId:this.config.project,...e})})}catch{throw new G(`Couldn't reach Nuni. Check your connection.`,`network`)}let n=await t.json().catch(()=>({}));if(!t.ok||!n.id)throw new G(n.message??`Couldn't post the comment`,n.code??`error`);return n.id}async createReply(e){let t;try{t=await fetch(`${this.config.convexSiteUrl}/widget/replies`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({publicId:this.config.project,...e})})}catch{throw new G(`Couldn't reach Nuni. Check your connection.`,`network`)}let n=await t.json().catch(()=>({}));if(!t.ok||!n.id)throw new G(n.message??`Couldn't post the reply`,n.code??`error`);return n.id}async uploadScreenshot(e,t,n){let r=await fetch(`${this.config.convexSiteUrl}/widget/screenshot`,{method:`POST`,headers:{"Content-Type":n.type,"X-Nuni-Project":this.config.project,"X-Nuni-Comment":e,"X-Nuni-Author":t},body:n});if(!r.ok){let e=await r.json().catch(()=>({}));throw new G(e.message??`Couldn't attach the screenshot`,e.code??`error`)}}async run(e){try{return await e}catch(e){throw new G(pi(e),`error`)}}editOwn(e,t,n){return this.run(this.client.mutation(F.comments.editOwn,{id:e,authorSecret:t,body:n}))}deleteOwn(e,t){return this.run(this.client.mutation(F.comments.deleteOwn,{id:e,authorSecret:t}))}resolve(e,t){return this.run(this.client.mutation(F.comments.resolve,{id:e,sessionToken:t}))}reopen(e,t){return this.run(this.client.mutation(F.comments.reopen,{id:e,sessionToken:t}))}editReply(e,t,n){return this.run(this.client.mutation(F.replies.editOwn,{id:e,authorSecret:t,body:n}))}deleteReply(e,t){return this.run(this.client.mutation(F.replies.deleteOwn,{id:e,authorSecret:t}))}removeReply(e,t){return this.run(this.client.mutation(F.replies.remove,{id:e,sessionToken:t}))}toggleReaction(e,t,n,r){return this.run(this.client.mutation(F.reactions.toggle,{publicId:this.config.project,commentId:e,targetId:t,emoji:n,authorSecret:r}))}remove(e,t){return this.run(this.client.mutation(F.comments.remove,{id:e,sessionToken:t}))}};function K(e,t={},...n){let r=document.createElement(e);for(let[e,n]of Object.entries(t))n!=null&&n!==!1&&(e.startsWith(`on`)&&typeof n==`function`?r.addEventListener(e.slice(2).toLowerCase(),n):e===`class`?r.className=String(n):n===!0?r.setAttribute(e,``):r.setAttribute(e,String(n)));for(let e of n.flat())e!=null&&e!==!1&&r.append(typeof e==`string`?document.createTextNode(e):e);return r}function q(e){let t=document.createElement(`span`);t.className=`icon`,t.setAttribute(`aria-hidden`,`true`);let n=new DOMParser().parseFromString(e,`image/svg+xml`);return t.append(document.importNode(n.documentElement,!0)),t}function hi(e){let t=e.trim().split(/\s+/).filter(Boolean);return(t.length>1?t[0][0]+t[t.length-1][0]:(t[0]??`?`).slice(0,2)).toUpperCase()}function gi(e){let t=0;for(let n of e)t=t*31+n.charCodeAt(0)>>>0;return`oklch(0.5 0.17 ${t%360})`}async function _i(e){try{return await navigator.clipboard.writeText(e),!0}catch{}let t=document.createElement(`textarea`);t.value=e,t.setAttribute(`readonly`,``),t.style.cssText=`position:fixed;top:0;left:0;opacity:0`,document.body.appendChild(t),t.select();try{return document.execCommand(`copy`)}catch{return!1}finally{t.remove()}}function vi(e){let t=document.createElement(`span`);if(t.style.color=e,!t.style.color)return null;t.style.display=`none`,document.documentElement.appendChild(t);let n=getComputedStyle(t).color;if(t.remove(),/^rgba?\(/.test(n)){let e=n.match(/[\d.]+/g)?.map(Number);if(e&&e.length>=3)return[e[0],e[1],e[2]]}try{let t=document.createElement(`canvas`);t.width=t.height=1;let n=t.getContext(`2d`);if(!n)return null;n.fillStyle=e,n.fillRect(0,0,1,1);let[r,i,a]=n.getImageData(0,0,1,1).data;return[r,i,a]}catch{return null}}function yi([e,t,n]){let r=e=>{let t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4},i=.2126*r(e)+.7152*r(t)+.0722*r(n);return 1.05/(i+.05)>=(i+.05)/.05?`#ffffff`:`#111111`}let bi={toolbar:`Nuni comments`,comment:`Comment`,addComment:`Add a comment`,addCommentKey:`Add a comment ({key})`,cancelAdding:`Cancel adding a comment`,pickElement:`Pick an element`,allComments:`All comments`,openCount:`Comments on this page: {count} open`,commentSelection:`Comment on the selected text`,commentSelectionKey:`Comment on the selected text ({key})`,pickHint:`Click anything to comment, or drag to mark an area`,pickHintMobile:`Tap anything to comment`,pickHintKeys:`Arrow keys move, Enter comments, Esc cancels`,picked:`Selected {element}`,comments:`Comments`,close:`Close`,tabOpen:`Open ({count})`,tabResolved:`Resolved ({count})`,loading:`Loading…`,noOpen:`No open comments on this page.`,noOpenKey:`No open comments on this page. Press {key} to add one.`,noResolved:`Nothing resolved yet.`,notFoundHere:`Couldn't find on this page`,searchComments:`Search comments`,noMatches:`No comments match “{query}”.`,otherPages:`Other pages`,openOnPage:`{count} open`,replyCount:{one:`{count} reply`,other:`{count} replies`},edited:`edited`,ownSite:`Own this website?`,claim:`Claim Nuni`,yourName:`Your name`,leaveComment:`Leave a comment`,notYou:`Not you?`,cancel:`Cancel`,post:`Post`,posting:`Posting…`,save:`Save`,send:`{key} + Enter`,charsLeft:{one:`{count} character left`,other:`{count} characters left`},pinLabel:`Comment by {name}: {body}`,commentBy:`Comment by {name}`,openScreenshot:`Open the screenshot`,screenshotTaken:`Screenshot taken when the comment was left`,resolved:`Resolved`,leftOn:`Left on {origin}`,approximate:`Approximate`,approximateHint:`The page changed; this pin is a best guess`,notFound:`Element not found`,originallyOn:`Originally on: {text}`,resolve:`Resolve`,reopen:`Reopen`,copyForAgent:`Copy for agent`,copyForAgentHint:`Copy for your coding agent`,loadingContext:`Loading page context…`,edit:`Edit`,delete:`Delete`,owner:`Owner`,addReaction:`Add a reaction`,reactions:`Reactions`,reactWith:`React with {emoji}`,reply:`Reply`,replyFirst:`Reply to start a thread`,sendReply:`Send reply`,editReply:`Edit reply`,deleteReply:`Delete reply`,confirmDeleteComment:`Delete this comment? This can't be undone.`,confirmDeleteReply:`Delete this reply?`,added:`Comment added`,saved:`Saved`,deleted:`Deleted`,replyDeleted:`Reply deleted`,reopened:`Reopened`,copied:`Copied for your coding agent`,copyFailed:`Couldn't copy`,signedIn:`You're signed in as the owner`,linkGone:`That comment was deleted or is on another page`,enterName:`Enter your name`,writeFirst:`Write a comment first`,commentTooLong:`Comments are limited to {count} characters`,replyTooLong:`Replies are limited to {count} characters`,postFailed:`Couldn't post the comment`,replyFailed:`Couldn't post the reply`,reactFailed:`Couldn't react`,failed:`Something went wrong`,justNow:`just now`};function xi(){if(typeof navigator>`u`)return!1;let e=navigator.userAgentData?.platform??navigator.platform??``;return/mac|iphone|ipad|ipod/i.test(e||navigator.userAgent)}function Si(e,t={}){let n={...bi,...t},r=null,i=null;try{r=new Intl.PluralRules(e),i=new Intl.RelativeTimeFormat(e,{numeric:`auto`,style:`narrow`})}catch{r=new Intl.PluralRules,i=new Intl.RelativeTimeFormat(void 0,{numeric:`auto`,style:`narrow`})}let a=(e,t={})=>{let i=n[e]??bi[e];return(typeof i==`string`?i:i[r.select(Number(t.count??0))]??i.other).replace(/\{(\w+)\}/g,(e,n)=>n in t?String(t[n]):e)};return{locale:e,t:a,timeAgo:(t,n=Date.now())=>{let r=Math.max(0,Math.round((n-t)/1e3));if(r<45)return a(`justNow`);let o=Math.round(r/60);if(o<60)return i.format(-o,`minute`);let s=Math.round(o/60);if(s<24)return i.format(-s,`hour`);let c=Math.round(s/24);if(c<30)return i.format(-c,`day`);try{return new Date(t).toLocaleDateString(e)}catch{return new Date(t).toLocaleDateString()}},mod:xi()?`⌘`:`Ctrl`}}let J=e=>`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">${e}</svg>`,Y={comment:J(`<path d="M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.6A8 8 0 1 1 21 12z"/>`),list:J(`<path d="M8 6h13M8 12h13M8 18h13M3 6h.01M3 12h.01M3 18h.01"/>`),close:J(`<path d="M18 6 6 18M6 6l12 12"/>`),check:J(`<path d="M20 6 9 17l-5-5"/>`),undo:J(`<path d="M3 7v6h6"/><path d="M21 17a9 9 0 0 0-15-6.7L3 13"/>`),trash:J(`<path d="M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6"/>`),edit:J(`<path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"/>`),send:J(`<path d="m22 2-7 20-4-9-9-4z"/><path d="M22 2 11 13"/>`),bot:J(`<path d="M12 8V4H8"/><rect width="16" height="12" x="4" y="8" rx="2"/><path d="M2 14h2M20 14h2M15 13v2M9 13v2"/>`),smile:J(`<circle cx="12" cy="12" r="9"/><path d="M8 14s1.5 2 4 2 4-2 4-2M9 9h.01M15 9h.01"/>`),user:J(`<circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/>`),arrowUp:J(`<path d="M12 19V5M5 12l7-7 7 7"/>`),search:J(`<circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/>`),target:J(`<circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="3"/>`),github:`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="currentColor"><path d="M12 .5a11.5 11.5 0 0 0-3.6 22.4c.6.1.8-.3.8-.6v-2c-3.2.7-3.9-1.5-3.9-1.5-.5-1.3-1.3-1.7-1.3-1.7-1-.7.1-.7.1-.7 1.2.1 1.8 1.2 1.8 1.2 1 1.8 2.8 1.3 3.5 1 .1-.8.4-1.3.7-1.6-2.6-.3-5.3-1.3-5.3-5.7 0-1.3.5-2.3 1.2-3.1-.1-.3-.5-1.5.1-3.1 0 0 1-.3 3.2 1.2a11 11 0 0 1 5.8 0c2.2-1.5 3.2-1.2 3.2-1.2.6 1.6.2 2.8.1 3.1.8.8 1.2 1.9 1.2 3.1 0 4.4-2.7 5.4-5.3 5.7.4.4.8 1.1.8 2.2v3.3c0 .3.2.7.8.6A11.5 11.5 0 0 0 12 .5z"/></svg>`,link:J(`<path d="M15 3h6v6M10 14 21 3M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>`)},Ci=`nuni:locationchange`,wi=!1;function Ti(e){if(!wi){wi=!0;for(let e of[`pushState`,`replaceState`]){let t=history[e];history[e]=function(...e){let n=t.apply(this,e);return window.dispatchEvent(new Event(Ci)),n}}}let t=location.href,n=()=>{location.href!==t&&(t=location.href,e())};window.addEventListener(Ci,n),window.addEventListener(`popstate`,n),window.addEventListener(`hashchange`,n);let r=window.navigation,i=()=>setTimeout(n,0);return r?.addEventListener(`navigatesuccess`,i),()=>{window.removeEventListener(Ci,n),window.removeEventListener(`popstate`,n),window.removeEventListener(`hashchange`,n),r?.removeEventListener(`navigatesuccess`,i)}}async function Ei(e){let t=new TextEncoder().encode(e);if(typeof crypto<`u`&&crypto.subtle){let e=await crypto.subtle.digest(`SHA-256`,t);return Di(new Uint8Array(e))}return Di(ki(t))}function Di(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}let Oi=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function ki(e){let t=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),n=e.length*8,r=new Uint8Array(e.length+9+63>>6<<6);r.set(e),r[e.length]=128;let i=new DataView(r.buffer);i.setUint32(r.length-4,n>>>0),i.setUint32(r.length-8,Math.floor(n/2**32));let a=/* @__PURE__ */ new Uint32Array(64),o=(e,t)=>e>>>t|e<<32-t;for(let e=0;e<r.length;e+=64){for(let t=0;t<16;t++)a[t]=i.getUint32(e+t*4);for(let e=16;e<64;e++){let t=a[e-15],n=a[e-2],r=o(t,7)^o(t,18)^t>>>3,i=o(n,17)^o(n,19)^n>>>10;a[e]=a[e-16]+r+a[e-7]+i>>>0}let[n,r,s,c,l,u,d,f]=t;for(let e=0;e<64;e++){let t=o(l,6)^o(l,11)^o(l,25),i=l&u^~l&d,p=f+t+i+Oi[e]+a[e]>>>0,m=(o(n,2)^o(n,13)^o(n,22))+(n&r^n&s^r&s)>>>0;f=d,d=u,u=l,l=c+p>>>0,c=s,s=r,r=n,n=p+m>>>0}t[0]=t[0]+n>>>0,t[1]=t[1]+r>>>0,t[2]=t[2]+s>>>0,t[3]=t[3]+c>>>0,t[4]=t[4]+l>>>0,t[5]=t[5]+u>>>0,t[6]=t[6]+d>>>0,t[7]=t[7]+f>>>0}let s=/* @__PURE__ */ new Uint8Array(32),c=new DataView(s.buffer);return t.forEach((e,t)=>c.setUint32(t*4,e)),s}function Ai(e,t){e.scrollIntoView({block:`center`,inline:`center`,behavior:`instant`});let n=e;for(;n;){let e=n.parentElement;if(e){let r=e.ownerDocument.defaultView?.getComputedStyle(e),i=r&&/auto|scroll|hidden/.test(r.overflowX),a=r&&/auto|scroll|hidden/.test(r.overflowY);if(e!==e.ownerDocument.scrollingElement&&(i||a)){let n=nt(e,document),r=t();e.scrollBy({left:i?r.x-n.left-e.clientLeft-e.clientWidth/2:0,top:a?r.y-n.top-e.clientTop-e.clientHeight/2:0,behavior:`instant`})}n=e;continue}let r=n.getRootNode();if(S(r)){n=r.host;continue}let i=n.ownerDocument,a=i.defaultView,o=$e(i);if(a){let e=t(),n=o?nt(o,document):{left:0,top:0};a.scrollBy({left:e.x-n.left-(o?.clientLeft??0)-a.innerWidth/2,top:e.y-n.top-(o?.clientTop??0)-a.innerHeight/2,behavior:`instant`})}n=o}}let ji=/* @__PURE__ */ new Map;function Mi(e){try{return window.localStorage.getItem(e)}catch{return ji.get(e)??null}}function X(e,t){try{t===null?window.localStorage.removeItem(e):window.localStorage.setItem(e,t)}catch{t===null?ji.delete(e):ji.set(e,t)}}let Z={name:`nuni:name`,secret:`nuni:author-secret`,session:e=>`nuni:session:${e}`,position:e=>`nuni:position:${e}`,lastViewed:e=>`nuni:last-viewed:${e}`},Ni=`nuni-picking`,Pi=[`pointerdown`,`mousedown`,`pointerup`,`mouseup`];function Fi(e){return Array.from(e.getClientRects()).filter(e=>e.width>0&&e.height>0)}function Ii(e,t){let n=e.region;if(!n)return null;let r=nt(t,document);return{left:r.left+n.x*r.width,top:r.top+n.y*r.height,width:n.w*r.width,height:n.h*r.height}}let Li=e=>e.replace(/\s+/g,` `).trim();function Ri(e){typeof requestIdleCallback==`function`?requestIdleCallback(e,{timeout:100}):setTimeout(e,0)}function zi(e,t=0){if(t>3)return[];let n=[];for(let r of Array.from(e.querySelectorAll(`iframe`))){let e=et(r);e?.documentElement&&n.push(e,...zi(e,t+1))}return n}let Bi=`(max-width: 640px)`;function Vi(e){if(!e||e.nodeType!==1)return!1;let t=e;return t.isContentEditable||t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.tagName===`SELECT`}function Hi(e){return K(`span`,{class:`avatar`,style:`background:${gi(e)}`},hi(e))}function Ui(e){let t=e.tagName.toLowerCase(),n=e.id?`#${e.id}`:``,r=Array.from(e.classList).slice(0,2).map(e=>`.${e}`).join(``),i=x(e,40);return`${t}${n}${r}${i?` "${i}"`:``}`}function Wi(e,t){let n=/[?#]/.test(e)?t.origin+e:t.origin+e+t.search;try{return new URL(n).origin===t.origin?n:null}catch{return null}}var Gi=class{constructor(e,t){this.config=e,this.runtime=t,b(this,`host`,void 0),b(this,`root`,void 0),b(this,`markLayer`,void 0),b(this,`pinLayer`,void 0),b(this,`overlayLayer`,void 0),b(this,`selectButton`,void 0),b(this,`uiLayer`,void 0),b(this,`api`,void 0),b(this,`cleanups`,[]),b(this,`pageUnsub`,null),b(this,`sessionUnsub`,null),b(this,`pageKey`,``),b(this,`comments`,[]),b(this,`loaded`,!1),b(this,`placements`,/* @__PURE__ */ new Map),b(this,`pins`,/* @__PURE__ */ new Map),b(this,`status`,null),b(this,`pages`,[]),b(this,`picking`,!1),b(this,`panelOpen`,!1),b(this,`tab`,`open`),b(this,`search`,``),b(this,`lastViewedId`,void 0),b(this,`card`,null),b(this,`activeId`,null),b(this,`hoverEl`,null),b(this,`toastTimer`,0),b(this,`toast`,null),b(this,`name`,Mi(Z.name)??``),b(this,`secret`,void 0),b(this,`secretHash`,``),b(this,`ownerToken`,void 0),b(this,`ownerName`,null),b(this,`deepLinkId`,null),b(this,`extraComment`,null),b(this,`ownerDetail`,null),b(this,`ownerDetailId`,null),b(this,`ownerDetailLoaded`,!1),b(this,`ownerDetailUnsub`,null),b(this,`thread`,null),b(this,`threadId`,null),b(this,`threadUnsub`,null),b(this,`resolveRun`,0),b(this,`scopeWatchers`,/* @__PURE__ */ new Map),b(this,`pickDocs`,[]),b(this,`dragStart`,null),b(this,`dragBox`,null),b(this,`dragEnded`,!1),b(this,`selection`,null),b(this,`pointerDown`,!1),b(this,`selectionFrame`,0),b(this,`returnFocus`,null),b(this,`focusNext`,null),b(this,`confirming`,null),b(this,`live`,void 0),b(this,`layoutFrame`,0),b(this,`pinPositions`,/* @__PURE__ */ new Map),b(this,`resolveTimer`,0),b(this,`shownPlacements`,``),b(this,`i18n`,void 0),b(this,`position`,void 0),b(this,`toolbarDrag`,null),b(this,`endToolbarDrag`,null),b(this,`toolbarDropped`,!1),b(this,`isIgnored`,e=>e===this.host||this.host.contains(e)),b(this,`onFrameKey`,e=>this.onKeyDown(e)),b(this,`swallow`,e=>{if(this.fromPage(e)){if(e.type===`pointerdown`&&e instanceof PointerEvent){let t=this.fromPage(e);t&&(this.hoverEl=en(t),this.renderHighlight()),this.dragEnded=!1,this.dragStart=e.pointerType!==`touch`&&e.button===0&&(t?.ownerDocument??null)===document?{x:e.clientX,y:e.clientY}:null}if(e.type===`pointerup`&&this.dragBox){let e=this.dragBox;this.dragStart=null,this.dragBox=null,this.dragEnded=!0,setTimeout(()=>{this.dragEnded=!1,this.picking&&this.commentOnArea(e)},0)}else e.type===`pointerup`&&(this.dragStart=null);e.preventDefault(),e.stopPropagation()}}),b(this,`onPickMove`,e=>{let t=this.dragStart;if(t){let n=e.clientX-t.x,r=e.clientY-t.y;if(this.dragBox||Math.hypot(n,r)>6){this.dragBox={left:Math.min(t.x,e.clientX),top:Math.min(t.y,e.clientY),width:Math.abs(n),height:Math.abs(r)},this.renderHighlight();return}}let n=this.fromPage(e),r=n?en(n):null;r!==this.hoverEl&&(this.hoverEl=r,this.renderHighlight())}),b(this,`onPickClick`,e=>{let t=this.fromPage(e);if(!t||(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation(),this.dragEnded))return;let n=en(t),r=Dt(n,{x:e.clientX,y:e.clientY},{ignoreAttributePrefixes:[],document});this.openComposer({anchor:r,element:n})}),this.i18n=Si(e.locale,e.messages);let n=Mi(Z.secret);n||(n=g(),X(Z.secret,n)),this.secret=n,this.ownerToken=Mi(Z.session(e.project)),this.lastViewedId=Mi(Z.lastViewed(e.project)),this.position=se(Mi(Z.position(e.project))??void 0,ae,e.position),this.host=document.createElement(`div`),this.host.id=`nuni-root`,this.host.setAttribute(`data-nuni`,``),this.applyAppearance(),this.root=this.host.attachShadow({mode:`open`});let r=document.createElement(`style`);r.textContent=`
|
|
10
10
|
:host {
|
|
11
11
|
all: initial;
|
|
12
12
|
position: fixed;
|
|
@@ -79,7 +79,18 @@ button { cursor: pointer; }
|
|
|
79
79
|
border: 1px solid var(--n-border);
|
|
80
80
|
box-shadow: var(--n-shadow);
|
|
81
81
|
pointer-events: auto;
|
|
82
|
-
|
|
82
|
+
cursor: grab;
|
|
83
|
+
touch-action: none;
|
|
84
|
+
user-select: none;
|
|
85
|
+
-webkit-user-select: none;
|
|
86
|
+
}
|
|
87
|
+
.toolbar[data-dragging] {
|
|
88
|
+
cursor: grabbing;
|
|
89
|
+
box-shadow: 0 2px 4px rgba(0,0,0,0.08), 0 16px 40px rgba(0,0,0,0.2);
|
|
90
|
+
}
|
|
91
|
+
/* While dragging, the host covers the page so no move is lost to it. */
|
|
92
|
+
:host([data-dragging]) { pointer-events: auto; cursor: grabbing; }
|
|
93
|
+
:host([data-dragging]) .tb-btn { pointer-events: none; }
|
|
83
94
|
.tb-btn {
|
|
84
95
|
display: inline-flex;
|
|
85
96
|
align-items: center;
|
|
@@ -236,7 +247,6 @@ button { cursor: pointer; }
|
|
|
236
247
|
gap: 12px;
|
|
237
248
|
}
|
|
238
249
|
.confirm p { margin: 0; }
|
|
239
|
-
.btn-danger-solid { background: var(--n-danger); color: #fff; border-color: transparent; }
|
|
240
250
|
|
|
241
251
|
/* Pins */
|
|
242
252
|
.pin {
|
|
@@ -286,59 +296,34 @@ button { cursor: pointer; }
|
|
|
286
296
|
/* Cards (composer + thread) */
|
|
287
297
|
.card {
|
|
288
298
|
position: fixed;
|
|
289
|
-
width:
|
|
299
|
+
width: 340px;
|
|
290
300
|
max-width: calc(100vw - 24px);
|
|
291
301
|
background: var(--n-bg);
|
|
292
302
|
color: var(--n-fg);
|
|
293
303
|
border: 1px solid var(--n-border);
|
|
294
|
-
border-radius:
|
|
304
|
+
border-radius: 14px;
|
|
295
305
|
box-shadow: var(--n-shadow);
|
|
296
306
|
pointer-events: auto;
|
|
297
307
|
overflow: hidden;
|
|
298
308
|
}
|
|
299
|
-
.card-body { padding: 12px; display: grid; gap: 10px; }
|
|
309
|
+
.card-body { padding: 12px 14px; display: grid; gap: 10px; }
|
|
300
310
|
.card[data-card="thread"] { display: flex; flex-direction: column; max-height: calc(100vh - 24px); }
|
|
301
|
-
.
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
.reply-form .field { flex: 1 1 100%; }
|
|
308
|
-
/* A fixed size: growing on focus would move the Send button mid-click. */
|
|
309
|
-
.reply-form .field-reply { flex: 1 1 0; min-height: 56px; height: 56px; resize: none; }
|
|
310
|
-
.reactions { display: flex; flex-wrap: wrap; gap: 4px; align-items: center; position: relative; }
|
|
311
|
-
.reaction {
|
|
312
|
-
display: inline-flex;
|
|
313
|
-
align-items: center;
|
|
314
|
-
gap: 4px;
|
|
315
|
-
height: 24px;
|
|
316
|
-
padding: 0 8px;
|
|
317
|
-
border: 1px solid var(--n-border);
|
|
318
|
-
border-radius: 999px;
|
|
319
|
-
background: var(--n-bg);
|
|
311
|
+
.card .quote {
|
|
312
|
+
margin: 0;
|
|
313
|
+
padding: 6px 10px;
|
|
314
|
+
border-left: 0;
|
|
315
|
+
border-radius: 8px;
|
|
316
|
+
background: var(--n-accent-soft);
|
|
320
317
|
color: var(--n-fg);
|
|
321
|
-
font-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
.reaction[aria-pressed="true"] { border-color: var(--n-accent); background: var(--n-accent-soft); }
|
|
325
|
-
.reaction-add { color: var(--n-fg-muted); padding: 0 6px; }
|
|
326
|
-
.reaction-picker {
|
|
327
|
-
display: flex;
|
|
328
|
-
gap: 2px;
|
|
329
|
-
padding: 4px;
|
|
330
|
-
border: 1px solid var(--n-border);
|
|
331
|
-
border-radius: 999px;
|
|
332
|
-
background: var(--n-bg);
|
|
333
|
-
box-shadow: var(--n-shadow);
|
|
318
|
+
font-style: normal;
|
|
319
|
+
font-size: 13px;
|
|
320
|
+
box-shadow: inset 2px 0 0 var(--n-accent);
|
|
334
321
|
}
|
|
335
|
-
.
|
|
336
|
-
.btn-xs { width: 24px; height: 24px; }
|
|
337
|
-
.card-head { display: flex; align-items: center; gap: 8px; }
|
|
322
|
+
.card-head { display: flex; align-items: center; gap: 8px; min-width: 0; }
|
|
338
323
|
.card-head .spacer { flex: 1; }
|
|
339
324
|
.avatar {
|
|
340
|
-
width:
|
|
341
|
-
height:
|
|
325
|
+
width: 26px;
|
|
326
|
+
height: 26px;
|
|
342
327
|
border-radius: 999px;
|
|
343
328
|
color: #fff;
|
|
344
329
|
font-size: 10px;
|
|
@@ -348,8 +333,8 @@ button { cursor: pointer; }
|
|
|
348
333
|
justify-content: center;
|
|
349
334
|
flex: none;
|
|
350
335
|
}
|
|
351
|
-
.author { font-weight: 600; }
|
|
352
|
-
.meta { color: var(--n-fg-muted); font-size: 12px; }
|
|
336
|
+
.author { font-weight: 600; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
337
|
+
.meta { color: var(--n-fg-muted); font-size: 12px; white-space: nowrap; }
|
|
353
338
|
.badge {
|
|
354
339
|
display: inline-flex;
|
|
355
340
|
align-items: center;
|
|
@@ -364,28 +349,147 @@ button { cursor: pointer; }
|
|
|
364
349
|
text-overflow: ellipsis;
|
|
365
350
|
white-space: nowrap;
|
|
366
351
|
}
|
|
352
|
+
.badge .icon { width: 12px; height: 12px; }
|
|
367
353
|
.badge-ok { background: rgba(31,157,85,0.14); color: var(--n-ok); }
|
|
368
|
-
.
|
|
354
|
+
.badge-owner { background: var(--n-accent-soft); color: var(--n-accent); }
|
|
355
|
+
.comment-body { white-space: pre-wrap; word-break: break-word; line-height: 1.5; }
|
|
369
356
|
.shot {
|
|
370
357
|
display: block;
|
|
371
358
|
border: 1px solid var(--n-border);
|
|
372
|
-
border-radius:
|
|
359
|
+
border-radius: 10px;
|
|
373
360
|
overflow: hidden;
|
|
374
361
|
background: var(--n-bg-subtle);
|
|
375
362
|
}
|
|
376
363
|
.shot img { display: block; width: 100%; max-height: 160px; object-fit: cover; object-position: top; }
|
|
377
|
-
.
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
width:
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
border: 1px solid var(--n-border);
|
|
364
|
+
.icon-btn {
|
|
365
|
+
display: inline-grid;
|
|
366
|
+
place-items: center;
|
|
367
|
+
width: 28px;
|
|
368
|
+
height: 28px;
|
|
369
|
+
padding: 0;
|
|
370
|
+
border: 0;
|
|
385
371
|
border-radius: 8px;
|
|
386
|
-
background:
|
|
372
|
+
background: none;
|
|
373
|
+
color: var(--n-fg-muted);
|
|
374
|
+
flex: none;
|
|
375
|
+
transition: background 120ms ease, color 120ms ease;
|
|
376
|
+
}
|
|
377
|
+
.icon-btn:hover { background: var(--n-bg-subtle); color: var(--n-fg); }
|
|
378
|
+
.icon-btn:disabled { opacity: 0.4; cursor: default; background: none; }
|
|
379
|
+
.icon-btn-danger:hover { background: color-mix(in srgb, var(--n-danger) 12%, transparent); color: var(--n-danger); }
|
|
380
|
+
.icon-btn.is-resolved, .icon-btn.is-resolved:hover { background: rgba(31,157,85,0.14); color: var(--n-ok); }
|
|
381
|
+
|
|
382
|
+
/* A message (the comment or a reply): text lines up with the name. */
|
|
383
|
+
.msg { gap: 2px; padding: 12px 8px 8px 14px; }
|
|
384
|
+
.msg-main { display: grid; gap: 8px; padding: 0 6px 0 34px; min-width: 0; }
|
|
385
|
+
.msg .card-head { min-height: 28px; }
|
|
386
|
+
.badges { display: flex; flex-wrap: wrap; gap: 4px; }
|
|
387
|
+
.msg-foot { display: flex; align-items: center; gap: 2px; margin-right: -6px; }
|
|
388
|
+
.msg-foot .spacer { flex: 1; }
|
|
389
|
+
/* A reply's tools float over its header on hover, so names never truncate. */
|
|
390
|
+
.msg-tools:empty { display: none; }
|
|
391
|
+
.msg-tools {
|
|
392
|
+
position: absolute;
|
|
393
|
+
top: 4px;
|
|
394
|
+
right: 8px;
|
|
395
|
+
display: flex;
|
|
396
|
+
gap: 2px;
|
|
397
|
+
padding: 2px;
|
|
398
|
+
border: 1px solid var(--n-border);
|
|
399
|
+
border-radius: 10px;
|
|
400
|
+
background: var(--n-bg);
|
|
401
|
+
box-shadow: 0 1px 2px rgba(0,0,0,0.06), 0 4px 12px rgba(0,0,0,0.08);
|
|
402
|
+
opacity: 0;
|
|
403
|
+
pointer-events: none;
|
|
404
|
+
transition: opacity 120ms ease;
|
|
405
|
+
}
|
|
406
|
+
.reply:hover .msg-tools, .reply:focus-within .msg-tools { opacity: 1; pointer-events: auto; }
|
|
407
|
+
@media (hover: none) {
|
|
408
|
+
.msg-tools { position: static; opacity: 1; pointer-events: auto; padding: 0; border: 0; box-shadow: none; background: none; }
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/* Replies */
|
|
412
|
+
.thread { border-top: 1px solid var(--n-border); display: grid; min-height: 0; }
|
|
413
|
+
.replies { display: grid; padding: 4px 0; overflow-y: auto; max-height: 45vh; }
|
|
414
|
+
.reply.msg { position: relative; display: grid; padding: 8px 8px 8px 14px; }
|
|
415
|
+
.reply-form {
|
|
416
|
+
display: grid;
|
|
417
|
+
margin: 4px 12px 12px;
|
|
418
|
+
border: 1px solid var(--n-border);
|
|
419
|
+
border-radius: 12px;
|
|
420
|
+
background: var(--n-bg);
|
|
421
|
+
transition: box-shadow 140ms ease, border-color 140ms ease;
|
|
422
|
+
}
|
|
423
|
+
.reply-form:focus-within {
|
|
424
|
+
border-color: color-mix(in srgb, var(--n-accent) 45%, var(--n-border));
|
|
425
|
+
box-shadow: 0 0 0 3px var(--n-accent-soft);
|
|
426
|
+
}
|
|
427
|
+
.reply-name {
|
|
428
|
+
padding: 8px 12px 6px;
|
|
429
|
+
border: 0;
|
|
430
|
+
border-bottom: 1px solid var(--n-border);
|
|
431
|
+
background: none;
|
|
432
|
+
outline: none;
|
|
433
|
+
font-weight: 600;
|
|
434
|
+
}
|
|
435
|
+
.reply-row { display: flex; align-items: flex-end; gap: 4px; padding: 4px; }
|
|
436
|
+
.reply-text {
|
|
437
|
+
flex: 1;
|
|
438
|
+
min-width: 0;
|
|
439
|
+
min-height: 32px;
|
|
440
|
+
max-height: 160px;
|
|
441
|
+
padding: 6px 8px;
|
|
442
|
+
border: 0;
|
|
443
|
+
background: none;
|
|
444
|
+
outline: none;
|
|
445
|
+
resize: none;
|
|
446
|
+
line-height: 1.4;
|
|
387
447
|
}
|
|
388
|
-
.
|
|
448
|
+
.reply-name::placeholder, .reply-text::placeholder { color: var(--n-fg-muted); opacity: 1; font-weight: 400; }
|
|
449
|
+
.reply-send {
|
|
450
|
+
display: inline-grid;
|
|
451
|
+
place-items: center;
|
|
452
|
+
width: 32px;
|
|
453
|
+
height: 32px;
|
|
454
|
+
border: 0;
|
|
455
|
+
border-radius: 999px;
|
|
456
|
+
background: var(--n-accent);
|
|
457
|
+
color: var(--n-accent-fg);
|
|
458
|
+
flex: none;
|
|
459
|
+
}
|
|
460
|
+
.reply-send:hover { filter: brightness(1.08); }
|
|
461
|
+
.reply-send:disabled { opacity: 0.4; cursor: default; filter: none; }
|
|
462
|
+
|
|
463
|
+
/* Reactions */
|
|
464
|
+
.reactions { display: flex; flex-wrap: wrap; gap: 4px; align-items: center; position: relative; }
|
|
465
|
+
.reaction {
|
|
466
|
+
display: inline-flex;
|
|
467
|
+
align-items: center;
|
|
468
|
+
gap: 4px;
|
|
469
|
+
height: 26px;
|
|
470
|
+
padding: 0 8px;
|
|
471
|
+
border: 1px solid var(--n-border);
|
|
472
|
+
border-radius: 999px;
|
|
473
|
+
background: var(--n-bg);
|
|
474
|
+
color: var(--n-fg);
|
|
475
|
+
font-size: 12px;
|
|
476
|
+
}
|
|
477
|
+
.reaction:hover { background: var(--n-bg-subtle); }
|
|
478
|
+
.reaction[aria-pressed="true"] { border-color: color-mix(in srgb, var(--n-accent) 50%, transparent); background: var(--n-accent-soft); }
|
|
479
|
+
.reaction-add { color: var(--n-fg-muted); padding: 0 6px; border-color: transparent; }
|
|
480
|
+
.reaction-add:hover, .reaction-add[aria-expanded="true"] { color: var(--n-fg); }
|
|
481
|
+
.reaction-picker {
|
|
482
|
+
display: flex;
|
|
483
|
+
gap: 2px;
|
|
484
|
+
padding: 4px;
|
|
485
|
+
border: 1px solid var(--n-border);
|
|
486
|
+
border-radius: 999px;
|
|
487
|
+
background: var(--n-bg);
|
|
488
|
+
box-shadow: var(--n-shadow);
|
|
489
|
+
}
|
|
490
|
+
.reaction-picker .reaction { border-color: transparent; font-size: 14px; }
|
|
491
|
+
|
|
492
|
+
/* Shared controls */
|
|
389
493
|
.field {
|
|
390
494
|
width: 100%;
|
|
391
495
|
padding: 8px 10px;
|
|
@@ -417,11 +521,94 @@ textarea.field { resize: vertical; min-height: 72px; max-height: 240px; }
|
|
|
417
521
|
.btn-ghost { border-color: transparent; background: transparent; }
|
|
418
522
|
.btn-icon { width: 32px; padding: 0; justify-content: center; }
|
|
419
523
|
.btn-danger { color: var(--n-danger); }
|
|
420
|
-
.
|
|
524
|
+
/* After .btn, which would otherwise paint over the red with the card's background. */
|
|
525
|
+
.btn-danger-solid,
|
|
526
|
+
.btn-danger-solid:hover { background: var(--n-danger); border-color: var(--n-danger); color: #fff; }
|
|
527
|
+
.btn-danger-solid:hover { filter: brightness(1.08); }
|
|
421
528
|
.error { color: var(--n-danger); font-size: 12px; }
|
|
422
529
|
.divider { height: 1px; background: var(--n-border); }
|
|
423
|
-
|
|
424
|
-
|
|
530
|
+
|
|
531
|
+
/* Composer: one surface, the card itself is the input. */
|
|
532
|
+
.composer {
|
|
533
|
+
display: grid;
|
|
534
|
+
transition: box-shadow 140ms ease, border-color 140ms ease;
|
|
535
|
+
}
|
|
536
|
+
.composer:focus-within {
|
|
537
|
+
border-color: color-mix(in srgb, var(--n-accent) 45%, var(--n-border));
|
|
538
|
+
box-shadow: 0 0 0 4px var(--n-accent-soft), var(--n-shadow);
|
|
539
|
+
}
|
|
540
|
+
.composer.sheet:focus-within { border-color: var(--n-border); box-shadow: var(--n-shadow); }
|
|
541
|
+
.composer .spacer { flex: 1; }
|
|
542
|
+
.cmp-head { display: flex; align-items: center; gap: 8px; min-height: 48px; padding: 10px 44px 4px 14px; }
|
|
543
|
+
.avatar-empty { background: var(--n-bg-subtle); color: var(--n-fg-muted); }
|
|
544
|
+
.avatar-empty .icon { width: 14px; height: 14px; }
|
|
545
|
+
.cmp-name {
|
|
546
|
+
flex: 1;
|
|
547
|
+
min-width: 0;
|
|
548
|
+
padding: 0;
|
|
549
|
+
border: 0;
|
|
550
|
+
background: none;
|
|
551
|
+
outline: none;
|
|
552
|
+
font-weight: 600;
|
|
553
|
+
}
|
|
554
|
+
.cmp-link {
|
|
555
|
+
border: 0;
|
|
556
|
+
background: none;
|
|
557
|
+
padding: 2px 4px;
|
|
558
|
+
border-radius: 6px;
|
|
559
|
+
color: var(--n-fg-muted);
|
|
560
|
+
font-size: 12px;
|
|
561
|
+
white-space: nowrap;
|
|
562
|
+
}
|
|
563
|
+
.cmp-link:hover { color: var(--n-fg); }
|
|
564
|
+
.composer .quote { margin: 6px 14px 0; }
|
|
565
|
+
.cmp-text {
|
|
566
|
+
display: block;
|
|
567
|
+
width: 100%;
|
|
568
|
+
min-height: 76px;
|
|
569
|
+
max-height: 240px;
|
|
570
|
+
padding: 8px 14px;
|
|
571
|
+
border: 0;
|
|
572
|
+
background: none;
|
|
573
|
+
outline: none;
|
|
574
|
+
resize: none;
|
|
575
|
+
line-height: 1.5;
|
|
576
|
+
}
|
|
577
|
+
.cmp-name::placeholder, .cmp-text::placeholder { color: var(--n-fg-muted); opacity: 1; }
|
|
578
|
+
.cmp-name::placeholder { font-weight: 500; }
|
|
579
|
+
.cmp-error { padding: 0 14px 4px; }
|
|
580
|
+
.cmp-foot { display: flex; align-items: center; gap: 8px; padding: 6px 8px 8px 14px; }
|
|
581
|
+
.cmp-keys { display: inline-flex; gap: 3px; }
|
|
582
|
+
.cmp-keys kbd {
|
|
583
|
+
display: inline-grid;
|
|
584
|
+
place-items: center;
|
|
585
|
+
min-width: 20px;
|
|
586
|
+
height: 20px;
|
|
587
|
+
padding: 0 4px;
|
|
588
|
+
border: 1px solid var(--n-border);
|
|
589
|
+
border-bottom-width: 2px;
|
|
590
|
+
border-radius: 5px;
|
|
591
|
+
color: var(--n-fg-muted);
|
|
592
|
+
font: 500 11px/1 var(--n-font);
|
|
593
|
+
}
|
|
594
|
+
.cmp-count { color: var(--n-fg-muted); font-size: 12px; font-variant-numeric: tabular-nums; }
|
|
595
|
+
.cmp-post {
|
|
596
|
+
display: inline-flex;
|
|
597
|
+
align-items: center;
|
|
598
|
+
gap: 6px;
|
|
599
|
+
height: 32px;
|
|
600
|
+
padding: 0 10px 0 14px;
|
|
601
|
+
border: 0;
|
|
602
|
+
border-radius: 999px;
|
|
603
|
+
background: var(--n-accent);
|
|
604
|
+
color: var(--n-accent-fg);
|
|
605
|
+
font-weight: 600;
|
|
606
|
+
font-size: 13px;
|
|
607
|
+
}
|
|
608
|
+
.cmp-post:hover { filter: brightness(1.08); }
|
|
609
|
+
.cmp-post:disabled { opacity: 0.4; cursor: default; filter: none; }
|
|
610
|
+
.cmp-close { position: absolute; top: 13px; right: 8px; }
|
|
611
|
+
@media (hover: none) { .cmp-keys { display: none; } }
|
|
425
612
|
|
|
426
613
|
/* Panel */
|
|
427
614
|
.panel {
|
|
@@ -443,7 +630,7 @@ textarea.field { resize: vertical; min-height: 72px; max-height: 240px; }
|
|
|
443
630
|
}
|
|
444
631
|
.panel-head { display: flex; align-items: center; gap: 8px; padding: 12px; border-bottom: 1px solid var(--n-border); }
|
|
445
632
|
.panel-title { font-weight: 650; flex: 1; }
|
|
446
|
-
.tabs { display: flex; gap: 4px; padding:
|
|
633
|
+
.tabs { display: flex; gap: 4px; padding: 0 12px; margin-top: 8px; }
|
|
447
634
|
.tab {
|
|
448
635
|
border: 0;
|
|
449
636
|
background: transparent;
|
|
@@ -466,6 +653,11 @@ textarea.field { resize: vertical; min-height: 72px; max-height: 240px; }
|
|
|
466
653
|
border-radius: 10px;
|
|
467
654
|
}
|
|
468
655
|
.item:hover { background: var(--n-bg-subtle); }
|
|
656
|
+
/* The comment opened last, so it's easy to find your place again. */
|
|
657
|
+
.item[aria-current="true"] { background: var(--n-accent-soft); box-shadow: inset 3px 0 0 var(--n-accent); }
|
|
658
|
+
.panel-search { position: relative; padding: 0 12px; margin-top: 8px; }
|
|
659
|
+
.panel-search .icon { position: absolute; left: 22px; top: 50%; transform: translateY(-50%); color: var(--n-fg-muted); pointer-events: none; }
|
|
660
|
+
.panel-search .field { padding-left: 32px; }
|
|
469
661
|
.item-text { display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; word-break: break-word; }
|
|
470
662
|
.section-label { padding: 12px 10px 4px; font-size: 11px; font-weight: 650; letter-spacing: 0.04em; text-transform: uppercase; color: var(--n-fg-muted); }
|
|
471
663
|
.empty { padding: 32px 16px; text-align: center; color: var(--n-fg-muted); }
|
|
@@ -509,8 +701,10 @@ a.item { color: inherit; text-decoration: none; }
|
|
|
509
701
|
* { transition: none !important; animation: none !important; }
|
|
510
702
|
}
|
|
511
703
|
|
|
512
|
-
/* The toolbar's
|
|
704
|
+
/* The toolbar's spot (the position option, or where it was dragged) */
|
|
513
705
|
:host([data-position$="left"]) .toolbar { right: auto; left: 16px; }
|
|
706
|
+
:host([data-position$="center"]) .toolbar { left: 0; right: 0; width: max-content; margin-inline: auto; }
|
|
707
|
+
:host([data-position="top-center"]) .pick-hint { top: auto; bottom: 12px; }
|
|
514
708
|
:host([data-position^="top"]) .toolbar { bottom: auto; top: 16px; }
|
|
515
709
|
:host([data-position$="left"]) .panel { right: auto; left: 12px; }
|
|
516
710
|
:host([data-position^="top"]) .panel { top: 72px; bottom: 12px; }
|
|
@@ -519,4 +713,4 @@ a.item { color: inherit; text-decoration: none; }
|
|
|
519
713
|
:host([data-position$="left"]) .toolbar { left: 12px; }
|
|
520
714
|
:host([data-position^="top"]) .toolbar { top: 12px; }
|
|
521
715
|
}
|
|
522
|
-
`,this.markLayer=K(`div`,{class:`marks`,"aria-hidden":`true`}),this.pinLayer=K(`div`,{class:`pins`}),this.overlayLayer=K(`div`,{class:`overlay`}),this.uiLayer=K(`div`,{class:`ui`}),this.selectButton=K(`button`,{class:`select-btn`,type:`button`,hidden:!0,title:this.withKey(`commentSelection`,`commentSelectionKey`),onmousedown:e=>e.preventDefault(),onpointerdown:e=>e.preventDefault(),onclick:()=>this.commentOnSelection()},q(X.comment),this.t(`comment`)),this.live=K(`div`,{class:`sr`,role:`status`,"aria-live":`polite`}),this.root.append(r,this.markLayer,this.pinLayer,this.overlayLayer,this.uiLayer,this.selectButton,this.live),this.uiLayer.addEventListener(`keydown`,e=>this.trapFocus(e)),this.api=new mi(e)}t(e,t){return this.i18n.t(e,t)}withKey(e,t){let n=this.config.hotkey;return n?this.t(t,{key:n.toUpperCase()}):this.t(e)}applyAppearance(){let{position:e,theme:t,accentColor:n,zIndex:r}=this.config;this.host.dataset.position=e,this.host.dataset.theme=t,r!==null&&(this.host.style.zIndex=String(r));let i=n?_i(n):null;if(!i)return;let[a,o,s]=i;this.host.style.setProperty(`--n-accent`,`rgb(${a}, ${o}, ${s})`),this.host.style.setProperty(`--n-accent-soft`,`rgba(${a}, ${o}, ${s}, 0.14)`),this.host.style.setProperty(`--n-accent-fg`,vi(i))}start(){document.body.appendChild(this.host),Ti(this.secret).then(e=>{this.secretHash=e,this.render()}),this.api.touch(location.origin),this.cleanups.push(this.api.onStatus(e=>{this.status=e,this.render()})),this.cleanups.push(this.api.onPages(e=>{this.pages=e,this.render()})),this.ownerToken&&this.watchSession(this.ownerToken),this.readDeepLink(),this.subscribePage(),this.cleanups.push(wi(()=>{this.readDeepLink(),this.subscribePage()}));let e=e=>this.onKeyDown(e),t=()=>this.scheduleLayout(),n=e=>this.onMessage(e);window.addEventListener(`keydown`,e,!0),window.addEventListener(`scroll`,t,{capture:!0,passive:!0}),window.addEventListener(`resize`,t,{passive:!0}),window.addEventListener(`message`,n);let r=()=>this.scheduleSelection(),i=e=>{e.composedPath().includes(this.host)||(this.pointerDown=!0,this.scheduleSelection())},a=()=>{this.pointerDown=!1,this.scheduleSelection()};document.addEventListener(`selectionchange`,r),document.addEventListener(`pointerdown`,i,!0),document.addEventListener(`pointerup`,a,!0),this.cleanups.push(()=>{document.removeEventListener(`selectionchange`,r),document.removeEventListener(`pointerdown`,i,!0),document.removeEventListener(`pointerup`,a,!0),cancelAnimationFrame(this.selectionFrame)}),this.cleanups.push(()=>{window.removeEventListener(`keydown`,e,!0),window.removeEventListener(`scroll`,t,!0),window.removeEventListener(`resize`,t),window.removeEventListener(`message`,n)});let o=new MutationObserver(e=>{e.every(e=>this.host.contains(e.target)||e.target===this.host)||this.scheduleResolve()});o.observe(document.body,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:[`class`,`style`,`hidden`,`open`,`id`]});let s=new ResizeObserver(()=>this.scheduleLayout());s.observe(document.documentElement),this.cleanups.push(()=>{o.disconnect(),s.disconnect()}),this.render()}destroy(){this.setPicking(!1),this.pageUnsub?.(),this.sessionUnsub?.(),this.ownerDetailUnsub?.(),this.threadUnsub?.(),this.resolveRun++;for(let e of this.scopeWatchers.values())e();this.scopeWatchers.clear();for(let e of this.cleanups)e();cancelAnimationFrame(this.layoutFrame),clearTimeout(this.resolveTimer),clearTimeout(this.toastTimer),this.host.remove(),this.api.close()}currentPageKey(){let e=new URL(location.href);return this.config.getPageKey(e)}subscribePage(){let e=this.currentPageKey();e===this.pageKey&&this.pageUnsub||(this.pageKey=e,this.pageUnsub?.(),this.comments=[],this.extraComment=null,this.loaded=!1,this.placements.clear(),this.card=null,this.activeId=null,this.pageUnsub=this.api.onPage(e,e=>{let t=this.extraComment,n=t&&!e.some(e=>e._id===t._id)?[...e,t]:e;this.comments=n.sort((e,t)=>e.createdAt-t.createdAt),this.loaded=!0,this.resolvePlacements(this.placements.size>0,this.deepLinkId??void 0),this.openDeepLink(),this.render()},()=>{}),this.render())}watchSession(e){this.sessionUnsub?.(),this.sessionUnsub=this.api.onSession(e,e=>{e.valid?this.ownerName=e.ownerName??this.t(`owner`):(this.ownerName=null,this.ownerToken=null,Mi(Z.session(this.config.project),null),this.sessionUnsub?.(),this.sessionUnsub=null),this.render()})}syncOwnerDetail(){let e=this.ownerToken,t=this.card?.kind===`thread`&&this.isOwner&&e?this.card.id:null;t!==this.ownerDetailId&&(this.ownerDetailUnsub?.(),this.ownerDetailUnsub=null,this.ownerDetail=null,this.ownerDetailLoaded=!1,this.ownerDetailId=t,t&&e&&(this.ownerDetailUnsub=this.api.onOwnerComment(t,e,e=>{this.ownerDetailId===t&&(this.ownerDetail=e,this.ownerDetailLoaded=!0,this.render())})))}syncThread(){let e=this.card?.kind===`thread`?this.card.id:null;e!==this.threadId&&(this.threadUnsub?.(),this.threadUnsub=null,this.thread=null,this.threadId=e,e&&(this.threadUnsub=this.api.onThread(e,t=>{this.threadId===e&&(this.thread=t,this.render())})))}get isOwner(){return!!(this.ownerToken&&this.ownerName)}isMine(e){return!!this.secretHash&&e.authorKeyHash===this.secretHash}visibleComments(){return this.comments.filter(e=>e.status===(this.panelOpen&&this.tab===`resolved`?`resolved`:`open`)||this.card?.kind===`thread`&&this.card.id===e._id)}scheduleResolve(){clearTimeout(this.resolveTimer),this.resolveTimer=window.setTimeout(()=>this.resolvePlacements(!0),200)}stillPlaced(e){let t=this.placements.get(e._id);if(!t?.element?.isConnected)return!1;let n=e.anchor.quote;if(n)return t.range!==void 0&&Li(t.range.toString())===n.exact;let r=x(t.element),i=e.anchor.text;return!i||r===i||S(r,i)>.8}resolvePlacements(e,t){let n=++this.resolveRun,r=new Set(this.comments.map(e=>e._id));for(let e of this.placements.keys())r.has(e)||this.placements.delete(e);let i=this.comments.filter(t=>!(e&&this.stillPlaced(t))),a=t?i.findIndex(e=>e._id===t):-1;a>0&&i.unshift(...i.splice(a,1));let o=Mt(),s={isIgnored:this.isIgnored,document},c=()=>{if(n!==this.resolveRun)return;let t=performance.now();for(;i.length;){let e=i.shift(),n=Xt(e.anchor,document,s,o);if(this.placements.set(e._id,{element:n.element,confidence:n.confidence,range:n.range}),performance.now()-t>8)break}this.watchScopes(),this.renderPins(),this.layout(),i.length?Ri(c):(e||n>1)&&this.panelOpen&&this.render()};c()}watchScopes(){let e=/* @__PURE__ */ new Set;for(let{element:t}of this.placements.values()){let n=t;for(let t=0;n&&t<8;t++){let t=Xe(n);if(t===document)break;e.add(t),n=C(t)?t.host:Qe(t)}}for(let[t,n]of this.scopeWatchers)e.has(t)||(n(),this.scopeWatchers.delete(t));for(let t of e)this.scopeWatchers.has(t)||this.scopeWatchers.set(t,this.watchScope(t))}watchScope(e){let t=new MutationObserver(()=>this.scheduleResolve()),n=C(e)?null:e;t.observe(n?n.body??n.documentElement:e,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:[`class`,`style`,`hidden`,`open`,`id`]});let r=()=>this.scheduleLayout(),i=n?.defaultView??e;return i.addEventListener(`scroll`,r,{capture:!0,passive:!0}),n?.defaultView?.addEventListener(`resize`,r,{passive:!0}),()=>{t.disconnect(),i.removeEventListener(`scroll`,r,!0),n?.defaultView?.removeEventListener(`resize`,r)}}pinPoint(e){let t=this.placements.get(e._id),n=t?.element;return!n||!Ae(n)||tt(n,document).clipped?null:this.anchorPoint(e.anchor,n,t.range)}anchorPoint(e,t,n){if(n&&n.startContainer.ownerDocument===document){let e=Fi(n).at(-1);if(e)return{x:e.right,y:e.top+e.height/2}}let r=tt(t,document);return{x:r.left+e.offset.x*r.width,y:r.top+e.offset.y*r.height}}renderMarks(){let e=[],t=(t,n)=>{let r=K(`div`,{class:n});Object.assign(r.style,{left:`${t.left}px`,top:`${t.top}px`,width:`${t.width}px`,height:`${t.height}px`}),e.push(r)},n=(e,n,r,i)=>{if(n){if(r&&r.startContainer.ownerDocument===document)for(let e of Fi(r))t(e,i?`mark mark-active`:`mark`);if(i){let r=Ii(e,n);r&&t(r,`area`)}}};if(this.card?.kind===`composer`){let{draft:e}=this.card;n(e.anchor,e.element,e.range,!0)}for(let e of this.visibleComments()){let t=this.placements.get(e._id),r=this.activeId===e._id;(r||e.status===`open`&&e.anchor.quote)&&(this.pins.get(e._id)?.hidden||n(e.anchor,t?.element,t?.range,r))}this.markLayer.replaceChildren(...e)}scheduleLayout(){this.layoutFrame||(this.layoutFrame=requestAnimationFrame(()=>{this.layoutFrame=0,this.layout()}))}layout(){let e=window.innerWidth,t=window.innerHeight,n=[];this.pinPositions.clear();for(let r of this.visibleComments()){let i=this.pins.get(r._id);if(!i)continue;let a=this.pinPoint(r);if(i.hidden=!(a&&a.x>=-10&&a.y>=-10&&a.x<=e+10&&a.y<=t+10),!a)continue;let o=a.y,s=a.x;for(;n.some(e=>Math.abs(e.x-s)<14&&Math.abs(e.y-o)<14);)s+=18;n.push({x:s,y:o}),this.pinPositions.set(r._id,{x:s,y:o}),i.style.transform=`translate(${Math.round(s)}px, ${Math.round(o)}px)`}this.renderMarks(),this.positionCard(),this.picking&&(this.hoverEl||this.dragBox)&&this.renderHighlight(),this.placeSelectButton()}setPicking(e){if(this.picking===e)return;this.picking=e;let t=document.documentElement;if(this.dragStart=null,this.dragBox=null,e){this.card=null,window.matchMedia(Bi).matches&&(this.panelOpen=!1),this.pickDocs=[document,...zi(document)];for(let e of this.pickDocs){e.documentElement.classList.add(Ni),this.injectCursorStyle(e),e.addEventListener(`pointermove`,this.onPickMove,!0),e.addEventListener(`click`,this.onPickClick,!0);for(let t of Pi)e.addEventListener(t,this.swallow,{capture:!0,passive:!1});e!==document&&e.addEventListener(`keydown`,this.onFrameKey,!0)}}else{t.classList.remove(Ni),this.hoverEl=null;for(let e of this.pickDocs){e.documentElement?.classList.remove(Ni),e.removeEventListener(`pointermove`,this.onPickMove,!0),e.removeEventListener(`click`,this.onPickClick,!0);for(let t of Pi)e.removeEventListener(t,this.swallow,!0);e.removeEventListener(`keydown`,this.onFrameKey,!0)}this.pickDocs=[]}this.render()}injectCursorStyle(e){if(e.getElementById(`nuni-cursor-style`))return;let t=e.createElement(`style`);t.id=`nuni-cursor-style`,t.textContent=`html.${Ni}, html.${Ni} * { cursor: crosshair !important; }`,(e.head??e.documentElement).appendChild(t),this.cleanups.push(()=>t.remove())}fromPage(e){let t=e.composedPath();if(t.includes(this.host))return null;let n=t[0]??e.target;return n&&n.nodeType===1?n:null}commentOnArea(e){let t=kt(document,e,this.isIgnored),n=jt(t,e,{ignoreAttributePrefixes:[],document});this.openComposer({anchor:n,element:t})}pageSelection(){let e=document.getSelection();if(!e||e.isCollapsed||!e.rangeCount)return null;let t=e.getRangeAt(0),n=t.commonAncestorContainer,r=n.nodeType===1?n:n.parentElement;return!r||r===this.host||this.host.contains(r)||r.closest(`input, textarea, select, [contenteditable]`)||r.closest(`[data-nuni]`)?null:Li(t.toString())?t:null}commentOnSelection(){let e=this.pageSelection();if(!e)return;let t=Ot(e,{ignoreAttributePrefixes:[],document});if(!t)return;let n=e.cloneRange();document.getSelection()?.removeAllRanges(),this.selection=null,this.openComposer({...t,range:n})}scheduleSelection(){this.selectionFrame||(this.selectionFrame=requestAnimationFrame(()=>{this.selectionFrame=0,this.selection=this.picking||this.pointerDown?null:this.pageSelection(),this.placeSelectButton()}))}placeSelectButton(){let e=this.selectButton,t=this.selection,n=t?Fi(t).at(-1):void 0,r=window.innerWidth,i=window.innerHeight;if(!t||!n||n.bottom<0||n.top>i){e.hidden=!0;return}e.hidden=!1;let a=e.offsetWidth||96,o=e.offsetHeight||32,s=n.bottom+8;s+o>i-8&&(s=n.top-o-8);let c=Math.max(8,Math.min(n.right-a/2,r-a-8));e.style.transform=`translate(${Math.round(c)}px, ${Math.round(s)}px)`}openComposer(e){let{element:t}=e;if(this.setPicking(!1),this.config.capture.dom)try{e.dom=we(t)}catch{}this.card={kind:`composer`,draft:e},this.activeId=null,this.render(),this.focusComposer(),this.takeScreenshot(e)}async takeScreenshot(e){let t=this.runtime.loadScreenshot;if(!t||e.element.ownerDocument!==document)return;let n=getComputedStyle(this.host).getPropertyValue(`--n-accent`).trim()||`#d6246e`;try{await new Promise(e=>setTimeout(e,60));let r=await t(),{range:i,anchor:a,element:o}=e,s=i?()=>i.getBoundingClientRect():a.region?()=>{let e=Ii(a,o);return{left:e.left,top:e.top,right:e.left+e.width,bottom:e.top+e.height}}:void 0,c=r?await r(o,{exclude:this.host,accent:n,focus:s}):null;if(!c||!this.isComposing(e)||e.sending)return;let l=await Hi(c);if(!this.isComposing(e)||e.sending)return;e.screenshot={blob:c,preview:l},this.render()}catch{}}isComposing(e){return this.card?.kind===`composer`&&this.card.draft===e}collectContext(e){let{collectors:t}=this.runtime,n={},r=t.console(),i=t.network();return r.length&&(n.console=r),i.length&&(n.network=i),e.dom&&(n.dom=e.dom),Object.keys(n).length?n:void 0}async attachScreenshot(e,t){try{await this.api.uploadScreenshot(e,this.secret,t)}catch{}}copyForAgent(e){let t=this.ownerDetail?._id===e._id?this.ownerDetail:null,n=this.threadId===e._id?this.thread?.replies:void 0;gi(m(t??{...e,replies:n},{includeContext:!!t})).then(e=>this.showToast(e?this.t(`copied`):this.t(`copyFailed`)))}renderHighlight(){if(this.overlayLayer.replaceChildren(),!this.picking)return;let e=window.matchMedia(Bi).matches;if(this.overlayLayer.append(K(`div`,{class:`pick-hint`},e?this.t(`pickHintMobile`):[K(`span`,{},this.t(`pickHint`)),K(`span`,{class:`pick-keys`},this.t(`pickHintKeys`))])),this.dragBox){let e=K(`div`,{class:`highlight drag-box`});Object.assign(e.style,{left:`${this.dragBox.left}px`,top:`${this.dragBox.top}px`,width:`${this.dragBox.width}px`,height:`${this.dragBox.height}px`}),this.overlayLayer.append(e);return}let t=this.hoverEl;if(!t||t===t.ownerDocument.documentElement)return;let n=tt(t,document),r=K(`div`,{class:`highlight`},K(`span`,{class:`highlight-label`},Ui(t)));Object.assign(r.style,{left:`${n.left-2}px`,top:`${n.top-2}px`,width:`${n.width+4}px`,height:`${n.height+4}px`}),this.overlayLayer.append(r)}onKeyDown(e){let t=e.composedPath().includes(this.host);if(e.key===`Escape`){if(this.confirming)this.answer(!1);else if(this.picking)this.setPicking(!1);else if(this.card)this.closeCard();else if(this.panelOpen)this.togglePanel(!1);else return;e.stopPropagation();return}if(Vi(e.composedPath()[0]??e.target)||e.metaKey||e.ctrlKey||e.altKey||this.picking&&!t&&this.onPickKey(e)||t&&this.confirming||e.repeat)return;let n=this.config.hotkey;n&&e.key.toLowerCase()===n&&(e.preventDefault(),!this.picking&&this.pageSelection()?this.commentOnSelection():this.setPicking(!this.picking))}onPickKey(e){if(![`ArrowUp`,`ArrowDown`,`ArrowLeft`,`ArrowRight`,`Enter`].includes(e.key))return!1;e.preventDefault(),e.stopPropagation();let t=this.hoverEl;if(!t||!t.isConnected)return this.movePickTo(this.keyboardStart()),!0;if(e.key===`Enter`){let e=t.getBoundingClientRect(),n=Et(t,{x:e.left+e.width/2,y:e.top+e.height/2},{ignoreAttributePrefixes:[],document});return this.openComposer({anchor:n,element:t}),!0}let n=t=>{for(;t&&(t===this.host||!Ae(t));)t=e.key===`ArrowLeft`?t.previousElementSibling:t.nextElementSibling;return t},r=t.ownerDocument.body;return e.key===`ArrowUp`?t.parentElement&&t!==r&&(t=t.parentElement):t=e.key===`ArrowDown`?n(t.firstElementChild)??t:e.key===`ArrowLeft`?n(t.previousElementSibling)??t:n(t.nextElementSibling)??t,this.movePickTo(t),!0}keyboardStart(){let e=document.activeElement;if(e&&e!==document.body&&e!==this.host)return e;let t=document.elementsFromPoint(window.innerWidth/2,window.innerHeight/2).find(e=>!this.isIgnored(e));return t?$t(t):document.body}movePickTo(e){this.hoverEl=e,e.scrollIntoView({block:`nearest`,inline:`nearest`}),this.live.textContent=this.t(`picked`,{element:Ui(e)}),this.renderHighlight()}trapFocus(e){if(e.key!==`Tab`)return;let t=e.composedPath()[0]?.closest?.(`.confirm, [data-card], .panel`);if(!t)return;let n=Array.from(t.querySelectorAll(`button:not([disabled]), input, textarea, a[href], [tabindex="0"]`)).filter(e=>!e.closest(`[hidden]`));if(!n.length)return;let r=n[0],i=n[n.length-1],a=this.root.activeElement;e.shiftKey&&a===r?(e.preventDefault(),i.focus()):!e.shiftKey&&a===i&&(e.preventDefault(),r.focus())}keepFocus(){if(this.returnFocus)return;let e=this.root.activeElement;if(e){this.returnFocus=e.dataset.focusKey??e;return}let t=document.activeElement;this.returnFocus=t&&t!==document.body&&t!==this.host?t:null}restoreFocus(){let e=this.returnFocus;this.returnFocus=null;let t=typeof e==`string`?this.uiLayer.querySelector(`[data-focus-key="${e}"]`):e;t?.isConnected&&t.focus({preventScroll:!0})}ask(e,t){this.confirming?.done(!1);let n=this.root.activeElement?.dataset.focusKey??null;return new Promise(r=>{this.confirming={message:e,action:t,done:r,from:n},this.focusNext=`[data-focus-key="confirm-cancel"]`,this.render()})}answer(e){let t=this.confirming;t&&(this.confirming=null,!e&&t.from&&(this.focusNext=`[data-focus-key="${t.from}"]`),this.render(),t.done(e))}renderConfirm(){let e=this.confirming;return e?K(`div`,{class:`confirm-backdrop`,onclick:()=>this.answer(!1)},K(`div`,{class:`confirm`,role:`alertdialog`,"aria-modal":`true`,"aria-labelledby":`nuni-confirm-text`,onclick:e=>e.stopPropagation()},K(`p`,{id:`nuni-confirm-text`},e.message),K(`div`,{class:`row`},K(`span`,{class:`spacer`}),K(`button`,{class:`btn btn-ghost`,type:`button`,"data-focus-key":`confirm-cancel`,onclick:()=>this.answer(!1)},this.t(`cancel`)),K(`button`,{class:`btn btn-danger-solid`,type:`button`,"data-focus-key":`confirm-ok`,onclick:()=>this.answer(!0)},e.action)))):null}openClaim(){let e=new URL(`${this.config.appUrl}/dashboard/claim`);e.searchParams.set(`project`,this.config.project),e.searchParams.set(`origin`,location.origin),window.open(e.toString(),`nuni-claim`,`popup,width=480,height=680`)||(location.href=e.toString())}onMessage(e){let t;try{t=new URL(this.config.appUrl).origin}catch{return}if(e.origin!==t)return;let n=e.data;n&&n.type===`nuni:session`&&n.project===this.config.project&&typeof n.token==`string`&&n.token.startsWith(`nuni_s_`)&&(this.ownerToken=n.token,Mi(Z.session(this.config.project),n.token),this.watchSession(n.token),this.showToast(this.t(`signedIn`)))}readDeepLink(){let e=new URL(location.href),t=e.searchParams.get(`nuni`);t&&(this.deepLinkId=t,e.searchParams.delete(`nuni`),history.replaceState(history.state,``,e.toString()))}openDeepLink(){let e=this.deepLinkId;if(!e||!this.loaded)return;this.deepLinkId=null;let t=this.comments.find(t=>t._id===e);if(t){this.focusDeepLinked(t);return}this.api.getComment(e).then(e=>{if(!e||e.page.path!==this.pageKey){this.showToast(this.t(`linkGone`));return}this.extraComment=e,this.comments=[...this.comments.filter(t=>t._id!==e._id),e],this.resolvePlacements(!1,e._id),this.focusDeepLinked(e)})}focusDeepLinked(e){this.focusComment(e._id)}focusComment(e){let t=this.placements.get(e),n=this.comments.find(t=>t._id===e);t?.element&&n&&ki(t.element,()=>this.anchorPoint(n.anchor,t.element,t.range)),this.openThread(e),window.matchMedia(Bi).matches&&(this.panelOpen=!1),this.render(),setTimeout(()=>this.scheduleLayout(),400)}async submitDraft(e,t,r){let i=r.trim().slice(0,_.nameMaxLength),a=t.trim();if(!i)return this.setDraftError(e,this.t(`enterName`));if(!a)return this.setDraftError(e,this.t(`writeFirst`));if(a.length>_.bodyMaxLength)return this.setDraftError(e,this.t(`commentTooLong`,{count:_.bodyMaxLength}));this.name=i,Mi(Z.name,i),e.sending=!0,e.error=void 0,this.render();let o=n(location.href),s=e.screenshot;try{let t=await this.api.createComment({body:a,authorName:i,authorSecret:this.secret,page:{...o,path:this.pageKey,title:document.title.slice(0,300)},anchor:e.anchor,viewport:{w:window.innerWidth,h:window.innerHeight,dpr:window.devicePixelRatio||1},context:this.collectContext(e)});s&&this.attachScreenshot(t,s.blob),this.placements.set(t,{element:e.element,confidence:`exact`,range:e.range}),this.card?.kind===`composer`&&this.card.draft===e&&(this.card=null),this.showToast(this.t(`added`))}catch(t){e.sending=!1,e.error=t instanceof G?t.message:this.t(`postFailed`)}this.render()}setDraftError(e,t){e.error=t,this.render()}async act(e,t,n){let r=this.card;r?.kind===`thread`&&(r.busy=!0,r.error=void 0,this.render());try{return await t(),n&&this.showToast(n),this.card?.kind===`thread`&&this.card.id===e&&(this.card.busy=!1,this.card.editing=!1),this.render(),!0}catch(t){return this.card?.kind===`thread`&&this.card.id===e&&(this.card.busy=!1,this.card.error=t instanceof Error?t.message:this.t(`failed`)),this.render(),!1}}resolveComment(e){let t=this.ownerToken;t&&this.act(e._id,()=>this.api.resolve(e._id,t),this.t(`resolved`)).then(t=>{t&&!(this.panelOpen&&this.tab===`resolved`)&&this.card?.kind===`thread`&&this.card.id===e._id&&this.closeCard()})}reopenComment(e){let t=this.ownerToken;t&&this.act(e._id,()=>this.api.reopen(e._id,t),this.t(`reopened`))}async deleteComment(e){if(!await this.ask(this.t(`confirmDeleteComment`),this.t(`delete`)))return;let t=this.ownerToken,n=this.isMine(e)?()=>this.api.deleteOwn(e._id,this.secret):t?()=>this.api.remove(e._id,t):null;n&&this.act(e._id,n,this.t(`deleted`)).then(t=>{t&&(this.extraComment?._id===e._id&&(this.extraComment=null),this.comments=this.comments.filter(t=>t._id!==e._id),this.placements.delete(e._id),this.closeCard())})}isMyReply(e){return!!this.secretHash&&e.authorKeyHash===this.secretHash}async sendReply(e,t,n){let r=this.card;if(r?.kind!==`thread`||r.id!==e._id)return;let i=(this.isOwner?this.ownerName:n)?.trim().slice(0,_.nameMaxLength),a=t.trim();if(a){if(!i){r.error=this.t(`enterName`),this.render();return}if(a.length>_.bodyMaxLength){r.error=this.t(`replyTooLong`,{count:_.bodyMaxLength}),this.render();return}this.isOwner||(this.name=i,Mi(Z.name,i)),r.sendingReply=!0,r.error=void 0,this.render();try{await this.api.createReply({commentId:e._id,body:a,authorName:i,authorSecret:this.secret,sessionToken:this.ownerToken??void 0});let t=this.uiLayer.querySelector(`[data-focus-key="reply"]`);t&&(t.value=``)}catch(e){r.error=e instanceof G?e.message:this.t(`replyFailed`)}r.sendingReply=!1,this.render()}}toggleReaction(e,t,n){this.api.toggleReaction(e._id,t,n,this.secret).catch(t=>{this.card?.kind===`thread`&&this.card.id===e._id&&(this.card.error=t instanceof Error?t.message:this.t(`reactFailed`),this.render())})}async deleteReply(e,t){if(!await this.ask(this.t(`confirmDeleteReply`),this.t(`delete`)))return;let n=this.ownerToken,r=this.isMyReply(t)?()=>this.api.deleteReply(t._id,this.secret):n?()=>this.api.removeReply(t._id,n):null;r&&this.act(e._id,r,this.t(`replyDeleted`))}saveReplyEdit(e,t,n){this.act(e._id,()=>this.api.editReply(t._id,this.secret,n),this.t(`saved`)).then(e=>{e&&this.card?.kind===`thread`&&(this.card.replyEditing=void 0,this.render())})}saveEdit(e,t){this.act(e._id,()=>this.api.editOwn(e._id,this.secret,t),this.t(`saved`))}showToast(e){this.toast=e,clearTimeout(this.toastTimer),this.toastTimer=window.setTimeout(()=>{this.toast=null,this.render()},2400),this.render()}togglePanel(e=!this.panelOpen){e!==this.panelOpen&&(this.panelOpen=e,e&&(this.keepFocus(),this.focusNext=`.panel [role="tab"][aria-selected="true"]`,window.matchMedia(Bi).matches&&(this.card=null)),this.render(),!e&&!this.card&&this.restoreFocus())}closeCard(){let e=this.card!==null;this.card=null,this.activeId=null,this.render(),e&&!this.panelOpen&&this.restoreFocus()}openThread(e){this.keepFocus(),this.activeId=e,this.card={kind:`thread`,id:e},this.focusNext=`[data-card="thread"] .card-head button`}render(){this.syncOwnerDetail(),this.syncThread(),this.renderPins(),this.renderUi(),this.renderHighlight(),this.layout()}renderPins(){let e=this.visibleComments(),t=new Set(e.map(e=>e._id));for(let[e,n]of this.pins)t.has(e)||(n.remove(),this.pins.delete(e));for(let t of e){let e=this.pins.get(t._id);if(!e){e=K(`button`,{class:`pin`,type:`button`,hidden:!0});let n=t._id;e.addEventListener(`click`,e=>{e.stopPropagation(),this.card?.kind===`thread`&&this.card.id===n?this.closeCard():(this.openThread(n),this.render())}),this.pins.set(t._id,e),this.pinLayer.append(e)}e.textContent=J(t.authorName),e.style.background=hi(t.authorName),e.setAttribute(`aria-label`,this.t(`pinLabel`,{name:t.authorName,body:t.body.slice(0,80)})),t.replyCount?e.dataset.replies=String(t.replyCount):delete e.dataset.replies,e.dataset.status=t.status,e.dataset.active=String(this.activeId===t._id),e.dataset.confidence=this.placements.get(t._id)?.confidence??`lost`}if(this.pinLayer.querySelector(`.pin-draft`)?.remove(),this.card?.kind===`composer`){let{draft:e}=this.card,{x:t,y:n}=this.anchorPoint(e.anchor,e.element,e.range),r=K(`div`,{class:`pin pin-draft pin-pending`,"aria-hidden":`true`},this.name?J(this.name):`+`);r.style.background=this.name?hi(this.name):`var(--n-accent)`,r.style.transform=`translate(${Math.round(t)}px, ${Math.round(n)}px)`,this.pinLayer.append(r)}}renderUi(){let e=[this.renderToolbar()];this.panelOpen&&e.push(this.renderPanel());let t=this.renderCard();t&&e.push(t),this.toast&&e.push(K(`div`,{class:`toast`,role:`status`},this.toast));let n=this.renderConfirm();n&&e.push(n);let r=this.root.activeElement,i=r?.dataset.focusKey,a=r instanceof HTMLTextAreaElement||r instanceof HTMLInputElement?{start:r.selectionStart,end:r.selectionEnd}:null;this.uiLayer.replaceChildren(...e);let o=this.focusNext;this.focusNext=null;let s=o?this.uiLayer.querySelector(o):null;if(s)s.focus();else if(i){let e=this.uiLayer.querySelector(`[data-focus-key="${i}"]`);e?.focus(),a&&(e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement)&&e.setSelectionRange(a.start,a.end)}this.positionCard()}renderToolbar(){let e=this.comments.filter(e=>e.status===`open`).length;return K(`div`,{class:`toolbar`,role:`toolbar`,"aria-label":this.t(`toolbar`)},K(`button`,{class:`tb-btn`,type:`button`,"aria-pressed":String(this.picking),"data-focus-key":`tb-comment`,"aria-label":this.picking?this.t(`cancelAdding`):this.t(`addComment`),title:this.withKey(`addComment`,`addCommentKey`),onclick:()=>this.setPicking(!this.picking)},q(X.comment),K(`span`,{class:`tb-label`},this.picking?this.t(`pickElement`):this.config.label??this.t(`comment`))),K(`button`,{class:`tb-btn`,type:`button`,"aria-pressed":String(this.panelOpen),"data-focus-key":`tb-panel`,"aria-label":this.t(`openCount`,{count:e}),title:this.t(`allComments`),onclick:()=>this.togglePanel()},q(X.list),K(`span`,{class:`tb-count`},String(e))))}renderPanel(){let e=this.comments.filter(e=>e.status===`open`),t=this.comments.filter(e=>e.status===`resolved`),n=this.tab===`open`?e:t,r=n.filter(e=>this.placements.get(e._id)?.element),i=n.filter(e=>!this.placements.get(e._id)?.element),a=this.pages.filter(e=>e.path!==this.pageKey),o=e=>K(`button`,{class:`item`,type:`button`,"data-focus-key":`item-${e._id}`,onclick:()=>this.focusComment(e._id)},K(`div`,{class:`row`},K(`span`,{class:`avatar`,style:`background:${hi(e.authorName)}`},J(e.authorName)),K(`span`,{class:`author`},e.authorName),K(`span`,{class:`meta`},this.i18n.timeAgo(e.createdAt)+(e.replyCount?` · ${this.t(`replyCount`,{count:e.replyCount})}`:``)),e.page.origin===location.origin?null:K(`span`,{class:`badge`,title:e.page.origin},new URL(e.page.origin).host)),e.anchor.quote?K(`div`,{class:`item-quote`},e.anchor.quote.exact):null,K(`div`,{class:`item-text`},e.body)),s=[];if(this.loaded?n.length?(s.push(...r.map(o)),i.length&&(s.push(K(`div`,{class:`section-label`},this.t(`notFoundHere`))),s.push(...i.map(o)))):s.push(K(`div`,{class:`empty`},this.tab===`open`?this.withKey(`noOpen`,`noOpenKey`):this.t(`noResolved`))):s.push(K(`div`,{class:`empty`},this.t(`loading`))),a.length){s.push(K(`div`,{class:`section-label`},this.t(`otherPages`)));for(let e of a.slice(0,20)){let t=Wi(e.path,location);s.push(K(t===null?`div`:`a`,t===null?{class:`item`}:{class:`item`,href:t},K(`div`,{class:`row`},K(`span`,{class:`author`},e.path),K(`span`,{class:`spacer`}),K(`span`,{class:`badge`},this.t(`openOnPage`,{count:e.count})))))}}return K(`div`,{class:`panel`,role:`dialog`,"aria-label":this.t(`comments`)},K(`div`,{class:`panel-head`},K(`div`,{class:`panel-title`},this.t(`comments`)),K(`button`,{class:`btn btn-ghost btn-icon`,type:`button`,"aria-label":this.t(`close`),onclick:()=>this.togglePanel(!1)},q(X.close))),K(`div`,{class:`tabs`,role:`tablist`,"aria-label":this.t(`comments`),onkeydown:e=>{let t=e.key;[`ArrowLeft`,`ArrowRight`,`Home`,`End`].includes(t)&&(e.preventDefault(),this.tab=t===`Home`?`open`:t===`End`||this.tab===`open`?`resolved`:`open`,this.focusNext=`[data-focus-key="tab-${this.tab}"]`,this.render())}},[`open`,`resolved`].map(n=>K(`button`,{class:`tab`,role:`tab`,type:`button`,id:`nuni-tab-${n}`,"data-focus-key":`tab-${n}`,"aria-selected":String(this.tab===n),"aria-controls":`nuni-panel-list`,tabindex:this.tab===n?0:-1,onclick:()=>{this.tab=n,this.render()}},n===`open`?this.t(`tabOpen`,{count:e.length}):this.t(`tabResolved`,{count:t.length})))),K(`div`,{class:`panel-list`,id:`nuni-panel-list`,role:`tabpanel`,"aria-labelledby":`nuni-tab-${this.tab}`},...s),this.status&&!this.status.claimed&&!this.isOwner?this.renderPanelFooter():null)}renderPanelFooter(){return K(`div`,{class:`panel-foot`},K(`div`,{class:`row`},K(`span`,{class:`meta`},this.t(`ownSite`)),K(`span`,{class:`spacer`}),K(`button`,{class:`btn`,type:`button`,onclick:()=>this.openClaim()},q(X.github),this.t(`claim`))))}renderCard(){let e=this.card;if(!e)return null;let t=`card${window.matchMedia(Bi).matches?` sheet`:``}`;if(e.kind===`composer`){let{draft:n}=e,r=!this.name,i=K(`input`,{class:`field`,placeholder:this.t(`yourName`),value:this.name,maxlength:_.nameMaxLength,autocomplete:`name`,"data-focus-key":`name`,"aria-label":this.t(`yourName`)}),a=K(`textarea`,{class:`field`,placeholder:this.t(`leaveComment`),maxlength:_.bodyMaxLength,"data-focus-key":`body`,"aria-label":this.t(`comment`)}),o=this.uiLayer.querySelector(`[data-focus-key="body"]`);o&&(a.value=o.value);let s=this.uiLayer.querySelector(`[data-focus-key="name"]`);s&&(i.value=s.value);let c=()=>void this.submitDraft(n,a.value,r?i.value:this.name);return a.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),c())}),K(`form`,{class:t,"data-card":`composer`,onsubmit:e=>{e.preventDefault(),c()}},K(`div`,{class:`card-body`},r?i:K(`div`,{class:`row`},K(`span`,{class:`avatar`,style:`background:${hi(this.name)}`},J(this.name)),K(`span`,{class:`author`},this.name),K(`span`,{class:`spacer`}),K(`button`,{class:`link`,type:`button`,onclick:()=>{this.name=``,this.render()}},this.t(`notYou`))),n.anchor.quote?K(`blockquote`,{class:`quote`},n.anchor.quote.exact):null,a,n.screenshot?K(`div`,{class:`shot-preview`},K(`img`,{src:n.screenshot.preview,alt:this.t(`screenshotAlt`)}),K(`div`,{class:`shot-note`},K(`span`,{},this.t(`screenshotNote`)),K(`span`,{class:`spacer`}),K(`button`,{class:`link`,type:`button`,onclick:()=>{n.screenshot=void 0,this.render()}},this.t(`remove`)))):null,n.error?K(`div`,{class:`error`,role:`alert`},n.error):null,K(`div`,{class:`row`},K(`span`,{class:`kbd`},this.t(`send`,{key:this.i18n.mod})),K(`span`,{class:`spacer`}),K(`button`,{class:`btn btn-ghost`,type:`button`,onclick:()=>this.closeCard()},this.t(`cancel`)),K(`button`,{class:`btn btn-primary`,type:`submit`,disabled:!!n.sending},q(X.send),n.sending?this.t(`posting`):this.t(`post`)))))}let n=this.comments.find(t=>t._id===e.id);if(!n)return null;let r=this.isMine(n),i=this.isOwner,a=this.placements.get(n._id),o;if(e.editing){let t=K(`textarea`,{class:`field`,maxlength:_.bodyMaxLength,"data-focus-key":`edit`}),r=this.uiLayer.querySelector(`[data-focus-key="edit"]`);t.value=r?r.value:n.body,o=K(`div`,{class:`card-body`},t,K(`div`,{class:`row`},K(`span`,{class:`spacer`}),K(`button`,{class:`btn btn-ghost`,type:`button`,onclick:()=>{e.editing=!1,this.render()}},this.t(`cancel`)),K(`button`,{class:`btn btn-primary`,type:`button`,disabled:!!e.busy,onclick:()=>this.saveEdit(n,t.value)},this.t(`save`))))}else o=K(`div`,{class:`card-body`},K(`div`,{class:`card-head`},K(`span`,{class:`avatar`,style:`background:${hi(n.authorName)}`},J(n.authorName)),K(`span`,{class:`author`},n.authorName),K(`span`,{class:`meta`},this.i18n.timeAgo(n.createdAt)+(n.editedAt?` · ${this.t(`edited`)}`:``)),K(`span`,{class:`spacer`}),K(`button`,{class:`btn btn-ghost btn-icon`,type:`button`,"aria-label":this.t(`close`),onclick:()=>this.closeCard()},q(X.close))),n.anchor.quote?K(`blockquote`,{class:`quote`},n.anchor.quote.exact):null,K(`div`,{class:`comment-body`},n.body),this.ownerDetail?._id===n._id&&this.ownerDetail.screenshotUrl?K(`a`,{class:`shot`,href:this.ownerDetail.screenshotUrl,target:`_blank`,rel:`noreferrer`,title:this.t(`openScreenshot`)},K(`img`,{src:this.ownerDetail.screenshotUrl,alt:this.t(`screenshotTaken`)})):null,K(`div`,{class:`row`},n.status===`resolved`?K(`span`,{class:`badge badge-ok`},q(X.check),this.t(`resolved`)):null,n.page.origin===location.origin?null:K(`span`,{class:`badge`,title:this.t(`leftOn`,{origin:n.page.origin})},new URL(n.page.origin).host),a?.confidence===`low`?K(`span`,{class:`badge`,title:this.t(`approximateHint`)},this.t(`approximate`)):null,a?.element?null:K(`span`,{class:`badge`,title:this.t(`originallyOn`,{text:n.anchor.text||n.anchor.tag})},this.t(`notFound`))),this.renderReactions(n,n._id),e.error?K(`div`,{class:`error`,role:`alert`},e.error):null);let s=[];if(!e.editing){i&&s.push(n.status===`open`?K(`button`,{class:`btn`,type:`button`,disabled:!!e.busy,onclick:()=>this.resolveComment(n)},q(X.check),this.t(`resolve`)):K(`button`,{class:`btn`,type:`button`,disabled:!!e.busy,onclick:()=>this.reopenComment(n)},q(X.undo),this.t(`reopen`))),s.push(K(`span`,{class:`spacer`}));let t=i&&!(this.ownerDetailLoaded&&this.ownerDetailId===n._id);s.push(K(`button`,{class:`btn btn-ghost btn-icon`,type:`button`,"aria-label":this.t(`copyForAgent`),title:t?this.t(`loadingContext`):this.t(`copyForAgentHint`),disabled:t,onclick:()=>this.copyForAgent(n)},q(X.bot))),r&&s.push(K(`button`,{class:`btn btn-ghost btn-icon`,type:`button`,"aria-label":this.t(`edit`),title:this.t(`edit`),onclick:()=>{e.editing=!0,this.render()}},q(X.edit))),(r||i)&&s.push(K(`button`,{class:`btn btn-ghost btn-icon btn-danger`,type:`button`,"aria-label":this.t(`delete`),title:this.t(`delete`),"data-focus-key":`delete`,disabled:!!e.busy,onclick:()=>void this.deleteComment(n)},q(X.trash)))}return K(`div`,{class:t,"data-card":`thread`,role:`dialog`,"aria-label":this.t(`commentBy`,{name:n.authorName})},o,s.length?K(`div`,{class:`actions`},...s):null,e.editing?null:this.renderThread(n))}renderReactions(e,t){let n=this.card;if(n?.kind!==`thread`)return null;let r=this.threadId===e._id&&this.thread?this.thread.reactions.filter(e=>e.targetId===t):[],i=n.picker===t;return K(`div`,{class:`reactions`},...r.map(n=>{let r=n.authorKeyHashes.includes(this.secretHash);return K(`button`,{class:`reaction`,type:`button`,"aria-pressed":String(r),"aria-label":`${n.emoji} ${n.count}${r?`, including you`:``}`,onclick:()=>this.toggleReaction(e,t,n.emoji)},`${n.emoji} ${n.count}`)}),K(`button`,{class:`reaction reaction-add`,type:`button`,"aria-label":this.t(`addReaction`),"aria-expanded":String(i),title:this.t(`addReaction`),onclick:()=>{n.picker=i?null:t,this.render()}},q(X.smile)),i?K(`div`,{class:`reaction-picker`,role:`group`,"aria-label":this.t(`reactions`)},...re.map(r=>K(`button`,{class:`reaction`,type:`button`,"aria-label":this.t(`reactWith`,{emoji:r}),onclick:()=>{n.picker=null,this.toggleReaction(e,t,r),this.render()}},r))):null)}renderThread(e){let t=this.card;if(t?.kind!==`thread`)return null;let n=this.threadId===e._id?this.thread?.replies??[]:[],r=this.isOwner,i=n.map(n=>{let i=this.isMyReply(n);if(t.replyEditing===n._id){let r=K(`textarea`,{class:`field`,maxlength:_.bodyMaxLength,"data-focus-key":`reply-edit-${n._id}`,"aria-label":this.t(`editReply`)}),i=this.uiLayer.querySelector(`[data-focus-key="reply-edit-${n._id}"]`);return r.value=i?i.value:n.body,K(`div`,{class:`reply`},r,K(`div`,{class:`row`},K(`span`,{class:`spacer`}),K(`button`,{class:`btn btn-ghost`,type:`button`,onclick:()=>{t.replyEditing=void 0,this.render()}},this.t(`cancel`)),K(`button`,{class:`btn btn-primary`,type:`button`,disabled:!!t.busy,onclick:()=>this.saveReplyEdit(e,n,r.value)},this.t(`save`))))}return K(`div`,{class:`reply`,"data-reply":n._id},K(`div`,{class:`card-head`},K(`span`,{class:`avatar avatar-sm`,style:`background:${hi(n.authorName)}`},J(n.authorName)),K(`span`,{class:`author`},n.authorName),n.isOwner?K(`span`,{class:`badge badge-owner`},this.t(`owner`)):null,K(`span`,{class:`meta`},this.i18n.timeAgo(n.createdAt)+(n.editedAt?` · ${this.t(`edited`)}`:``)),K(`span`,{class:`spacer`}),i?K(`button`,{class:`btn btn-ghost btn-icon btn-xs`,type:`button`,"aria-label":this.t(`editReply`),title:this.t(`edit`),onclick:()=>{t.replyEditing=n._id,this.render()}},q(X.edit)):null,i||r?K(`button`,{class:`btn btn-ghost btn-icon btn-xs btn-danger`,type:`button`,"aria-label":this.t(`deleteReply`),title:this.t(`delete`),"data-focus-key":`delete-${n._id}`,disabled:!!t.busy,onclick:()=>void this.deleteReply(e,n)},q(X.trash)):null),K(`div`,{class:`comment-body`},n.body),this.renderReactions(e,n._id))}),a=!r&&!this.name,o=K(`input`,{class:`field`,placeholder:this.t(`yourName`),value:this.name,maxlength:_.nameMaxLength,autocomplete:`name`,"data-focus-key":`reply-name`,"aria-label":this.t(`yourName`)}),s=this.uiLayer.querySelector(`[data-focus-key="reply-name"]`);s&&(o.value=s.value);let c=K(`textarea`,{class:`field field-reply`,placeholder:n.length?this.t(`reply`):this.t(`replyFirst`),maxlength:_.bodyMaxLength,"data-focus-key":`reply`,"aria-label":this.t(`reply`)}),l=this.uiLayer.querySelector(`[data-focus-key="reply"]`);l&&(c.value=l.value);let u=()=>void this.sendReply(e,c.value,a?o.value:this.name);return c.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),u())}),K(`div`,{class:`thread`},i.length?K(`div`,{class:`replies`,role:`list`,"aria-label":this.t(`replyCount`,{count:i.length})},...i.map(e=>(e.setAttribute(`role`,`listitem`),e))):null,K(`form`,{class:`reply-form`,onsubmit:e=>{e.preventDefault(),u()}},a?o:null,c,K(`button`,{class:`btn btn-primary btn-icon`,type:`submit`,"aria-label":this.t(`sendReply`),title:this.t(`sendReply`),disabled:!!t.sendingReply},q(X.send))))}positionCard(){let e=this.uiLayer.querySelector(`[data-card]`);if(!e||e.classList.contains(`sheet`))return;let t=null;if(this.card?.kind===`composer`){let{draft:e}=this.card;t=this.anchorPoint(e.anchor,e.element,e.range)}else if(this.card?.kind===`thread`){let e=this.comments.find(e=>this.card?.kind===`thread`&&e._id===this.card.id);t=e?this.pinPositions.get(e._id)??this.pinPoint(e):null}let n=e.offsetWidth||320,r=e.offsetHeight||160,i=window.innerWidth,a=window.innerHeight,o,s;if(t)o=t.x+36,s=t.y-28,o+n>i-12&&(o=t.x-n-12);else{let{position:e}=this.config;o=e.endsWith(`left`)?16:i-n-16,s=e.startsWith(`top`)?72:a-r-72}o=Math.max(12,Math.min(o,i-n-12)),s=Math.max(12,Math.min(s,a-r-12)),e.style.left=`${Math.round(o)}px`,e.style.top=`${Math.round(s)}px`}focusComposer(){requestAnimationFrame(()=>{this.uiLayer.querySelector(this.name?`[data-focus-key="body"]`:`[data-focus-key="name"]`)?.focus()})}};function Ki(e){let t=[e.convexUrl,e.convexSiteUrl].flatMap(e=>{try{return[new URL(e).origin]}catch{return[]}});return e=>{try{return t.includes(new URL(e,location.href).origin)}catch{return!1}}}let Q=null;function qi(e,t){let n={destroy(){}};if(typeof window>`u`||typeof document>`u`)return n;if(!ne(e.project))return console.warn(`[nuni] "${e.project}" is not a valid project ID. Run \`npx @nuniapp/cli@latest init\` to get one.`),n;if(Q?.project===e.project)return Ji(Q);Q&&Yi(Q);let r=y(e),i={project:e.project,widget:null,collectors:ye(r.capture,Ki(r)),timer:0,handles:0};Q=i;let a=()=>{if(Q===i){if(!document.body){i.timer=window.setTimeout(a,50);return}i.widget=new Gi(r,{collectors:i.collectors,loadScreenshot:r.capture.screenshot?t.loadScreenshot:null}),i.widget.start()}},o=window.requestIdleCallback;return o?o(a,{timeout:1500}):i.timer=window.setTimeout(a,1),Ji(i)}function Ji(e){e.handles++;let t=!1;return{destroy(){t||(t=!0,e.handles--,e.handles<=0&&Q===e&&Yi(e))}}}function Yi(e){clearTimeout(e.timer),e.widget?.destroy(),e.widget=null,e.collectors.stop(),Q===e&&(Q=null)}let Xi=document.currentScript??document.querySelector(`script[data-project][src*='nuni']`),Zi=null;function Qi(){return Zi??(Zi=new Promise(e=>{if(window.__nuniScreenshot)return e(window.__nuniScreenshot);let t=document.createElement(`script`);t.src=new URL(`nuni-screenshot.global.js`,Xi.src).href,t.async=!0,t.onload=()=>e(window.__nuniScreenshot??null),t.onerror=()=>{Zi=null,e(null)},document.head.appendChild(t)})),Zi}function $i(e){return qi(e,{loadScreenshot:Xi?.src?Qi:null})}window.Nuni={init:$i,version:`0.1.6`};function ea(e){if(e!==void 0)return!/^(false|0|off|no)$/i.test(e.trim())}let $=Xi?.dataset;$?.project&&$i({project:$.project,convexUrl:$.convexUrl,convexSiteUrl:$.convexSiteUrl,appUrl:$.appUrl,pageKey:$.pageKey,position:$.position,accentColor:$.accentColor,theme:$.theme,label:$.label,hotkey:$.hotkey===void 0?void 0:ea($.hotkey)!==!1&&$.hotkey,zIndex:$.zIndex===void 0?void 0:Number($.zIndex),locale:$.locale,capture:{console:ea($.captureConsole),network:ea($.captureNetwork),dom:ea($.captureDom),screenshot:ea($.captureScreenshot)}})})();
|
|
716
|
+
`,this.markLayer=K(`div`,{class:`marks`,"aria-hidden":`true`}),this.pinLayer=K(`div`,{class:`pins`}),this.overlayLayer=K(`div`,{class:`overlay`}),this.uiLayer=K(`div`,{class:`ui`}),this.selectButton=K(`button`,{class:`select-btn`,type:`button`,hidden:!0,title:this.withKey(`commentSelection`,`commentSelectionKey`),onmousedown:e=>e.preventDefault(),onpointerdown:e=>e.preventDefault(),onclick:()=>this.commentOnSelection()},q(Y.comment),this.t(`comment`)),this.live=K(`div`,{class:`sr`,role:`status`,"aria-live":`polite`}),this.root.append(r,this.markLayer,this.pinLayer,this.overlayLayer,this.uiLayer,this.selectButton,this.live),this.uiLayer.addEventListener(`keydown`,e=>this.trapFocus(e)),this.root.addEventListener(`click`,e=>{this.toolbarDropped&&(e.preventDefault(),e.stopPropagation())},!0),this.api=new mi(e)}t(e,t){return this.i18n.t(e,t)}withKey(e,t){let n=this.config.hotkey;return n?this.t(t,{key:n.toUpperCase()}):this.t(e)}applyAppearance(){let{theme:e,accentColor:t,zIndex:n}=this.config;this.host.dataset.position=this.position,this.host.dataset.theme=e,n!==null&&(this.host.style.zIndex=String(n));let r=t?vi(t):null;if(!r)return;let[i,a,o]=r;this.host.style.setProperty(`--n-accent`,`rgb(${i}, ${a}, ${o})`),this.host.style.setProperty(`--n-accent-soft`,`rgba(${i}, ${a}, ${o}, 0.14)`),this.host.style.setProperty(`--n-accent-fg`,yi(r))}start(){document.body.appendChild(this.host),Ei(this.secret).then(e=>{this.secretHash=e,this.render()}),this.api.touch(location.origin),this.cleanups.push(this.api.onStatus(e=>{this.status=e,this.render()})),this.cleanups.push(this.api.onPages(e=>{this.pages=e,this.render()})),this.ownerToken&&this.watchSession(this.ownerToken),this.readDeepLink(),this.subscribePage(),this.cleanups.push(Ti(()=>{this.readDeepLink(),this.subscribePage()}));let e=e=>this.onKeyDown(e),t=()=>this.scheduleLayout(),n=e=>this.onMessage(e);window.addEventListener(`keydown`,e,!0),window.addEventListener(`scroll`,t,{capture:!0,passive:!0}),window.addEventListener(`resize`,t,{passive:!0}),window.addEventListener(`message`,n);let r=()=>this.scheduleSelection(),i=e=>{e.composedPath().includes(this.host)||(this.pointerDown=!0,this.scheduleSelection(),this.closeCardFromOutside(e))},a=()=>{this.pointerDown=!1,this.scheduleSelection()};document.addEventListener(`selectionchange`,r),document.addEventListener(`pointerdown`,i,!0),document.addEventListener(`pointerup`,a,!0),this.cleanups.push(()=>{document.removeEventListener(`selectionchange`,r),document.removeEventListener(`pointerdown`,i,!0),document.removeEventListener(`pointerup`,a,!0),cancelAnimationFrame(this.selectionFrame)}),this.cleanups.push(()=>{window.removeEventListener(`keydown`,e,!0),window.removeEventListener(`scroll`,t,!0),window.removeEventListener(`resize`,t),window.removeEventListener(`message`,n)});let o=new MutationObserver(e=>{e.every(e=>this.host.contains(e.target)||e.target===this.host)||this.scheduleResolve()});o.observe(document.body,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:[`class`,`style`,`hidden`,`open`,`id`]});let s=new ResizeObserver(()=>this.scheduleLayout());s.observe(document.documentElement),this.cleanups.push(()=>{o.disconnect(),s.disconnect()}),this.render()}destroy(){this.setPicking(!1),this.endToolbarDrag?.(),this.pageUnsub?.(),this.sessionUnsub?.(),this.ownerDetailUnsub?.(),this.threadUnsub?.(),this.resolveRun++;for(let e of this.scopeWatchers.values())e();this.scopeWatchers.clear();for(let e of this.cleanups)e();cancelAnimationFrame(this.layoutFrame),clearTimeout(this.resolveTimer),clearTimeout(this.toastTimer),this.host.remove(),this.api.close()}currentPageKey(){let e=new URL(location.href);return this.config.getPageKey(e)}subscribePage(){let e=this.currentPageKey();e===this.pageKey&&this.pageUnsub||(this.pageKey=e,this.pageUnsub?.(),this.comments=[],this.extraComment=null,this.loaded=!1,this.placements.clear(),this.card=null,this.activeId=null,this.pageUnsub=this.api.onPage(e,e=>{let t=this.extraComment,n=t&&!e.some(e=>e._id===t._id)?[...e,t]:e;this.comments=n.sort((e,t)=>e.createdAt-t.createdAt),this.loaded=!0,this.resolvePlacements(this.placements.size>0,this.deepLinkId??void 0),this.openDeepLink(),this.render()},()=>{}),this.render())}watchSession(e){this.sessionUnsub?.(),this.sessionUnsub=this.api.onSession(e,e=>{e.valid?this.ownerName=e.ownerName??this.t(`owner`):(this.ownerName=null,this.ownerToken=null,X(Z.session(this.config.project),null),this.sessionUnsub?.(),this.sessionUnsub=null),this.render()})}syncOwnerDetail(){let e=this.ownerToken,t=this.card?.kind===`thread`&&this.isOwner&&e?this.card.id:null;t!==this.ownerDetailId&&(this.ownerDetailUnsub?.(),this.ownerDetailUnsub=null,this.ownerDetail=null,this.ownerDetailLoaded=!1,this.ownerDetailId=t,t&&e&&(this.ownerDetailUnsub=this.api.onOwnerComment(t,e,e=>{this.ownerDetailId===t&&(this.ownerDetail=e,this.ownerDetailLoaded=!0,this.render())})))}syncThread(){let e=this.card?.kind===`thread`?this.card.id:null;e!==this.threadId&&(this.threadUnsub?.(),this.threadUnsub=null,this.thread=null,this.threadId=e,e&&(this.threadUnsub=this.api.onThread(e,t=>{this.threadId===e&&(this.thread=t,this.render())})))}get isOwner(){return!!(this.ownerToken&&this.ownerName)}isMine(e){return!!this.secretHash&&e.authorKeyHash===this.secretHash}visibleComments(){return this.comments.filter(e=>e.status===(this.panelOpen&&this.tab===`resolved`?`resolved`:`open`)||this.card?.kind===`thread`&&this.card.id===e._id)}scheduleResolve(){clearTimeout(this.resolveTimer),this.resolveTimer=window.setTimeout(()=>this.resolvePlacements(!0),200)}stillPlaced(e){let t=this.placements.get(e._id);if(!t?.element?.isConnected)return!1;let n=e.anchor.quote;if(n)return t.range!==void 0&&Li(t.range.toString())===n.exact;let r=x(t.element),i=e.anchor.text;return!i||r===i||Fe(r,i)>.8}resolvePlacements(e,t){let n=++this.resolveRun,r=new Set(this.comments.map(e=>e._id));for(let e of this.placements.keys())r.has(e)||this.placements.delete(e);let i=this.comments.filter(t=>!(e&&this.stillPlaced(t))),a=t?i.findIndex(e=>e._id===t):-1;a>0&&i.unshift(...i.splice(a,1));let o=Nt(),s={isIgnored:this.isIgnored,document},c=()=>{if(n!==this.resolveRun)return;let t=performance.now();for(;i.length;){let e=i.shift(),n=Zt(e.anchor,document,s,o);if(this.placements.set(e._id,{element:n.element,confidence:n.confidence,range:n.range}),performance.now()-t>8)break}this.watchScopes(),this.renderPins(),this.layout(),i.length?Ri(c):(e||n>1)&&this.panelOpen&&this.placementSummary()!==this.shownPlacements&&this.render()};c()}placementSummary(){return this.comments.map(e=>{let t=this.placements.get(e._id);return t?.element?t.confidence===`low`?`~`:`+`:`-`}).join(``)}watchScopes(){let e=/* @__PURE__ */ new Set;for(let{element:t}of this.placements.values()){let n=t;for(let t=0;n&&t<8;t++){let t=Ze(n);if(t===document)break;e.add(t),n=S(t)?t.host:$e(t)}}for(let[t,n]of this.scopeWatchers)e.has(t)||(n(),this.scopeWatchers.delete(t));for(let t of e)this.scopeWatchers.has(t)||this.scopeWatchers.set(t,this.watchScope(t))}watchScope(e){let t=new MutationObserver(()=>this.scheduleResolve()),n=S(e)?null:e;t.observe(n?n.body??n.documentElement:e,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:[`class`,`style`,`hidden`,`open`,`id`]});let r=()=>this.scheduleLayout(),i=n?.defaultView??e;return i.addEventListener(`scroll`,r,{capture:!0,passive:!0}),n?.defaultView?.addEventListener(`resize`,r,{passive:!0}),()=>{t.disconnect(),i.removeEventListener(`scroll`,r,!0),n?.defaultView?.removeEventListener(`resize`,r)}}pinPoint(e){let t=this.placements.get(e._id),n=t?.element;return!n||!Ae(n)||nt(n,document).clipped?null:this.anchorPoint(e.anchor,n,t.range)}anchorPoint(e,t,n){if(n&&n.startContainer.ownerDocument===document){let e=Fi(n).at(-1);if(e)return{x:e.right,y:e.top+e.height/2}}let r=nt(t,document);return{x:r.left+e.offset.x*r.width,y:r.top+e.offset.y*r.height}}renderMarks(){let e=[],t=(t,n)=>{let r=K(`div`,{class:n});Object.assign(r.style,{left:`${t.left}px`,top:`${t.top}px`,width:`${t.width}px`,height:`${t.height}px`}),e.push(r)},n=(e,n,r,i)=>{if(n){if(r&&r.startContainer.ownerDocument===document)for(let e of Fi(r))t(e,i?`mark mark-active`:`mark`);if(i){let r=Ii(e,n);r&&t(r,`area`)}}};if(this.card?.kind===`composer`){let{draft:e}=this.card;n(e.anchor,e.element,e.range,!0)}for(let e of this.visibleComments()){let t=this.placements.get(e._id),r=this.activeId===e._id;(r||e.status===`open`&&e.anchor.quote)&&(this.pins.get(e._id)?.hidden||n(e.anchor,t?.element,t?.range,r))}this.markLayer.replaceChildren(...e)}scheduleLayout(){this.layoutFrame||(this.layoutFrame=requestAnimationFrame(()=>{this.layoutFrame=0,this.layout()}))}layout(){let e=window.innerWidth,t=window.innerHeight,n=[];this.pinPositions.clear();for(let r of this.visibleComments()){let i=this.pins.get(r._id);if(!i)continue;let a=this.pinPoint(r);if(i.hidden=!(a&&a.x>=-10&&a.y>=-10&&a.x<=e+10&&a.y<=t+10),!a)continue;let o=a.y,s=a.x;for(;n.some(e=>Math.abs(e.x-s)<14&&Math.abs(e.y-o)<14);)s+=18;n.push({x:s,y:o}),this.pinPositions.set(r._id,{x:s,y:o}),i.style.transform=`translate(${Math.round(s)}px, ${Math.round(o)}px)`}this.renderMarks(),this.positionCard(),this.picking&&(this.hoverEl||this.dragBox)&&this.renderHighlight(),this.placeSelectButton()}setPicking(e){if(this.picking===e)return;this.picking=e;let t=document.documentElement;if(this.dragStart=null,this.dragBox=null,e){this.card=null,window.matchMedia(Bi).matches&&(this.panelOpen=!1),this.pickDocs=[document,...zi(document)];for(let e of this.pickDocs){e.documentElement.classList.add(Ni),this.injectCursorStyle(e),e.addEventListener(`pointermove`,this.onPickMove,!0),e.addEventListener(`click`,this.onPickClick,!0);for(let t of Pi)e.addEventListener(t,this.swallow,{capture:!0,passive:!1});e!==document&&e.addEventListener(`keydown`,this.onFrameKey,!0)}}else{t.classList.remove(Ni),this.hoverEl=null;for(let e of this.pickDocs){e.documentElement?.classList.remove(Ni),e.removeEventListener(`pointermove`,this.onPickMove,!0),e.removeEventListener(`click`,this.onPickClick,!0);for(let t of Pi)e.removeEventListener(t,this.swallow,!0);e.removeEventListener(`keydown`,this.onFrameKey,!0)}this.pickDocs=[]}this.render()}injectCursorStyle(e){if(e.getElementById(`nuni-cursor-style`))return;let t=e.createElement(`style`);t.id=`nuni-cursor-style`,t.textContent=`html.${Ni}, html.${Ni} * { cursor: crosshair !important; }`,(e.head??e.documentElement).appendChild(t),this.cleanups.push(()=>t.remove())}fromPage(e){let t=e.composedPath();if(t.includes(this.host))return null;let n=t[0]??e.target;return n&&n.nodeType===1?n:null}commentOnArea(e){let t=At(document,e,this.isIgnored),n=Mt(t,e,{ignoreAttributePrefixes:[],document});this.openComposer({anchor:n,element:t})}pageSelection(){let e=document.getSelection();if(!e||e.isCollapsed||!e.rangeCount)return null;let t=e.getRangeAt(0),n=t.commonAncestorContainer,r=n.nodeType===1?n:n.parentElement;return!r||r===this.host||this.host.contains(r)||r.closest(`input, textarea, select, [contenteditable]`)||r.closest(`[data-nuni]`)?null:Li(t.toString())?t:null}commentOnSelection(){let e=this.pageSelection();if(!e)return;let t=kt(e,{ignoreAttributePrefixes:[],document});if(!t)return;let n=e.cloneRange();document.getSelection()?.removeAllRanges(),this.selection=null,this.openComposer({...t,range:n})}scheduleSelection(){this.selectionFrame||(this.selectionFrame=requestAnimationFrame(()=>{this.selectionFrame=0,this.selection=this.picking||this.pointerDown?null:this.pageSelection(),this.placeSelectButton()}))}placeSelectButton(){let e=this.selectButton,t=this.selection,n=t?Fi(t).at(-1):void 0,r=window.innerWidth,i=window.innerHeight;if(!t||!n||n.bottom<0||n.top>i){e.hidden=!0;return}e.hidden=!1;let a=e.offsetWidth||96,o=e.offsetHeight||32,s=n.bottom+8;s+o>i-8&&(s=n.top-o-8);let c=Math.max(8,Math.min(n.right-a/2,r-a-8));e.style.transform=`translate(${Math.round(c)}px, ${Math.round(s)}px)`}openComposer(e){let{element:t}=e;if(this.setPicking(!1),this.config.capture.dom)try{e.dom=we(t)}catch{}this.card={kind:`composer`,draft:e},this.activeId=null,this.render(),this.focusComposer(),e.screenshot=this.takeScreenshot(e)}async takeScreenshot(e){let t=this.runtime.loadScreenshot;if(!t||e.element.ownerDocument!==document)return null;let n=getComputedStyle(this.host).getPropertyValue(`--n-accent`).trim()||`#d6246e`;try{await new Promise(e=>setTimeout(e,60));let r=await t(),{range:i,anchor:a,element:o}=e,s=i?()=>i.getBoundingClientRect():a.region?()=>{let e=Ii(a,o);return{left:e.left,top:e.top,right:e.left+e.width,bottom:e.top+e.height}}:void 0;return r?await r(o,{exclude:this.host,accent:n,focus:s}):null}catch{return null}}collectContext(e){let{collectors:t}=this.runtime,n={},r=t.console(),i=t.network();return r.length&&(n.console=r),i.length&&(n.network=i),e.dom&&(n.dom=e.dom),Object.keys(n).length?n:void 0}async attachScreenshot(e,t){try{let n=await t;n&&await this.api.uploadScreenshot(e,this.secret,n)}catch{}}copyForAgent(e){let t=this.ownerDetail?._id===e._id?this.ownerDetail:null,n=this.threadId===e._id?this.thread?.replies:void 0;_i(m(t??{...e,replies:n},{includeContext:!!t})).then(e=>this.showToast(e?this.t(`copied`):this.t(`copyFailed`)))}renderHighlight(){if(this.overlayLayer.replaceChildren(),!this.picking)return;let e=window.matchMedia(Bi).matches;if(this.overlayLayer.append(K(`div`,{class:`pick-hint`},e?this.t(`pickHintMobile`):[K(`span`,{},this.t(`pickHint`)),K(`span`,{class:`pick-keys`},this.t(`pickHintKeys`))])),this.dragBox){let e=K(`div`,{class:`highlight drag-box`});Object.assign(e.style,{left:`${this.dragBox.left}px`,top:`${this.dragBox.top}px`,width:`${this.dragBox.width}px`,height:`${this.dragBox.height}px`}),this.overlayLayer.append(e);return}let t=this.hoverEl;if(!t||t===t.ownerDocument.documentElement)return;let n=nt(t,document),r=K(`div`,{class:`highlight`},K(`span`,{class:`highlight-label`},Ui(t)));Object.assign(r.style,{left:`${n.left-2}px`,top:`${n.top-2}px`,width:`${n.width+4}px`,height:`${n.height+4}px`}),this.overlayLayer.append(r)}onKeyDown(e){let t=e.composedPath().includes(this.host);if(e.key===`Escape`){if(this.confirming)this.answer(!1);else if(this.picking)this.setPicking(!1);else if(this.card)this.closeCard();else if(this.panelOpen&&this.search)this.search=``,this.render();else if(this.panelOpen)this.togglePanel(!1);else return;e.stopPropagation();return}if(Vi(e.composedPath()[0]??e.target)||e.metaKey||e.ctrlKey||e.altKey||this.picking&&!t&&this.onPickKey(e)||t&&this.confirming||e.repeat)return;let n=this.config.hotkey;n&&e.key.toLowerCase()===n&&(e.preventDefault(),!this.picking&&this.pageSelection()?this.commentOnSelection():this.setPicking(!this.picking))}onPickKey(e){if(![`ArrowUp`,`ArrowDown`,`ArrowLeft`,`ArrowRight`,`Enter`].includes(e.key))return!1;e.preventDefault(),e.stopPropagation();let t=this.hoverEl;if(!t||!t.isConnected)return this.movePickTo(this.keyboardStart()),!0;if(e.key===`Enter`){let e=t.getBoundingClientRect(),n=Dt(t,{x:e.left+e.width/2,y:e.top+e.height/2},{ignoreAttributePrefixes:[],document});return this.openComposer({anchor:n,element:t}),!0}let n=t=>{for(;t&&(t===this.host||!Ae(t));)t=e.key===`ArrowLeft`?t.previousElementSibling:t.nextElementSibling;return t},r=t.ownerDocument.body;return e.key===`ArrowUp`?t.parentElement&&t!==r&&(t=t.parentElement):t=e.key===`ArrowDown`?n(t.firstElementChild)??t:e.key===`ArrowLeft`?n(t.previousElementSibling)??t:n(t.nextElementSibling)??t,this.movePickTo(t),!0}keyboardStart(){let e=document.activeElement;if(e&&e!==document.body&&e!==this.host)return e;let t=document.elementsFromPoint(window.innerWidth/2,window.innerHeight/2).find(e=>!this.isIgnored(e));return t?en(t):document.body}movePickTo(e){this.hoverEl=e,e.scrollIntoView({block:`nearest`,inline:`nearest`}),this.live.textContent=this.t(`picked`,{element:Ui(e)}),this.renderHighlight()}trapFocus(e){if(e.key!==`Tab`)return;let t=e.composedPath()[0]?.closest?.(`.confirm, [data-card], .panel`);if(!t)return;let n=Array.from(t.querySelectorAll(`button:not([disabled]), input, textarea, a[href], [tabindex="0"]`)).filter(e=>!e.closest(`[hidden]`));if(!n.length)return;let r=n[0],i=n[n.length-1],a=this.root.activeElement;e.shiftKey&&a===r?(e.preventDefault(),i.focus()):!e.shiftKey&&a===i&&(e.preventDefault(),r.focus())}keepFocus(){if(this.returnFocus)return;let e=this.root.activeElement;if(e){this.returnFocus=e.dataset.focusKey??e;return}let t=document.activeElement;this.returnFocus=t&&t!==document.body&&t!==this.host?t:null}restoreFocus(){let e=this.returnFocus;this.returnFocus=null;let t=typeof e==`string`?this.uiLayer.querySelector(`[data-focus-key="${e}"]`):e;t?.isConnected&&t.focus({preventScroll:!0})}ask(e,t){this.confirming?.done(!1);let n=this.root.activeElement?.dataset.focusKey??null;return new Promise(r=>{this.confirming={message:e,action:t,done:r,from:n},this.focusNext=`[data-focus-key="confirm-cancel"]`,this.render()})}answer(e){let t=this.confirming;t&&(this.confirming=null,!e&&t.from&&(this.focusNext=`[data-focus-key="${t.from}"]`),this.render(),t.done(e))}renderConfirm(){let e=this.confirming;return e?K(`div`,{class:`confirm-backdrop`,onclick:()=>this.answer(!1)},K(`div`,{class:`confirm`,role:`alertdialog`,"aria-modal":`true`,"aria-labelledby":`nuni-confirm-text`,onclick:e=>e.stopPropagation()},K(`p`,{id:`nuni-confirm-text`},e.message),K(`div`,{class:`row`},K(`span`,{class:`spacer`}),K(`button`,{class:`btn btn-ghost`,type:`button`,"data-focus-key":`confirm-cancel`,onclick:()=>this.answer(!1)},this.t(`cancel`)),K(`button`,{class:`btn btn-danger-solid`,type:`button`,"data-focus-key":`confirm-ok`,onclick:()=>this.answer(!0)},e.action)))):null}openClaim(){let e=new URL(`${this.config.appUrl}/dashboard/claim`);e.searchParams.set(`project`,this.config.project),e.searchParams.set(`origin`,location.origin),window.open(e.toString(),`nuni-claim`,`popup,width=480,height=680`)||(location.href=e.toString())}onMessage(e){let t;try{t=new URL(this.config.appUrl).origin}catch{return}if(e.origin!==t)return;let n=e.data;n&&n.type===`nuni:session`&&n.project===this.config.project&&typeof n.token==`string`&&n.token.startsWith(`nuni_s_`)&&(this.ownerToken=n.token,X(Z.session(this.config.project),n.token),this.watchSession(n.token),this.showToast(this.t(`signedIn`)))}readDeepLink(){let e=new URL(location.href),t=e.searchParams.get(`nuni`);t&&(this.deepLinkId=t,e.searchParams.delete(`nuni`),history.replaceState(history.state,``,e.toString()))}openDeepLink(){let e=this.deepLinkId;if(!e||!this.loaded)return;this.deepLinkId=null;let t=this.comments.find(t=>t._id===e);if(t){this.focusDeepLinked(t);return}this.api.getComment(e).then(e=>{if(!e||e.page.path!==this.pageKey){this.showToast(this.t(`linkGone`));return}this.extraComment=e,this.comments=[...this.comments.filter(t=>t._id!==e._id),e],this.resolvePlacements(!1,e._id),this.focusDeepLinked(e)})}focusDeepLinked(e){this.focusComment(e._id)}focusComment(e){let t=this.placements.get(e),n=this.comments.find(t=>t._id===e);t?.element&&n&&Ai(t.element,()=>this.anchorPoint(n.anchor,t.element,t.range)),this.openThread(e),window.matchMedia(Bi).matches&&(this.panelOpen=!1),this.render(),setTimeout(()=>this.scheduleLayout(),400)}async submitDraft(e,t,r){let i=r.trim().slice(0,_.nameMaxLength),a=t.trim();if(!i)return this.setDraftError(e,this.t(`enterName`));if(!a)return this.setDraftError(e,this.t(`writeFirst`));if(a.length>_.bodyMaxLength)return this.setDraftError(e,this.t(`commentTooLong`,{count:_.bodyMaxLength}));this.name=i,X(Z.name,i),e.sending=!0,e.error=void 0,this.render();let o=n(location.href),s=e.screenshot;try{let t=await this.api.createComment({body:a,authorName:i,authorSecret:this.secret,page:{...o,path:this.pageKey,title:document.title.slice(0,300)},anchor:e.anchor,viewport:{w:window.innerWidth,h:window.innerHeight,dpr:window.devicePixelRatio||1},context:this.collectContext(e)});s&&this.attachScreenshot(t,s),this.placements.set(t,{element:e.element,confidence:`exact`,range:e.range}),this.card?.kind===`composer`&&this.card.draft===e&&(this.card=null),this.showToast(this.t(`added`))}catch(t){e.sending=!1,e.error=t instanceof G?t.message:this.t(`postFailed`)}this.render()}setDraftError(e,t){e.error=t,this.render()}async act(e,t,n){let r=this.card;r?.kind===`thread`&&(r.busy=!0,r.error=void 0,this.render());try{return await t(),n&&this.showToast(n),this.card?.kind===`thread`&&this.card.id===e&&(this.card.busy=!1,this.card.editing=!1),this.render(),!0}catch(t){return this.card?.kind===`thread`&&this.card.id===e&&(this.card.busy=!1,this.card.error=t instanceof Error?t.message:this.t(`failed`)),this.render(),!1}}resolveComment(e){let t=this.ownerToken;t&&this.act(e._id,()=>this.api.resolve(e._id,t),this.t(`resolved`)).then(t=>{t&&!(this.panelOpen&&this.tab===`resolved`)&&this.card?.kind===`thread`&&this.card.id===e._id&&this.closeCard()})}reopenComment(e){let t=this.ownerToken;t&&this.act(e._id,()=>this.api.reopen(e._id,t),this.t(`reopened`))}async deleteComment(e){if(!await this.ask(this.t(`confirmDeleteComment`),this.t(`delete`)))return;let t=this.ownerToken,n=this.isMine(e)?()=>this.api.deleteOwn(e._id,this.secret):t?()=>this.api.remove(e._id,t):null;n&&this.act(e._id,n,this.t(`deleted`)).then(t=>{t&&(this.extraComment?._id===e._id&&(this.extraComment=null),this.comments=this.comments.filter(t=>t._id!==e._id),this.placements.delete(e._id),this.closeCard())})}isMyReply(e){return!!this.secretHash&&e.authorKeyHash===this.secretHash}async sendReply(e,t,n){let r=this.card;if(r?.kind!==`thread`||r.id!==e._id)return;let i=(this.isOwner?this.ownerName:n)?.trim().slice(0,_.nameMaxLength),a=t.trim();if(a){if(!i){r.error=this.t(`enterName`),this.render();return}if(a.length>_.bodyMaxLength){r.error=this.t(`replyTooLong`,{count:_.bodyMaxLength}),this.render();return}this.isOwner||(this.name=i,X(Z.name,i)),r.sendingReply=!0,r.error=void 0,this.render();try{await this.api.createReply({commentId:e._id,body:a,authorName:i,authorSecret:this.secret,sessionToken:this.ownerToken??void 0});let t=this.uiLayer.querySelector(`[data-focus-key="reply"]`);t&&(t.value=``)}catch(e){r.error=e instanceof G?e.message:this.t(`replyFailed`)}r.sendingReply=!1,this.render()}}toggleReaction(e,t,n){this.api.toggleReaction(e._id,t,n,this.secret).catch(t=>{this.card?.kind===`thread`&&this.card.id===e._id&&(this.card.error=t instanceof Error?t.message:this.t(`reactFailed`),this.render())})}async deleteReply(e,t){if(!await this.ask(this.t(`confirmDeleteReply`),this.t(`delete`)))return;let n=this.ownerToken,r=this.isMyReply(t)?()=>this.api.deleteReply(t._id,this.secret):n?()=>this.api.removeReply(t._id,n):null;r&&this.act(e._id,r,this.t(`replyDeleted`))}saveReplyEdit(e,t,n){this.act(e._id,()=>this.api.editReply(t._id,this.secret,n),this.t(`saved`)).then(e=>{e&&this.card?.kind===`thread`&&(this.card.replyEditing=void 0,this.render())})}saveEdit(e,t){this.act(e._id,()=>this.api.editOwn(e._id,this.secret,t),this.t(`saved`))}showToast(e){this.toast=e,clearTimeout(this.toastTimer),this.toastTimer=window.setTimeout(()=>{this.toast=null,this.render()},2400),this.render()}togglePanel(e=!this.panelOpen){e!==this.panelOpen&&(this.panelOpen=e,e?(this.keepFocus(),this.focusNext=`.panel [role="tab"][aria-selected="true"]`,window.matchMedia(Bi).matches&&(this.card=null)):this.search=``,this.render(),e&&this.uiLayer.querySelector(`.panel .item[aria-current="true"]`)?.scrollIntoView({block:`nearest`}),!e&&!this.card&&this.restoreFocus())}closeCardFromOutside(e){this.card&&!this.picking&&!this.confirming&&e.isPrimary&&(qi(e)||[...this.uiLayer.querySelector(`[data-card]`)?.querySelectorAll(`textarea`)??[]].some(e=>e.value.trim())||(this.panelOpen||(this.returnFocus=null),this.closeCard()))}closeCard(){let e=this.card!==null;this.card=null,this.activeId=null,this.render(),e&&!this.panelOpen&&this.restoreFocus()}openThread(e){this.keepFocus(),this.activeId=e,this.lastViewedId=e,X(Z.lastViewed(this.config.project),e),this.card={kind:`thread`,id:e},this.focusNext=`[data-card="thread"] .card-close`}render(){this.syncOwnerDetail(),this.syncThread(),this.renderPins(),this.renderUi(),this.renderHighlight(),this.layout()}renderPins(){let e=this.visibleComments(),t=new Set(e.map(e=>e._id));for(let[e,n]of this.pins)t.has(e)||(n.remove(),this.pins.delete(e));for(let t of e){let e=this.pins.get(t._id);if(!e){e=K(`button`,{class:`pin`,type:`button`,hidden:!0});let n=t._id;e.addEventListener(`click`,e=>{e.stopPropagation(),this.card?.kind===`thread`&&this.card.id===n?this.closeCard():(this.openThread(n),this.render())}),this.pins.set(t._id,e),this.pinLayer.append(e)}e.textContent=hi(t.authorName),e.style.background=gi(t.authorName),e.setAttribute(`aria-label`,this.t(`pinLabel`,{name:t.authorName,body:t.body.slice(0,80)})),t.replyCount?e.dataset.replies=String(t.replyCount):delete e.dataset.replies,e.dataset.status=t.status,e.dataset.active=String(this.activeId===t._id),e.dataset.confidence=this.placements.get(t._id)?.confidence??`lost`}if(this.pinLayer.querySelector(`.pin-draft`)?.remove(),this.card?.kind===`composer`){let{draft:e}=this.card,{x:t,y:n}=this.anchorPoint(e.anchor,e.element,e.range),r=K(`div`,{class:`pin pin-draft pin-pending`,"aria-hidden":`true`},this.name?hi(this.name):`+`);r.style.background=this.name?gi(this.name):`var(--n-accent)`,r.style.transform=`translate(${Math.round(t)}px, ${Math.round(n)}px)`,this.pinLayer.append(r)}}renderUi(){this.shownPlacements=this.placementSummary();let e=[this.renderToolbar()];this.panelOpen&&e.push(this.renderPanel());let t=this.renderCard();t&&e.push(t),this.toast&&e.push(K(`div`,{class:`toast`,role:`status`},this.toast));let n=this.renderConfirm();n&&e.push(n);let r=this.root.activeElement,i=r?.dataset.focusKey,a=r instanceof HTMLTextAreaElement||r instanceof HTMLInputElement?{start:r.selectionStart,end:r.selectionEnd}:null;this.uiLayer.replaceChildren(...e);let o=this.focusNext;this.focusNext=null;let s=o?this.uiLayer.querySelector(o):null;if(s)s.focus();else if(i){let e=this.uiLayer.querySelector(`[data-focus-key="${i}"]`);e?.focus(),a&&(e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement)&&e.setSelectionRange(a.start,a.end)}this.positionCard()}renderToolbar(){let e=this.comments.filter(e=>e.status===`open`).length,t=this.toolbarDrag?.moving?this.toolbarDrag:null;return K(`div`,{class:`toolbar`,role:`toolbar`,"aria-label":this.t(`toolbar`),"data-dragging":!!t,style:t&&`transform: translate(${t.dx}px, ${t.dy}px)`,onpointerdown:e=>this.startToolbarDrag(e)},K(`button`,{class:`tb-btn`,type:`button`,"aria-pressed":String(this.picking),"data-focus-key":`tb-comment`,"aria-label":this.picking?this.t(`cancelAdding`):this.t(`addComment`),title:this.withKey(`addComment`,`addCommentKey`),onclick:()=>this.setPicking(!this.picking)},q(Y.comment),K(`span`,{class:`tb-label`},this.picking?this.t(`pickElement`):this.config.label??this.t(`comment`))),K(`button`,{class:`tb-btn`,type:`button`,"aria-pressed":String(this.panelOpen),"data-focus-key":`tb-panel`,"aria-label":this.t(`openCount`,{count:e}),title:this.t(`allComments`),onclick:()=>this.togglePanel()},q(Y.list),K(`span`,{class:`tb-count`},String(e))))}startToolbarDrag(e){if(e.button!==0||!e.isPrimary)return;this.endToolbarDrag?.();let t={id:e.pointerId,x:e.clientX,y:e.clientY,dx:0,dy:0,moving:!1};this.toolbarDrag=t;let n=()=>this.uiLayer.querySelector(`.toolbar`),r=e=>{e.pointerId===t.id&&(t.dx=e.clientX-t.x,t.dy=e.clientY-t.y,!(!t.moving&&Math.hypot(t.dx,t.dy)<5)&&(t.moving||(t.moving=!0,this.host.dataset.dragging=``,n()?.setAttribute(`data-dragging`,``)),e.preventDefault(),n()?.style.setProperty(`transform`,`translate(${t.dx}px, ${t.dy}px)`)))},i=e=>{e.pointerId===t.id&&(this.endToolbarDrag?.(),t.moving&&this.dropToolbar(n(),!0))},a=e=>{e instanceof PointerEvent&&e.pointerId!==t.id||(this.endToolbarDrag?.(),t.moving&&this.dropToolbar(n(),!1))};window.addEventListener(`pointermove`,r,!0),window.addEventListener(`pointerup`,i,!0),window.addEventListener(`pointercancel`,a,!0),window.addEventListener(`blur`,a),this.endToolbarDrag=()=>{window.removeEventListener(`pointermove`,r,!0),window.removeEventListener(`pointerup`,i,!0),window.removeEventListener(`pointercancel`,a,!0),window.removeEventListener(`blur`,a),delete this.host.dataset.dragging,this.toolbarDrag=null,this.endToolbarDrag=null}}dropToolbar(e,t){if(this.toolbarDropped=!0,setTimeout(()=>this.toolbarDropped=!1),!e)return;let n=e.getBoundingClientRect();if(t){let e=Ki(n.left+n.width/2,n.top+n.height/2);this.position=e,this.host.dataset.position=e,X(Z.position(this.config.project),e===this.config.position?null:e)}e.removeAttribute(`data-dragging`),e.style.removeProperty(`transform`);let r=e.getBoundingClientRect();matchMedia(`(prefers-reduced-motion: reduce)`).matches||e.animate([{transform:`translate(${n.left-r.left}px, ${n.top-r.top}px)`},{transform:`none`}],{duration:320,easing:`cubic-bezier(0.2, 0.9, 0.3, 1.15)`})}renderPanel(){let e=this.comments.filter(e=>e.status===`open`),t=this.comments.filter(e=>e.status===`resolved`),n=this.search.trim().toLocaleLowerCase(),r=(...e)=>!n||e.some(e=>e?.toLocaleLowerCase().includes(n)),i=(this.tab===`open`?e:t).filter(e=>r(e.body,e.authorName,e.anchor.quote?.exact)),a=i.filter(e=>this.placements.get(e._id)?.element),o=i.filter(e=>!this.placements.get(e._id)?.element),s=this.pages.filter(e=>e.path!==this.pageKey&&r(e.path)),c=e=>K(`button`,{class:`item`,type:`button`,"aria-current":e._id===this.lastViewedId?`true`:null,"data-focus-key":`item-${e._id}`,onclick:()=>this.focusComment(e._id)},K(`div`,{class:`row`},K(`span`,{class:`avatar`,style:`background:${gi(e.authorName)}`},hi(e.authorName)),K(`span`,{class:`author`},e.authorName),K(`span`,{class:`meta`},this.i18n.timeAgo(e.createdAt)+(e.replyCount?` · ${this.t(`replyCount`,{count:e.replyCount})}`:``)),e.page.origin===location.origin?null:K(`span`,{class:`badge`,title:e.page.origin},new URL(e.page.origin).host)),e.anchor.quote?K(`div`,{class:`item-quote`},e.anchor.quote.exact):null,K(`div`,{class:`item-text`},e.body)),l=[];if(this.loaded?!i.length&&n?l.push(K(`div`,{class:`empty`},this.t(`noMatches`,{query:this.search.trim()}))):i.length?(l.push(...a.map(c)),o.length&&(l.push(K(`div`,{class:`section-label`},this.t(`notFoundHere`))),l.push(...o.map(c)))):l.push(K(`div`,{class:`empty`},this.tab===`open`?this.withKey(`noOpen`,`noOpenKey`):this.t(`noResolved`))):l.push(K(`div`,{class:`empty`},this.t(`loading`))),s.length){l.push(K(`div`,{class:`section-label`},this.t(`otherPages`)));for(let e of s.slice(0,20)){let t=Wi(e.path,location);l.push(K(t===null?`div`:`a`,t===null?{class:`item`}:{class:`item`,href:t},K(`div`,{class:`row`},K(`span`,{class:`author`},e.path),K(`span`,{class:`spacer`}),K(`span`,{class:`badge`},this.t(`openOnPage`,{count:e.count})))))}}return K(`div`,{class:`panel`,role:`dialog`,"aria-label":this.t(`comments`)},K(`div`,{class:`panel-head`},K(`div`,{class:`panel-title`},this.t(`comments`)),K(`button`,{class:`btn btn-ghost btn-icon`,type:`button`,"aria-label":this.t(`close`),onclick:()=>this.togglePanel(!1)},q(Y.close))),this.comments.length?K(`div`,{class:`panel-search`},q(Y.search),K(`input`,{class:`field`,type:`search`,value:this.search,placeholder:this.t(`searchComments`),"aria-label":this.t(`searchComments`),"aria-controls":`nuni-panel-list`,"data-focus-key":`panel-search`,oninput:e=>{this.search=e.target.value,this.render()}})):null,K(`div`,{class:`tabs`,role:`tablist`,"aria-label":this.t(`comments`),onkeydown:e=>{let t=e.key;[`ArrowLeft`,`ArrowRight`,`Home`,`End`].includes(t)&&(e.preventDefault(),this.tab=t===`Home`?`open`:t===`End`||this.tab===`open`?`resolved`:`open`,this.focusNext=`[data-focus-key="tab-${this.tab}"]`,this.render())}},[`open`,`resolved`].map(n=>K(`button`,{class:`tab`,role:`tab`,type:`button`,id:`nuni-tab-${n}`,"data-focus-key":`tab-${n}`,"aria-selected":String(this.tab===n),"aria-controls":`nuni-panel-list`,tabindex:this.tab===n?0:-1,onclick:()=>{this.tab=n,this.render()}},n===`open`?this.t(`tabOpen`,{count:e.length}):this.t(`tabResolved`,{count:t.length})))),K(`div`,{class:`panel-list`,id:`nuni-panel-list`,role:`tabpanel`,"aria-labelledby":`nuni-tab-${this.tab}`},...l),this.status&&!this.status.claimed&&!this.isOwner?this.renderPanelFooter():null)}renderPanelFooter(){return K(`div`,{class:`panel-foot`},K(`div`,{class:`row`},K(`span`,{class:`meta`},this.t(`ownSite`)),K(`span`,{class:`spacer`}),K(`button`,{class:`btn`,type:`button`,onclick:()=>this.openClaim()},q(Y.github),this.t(`claim`))))}renderComposer(e,t){let n=!this.name,r=K(`span`,{class:`avatar cmp-avatar`,"aria-hidden":`true`}),i=e=>{let t=e.trim();r.classList.toggle(`avatar-empty`,!t),t?(r.textContent=hi(t),r.style.background=gi(t)):(r.replaceChildren(q(Y.user)),r.style.background=``)},a=K(`input`,{class:`cmp-name`,placeholder:this.t(`yourName`),value:this.name,maxlength:_.nameMaxLength,autocomplete:`name`,"data-focus-key":`name`,"aria-label":this.t(`yourName`)}),o=K(`textarea`,{class:`cmp-text`,placeholder:this.t(`leaveComment`),maxlength:_.bodyMaxLength,rows:3,"data-focus-key":`body`,"aria-label":this.t(`comment`)}),s=this.uiLayer.querySelector(`[data-focus-key="body"]`);s&&(o.value=s.value);let c=this.uiLayer.querySelector(`[data-focus-key="name"]`);c&&(a.value=c.value),i(n?a.value:this.name),a.addEventListener(`input`,()=>i(a.value));let l=K(`span`,{class:`cmp-count`,"aria-live":`polite`}),u=K(`button`,{class:`cmp-post`,type:`submit`,disabled:!!e.sending||!o.value.trim()},e.sending?this.t(`posting`):this.t(`post`),q(Y.arrowUp)),d=()=>{u.disabled=!!e.sending||!o.value.trim();let t=_.bodyMaxLength-o.value.length;l.textContent=t<=_.bodyMaxLength*.1?this.t(`charsLeft`,{count:t}):``,o.style.height=`auto`,o.style.height=`${o.scrollHeight+2}px`};o.addEventListener(`input`,()=>{d(),this.positionCard()}),requestAnimationFrame(()=>{o.isConnected&&(d(),this.positionCard())});let f=()=>void this.submitDraft(e,o.value,n?a.value:this.name);return o.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),f())}),K(`form`,{class:`${t} composer`,"data-card":`composer`,onsubmit:e=>{e.preventDefault(),f()}},K(`div`,{class:`cmp-head`},r,n?a:K(`span`,{class:`author`},this.name),K(`span`,{class:`spacer`}),n?null:K(`button`,{class:`cmp-link`,type:`button`,onclick:()=>{this.name=``,this.render(),this.focusComposer()}},this.t(`notYou`))),e.anchor.quote?K(`blockquote`,{class:`quote`},e.anchor.quote.exact):null,o,e.error?K(`div`,{class:`error cmp-error`,role:`alert`},e.error):null,K(`div`,{class:`cmp-foot`},K(`span`,{class:`cmp-keys`,title:this.t(`send`,{key:this.i18n.mod})},K(`kbd`,{},this.i18n.mod),K(`kbd`,{},`↵`)),l,K(`span`,{class:`spacer`}),u),K(`button`,{class:`icon-btn cmp-close`,type:`button`,"aria-label":this.t(`cancel`),title:this.t(`cancel`),onclick:()=>this.closeCard()},q(Y.close)))}renderCard(){let e=this.card;if(!e)return null;let t=`card${window.matchMedia(Bi).matches?` sheet`:``}`;if(e.kind===`composer`)return this.renderComposer(e.draft,t);let n=this.comments.find(t=>t._id===e.id);if(!n)return null;let r=this.isMine(n),i=this.isOwner,a=this.placements.get(n._id),o;if(e.editing){let t=K(`textarea`,{class:`field`,maxlength:_.bodyMaxLength,"data-focus-key":`edit`}),r=this.uiLayer.querySelector(`[data-focus-key="edit"]`);t.value=r?r.value:n.body,o=K(`div`,{class:`card-body`},t,K(`div`,{class:`row`},K(`span`,{class:`spacer`}),K(`button`,{class:`btn btn-ghost`,type:`button`,onclick:()=>{e.editing=!1,this.render()}},this.t(`cancel`)),K(`button`,{class:`btn btn-primary`,type:`button`,disabled:!!e.busy,onclick:()=>this.saveEdit(n,t.value)},this.t(`save`))))}else{let t=[n.status===`resolved`?K(`span`,{class:`badge badge-ok`},q(Y.check),this.t(`resolved`)):null,n.page.origin===location.origin?null:K(`span`,{class:`badge`,title:this.t(`leftOn`,{origin:n.page.origin})},new URL(n.page.origin).host),a?.confidence===`low`?K(`span`,{class:`badge`,title:this.t(`approximateHint`)},this.t(`approximate`)):null,a?.element?null:K(`span`,{class:`badge`,title:this.t(`originallyOn`,{text:n.anchor.text||n.anchor.tag})},this.t(`notFound`))].filter(e=>e!==null),s=i&&!(this.ownerDetailLoaded&&this.ownerDetailId===n._id),c=n.status===`resolved`;o=K(`div`,{class:`card-body msg`},K(`div`,{class:`card-head`},Hi(n.authorName),K(`span`,{class:`author`},n.authorName),K(`span`,{class:`meta`},this.i18n.timeAgo(n.createdAt)+(n.editedAt?` · ${this.t(`edited`)}`:``)),K(`span`,{class:`spacer`}),i?K(`button`,{class:`icon-btn${c?` is-resolved`:``}`,type:`button`,"aria-label":this.t(c?`reopen`:`resolve`),title:this.t(c?`reopen`:`resolve`),disabled:!!e.busy,onclick:()=>c?this.reopenComment(n):this.resolveComment(n)},q(Y.check)):null,K(`button`,{class:`icon-btn card-close`,type:`button`,"aria-label":this.t(`close`),title:this.t(`close`),onclick:()=>this.closeCard()},q(Y.close))),K(`div`,{class:`msg-main`},n.anchor.quote?K(`blockquote`,{class:`quote`},n.anchor.quote.exact):null,K(`div`,{class:`comment-body`},n.body),this.ownerDetail?._id===n._id&&this.ownerDetail.screenshotUrl?K(`a`,{class:`shot`,href:this.ownerDetail.screenshotUrl,target:`_blank`,rel:`noreferrer`,title:this.t(`openScreenshot`)},K(`img`,{src:this.ownerDetail.screenshotUrl,alt:this.t(`screenshotTaken`)})):null,t.length?K(`div`,{class:`badges`},...t):null,K(`div`,{class:`msg-foot`},this.renderReactions(n,n._id),K(`span`,{class:`spacer`}),K(`button`,{class:`icon-btn`,type:`button`,"aria-label":this.t(`copyForAgent`),title:s?this.t(`loadingContext`):this.t(`copyForAgentHint`),disabled:s,onclick:()=>this.copyForAgent(n)},q(Y.bot)),r?K(`button`,{class:`icon-btn`,type:`button`,"aria-label":this.t(`edit`),title:this.t(`edit`),onclick:()=>{e.editing=!0,this.render()}},q(Y.edit)):null,r||i?K(`button`,{class:`icon-btn icon-btn-danger`,type:`button`,"aria-label":this.t(`delete`),title:this.t(`delete`),"data-focus-key":`delete`,disabled:!!e.busy,onclick:()=>void this.deleteComment(n)},q(Y.trash)):null),e.error?K(`div`,{class:`error`,role:`alert`},e.error):null))}return K(`div`,{class:t,"data-card":`thread`,role:`dialog`,"aria-label":this.t(`commentBy`,{name:n.authorName})},o,e.editing?null:this.renderThread(n))}renderReactions(e,t,n=!0){let r=this.card;if(r?.kind!==`thread`)return null;let i=this.threadId===e._id&&this.thread?this.thread.reactions.filter(e=>e.targetId===t):[],a=r.picker===t;return!n&&!i.length&&!a?null:K(`div`,{class:`reactions`},...i.map(n=>{let r=n.authorKeyHashes.includes(this.secretHash);return K(`button`,{class:`reaction`,type:`button`,"aria-pressed":String(r),"aria-label":`${n.emoji} ${n.count}${r?`, including you`:``}`,onclick:()=>this.toggleReaction(e,t,n.emoji)},`${n.emoji} ${n.count}`)}),n?this.reactionAdd(t,`reaction reaction-add`):null,a?K(`div`,{class:`reaction-picker`,role:`group`,"aria-label":this.t(`reactions`)},...re.map(n=>K(`button`,{class:`reaction`,type:`button`,"aria-label":this.t(`reactWith`,{emoji:n}),onclick:()=>{r.picker=null,this.toggleReaction(e,t,n),this.render()}},n))):null)}reactionAdd(e,t){let n=this.card;if(n?.kind!==`thread`)return null;let r=n.picker===e;return K(`button`,{class:t,type:`button`,"aria-label":this.t(`addReaction`),"aria-expanded":String(r),title:this.t(`addReaction`),onclick:()=>{n.picker=r?null:e,this.render()}},q(Y.smile))}renderThread(e){let t=this.card;if(t?.kind!==`thread`)return null;let n=this.threadId===e._id?this.thread?.replies??[]:[],r=this.isOwner,i=n.map(n=>{let i=this.isMyReply(n);if(t.replyEditing===n._id){let r=K(`textarea`,{class:`field`,maxlength:_.bodyMaxLength,"data-focus-key":`reply-edit-${n._id}`,"aria-label":this.t(`editReply`)}),i=this.uiLayer.querySelector(`[data-focus-key="reply-edit-${n._id}"]`);return r.value=i?i.value:n.body,K(`div`,{class:`reply`},r,K(`div`,{class:`row`},K(`span`,{class:`spacer`}),K(`button`,{class:`btn btn-ghost`,type:`button`,onclick:()=>{t.replyEditing=void 0,this.render()}},this.t(`cancel`)),K(`button`,{class:`btn btn-primary`,type:`button`,disabled:!!t.busy,onclick:()=>this.saveReplyEdit(e,n,r.value)},this.t(`save`))))}return K(`div`,{class:`reply msg`,"data-reply":n._id},K(`div`,{class:`card-head`},Hi(n.authorName),K(`span`,{class:`author`},n.authorName),n.isOwner?K(`span`,{class:`badge badge-owner`},this.t(`owner`)):null,K(`span`,{class:`meta`},this.i18n.timeAgo(n.createdAt)+(n.editedAt?` · ${this.t(`edited`)}`:``)),K(`span`,{class:`spacer`}),K(`span`,{class:`msg-tools`},this.reactionAdd(n._id,`icon-btn`),i?K(`button`,{class:`icon-btn`,type:`button`,"aria-label":this.t(`editReply`),title:this.t(`edit`),onclick:()=>{t.replyEditing=n._id,this.render()}},q(Y.edit)):null,i||r?K(`button`,{class:`icon-btn icon-btn-danger`,type:`button`,"aria-label":this.t(`deleteReply`),title:this.t(`delete`),"data-focus-key":`delete-${n._id}`,disabled:!!t.busy,onclick:()=>void this.deleteReply(e,n)},q(Y.trash)):null)),K(`div`,{class:`msg-main`},K(`div`,{class:`comment-body`},n.body),this.renderReactions(e,n._id,!1)))}),a=!r&&!this.name,o=K(`input`,{class:`reply-name`,placeholder:this.t(`yourName`),value:this.name,maxlength:_.nameMaxLength,autocomplete:`name`,"data-focus-key":`reply-name`,"aria-label":this.t(`yourName`)}),s=this.uiLayer.querySelector(`[data-focus-key="reply-name"]`);s&&(o.value=s.value);let c=K(`textarea`,{class:`reply-text`,placeholder:n.length?this.t(`reply`):this.t(`replyFirst`),maxlength:_.bodyMaxLength,rows:1,"data-focus-key":`reply`,"aria-label":this.t(`reply`)}),l=this.uiLayer.querySelector(`[data-focus-key="reply"]`);l&&(c.value=l.value);let u=K(`button`,{class:`reply-send`,type:`submit`,"aria-label":this.t(`sendReply`),title:this.t(`sendReply`),disabled:!!t.sendingReply||!c.value.trim()},q(Y.arrowUp)),d=()=>{u.disabled=!!t.sendingReply||!c.value.trim(),c.style.height=`auto`,c.style.height=`${c.scrollHeight}px`};c.addEventListener(`input`,d),requestAnimationFrame(()=>{c.isConnected&&d()});let f=()=>void this.sendReply(e,c.value,a?o.value:this.name);return c.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),f())}),K(`div`,{class:`thread`},i.length?K(`div`,{class:`replies`,role:`list`,"aria-label":this.t(`replyCount`,{count:i.length})},...i.map(e=>(e.setAttribute(`role`,`listitem`),e))):null,K(`form`,{class:`reply-form`,onsubmit:e=>{e.preventDefault(),f()}},a?o:null,K(`div`,{class:`reply-row`},c,u)))}positionCard(){let e=this.uiLayer.querySelector(`[data-card]`);if(!e||e.classList.contains(`sheet`))return;let t=null;if(this.card?.kind===`composer`){let{draft:e}=this.card;t=this.anchorPoint(e.anchor,e.element,e.range)}else if(this.card?.kind===`thread`){let e=this.comments.find(e=>this.card?.kind===`thread`&&e._id===this.card.id);t=e?this.pinPositions.get(e._id)??this.pinPoint(e):null}let n=e.offsetWidth||320,r=e.offsetHeight||160,i=window.innerWidth,a=window.innerHeight,o,s;if(t)o=t.x+36,s=t.y-28,o+n>i-12&&(o=t.x-n-12);else{let{position:e}=this;o=e.endsWith(`left`)?16:e.endsWith(`center`)?(i-n)/2:i-n-16,s=e.startsWith(`top`)?72:a-r-72}o=Math.max(12,Math.min(o,i-n-12)),s=Math.max(12,Math.min(s,a-r-12)),e.style.left=`${Math.round(o)}px`,e.style.top=`${Math.round(s)}px`}focusComposer(){requestAnimationFrame(()=>{this.uiLayer.querySelector(this.name?`[data-focus-key="body"]`:`[data-focus-key="name"]`)?.focus()})}};function Ki(e,t){let n=window.innerWidth,r=e<n/3?`left`:e>n*2/3?`right`:`center`;return`${t<window.innerHeight/2?`top`:`bottom`}-${r}`}function qi(e){let t=e.composedPath()[0];if(!(t instanceof Element))return!1;let n=document.documentElement;if(t===n)return e.clientX>=n.clientWidth||e.clientY>=n.clientHeight;if(!(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth))return!1;let r=t.getBoundingClientRect();return e.clientX-r.left-t.clientLeft>=t.clientWidth||e.clientY-r.top-t.clientTop>=t.clientHeight}function Ji(e){let t=[e.convexUrl,e.convexSiteUrl].flatMap(e=>{try{return[new URL(e).origin]}catch{return[]}});return e=>{try{return t.includes(new URL(e,location.href).origin)}catch{return!1}}}let Q=null;function Yi(e,t){let n={destroy(){}};if(typeof window>`u`||typeof document>`u`)return n;if(!ne(e.project))return console.warn(`[nuni] "${e.project}" is not a valid project ID. Run \`npx @nuniapp/cli@latest init\` to get one.`),n;if(Q?.project===e.project)return Xi(Q);Q&&Zi(Q);let r=y(e),i={project:e.project,widget:null,collectors:ye(r.capture,Ji(r)),timer:0,handles:0};Q=i;let a=()=>{if(Q===i){if(!document.body){i.timer=window.setTimeout(a,50);return}i.widget=new Gi(r,{collectors:i.collectors,loadScreenshot:r.capture.screenshot?t.loadScreenshot:null}),i.widget.start()}},o=window.requestIdleCallback;return o?o(a,{timeout:1500}):i.timer=window.setTimeout(a,1),Xi(i)}function Xi(e){e.handles++;let t=!1;return{destroy(){t||(t=!0,e.handles--,e.handles<=0&&Q===e&&Zi(e))}}}function Zi(e){clearTimeout(e.timer),e.widget?.destroy(),e.widget=null,e.collectors.stop(),Q===e&&(Q=null)}let Qi=document.currentScript??document.querySelector(`script[data-project][src*='nuni']`),$i=null;function ea(){return $i??($i=new Promise(e=>{if(window.__nuniScreenshot)return e(window.__nuniScreenshot);let t=document.createElement(`script`);t.src=new URL(`nuni-screenshot.global.js`,Qi.src).href,t.async=!0,t.onload=()=>e(window.__nuniScreenshot??null),t.onerror=()=>{$i=null,e(null)},document.head.appendChild(t)})),$i}function ta(e){return Yi(e,{loadScreenshot:Qi?.src?ea:null})}window.Nuni={init:ta,version:`0.1.8`};function na(e){if(e!==void 0)return!/^(false|0|off|no)$/i.test(e.trim())}let $=Qi?.dataset;$?.project&&ta({project:$.project,convexUrl:$.convexUrl,convexSiteUrl:$.convexSiteUrl,appUrl:$.appUrl,pageKey:$.pageKey,position:$.position,accentColor:$.accentColor,theme:$.theme,label:$.label,hotkey:$.hotkey===void 0?void 0:na($.hotkey)!==!1&&$.hotkey,zIndex:$.zIndex===void 0?void 0:Number($.zIndex),locale:$.locale,capture:{console:na($.captureConsole),network:na($.captureNetwork),dom:na($.captureDom),screenshot:na($.captureScreenshot)}})})();
|