@nuniapp/widget 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,327 @@
1
+ (function(){let e=`123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz`,t=RegExp(`^nuni_[${e}]{22}$`);function n(t){let n=new Uint8Array(t);crypto.getRandomValues(n);let r=``;for(let t of n){let n=t;for(;n>=232;){let e=/* @__PURE__ */ new Uint8Array(1);crypto.getRandomValues(e),n=e[0]}r+=e[n%58]}return r}function r(e){return typeof e==`string`&&t.test(e)}function i(){return n(32)}let a={bodyMaxLength:2e3,nameMaxLength:50,unclaimedCommentCap:500,maxOriginsPerProject:20,sessionTtlMs:2592e6,anchorTextMaxLength:120,pageOpenLimit:1e3,pageResolvedLimit:200};function o(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname;if(t.hash.startsWith(`#/`)||t.hash.startsWith(`#!/`)){let e=t.hash.replace(/^#!?/,``).split(`?`)[0]??`/`;n=s(n,e)}try{n=decodeURI(n)}catch{}return n=n.replace(/\/index\.html?$/i,`/`),n=n.replace(/\/{2,}/g,`/`),n.length>1&&!n.includes(`#`)&&(n=n.replace(/\/$/,``)),n||`/`}function s(e,t){return`${e.replace(/\/index\.html?$/i,`/`).replace(/\/$/,``)}/#${t.length>1?t.replace(/\/$/,``):t}`}function c(e){let t=typeof e==`string`?new URL(e):e;return{origin:t.origin,path:o(t),search:t.search,hash:t.hash,url:t.href}}function l(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}}function u(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 d(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 f(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 p(e){let t=e.documentElement;return{w:t.scrollWidth,h:t.scrollHeight}}function ee(e){return Number.isFinite(e)?Math.min(1,Math.max(0,e)):.5}function m(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 h(e,t){let n=t.ignoreAttributePrefixes;return!n||!n.some(t=>e.startsWith(t))}let te=/^-?(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)(-|$)/,g=/* @__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(`.`)),_=[/_{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 v(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 ne(e){return/[[\]:/()%!#@&*,.>+~=]/.test(e)||g.has(e)?!0:te.test(e)}function re(e){return!e||e.length>40||e.startsWith(`nuni-`)||ne(e)||_.some(t=>t.test(e))?!1:!v(e)}function y(e){let t=[];for(let n of Array.from(e.classList))if(re(n)&&t.push(n),t.length>=4)break;return t}let ie=[/^:[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 ae(e){return!e||e.length>80||ie.some(t=>t.test(e))?!1:!v(e)}let oe=[`data-nuni`,`data-testid`,`data-test-id`,`data-test`,`data-cy`,`data-qa`],se=[`aria-label`,`name`,`href`,`src`,`alt`,`placeholder`,`title`,`type`,`role`,`for`,`value`];function b(e){return typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/([^\w-])/g,`\\$1`).replace(/^(\d)/,`\\3$1 `)}function ce(e,t){return`[${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"]`}function le(e,t){for(let n of oe){if(!h(n,t))continue;let r=e.getAttribute(n);if(r&&r.length<=100)return{attr:n,value:r}}return null}function x(e){let t=e.getAttribute(`id`);return t&&ae(t)?t:null}function ue(e){return e.tagName.toLowerCase()}function de(e){let t=1,n=e.previousElementSibling;for(;n;)n.tagName===e.tagName&&t++,n=n.previousElementSibling;return t}function fe(e){let t=e.parentElement;if(!t)return 1;let n=0;for(let r of Array.from(t.children))r.tagName===e.tagName&&n++;return n}function S(e,t){try{return e.querySelectorAll(t).length}catch{return 1/0}}function pe(e,t){return S(e,`#${b(t)}`)===1}function me(e){let t=e.ownerDocument,n=[],r=e;for(;r&&r!==t.documentElement;){let i=x(r);if(i&&r!==e&&pe(t,i))return n.unshift(`#${b(i)}`),n.join(` > `);let a=ue(r);n.unshift(fe(r)>1?`${a}:nth-of-type(${de(r)})`:a),r=r.parentElement}return n.length?`html > ${n.join(` > `)}`:`html`}function he(e,t){let n=ue(e),r=le(e,t);if(r)return n+ce(r.attr,r.value);let i=n;for(let t of y(e).slice(0,2))i+=`.${b(t)}`;for(let r of[`name`,`type`,`role`]){let a=e.getAttribute(r);if(a&&a.length<=40&&h(r,t)){if(r===`type`&&n!==`input`&&n!==`button`)continue;i+=ce(r,a)}}let a=e.getAttribute(`aria-label`);return a&&a.length<=60&&(i+=ce(`aria-label`,a)),i}function ge(e,t={}){let n=e.ownerDocument,r=x(e);if(r&&pe(n,r))return`#${b(r)}`;let i=[],a=e;for(let e=0;a&&e<6;e++){if(a===n.documentElement||a===n.body){i.unshift(ue(a));break}let r=x(a);if(e>0&&r&&pe(n,r)){i.unshift(`#${b(r)}`);let e=i.join(` > `);if(S(n,e)===1)return e;break}i.unshift(he(a,t));let o=i.join(` > `);if(S(n,o)===1)return o;let s=a.parentElement;if(s&&S(s,`:scope > ${i[0]}`)>1&&(i[0]=`${i[0]}:nth-of-type(${de(a)})`,o=i.join(` > `),S(n,o)===1))return o;a=a.parentElement}let o=i.join(` > `);return S(n,o)===1?o:void 0}let _e=/* @__PURE__ */ new Set([`SCRIPT`,`STYLE`,`NOSCRIPT`,`TEMPLATE`,`SVG`]);function ve(e){return e.replace(/\s+/g,` `).trim()}function C(e,t=120){if(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)return ve(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(!_e.has(i)){if(i===`IMG`){n+=` `+(e.getAttribute(`alt`)??``)+` `;return}for(let t of Array.from(e.childNodes))r(t);(i===`BR`||i===`P`||i===`DIV`||i===`LI`)&&(n+=` `)}};return r(e),ve(n).slice(0,t)}function ye(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 be(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=ye(n),a=ye(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))}function xe(e,t){let n={};for(let r of se){if(!h(r,t)||r===`value`&&!(e instanceof HTMLButtonElement||e.getAttribute(`type`)===`submit`))continue;let i=e.getAttribute(r);i&&(n[r]=i.slice(0,200))}return n}function Se(e){let t=[],n=e.parentElement;for(;n&&t.length<5&&n!==n.ownerDocument.documentElement;){let e=x(n),r={tag:n.tagName.toLowerCase(),classes:y(n).slice(0,3)};if(e&&(r.id=e),t.length<3&&n!==n.ownerDocument.body){let e=C(n,80);e&&(r.text=e)}t.push(r),n=n.parentElement}return t}function Ce(e,t,n={}){let r=e.ownerDocument,i=d(e),o=f(r),s=e.getBoundingClientRect(),c=t?{x:ee(s.width?(t.x-s.left)/s.width:.5),y:ee(s.height?(t.y-s.top)/s.height:.5)}:{x:.5,y:.5},l=x(e),m=le(e,n),h=ge(e,n),te=e.getAttribute(`role`)??void 0,g=e.parentElement,_=g?Array.from(g.children):[e],v={v:1,selectors:{path:me(e),...l?{id:l}:{},...m?{testId:`${m.attr}=${m.value}`}:{},...h?{css:h}:{}},tag:e.tagName.toLowerCase(),classes:y(e),text:C(e,a.anchorTextMaxLength),attrs:xe(e,n),ancestors:Se(e),siblingIndex:_.indexOf(e),siblingCount:_.length,rect:i,offset:c,viewport:o,docSize:p(r)};te&&(v.role=te);let ne=u(e);return ne&&(v.componentName=ne),v}let we={exact:.9,high:.72,low:.55},Te=3e3;function Ee(e,t,n=20){if(!t)return[];try{return Array.from(e.querySelectorAll(t)).slice(0,n)}catch{return[]}}function De(e,t){if(!t)return!1;try{return e.matches(t)}catch{return!1}}function Oe(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 ke(e){let t=e.indexOf(`=`);return t>0?[e.slice(0,t),e.slice(t+1)]:null}function Ae(e,t){return`[${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"]`}function je(e,t){try{let n=new URL(e,t.baseURI);return n.pathname.replace(/\/$/,``)+n.search}catch{return e}}function Me(e){let t=e.parentElement;if(!t)return 0;let n=y(e).join(` `),r=0;for(let i of Array.from(t.children))i!==e&&i.tagName===e.tagName&&y(i).join(` `)===n&&r++;return r}let Ne=/* @__PURE__ */ new Set([`href`,`name`,`aria-label`,`src`,`for`,`placeholder`,`alt`,`title`]);function Pe(e,t,n,r,i){let a=0,o=0,s=(e,t)=>{a+=e*t,o+=e};s(1,+(t.tagName.toLowerCase()===e.tag));let c=!1;if(e.selectors.id){let n=t.getAttribute(`id`)===e.selectors.id;c||(c=n),s(3,+!!n)}if(e.selectors.testId){let n=ke(e.selectors.testId),r=!!(n&&t.getAttribute(n[0])===n[1]);c||(c=r),s(4,+!!r)}let l=De(t,e.selectors.css);e.selectors.css&&s(1.5,+!!l);let d=r.pathMatch===t;s(1,+!!d),e.classes&&e.classes.length&&s(1.5,Oe(y(t),e.classes));let f=Object.keys(e.attrs).filter(e=>h(e,i)),p=!1;if(f.length){let r=0,i=0,a=0;for(let o of f){let s=Ne.has(o);s&&i++;let c=t.getAttribute(o);if(c==null)continue;let l=e.attrs[o];(o===`href`||o===`src`?je(c,n)===je(l,n):c===l)?(r++,s&&a++):r+=be(c,l)*.5}s(2,r/f.length),p=i>0&&a===i}e.role&&s(.5,+(t.getAttribute(`role`)===e.role)),e.componentName&&s(.5,+(u(t)===e.componentName));let ee=C(t),m=e.text?be(ee,e.text):ee?.3:1;s(e.text?3:1,m);let te=0,g=0,_=null,v=t.parentElement;e.ancestors.forEach((t,n)=>{let r=1-n*.15;if(g+=r,!v)return;let i=v.tagName.toLowerCase()===t.tag?.4:0,a=v.getAttribute(`id`);t.id?i+=a===t.id?.35:0:i+=.35*(a?.5:1),i+=.25*Oe(y(v),t.classes),te+=r*i,_===null&&t.text&&t.text!==e.text&&(_=be(C(v,80),t.text)),v=v.parentElement}),g&&s(1.5,te/g),_!==null&&s(2,_);let ne=t.parentElement,re=ne?Array.prototype.indexOf.call(ne.children,t):0;s(.5,Math.max(0,1-Math.abs(re-e.siblingIndex)/3));let ie=Math.max(0,1-Math.abs(r.viewportRatio-1)*2);if(ie>0&&e.rect.w+e.rect.h>0){let i=t.getBoundingClientRect();if(i.width+i.height>0){let t=n.defaultView,a=i.left+(t?.scrollX??0)+i.width/2,o=i.top+(t?.scrollY??0)+i.height/2,c=(e.rect.x+e.rect.w/2)*r.viewportRatio,l=e.rect.y+e.rect.h/2,u=Math.hypot(a-c,o-l);s(1.5*ie,Math.exp(-u/250));let d=Math.min(i.width,e.rect.w)/Math.max(i.width,e.rect.w,1),f=Math.min(i.height,e.rect.h)/Math.max(i.height,e.rect.h,1);s(.5*ie,d*f)}}let ae=o?a/o:0,oe=(l||!e.selectors.css)&&d&&p;if(e.text.length>=2&&m<.999){let e=Me(t)>0?.2+.8*m*m:.7+.3*m;ae*=c||oe?Math.max(e,.92):e}return{el:t,score:ae,text:m,context:_,strong:c||oe}}function Fe(e,t,n){let r=/* @__PURE__ */ new Set,i=e=>e===t.documentElement||(n.isIgnored?.(e)??!1),a=e=>{e&&!i(e)&&r.add(e)};if(e.selectors.id&&a(t.getElementById(e.selectors.id)),e.selectors.testId){let n=ke(e.selectors.testId);n&&Ee(t,Ae(n[0],n[1])).forEach(a)}Ee(t,e.selectors.css).forEach(a);let o=Ee(t,e.selectors.path,1)[0]??null;a(o);let s=e.text.slice(0,24).toLowerCase(),c=t.getElementsByTagName(e.tag),l=c.length<=Te;for(let e=0;e<c.length&&e<Te*2;e++){let t=c[e];if(l){a(t);continue}let n=t.textContent?.toLowerCase()??``;s&&n.includes(s)&&a(t)}if(e.text.length>=3){let n=e.text.toLowerCase(),r=t.createTreeWalker(t.body??t.documentElement,1),i=0;for(let t=r.nextNode();t&&i<Te*3;t=r.nextNode()){i++;let r=t;if(r.tagName.toLowerCase()===e.tag)continue;let o=r.textContent;!o||o.length>n.length*3+20||C(r).toLowerCase()===n&&a(r)}}return{candidates:r,pathMatch:o}}function Ie(e,t=document,n={}){if(e.tag===`body`||e.tag===`html`)return{element:t.body,confidence:`exact`,score:1};let{candidates:r,pathMatch:i}=Fe(e,t,n);if(!r.size)return{element:null,confidence:`lost`,score:0};let a=t.defaultView,o=e.viewport.w&&a?.innerWidth?a.innerWidth/e.viewport.w:1,s=[];for(let a of r)s.push(Pe(e,a,t,{pathMatch:i,viewportRatio:o},n));if(s.filter(t=>t.text>=.999&&t.el.tagName.toLowerCase()===e.tag).length>1)for(let e of s)e.context===null||e.strong||(e.score*=.2+.8*e.context*e.context);s.sort((e,t)=>t.score-e.score);let c=s[0],l=s.find(e=>e.el!==c.el&&!c.el.contains(e.el)&&!e.el.contains(c.el));if(c.score<we.low)return{element:null,confidence:`lost`,score:c.score};let u=c.score>=we.exact&&c.text>=.999?`exact`:c.score>=we.high?`high`:`low`;return l&&c.score-l.score<.03&&(u=`low`),{element:c.el,confidence:u,score:c.score}}let Le=/* @__PURE__ */ new Set([`SPAN`,`STRONG`,`EM`,`B`,`I`,`SMALL`,`MARK`,`SUB`,`SUP`,`ABBR`,`CODE`,`KBD`,`TIME`,`U`,`S`]);function Re(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(;Le.has(t.tagName)&&t.parentElement&&t.parentElement!==t.ownerDocument.body&&!t.id;)t=t.parentElement;return t}for(var w=[],T=[],ze=Uint8Array,Be=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,E=0,Ve=Be.length;E<Ve;++E)w[E]=Be[E],T[Be.charCodeAt(E)]=E;T[45]=62,T[95]=63;function He(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 Ue(e,t,n){return(t+n)*3/4-n}function We(e){for(var t,n=He(e),r=n[0],i=n[1],a=new ze(Ue(e,r,i)),o=0,s=i>0?r-4:r,c=0;c<s;c+=4)t=T[e.charCodeAt(c)]<<18|T[e.charCodeAt(c+1)]<<12|T[e.charCodeAt(c+2)]<<6|T[e.charCodeAt(c+3)],a[o++]=t>>16&255,a[o++]=t>>8&255,a[o++]=t&255;return i===2&&(t=T[e.charCodeAt(c)]<<2|T[e.charCodeAt(c+1)]>>4,a[o++]=t&255),i===1&&(t=T[e.charCodeAt(c)]<<10|T[e.charCodeAt(c+1)]<<4|T[e.charCodeAt(c+2)]>>2,a[o++]=t>>8&255,a[o++]=t&255),a}function Ge(e){return w[e>>18&63]+w[e>>12&63]+w[e>>6&63]+w[e&63]}function Ke(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(Ge(r));return i.join(``)}function qe(e){for(var t,n=e.length,r=n%3,i=[],a=16383,o=0,s=n-r;o<s;o+=a)i.push(Ke(e,o,o+a>s?s:o+a));return r===1?(t=e[n-1],i.push(w[t>>2]+w[t<<4&63]+`==`)):r===2&&(t=(e[n-2]<<8)+e[n-1],i.push(w[t>>10]+w[t>>4&63]+w[t<<2&63]+`=`)),i.join(``)}function D(e){if(e===void 0)return{};if(!Ye(e))throw Error(`The arguments to a Convex function must be an object. Received: ${e}`);return e}function Je(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 Ye(e){let t=typeof e==`object`,n=Object.getPrototypeOf(e),r=n===null||n===Object.prototype||n?.constructor?.name===`Object`;return t&&r}let O=BigInt(`-9223372036854775808`),Xe=BigInt(`9223372036854775807`),Ze=BigInt(`0`),Qe=BigInt(`8`),$e=BigInt(`256`),et=`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 tt=class{[Symbol.toPrimitive](e){if(e===`string`)return this.toString();throw Error(et)}valueOf(){throw Error(et)}toJSON(){throw Error(et)}toString(){return`[unresolved commit timestamp]`}};let nt=new tt;function rt(e){return Number.isNaN(e)||!Number.isFinite(e)||Object.is(e,-0)}function it(e){e<Ze&&(e-=O+O);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>>=Qe;return qe(n)}function at(e){let t=We(e);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);let n=Ze,r=Ze;for(let e of t)n+=BigInt(e)*$e**r,r++;return n>Xe&&(n+=O+O),n}function ot(e){if(e<O||Xe<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),qe(new Uint8Array(t))}function st(e){let t=We(e);if(t.byteLength!==8)throw Error(`Received ${t.byteLength} bytes, expected 8 for $integer`);return new DataView(t.buffer).getBigInt64(0,!0)}let ct=DataView.prototype.setBigInt64?ot:it,lt=DataView.prototype.getBigInt64?st:at,ut=1024;function dt(e){if(e.length>ut)throw Error(`Field name ${e} exceeds maximum field name length ${ut}.`);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 k(e){if(e===null||typeof e==`boolean`||typeof e==`number`||typeof e==`string`)return e;if(Array.isArray(e))return e.map(e=>k(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 We(e.$bytes).buffer}if(n===`$integer`){if(typeof e.$integer!=`string`)throw Error(`Malformed $integer field on ${e}`);return lt(e.$integer)}if(n===`$float`){if(typeof e.$float!=`string`)throw Error(`Malformed $float field on ${e}`);let t=We(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(!rt(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 nt}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))dt(t),n[t]=k(r);return n}function A(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 ft(e,t,n,r){if(e===void 0){let e=n&&` (present at path ${n} in original object ${A(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<O||Xe<e)throw Error(`BigInt ${e} does not fit into a 64-bit signed integer.`);return{$integer:ct(e)}}if(typeof e==`number`){if(rt(e)){let t=/* @__PURE__ */ new ArrayBuffer(8);return new DataView(t).setFloat64(0,e,!0),{$float:qe(new Uint8Array(t))}}return e}if(typeof e==`boolean`||typeof e==`string`)return e;if(e instanceof ArrayBuffer)return{$bytes:qe(new Uint8Array(e))};if(e instanceof tt)return{$commitTs:null};if(Array.isArray(e))return e.map((e,r)=>ft(e,t,n+`[${r}]`,!1));if(e instanceof Set)throw Error(pt(n,`Set`,[...e],t));if(e instanceof Map)throw Error(pt(n,`Map`,[...e],t));if(!Ye(e)){let r=e?.constructor?.name,i=r?`${r} `:``;throw Error(pt(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&&(dt(e),i[e]=mt(o,t,n+`.${e}`)):(dt(e),i[e]=ft(o,t,n+`.${e}`,!1));return i}function pt(e,t,n,r){return e?`${t}${A(n)} is not a supported Convex type (present at path ${e} in original object ${A(r)}). To learn about Convex's supported types, see https://docs.convex.dev/using/types.`:`${t}${A(n)} is not a supported Convex type.`}function mt(e,t,n){if(e===void 0)return{$undefined:null};if(t===void 0)throw Error(`Programming error. Current value is ${A(e)} but original value is undefined`);return ft(e,t,n,!1)}function j(e){return ft(e,e,``,!1)}var ht=Object.defineProperty,gt=(e,t,n)=>t in e?ht(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,_t=(e,t,n)=>gt(e,typeof t==`symbol`?t:t+``,n),vt,yt;let bt=Symbol.for(`ConvexError`);var xt=class extends (yt=Error,vt=bt,yt){constructor(e){super(typeof e==`string`?e:A(e)),_t(this,`name`,`ConvexError`),_t(this,`data`),_t(this,vt,!0),this.data=e}};let St=`1.46.0`,Ct=Symbol.for(`functionName`),wt=Symbol.for(`toReferencePath`);function Tt(e){return e[wt]??null}function Et(e){return e.startsWith(`function://`)}function Dt(e){let t;if(typeof e==`string`)t=Et(e)?{functionHandle:e}:{name:e};else if(e[Ct])t={name:e[Ct]};else{let n=Tt(e);if(!n)throw Error(`${e} is not a functionReference`);t={reference:n}}return t}function M(e){let t=Dt(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[Ct];if(!n)throw Error(`${e} is not a functionReference`);return n}function Ot(e=[]){return new Proxy({},{get(t,n){if(typeof n==`string`)return Ot([...e,n]);if(n===Ct){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 kt=Ot();function At(e,t){return new Proxy({},{get(n,r){if(typeof r==`string`)return At(e,[...t,r]);if(r===wt){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 jt=()=>At(`components`,[]),N=kt;jt();var Mt=Object.defineProperty,Nt=(e,t,n)=>t in e?Mt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Pt=(e,t,n)=>Nt(e,typeof t==`symbol`?t:t+``,n);function Ft(e){switch(e){case`query`:return`Q`;case`mutation`:return`M`;case`action`:return`A`;case`any`:return`?`}}var It=class{constructor(e){Pt(this,`_onLogLineFuncs`),Pt(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 Lt(e){let t=new It(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 Rt(e){return new It(e)}function zt(e,t,n,r,i){let a=Ft(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 Bt(e,t){let n=`[CONVEX FATAL ERROR] ${t}`;return e.error(n),Error(n)}function P(e,t,n){return`[CONVEX ${Ft(e)}(${t})] ${n.errorMessage}
2
+ Called by client`}function Vt(e,t){return t.data=e.errorData,t}function F(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 I(e,t){return JSON.stringify({udfPath:F(e),args:j(t)})}function Ht(e,t,n){let{initialNumItems:r,id:i}=n;return JSON.stringify({type:`paginated`,udfPath:F(e),args:j(t),options:j({initialNumItems:r,id:i})})}function Ut(e){return JSON.parse(e).type===`paginated`}var Wt=Object.defineProperty,Gt=(e,t,n)=>t in e?Wt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,L=(e,t,n)=>Gt(e,typeof t==`symbol`?t:t+``,n),Kt=class{constructor(){L(this,`nextQueryId`),L(this,`querySetVersion`),L(this,`querySet`),L(this,`queryIdToToken`),L(this,`identityVersion`),L(this,`auth`),L(this,`outstandingQueriesOlderThanRestart`),L(this,`outstandingAuthOlderThanRestart`),L(this,`paused`),L(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=F(e),a=I(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:[j(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=I(F(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:[j(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]}}}},qt=Object.defineProperty,Jt=(e,t,n)=>t in e?qt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Yt=(e,t,n)=>Jt(e,typeof t==`symbol`?t:t+``,n),Xt=class{constructor(e,t){this.logger=e,this.markConnectionStateDirty=t,Yt(this,`inflightRequests`),Yt(this,`requestsOlderThanRestart`),Yt(this,`inflightMutationsCount`,0),Yt(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)zt(this.logger,`info`,n,r,t);let i=t.status,a,o;if(e.success)a={success:!0,logLines:e.logLines,value:k(e.result)},o=()=>i.onResult(a);else{let t=e.result,{errorData:s}=e;zt(this.logger,`error`,n,r,t),a={success:!1,errorMessage:t,errorData:s===void 0?void 0:k(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}},Zt=Object.defineProperty,Qt=(e,t,n)=>t in e?Zt(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,$t=(e,t,n)=>Qt(e,typeof t==`symbol`?t:t+``,n),en=class e{constructor(e){$t(this,`queryResults`),$t(this,`modifiedQueries`),this.queryResults=e,this.modifiedQueries=[]}getQuery(t,...n){let r=D(n[0]),i=M(t),a=this.queryResults.get(I(i,r));if(a!==void 0)return e.queryValue(a.result)}getAllQueries(t){let n=[],r=M(t);for(let t of this.queryResults.values())t.udfPath===F(r)&&n.push({args:t.args,value:e.queryValue(t.result)});return n}setQuery(e,t,n){let r=D(t),i=M(e),a=I(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}},tn=class{constructor(){$t(this,`queryResults`),$t(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 en(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 en(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(P(`query`,t.udfPath,n)):Vt(n,new xt(P(`query`,t.udfPath,n)))}}hasQueryResult(e){return this.queryResults.get(e)!==void 0}queryLogs(e){return this.queryResults.get(e)?.result?.logLines}},nn=Object.defineProperty,rn=(e,t,n)=>t in e?nn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,an=(e,t,n)=>rn(e,typeof t==`symbol`?t:t+``,n),R=class e{constructor(e,t){an(this,`low`),an(this,`high`),an(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?on:t>=cn?ln:new e(t%z|0,t/z|0)}toString(){return(BigInt(this.high)*BigInt(z)+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 on=new R(0,0),sn=65536,z=sn*sn,cn=z*z,ln=new R(-1,-1);var un=Object.defineProperty,dn=(e,t,n)=>t in e?un(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,fn=(e,t,n)=>dn(e,typeof t==`symbol`?t:t+``,n),pn=class{constructor(e,t){fn(this,`version`),fn(this,`remoteQuerySet`),fn(this,`queryPath`),fn(this,`logger`),this.version={querySet:0,ts:R.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)zt(this.logger,`info`,`query`,e,n);let n=k(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)zt(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:k(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 mn(e){let t=We(e);return R.fromBytesLE(Array.from(t))}function hn(e){return qe(new Uint8Array(e.toBytesLE()))}function gn(e){switch(e.type){case`FatalError`:case`AuthError`:case`ActionResponse`:case`TransitionChunk`:case`Ping`:return{...e};case`MutationResponse`:return e.success?{...e,ts:mn(e.ts)}:{...e};case`Transition`:return{...e,startVersion:{...e.startVersion,ts:mn(e.startVersion.ts)},endVersion:{...e.endVersion,ts:mn(e.endVersion.ts)}}}}function _n(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:hn(e.maxObservedTimestamp)}}}var vn=Object.defineProperty,yn=(e,t,n)=>t in e?vn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,B=(e,t,n)=>yn(e,typeof t==`symbol`?t:t+``,n);let bn;function V(){return bn===void 0&&(bn=Date.now()),typeof performance>`u`||!performance.now?Date.now():Math.round(bn+performance.now())}function xn(){return`t=${Math.round((V()-bn)/100)/10}s`}let Sn={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 Cn(e){if(e===void 0)return`Unknown`;for(let t of Object.keys(Sn))if(e.startsWith(t))return t;return`Unknown`}var wn=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=gn(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`,xn(),`after disconnect due to`,this.lastCloseReason):this.logger.log(`WebSocket reconnected at`,xn())),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=gn(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=Cn(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=_n(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:Sn[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 Tn(){return En()}function En(){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 H=class extends Error{};H.prototype.name=`InvalidTokenError`;function Dn(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 On(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 Dn(t)}catch{return atob(t)}}function kn(e,t){if(typeof e!=`string`)throw new H(`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 H(`Invalid token specified: missing part #${n+1}`);let i;try{i=On(r)}catch(e){throw new H(`Invalid token specified: invalid base64 for part #${n+1} (${e.message})`)}try{return JSON.parse(i)}catch(e){throw new H(`Invalid token specified: invalid json for part #${n+1} (${e.message})`)}}var An=Object.defineProperty,jn=(e,t,n)=>t in e?An(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,U=(e,t,n)=>jn(e,typeof t==`symbol`?t:t+``,n),Mn=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 kn(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 Nn=[`convexClientConstructed`,`convexWebSocketOpen`,`convexFirstMessageReceived`];function Pn(e,t){let n={sessionId:t};typeof performance<`u`&&performance.mark&&performance.mark(e,{detail:n})}function Fn(e){let t=e.name.slice(6);return t=t.charAt(0).toLowerCase()+t.slice(1),{name:t,startTime:e.startTime}}function In(e){if(typeof performance>`u`||!performance.getEntriesByName)return[];let t=[];for(let n of Nn){let r=performance.getEntriesByName(n).filter(e=>e.entryType===`mark`).filter(t=>t.detail.sessionId===e);t.push(...r)}return t.map(Fn)}var Ln=Object.defineProperty,Rn=(e,t,n)=>t in e?Ln(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,W=(e,t,n)=>Rn(e,typeof t==`symbol`?t:t+``,n),zn=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&&Pn(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&&Je(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?Rt({verbose:n.verbose??!1}):n.logger!==!0&&n.logger?n.logger:Lt({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/${St}/sync`;this.state=new Kt,this.remoteQuerySet=new pn(e=>this.state.queryPath(e),this.logger),this.requestManager=new Xt(this.logger,this.markConnectionStateDirty);let u=()=>{this.webSocketManager.pause(),this.state.pause()};this.authenticationManager=new Mn(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 tn,this.addOnTransitionHandler(e=>{t(e.queries.map(e=>e.token))}),this._nextRequestId=0,this._sessionId=Tn();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 wn(l,{onOpen:e=>{this.mark(`convexWebSocketOpen`),this.webSocketManager.sendMessage({...e,type:`Connect`,sessionId:this._sessionId,maxObservedTimestamp:this.maxObservedTimestamp}),this.remoteQuerySet=new pn(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=Bt(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?kn(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=D(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=I(e,D(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=I(e,D(t));return this.optimisticQueryResults.queryLogs(n)}queryJournal(e,t){let n=I(e,D(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(P(`mutation`,e,r)):Vt(r,new xt(P(`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=D(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:[j(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(P(`action`,e,n)):Vt(n,new xt(P(`action`,e,n)));return n.value}async actionInternal(e,t,n){let r=D(t),i=this.nextRequestId;this._nextRequestId++,this.tryReportLongDisconnect();let a={type:`Action`,requestId:i,udfPath:e,componentPath:n,args:[j(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=In(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-${St}`},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 Bn(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 Vn=Object.defineProperty,Hn=(e,t,n)=>t in e?Vn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Un=(e,t,n)=>Hn(e,typeof t==`symbol`?t:t+``,n),Wn=class{constructor(e,t){this.client=e,this.onTransition=t,Un(this,`paginatedQuerySet`,/* @__PURE__ */ new Map),Un(this,`lastTransitionTs`),this.lastTransitionTs=R.fromNumber(0),this.client.addOnTransitionHandler(e=>this.onBaseTransition(e))}subscribe(e,t,n){let r=F(e),i=Ht(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=Ht(F(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=Bn(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=Bn(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=Bn(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}},Gn=Object.defineProperty,Kn=(e,t,n)=>t in e?Gn(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,G=(e,t,n)=>Kn(e,typeof t==`symbol`?t:t+``,n),qn=class{constructor(e,t={}){G(this,`listeners`),G(this,`_client`),G(this,`_paginatedClient`),G(this,`callNewListenersWithCurrentValuesTimer`),G(this,`_closed`),G(this,`_disabled`),t.skipConvexDeploymentUrlCheck!==!0&&Je(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 zn(e,()=>{},r),this._paginatedClient=new Wn(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(M(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(M(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(M(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=Ut(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(M(e),t,n)}async action(e,t){if(this.disabled)throw Error(`ConvexClient is disabled`);return await this.client.action(M(e),t)}async query(e,t){if(this.disabled)throw Error(`ConvexClient is disabled`);let n=this.client.localQueryResult(M(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)}};function Jn(e){"@babel/helpers - typeof";return Jn=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},Jn(e)}function Yn(e,t){if(Jn(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(Jn(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Xn(e){var t=Yn(e,`string`);return Jn(t)==`symbol`?t:t+``}function K(e,t,n){return(t=Xn(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var Zn=class extends Error{constructor(e,t){super(e),this.code=t}};function Qn(e){let t=e?.data;return t?.message?t.message:e instanceof Error?e.message:`Something went wrong`}var $n=class{constructor(e){this.config=e,K(this,`client`,void 0),this.client=new qn(e.convexUrl,{unsavedChangesWarning:!1,skipConvexDeploymentUrlCheck:!/\.convex\.cloud\/?$/.test(e.convexUrl)})}close(){return this.client.close()}touch(e){return this.client.mutation(N.projects.touch,{publicId:this.config.project,origin:e}).catch(()=>null)}onStatus(e){return this.client.onUpdate(N.projects.status,{publicId:this.config.project},e,()=>{})}onPage(e,t,n){return this.client.onUpdate(N.comments.listForPage,{publicId:this.config.project,path:e},e=>t(e),n)}onPages(e){return this.client.onUpdate(N.comments.pagesWithComments,{publicId:this.config.project},e,()=>{})}onSession(e,t){return this.client.onUpdate(N.sessions.validate,{publicId:this.config.project,sessionToken:e},t,()=>{})}getComment(e){return this.client.query(N.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 Zn(`Couldn't reach Nuni. Check your connection.`,`network`)}let n=await t.json().catch(()=>({}));if(!t.ok||!n.id)throw new Zn(n.message??`Couldn't post the comment`,n.code??`error`);return n.id}async run(e){try{return await e}catch(e){throw new Zn(Qn(e),`error`)}}editOwn(e,t,n){return this.run(this.client.mutation(N.comments.editOwn,{id:e,authorSecret:t,body:n}))}deleteOwn(e,t){return this.run(this.client.mutation(N.comments.deleteOwn,{id:e,authorSecret:t}))}resolve(e,t){return this.run(this.client.mutation(N.comments.resolve,{id:e,sessionToken:t}))}reopen(e,t){return this.run(this.client.mutation(N.comments.reopen,{id:e,sessionToken:t}))}remove(e,t){return this.run(this.client.mutation(N.comments.remove,{id:e,sessionToken:t}))}signOut(e){return this.client.mutation(N.sessions.revokeOwn,{sessionToken:e}).catch(()=>null)}};function q(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 J(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 er(e,t=Date.now()){let n=Math.max(0,Math.round((t-e)/1e3));if(n<45)return`just now`;let r=Math.round(n/60);if(r<60)return`${r}m ago`;let i=Math.round(r/60);if(i<24)return`${i}h ago`;let a=Math.round(i/24);return a<30?`${a}d ago`:new Date(e).toLocaleDateString()}function tr(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 nr(e){let t=0;for(let n of e)t=t*31+n.charCodeAt(0)>>>0;return`oklch(0.62 0.17 ${t%360})`}let Y=e=>`<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"/>`),target:Y(`<circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="3"/>`),github:`<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"/>`)},rr=`nuni:locationchange`,ir=!1;function ar(e){if(!ir){ir=!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(rr)),n}}}let t=location.href,n=()=>{location.href!==t&&(t=location.href,e())};window.addEventListener(rr,n),window.addEventListener(`popstate`,n),window.addEventListener(`hashchange`,n);let r=window.navigation,i=()=>setTimeout(n,0);return r?.addEventListener(`navigatesuccess`,i),()=>{window.removeEventListener(rr,n),window.removeEventListener(`popstate`,n),window.removeEventListener(`hashchange`,n),r?.removeEventListener(`navigatesuccess`,i)}}async function or(e){let t=new TextEncoder().encode(e);if(typeof crypto<`u`&&crypto.subtle){let e=await crypto.subtle.digest(`SHA-256`,t);return sr(new Uint8Array(e))}return sr(lr(t))}function sr(e){return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)}let cr=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 lr(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+cr[e]+a[e]>>>0,ee=(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+ee>>>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}let ur=/* @__PURE__ */ new Map;function dr(e){try{return window.localStorage.getItem(e)}catch{return ur.get(e)??null}}function Z(e,t){try{t===null?window.localStorage.removeItem(e):window.localStorage.setItem(e,t)}catch{t===null?ur.delete(e):ur.set(e,t)}}let Q={name:`nuni:name`,secret:`nuni:author-secret`,session:e=>`nuni:session:${e}`,showResolved:`nuni:show-resolved`},fr=`nuni-picking`,pr=`(max-width: 640px)`;function mr(e){return e instanceof HTMLElement?e.isContentEditable||e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.tagName===`SELECT`:!1}function hr(e){let t=e.tagName.toLowerCase(),n=e.id?`#${e.id}`:``,r=Array.from(e.classList).slice(0,2).map(e=>`.${e}`).join(``),i=C(e,40);return`${t}${n}${r}${i?` "${i}"`:``}`}var gr=class{constructor(e){this.config=e,K(this,`host`,void 0),K(this,`root`,void 0),K(this,`pinLayer`,void 0),K(this,`overlayLayer`,void 0),K(this,`uiLayer`,void 0),K(this,`api`,void 0),K(this,`cleanups`,[]),K(this,`pageUnsub`,null),K(this,`sessionUnsub`,null),K(this,`pageKey`,``),K(this,`comments`,[]),K(this,`loaded`,!1),K(this,`placements`,/* @__PURE__ */ new Map),K(this,`pins`,/* @__PURE__ */ new Map),K(this,`status`,{exists:!1,claimed:!1,ownerName:null,openCount:0}),K(this,`pages`,[]),K(this,`picking`,!1),K(this,`panelOpen`,!1),K(this,`tab`,`open`),K(this,`showResolved`,dr(Q.showResolved)===`1`),K(this,`card`,null),K(this,`activeId`,null),K(this,`hoverEl`,null),K(this,`toastTimer`,0),K(this,`toast`,null),K(this,`name`,dr(Q.name)??``),K(this,`secret`,void 0),K(this,`secretHash`,``),K(this,`ownerToken`,void 0),K(this,`ownerName`,null),K(this,`deepLinkId`,null),K(this,`extraComment`,null),K(this,`layoutFrame`,0),K(this,`pinPositions`,/* @__PURE__ */ new Map),K(this,`resolveTimer`,0),K(this,`isIgnored`,e=>e===this.host||this.host.contains(e)),K(this,`swallow`,e=>{if(this.fromPage(e)){if(e.type===`pointerdown`&&e instanceof PointerEvent){let t=this.fromPage(e);t&&(this.hoverEl=Re(t),this.renderHighlight())}e.preventDefault(),e.stopPropagation()}}),K(this,`onPickMove`,e=>{let t=this.fromPage(e),n=t?Re(t):null;n!==this.hoverEl&&(this.hoverEl=n,this.renderHighlight())}),K(this,`onPickClick`,e=>{let t=this.fromPage(e);if(!t)return;e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation();let n=Re(t),r=Ce(n,{x:e.clientX,y:e.clientY},{ignoreAttributePrefixes:[]});this.setPicking(!1),this.card={kind:`composer`,draft:{anchor:r,element:n}},this.render(),this.focusComposer()});let t=dr(Q.secret);t||(t=i(),Z(Q.secret,t)),this.secret=t,this.ownerToken=dr(Q.session(e.project)),this.host=document.createElement(`div`),this.host.id=`nuni-root`,this.host.setAttribute(`data-nuni`,``),this.root=this.host.attachShadow({mode:`open`});let n=document.createElement(`style`);n.textContent=`
3
+ :host {
4
+ all: initial;
5
+ position: fixed;
6
+ inset: 0;
7
+ z-index: 2147483646;
8
+ pointer-events: none;
9
+ color-scheme: light dark;
10
+ --n-bg: #ffffff;
11
+ --n-bg-subtle: #f6f5f7;
12
+ --n-fg: #1c1a1f;
13
+ --n-fg-muted: #6c6773;
14
+ --n-border: rgba(28, 26, 31, 0.12);
15
+ --n-accent: #d6246e;
16
+ --n-accent-fg: #ffffff;
17
+ --n-accent-soft: rgba(214, 36, 110, 0.12);
18
+ --n-ok: #1f9d55;
19
+ --n-danger: #d93025;
20
+ --n-shadow: 0 1px 2px rgba(0,0,0,0.06), 0 8px 24px rgba(0,0,0,0.12);
21
+ --n-radius: 12px;
22
+ --n-font: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
23
+ font-family: var(--n-font);
24
+ font-size: 14px;
25
+ line-height: 1.45;
26
+ -webkit-font-smoothing: antialiased;
27
+ }
28
+ @media (prefers-color-scheme: dark) {
29
+ :host {
30
+ --n-bg: #1d1b20;
31
+ --n-bg-subtle: #2a272e;
32
+ --n-fg: #f4f2f6;
33
+ --n-fg-muted: #a8a2ae;
34
+ --n-border: rgba(255, 255, 255, 0.12);
35
+ --n-accent: #ff4d94;
36
+ --n-accent-soft: rgba(255, 77, 148, 0.18);
37
+ --n-shadow: 0 1px 2px rgba(0,0,0,0.4), 0 12px 32px rgba(0,0,0,0.5);
38
+ }
39
+ }
40
+ *, *::before, *::after { box-sizing: border-box; }
41
+ button, input, textarea { font: inherit; color: inherit; }
42
+ button { cursor: pointer; }
43
+ :focus-visible { outline: 2px solid var(--n-accent); outline-offset: 2px; }
44
+ .icon { display: inline-flex; width: 16px; height: 16px; flex: none; }
45
+ .icon svg { width: 100%; height: 100%; }
46
+ .sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
47
+
48
+ /* Toolbar */
49
+ .toolbar {
50
+ position: fixed;
51
+ right: 16px;
52
+ bottom: 16px;
53
+ display: flex;
54
+ gap: 4px;
55
+ padding: 4px;
56
+ border-radius: 999px;
57
+ background: var(--n-bg);
58
+ color: var(--n-fg);
59
+ border: 1px solid var(--n-border);
60
+ box-shadow: var(--n-shadow);
61
+ pointer-events: auto;
62
+ }
63
+ .tb-btn {
64
+ display: inline-flex;
65
+ align-items: center;
66
+ gap: 6px;
67
+ height: 36px;
68
+ padding: 0 14px;
69
+ border: 0;
70
+ border-radius: 999px;
71
+ background: transparent;
72
+ font-weight: 550;
73
+ white-space: nowrap;
74
+ }
75
+ .tb-btn:hover { background: var(--n-bg-subtle); }
76
+ .tb-btn[aria-pressed="true"] { background: var(--n-accent); color: var(--n-accent-fg); }
77
+ .tb-count {
78
+ min-width: 20px;
79
+ height: 20px;
80
+ padding: 0 6px;
81
+ border-radius: 999px;
82
+ background: var(--n-bg-subtle);
83
+ color: var(--n-fg-muted);
84
+ font-size: 12px;
85
+ display: inline-flex;
86
+ align-items: center;
87
+ justify-content: center;
88
+ }
89
+ .tb-btn[aria-pressed="true"] .tb-count { background: rgba(255,255,255,0.25); color: inherit; }
90
+
91
+ /* Picking */
92
+ .pick-hint {
93
+ position: fixed;
94
+ top: 12px;
95
+ left: 50%;
96
+ transform: translateX(-50%);
97
+ padding: 6px 12px;
98
+ border-radius: 999px;
99
+ background: var(--n-fg);
100
+ color: var(--n-bg);
101
+ font-size: 13px;
102
+ box-shadow: var(--n-shadow);
103
+ pointer-events: none;
104
+ }
105
+ .highlight {
106
+ position: fixed;
107
+ border: 2px solid var(--n-accent);
108
+ background: var(--n-accent-soft);
109
+ border-radius: 4px;
110
+ pointer-events: none;
111
+ transition: all 60ms ease-out;
112
+ }
113
+ .highlight-label {
114
+ position: absolute;
115
+ left: -2px;
116
+ bottom: 100%;
117
+ margin-bottom: 4px;
118
+ padding: 1px 6px;
119
+ border-radius: 4px;
120
+ background: var(--n-accent);
121
+ color: var(--n-accent-fg);
122
+ font: 11px/1.6 ui-monospace, SFMono-Regular, Menlo, monospace;
123
+ white-space: nowrap;
124
+ max-width: 280px;
125
+ overflow: hidden;
126
+ text-overflow: ellipsis;
127
+ }
128
+
129
+ /* Pins */
130
+ .pin {
131
+ position: fixed;
132
+ left: 0;
133
+ top: 0;
134
+ width: 28px;
135
+ height: 28px;
136
+ margin: -28px 0 0 0;
137
+ border: 2px solid #fff;
138
+ border-radius: 14px 14px 14px 2px;
139
+ color: #fff;
140
+ font-size: 11px;
141
+ font-weight: 700;
142
+ display: flex;
143
+ align-items: center;
144
+ justify-content: center;
145
+ box-shadow: 0 2px 8px rgba(0,0,0,0.25);
146
+ pointer-events: auto;
147
+ cursor: pointer;
148
+ transition: transform 120ms ease;
149
+ will-change: transform;
150
+ }
151
+ .pin:hover, .pin[data-active="true"] { z-index: 2; }
152
+ .pin[data-active="true"] { box-shadow: 0 0 0 3px var(--n-accent), 0 2px 8px rgba(0,0,0,0.25); }
153
+ .pin[data-status="resolved"] { opacity: 0.55; filter: grayscale(0.6); }
154
+ .pin[data-confidence="low"] { border-style: dashed; }
155
+ .pin[hidden] { display: none; }
156
+ .pin-pending { opacity: 0.7; }
157
+
158
+ /* Cards (composer + thread) */
159
+ .card {
160
+ position: fixed;
161
+ width: 320px;
162
+ max-width: calc(100vw - 24px);
163
+ background: var(--n-bg);
164
+ color: var(--n-fg);
165
+ border: 1px solid var(--n-border);
166
+ border-radius: var(--n-radius);
167
+ box-shadow: var(--n-shadow);
168
+ pointer-events: auto;
169
+ overflow: hidden;
170
+ }
171
+ .card-body { padding: 12px; display: grid; gap: 10px; }
172
+ .card-head { display: flex; align-items: center; gap: 8px; }
173
+ .card-head .spacer { flex: 1; }
174
+ .avatar {
175
+ width: 24px;
176
+ height: 24px;
177
+ border-radius: 999px;
178
+ color: #fff;
179
+ font-size: 10px;
180
+ font-weight: 700;
181
+ display: inline-flex;
182
+ align-items: center;
183
+ justify-content: center;
184
+ flex: none;
185
+ }
186
+ .author { font-weight: 600; }
187
+ .meta { color: var(--n-fg-muted); font-size: 12px; }
188
+ .badge {
189
+ display: inline-flex;
190
+ align-items: center;
191
+ gap: 4px;
192
+ padding: 1px 6px;
193
+ border-radius: 999px;
194
+ background: var(--n-bg-subtle);
195
+ color: var(--n-fg-muted);
196
+ font-size: 11px;
197
+ max-width: 160px;
198
+ overflow: hidden;
199
+ text-overflow: ellipsis;
200
+ white-space: nowrap;
201
+ }
202
+ .badge-ok { background: rgba(31,157,85,0.14); color: var(--n-ok); }
203
+ .comment-body { white-space: pre-wrap; word-break: break-word; }
204
+ .field {
205
+ width: 100%;
206
+ padding: 8px 10px;
207
+ border: 1px solid var(--n-border);
208
+ border-radius: 8px;
209
+ background: var(--n-bg);
210
+ outline: none;
211
+ }
212
+ .field:focus { border-color: var(--n-accent); box-shadow: 0 0 0 3px var(--n-accent-soft); }
213
+ textarea.field { resize: vertical; min-height: 72px; max-height: 240px; }
214
+ .row { display: flex; align-items: center; gap: 8px; }
215
+ .row .spacer { flex: 1; }
216
+ .btn {
217
+ display: inline-flex;
218
+ align-items: center;
219
+ gap: 6px;
220
+ height: 32px;
221
+ padding: 0 12px;
222
+ border-radius: 8px;
223
+ border: 1px solid var(--n-border);
224
+ background: var(--n-bg);
225
+ font-weight: 550;
226
+ font-size: 13px;
227
+ }
228
+ .btn:hover { background: var(--n-bg-subtle); }
229
+ .btn:disabled { opacity: 0.5; cursor: default; }
230
+ .btn-primary { background: var(--n-accent); border-color: var(--n-accent); color: var(--n-accent-fg); }
231
+ .btn-primary:hover { background: var(--n-accent); filter: brightness(1.05); }
232
+ .btn-ghost { border-color: transparent; background: transparent; }
233
+ .btn-icon { width: 32px; padding: 0; justify-content: center; }
234
+ .btn-danger { color: var(--n-danger); }
235
+ .kbd { color: var(--n-fg-muted); font-size: 11px; }
236
+ .error { color: var(--n-danger); font-size: 12px; }
237
+ .divider { height: 1px; background: var(--n-border); }
238
+ .actions { display: flex; gap: 4px; padding: 8px 12px; border-top: 1px solid var(--n-border); background: var(--n-bg-subtle); }
239
+ .actions .spacer { flex: 1; }
240
+
241
+ /* Panel */
242
+ .panel {
243
+ position: fixed;
244
+ top: 12px;
245
+ right: 12px;
246
+ bottom: 72px;
247
+ width: 340px;
248
+ max-width: calc(100vw - 24px);
249
+ display: flex;
250
+ flex-direction: column;
251
+ background: var(--n-bg);
252
+ color: var(--n-fg);
253
+ border: 1px solid var(--n-border);
254
+ border-radius: var(--n-radius);
255
+ box-shadow: var(--n-shadow);
256
+ pointer-events: auto;
257
+ overflow: hidden;
258
+ }
259
+ .panel-head { display: flex; align-items: center; gap: 8px; padding: 12px; border-bottom: 1px solid var(--n-border); }
260
+ .panel-title { font-weight: 650; flex: 1; }
261
+ .tabs { display: flex; gap: 4px; padding: 8px 12px 0; }
262
+ .tab {
263
+ border: 0;
264
+ background: transparent;
265
+ padding: 6px 10px;
266
+ border-radius: 8px;
267
+ color: var(--n-fg-muted);
268
+ font-weight: 550;
269
+ font-size: 13px;
270
+ }
271
+ .tab[aria-selected="true"] { background: var(--n-bg-subtle); color: var(--n-fg); }
272
+ .panel-list { flex: 1; overflow: auto; padding: 8px; display: grid; align-content: start; gap: 4px; }
273
+ .item {
274
+ display: grid;
275
+ gap: 4px;
276
+ text-align: left;
277
+ width: 100%;
278
+ border: 0;
279
+ background: transparent;
280
+ padding: 10px;
281
+ border-radius: 10px;
282
+ }
283
+ .item:hover { background: var(--n-bg-subtle); }
284
+ .item-text { display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; word-break: break-word; }
285
+ .section-label { padding: 12px 10px 4px; font-size: 11px; font-weight: 650; letter-spacing: 0.04em; text-transform: uppercase; color: var(--n-fg-muted); }
286
+ .empty { padding: 32px 16px; text-align: center; color: var(--n-fg-muted); }
287
+ .panel-foot { padding: 12px; border-top: 1px solid var(--n-border); display: grid; gap: 8px; font-size: 13px; }
288
+ .link { border: 0; background: none; padding: 0; color: var(--n-accent); font-weight: 600; text-decoration: none; }
289
+ .link:hover { text-decoration: underline; }
290
+ a.item { color: inherit; text-decoration: none; }
291
+ .toggle { display: flex; align-items: center; gap: 8px; color: var(--n-fg-muted); font-size: 13px; }
292
+
293
+ .toast {
294
+ position: fixed;
295
+ left: 50%;
296
+ bottom: 72px;
297
+ transform: translateX(-50%);
298
+ padding: 8px 14px;
299
+ border-radius: 999px;
300
+ background: var(--n-fg);
301
+ color: var(--n-bg);
302
+ font-size: 13px;
303
+ box-shadow: var(--n-shadow);
304
+ pointer-events: none;
305
+ }
306
+
307
+ @media (max-width: 640px) {
308
+ .toolbar { right: 12px; bottom: 12px; }
309
+ .tb-label { display: none; }
310
+ .card.sheet {
311
+ left: 0 !important;
312
+ right: 0;
313
+ bottom: 0;
314
+ top: auto !important;
315
+ width: 100%;
316
+ max-width: none;
317
+ border-radius: 16px 16px 0 0;
318
+ padding-bottom: env(safe-area-inset-bottom);
319
+ }
320
+ .panel { top: auto; left: 0; right: 0; bottom: 0; width: 100%; max-width: none; height: 70vh; border-radius: 16px 16px 0 0; }
321
+ .pin { width: 32px; height: 32px; margin-top: -32px; }
322
+ .pin::after { content: ""; position: absolute; inset: -8px; }
323
+ }
324
+ @media (prefers-reduced-motion: reduce) {
325
+ * { transition: none !important; animation: none !important; }
326
+ }
327
+ `,this.pinLayer=q(`div`,{class:`pins`}),this.overlayLayer=q(`div`,{class:`overlay`}),this.uiLayer=q(`div`,{class:`ui`}),this.root.append(n,this.pinLayer,this.overlayLayer,this.uiLayer),this.api=new $n(e)}start(){document.body.appendChild(this.host),or(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(ar(()=>{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),this.cleanups.push(()=>{window.removeEventListener(`keydown`,e,!0),window.removeEventListener(`scroll`,t,!0),window.removeEventListener(`resize`,t),window.removeEventListener(`message`,n)});let r=new MutationObserver(e=>{e.every(e=>this.host.contains(e.target)||e.target===this.host)||this.scheduleResolve()});r.observe(document.body,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:[`class`,`style`,`hidden`,`open`,`id`]});let i=new ResizeObserver(()=>this.scheduleLayout());i.observe(document.documentElement),this.cleanups.push(()=>{r.disconnect(),i.disconnect()}),this.render()}destroy(){this.setPicking(!1),this.pageUnsub?.(),this.sessionUnsub?.();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)??o(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(!1),this.openDeepLink(),this.render()},()=>{}),this.render())}watchSession(e){this.sessionUnsub?.(),this.sessionUnsub=this.api.onSession(e,e=>{e.valid?this.ownerName=e.ownerName??`Owner`:(this.ownerName=null,this.ownerToken=null,Z(Q.session(this.config.project),null),this.sessionUnsub?.(),this.sessionUnsub=null),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===`open`||this.showResolved)}scheduleResolve(){clearTimeout(this.resolveTimer),this.resolveTimer=window.setTimeout(()=>this.resolvePlacements(!0),200)}resolvePlacements(e){let t=new Set(this.comments.map(e=>e._id));for(let e of this.placements.keys())t.has(e)||this.placements.delete(e);for(let t of this.comments){let n=this.placements.get(t._id);if(e&&n?.element&&n.element.isConnected){let e=C(n.element),r=t.anchor.text;if(!r||e===r||be(e,r)>.8)continue}let r=Ie(t.anchor,document,{isIgnored:this.isIgnored});this.placements.set(t._id,{element:r.element,confidence:r.confidence})}this.renderPins(),this.layout(),e&&this.panelOpen&&this.render()}pinPoint(e){let t=this.placements.get(e._id)?.element;if(!t||!m(t))return null;let n=t.getBoundingClientRect();return{x:n.left+e.anchor.offset.x*n.width,y:n.top+e.anchor.offset.y*n.height}}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.positionCard(),this.picking&&this.hoverEl&&this.renderHighlight()}setPicking(e){if(this.picking===e)return;this.picking=e;let t=document.documentElement;if(e){this.card=null,window.matchMedia(pr).matches&&(this.panelOpen=!1),t.classList.add(fr),this.injectCursorStyle(),document.addEventListener(`pointermove`,this.onPickMove,!0),document.addEventListener(`click`,this.onPickClick,!0);for(let e of[`pointerdown`,`mousedown`,`pointerup`,`mouseup`])document.addEventListener(e,this.swallow,{capture:!0,passive:!1})}else{t.classList.remove(fr),this.hoverEl=null,document.removeEventListener(`pointermove`,this.onPickMove,!0),document.removeEventListener(`click`,this.onPickClick,!0);for(let e of[`pointerdown`,`mousedown`,`pointerup`,`mouseup`])document.removeEventListener(e,this.swallow,!0)}this.render()}injectCursorStyle(){if(document.getElementById(`nuni-cursor-style`))return;let e=document.createElement(`style`);e.id=`nuni-cursor-style`,e.textContent=`html.${fr}, html.${fr} * { cursor: crosshair !important; }`,document.head.appendChild(e),this.cleanups.push(()=>e.remove())}fromPage(e){if(e.composedPath().includes(this.host))return null;let t=e.target;return t instanceof Element?t:null}renderHighlight(){if(this.overlayLayer.replaceChildren(),!this.picking)return;this.overlayLayer.append(q(`div`,{class:`pick-hint`},`Click anything to comment · Esc to cancel`));let e=this.hoverEl;if(!e||e===document.documentElement)return;let t=e.getBoundingClientRect(),n=q(`div`,{class:`highlight`},q(`span`,{class:`highlight-label`},hr(e)));Object.assign(n.style,{left:`${t.left-2}px`,top:`${t.top-2}px`,width:`${t.width+4}px`,height:`${t.height+4}px`}),this.overlayLayer.append(n)}onKeyDown(e){let t=e.composedPath().includes(this.host);if(e.key===`Escape`){if(this.picking)this.setPicking(!1);else if(this.card)this.closeCard();else if(this.panelOpen)this.togglePanel(!1);else return;e.stopPropagation();return}t||mr(e.target)||e.metaKey||e.ctrlKey||e.altKey||e.repeat||(e.key===`c`||e.key===`C`)&&(e.preventDefault(),this.setPicking(!this.picking))}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,Z(Q.session(this.config.project),n.token),this.watchSession(n.token),this.showToast(`You're signed in as the owner`))}signOut(){this.ownerToken&&this.api.signOut(this.ownerToken),Z(Q.session(this.config.project),null),this.ownerToken=null,this.ownerName=null,this.sessionUnsub?.(),this.sessionUnsub=null,this.render()}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(`That comment was deleted or is on another page`);return}this.extraComment=e,this.comments=[...this.comments.filter(t=>t._id!==e._id),e],this.resolvePlacements(!1),this.focusDeepLinked(e)})}focusDeepLinked(e){e.status===`resolved`&&!this.showResolved&&(this.showResolved=!0,this.renderPins()),this.focusComment(e._id)}focusComment(e){this.placements.get(e)?.element?.scrollIntoView({block:`center`,behavior:`smooth`}),this.activeId=e,this.card={kind:`thread`,id:e},window.matchMedia(pr).matches&&(this.panelOpen=!1),this.render(),setTimeout(()=>this.scheduleLayout(),400)}async submitDraft(e,t,n){let r=n.trim().slice(0,a.nameMaxLength),i=t.trim();if(!r)return this.setDraftError(e,`Enter your name`);if(!i)return this.setDraftError(e,`Write a comment first`);if(i.length>a.bodyMaxLength)return this.setDraftError(e,`Comments are limited to ${a.bodyMaxLength} characters`);this.name=r,Z(Q.name,r),e.sending=!0,e.error=void 0,this.render();let o=c(location.href);try{let t=await this.api.createComment({body:i,authorName:r,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}});this.placements.set(t,{element:e.element,confidence:`exact`}),this.card?.kind===`composer`&&this.card.draft===e&&(this.card=null),this.showToast(`Comment added`)}catch(t){e.sending=!1,e.error=t instanceof Zn?t.message:`Couldn't post the comment`}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:`Something went wrong`),this.render(),!1}}resolveComment(e){let t=this.ownerToken;t&&this.act(e._id,()=>this.api.resolve(e._id,t),`Resolved`).then(t=>{t&&!this.showResolved&&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),`Reopened`)}deleteComment(e){if(!window.confirm(`Delete this comment? This can't be undone.`))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,`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())})}saveEdit(e,t){this.act(e._id,()=>this.api.editOwn(e._id,this.secret,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){this.panelOpen=e,e&&window.matchMedia(pr).matches&&(this.card=null),this.render()}closeCard(){this.card=null,this.activeId=null,this.render()}render(){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=q(`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.activeId=n,this.card={kind:`thread`,id:n},this.render())}),this.pins.set(t._id,e),this.pinLayer.append(e)}e.textContent=tr(t.authorName),e.style.background=nr(t.authorName),e.setAttribute(`aria-label`,`Comment by ${t.authorName}: ${t.body.slice(0,80)}`),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,t=e.element.getBoundingClientRect(),n=t.left+e.anchor.offset.x*t.width,r=t.top+e.anchor.offset.y*t.height,i=q(`div`,{class:`pin pin-draft pin-pending`,"aria-hidden":`true`},this.name?tr(this.name):`+`);i.style.background=this.name?nr(this.name):`var(--n-accent)`,i.style.transform=`translate(${Math.round(n)}px, ${Math.round(r)}px)`,this.pinLayer.append(i)}}renderUi(){let e=[this.renderToolbar()];this.panelOpen&&e.push(this.renderPanel());let t=this.renderCard();t&&e.push(t),this.toast&&e.push(q(`div`,{class:`toast`,role:`status`},this.toast));let n=this.root.activeElement,r=n?.dataset.focusKey,i=n instanceof HTMLTextAreaElement||n instanceof HTMLInputElement?{start:n.selectionStart,end:n.selectionEnd}:null;if(this.uiLayer.replaceChildren(...e),r){let e=this.uiLayer.querySelector(`[data-focus-key="${r}"]`);e?.focus(),i&&(e instanceof HTMLTextAreaElement||e instanceof HTMLInputElement)&&e.setSelectionRange(i.start,i.end)}this.positionCard()}renderToolbar(){let e=this.comments.filter(e=>e.status===`open`).length;return q(`div`,{class:`toolbar`,role:`toolbar`,"aria-label":`Nuni comments`},q(`button`,{class:`tb-btn`,type:`button`,"aria-pressed":String(this.picking),"aria-label":this.picking?`Cancel adding a comment`:`Add a comment`,title:`Add a comment (C)`,onclick:()=>this.setPicking(!this.picking)},J(X.comment),q(`span`,{class:`tb-label`},this.picking?`Pick an element`:`Comment`)),q(`button`,{class:`tb-btn`,type:`button`,"aria-pressed":String(this.panelOpen),"aria-label":`Comments on this page: ${e} open`,title:`All comments`,onclick:()=>this.togglePanel()},J(X.list),q(`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=>q(`button`,{class:`item`,type:`button`,onclick:()=>{e.status===`resolved`&&!this.showResolved&&(this.showResolved=!0,Z(Q.showResolved,`1`)),this.focusComment(e._id)}},q(`div`,{class:`row`},q(`span`,{class:`avatar`,style:`background:${nr(e.authorName)}`},tr(e.authorName)),q(`span`,{class:`author`},e.authorName),q(`span`,{class:`meta`},er(e.createdAt)),e.page.origin===location.origin?null:q(`span`,{class:`badge`,title:e.page.origin},new URL(e.page.origin).host)),q(`div`,{class:`item-text`},e.body)),s=[];if(this.loaded?n.length?(s.push(...r.map(o)),i.length&&(s.push(q(`div`,{class:`section-label`},`Couldn't find on this page`)),s.push(...i.map(o)))):s.push(q(`div`,{class:`empty`},this.tab===`open`?`No open comments on this page. Press C to add one.`:`Nothing resolved yet.`)):s.push(q(`div`,{class:`empty`},`Loading…`)),a.length){s.push(q(`div`,{class:`section-label`},`Other pages`));for(let e of a.slice(0,20)){let t=e.path.includes(`#`)?location.origin+e.path:location.origin+e.path+location.search;s.push(q(`a`,{class:`item`,href:t},q(`div`,{class:`row`},q(`span`,{class:`author`},e.path),q(`span`,{class:`spacer`}),q(`span`,{class:`badge`},`${e.count} open`))))}}return q(`div`,{class:`panel`,role:`dialog`,"aria-label":`Comments`},q(`div`,{class:`panel-head`},q(`div`,{class:`panel-title`},`Comments`),q(`button`,{class:`btn btn-ghost btn-icon`,type:`button`,"aria-label":`Close`,onclick:()=>this.togglePanel(!1)},J(X.close))),q(`div`,{class:`tabs`,role:`tablist`},q(`button`,{class:`tab`,role:`tab`,type:`button`,"aria-selected":String(this.tab===`open`),onclick:()=>{this.tab=`open`,this.render()}},`Open (${e.length})`),q(`button`,{class:`tab`,role:`tab`,type:`button`,"aria-selected":String(this.tab===`resolved`),onclick:()=>{this.tab=`resolved`,this.render()}},`Resolved (${t.length})`)),q(`div`,{class:`panel-list`},...s),this.renderPanelFooter())}renderPanelFooter(){let e=q(`label`,{class:`toggle`},q(`input`,{type:`checkbox`,checked:this.showResolved,onchange:e=>{this.showResolved=e.target.checked,Z(Q.showResolved,this.showResolved?`1`:null),this.render()}}),`Show resolved pins`),t;return t=this.isOwner?q(`div`,{class:`row`},q(`span`,{class:`badge badge-ok`},J(X.check),`Owner`),q(`span`,{class:`meta`},this.ownerName??``),q(`span`,{class:`spacer`}),q(`a`,{class:`link`,href:`${this.config.appUrl}/dashboard/p/${this.config.project}`,target:`_blank`,rel:`noopener`},`Dashboard`),q(`button`,{class:`link`,type:`button`,onclick:()=>this.signOut()},`Sign out`)):this.status.claimed?q(`div`,{class:`row`},q(`span`,{class:`meta`},`Managed by ${this.status.ownerName??`the owner`}`),q(`span`,{class:`spacer`}),q(`button`,{class:`link`,type:`button`,onclick:()=>this.openClaim()},`Owner sign in`)):q(`div`,{class:`row`},q(`span`,{class:`meta`},`Own this website?`),q(`span`,{class:`spacer`}),q(`button`,{class:`btn`,type:`button`,onclick:()=>this.openClaim()},J(X.github),`Claim Nuni`)),q(`div`,{class:`panel-foot`},e,t)}renderCard(){let e=this.card;if(!e)return null;let t=`card${window.matchMedia(pr).matches?` sheet`:``}`;if(e.kind===`composer`){let{draft:n}=e,r=!this.name,i=q(`input`,{class:`field`,placeholder:`Your name`,value:this.name,maxlength:a.nameMaxLength,autocomplete:`name`,"data-focus-key":`name`,"aria-label":`Your name`}),o=q(`textarea`,{class:`field`,placeholder:`Leave a comment`,maxlength:a.bodyMaxLength,"data-focus-key":`body`,"aria-label":`Comment`}),s=this.uiLayer.querySelector(`[data-focus-key="body"]`);s&&(o.value=s.value);let c=this.uiLayer.querySelector(`[data-focus-key="name"]`);c&&(i.value=c.value);let l=()=>void this.submitDraft(n,o.value,r?i.value:this.name);return o.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&(e.preventDefault(),l())}),q(`form`,{class:t,"data-card":`composer`,onsubmit:e=>{e.preventDefault(),l()}},q(`div`,{class:`card-body`},r?i:q(`div`,{class:`row`},q(`span`,{class:`avatar`,style:`background:${nr(this.name)}`},tr(this.name)),q(`span`,{class:`author`},this.name),q(`span`,{class:`spacer`}),q(`button`,{class:`link`,type:`button`,onclick:()=>{this.name=``,this.render()}},`Not you?`)),o,n.error?q(`div`,{class:`error`,role:`alert`},n.error):null,q(`div`,{class:`row`},q(`span`,{class:`kbd`},`⌘ + Enter`),q(`span`,{class:`spacer`}),q(`button`,{class:`btn btn-ghost`,type:`button`,onclick:()=>this.closeCard()},`Cancel`),q(`button`,{class:`btn btn-primary`,type:`submit`,disabled:!!n.sending},J(X.send),n.sending?`Posting…`:`Post`))))}let n=this.comments.find(t=>t._id===e.id);if(!n)return null;let r=this.isMine(n),i=this.isOwner,o=this.placements.get(n._id),s;if(e.editing){let t=q(`textarea`,{class:`field`,maxlength:a.bodyMaxLength,"data-focus-key":`edit`}),r=this.uiLayer.querySelector(`[data-focus-key="edit"]`);t.value=r?r.value:n.body,s=q(`div`,{class:`card-body`},t,q(`div`,{class:`row`},q(`span`,{class:`spacer`}),q(`button`,{class:`btn btn-ghost`,type:`button`,onclick:()=>{e.editing=!1,this.render()}},`Cancel`),q(`button`,{class:`btn btn-primary`,type:`button`,disabled:!!e.busy,onclick:()=>this.saveEdit(n,t.value)},`Save`)))}else s=q(`div`,{class:`card-body`},q(`div`,{class:`card-head`},q(`span`,{class:`avatar`,style:`background:${nr(n.authorName)}`},tr(n.authorName)),q(`span`,{class:`author`},n.authorName),q(`span`,{class:`meta`},er(n.createdAt)+(n.editedAt?` · edited`:``)),q(`span`,{class:`spacer`}),q(`button`,{class:`btn btn-ghost btn-icon`,type:`button`,"aria-label":`Close`,onclick:()=>this.closeCard()},J(X.close))),q(`div`,{class:`comment-body`},n.body),q(`div`,{class:`row`},n.status===`resolved`?q(`span`,{class:`badge badge-ok`},J(X.check),`Resolved`):null,n.page.origin===location.origin?null:q(`span`,{class:`badge`,title:`Left on ${n.page.origin}`},new URL(n.page.origin).host),o?.confidence===`low`?q(`span`,{class:`badge`,title:`The page changed; this pin is a best guess`},`Approximate`):null,o?.element?null:q(`span`,{class:`badge`,title:`Originally on: ${n.anchor.text||n.anchor.tag}`},`Element not found`)),e.error?q(`div`,{class:`error`,role:`alert`},e.error):null);let c=[];return e.editing||(i&&c.push(n.status===`open`?q(`button`,{class:`btn`,type:`button`,disabled:!!e.busy,onclick:()=>this.resolveComment(n)},J(X.check),`Resolve`):q(`button`,{class:`btn`,type:`button`,disabled:!!e.busy,onclick:()=>this.reopenComment(n)},J(X.undo),`Reopen`)),c.push(q(`span`,{class:`spacer`})),r&&c.push(q(`button`,{class:`btn btn-ghost btn-icon`,type:`button`,"aria-label":`Edit`,title:`Edit`,onclick:()=>{e.editing=!0,this.render()}},J(X.edit))),(r||i)&&c.push(q(`button`,{class:`btn btn-ghost btn-icon btn-danger`,type:`button`,"aria-label":`Delete`,title:`Delete`,disabled:!!e.busy,onclick:()=>this.deleteComment(n)},J(X.trash)))),q(`div`,{class:t,"data-card":`thread`,role:`dialog`,"aria-label":`Comment by ${n.authorName}`},s,c.length>1||i?q(`div`,{class:`actions`},...c):null)}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,n=e.element.getBoundingClientRect();t={x:n.left+e.anchor.offset.x*n.width,y:n.top+e.anchor.offset.y*n.height}}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;t?(o=t.x+36,s=t.y-28,o+n>i-12&&(o=t.x-n-12)):(o=i-n-16,s=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()})}};let $=null;function _r(e){let t={destroy(){}};if(typeof window>`u`||typeof document>`u`)return t;if(!r(e.project))return console.warn(`[nuni] "${e.project}" is not a valid project ID. Run \`npx @nuniapp/cli init\` to get one.`),t;if($?.project===e.project)return vr($);$&&yr($);let n=l(e),i={project:e.project,widget:null,timer:0,handles:0};$=i;let a=()=>{if($===i){if(!document.body){i.timer=window.setTimeout(a,50);return}i.widget=new gr(n),i.widget.start()}},o=window.requestIdleCallback;return o?o(a,{timeout:1500}):i.timer=window.setTimeout(a,1),vr(i)}function vr(e){e.handles++;let t=!1;return{destroy(){t||(t=!0,e.handles--,e.handles<=0&&$===e&&yr(e))}}}function yr(e){clearTimeout(e.timer),e.widget?.destroy(),e.widget=null,$===e&&($=null)}window.Nuni={init:_r,version:`0.1.0`};let br=document.currentScript??document.querySelector(`script[data-project][src*='nuni']`),xr=br?.dataset.project;xr&&_r({project:xr,convexUrl:br?.dataset.convexUrl,convexSiteUrl:br?.dataset.convexSiteUrl,appUrl:br?.dataset.appUrl})})();