diff --git a/dist/assets/index-BHCNYw42.js b/dist/assets/index-BHCNYw42.js new file mode 100644 index 0000000..d48094b --- /dev/null +++ b/dist/assets/index-BHCNYw42.js @@ -0,0 +1,473 @@ +function ty(e,t){for(var n=0;nr[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();function cu(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Fh={exports:{}},Eo={},Ih={exports:{}},Y={};/** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var qs=Symbol.for("react.element"),ny=Symbol.for("react.portal"),ry=Symbol.for("react.fragment"),sy=Symbol.for("react.strict_mode"),iy=Symbol.for("react.profiler"),oy=Symbol.for("react.provider"),ay=Symbol.for("react.context"),ly=Symbol.for("react.forward_ref"),uy=Symbol.for("react.suspense"),cy=Symbol.for("react.memo"),dy=Symbol.for("react.lazy"),Vc=Symbol.iterator;function fy(e){return e===null||typeof e!="object"?null:(e=Vc&&e[Vc]||e["@@iterator"],typeof e=="function"?e:null)}var zh={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Oh=Object.assign,$h={};function Fr(e,t,n){this.props=e,this.context=t,this.refs=$h,this.updater=n||zh}Fr.prototype.isReactComponent={};Fr.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};Fr.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function Bh(){}Bh.prototype=Fr.prototype;function du(e,t,n){this.props=e,this.context=t,this.refs=$h,this.updater=n||zh}var fu=du.prototype=new Bh;fu.constructor=du;Oh(fu,Fr.prototype);fu.isPureReactComponent=!0;var Fc=Array.isArray,Uh=Object.prototype.hasOwnProperty,hu={current:null},Wh={key:!0,ref:!0,__self:!0,__source:!0};function Hh(e,t,n){var r,s={},i=null,o=null;if(t!=null)for(r in t.ref!==void 0&&(o=t.ref),t.key!==void 0&&(i=""+t.key),t)Uh.call(t,r)&&!Wh.hasOwnProperty(r)&&(s[r]=t[r]);var a=arguments.length-2;if(a===1)s.children=n;else if(1>>1,E=_[L];if(0>>1;Ls(te,F))Gs(be,te)?(_[L]=be,_[G]=F,L=G):(_[L]=te,_[X]=F,L=X);else if(Gs(be,F))_[L]=be,_[G]=F,L=G;else break e}}return N}function s(_,N){var F=_.sortIndex-N.sortIndex;return F!==0?F:_.id-N.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var o=Date,a=o.now();e.unstable_now=function(){return o.now()-a}}var l=[],c=[],d=1,f=null,u=3,h=!1,p=!1,g=!1,x=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,y=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function w(_){for(var N=n(c);N!==null;){if(N.callback===null)r(c);else if(N.startTime<=_)r(c),N.sortIndex=N.expirationTime,t(l,N);else break;N=n(c)}}function b(_){if(g=!1,w(_),!p)if(n(l)!==null)p=!0,A(S);else{var N=n(c);N!==null&&q(b,N.startTime-_)}}function S(_,N){p=!1,g&&(g=!1,v(j),j=-1),h=!0;var F=u;try{for(w(N),f=n(l);f!==null&&(!(f.expirationTime>N)||_&&!z());){var L=f.callback;if(typeof L=="function"){f.callback=null,u=f.priorityLevel;var E=L(f.expirationTime<=N);N=e.unstable_now(),typeof E=="function"?f.callback=E:f===n(l)&&r(l),w(N)}else r(l);f=n(l)}if(f!==null)var W=!0;else{var X=n(c);X!==null&&q(b,X.startTime-N),W=!1}return W}finally{f=null,u=F,h=!1}}var C=!1,P=null,j=-1,D=5,T=-1;function z(){return!(e.unstable_now()-T_||125<_?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):D=0<_?Math.floor(1e3/_):5},e.unstable_getCurrentPriorityLevel=function(){return u},e.unstable_getFirstCallbackNode=function(){return n(l)},e.unstable_next=function(_){switch(u){case 1:case 2:case 3:var N=3;break;default:N=u}var F=u;u=N;try{return _()}finally{u=F}},e.unstable_pauseExecution=function(){},e.unstable_requestPaint=function(){},e.unstable_runWithPriority=function(_,N){switch(_){case 1:case 2:case 3:case 4:case 5:break;default:_=3}var F=u;u=_;try{return N()}finally{u=F}},e.unstable_scheduleCallback=function(_,N,F){var L=e.unstable_now();switch(typeof F=="object"&&F!==null?(F=F.delay,F=typeof F=="number"&&0L?(_.sortIndex=F,t(c,_),n(l)===null&&_===n(c)&&(g?(v(j),j=-1):g=!0,q(b,F-L))):(_.sortIndex=E,t(l,_),p||h||(p=!0,A(S))),_},e.unstable_shouldYield=z,e.unstable_wrapCallback=function(_){var N=u;return function(){var F=u;u=N;try{return _.apply(this,arguments)}finally{u=F}}}})(Xh);Kh.exports=Xh;var Cy=Kh.exports;/** + * @license React + * react-dom.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Py=k,Ze=Cy;function M(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Xa=Object.prototype.hasOwnProperty,jy=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,zc={},Oc={};function Ey(e){return Xa.call(Oc,e)?!0:Xa.call(zc,e)?!1:jy.test(e)?Oc[e]=!0:(zc[e]=!0,!1)}function Ty(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Ny(e,t,n,r){if(t===null||typeof t>"u"||Ty(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function $e(e,t,n,r,s,i,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=o}var _e={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){_e[e]=new $e(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];_e[t]=new $e(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){_e[e]=new $e(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){_e[e]=new $e(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){_e[e]=new $e(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){_e[e]=new $e(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){_e[e]=new $e(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){_e[e]=new $e(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){_e[e]=new $e(e,5,!1,e.toLowerCase(),null,!1,!1)});var mu=/[\-:]([a-z])/g;function gu(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(mu,gu);_e[t]=new $e(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(mu,gu);_e[t]=new $e(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(mu,gu);_e[t]=new $e(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){_e[e]=new $e(e,1,!1,e.toLowerCase(),null,!1,!1)});_e.xlinkHref=new $e("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){_e[e]=new $e(e,1,!1,e.toLowerCase(),null,!0,!0)});function yu(e,t,n,r){var s=_e.hasOwnProperty(t)?_e[t]:null;(s!==null?s.type!==0:r||!(2a||s[o]!==i[a]){var l=` +`+s[o].replace(" at new "," at ");return e.displayName&&l.includes("")&&(l=l.replace("",e.displayName)),l}while(1<=o&&0<=a);break}}}finally{ia=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?rs(e):""}function My(e){switch(e.tag){case 5:return rs(e.type);case 16:return rs("Lazy");case 13:return rs("Suspense");case 19:return rs("SuspenseList");case 0:case 2:case 15:return e=oa(e.type,!1),e;case 11:return e=oa(e.type.render,!1),e;case 1:return e=oa(e.type,!0),e;default:return""}}function el(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case rr:return"Fragment";case nr:return"Portal";case Qa:return"Profiler";case vu:return"StrictMode";case Za:return"Suspense";case Ja:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Jh:return(e.displayName||"Context")+".Consumer";case Zh:return(e._context.displayName||"Context")+".Provider";case xu:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case wu:return t=e.displayName||null,t!==null?t:el(e.type)||"Memo";case Zt:t=e._payload,e=e._init;try{return el(e(t))}catch{}}return null}function _y(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return el(t);case 8:return t===vu?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function vn(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function tp(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Ay(e){var t=tp(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var s=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(o){r=""+o,i.call(this,o)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function oi(e){e._valueTracker||(e._valueTracker=Ay(e))}function np(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=tp(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Ui(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function tl(e,t){var n=t.checked;return fe({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Bc(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=vn(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function rp(e,t){t=t.checked,t!=null&&yu(e,"checked",t,!1)}function nl(e,t){rp(e,t);var n=vn(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?rl(e,t.type,n):t.hasOwnProperty("defaultValue")&&rl(e,t.type,vn(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Uc(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function rl(e,t,n){(t!=="number"||Ui(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var ss=Array.isArray;function vr(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=ai.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Cs(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var ls={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Ly=["Webkit","ms","Moz","O"];Object.keys(ls).forEach(function(e){Ly.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),ls[t]=ls[e]})});function ap(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||ls.hasOwnProperty(e)&&ls[e]?(""+t).trim():t+"px"}function lp(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=ap(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var Dy=fe({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ol(e,t){if(t){if(Dy[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(M(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(M(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(M(61))}if(t.style!=null&&typeof t.style!="object")throw Error(M(62))}}function al(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var ll=null;function bu(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ul=null,xr=null,wr=null;function qc(e){if(e=Xs(e)){if(typeof ul!="function")throw Error(M(280));var t=e.stateNode;t&&(t=Ao(t),ul(e.stateNode,e.type,t))}}function up(e){xr?wr?wr.push(e):wr=[e]:xr=e}function cp(){if(xr){var e=xr,t=wr;if(wr=xr=null,qc(e),t)for(e=0;e>>=0,e===0?32:31-(Hy(e)/qy|0)|0}var li=64,ui=4194304;function is(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function Gi(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,i=e.pingedLanes,o=n&268435455;if(o!==0){var a=o&~s;a!==0?r=is(a):(i&=o,i!==0&&(r=is(i)))}else o=n&~s,o!==0?r=is(o):i!==0&&(r=is(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&s)&&(s=r&-r,i=t&-t,s>=i||s===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Ys(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-gt(t),e[t]=n}function Xy(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=cs),td=" ",nd=!1;function Mp(e,t){switch(e){case"keyup":return C1.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function _p(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var sr=!1;function j1(e,t){switch(e){case"compositionend":return _p(t);case"keypress":return t.which!==32?null:(nd=!0,td);case"textInput":return e=t.data,e===td&&nd?null:e;default:return null}}function E1(e,t){if(sr)return e==="compositionend"||!Nu&&Mp(e,t)?(e=Tp(),Mi=ju=sn=null,sr=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=od(n)}}function Rp(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Rp(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Vp(){for(var e=window,t=Ui();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Ui(e.document)}return t}function Mu(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function V1(e){var t=Vp(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Rp(n.ownerDocument.documentElement,n)){if(r!==null&&Mu(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var s=n.textContent.length,i=Math.min(r.start,s);r=r.end===void 0?i:Math.min(r.end,s),!e.extend&&i>r&&(s=r,r=i,i=s),s=ad(n,i);var o=ad(n,r);s&&o&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,ir=null,ml=null,fs=null,gl=!1;function ld(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;gl||ir==null||ir!==Ui(r)||(r=ir,"selectionStart"in r&&Mu(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),fs&&Ms(fs,r)||(fs=r,r=Xi(ml,"onSelect"),0lr||(e.current=Sl[lr],Sl[lr]=null,lr--)}function J(e,t){lr++,Sl[lr]=e.current,e.current=t}var xn={},Ve=kn(xn),We=kn(!1),Un=xn;function Er(e,t){var n=e.type.contextTypes;if(!n)return xn;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var s={},i;for(i in n)s[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function He(e){return e=e.childContextTypes,e!=null}function Zi(){ie(We),ie(Ve)}function md(e,t,n){if(Ve.current!==xn)throw Error(M(168));J(Ve,t),J(We,n)}function Hp(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(M(108,_y(e)||"Unknown",s));return fe({},n,r)}function Ji(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||xn,Un=Ve.current,J(Ve,e),J(We,We.current),!0}function gd(e,t,n){var r=e.stateNode;if(!r)throw Error(M(169));n?(e=Hp(e,t,Un),r.__reactInternalMemoizedMergedChildContext=e,ie(We),ie(Ve),J(Ve,e)):ie(We),J(We,n)}var Lt=null,Lo=!1,wa=!1;function qp(e){Lt===null?Lt=[e]:Lt.push(e)}function Y1(e){Lo=!0,qp(e)}function Cn(){if(!wa&&Lt!==null){wa=!0;var e=0,t=Z;try{var n=Lt;for(Z=1;e>=o,s-=o,Dt=1<<32-gt(t)+s|n<j?(D=P,P=null):D=P.sibling;var T=u(v,P,w[j],b);if(T===null){P===null&&(P=D);break}e&&P&&T.alternate===null&&t(v,P),y=i(T,y,j),C===null?S=T:C.sibling=T,C=T,P=D}if(j===w.length)return n(v,P),le&&An(v,j),S;if(P===null){for(;jj?(D=P,P=null):D=P.sibling;var z=u(v,P,T.value,b);if(z===null){P===null&&(P=D);break}e&&P&&z.alternate===null&&t(v,P),y=i(z,y,j),C===null?S=z:C.sibling=z,C=z,P=D}if(T.done)return n(v,P),le&&An(v,j),S;if(P===null){for(;!T.done;j++,T=w.next())T=f(v,T.value,b),T!==null&&(y=i(T,y,j),C===null?S=T:C.sibling=T,C=T);return le&&An(v,j),S}for(P=r(v,P);!T.done;j++,T=w.next())T=h(P,v,j,T.value,b),T!==null&&(e&&T.alternate!==null&&P.delete(T.key===null?j:T.key),y=i(T,y,j),C===null?S=T:C.sibling=T,C=T);return e&&P.forEach(function(V){return t(v,V)}),le&&An(v,j),S}function x(v,y,w,b){if(typeof w=="object"&&w!==null&&w.type===rr&&w.key===null&&(w=w.props.children),typeof w=="object"&&w!==null){switch(w.$$typeof){case ii:e:{for(var S=w.key,C=y;C!==null;){if(C.key===S){if(S=w.type,S===rr){if(C.tag===7){n(v,C.sibling),y=s(C,w.props.children),y.return=v,v=y;break e}}else if(C.elementType===S||typeof S=="object"&&S!==null&&S.$$typeof===Zt&&xd(S)===C.type){n(v,C.sibling),y=s(C,w.props),y.ref=Xr(v,C,w),y.return=v,v=y;break e}n(v,C);break}else t(v,C);C=C.sibling}w.type===rr?(y=$n(w.props.children,v.mode,b,w.key),y.return=v,v=y):(b=Ii(w.type,w.key,w.props,null,v.mode,b),b.ref=Xr(v,y,w),b.return=v,v=b)}return o(v);case nr:e:{for(C=w.key;y!==null;){if(y.key===C)if(y.tag===4&&y.stateNode.containerInfo===w.containerInfo&&y.stateNode.implementation===w.implementation){n(v,y.sibling),y=s(y,w.children||[]),y.return=v,v=y;break e}else{n(v,y);break}else t(v,y);y=y.sibling}y=Ta(w,v.mode,b),y.return=v,v=y}return o(v);case Zt:return C=w._init,x(v,y,C(w._payload),b)}if(ss(w))return p(v,y,w,b);if(Hr(w))return g(v,y,w,b);gi(v,w)}return typeof w=="string"&&w!==""||typeof w=="number"?(w=""+w,y!==null&&y.tag===6?(n(v,y.sibling),y=s(y,w),y.return=v,v=y):(n(v,y),y=Ea(w,v.mode,b),y.return=v,v=y),o(v)):n(v,y)}return x}var Nr=Xp(!0),Qp=Xp(!1),no=kn(null),ro=null,dr=null,Du=null;function Ru(){Du=dr=ro=null}function Vu(e){var t=no.current;ie(no),e._currentValue=t}function Pl(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function Sr(e,t){ro=e,Du=dr=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Ue=!0),e.firstContext=null)}function ut(e){var t=e._currentValue;if(Du!==e)if(e={context:e,memoizedValue:t,next:null},dr===null){if(ro===null)throw Error(M(308));dr=e,ro.dependencies={lanes:0,firstContext:e}}else dr=dr.next=e;return t}var Fn=null;function Fu(e){Fn===null?Fn=[e]:Fn.push(e)}function Zp(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,Fu(t)):(n.next=s.next,s.next=n),t.interleaved=n,Bt(e,r)}function Bt(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Jt=!1;function Iu(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Jp(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Ft(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function fn(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,K&2){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,Bt(e,n)}return s=r.interleaved,s===null?(t.next=t,Fu(r)):(t.next=s.next,s.next=t),r.interleaved=t,Bt(e,n)}function Ai(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ku(e,n)}}function wd(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?s=i=o:i=i.next=o,n=n.next}while(n!==null);i===null?s=i=t:i=i.next=t}else s=i=t;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function so(e,t,n,r){var s=e.updateQueue;Jt=!1;var i=s.firstBaseUpdate,o=s.lastBaseUpdate,a=s.shared.pending;if(a!==null){s.shared.pending=null;var l=a,c=l.next;l.next=null,o===null?i=c:o.next=c,o=l;var d=e.alternate;d!==null&&(d=d.updateQueue,a=d.lastBaseUpdate,a!==o&&(a===null?d.firstBaseUpdate=c:a.next=c,d.lastBaseUpdate=l))}if(i!==null){var f=s.baseState;o=0,d=c=l=null,a=i;do{var u=a.lane,h=a.eventTime;if((r&u)===u){d!==null&&(d=d.next={eventTime:h,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var p=e,g=a;switch(u=t,h=n,g.tag){case 1:if(p=g.payload,typeof p=="function"){f=p.call(h,f,u);break e}f=p;break e;case 3:p.flags=p.flags&-65537|128;case 0:if(p=g.payload,u=typeof p=="function"?p.call(h,f,u):p,u==null)break e;f=fe({},f,u);break e;case 2:Jt=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,u=s.effects,u===null?s.effects=[a]:u.push(a))}else h={eventTime:h,lane:u,tag:a.tag,payload:a.payload,callback:a.callback,next:null},d===null?(c=d=h,l=f):d=d.next=h,o|=u;if(a=a.next,a===null){if(a=s.shared.pending,a===null)break;u=a,a=u.next,u.next=null,s.lastBaseUpdate=u,s.shared.pending=null}}while(!0);if(d===null&&(l=f),s.baseState=l,s.firstBaseUpdate=c,s.lastBaseUpdate=d,t=s.shared.interleaved,t!==null){s=t;do o|=s.lane,s=s.next;while(s!==t)}else i===null&&(s.shared.lanes=0);qn|=o,e.lanes=o,e.memoizedState=f}}function bd(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Sa.transition;Sa.transition={};try{e(!1),t()}finally{Z=n,Sa.transition=r}}function gm(){return ct().memoizedState}function Z1(e,t,n){var r=pn(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},ym(e))vm(t,n);else if(n=Zp(e,t,n,r),n!==null){var s=ze();yt(n,e,r,s),xm(n,t,r)}}function J1(e,t,n){var r=pn(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(ym(e))vm(t,s);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var o=t.lastRenderedState,a=i(o,n);if(s.hasEagerState=!0,s.eagerState=a,xt(a,o)){var l=t.interleaved;l===null?(s.next=s,Fu(t)):(s.next=l.next,l.next=s),t.interleaved=s;return}}catch{}finally{}n=Zp(e,t,s,r),n!==null&&(s=ze(),yt(n,e,r,s),xm(n,t,r))}}function ym(e){var t=e.alternate;return e===de||t!==null&&t===de}function vm(e,t){hs=oo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function xm(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ku(e,n)}}var ao={readContext:ut,useCallback:Ae,useContext:Ae,useEffect:Ae,useImperativeHandle:Ae,useInsertionEffect:Ae,useLayoutEffect:Ae,useMemo:Ae,useReducer:Ae,useRef:Ae,useState:Ae,useDebugValue:Ae,useDeferredValue:Ae,useTransition:Ae,useMutableSource:Ae,useSyncExternalStore:Ae,useId:Ae,unstable_isNewReconciler:!1},ev={readContext:ut,useCallback:function(e,t){return St().memoizedState=[e,t===void 0?null:t],e},useContext:ut,useEffect:kd,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Di(4194308,4,dm.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Di(4194308,4,e,t)},useInsertionEffect:function(e,t){return Di(4,2,e,t)},useMemo:function(e,t){var n=St();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=St();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Z1.bind(null,de,e),[r.memoizedState,e]},useRef:function(e){var t=St();return e={current:e},t.memoizedState=e},useState:Sd,useDebugValue:qu,useDeferredValue:function(e){return St().memoizedState=e},useTransition:function(){var e=Sd(!1),t=e[0];return e=Q1.bind(null,e[1]),St().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=de,s=St();if(le){if(n===void 0)throw Error(M(407));n=n()}else{if(n=t(),Ee===null)throw Error(M(349));Hn&30||rm(r,t,n)}s.memoizedState=n;var i={value:n,getSnapshot:t};return s.queue=i,kd(im.bind(null,r,i,e),[e]),r.flags|=2048,Is(9,sm.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=St(),t=Ee.identifierPrefix;if(le){var n=Rt,r=Dt;n=(r&~(1<<32-gt(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Vs++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=o.createElement(n,{is:r.is}):(e=o.createElement(n),n==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,n),e[kt]=t,e[Ls]=r,Nm(e,t,!1,!1),t.stateNode=e;e:{switch(o=al(n,r),n){case"dialog":re("cancel",e),re("close",e),s=r;break;case"iframe":case"object":case"embed":re("load",e),s=r;break;case"video":case"audio":for(s=0;sAr&&(t.flags|=128,r=!0,Qr(i,!1),t.lanes=4194304)}else{if(!r)if(e=io(o),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Qr(i,!0),i.tail===null&&i.tailMode==="hidden"&&!o.alternate&&!le)return Le(t),null}else 2*ge()-i.renderingStartTime>Ar&&n!==1073741824&&(t.flags|=128,r=!0,Qr(i,!1),t.lanes=4194304);i.isBackwards?(o.sibling=t.child,t.child=o):(n=i.last,n!==null?n.sibling=o:t.child=o,i.last=o)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=ge(),t.sibling=null,n=ue.current,J(ue,r?n&1|2:n&1),t):(Le(t),null);case 22:case 23:return Zu(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Ye&1073741824&&(Le(t),t.subtreeFlags&6&&(t.flags|=8192)):Le(t),null;case 24:return null;case 25:return null}throw Error(M(156,t.tag))}function lv(e,t){switch(Au(t),t.tag){case 1:return He(t.type)&&Zi(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Mr(),ie(We),ie(Ve),$u(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Ou(t),null;case 13:if(ie(ue),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(M(340));Tr()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ie(ue),null;case 4:return Mr(),null;case 10:return Vu(t.type._context),null;case 22:case 23:return Zu(),null;case 24:return null;default:return null}}var vi=!1,Re=!1,uv=typeof WeakSet=="function"?WeakSet:Set,I=null;function fr(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){pe(e,t,r)}else n.current=null}function Dl(e,t,n){try{n()}catch(r){pe(e,t,r)}}var Dd=!1;function cv(e,t){if(yl=Yi,e=Vp(),Mu(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var s=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var o=0,a=-1,l=-1,c=0,d=0,f=e,u=null;t:for(;;){for(var h;f!==n||s!==0&&f.nodeType!==3||(a=o+s),f!==i||r!==0&&f.nodeType!==3||(l=o+r),f.nodeType===3&&(o+=f.nodeValue.length),(h=f.firstChild)!==null;)u=f,f=h;for(;;){if(f===e)break t;if(u===n&&++c===s&&(a=o),u===i&&++d===r&&(l=o),(h=f.nextSibling)!==null)break;f=u,u=f.parentNode}f=h}n=a===-1||l===-1?null:{start:a,end:l}}else n=null}n=n||{start:0,end:0}}else n=null;for(vl={focusedElem:e,selectionRange:n},Yi=!1,I=t;I!==null;)if(t=I,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,I=e;else for(;I!==null;){t=I;try{var p=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(p!==null){var g=p.memoizedProps,x=p.memoizedState,v=t.stateNode,y=v.getSnapshotBeforeUpdate(t.elementType===t.type?g:ft(t.type,g),x);v.__reactInternalSnapshotBeforeUpdate=y}break;case 3:var w=t.stateNode.containerInfo;w.nodeType===1?w.textContent="":w.nodeType===9&&w.documentElement&&w.removeChild(w.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(M(163))}}catch(b){pe(t,t.return,b)}if(e=t.sibling,e!==null){e.return=t.return,I=e;break}I=t.return}return p=Dd,Dd=!1,p}function ps(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var i=s.destroy;s.destroy=void 0,i!==void 0&&Dl(t,n,i)}s=s.next}while(s!==r)}}function Vo(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Rl(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Am(e){var t=e.alternate;t!==null&&(e.alternate=null,Am(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[kt],delete t[Ls],delete t[bl],delete t[q1],delete t[G1])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Lm(e){return e.tag===5||e.tag===3||e.tag===4}function Rd(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Lm(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Vl(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Qi));else if(r!==4&&(e=e.child,e!==null))for(Vl(e,t,n),e=e.sibling;e!==null;)Vl(e,t,n),e=e.sibling}function Fl(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Fl(e,t,n),e=e.sibling;e!==null;)Fl(e,t,n),e=e.sibling}var Ne=null,ht=!1;function Yt(e,t,n){for(n=n.child;n!==null;)Dm(e,t,n),n=n.sibling}function Dm(e,t,n){if(jt&&typeof jt.onCommitFiberUnmount=="function")try{jt.onCommitFiberUnmount(To,n)}catch{}switch(n.tag){case 5:Re||fr(n,t);case 6:var r=Ne,s=ht;Ne=null,Yt(e,t,n),Ne=r,ht=s,Ne!==null&&(ht?(e=Ne,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Ne.removeChild(n.stateNode));break;case 18:Ne!==null&&(ht?(e=Ne,n=n.stateNode,e.nodeType===8?xa(e.parentNode,n):e.nodeType===1&&xa(e,n),Ts(e)):xa(Ne,n.stateNode));break;case 4:r=Ne,s=ht,Ne=n.stateNode.containerInfo,ht=!0,Yt(e,t,n),Ne=r,ht=s;break;case 0:case 11:case 14:case 15:if(!Re&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var i=s,o=i.destroy;i=i.tag,o!==void 0&&(i&2||i&4)&&Dl(n,t,o),s=s.next}while(s!==r)}Yt(e,t,n);break;case 1:if(!Re&&(fr(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(a){pe(n,t,a)}Yt(e,t,n);break;case 21:Yt(e,t,n);break;case 22:n.mode&1?(Re=(r=Re)||n.memoizedState!==null,Yt(e,t,n),Re=r):Yt(e,t,n);break;default:Yt(e,t,n)}}function Vd(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new uv),t.forEach(function(r){var s=xv.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function dt(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=o),r&=~i}if(r=s,r=ge()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*fv(r/1960))-r,10e?16:e,on===null)var r=!1;else{if(e=on,on=null,co=0,K&6)throw Error(M(331));var s=K;for(K|=4,I=e.current;I!==null;){var i=I,o=i.child;if(I.flags&16){var a=i.deletions;if(a!==null){for(var l=0;lge()-Xu?On(e,0):Ku|=n),qe(e,t)}function Bm(e,t){t===0&&(e.mode&1?(t=ui,ui<<=1,!(ui&130023424)&&(ui=4194304)):t=1);var n=ze();e=Bt(e,t),e!==null&&(Ys(e,t,n),qe(e,n))}function vv(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Bm(e,n)}function xv(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(M(314))}r!==null&&r.delete(t),Bm(e,n)}var Um;Um=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||We.current)Ue=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Ue=!1,ov(e,t,n);Ue=!!(e.flags&131072)}else Ue=!1,le&&t.flags&1048576&&Gp(t,to,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Ri(e,t),e=t.pendingProps;var s=Er(t,Ve.current);Sr(t,n),s=Uu(null,t,r,e,s,n);var i=Wu();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,He(r)?(i=!0,Ji(t)):i=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,Iu(t),s.updater=Ro,t.stateNode=s,s._reactInternals=t,El(t,r,e,n),t=Ml(null,t,r,!0,i,n)):(t.tag=0,le&&i&&_u(t),Ie(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Ri(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=bv(r),e=ft(r,e),s){case 0:t=Nl(null,t,r,e,n);break e;case 1:t=_d(null,t,r,e,n);break e;case 11:t=Nd(null,t,r,e,n);break e;case 14:t=Md(null,t,r,ft(r.type,e),n);break e}throw Error(M(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:ft(r,s),Nl(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:ft(r,s),_d(e,t,r,s,n);case 3:e:{if(jm(t),e===null)throw Error(M(387));r=t.pendingProps,i=t.memoizedState,s=i.element,Jp(e,t),so(t,r,null,n);var o=t.memoizedState;if(r=o.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){s=_r(Error(M(423)),t),t=Ad(e,t,r,n,s);break e}else if(r!==s){s=_r(Error(M(424)),t),t=Ad(e,t,r,n,s);break e}else for(Ke=dn(t.stateNode.containerInfo.firstChild),Qe=t,le=!0,pt=null,n=Qp(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Tr(),r===s){t=Ut(e,t,n);break e}Ie(e,t,r,n)}t=t.child}return t;case 5:return em(t),e===null&&Cl(t),r=t.type,s=t.pendingProps,i=e!==null?e.memoizedProps:null,o=s.children,xl(r,s)?o=null:i!==null&&xl(r,i)&&(t.flags|=32),Pm(e,t),Ie(e,t,o,n),t.child;case 6:return e===null&&Cl(t),null;case 13:return Em(e,t,n);case 4:return zu(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Nr(t,null,r,n):Ie(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:ft(r,s),Nd(e,t,r,s,n);case 7:return Ie(e,t,t.pendingProps,n),t.child;case 8:return Ie(e,t,t.pendingProps.children,n),t.child;case 12:return Ie(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,s=t.pendingProps,i=t.memoizedProps,o=s.value,J(no,r._currentValue),r._currentValue=o,i!==null)if(xt(i.value,o)){if(i.children===s.children&&!We.current){t=Ut(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var a=i.dependencies;if(a!==null){o=i.child;for(var l=a.firstContext;l!==null;){if(l.context===r){if(i.tag===1){l=Ft(-1,n&-n),l.tag=2;var c=i.updateQueue;if(c!==null){c=c.shared;var d=c.pending;d===null?l.next=l:(l.next=d.next,d.next=l),c.pending=l}}i.lanes|=n,l=i.alternate,l!==null&&(l.lanes|=n),Pl(i.return,n,t),a.lanes|=n;break}l=l.next}}else if(i.tag===10)o=i.type===t.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(M(341));o.lanes|=n,a=o.alternate,a!==null&&(a.lanes|=n),Pl(o,n,t),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===t){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}Ie(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,Sr(t,n),s=ut(s),r=r(s),t.flags|=1,Ie(e,t,r,n),t.child;case 14:return r=t.type,s=ft(r,t.pendingProps),s=ft(r.type,s),Md(e,t,r,s,n);case 15:return km(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:ft(r,s),Ri(e,t),t.tag=1,He(r)?(e=!0,Ji(t)):e=!1,Sr(t,n),wm(t,r,s),El(t,r,s,n),Ml(null,t,r,!0,e,n);case 19:return Tm(e,t,n);case 22:return Cm(e,t,n)}throw Error(M(156,t.tag))};function Wm(e,t){return yp(e,t)}function wv(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function at(e,t,n,r){return new wv(e,t,n,r)}function ec(e){return e=e.prototype,!(!e||!e.isReactComponent)}function bv(e){if(typeof e=="function")return ec(e)?1:0;if(e!=null){if(e=e.$$typeof,e===xu)return 11;if(e===wu)return 14}return 2}function mn(e,t){var n=e.alternate;return n===null?(n=at(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Ii(e,t,n,r,s,i){var o=2;if(r=e,typeof e=="function")ec(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case rr:return $n(n.children,s,i,t);case vu:o=8,s|=8;break;case Qa:return e=at(12,n,t,s|2),e.elementType=Qa,e.lanes=i,e;case Za:return e=at(13,n,t,s),e.elementType=Za,e.lanes=i,e;case Ja:return e=at(19,n,t,s),e.elementType=Ja,e.lanes=i,e;case ep:return Io(n,s,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Zh:o=10;break e;case Jh:o=9;break e;case xu:o=11;break e;case wu:o=14;break e;case Zt:o=16,r=null;break e}throw Error(M(130,e==null?e:typeof e,""))}return t=at(o,n,t,s),t.elementType=e,t.type=r,t.lanes=i,t}function $n(e,t,n,r){return e=at(7,e,r,t),e.lanes=n,e}function Io(e,t,n,r){return e=at(22,e,r,t),e.elementType=ep,e.lanes=n,e.stateNode={isHidden:!1},e}function Ea(e,t,n){return e=at(6,e,null,t),e.lanes=n,e}function Ta(e,t,n){return t=at(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Sv(e,t,n,r,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=la(0),this.expirationTimes=la(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=la(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function tc(e,t,n,r,s,i,o,a,l){return e=new Sv(e,t,n,a,l),t===1?(t=1,i===!0&&(t|=8)):t=0,i=at(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Iu(i),e}function kv(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Ym)}catch(e){console.error(e)}}Ym(),Yh.exports=et;var Tv=Yh.exports,Wd=Tv;Ka.createRoot=Wd.createRoot,Ka.hydrateRoot=Wd.hydrateRoot;/** + * @remix-run/router v1.23.0 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function Os(){return Os=Object.assign?Object.assign.bind():function(e){for(var t=1;t"u")throw new Error(t)}function Km(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function Mv(){return Math.random().toString(36).substr(2,8)}function qd(e,t){return{usr:e.state,key:e.key,idx:t}}function Bl(e,t,n,r){return n===void 0&&(n=null),Os({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?Or(t):t,{state:n,key:t&&t.key||r||Mv()})}function po(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function Or(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function _v(e,t,n,r){r===void 0&&(r={});let{window:s=document.defaultView,v5Compat:i=!1}=r,o=s.history,a=an.Pop,l=null,c=d();c==null&&(c=0,o.replaceState(Os({},o.state,{idx:c}),""));function d(){return(o.state||{idx:null}).idx}function f(){a=an.Pop;let x=d(),v=x==null?null:x-c;c=x,l&&l({action:a,location:g.location,delta:v})}function u(x,v){a=an.Push;let y=Bl(g.location,x,v);c=d()+1;let w=qd(y,c),b=g.createHref(y);try{o.pushState(w,"",b)}catch(S){if(S instanceof DOMException&&S.name==="DataCloneError")throw S;s.location.assign(b)}i&&l&&l({action:a,location:g.location,delta:1})}function h(x,v){a=an.Replace;let y=Bl(g.location,x,v);c=d();let w=qd(y,c),b=g.createHref(y);o.replaceState(w,"",b),i&&l&&l({action:a,location:g.location,delta:0})}function p(x){let v=s.location.origin!=="null"?s.location.origin:s.location.href,y=typeof x=="string"?x:po(x);return y=y.replace(/ $/,"%20"),ve(v,"No window.location.(origin|href) available to create URL for href: "+y),new URL(y,v)}let g={get action(){return a},get location(){return e(s,o)},listen(x){if(l)throw new Error("A history only accepts one active listener");return s.addEventListener(Hd,f),l=x,()=>{s.removeEventListener(Hd,f),l=null}},createHref(x){return t(s,x)},createURL:p,encodeLocation(x){let v=p(x);return{pathname:v.pathname,search:v.search,hash:v.hash}},push:u,replace:h,go(x){return o.go(x)}};return g}var Gd;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(Gd||(Gd={}));function Av(e,t,n){return n===void 0&&(n="/"),Lv(e,t,n)}function Lv(e,t,n,r){let s=typeof t=="string"?Or(t):t,i=ic(s.pathname||"/",n);if(i==null)return null;let o=Xm(e);Dv(o);let a=null;for(let l=0;a==null&&l{let l={relativePath:a===void 0?i.path||"":a,caseSensitive:i.caseSensitive===!0,childrenIndex:o,route:i};l.relativePath.startsWith("/")&&(ve(l.relativePath.startsWith(r),'Absolute route path "'+l.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),l.relativePath=l.relativePath.slice(r.length));let c=gn([r,l.relativePath]),d=n.concat(l);i.children&&i.children.length>0&&(ve(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+c+'".')),Xm(i.children,t,d,c)),!(i.path==null&&!i.index)&&t.push({path:c,score:$v(c,i.index),routesMeta:d})};return e.forEach((i,o)=>{var a;if(i.path===""||!((a=i.path)!=null&&a.includes("?")))s(i,o);else for(let l of Qm(i.path))s(i,o,l)}),t}function Qm(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,s=n.endsWith("?"),i=n.replace(/\?$/,"");if(r.length===0)return s?[i,""]:[i];let o=Qm(r.join("/")),a=[];return a.push(...o.map(l=>l===""?i:[i,l].join("/"))),s&&a.push(...o),a.map(l=>e.startsWith("/")&&l===""?"/":l)}function Dv(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:Bv(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const Rv=/^:[\w-]+$/,Vv=3,Fv=2,Iv=1,zv=10,Ov=-2,Yd=e=>e==="*";function $v(e,t){let n=e.split("/"),r=n.length;return n.some(Yd)&&(r+=Ov),t&&(r+=Fv),n.filter(s=>!Yd(s)).reduce((s,i)=>s+(Rv.test(i)?Vv:i===""?Iv:zv),r)}function Bv(e,t){return e.length===t.length&&e.slice(0,-1).every((r,s)=>r===t[s])?e[e.length-1]-t[t.length-1]:0}function Uv(e,t,n){let{routesMeta:r}=e,s={},i="/",o=[];for(let a=0;a{let{paramName:u,isOptional:h}=d;if(u==="*"){let g=a[f]||"";o=i.slice(0,i.length-g.length).replace(/(.)\/+$/,"$1")}const p=a[f];return h&&!p?c[u]=void 0:c[u]=(p||"").replace(/%2F/g,"/"),c},{}),pathname:i,pathnameBase:o,pattern:e}}function Hv(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Km(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],s="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(o,a,l)=>(r.push({paramName:a,isOptional:l!=null}),l?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),s+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?s+="\\/*$":e!==""&&e!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,t?void 0:"i"),r]}function qv(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Km(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function ic(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function Gv(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:s=""}=typeof e=="string"?Or(e):e;return{pathname:n?n.startsWith("/")?n:Yv(n,t):t,search:Qv(r),hash:Zv(s)}}function Yv(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(s=>{s===".."?n.length>1&&n.pop():s!=="."&&n.push(s)}),n.length>1?n.join("/"):"/"}function Na(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function Kv(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function oc(e,t){let n=Kv(e);return t?n.map((r,s)=>s===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function ac(e,t,n,r){r===void 0&&(r=!1);let s;typeof e=="string"?s=Or(e):(s=Os({},e),ve(!s.pathname||!s.pathname.includes("?"),Na("?","pathname","search",s)),ve(!s.pathname||!s.pathname.includes("#"),Na("#","pathname","hash",s)),ve(!s.search||!s.search.includes("#"),Na("#","search","hash",s)));let i=e===""||s.pathname==="",o=i?"/":s.pathname,a;if(o==null)a=n;else{let f=t.length-1;if(!r&&o.startsWith("..")){let u=o.split("/");for(;u[0]==="..";)u.shift(),f-=1;s.pathname=u.join("/")}a=f>=0?t[f]:"/"}let l=Gv(s,a),c=o&&o!=="/"&&o.endsWith("/"),d=(i||o===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(c||d)&&(l.pathname+="/"),l}const gn=e=>e.join("/").replace(/\/\/+/g,"/"),Xv=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),Qv=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,Zv=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function Jv(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const Zm=["post","put","patch","delete"];new Set(Zm);const ex=["get",...Zm];new Set(ex);/** + * React Router v6.30.1 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function $s(){return $s=Object.assign?Object.assign.bind():function(e){for(var t=1;t{a.current=!0}),k.useCallback(function(c,d){if(d===void 0&&(d={}),!a.current)return;if(typeof c=="number"){r.go(c);return}let f=ac(c,JSON.parse(o),i,d.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:gn([t,f.pathname])),(d.replace?r.replace:r.push)(f,d.state,d)},[t,r,o,i,e])}function t0(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=k.useContext(Pn),{matches:s}=k.useContext(jn),{pathname:i}=En(),o=JSON.stringify(oc(s,r.v7_relativeSplatPath));return k.useMemo(()=>ac(e,JSON.parse(o),i,n==="path"),[e,o,i,n])}function sx(e,t){return ix(e,t)}function ix(e,t,n,r){$r()||ve(!1);let{navigator:s}=k.useContext(Pn),{matches:i}=k.useContext(jn),o=i[i.length-1],a=o?o.params:{};o&&o.pathname;let l=o?o.pathnameBase:"/";o&&o.route;let c=En(),d;if(t){var f;let x=typeof t=="string"?Or(t):t;l==="/"||(f=x.pathname)!=null&&f.startsWith(l)||ve(!1),d=x}else d=c;let u=d.pathname||"/",h=u;if(l!=="/"){let x=l.replace(/^\//,"").split("/");h="/"+u.replace(/^\//,"").split("/").slice(x.length).join("/")}let p=Av(e,{pathname:h}),g=cx(p&&p.map(x=>Object.assign({},x,{params:Object.assign({},a,x.params),pathname:gn([l,s.encodeLocation?s.encodeLocation(x.pathname).pathname:x.pathname]),pathnameBase:x.pathnameBase==="/"?l:gn([l,s.encodeLocation?s.encodeLocation(x.pathnameBase).pathname:x.pathnameBase])})),i,n,r);return t&&g?k.createElement(Uo.Provider,{value:{location:$s({pathname:"/",search:"",hash:"",state:null,key:"default"},d),navigationType:an.Pop}},g):g}function ox(){let e=px(),t=Jv(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,s={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return k.createElement(k.Fragment,null,k.createElement("h2",null,"Unexpected Application Error!"),k.createElement("h3",{style:{fontStyle:"italic"}},t),n?k.createElement("pre",{style:s},n):null,null)}const ax=k.createElement(ox,null);class lx extends k.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?k.createElement(jn.Provider,{value:this.props.routeContext},k.createElement(Jm.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function ux(e){let{routeContext:t,match:n,children:r}=e,s=k.useContext(lc);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),k.createElement(jn.Provider,{value:t},r)}function cx(e,t,n,r){var s;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var i;if(!n)return null;if(n.errors)e=n.matches;else if((i=r)!=null&&i.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let o=e,a=(s=n)==null?void 0:s.errors;if(a!=null){let d=o.findIndex(f=>f.route.id&&(a==null?void 0:a[f.route.id])!==void 0);d>=0||ve(!1),o=o.slice(0,Math.min(o.length,d+1))}let l=!1,c=-1;if(n&&r&&r.v7_partialHydration)for(let d=0;d=0?o=o.slice(0,c+1):o=[o[0]];break}}}return o.reduceRight((d,f,u)=>{let h,p=!1,g=null,x=null;n&&(h=a&&f.route.id?a[f.route.id]:void 0,g=f.route.errorElement||ax,l&&(c<0&&u===0?(gx("route-fallback"),p=!0,x=null):c===u&&(p=!0,x=f.route.hydrateFallbackElement||null)));let v=t.concat(o.slice(0,u+1)),y=()=>{let w;return h?w=g:p?w=x:f.route.Component?w=k.createElement(f.route.Component,null):f.route.element?w=f.route.element:w=d,k.createElement(ux,{match:f,routeContext:{outlet:d,matches:v,isDataRoute:n!=null},children:w})};return n&&(f.route.ErrorBoundary||f.route.errorElement||u===0)?k.createElement(lx,{location:n.location,revalidation:n.revalidation,component:g,error:h,children:y(),routeContext:{outlet:null,matches:v,isDataRoute:!0}}):y()},null)}var n0=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(n0||{}),r0=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(r0||{});function dx(e){let t=k.useContext(lc);return t||ve(!1),t}function fx(e){let t=k.useContext(tx);return t||ve(!1),t}function hx(e){let t=k.useContext(jn);return t||ve(!1),t}function s0(e){let t=hx(),n=t.matches[t.matches.length-1];return n.route.id||ve(!1),n.route.id}function px(){var e;let t=k.useContext(Jm),n=fx(),r=s0();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function mx(){let{router:e}=dx(n0.UseNavigateStable),t=s0(r0.UseNavigateStable),n=k.useRef(!1);return e0(()=>{n.current=!0}),k.useCallback(function(s,i){i===void 0&&(i={}),n.current&&(typeof s=="number"?e.navigate(s):e.navigate(s,$s({fromRouteId:t},i)))},[e,t])}const Kd={};function gx(e,t,n){Kd[e]||(Kd[e]=!0)}function yx(e,t){e==null||e.v7_startTransition,e==null||e.v7_relativeSplatPath}function vx(e){let{to:t,replace:n,state:r,relative:s}=e;$r()||ve(!1);let{future:i,static:o}=k.useContext(Pn),{matches:a}=k.useContext(jn),{pathname:l}=En(),c=Wo(),d=ac(t,oc(a,i.v7_relativeSplatPath),l,s==="path"),f=JSON.stringify(d);return k.useEffect(()=>c(JSON.parse(f),{replace:n,state:r,relative:s}),[c,f,s,n,r]),null}function _t(e){ve(!1)}function xx(e){let{basename:t="/",children:n=null,location:r,navigationType:s=an.Pop,navigator:i,static:o=!1,future:a}=e;$r()&&ve(!1);let l=t.replace(/^\/*/,"/"),c=k.useMemo(()=>({basename:l,navigator:i,static:o,future:$s({v7_relativeSplatPath:!1},a)}),[l,a,i,o]);typeof r=="string"&&(r=Or(r));let{pathname:d="/",search:f="",hash:u="",state:h=null,key:p="default"}=r,g=k.useMemo(()=>{let x=ic(d,l);return x==null?null:{location:{pathname:x,search:f,hash:u,state:h,key:p},navigationType:s}},[l,d,f,u,h,p,s]);return g==null?null:k.createElement(Pn.Provider,{value:c},k.createElement(Uo.Provider,{children:n,value:g}))}function wx(e){let{children:t,location:n}=e;return sx(Ul(t),n)}new Promise(()=>{});function Ul(e,t){t===void 0&&(t=[]);let n=[];return k.Children.forEach(e,(r,s)=>{if(!k.isValidElement(r))return;let i=[...t,s];if(r.type===k.Fragment){n.push.apply(n,Ul(r.props.children,i));return}r.type!==_t&&ve(!1),!r.props.index||!r.props.children||ve(!1);let o={id:r.props.id||i.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(o.children=Ul(r.props.children,i)),n.push(o)}),n}/** + * React Router DOM v6.30.1 + * + * Copyright (c) Remix Software Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE.md file in the root directory of this source tree. + * + * @license MIT + */function Wl(){return Wl=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0)&&(n[s]=e[s]);return n}function Sx(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function kx(e,t){return e.button===0&&(!t||t==="_self")&&!Sx(e)}function Hl(e){return e===void 0&&(e=""),new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(s=>[n,s]):[[n,r]])},[]))}function Cx(e,t){let n=Hl(e);return t&&t.forEach((r,s)=>{n.has(s)||t.getAll(s).forEach(i=>{n.append(s,i)})}),n}const Px=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],jx="6";try{window.__reactRouterVersion=jx}catch{}const Ex="startTransition",Xd=yy[Ex];function Tx(e){let{basename:t,children:n,future:r,window:s}=e,i=k.useRef();i.current==null&&(i.current=Nv({window:s,v5Compat:!0}));let o=i.current,[a,l]=k.useState({action:o.action,location:o.location}),{v7_startTransition:c}=r||{},d=k.useCallback(f=>{c&&Xd?Xd(()=>l(f)):l(f)},[l,c]);return k.useLayoutEffect(()=>o.listen(d),[o,d]),k.useEffect(()=>yx(r),[r]),k.createElement(xx,{basename:t,children:n,location:a.location,navigationType:a.action,navigator:o,future:r})}const Nx=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Mx=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,zi=k.forwardRef(function(t,n){let{onClick:r,relative:s,reloadDocument:i,replace:o,state:a,target:l,to:c,preventScrollReset:d,viewTransition:f}=t,u=bx(t,Px),{basename:h}=k.useContext(Pn),p,g=!1;if(typeof c=="string"&&Mx.test(c)&&(p=c,Nx))try{let w=new URL(window.location.href),b=c.startsWith("//")?new URL(w.protocol+c):new URL(c),S=ic(b.pathname,h);b.origin===w.origin&&S!=null?c=S+b.search+b.hash:g=!0}catch{}let x=nx(c,{relative:s}),v=_x(c,{replace:o,state:a,target:l,preventScrollReset:d,relative:s,viewTransition:f});function y(w){r&&r(w),w.defaultPrevented||v(w)}return k.createElement("a",Wl({},u,{href:p||x,onClick:g||i?r:y,ref:n,target:l}))});var Qd;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(Qd||(Qd={}));var Zd;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(Zd||(Zd={}));function _x(e,t){let{target:n,replace:r,state:s,preventScrollReset:i,relative:o,viewTransition:a}=t===void 0?{}:t,l=Wo(),c=En(),d=t0(e,{relative:o});return k.useCallback(f=>{if(kx(f,n)){f.preventDefault();let u=r!==void 0?r:po(c)===po(d);l(e,{replace:u,state:s,preventScrollReset:i,relative:o,viewTransition:a})}},[c,l,d,r,s,n,e,i,o,a])}function Ax(e){let t=k.useRef(Hl(e)),n=k.useRef(!1),r=En(),s=k.useMemo(()=>Cx(r.search,n.current?null:t.current),[r.search]),i=Wo(),o=k.useCallback((a,l)=>{const c=Hl(typeof a=="function"?a(s):a);n.current=!0,i("?"+c,l)},[i,s]);return[s,o]}let Lx={data:""},Dx=e=>{if(typeof window=="object"){let t=(e?e.querySelector("#_goober"):window._goober)||Object.assign(document.createElement("style"),{innerHTML:" ",id:"_goober"});return t.nonce=window.__nonce__,t.parentNode||(e||document.head).appendChild(t),t.firstChild}return e||Lx},Rx=/(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g,Vx=/\/\*[^]*?\*\/| +/g,Jd=/\n+/g,rn=(e,t)=>{let n="",r="",s="";for(let i in e){let o=e[i];i[0]=="@"?i[1]=="i"?n=i+" "+o+";":r+=i[1]=="f"?rn(o,i):i+"{"+rn(o,i[1]=="k"?"":t)+"}":typeof o=="object"?r+=rn(o,t?t.replace(/([^,])+/g,a=>i.replace(/([^,]*:\S+\([^)]*\))|([^,])+/g,l=>/&/.test(l)?l.replace(/&/g,a):a?a+" "+l:l)):i):o!=null&&(i=/^--/.test(i)?i:i.replace(/[A-Z]/g,"-$&").toLowerCase(),s+=rn.p?rn.p(i,o):i+":"+o+";")}return n+(t&&s?t+"{"+s+"}":s)+r},Nt={},i0=e=>{if(typeof e=="object"){let t="";for(let n in e)t+=n+i0(e[n]);return t}return e},Fx=(e,t,n,r,s)=>{let i=i0(e),o=Nt[i]||(Nt[i]=(l=>{let c=0,d=11;for(;c>>0;return"go"+d})(i));if(!Nt[o]){let l=i!==e?e:(c=>{let d,f,u=[{}];for(;d=Rx.exec(c.replace(Vx,""));)d[4]?u.shift():d[3]?(f=d[3].replace(Jd," ").trim(),u.unshift(u[0][f]=u[0][f]||{})):u[0][d[1]]=d[2].replace(Jd," ").trim();return u[0]})(e);Nt[o]=rn(s?{["@keyframes "+o]:l}:l,n?"":"."+o)}let a=n&&Nt.g?Nt.g:null;return n&&(Nt.g=Nt[o]),((l,c,d,f)=>{f?c.data=c.data.replace(f,l):c.data.indexOf(l)===-1&&(c.data=d?l+c.data:c.data+l)})(Nt[o],t,r,a),o},Ix=(e,t,n)=>e.reduce((r,s,i)=>{let o=t[i];if(o&&o.call){let a=o(n),l=a&&a.props&&a.props.className||/^go/.test(a)&&a;o=l?"."+l:a&&typeof a=="object"?a.props?"":rn(a,""):a===!1?"":a}return r+s+(o??"")},"");function Ho(e){let t=this||{},n=e.call?e(t.p):e;return Fx(n.unshift?n.raw?Ix(n,[].slice.call(arguments,1),t.p):n.reduce((r,s)=>Object.assign(r,s&&s.call?s(t.p):s),{}):n,Dx(t.target),t.g,t.o,t.k)}let o0,ql,Gl;Ho.bind({g:1});let Wt=Ho.bind({k:1});function zx(e,t,n,r){rn.p=t,o0=e,ql=n,Gl=r}function Tn(e,t){let n=this||{};return function(){let r=arguments;function s(i,o){let a=Object.assign({},i),l=a.className||s.className;n.p=Object.assign({theme:ql&&ql()},a),n.o=/ *go\d+/.test(l),a.className=Ho.apply(n,r)+(l?" "+l:"");let c=e;return e[0]&&(c=a.as||e,delete a.as),Gl&&c[0]&&Gl(a),o0(c,a)}return s}}var Ox=e=>typeof e=="function",mo=(e,t)=>Ox(e)?e(t):e,$x=(()=>{let e=0;return()=>(++e).toString()})(),a0=(()=>{let e;return()=>{if(e===void 0&&typeof window<"u"){let t=matchMedia("(prefers-reduced-motion: reduce)");e=!t||t.matches}return e}})(),Bx=20,uc="default",l0=(e,t)=>{let{toastLimit:n}=e.settings;switch(t.type){case 0:return{...e,toasts:[t.toast,...e.toasts].slice(0,n)};case 1:return{...e,toasts:e.toasts.map(o=>o.id===t.toast.id?{...o,...t.toast}:o)};case 2:let{toast:r}=t;return l0(e,{type:e.toasts.find(o=>o.id===r.id)?1:0,toast:r});case 3:let{toastId:s}=t;return{...e,toasts:e.toasts.map(o=>o.id===s||s===void 0?{...o,dismissed:!0,visible:!1}:o)};case 4:return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(o=>o.id!==t.toastId)};case 5:return{...e,pausedAt:t.time};case 6:let i=t.time-(e.pausedAt||0);return{...e,pausedAt:void 0,toasts:e.toasts.map(o=>({...o,pauseDuration:o.pauseDuration+i}))}}},Oi=[],u0={toasts:[],pausedAt:void 0,settings:{toastLimit:Bx}},Ct={},c0=(e,t=uc)=>{Ct[t]=l0(Ct[t]||u0,e),Oi.forEach(([n,r])=>{n===t&&r(Ct[t])})},d0=e=>Object.keys(Ct).forEach(t=>c0(e,t)),Ux=e=>Object.keys(Ct).find(t=>Ct[t].toasts.some(n=>n.id===e)),qo=(e=uc)=>t=>{c0(t,e)},Wx={blank:4e3,error:4e3,success:2e3,loading:1/0,custom:4e3},Hx=(e={},t=uc)=>{let[n,r]=k.useState(Ct[t]||u0),s=k.useRef(Ct[t]);k.useEffect(()=>(s.current!==Ct[t]&&r(Ct[t]),Oi.push([t,r]),()=>{let o=Oi.findIndex(([a])=>a===t);o>-1&&Oi.splice(o,1)}),[t]);let i=n.toasts.map(o=>{var a,l,c;return{...e,...e[o.type],...o,removeDelay:o.removeDelay||((a=e[o.type])==null?void 0:a.removeDelay)||(e==null?void 0:e.removeDelay),duration:o.duration||((l=e[o.type])==null?void 0:l.duration)||(e==null?void 0:e.duration)||Wx[o.type],style:{...e.style,...(c=e[o.type])==null?void 0:c.style,...o.style}}});return{...n,toasts:i}},qx=(e,t="blank",n)=>({createdAt:Date.now(),visible:!0,dismissed:!1,type:t,ariaProps:{role:"status","aria-live":"polite"},message:e,pauseDuration:0,...n,id:(n==null?void 0:n.id)||$x()}),Zs=e=>(t,n)=>{let r=qx(t,e,n);return qo(r.toasterId||Ux(r.id))({type:2,toast:r}),r.id},ke=(e,t)=>Zs("blank")(e,t);ke.error=Zs("error");ke.success=Zs("success");ke.loading=Zs("loading");ke.custom=Zs("custom");ke.dismiss=(e,t)=>{let n={type:3,toastId:e};t?qo(t)(n):d0(n)};ke.dismissAll=e=>ke.dismiss(void 0,e);ke.remove=(e,t)=>{let n={type:4,toastId:e};t?qo(t)(n):d0(n)};ke.removeAll=e=>ke.remove(void 0,e);ke.promise=(e,t,n)=>{let r=ke.loading(t.loading,{...n,...n==null?void 0:n.loading});return typeof e=="function"&&(e=e()),e.then(s=>{let i=t.success?mo(t.success,s):void 0;return i?ke.success(i,{id:r,...n,...n==null?void 0:n.success}):ke.dismiss(r),s}).catch(s=>{let i=t.error?mo(t.error,s):void 0;i?ke.error(i,{id:r,...n,...n==null?void 0:n.error}):ke.dismiss(r)}),e};var Gx=1e3,Yx=(e,t="default")=>{let{toasts:n,pausedAt:r}=Hx(e,t),s=k.useRef(new Map).current,i=k.useCallback((f,u=Gx)=>{if(s.has(f))return;let h=setTimeout(()=>{s.delete(f),o({type:4,toastId:f})},u);s.set(f,h)},[]);k.useEffect(()=>{if(r)return;let f=Date.now(),u=n.map(h=>{if(h.duration===1/0)return;let p=(h.duration||0)+h.pauseDuration-(f-h.createdAt);if(p<0){h.visible&&ke.dismiss(h.id);return}return setTimeout(()=>ke.dismiss(h.id,t),p)});return()=>{u.forEach(h=>h&&clearTimeout(h))}},[n,r,t]);let o=k.useCallback(qo(t),[t]),a=k.useCallback(()=>{o({type:5,time:Date.now()})},[o]),l=k.useCallback((f,u)=>{o({type:1,toast:{id:f,height:u}})},[o]),c=k.useCallback(()=>{r&&o({type:6,time:Date.now()})},[r,o]),d=k.useCallback((f,u)=>{let{reverseOrder:h=!1,gutter:p=8,defaultPosition:g}=u||{},x=n.filter(w=>(w.position||g)===(f.position||g)&&w.height),v=x.findIndex(w=>w.id===f.id),y=x.filter((w,b)=>bw.visible).slice(...h?[y+1]:[0,y]).reduce((w,b)=>w+(b.height||0)+p,0)},[n]);return k.useEffect(()=>{n.forEach(f=>{if(f.dismissed)i(f.id,f.removeDelay);else{let u=s.get(f.id);u&&(clearTimeout(u),s.delete(f.id))}})},[n,i]),{toasts:n,handlers:{updateHeight:l,startPause:a,endPause:c,calculateOffset:d}}},Kx=Wt` +from { + transform: scale(0) rotate(45deg); + opacity: 0; +} +to { + transform: scale(1) rotate(45deg); + opacity: 1; +}`,Xx=Wt` +from { + transform: scale(0); + opacity: 0; +} +to { + transform: scale(1); + opacity: 1; +}`,Qx=Wt` +from { + transform: scale(0) rotate(90deg); + opacity: 0; +} +to { + transform: scale(1) rotate(90deg); + opacity: 1; +}`,Zx=Tn("div")` + width: 20px; + opacity: 0; + height: 20px; + border-radius: 10px; + background: ${e=>e.primary||"#ff4b4b"}; + position: relative; + transform: rotate(45deg); + + animation: ${Kx} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) + forwards; + animation-delay: 100ms; + + &:after, + &:before { + content: ''; + animation: ${Xx} 0.15s ease-out forwards; + animation-delay: 150ms; + position: absolute; + border-radius: 3px; + opacity: 0; + background: ${e=>e.secondary||"#fff"}; + bottom: 9px; + left: 4px; + height: 2px; + width: 12px; + } + + &:before { + animation: ${Qx} 0.15s ease-out forwards; + animation-delay: 180ms; + transform: rotate(90deg); + } +`,Jx=Wt` + from { + transform: rotate(0deg); + } + to { + transform: rotate(360deg); + } +`,e2=Tn("div")` + width: 12px; + height: 12px; + box-sizing: border-box; + border: 2px solid; + border-radius: 100%; + border-color: ${e=>e.secondary||"#e0e0e0"}; + border-right-color: ${e=>e.primary||"#616161"}; + animation: ${Jx} 1s linear infinite; +`,t2=Wt` +from { + transform: scale(0) rotate(45deg); + opacity: 0; +} +to { + transform: scale(1) rotate(45deg); + opacity: 1; +}`,n2=Wt` +0% { + height: 0; + width: 0; + opacity: 0; +} +40% { + height: 0; + width: 6px; + opacity: 1; +} +100% { + opacity: 1; + height: 10px; +}`,r2=Tn("div")` + width: 20px; + opacity: 0; + height: 20px; + border-radius: 10px; + background: ${e=>e.primary||"#61d345"}; + position: relative; + transform: rotate(45deg); + + animation: ${t2} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) + forwards; + animation-delay: 100ms; + &:after { + content: ''; + box-sizing: border-box; + animation: ${n2} 0.2s ease-out forwards; + opacity: 0; + animation-delay: 200ms; + position: absolute; + border-right: 2px solid; + border-bottom: 2px solid; + border-color: ${e=>e.secondary||"#fff"}; + bottom: 6px; + left: 6px; + height: 10px; + width: 6px; + } +`,s2=Tn("div")` + position: absolute; +`,i2=Tn("div")` + position: relative; + display: flex; + justify-content: center; + align-items: center; + min-width: 20px; + min-height: 20px; +`,o2=Wt` +from { + transform: scale(0.6); + opacity: 0.4; +} +to { + transform: scale(1); + opacity: 1; +}`,a2=Tn("div")` + position: relative; + transform: scale(0.6); + opacity: 0.4; + min-width: 20px; + animation: ${o2} 0.3s 0.12s cubic-bezier(0.175, 0.885, 0.32, 1.275) + forwards; +`,l2=({toast:e})=>{let{icon:t,type:n,iconTheme:r}=e;return t!==void 0?typeof t=="string"?k.createElement(a2,null,t):t:n==="blank"?null:k.createElement(i2,null,k.createElement(e2,{...r}),n!=="loading"&&k.createElement(s2,null,n==="error"?k.createElement(Zx,{...r}):k.createElement(r2,{...r})))},u2=e=>` +0% {transform: translate3d(0,${e*-200}%,0) scale(.6); opacity:.5;} +100% {transform: translate3d(0,0,0) scale(1); opacity:1;} +`,c2=e=>` +0% {transform: translate3d(0,0,-1px) scale(1); opacity:1;} +100% {transform: translate3d(0,${e*-150}%,-1px) scale(.6); opacity:0;} +`,d2="0%{opacity:0;} 100%{opacity:1;}",f2="0%{opacity:1;} 100%{opacity:0;}",h2=Tn("div")` + display: flex; + align-items: center; + background: #fff; + color: #363636; + line-height: 1.3; + will-change: transform; + box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1), 0 3px 3px rgba(0, 0, 0, 0.05); + max-width: 350px; + pointer-events: auto; + padding: 8px 10px; + border-radius: 8px; +`,p2=Tn("div")` + display: flex; + justify-content: center; + margin: 4px 10px; + color: inherit; + flex: 1 1 auto; + white-space: pre-line; +`,m2=(e,t)=>{let n=e.includes("top")?1:-1,[r,s]=a0()?[d2,f2]:[u2(n),c2(n)];return{animation:t?`${Wt(r)} 0.35s cubic-bezier(.21,1.02,.73,1) forwards`:`${Wt(s)} 0.4s forwards cubic-bezier(.06,.71,.55,1)`}},g2=k.memo(({toast:e,position:t,style:n,children:r})=>{let s=e.height?m2(e.position||t||"top-center",e.visible):{opacity:0},i=k.createElement(l2,{toast:e}),o=k.createElement(p2,{...e.ariaProps},mo(e.message,e));return k.createElement(h2,{className:e.className,style:{...s,...n,...e.style}},typeof r=="function"?r({icon:i,message:o}):k.createElement(k.Fragment,null,i,o))});zx(k.createElement);var y2=({id:e,className:t,style:n,onHeightUpdate:r,children:s})=>{let i=k.useCallback(o=>{if(o){let a=()=>{let l=o.getBoundingClientRect().height;r(e,l)};a(),new MutationObserver(a).observe(o,{subtree:!0,childList:!0,characterData:!0})}},[e,r]);return k.createElement("div",{ref:i,className:t,style:n},s)},v2=(e,t)=>{let n=e.includes("top"),r=n?{top:0}:{bottom:0},s=e.includes("center")?{justifyContent:"center"}:e.includes("right")?{justifyContent:"flex-end"}:{};return{left:0,right:0,display:"flex",position:"absolute",transition:a0()?void 0:"all 230ms cubic-bezier(.21,1.02,.73,1)",transform:`translateY(${t*(n?1:-1)}px)`,...r,...s}},x2=Ho` + z-index: 9999; + > * { + pointer-events: auto; + } +`,bi=16,w2=({reverseOrder:e,position:t="top-center",toastOptions:n,gutter:r,children:s,toasterId:i,containerStyle:o,containerClassName:a})=>{let{toasts:l,handlers:c}=Yx(n,i);return k.createElement("div",{"data-rht-toaster":i||"",style:{position:"fixed",zIndex:9999,top:bi,left:bi,right:bi,bottom:bi,pointerEvents:"none",...o},className:a,onMouseEnter:c.startPause,onMouseLeave:c.endPause},l.map(d=>{let f=d.position||t,u=c.calculateOffset(d,{reverseOrder:e,gutter:r,defaultPosition:t}),h=v2(f,u);return k.createElement(y2,{id:d.id,key:d.id,onHeightUpdate:c.updateHeight,className:d.visible?x2:"",style:h},d.type==="custom"?mo(d.message,d):s?s(d):k.createElement(g2,{toast:d,position:f}))}))},he=ke;const f0=k.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"}),Go=k.createContext({}),cc=k.createContext(null),Yo=typeof document<"u",b2=Yo?k.useLayoutEffect:k.useEffect,h0=k.createContext({strict:!1}),dc=e=>e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),S2="framerAppearId",p0="data-"+dc(S2);function k2(e,t,n,r){const{visualElement:s}=k.useContext(Go),i=k.useContext(h0),o=k.useContext(cc),a=k.useContext(f0).reducedMotion,l=k.useRef();r=r||i.renderer,!l.current&&r&&(l.current=r(e,{visualState:t,parent:s,props:n,presenceContext:o,blockInitialAnimation:o?o.initial===!1:!1,reducedMotionConfig:a}));const c=l.current;k.useInsertionEffect(()=>{c&&c.update(n,o)});const d=k.useRef(!!(n[p0]&&!window.HandoffComplete));return b2(()=>{c&&(c.render(),d.current&&c.animationState&&c.animationState.animateChanges())}),k.useEffect(()=>{c&&(c.updateFeatures(),!d.current&&c.animationState&&c.animationState.animateChanges(),d.current&&(d.current=!1,window.HandoffComplete=!0))}),c}function pr(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function C2(e,t,n){return k.useCallback(r=>{r&&e.mount&&e.mount(r),t&&(r?t.mount(r):t.unmount()),n&&(typeof n=="function"?n(r):pr(n)&&(n.current=r))},[t])}function Bs(e){return typeof e=="string"||Array.isArray(e)}function Ko(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}const fc=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],hc=["initial",...fc];function Xo(e){return Ko(e.animate)||hc.some(t=>Bs(e[t]))}function m0(e){return!!(Xo(e)||e.variants)}function P2(e,t){if(Xo(e)){const{initial:n,animate:r}=e;return{initial:n===!1||Bs(n)?n:void 0,animate:Bs(r)?r:void 0}}return e.inherit!==!1?t:{}}function j2(e){const{initial:t,animate:n}=P2(e,k.useContext(Go));return k.useMemo(()=>({initial:t,animate:n}),[ef(t),ef(n)])}function ef(e){return Array.isArray(e)?e.join(" "):e}const tf={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},Us={};for(const e in tf)Us[e]={isEnabled:t=>tf[e].some(n=>!!t[n])};function E2(e){for(const t in e)Us[t]={...Us[t],...e[t]}}const g0=k.createContext({}),y0=k.createContext({}),T2=Symbol.for("motionComponentSymbol");function N2({preloadedFeatures:e,createVisualElement:t,useRender:n,useVisualState:r,Component:s}){e&&E2(e);function i(a,l){let c;const d={...k.useContext(f0),...a,layoutId:M2(a)},{isStatic:f}=d,u=j2(a),h=r(a,f);if(!f&&Yo){u.visualElement=k2(s,h,d,t);const p=k.useContext(y0),g=k.useContext(h0).strict;u.visualElement&&(c=u.visualElement.loadFeatures(d,g,e,p))}return k.createElement(Go.Provider,{value:u},c&&u.visualElement?k.createElement(c,{visualElement:u.visualElement,...d}):null,n(s,a,C2(h,u.visualElement,l),h,f,u.visualElement))}const o=k.forwardRef(i);return o[T2]=s,o}function M2({layoutId:e}){const t=k.useContext(g0).id;return t&&e!==void 0?t+"-"+e:e}function _2(e){function t(r,s={}){return N2(e(r,s))}if(typeof Proxy>"u")return t;const n=new Map;return new Proxy(t,{get:(r,s)=>(n.has(s)||n.set(s,t(s)),n.get(s))})}const A2=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function pc(e){return typeof e!="string"||e.includes("-")?!1:!!(A2.indexOf(e)>-1||/[A-Z]/.test(e))}const go={};function L2(e){Object.assign(go,e)}const Js=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Qn=new Set(Js);function v0(e,{layout:t,layoutId:n}){return Qn.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!go[e]||e==="opacity")}const Ge=e=>!!(e&&e.getVelocity),D2={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},R2=Js.length;function V2(e,{enableHardwareAcceleration:t=!0,allowTransformNone:n=!0},r,s){let i="";for(let o=0;ot=>typeof t=="string"&&t.startsWith(e),w0=x0("--"),Yl=x0("var(--"),F2=/var\s*\(\s*--[\w-]+(\s*,\s*(?:(?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)+)?\s*\)/g,I2=(e,t)=>t&&typeof e=="number"?t.transform(e):e,wn=(e,t,n)=>Math.min(Math.max(n,e),t),Zn={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},ys={...Zn,transform:e=>wn(0,1,e)},Si={...Zn,default:1},vs=e=>Math.round(e*1e5)/1e5,Qo=/(-)?([\d]*\.?[\d])+/g,b0=/(#[0-9a-f]{3,8}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))/gi,z2=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))$/i;function ei(e){return typeof e=="string"}const ti=e=>({test:t=>ei(t)&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),Qt=ti("deg"),Tt=ti("%"),B=ti("px"),O2=ti("vh"),$2=ti("vw"),nf={...Tt,parse:e=>Tt.parse(e)/100,transform:e=>Tt.transform(e*100)},rf={...Zn,transform:Math.round},S0={borderWidth:B,borderTopWidth:B,borderRightWidth:B,borderBottomWidth:B,borderLeftWidth:B,borderRadius:B,radius:B,borderTopLeftRadius:B,borderTopRightRadius:B,borderBottomRightRadius:B,borderBottomLeftRadius:B,width:B,maxWidth:B,height:B,maxHeight:B,size:B,top:B,right:B,bottom:B,left:B,padding:B,paddingTop:B,paddingRight:B,paddingBottom:B,paddingLeft:B,margin:B,marginTop:B,marginRight:B,marginBottom:B,marginLeft:B,rotate:Qt,rotateX:Qt,rotateY:Qt,rotateZ:Qt,scale:Si,scaleX:Si,scaleY:Si,scaleZ:Si,skew:Qt,skewX:Qt,skewY:Qt,distance:B,translateX:B,translateY:B,translateZ:B,x:B,y:B,z:B,perspective:B,transformPerspective:B,opacity:ys,originX:nf,originY:nf,originZ:B,zIndex:rf,fillOpacity:ys,strokeOpacity:ys,numOctaves:rf};function mc(e,t,n,r){const{style:s,vars:i,transform:o,transformOrigin:a}=e;let l=!1,c=!1,d=!0;for(const f in t){const u=t[f];if(w0(f)){i[f]=u;continue}const h=S0[f],p=I2(u,h);if(Qn.has(f)){if(l=!0,o[f]=p,!d)continue;u!==(h.default||0)&&(d=!1)}else f.startsWith("origin")?(c=!0,a[f]=p):s[f]=p}if(t.transform||(l||r?s.transform=V2(e.transform,n,d,r):s.transform&&(s.transform="none")),c){const{originX:f="50%",originY:u="50%",originZ:h=0}=a;s.transformOrigin=`${f} ${u} ${h}`}}const gc=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function k0(e,t,n){for(const r in t)!Ge(t[r])&&!v0(r,n)&&(e[r]=t[r])}function B2({transformTemplate:e},t,n){return k.useMemo(()=>{const r=gc();return mc(r,t,{enableHardwareAcceleration:!n},e),Object.assign({},r.vars,r.style)},[t])}function U2(e,t,n){const r=e.style||{},s={};return k0(s,r,e),Object.assign(s,B2(e,t,n)),e.transformValues?e.transformValues(s):s}function W2(e,t,n){const r={},s=U2(e,t,n);return e.drag&&e.dragListener!==!1&&(r.draggable=!1,s.userSelect=s.WebkitUserSelect=s.WebkitTouchCallout="none",s.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(r.tabIndex=0),r.style=s,r}const H2=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","transformValues","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function yo(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||H2.has(e)}let C0=e=>!yo(e);function q2(e){e&&(C0=t=>t.startsWith("on")?!yo(t):e(t))}try{q2(require("@emotion/is-prop-valid").default)}catch{}function G2(e,t,n){const r={};for(const s in e)s==="values"&&typeof e.values=="object"||(C0(s)||n===!0&&yo(s)||!t&&!yo(s)||e.draggable&&s.startsWith("onDrag"))&&(r[s]=e[s]);return r}function sf(e,t,n){return typeof e=="string"?e:B.transform(t+n*e)}function Y2(e,t,n){const r=sf(t,e.x,e.width),s=sf(n,e.y,e.height);return`${r} ${s}`}const K2={offset:"stroke-dashoffset",array:"stroke-dasharray"},X2={offset:"strokeDashoffset",array:"strokeDasharray"};function Q2(e,t,n=1,r=0,s=!0){e.pathLength=1;const i=s?K2:X2;e[i.offset]=B.transform(-r);const o=B.transform(t),a=B.transform(n);e[i.array]=`${o} ${a}`}function yc(e,{attrX:t,attrY:n,attrScale:r,originX:s,originY:i,pathLength:o,pathSpacing:a=1,pathOffset:l=0,...c},d,f,u){if(mc(e,c,d,u),f){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};const{attrs:h,style:p,dimensions:g}=e;h.transform&&(g&&(p.transform=h.transform),delete h.transform),g&&(s!==void 0||i!==void 0||p.transform)&&(p.transformOrigin=Y2(g,s!==void 0?s:.5,i!==void 0?i:.5)),t!==void 0&&(h.x=t),n!==void 0&&(h.y=n),r!==void 0&&(h.scale=r),o!==void 0&&Q2(h,o,a,l,!1)}const P0=()=>({...gc(),attrs:{}}),vc=e=>typeof e=="string"&&e.toLowerCase()==="svg";function Z2(e,t,n,r){const s=k.useMemo(()=>{const i=P0();return yc(i,t,{enableHardwareAcceleration:!1},vc(r),e.transformTemplate),{...i.attrs,style:{...i.style}}},[t]);if(e.style){const i={};k0(i,e.style,e),s.style={...i,...s.style}}return s}function J2(e=!1){return(n,r,s,{latestValues:i},o)=>{const l=(pc(n)?Z2:W2)(r,i,o,n),d={...G2(r,typeof n=="string",e),...l,ref:s},{children:f}=r,u=k.useMemo(()=>Ge(f)?f.get():f,[f]);return k.createElement(n,{...d,children:u})}}function j0(e,{style:t,vars:n},r,s){Object.assign(e.style,t,s&&s.getProjectionStyles(r));for(const i in n)e.style.setProperty(i,n[i])}const E0=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function T0(e,t,n,r){j0(e,t,void 0,r);for(const s in t.attrs)e.setAttribute(E0.has(s)?s:dc(s),t.attrs[s])}function xc(e,t){const{style:n}=e,r={};for(const s in n)(Ge(n[s])||t.style&&Ge(t.style[s])||v0(s,e))&&(r[s]=n[s]);return r}function N0(e,t){const n=xc(e,t);for(const r in e)if(Ge(e[r])||Ge(t[r])){const s=Js.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;n[s]=e[r]}return n}function wc(e,t,n,r={},s={}){return typeof t=="function"&&(t=t(n!==void 0?n:e.custom,r,s)),typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"&&(t=t(n!==void 0?n:e.custom,r,s)),t}function ew(e){const t=k.useRef(null);return t.current===null&&(t.current=e()),t.current}const vo=e=>Array.isArray(e),tw=e=>!!(e&&typeof e=="object"&&e.mix&&e.toValue),nw=e=>vo(e)?e[e.length-1]||0:e;function $i(e){const t=Ge(e)?e.get():e;return tw(t)?t.toValue():t}function rw({scrapeMotionValuesFromProps:e,createRenderState:t,onMount:n},r,s,i){const o={latestValues:sw(r,s,i,e),renderState:t()};return n&&(o.mount=a=>n(r,a,o)),o}const M0=e=>(t,n)=>{const r=k.useContext(Go),s=k.useContext(cc),i=()=>rw(e,t,r,s);return n?i():ew(i)};function sw(e,t,n,r){const s={},i=r(e,{});for(const u in i)s[u]=$i(i[u]);let{initial:o,animate:a}=e;const l=Xo(e),c=m0(e);t&&c&&!l&&e.inherit!==!1&&(o===void 0&&(o=t.initial),a===void 0&&(a=t.animate));let d=n?n.initial===!1:!1;d=d||o===!1;const f=d?a:o;return f&&typeof f!="boolean"&&!Ko(f)&&(Array.isArray(f)?f:[f]).forEach(h=>{const p=wc(e,h);if(!p)return;const{transitionEnd:g,transition:x,...v}=p;for(const y in v){let w=v[y];if(Array.isArray(w)){const b=d?w.length-1:0;w=w[b]}w!==null&&(s[y]=w)}for(const y in g)s[y]=g[y]}),s}const ye=e=>e;class of{constructor(){this.order=[],this.scheduled=new Set}add(t){if(!this.scheduled.has(t))return this.scheduled.add(t),this.order.push(t),!0}remove(t){const n=this.order.indexOf(t);n!==-1&&(this.order.splice(n,1),this.scheduled.delete(t))}clear(){this.order.length=0,this.scheduled.clear()}}function iw(e){let t=new of,n=new of,r=0,s=!1,i=!1;const o=new WeakSet,a={schedule:(l,c=!1,d=!1)=>{const f=d&&s,u=f?t:n;return c&&o.add(l),u.add(l)&&f&&s&&(r=t.order.length),l},cancel:l=>{n.remove(l),o.delete(l)},process:l=>{if(s){i=!0;return}if(s=!0,[t,n]=[n,t],n.clear(),r=t.order.length,r)for(let c=0;c(f[u]=iw(()=>n=!0),f),{}),o=f=>i[f].process(s),a=()=>{const f=performance.now();n=!1,s.delta=r?1e3/60:Math.max(Math.min(f-s.timestamp,ow),1),s.timestamp=f,s.isProcessing=!0,ki.forEach(o),s.isProcessing=!1,n&&t&&(r=!1,e(a))},l=()=>{n=!0,r=!0,s.isProcessing||e(a)};return{schedule:ki.reduce((f,u)=>{const h=i[u];return f[u]=(p,g=!1,x=!1)=>(n||l(),h.schedule(p,g,x)),f},{}),cancel:f=>ki.forEach(u=>i[u].cancel(f)),state:s,steps:i}}const{schedule:oe,cancel:Ht,state:De,steps:Ma}=aw(typeof requestAnimationFrame<"u"?requestAnimationFrame:ye,!0),lw={useVisualState:M0({scrapeMotionValuesFromProps:N0,createRenderState:P0,onMount:(e,t,{renderState:n,latestValues:r})=>{oe.read(()=>{try{n.dimensions=typeof t.getBBox=="function"?t.getBBox():t.getBoundingClientRect()}catch{n.dimensions={x:0,y:0,width:0,height:0}}}),oe.render(()=>{yc(n,r,{enableHardwareAcceleration:!1},vc(t.tagName),e.transformTemplate),T0(t,n)})}})},uw={useVisualState:M0({scrapeMotionValuesFromProps:xc,createRenderState:gc})};function cw(e,{forwardMotionProps:t=!1},n,r){return{...pc(e)?lw:uw,preloadedFeatures:n,useRender:J2(t),createVisualElement:r,Component:e}}function Vt(e,t,n,r={passive:!0}){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n)}const _0=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1;function Zo(e,t="page"){return{point:{x:e[t+"X"],y:e[t+"Y"]}}}const dw=e=>t=>_0(t)&&e(t,Zo(t));function It(e,t,n,r){return Vt(e,t,dw(n),r)}const fw=(e,t)=>n=>t(e(n)),yn=(...e)=>e.reduce(fw);function A0(e){let t=null;return()=>{const n=()=>{t=null};return t===null?(t=e,n):!1}}const af=A0("dragHorizontal"),lf=A0("dragVertical");function L0(e){let t=!1;if(e==="y")t=lf();else if(e==="x")t=af();else{const n=af(),r=lf();n&&r?t=()=>{n(),r()}:(n&&n(),r&&r())}return t}function D0(){const e=L0(!0);return e?(e(),!1):!0}class Nn{constructor(t){this.isMounted=!1,this.node=t}update(){}}function uf(e,t){const n="pointer"+(t?"enter":"leave"),r="onHover"+(t?"Start":"End"),s=(i,o)=>{if(i.pointerType==="touch"||D0())return;const a=e.getProps();e.animationState&&a.whileHover&&e.animationState.setActive("whileHover",t),a[r]&&oe.update(()=>a[r](i,o))};return It(e.current,n,s,{passive:!e.getProps()[r]})}class hw extends Nn{mount(){this.unmount=yn(uf(this.node,!0),uf(this.node,!1))}unmount(){}}class pw extends Nn{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=yn(Vt(this.node.current,"focus",()=>this.onFocus()),Vt(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}const R0=(e,t)=>t?e===t?!0:R0(e,t.parentElement):!1;function _a(e,t){if(!t)return;const n=new PointerEvent("pointer"+e);t(n,Zo(n))}class mw extends Nn{constructor(){super(...arguments),this.removeStartListeners=ye,this.removeEndListeners=ye,this.removeAccessibleListeners=ye,this.startPointerPress=(t,n)=>{if(this.isPressing)return;this.removeEndListeners();const r=this.node.getProps(),i=It(window,"pointerup",(a,l)=>{if(!this.checkPressEnd())return;const{onTap:c,onTapCancel:d,globalTapTarget:f}=this.node.getProps();oe.update(()=>{!f&&!R0(this.node.current,a.target)?d&&d(a,l):c&&c(a,l)})},{passive:!(r.onTap||r.onPointerUp)}),o=It(window,"pointercancel",(a,l)=>this.cancelPress(a,l),{passive:!(r.onTapCancel||r.onPointerCancel)});this.removeEndListeners=yn(i,o),this.startPress(t,n)},this.startAccessiblePress=()=>{const t=i=>{if(i.key!=="Enter"||this.isPressing)return;const o=a=>{a.key!=="Enter"||!this.checkPressEnd()||_a("up",(l,c)=>{const{onTap:d}=this.node.getProps();d&&oe.update(()=>d(l,c))})};this.removeEndListeners(),this.removeEndListeners=Vt(this.node.current,"keyup",o),_a("down",(a,l)=>{this.startPress(a,l)})},n=Vt(this.node.current,"keydown",t),r=()=>{this.isPressing&&_a("cancel",(i,o)=>this.cancelPress(i,o))},s=Vt(this.node.current,"blur",r);this.removeAccessibleListeners=yn(n,s)}}startPress(t,n){this.isPressing=!0;const{onTapStart:r,whileTap:s}=this.node.getProps();s&&this.node.animationState&&this.node.animationState.setActive("whileTap",!0),r&&oe.update(()=>r(t,n))}checkPressEnd(){return this.removeEndListeners(),this.isPressing=!1,this.node.getProps().whileTap&&this.node.animationState&&this.node.animationState.setActive("whileTap",!1),!D0()}cancelPress(t,n){if(!this.checkPressEnd())return;const{onTapCancel:r}=this.node.getProps();r&&oe.update(()=>r(t,n))}mount(){const t=this.node.getProps(),n=It(t.globalTapTarget?window:this.node.current,"pointerdown",this.startPointerPress,{passive:!(t.onTapStart||t.onPointerStart)}),r=Vt(this.node.current,"focus",this.startAccessiblePress);this.removeStartListeners=yn(n,r)}unmount(){this.removeStartListeners(),this.removeEndListeners(),this.removeAccessibleListeners()}}const Kl=new WeakMap,Aa=new WeakMap,gw=e=>{const t=Kl.get(e.target);t&&t(e)},yw=e=>{e.forEach(gw)};function vw({root:e,...t}){const n=e||document;Aa.has(n)||Aa.set(n,{});const r=Aa.get(n),s=JSON.stringify(t);return r[s]||(r[s]=new IntersectionObserver(yw,{root:e,...t})),r[s]}function xw(e,t,n){const r=vw(t);return Kl.set(e,n),r.observe(e),()=>{Kl.delete(e),r.unobserve(e)}}const ww={some:0,all:1};class bw extends Nn{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:n,margin:r,amount:s="some",once:i}=t,o={root:n?n.current:void 0,rootMargin:r,threshold:typeof s=="number"?s:ww[s]},a=l=>{const{isIntersecting:c}=l;if(this.isInView===c||(this.isInView=c,i&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:d,onViewportLeave:f}=this.node.getProps(),u=c?d:f;u&&u(l)};return xw(this.node.current,o,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(Sw(t,n))&&this.startObserver()}unmount(){}}function Sw({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const kw={inView:{Feature:bw},tap:{Feature:mw},focus:{Feature:pw},hover:{Feature:hw}};function V0(e,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==e.length)return!1;for(let r=0;rt[r]=n.get()),t}function Pw(e){const t={};return e.values.forEach((n,r)=>t[r]=n.getVelocity()),t}function Jo(e,t,n){const r=e.getProps();return wc(r,t,n!==void 0?n:r.custom,Cw(e),Pw(e))}let bc=ye;const Bn=e=>e*1e3,zt=e=>e/1e3,jw={current:!1},F0=e=>Array.isArray(e)&&typeof e[0]=="number";function I0(e){return!!(!e||typeof e=="string"&&z0[e]||F0(e)||Array.isArray(e)&&e.every(I0))}const as=([e,t,n,r])=>`cubic-bezier(${e}, ${t}, ${n}, ${r})`,z0={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:as([0,.65,.55,1]),circOut:as([.55,0,1,.45]),backIn:as([.31,.01,.66,-.59]),backOut:as([.33,1.53,.69,.99])};function O0(e){if(e)return F0(e)?as(e):Array.isArray(e)?e.map(O0):z0[e]}function Ew(e,t,n,{delay:r=0,duration:s,repeat:i=0,repeatType:o="loop",ease:a,times:l}={}){const c={[t]:n};l&&(c.offset=l);const d=O0(a);return Array.isArray(d)&&(c.easing=d),e.animate(c,{delay:r,duration:s,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:i+1,direction:o==="reverse"?"alternate":"normal"})}function Tw(e,{repeat:t,repeatType:n="loop"}){const r=t&&n!=="loop"&&t%2===1?0:e.length-1;return e[r]}const $0=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,Nw=1e-7,Mw=12;function _w(e,t,n,r,s){let i,o,a=0;do o=t+(n-t)/2,i=$0(o,r,s)-e,i>0?n=o:t=o;while(Math.abs(i)>Nw&&++a_w(i,0,1,e,n);return i=>i===0||i===1?i:$0(s(i),t,r)}const Aw=ni(.42,0,1,1),Lw=ni(0,0,.58,1),B0=ni(.42,0,.58,1),Dw=e=>Array.isArray(e)&&typeof e[0]!="number",U0=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,W0=e=>t=>1-e(1-t),Sc=e=>1-Math.sin(Math.acos(e)),H0=W0(Sc),Rw=U0(Sc),q0=ni(.33,1.53,.69,.99),kc=W0(q0),Vw=U0(kc),Fw=e=>(e*=2)<1?.5*kc(e):.5*(2-Math.pow(2,-10*(e-1))),Iw={linear:ye,easeIn:Aw,easeInOut:B0,easeOut:Lw,circIn:Sc,circInOut:Rw,circOut:H0,backIn:kc,backInOut:Vw,backOut:q0,anticipate:Fw},cf=e=>{if(Array.isArray(e)){bc(e.length===4);const[t,n,r,s]=e;return ni(t,n,r,s)}else if(typeof e=="string")return Iw[e];return e},Cc=(e,t)=>n=>!!(ei(n)&&z2.test(n)&&n.startsWith(e)||t&&Object.prototype.hasOwnProperty.call(n,t)),G0=(e,t,n)=>r=>{if(!ei(r))return r;const[s,i,o,a]=r.match(Qo);return{[e]:parseFloat(s),[t]:parseFloat(i),[n]:parseFloat(o),alpha:a!==void 0?parseFloat(a):1}},zw=e=>wn(0,255,e),La={...Zn,transform:e=>Math.round(zw(e))},zn={test:Cc("rgb","red"),parse:G0("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:r=1})=>"rgba("+La.transform(e)+", "+La.transform(t)+", "+La.transform(n)+", "+vs(ys.transform(r))+")"};function Ow(e){let t="",n="",r="",s="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),r=e.substring(5,7),s=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),r=e.substring(3,4),s=e.substring(4,5),t+=t,n+=n,r+=r,s+=s),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(r,16),alpha:s?parseInt(s,16)/255:1}}const Xl={test:Cc("#"),parse:Ow,transform:zn.transform},mr={test:Cc("hsl","hue"),parse:G0("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(e)+", "+Tt.transform(vs(t))+", "+Tt.transform(vs(n))+", "+vs(ys.transform(r))+")"},Fe={test:e=>zn.test(e)||Xl.test(e)||mr.test(e),parse:e=>zn.test(e)?zn.parse(e):mr.test(e)?mr.parse(e):Xl.parse(e),transform:e=>ei(e)?e:e.hasOwnProperty("red")?zn.transform(e):mr.transform(e)},ce=(e,t,n)=>-n*e+n*t+e;function Da(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function $w({hue:e,saturation:t,lightness:n,alpha:r}){e/=360,t/=100,n/=100;let s=0,i=0,o=0;if(!t)s=i=o=n;else{const a=n<.5?n*(1+t):n+t-n*t,l=2*n-a;s=Da(l,a,e+1/3),i=Da(l,a,e),o=Da(l,a,e-1/3)}return{red:Math.round(s*255),green:Math.round(i*255),blue:Math.round(o*255),alpha:r}}const Ra=(e,t,n)=>{const r=e*e;return Math.sqrt(Math.max(0,n*(t*t-r)+r))},Bw=[Xl,zn,mr],Uw=e=>Bw.find(t=>t.test(e));function df(e){const t=Uw(e);let n=t.parse(e);return t===mr&&(n=$w(n)),n}const Y0=(e,t)=>{const n=df(e),r=df(t),s={...n};return i=>(s.red=Ra(n.red,r.red,i),s.green=Ra(n.green,r.green,i),s.blue=Ra(n.blue,r.blue,i),s.alpha=ce(n.alpha,r.alpha,i),zn.transform(s))};function Ww(e){var t,n;return isNaN(e)&&ei(e)&&(((t=e.match(Qo))===null||t===void 0?void 0:t.length)||0)+(((n=e.match(b0))===null||n===void 0?void 0:n.length)||0)>0}const K0={regex:F2,countKey:"Vars",token:"${v}",parse:ye},X0={regex:b0,countKey:"Colors",token:"${c}",parse:Fe.parse},Q0={regex:Qo,countKey:"Numbers",token:"${n}",parse:Zn.parse};function Va(e,{regex:t,countKey:n,token:r,parse:s}){const i=e.tokenised.match(t);i&&(e["num"+n]=i.length,e.tokenised=e.tokenised.replace(t,r),e.values.push(...i.map(s)))}function xo(e){const t=e.toString(),n={value:t,tokenised:t,values:[],numVars:0,numColors:0,numNumbers:0};return n.value.includes("var(--")&&Va(n,K0),Va(n,X0),Va(n,Q0),n}function Z0(e){return xo(e).values}function J0(e){const{values:t,numColors:n,numVars:r,tokenised:s}=xo(e),i=t.length;return o=>{let a=s;for(let l=0;ltypeof e=="number"?0:e;function qw(e){const t=Z0(e);return J0(e)(t.map(Hw))}const bn={test:Ww,parse:Z0,createTransformer:J0,getAnimatableNone:qw},eg=(e,t)=>n=>`${n>0?t:e}`;function tg(e,t){return typeof e=="number"?n=>ce(e,t,n):Fe.test(e)?Y0(e,t):e.startsWith("var(")?eg(e,t):rg(e,t)}const ng=(e,t)=>{const n=[...e],r=n.length,s=e.map((i,o)=>tg(i,t[o]));return i=>{for(let o=0;o{const n={...e,...t},r={};for(const s in n)e[s]!==void 0&&t[s]!==void 0&&(r[s]=tg(e[s],t[s]));return s=>{for(const i in r)n[i]=r[i](s);return n}},rg=(e,t)=>{const n=bn.createTransformer(t),r=xo(e),s=xo(t);return r.numVars===s.numVars&&r.numColors===s.numColors&&r.numNumbers>=s.numNumbers?yn(ng(r.values,s.values),n):eg(e,t)},Ws=(e,t,n)=>{const r=t-e;return r===0?1:(n-e)/r},ff=(e,t)=>n=>ce(e,t,n);function Yw(e){return typeof e=="number"?ff:typeof e=="string"?Fe.test(e)?Y0:rg:Array.isArray(e)?ng:typeof e=="object"?Gw:ff}function Kw(e,t,n){const r=[],s=n||Yw(e[0]),i=e.length-1;for(let o=0;ot[0];e[0]>e[i-1]&&(e=[...e].reverse(),t=[...t].reverse());const o=Kw(t,r,s),a=o.length,l=c=>{let d=0;if(a>1)for(;dl(wn(e[0],e[i-1],c)):l}function Xw(e,t){const n=e[e.length-1];for(let r=1;r<=t;r++){const s=Ws(0,t,r);e.push(ce(n,1,s))}}function Qw(e){const t=[0];return Xw(t,e.length-1),t}function Zw(e,t){return e.map(n=>n*t)}function Jw(e,t){return e.map(()=>t||B0).splice(0,e.length-1)}function wo({duration:e=300,keyframes:t,times:n,ease:r="easeInOut"}){const s=Dw(r)?r.map(cf):cf(r),i={done:!1,value:t[0]},o=Zw(n&&n.length===t.length?n:Qw(t),e),a=sg(o,t,{ease:Array.isArray(s)?s:Jw(t,s)});return{calculatedDuration:e,next:l=>(i.value=a(l),i.done=l>=e,i)}}function ig(e,t){return t?e*(1e3/t):0}const e5=5;function og(e,t,n){const r=Math.max(t-e5,0);return ig(n-e(r),t-r)}const Fa=.001,t5=.01,n5=10,r5=.05,s5=1;function i5({duration:e=800,bounce:t=.25,velocity:n=0,mass:r=1}){let s,i,o=1-t;o=wn(r5,s5,o),e=wn(t5,n5,zt(e)),o<1?(s=c=>{const d=c*o,f=d*e,u=d-n,h=Ql(c,o),p=Math.exp(-f);return Fa-u/h*p},i=c=>{const f=c*o*e,u=f*n+n,h=Math.pow(o,2)*Math.pow(c,2)*e,p=Math.exp(-f),g=Ql(Math.pow(c,2),o);return(-s(c)+Fa>0?-1:1)*((u-h)*p)/g}):(s=c=>{const d=Math.exp(-c*e),f=(c-n)*e+1;return-Fa+d*f},i=c=>{const d=Math.exp(-c*e),f=(n-c)*(e*e);return d*f});const a=5/e,l=a5(s,i,a);if(e=Bn(e),isNaN(l))return{stiffness:100,damping:10,duration:e};{const c=Math.pow(l,2)*r;return{stiffness:c,damping:o*2*Math.sqrt(r*c),duration:e}}}const o5=12;function a5(e,t,n){let r=n;for(let s=1;se[n]!==void 0)}function c5(e){let t={velocity:0,stiffness:100,damping:10,mass:1,isResolvedFromDuration:!1,...e};if(!hf(e,u5)&&hf(e,l5)){const n=i5(e);t={...t,...n,mass:1},t.isResolvedFromDuration=!0}return t}function ag({keyframes:e,restDelta:t,restSpeed:n,...r}){const s=e[0],i=e[e.length-1],o={done:!1,value:s},{stiffness:a,damping:l,mass:c,duration:d,velocity:f,isResolvedFromDuration:u}=c5({...r,velocity:-zt(r.velocity||0)}),h=f||0,p=l/(2*Math.sqrt(a*c)),g=i-s,x=zt(Math.sqrt(a/c)),v=Math.abs(g)<5;n||(n=v?.01:2),t||(t=v?.005:.5);let y;if(p<1){const w=Ql(x,p);y=b=>{const S=Math.exp(-p*x*b);return i-S*((h+p*x*g)/w*Math.sin(w*b)+g*Math.cos(w*b))}}else if(p===1)y=w=>i-Math.exp(-x*w)*(g+(h+x*g)*w);else{const w=x*Math.sqrt(p*p-1);y=b=>{const S=Math.exp(-p*x*b),C=Math.min(w*b,300);return i-S*((h+p*x*g)*Math.sinh(C)+w*g*Math.cosh(C))/w}}return{calculatedDuration:u&&d||null,next:w=>{const b=y(w);if(u)o.done=w>=d;else{let S=h;w!==0&&(p<1?S=og(y,w,b):S=0);const C=Math.abs(S)<=n,P=Math.abs(i-b)<=t;o.done=C&&P}return o.value=o.done?i:b,o}}}function pf({keyframes:e,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:s=10,bounceStiffness:i=500,modifyTarget:o,min:a,max:l,restDelta:c=.5,restSpeed:d}){const f=e[0],u={done:!1,value:f},h=j=>a!==void 0&&jl,p=j=>a===void 0?l:l===void 0||Math.abs(a-j)-g*Math.exp(-j/r),w=j=>v+y(j),b=j=>{const D=y(j),T=w(j);u.done=Math.abs(D)<=c,u.value=u.done?v:T};let S,C;const P=j=>{h(u.value)&&(S=j,C=ag({keyframes:[u.value,p(u.value)],velocity:og(w,j,u.value),damping:s,stiffness:i,restDelta:c,restSpeed:d}))};return P(0),{calculatedDuration:null,next:j=>{let D=!1;return!C&&S===void 0&&(D=!0,b(j),P(j)),S!==void 0&&j>S?C.next(j-S):(!D&&b(j),u)}}}const d5=e=>{const t=({timestamp:n})=>e(n);return{start:()=>oe.update(t,!0),stop:()=>Ht(t),now:()=>De.isProcessing?De.timestamp:performance.now()}},mf=2e4;function gf(e){let t=0;const n=50;let r=e.next(t);for(;!r.done&&t=mf?1/0:t}const f5={decay:pf,inertia:pf,tween:wo,keyframes:wo,spring:ag};function bo({autoplay:e=!0,delay:t=0,driver:n=d5,keyframes:r,type:s="keyframes",repeat:i=0,repeatDelay:o=0,repeatType:a="loop",onPlay:l,onStop:c,onComplete:d,onUpdate:f,...u}){let h=1,p=!1,g,x;const v=()=>{x=new Promise(L=>{g=L})};v();let y;const w=f5[s]||wo;let b;w!==wo&&typeof r[0]!="number"&&(b=sg([0,100],r,{clamp:!1}),r=[0,100]);const S=w({...u,keyframes:r});let C;a==="mirror"&&(C=w({...u,keyframes:[...r].reverse(),velocity:-(u.velocity||0)}));let P="idle",j=null,D=null,T=null;S.calculatedDuration===null&&i&&(S.calculatedDuration=gf(S));const{calculatedDuration:z}=S;let V=1/0,U=1/0;z!==null&&(V=z+o,U=V*(i+1)-o);let R=0;const Q=L=>{if(D===null)return;h>0&&(D=Math.min(D,L)),h<0&&(D=Math.min(L-U/h,D)),j!==null?R=j:R=Math.round(L-D)*h;const E=R-t*(h>=0?1:-1),W=h>=0?E<0:E>U;R=Math.max(E,0),P==="finished"&&j===null&&(R=U);let X=R,te=S;if(i){const Jn=Math.min(R,U)/V;let Mn=Math.floor(Jn),wt=Jn%1;!wt&&Jn>=1&&(wt=1),wt===1&&Mn--,Mn=Math.min(Mn,i+1),!!(Mn%2)&&(a==="reverse"?(wt=1-wt,o&&(wt-=o/V)):a==="mirror"&&(te=C)),X=wn(0,1,wt)*V}const G=W?{done:!1,value:r[0]}:te.next(X);b&&(G.value=b(G.value));let{done:be}=G;!W&&z!==null&&(be=h>=0?R>=U:R<=0);const ri=j===null&&(P==="finished"||P==="running"&&be);return f&&f(G.value),ri&&_(),G},A=()=>{y&&y.stop(),y=void 0},q=()=>{P="idle",A(),g(),v(),D=T=null},_=()=>{P="finished",d&&d(),A(),g()},N=()=>{if(p)return;y||(y=n(Q));const L=y.now();l&&l(),j!==null?D=L-j:(!D||P==="finished")&&(D=L),P==="finished"&&v(),T=D,j=null,P="running",y.start()};e&&N();const F={then(L,E){return x.then(L,E)},get time(){return zt(R)},set time(L){L=Bn(L),R=L,j!==null||!y||h===0?j=L:D=y.now()-L/h},get duration(){const L=S.calculatedDuration===null?gf(S):S.calculatedDuration;return zt(L)},get speed(){return h},set speed(L){L===h||!y||(h=L,F.time=zt(R))},get state(){return P},play:N,pause:()=>{P="paused",j=R},stop:()=>{p=!0,P!=="idle"&&(P="idle",c&&c(),q())},cancel:()=>{T!==null&&Q(T),q()},complete:()=>{P="finished"},sample:L=>(D=0,Q(L))};return F}function h5(e){let t;return()=>(t===void 0&&(t=e()),t)}const p5=h5(()=>Object.hasOwnProperty.call(Element.prototype,"animate")),m5=new Set(["opacity","clipPath","filter","transform","backgroundColor"]),Ci=10,g5=2e4,y5=(e,t)=>t.type==="spring"||e==="backgroundColor"||!I0(t.ease);function v5(e,t,{onUpdate:n,onComplete:r,...s}){if(!(p5()&&m5.has(t)&&!s.repeatDelay&&s.repeatType!=="mirror"&&s.damping!==0&&s.type!=="inertia"))return!1;let o=!1,a,l,c=!1;const d=()=>{l=new Promise(w=>{a=w})};d();let{keyframes:f,duration:u=300,ease:h,times:p}=s;if(y5(t,s)){const w=bo({...s,repeat:0,delay:0});let b={done:!1,value:f[0]};const S=[];let C=0;for(;!b.done&&C{c=!1,g.cancel()},v=()=>{c=!0,oe.update(x),a(),d()};return g.onfinish=()=>{c||(e.set(Tw(f,s)),r&&r(),v())},{then(w,b){return l.then(w,b)},attachTimeline(w){return g.timeline=w,g.onfinish=null,ye},get time(){return zt(g.currentTime||0)},set time(w){g.currentTime=Bn(w)},get speed(){return g.playbackRate},set speed(w){g.playbackRate=w},get duration(){return zt(u)},play:()=>{o||(g.play(),Ht(x))},pause:()=>g.pause(),stop:()=>{if(o=!0,g.playState==="idle")return;const{currentTime:w}=g;if(w){const b=bo({...s,autoplay:!1});e.setWithVelocity(b.sample(w-Ci).value,b.sample(w).value,Ci)}v()},complete:()=>{c||g.finish()},cancel:v}}function x5({keyframes:e,delay:t,onUpdate:n,onComplete:r}){const s=()=>(n&&n(e[e.length-1]),r&&r(),{time:0,speed:1,duration:0,play:ye,pause:ye,stop:ye,then:i=>(i(),Promise.resolve()),cancel:ye,complete:ye});return t?bo({keyframes:[0,1],duration:0,delay:t,onComplete:s}):s()}const w5={type:"spring",stiffness:500,damping:25,restSpeed:10},b5=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),S5={type:"keyframes",duration:.8},k5={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},C5=(e,{keyframes:t})=>t.length>2?S5:Qn.has(e)?e.startsWith("scale")?b5(t[1]):w5:k5,Zl=(e,t)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(bn.test(t)||t==="0")&&!t.startsWith("url(")),P5=new Set(["brightness","contrast","saturate","opacity"]);function j5(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[r]=n.match(Qo)||[];if(!r)return e;const s=n.replace(r,"");let i=P5.has(t)?1:0;return r!==n&&(i*=100),t+"("+i+s+")"}const E5=/([a-z-]*)\(.*?\)/g,Jl={...bn,getAnimatableNone:e=>{const t=e.match(E5);return t?t.map(j5).join(" "):e}},T5={...S0,color:Fe,backgroundColor:Fe,outlineColor:Fe,fill:Fe,stroke:Fe,borderColor:Fe,borderTopColor:Fe,borderRightColor:Fe,borderBottomColor:Fe,borderLeftColor:Fe,filter:Jl,WebkitFilter:Jl},Pc=e=>T5[e];function lg(e,t){let n=Pc(e);return n!==Jl&&(n=bn),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const ug=e=>/^0[^.\s]+$/.test(e);function N5(e){if(typeof e=="number")return e===0;if(e!==null)return e==="none"||e==="0"||ug(e)}function M5(e,t,n,r){const s=Zl(t,n);let i;Array.isArray(n)?i=[...n]:i=[null,n];const o=r.from!==void 0?r.from:e.get();let a;const l=[];for(let c=0;cs=>{const i=jc(r,e)||{},o=i.delay||r.delay||0;let{elapsed:a=0}=r;a=a-Bn(o);const l=M5(t,e,n,i),c=l[0],d=l[l.length-1],f=Zl(e,c),u=Zl(e,d);let h={keyframes:l,velocity:t.getVelocity(),ease:"easeOut",...i,delay:-a,onUpdate:p=>{t.set(p),i.onUpdate&&i.onUpdate(p)},onComplete:()=>{s(),i.onComplete&&i.onComplete()}};if(_5(i)||(h={...h,...C5(e,h)}),h.duration&&(h.duration=Bn(h.duration)),h.repeatDelay&&(h.repeatDelay=Bn(h.repeatDelay)),!f||!u||jw.current||i.type===!1||A5.skipAnimations)return x5(h);if(!r.isHandoff&&t.owner&&t.owner.current instanceof HTMLElement&&!t.owner.getProps().onUpdate){const p=v5(t,e,h);if(p)return p}return bo(h)};function So(e){return!!(Ge(e)&&e.add)}const cg=e=>/^\-?\d*\.?\d+$/.test(e);function Tc(e,t){e.indexOf(t)===-1&&e.push(t)}function Nc(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}class Mc{constructor(){this.subscriptions=[]}add(t){return Tc(this.subscriptions,t),()=>Nc(this.subscriptions,t)}notify(t,n,r){const s=this.subscriptions.length;if(s)if(s===1)this.subscriptions[0](t,n,r);else for(let i=0;i!isNaN(parseFloat(e));class D5{constructor(t,n={}){this.version="10.18.0",this.timeDelta=0,this.lastUpdated=0,this.canTrackVelocity=!1,this.events={},this.updateAndNotify=(r,s=!0)=>{this.prev=this.current,this.current=r;const{delta:i,timestamp:o}=De;this.lastUpdated!==o&&(this.timeDelta=i,this.lastUpdated=o,oe.postRender(this.scheduleVelocityCheck)),this.prev!==this.current&&this.events.change&&this.events.change.notify(this.current),this.events.velocityChange&&this.events.velocityChange.notify(this.getVelocity()),s&&this.events.renderRequest&&this.events.renderRequest.notify(this.current)},this.scheduleVelocityCheck=()=>oe.postRender(this.velocityCheck),this.velocityCheck=({timestamp:r})=>{r!==this.lastUpdated&&(this.prev=this.current,this.events.velocityChange&&this.events.velocityChange.notify(this.getVelocity()))},this.hasAnimated=!1,this.prev=this.current=t,this.canTrackVelocity=L5(this.current),this.owner=n.owner}onChange(t){return this.on("change",t)}on(t,n){this.events[t]||(this.events[t]=new Mc);const r=this.events[t].add(n);return t==="change"?()=>{r(),oe.read(()=>{this.events.change.getSize()||this.stop()})}:r}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,n){this.passiveEffect=t,this.stopPassiveEffect=n}set(t,n=!0){!n||!this.passiveEffect?this.updateAndNotify(t,n):this.passiveEffect(t,this.updateAndNotify)}setWithVelocity(t,n,r){this.set(n),this.prev=t,this.timeDelta=r}jump(t){this.updateAndNotify(t),this.prev=t,this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}get(){return this.current}getPrevious(){return this.prev}getVelocity(){return this.canTrackVelocity?ig(parseFloat(this.current)-parseFloat(this.prev),this.timeDelta):0}start(t){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=t(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function Lr(e,t){return new D5(e,t)}const dg=e=>t=>t.test(e),R5={test:e=>e==="auto",parse:e=>e},fg=[Zn,B,Tt,Qt,$2,O2,R5],Jr=e=>fg.find(dg(e)),V5=[...fg,Fe,bn],F5=e=>V5.find(dg(e));function I5(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,Lr(n))}function z5(e,t){const n=Jo(e,t);let{transitionEnd:r={},transition:s={},...i}=n?e.makeTargetAnimatable(n,!1):{};i={...i,...r};for(const o in i){const a=nw(i[o]);I5(e,o,a)}}function O5(e,t,n){var r,s;const i=Object.keys(t).filter(a=>!e.hasValue(a)),o=i.length;if(o)for(let a=0;al.remove(f))),c.push(x)}return o&&Promise.all(c).then(()=>{o&&z5(e,o)}),c}function eu(e,t,n={}){const r=Jo(e,t,n.custom);let{transition:s=e.getDefaultTransition()||{}}=r||{};n.transitionOverride&&(s=n.transitionOverride);const i=r?()=>Promise.all(hg(e,r,n)):()=>Promise.resolve(),o=e.variantChildren&&e.variantChildren.size?(l=0)=>{const{delayChildren:c=0,staggerChildren:d,staggerDirection:f}=s;return H5(e,t,c+l,d,f,n)}:()=>Promise.resolve(),{when:a}=s;if(a){const[l,c]=a==="beforeChildren"?[i,o]:[o,i];return l().then(()=>c())}else return Promise.all([i(),o(n.delay)])}function H5(e,t,n=0,r=0,s=1,i){const o=[],a=(e.variantChildren.size-1)*r,l=s===1?(c=0)=>c*r:(c=0)=>a-c*r;return Array.from(e.variantChildren).sort(q5).forEach((c,d)=>{c.notify("AnimationStart",t),o.push(eu(c,t,{...i,delay:n+l(d)}).then(()=>c.notify("AnimationComplete",t)))}),Promise.all(o)}function q5(e,t){return e.sortNodePosition(t)}function G5(e,t,n={}){e.notify("AnimationStart",t);let r;if(Array.isArray(t)){const s=t.map(i=>eu(e,i,n));r=Promise.all(s)}else if(typeof t=="string")r=eu(e,t,n);else{const s=typeof t=="function"?Jo(e,t,n.custom):t;r=Promise.all(hg(e,s,n))}return r.then(()=>e.notify("AnimationComplete",t))}const Y5=[...fc].reverse(),K5=fc.length;function X5(e){return t=>Promise.all(t.map(({animation:n,options:r})=>G5(e,n,r)))}function Q5(e){let t=X5(e);const n=J5();let r=!0;const s=(l,c)=>{const d=Jo(e,c);if(d){const{transition:f,transitionEnd:u,...h}=d;l={...l,...h,...u}}return l};function i(l){t=l(e)}function o(l,c){const d=e.getProps(),f=e.getVariantContext(!0)||{},u=[],h=new Set;let p={},g=1/0;for(let v=0;vg&&S,T=!1;const z=Array.isArray(b)?b:[b];let V=z.reduce(s,{});C===!1&&(V={});const{prevResolvedValues:U={}}=w,R={...U,...V},Q=A=>{D=!0,h.has(A)&&(T=!0,h.delete(A)),w.needsAnimating[A]=!0};for(const A in R){const q=V[A],_=U[A];if(p.hasOwnProperty(A))continue;let N=!1;vo(q)&&vo(_)?N=!V0(q,_):N=q!==_,N?q!==void 0?Q(A):h.add(A):q!==void 0&&h.has(A)?Q(A):w.protectedKeys[A]=!0}w.prevProp=b,w.prevResolvedValues=V,w.isActive&&(p={...p,...V}),r&&e.blockInitialAnimation&&(D=!1),D&&(!P||T)&&u.push(...z.map(A=>({animation:A,options:{type:y,...l}})))}if(h.size){const v={};h.forEach(y=>{const w=e.getBaseTarget(y);w!==void 0&&(v[y]=w)}),u.push({animation:v})}let x=!!u.length;return r&&(d.initial===!1||d.initial===d.animate)&&!e.manuallyAnimateOnMount&&(x=!1),r=!1,x?t(u):Promise.resolve()}function a(l,c,d){var f;if(n[l].isActive===c)return Promise.resolve();(f=e.variantChildren)===null||f===void 0||f.forEach(h=>{var p;return(p=h.animationState)===null||p===void 0?void 0:p.setActive(l,c)}),n[l].isActive=c;const u=o(d,l);for(const h in n)n[h].protectedKeys={};return u}return{animateChanges:o,setActive:a,setAnimateFunction:i,getState:()=>n}}function Z5(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!V0(t,e):!1}function _n(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function J5(){return{animate:_n(!0),whileInView:_n(),whileHover:_n(),whileTap:_n(),whileDrag:_n(),whileFocus:_n(),exit:_n()}}class e3 extends Nn{constructor(t){super(t),t.animationState||(t.animationState=Q5(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();this.unmount(),Ko(t)&&(this.unmount=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){}}let t3=0;class n3 extends Nn{constructor(){super(...arguments),this.id=t3++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n,custom:r}=this.node.presenceContext,{isPresent:s}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===s)return;const i=this.node.animationState.setActive("exit",!t,{custom:r??this.node.getProps().custom});n&&!t&&i.then(()=>n(this.id))}mount(){const{register:t}=this.node.presenceContext||{};t&&(this.unmount=t(this.id))}unmount(){}}const r3={animation:{Feature:e3},exit:{Feature:n3}},yf=(e,t)=>Math.abs(e-t);function s3(e,t){const n=yf(e.x,t.x),r=yf(e.y,t.y);return Math.sqrt(n**2+r**2)}class pg{constructor(t,n,{transformPagePoint:r,contextWindow:s,dragSnapToOrigin:i=!1}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const f=za(this.lastMoveEventInfo,this.history),u=this.startEvent!==null,h=s3(f.offset,{x:0,y:0})>=3;if(!u&&!h)return;const{point:p}=f,{timestamp:g}=De;this.history.push({...p,timestamp:g});const{onStart:x,onMove:v}=this.handlers;u||(x&&x(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),v&&v(this.lastMoveEvent,f)},this.handlePointerMove=(f,u)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=Ia(u,this.transformPagePoint),oe.update(this.updatePoint,!0)},this.handlePointerUp=(f,u)=>{this.end();const{onEnd:h,onSessionEnd:p,resumeAnimation:g}=this.handlers;if(this.dragSnapToOrigin&&g&&g(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const x=za(f.type==="pointercancel"?this.lastMoveEventInfo:Ia(u,this.transformPagePoint),this.history);this.startEvent&&h&&h(f,x),p&&p(f,x)},!_0(t))return;this.dragSnapToOrigin=i,this.handlers=n,this.transformPagePoint=r,this.contextWindow=s||window;const o=Zo(t),a=Ia(o,this.transformPagePoint),{point:l}=a,{timestamp:c}=De;this.history=[{...l,timestamp:c}];const{onSessionStart:d}=n;d&&d(t,za(a,this.history)),this.removeListeners=yn(It(this.contextWindow,"pointermove",this.handlePointerMove),It(this.contextWindow,"pointerup",this.handlePointerUp),It(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),Ht(this.updatePoint)}}function Ia(e,t){return t?{point:t(e.point)}:e}function vf(e,t){return{x:e.x-t.x,y:e.y-t.y}}function za({point:e},t){return{point:e,delta:vf(e,mg(t)),offset:vf(e,i3(t)),velocity:o3(t,.1)}}function i3(e){return e[0]}function mg(e){return e[e.length-1]}function o3(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,r=null;const s=mg(e);for(;n>=0&&(r=e[n],!(s.timestamp-r.timestamp>Bn(t)));)n--;if(!r)return{x:0,y:0};const i=zt(s.timestamp-r.timestamp);if(i===0)return{x:0,y:0};const o={x:(s.x-r.x)/i,y:(s.y-r.y)/i};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}function Je(e){return e.max-e.min}function tu(e,t=0,n=.01){return Math.abs(e-t)<=n}function xf(e,t,n,r=.5){e.origin=r,e.originPoint=ce(t.min,t.max,e.origin),e.scale=Je(n)/Je(t),(tu(e.scale,1,1e-4)||isNaN(e.scale))&&(e.scale=1),e.translate=ce(n.min,n.max,e.origin)-e.originPoint,(tu(e.translate)||isNaN(e.translate))&&(e.translate=0)}function xs(e,t,n,r){xf(e.x,t.x,n.x,r?r.originX:void 0),xf(e.y,t.y,n.y,r?r.originY:void 0)}function wf(e,t,n){e.min=n.min+t.min,e.max=e.min+Je(t)}function a3(e,t,n){wf(e.x,t.x,n.x),wf(e.y,t.y,n.y)}function bf(e,t,n){e.min=t.min-n.min,e.max=e.min+Je(t)}function ws(e,t,n){bf(e.x,t.x,n.x),bf(e.y,t.y,n.y)}function l3(e,{min:t,max:n},r){return t!==void 0&&en&&(e=r?ce(n,e,r.max):Math.min(e,n)),e}function Sf(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function u3(e,{top:t,left:n,bottom:r,right:s}){return{x:Sf(e.x,n,s),y:Sf(e.y,t,r)}}function kf(e,t){let n=t.min-e.min,r=t.max-e.max;return t.max-t.minr?n=Ws(t.min,t.max-r,e.min):r>s&&(n=Ws(e.min,e.max-s,t.min)),wn(0,1,n)}function f3(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const nu=.35;function h3(e=nu){return e===!1?e=0:e===!0&&(e=nu),{x:Cf(e,"left","right"),y:Cf(e,"top","bottom")}}function Cf(e,t,n){return{min:Pf(e,t),max:Pf(e,n)}}function Pf(e,t){return typeof e=="number"?e:e[t]||0}const jf=()=>({translate:0,scale:1,origin:0,originPoint:0}),gr=()=>({x:jf(),y:jf()}),Ef=()=>({min:0,max:0}),xe=()=>({x:Ef(),y:Ef()});function st(e){return[e("x"),e("y")]}function gg({top:e,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:e,max:r}}}function p3({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function m3(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),r=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:r.y,right:r.x}}function Oa(e){return e===void 0||e===1}function ru({scale:e,scaleX:t,scaleY:n}){return!Oa(e)||!Oa(t)||!Oa(n)}function Dn(e){return ru(e)||yg(e)||e.z||e.rotate||e.rotateX||e.rotateY}function yg(e){return Tf(e.x)||Tf(e.y)}function Tf(e){return e&&e!=="0%"}function ko(e,t,n){const r=e-n,s=t*r;return n+s}function Nf(e,t,n,r,s){return s!==void 0&&(e=ko(e,s,r)),ko(e,n,r)+t}function su(e,t=0,n=1,r,s){e.min=Nf(e.min,t,n,r,s),e.max=Nf(e.max,t,n,r,s)}function vg(e,{x:t,y:n}){su(e.x,t.translate,t.scale,t.originPoint),su(e.y,n.translate,n.scale,n.originPoint)}function g3(e,t,n,r=!1){const s=n.length;if(!s)return;t.x=t.y=1;let i,o;for(let a=0;a1.0000000000001||e<.999999999999?e:1}function en(e,t){e.min=e.min+t,e.max=e.max+t}function _f(e,t,[n,r,s]){const i=t[s]!==void 0?t[s]:.5,o=ce(e.min,e.max,i);su(e,t[n],t[r],o,t.scale)}const y3=["x","scaleX","originX"],v3=["y","scaleY","originY"];function yr(e,t){_f(e.x,t,y3),_f(e.y,t,v3)}function xg(e,t){return gg(m3(e.getBoundingClientRect(),t))}function x3(e,t,n){const r=xg(e,n),{scroll:s}=t;return s&&(en(r.x,s.offset.x),en(r.y,s.offset.y)),r}const wg=({current:e})=>e?e.ownerDocument.defaultView:null,w3=new WeakMap;class b3{constructor(t){this.openGlobalLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=xe(),this.visualElement=t}start(t,{snapToCursor:n=!1}={}){const{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;const s=d=>{const{dragSnapToOrigin:f}=this.getProps();f?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(Zo(d,"page").point)},i=(d,f)=>{const{drag:u,dragPropagation:h,onDragStart:p}=this.getProps();if(u&&!h&&(this.openGlobalLock&&this.openGlobalLock(),this.openGlobalLock=L0(u),!this.openGlobalLock))return;this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),st(x=>{let v=this.getAxisMotionValue(x).get()||0;if(Tt.test(v)){const{projection:y}=this.visualElement;if(y&&y.layout){const w=y.layout.layoutBox[x];w&&(v=Je(w)*(parseFloat(v)/100))}}this.originPoint[x]=v}),p&&oe.update(()=>p(d,f),!1,!0);const{animationState:g}=this.visualElement;g&&g.setActive("whileDrag",!0)},o=(d,f)=>{const{dragPropagation:u,dragDirectionLock:h,onDirectionLock:p,onDrag:g}=this.getProps();if(!u&&!this.openGlobalLock)return;const{offset:x}=f;if(h&&this.currentDirection===null){this.currentDirection=S3(x),this.currentDirection!==null&&p&&p(this.currentDirection);return}this.updateAxis("x",f.point,x),this.updateAxis("y",f.point,x),this.visualElement.render(),g&&g(d,f)},a=(d,f)=>this.stop(d,f),l=()=>st(d=>{var f;return this.getAnimationState(d)==="paused"&&((f=this.getAxisMotionValue(d).animation)===null||f===void 0?void 0:f.play())}),{dragSnapToOrigin:c}=this.getProps();this.panSession=new pg(t,{onSessionStart:s,onStart:i,onMove:o,onSessionEnd:a,resumeAnimation:l},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:c,contextWindow:wg(this.visualElement)})}stop(t,n){const r=this.isDragging;if(this.cancel(),!r)return;const{velocity:s}=n;this.startAnimation(s);const{onDragEnd:i}=this.getProps();i&&oe.update(()=>i(t,n))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:r}=this.getProps();!r&&this.openGlobalLock&&(this.openGlobalLock(),this.openGlobalLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(t,n,r){const{drag:s}=this.getProps();if(!r||!Pi(t,s,this.currentDirection))return;const i=this.getAxisMotionValue(t);let o=this.originPoint[t]+r[t];this.constraints&&this.constraints[t]&&(o=l3(o,this.constraints[t],this.elastic[t])),i.set(o)}resolveConstraints(){var t;const{dragConstraints:n,dragElastic:r}=this.getProps(),s=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(t=this.visualElement.projection)===null||t===void 0?void 0:t.layout,i=this.constraints;n&&pr(n)?this.constraints||(this.constraints=this.resolveRefConstraints()):n&&s?this.constraints=u3(s.layoutBox,n):this.constraints=!1,this.elastic=h3(r),i!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&st(o=>{this.getAxisMotionValue(o)&&(this.constraints[o]=f3(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!pr(t))return!1;const r=t.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const i=x3(r,s.root,this.visualElement.getTransformPagePoint());let o=c3(s.layout.layoutBox,i);if(n){const a=n(p3(o));this.hasMutatedConstraints=!!a,a&&(o=gg(a))}return o}startAnimation(t){const{drag:n,dragMomentum:r,dragElastic:s,dragTransition:i,dragSnapToOrigin:o,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=st(d=>{if(!Pi(d,n,this.currentDirection))return;let f=l&&l[d]||{};o&&(f={min:0,max:0});const u=s?200:1e6,h=s?40:1e7,p={type:"inertia",velocity:r?t[d]:0,bounceStiffness:u,bounceDamping:h,timeConstant:750,restDelta:1,restSpeed:10,...i,...f};return this.startAxisValueAnimation(d,p)});return Promise.all(c).then(a)}startAxisValueAnimation(t,n){const r=this.getAxisMotionValue(t);return r.start(Ec(t,r,0,n))}stopAnimation(){st(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){st(t=>{var n;return(n=this.getAxisMotionValue(t).animation)===null||n===void 0?void 0:n.pause()})}getAnimationState(t){var n;return(n=this.getAxisMotionValue(t).animation)===null||n===void 0?void 0:n.state}getAxisMotionValue(t){const n="_drag"+t.toUpperCase(),r=this.visualElement.getProps(),s=r[n];return s||this.visualElement.getValue(t,(r.initial?r.initial[t]:void 0)||0)}snapToCursor(t){st(n=>{const{drag:r}=this.getProps();if(!Pi(n,r,this.currentDirection))return;const{projection:s}=this.visualElement,i=this.getAxisMotionValue(n);if(s&&s.layout){const{min:o,max:a}=s.layout.layoutBox[n];i.set(t[n]-ce(o,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:r}=this.visualElement;if(!pr(n)||!r||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};st(o=>{const a=this.getAxisMotionValue(o);if(a){const l=a.get();s[o]=d3({min:l,max:l},this.constraints[o])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.resolveConstraints(),st(o=>{if(!Pi(o,t,null))return;const a=this.getAxisMotionValue(o),{min:l,max:c}=this.constraints[o];a.set(ce(l,c,s[o]))})}addListeners(){if(!this.visualElement.current)return;w3.set(this.visualElement,this);const t=this.visualElement.current,n=It(t,"pointerdown",l=>{const{drag:c,dragListener:d=!0}=this.getProps();c&&d&&this.start(l)}),r=()=>{const{dragConstraints:l}=this.getProps();pr(l)&&(this.constraints=this.resolveRefConstraints())},{projection:s}=this.visualElement,i=s.addEventListener("measure",r);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),r();const o=Vt(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(st(d=>{const f=this.getAxisMotionValue(d);f&&(this.originPoint[d]+=l[d].translate,f.set(f.get()+l[d].translate))}),this.visualElement.render())});return()=>{o(),n(),i(),a&&a()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:r=!1,dragPropagation:s=!1,dragConstraints:i=!1,dragElastic:o=nu,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:r,dragPropagation:s,dragConstraints:i,dragElastic:o,dragMomentum:a}}}function Pi(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function S3(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class k3 extends Nn{constructor(t){super(t),this.removeGroupControls=ye,this.removeListeners=ye,this.controls=new b3(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||ye}unmount(){this.removeGroupControls(),this.removeListeners()}}const Af=e=>(t,n)=>{e&&oe.update(()=>e(t,n))};class C3 extends Nn{constructor(){super(...arguments),this.removePointerDownListener=ye}onPointerDown(t){this.session=new pg(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:wg(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:r,onPanEnd:s}=this.node.getProps();return{onSessionStart:Af(t),onStart:Af(n),onMove:r,onEnd:(i,o)=>{delete this.session,s&&oe.update(()=>s(i,o))}}}mount(){this.removePointerDownListener=It(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}function P3(){const e=k.useContext(cc);if(e===null)return[!0,null];const{isPresent:t,onExitComplete:n,register:r}=e,s=k.useId();return k.useEffect(()=>r(s),[]),!t&&n?[!1,()=>n&&n(s)]:[!0]}const Bi={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Lf(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const es={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(B.test(e))e=parseFloat(e);else return e;const n=Lf(e,t.target.x),r=Lf(e,t.target.y);return`${n}% ${r}%`}},j3={correct:(e,{treeScale:t,projectionDelta:n})=>{const r=e,s=bn.parse(e);if(s.length>5)return r;const i=bn.createTransformer(e),o=typeof s[0]!="number"?1:0,a=n.x.scale*t.x,l=n.y.scale*t.y;s[0+o]/=a,s[1+o]/=l;const c=ce(a,l,.5);return typeof s[2+o]=="number"&&(s[2+o]/=c),typeof s[3+o]=="number"&&(s[3+o]/=c),i(s)}};class E3 extends Gs.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r,layoutId:s}=this.props,{projection:i}=t;L2(T3),i&&(n.group&&n.group.add(i),r&&r.register&&s&&r.register(i),i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),Bi.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:r,drag:s,isPresent:i}=this.props,o=r.projection;return o&&(o.isPresent=i,s||t.layoutDependency!==n||n===void 0?o.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?o.promote():o.relegate()||oe.postRender(()=>{const a=o.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),queueMicrotask(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r}=this.props,{projection:s}=t;s&&(s.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(s),r&&r.deregister&&r.deregister(s))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function bg(e){const[t,n]=P3(),r=k.useContext(g0);return Gs.createElement(E3,{...e,layoutGroup:r,switchLayoutGroup:k.useContext(y0),isPresent:t,safeToRemove:n})}const T3={borderRadius:{...es,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:es,borderTopRightRadius:es,borderBottomLeftRadius:es,borderBottomRightRadius:es,boxShadow:j3},Sg=["TopLeft","TopRight","BottomLeft","BottomRight"],N3=Sg.length,Df=e=>typeof e=="string"?parseFloat(e):e,Rf=e=>typeof e=="number"||B.test(e);function M3(e,t,n,r,s,i){s?(e.opacity=ce(0,n.opacity!==void 0?n.opacity:1,_3(r)),e.opacityExit=ce(t.opacity!==void 0?t.opacity:1,0,A3(r))):i&&(e.opacity=ce(t.opacity!==void 0?t.opacity:1,n.opacity!==void 0?n.opacity:1,r));for(let o=0;ort?1:n(Ws(e,t,r))}function Ff(e,t){e.min=t.min,e.max=t.max}function rt(e,t){Ff(e.x,t.x),Ff(e.y,t.y)}function If(e,t,n,r,s){return e-=t,e=ko(e,1/n,r),s!==void 0&&(e=ko(e,1/s,r)),e}function L3(e,t=0,n=1,r=.5,s,i=e,o=e){if(Tt.test(t)&&(t=parseFloat(t),t=ce(o.min,o.max,t/100)-o.min),typeof t!="number")return;let a=ce(i.min,i.max,r);e===i&&(a-=t),e.min=If(e.min,t,n,a,s),e.max=If(e.max,t,n,a,s)}function zf(e,t,[n,r,s],i,o){L3(e,t[n],t[r],t[s],t.scale,i,o)}const D3=["x","scaleX","originX"],R3=["y","scaleY","originY"];function Of(e,t,n,r){zf(e.x,t,D3,n?n.x:void 0,r?r.x:void 0),zf(e.y,t,R3,n?n.y:void 0,r?r.y:void 0)}function $f(e){return e.translate===0&&e.scale===1}function Cg(e){return $f(e.x)&&$f(e.y)}function V3(e,t){return e.x.min===t.x.min&&e.x.max===t.x.max&&e.y.min===t.y.min&&e.y.max===t.y.max}function Pg(e,t){return Math.round(e.x.min)===Math.round(t.x.min)&&Math.round(e.x.max)===Math.round(t.x.max)&&Math.round(e.y.min)===Math.round(t.y.min)&&Math.round(e.y.max)===Math.round(t.y.max)}function Bf(e){return Je(e.x)/Je(e.y)}class F3{constructor(){this.members=[]}add(t){Tc(this.members,t),t.scheduleRender()}remove(t){if(Nc(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){const n=this.members.findIndex(s=>t===s);if(n===0)return!1;let r;for(let s=n;s>=0;s--){const i=this.members[s];if(i.isPresent!==!1){r=i;break}}return r?(this.promote(r),!0):!1}promote(t,n){const r=this.lead;if(t!==r&&(this.prevLead=r,this.lead=t,t.show(),r)){r.instance&&r.scheduleRender(),t.scheduleRender(),t.resumeFrom=r,n&&(t.resumeFrom.preserveOpacity=!0),r.snapshot&&(t.snapshot=r.snapshot,t.snapshot.latestValues=r.animationValues||r.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:s}=t.options;s===!1&&r.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:n,resumingFrom:r}=t;n.onExitComplete&&n.onExitComplete(),r&&r.options.onExitComplete&&r.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function Uf(e,t,n){let r="";const s=e.x.translate/t.x,i=e.y.translate/t.y;if((s||i)&&(r=`translate3d(${s}px, ${i}px, 0) `),(t.x!==1||t.y!==1)&&(r+=`scale(${1/t.x}, ${1/t.y}) `),n){const{rotate:l,rotateX:c,rotateY:d}=n;l&&(r+=`rotate(${l}deg) `),c&&(r+=`rotateX(${c}deg) `),d&&(r+=`rotateY(${d}deg) `)}const o=e.x.scale*t.x,a=e.y.scale*t.y;return(o!==1||a!==1)&&(r+=`scale(${o}, ${a})`),r||"none"}const I3=(e,t)=>e.depth-t.depth;class z3{constructor(){this.children=[],this.isDirty=!1}add(t){Tc(this.children,t),this.isDirty=!0}remove(t){Nc(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(I3),this.isDirty=!1,this.children.forEach(t)}}function O3(e,t){const n=performance.now(),r=({timestamp:s})=>{const i=s-n;i>=t&&(Ht(r),e(i-t))};return oe.read(r,!0),()=>Ht(r)}function $3(e){window.MotionDebug&&window.MotionDebug.record(e)}function B3(e){return e instanceof SVGElement&&e.tagName!=="svg"}function U3(e,t,n){const r=Ge(e)?e:Lr(e);return r.start(Ec("",r,t,n)),r.animation}const Wf=["","X","Y","Z"],W3={visibility:"hidden"},Hf=1e3;let H3=0;const Rn={type:"projectionFrame",totalNodes:0,resolvedTargetDeltas:0,recalculatedProjection:0};function jg({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:s}){return class{constructor(o={},a=t==null?void 0:t()){this.id=H3++,this.animationId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,Rn.totalNodes=Rn.resolvedTargetDeltas=Rn.recalculatedProjection=0,this.nodes.forEach(Y3),this.nodes.forEach(J3),this.nodes.forEach(e4),this.nodes.forEach(K3),$3(Rn)},this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=o,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let l=0;lthis.root.updateBlockedByResize=!1;e(o,()=>{this.root.updateBlockedByResize=!0,f&&f(),f=O3(u,250),Bi.hasAnimatedSinceResize&&(Bi.hasAnimatedSinceResize=!1,this.nodes.forEach(Gf))})}l&&this.root.registerSharedNode(l,this),this.options.animate!==!1&&d&&(l||c)&&this.addEventListener("didUpdate",({delta:f,hasLayoutChanged:u,hasRelativeTargetChanged:h,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||i4,{onLayoutAnimationStart:x,onLayoutAnimationComplete:v}=d.getProps(),y=!this.targetLayout||!Pg(this.targetLayout,p)||h,w=!u&&h;if(this.options.layoutRoot||this.resumeFrom&&this.resumeFrom.instance||w||u&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0),this.setAnimationOrigin(f,w);const b={...jc(g,"layout"),onPlay:x,onComplete:v};(d.shouldReduceMotion||this.options.layoutRoot)&&(b.delay=0,b.type=!1),this.startAnimation(b)}else u||Gf(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=p})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const o=this.getStack();o&&o.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,Ht(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(t4),this.animationId++)}getTransformTemplate(){const{visualElement:o}=this.options;return o&&o.getProps().transformTemplate}willUpdate(o=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let d=0;dthis.update()))}clearAllSnapshots(){this.nodes.forEach(X3),this.sharedNodes.forEach(n4)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,oe.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){oe.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure())}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let l=0;l{const S=b/1e3;Yf(f.x,o.x,S),Yf(f.y,o.y,S),this.setTargetDelta(f),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(ws(u,this.layout.layoutBox,this.relativeParent.layout.layoutBox),r4(this.relativeTarget,this.relativeTargetOrigin,u,S),w&&V3(this.relativeTarget,w)&&(this.isProjectionDirty=!1),w||(w=xe()),rt(w,this.relativeTarget)),g&&(this.animationValues=d,M3(d,c,this.latestValues,S,y,v)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=S},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(o){this.notifyListeners("animationStart"),this.currentAnimation&&this.currentAnimation.stop(),this.resumingFrom&&this.resumingFrom.currentAnimation&&this.resumingFrom.currentAnimation.stop(),this.pendingAnimation&&(Ht(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=oe.update(()=>{Bi.hasAnimatedSinceResize=!0,this.currentAnimation=U3(0,Hf,{...o,onUpdate:a=>{this.mixTargetDelta(a),o.onUpdate&&o.onUpdate(a)},onComplete:()=>{o.onComplete&&o.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const o=this.getStack();o&&o.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(Hf),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const o=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:d}=o;if(!(!a||!l||!c)){if(this!==o&&this.layout&&c&&Eg(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||xe();const f=Je(this.layout.layoutBox.x);l.x.min=o.target.x.min,l.x.max=l.x.min+f;const u=Je(this.layout.layoutBox.y);l.y.min=o.target.y.min,l.y.max=l.y.min+u}rt(a,l),yr(a,d),xs(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(o,a){this.sharedNodes.has(o)||this.sharedNodes.set(o,new F3),this.sharedNodes.get(o).add(a);const c=a.options.initialPromotionConfig;a.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.shouldPreserveFollowOpacity(a):void 0})}isLead(){const o=this.getStack();return o?o.lead===this:!0}getLead(){var o;const{layoutId:a}=this.options;return a?((o=this.getStack())===null||o===void 0?void 0:o.lead)||this:this}getPrevLead(){var o;const{layoutId:a}=this.options;return a?(o=this.getStack())===null||o===void 0?void 0:o.prevLead:void 0}getStack(){const{layoutId:o}=this.options;if(o)return this.root.sharedNodes.get(o)}promote({needsReset:o,transition:a,preserveFollowOpacity:l}={}){const c=this.getStack();c&&c.promote(this,l),o&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const o=this.getStack();return o?o.relegate(this):!1}resetRotation(){const{visualElement:o}=this.options;if(!o)return;let a=!1;const{latestValues:l}=o;if((l.rotate||l.rotateX||l.rotateY||l.rotateZ)&&(a=!0),!a)return;const c={};for(let d=0;d{var a;return(a=o.currentAnimation)===null||a===void 0?void 0:a.stop()}),this.root.nodes.forEach(qf),this.root.sharedNodes.clear()}}}function q3(e){e.updateLayout()}function G3(e){var t;const n=((t=e.resumeFrom)===null||t===void 0?void 0:t.snapshot)||e.snapshot;if(e.isLead()&&e.layout&&n&&e.hasListeners("didUpdate")){const{layoutBox:r,measuredBox:s}=e.layout,{animationType:i}=e.options,o=n.source!==e.layout.source;i==="size"?st(f=>{const u=o?n.measuredBox[f]:n.layoutBox[f],h=Je(u);u.min=r[f].min,u.max=u.min+h}):Eg(i,n.layoutBox,r)&&st(f=>{const u=o?n.measuredBox[f]:n.layoutBox[f],h=Je(r[f]);u.max=u.min+h,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[f].max=e.relativeTarget[f].min+h)});const a=gr();xs(a,r,n.layoutBox);const l=gr();o?xs(l,e.applyTransform(s,!0),n.measuredBox):xs(l,r,n.layoutBox);const c=!Cg(a);let d=!1;if(!e.resumeFrom){const f=e.getClosestProjectingParent();if(f&&!f.resumeFrom){const{snapshot:u,layout:h}=f;if(u&&h){const p=xe();ws(p,n.layoutBox,u.layoutBox);const g=xe();ws(g,r,h.layoutBox),Pg(p,g)||(d=!0),f.options.layoutRoot&&(e.relativeTarget=g,e.relativeTargetOrigin=p,e.relativeParent=f)}}}e.notifyListeners("didUpdate",{layout:r,snapshot:n,delta:l,layoutDelta:a,hasLayoutChanged:c,hasRelativeTargetChanged:d})}else if(e.isLead()){const{onExitComplete:r}=e.options;r&&r()}e.options.transition=void 0}function Y3(e){Rn.totalNodes++,e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function K3(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function X3(e){e.clearSnapshot()}function qf(e){e.clearMeasurements()}function Q3(e){e.isLayoutDirty=!1}function Z3(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function Gf(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function J3(e){e.resolveTargetDelta()}function e4(e){e.calcProjection()}function t4(e){e.resetRotation()}function n4(e){e.removeLeadSnapshot()}function Yf(e,t,n){e.translate=ce(t.translate,0,n),e.scale=ce(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function Kf(e,t,n,r){e.min=ce(t.min,n.min,r),e.max=ce(t.max,n.max,r)}function r4(e,t,n,r){Kf(e.x,t.x,n.x,r),Kf(e.y,t.y,n.y,r)}function s4(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const i4={duration:.45,ease:[.4,0,.1,1]},Xf=e=>typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes(e),Qf=Xf("applewebkit/")&&!Xf("chrome/")?Math.round:ye;function Zf(e){e.min=Qf(e.min),e.max=Qf(e.max)}function o4(e){Zf(e.x),Zf(e.y)}function Eg(e,t,n){return e==="position"||e==="preserve-aspect"&&!tu(Bf(t),Bf(n),.2)}const a4=jg({attachResizeListener:(e,t)=>Vt(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),$a={current:void 0},Tg=jg({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!$a.current){const e=new a4({});e.mount(window),e.setOptions({layoutScroll:!0}),$a.current=e}return $a.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),l4={pan:{Feature:C3},drag:{Feature:k3,ProjectionNode:Tg,MeasureLayout:bg}},u4=/var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/;function c4(e){const t=u4.exec(e);if(!t)return[,];const[,n,r]=t;return[n,r]}function iu(e,t,n=1){const[r,s]=c4(e);if(!r)return;const i=window.getComputedStyle(t).getPropertyValue(r);if(i){const o=i.trim();return cg(o)?parseFloat(o):o}else return Yl(s)?iu(s,t,n+1):s}function d4(e,{...t},n){const r=e.current;if(!(r instanceof Element))return{target:t,transitionEnd:n};n&&(n={...n}),e.values.forEach(s=>{const i=s.get();if(!Yl(i))return;const o=iu(i,r);o&&s.set(o)});for(const s in t){const i=t[s];if(!Yl(i))continue;const o=iu(i,r);o&&(t[s]=o,n||(n={}),n[s]===void 0&&(n[s]=i))}return{target:t,transitionEnd:n}}const f4=new Set(["width","height","top","left","right","bottom","x","y","translateX","translateY"]),Ng=e=>f4.has(e),h4=e=>Object.keys(e).some(Ng),Jf=e=>e===Zn||e===B,eh=(e,t)=>parseFloat(e.split(", ")[t]),th=(e,t)=>(n,{transform:r})=>{if(r==="none"||!r)return 0;const s=r.match(/^matrix3d\((.+)\)$/);if(s)return eh(s[1],t);{const i=r.match(/^matrix\((.+)\)$/);return i?eh(i[1],e):0}},p4=new Set(["x","y","z"]),m4=Js.filter(e=>!p4.has(e));function g4(e){const t=[];return m4.forEach(n=>{const r=e.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith("scale")?1:0))}),t.length&&e.render(),t}const Dr={width:({x:e},{paddingLeft:t="0",paddingRight:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),height:({y:e},{paddingTop:t="0",paddingBottom:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:th(4,13),y:th(5,14)};Dr.translateX=Dr.x;Dr.translateY=Dr.y;const y4=(e,t,n)=>{const r=t.measureViewportBox(),s=t.current,i=getComputedStyle(s),{display:o}=i,a={};o==="none"&&t.setStaticValue("display",e.display||"block"),n.forEach(c=>{a[c]=Dr[c](r,i)}),t.render();const l=t.measureViewportBox();return n.forEach(c=>{const d=t.getValue(c);d&&d.jump(a[c]),e[c]=Dr[c](l,i)}),e},v4=(e,t,n={},r={})=>{t={...t},r={...r};const s=Object.keys(t).filter(Ng);let i=[],o=!1;const a=[];if(s.forEach(l=>{const c=e.getValue(l);if(!e.hasValue(l))return;let d=n[l],f=Jr(d);const u=t[l];let h;if(vo(u)){const p=u.length,g=u[0]===null?1:0;d=u[g],f=Jr(d);for(let x=g;x=0?window.pageYOffset:null,c=y4(t,e,a);return i.length&&i.forEach(([d,f])=>{e.getValue(d).set(f)}),e.render(),Yo&&l!==null&&window.scrollTo({top:l}),{target:c,transitionEnd:r}}else return{target:t,transitionEnd:r}};function x4(e,t,n,r){return h4(t)?v4(e,t,n,r):{target:t,transitionEnd:r}}const w4=(e,t,n,r)=>{const s=d4(e,t,r);return t=s.target,r=s.transitionEnd,x4(e,t,n,r)},ou={current:null},Mg={current:!1};function b4(){if(Mg.current=!0,!!Yo)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>ou.current=e.matches;e.addListener(t),t()}else ou.current=!1}function S4(e,t,n){const{willChange:r}=t;for(const s in t){const i=t[s],o=n[s];if(Ge(i))e.addValue(s,i),So(r)&&r.add(s);else if(Ge(o))e.addValue(s,Lr(i,{owner:e})),So(r)&&r.remove(s);else if(o!==i)if(e.hasValue(s)){const a=e.getValue(s);!a.hasAnimated&&a.set(i)}else{const a=e.getStaticValue(s);e.addValue(s,Lr(a!==void 0?a:i,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const nh=new WeakMap,_g=Object.keys(Us),k4=_g.length,rh=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"],C4=hc.length;class P4{constructor({parent:t,props:n,presenceContext:r,reducedMotionConfig:s,visualState:i},o={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.scheduleRender=()=>oe.render(this.render,!1,!0);const{latestValues:a,renderState:l}=i;this.latestValues=a,this.baseTarget={...a},this.initialValues=n.initial?{...a}:{},this.renderState=l,this.parent=t,this.props=n,this.presenceContext=r,this.depth=t?t.depth+1:0,this.reducedMotionConfig=s,this.options=o,this.isControllingVariants=Xo(n),this.isVariantNode=m0(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:c,...d}=this.scrapeMotionValuesFromProps(n,{});for(const f in d){const u=d[f];a[f]!==void 0&&Ge(u)&&(u.set(a[f],!1),So(c)&&c.add(f))}}scrapeMotionValuesFromProps(t,n){return{}}mount(t){this.current=t,nh.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,r)=>this.bindToMotionValue(r,n)),Mg.current||b4(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:ou.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){nh.delete(this.current),this.projection&&this.projection.unmount(),Ht(this.notifyUpdate),Ht(this.render),this.valueSubscriptions.forEach(t=>t()),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent&&this.parent.children.delete(this);for(const t in this.events)this.events[t].clear();for(const t in this.features)this.features[t].unmount();this.current=null}bindToMotionValue(t,n){const r=Qn.has(t),s=n.on("change",o=>{this.latestValues[t]=o,this.props.onUpdate&&oe.update(this.notifyUpdate,!1,!0),r&&this.projection&&(this.projection.isTransformDirty=!0)}),i=n.on("renderRequest",this.scheduleRender);this.valueSubscriptions.set(t,()=>{s(),i()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}loadFeatures({children:t,...n},r,s,i){let o,a;for(let l=0;lthis.scheduleRender(),animationType:typeof c=="string"?c:"both",initialPromotionConfig:i,layoutScroll:u,layoutRoot:h})}return a}updateFeatures(){for(const t in this.features){const n=this.features[t];n.isMounted?n.update():(n.mount(),n.isMounted=!0)}}triggerBuild(){this.build(this.renderState,this.latestValues,this.options,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):xe()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}makeTargetAnimatable(t,n=!0){return this.makeTargetAnimatableFromInstance(t,this.props,n)}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let r=0;rn.variantChildren.delete(t)}addValue(t,n){n!==this.values.get(t)&&(this.removeValue(t),this.bindToMotionValue(t,n)),this.values.set(t,n),this.latestValues[t]=n.get()}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let r=this.values.get(t);return r===void 0&&n!==void 0&&(r=Lr(n,{owner:this}),this.addValue(t,r)),r}readValue(t){var n;return this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:(n=this.getBaseTargetFromProps(this.props,t))!==null&&n!==void 0?n:this.readValueFromInstance(this.current,t,this.options)}setBaseTarget(t,n){this.baseTarget[t]=n}getBaseTarget(t){var n;const{initial:r}=this.props,s=typeof r=="string"||typeof r=="object"?(n=wc(this.props,r))===null||n===void 0?void 0:n[t]:void 0;if(r&&s!==void 0)return s;const i=this.getBaseTargetFromProps(this.props,t);return i!==void 0&&!Ge(i)?i:this.initialValues[t]!==void 0&&s===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new Mc),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}}class Ag extends P4{sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){return t.style?t.style[n]:void 0}removeValueFromRenderState(t,{vars:n,style:r}){delete n[t],delete r[t]}makeTargetAnimatableFromInstance({transition:t,transitionEnd:n,...r},{transformValues:s},i){let o=B5(r,t||{},this);if(s&&(n&&(n=s(n)),r&&(r=s(r)),o&&(o=s(o))),i){O5(this,r,o);const a=w4(this,r,o,n);n=a.transitionEnd,r=a.target}return{transition:t,transitionEnd:n,...r}}}function j4(e){return window.getComputedStyle(e)}class E4 extends Ag{constructor(){super(...arguments),this.type="html"}readValueFromInstance(t,n){if(Qn.has(n)){const r=Pc(n);return r&&r.default||0}else{const r=j4(t),s=(w0(n)?r.getPropertyValue(n):r[n])||0;return typeof s=="string"?s.trim():s}}measureInstanceViewportBox(t,{transformPagePoint:n}){return xg(t,n)}build(t,n,r,s){mc(t,n,r,s.transformTemplate)}scrapeMotionValuesFromProps(t,n){return xc(t,n)}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;Ge(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}renderInstance(t,n,r,s){j0(t,n,r,s)}}class T4 extends Ag{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(Qn.has(n)){const r=Pc(n);return r&&r.default||0}return n=E0.has(n)?n:dc(n),t.getAttribute(n)}measureInstanceViewportBox(){return xe()}scrapeMotionValuesFromProps(t,n){return N0(t,n)}build(t,n,r,s){yc(t,n,r,this.isSVGTag,s.transformTemplate)}renderInstance(t,n,r,s){T0(t,n,r,s)}mount(t){this.isSVGTag=vc(t.tagName),super.mount(t)}}const N4=(e,t)=>pc(e)?new T4(t,{enableHardwareAcceleration:!1}):new E4(t,{enableHardwareAcceleration:!0}),M4={layout:{ProjectionNode:Tg,MeasureLayout:bg}},_4={...r3,...kw,...l4,...M4},O=_2((e,t)=>cw(e,t,_4,N4)),A4={},sh=e=>{let t;const n=new Set,r=(d,f)=>{const u=typeof d=="function"?d(t):d;if(!Object.is(u,t)){const h=t;t=f??(typeof u!="object"||u===null)?u:Object.assign({},t,u),n.forEach(p=>p(t,h))}},s=()=>t,l={setState:r,getState:s,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(A4?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},c=t=e(r,s,l);return l},L4=e=>e?sh(e):sh;var Lg={exports:{}},Dg={},Rg={exports:{}},Vg={};/** + * @license React + * use-sync-external-store-shim.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Rr=k;function D4(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var R4=typeof Object.is=="function"?Object.is:D4,V4=Rr.useState,F4=Rr.useEffect,I4=Rr.useLayoutEffect,z4=Rr.useDebugValue;function O4(e,t){var n=t(),r=V4({inst:{value:n,getSnapshot:t}}),s=r[0].inst,i=r[1];return I4(function(){s.value=n,s.getSnapshot=t,Ba(s)&&i({inst:s})},[e,n,t]),F4(function(){return Ba(s)&&i({inst:s}),e(function(){Ba(s)&&i({inst:s})})},[e]),z4(n),n}function Ba(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!R4(e,n)}catch{return!0}}function $4(e,t){return t()}var B4=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?$4:O4;Vg.useSyncExternalStore=Rr.useSyncExternalStore!==void 0?Rr.useSyncExternalStore:B4;Rg.exports=Vg;var U4=Rg.exports;/** + * @license React + * use-sync-external-store-shim/with-selector.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var ea=k,W4=U4;function H4(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var q4=typeof Object.is=="function"?Object.is:H4,G4=W4.useSyncExternalStore,Y4=ea.useRef,K4=ea.useEffect,X4=ea.useMemo,Q4=ea.useDebugValue;Dg.useSyncExternalStoreWithSelector=function(e,t,n,r,s){var i=Y4(null);if(i.current===null){var o={hasValue:!1,value:null};i.current=o}else o=i.current;i=X4(function(){function l(h){if(!c){if(c=!0,d=h,h=r(h),s!==void 0&&o.hasValue){var p=o.value;if(s(p,h))return f=p}return f=h}if(p=f,q4(d,h))return p;var g=r(h);return s!==void 0&&s(p,g)?(d=h,p):(d=h,f=g)}var c=!1,d,f,u=n===void 0?null:n;return[function(){return l(t())},u===null?void 0:function(){return l(u())}]},[t,n,r,s]);var a=G4(e,i[0],i[1]);return K4(function(){o.hasValue=!0,o.value=a},[a]),Q4(a),a};Lg.exports=Dg;var Z4=Lg.exports;const J4=cu(Z4),Fg={},{useDebugValue:eb}=Gs,{useSyncExternalStoreWithSelector:tb}=J4;let ih=!1;const nb=e=>e;function rb(e,t=nb,n){(Fg?"production":void 0)!=="production"&&n&&!ih&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),ih=!0);const r=tb(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return eb(r),r}const sb=e=>{(Fg?"production":void 0)!=="production"&&typeof e!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const t=typeof e=="function"?L4(e):e,n=(r,s)=>rb(t,r,s);return Object.assign(n,t),n},ib=e=>sb,ob={};function ab(e,t){let n;try{n=e()}catch{return}return{getItem:s=>{var i;const o=l=>l===null?null:JSON.parse(l,void 0),a=(i=n.getItem(s))!=null?i:null;return a instanceof Promise?a.then(o):o(a)},setItem:(s,i)=>n.setItem(s,JSON.stringify(i,void 0)),removeItem:s=>n.removeItem(s)}}const Hs=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return Hs(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return Hs(r)(n)}}}},lb=(e,t)=>(n,r,s)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:x=>x,version:0,merge:(x,v)=>({...v,...x}),...t},o=!1;const a=new Set,l=new Set;let c;try{c=i.getStorage()}catch{}if(!c)return e((...x)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...x)},r,s);const d=Hs(i.serialize),f=()=>{const x=i.partialize({...r()});let v;const y=d({state:x,version:i.version}).then(w=>c.setItem(i.name,w)).catch(w=>{v=w});if(v)throw v;return y},u=s.setState;s.setState=(x,v)=>{u(x,v),f()};const h=e((...x)=>{n(...x),f()},r,s);let p;const g=()=>{var x;if(!c)return;o=!1,a.forEach(y=>y(r()));const v=((x=i.onRehydrateStorage)==null?void 0:x.call(i,r()))||void 0;return Hs(c.getItem.bind(c))(i.name).then(y=>{if(y)return i.deserialize(y)}).then(y=>{if(y)if(typeof y.version=="number"&&y.version!==i.version){if(i.migrate)return i.migrate(y.state,y.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return y.state}).then(y=>{var w;return p=i.merge(y,(w=r())!=null?w:h),n(p,!0),f()}).then(()=>{v==null||v(p,void 0),o=!0,l.forEach(y=>y(p))}).catch(y=>{v==null||v(void 0,y)})};return s.persist={setOptions:x=>{i={...i,...x},x.getStorage&&(c=x.getStorage())},clearStorage:()=>{c==null||c.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>g(),hasHydrated:()=>o,onHydrate:x=>(a.add(x),()=>{a.delete(x)}),onFinishHydration:x=>(l.add(x),()=>{l.delete(x)})},g(),p||h},ub=(e,t)=>(n,r,s)=>{let i={storage:ab(()=>localStorage),partialize:g=>g,version:0,merge:(g,x)=>({...x,...g}),...t},o=!1;const a=new Set,l=new Set;let c=i.storage;if(!c)return e((...g)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...g)},r,s);const d=()=>{const g=i.partialize({...r()});return c.setItem(i.name,{state:g,version:i.version})},f=s.setState;s.setState=(g,x)=>{f(g,x),d()};const u=e((...g)=>{n(...g),d()},r,s);s.getInitialState=()=>u;let h;const p=()=>{var g,x;if(!c)return;o=!1,a.forEach(y=>{var w;return y((w=r())!=null?w:u)});const v=((x=i.onRehydrateStorage)==null?void 0:x.call(i,(g=r())!=null?g:u))||void 0;return Hs(c.getItem.bind(c))(i.name).then(y=>{if(y)if(typeof y.version=="number"&&y.version!==i.version){if(i.migrate)return[!0,i.migrate(y.state,y.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,y.state];return[!1,void 0]}).then(y=>{var w;const[b,S]=y;if(h=i.merge(S,(w=r())!=null?w:u),n(h,!0),b)return d()}).then(()=>{v==null||v(h,void 0),h=r(),o=!0,l.forEach(y=>y(h))}).catch(y=>{v==null||v(void 0,y)})};return s.persist={setOptions:g=>{i={...i,...g},g.storage&&(c=g.storage)},clearStorage:()=>{c==null||c.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>p(),hasHydrated:()=>o,onHydrate:g=>(a.add(g),()=>{a.delete(g)}),onFinishHydration:g=>(l.add(g),()=>{l.delete(g)})},i.skipHydration||p(),h||u},cb=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((ob?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),lb(e,t)):ub(e,t),db=cb,oh={currentUser:null,partnerUser:null,isLoading:!1,error:null,currentTrack:null,isPlaying:!1},ae=ib()(db(e=>({...oh,mixedPlaylists:[],memoryLane:[],theme:"green",setCurrentUser:t=>e({currentUser:t}),setPartnerUser:t=>e({partnerUser:t}),logout:()=>e({currentUser:null,partnerUser:null,currentTrack:null,isPlaying:!1,mixedPlaylists:[],memoryLane:[],error:null}),setLoading:t=>e({isLoading:t}),setError:t=>e({error:t}),setCurrentTrack:t=>e({currentTrack:t}),setIsPlaying:t=>e({isPlaying:t}),addMixedPlaylist:t=>e(n=>({mixedPlaylists:[...n.mixedPlaylists,t]})),removeMixedPlaylist:t=>e(n=>({mixedPlaylists:n.mixedPlaylists.filter(r=>r.id!==t)})),setMixedPlaylists:t=>e({mixedPlaylists:t}),addMemoryLaneItem:t=>e(n=>({memoryLane:[...n.memoryLane,t].sort((r,s)=>new Date(s.date).getTime()-new Date(r.date).getTime())})),removeMemoryLaneItem:t=>e(n=>({memoryLane:n.memoryLane.filter(r=>r.id!==t)})),setTheme:t=>e({theme:t}),clearAllData:()=>e({...oh,mixedPlaylists:[],memoryLane:[]})}),{name:"spotify-app-settings",partialize:e=>({theme:e.theme})}));function fb(){{const e="/api";try{const t=typeof window<"u"&&window.location.protocol==="https:",n=new URL(e,window.location.origin);if(t&&n.protocol==="http:"&&n.hostname==="159.195.9.107"&&(n.port==="8081"||n.port===""))return"https://159.195.9.107:8082"}catch{}return e}}const Br=fb();function qt(){try{const e=localStorage.getItem("spotify-user");if(!e)return null;const t=JSON.parse(e);return(t==null?void 0:t.jwt)||(t==null?void 0:t.token)||null}catch{return null}}async function Pt(e,t,n){const r=await fetch(`${Br}${e}`,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:qt()?{Authorization:`Bearer ${qt()}`}:{}},body:t?JSON.stringify(t):void 0});if(!r.ok){const s=await r.text();throw new Error(s||`Request failed: ${r.status}`)}return r.json()}async function se(e,t){const n=await fetch(`${Br}${e}`,{headers:{...t?{Authorization:`Bearer ${t}`}:qt()?{Authorization:`Bearer ${qt()}`}:{}}});if(!n.ok){const r=await n.text();throw new Error(r||`Request failed: ${n.status}`)}return n.json()}function hb(e){const t=qt(),n=new URL(`${Br}${e}`,window.location.origin);return t&&n.searchParams.set("token",t),new EventSource(n.toString())}async function pb(e,t,n){const r=await fetch(`${Br}${e}`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",...qt()?{Authorization:`Bearer ${qt()}`}:{}},body:new URLSearchParams(t).toString()});if(!r.ok){const s=await r.text();throw new Error(s||`Request failed: ${r.status}`)}return r.json()}async function mb(e,t){const n=await fetch(`${Br}${e}`,{method:"DELETE",headers:{...t?{Authorization:`Bearer ${t}`}:qt()?{Authorization:`Bearer ${qt()}`}:{}}});if(!n.ok){const r=await n.text();throw new Error(r||`Request failed: ${n.status}`)}return n.json()}const Vr=e=>{const t={green:{primary:"bg-theme-green-primary text-white",secondary:"bg-theme-green-secondary text-white",accent:"bg-theme-green-accent text-white",border:"border-theme-green-primary",text:"text-theme-green-primary",gradient:"from-theme-green-primary to-theme-green-secondary",glass:"bg-theme-green-primary/10 border-theme-green-primary/30",hover:"hover:bg-theme-green-primary/20",cssVars:{primary:"#1db954",secondary:"#1ed760",accent:"#00e676"}},pink:{primary:"bg-theme-pink-primary text-white",secondary:"bg-theme-pink-secondary text-white",accent:"bg-theme-pink-accent text-white",border:"border-theme-pink-primary",text:"text-theme-pink-primary",gradient:"from-theme-pink-primary to-theme-pink-secondary",glass:"bg-theme-pink-primary/10 border-theme-pink-primary/30",hover:"hover:bg-theme-pink-primary/20",cssVars:{primary:"#ec4899",secondary:"#f472b6",accent:"#fb7185"}},blue:{primary:"bg-theme-blue-primary text-white",secondary:"bg-theme-blue-secondary text-white",accent:"bg-theme-blue-accent text-white",border:"border-theme-blue-primary",text:"text-theme-blue-primary",gradient:"from-theme-blue-primary to-theme-blue-secondary",glass:"bg-theme-blue-primary/10 border-theme-blue-primary/30",hover:"hover:bg-theme-blue-primary/20",cssVars:{primary:"#3b82f6",secondary:"#60a5fa",accent:"#93c5fd"}},red:{primary:"bg-theme-red-primary text-white",secondary:"bg-theme-red-secondary text-white",accent:"bg-theme-red-accent text-white",border:"border-theme-red-primary",text:"text-theme-red-primary",gradient:"from-theme-red-primary to-theme-red-secondary",glass:"bg-theme-red-primary/10 border-theme-red-primary/30",hover:"hover:bg-theme-red-primary/20",cssVars:{primary:"#dc2626",secondary:"#ef4444",accent:"#f87171"}},purple:{primary:"bg-theme-purple-primary text-white",secondary:"bg-theme-purple-secondary text-white",accent:"bg-theme-purple-accent text-white",border:"border-theme-purple-primary",text:"text-theme-purple-primary",gradient:"from-theme-purple-primary to-theme-purple-secondary",glass:"bg-theme-purple-primary/10 border-theme-purple-primary/30",hover:"hover:bg-theme-purple-primary/20",cssVars:{primary:"#8b5cf6",secondary:"#a78bfa",accent:"#c4b5fd"}},yellow:{primary:"bg-theme-yellow-primary text-black",secondary:"bg-theme-yellow-secondary text-black",accent:"bg-theme-yellow-accent text-black",border:"border-theme-yellow-primary",text:"text-theme-yellow-primary",gradient:"from-theme-yellow-primary to-theme-yellow-secondary",glass:"bg-theme-yellow-primary/10 border-theme-yellow-primary/30",hover:"hover:bg-theme-yellow-primary/20",cssVars:{primary:"#eab308",secondary:"#f59e0b",accent:"#fbbf24"}},turquoise:{primary:"bg-theme-turquoise-primary text-white",secondary:"bg-theme-turquoise-secondary text-white",accent:"bg-theme-turquoise-accent text-white",border:"border-theme-turquoise-primary",text:"text-theme-turquoise-primary",gradient:"from-theme-turquoise-primary to-theme-turquoise-secondary",glass:"bg-theme-turquoise-primary/10 border-theme-turquoise-primary/30",hover:"hover:bg-theme-turquoise-primary/20",cssVars:{primary:"#06b6d4",secondary:"#22d3ee",accent:"#67e8f9"}}},n=t[e]||t.green;if(typeof document<"u"){const r=document.documentElement;r.style.setProperty("--theme-primary",n.cssVars.primary),r.style.setProperty("--theme-secondary",n.cssVars.secondary),r.style.setProperty("--theme-accent",n.cssVars.accent)}return n},ah=e=>({green:120,pink:300,blue:360,red:245,purple:280,yellow:200,turquoise:40})[e]||120;function bs(e){let t=e[0],n=e[1],r=e[2];return Math.sqrt(t*t+n*n+r*r)}function au(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e}function gb(e,t,n,r){return e[0]=t,e[1]=n,e[2]=r,e}function lh(e,t,n){return e[0]=t[0]+n[0],e[1]=t[1]+n[1],e[2]=t[2]+n[2],e}function uh(e,t,n){return e[0]=t[0]-n[0],e[1]=t[1]-n[1],e[2]=t[2]-n[2],e}function yb(e,t,n){return e[0]=t[0]*n[0],e[1]=t[1]*n[1],e[2]=t[2]*n[2],e}function vb(e,t,n){return e[0]=t[0]/n[0],e[1]=t[1]/n[1],e[2]=t[2]/n[2],e}function Ua(e,t,n){return e[0]=t[0]*n,e[1]=t[1]*n,e[2]=t[2]*n,e}function xb(e,t){let n=t[0]-e[0],r=t[1]-e[1],s=t[2]-e[2];return Math.sqrt(n*n+r*r+s*s)}function wb(e,t){let n=t[0]-e[0],r=t[1]-e[1],s=t[2]-e[2];return n*n+r*r+s*s}function ch(e){let t=e[0],n=e[1],r=e[2];return t*t+n*n+r*r}function bb(e,t){return e[0]=-t[0],e[1]=-t[1],e[2]=-t[2],e}function Sb(e,t){return e[0]=1/t[0],e[1]=1/t[1],e[2]=1/t[2],e}function lu(e,t){let n=t[0],r=t[1],s=t[2],i=n*n+r*r+s*s;return i>0&&(i=1/Math.sqrt(i)),e[0]=t[0]*i,e[1]=t[1]*i,e[2]=t[2]*i,e}function Ig(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function dh(e,t,n){let r=t[0],s=t[1],i=t[2],o=n[0],a=n[1],l=n[2];return e[0]=s*l-i*a,e[1]=i*o-r*l,e[2]=r*a-s*o,e}function kb(e,t,n,r){let s=t[0],i=t[1],o=t[2];return e[0]=s+r*(n[0]-s),e[1]=i+r*(n[1]-i),e[2]=o+r*(n[2]-o),e}function Cb(e,t,n,r,s){const i=Math.exp(-r*s);let o=t[0],a=t[1],l=t[2];return e[0]=n[0]+(o-n[0])*i,e[1]=n[1]+(a-n[1])*i,e[2]=n[2]+(l-n[2])*i,e}function Pb(e,t,n){let r=t[0],s=t[1],i=t[2],o=n[3]*r+n[7]*s+n[11]*i+n[15];return o=o||1,e[0]=(n[0]*r+n[4]*s+n[8]*i+n[12])/o,e[1]=(n[1]*r+n[5]*s+n[9]*i+n[13])/o,e[2]=(n[2]*r+n[6]*s+n[10]*i+n[14])/o,e}function jb(e,t,n){let r=t[0],s=t[1],i=t[2],o=n[3]*r+n[7]*s+n[11]*i+n[15];return o=o||1,e[0]=(n[0]*r+n[4]*s+n[8]*i)/o,e[1]=(n[1]*r+n[5]*s+n[9]*i)/o,e[2]=(n[2]*r+n[6]*s+n[10]*i)/o,e}function Eb(e,t,n){let r=t[0],s=t[1],i=t[2];return e[0]=r*n[0]+s*n[3]+i*n[6],e[1]=r*n[1]+s*n[4]+i*n[7],e[2]=r*n[2]+s*n[5]+i*n[8],e}function Tb(e,t,n){let r=t[0],s=t[1],i=t[2],o=n[0],a=n[1],l=n[2],c=n[3],d=a*i-l*s,f=l*r-o*i,u=o*s-a*r,h=a*u-l*f,p=l*d-o*u,g=o*f-a*d,x=c*2;return d*=x,f*=x,u*=x,h*=2,p*=2,g*=2,e[0]=r+d+h,e[1]=s+f+p,e[2]=i+u+g,e}const Nb=function(){const e=[0,0,0],t=[0,0,0];return function(n,r){au(e,n),au(t,r),lu(e,e),lu(t,t);let s=Ig(e,t);return s>1?0:s<-1?Math.PI:Math.acos(s)}}();function Mb(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}class mt extends Array{constructor(t=0,n=t,r=t){return super(t,n,r),this}get x(){return this[0]}get y(){return this[1]}get z(){return this[2]}set x(t){this[0]=t}set y(t){this[1]=t}set z(t){this[2]=t}set(t,n=t,r=t){return t.length?this.copy(t):(gb(this,t,n,r),this)}copy(t){return au(this,t),this}add(t,n){return n?lh(this,t,n):lh(this,this,t),this}sub(t,n){return n?uh(this,t,n):uh(this,this,t),this}multiply(t){return t.length?yb(this,this,t):Ua(this,this,t),this}divide(t){return t.length?vb(this,this,t):Ua(this,this,1/t),this}inverse(t=this){return Sb(this,t),this}len(){return bs(this)}distance(t){return t?xb(this,t):bs(this)}squaredLen(){return ch(this)}squaredDistance(t){return t?wb(this,t):ch(this)}negate(t=this){return bb(this,t),this}cross(t,n){return n?dh(this,t,n):dh(this,this,t),this}scale(t){return Ua(this,this,t),this}normalize(){return lu(this,this),this}dot(t){return Ig(this,t)}equals(t){return Mb(this,t)}applyMatrix3(t){return Eb(this,this,t),this}applyMatrix4(t){return Pb(this,this,t),this}scaleRotateMatrix4(t){return jb(this,this,t),this}applyQuaternion(t){return Tb(this,this,t),this}angle(t){return Nb(this,t)}lerp(t,n){return kb(this,this,t,n),this}smoothLerp(t,n,r){return Cb(this,this,t,n,r),this}clone(){return new mt(this[0],this[1],this[2])}fromArray(t,n=0){return this[0]=t[n],this[1]=t[n+1],this[2]=t[n+2],this}toArray(t=[],n=0){return t[n]=this[0],t[n+1]=this[1],t[n+2]=this[2],t}transformDirection(t){const n=this[0],r=this[1],s=this[2];return this[0]=t[0]*n+t[4]*r+t[8]*s,this[1]=t[1]*n+t[5]*r+t[9]*s,this[2]=t[2]*n+t[6]*r+t[10]*s,this.normalize()}}const fh=new mt;let _b=1,Ab=1,hh=!1;class Lb{constructor(t,n={}){t.canvas||console.error("gl not passed as first argument to Geometry"),this.gl=t,this.attributes=n,this.id=_b++,this.VAOs={},this.drawRange={start:0,count:0},this.instancedCount=0,this.gl.renderer.bindVertexArray(null),this.gl.renderer.currentGeometry=null,this.glState=this.gl.renderer.state;for(let r in n)this.addAttribute(r,n[r])}addAttribute(t,n){if(this.attributes[t]=n,n.id=Ab++,n.size=n.size||1,n.type=n.type||(n.data.constructor===Float32Array?this.gl.FLOAT:n.data.constructor===Uint16Array?this.gl.UNSIGNED_SHORT:this.gl.UNSIGNED_INT),n.target=t==="index"?this.gl.ELEMENT_ARRAY_BUFFER:this.gl.ARRAY_BUFFER,n.normalized=n.normalized||!1,n.stride=n.stride||0,n.offset=n.offset||0,n.count=n.count||(n.stride?n.data.byteLength/n.stride:n.data.length/n.size),n.divisor=n.instanced||0,n.needsUpdate=!1,n.usage=n.usage||this.gl.STATIC_DRAW,n.buffer||this.updateAttribute(n),n.divisor){if(this.isInstanced=!0,this.instancedCount&&this.instancedCount!==n.count*n.divisor)return console.warn("geometry has multiple instanced buffers of different length"),this.instancedCount=Math.min(this.instancedCount,n.count*n.divisor);this.instancedCount=n.count*n.divisor}else t==="index"?this.drawRange.count=n.count:this.attributes.index||(this.drawRange.count=Math.max(this.drawRange.count,n.count))}updateAttribute(t){const n=!t.buffer;n&&(t.buffer=this.gl.createBuffer()),this.glState.boundBuffer!==t.buffer&&(this.gl.bindBuffer(t.target,t.buffer),this.glState.boundBuffer=t.buffer),n?this.gl.bufferData(t.target,t.data,t.usage):this.gl.bufferSubData(t.target,0,t.data),t.needsUpdate=!1}setIndex(t){this.addAttribute("index",t)}setDrawRange(t,n){this.drawRange.start=t,this.drawRange.count=n}setInstancedCount(t){this.instancedCount=t}createVAO(t){this.VAOs[t.attributeOrder]=this.gl.renderer.createVertexArray(),this.gl.renderer.bindVertexArray(this.VAOs[t.attributeOrder]),this.bindAttributes(t)}bindAttributes(t){t.attributeLocations.forEach((n,{name:r,type:s})=>{if(!this.attributes[r]){console.warn(`active attribute ${r} not being supplied`);return}const i=this.attributes[r];this.gl.bindBuffer(i.target,i.buffer),this.glState.boundBuffer=i.buffer;let o=1;s===35674&&(o=2),s===35675&&(o=3),s===35676&&(o=4);const a=i.size/o,l=o===1?0:o*o*4,c=o===1?0:o*4;for(let d=0;d{const a=this.attributes[o];a.needsUpdate&&this.updateAttribute(a)});let r=2;((s=this.attributes.index)==null?void 0:s.type)===this.gl.UNSIGNED_INT&&(r=4),this.isInstanced?this.attributes.index?this.gl.renderer.drawElementsInstanced(n,this.drawRange.count,this.attributes.index.type,this.attributes.index.offset+this.drawRange.start*r,this.instancedCount):this.gl.renderer.drawArraysInstanced(n,this.drawRange.start,this.drawRange.count,this.instancedCount):this.attributes.index?this.gl.drawElements(n,this.drawRange.count,this.attributes.index.type,this.attributes.index.offset+this.drawRange.start*r):this.gl.drawArrays(n,this.drawRange.start,this.drawRange.count)}getPosition(){const t=this.attributes.position;if(t.data)return t;if(!hh)return console.warn("No position buffer data found to compute bounds"),hh=!0}computeBoundingBox(t){t||(t=this.getPosition());const n=t.data,r=t.size;this.bounds||(this.bounds={min:new mt,max:new mt,center:new mt,scale:new mt,radius:1/0});const s=this.bounds.min,i=this.bounds.max,o=this.bounds.center,a=this.bounds.scale;s.set(1/0),i.set(-1/0);for(let l=0,c=n.length;l{let o=this.uniforms[i.uniformName];for(const a of i.nameComponents){if(!o)break;if(a in o)o=o[a];else{if(Array.isArray(o.value))break;o=void 0;break}}if(!o)return gh(`Active uniform ${i.name} has not been supplied`);if(o&&o.value===void 0)return gh(`${i.name} uniform is missing a value parameter`);if(o.value.texture)return n=n+1,o.value.update(n),Wa(this.gl,i.type,s,n);if(o.value.length&&o.value[0].texture){const a=[];return o.value.forEach(l=>{n=n+1,l.update(n),a.push(n)}),Wa(this.gl,i.type,s,a)}Wa(this.gl,i.type,s,o.value)}),this.applyState(),t&&this.gl.renderer.setFrontFace(this.frontFace===this.gl.CCW?this.gl.CW:this.gl.CCW)}remove(){this.gl.deleteProgram(this.program)}}function Wa(e,t,n,r){r=r.length?Vb(r):r;const s=e.renderer.state.uniformLocations.get(n);if(r.length)if(s===void 0||s.length!==r.length)e.renderer.state.uniformLocations.set(n,r.slice(0));else{if(Fb(s,r))return;s.set?s.set(r):Ib(s,r),e.renderer.state.uniformLocations.set(n,s)}else{if(s===r)return;e.renderer.state.uniformLocations.set(n,r)}switch(t){case 5126:return r.length?e.uniform1fv(n,r):e.uniform1f(n,r);case 35664:return e.uniform2fv(n,r);case 35665:return e.uniform3fv(n,r);case 35666:return e.uniform4fv(n,r);case 35670:case 5124:case 35678:case 36306:case 35680:case 36289:return r.length?e.uniform1iv(n,r):e.uniform1i(n,r);case 35671:case 35667:return e.uniform2iv(n,r);case 35672:case 35668:return e.uniform3iv(n,r);case 35673:case 35669:return e.uniform4iv(n,r);case 35674:return e.uniformMatrix2fv(n,!1,r);case 35675:return e.uniformMatrix3fv(n,!1,r);case 35676:return e.uniformMatrix4fv(n,!1,r)}}function mh(e){let t=e.split(` +`);for(let n=0;n100||(console.warn(e),Ha++,Ha>100&&console.warn("More than 100 program warnings - stopping logs."))}const qa=new mt;let zb=1;class Ob{constructor({canvas:t=document.createElement("canvas"),width:n=300,height:r=150,dpr:s=1,alpha:i=!1,depth:o=!0,stencil:a=!1,antialias:l=!1,premultipliedAlpha:c=!1,preserveDrawingBuffer:d=!1,powerPreference:f="default",autoClear:u=!0,webgl:h=2}={}){const p={alpha:i,depth:o,stencil:a,antialias:l,premultipliedAlpha:c,preserveDrawingBuffer:d,powerPreference:f};this.dpr=s,this.alpha=i,this.color=!0,this.depth=o,this.stencil=a,this.premultipliedAlpha=c,this.autoClear=u,this.id=zb++,h===2&&(this.gl=t.getContext("webgl2",p)),this.isWebgl2=!!this.gl,this.gl||(this.gl=t.getContext("webgl",p)),this.gl||console.error("unable to create webgl context"),this.gl.renderer=this,this.setSize(n,r),this.state={},this.state.blendFunc={src:this.gl.ONE,dst:this.gl.ZERO},this.state.blendEquation={modeRGB:this.gl.FUNC_ADD},this.state.cullFace=!1,this.state.frontFace=this.gl.CCW,this.state.depthMask=!0,this.state.depthFunc=this.gl.LEQUAL,this.state.premultiplyAlpha=!1,this.state.flipY=!1,this.state.unpackAlignment=4,this.state.framebuffer=null,this.state.viewport={x:0,y:0,width:null,height:null},this.state.textureUnits=[],this.state.activeTextureUnit=0,this.state.boundBuffer=null,this.state.uniformLocations=new Map,this.state.currentProgram=null,this.extensions={},this.isWebgl2?(this.getExtension("EXT_color_buffer_float"),this.getExtension("OES_texture_float_linear")):(this.getExtension("OES_texture_float"),this.getExtension("OES_texture_float_linear"),this.getExtension("OES_texture_half_float"),this.getExtension("OES_texture_half_float_linear"),this.getExtension("OES_element_index_uint"),this.getExtension("OES_standard_derivatives"),this.getExtension("EXT_sRGB"),this.getExtension("WEBGL_depth_texture"),this.getExtension("WEBGL_draw_buffers")),this.getExtension("WEBGL_compressed_texture_astc"),this.getExtension("EXT_texture_compression_bptc"),this.getExtension("WEBGL_compressed_texture_s3tc"),this.getExtension("WEBGL_compressed_texture_etc1"),this.getExtension("WEBGL_compressed_texture_pvrtc"),this.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),this.vertexAttribDivisor=this.getExtension("ANGLE_instanced_arrays","vertexAttribDivisor","vertexAttribDivisorANGLE"),this.drawArraysInstanced=this.getExtension("ANGLE_instanced_arrays","drawArraysInstanced","drawArraysInstancedANGLE"),this.drawElementsInstanced=this.getExtension("ANGLE_instanced_arrays","drawElementsInstanced","drawElementsInstancedANGLE"),this.createVertexArray=this.getExtension("OES_vertex_array_object","createVertexArray","createVertexArrayOES"),this.bindVertexArray=this.getExtension("OES_vertex_array_object","bindVertexArray","bindVertexArrayOES"),this.deleteVertexArray=this.getExtension("OES_vertex_array_object","deleteVertexArray","deleteVertexArrayOES"),this.drawBuffers=this.getExtension("WEBGL_draw_buffers","drawBuffers","drawBuffersWEBGL"),this.parameters={},this.parameters.maxTextureUnits=this.gl.getParameter(this.gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),this.parameters.maxAnisotropy=this.getExtension("EXT_texture_filter_anisotropic")?this.gl.getParameter(this.getExtension("EXT_texture_filter_anisotropic").MAX_TEXTURE_MAX_ANISOTROPY_EXT):0}setSize(t,n){this.width=t,this.height=n,this.gl.canvas.width=t*this.dpr,this.gl.canvas.height=n*this.dpr,this.gl.canvas.style&&Object.assign(this.gl.canvas.style,{width:t+"px",height:n+"px"})}setViewport(t,n,r=0,s=0){this.state.viewport.width===t&&this.state.viewport.height===n||(this.state.viewport.width=t,this.state.viewport.height=n,this.state.viewport.x=r,this.state.viewport.y=s,this.gl.viewport(r,s,t,n))}setScissor(t,n,r=0,s=0){this.gl.scissor(r,s,t,n)}enable(t){this.state[t]!==!0&&(this.gl.enable(t),this.state[t]=!0)}disable(t){this.state[t]!==!1&&(this.gl.disable(t),this.state[t]=!1)}setBlendFunc(t,n,r,s){this.state.blendFunc.src===t&&this.state.blendFunc.dst===n&&this.state.blendFunc.srcAlpha===r&&this.state.blendFunc.dstAlpha===s||(this.state.blendFunc.src=t,this.state.blendFunc.dst=n,this.state.blendFunc.srcAlpha=r,this.state.blendFunc.dstAlpha=s,r!==void 0?this.gl.blendFuncSeparate(t,n,r,s):this.gl.blendFunc(t,n))}setBlendEquation(t,n){t=t||this.gl.FUNC_ADD,!(this.state.blendEquation.modeRGB===t&&this.state.blendEquation.modeAlpha===n)&&(this.state.blendEquation.modeRGB=t,this.state.blendEquation.modeAlpha=n,n!==void 0?this.gl.blendEquationSeparate(t,n):this.gl.blendEquation(t))}setCullFace(t){this.state.cullFace!==t&&(this.state.cullFace=t,this.gl.cullFace(t))}setFrontFace(t){this.state.frontFace!==t&&(this.state.frontFace=t,this.gl.frontFace(t))}setDepthMask(t){this.state.depthMask!==t&&(this.state.depthMask=t,this.gl.depthMask(t))}setDepthFunc(t){this.state.depthFunc!==t&&(this.state.depthFunc=t,this.gl.depthFunc(t))}setStencilMask(t){this.state.stencilMask!==t&&(this.state.stencilMask=t,this.gl.stencilMask(t))}setStencilFunc(t,n,r){this.state.stencilFunc===t&&this.state.stencilRef===n&&this.state.stencilFuncMask===r||(this.state.stencilFunc=t||this.gl.ALWAYS,this.state.stencilRef=n||0,this.state.stencilFuncMask=r||0,this.gl.stencilFunc(t||this.gl.ALWAYS,n||0,r||0))}setStencilOp(t,n,r){this.state.stencilFail===t&&this.state.stencilDepthFail===n&&this.state.stencilDepthPass===r||(this.state.stencilFail=t,this.state.stencilDepthFail=n,this.state.stencilDepthPass=r,this.gl.stencilOp(t,n,r))}activeTexture(t){this.state.activeTextureUnit!==t&&(this.state.activeTextureUnit=t,this.gl.activeTexture(this.gl.TEXTURE0+t))}bindFramebuffer({target:t=this.gl.FRAMEBUFFER,buffer:n=null}={}){this.state.framebuffer!==n&&(this.state.framebuffer=n,this.gl.bindFramebuffer(t,n))}getExtension(t,n,r){return n&&this.gl[n]?this.gl[n].bind(this.gl):(this.extensions[t]||(this.extensions[t]=this.gl.getExtension(t)),n?this.extensions[t]?this.extensions[t][r].bind(this.extensions[t]):null:this.extensions[t])}sortOpaque(t,n){return t.renderOrder!==n.renderOrder?t.renderOrder-n.renderOrder:t.program.id!==n.program.id?t.program.id-n.program.id:t.zDepth!==n.zDepth?t.zDepth-n.zDepth:n.id-t.id}sortTransparent(t,n){return t.renderOrder!==n.renderOrder?t.renderOrder-n.renderOrder:t.zDepth!==n.zDepth?n.zDepth-t.zDepth:n.id-t.id}sortUI(t,n){return t.renderOrder!==n.renderOrder?t.renderOrder-n.renderOrder:t.program.id!==n.program.id?t.program.id-n.program.id:n.id-t.id}getRenderList({scene:t,camera:n,frustumCull:r,sort:s}){let i=[];if(n&&r&&n.updateFrustum(),t.traverse(o=>{if(!o.visible)return!0;o.draw&&(r&&o.frustumCulled&&n&&!n.frustumIntersectsMesh(o)||i.push(o))}),s){const o=[],a=[],l=[];i.forEach(c=>{c.program.transparent?c.program.depthTest?a.push(c):l.push(c):o.push(c),c.zDepth=0,!(c.renderOrder!==0||!c.program.depthTest||!n)&&(c.worldMatrix.getTranslation(qa),qa.applyMatrix4(n.projectionViewMatrix),c.zDepth=qa.z)}),o.sort(this.sortOpaque),a.sort(this.sortTransparent),l.sort(this.sortUI),i=o.concat(a,l)}return i}render({scene:t,camera:n,target:r=null,update:s=!0,sort:i=!0,frustumCull:o=!0,clear:a}){r===null?(this.bindFramebuffer(),this.setViewport(this.width*this.dpr,this.height*this.dpr)):(this.bindFramebuffer(r),this.setViewport(r.width,r.height)),(a||this.autoClear&&a!==!1)&&(this.depth&&(!r||r.depth)&&(this.enable(this.gl.DEPTH_TEST),this.setDepthMask(!0)),(this.stencil||!r||r.stencil)&&(this.enable(this.gl.STENCIL_TEST),this.setStencilMask(255)),this.gl.clear((this.color?this.gl.COLOR_BUFFER_BIT:0)|(this.depth?this.gl.DEPTH_BUFFER_BIT:0)|(this.stencil?this.gl.STENCIL_BUFFER_BIT:0))),s&&t.updateMatrixWorld(),n&&n.updateMatrixWorld(),this.getRenderList({scene:t,camera:n,frustumCull:o,sort:i}).forEach(c=>{c.draw({camera:n})})}}function $b(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e}function Bb(e,t,n,r,s){return e[0]=t,e[1]=n,e[2]=r,e[3]=s,e}function Ub(e,t){let n=t[0],r=t[1],s=t[2],i=t[3],o=n*n+r*r+s*s+i*i;return o>0&&(o=1/Math.sqrt(o)),e[0]=n*o,e[1]=r*o,e[2]=s*o,e[3]=i*o,e}function Wb(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]}function Hb(e){return e[0]=0,e[1]=0,e[2]=0,e[3]=1,e}function qb(e,t,n){n=n*.5;let r=Math.sin(n);return e[0]=r*t[0],e[1]=r*t[1],e[2]=r*t[2],e[3]=Math.cos(n),e}function yh(e,t,n){let r=t[0],s=t[1],i=t[2],o=t[3],a=n[0],l=n[1],c=n[2],d=n[3];return e[0]=r*d+o*a+s*c-i*l,e[1]=s*d+o*l+i*a-r*c,e[2]=i*d+o*c+r*l-s*a,e[3]=o*d-r*a-s*l-i*c,e}function Gb(e,t,n){n*=.5;let r=t[0],s=t[1],i=t[2],o=t[3],a=Math.sin(n),l=Math.cos(n);return e[0]=r*l+o*a,e[1]=s*l+i*a,e[2]=i*l-s*a,e[3]=o*l-r*a,e}function Yb(e,t,n){n*=.5;let r=t[0],s=t[1],i=t[2],o=t[3],a=Math.sin(n),l=Math.cos(n);return e[0]=r*l-i*a,e[1]=s*l+o*a,e[2]=i*l+r*a,e[3]=o*l-s*a,e}function Kb(e,t,n){n*=.5;let r=t[0],s=t[1],i=t[2],o=t[3],a=Math.sin(n),l=Math.cos(n);return e[0]=r*l+s*a,e[1]=s*l-r*a,e[2]=i*l+o*a,e[3]=o*l-i*a,e}function Xb(e,t,n,r){let s=t[0],i=t[1],o=t[2],a=t[3],l=n[0],c=n[1],d=n[2],f=n[3],u,h,p,g,x;return h=s*l+i*c+o*d+a*f,h<0&&(h=-h,l=-l,c=-c,d=-d,f=-f),1-h>1e-6?(u=Math.acos(h),p=Math.sin(u),g=Math.sin((1-r)*u)/p,x=Math.sin(r*u)/p):(g=1-r,x=r),e[0]=g*s+x*l,e[1]=g*i+x*c,e[2]=g*o+x*d,e[3]=g*a+x*f,e}function Qb(e,t){let n=t[0],r=t[1],s=t[2],i=t[3],o=n*n+r*r+s*s+i*i,a=o?1/o:0;return e[0]=-n*a,e[1]=-r*a,e[2]=-s*a,e[3]=i*a,e}function Zb(e,t){return e[0]=-t[0],e[1]=-t[1],e[2]=-t[2],e[3]=t[3],e}function Jb(e,t){let n=t[0]+t[4]+t[8],r;if(n>0)r=Math.sqrt(n+1),e[3]=.5*r,r=.5/r,e[0]=(t[5]-t[7])*r,e[1]=(t[6]-t[2])*r,e[2]=(t[1]-t[3])*r;else{let s=0;t[4]>t[0]&&(s=1),t[8]>t[s*3+s]&&(s=2);let i=(s+1)%3,o=(s+2)%3;r=Math.sqrt(t[s*3+s]-t[i*3+i]-t[o*3+o]+1),e[s]=.5*r,r=.5/r,e[3]=(t[i*3+o]-t[o*3+i])*r,e[i]=(t[i*3+s]+t[s*3+i])*r,e[o]=(t[o*3+s]+t[s*3+o])*r}return e}function eS(e,t,n="YXZ"){let r=Math.sin(t[0]*.5),s=Math.cos(t[0]*.5),i=Math.sin(t[1]*.5),o=Math.cos(t[1]*.5),a=Math.sin(t[2]*.5),l=Math.cos(t[2]*.5);return n==="XYZ"?(e[0]=r*o*l+s*i*a,e[1]=s*i*l-r*o*a,e[2]=s*o*a+r*i*l,e[3]=s*o*l-r*i*a):n==="YXZ"?(e[0]=r*o*l+s*i*a,e[1]=s*i*l-r*o*a,e[2]=s*o*a-r*i*l,e[3]=s*o*l+r*i*a):n==="ZXY"?(e[0]=r*o*l-s*i*a,e[1]=s*i*l+r*o*a,e[2]=s*o*a+r*i*l,e[3]=s*o*l-r*i*a):n==="ZYX"?(e[0]=r*o*l-s*i*a,e[1]=s*i*l+r*o*a,e[2]=s*o*a-r*i*l,e[3]=s*o*l+r*i*a):n==="YZX"?(e[0]=r*o*l+s*i*a,e[1]=s*i*l+r*o*a,e[2]=s*o*a-r*i*l,e[3]=s*o*l-r*i*a):n==="XZY"&&(e[0]=r*o*l-s*i*a,e[1]=s*i*l-r*o*a,e[2]=s*o*a+r*i*l,e[3]=s*o*l+r*i*a),e}const tS=$b,nS=Bb,rS=Wb,sS=Ub;class iS extends Array{constructor(t=0,n=0,r=0,s=1){super(t,n,r,s),this.onChange=()=>{},this._target=this;const i=["0","1","2","3"];return new Proxy(this,{set(o,a){const l=Reflect.set(...arguments);return l&&i.includes(a)&&o.onChange(),l}})}get x(){return this[0]}get y(){return this[1]}get z(){return this[2]}get w(){return this[3]}set x(t){this._target[0]=t,this.onChange()}set y(t){this._target[1]=t,this.onChange()}set z(t){this._target[2]=t,this.onChange()}set w(t){this._target[3]=t,this.onChange()}identity(){return Hb(this._target),this.onChange(),this}set(t,n,r,s){return t.length?this.copy(t):(nS(this._target,t,n,r,s),this.onChange(),this)}rotateX(t){return Gb(this._target,this._target,t),this.onChange(),this}rotateY(t){return Yb(this._target,this._target,t),this.onChange(),this}rotateZ(t){return Kb(this._target,this._target,t),this.onChange(),this}inverse(t=this._target){return Qb(this._target,t),this.onChange(),this}conjugate(t=this._target){return Zb(this._target,t),this.onChange(),this}copy(t){return tS(this._target,t),this.onChange(),this}normalize(t=this._target){return sS(this._target,t),this.onChange(),this}multiply(t,n){return n?yh(this._target,t,n):yh(this._target,this._target,t),this.onChange(),this}dot(t){return rS(this._target,t)}fromMatrix3(t){return Jb(this._target,t),this.onChange(),this}fromEuler(t,n){return eS(this._target,t,t.order),n||this.onChange(),this}fromAxisAngle(t,n){return qb(this._target,t,n),this.onChange(),this}slerp(t,n){return Xb(this._target,this._target,t,n),this.onChange(),this}fromArray(t,n=0){return this._target[0]=t[n],this._target[1]=t[n+1],this._target[2]=t[n+2],this._target[3]=t[n+3],this.onChange(),this}toArray(t=[],n=0){return t[n]=this[0],t[n+1]=this[1],t[n+2]=this[2],t[n+3]=this[3],t}}const oS=1e-6;function aS(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function lS(e,t,n,r,s,i,o,a,l,c,d,f,u,h,p,g,x){return e[0]=t,e[1]=n,e[2]=r,e[3]=s,e[4]=i,e[5]=o,e[6]=a,e[7]=l,e[8]=c,e[9]=d,e[10]=f,e[11]=u,e[12]=h,e[13]=p,e[14]=g,e[15]=x,e}function uS(e){return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function cS(e,t){let n=t[0],r=t[1],s=t[2],i=t[3],o=t[4],a=t[5],l=t[6],c=t[7],d=t[8],f=t[9],u=t[10],h=t[11],p=t[12],g=t[13],x=t[14],v=t[15],y=n*a-r*o,w=n*l-s*o,b=n*c-i*o,S=r*l-s*a,C=r*c-i*a,P=s*c-i*l,j=d*g-f*p,D=d*x-u*p,T=d*v-h*p,z=f*x-u*g,V=f*v-h*g,U=u*v-h*x,R=y*U-w*V+b*z+S*T-C*D+P*j;return R?(R=1/R,e[0]=(a*U-l*V+c*z)*R,e[1]=(s*V-r*U-i*z)*R,e[2]=(g*P-x*C+v*S)*R,e[3]=(u*C-f*P-h*S)*R,e[4]=(l*T-o*U-c*D)*R,e[5]=(n*U-s*T+i*D)*R,e[6]=(x*b-p*P-v*w)*R,e[7]=(d*P-u*b+h*w)*R,e[8]=(o*V-a*T+c*j)*R,e[9]=(r*T-n*V-i*j)*R,e[10]=(p*C-g*b+v*y)*R,e[11]=(f*b-d*C-h*y)*R,e[12]=(a*D-o*z-l*j)*R,e[13]=(n*z-r*D+s*j)*R,e[14]=(g*w-p*S-x*y)*R,e[15]=(d*S-f*w+u*y)*R,e):null}function zg(e){let t=e[0],n=e[1],r=e[2],s=e[3],i=e[4],o=e[5],a=e[6],l=e[7],c=e[8],d=e[9],f=e[10],u=e[11],h=e[12],p=e[13],g=e[14],x=e[15],v=t*o-n*i,y=t*a-r*i,w=t*l-s*i,b=n*a-r*o,S=n*l-s*o,C=r*l-s*a,P=c*p-d*h,j=c*g-f*h,D=c*x-u*h,T=d*g-f*p,z=d*x-u*p,V=f*x-u*g;return v*V-y*z+w*T+b*D-S*j+C*P}function vh(e,t,n){let r=t[0],s=t[1],i=t[2],o=t[3],a=t[4],l=t[5],c=t[6],d=t[7],f=t[8],u=t[9],h=t[10],p=t[11],g=t[12],x=t[13],v=t[14],y=t[15],w=n[0],b=n[1],S=n[2],C=n[3];return e[0]=w*r+b*a+S*f+C*g,e[1]=w*s+b*l+S*u+C*x,e[2]=w*i+b*c+S*h+C*v,e[3]=w*o+b*d+S*p+C*y,w=n[4],b=n[5],S=n[6],C=n[7],e[4]=w*r+b*a+S*f+C*g,e[5]=w*s+b*l+S*u+C*x,e[6]=w*i+b*c+S*h+C*v,e[7]=w*o+b*d+S*p+C*y,w=n[8],b=n[9],S=n[10],C=n[11],e[8]=w*r+b*a+S*f+C*g,e[9]=w*s+b*l+S*u+C*x,e[10]=w*i+b*c+S*h+C*v,e[11]=w*o+b*d+S*p+C*y,w=n[12],b=n[13],S=n[14],C=n[15],e[12]=w*r+b*a+S*f+C*g,e[13]=w*s+b*l+S*u+C*x,e[14]=w*i+b*c+S*h+C*v,e[15]=w*o+b*d+S*p+C*y,e}function dS(e,t,n){let r=n[0],s=n[1],i=n[2],o,a,l,c,d,f,u,h,p,g,x,v;return t===e?(e[12]=t[0]*r+t[4]*s+t[8]*i+t[12],e[13]=t[1]*r+t[5]*s+t[9]*i+t[13],e[14]=t[2]*r+t[6]*s+t[10]*i+t[14],e[15]=t[3]*r+t[7]*s+t[11]*i+t[15]):(o=t[0],a=t[1],l=t[2],c=t[3],d=t[4],f=t[5],u=t[6],h=t[7],p=t[8],g=t[9],x=t[10],v=t[11],e[0]=o,e[1]=a,e[2]=l,e[3]=c,e[4]=d,e[5]=f,e[6]=u,e[7]=h,e[8]=p,e[9]=g,e[10]=x,e[11]=v,e[12]=o*r+d*s+p*i+t[12],e[13]=a*r+f*s+g*i+t[13],e[14]=l*r+u*s+x*i+t[14],e[15]=c*r+h*s+v*i+t[15]),e}function fS(e,t,n){let r=n[0],s=n[1],i=n[2];return e[0]=t[0]*r,e[1]=t[1]*r,e[2]=t[2]*r,e[3]=t[3]*r,e[4]=t[4]*s,e[5]=t[5]*s,e[6]=t[6]*s,e[7]=t[7]*s,e[8]=t[8]*i,e[9]=t[9]*i,e[10]=t[10]*i,e[11]=t[11]*i,e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function hS(e,t,n,r){let s=r[0],i=r[1],o=r[2],a=Math.hypot(s,i,o),l,c,d,f,u,h,p,g,x,v,y,w,b,S,C,P,j,D,T,z,V,U,R,Q;return Math.abs(a)0?(v=Math.sqrt(x+1)*2,t[3]=.25*v,t[0]=(u-p)/v,t[1]=(h-c)/v,t[2]=(l-d)/v):a>f&&a>g?(v=Math.sqrt(1+a-f-g)*2,t[3]=(u-p)/v,t[0]=.25*v,t[1]=(l+d)/v,t[2]=(h+c)/v):f>g?(v=Math.sqrt(1+f-a-g)*2,t[3]=(h-c)/v,t[0]=(l+d)/v,t[1]=.25*v,t[2]=(u+p)/v):(v=Math.sqrt(1+g-a-f)*2,t[3]=(l-d)/v,t[0]=(h+c)/v,t[1]=(u+p)/v,t[2]=.25*v),t}}();function gS(e,t,n,r){let s=bs([e[0],e[1],e[2]]);const i=bs([e[4],e[5],e[6]]),o=bs([e[8],e[9],e[10]]);zg(e)<0&&(s=-s),n[0]=e[12],n[1]=e[13],n[2]=e[14];const l=e.slice(),c=1/s,d=1/i,f=1/o;l[0]*=c,l[1]*=c,l[2]*=c,l[4]*=d,l[5]*=d,l[6]*=d,l[8]*=f,l[9]*=f,l[10]*=f,$g(t,l),r[0]=s,r[1]=i,r[2]=o}function yS(e,t,n,r){const s=e,i=t[0],o=t[1],a=t[2],l=t[3],c=i+i,d=o+o,f=a+a,u=i*c,h=i*d,p=i*f,g=o*d,x=o*f,v=a*f,y=l*c,w=l*d,b=l*f,S=r[0],C=r[1],P=r[2];return s[0]=(1-(g+v))*S,s[1]=(h+b)*S,s[2]=(p-w)*S,s[3]=0,s[4]=(h-b)*C,s[5]=(1-(u+v))*C,s[6]=(x+y)*C,s[7]=0,s[8]=(p+w)*P,s[9]=(x-y)*P,s[10]=(1-(u+g))*P,s[11]=0,s[12]=n[0],s[13]=n[1],s[14]=n[2],s[15]=1,s}function vS(e,t){let n=t[0],r=t[1],s=t[2],i=t[3],o=n+n,a=r+r,l=s+s,c=n*o,d=r*o,f=r*a,u=s*o,h=s*a,p=s*l,g=i*o,x=i*a,v=i*l;return e[0]=1-f-p,e[1]=d+v,e[2]=u-x,e[3]=0,e[4]=d-v,e[5]=1-c-p,e[6]=h+g,e[7]=0,e[8]=u+x,e[9]=h-g,e[10]=1-c-f,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function xS(e,t,n,r,s){let i=1/Math.tan(t/2),o=1/(r-s);return e[0]=i/n,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=i,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=(s+r)*o,e[11]=-1,e[12]=0,e[13]=0,e[14]=2*s*r*o,e[15]=0,e}function wS(e,t,n,r,s,i,o){let a=1/(t-n),l=1/(r-s),c=1/(i-o);return e[0]=-2*a,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=-2*l,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=2*c,e[11]=0,e[12]=(t+n)*a,e[13]=(s+r)*l,e[14]=(o+i)*c,e[15]=1,e}function bS(e,t,n,r){let s=t[0],i=t[1],o=t[2],a=r[0],l=r[1],c=r[2],d=s-n[0],f=i-n[1],u=o-n[2],h=d*d+f*f+u*u;h===0?u=1:(h=1/Math.sqrt(h),d*=h,f*=h,u*=h);let p=l*u-c*f,g=c*d-a*u,x=a*f-l*d;return h=p*p+g*g+x*x,h===0&&(c?a+=1e-6:l?c+=1e-6:l+=1e-6,p=l*u-c*f,g=c*d-a*u,x=a*f-l*d,h=p*p+g*g+x*x),h=1/Math.sqrt(h),p*=h,g*=h,x*=h,e[0]=p,e[1]=g,e[2]=x,e[3]=0,e[4]=f*x-u*g,e[5]=u*p-d*x,e[6]=d*g-f*p,e[7]=0,e[8]=d,e[9]=f,e[10]=u,e[11]=0,e[12]=s,e[13]=i,e[14]=o,e[15]=1,e}function xh(e,t,n){return e[0]=t[0]+n[0],e[1]=t[1]+n[1],e[2]=t[2]+n[2],e[3]=t[3]+n[3],e[4]=t[4]+n[4],e[5]=t[5]+n[5],e[6]=t[6]+n[6],e[7]=t[7]+n[7],e[8]=t[8]+n[8],e[9]=t[9]+n[9],e[10]=t[10]+n[10],e[11]=t[11]+n[11],e[12]=t[12]+n[12],e[13]=t[13]+n[13],e[14]=t[14]+n[14],e[15]=t[15]+n[15],e}function wh(e,t,n){return e[0]=t[0]-n[0],e[1]=t[1]-n[1],e[2]=t[2]-n[2],e[3]=t[3]-n[3],e[4]=t[4]-n[4],e[5]=t[5]-n[5],e[6]=t[6]-n[6],e[7]=t[7]-n[7],e[8]=t[8]-n[8],e[9]=t[9]-n[9],e[10]=t[10]-n[10],e[11]=t[11]-n[11],e[12]=t[12]-n[12],e[13]=t[13]-n[13],e[14]=t[14]-n[14],e[15]=t[15]-n[15],e}function SS(e,t,n){return e[0]=t[0]*n,e[1]=t[1]*n,e[2]=t[2]*n,e[3]=t[3]*n,e[4]=t[4]*n,e[5]=t[5]*n,e[6]=t[6]*n,e[7]=t[7]*n,e[8]=t[8]*n,e[9]=t[9]*n,e[10]=t[10]*n,e[11]=t[11]*n,e[12]=t[12]*n,e[13]=t[13]*n,e[14]=t[14]*n,e[15]=t[15]*n,e}class Co extends Array{constructor(t=1,n=0,r=0,s=0,i=0,o=1,a=0,l=0,c=0,d=0,f=1,u=0,h=0,p=0,g=0,x=1){return super(t,n,r,s,i,o,a,l,c,d,f,u,h,p,g,x),this}get x(){return this[12]}get y(){return this[13]}get z(){return this[14]}get w(){return this[15]}set x(t){this[12]=t}set y(t){this[13]=t}set z(t){this[14]=t}set w(t){this[15]=t}set(t,n,r,s,i,o,a,l,c,d,f,u,h,p,g,x){return t.length?this.copy(t):(lS(this,t,n,r,s,i,o,a,l,c,d,f,u,h,p,g,x),this)}translate(t,n=this){return dS(this,n,t),this}rotate(t,n,r=this){return hS(this,r,t,n),this}scale(t,n=this){return fS(this,n,typeof t=="number"?[t,t,t]:t),this}add(t,n){return n?xh(this,t,n):xh(this,this,t),this}sub(t,n){return n?wh(this,t,n):wh(this,this,t),this}multiply(t,n){return t.length?n?vh(this,t,n):vh(this,this,t):SS(this,this,t),this}identity(){return uS(this),this}copy(t){return aS(this,t),this}fromPerspective({fov:t,aspect:n,near:r,far:s}={}){return xS(this,t,n,r,s),this}fromOrthogonal({left:t,right:n,bottom:r,top:s,near:i,far:o}){return wS(this,t,n,r,s,i,o),this}fromQuaternion(t){return vS(this,t),this}setPosition(t){return this.x=t[0],this.y=t[1],this.z=t[2],this}inverse(t=this){return cS(this,t),this}compose(t,n,r){return yS(this,t,n,r),this}decompose(t,n,r){return gS(this,t,n,r),this}getRotation(t){return $g(t,this),this}getTranslation(t){return pS(t,this),this}getScaling(t){return Og(t,this),this}getMaxScaleOnAxis(){return mS(this)}lookAt(t,n,r){return bS(this,t,n,r),this}determinant(){return zg(this)}fromArray(t,n=0){return this[0]=t[n],this[1]=t[n+1],this[2]=t[n+2],this[3]=t[n+3],this[4]=t[n+4],this[5]=t[n+5],this[6]=t[n+6],this[7]=t[n+7],this[8]=t[n+8],this[9]=t[n+9],this[10]=t[n+10],this[11]=t[n+11],this[12]=t[n+12],this[13]=t[n+13],this[14]=t[n+14],this[15]=t[n+15],this}toArray(t=[],n=0){return t[n]=this[0],t[n+1]=this[1],t[n+2]=this[2],t[n+3]=this[3],t[n+4]=this[4],t[n+5]=this[5],t[n+6]=this[6],t[n+7]=this[7],t[n+8]=this[8],t[n+9]=this[9],t[n+10]=this[10],t[n+11]=this[11],t[n+12]=this[12],t[n+13]=this[13],t[n+14]=this[14],t[n+15]=this[15],t}}function kS(e,t,n="YXZ"){return n==="XYZ"?(e[1]=Math.asin(Math.min(Math.max(t[8],-1),1)),Math.abs(t[8])<.99999?(e[0]=Math.atan2(-t[9],t[10]),e[2]=Math.atan2(-t[4],t[0])):(e[0]=Math.atan2(t[6],t[5]),e[2]=0)):n==="YXZ"?(e[0]=Math.asin(-Math.min(Math.max(t[9],-1),1)),Math.abs(t[9])<.99999?(e[1]=Math.atan2(t[8],t[10]),e[2]=Math.atan2(t[1],t[5])):(e[1]=Math.atan2(-t[2],t[0]),e[2]=0)):n==="ZXY"?(e[0]=Math.asin(Math.min(Math.max(t[6],-1),1)),Math.abs(t[6])<.99999?(e[1]=Math.atan2(-t[2],t[10]),e[2]=Math.atan2(-t[4],t[5])):(e[1]=0,e[2]=Math.atan2(t[1],t[0]))):n==="ZYX"?(e[1]=Math.asin(-Math.min(Math.max(t[2],-1),1)),Math.abs(t[2])<.99999?(e[0]=Math.atan2(t[6],t[10]),e[2]=Math.atan2(t[1],t[0])):(e[0]=0,e[2]=Math.atan2(-t[4],t[5]))):n==="YZX"?(e[2]=Math.asin(Math.min(Math.max(t[1],-1),1)),Math.abs(t[1])<.99999?(e[0]=Math.atan2(-t[9],t[5]),e[1]=Math.atan2(-t[2],t[0])):(e[0]=0,e[1]=Math.atan2(t[8],t[10]))):n==="XZY"&&(e[2]=Math.asin(-Math.min(Math.max(t[4],-1),1)),Math.abs(t[4])<.99999?(e[0]=Math.atan2(t[6],t[5]),e[1]=Math.atan2(t[8],t[0])):(e[0]=Math.atan2(-t[9],t[10]),e[1]=0)),e}const bh=new Co;class CS extends Array{constructor(t=0,n=t,r=t,s="YXZ"){super(t,n,r),this.order=s,this.onChange=()=>{},this._target=this;const i=["0","1","2"];return new Proxy(this,{set(o,a){const l=Reflect.set(...arguments);return l&&i.includes(a)&&o.onChange(),l}})}get x(){return this[0]}get y(){return this[1]}get z(){return this[2]}set x(t){this._target[0]=t,this.onChange()}set y(t){this._target[1]=t,this.onChange()}set z(t){this._target[2]=t,this.onChange()}set(t,n=t,r=t){return t.length?this.copy(t):(this._target[0]=t,this._target[1]=n,this._target[2]=r,this.onChange(),this)}copy(t){return this._target[0]=t[0],this._target[1]=t[1],this._target[2]=t[2],this.onChange(),this}reorder(t){return this._target.order=t,this.onChange(),this}fromRotationMatrix(t,n=this.order){return kS(this._target,t,n),this.onChange(),this}fromQuaternion(t,n=this.order,r){return bh.fromQuaternion(t),this._target.fromRotationMatrix(bh,n),r||this.onChange(),this}fromArray(t,n=0){return this._target[0]=t[n],this._target[1]=t[n+1],this._target[2]=t[n+2],this}toArray(t=[],n=0){return t[n]=this[0],t[n+1]=this[1],t[n+2]=this[2],t}}class PS{constructor(){this.parent=null,this.children=[],this.visible=!0,this.matrix=new Co,this.worldMatrix=new Co,this.matrixAutoUpdate=!0,this.worldMatrixNeedsUpdate=!1,this.position=new mt,this.quaternion=new iS,this.scale=new mt(1),this.rotation=new CS,this.up=new mt(0,1,0),this.rotation._target.onChange=()=>this.quaternion.fromEuler(this.rotation,!0),this.quaternion._target.onChange=()=>this.rotation.fromQuaternion(this.quaternion,void 0,!0)}setParent(t,n=!0){this.parent&&t!==this.parent&&this.parent.removeChild(this,!1),this.parent=t,n&&t&&t.addChild(this,!1)}addChild(t,n=!0){~this.children.indexOf(t)||this.children.push(t),n&&t.setParent(this,!1)}removeChild(t,n=!0){~this.children.indexOf(t)&&this.children.splice(this.children.indexOf(t),1),n&&t.setParent(null,!1)}updateMatrixWorld(t){this.matrixAutoUpdate&&this.updateMatrix(),(this.worldMatrixNeedsUpdate||t)&&(this.parent===null?this.worldMatrix.copy(this.matrix):this.worldMatrix.multiply(this.parent.worldMatrix,this.matrix),this.worldMatrixNeedsUpdate=!1,t=!0);for(let n=0,r=this.children.length;nr&&r({mesh:this,camera:t}));let n=this.program.cullFace&&this.worldMatrix.determinant()<0;this.program.use({flipFaces:n}),this.geometry.draw({mode:this.mode,program:this.program}),this.afterRenderCallbacks.forEach(r=>r&&r({mesh:this,camera:t}))}}function zS(e,t){return e[0]=t[0],e[1]=t[1],e}function OS(e,t,n){return e[0]=t,e[1]=n,e}function kh(e,t,n){return e[0]=t[0]+n[0],e[1]=t[1]+n[1],e}function Ch(e,t,n){return e[0]=t[0]-n[0],e[1]=t[1]-n[1],e}function $S(e,t,n){return e[0]=t[0]*n[0],e[1]=t[1]*n[1],e}function BS(e,t,n){return e[0]=t[0]/n[0],e[1]=t[1]/n[1],e}function Ga(e,t,n){return e[0]=t[0]*n,e[1]=t[1]*n,e}function US(e,t){var n=t[0]-e[0],r=t[1]-e[1];return Math.sqrt(n*n+r*r)}function WS(e,t){var n=t[0]-e[0],r=t[1]-e[1];return n*n+r*r}function Ph(e){var t=e[0],n=e[1];return Math.sqrt(t*t+n*n)}function HS(e){var t=e[0],n=e[1];return t*t+n*n}function qS(e,t){return e[0]=-t[0],e[1]=-t[1],e}function GS(e,t){return e[0]=1/t[0],e[1]=1/t[1],e}function YS(e,t){var n=t[0],r=t[1],s=n*n+r*r;return s>0&&(s=1/Math.sqrt(s)),e[0]=t[0]*s,e[1]=t[1]*s,e}function KS(e,t){return e[0]*t[0]+e[1]*t[1]}function jh(e,t){return e[0]*t[1]-e[1]*t[0]}function XS(e,t,n,r){var s=t[0],i=t[1];return e[0]=s+r*(n[0]-s),e[1]=i+r*(n[1]-i),e}function QS(e,t,n,r,s){const i=Math.exp(-r*s);let o=t[0],a=t[1];return e[0]=n[0]+(o-n[0])*i,e[1]=n[1]+(a-n[1])*i,e}function ZS(e,t,n){var r=t[0],s=t[1];return e[0]=n[0]*r+n[3]*s+n[6],e[1]=n[1]*r+n[4]*s+n[7],e}function JS(e,t,n){let r=t[0],s=t[1];return e[0]=n[0]*r+n[4]*s+n[12],e[1]=n[1]*r+n[5]*s+n[13],e}function ek(e,t){return e[0]===t[0]&&e[1]===t[1]}class _c extends Array{constructor(t=0,n=t){return super(t,n),this}get x(){return this[0]}get y(){return this[1]}set x(t){this[0]=t}set y(t){this[1]=t}set(t,n=t){return t.length?this.copy(t):(OS(this,t,n),this)}copy(t){return zS(this,t),this}add(t,n){return n?kh(this,t,n):kh(this,this,t),this}sub(t,n){return n?Ch(this,t,n):Ch(this,this,t),this}multiply(t){return t.length?$S(this,this,t):Ga(this,this,t),this}divide(t){return t.length?BS(this,this,t):Ga(this,this,1/t),this}inverse(t=this){return GS(this,t),this}len(){return Ph(this)}distance(t){return t?US(this,t):Ph(this)}squaredLen(){return this.squaredDistance()}squaredDistance(t){return t?WS(this,t):HS(this)}negate(t=this){return qS(this,t),this}cross(t,n){return n?jh(t,n):jh(this,t)}scale(t){return Ga(this,this,t),this}normalize(){return YS(this,this),this}dot(t){return KS(this,t)}equals(t){return ek(this,t)}applyMatrix3(t){return ZS(this,this,t),this}applyMatrix4(t){return JS(this,this,t),this}lerp(t,n){return XS(this,this,t,n),this}smoothLerp(t,n,r){return QS(this,this,t,n,r),this}clone(){return new _c(this[0],this[1])}fromArray(t,n=0){return this[0]=t[n],this[1]=t[n+1],this}toArray(t=[],n=0){return t[n]=this[0],t[n+1]=this[1],t}}class tk extends Lb{constructor(t,{attributes:n={}}={}){Object.assign(n,{position:{size:2,data:new Float32Array([-1,-1,3,-1,-1,3])},uv:{size:2,data:new Float32Array([0,0,2,0,0,2])}}),super(t,n)}}const nk=` +attribute vec2 position; +void main(){gl_Position=vec4(position,0.0,1.0);} +`,rk=` +#ifdef GL_ES +precision lowp float; +#endif +uniform vec2 uResolution; +uniform float uTime; +uniform float uHueShift; +uniform float uNoise; +uniform float uScan; +uniform float uScanFreq; +uniform float uWarp; +#define iTime uTime +#define iResolution uResolution + +vec4 buf[8]; +float rand(vec2 c){return fract(sin(dot(c,vec2(12.9898,78.233)))*43758.5453);} + +mat3 rgb2yiq=mat3(0.299,0.587,0.114,0.596,-0.274,-0.322,0.211,-0.523,0.312); +mat3 yiq2rgb=mat3(1.0,0.956,0.621,1.0,-0.272,-0.647,1.0,-1.106,1.703); + +vec3 hueShiftRGB(vec3 col,float deg){ + vec3 yiq=rgb2yiq*col; + float rad=radians(deg); + float cosh=cos(rad),sinh=sin(rad); + vec3 yiqShift=vec3(yiq.x,yiq.y*cosh-yiq.z*sinh,yiq.y*sinh+yiq.z*cosh); + return clamp(yiq2rgb*yiqShift,0.0,1.0); +} + +vec4 sigmoid(vec4 x){return 1./(1.+exp(-x));} + +vec4 cppn_fn(vec2 coordinate,float in0,float in1,float in2){ + buf[6]=vec4(coordinate.x,coordinate.y,0.3948333106474662+in0,0.36+in1); + buf[7]=vec4(0.14+in2,sqrt(coordinate.x*coordinate.x+coordinate.y*coordinate.y),0.,0.); + buf[0]=mat4(vec4(6.5404263,-3.6126034,0.7590882,-1.13613),vec4(2.4582713,3.1660357,1.2219609,0.06276096),vec4(-5.478085,-6.159632,1.8701609,-4.7742867),vec4(6.039214,-5.542865,-0.90925294,3.251348))*buf[6]+mat4(vec4(0.8473259,-5.722911,3.975766,1.6522468),vec4(-0.24321538,0.5839259,-1.7661959,-5.350116),vec4(0.,0.,0.,0.),vec4(0.,0.,0.,0.))*buf[7]+vec4(0.21808943,1.1243913,-1.7969975,5.0294676); + buf[1]=mat4(vec4(-3.3522482,-6.0612736,0.55641043,-4.4719114),vec4(0.8631464,1.7432913,5.643898,1.6106541),vec4(2.4941394,-3.5012043,1.7184316,6.357333),vec4(3.310376,8.209261,1.1355612,-1.165539))*buf[6]+mat4(vec4(5.24046,-13.034365,0.009859298,15.870829),vec4(2.987511,3.129433,-0.89023495,-1.6822904),vec4(0.,0.,0.,0.),vec4(0.,0.,0.,0.))*buf[7]+vec4(-5.9457836,-6.573602,-0.8812491,1.5436668); + buf[0]=sigmoid(buf[0]);buf[1]=sigmoid(buf[1]); + buf[2]=mat4(vec4(-15.219568,8.095543,-2.429353,-1.9381982),vec4(-5.951362,4.3115187,2.6393783,1.274315),vec4(-7.3145227,6.7297835,5.2473326,5.9411426),vec4(5.0796127,8.979051,-1.7278991,-1.158976))*buf[6]+mat4(vec4(-11.967154,-11.608155,6.1486754,11.237008),vec4(2.124141,-6.263192,-1.7050359,-0.7021966),vec4(0.,0.,0.,0.),vec4(0.,0.,0.,0.))*buf[7]+vec4(-4.17164,-3.2281182,-4.576417,-3.6401186); + buf[3]=mat4(vec4(3.1832156,-13.738922,1.879223,3.233465),vec4(0.64300746,12.768129,1.9141049,0.50990224),vec4(-0.049295485,4.4807224,1.4733979,1.801449),vec4(5.0039253,13.000481,3.3991797,-4.5561905))*buf[6]+mat4(vec4(-0.1285731,7.720628,-3.1425676,4.742367),vec4(0.6393625,3.714393,-0.8108378,-0.39174938),vec4(0.,0.,0.,0.),vec4(0.,0.,0.,0.))*buf[7]+vec4(-1.1811101,-21.621881,0.7851888,1.2329718); + buf[2]=sigmoid(buf[2]);buf[3]=sigmoid(buf[3]); + buf[4]=mat4(vec4(5.214916,-7.183024,2.7228765,2.6592617),vec4(-5.601878,-25.3591,4.067988,0.4602802),vec4(-10.57759,24.286327,21.102104,37.546658),vec4(4.3024497,-1.9625226,2.3458803,-1.372816))*buf[0]+mat4(vec4(-17.6526,-10.507558,2.2587414,12.462782),vec4(6.265566,-502.75443,-12.642513,0.9112289),vec4(-10.983244,20.741234,-9.701768,-0.7635988),vec4(5.383626,1.4819539,-4.1911616,-4.8444734))*buf[1]+mat4(vec4(12.785233,-16.345072,-0.39901125,1.7955981),vec4(-30.48365,-1.8345358,1.4542528,-1.1118771),vec4(19.872723,-7.337935,-42.941723,-98.52709),vec4(8.337645,-2.7312303,-2.2927687,-36.142323))*buf[2]+mat4(vec4(-16.298317,3.5471997,-0.44300047,-9.444417),vec4(57.5077,-35.609753,16.163465,-4.1534753),vec4(-0.07470326,-3.8656476,-7.0901804,3.1523974),vec4(-12.559385,-7.077619,1.490437,-0.8211543))*buf[3]+vec4(-7.67914,15.927437,1.3207729,-1.6686112); + buf[5]=mat4(vec4(-1.4109162,-0.372762,-3.770383,-21.367174),vec4(-6.2103205,-9.35908,0.92529047,8.82561),vec4(11.460242,-22.348068,13.625772,-18.693201),vec4(-0.3429052,-3.9905605,-2.4626114,-0.45033523))*buf[0]+mat4(vec4(7.3481627,-4.3661838,-6.3037653,-3.868115),vec4(1.5462853,6.5488915,1.9701879,-0.58291394),vec4(6.5858274,-2.2180402,3.7127688,-1.3730392),vec4(-5.7973905,10.134961,-2.3395722,-5.965605))*buf[1]+mat4(vec4(-2.5132585,-6.6685553,-1.4029363,-0.16285264),vec4(-0.37908727,0.53738135,4.389061,-1.3024765),vec4(-0.70647055,2.0111287,-5.1659346,-3.728635),vec4(-13.562562,10.487719,-0.9173751,-2.6487076))*buf[2]+mat4(vec4(-8.645013,6.5546675,-6.3944063,-5.5933375),vec4(-0.57783127,-1.077275,36.91025,5.736769),vec4(14.283112,3.7146652,7.1452246,-4.5958776),vec4(2.7192075,3.6021907,-4.366337,-2.3653464))*buf[3]+vec4(-5.9000807,-4.329569,1.2427121,8.59503); + buf[4]=sigmoid(buf[4]);buf[5]=sigmoid(buf[5]); + buf[6]=mat4(vec4(-1.61102,0.7970257,1.4675229,0.20917463),vec4(-28.793737,-7.1390953,1.5025433,4.656581),vec4(-10.94861,39.66238,0.74318546,-10.095605),vec4(-0.7229728,-1.5483948,0.7301322,2.1687684))*buf[0]+mat4(vec4(3.2547753,21.489103,-1.0194173,-3.3100595),vec4(-3.7316632,-3.3792162,-7.223193,-0.23685838),vec4(13.1804495,0.7916005,5.338587,5.687114),vec4(-4.167605,-17.798311,-6.815736,-1.6451967))*buf[1]+mat4(vec4(0.604885,-7.800309,-7.213122,-2.741014),vec4(-3.522382,-0.12359311,-0.5258442,0.43852118),vec4(9.6752825,-22.853785,2.062431,0.099892326),vec4(-4.3196306,-17.730087,2.5184598,5.30267))*buf[2]+mat4(vec4(-6.545563,-15.790176,-6.0438633,-5.415399),vec4(-43.591583,28.551912,-16.00161,18.84728),vec4(4.212382,8.394307,3.0958717,8.657522),vec4(-5.0237565,-4.450633,-4.4768,-5.5010443))*buf[3]+mat4(vec4(1.6985557,-67.05806,6.897715,1.9004834),vec4(1.8680354,2.3915145,2.5231109,4.081538),vec4(11.158006,1.7294737,2.0738268,7.386411),vec4(-4.256034,-306.24686,8.258898,-17.132736))*buf[4]+mat4(vec4(1.6889864,-4.5852966,3.8534803,-6.3482175),vec4(1.3543309,-1.2640043,9.932754,2.9079645),vec4(-5.2770967,0.07150358,-0.13962056,3.3269649),vec4(28.34703,-4.918278,6.1044083,4.085355))*buf[5]+vec4(6.6818056,12.522166,-3.7075126,-4.104386); + buf[7]=mat4(vec4(-8.265602,-4.7027016,5.098234,0.7509808),vec4(8.6507845,-17.15949,16.51939,-8.884479),vec4(-4.036479,-2.3946867,-2.6055532,-1.9866527),vec4(-2.2167742,-1.8135649,-5.9759874,4.8846445))*buf[0]+mat4(vec4(6.7790847,3.5076547,-2.8191125,-2.7028968),vec4(-5.743024,-0.27844876,1.4958696,-5.0517144),vec4(13.122226,15.735168,-2.9397483,-4.101023),vec4(-14.375265,-5.030483,-6.2599335,2.9848232))*buf[1]+mat4(vec4(4.0950394,-0.94011575,-5.674733,4.755022),vec4(4.3809423,4.8310084,1.7425908,-3.437416),vec4(2.117492,0.16342592,-104.56341,16.949184),vec4(-5.22543,-2.994248,3.8350096,-1.9364246))*buf[2]+mat4(vec4(-5.900337,1.7946124,-13.604192,-3.8060522),vec4(6.6583457,31.911177,25.164474,91.81147),vec4(11.840538,4.1503043,-0.7314397,6.768467),vec4(-6.3967767,4.034772,6.1714606,-0.32874924))*buf[3]+mat4(vec4(3.4992442,-196.91893,-8.923708,2.8142626),vec4(3.4806502,-3.1846354,5.1725626,5.1804223),vec4(-2.4009497,15.585794,1.2863957,2.0252278),vec4(-71.25271,-62.441242,-8.138444,0.50670296))*buf[4]+mat4(vec4(-12.291733,-11.176166,-7.3474145,4.390294),vec4(10.805477,5.6337385,-0.9385842,-4.7348723),vec4(-12.869276,-7.039391,5.3029537,7.5436664),vec4(1.4593618,8.91898,3.5101583,5.840625))*buf[5]+vec4(2.2415268,-6.705987,-0.98861027,-2.117676); + buf[6]=sigmoid(buf[6]);buf[7]=sigmoid(buf[7]); + buf[0]=mat4(vec4(1.6794263,1.3817469,2.9625452,0.),vec4(-1.8834411,-1.4806935,-3.5924516,0.),vec4(-1.3279216,-1.0918057,-2.3124623,0.),vec4(0.2662234,0.23235129,0.44178495,0.))*buf[0]+mat4(vec4(-0.6299101,-0.5945583,-0.9125601,0.),vec4(0.17828953,0.18300213,0.18182953,0.),vec4(-2.96544,-2.5819945,-4.9001055,0.),vec4(1.4195864,1.1868085,2.5176322,0.))*buf[1]+mat4(vec4(-1.2584374,-1.0552157,-2.1688404,0.),vec4(-0.7200217,-0.52666044,-1.438251,0.),vec4(0.15345335,0.15196142,0.272854,0.),vec4(0.945728,0.8861938,1.2766753,0.))*buf[2]+mat4(vec4(-2.4218085,-1.968602,-4.35166,0.),vec4(-22.683098,-18.0544,-41.954372,0.),vec4(0.63792,0.5470648,1.1078634,0.),vec4(-1.5489894,-1.3075932,-2.6444845,0.))*buf[3]+mat4(vec4(-0.49252132,-0.39877754,-0.91366625,0.),vec4(0.95609266,0.7923952,1.640221,0.),vec4(0.30616966,0.15693925,0.8639857,0.),vec4(1.1825981,0.94504964,2.176963,0.))*buf[4]+mat4(vec4(0.35446745,0.3293795,0.59547555,0.),vec4(-0.58784515,-0.48177817,-1.0614829,0.),vec4(2.5271258,1.9991658,4.6846647,0.),vec4(0.13042648,0.08864098,0.30187556,0.))*buf[5]+mat4(vec4(-1.7718065,-1.4033192,-3.3355875,0.),vec4(3.1664357,2.638297,5.378702,0.),vec4(-3.1724713,-2.6107926,-5.549295,0.),vec4(-2.851368,-2.249092,-5.3013067,0.))*buf[6]+mat4(vec4(1.5203838,1.2212278,2.8404984,0.),vec4(1.5210563,1.2651345,2.683903,0.),vec4(2.9789467,2.4364579,5.2347264,0.),vec4(2.2270417,1.8825914,3.8028636,0.))*buf[7]+vec4(-1.5468478,-3.6171484,0.24762098,0.); + buf[0]=sigmoid(buf[0]); + return vec4(buf[0].x,buf[0].y,buf[0].z,1.); +} + +void mainImage(out vec4 fragColor,in vec2 fragCoord){ + vec2 uv=fragCoord/uResolution.xy*2.-1.; + uv.y*=-1.; + uv+=uWarp*vec2(sin(uv.y*6.283+uTime*0.5),cos(uv.x*6.283+uTime*0.5))*0.05; + fragColor=cppn_fn(uv,0.1*sin(0.3*uTime),0.1*sin(0.69*uTime),0.1*sin(0.44*uTime)); +} + +void main(){ + vec4 col;mainImage(col,gl_FragCoord.xy); + col.rgb=hueShiftRGB(col.rgb,uHueShift); + float scanline_val=sin(gl_FragCoord.y*uScanFreq)*0.5+0.5; + col.rgb*=1.-(scanline_val*scanline_val)*uScan; + col.rgb+=(rand(gl_FragCoord.xy+uTime)-0.5)*uNoise; + gl_FragColor=vec4(clamp(col.rgb,0.0,1.0),1.0); +} +`;class sk extends k.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("ErrorBoundary caught an error:",t,n)}render(){return this.state.hasError?this.props.fallback||m.jsx("div",{style:{position:"fixed",top:0,left:0,width:"100%",height:"100%",background:"radial-gradient(circle at center, rgba(0,0,0,0.8) 0%, rgba(0,0,0,1) 100%)",zIndex:-1,pointerEvents:"none"}}):this.props.children}}function ik({hueShift:e=60,noiseIntensity:t=.03,scanlineIntensity:n=.08,speed:r=.4,scanlineFrequency:s=.6,warpAmount:i=.15,resolutionScale:o=1}){const a=k.useRef(null);return k.useEffect(()=>{const l=a.current;if(!l){console.error("DarkVeil: Canvas not found");return}let c,d,f;try{c=new Ob({dpr:Math.min(window.devicePixelRatio,2),canvas:l});const x=c.gl;if(!x){console.error("DarkVeil: WebGL context not available");return}const v=new tk(x);d=new Rb(x,{vertex:nk,fragment:rk,uniforms:{uTime:{value:0},uResolution:{value:new _c},uHueShift:{value:e},uNoise:{value:t},uScan:{value:n},uScanFreq:{value:s},uWarp:{value:i}}}),f=new IS(x,{geometry:v,program:d}),console.log("DarkVeil: Successfully initialized")}catch(x){console.error("DarkVeil: Initialization error:",x);return}const u=()=>{const x=window.innerWidth,v=window.innerHeight;c.setSize(x*o,v*o),d.uniforms.uResolution.value.set(x,v)};window.addEventListener("resize",u),u();const h=performance.now();let p=0;const g=()=>{d.uniforms.uTime.value=(performance.now()-h)/1e3*r,d.uniforms.uHueShift.value=e,d.uniforms.uNoise.value=t,d.uniforms.uScan.value=n,d.uniforms.uScanFreq.value=s,d.uniforms.uWarp.value=i,c.render({scene:f}),p=requestAnimationFrame(g)};return g(),()=>{cancelAnimationFrame(p),window.removeEventListener("resize",u)}},[e,t,n,r,s,i,o]),m.jsxs(m.Fragment,{children:[m.jsx("div",{style:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",background:"radial-gradient(circle at center, rgba(50,20,80,0.8) 0%, rgba(20,10,40,0.9) 50%, rgba(0,0,0,1) 100%)",zIndex:-10,pointerEvents:"none"}}),m.jsx("canvas",{ref:a,style:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",zIndex:-5,pointerEvents:"none",display:"block"}})]})}function Eh(e){return m.jsx(sk,{children:m.jsx(ik,{...e})})}/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */var ok={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ak=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().trim(),ee=(e,t)=>{const n=k.forwardRef(({color:r="currentColor",size:s=24,strokeWidth:i=2,absoluteStrokeWidth:o,className:a="",children:l,...c},d)=>k.createElement("svg",{ref:d,...ok,width:s,height:s,stroke:r,strokeWidth:o?Number(i)*24/Number(s):i,className:["lucide",`lucide-${ak(e)}`,a].join(" "),...c},[...t.map(([f,u])=>k.createElement(f,u)),...Array.isArray(l)?l:[l]]));return n.displayName=`${e}`,n};/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const lk=ee("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const uk=ee("Calendar",[["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",ry:"2",key:"eu3xkr"}],["line",{x1:"16",x2:"16",y1:"2",y2:"6",key:"m3sa8f"}],["line",{x1:"8",x2:"8",y1:"2",y2:"6",key:"18kwsl"}],["line",{x1:"3",x2:"21",y1:"10",y2:"10",key:"xt86sb"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const ck=ee("Camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const dk=ee("CheckCircle",[["path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14",key:"g774vq"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Po=ee("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Bg=ee("ExternalLink",[["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}],["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["line",{x1:"10",x2:"21",y1:"14",y2:"3",key:"18c3s4"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Xe=ee("Heart",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const fk=ee("Loader2",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Th=ee("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const hk=ee("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const vt=ee("Music",[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const pk=ee("Pause",[["rect",{width:"4",height:"16",x:"6",y:"4",key:"iffhe4"}],["rect",{width:"4",height:"16",x:"14",y:"4",key:"sjin7j"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ug=ee("PlayCircle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polygon",{points:"10 8 16 12 10 16 10 8",key:"1cimsy"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Nh=ee("Play",[["polygon",{points:"5 3 19 12 5 21 5 3",key:"191637"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ac=ee("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Mh=ee("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Yn=ee("Sparkles",[["path",{d:"m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z",key:"17u4zn"}],["path",{d:"M5 3v4",key:"bklmnn"}],["path",{d:"M19 17v4",key:"iiml17"}],["path",{d:"M3 5h4",key:"nem4j1"}],["path",{d:"M17 19h4",key:"lbex7p"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const mk=ee("Star",[["polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2",key:"8f66p6"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Wg=ee("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const gk=ee("TrendingUp",[["polyline",{points:"22 7 13.5 15.5 8.5 10.5 2 17",key:"126l90"}],["polyline",{points:"16 7 22 7 22 13",key:"kwv8wd"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Ss=ee("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const Hg=ee("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const yk=ee("Volume2",[["polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5",key:"16drj5"}],["path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07",key:"ltjumu"}],["path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14",key:"1kegas"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const vk=ee("Wand2",[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72Z",key:"1bcowg"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const xk=ee("XCircle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** + * @license lucide-react v0.294.0 - ISC + * + * This source code is licensed under the ISC license. + * See the LICENSE file in the root directory of this source tree. + */const _h=ee("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);function qg(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(t=0;t{const t=kk(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:o=>{const a=o.split(Lc);return a[0]===""&&a.length!==1&&a.shift(),Gg(a,t)||Sk(o)},getConflictingClassGroupIds:(o,a)=>{const l=n[o]||[];return a&&r[o]?[...l,...r[o]]:l}}},Gg=(e,t)=>{var o;if(e.length===0)return t.classGroupId;const n=e[0],r=t.nextPart.get(n),s=r?Gg(e.slice(1),r):void 0;if(s)return s;if(t.validators.length===0)return;const i=e.join(Lc);return(o=t.validators.find(({validator:a})=>a(i)))==null?void 0:o.classGroupId},Ah=/^\[(.+)\]$/,Sk=e=>{if(Ah.test(e)){const t=Ah.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},kk=e=>{const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return Pk(Object.entries(e.classGroups),n).forEach(([i,o])=>{uu(o,r,i,t)}),r},uu=(e,t,n,r)=>{e.forEach(s=>{if(typeof s=="string"){const i=s===""?t:Lh(t,s);i.classGroupId=n;return}if(typeof s=="function"){if(Ck(s)){uu(s(r),t,n,r);return}t.validators.push({validator:s,classGroupId:n});return}Object.entries(s).forEach(([i,o])=>{uu(o,Lh(t,i),n,r)})})},Lh=(e,t)=>{let n=e;return t.split(Lc).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},Ck=e=>e.isThemeGetter,Pk=(e,t)=>t?e.map(([n,r])=>{const s=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([o,a])=>[t+o,a])):i);return[n,s]}):e,jk=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;const s=(i,o)=>{n.set(i,o),t++,t>e&&(t=0,r=n,n=new Map)};return{get(i){let o=n.get(i);if(o!==void 0)return o;if((o=r.get(i))!==void 0)return s(i,o),o},set(i,o){n.has(i)?n.set(i,o):s(i,o)}}},Yg="!",Ek=e=>{const{separator:t,experimentalParseClassName:n}=e,r=t.length===1,s=t[0],i=t.length,o=a=>{const l=[];let c=0,d=0,f;for(let x=0;xd?f-d:void 0;return{modifiers:l,hasImportantModifier:h,baseClassName:p,maybePostfixModifierPosition:g}};return n?a=>n({className:a,parseClassName:o}):o},Tk=e=>{if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t},Nk=e=>({cache:jk(e.cacheSize),parseClassName:Ek(e),...bk(e)}),Mk=/\s+/,_k=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:s}=t,i=[],o=e.trim().split(Mk);let a="";for(let l=o.length-1;l>=0;l-=1){const c=o[l],{modifiers:d,hasImportantModifier:f,baseClassName:u,maybePostfixModifierPosition:h}=n(c);let p=!!h,g=r(p?u.substring(0,h):u);if(!g){if(!p){a=c+(a.length>0?" "+a:a);continue}if(g=r(u),!g){a=c+(a.length>0?" "+a:a);continue}p=!1}const x=Tk(d).join(":"),v=f?x+Yg:x,y=v+g;if(i.includes(y))continue;i.push(y);const w=s(g,p);for(let b=0;b0?" "+a:a)}return a};function Ak(){let e=0,t,n,r="";for(;e{if(typeof e=="string")return e;let t,n="";for(let r=0;rf(d),e());return n=Nk(c),r=n.cache.get,s=n.cache.set,i=a,a(l)}function a(l){const c=r(l);if(c)return c;const d=_k(l,n);return s(l,d),d}return function(){return i(Ak.apply(null,arguments))}}const ne=e=>{const t=n=>n[e]||[];return t.isThemeGetter=!0,t},Xg=/^\[(?:([a-z-]+):)?(.+)\]$/i,Dk=/^\d+\/\d+$/,Rk=new Set(["px","full","screen"]),Vk=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Fk=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Ik=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,zk=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Ok=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Mt=e=>Cr(e)||Rk.has(e)||Dk.test(e),Kt=e=>Ur(e,"length",Yk),Cr=e=>!!e&&!Number.isNaN(Number(e)),Ya=e=>Ur(e,"number",Cr),ts=e=>!!e&&Number.isInteger(Number(e)),$k=e=>e.endsWith("%")&&Cr(e.slice(0,-1)),H=e=>Xg.test(e),Xt=e=>Vk.test(e),Bk=new Set(["length","size","percentage"]),Uk=e=>Ur(e,Bk,Qg),Wk=e=>Ur(e,"position",Qg),Hk=new Set(["image","url"]),qk=e=>Ur(e,Hk,Xk),Gk=e=>Ur(e,"",Kk),ns=()=>!0,Ur=(e,t,n)=>{const r=Xg.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1},Yk=e=>Fk.test(e)&&!Ik.test(e),Qg=()=>!1,Kk=e=>zk.test(e),Xk=e=>Ok.test(e),Qk=()=>{const e=ne("colors"),t=ne("spacing"),n=ne("blur"),r=ne("brightness"),s=ne("borderColor"),i=ne("borderRadius"),o=ne("borderSpacing"),a=ne("borderWidth"),l=ne("contrast"),c=ne("grayscale"),d=ne("hueRotate"),f=ne("invert"),u=ne("gap"),h=ne("gradientColorStops"),p=ne("gradientColorStopPositions"),g=ne("inset"),x=ne("margin"),v=ne("opacity"),y=ne("padding"),w=ne("saturate"),b=ne("scale"),S=ne("sepia"),C=ne("skew"),P=ne("space"),j=ne("translate"),D=()=>["auto","contain","none"],T=()=>["auto","hidden","clip","visible","scroll"],z=()=>["auto",H,t],V=()=>[H,t],U=()=>["",Mt,Kt],R=()=>["auto",Cr,H],Q=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],A=()=>["solid","dashed","dotted","double","none"],q=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],_=()=>["start","end","center","between","around","evenly","stretch"],N=()=>["","0",H],F=()=>["auto","avoid","all","avoid-page","page","left","right","column"],L=()=>[Cr,H];return{cacheSize:500,separator:":",theme:{colors:[ns],spacing:[Mt,Kt],blur:["none","",Xt,H],brightness:L(),borderColor:[e],borderRadius:["none","","full",Xt,H],borderSpacing:V(),borderWidth:U(),contrast:L(),grayscale:N(),hueRotate:L(),invert:N(),gap:V(),gradientColorStops:[e],gradientColorStopPositions:[$k,Kt],inset:z(),margin:z(),opacity:L(),padding:V(),saturate:L(),scale:L(),sepia:N(),skew:L(),space:V(),translate:V()},classGroups:{aspect:[{aspect:["auto","square","video",H]}],container:["container"],columns:[{columns:[Xt]}],"break-after":[{"break-after":F()}],"break-before":[{"break-before":F()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...Q(),H]}],overflow:[{overflow:T()}],"overflow-x":[{"overflow-x":T()}],"overflow-y":[{"overflow-y":T()}],overscroll:[{overscroll:D()}],"overscroll-x":[{"overscroll-x":D()}],"overscroll-y":[{"overscroll-y":D()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[g]}],"inset-x":[{"inset-x":[g]}],"inset-y":[{"inset-y":[g]}],start:[{start:[g]}],end:[{end:[g]}],top:[{top:[g]}],right:[{right:[g]}],bottom:[{bottom:[g]}],left:[{left:[g]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",ts,H]}],basis:[{basis:z()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",H]}],grow:[{grow:N()}],shrink:[{shrink:N()}],order:[{order:["first","last","none",ts,H]}],"grid-cols":[{"grid-cols":[ns]}],"col-start-end":[{col:["auto",{span:["full",ts,H]},H]}],"col-start":[{"col-start":R()}],"col-end":[{"col-end":R()}],"grid-rows":[{"grid-rows":[ns]}],"row-start-end":[{row:["auto",{span:[ts,H]},H]}],"row-start":[{"row-start":R()}],"row-end":[{"row-end":R()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",H]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",H]}],gap:[{gap:[u]}],"gap-x":[{"gap-x":[u]}],"gap-y":[{"gap-y":[u]}],"justify-content":[{justify:["normal",..._()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",..._(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[..._(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[y]}],px:[{px:[y]}],py:[{py:[y]}],ps:[{ps:[y]}],pe:[{pe:[y]}],pt:[{pt:[y]}],pr:[{pr:[y]}],pb:[{pb:[y]}],pl:[{pl:[y]}],m:[{m:[x]}],mx:[{mx:[x]}],my:[{my:[x]}],ms:[{ms:[x]}],me:[{me:[x]}],mt:[{mt:[x]}],mr:[{mr:[x]}],mb:[{mb:[x]}],ml:[{ml:[x]}],"space-x":[{"space-x":[P]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[P]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",H,t]}],"min-w":[{"min-w":[H,t,"min","max","fit"]}],"max-w":[{"max-w":[H,t,"none","full","min","max","fit","prose",{screen:[Xt]},Xt]}],h:[{h:[H,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[H,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[H,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[H,t,"auto","min","max","fit"]}],"font-size":[{text:["base",Xt,Kt]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Ya]}],"font-family":[{font:[ns]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",H]}],"line-clamp":[{"line-clamp":["none",Cr,Ya]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Mt,H]}],"list-image":[{"list-image":["none",H]}],"list-style-type":[{list:["none","disc","decimal",H]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[v]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[v]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...A(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Mt,Kt]}],"underline-offset":[{"underline-offset":["auto",Mt,H]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:V()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",H]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",H]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[v]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...Q(),Wk]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",Uk]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},qk]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[p]}],"gradient-via-pos":[{via:[p]}],"gradient-to-pos":[{to:[p]}],"gradient-from":[{from:[h]}],"gradient-via":[{via:[h]}],"gradient-to":[{to:[h]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[a]}],"border-w-x":[{"border-x":[a]}],"border-w-y":[{"border-y":[a]}],"border-w-s":[{"border-s":[a]}],"border-w-e":[{"border-e":[a]}],"border-w-t":[{"border-t":[a]}],"border-w-r":[{"border-r":[a]}],"border-w-b":[{"border-b":[a]}],"border-w-l":[{"border-l":[a]}],"border-opacity":[{"border-opacity":[v]}],"border-style":[{border:[...A(),"hidden"]}],"divide-x":[{"divide-x":[a]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[a]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[v]}],"divide-style":[{divide:A()}],"border-color":[{border:[s]}],"border-color-x":[{"border-x":[s]}],"border-color-y":[{"border-y":[s]}],"border-color-s":[{"border-s":[s]}],"border-color-e":[{"border-e":[s]}],"border-color-t":[{"border-t":[s]}],"border-color-r":[{"border-r":[s]}],"border-color-b":[{"border-b":[s]}],"border-color-l":[{"border-l":[s]}],"divide-color":[{divide:[s]}],"outline-style":[{outline:["",...A()]}],"outline-offset":[{"outline-offset":[Mt,H]}],"outline-w":[{outline:[Mt,Kt]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:U()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[v]}],"ring-offset-w":[{"ring-offset":[Mt,Kt]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Xt,Gk]}],"shadow-color":[{shadow:[ns]}],opacity:[{opacity:[v]}],"mix-blend":[{"mix-blend":[...q(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":q()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[l]}],"drop-shadow":[{"drop-shadow":["","none",Xt,H]}],grayscale:[{grayscale:[c]}],"hue-rotate":[{"hue-rotate":[d]}],invert:[{invert:[f]}],saturate:[{saturate:[w]}],sepia:[{sepia:[S]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[l]}],"backdrop-grayscale":[{"backdrop-grayscale":[c]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[d]}],"backdrop-invert":[{"backdrop-invert":[f]}],"backdrop-opacity":[{"backdrop-opacity":[v]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[S]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[o]}],"border-spacing-x":[{"border-spacing-x":[o]}],"border-spacing-y":[{"border-spacing-y":[o]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",H]}],duration:[{duration:L()}],ease:[{ease:["linear","in","out","in-out",H]}],delay:[{delay:L()}],animate:[{animate:["none","spin","ping","pulse","bounce",H]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[b]}],"scale-x":[{"scale-x":[b]}],"scale-y":[{"scale-y":[b]}],rotate:[{rotate:[ts,H]}],"translate-x":[{"translate-x":[j]}],"translate-y":[{"translate-y":[j]}],"skew-x":[{"skew-x":[C]}],"skew-y":[{"skew-y":[C]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",H]}],accent:[{accent:["auto",e]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",H]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":V()}],"scroll-mx":[{"scroll-mx":V()}],"scroll-my":[{"scroll-my":V()}],"scroll-ms":[{"scroll-ms":V()}],"scroll-me":[{"scroll-me":V()}],"scroll-mt":[{"scroll-mt":V()}],"scroll-mr":[{"scroll-mr":V()}],"scroll-mb":[{"scroll-mb":V()}],"scroll-ml":[{"scroll-ml":V()}],"scroll-p":[{"scroll-p":V()}],"scroll-px":[{"scroll-px":V()}],"scroll-py":[{"scroll-py":V()}],"scroll-ps":[{"scroll-ps":V()}],"scroll-pe":[{"scroll-pe":V()}],"scroll-pt":[{"scroll-pt":V()}],"scroll-pr":[{"scroll-pr":V()}],"scroll-pb":[{"scroll-pb":V()}],"scroll-pl":[{"scroll-pl":V()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",H]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[Mt,Kt,Ya]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},Zk=Lk(Qk);function Dh(...e){return Zk(wk(e))}function Zg(e){const t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${t}:${n.toString().padStart(2,"0")}`}function Pr(e){const t=new Date(e),r=(new Date().getTime()-t.getTime())/(1e3*60*60);return r<1?`${Math.floor(r*60)}m ago`:r<24?`${Math.floor(r)}h ago`:`${Math.floor(r/24)}d ago`}const Jk=()=>{var V,U,R,Q,A,q,_,N,F,L;const[e,t]=k.useState(!1),[n,r]=k.useState(!1),[s,i]=k.useState({x:0,y:0}),[o,a]=k.useState(!1),[l,c]=k.useState({x:0,y:0}),{currentUser:d,partnerUser:f,logout:u,theme:h,setTheme:p,setPartnerUser:g}=ae(),[x,v]=k.useState(""),[y,w]=k.useState(!1),[b,S]=k.useState(!1),C=En(),P=[{name:"Dashboard",href:"/",icon:Xe},{name:"Last Listened",href:"/last-listened",icon:vt},{name:"Mixed Playlist",href:"/mixed-playlist",icon:Ug},{name:"Memory Lane",href:"/memory-lane",icon:Yn}],j=()=>{u(),localStorage.removeItem("spotify-user"),localStorage.removeItem("spotify-partner")},D=async()=>{var E,W;if(!(!((E=d==null?void 0:d.user)!=null&&E.id)||!((W=f==null?void 0:f.user)!=null&&W.id))&&confirm(`Are you sure you want to remove ${f.user.display_name} as your partner?`)){S(!0);try{await Pt("/partners/remove",{partnerId:f.user.id})}catch(X){try{await Pt("/partners/clear",{userId:d.user.id})}catch(te){console.error("Failed to remove partner:",X,te)}}finally{g(null),localStorage.removeItem("spotify-partner"),S(!1)}}},T=Vr(h);k.useEffect(()=>{Vr(h)},[h]),k.useEffect(()=>{if(n){const E=Math.min(600,window.innerWidth-40),W=Math.min(window.innerHeight*.9,800),X=(window.innerWidth-E)/2,te=(window.innerHeight-W)/2;i({x:X,y:te})}},[n]),k.useEffect(()=>{const E=X=>{o&&i({x:X.clientX-l.x,y:X.clientY-l.y})},W=()=>{a(!1)};return o&&(document.addEventListener("mousemove",E),document.addEventListener("mouseup",W)),()=>{document.removeEventListener("mousemove",E),document.removeEventListener("mouseup",W)}},[o,l]);const z=E=>{a(!0),c({x:E.clientX-s.x,y:E.clientY-s.y})};return m.jsxs(O.nav,{initial:{y:-100,opacity:0},animate:{y:0,opacity:1},className:"sticky top-0 z-50",style:{background:"rgba(0, 0, 0, 0.8)",backdropFilter:"blur(20px)",borderBottom:"1px solid rgba(255, 255, 255, 0.05)"},children:[m.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8",children:[m.jsxs("div",{className:"flex justify-between items-center h-16",children:[m.jsxs(zi,{to:"/",className:"flex items-center space-x-2",children:[m.jsx(O.div,{whileHover:{scale:1.1,rotate:5},className:"w-8 h-8 rounded-full flex items-center justify-center",style:{background:`linear-gradient(135deg, ${((V=T.cssVars)==null?void 0:V.primary)||"#1db954"} 0%, ${((U=T.cssVars)==null?void 0:U.secondary)||"#1ed760"} 100%)`},children:m.jsx(Xe,{className:"w-5 h-5 text-white"})}),m.jsx("span",{className:"text-xl font-bold gradient-text",children:"Our Musical Journey"})]}),m.jsx("div",{className:"hidden md:flex items-center space-x-1",children:P.map(E=>{var X,te,G,be;const W=C.pathname===E.href;return m.jsxs(zi,{to:E.href,className:Dh("flex items-center space-x-2 px-4 py-2 rounded-xl transition-all duration-300",W?"text-white":"text-white/60 hover:text-white hover:bg-white/5"),style:W?{background:`linear-gradient(135deg, ${((X=T.cssVars)==null?void 0:X.primary)||"#1db954"}15 0%, ${((te=T.cssVars)==null?void 0:te.secondary)||"#1ed760"}10 100%)`,border:`1px solid ${((G=T.cssVars)==null?void 0:G.primary)||"#1db954"}30`}:{},children:[m.jsx(E.icon,{className:"w-4 h-4",style:{color:W?(be=T.cssVars)==null?void 0:be.primary:void 0}}),m.jsx("span",{className:"font-medium",children:E.name})]},E.name)})}),m.jsxs("div",{className:"hidden md:flex items-center space-x-4",children:[!f&&m.jsxs("div",{className:"flex items-center space-x-2",children:[m.jsx("input",{value:x,onChange:E=>v(E.target.value),placeholder:"Partner Spotify ID",className:"bg-white/10 text-white text-sm px-2 py-1 rounded"}),m.jsx("button",{disabled:y||!x,onClick:async()=>{var E;if(!(!((E=d==null?void 0:d.user)!=null&&E.id)||!x)){w(!0);try{await Pt("/partners/request",{toUid:x})}finally{w(!1)}}},className:`${T.primary} ${T.hover} text-white px-3 py-1 rounded text-sm disabled:opacity-50`,children:y?"Sending...":"Send Request"})]}),f&&m.jsxs(O.div,{initial:{scale:0},animate:{scale:1},className:"flex items-center space-x-2 text-sm text-white/70",children:[m.jsx(Ss,{className:"w-4 h-4"}),m.jsxs("span",{children:["+ ",(R=f.user)==null?void 0:R.display_name]})]}),m.jsxs(O.button,{whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>r(!0),className:"flex items-center space-x-2 px-3 py-2 rounded-xl text-white/60 hover:text-white transition-all duration-300",style:{color:(Q=T.cssVars)==null?void 0:Q.primary},onMouseEnter:E=>{E.currentTarget.style.background="rgba(255, 255, 255, 0.05)"},onMouseLeave:E=>{E.currentTarget.style.background="transparent"},children:[m.jsx(Mh,{className:"w-4 h-4"}),m.jsx("span",{className:"hidden lg:block",children:"Settings"})]}),m.jsxs(O.button,{whileHover:{scale:1.05},whileTap:{scale:.95},onClick:j,className:"flex items-center space-x-2 px-3 py-2 rounded-xl text-white/60 hover:text-white transition-all duration-300",onMouseEnter:E=>{E.currentTarget.style.background="rgba(239, 68, 68, 0.1)"},onMouseLeave:E=>{E.currentTarget.style.background="transparent"},children:[m.jsx(Th,{className:"w-4 h-4"}),m.jsx("span",{className:"hidden lg:block",children:"Logout"})]})]}),m.jsx("button",{onClick:()=>t(!e),className:"md:hidden p-2 rounded-lg text-white/70 hover:text-white hover:bg-white/10 transition-all duration-300",children:e?m.jsx(_h,{className:"w-6 h-6"}):m.jsx(hk,{className:"w-6 h-6"})})]}),e&&m.jsx(O.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},className:"md:hidden py-4 border-t border-white/10",children:m.jsxs("div",{className:"space-y-2",children:[P.map(E=>{var X,te,G,be;const W=C.pathname===E.href;return m.jsxs(zi,{to:E.href,onClick:()=>t(!1),className:Dh("flex items-center space-x-3 px-4 py-3 rounded-xl transition-all duration-300",W?"text-white":"text-white/60 hover:text-white hover:bg-white/5"),style:W?{background:`linear-gradient(135deg, ${((X=T.cssVars)==null?void 0:X.primary)||"#1db954"}15 0%, ${((te=T.cssVars)==null?void 0:te.secondary)||"#1ed760"}10 100%)`,border:`1px solid ${((G=T.cssVars)==null?void 0:G.primary)||"#1db954"}30`}:{},children:[m.jsx(E.icon,{className:"w-5 h-5",style:{color:W?(be=T.cssVars)==null?void 0:be.primary:void 0}}),m.jsx("span",{className:"font-medium",children:E.name})]},E.name)}),m.jsxs("div",{className:"pt-4 border-t border-white/10",children:[f&&m.jsxs("div",{className:"flex items-center space-x-3 px-4 py-2 text-sm text-white/70",children:[m.jsx(Ss,{className:"w-4 h-4"}),m.jsxs("span",{children:["Connected with ",(A=f.user)==null?void 0:A.display_name]})]}),m.jsxs("button",{onClick:()=>{r(!0),t(!1)},className:"w-full flex items-center space-x-3 px-4 py-3 rounded-xl text-white/60 hover:text-white transition-all duration-300",style:{color:(q=T.cssVars)==null?void 0:q.primary},onMouseEnter:E=>{E.currentTarget.style.background="rgba(255, 255, 255, 0.05)"},onMouseLeave:E=>{E.currentTarget.style.background="transparent"},children:[m.jsx(Mh,{className:"w-5 h-5"}),m.jsx("span",{className:"font-medium",children:"Settings"})]}),m.jsxs("button",{onClick:j,className:"w-full flex items-center space-x-3 px-4 py-3 rounded-xl text-white/60 hover:text-white transition-all duration-300",onMouseEnter:E=>{E.currentTarget.style.background="rgba(239, 68, 68, 0.1)"},onMouseLeave:E=>{E.currentTarget.style.background="transparent"},children:[m.jsx(Th,{className:"w-5 h-5"}),m.jsx("span",{className:"font-medium",children:"Logout"})]})]})]})})]}),n&&m.jsxs(m.Fragment,{children:[m.jsx(O.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 bg-black/50 backdrop-blur-md z-40",onClick:()=>r(!1)}),m.jsxs(O.div,{initial:{opacity:0,scale:.8,y:30},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.8,y:30},className:"fixed z-50 overflow-hidden",style:{left:s.x,top:s.y,width:Math.min(600,window.innerWidth-40),height:Math.min(window.innerHeight*.9,800),background:"linear-gradient(135deg, rgba(0,0,0,0.9) 0%, rgba(20,20,20,0.95) 50%, rgba(0,0,0,0.9) 100%)",backdropFilter:"blur(24px) saturate(180%)",WebkitBackdropFilter:"blur(24px) saturate(180%)",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"16px",boxShadow:"0 25px 50px rgba(0,0,0,0.5)",cursor:o?"grabbing":"default"},children:[m.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-white/20 cursor-grab active:cursor-grabbing select-none",onMouseDown:z,style:{background:"linear-gradient(135deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.02) 100%)"},children:[m.jsxs("div",{className:"flex items-center space-x-3",children:[m.jsxs("div",{className:"flex space-x-2",children:[m.jsx("div",{className:"w-3 h-3 rounded-full bg-red-500"}),m.jsx("div",{className:"w-3 h-3 rounded-full bg-yellow-500"}),m.jsx("div",{className:"w-3 h-3 rounded-full bg-green-500"})]}),m.jsx("h2",{className:"text-lg font-semibold text-white",children:"Settings"})]}),m.jsx("button",{onClick:()=>r(!1),className:"text-white/70 hover:text-white hover:bg-white/10 p-2 rounded-lg transition-all duration-200",children:m.jsx(_h,{className:"w-5 h-5"})})]}),m.jsx("div",{className:"overflow-y-auto p-4 sm:p-6",style:{height:"calc(100% - 60px)"},children:m.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[(d==null?void 0:d.user)&&m.jsxs("div",{children:[m.jsx("h3",{className:"text-lg font-semibold text-white mb-4 drop-shadow-md",children:"Your Account"}),m.jsxs("div",{className:"rounded-xl p-4 border border-white/20 transition-all duration-300 hover:border-white/30 hover:shadow-lg hover:shadow-white/5",style:{background:"linear-gradient(135deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.02) 100%)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)"},onMouseEnter:E=>{E.currentTarget.style.background="linear-gradient(135deg, rgba(255,255,255,0.08) 0%, rgba(255,255,255,0.04) 100%)"},onMouseLeave:E=>{E.currentTarget.style.background="linear-gradient(135deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.02) 100%)"},children:[m.jsx("div",{className:"text-sm text-white/70 mb-2 font-medium",children:"Spotify ID"}),m.jsx("div",{className:"text-white font-mono text-sm break-all rounded-lg p-3 mb-3",style:{background:"rgba(0,0,0,0.4)",border:"1px solid rgba(255,255,255,0.1)"},children:d.user.id}),m.jsxs("div",{className:"text-sm text-white/80",children:["Display Name: ",m.jsx("span",{className:"text-white font-medium",children:d.user.display_name})]})]})]}),m.jsxs("div",{children:[m.jsx("h3",{className:"text-lg font-semibold text-white mb-4 drop-shadow-md",children:"Partner"}),f?m.jsx("div",{className:"rounded-xl p-4 border border-white/20 transition-all duration-300 hover:border-white/30 hover:shadow-lg hover:shadow-white/5",style:{background:"linear-gradient(135deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.02) 100%)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)"},onMouseEnter:E=>{E.currentTarget.style.background="linear-gradient(135deg, rgba(255,255,255,0.08) 0%, rgba(255,255,255,0.04) 100%)"},onMouseLeave:E=>{E.currentTarget.style.background="linear-gradient(135deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.02) 100%)"},children:m.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between space-y-3 sm:space-y-0",children:[m.jsxs("div",{className:"flex items-center space-x-3 sm:space-x-4",children:[m.jsx("div",{className:"w-10 h-10 sm:w-12 sm:h-12 bg-gradient-to-br from-purple-500 to-pink-500 rounded-full flex items-center justify-center shadow-lg",children:m.jsx(Ss,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),m.jsxs("div",{className:"flex-1 min-w-0",children:[m.jsx("div",{className:"text-white font-semibold text-base sm:text-lg truncate",children:(_=f.user)==null?void 0:_.display_name}),m.jsx("div",{className:"text-xs text-white/70 break-all rounded px-2 py-1 mt-1 inline-block",style:{background:"rgba(0,0,0,0.3)",border:"1px solid rgba(255,255,255,0.1)"},children:(N=f.user)==null?void 0:N.id}),m.jsx("div",{className:"text-sm text-green-400 font-medium mt-2",children:"✓ Connected"})]})]}),m.jsxs("button",{onClick:D,disabled:b,className:"flex items-center space-x-2 p-2 sm:p-3 text-red-400 hover:text-red-300 rounded-xl transition-all duration-200 disabled:opacity-50 self-start sm:self-auto",style:{background:"rgba(239, 68, 68, 0.1)"},onMouseEnter:E=>{E.currentTarget.style.background="rgba(239, 68, 68, 0.2)"},onMouseLeave:E=>{E.currentTarget.style.background="rgba(239, 68, 68, 0.1)"},children:[m.jsx(Wg,{className:"w-4 h-4 sm:w-5 sm:h-5"}),m.jsx("span",{className:"text-sm sm:hidden",children:"Remove"})]})]})}):m.jsxs("div",{className:"rounded-xl p-4 border border-white/20 space-y-4 transition-all duration-300 hover:border-white/30 hover:shadow-lg hover:shadow-white/5",style:{background:"linear-gradient(135deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.02) 100%)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)"},onMouseEnter:E=>{E.currentTarget.style.background="linear-gradient(135deg, rgba(255,255,255,0.08) 0%, rgba(255,255,255,0.04) 100%)"},onMouseLeave:E=>{E.currentTarget.style.background="linear-gradient(135deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.02) 100%)"},children:[m.jsxs("div",{children:[m.jsx("label",{className:"text-sm text-white/70 mb-2 block font-medium",children:"Partner Spotify ID"}),m.jsx("input",{value:x,onChange:E=>v(E.target.value),placeholder:"Enter partner's Spotify ID...",className:"w-full text-white text-sm px-4 py-3 rounded-xl placeholder-white/50 border focus:outline-none transition-all",style:{background:"rgba(0,0,0,0.4)",border:"1px solid rgba(255,255,255,0.2)"},onFocus:E=>{E.target.style.border="1px solid rgba(255,255,255,0.4)"},onBlur:E=>{E.target.style.border="1px solid rgba(255,255,255,0.2)"}})]}),m.jsx("button",{disabled:y||!x,onClick:async()=>{var E;if(!(!((E=d==null?void 0:d.user)!=null&&E.id)||!x)){w(!0);try{await Pt("/partners/request",{toUid:x}),v("")}finally{w(!1)}}},className:"w-full text-white px-4 py-3 rounded-xl text-sm disabled:opacity-50 transition-all duration-200 font-medium",style:{background:`linear-gradient(135deg, ${((F=T.cssVars)==null?void 0:F.primary)||"#1db954"} 0%, ${((L=T.cssVars)==null?void 0:L.secondary)||"#1ed760"} 100%)`},onMouseEnter:E=>{var W;E.currentTarget.style.transform="translateY(-1px)",E.currentTarget.style.boxShadow=`0 8px 25px ${((W=T.cssVars)==null?void 0:W.primary)||"#1db954"}40`},onMouseLeave:E=>{E.currentTarget.style.transform="translateY(0)",E.currentTarget.style.boxShadow="none"},children:y?"Sending...":"Send Partner Request"})]})]}),m.jsxs("div",{children:[m.jsx("h3",{className:"text-lg font-semibold text-white mb-4 drop-shadow-md",children:"Color Theme"}),m.jsx("div",{className:"rounded-xl p-4 border border-white/20 transition-all duration-300 hover:border-white/30 hover:shadow-lg hover:shadow-white/5",style:{background:"linear-gradient(135deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.02) 100%)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)"},onMouseEnter:E=>{E.currentTarget.style.background="linear-gradient(135deg, rgba(255,255,255,0.08) 0%, rgba(255,255,255,0.04) 100%)"},onMouseLeave:E=>{E.currentTarget.style.background="linear-gradient(135deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.02) 100%)"},children:m.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 sm:gap-3",children:[{name:"Green",value:"green",color:"from-green-500 to-emerald-500"},{name:"Pink",value:"pink",color:"from-pink-500 to-rose-500"},{name:"Blue",value:"blue",color:"from-blue-400 to-cyan-400"},{name:"Red",value:"red",color:"from-red-600 to-red-800"},{name:"Purple",value:"purple",color:"from-purple-500 to-violet-600"},{name:"Yellow",value:"yellow",color:"from-yellow-400 to-orange-500"},{name:"Turquoise",value:"turquoise",color:"from-cyan-400 to-blue-500"}].map(E=>{var W,X,te;return m.jsxs("button",{onClick:()=>p(E.value),className:"flex items-center space-x-3 p-3 rounded-xl border transition-all duration-200",style:{border:h===E.value?`2px solid ${((W=T.cssVars)==null?void 0:W.primary)||"#1db954"}`:"1px solid rgba(255,255,255,0.2)",background:h===E.value?`linear-gradient(135deg, ${((X=T.cssVars)==null?void 0:X.primary)||"#1db954"}15 0%, ${((te=T.cssVars)==null?void 0:te.secondary)||"#1ed760"}10 100%)`:"rgba(255,255,255,0.02)"},onMouseEnter:G=>{var be;h!==E.value?(G.currentTarget.style.background="rgba(255,255,255,0.08)",G.currentTarget.style.border="1px solid rgba(255,255,255,0.4)",G.currentTarget.style.transform="translateY(-2px)",G.currentTarget.style.boxShadow="0 4px 12px rgba(0,0,0,0.3)"):(G.currentTarget.style.transform="translateY(-1px)",G.currentTarget.style.boxShadow=`0 6px 20px ${((be=T.cssVars)==null?void 0:be.primary)||"#1db954"}30`)},onMouseLeave:G=>{h!==E.value?(G.currentTarget.style.background="rgba(255,255,255,0.02)",G.currentTarget.style.border="1px solid rgba(255,255,255,0.2)",G.currentTarget.style.transform="translateY(0)",G.currentTarget.style.boxShadow="none"):(G.currentTarget.style.transform="translateY(0)",G.currentTarget.style.boxShadow="none")},children:[m.jsx("div",{className:`w-5 h-5 rounded-full bg-gradient-to-r ${E.color} shadow-sm`}),m.jsx("span",{className:"text-white text-sm font-medium",children:E.name})]},E.value)})})})]})]})})]})]})]})};var Jg={exports:{}};(function(e){var t=function(){var n="https://api.spotify.com/v1",r=null,s=null,i=function(u,h){return u.abort=h,u},o=function(u,h){var p;if(s!==null){var g=s.defer();u(function(x){g.resolve(x)},function(x){g.reject(x)}),p=g.promise}else window.Promise&&(p=new window.Promise(u));return p?new i(p,h):null},a=function(){var u=Array.prototype.slice.call(arguments),h=u[0],p=u.slice(1);return h=h||{},p.forEach(function(g){for(var x in g)g.hasOwnProperty(x)&&(h[x]=g[x])}),h},l=function(u,h){var p="";for(var g in h)if(h.hasOwnProperty(g)){var x=h[g];p+=encodeURIComponent(g)+"="+encodeURIComponent(x)+"&"}return p.length>0&&(p=p.substring(0,p.length-1),u=u+"?"+p),u},c=function(u,h){var p=new XMLHttpRequest,g=function(x,v){function y(C){x&&x(C),h&&h(null,C)}function w(){v&&v(p),h&&h(p,null)}var b=u.type||"GET";if(p.open(b,l(u.url,u.params)),r&&p.setRequestHeader("Authorization","Bearer "+r),p.onreadystatechange=function(){if(p.readyState===4){var C=null;try{C=p.responseText?JSON.parse(p.responseText):""}catch(P){console.error(P)}p.status>=200&&p.status<300?y(C):w()}},b==="GET")p.send(null);else{var S=null;u.postData&&(u.contentType==="image/jpeg"?(S=u.postData,p.setRequestHeader("Content-Type",u.contentType)):(S=JSON.stringify(u.postData),p.setRequestHeader("Content-Type","application/json"))),p.send(S)}};return h?(g(),null):o(g,function(){p.abort()})},d=function(u,h,p,g){var x={},v=null;typeof h=="object"?(x=h,v=p):typeof h=="function"&&(v=h);var y=u.type||"GET";return y!=="GET"&&u.postData&&!g?u.postData=a(u.postData,x):u.params=a(u.params,x),c(u,v)},f=function(){};return f.prototype={constructor:t},f.prototype.getGeneric=function(u,h){var p={url:u};return d(p,h)},f.prototype.getMe=function(u,h){var p={url:n+"/me"};return d(p,u,h)},f.prototype.getMySavedTracks=function(u,h){var p={url:n+"/me/tracks"};return d(p,u,h)},f.prototype.addToMySavedTracks=function(u,h,p){var g={url:n+"/me/tracks",type:"PUT",postData:u};return d(g,h,p)},f.prototype.removeFromMySavedTracks=function(u,h,p){var g={url:n+"/me/tracks",type:"DELETE",postData:u};return d(g,h,p)},f.prototype.containsMySavedTracks=function(u,h,p){var g={url:n+"/me/tracks/contains",params:{ids:u.join(",")}};return d(g,h,p)},f.prototype.getMySavedAlbums=function(u,h){var p={url:n+"/me/albums"};return d(p,u,h)},f.prototype.addToMySavedAlbums=function(u,h,p){var g={url:n+"/me/albums",type:"PUT",postData:u};return d(g,h,p)},f.prototype.removeFromMySavedAlbums=function(u,h,p){var g={url:n+"/me/albums",type:"DELETE",postData:u};return d(g,h,p)},f.prototype.containsMySavedAlbums=function(u,h,p){var g={url:n+"/me/albums/contains",params:{ids:u.join(",")}};return d(g,h,p)},f.prototype.getMyTopArtists=function(u,h){var p={url:n+"/me/top/artists"};return d(p,u,h)},f.prototype.getMyTopTracks=function(u,h){var p={url:n+"/me/top/tracks"};return d(p,u,h)},f.prototype.getMyRecentlyPlayedTracks=function(u,h){var p={url:n+"/me/player/recently-played"};return d(p,u,h)},f.prototype.followUsers=function(u,h){var p={url:n+"/me/following/",type:"PUT",params:{ids:u.join(","),type:"user"}};return d(p,h)},f.prototype.followArtists=function(u,h){var p={url:n+"/me/following/",type:"PUT",params:{ids:u.join(","),type:"artist"}};return d(p,h)},f.prototype.followPlaylist=function(u,h,p){var g={url:n+"/playlists/"+u+"/followers",type:"PUT",postData:{}};return d(g,h,p)},f.prototype.unfollowUsers=function(u,h){var p={url:n+"/me/following/",type:"DELETE",params:{ids:u.join(","),type:"user"}};return d(p,h)},f.prototype.unfollowArtists=function(u,h){var p={url:n+"/me/following/",type:"DELETE",params:{ids:u.join(","),type:"artist"}};return d(p,h)},f.prototype.unfollowPlaylist=function(u,h){var p={url:n+"/playlists/"+u+"/followers",type:"DELETE"};return d(p,h)},f.prototype.isFollowingUsers=function(u,h){var p={url:n+"/me/following/contains",type:"GET",params:{ids:u.join(","),type:"user"}};return d(p,h)},f.prototype.isFollowingArtists=function(u,h){var p={url:n+"/me/following/contains",type:"GET",params:{ids:u.join(","),type:"artist"}};return d(p,h)},f.prototype.areFollowingPlaylist=function(u,h,p){var g={url:n+"/playlists/"+u+"/followers/contains",type:"GET",params:{ids:h.join(",")}};return d(g,p)},f.prototype.getFollowedArtists=function(u,h){var p={url:n+"/me/following",type:"GET",params:{type:"artist"}};return d(p,u,h)},f.prototype.getUser=function(u,h,p){var g={url:n+"/users/"+encodeURIComponent(u)};return d(g,h,p)},f.prototype.getUserPlaylists=function(u,h,p){var g;return typeof u=="string"?g={url:n+"/users/"+encodeURIComponent(u)+"/playlists"}:(g={url:n+"/me/playlists"},p=h,h=u),d(g,h,p)},f.prototype.getPlaylist=function(u,h,p){var g={url:n+"/playlists/"+u};return d(g,h,p)},f.prototype.getPlaylistTracks=function(u,h,p){var g={url:n+"/playlists/"+u+"/tracks"};return d(g,h,p)},f.prototype.getPlaylistCoverImage=function(u,h){var p={url:n+"/playlists/"+u+"/images"};return d(p,h)},f.prototype.createPlaylist=function(u,h,p){var g={url:n+"/users/"+encodeURIComponent(u)+"/playlists",type:"POST",postData:h};return d(g,h,p)},f.prototype.changePlaylistDetails=function(u,h,p){var g={url:n+"/playlists/"+u,type:"PUT",postData:h};return d(g,h,p)},f.prototype.addTracksToPlaylist=function(u,h,p,g){var x={url:n+"/playlists/"+u+"/tracks",type:"POST",postData:{uris:h}};return d(x,p,g,!0)},f.prototype.replaceTracksInPlaylist=function(u,h,p){var g={url:n+"/playlists/"+u+"/tracks",type:"PUT",postData:{uris:h}};return d(g,{},p)},f.prototype.reorderTracksInPlaylist=function(u,h,p,g,x){var v={url:n+"/playlists/"+u+"/tracks",type:"PUT",postData:{range_start:h,insert_before:p}};return d(v,g,x)},f.prototype.removeTracksFromPlaylist=function(u,h,p){var g=h.map(function(v){return typeof v=="string"?{uri:v}:v}),x={url:n+"/playlists/"+u+"/tracks",type:"DELETE",postData:{tracks:g}};return d(x,{},p)},f.prototype.removeTracksFromPlaylistWithSnapshotId=function(u,h,p,g){var x=h.map(function(y){return typeof y=="string"?{uri:y}:y}),v={url:n+"/playlists/"+u+"/tracks",type:"DELETE",postData:{tracks:x,snapshot_id:p}};return d(v,{},g)},f.prototype.removeTracksFromPlaylistInPositions=function(u,h,p,g){var x={url:n+"/playlists/"+u+"/tracks",type:"DELETE",postData:{positions:h,snapshot_id:p}};return d(x,{},g)},f.prototype.uploadCustomPlaylistCoverImage=function(u,h,p){var g={url:n+"/playlists/"+u+"/images",type:"PUT",postData:h.replace(/^data:image\/jpeg;base64,/,""),contentType:"image/jpeg"};return d(g,{},p)},f.prototype.getAlbum=function(u,h,p){var g={url:n+"/albums/"+u};return d(g,h,p)},f.prototype.getAlbumTracks=function(u,h,p){var g={url:n+"/albums/"+u+"/tracks"};return d(g,h,p)},f.prototype.getAlbums=function(u,h,p){var g={url:n+"/albums/",params:{ids:u.join(",")}};return d(g,h,p)},f.prototype.getTrack=function(u,h,p){var g={};return g.url=n+"/tracks/"+u,d(g,h,p)},f.prototype.getTracks=function(u,h,p){var g={url:n+"/tracks/",params:{ids:u.join(",")}};return d(g,h,p)},f.prototype.getArtist=function(u,h,p){var g={url:n+"/artists/"+u};return d(g,h,p)},f.prototype.getArtists=function(u,h,p){var g={url:n+"/artists/",params:{ids:u.join(",")}};return d(g,h,p)},f.prototype.getArtistAlbums=function(u,h,p){var g={url:n+"/artists/"+u+"/albums"};return d(g,h,p)},f.prototype.getArtistTopTracks=function(u,h,p,g){var x={url:n+"/artists/"+u+"/top-tracks",params:{country:h}};return d(x,p,g)},f.prototype.getArtistRelatedArtists=function(u,h,p){var g={url:n+"/artists/"+u+"/related-artists"};return d(g,h,p)},f.prototype.getFeaturedPlaylists=function(u,h){var p={url:n+"/browse/featured-playlists"};return d(p,u,h)},f.prototype.getNewReleases=function(u,h){var p={url:n+"/browse/new-releases"};return d(p,u,h)},f.prototype.getCategories=function(u,h){var p={url:n+"/browse/categories"};return d(p,u,h)},f.prototype.getCategory=function(u,h,p){var g={url:n+"/browse/categories/"+u};return d(g,h,p)},f.prototype.getCategoryPlaylists=function(u,h,p){var g={url:n+"/browse/categories/"+u+"/playlists"};return d(g,h,p)},f.prototype.search=function(u,h,p,g){var x={url:n+"/search/",params:{q:u,type:h.join(",")}};return d(x,p,g)},f.prototype.searchAlbums=function(u,h,p){return this.search(u,["album"],h,p)},f.prototype.searchArtists=function(u,h,p){return this.search(u,["artist"],h,p)},f.prototype.searchTracks=function(u,h,p){return this.search(u,["track"],h,p)},f.prototype.searchPlaylists=function(u,h,p){return this.search(u,["playlist"],h,p)},f.prototype.searchShows=function(u,h,p){return this.search(u,["show"],h,p)},f.prototype.searchEpisodes=function(u,h,p){return this.search(u,["episode"],h,p)},f.prototype.getAudioFeaturesForTrack=function(u,h){var p={};return p.url=n+"/audio-features/"+u,d(p,{},h)},f.prototype.getAudioFeaturesForTracks=function(u,h){var p={url:n+"/audio-features",params:{ids:u}};return d(p,{},h)},f.prototype.getAudioAnalysisForTrack=function(u,h){var p={};return p.url=n+"/audio-analysis/"+u,d(p,{},h)},f.prototype.getRecommendations=function(u,h){var p={url:n+"/recommendations"};return d(p,u,h)},f.prototype.getAvailableGenreSeeds=function(u){var h={url:n+"/recommendations/available-genre-seeds"};return d(h,{},u)},f.prototype.getMyDevices=function(u){var h={url:n+"/me/player/devices"};return d(h,{},u)},f.prototype.getMyCurrentPlaybackState=function(u,h){var p={url:n+"/me/player"};return d(p,u,h)},f.prototype.getMyCurrentPlayingTrack=function(u,h){var p={url:n+"/me/player/currently-playing"};return d(p,u,h)},f.prototype.transferMyPlayback=function(u,h,p){var g=h||{};g.device_ids=u;var x={type:"PUT",url:n+"/me/player",postData:g};return d(x,h,p)},f.prototype.play=function(u,h){u=u||{};var p="device_id"in u?{device_id:u.device_id}:null,g={};["context_uri","uris","offset","position_ms"].forEach(function(y){y in u&&(g[y]=u[y])});var x={type:"PUT",url:n+"/me/player/play",params:p,postData:g},v=typeof u=="function"?u:{};return d(x,v,h)},f.prototype.queue=function(u,h,p){h=h||{};var g="device_id"in h?{uri:u,device_id:h.device_id}:{uri:u},x={type:"POST",url:n+"/me/player/queue",params:g};return d(x,h,p)},f.prototype.pause=function(u,h){u=u||{};var p="device_id"in u?{device_id:u.device_id}:null,g={type:"PUT",url:n+"/me/player/pause",params:p};return d(g,u,h)},f.prototype.skipToNext=function(u,h){u=u||{};var p="device_id"in u?{device_id:u.device_id}:null,g={type:"POST",url:n+"/me/player/next",params:p};return d(g,u,h)},f.prototype.skipToPrevious=function(u,h){u=u||{};var p="device_id"in u?{device_id:u.device_id}:null,g={type:"POST",url:n+"/me/player/previous",params:p};return d(g,u,h)},f.prototype.seek=function(u,h,p){h=h||{};var g={position_ms:u};"device_id"in h&&(g.device_id=h.device_id);var x={type:"PUT",url:n+"/me/player/seek",params:g};return d(x,h,p)},f.prototype.setRepeat=function(u,h,p){h=h||{};var g={state:u};"device_id"in h&&(g.device_id=h.device_id);var x={type:"PUT",url:n+"/me/player/repeat",params:g};return d(x,h,p)},f.prototype.setVolume=function(u,h,p){h=h||{};var g={volume_percent:u};"device_id"in h&&(g.device_id=h.device_id);var x={type:"PUT",url:n+"/me/player/volume",params:g};return d(x,h,p)},f.prototype.setShuffle=function(u,h,p){h=h||{};var g={state:u};"device_id"in h&&(g.device_id=h.device_id);var x={type:"PUT",url:n+"/me/player/shuffle",params:g};return d(x,h,p)},f.prototype.getShow=function(u,h,p){var g={};return g.url=n+"/shows/"+u,d(g,h,p)},f.prototype.getShows=function(u,h,p){var g={url:n+"/shows/",params:{ids:u.join(",")}};return d(g,h,p)},f.prototype.getMySavedShows=function(u,h){var p={url:n+"/me/shows"};return d(p,u,h)},f.prototype.addToMySavedShows=function(u,h,p){var g={url:n+"/me/shows",type:"PUT",postData:u};return d(g,h,p)},f.prototype.removeFromMySavedShows=function(u,h,p){var g={url:n+"/me/shows",type:"DELETE",postData:u};return d(g,h,p)},f.prototype.containsMySavedShows=function(u,h,p){var g={url:n+"/me/shows/contains",params:{ids:u.join(",")}};return d(g,h,p)},f.prototype.getShowEpisodes=function(u,h,p){var g={url:n+"/shows/"+u+"/episodes"};return d(g,h,p)},f.prototype.getEpisode=function(u,h,p){var g={};return g.url=n+"/episodes/"+u,d(g,h,p)},f.prototype.getEpisodes=function(u,h,p){var g={url:n+"/episodes/",params:{ids:u.join(",")}};return d(g,h,p)},f.prototype.getAccessToken=function(){return r},f.prototype.setAccessToken=function(u){r=u},f.prototype.setPromiseImplementation=function(u){var h=!1;try{var p=new u(function(g){g()});typeof p.then=="function"&&typeof p.catch=="function"&&(h=!0)}catch(g){console.error(g)}if(h)s=u;else throw new Error("Unsupported implementation of Promises/A+")},f}();e.exports=t})(Jg);var e6=Jg.exports;const t6=cu(e6),n6="7cab80d02df44a5bb96725be60a45875",ey="https://159.195.9.107:3443/callback.html";console.log("🔍 Debug - Current redirect URI:",ey);console.log("🔍 Debug - Environment VITE_REDIRECT_URI:","https://159.195.9.107:3443/callback.html");const jo=new t6,r6=()=>{const e=["user-read-private","user-read-email","user-read-recently-played","user-top-read","playlist-read-private","playlist-read-collaborative","playlist-modify-public","playlist-modify-private","user-read-playback-state","user-modify-playback-state","user-read-currently-playing"].join(" "),n=`https://accounts.spotify.com/authorize?${new URLSearchParams({client_id:n6,response_type:"code",redirect_uri:ey,scope:e,show_dialog:"true"}).toString()}`;return console.log("🔍 Debug - Generated Spotify Auth URL:",n),n},s6=async(e,t)=>{jo.setAccessToken(e),await jo.play({uris:[t]})},i6=async e=>{jo.setAccessToken(e),await jo.pause()},o6=()=>{const[e,t]=k.useState(!1),n=()=>{t(!0),window.location.href=r6()},r=[{icon:vt,title:"Last Listened",description:"Discover what your partner is listening to right now and play it instantly"},{icon:Yn,title:"Mixed Playlist",description:"AI-powered playlists that blend your musical tastes perfectly"},{icon:Xe,title:"Memory Lane",description:"Create beautiful musical memories and shared experiences together"}];return m.jsx("div",{className:"min-h-screen flex items-center justify-center px-4 bg-black",children:m.jsxs("div",{className:"max-w-4xl w-full relative",children:[m.jsxs(O.div,{initial:{opacity:0,y:50},animate:{opacity:1,y:0},transition:{duration:.8},className:"text-center mb-12",children:[m.jsx(O.div,{initial:{scale:0},animate:{scale:1},transition:{delay:.2,type:"spring",stiffness:200},className:"w-20 h-20 mx-auto mb-6 bg-gradient-to-br from-pink-500 to-red-500 rounded-full flex items-center justify-center",children:m.jsx(Xe,{className:"w-10 h-10 text-white"})}),m.jsxs("h1",{className:"text-5xl md:text-6xl font-bold mb-4",children:[m.jsx("span",{className:"gradient-text",children:"Our Musical"}),m.jsx("br",{}),m.jsx("span",{className:"text-white",children:"Journey"})]}),m.jsx("p",{className:"text-xl text-white/70 max-w-2xl mx-auto leading-relaxed",children:"A private space where two hearts connect through music. Discover, share, and create beautiful musical memories together."})]}),m.jsx(O.div,{initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{delay:.4,duration:.8},className:"grid md:grid-cols-3 gap-6 mb-12",children:r.map((s,i)=>m.jsxs(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.5+i*.1},whileHover:{y:-8,scale:1.03},className:"glass-bubble rounded-3xl p-8 text-center group cursor-pointer",children:[m.jsx(O.div,{whileHover:{rotate:15,scale:1.15},className:"w-16 h-16 mx-auto mb-6 bg-gradient-to-br from-purple-500/30 via-blue-500/30 to-pink-500/30 rounded-2xl flex items-center justify-center backdrop-blur-sm",children:m.jsx(s.icon,{className:"w-8 h-8 text-white"})}),m.jsx("h3",{className:"text-2xl font-bold text-white mb-3",children:s.title}),m.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:s.description})]},s.title))}),m.jsxs(O.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},transition:{delay:.8,duration:.6},className:"glass-fluid rounded-3xl p-10 max-w-lg mx-auto",children:[m.jsxs("div",{className:"text-center mb-8",children:[m.jsx(O.div,{initial:{scale:0},animate:{scale:1},transition:{delay:1,type:"spring",stiffness:200},className:"w-20 h-20 mx-auto mb-6 bg-gradient-to-br from-purple-500/30 via-blue-500/30 to-pink-500/30 rounded-2xl flex items-center justify-center backdrop-blur-sm",children:m.jsx(Hg,{className:"w-10 h-10 text-white"})}),m.jsx("h2",{className:"text-3xl font-bold text-white mb-3",children:"Begin Your Journey"}),m.jsx("p",{className:"text-white/70 text-lg",children:"Connect your Spotify account to start your musical love story"})]}),m.jsx(O.button,{whileHover:{scale:1.05,boxShadow:"0 15px 40px rgba(147, 51, 234, 0.4)"},whileTap:{scale:.95},onClick:n,disabled:e,className:"w-full bg-gradient-to-r from-purple-600 via-blue-600 to-pink-600 hover:from-purple-700 hover:via-blue-700 hover:to-pink-700 text-white font-bold py-5 px-8 rounded-2xl transition-all duration-300 flex items-center justify-center space-x-3 disabled:opacity-50 shadow-2xl",children:e?m.jsx("div",{className:"w-6 h-6 border-2 border-white border-t-transparent rounded-full animate-spin"}):m.jsxs(m.Fragment,{children:[m.jsx("span",{className:"text-lg",children:"Connect with Spotify"}),m.jsx(lk,{className:"w-6 h-6"})]})}),m.jsx("p",{className:"text-sm text-white/60 text-center mt-6 leading-relaxed",children:"We'll only access your listening history and playlist data to create your personalized musical journey"})]}),m.jsx(O.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1,duration:.6},className:"text-center mt-12",children:m.jsx("p",{className:"text-white/40 text-sm",children:"Made with 💕 for a special someone"})})]})})},a6=()=>{var P,j,D,T,z,V,U,R,Q,A,q,_,N,F,L,E,W,X,te,G,be,ri,Jn,Mn,wt,ta,Dc;const{currentUser:e,partnerUser:t,theme:n}=ae(),r=Vr(n),[s,i]=k.useState([]),[o,a]=k.useState(!1),[l,c]=k.useState(null),[d,f]=k.useState(""),[u,h]=k.useState(!1),[p,g]=k.useState(null),[x,v]=k.useState(null);k.useEffect(()=>{let $;const me=async()=>{var Pe,Te,nt;try{const er=(Pe=e==null?void 0:e.user)==null?void 0:Pe.id;if(er){const na=await se(`/users/${er}/recently-played`),Wr=ae.getState().currentUser;Wr&&ae.getState().setCurrentUser({...Wr,recentlyPlayed:na})}const Rc=(nt=(Te=ae.getState().partnerUser)==null?void 0:Te.user)==null?void 0:nt.id;if(Rc){const na=await se(`/users/${Rc}/recently-played`),Wr=ae.getState().partnerUser;Wr&&ae.getState().setPartnerUser({...Wr,recentlyPlayed:na})}}catch{}$=setTimeout(me,3e4)};return me(),()=>clearTimeout($)},[(P=e==null?void 0:e.user)==null?void 0:P.id,(j=t==null?void 0:t.user)==null?void 0:j.id]),k.useEffect(()=>{(async()=>{var me;if((me=e==null?void 0:e.user)!=null&&me.id){a(!0);try{const Pe=await se(`/partners/requests/${e.user.id}`);i(Pe)}catch{i([])}finally{a(!1)}}})()},[(D=e==null?void 0:e.user)==null?void 0:D.id]),k.useEffect(()=>{let $;const me=async()=>{var Te;if((Te=e==null?void 0:e.user)!=null&&Te.id)try{const nt=await se(`/users/${e.user.id}/status`);c(nt)}catch{}},Pe=()=>{if(!(l!=null&&l.nextSyncAt)){f("");return}const Te=l.nextSyncAt-Date.now();if(Te<=0){f("now");return}const nt=Math.floor(Te/6e4),er=Math.floor(Te%6e4/1e3);f(`${nt}m ${er}s`)};return me(),$=setInterval(()=>{Pe()},1e3),()=>clearInterval($)},[(T=e==null?void 0:e.user)==null?void 0:T.id,l==null?void 0:l.nextSyncAt]),k.useEffect(()=>{let $;const me=async()=>{var Pe,Te;try{const nt=(Pe=e==null?void 0:e.user)==null?void 0:Pe.id;nt&&(g(await se(`/users/${nt}/now-playing`)),(Te=t==null?void 0:t.user)!=null&&Te.id?v(await se(`/users/${t.user.id}/now-playing`)):v(null))}catch{}$=setTimeout(me,8e3)};return me(),()=>clearTimeout($)},[(z=e==null?void 0:e.user)==null?void 0:z.id,(V=t==null?void 0:t.user)==null?void 0:V.id]);const y=async()=>{var $;if(($=e==null?void 0:e.user)!=null&&$.id){h(!0);try{await Pt(`/users/${e.user.id}/sync`);const me=await se(`/users/${e.user.id}/status`);c(me);const[Pe,Te]=await Promise.all([se(`/users/${e.user.id}/recently-played`),se(`/users/${e.user.id}/top-tracks?time_range=short_term`)]),nt=ae.getState().currentUser;nt&&ae.getState().setCurrentUser({...nt,recentlyPlayed:Pe,topTracks:Te.map(er=>er.track)}),he.success("Synced latest data")}catch{he.error("Failed to sync")}finally{h(!1)}}},w=async $=>{await Pt(`/partners/requests/${$}/accept`),i(me=>me.filter(Pe=>Pe.id!==$))},b=async $=>{await Pt(`/partners/requests/${$}/decline`),i(me=>me.filter(Pe=>Pe.id!==$))},S=[{title:"Last Listened",description:"See what your partner is listening to right now",icon:vt,href:"/last-listened",primaryColor:((U=r.cssVars)==null?void 0:U.primary)||"#1db954",secondaryColor:((R=r.cssVars)==null?void 0:R.secondary)||"#1ed760",accentColor:((Q=r.cssVars)==null?void 0:Q.accent)||"#00e676"},{title:"Mixed Playlist",description:"Create AI-powered playlists blending both your tastes",icon:Ug,href:"/mixed-playlist",primaryColor:((A=r.cssVars)==null?void 0:A.secondary)||"#1ed760",secondaryColor:((q=r.cssVars)==null?void 0:q.accent)||"#00e676",accentColor:((_=r.cssVars)==null?void 0:_.primary)||"#1db954"},{title:"Memory Lane",description:"Your shared musical journey and memories",icon:Yn,href:"/memory-lane",primaryColor:((N=r.cssVars)==null?void 0:N.accent)||"#00e676",secondaryColor:((F=r.cssVars)==null?void 0:F.primary)||"#1db954",accentColor:((L=r.cssVars)==null?void 0:L.secondary)||"#1ed760"}],C=()=>{var $;return($=e==null?void 0:e.recentlyPlayed)!=null&&$[0]?Pr(e.recentlyPlayed[0].played_at):null};return m.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8",children:[m.jsxs(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"mb-8",children:[m.jsxs("h1",{className:"text-4xl font-bold text-white mb-2",children:["Welcome back, ",m.jsx("span",{className:"gradient-text",children:(E=e==null?void 0:e.user)==null?void 0:E.display_name})]}),m.jsx("p",{className:"text-white/70 text-lg",children:"Ready to explore your musical connection together?"})]}),m.jsxs(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"grid md:grid-cols-2 gap-6 mb-8",children:[m.jsxs("div",{className:"glass rounded-2xl p-6",children:[m.jsx("div",{className:"text-white/70 mb-2",children:"You"}),p!=null&&p.is_playing&&(p!=null&&p.item)?m.jsxs("div",{className:"flex items-center gap-4",children:[m.jsx("img",{src:((te=(X=(W=p.item.album)==null?void 0:W.images)==null?void 0:X[0])==null?void 0:te.url)||"/placeholder-album.png",className:"w-14 h-14 rounded"}),m.jsxs("div",{className:"min-w-0",children:[m.jsx("div",{className:"text-white font-semibold truncate",children:p.item.name}),m.jsx("div",{className:"text-white/70 text-sm truncate",children:(G=p.item.artists)==null?void 0:G.map($=>$.name).join(", ")})]})]}):m.jsx("div",{className:"text-white/50",children:"Not playing"})]}),m.jsxs("div",{className:"glass rounded-2xl p-6",children:[m.jsx("div",{className:"text-white/70 mb-2",children:"Partner"}),x!=null&&x.is_playing&&(x!=null&&x.item)?m.jsxs("div",{className:"flex items-center gap-4",children:[m.jsx("img",{src:((Jn=(ri=(be=x.item.album)==null?void 0:be.images)==null?void 0:ri[0])==null?void 0:Jn.url)||"/placeholder-album.png",className:"w-14 h-14 rounded"}),m.jsxs("div",{className:"min-w-0",children:[m.jsx("div",{className:"text-white font-semibold truncate",children:x.item.name}),m.jsx("div",{className:"text-white/70 text-sm truncate",children:(Mn=x.item.artists)==null?void 0:Mn.map($=>$.name).join(", ")})]})]}):m.jsx("div",{className:"text-white/50",children:"Not playing"})]})]}),m.jsxs(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.1},className:"mb-8",children:[m.jsxs("div",{className:"flex items-center justify-between mb-4",children:[m.jsx("div",{className:"text-white/70 text-sm",children:(l==null?void 0:l.lastSyncedAt)&&m.jsxs("span",{children:["Last sync: ",new Date(l.lastSyncedAt).toLocaleTimeString()," • Next in: ",d||"—"]})}),m.jsx("button",{onClick:y,disabled:u,className:"bg-white/10 hover:bg-white/20 text-white px-4 py-2 rounded-lg text-sm disabled:opacity-50",children:u?"Refreshing…":"Hard Refresh"})]}),t?m.jsx("div",{className:"glass-bubble rounded-3xl p-8 border border-spotify-green/30 glow",children:m.jsxs("div",{className:"flex items-center space-x-6",children:[m.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-spotify-green to-green-600 rounded-2xl flex items-center justify-center",children:m.jsx(Xe,{className:"w-8 h-8 text-white"})}),m.jsxs("div",{children:[m.jsxs("h3",{className:"text-xl font-semibold text-white",children:["Connected with ",(wt=t.user)==null?void 0:wt.display_name]}),m.jsx("p",{className:"text-white/70",children:"Your musical journey is ready to begin! 💕"})]})]})}):m.jsx("div",{className:"glass-bubble rounded-3xl p-8 border border-orange-500/30",children:m.jsxs("div",{className:"flex items-center space-x-6",children:[m.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-orange-500 to-red-500 rounded-2xl flex items-center justify-center",children:m.jsx(Ac,{className:"w-8 h-8 text-white"})}),m.jsxs("div",{children:[m.jsx("h3",{className:"text-xl font-semibold text-white",children:"Invite your partner"}),m.jsx("p",{className:"text-white/70 mb-2",children:"Ask your partner to search you in the app and send a request."}),o?m.jsx("div",{className:"text-white/60",children:"Loading requests..."}):s.length>0?m.jsx("div",{className:"space-y-3",children:s.map($=>m.jsxs("div",{className:"flex items-center justify-between bg-white/5 rounded-lg p-3",children:[m.jsxs("div",{className:"text-white/80 text-sm",children:["Request from ",$.from_user_id]}),m.jsxs("div",{className:"space-x-2",children:[m.jsx("button",{onClick:()=>w($.id),className:"bg-spotify-green hover:bg-spotify-green/90 text-white px-3 py-1 rounded-md text-sm",children:"Accept"}),m.jsx("button",{onClick:()=>b($.id),className:"bg-white/10 hover:bg-white/20 text-white px-3 py-1 rounded-md text-sm",children:"Decline"})]})]},$.id))}):m.jsx("div",{className:"text-white/60 text-sm",children:"No incoming requests yet"})]})]})})]}),m.jsxs(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.2},className:"grid grid-cols-1 md:grid-cols-3 gap-6 mb-8",children:[m.jsx("div",{className:"glass-bubble rounded-2xl p-6",children:m.jsxs("div",{className:"flex items-center space-x-4",children:[m.jsx("div",{className:"w-12 h-12 bg-gradient-to-br from-blue-500/30 to-cyan-500/30 rounded-xl flex items-center justify-center",children:m.jsx(Po,{className:"w-6 h-6 text-blue-400"})}),m.jsxs("div",{children:[m.jsx("p",{className:"text-white/70 text-sm",children:"Your last played"}),m.jsx("p",{className:"text-white font-semibold",children:C()||"No recent plays"})]})]})}),m.jsx("div",{className:"glass-bubble rounded-2xl p-6",children:m.jsxs("div",{className:"flex items-center space-x-4",children:[m.jsx("div",{className:"w-12 h-12 bg-gradient-to-br from-green-500/30 to-emerald-500/30 rounded-xl flex items-center justify-center",children:m.jsx(gk,{className:"w-6 h-6 text-green-400"})}),m.jsxs("div",{children:[m.jsx("p",{className:"text-white/70 text-sm",children:"Top tracks analyzed"}),m.jsxs("p",{className:"text-white font-semibold",children:[((ta=e==null?void 0:e.topTracks)==null?void 0:ta.length)||0," songs"]})]})]})}),m.jsx("div",{className:"glass-bubble rounded-2xl p-6",children:m.jsxs("div",{className:"flex items-center space-x-4",children:[m.jsx("div",{className:"w-12 h-12 bg-gradient-to-br from-purple-500/30 to-pink-500/30 rounded-xl flex items-center justify-center",children:m.jsx(Ss,{className:"w-6 h-6 text-purple-400"})}),m.jsxs("div",{children:[m.jsx("p",{className:"text-white/70 text-sm",children:"Recently played"}),m.jsxs("p",{className:"text-white font-semibold",children:[((Dc=e==null?void 0:e.recentlyPlayed)==null?void 0:Dc.length)||0," tracks"]})]})]})})]}),m.jsx(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},className:"grid md:grid-cols-3 gap-6",children:S.map(($,me)=>m.jsx(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.4+me*.1},whileHover:{y:-5,scale:1.02},children:m.jsx(zi,{to:$.href,children:m.jsxs("div",{className:`glass rounded-2xl p-6 h-full border ${$.borderColor} group cursor-pointer transition-all duration-300 hover:shadow-xl`,children:[m.jsx("div",{className:"w-12 h-12 rounded-xl flex items-center justify-center mb-4 group-hover:scale-110 transition-transform duration-300",style:{background:`linear-gradient(135deg, ${$.primaryColor}20 0%, ${$.secondaryColor}10 100%)`,border:`1px solid ${$.primaryColor}30`},children:m.jsx($.icon,{className:"w-6 h-6",style:{color:$.primaryColor}})}),m.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:$.title}),m.jsx("p",{className:"text-white/70 text-sm leading-relaxed mb-4",children:$.description}),m.jsx("div",{className:"w-full h-1 rounded-full opacity-0 group-hover:opacity-100 transition-opacity duration-300",style:{background:`linear-gradient(90deg, ${$.primaryColor} 0%, ${$.secondaryColor} 100%)`}})]})})},$.title))}),(e==null?void 0:e.recentlyPlayed)&&e.recentlyPlayed.length>0&&m.jsxs(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.6},className:"mt-8",children:[m.jsx("h2",{className:"text-2xl font-bold text-white mb-4",children:"Your Recent Activity"}),m.jsx("div",{className:"glass rounded-2xl p-6",children:m.jsx("div",{className:"space-y-4",children:e.recentlyPlayed.slice(0,3).map(($,me)=>{var Pe,Te;return m.jsxs(O.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:.7+me*.1},className:"flex items-center space-x-4 p-3 rounded-lg hover:bg-white/5 transition-colors",children:[m.jsx("img",{src:((Pe=$.track.album.images[0])==null?void 0:Pe.url)||"/placeholder-album.png",alt:$.track.album.name,className:"w-12 h-12 rounded-lg object-cover"}),m.jsxs("div",{className:"flex-1",children:[m.jsx("h4",{className:"text-white font-medium",children:$.track.name}),m.jsx("p",{className:"text-white/70 text-sm",children:(Te=$.track.artists[0])==null?void 0:Te.name})]}),m.jsx("div",{className:"text-white/50 text-sm",children:Pr($.played_at)})]},$.track.id)})})})]})]})};let ji=!1;const Rh=()=>{const[e]=Ax(),t=Wo(),{setCurrentUser:n,setPartnerUser:r,currentUser:s}=ae(),[i,o]=k.useState("loading"),[a,l]=k.useState("");k.useEffect(()=>{(async()=>{if(ji){console.log("🔍 CallbackPage - Already processing globally, skipping...");return}ji=!0,console.log("🔍 CallbackPage - Global processing flag set to TRUE");try{const u=e.get("code"),h=e.get("error");if(console.log("🔍 CallbackPage - Code:",u),console.log("🔍 CallbackPage - Error:",h),h)throw new Error("Spotify authorization was denied");if(!u)throw new Error("No authorization code received");l("Exchanging authorization code..."),console.log("🔍 CallbackPage - Exchanging code with backend...");const p=await pb("/auth/exchange",{code:u});l("Syncing your music data..."),await Pt(`/users/${p.uid}/sync`,void 0,p.token),l("Loading your profile...");const[g,x,v]=await Promise.all([se(`/users/${p.uid}`),se(`/users/${p.uid}/recently-played`),se(`/users/${p.uid}/top-tracks?time_range=short_term`)]),y={user:g,accessToken:p.access_token,refreshToken:p.refresh_token,isAuthenticated:!0,recentlyPlayed:x,topTracks:v.map(w=>w.track),topArtists:[],jwt:p.token};localStorage.setItem("spotify-user",JSON.stringify(y)),s?(r(y),localStorage.setItem("spotify-partner",JSON.stringify(y)),l("Partner connected! Your musical journey begins...")):(n(y),l("Welcome! Setting up your musical journey...")),o("success"),he.success(s?"Partner connected successfully!":"Successfully connected to Spotify!",{duration:3e3}),setTimeout(()=>{t("/"),setTimeout(()=>{ji=!1,console.log("🔍 CallbackPage - Global processing flag set to FALSE (after success)")},1e3)},2e3)}catch(u){console.error("🔍 CallbackPage - ERROR:",u),console.error("🔍 CallbackPage - Error details:",{message:u instanceof Error?u.message:"Unknown error",stack:u instanceof Error?u.stack:void 0}),o("error"),l(u instanceof Error?u.message:"An unexpected error occurred"),he.error("Failed to connect to Spotify. Please try again."),setTimeout(()=>{t("/"),setTimeout(()=>{ji=!1,console.log("🔍 CallbackPage - Global processing flag set to FALSE (after error)")},1e3)},3e3)}})()},[e,t,n,r,s]);const c=()=>{switch(i){case"loading":return m.jsx(fk,{className:"w-12 h-12 text-spotify-green animate-spin"});case"success":return m.jsx(dk,{className:"w-12 h-12 text-green-400"});case"error":return m.jsx(xk,{className:"w-12 h-12 text-red-400"})}},d=()=>{switch(i){case"loading":return"border-spotify-green/30";case"success":return"border-green-400/30";case"error":return"border-red-400/30"}};return m.jsx("div",{className:"min-h-screen flex items-center justify-center px-4 bg-black",children:m.jsxs(O.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},className:"glass-fluid rounded-3xl p-10 max-w-md w-full text-center",children:[m.jsx(O.div,{initial:{scale:0},animate:{scale:1},transition:{delay:.2,type:"spring",stiffness:200},className:`w-20 h-20 mx-auto mb-6 rounded-full border-2 flex items-center justify-center ${d()}`,children:c()}),m.jsxs(O.h2,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},className:"text-2xl font-bold text-white mb-4",children:[i==="loading"&&"Connecting...",i==="success"&&"Success!",i==="error"&&"Connection Failed"]}),m.jsx(O.p,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.4},className:"text-white/70 mb-6",children:a}),i==="loading"&&m.jsx(O.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.5},className:"w-full bg-white/10 rounded-full h-2 mb-4",children:m.jsx(O.div,{className:"bg-spotify-green h-2 rounded-full",initial:{width:0},animate:{width:"100%"},transition:{duration:3,ease:"easeInOut"}})}),i==="error"&&m.jsx(O.button,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.5},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>t("/"),className:"bg-spotify-green hover:bg-spotify-green/90 text-white font-semibold py-3 px-6 rounded-lg transition-all duration-300",children:"Try Again"}),i==="success"&&m.jsx(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.5},className:"text-spotify-green text-sm",children:"Redirecting you to your musical journey..."})]})})},l6=()=>{var g,x,v;const{currentUser:e,partnerUser:t,currentTrack:n,isPlaying:r,setCurrentTrack:s,setIsPlaying:i,theme:o}=ae(),a=Vr(o),[l,c]=k.useState(!1),[d,f]=k.useState(null),u=k.useMemo(()=>{const y=((e==null?void 0:e.recentlyPlayed)||[]).map(P=>({who:"you",played_at:new Date(P.played_at).getTime(),track:P.track,key:`you-${P.track.id}-${P.played_at}`})),w=((t==null?void 0:t.recentlyPlayed)||[]).map(P=>({who:"partner",played_at:new Date(P.played_at).getTime(),track:P.track,key:`partner-${P.track.id}-${P.played_at}`})),b=[...y,...w].sort((P,j)=>j.played_at-P.played_at).slice(0,30),S=new Set,C=new Set;return b.forEach(P=>{const j=P.track.id;S.has(j)?C.add(j):S.add(j)}),{items:b,overlaps:C}},[e==null?void 0:e.recentlyPlayed,t==null?void 0:t.recentlyPlayed]),h=async(y,w)=>{var b,S;if(!(e!=null&&e.accessToken)){he.error("Not authenticated with Spotify");return}try{c(!0),f(w),r&&d===w?(await i6(e.accessToken),i(!1),s(null),f(null)):(await s6(e.accessToken,y),i(!0),s(((S=(b=e.recentlyPlayed)==null?void 0:b.find(C=>C.track.id===w))==null?void 0:S.track)||null)),he.success(r&&d===w?"Paused":"Now playing")}catch(C){console.error("Playback error:",C),he.error("Failed to play track. Make sure Spotify is open on your device.")}finally{c(!1)}},p=({user:y,title:w,isPartner:b=!1})=>{var C,P,j,D,T;if(!((C=y==null?void 0:y.recentlyPlayed)!=null&&C.length))return m.jsxs(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"glass rounded-2xl p-8 text-center",children:[m.jsx(vt,{className:"w-16 h-16 mx-auto mb-4 text-white/30"}),m.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:"No recent activity"}),m.jsxs("p",{className:"text-white/70",children:[b?"Your partner":"You"," haven't played any music recently"]})]});const S=y.recentlyPlayed[0];return m.jsxs(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"glass rounded-2xl p-6",children:[m.jsxs("div",{className:"flex items-center space-x-4 mb-6",children:[m.jsx("div",{className:`w-12 h-12 rounded-full flex items-center justify-center ${b?"bg-gradient-to-br from-pink-500 to-purple-600":"bg-gradient-to-br from-blue-500 to-cyan-600"}`,children:m.jsx(Ss,{className:"w-6 h-6 text-white"})}),m.jsxs("div",{children:[m.jsx("h2",{className:"text-2xl font-bold text-white",children:w}),m.jsxs("p",{className:"text-white/70",children:["Last played: ",Pr(S.played_at)]})]})]}),m.jsx(O.div,{whileHover:{scale:1.02},className:"bg-white/5 rounded-xl p-6 mb-6 border border-white/10",children:m.jsxs("div",{className:"flex items-center space-x-6",children:[m.jsxs("div",{className:"relative",children:[m.jsx("img",{src:((P=S.track.album.images[0])==null?void 0:P.url)||"/placeholder-album.png",alt:S.track.album.name,className:"w-20 h-20 rounded-lg object-cover"}),r&&d===S.track.id&&m.jsx("div",{className:"absolute inset-0 rounded-lg flex items-center justify-center",style:{backgroundColor:`${((j=a.cssVars)==null?void 0:j.primary)||"#1db954"}20`},children:m.jsx(yk,{className:"w-6 h-6",style:{color:((D=a.cssVars)==null?void 0:D.primary)||"#1db954"}})})]}),m.jsxs("div",{className:"flex-1",children:[m.jsx("h3",{className:"text-xl font-semibold text-white mb-1",children:S.track.name}),m.jsx("p",{className:"text-white/70 mb-2",children:S.track.artists.map(z=>z.name).join(", ")}),m.jsxs("p",{className:"text-white/50 text-sm",children:[S.track.album.name," • ",Zg(S.track.duration_ms)]})]}),m.jsxs("div",{className:"flex items-center space-x-3",children:[m.jsx("button",{onClick:()=>h(S.track.external_urls.spotify,S.track.id),disabled:l,className:"w-12 h-12 rounded-full flex items-center justify-center transition-all duration-300 text-white disabled:opacity-50",style:{backgroundColor:r&&d===S.track.id?"#ef4444":((T=a.cssVars)==null?void 0:T.primary)||"#1db954"},onMouseEnter:z=>{l||(z.currentTarget.style.opacity="0.9")},onMouseLeave:z=>{l||(z.currentTarget.style.opacity="1")},children:l&&d===S.track.id?m.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"}):r&&d===S.track.id?m.jsx(pk,{className:"w-5 h-5"}):m.jsx(Nh,{className:"w-5 h-5 ml-0.5"})}),m.jsx("a",{href:S.track.external_urls.spotify,target:"_blank",rel:"noopener noreferrer",className:"w-10 h-10 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center transition-colors",children:m.jsx(Bg,{className:"w-4 h-4 text-white"})})]})]})}),m.jsxs("div",{children:[m.jsxs("h3",{className:"text-lg font-semibold text-white mb-4 flex items-center space-x-2",children:[m.jsx(Po,{className:"w-5 h-5"}),m.jsx("span",{children:"Recent History"})]}),m.jsx("div",{className:"space-y-3",children:y.recentlyPlayed.slice(0,5).map((z,V)=>{var U,R,Q;return m.jsxs(O.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:V*.1},className:"flex items-center space-x-4 p-3 rounded-lg hover:bg-white/5 transition-colors group",children:[m.jsx("img",{src:((U=z.track.album.images[0])==null?void 0:U.url)||"/placeholder-album.png",alt:z.track.album.name,className:"w-12 h-12 rounded-lg object-cover"}),m.jsxs("div",{className:"flex-1",children:[m.jsx("h4",{className:"text-white font-medium group-hover:text-spotify-green transition-colors",children:z.track.name}),m.jsx("p",{className:"text-white/70 text-sm",children:(R=z.track.artists[0])==null?void 0:R.name})]}),m.jsx("div",{className:"text-white/50 text-sm",children:Pr(z.played_at)}),m.jsx("button",{onClick:()=>h(z.track.external_urls.spotify,z.track.id),disabled:l,className:"opacity-0 group-hover:opacity-100 w-8 h-8 rounded-full flex items-center justify-center transition-all disabled:opacity-50",style:{backgroundColor:((Q=a.cssVars)==null?void 0:Q.primary)||"#1db954"},onMouseEnter:A=>{l||(A.currentTarget.style.opacity="0.9")},onMouseLeave:A=>{l||(A.currentTarget.style.opacity="1")},children:m.jsx(Nh,{className:"w-4 h-4 text-white ml-0.5"})})]},z.track.id)})})]})]})};return m.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8",children:[m.jsxs(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"mb-8",children:[m.jsxs("h1",{className:"text-4xl font-bold text-white mb-2 flex items-center space-x-3",children:[m.jsx(Xe,{className:"w-10 h-10",style:{color:((g=a.cssVars)==null?void 0:g.primary)||"#1db954"}}),m.jsx("span",{children:"What's Playing"})]}),m.jsx("p",{className:"text-white/70 text-lg",children:"Discover what you and your partner are listening to right now"})]}),m.jsxs("div",{className:"grid lg:grid-cols-2 gap-8",children:[e&&m.jsx(p,{user:e,title:`${(x=e.user)==null?void 0:x.display_name}'s Music`,isPartner:!1}),t&&m.jsx(p,{user:t,title:`${(v=t.user)==null?void 0:v.display_name}'s Music`,isPartner:!0}),!t&&m.jsxs(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"glass rounded-2xl p-8 text-center",children:[m.jsx(Xe,{className:"w-16 h-16 mx-auto mb-4 text-pink-400"}),m.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:"Waiting for your partner"}),m.jsx("p",{className:"text-white/70 mb-4",children:"Invite your partner to connect their Spotify account to see their music"}),m.jsx("button",{className:"bg-pink-500 hover:bg-pink-600 text-white px-6 py-3 rounded-lg transition-colors",children:"Send Invitation"})]})]}),e&&t&&m.jsxs(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"glass rounded-2xl p-8 mt-8",children:[m.jsxs("h3",{className:"text-lg font-semibold text-white mb-4 flex items-center space-x-2",children:[m.jsx(Po,{className:"w-5 h-5"}),m.jsx("span",{children:"Shared Timeline"})]}),m.jsx("div",{className:"space-y-3",children:u.items.map(y=>{var w,b,S,C,P;return m.jsxs("div",{className:"flex items-center gap-4 p-3 rounded-lg bg-white/5",children:[m.jsx("img",{src:((S=(b=(w=y.track.album)==null?void 0:w.images)==null?void 0:b[0])==null?void 0:S.url)||"/placeholder-album.png",alt:((C=y.track.album)==null?void 0:C.name)||"Album",className:"w-10 h-10 rounded"}),m.jsxs("div",{className:"flex-1 min-w-0",children:[m.jsxs("div",{className:"flex items-center gap-2",children:[m.jsx("span",{className:"text-white font-medium truncate",children:y.track.name}),u.overlaps.has(y.track.id)&&m.jsx("span",{className:"text-pink-400 text-sm",children:"💕"})]}),m.jsx("div",{className:"text-white/70 text-sm truncate",children:(P=y.track.artists)==null?void 0:P.map(j=>j.name).join(", ")})]}),m.jsxs("div",{className:"text-white/50 text-xs w-32 text-right",children:[Pr(new Date(y.played_at).toISOString()),m.jsx("div",{className:"text-white/60",children:y.who==="you"?"You":"Partner"})]})]},y.key)})})]})]})},u6=({imageUrl:e,alt:t,fallbackGradient:n})=>{const[r,s]=k.useState(null),[i,o]=k.useState(!0),[a,l]=k.useState(!1);return k.useEffect(()=>{e.startsWith("http")?(s(e),o(!1)):(async()=>{try{const d=await fetch(`${Br}${e}`);if(d.ok){const f=await d.json();s(f.dataUrl)}else l(!0)}catch{l(!0)}finally{o(!1)}})()},[e]),i?m.jsx("div",{className:"w-full h-full bg-gradient-to-br from-gray-500 to-gray-600 flex items-center justify-center",children:m.jsx(vt,{className:"w-8 h-8 text-white animate-pulse"})}):a||!r?m.jsx("div",{className:`w-full h-full flex items-center justify-center ${n}`,children:m.jsx(vt,{className:"w-8 h-8 text-white"})}):m.jsx("img",{src:r,alt:t,className:"w-full h-full object-cover",onError:()=>l(!0)})};function Vh(e){var r;const t=(r=e.vibe)==null?void 0:r.toLowerCase(),n=e.genres||[];if(t)switch(t){case"energetic":return"bg-gradient-to-br from-red-500 to-orange-500";case"chill":return"bg-gradient-to-br from-blue-500 to-teal-500";case"romantic":return"bg-gradient-to-br from-pink-500 to-rose-500";case"party":return"bg-gradient-to-br from-purple-500 to-pink-500";case"workout":return"bg-gradient-to-br from-green-500 to-lime-500";case"study":return"bg-gradient-to-br from-indigo-500 to-blue-500";case"sad":return"bg-gradient-to-br from-gray-500 to-slate-500";case"happy":return"bg-gradient-to-br from-yellow-500 to-orange-500"}if(n.length>0)switch(n[0].toLowerCase()){case"pop":return"bg-gradient-to-br from-pink-500 to-purple-500";case"rock":return"bg-gradient-to-br from-red-500 to-black";case"hip-hop":case"rap":return"bg-gradient-to-br from-yellow-500 to-red-500";case"electronic":case"edm":return"bg-gradient-to-br from-cyan-500 to-blue-500";case"jazz":return"bg-gradient-to-br from-amber-500 to-orange-500";case"classical":return"bg-gradient-to-br from-slate-500 to-gray-600";case"country":return"bg-gradient-to-br from-green-600 to-yellow-600";case"r&b":return"bg-gradient-to-br from-purple-600 to-pink-600";case"indie":return"bg-gradient-to-br from-teal-500 to-green-500";case"alternative":return"bg-gradient-to-br from-gray-600 to-purple-600"}return"bg-gradient-to-br from-purple-500 to-pink-500"}const c6=()=>{var V,U,R,Q;const{currentUser:e,partnerUser:t,mixedPlaylists:n,addMixedPlaylist:r,removeMixedPlaylist:s,setMixedPlaylists:i,theme:o}=ae(),a=Vr(o),[l,c]=k.useState(!1),[d,f]=k.useState(!1),[u,h]=k.useState(null),[p,g]=k.useState(""),[x,v]=k.useState(""),[y,w]=k.useState(!0),[b,S]=k.useState(!1),C=x.split(",").map(A=>A.trim()).filter(A=>A.length>0);k.useEffect(()=>{(async()=>{if(e!=null&&e.jwt)try{console.log("Loading playlists from database...");const q=await se("/playlists/mixed",e.jwt);console.log("Loaded playlists:",q.playlists);const _=q.playlists.map(N=>{var L;const F=N.track_uris?JSON.parse(N.track_uris):[];return console.log("Processing playlist:",N.name,"track_uris count:",F.length,"raw track_uris:",((L=N.track_uris)==null?void 0:L.substring(0,100))+"..."),{id:N.id,name:N.name,description:N.description,tracks:[],createdAt:new Date(N.created_at),createdBy:"AI Magic ✨",spotifyId:N.creator_spotify_id,spotifyUrl:N.creator_spotify_url,partnerSpotifyId:N.partner_spotify_id,partnerSpotifyUrl:N.partner_spotify_url,vibe:N.vibe,genres:N.genres?JSON.parse(N.genres):[],trackUris:F,spotifyImageUrl:N.creator_spotify_image_url}});i(_)}catch(q){console.error("Failed to load playlists:",q)}})()},[e==null?void 0:e.jwt]);const P=async()=>{var A,q,_,N,F,L;if(!u||!((A=e==null?void 0:e.user)!=null&&A.id)){he.error("Unable to create playlist");return}if(!(e!=null&&e.jwt)){he.error("Please login again");return}f(!0);try{const E={partnerId:((q=t==null?void 0:t.user)==null?void 0:q.id)||e.user.id,createForBoth:!1,includeKnown:!0,name:u.name,description:u.description},W=await Pt("/playlists/mixed",E,e.jwt);r({...u,spotifyId:(N=(_=W==null?void 0:W.createdFor)==null?void 0:_.creator)==null?void 0:N.playlistId,spotifyUrl:(L=(F=W==null?void 0:W.createdFor)==null?void 0:F.creator)==null?void 0:L.url}),he.success("Playlist created on Spotify!"),h(null)}catch(E){console.error("Spotify playlist creation error:",E),he.error("Failed to create playlist on Spotify")}finally{f(!1)}},j=async()=>{var A,q,_,N;if(!((A=e==null?void 0:e.user)!=null&&A.id)||!((q=t==null?void 0:t.user)!=null&&q.id)){he.error("Missing users");return}if(!(e!=null&&e.jwt)){he.error("Please login again");return}f(!0);try{const F={partnerId:t.user.id,createForBoth:b,includeKnown:y,vibe:p||void 0,genres:C.length?C:void 0,description:(u==null?void 0:u.description)||"An AI-blended mix with fresh recommendations"},L=await Pt("/playlists/mixed",F,e.jwt);b&&L.createdFor.partnerError?he.success("Your playlist created! Partner sync failed: "+L.createdFor.partnerError):b&&L.createdFor.partner?he.success("Enhanced playlist created on both accounts!"):he.success("Enhanced playlist created!");const E={id:L.id,name:L.name,description:F.description,tracks:[],createdAt:new Date,createdBy:"AI Magic ✨",spotifyId:L.createdFor.creator.playlistId,spotifyUrl:L.createdFor.creator.url,partnerSpotifyId:(_=L.createdFor.partner)==null?void 0:_.playlistId,partnerSpotifyUrl:(N=L.createdFor.partner)==null?void 0:N.url,vibe:F.vibe,genres:F.genres||[],trackUris:L.trackUris||[],spotifyImageUrl:L.spotifyImageUrl};r(E),h(null)}catch(F){console.error(F),he.error("Failed to create enhanced playlist")}finally{f(!1)}},D=()=>{u&&(r(u),h(null),he.success("Playlist saved locally!"))},T=({playlist:A,isNew:q=!1})=>{var _;return m.jsxs(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},whileHover:{scale:1.02},className:`glass rounded-2xl p-6 ${q?"border-spotify-green/50":"border-white/10"}`,children:[m.jsxs("div",{className:"flex items-start justify-between mb-4",children:[m.jsxs("div",{className:"flex items-center space-x-4",children:[m.jsxs("div",{className:`w-16 h-16 rounded-xl flex items-center justify-center overflow-hidden ${q?"bg-gradient-to-br from-spotify-green to-green-600":"bg-gradient-to-br from-purple-500 to-pink-500"}`,children:[q?m.jsx(Yn,{className:"w-8 h-8 text-white"}):A.spotifyImageUrl?m.jsx(u6,{imageUrl:A.spotifyImageUrl,alt:A.name,fallbackGradient:Vh(A)}):null,!q&&m.jsx("div",{className:`w-full h-full flex items-center justify-center ${A.spotifyImageUrl?"bg-gradient-to-br from-purple-500 to-pink-500":Vh(A)}`,style:{display:A.spotifyImageUrl?"none":"flex"},children:m.jsx(vt,{className:"w-8 h-8 text-white"})})]}),m.jsxs("div",{children:[m.jsx("h3",{className:"text-xl font-semibold text-white",children:A.name}),m.jsx("p",{className:"text-white/70 text-sm",children:A.description}),m.jsxs("div",{className:"flex flex-wrap gap-1 mt-1 mb-1",children:[A.vibe&&m.jsx("span",{className:"px-2 py-0.5 bg-blue-500/20 text-blue-300 text-xs rounded-full",children:A.vibe}),A.genres&&A.genres.length>0&&A.genres.slice(0,2).map((N,F)=>m.jsx("span",{className:"px-2 py-0.5 bg-green-500/20 text-green-300 text-xs rounded-full",children:N},F))]}),m.jsxs("p",{className:"text-white/50 text-xs",children:["Created ",q?"just now":new Date(A.createdAt).toLocaleDateString()," • ",A.tracks.length||((_=A.trackUris)==null?void 0:_.length)||0," tracks"]})]})]}),m.jsxs("div",{className:"flex items-center space-x-2",children:[A.spotifyUrl&&m.jsx("a",{href:A.spotifyUrl,target:"_blank",rel:"noopener noreferrer",className:"w-8 h-8 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center transition-colors",title:"Open in Spotify",children:m.jsx(Bg,{className:"w-4 h-4 text-white"})}),A.partnerSpotifyUrl&&m.jsx("a",{href:A.partnerSpotifyUrl,target:"_blank",rel:"noopener noreferrer",className:"w-8 h-8 rounded-full bg-pink-500/20 hover:bg-pink-500/30 flex items-center justify-center transition-colors",title:"Partner's playlist in Spotify",children:m.jsx(Xe,{className:"w-4 h-4 text-pink-400"})}),!q&&m.jsx("button",{onClick:async()=>{try{e!=null&&e.jwt&&await mb(`/playlists/mixed/${A.id}`,e.jwt),s(A.id),he.success("Playlist deleted successfully")}catch(N){console.error("Failed to delete playlist:",N),he.error("Failed to delete playlist")}},className:"w-8 h-8 rounded-full bg-red-500/20 hover:bg-red-500/30 flex items-center justify-center transition-colors",children:m.jsx(Wg,{className:"w-4 h-4 text-red-400"})})]})]}),m.jsx("div",{className:"space-y-3 max-h-64 overflow-y-auto",children:A.tracks.length>0?m.jsxs(m.Fragment,{children:[A.tracks.slice(0,5).map((N,F)=>{var L,E,W,X,te,G;return m.jsxs(O.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:F*.1},className:"flex items-center space-x-3 p-2 rounded-lg hover:bg-white/5 transition-colors",children:[m.jsx("img",{src:((W=(E=(L=N.album)==null?void 0:L.images)==null?void 0:E[0])==null?void 0:W.url)||"/placeholder-album.png",alt:((X=N.album)==null?void 0:X.name)||"Unknown Album",className:"w-10 h-10 rounded-lg object-cover"}),m.jsxs("div",{className:"flex-1 min-w-0",children:[m.jsx("h4",{className:"text-white font-medium truncate",children:N.name}),m.jsx("p",{className:"text-white/70 text-sm truncate",children:((G=(te=N.artists)==null?void 0:te[0])==null?void 0:G.name)||"Unknown Artist"})]}),m.jsx("div",{className:"text-white/50 text-sm",children:Zg(N.duration_ms)})]},N.id)}),A.tracks.length>5&&m.jsxs("div",{className:"text-center text-white/50 text-sm py-2",children:["+",A.tracks.length-5," more tracks"]})]}):A.trackUris&&A.trackUris.length>0?m.jsx("div",{className:"text-center py-4"}):m.jsx("div",{className:"text-center text-white/50 text-sm py-4",children:"No tracks available"})}),q&&m.jsxs("div",{className:"flex items-center space-x-3 mt-6 pt-4 border-t border-white/10",children:[m.jsx("button",{onClick:P,disabled:d||b,className:"flex-1 bg-spotify-green hover:bg-spotify-green/90 text-white font-semibold py-3 px-4 rounded-lg transition-colors flex items-center justify-center space-x-2 disabled:opacity-50",children:d?m.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"}):m.jsxs(m.Fragment,{children:[m.jsx(Ac,{className:"w-4 h-4"}),m.jsx("span",{children:b?"Disabled (using Create for both)":"Create on Spotify"})]})}),m.jsx("button",{onClick:D,className:"px-4 py-3 bg-white/10 hover:bg-white/20 text-white rounded-lg transition-colors",children:"Save Locally"})]})]})},z=(e==null?void 0:e.topTracks)&&(t==null?void 0:t.topTracks);return m.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8",children:[m.jsxs(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"mb-8",children:[m.jsxs("h1",{className:"text-4xl font-bold text-white mb-2 flex items-center space-x-3",children:[m.jsx(Yn,{className:"w-10 h-10",style:{color:((V=a.cssVars)==null?void 0:V.primary)||"#1db954"}}),m.jsx("span",{children:"Mixed Playlists"})]}),m.jsx("p",{className:"text-white/70 text-lg",children:"AI-powered playlists that perfectly blend your musical tastes together"})]}),z&&m.jsx(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.1},className:"mb-8",children:m.jsxs("div",{className:"glass rounded-2xl p-8 text-center",style:{borderColor:`${((U=a.cssVars)==null?void 0:U.primary)||"#1db954"}30`},children:[m.jsx("div",{className:"w-16 h-16 mx-auto mb-4 rounded-full flex items-center justify-center",style:{background:`linear-gradient(135deg, ${((R=a.cssVars)==null?void 0:R.primary)||"#1db954"} 0%, ${((Q=a.cssVars)==null?void 0:Q.secondary)||"#1ed760"} 100%)`},children:m.jsx(vk,{className:"w-8 h-8 text-white"})}),m.jsx("h2",{className:"text-2xl font-bold text-white mb-2",children:"Create Your Perfect Mix"}),m.jsx("p",{className:"text-white/70 mb-6 max-w-2xl mx-auto",children:"Our AI analyzes both your music tastes and creates a playlist that represents your unique musical connection"}),m.jsxs("div",{className:"mt-4 text-white/50 text-sm",children:["Analyzing ",e.topTracks.length+t.topTracks.length," tracks from both users"]}),m.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 text-left mt-8",children:[m.jsxs("div",{children:[m.jsx("label",{className:"block text-white/80 text-sm mb-1",children:"Vibe"}),m.jsxs("select",{className:"w-full bg-white/10 text-white rounded-lg p-2 appearance-none focus:outline-none focus:ring-2 focus:ring-spotify-green",value:p,onChange:A=>g(A.target.value),children:[m.jsx("option",{value:"",children:"Auto"}),m.jsx("option",{value:"energetic",children:"Energetic"}),m.jsx("option",{value:"chill",children:"Chill"}),m.jsx("option",{value:"happy",children:"Happy"}),m.jsx("option",{value:"sad",children:"Sad"}),m.jsx("option",{value:"party",children:"Party"}),m.jsx("option",{value:"focus",children:"Focus"})]})]}),m.jsxs("div",{children:[m.jsx("label",{className:"block text-white/80 text-sm mb-1",children:"Genres (comma-separated)"}),m.jsx("input",{className:"w-full bg-white/10 text-white rounded-lg p-2 placeholder-white/60 focus:outline-none focus:ring-2 focus:ring-spotify-green",placeholder:"pop, rock, edm",value:x,onChange:A=>v(A.target.value)})]}),m.jsxs("label",{className:"flex items-center space-x-2 text-white/80",children:[m.jsx("input",{type:"checkbox",checked:y,onChange:A=>w(A.target.checked)}),m.jsx("span",{children:"Include songs we already know"})]}),m.jsxs("label",{className:"flex items-center space-x-2 text-white/80",children:[m.jsx("input",{type:"checkbox",checked:b,onChange:A=>S(A.target.checked)}),m.jsx("span",{children:"Create playlist on both accounts"}),b&&m.jsx("span",{className:"text-xs text-pink-400 ml-2",children:"✨ Synced"})]})]}),m.jsx("div",{className:"flex items-center justify-center gap-3 mt-6",children:m.jsx("button",{onClick:j,disabled:d,className:"bg-white/10 hover:bg-white/20 text-white font-semibold py-3 px-4 rounded-lg transition-colors disabled:opacity-50",children:"Create Enhanced Playlist"})})]})}),u&&m.jsxs(O.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},className:"mb-8",children:[m.jsx("h2",{className:"text-2xl font-bold text-white mb-4",children:"✨ Your New Playlist"}),m.jsx(T,{playlist:u,isNew:!0})]}),n.length>0&&m.jsxs(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},children:[m.jsx("h2",{className:"text-2xl font-bold text-white mb-4",children:"Your Mixed Playlists"}),m.jsx("div",{className:"grid gap-6",children:n.map(A=>m.jsx(T,{playlist:A},A.id))})]}),!z&&m.jsxs(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"glass rounded-2xl p-12 text-center",children:[m.jsx(Xe,{className:"w-16 h-16 mx-auto mb-4 text-pink-400"}),m.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:t?"Loading music data":"Waiting for your partner"}),m.jsx("p",{className:"text-white/70",children:t?"We need to analyze both your music tastes to create the perfect mixed playlist":"Invite your partner to connect their Spotify account to start creating mixed playlists"})]}),n.length===0&&z&&!u&&m.jsxs(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"glass rounded-2xl p-12 text-center",children:[m.jsx(vt,{className:"w-16 h-16 mx-auto mb-4 text-white/30"}),m.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:"No playlists yet"}),m.jsx("p",{className:"text-white/70",children:"Create your first mixed playlist to start your musical journey together"})]})]})},d6=()=>{const{currentUser:e,partnerUser:t,memoryLane:n,addMemoryLaneItem:r}=ae(),[s,i]=k.useState(!1),[o,a]=k.useState({title:"",description:"",type:"milestone"});k.useEffect(()=>{var u,h,p,g,x,v,y,w,b,S,C,P;e&&t&&n.length===0&&[{id:"1",type:"milestone",title:"First Musical Connection",description:`${(u=e.user)==null?void 0:u.display_name} and ${(h=t.user)==null?void 0:h.display_name} discovered their shared love for music`,date:new Date(Date.now()-6048e5),users:[((p=e.user)==null?void 0:p.id)||"",((g=t.user)==null?void 0:g.id)||""]},{id:"2",type:"shared_track",title:"Shared Love for This Song",description:`Both of you have been listening to "${((v=(x=e.recentlyPlayed)==null?void 0:x[0])==null?void 0:v.track.name)||"Your favorite track"}" recently`,track:(w=(y=e.recentlyPlayed)==null?void 0:y[0])==null?void 0:w.track,date:new Date(Date.now()-2592e5),users:[((b=e.user)==null?void 0:b.id)||"",((S=t.user)==null?void 0:S.id)||""]},{id:"3",type:"playlist_created",title:"Our First Mixed Playlist",description:"Created a beautiful blend of your musical tastes",date:new Date(Date.now()-864e5),users:[((C=e.user)==null?void 0:C.id)||"",((P=t.user)==null?void 0:P.id)||""]}].forEach(D=>{r(D)})},[e,t,n.length,r]);const l=()=>{var h,p;if(!o.title.trim()||!o.description.trim()){he.error("Please fill in both title and description");return}const u={id:Date.now().toString(),...o,date:new Date,users:[((h=e==null?void 0:e.user)==null?void 0:h.id)||"",((p=t==null?void 0:t.user)==null?void 0:p.id)||""]};r(u),a({title:"",description:"",type:"milestone"}),i(!1),he.success("Memory added to your journey!")},c=u=>{switch(u){case"shared_track":return m.jsx(vt,{className:"w-5 h-5"});case"playlist_created":return m.jsx(Yn,{className:"w-5 h-5"});case"milestone":return m.jsx(mk,{className:"w-5 h-5"});default:return m.jsx(Xe,{className:"w-5 h-5"})}},d=u=>{switch(u){case"shared_track":return"from-blue-500 to-cyan-500";case"playlist_created":return"from-purple-500 to-pink-500";case"milestone":return"from-yellow-500 to-orange-500";default:return"from-pink-500 to-red-500"}},f=({memory:u,index:h})=>{var p,g;return m.jsxs(O.div,{initial:{opacity:0,x:-50},animate:{opacity:1,x:0},transition:{delay:h*.1},className:"relative",children:[hi(!0),className:"bg-gradient-to-r from-pink-500 to-red-500 hover:from-pink-600 hover:to-red-600 text-white font-semibold py-3 px-6 rounded-xl transition-all duration-300 flex items-center space-x-2",children:[m.jsx(Ac,{className:"w-5 h-5"}),m.jsx("span",{children:"Add Memory"})]})]})}),s&&m.jsx(O.div,{initial:{opacity:0},animate:{opacity:1},className:"fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4",onClick:()=>i(!1),children:m.jsxs(O.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},onClick:u=>u.stopPropagation(),className:"glass rounded-2xl p-8 max-w-md w-full",children:[m.jsx("h3",{className:"text-2xl font-bold text-white mb-6",children:"Add a New Memory"}),m.jsxs("div",{className:"space-y-4",children:[m.jsxs("div",{children:[m.jsx("label",{className:"block text-white/70 text-sm font-medium mb-2",children:"Title"}),m.jsx("input",{type:"text",value:o.title,onChange:u=>a({...o,title:u.target.value}),className:"w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:border-spotify-green",placeholder:"What's this memory about?"})]}),m.jsxs("div",{children:[m.jsx("label",{className:"block text-white/70 text-sm font-medium mb-2",children:"Description"}),m.jsx("textarea",{value:o.description,onChange:u=>a({...o,description:u.target.value}),className:"w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:border-spotify-green h-24 resize-none",placeholder:"Tell the story of this memory..."})]}),m.jsxs("div",{children:[m.jsx("label",{className:"block text-white/70 text-sm font-medium mb-2",children:"Type"}),m.jsxs("select",{value:o.type,onChange:u=>a({...o,type:u.target.value}),className:"w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:border-spotify-green",children:[m.jsx("option",{value:"milestone",children:"Milestone"}),m.jsx("option",{value:"shared_track",children:"Shared Track"}),m.jsx("option",{value:"playlist_created",children:"Playlist Created"})]})]})]}),m.jsxs("div",{className:"flex items-center space-x-3 mt-6",children:[m.jsx("button",{onClick:l,className:"flex-1 bg-spotify-green hover:bg-spotify-green/90 text-white font-semibold py-3 px-4 rounded-lg transition-colors",children:"Add Memory"}),m.jsx("button",{onClick:()=>i(!1),className:"px-4 py-3 bg-white/10 hover:bg-white/20 text-white rounded-lg transition-colors",children:"Cancel"})]})]})}),m.jsx("div",{className:"space-y-8",children:n.length>0?n.map((u,h)=>m.jsx(f,{memory:u,index:h},u.id)):m.jsxs(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"glass rounded-2xl p-12 text-center",children:[m.jsx(ck,{className:"w-16 h-16 mx-auto mb-4 text-white/30"}),m.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:"No memories yet"}),m.jsx("p",{className:"text-white/70 mb-6",children:"Start creating beautiful musical memories together"}),m.jsx("button",{onClick:()=>i(!0),className:"bg-gradient-to-r from-pink-500 to-red-500 hover:from-pink-600 hover:to-red-600 text-white font-semibold py-3 px-6 rounded-xl transition-all duration-300",children:"Create First Memory"})]})}),n.length>0&&m.jsxs(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.5},className:"mt-12 grid grid-cols-1 md:grid-cols-3 gap-6",children:[m.jsxs("div",{className:"glass rounded-2xl p-6 text-center",children:[m.jsx("div",{className:"w-12 h-12 mx-auto mb-3 bg-gradient-to-br from-pink-500 to-red-500 rounded-full flex items-center justify-center",children:m.jsx(Xe,{className:"w-6 h-6 text-white"})}),m.jsx("h4",{className:"text-2xl font-bold text-white mb-1",children:n.length}),m.jsx("p",{className:"text-white/70 text-sm",children:"Memories Created"})]}),m.jsxs("div",{className:"glass rounded-2xl p-6 text-center",children:[m.jsx("div",{className:"w-12 h-12 mx-auto mb-3 bg-gradient-to-br from-blue-500 to-cyan-500 rounded-full flex items-center justify-center",children:m.jsx(vt,{className:"w-6 h-6 text-white"})}),m.jsx("h4",{className:"text-2xl font-bold text-white mb-1",children:n.filter(u=>u.type==="shared_track").length}),m.jsx("p",{className:"text-white/70 text-sm",children:"Shared Tracks"})]}),m.jsxs("div",{className:"glass rounded-2xl p-6 text-center",children:[m.jsx("div",{className:"w-12 h-12 mx-auto mb-3 bg-gradient-to-br from-purple-500 to-pink-500 rounded-full flex items-center justify-center",children:m.jsx(Yn,{className:"w-6 h-6 text-white"})}),m.jsx("h4",{className:"text-2xl font-bold text-white mb-1",children:n.filter(u=>u.type==="playlist_created").length}),m.jsx("p",{className:"text-white/70 text-sm",children:"Playlists Created"})]})]})]})};function f6(e,t){if(!e||!t)return 0;const n=["energy","valence"];let r=0,s=0;for(const i of n)typeof e[i]=="number"&&typeof t[i]=="number"&&(r+=1-Math.min(1,Math.abs(e[i]-t[i])),s++);return s?Math.round(r/s*100):0}const h6=()=>{var u,h;const{currentUser:e,partnerUser:t}=ae(),[n,r]=k.useState(null),[s,i]=k.useState(null),[o,a]=k.useState(null),[l,c]=k.useState(null);k.useEffect(()=>{let p;const g=async()=>{var x,v,y,w;try{const b=(x=e==null?void 0:e.user)==null?void 0:x.id;if(b){const C=await se(`/users/${b}/now-playing`);r(C);const P=(v=C==null?void 0:C.item)==null?void 0:v.id;if(P){const j=await se(`/users/${b}/audio-features?ids=${P}`);a(((j==null?void 0:j.audio_features)||[])[0]||null)}}const S=(y=t==null?void 0:t.user)==null?void 0:y.id;if(S){const C=await se(`/users/${S}/now-playing`);i(C);const P=(w=C==null?void 0:C.item)==null?void 0:w.id;if(P){const j=await se(`/users/${S}/audio-features?ids=${P}`);c(((j==null?void 0:j.audio_features)||[])[0]||null)}}}catch{}p=setTimeout(g,8e3)};return g(),()=>clearTimeout(p)},[(u=e==null?void 0:e.user)==null?void 0:u.id,(h=t==null?void 0:t.user)==null?void 0:h.id]);const d=k.useMemo(()=>f6(o,l),[o,l]),f=({data:p,who:g})=>{var v,y,w;if(!(p!=null&&p.is_playing)||!(p!=null&&p.item))return m.jsxs("div",{className:"glass rounded-2xl p-6 text-white/70",children:[g," is not playing"]});const x=p.item;return m.jsxs("div",{className:"glass rounded-2xl p-6 flex items-center gap-4",children:[m.jsx("img",{src:((w=(y=(v=x==null?void 0:x.album)==null?void 0:v.images)==null?void 0:y[0])==null?void 0:w.url)||"/placeholder-album.png",alt:x==null?void 0:x.name,className:"w-16 h-16 rounded"}),m.jsxs("div",{className:"flex-1 min-w-0",children:[m.jsx("div",{className:"text-white font-semibold truncate",children:x==null?void 0:x.name}),m.jsx("div",{className:"text-white/70 text-sm truncate",children:((x==null?void 0:x.artists)||[]).map(b=>b.name).join(", ")})]}),m.jsx("div",{className:"flex gap-1",children:[...Array(12)].map((b,S)=>m.jsx("div",{className:"w-1 bg-spotify-green/60 animate-pulse",style:{height:`${(Math.sin(S)*.5+.5)*32+8}px`,animationDelay:`${S*50}ms`}},S))})]})};return m.jsxs("div",{className:"max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8",children:[m.jsxs(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"mb-6",children:[m.jsx("h1",{className:"text-3xl font-bold text-white",children:"Live Dashboard"}),m.jsx("p",{className:"text-white/70",children:"See what you are both playing right now"})]}),m.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[m.jsx(f,{data:n,who:"You"}),m.jsx(f,{data:s,who:"Partner"})]}),(n==null?void 0:n.is_playing)&&(s==null?void 0:s.is_playing)&&m.jsxs(O.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"glass rounded-2xl p-6 mt-6 text-center",children:[m.jsx("div",{className:"text-white/80",children:"Harmony Match"}),m.jsxs("div",{className:"text-4xl font-extrabold text-white mt-1",children:[d,"%"]})]})]})};function p6(){var o,a;const{currentUser:e,partnerUser:t,isLoading:n,theme:r}=ae(),s=En();console.log("🔍 App - Current location:",s.pathname),k.useEffect(()=>{Vr(r)},[r]),k.useEffect(()=>{const l=localStorage.getItem("spotify-user"),c=localStorage.getItem("spotify-partner");if(l)try{const d=JSON.parse(l);ae.getState().setCurrentUser(d)}catch(d){console.error("Failed to parse stored user data:",d),localStorage.removeItem("spotify-user")}if(c)try{const d=JSON.parse(c);ae.getState().setPartnerUser(d)}catch(d){console.error("Failed to parse stored partner data:",d),localStorage.removeItem("spotify-partner")}},[]),k.useEffect(()=>{(async()=>{var d,f;const c=(f=(d=ae.getState().currentUser)==null?void 0:d.user)==null?void 0:f.id;if(c&&!ae.getState().partnerUser)try{const u=await se(`/partners/partner/${c}`);if(u.partnerId){const[h,p,g]=await Promise.all([se(`/users/${u.partnerId}`),se(`/users/${u.partnerId}/recently-played`),se(`/users/${u.partnerId}/top-tracks?time_range=short_term`)]);ae.getState().setPartnerUser({user:h,accessToken:null,refreshToken:null,isAuthenticated:!0,recentlyPlayed:p,topTracks:g.map(x=>x.track),topArtists:[]})}}catch{}})()},[(o=e==null?void 0:e.user)==null?void 0:o.id]),k.useEffect(()=>{var d,f;const l=(f=(d=ae.getState().currentUser)==null?void 0:d.user)==null?void 0:f.id;if(!l)return;const c=hb(`/partners/events/${l}`);return c.onmessage=async u=>{var h,p;if(u.data)try{const g=JSON.parse(u.data);if((g==null?void 0:g.type)==="partner:connected"||(g==null?void 0:g.type)==="partner:disconnected"){const x=await se(`/partners/partner/${l}`),v=((p=(h=ae.getState().partnerUser)==null?void 0:h.user)==null?void 0:p.id)||null;if(!(x!=null&&x.partnerId)&&v){ae.getState().setPartnerUser(null),localStorage.removeItem("spotify-partner");return}if(x!=null&&x.partnerId&&x.partnerId!==v)try{const[y,w,b]=await Promise.all([se(`/users/${x.partnerId}`),se(`/users/${x.partnerId}/recently-played`),se(`/users/${x.partnerId}/top-tracks?time_range=short_term`)]);ae.getState().setPartnerUser({user:y,accessToken:null,refreshToken:null,isAuthenticated:!0,recentlyPlayed:w,topTracks:b.map(S=>S.track),topArtists:[]})}catch{}}(g==null?void 0:g.type)==="partner:request"||(g==null||g.type)}catch{}},c.onerror=()=>{try{c.close()}catch{}},()=>{try{c.close()}catch{}}},[(a=e==null?void 0:e.user)==null?void 0:a.id]);const i=(e==null?void 0:e.isAuthenticated)||!1;return n?m.jsxs("div",{className:"min-h-screen flex items-center justify-center relative",children:[m.jsx(Eh,{hueShift:ah(r)}),m.jsxs(O.div,{initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},className:"glass-fluid rounded-3xl p-10 flex flex-col items-center space-y-6 relative z-20",children:[m.jsx("div",{className:"w-16 h-16 border-4 border-t-transparent rounded-full animate-spin",style:{borderColor:"var(--theme-primary) var(--theme-primary) var(--theme-primary) transparent"}}),m.jsx("p",{className:"text-white font-medium text-lg",children:"Loading your musical journey..."})]})]}):m.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[m.jsx(Eh,{hueShift:ah(r)}),m.jsxs("div",{className:"relative z-20",children:[i&&m.jsx(Jk,{}),m.jsxs(wx,{children:[m.jsx(_t,{path:"/",element:i?m.jsx(a6,{}):m.jsx(o6,{})}),m.jsx(_t,{path:"/callback",element:m.jsx(Rh,{})}),m.jsx(_t,{path:"/callback.html",element:m.jsx(Rh,{})}),i&&m.jsxs(m.Fragment,{children:[m.jsx(_t,{path:"/last-listened",element:m.jsx(l6,{})}),m.jsx(_t,{path:"/mixed-playlist",element:m.jsx(c6,{})}),m.jsx(_t,{path:"/memory-lane",element:m.jsx(d6,{})}),m.jsx(_t,{path:"/live",element:m.jsx(h6,{})})]}),m.jsx(_t,{path:"*",element:m.jsx(vx,{to:"/",replace:!0})})]})]})]})}Ka.createRoot(document.getElementById("root")).render(m.jsx(Gs.StrictMode,{children:m.jsxs(Tx,{children:[m.jsx(p6,{}),m.jsx(w2,{position:"top-right",toastOptions:{duration:4e3,style:{background:"rgba(255, 255, 255, 0.1)",backdropFilter:"blur(20px)",border:"1px solid rgba(255, 255, 255, 0.2)",color:"#fff"}}})]})})); diff --git a/dist/assets/index-DVwnln3h.js b/dist/assets/index-DVwnln3h.js deleted file mode 100644 index ce8f974..0000000 --- a/dist/assets/index-DVwnln3h.js +++ /dev/null @@ -1,473 +0,0 @@ -function ey(e,t){for(var n=0;nr[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const o of i.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(s){if(s.ep)return;s.ep=!0;const i=n(s);fetch(s.href,i)}})();function uu(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Vh={exports:{}},jo={},Fh={exports:{}},q={};/** - * @license React - * react.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Hs=Symbol.for("react.element"),ty=Symbol.for("react.portal"),ny=Symbol.for("react.fragment"),ry=Symbol.for("react.strict_mode"),sy=Symbol.for("react.profiler"),iy=Symbol.for("react.provider"),oy=Symbol.for("react.context"),ay=Symbol.for("react.forward_ref"),ly=Symbol.for("react.suspense"),uy=Symbol.for("react.memo"),cy=Symbol.for("react.lazy"),Vc=Symbol.iterator;function dy(e){return e===null||typeof e!="object"?null:(e=Vc&&e[Vc]||e["@@iterator"],typeof e=="function"?e:null)}var zh={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Ih=Object.assign,Oh={};function Fr(e,t,n){this.props=e,this.context=t,this.refs=Oh,this.updater=n||zh}Fr.prototype.isReactComponent={};Fr.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};Fr.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function $h(){}$h.prototype=Fr.prototype;function cu(e,t,n){this.props=e,this.context=t,this.refs=Oh,this.updater=n||zh}var du=cu.prototype=new $h;du.constructor=cu;Ih(du,Fr.prototype);du.isPureReactComponent=!0;var Fc=Array.isArray,Bh=Object.prototype.hasOwnProperty,fu={current:null},Uh={key:!0,ref:!0,__self:!0,__source:!0};function Wh(e,t,n){var r,s={},i=null,o=null;if(t!=null)for(r in t.ref!==void 0&&(o=t.ref),t.key!==void 0&&(i=""+t.key),t)Bh.call(t,r)&&!Uh.hasOwnProperty(r)&&(s[r]=t[r]);var a=arguments.length-2;if(a===1)s.children=n;else if(1>>1,E=M[R];if(0>>1;Rs(ce,z))Gs(we,ce)?(M[R]=we,M[G]=z,R=G):(M[R]=ce,M[Q]=z,R=Q);else if(Gs(we,z))M[R]=we,M[G]=z,R=G;else break e}}return D}function s(M,D){var z=M.sortIndex-D.sortIndex;return z!==0?z:M.id-D.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var o=Date,a=o.now();e.unstable_now=function(){return o.now()-a}}var l=[],c=[],d=1,f=null,u=3,h=!1,p=!1,g=!1,w=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,y=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function x(M){for(var D=n(c);D!==null;){if(D.callback===null)r(c);else if(D.startTime<=M)r(c),D.sortIndex=D.expirationTime,t(l,D);else break;D=n(c)}}function b(M){if(g=!1,x(M),!p)if(n(l)!==null)p=!0,B(S);else{var D=n(c);D!==null&&K(b,D.startTime-M)}}function S(M,D){p=!1,g&&(g=!1,v(j),j=-1),h=!0;var z=u;try{for(x(D),f=n(l);f!==null&&(!(f.expirationTime>D)||M&&!F());){var R=f.callback;if(typeof R=="function"){f.callback=null,u=f.priorityLevel;var E=R(f.expirationTime<=D);D=e.unstable_now(),typeof E=="function"?f.callback=E:f===n(l)&&r(l),x(D)}else r(l);f=n(l)}if(f!==null)var Y=!0;else{var Q=n(c);Q!==null&&K(b,Q.startTime-D),Y=!1}return Y}finally{f=null,u=z,h=!1}}var C=!1,P=null,j=-1,_=5,T=-1;function F(){return!(e.unstable_now()-T<_)}function L(){if(P!==null){var M=e.unstable_now();T=M;var D=!0;try{D=P(!0,M)}finally{D?W():(C=!1,P=null)}}else C=!1}var W;if(typeof y=="function")W=function(){y(L)};else if(typeof MessageChannel<"u"){var A=new MessageChannel,O=A.port2;A.port1.onmessage=L,W=function(){O.postMessage(null)}}else W=function(){w(L,0)};function B(M){P=M,C||(C=!0,W())}function K(M,D){j=w(function(){M(e.unstable_now())},D)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(M){M.callback=null},e.unstable_continueExecution=function(){p||h||(p=!0,B(S))},e.unstable_forceFrameRate=function(M){0>M||125R?(M.sortIndex=z,t(c,M),n(l)===null&&M===n(c)&&(g?(v(j),j=-1):g=!0,K(b,z-R))):(M.sortIndex=E,t(l,M),p||h||(p=!0,B(S))),M},e.unstable_shouldYield=F,e.unstable_wrapCallback=function(M){var D=u;return function(){var z=u;u=D;try{return M.apply(this,arguments)}finally{u=z}}}})(Kh);Yh.exports=Kh;var ky=Yh.exports;/** - * @license React - * react-dom.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Cy=k,Qe=ky;function N(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Ka=Object.prototype.hasOwnProperty,Py=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Ic={},Oc={};function jy(e){return Ka.call(Oc,e)?!0:Ka.call(Ic,e)?!1:Py.test(e)?Oc[e]=!0:(Ic[e]=!0,!1)}function Ey(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function Ty(e,t,n,r){if(t===null||typeof t>"u"||Ey(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function $e(e,t,n,r,s,i,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=o}var _e={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){_e[e]=new $e(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];_e[t]=new $e(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){_e[e]=new $e(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){_e[e]=new $e(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){_e[e]=new $e(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){_e[e]=new $e(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){_e[e]=new $e(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){_e[e]=new $e(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){_e[e]=new $e(e,5,!1,e.toLowerCase(),null,!1,!1)});var pu=/[\-:]([a-z])/g;function mu(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(pu,mu);_e[t]=new $e(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(pu,mu);_e[t]=new $e(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(pu,mu);_e[t]=new $e(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){_e[e]=new $e(e,1,!1,e.toLowerCase(),null,!1,!1)});_e.xlinkHref=new $e("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){_e[e]=new $e(e,1,!1,e.toLowerCase(),null,!0,!0)});function gu(e,t,n,r){var s=_e.hasOwnProperty(t)?_e[t]:null;(s!==null?s.type!==0:r||!(2a||s[o]!==i[a]){var l=` -`+s[o].replace(" at new "," at ");return e.displayName&&l.includes("")&&(l=l.replace("",e.displayName)),l}while(1<=o&&0<=a);break}}}finally{sa=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?ns(e):""}function Ny(e){switch(e.tag){case 5:return ns(e.type);case 16:return ns("Lazy");case 13:return ns("Suspense");case 19:return ns("SuspenseList");case 0:case 2:case 15:return e=ia(e.type,!1),e;case 11:return e=ia(e.type.render,!1),e;case 1:return e=ia(e.type,!0),e;default:return""}}function Ja(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case nr:return"Fragment";case tr:return"Portal";case Xa:return"Profiler";case yu:return"StrictMode";case Qa:return"Suspense";case Za:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case Zh:return(e.displayName||"Context")+".Consumer";case Qh:return(e._context.displayName||"Context")+".Provider";case vu:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case xu:return t=e.displayName||null,t!==null?t:Ja(e.type)||"Memo";case Qt:t=e._payload,e=e._init;try{return Ja(e(t))}catch{}}return null}function My(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return Ja(t);case 8:return t===yu?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function yn(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function ep(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function _y(e){var t=ep(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var s=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(o){r=""+o,i.call(this,o)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function ii(e){e._valueTracker||(e._valueTracker=_y(e))}function tp(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=ep(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function Bi(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function el(e,t){var n=t.checked;return ue({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Bc(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=yn(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function np(e,t){t=t.checked,t!=null&&gu(e,"checked",t,!1)}function tl(e,t){np(e,t);var n=yn(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?nl(e,t.type,n):t.hasOwnProperty("defaultValue")&&nl(e,t.type,yn(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Uc(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function nl(e,t,n){(t!=="number"||Bi(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var rs=Array.isArray;function yr(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=oi.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function ks(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var as={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Ay=["Webkit","ms","Moz","O"];Object.keys(as).forEach(function(e){Ay.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),as[t]=as[e]})});function op(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||as.hasOwnProperty(e)&&as[e]?(""+t).trim():t+"px"}function ap(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=op(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var Ly=ue({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function il(e,t){if(t){if(Ly[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(N(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(N(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(N(61))}if(t.style!=null&&typeof t.style!="object")throw Error(N(62))}}function ol(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var al=null;function wu(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var ll=null,vr=null,xr=null;function qc(e){if(e=Ks(e)){if(typeof ll!="function")throw Error(N(280));var t=e.stateNode;t&&(t=_o(t),ll(e.stateNode,e.type,t))}}function lp(e){vr?xr?xr.push(e):xr=[e]:vr=e}function up(){if(vr){var e=vr,t=xr;if(xr=vr=null,qc(e),t)for(e=0;e>>=0,e===0?32:31-(Wy(e)/Hy|0)|0}var ai=64,li=4194304;function ss(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function qi(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,i=e.pingedLanes,o=n&268435455;if(o!==0){var a=o&~s;a!==0?r=ss(a):(i&=o,i!==0&&(r=ss(i)))}else o=n&~s,o!==0?r=ss(o):i!==0&&(r=ss(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&s)&&(s=r&-r,i=t&-t,s>=i||s===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function Gs(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-gt(t),e[t]=n}function Ky(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=us),td=" ",nd=!1;function Np(e,t){switch(e){case"keyup":return k1.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Mp(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var rr=!1;function P1(e,t){switch(e){case"compositionend":return Mp(t);case"keypress":return t.which!==32?null:(nd=!0,td);case"textInput":return e=t.data,e===td&&nd?null:e;default:return null}}function j1(e,t){if(rr)return e==="compositionend"||!Tu&&Np(e,t)?(e=Ep(),Ni=Pu=rn=null,rr=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=od(n)}}function Dp(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Dp(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Rp(){for(var e=window,t=Bi();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=Bi(e.document)}return t}function Nu(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function R1(e){var t=Rp(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&Dp(n.ownerDocument.documentElement,n)){if(r!==null&&Nu(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var s=n.textContent.length,i=Math.min(r.start,s);r=r.end===void 0?i:Math.min(r.end,s),!e.extend&&i>r&&(s=r,r=i,i=s),s=ad(n,i);var o=ad(n,r);s&&o&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,sr=null,pl=null,ds=null,ml=!1;function ld(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ml||sr==null||sr!==Bi(r)||(r=sr,"selectionStart"in r&&Nu(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),ds&&Ns(ds,r)||(ds=r,r=Ki(pl,"onSelect"),0ar||(e.current=bl[ar],bl[ar]=null,ar--)}function J(e,t){ar++,bl[ar]=e.current,e.current=t}var vn={},Ve=Sn(vn),We=Sn(!1),Bn=vn;function jr(e,t){var n=e.type.contextTypes;if(!n)return vn;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var s={},i;for(i in n)s[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function He(e){return e=e.childContextTypes,e!=null}function Qi(){re(We),re(Ve)}function md(e,t,n){if(Ve.current!==vn)throw Error(N(168));J(Ve,t),J(We,n)}function Wp(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(N(108,My(e)||"Unknown",s));return ue({},n,r)}function Zi(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||vn,Bn=Ve.current,J(Ve,e),J(We,We.current),!0}function gd(e,t,n){var r=e.stateNode;if(!r)throw Error(N(169));n?(e=Wp(e,t,Bn),r.__reactInternalMemoizedMergedChildContext=e,re(We),re(Ve),J(Ve,e)):re(We),J(We,n)}var At=null,Ao=!1,xa=!1;function Hp(e){At===null?At=[e]:At.push(e)}function G1(e){Ao=!0,Hp(e)}function kn(){if(!xa&&At!==null){xa=!0;var e=0,t=Z;try{var n=At;for(Z=1;e>=o,s-=o,Lt=1<<32-gt(t)+s|n<j?(_=P,P=null):_=P.sibling;var T=u(v,P,x[j],b);if(T===null){P===null&&(P=_);break}e&&P&&T.alternate===null&&t(v,P),y=i(T,y,j),C===null?S=T:C.sibling=T,C=T,P=_}if(j===x.length)return n(v,P),ie&&_n(v,j),S;if(P===null){for(;jj?(_=P,P=null):_=P.sibling;var F=u(v,P,T.value,b);if(F===null){P===null&&(P=_);break}e&&P&&F.alternate===null&&t(v,P),y=i(F,y,j),C===null?S=F:C.sibling=F,C=F,P=_}if(T.done)return n(v,P),ie&&_n(v,j),S;if(P===null){for(;!T.done;j++,T=x.next())T=f(v,T.value,b),T!==null&&(y=i(T,y,j),C===null?S=T:C.sibling=T,C=T);return ie&&_n(v,j),S}for(P=r(v,P);!T.done;j++,T=x.next())T=h(P,v,j,T.value,b),T!==null&&(e&&T.alternate!==null&&P.delete(T.key===null?j:T.key),y=i(T,y,j),C===null?S=T:C.sibling=T,C=T);return e&&P.forEach(function(L){return t(v,L)}),ie&&_n(v,j),S}function w(v,y,x,b){if(typeof x=="object"&&x!==null&&x.type===nr&&x.key===null&&(x=x.props.children),typeof x=="object"&&x!==null){switch(x.$$typeof){case si:e:{for(var S=x.key,C=y;C!==null;){if(C.key===S){if(S=x.type,S===nr){if(C.tag===7){n(v,C.sibling),y=s(C,x.props.children),y.return=v,v=y;break e}}else if(C.elementType===S||typeof S=="object"&&S!==null&&S.$$typeof===Qt&&xd(S)===C.type){n(v,C.sibling),y=s(C,x.props),y.ref=Kr(v,C,x),y.return=v,v=y;break e}n(v,C);break}else t(v,C);C=C.sibling}x.type===nr?(y=On(x.props.children,v.mode,b,x.key),y.return=v,v=y):(b=Fi(x.type,x.key,x.props,null,v.mode,b),b.ref=Kr(v,y,x),b.return=v,v=b)}return o(v);case tr:e:{for(C=x.key;y!==null;){if(y.key===C)if(y.tag===4&&y.stateNode.containerInfo===x.containerInfo&&y.stateNode.implementation===x.implementation){n(v,y.sibling),y=s(y,x.children||[]),y.return=v,v=y;break e}else{n(v,y);break}else t(v,y);y=y.sibling}y=Ea(x,v.mode,b),y.return=v,v=y}return o(v);case Qt:return C=x._init,w(v,y,C(x._payload),b)}if(rs(x))return p(v,y,x,b);if(Wr(x))return g(v,y,x,b);mi(v,x)}return typeof x=="string"&&x!==""||typeof x=="number"?(x=""+x,y!==null&&y.tag===6?(n(v,y.sibling),y=s(y,x),y.return=v,v=y):(n(v,y),y=ja(x,v.mode,b),y.return=v,v=y),o(v)):n(v,y)}return w}var Tr=Kp(!0),Xp=Kp(!1),to=Sn(null),no=null,cr=null,Lu=null;function Du(){Lu=cr=no=null}function Ru(e){var t=to.current;re(to),e._currentValue=t}function Cl(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function br(e,t){no=e,Lu=cr=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(Ue=!0),e.firstContext=null)}function ut(e){var t=e._currentValue;if(Lu!==e)if(e={context:e,memoizedValue:t,next:null},cr===null){if(no===null)throw Error(N(308));cr=e,no.dependencies={lanes:0,firstContext:e}}else cr=cr.next=e;return t}var Vn=null;function Vu(e){Vn===null?Vn=[e]:Vn.push(e)}function Qp(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,Vu(t)):(n.next=s.next,s.next=n),t.interleaved=n,Bt(e,r)}function Bt(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Zt=!1;function Fu(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Zp(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Vt(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function dn(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,X&2){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,Bt(e,n)}return s=r.interleaved,s===null?(t.next=t,Vu(r)):(t.next=s.next,s.next=t),r.interleaved=t,Bt(e,n)}function _i(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Su(e,n)}}function wd(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?s=i=o:i=i.next=o,n=n.next}while(n!==null);i===null?s=i=t:i=i.next=t}else s=i=t;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function ro(e,t,n,r){var s=e.updateQueue;Zt=!1;var i=s.firstBaseUpdate,o=s.lastBaseUpdate,a=s.shared.pending;if(a!==null){s.shared.pending=null;var l=a,c=l.next;l.next=null,o===null?i=c:o.next=c,o=l;var d=e.alternate;d!==null&&(d=d.updateQueue,a=d.lastBaseUpdate,a!==o&&(a===null?d.firstBaseUpdate=c:a.next=c,d.lastBaseUpdate=l))}if(i!==null){var f=s.baseState;o=0,d=c=l=null,a=i;do{var u=a.lane,h=a.eventTime;if((r&u)===u){d!==null&&(d=d.next={eventTime:h,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var p=e,g=a;switch(u=t,h=n,g.tag){case 1:if(p=g.payload,typeof p=="function"){f=p.call(h,f,u);break e}f=p;break e;case 3:p.flags=p.flags&-65537|128;case 0:if(p=g.payload,u=typeof p=="function"?p.call(h,f,u):p,u==null)break e;f=ue({},f,u);break e;case 2:Zt=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,u=s.effects,u===null?s.effects=[a]:u.push(a))}else h={eventTime:h,lane:u,tag:a.tag,payload:a.payload,callback:a.callback,next:null},d===null?(c=d=h,l=f):d=d.next=h,o|=u;if(a=a.next,a===null){if(a=s.shared.pending,a===null)break;u=a,a=u.next,u.next=null,s.lastBaseUpdate=u,s.shared.pending=null}}while(!0);if(d===null&&(l=f),s.baseState=l,s.firstBaseUpdate=c,s.lastBaseUpdate=d,t=s.shared.interleaved,t!==null){s=t;do o|=s.lane,s=s.next;while(s!==t)}else i===null&&(s.shared.lanes=0);Hn|=o,e.lanes=o,e.memoizedState=f}}function bd(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=ba.transition;ba.transition={};try{e(!1),t()}finally{Z=n,ba.transition=r}}function mm(){return ct().memoizedState}function Q1(e,t,n){var r=hn(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},gm(e))ym(t,n);else if(n=Qp(e,t,n,r),n!==null){var s=Ie();yt(n,e,r,s),vm(n,t,r)}}function Z1(e,t,n){var r=hn(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(gm(e))ym(t,s);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var o=t.lastRenderedState,a=i(o,n);if(s.hasEagerState=!0,s.eagerState=a,vt(a,o)){var l=t.interleaved;l===null?(s.next=s,Vu(t)):(s.next=l.next,l.next=s),t.interleaved=s;return}}catch{}finally{}n=Qp(e,t,s,r),n!==null&&(s=Ie(),yt(n,e,r,s),vm(n,t,r))}}function gm(e){var t=e.alternate;return e===le||t!==null&&t===le}function ym(e,t){fs=io=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function vm(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Su(e,n)}}var oo={readContext:ut,useCallback:Ae,useContext:Ae,useEffect:Ae,useImperativeHandle:Ae,useInsertionEffect:Ae,useLayoutEffect:Ae,useMemo:Ae,useReducer:Ae,useRef:Ae,useState:Ae,useDebugValue:Ae,useDeferredValue:Ae,useTransition:Ae,useMutableSource:Ae,useSyncExternalStore:Ae,useId:Ae,unstable_isNewReconciler:!1},J1={readContext:ut,useCallback:function(e,t){return bt().memoizedState=[e,t===void 0?null:t],e},useContext:ut,useEffect:kd,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,Li(4194308,4,cm.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Li(4194308,4,e,t)},useInsertionEffect:function(e,t){return Li(4,2,e,t)},useMemo:function(e,t){var n=bt();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=bt();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Q1.bind(null,le,e),[r.memoizedState,e]},useRef:function(e){var t=bt();return e={current:e},t.memoizedState=e},useState:Sd,useDebugValue:Hu,useDeferredValue:function(e){return bt().memoizedState=e},useTransition:function(){var e=Sd(!1),t=e[0];return e=X1.bind(null,e[1]),bt().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=le,s=bt();if(ie){if(n===void 0)throw Error(N(407));n=n()}else{if(n=t(),Ee===null)throw Error(N(349));Wn&30||nm(r,t,n)}s.memoizedState=n;var i={value:n,getSnapshot:t};return s.queue=i,kd(sm.bind(null,r,i,e),[e]),r.flags|=2048,Fs(9,rm.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=bt(),t=Ee.identifierPrefix;if(ie){var n=Dt,r=Lt;n=(r&~(1<<32-gt(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=Rs++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=o.createElement(n,{is:r.is}):(e=o.createElement(n),n==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,n),e[St]=t,e[As]=r,Tm(e,t,!1,!1),t.stateNode=e;e:{switch(o=ol(n,r),n){case"dialog":ne("cancel",e),ne("close",e),s=r;break;case"iframe":case"object":case"embed":ne("load",e),s=r;break;case"video":case"audio":for(s=0;s_r&&(t.flags|=128,r=!0,Xr(i,!1),t.lanes=4194304)}else{if(!r)if(e=so(o),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),Xr(i,!0),i.tail===null&&i.tailMode==="hidden"&&!o.alternate&&!ie)return Le(t),null}else 2*he()-i.renderingStartTime>_r&&n!==1073741824&&(t.flags|=128,r=!0,Xr(i,!1),t.lanes=4194304);i.isBackwards?(o.sibling=t.child,t.child=o):(n=i.last,n!==null?n.sibling=o:t.child=o,i.last=o)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=he(),t.sibling=null,n=oe.current,J(oe,r?n&1|2:n&1),t):(Le(t),null);case 22:case 23:return Qu(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Ye&1073741824&&(Le(t),t.subtreeFlags&6&&(t.flags|=8192)):Le(t),null;case 24:return null;case 25:return null}throw Error(N(156,t.tag))}function av(e,t){switch(_u(t),t.tag){case 1:return He(t.type)&&Qi(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Nr(),re(We),re(Ve),Ou(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return Iu(t),null;case 13:if(re(oe),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(N(340));Er()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return re(oe),null;case 4:return Nr(),null;case 10:return Ru(t.type._context),null;case 22:case 23:return Qu(),null;case 24:return null;default:return null}}var yi=!1,Re=!1,lv=typeof WeakSet=="function"?WeakSet:Set,V=null;function dr(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){de(e,t,r)}else n.current=null}function Ll(e,t,n){try{n()}catch(r){de(e,t,r)}}var Dd=!1;function uv(e,t){if(gl=Gi,e=Rp(),Nu(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var s=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var o=0,a=-1,l=-1,c=0,d=0,f=e,u=null;t:for(;;){for(var h;f!==n||s!==0&&f.nodeType!==3||(a=o+s),f!==i||r!==0&&f.nodeType!==3||(l=o+r),f.nodeType===3&&(o+=f.nodeValue.length),(h=f.firstChild)!==null;)u=f,f=h;for(;;){if(f===e)break t;if(u===n&&++c===s&&(a=o),u===i&&++d===r&&(l=o),(h=f.nextSibling)!==null)break;f=u,u=f.parentNode}f=h}n=a===-1||l===-1?null:{start:a,end:l}}else n=null}n=n||{start:0,end:0}}else n=null;for(yl={focusedElem:e,selectionRange:n},Gi=!1,V=t;V!==null;)if(t=V,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,V=e;else for(;V!==null;){t=V;try{var p=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(p!==null){var g=p.memoizedProps,w=p.memoizedState,v=t.stateNode,y=v.getSnapshotBeforeUpdate(t.elementType===t.type?g:ft(t.type,g),w);v.__reactInternalSnapshotBeforeUpdate=y}break;case 3:var x=t.stateNode.containerInfo;x.nodeType===1?x.textContent="":x.nodeType===9&&x.documentElement&&x.removeChild(x.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(N(163))}}catch(b){de(t,t.return,b)}if(e=t.sibling,e!==null){e.return=t.return,V=e;break}V=t.return}return p=Dd,Dd=!1,p}function hs(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var i=s.destroy;s.destroy=void 0,i!==void 0&&Ll(t,n,i)}s=s.next}while(s!==r)}}function Ro(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Dl(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function _m(e){var t=e.alternate;t!==null&&(e.alternate=null,_m(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[St],delete t[As],delete t[wl],delete t[H1],delete t[q1])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Am(e){return e.tag===5||e.tag===3||e.tag===4}function Rd(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Am(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Rl(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Xi));else if(r!==4&&(e=e.child,e!==null))for(Rl(e,t,n),e=e.sibling;e!==null;)Rl(e,t,n),e=e.sibling}function Vl(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Vl(e,t,n),e=e.sibling;e!==null;)Vl(e,t,n),e=e.sibling}var Ne=null,ht=!1;function Gt(e,t,n){for(n=n.child;n!==null;)Lm(e,t,n),n=n.sibling}function Lm(e,t,n){if(Pt&&typeof Pt.onCommitFiberUnmount=="function")try{Pt.onCommitFiberUnmount(Eo,n)}catch{}switch(n.tag){case 5:Re||dr(n,t);case 6:var r=Ne,s=ht;Ne=null,Gt(e,t,n),Ne=r,ht=s,Ne!==null&&(ht?(e=Ne,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):Ne.removeChild(n.stateNode));break;case 18:Ne!==null&&(ht?(e=Ne,n=n.stateNode,e.nodeType===8?va(e.parentNode,n):e.nodeType===1&&va(e,n),Es(e)):va(Ne,n.stateNode));break;case 4:r=Ne,s=ht,Ne=n.stateNode.containerInfo,ht=!0,Gt(e,t,n),Ne=r,ht=s;break;case 0:case 11:case 14:case 15:if(!Re&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var i=s,o=i.destroy;i=i.tag,o!==void 0&&(i&2||i&4)&&Ll(n,t,o),s=s.next}while(s!==r)}Gt(e,t,n);break;case 1:if(!Re&&(dr(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(a){de(n,t,a)}Gt(e,t,n);break;case 21:Gt(e,t,n);break;case 22:n.mode&1?(Re=(r=Re)||n.memoizedState!==null,Gt(e,t,n),Re=r):Gt(e,t,n);break;default:Gt(e,t,n)}}function Vd(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new lv),t.forEach(function(r){var s=vv.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function dt(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=o),r&=~i}if(r=s,r=he()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*dv(r/1960))-r,10e?16:e,sn===null)var r=!1;else{if(e=sn,sn=null,uo=0,X&6)throw Error(N(331));var s=X;for(X|=4,V=e.current;V!==null;){var i=V,o=i.child;if(V.flags&16){var a=i.deletions;if(a!==null){for(var l=0;lhe()-Ku?In(e,0):Yu|=n),qe(e,t)}function $m(e,t){t===0&&(e.mode&1?(t=li,li<<=1,!(li&130023424)&&(li=4194304)):t=1);var n=Ie();e=Bt(e,t),e!==null&&(Gs(e,t,n),qe(e,n))}function yv(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),$m(e,n)}function vv(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(N(314))}r!==null&&r.delete(t),$m(e,n)}var Bm;Bm=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||We.current)Ue=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return Ue=!1,iv(e,t,n);Ue=!!(e.flags&131072)}else Ue=!1,ie&&t.flags&1048576&&qp(t,eo,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Di(e,t),e=t.pendingProps;var s=jr(t,Ve.current);br(t,n),s=Bu(null,t,r,e,s,n);var i=Uu();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,He(r)?(i=!0,Zi(t)):i=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,Fu(t),s.updater=Do,t.stateNode=s,s._reactInternals=t,jl(t,r,e,n),t=Nl(null,t,r,!0,i,n)):(t.tag=0,ie&&i&&Mu(t),ze(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Di(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=wv(r),e=ft(r,e),s){case 0:t=Tl(null,t,r,e,n);break e;case 1:t=_d(null,t,r,e,n);break e;case 11:t=Nd(null,t,r,e,n);break e;case 14:t=Md(null,t,r,ft(r.type,e),n);break e}throw Error(N(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:ft(r,s),Tl(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:ft(r,s),_d(e,t,r,s,n);case 3:e:{if(Pm(t),e===null)throw Error(N(387));r=t.pendingProps,i=t.memoizedState,s=i.element,Zp(e,t),ro(t,r,null,n);var o=t.memoizedState;if(r=o.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){s=Mr(Error(N(423)),t),t=Ad(e,t,r,n,s);break e}else if(r!==s){s=Mr(Error(N(424)),t),t=Ad(e,t,r,n,s);break e}else for(Ke=cn(t.stateNode.containerInfo.firstChild),Xe=t,ie=!0,pt=null,n=Xp(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(Er(),r===s){t=Ut(e,t,n);break e}ze(e,t,r,n)}t=t.child}return t;case 5:return Jp(t),e===null&&kl(t),r=t.type,s=t.pendingProps,i=e!==null?e.memoizedProps:null,o=s.children,vl(r,s)?o=null:i!==null&&vl(r,i)&&(t.flags|=32),Cm(e,t),ze(e,t,o,n),t.child;case 6:return e===null&&kl(t),null;case 13:return jm(e,t,n);case 4:return zu(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Tr(t,null,r,n):ze(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:ft(r,s),Nd(e,t,r,s,n);case 7:return ze(e,t,t.pendingProps,n),t.child;case 8:return ze(e,t,t.pendingProps.children,n),t.child;case 12:return ze(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,s=t.pendingProps,i=t.memoizedProps,o=s.value,J(to,r._currentValue),r._currentValue=o,i!==null)if(vt(i.value,o)){if(i.children===s.children&&!We.current){t=Ut(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var a=i.dependencies;if(a!==null){o=i.child;for(var l=a.firstContext;l!==null;){if(l.context===r){if(i.tag===1){l=Vt(-1,n&-n),l.tag=2;var c=i.updateQueue;if(c!==null){c=c.shared;var d=c.pending;d===null?l.next=l:(l.next=d.next,d.next=l),c.pending=l}}i.lanes|=n,l=i.alternate,l!==null&&(l.lanes|=n),Cl(i.return,n,t),a.lanes|=n;break}l=l.next}}else if(i.tag===10)o=i.type===t.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(N(341));o.lanes|=n,a=o.alternate,a!==null&&(a.lanes|=n),Cl(o,n,t),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===t){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}ze(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,br(t,n),s=ut(s),r=r(s),t.flags|=1,ze(e,t,r,n),t.child;case 14:return r=t.type,s=ft(r,t.pendingProps),s=ft(r.type,s),Md(e,t,r,s,n);case 15:return Sm(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:ft(r,s),Di(e,t),t.tag=1,He(r)?(e=!0,Zi(t)):e=!1,br(t,n),xm(t,r,s),jl(t,r,s,n),Nl(null,t,r,!0,e,n);case 19:return Em(e,t,n);case 22:return km(e,t,n)}throw Error(N(156,t.tag))};function Um(e,t){return gp(e,t)}function xv(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function ot(e,t,n,r){return new xv(e,t,n,r)}function Ju(e){return e=e.prototype,!(!e||!e.isReactComponent)}function wv(e){if(typeof e=="function")return Ju(e)?1:0;if(e!=null){if(e=e.$$typeof,e===vu)return 11;if(e===xu)return 14}return 2}function pn(e,t){var n=e.alternate;return n===null?(n=ot(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Fi(e,t,n,r,s,i){var o=2;if(r=e,typeof e=="function")Ju(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case nr:return On(n.children,s,i,t);case yu:o=8,s|=8;break;case Xa:return e=ot(12,n,t,s|2),e.elementType=Xa,e.lanes=i,e;case Qa:return e=ot(13,n,t,s),e.elementType=Qa,e.lanes=i,e;case Za:return e=ot(19,n,t,s),e.elementType=Za,e.lanes=i,e;case Jh:return Fo(n,s,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case Qh:o=10;break e;case Zh:o=9;break e;case vu:o=11;break e;case xu:o=14;break e;case Qt:o=16,r=null;break e}throw Error(N(130,e==null?e:typeof e,""))}return t=ot(o,n,t,s),t.elementType=e,t.type=r,t.lanes=i,t}function On(e,t,n,r){return e=ot(7,e,r,t),e.lanes=n,e}function Fo(e,t,n,r){return e=ot(22,e,r,t),e.elementType=Jh,e.lanes=n,e.stateNode={isHidden:!1},e}function ja(e,t,n){return e=ot(6,e,null,t),e.lanes=n,e}function Ea(e,t,n){return t=ot(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function bv(e,t,n,r,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=aa(0),this.expirationTimes=aa(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=aa(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function ec(e,t,n,r,s,i,o,a,l){return e=new bv(e,t,n,a,l),t===1?(t=1,i===!0&&(t|=8)):t=0,i=ot(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Fu(i),e}function Sv(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(Gm)}catch(e){console.error(e)}}Gm(),Gh.exports=Je;var Ev=Gh.exports,Wd=Ev;Ya.createRoot=Wd.createRoot,Ya.hydrateRoot=Wd.hydrateRoot;/** - * @remix-run/router v1.23.0 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function Is(){return Is=Object.assign?Object.assign.bind():function(e){for(var t=1;t"u")throw new Error(t)}function Ym(e,t){if(!e){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function Nv(){return Math.random().toString(36).substr(2,8)}function qd(e,t){return{usr:e.state,key:e.key,idx:t}}function $l(e,t,n,r){return n===void 0&&(n=null),Is({pathname:typeof e=="string"?e:e.pathname,search:"",hash:""},typeof t=="string"?Or(t):t,{state:n,key:t&&t.key||r||Nv()})}function ho(e){let{pathname:t="/",search:n="",hash:r=""}=e;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function Or(e){let t={};if(e){let n=e.indexOf("#");n>=0&&(t.hash=e.substr(n),e=e.substr(0,n));let r=e.indexOf("?");r>=0&&(t.search=e.substr(r),e=e.substr(0,r)),e&&(t.pathname=e)}return t}function Mv(e,t,n,r){r===void 0&&(r={});let{window:s=document.defaultView,v5Compat:i=!1}=r,o=s.history,a=on.Pop,l=null,c=d();c==null&&(c=0,o.replaceState(Is({},o.state,{idx:c}),""));function d(){return(o.state||{idx:null}).idx}function f(){a=on.Pop;let w=d(),v=w==null?null:w-c;c=w,l&&l({action:a,location:g.location,delta:v})}function u(w,v){a=on.Push;let y=$l(g.location,w,v);c=d()+1;let x=qd(y,c),b=g.createHref(y);try{o.pushState(x,"",b)}catch(S){if(S instanceof DOMException&&S.name==="DataCloneError")throw S;s.location.assign(b)}i&&l&&l({action:a,location:g.location,delta:1})}function h(w,v){a=on.Replace;let y=$l(g.location,w,v);c=d();let x=qd(y,c),b=g.createHref(y);o.replaceState(x,"",b),i&&l&&l({action:a,location:g.location,delta:0})}function p(w){let v=s.location.origin!=="null"?s.location.origin:s.location.href,y=typeof w=="string"?w:ho(w);return y=y.replace(/ $/,"%20"),me(v,"No window.location.(origin|href) available to create URL for href: "+y),new URL(y,v)}let g={get action(){return a},get location(){return e(s,o)},listen(w){if(l)throw new Error("A history only accepts one active listener");return s.addEventListener(Hd,f),l=w,()=>{s.removeEventListener(Hd,f),l=null}},createHref(w){return t(s,w)},createURL:p,encodeLocation(w){let v=p(w);return{pathname:v.pathname,search:v.search,hash:v.hash}},push:u,replace:h,go(w){return o.go(w)}};return g}var Gd;(function(e){e.data="data",e.deferred="deferred",e.redirect="redirect",e.error="error"})(Gd||(Gd={}));function _v(e,t,n){return n===void 0&&(n="/"),Av(e,t,n)}function Av(e,t,n,r){let s=typeof t=="string"?Or(t):t,i=sc(s.pathname||"/",n);if(i==null)return null;let o=Km(e);Lv(o);let a=null;for(let l=0;a==null&&l{let l={relativePath:a===void 0?i.path||"":a,caseSensitive:i.caseSensitive===!0,childrenIndex:o,route:i};l.relativePath.startsWith("/")&&(me(l.relativePath.startsWith(r),'Absolute route path "'+l.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),l.relativePath=l.relativePath.slice(r.length));let c=mn([r,l.relativePath]),d=n.concat(l);i.children&&i.children.length>0&&(me(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+c+'".')),Km(i.children,t,d,c)),!(i.path==null&&!i.index)&&t.push({path:c,score:Ov(c,i.index),routesMeta:d})};return e.forEach((i,o)=>{var a;if(i.path===""||!((a=i.path)!=null&&a.includes("?")))s(i,o);else for(let l of Xm(i.path))s(i,o,l)}),t}function Xm(e){let t=e.split("/");if(t.length===0)return[];let[n,...r]=t,s=n.endsWith("?"),i=n.replace(/\?$/,"");if(r.length===0)return s?[i,""]:[i];let o=Xm(r.join("/")),a=[];return a.push(...o.map(l=>l===""?i:[i,l].join("/"))),s&&a.push(...o),a.map(l=>e.startsWith("/")&&l===""?"/":l)}function Lv(e){e.sort((t,n)=>t.score!==n.score?n.score-t.score:$v(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const Dv=/^:[\w-]+$/,Rv=3,Vv=2,Fv=1,zv=10,Iv=-2,Yd=e=>e==="*";function Ov(e,t){let n=e.split("/"),r=n.length;return n.some(Yd)&&(r+=Iv),t&&(r+=Vv),n.filter(s=>!Yd(s)).reduce((s,i)=>s+(Dv.test(i)?Rv:i===""?Fv:zv),r)}function $v(e,t){return e.length===t.length&&e.slice(0,-1).every((r,s)=>r===t[s])?e[e.length-1]-t[t.length-1]:0}function Bv(e,t,n){let{routesMeta:r}=e,s={},i="/",o=[];for(let a=0;a{let{paramName:u,isOptional:h}=d;if(u==="*"){let g=a[f]||"";o=i.slice(0,i.length-g.length).replace(/(.)\/+$/,"$1")}const p=a[f];return h&&!p?c[u]=void 0:c[u]=(p||"").replace(/%2F/g,"/"),c},{}),pathname:i,pathnameBase:o,pattern:e}}function Wv(e,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Ym(e==="*"||!e.endsWith("*")||e.endsWith("/*"),'Route path "'+e+'" will be treated as if it were '+('"'+e.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+e.replace(/\*$/,"/*")+'".'));let r=[],s="^"+e.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(o,a,l)=>(r.push({paramName:a,isOptional:l!=null}),l?"/?([^\\/]+)?":"/([^\\/]+)"));return e.endsWith("*")?(r.push({paramName:"*"}),s+=e==="*"||e==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?s+="\\/*$":e!==""&&e!=="/"&&(s+="(?:(?=\\/|$))"),[new RegExp(s,t?void 0:"i"),r]}function Hv(e){try{return e.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Ym(!1,'The URL path "'+e+'" could not be decoded because it is is a malformed URL segment. This is probably due to a bad percent '+("encoding ("+t+").")),e}}function sc(e,t){if(t==="/")return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=e.charAt(n);return r&&r!=="/"?null:e.slice(n)||"/"}function qv(e,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:s=""}=typeof e=="string"?Or(e):e;return{pathname:n?n.startsWith("/")?n:Gv(n,t):t,search:Xv(r),hash:Qv(s)}}function Gv(e,t){let n=t.replace(/\/+$/,"").split("/");return e.split("/").forEach(s=>{s===".."?n.length>1&&n.pop():s!=="."&&n.push(s)}),n.length>1?n.join("/"):"/"}function Ta(e,t,n,r){return"Cannot include a '"+e+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function Yv(e){return e.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function ic(e,t){let n=Yv(e);return t?n.map((r,s)=>s===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function oc(e,t,n,r){r===void 0&&(r=!1);let s;typeof e=="string"?s=Or(e):(s=Is({},e),me(!s.pathname||!s.pathname.includes("?"),Ta("?","pathname","search",s)),me(!s.pathname||!s.pathname.includes("#"),Ta("#","pathname","hash",s)),me(!s.search||!s.search.includes("#"),Ta("#","search","hash",s)));let i=e===""||s.pathname==="",o=i?"/":s.pathname,a;if(o==null)a=n;else{let f=t.length-1;if(!r&&o.startsWith("..")){let u=o.split("/");for(;u[0]==="..";)u.shift(),f-=1;s.pathname=u.join("/")}a=f>=0?t[f]:"/"}let l=qv(s,a),c=o&&o!=="/"&&o.endsWith("/"),d=(i||o===".")&&n.endsWith("/");return!l.pathname.endsWith("/")&&(c||d)&&(l.pathname+="/"),l}const mn=e=>e.join("/").replace(/\/\/+/g,"/"),Kv=e=>e.replace(/\/+$/,"").replace(/^\/*/,"/"),Xv=e=>!e||e==="?"?"":e.startsWith("?")?e:"?"+e,Qv=e=>!e||e==="#"?"":e.startsWith("#")?e:"#"+e;function Zv(e){return e!=null&&typeof e.status=="number"&&typeof e.statusText=="string"&&typeof e.internal=="boolean"&&"data"in e}const Qm=["post","put","patch","delete"];new Set(Qm);const Jv=["get",...Qm];new Set(Jv);/** - * React Router v6.30.1 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function Os(){return Os=Object.assign?Object.assign.bind():function(e){for(var t=1;t{a.current=!0}),k.useCallback(function(c,d){if(d===void 0&&(d={}),!a.current)return;if(typeof c=="number"){r.go(c);return}let f=oc(c,JSON.parse(o),i,d.relative==="path");e==null&&t!=="/"&&(f.pathname=f.pathname==="/"?t:mn([t,f.pathname])),(d.replace?r.replace:r.push)(f,d.state,d)},[t,r,o,i,e])}function e0(e,t){let{relative:n}=t===void 0?{}:t,{future:r}=k.useContext(Cn),{matches:s}=k.useContext(Pn),{pathname:i}=jn(),o=JSON.stringify(ic(s,r.v7_relativeSplatPath));return k.useMemo(()=>oc(e,JSON.parse(o),i,n==="path"),[e,o,i,n])}function rx(e,t){return sx(e,t)}function sx(e,t,n,r){$r()||me(!1);let{navigator:s}=k.useContext(Cn),{matches:i}=k.useContext(Pn),o=i[i.length-1],a=o?o.params:{};o&&o.pathname;let l=o?o.pathnameBase:"/";o&&o.route;let c=jn(),d;if(t){var f;let w=typeof t=="string"?Or(t):t;l==="/"||(f=w.pathname)!=null&&f.startsWith(l)||me(!1),d=w}else d=c;let u=d.pathname||"/",h=u;if(l!=="/"){let w=l.replace(/^\//,"").split("/");h="/"+u.replace(/^\//,"").split("/").slice(w.length).join("/")}let p=_v(e,{pathname:h}),g=ux(p&&p.map(w=>Object.assign({},w,{params:Object.assign({},a,w.params),pathname:mn([l,s.encodeLocation?s.encodeLocation(w.pathname).pathname:w.pathname]),pathnameBase:w.pathnameBase==="/"?l:mn([l,s.encodeLocation?s.encodeLocation(w.pathnameBase).pathname:w.pathnameBase])})),i,n,r);return t&&g?k.createElement(Bo.Provider,{value:{location:Os({pathname:"/",search:"",hash:"",state:null,key:"default"},d),navigationType:on.Pop}},g):g}function ix(){let e=hx(),t=Zv(e)?e.status+" "+e.statusText:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,s={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return k.createElement(k.Fragment,null,k.createElement("h2",null,"Unexpected Application Error!"),k.createElement("h3",{style:{fontStyle:"italic"}},t),n?k.createElement("pre",{style:s},n):null,null)}const ox=k.createElement(ix,null);class ax extends k.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?k.createElement(Pn.Provider,{value:this.props.routeContext},k.createElement(Zm.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function lx(e){let{routeContext:t,match:n,children:r}=e,s=k.useContext(ac);return s&&s.static&&s.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=n.route.id),k.createElement(Pn.Provider,{value:t},r)}function ux(e,t,n,r){var s;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),e==null){var i;if(!n)return null;if(n.errors)e=n.matches;else if((i=r)!=null&&i.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)e=n.matches;else return null}let o=e,a=(s=n)==null?void 0:s.errors;if(a!=null){let d=o.findIndex(f=>f.route.id&&(a==null?void 0:a[f.route.id])!==void 0);d>=0||me(!1),o=o.slice(0,Math.min(o.length,d+1))}let l=!1,c=-1;if(n&&r&&r.v7_partialHydration)for(let d=0;d=0?o=o.slice(0,c+1):o=[o[0]];break}}}return o.reduceRight((d,f,u)=>{let h,p=!1,g=null,w=null;n&&(h=a&&f.route.id?a[f.route.id]:void 0,g=f.route.errorElement||ox,l&&(c<0&&u===0?(mx("route-fallback"),p=!0,w=null):c===u&&(p=!0,w=f.route.hydrateFallbackElement||null)));let v=t.concat(o.slice(0,u+1)),y=()=>{let x;return h?x=g:p?x=w:f.route.Component?x=k.createElement(f.route.Component,null):f.route.element?x=f.route.element:x=d,k.createElement(lx,{match:f,routeContext:{outlet:d,matches:v,isDataRoute:n!=null},children:x})};return n&&(f.route.ErrorBoundary||f.route.errorElement||u===0)?k.createElement(ax,{location:n.location,revalidation:n.revalidation,component:g,error:h,children:y(),routeContext:{outlet:null,matches:v,isDataRoute:!0}}):y()},null)}var t0=function(e){return e.UseBlocker="useBlocker",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e}(t0||{}),n0=function(e){return e.UseBlocker="useBlocker",e.UseLoaderData="useLoaderData",e.UseActionData="useActionData",e.UseRouteError="useRouteError",e.UseNavigation="useNavigation",e.UseRouteLoaderData="useRouteLoaderData",e.UseMatches="useMatches",e.UseRevalidator="useRevalidator",e.UseNavigateStable="useNavigate",e.UseRouteId="useRouteId",e}(n0||{});function cx(e){let t=k.useContext(ac);return t||me(!1),t}function dx(e){let t=k.useContext(ex);return t||me(!1),t}function fx(e){let t=k.useContext(Pn);return t||me(!1),t}function r0(e){let t=fx(),n=t.matches[t.matches.length-1];return n.route.id||me(!1),n.route.id}function hx(){var e;let t=k.useContext(Zm),n=dx(),r=r0();return t!==void 0?t:(e=n.errors)==null?void 0:e[r]}function px(){let{router:e}=cx(t0.UseNavigateStable),t=r0(n0.UseNavigateStable),n=k.useRef(!1);return Jm(()=>{n.current=!0}),k.useCallback(function(s,i){i===void 0&&(i={}),n.current&&(typeof s=="number"?e.navigate(s):e.navigate(s,Os({fromRouteId:t},i)))},[e,t])}const Kd={};function mx(e,t,n){Kd[e]||(Kd[e]=!0)}function gx(e,t){e==null||e.v7_startTransition,e==null||e.v7_relativeSplatPath}function yx(e){let{to:t,replace:n,state:r,relative:s}=e;$r()||me(!1);let{future:i,static:o}=k.useContext(Cn),{matches:a}=k.useContext(Pn),{pathname:l}=jn(),c=Uo(),d=oc(t,ic(a,i.v7_relativeSplatPath),l,s==="path"),f=JSON.stringify(d);return k.useEffect(()=>c(JSON.parse(f),{replace:n,state:r,relative:s}),[c,f,s,n,r]),null}function Mt(e){me(!1)}function vx(e){let{basename:t="/",children:n=null,location:r,navigationType:s=on.Pop,navigator:i,static:o=!1,future:a}=e;$r()&&me(!1);let l=t.replace(/^\/*/,"/"),c=k.useMemo(()=>({basename:l,navigator:i,static:o,future:Os({v7_relativeSplatPath:!1},a)}),[l,a,i,o]);typeof r=="string"&&(r=Or(r));let{pathname:d="/",search:f="",hash:u="",state:h=null,key:p="default"}=r,g=k.useMemo(()=>{let w=sc(d,l);return w==null?null:{location:{pathname:w,search:f,hash:u,state:h,key:p},navigationType:s}},[l,d,f,u,h,p,s]);return g==null?null:k.createElement(Cn.Provider,{value:c},k.createElement(Bo.Provider,{children:n,value:g}))}function xx(e){let{children:t,location:n}=e;return rx(Bl(t),n)}new Promise(()=>{});function Bl(e,t){t===void 0&&(t=[]);let n=[];return k.Children.forEach(e,(r,s)=>{if(!k.isValidElement(r))return;let i=[...t,s];if(r.type===k.Fragment){n.push.apply(n,Bl(r.props.children,i));return}r.type!==Mt&&me(!1),!r.props.index||!r.props.children||me(!1);let o={id:r.props.id||i.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(o.children=Bl(r.props.children,i)),n.push(o)}),n}/** - * React Router DOM v6.30.1 - * - * Copyright (c) Remix Software Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE.md file in the root directory of this source tree. - * - * @license MIT - */function Ul(){return Ul=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0)&&(n[s]=e[s]);return n}function bx(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function Sx(e,t){return e.button===0&&(!t||t==="_self")&&!bx(e)}function Wl(e){return e===void 0&&(e=""),new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(s=>[n,s]):[[n,r]])},[]))}function kx(e,t){let n=Wl(e);return t&&t.forEach((r,s)=>{n.has(s)||t.getAll(s).forEach(i=>{n.append(s,i)})}),n}const Cx=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],Px="6";try{window.__reactRouterVersion=Px}catch{}const jx="startTransition",Xd=gy[jx];function Ex(e){let{basename:t,children:n,future:r,window:s}=e,i=k.useRef();i.current==null&&(i.current=Tv({window:s,v5Compat:!0}));let o=i.current,[a,l]=k.useState({action:o.action,location:o.location}),{v7_startTransition:c}=r||{},d=k.useCallback(f=>{c&&Xd?Xd(()=>l(f)):l(f)},[l,c]);return k.useLayoutEffect(()=>o.listen(d),[o,d]),k.useEffect(()=>gx(r),[r]),k.createElement(vx,{basename:t,children:n,location:a.location,navigationType:a.action,navigator:o,future:r})}const Tx=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Nx=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,zi=k.forwardRef(function(t,n){let{onClick:r,relative:s,reloadDocument:i,replace:o,state:a,target:l,to:c,preventScrollReset:d,viewTransition:f}=t,u=wx(t,Cx),{basename:h}=k.useContext(Cn),p,g=!1;if(typeof c=="string"&&Nx.test(c)&&(p=c,Tx))try{let x=new URL(window.location.href),b=c.startsWith("//")?new URL(x.protocol+c):new URL(c),S=sc(b.pathname,h);b.origin===x.origin&&S!=null?c=S+b.search+b.hash:g=!0}catch{}let w=tx(c,{relative:s}),v=Mx(c,{replace:o,state:a,target:l,preventScrollReset:d,relative:s,viewTransition:f});function y(x){r&&r(x),x.defaultPrevented||v(x)}return k.createElement("a",Ul({},u,{href:p||w,onClick:g||i?r:y,ref:n,target:l}))});var Qd;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(Qd||(Qd={}));var Zd;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(Zd||(Zd={}));function Mx(e,t){let{target:n,replace:r,state:s,preventScrollReset:i,relative:o,viewTransition:a}=t===void 0?{}:t,l=Uo(),c=jn(),d=e0(e,{relative:o});return k.useCallback(f=>{if(Sx(f,n)){f.preventDefault();let u=r!==void 0?r:ho(c)===ho(d);l(e,{replace:u,state:s,preventScrollReset:i,relative:o,viewTransition:a})}},[c,l,d,r,s,n,e,i,o,a])}function _x(e){let t=k.useRef(Wl(e)),n=k.useRef(!1),r=jn(),s=k.useMemo(()=>kx(r.search,n.current?null:t.current),[r.search]),i=Uo(),o=k.useCallback((a,l)=>{const c=Wl(typeof a=="function"?a(s):a);n.current=!0,i("?"+c,l)},[i,s]);return[s,o]}let Ax={data:""},Lx=e=>{if(typeof window=="object"){let t=(e?e.querySelector("#_goober"):window._goober)||Object.assign(document.createElement("style"),{innerHTML:" ",id:"_goober"});return t.nonce=window.__nonce__,t.parentNode||(e||document.head).appendChild(t),t.firstChild}return e||Ax},Dx=/(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g,Rx=/\/\*[^]*?\*\/| +/g,Jd=/\n+/g,nn=(e,t)=>{let n="",r="",s="";for(let i in e){let o=e[i];i[0]=="@"?i[1]=="i"?n=i+" "+o+";":r+=i[1]=="f"?nn(o,i):i+"{"+nn(o,i[1]=="k"?"":t)+"}":typeof o=="object"?r+=nn(o,t?t.replace(/([^,])+/g,a=>i.replace(/([^,]*:\S+\([^)]*\))|([^,])+/g,l=>/&/.test(l)?l.replace(/&/g,a):a?a+" "+l:l)):i):o!=null&&(i=/^--/.test(i)?i:i.replace(/[A-Z]/g,"-$&").toLowerCase(),s+=nn.p?nn.p(i,o):i+":"+o+";")}return n+(t&&s?t+"{"+s+"}":s)+r},Tt={},s0=e=>{if(typeof e=="object"){let t="";for(let n in e)t+=n+s0(e[n]);return t}return e},Vx=(e,t,n,r,s)=>{let i=s0(e),o=Tt[i]||(Tt[i]=(l=>{let c=0,d=11;for(;c>>0;return"go"+d})(i));if(!Tt[o]){let l=i!==e?e:(c=>{let d,f,u=[{}];for(;d=Dx.exec(c.replace(Rx,""));)d[4]?u.shift():d[3]?(f=d[3].replace(Jd," ").trim(),u.unshift(u[0][f]=u[0][f]||{})):u[0][d[1]]=d[2].replace(Jd," ").trim();return u[0]})(e);Tt[o]=nn(s?{["@keyframes "+o]:l}:l,n?"":"."+o)}let a=n&&Tt.g?Tt.g:null;return n&&(Tt.g=Tt[o]),((l,c,d,f)=>{f?c.data=c.data.replace(f,l):c.data.indexOf(l)===-1&&(c.data=d?l+c.data:c.data+l)})(Tt[o],t,r,a),o},Fx=(e,t,n)=>e.reduce((r,s,i)=>{let o=t[i];if(o&&o.call){let a=o(n),l=a&&a.props&&a.props.className||/^go/.test(a)&&a;o=l?"."+l:a&&typeof a=="object"?a.props?"":nn(a,""):a===!1?"":a}return r+s+(o??"")},"");function Wo(e){let t=this||{},n=e.call?e(t.p):e;return Vx(n.unshift?n.raw?Fx(n,[].slice.call(arguments,1),t.p):n.reduce((r,s)=>Object.assign(r,s&&s.call?s(t.p):s),{}):n,Lx(t.target),t.g,t.o,t.k)}let i0,Hl,ql;Wo.bind({g:1});let Wt=Wo.bind({k:1});function zx(e,t,n,r){nn.p=t,i0=e,Hl=n,ql=r}function En(e,t){let n=this||{};return function(){let r=arguments;function s(i,o){let a=Object.assign({},i),l=a.className||s.className;n.p=Object.assign({theme:Hl&&Hl()},a),n.o=/ *go\d+/.test(l),a.className=Wo.apply(n,r)+(l?" "+l:"");let c=e;return e[0]&&(c=a.as||e,delete a.as),ql&&c[0]&&ql(a),i0(c,a)}return s}}var Ix=e=>typeof e=="function",po=(e,t)=>Ix(e)?e(t):e,Ox=(()=>{let e=0;return()=>(++e).toString()})(),o0=(()=>{let e;return()=>{if(e===void 0&&typeof window<"u"){let t=matchMedia("(prefers-reduced-motion: reduce)");e=!t||t.matches}return e}})(),$x=20,lc="default",a0=(e,t)=>{let{toastLimit:n}=e.settings;switch(t.type){case 0:return{...e,toasts:[t.toast,...e.toasts].slice(0,n)};case 1:return{...e,toasts:e.toasts.map(o=>o.id===t.toast.id?{...o,...t.toast}:o)};case 2:let{toast:r}=t;return a0(e,{type:e.toasts.find(o=>o.id===r.id)?1:0,toast:r});case 3:let{toastId:s}=t;return{...e,toasts:e.toasts.map(o=>o.id===s||s===void 0?{...o,dismissed:!0,visible:!1}:o)};case 4:return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(o=>o.id!==t.toastId)};case 5:return{...e,pausedAt:t.time};case 6:let i=t.time-(e.pausedAt||0);return{...e,pausedAt:void 0,toasts:e.toasts.map(o=>({...o,pauseDuration:o.pauseDuration+i}))}}},Ii=[],l0={toasts:[],pausedAt:void 0,settings:{toastLimit:$x}},kt={},u0=(e,t=lc)=>{kt[t]=a0(kt[t]||l0,e),Ii.forEach(([n,r])=>{n===t&&r(kt[t])})},c0=e=>Object.keys(kt).forEach(t=>u0(e,t)),Bx=e=>Object.keys(kt).find(t=>kt[t].toasts.some(n=>n.id===e)),Ho=(e=lc)=>t=>{u0(t,e)},Ux={blank:4e3,error:4e3,success:2e3,loading:1/0,custom:4e3},Wx=(e={},t=lc)=>{let[n,r]=k.useState(kt[t]||l0),s=k.useRef(kt[t]);k.useEffect(()=>(s.current!==kt[t]&&r(kt[t]),Ii.push([t,r]),()=>{let o=Ii.findIndex(([a])=>a===t);o>-1&&Ii.splice(o,1)}),[t]);let i=n.toasts.map(o=>{var a,l,c;return{...e,...e[o.type],...o,removeDelay:o.removeDelay||((a=e[o.type])==null?void 0:a.removeDelay)||(e==null?void 0:e.removeDelay),duration:o.duration||((l=e[o.type])==null?void 0:l.duration)||(e==null?void 0:e.duration)||Ux[o.type],style:{...e.style,...(c=e[o.type])==null?void 0:c.style,...o.style}}});return{...n,toasts:i}},Hx=(e,t="blank",n)=>({createdAt:Date.now(),visible:!0,dismissed:!1,type:t,ariaProps:{role:"status","aria-live":"polite"},message:e,pauseDuration:0,...n,id:(n==null?void 0:n.id)||Ox()}),Qs=e=>(t,n)=>{let r=Hx(t,e,n);return Ho(r.toasterId||Bx(r.id))({type:2,toast:r}),r.id},Se=(e,t)=>Qs("blank")(e,t);Se.error=Qs("error");Se.success=Qs("success");Se.loading=Qs("loading");Se.custom=Qs("custom");Se.dismiss=(e,t)=>{let n={type:3,toastId:e};t?Ho(t)(n):c0(n)};Se.dismissAll=e=>Se.dismiss(void 0,e);Se.remove=(e,t)=>{let n={type:4,toastId:e};t?Ho(t)(n):c0(n)};Se.removeAll=e=>Se.remove(void 0,e);Se.promise=(e,t,n)=>{let r=Se.loading(t.loading,{...n,...n==null?void 0:n.loading});return typeof e=="function"&&(e=e()),e.then(s=>{let i=t.success?po(t.success,s):void 0;return i?Se.success(i,{id:r,...n,...n==null?void 0:n.success}):Se.dismiss(r),s}).catch(s=>{let i=t.error?po(t.error,s):void 0;i?Se.error(i,{id:r,...n,...n==null?void 0:n.error}):Se.dismiss(r)}),e};var qx=1e3,Gx=(e,t="default")=>{let{toasts:n,pausedAt:r}=Wx(e,t),s=k.useRef(new Map).current,i=k.useCallback((f,u=qx)=>{if(s.has(f))return;let h=setTimeout(()=>{s.delete(f),o({type:4,toastId:f})},u);s.set(f,h)},[]);k.useEffect(()=>{if(r)return;let f=Date.now(),u=n.map(h=>{if(h.duration===1/0)return;let p=(h.duration||0)+h.pauseDuration-(f-h.createdAt);if(p<0){h.visible&&Se.dismiss(h.id);return}return setTimeout(()=>Se.dismiss(h.id,t),p)});return()=>{u.forEach(h=>h&&clearTimeout(h))}},[n,r,t]);let o=k.useCallback(Ho(t),[t]),a=k.useCallback(()=>{o({type:5,time:Date.now()})},[o]),l=k.useCallback((f,u)=>{o({type:1,toast:{id:f,height:u}})},[o]),c=k.useCallback(()=>{r&&o({type:6,time:Date.now()})},[r,o]),d=k.useCallback((f,u)=>{let{reverseOrder:h=!1,gutter:p=8,defaultPosition:g}=u||{},w=n.filter(x=>(x.position||g)===(f.position||g)&&x.height),v=w.findIndex(x=>x.id===f.id),y=w.filter((x,b)=>bx.visible).slice(...h?[y+1]:[0,y]).reduce((x,b)=>x+(b.height||0)+p,0)},[n]);return k.useEffect(()=>{n.forEach(f=>{if(f.dismissed)i(f.id,f.removeDelay);else{let u=s.get(f.id);u&&(clearTimeout(u),s.delete(f.id))}})},[n,i]),{toasts:n,handlers:{updateHeight:l,startPause:a,endPause:c,calculateOffset:d}}},Yx=Wt` -from { - transform: scale(0) rotate(45deg); - opacity: 0; -} -to { - transform: scale(1) rotate(45deg); - opacity: 1; -}`,Kx=Wt` -from { - transform: scale(0); - opacity: 0; -} -to { - transform: scale(1); - opacity: 1; -}`,Xx=Wt` -from { - transform: scale(0) rotate(90deg); - opacity: 0; -} -to { - transform: scale(1) rotate(90deg); - opacity: 1; -}`,Qx=En("div")` - width: 20px; - opacity: 0; - height: 20px; - border-radius: 10px; - background: ${e=>e.primary||"#ff4b4b"}; - position: relative; - transform: rotate(45deg); - - animation: ${Yx} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) - forwards; - animation-delay: 100ms; - - &:after, - &:before { - content: ''; - animation: ${Kx} 0.15s ease-out forwards; - animation-delay: 150ms; - position: absolute; - border-radius: 3px; - opacity: 0; - background: ${e=>e.secondary||"#fff"}; - bottom: 9px; - left: 4px; - height: 2px; - width: 12px; - } - - &:before { - animation: ${Xx} 0.15s ease-out forwards; - animation-delay: 180ms; - transform: rotate(90deg); - } -`,Zx=Wt` - from { - transform: rotate(0deg); - } - to { - transform: rotate(360deg); - } -`,Jx=En("div")` - width: 12px; - height: 12px; - box-sizing: border-box; - border: 2px solid; - border-radius: 100%; - border-color: ${e=>e.secondary||"#e0e0e0"}; - border-right-color: ${e=>e.primary||"#616161"}; - animation: ${Zx} 1s linear infinite; -`,e2=Wt` -from { - transform: scale(0) rotate(45deg); - opacity: 0; -} -to { - transform: scale(1) rotate(45deg); - opacity: 1; -}`,t2=Wt` -0% { - height: 0; - width: 0; - opacity: 0; -} -40% { - height: 0; - width: 6px; - opacity: 1; -} -100% { - opacity: 1; - height: 10px; -}`,n2=En("div")` - width: 20px; - opacity: 0; - height: 20px; - border-radius: 10px; - background: ${e=>e.primary||"#61d345"}; - position: relative; - transform: rotate(45deg); - - animation: ${e2} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) - forwards; - animation-delay: 100ms; - &:after { - content: ''; - box-sizing: border-box; - animation: ${t2} 0.2s ease-out forwards; - opacity: 0; - animation-delay: 200ms; - position: absolute; - border-right: 2px solid; - border-bottom: 2px solid; - border-color: ${e=>e.secondary||"#fff"}; - bottom: 6px; - left: 6px; - height: 10px; - width: 6px; - } -`,r2=En("div")` - position: absolute; -`,s2=En("div")` - position: relative; - display: flex; - justify-content: center; - align-items: center; - min-width: 20px; - min-height: 20px; -`,i2=Wt` -from { - transform: scale(0.6); - opacity: 0.4; -} -to { - transform: scale(1); - opacity: 1; -}`,o2=En("div")` - position: relative; - transform: scale(0.6); - opacity: 0.4; - min-width: 20px; - animation: ${i2} 0.3s 0.12s cubic-bezier(0.175, 0.885, 0.32, 1.275) - forwards; -`,a2=({toast:e})=>{let{icon:t,type:n,iconTheme:r}=e;return t!==void 0?typeof t=="string"?k.createElement(o2,null,t):t:n==="blank"?null:k.createElement(s2,null,k.createElement(Jx,{...r}),n!=="loading"&&k.createElement(r2,null,n==="error"?k.createElement(Qx,{...r}):k.createElement(n2,{...r})))},l2=e=>` -0% {transform: translate3d(0,${e*-200}%,0) scale(.6); opacity:.5;} -100% {transform: translate3d(0,0,0) scale(1); opacity:1;} -`,u2=e=>` -0% {transform: translate3d(0,0,-1px) scale(1); opacity:1;} -100% {transform: translate3d(0,${e*-150}%,-1px) scale(.6); opacity:0;} -`,c2="0%{opacity:0;} 100%{opacity:1;}",d2="0%{opacity:1;} 100%{opacity:0;}",f2=En("div")` - display: flex; - align-items: center; - background: #fff; - color: #363636; - line-height: 1.3; - will-change: transform; - box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1), 0 3px 3px rgba(0, 0, 0, 0.05); - max-width: 350px; - pointer-events: auto; - padding: 8px 10px; - border-radius: 8px; -`,h2=En("div")` - display: flex; - justify-content: center; - margin: 4px 10px; - color: inherit; - flex: 1 1 auto; - white-space: pre-line; -`,p2=(e,t)=>{let n=e.includes("top")?1:-1,[r,s]=o0()?[c2,d2]:[l2(n),u2(n)];return{animation:t?`${Wt(r)} 0.35s cubic-bezier(.21,1.02,.73,1) forwards`:`${Wt(s)} 0.4s forwards cubic-bezier(.06,.71,.55,1)`}},m2=k.memo(({toast:e,position:t,style:n,children:r})=>{let s=e.height?p2(e.position||t||"top-center",e.visible):{opacity:0},i=k.createElement(a2,{toast:e}),o=k.createElement(h2,{...e.ariaProps},po(e.message,e));return k.createElement(f2,{className:e.className,style:{...s,...n,...e.style}},typeof r=="function"?r({icon:i,message:o}):k.createElement(k.Fragment,null,i,o))});zx(k.createElement);var g2=({id:e,className:t,style:n,onHeightUpdate:r,children:s})=>{let i=k.useCallback(o=>{if(o){let a=()=>{let l=o.getBoundingClientRect().height;r(e,l)};a(),new MutationObserver(a).observe(o,{subtree:!0,childList:!0,characterData:!0})}},[e,r]);return k.createElement("div",{ref:i,className:t,style:n},s)},y2=(e,t)=>{let n=e.includes("top"),r=n?{top:0}:{bottom:0},s=e.includes("center")?{justifyContent:"center"}:e.includes("right")?{justifyContent:"flex-end"}:{};return{left:0,right:0,display:"flex",position:"absolute",transition:o0()?void 0:"all 230ms cubic-bezier(.21,1.02,.73,1)",transform:`translateY(${t*(n?1:-1)}px)`,...r,...s}},v2=Wo` - z-index: 9999; - > * { - pointer-events: auto; - } -`,wi=16,x2=({reverseOrder:e,position:t="top-center",toastOptions:n,gutter:r,children:s,toasterId:i,containerStyle:o,containerClassName:a})=>{let{toasts:l,handlers:c}=Gx(n,i);return k.createElement("div",{"data-rht-toaster":i||"",style:{position:"fixed",zIndex:9999,top:wi,left:wi,right:wi,bottom:wi,pointerEvents:"none",...o},className:a,onMouseEnter:c.startPause,onMouseLeave:c.endPause},l.map(d=>{let f=d.position||t,u=c.calculateOffset(d,{reverseOrder:e,gutter:r,defaultPosition:t}),h=y2(f,u);return k.createElement(g2,{id:d.id,key:d.id,onHeightUpdate:c.updateHeight,className:d.visible?v2:"",style:h},d.type==="custom"?po(d.message,d):s?s(d):k.createElement(m2,{toast:d,position:f}))}))},Pe=Se;const d0=k.createContext({transformPagePoint:e=>e,isStatic:!1,reducedMotion:"never"}),qo=k.createContext({}),uc=k.createContext(null),Go=typeof document<"u",w2=Go?k.useLayoutEffect:k.useEffect,f0=k.createContext({strict:!1}),cc=e=>e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),b2="framerAppearId",h0="data-"+cc(b2);function S2(e,t,n,r){const{visualElement:s}=k.useContext(qo),i=k.useContext(f0),o=k.useContext(uc),a=k.useContext(d0).reducedMotion,l=k.useRef();r=r||i.renderer,!l.current&&r&&(l.current=r(e,{visualState:t,parent:s,props:n,presenceContext:o,blockInitialAnimation:o?o.initial===!1:!1,reducedMotionConfig:a}));const c=l.current;k.useInsertionEffect(()=>{c&&c.update(n,o)});const d=k.useRef(!!(n[h0]&&!window.HandoffComplete));return w2(()=>{c&&(c.render(),d.current&&c.animationState&&c.animationState.animateChanges())}),k.useEffect(()=>{c&&(c.updateFeatures(),!d.current&&c.animationState&&c.animationState.animateChanges(),d.current&&(d.current=!1,window.HandoffComplete=!0))}),c}function hr(e){return e&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"current")}function k2(e,t,n){return k.useCallback(r=>{r&&e.mount&&e.mount(r),t&&(r?t.mount(r):t.unmount()),n&&(typeof n=="function"?n(r):hr(n)&&(n.current=r))},[t])}function $s(e){return typeof e=="string"||Array.isArray(e)}function Yo(e){return e!==null&&typeof e=="object"&&typeof e.start=="function"}const dc=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],fc=["initial",...dc];function Ko(e){return Yo(e.animate)||fc.some(t=>$s(e[t]))}function p0(e){return!!(Ko(e)||e.variants)}function C2(e,t){if(Ko(e)){const{initial:n,animate:r}=e;return{initial:n===!1||$s(n)?n:void 0,animate:$s(r)?r:void 0}}return e.inherit!==!1?t:{}}function P2(e){const{initial:t,animate:n}=C2(e,k.useContext(qo));return k.useMemo(()=>({initial:t,animate:n}),[ef(t),ef(n)])}function ef(e){return Array.isArray(e)?e.join(" "):e}const tf={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]},Bs={};for(const e in tf)Bs[e]={isEnabled:t=>tf[e].some(n=>!!t[n])};function j2(e){for(const t in e)Bs[t]={...Bs[t],...e[t]}}const m0=k.createContext({}),g0=k.createContext({}),E2=Symbol.for("motionComponentSymbol");function T2({preloadedFeatures:e,createVisualElement:t,useRender:n,useVisualState:r,Component:s}){e&&j2(e);function i(a,l){let c;const d={...k.useContext(d0),...a,layoutId:N2(a)},{isStatic:f}=d,u=P2(a),h=r(a,f);if(!f&&Go){u.visualElement=S2(s,h,d,t);const p=k.useContext(g0),g=k.useContext(f0).strict;u.visualElement&&(c=u.visualElement.loadFeatures(d,g,e,p))}return k.createElement(qo.Provider,{value:u},c&&u.visualElement?k.createElement(c,{visualElement:u.visualElement,...d}):null,n(s,a,k2(h,u.visualElement,l),h,f,u.visualElement))}const o=k.forwardRef(i);return o[E2]=s,o}function N2({layoutId:e}){const t=k.useContext(m0).id;return t&&e!==void 0?t+"-"+e:e}function M2(e){function t(r,s={}){return T2(e(r,s))}if(typeof Proxy>"u")return t;const n=new Map;return new Proxy(t,{get:(r,s)=>(n.has(s)||n.set(s,t(s)),n.get(s))})}const _2=["animate","circle","defs","desc","ellipse","g","image","line","filter","marker","mask","metadata","path","pattern","polygon","polyline","rect","stop","switch","symbol","svg","text","tspan","use","view"];function hc(e){return typeof e!="string"||e.includes("-")?!1:!!(_2.indexOf(e)>-1||/[A-Z]/.test(e))}const mo={};function A2(e){Object.assign(mo,e)}const Zs=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Xn=new Set(Zs);function y0(e,{layout:t,layoutId:n}){return Xn.has(e)||e.startsWith("origin")||(t||n!==void 0)&&(!!mo[e]||e==="opacity")}const Ge=e=>!!(e&&e.getVelocity),L2={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},D2=Zs.length;function R2(e,{enableHardwareAcceleration:t=!0,allowTransformNone:n=!0},r,s){let i="";for(let o=0;ot=>typeof t=="string"&&t.startsWith(e),x0=v0("--"),Gl=v0("var(--"),V2=/var\s*\(\s*--[\w-]+(\s*,\s*(?:(?:[^)(]|\((?:[^)(]+|\([^)(]*\))*\))*)+)?\s*\)/g,F2=(e,t)=>t&&typeof e=="number"?t.transform(e):e,xn=(e,t,n)=>Math.min(Math.max(n,e),t),Qn={test:e=>typeof e=="number",parse:parseFloat,transform:e=>e},gs={...Qn,transform:e=>xn(0,1,e)},bi={...Qn,default:1},ys=e=>Math.round(e*1e5)/1e5,Xo=/(-)?([\d]*\.?[\d])+/g,w0=/(#[0-9a-f]{3,8}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))/gi,z2=/^(#[0-9a-f]{3,8}|(rgb|hsl)a?\((-?[\d\.]+%?[,\s]+){2}(-?[\d\.]+%?)\s*[\,\/]?\s*[\d\.]*%?\))$/i;function Js(e){return typeof e=="string"}const ei=e=>({test:t=>Js(t)&&t.endsWith(e)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${e}`}),Xt=ei("deg"),Et=ei("%"),U=ei("px"),I2=ei("vh"),O2=ei("vw"),nf={...Et,parse:e=>Et.parse(e)/100,transform:e=>Et.transform(e*100)},rf={...Qn,transform:Math.round},b0={borderWidth:U,borderTopWidth:U,borderRightWidth:U,borderBottomWidth:U,borderLeftWidth:U,borderRadius:U,radius:U,borderTopLeftRadius:U,borderTopRightRadius:U,borderBottomRightRadius:U,borderBottomLeftRadius:U,width:U,maxWidth:U,height:U,maxHeight:U,size:U,top:U,right:U,bottom:U,left:U,padding:U,paddingTop:U,paddingRight:U,paddingBottom:U,paddingLeft:U,margin:U,marginTop:U,marginRight:U,marginBottom:U,marginLeft:U,rotate:Xt,rotateX:Xt,rotateY:Xt,rotateZ:Xt,scale:bi,scaleX:bi,scaleY:bi,scaleZ:bi,skew:Xt,skewX:Xt,skewY:Xt,distance:U,translateX:U,translateY:U,translateZ:U,x:U,y:U,z:U,perspective:U,transformPerspective:U,opacity:gs,originX:nf,originY:nf,originZ:U,zIndex:rf,fillOpacity:gs,strokeOpacity:gs,numOctaves:rf};function pc(e,t,n,r){const{style:s,vars:i,transform:o,transformOrigin:a}=e;let l=!1,c=!1,d=!0;for(const f in t){const u=t[f];if(x0(f)){i[f]=u;continue}const h=b0[f],p=F2(u,h);if(Xn.has(f)){if(l=!0,o[f]=p,!d)continue;u!==(h.default||0)&&(d=!1)}else f.startsWith("origin")?(c=!0,a[f]=p):s[f]=p}if(t.transform||(l||r?s.transform=R2(e.transform,n,d,r):s.transform&&(s.transform="none")),c){const{originX:f="50%",originY:u="50%",originZ:h=0}=a;s.transformOrigin=`${f} ${u} ${h}`}}const mc=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function S0(e,t,n){for(const r in t)!Ge(t[r])&&!y0(r,n)&&(e[r]=t[r])}function $2({transformTemplate:e},t,n){return k.useMemo(()=>{const r=mc();return pc(r,t,{enableHardwareAcceleration:!n},e),Object.assign({},r.vars,r.style)},[t])}function B2(e,t,n){const r=e.style||{},s={};return S0(s,r,e),Object.assign(s,$2(e,t,n)),e.transformValues?e.transformValues(s):s}function U2(e,t,n){const r={},s=B2(e,t,n);return e.drag&&e.dragListener!==!1&&(r.draggable=!1,s.userSelect=s.WebkitUserSelect=s.WebkitTouchCallout="none",s.touchAction=e.drag===!0?"none":`pan-${e.drag==="x"?"y":"x"}`),e.tabIndex===void 0&&(e.onTap||e.onTapStart||e.whileTap)&&(r.tabIndex=0),r.style=s,r}const W2=new Set(["animate","exit","variants","initial","style","values","variants","transition","transformTemplate","transformValues","custom","inherit","onBeforeLayoutMeasure","onAnimationStart","onAnimationComplete","onUpdate","onDragStart","onDrag","onDragEnd","onMeasureDragConstraints","onDirectionLock","onDragTransitionEnd","_dragX","_dragY","onHoverStart","onHoverEnd","onViewportEnter","onViewportLeave","globalTapTarget","ignoreStrict","viewport"]);function go(e){return e.startsWith("while")||e.startsWith("drag")&&e!=="draggable"||e.startsWith("layout")||e.startsWith("onTap")||e.startsWith("onPan")||e.startsWith("onLayout")||W2.has(e)}let k0=e=>!go(e);function H2(e){e&&(k0=t=>t.startsWith("on")?!go(t):e(t))}try{H2(require("@emotion/is-prop-valid").default)}catch{}function q2(e,t,n){const r={};for(const s in e)s==="values"&&typeof e.values=="object"||(k0(s)||n===!0&&go(s)||!t&&!go(s)||e.draggable&&s.startsWith("onDrag"))&&(r[s]=e[s]);return r}function sf(e,t,n){return typeof e=="string"?e:U.transform(t+n*e)}function G2(e,t,n){const r=sf(t,e.x,e.width),s=sf(n,e.y,e.height);return`${r} ${s}`}const Y2={offset:"stroke-dashoffset",array:"stroke-dasharray"},K2={offset:"strokeDashoffset",array:"strokeDasharray"};function X2(e,t,n=1,r=0,s=!0){e.pathLength=1;const i=s?Y2:K2;e[i.offset]=U.transform(-r);const o=U.transform(t),a=U.transform(n);e[i.array]=`${o} ${a}`}function gc(e,{attrX:t,attrY:n,attrScale:r,originX:s,originY:i,pathLength:o,pathSpacing:a=1,pathOffset:l=0,...c},d,f,u){if(pc(e,c,d,u),f){e.style.viewBox&&(e.attrs.viewBox=e.style.viewBox);return}e.attrs=e.style,e.style={};const{attrs:h,style:p,dimensions:g}=e;h.transform&&(g&&(p.transform=h.transform),delete h.transform),g&&(s!==void 0||i!==void 0||p.transform)&&(p.transformOrigin=G2(g,s!==void 0?s:.5,i!==void 0?i:.5)),t!==void 0&&(h.x=t),n!==void 0&&(h.y=n),r!==void 0&&(h.scale=r),o!==void 0&&X2(h,o,a,l,!1)}const C0=()=>({...mc(),attrs:{}}),yc=e=>typeof e=="string"&&e.toLowerCase()==="svg";function Q2(e,t,n,r){const s=k.useMemo(()=>{const i=C0();return gc(i,t,{enableHardwareAcceleration:!1},yc(r),e.transformTemplate),{...i.attrs,style:{...i.style}}},[t]);if(e.style){const i={};S0(i,e.style,e),s.style={...i,...s.style}}return s}function Z2(e=!1){return(n,r,s,{latestValues:i},o)=>{const l=(hc(n)?Q2:U2)(r,i,o,n),d={...q2(r,typeof n=="string",e),...l,ref:s},{children:f}=r,u=k.useMemo(()=>Ge(f)?f.get():f,[f]);return k.createElement(n,{...d,children:u})}}function P0(e,{style:t,vars:n},r,s){Object.assign(e.style,t,s&&s.getProjectionStyles(r));for(const i in n)e.style.setProperty(i,n[i])}const j0=new Set(["baseFrequency","diffuseConstant","kernelMatrix","kernelUnitLength","keySplines","keyTimes","limitingConeAngle","markerHeight","markerWidth","numOctaves","targetX","targetY","surfaceScale","specularConstant","specularExponent","stdDeviation","tableValues","viewBox","gradientTransform","pathLength","startOffset","textLength","lengthAdjust"]);function E0(e,t,n,r){P0(e,t,void 0,r);for(const s in t.attrs)e.setAttribute(j0.has(s)?s:cc(s),t.attrs[s])}function vc(e,t){const{style:n}=e,r={};for(const s in n)(Ge(n[s])||t.style&&Ge(t.style[s])||y0(s,e))&&(r[s]=n[s]);return r}function T0(e,t){const n=vc(e,t);for(const r in e)if(Ge(e[r])||Ge(t[r])){const s=Zs.indexOf(r)!==-1?"attr"+r.charAt(0).toUpperCase()+r.substring(1):r;n[s]=e[r]}return n}function xc(e,t,n,r={},s={}){return typeof t=="function"&&(t=t(n!==void 0?n:e.custom,r,s)),typeof t=="string"&&(t=e.variants&&e.variants[t]),typeof t=="function"&&(t=t(n!==void 0?n:e.custom,r,s)),t}function J2(e){const t=k.useRef(null);return t.current===null&&(t.current=e()),t.current}const yo=e=>Array.isArray(e),ew=e=>!!(e&&typeof e=="object"&&e.mix&&e.toValue),tw=e=>yo(e)?e[e.length-1]||0:e;function Oi(e){const t=Ge(e)?e.get():e;return ew(t)?t.toValue():t}function nw({scrapeMotionValuesFromProps:e,createRenderState:t,onMount:n},r,s,i){const o={latestValues:rw(r,s,i,e),renderState:t()};return n&&(o.mount=a=>n(r,a,o)),o}const N0=e=>(t,n)=>{const r=k.useContext(qo),s=k.useContext(uc),i=()=>nw(e,t,r,s);return n?i():J2(i)};function rw(e,t,n,r){const s={},i=r(e,{});for(const u in i)s[u]=Oi(i[u]);let{initial:o,animate:a}=e;const l=Ko(e),c=p0(e);t&&c&&!l&&e.inherit!==!1&&(o===void 0&&(o=t.initial),a===void 0&&(a=t.animate));let d=n?n.initial===!1:!1;d=d||o===!1;const f=d?a:o;return f&&typeof f!="boolean"&&!Yo(f)&&(Array.isArray(f)?f:[f]).forEach(h=>{const p=xc(e,h);if(!p)return;const{transitionEnd:g,transition:w,...v}=p;for(const y in v){let x=v[y];if(Array.isArray(x)){const b=d?x.length-1:0;x=x[b]}x!==null&&(s[y]=x)}for(const y in g)s[y]=g[y]}),s}const pe=e=>e;class of{constructor(){this.order=[],this.scheduled=new Set}add(t){if(!this.scheduled.has(t))return this.scheduled.add(t),this.order.push(t),!0}remove(t){const n=this.order.indexOf(t);n!==-1&&(this.order.splice(n,1),this.scheduled.delete(t))}clear(){this.order.length=0,this.scheduled.clear()}}function sw(e){let t=new of,n=new of,r=0,s=!1,i=!1;const o=new WeakSet,a={schedule:(l,c=!1,d=!1)=>{const f=d&&s,u=f?t:n;return c&&o.add(l),u.add(l)&&f&&s&&(r=t.order.length),l},cancel:l=>{n.remove(l),o.delete(l)},process:l=>{if(s){i=!0;return}if(s=!0,[t,n]=[n,t],n.clear(),r=t.order.length,r)for(let c=0;c(f[u]=sw(()=>n=!0),f),{}),o=f=>i[f].process(s),a=()=>{const f=performance.now();n=!1,s.delta=r?1e3/60:Math.max(Math.min(f-s.timestamp,iw),1),s.timestamp=f,s.isProcessing=!0,Si.forEach(o),s.isProcessing=!1,n&&t&&(r=!1,e(a))},l=()=>{n=!0,r=!0,s.isProcessing||e(a)};return{schedule:Si.reduce((f,u)=>{const h=i[u];return f[u]=(p,g=!1,w=!1)=>(n||l(),h.schedule(p,g,w)),f},{}),cancel:f=>Si.forEach(u=>i[u].cancel(f)),state:s,steps:i}}const{schedule:se,cancel:Ht,state:De,steps:Na}=ow(typeof requestAnimationFrame<"u"?requestAnimationFrame:pe,!0),aw={useVisualState:N0({scrapeMotionValuesFromProps:T0,createRenderState:C0,onMount:(e,t,{renderState:n,latestValues:r})=>{se.read(()=>{try{n.dimensions=typeof t.getBBox=="function"?t.getBBox():t.getBoundingClientRect()}catch{n.dimensions={x:0,y:0,width:0,height:0}}}),se.render(()=>{gc(n,r,{enableHardwareAcceleration:!1},yc(t.tagName),e.transformTemplate),E0(t,n)})}})},lw={useVisualState:N0({scrapeMotionValuesFromProps:vc,createRenderState:mc})};function uw(e,{forwardMotionProps:t=!1},n,r){return{...hc(e)?aw:lw,preloadedFeatures:n,useRender:Z2(t),createVisualElement:r,Component:e}}function Rt(e,t,n,r={passive:!0}){return e.addEventListener(t,n,r),()=>e.removeEventListener(t,n)}const M0=e=>e.pointerType==="mouse"?typeof e.button!="number"||e.button<=0:e.isPrimary!==!1;function Qo(e,t="page"){return{point:{x:e[t+"X"],y:e[t+"Y"]}}}const cw=e=>t=>M0(t)&&e(t,Qo(t));function Ft(e,t,n,r){return Rt(e,t,cw(n),r)}const dw=(e,t)=>n=>t(e(n)),gn=(...e)=>e.reduce(dw);function _0(e){let t=null;return()=>{const n=()=>{t=null};return t===null?(t=e,n):!1}}const af=_0("dragHorizontal"),lf=_0("dragVertical");function A0(e){let t=!1;if(e==="y")t=lf();else if(e==="x")t=af();else{const n=af(),r=lf();n&&r?t=()=>{n(),r()}:(n&&n(),r&&r())}return t}function L0(){const e=A0(!0);return e?(e(),!1):!0}class Tn{constructor(t){this.isMounted=!1,this.node=t}update(){}}function uf(e,t){const n="pointer"+(t?"enter":"leave"),r="onHover"+(t?"Start":"End"),s=(i,o)=>{if(i.pointerType==="touch"||L0())return;const a=e.getProps();e.animationState&&a.whileHover&&e.animationState.setActive("whileHover",t),a[r]&&se.update(()=>a[r](i,o))};return Ft(e.current,n,s,{passive:!e.getProps()[r]})}class fw extends Tn{mount(){this.unmount=gn(uf(this.node,!0),uf(this.node,!1))}unmount(){}}class hw extends Tn{constructor(){super(...arguments),this.isActive=!1}onFocus(){let t=!1;try{t=this.node.current.matches(":focus-visible")}catch{t=!0}!t||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!0),this.isActive=!0)}onBlur(){!this.isActive||!this.node.animationState||(this.node.animationState.setActive("whileFocus",!1),this.isActive=!1)}mount(){this.unmount=gn(Rt(this.node.current,"focus",()=>this.onFocus()),Rt(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}const D0=(e,t)=>t?e===t?!0:D0(e,t.parentElement):!1;function Ma(e,t){if(!t)return;const n=new PointerEvent("pointer"+e);t(n,Qo(n))}class pw extends Tn{constructor(){super(...arguments),this.removeStartListeners=pe,this.removeEndListeners=pe,this.removeAccessibleListeners=pe,this.startPointerPress=(t,n)=>{if(this.isPressing)return;this.removeEndListeners();const r=this.node.getProps(),i=Ft(window,"pointerup",(a,l)=>{if(!this.checkPressEnd())return;const{onTap:c,onTapCancel:d,globalTapTarget:f}=this.node.getProps();se.update(()=>{!f&&!D0(this.node.current,a.target)?d&&d(a,l):c&&c(a,l)})},{passive:!(r.onTap||r.onPointerUp)}),o=Ft(window,"pointercancel",(a,l)=>this.cancelPress(a,l),{passive:!(r.onTapCancel||r.onPointerCancel)});this.removeEndListeners=gn(i,o),this.startPress(t,n)},this.startAccessiblePress=()=>{const t=i=>{if(i.key!=="Enter"||this.isPressing)return;const o=a=>{a.key!=="Enter"||!this.checkPressEnd()||Ma("up",(l,c)=>{const{onTap:d}=this.node.getProps();d&&se.update(()=>d(l,c))})};this.removeEndListeners(),this.removeEndListeners=Rt(this.node.current,"keyup",o),Ma("down",(a,l)=>{this.startPress(a,l)})},n=Rt(this.node.current,"keydown",t),r=()=>{this.isPressing&&Ma("cancel",(i,o)=>this.cancelPress(i,o))},s=Rt(this.node.current,"blur",r);this.removeAccessibleListeners=gn(n,s)}}startPress(t,n){this.isPressing=!0;const{onTapStart:r,whileTap:s}=this.node.getProps();s&&this.node.animationState&&this.node.animationState.setActive("whileTap",!0),r&&se.update(()=>r(t,n))}checkPressEnd(){return this.removeEndListeners(),this.isPressing=!1,this.node.getProps().whileTap&&this.node.animationState&&this.node.animationState.setActive("whileTap",!1),!L0()}cancelPress(t,n){if(!this.checkPressEnd())return;const{onTapCancel:r}=this.node.getProps();r&&se.update(()=>r(t,n))}mount(){const t=this.node.getProps(),n=Ft(t.globalTapTarget?window:this.node.current,"pointerdown",this.startPointerPress,{passive:!(t.onTapStart||t.onPointerStart)}),r=Rt(this.node.current,"focus",this.startAccessiblePress);this.removeStartListeners=gn(n,r)}unmount(){this.removeStartListeners(),this.removeEndListeners(),this.removeAccessibleListeners()}}const Yl=new WeakMap,_a=new WeakMap,mw=e=>{const t=Yl.get(e.target);t&&t(e)},gw=e=>{e.forEach(mw)};function yw({root:e,...t}){const n=e||document;_a.has(n)||_a.set(n,{});const r=_a.get(n),s=JSON.stringify(t);return r[s]||(r[s]=new IntersectionObserver(gw,{root:e,...t})),r[s]}function vw(e,t,n){const r=yw(t);return Yl.set(e,n),r.observe(e),()=>{Yl.delete(e),r.unobserve(e)}}const xw={some:0,all:1};class ww extends Tn{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){this.unmount();const{viewport:t={}}=this.node.getProps(),{root:n,margin:r,amount:s="some",once:i}=t,o={root:n?n.current:void 0,rootMargin:r,threshold:typeof s=="number"?s:xw[s]},a=l=>{const{isIntersecting:c}=l;if(this.isInView===c||(this.isInView=c,i&&!c&&this.hasEnteredView))return;c&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",c);const{onViewportEnter:d,onViewportLeave:f}=this.node.getProps(),u=c?d:f;u&&u(l)};return vw(this.node.current,o,a)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(bw(t,n))&&this.startObserver()}unmount(){}}function bw({viewport:e={}},{viewport:t={}}={}){return n=>e[n]!==t[n]}const Sw={inView:{Feature:ww},tap:{Feature:pw},focus:{Feature:hw},hover:{Feature:fw}};function R0(e,t){if(!Array.isArray(t))return!1;const n=t.length;if(n!==e.length)return!1;for(let r=0;rt[r]=n.get()),t}function Cw(e){const t={};return e.values.forEach((n,r)=>t[r]=n.getVelocity()),t}function Zo(e,t,n){const r=e.getProps();return xc(r,t,n!==void 0?n:r.custom,kw(e),Cw(e))}let wc=pe;const $n=e=>e*1e3,zt=e=>e/1e3,Pw={current:!1},V0=e=>Array.isArray(e)&&typeof e[0]=="number";function F0(e){return!!(!e||typeof e=="string"&&z0[e]||V0(e)||Array.isArray(e)&&e.every(F0))}const os=([e,t,n,r])=>`cubic-bezier(${e}, ${t}, ${n}, ${r})`,z0={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:os([0,.65,.55,1]),circOut:os([.55,0,1,.45]),backIn:os([.31,.01,.66,-.59]),backOut:os([.33,1.53,.69,.99])};function I0(e){if(e)return V0(e)?os(e):Array.isArray(e)?e.map(I0):z0[e]}function jw(e,t,n,{delay:r=0,duration:s,repeat:i=0,repeatType:o="loop",ease:a,times:l}={}){const c={[t]:n};l&&(c.offset=l);const d=I0(a);return Array.isArray(d)&&(c.easing=d),e.animate(c,{delay:r,duration:s,easing:Array.isArray(d)?"linear":d,fill:"both",iterations:i+1,direction:o==="reverse"?"alternate":"normal"})}function Ew(e,{repeat:t,repeatType:n="loop"}){const r=t&&n!=="loop"&&t%2===1?0:e.length-1;return e[r]}const O0=(e,t,n)=>(((1-3*n+3*t)*e+(3*n-6*t))*e+3*t)*e,Tw=1e-7,Nw=12;function Mw(e,t,n,r,s){let i,o,a=0;do o=t+(n-t)/2,i=O0(o,r,s)-e,i>0?n=o:t=o;while(Math.abs(i)>Tw&&++aMw(i,0,1,e,n);return i=>i===0||i===1?i:O0(s(i),t,r)}const _w=ti(.42,0,1,1),Aw=ti(0,0,.58,1),$0=ti(.42,0,.58,1),Lw=e=>Array.isArray(e)&&typeof e[0]!="number",B0=e=>t=>t<=.5?e(2*t)/2:(2-e(2*(1-t)))/2,U0=e=>t=>1-e(1-t),bc=e=>1-Math.sin(Math.acos(e)),W0=U0(bc),Dw=B0(bc),H0=ti(.33,1.53,.69,.99),Sc=U0(H0),Rw=B0(Sc),Vw=e=>(e*=2)<1?.5*Sc(e):.5*(2-Math.pow(2,-10*(e-1))),Fw={linear:pe,easeIn:_w,easeInOut:$0,easeOut:Aw,circIn:bc,circInOut:Dw,circOut:W0,backIn:Sc,backInOut:Rw,backOut:H0,anticipate:Vw},cf=e=>{if(Array.isArray(e)){wc(e.length===4);const[t,n,r,s]=e;return ti(t,n,r,s)}else if(typeof e=="string")return Fw[e];return e},kc=(e,t)=>n=>!!(Js(n)&&z2.test(n)&&n.startsWith(e)||t&&Object.prototype.hasOwnProperty.call(n,t)),q0=(e,t,n)=>r=>{if(!Js(r))return r;const[s,i,o,a]=r.match(Xo);return{[e]:parseFloat(s),[t]:parseFloat(i),[n]:parseFloat(o),alpha:a!==void 0?parseFloat(a):1}},zw=e=>xn(0,255,e),Aa={...Qn,transform:e=>Math.round(zw(e))},zn={test:kc("rgb","red"),parse:q0("red","green","blue"),transform:({red:e,green:t,blue:n,alpha:r=1})=>"rgba("+Aa.transform(e)+", "+Aa.transform(t)+", "+Aa.transform(n)+", "+ys(gs.transform(r))+")"};function Iw(e){let t="",n="",r="",s="";return e.length>5?(t=e.substring(1,3),n=e.substring(3,5),r=e.substring(5,7),s=e.substring(7,9)):(t=e.substring(1,2),n=e.substring(2,3),r=e.substring(3,4),s=e.substring(4,5),t+=t,n+=n,r+=r,s+=s),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(r,16),alpha:s?parseInt(s,16)/255:1}}const Kl={test:kc("#"),parse:Iw,transform:zn.transform},pr={test:kc("hsl","hue"),parse:q0("hue","saturation","lightness"),transform:({hue:e,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(e)+", "+Et.transform(ys(t))+", "+Et.transform(ys(n))+", "+ys(gs.transform(r))+")"},Fe={test:e=>zn.test(e)||Kl.test(e)||pr.test(e),parse:e=>zn.test(e)?zn.parse(e):pr.test(e)?pr.parse(e):Kl.parse(e),transform:e=>Js(e)?e:e.hasOwnProperty("red")?zn.transform(e):pr.transform(e)},ae=(e,t,n)=>-n*e+n*t+e;function La(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*(2/3-n)*6:e}function Ow({hue:e,saturation:t,lightness:n,alpha:r}){e/=360,t/=100,n/=100;let s=0,i=0,o=0;if(!t)s=i=o=n;else{const a=n<.5?n*(1+t):n+t-n*t,l=2*n-a;s=La(l,a,e+1/3),i=La(l,a,e),o=La(l,a,e-1/3)}return{red:Math.round(s*255),green:Math.round(i*255),blue:Math.round(o*255),alpha:r}}const Da=(e,t,n)=>{const r=e*e;return Math.sqrt(Math.max(0,n*(t*t-r)+r))},$w=[Kl,zn,pr],Bw=e=>$w.find(t=>t.test(e));function df(e){const t=Bw(e);let n=t.parse(e);return t===pr&&(n=Ow(n)),n}const G0=(e,t)=>{const n=df(e),r=df(t),s={...n};return i=>(s.red=Da(n.red,r.red,i),s.green=Da(n.green,r.green,i),s.blue=Da(n.blue,r.blue,i),s.alpha=ae(n.alpha,r.alpha,i),zn.transform(s))};function Uw(e){var t,n;return isNaN(e)&&Js(e)&&(((t=e.match(Xo))===null||t===void 0?void 0:t.length)||0)+(((n=e.match(w0))===null||n===void 0?void 0:n.length)||0)>0}const Y0={regex:V2,countKey:"Vars",token:"${v}",parse:pe},K0={regex:w0,countKey:"Colors",token:"${c}",parse:Fe.parse},X0={regex:Xo,countKey:"Numbers",token:"${n}",parse:Qn.parse};function Ra(e,{regex:t,countKey:n,token:r,parse:s}){const i=e.tokenised.match(t);i&&(e["num"+n]=i.length,e.tokenised=e.tokenised.replace(t,r),e.values.push(...i.map(s)))}function vo(e){const t=e.toString(),n={value:t,tokenised:t,values:[],numVars:0,numColors:0,numNumbers:0};return n.value.includes("var(--")&&Ra(n,Y0),Ra(n,K0),Ra(n,X0),n}function Q0(e){return vo(e).values}function Z0(e){const{values:t,numColors:n,numVars:r,tokenised:s}=vo(e),i=t.length;return o=>{let a=s;for(let l=0;ltypeof e=="number"?0:e;function Hw(e){const t=Q0(e);return Z0(e)(t.map(Ww))}const wn={test:Uw,parse:Q0,createTransformer:Z0,getAnimatableNone:Hw},J0=(e,t)=>n=>`${n>0?t:e}`;function eg(e,t){return typeof e=="number"?n=>ae(e,t,n):Fe.test(e)?G0(e,t):e.startsWith("var(")?J0(e,t):ng(e,t)}const tg=(e,t)=>{const n=[...e],r=n.length,s=e.map((i,o)=>eg(i,t[o]));return i=>{for(let o=0;o{const n={...e,...t},r={};for(const s in n)e[s]!==void 0&&t[s]!==void 0&&(r[s]=eg(e[s],t[s]));return s=>{for(const i in r)n[i]=r[i](s);return n}},ng=(e,t)=>{const n=wn.createTransformer(t),r=vo(e),s=vo(t);return r.numVars===s.numVars&&r.numColors===s.numColors&&r.numNumbers>=s.numNumbers?gn(tg(r.values,s.values),n):J0(e,t)},Us=(e,t,n)=>{const r=t-e;return r===0?1:(n-e)/r},ff=(e,t)=>n=>ae(e,t,n);function Gw(e){return typeof e=="number"?ff:typeof e=="string"?Fe.test(e)?G0:ng:Array.isArray(e)?tg:typeof e=="object"?qw:ff}function Yw(e,t,n){const r=[],s=n||Gw(e[0]),i=e.length-1;for(let o=0;ot[0];e[0]>e[i-1]&&(e=[...e].reverse(),t=[...t].reverse());const o=Yw(t,r,s),a=o.length,l=c=>{let d=0;if(a>1)for(;dl(xn(e[0],e[i-1],c)):l}function Kw(e,t){const n=e[e.length-1];for(let r=1;r<=t;r++){const s=Us(0,t,r);e.push(ae(n,1,s))}}function Xw(e){const t=[0];return Kw(t,e.length-1),t}function Qw(e,t){return e.map(n=>n*t)}function Zw(e,t){return e.map(()=>t||$0).splice(0,e.length-1)}function xo({duration:e=300,keyframes:t,times:n,ease:r="easeInOut"}){const s=Lw(r)?r.map(cf):cf(r),i={done:!1,value:t[0]},o=Qw(n&&n.length===t.length?n:Xw(t),e),a=rg(o,t,{ease:Array.isArray(s)?s:Zw(t,s)});return{calculatedDuration:e,next:l=>(i.value=a(l),i.done=l>=e,i)}}function sg(e,t){return t?e*(1e3/t):0}const Jw=5;function ig(e,t,n){const r=Math.max(t-Jw,0);return sg(n-e(r),t-r)}const Va=.001,e5=.01,t5=10,n5=.05,r5=1;function s5({duration:e=800,bounce:t=.25,velocity:n=0,mass:r=1}){let s,i,o=1-t;o=xn(n5,r5,o),e=xn(e5,t5,zt(e)),o<1?(s=c=>{const d=c*o,f=d*e,u=d-n,h=Xl(c,o),p=Math.exp(-f);return Va-u/h*p},i=c=>{const f=c*o*e,u=f*n+n,h=Math.pow(o,2)*Math.pow(c,2)*e,p=Math.exp(-f),g=Xl(Math.pow(c,2),o);return(-s(c)+Va>0?-1:1)*((u-h)*p)/g}):(s=c=>{const d=Math.exp(-c*e),f=(c-n)*e+1;return-Va+d*f},i=c=>{const d=Math.exp(-c*e),f=(n-c)*(e*e);return d*f});const a=5/e,l=o5(s,i,a);if(e=$n(e),isNaN(l))return{stiffness:100,damping:10,duration:e};{const c=Math.pow(l,2)*r;return{stiffness:c,damping:o*2*Math.sqrt(r*c),duration:e}}}const i5=12;function o5(e,t,n){let r=n;for(let s=1;se[n]!==void 0)}function u5(e){let t={velocity:0,stiffness:100,damping:10,mass:1,isResolvedFromDuration:!1,...e};if(!hf(e,l5)&&hf(e,a5)){const n=s5(e);t={...t,...n,mass:1},t.isResolvedFromDuration=!0}return t}function og({keyframes:e,restDelta:t,restSpeed:n,...r}){const s=e[0],i=e[e.length-1],o={done:!1,value:s},{stiffness:a,damping:l,mass:c,duration:d,velocity:f,isResolvedFromDuration:u}=u5({...r,velocity:-zt(r.velocity||0)}),h=f||0,p=l/(2*Math.sqrt(a*c)),g=i-s,w=zt(Math.sqrt(a/c)),v=Math.abs(g)<5;n||(n=v?.01:2),t||(t=v?.005:.5);let y;if(p<1){const x=Xl(w,p);y=b=>{const S=Math.exp(-p*w*b);return i-S*((h+p*w*g)/x*Math.sin(x*b)+g*Math.cos(x*b))}}else if(p===1)y=x=>i-Math.exp(-w*x)*(g+(h+w*g)*x);else{const x=w*Math.sqrt(p*p-1);y=b=>{const S=Math.exp(-p*w*b),C=Math.min(x*b,300);return i-S*((h+p*w*g)*Math.sinh(C)+x*g*Math.cosh(C))/x}}return{calculatedDuration:u&&d||null,next:x=>{const b=y(x);if(u)o.done=x>=d;else{let S=h;x!==0&&(p<1?S=ig(y,x,b):S=0);const C=Math.abs(S)<=n,P=Math.abs(i-b)<=t;o.done=C&&P}return o.value=o.done?i:b,o}}}function pf({keyframes:e,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:s=10,bounceStiffness:i=500,modifyTarget:o,min:a,max:l,restDelta:c=.5,restSpeed:d}){const f=e[0],u={done:!1,value:f},h=j=>a!==void 0&&jl,p=j=>a===void 0?l:l===void 0||Math.abs(a-j)-g*Math.exp(-j/r),x=j=>v+y(j),b=j=>{const _=y(j),T=x(j);u.done=Math.abs(_)<=c,u.value=u.done?v:T};let S,C;const P=j=>{h(u.value)&&(S=j,C=og({keyframes:[u.value,p(u.value)],velocity:ig(x,j,u.value),damping:s,stiffness:i,restDelta:c,restSpeed:d}))};return P(0),{calculatedDuration:null,next:j=>{let _=!1;return!C&&S===void 0&&(_=!0,b(j),P(j)),S!==void 0&&j>S?C.next(j-S):(!_&&b(j),u)}}}const c5=e=>{const t=({timestamp:n})=>e(n);return{start:()=>se.update(t,!0),stop:()=>Ht(t),now:()=>De.isProcessing?De.timestamp:performance.now()}},mf=2e4;function gf(e){let t=0;const n=50;let r=e.next(t);for(;!r.done&&t=mf?1/0:t}const d5={decay:pf,inertia:pf,tween:xo,keyframes:xo,spring:og};function wo({autoplay:e=!0,delay:t=0,driver:n=c5,keyframes:r,type:s="keyframes",repeat:i=0,repeatDelay:o=0,repeatType:a="loop",onPlay:l,onStop:c,onComplete:d,onUpdate:f,...u}){let h=1,p=!1,g,w;const v=()=>{w=new Promise(R=>{g=R})};v();let y;const x=d5[s]||xo;let b;x!==xo&&typeof r[0]!="number"&&(b=rg([0,100],r,{clamp:!1}),r=[0,100]);const S=x({...u,keyframes:r});let C;a==="mirror"&&(C=x({...u,keyframes:[...r].reverse(),velocity:-(u.velocity||0)}));let P="idle",j=null,_=null,T=null;S.calculatedDuration===null&&i&&(S.calculatedDuration=gf(S));const{calculatedDuration:F}=S;let L=1/0,W=1/0;F!==null&&(L=F+o,W=L*(i+1)-o);let A=0;const O=R=>{if(_===null)return;h>0&&(_=Math.min(_,R)),h<0&&(_=Math.min(R-W/h,_)),j!==null?A=j:A=Math.round(R-_)*h;const E=A-t*(h>=0?1:-1),Y=h>=0?E<0:E>W;A=Math.max(E,0),P==="finished"&&j===null&&(A=W);let Q=A,ce=S;if(i){const Zn=Math.min(A,W)/L;let Nn=Math.floor(Zn),xt=Zn%1;!xt&&Zn>=1&&(xt=1),xt===1&&Nn--,Nn=Math.min(Nn,i+1),!!(Nn%2)&&(a==="reverse"?(xt=1-xt,o&&(xt-=o/L)):a==="mirror"&&(ce=C)),Q=xn(0,1,xt)*L}const G=Y?{done:!1,value:r[0]}:ce.next(Q);b&&(G.value=b(G.value));let{done:we}=G;!Y&&F!==null&&(we=h>=0?A>=W:A<=0);const ni=j===null&&(P==="finished"||P==="running"&&we);return f&&f(G.value),ni&&M(),G},B=()=>{y&&y.stop(),y=void 0},K=()=>{P="idle",B(),g(),v(),_=T=null},M=()=>{P="finished",d&&d(),B(),g()},D=()=>{if(p)return;y||(y=n(O));const R=y.now();l&&l(),j!==null?_=R-j:(!_||P==="finished")&&(_=R),P==="finished"&&v(),T=_,j=null,P="running",y.start()};e&&D();const z={then(R,E){return w.then(R,E)},get time(){return zt(A)},set time(R){R=$n(R),A=R,j!==null||!y||h===0?j=R:_=y.now()-R/h},get duration(){const R=S.calculatedDuration===null?gf(S):S.calculatedDuration;return zt(R)},get speed(){return h},set speed(R){R===h||!y||(h=R,z.time=zt(A))},get state(){return P},play:D,pause:()=>{P="paused",j=A},stop:()=>{p=!0,P!=="idle"&&(P="idle",c&&c(),K())},cancel:()=>{T!==null&&O(T),K()},complete:()=>{P="finished"},sample:R=>(_=0,O(R))};return z}function f5(e){let t;return()=>(t===void 0&&(t=e()),t)}const h5=f5(()=>Object.hasOwnProperty.call(Element.prototype,"animate")),p5=new Set(["opacity","clipPath","filter","transform","backgroundColor"]),ki=10,m5=2e4,g5=(e,t)=>t.type==="spring"||e==="backgroundColor"||!F0(t.ease);function y5(e,t,{onUpdate:n,onComplete:r,...s}){if(!(h5()&&p5.has(t)&&!s.repeatDelay&&s.repeatType!=="mirror"&&s.damping!==0&&s.type!=="inertia"))return!1;let o=!1,a,l,c=!1;const d=()=>{l=new Promise(x=>{a=x})};d();let{keyframes:f,duration:u=300,ease:h,times:p}=s;if(g5(t,s)){const x=wo({...s,repeat:0,delay:0});let b={done:!1,value:f[0]};const S=[];let C=0;for(;!b.done&&C{c=!1,g.cancel()},v=()=>{c=!0,se.update(w),a(),d()};return g.onfinish=()=>{c||(e.set(Ew(f,s)),r&&r(),v())},{then(x,b){return l.then(x,b)},attachTimeline(x){return g.timeline=x,g.onfinish=null,pe},get time(){return zt(g.currentTime||0)},set time(x){g.currentTime=$n(x)},get speed(){return g.playbackRate},set speed(x){g.playbackRate=x},get duration(){return zt(u)},play:()=>{o||(g.play(),Ht(w))},pause:()=>g.pause(),stop:()=>{if(o=!0,g.playState==="idle")return;const{currentTime:x}=g;if(x){const b=wo({...s,autoplay:!1});e.setWithVelocity(b.sample(x-ki).value,b.sample(x).value,ki)}v()},complete:()=>{c||g.finish()},cancel:v}}function v5({keyframes:e,delay:t,onUpdate:n,onComplete:r}){const s=()=>(n&&n(e[e.length-1]),r&&r(),{time:0,speed:1,duration:0,play:pe,pause:pe,stop:pe,then:i=>(i(),Promise.resolve()),cancel:pe,complete:pe});return t?wo({keyframes:[0,1],duration:0,delay:t,onComplete:s}):s()}const x5={type:"spring",stiffness:500,damping:25,restSpeed:10},w5=e=>({type:"spring",stiffness:550,damping:e===0?2*Math.sqrt(550):30,restSpeed:10}),b5={type:"keyframes",duration:.8},S5={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},k5=(e,{keyframes:t})=>t.length>2?b5:Xn.has(e)?e.startsWith("scale")?w5(t[1]):x5:S5,Ql=(e,t)=>e==="zIndex"?!1:!!(typeof t=="number"||Array.isArray(t)||typeof t=="string"&&(wn.test(t)||t==="0")&&!t.startsWith("url(")),C5=new Set(["brightness","contrast","saturate","opacity"]);function P5(e){const[t,n]=e.slice(0,-1).split("(");if(t==="drop-shadow")return e;const[r]=n.match(Xo)||[];if(!r)return e;const s=n.replace(r,"");let i=C5.has(t)?1:0;return r!==n&&(i*=100),t+"("+i+s+")"}const j5=/([a-z-]*)\(.*?\)/g,Zl={...wn,getAnimatableNone:e=>{const t=e.match(j5);return t?t.map(P5).join(" "):e}},E5={...b0,color:Fe,backgroundColor:Fe,outlineColor:Fe,fill:Fe,stroke:Fe,borderColor:Fe,borderTopColor:Fe,borderRightColor:Fe,borderBottomColor:Fe,borderLeftColor:Fe,filter:Zl,WebkitFilter:Zl},Cc=e=>E5[e];function ag(e,t){let n=Cc(e);return n!==Zl&&(n=wn),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const lg=e=>/^0[^.\s]+$/.test(e);function T5(e){if(typeof e=="number")return e===0;if(e!==null)return e==="none"||e==="0"||lg(e)}function N5(e,t,n,r){const s=Ql(t,n);let i;Array.isArray(n)?i=[...n]:i=[null,n];const o=r.from!==void 0?r.from:e.get();let a;const l=[];for(let c=0;cs=>{const i=Pc(r,e)||{},o=i.delay||r.delay||0;let{elapsed:a=0}=r;a=a-$n(o);const l=N5(t,e,n,i),c=l[0],d=l[l.length-1],f=Ql(e,c),u=Ql(e,d);let h={keyframes:l,velocity:t.getVelocity(),ease:"easeOut",...i,delay:-a,onUpdate:p=>{t.set(p),i.onUpdate&&i.onUpdate(p)},onComplete:()=>{s(),i.onComplete&&i.onComplete()}};if(M5(i)||(h={...h,...k5(e,h)}),h.duration&&(h.duration=$n(h.duration)),h.repeatDelay&&(h.repeatDelay=$n(h.repeatDelay)),!f||!u||Pw.current||i.type===!1||_5.skipAnimations)return v5(h);if(!r.isHandoff&&t.owner&&t.owner.current instanceof HTMLElement&&!t.owner.getProps().onUpdate){const p=y5(t,e,h);if(p)return p}return wo(h)};function bo(e){return!!(Ge(e)&&e.add)}const ug=e=>/^\-?\d*\.?\d+$/.test(e);function Ec(e,t){e.indexOf(t)===-1&&e.push(t)}function Tc(e,t){const n=e.indexOf(t);n>-1&&e.splice(n,1)}class Nc{constructor(){this.subscriptions=[]}add(t){return Ec(this.subscriptions,t),()=>Tc(this.subscriptions,t)}notify(t,n,r){const s=this.subscriptions.length;if(s)if(s===1)this.subscriptions[0](t,n,r);else for(let i=0;i!isNaN(parseFloat(e));class L5{constructor(t,n={}){this.version="10.18.0",this.timeDelta=0,this.lastUpdated=0,this.canTrackVelocity=!1,this.events={},this.updateAndNotify=(r,s=!0)=>{this.prev=this.current,this.current=r;const{delta:i,timestamp:o}=De;this.lastUpdated!==o&&(this.timeDelta=i,this.lastUpdated=o,se.postRender(this.scheduleVelocityCheck)),this.prev!==this.current&&this.events.change&&this.events.change.notify(this.current),this.events.velocityChange&&this.events.velocityChange.notify(this.getVelocity()),s&&this.events.renderRequest&&this.events.renderRequest.notify(this.current)},this.scheduleVelocityCheck=()=>se.postRender(this.velocityCheck),this.velocityCheck=({timestamp:r})=>{r!==this.lastUpdated&&(this.prev=this.current,this.events.velocityChange&&this.events.velocityChange.notify(this.getVelocity()))},this.hasAnimated=!1,this.prev=this.current=t,this.canTrackVelocity=A5(this.current),this.owner=n.owner}onChange(t){return this.on("change",t)}on(t,n){this.events[t]||(this.events[t]=new Nc);const r=this.events[t].add(n);return t==="change"?()=>{r(),se.read(()=>{this.events.change.getSize()||this.stop()})}:r}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,n){this.passiveEffect=t,this.stopPassiveEffect=n}set(t,n=!0){!n||!this.passiveEffect?this.updateAndNotify(t,n):this.passiveEffect(t,this.updateAndNotify)}setWithVelocity(t,n,r){this.set(n),this.prev=t,this.timeDelta=r}jump(t){this.updateAndNotify(t),this.prev=t,this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}get(){return this.current}getPrevious(){return this.prev}getVelocity(){return this.canTrackVelocity?sg(parseFloat(this.current)-parseFloat(this.prev),this.timeDelta):0}start(t){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=t(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function Ar(e,t){return new L5(e,t)}const cg=e=>t=>t.test(e),D5={test:e=>e==="auto",parse:e=>e},dg=[Qn,U,Et,Xt,O2,I2,D5],Zr=e=>dg.find(cg(e)),R5=[...dg,Fe,wn],V5=e=>R5.find(cg(e));function F5(e,t,n){e.hasValue(t)?e.getValue(t).set(n):e.addValue(t,Ar(n))}function z5(e,t){const n=Zo(e,t);let{transitionEnd:r={},transition:s={},...i}=n?e.makeTargetAnimatable(n,!1):{};i={...i,...r};for(const o in i){const a=tw(i[o]);F5(e,o,a)}}function I5(e,t,n){var r,s;const i=Object.keys(t).filter(a=>!e.hasValue(a)),o=i.length;if(o)for(let a=0;al.remove(f))),c.push(w)}return o&&Promise.all(c).then(()=>{o&&z5(e,o)}),c}function Jl(e,t,n={}){const r=Zo(e,t,n.custom);let{transition:s=e.getDefaultTransition()||{}}=r||{};n.transitionOverride&&(s=n.transitionOverride);const i=r?()=>Promise.all(fg(e,r,n)):()=>Promise.resolve(),o=e.variantChildren&&e.variantChildren.size?(l=0)=>{const{delayChildren:c=0,staggerChildren:d,staggerDirection:f}=s;return W5(e,t,c+l,d,f,n)}:()=>Promise.resolve(),{when:a}=s;if(a){const[l,c]=a==="beforeChildren"?[i,o]:[o,i];return l().then(()=>c())}else return Promise.all([i(),o(n.delay)])}function W5(e,t,n=0,r=0,s=1,i){const o=[],a=(e.variantChildren.size-1)*r,l=s===1?(c=0)=>c*r:(c=0)=>a-c*r;return Array.from(e.variantChildren).sort(H5).forEach((c,d)=>{c.notify("AnimationStart",t),o.push(Jl(c,t,{...i,delay:n+l(d)}).then(()=>c.notify("AnimationComplete",t)))}),Promise.all(o)}function H5(e,t){return e.sortNodePosition(t)}function q5(e,t,n={}){e.notify("AnimationStart",t);let r;if(Array.isArray(t)){const s=t.map(i=>Jl(e,i,n));r=Promise.all(s)}else if(typeof t=="string")r=Jl(e,t,n);else{const s=typeof t=="function"?Zo(e,t,n.custom):t;r=Promise.all(fg(e,s,n))}return r.then(()=>e.notify("AnimationComplete",t))}const G5=[...dc].reverse(),Y5=dc.length;function K5(e){return t=>Promise.all(t.map(({animation:n,options:r})=>q5(e,n,r)))}function X5(e){let t=K5(e);const n=Z5();let r=!0;const s=(l,c)=>{const d=Zo(e,c);if(d){const{transition:f,transitionEnd:u,...h}=d;l={...l,...h,...u}}return l};function i(l){t=l(e)}function o(l,c){const d=e.getProps(),f=e.getVariantContext(!0)||{},u=[],h=new Set;let p={},g=1/0;for(let v=0;vg&&S,T=!1;const F=Array.isArray(b)?b:[b];let L=F.reduce(s,{});C===!1&&(L={});const{prevResolvedValues:W={}}=x,A={...W,...L},O=B=>{_=!0,h.has(B)&&(T=!0,h.delete(B)),x.needsAnimating[B]=!0};for(const B in A){const K=L[B],M=W[B];if(p.hasOwnProperty(B))continue;let D=!1;yo(K)&&yo(M)?D=!R0(K,M):D=K!==M,D?K!==void 0?O(B):h.add(B):K!==void 0&&h.has(B)?O(B):x.protectedKeys[B]=!0}x.prevProp=b,x.prevResolvedValues=L,x.isActive&&(p={...p,...L}),r&&e.blockInitialAnimation&&(_=!1),_&&(!P||T)&&u.push(...F.map(B=>({animation:B,options:{type:y,...l}})))}if(h.size){const v={};h.forEach(y=>{const x=e.getBaseTarget(y);x!==void 0&&(v[y]=x)}),u.push({animation:v})}let w=!!u.length;return r&&(d.initial===!1||d.initial===d.animate)&&!e.manuallyAnimateOnMount&&(w=!1),r=!1,w?t(u):Promise.resolve()}function a(l,c,d){var f;if(n[l].isActive===c)return Promise.resolve();(f=e.variantChildren)===null||f===void 0||f.forEach(h=>{var p;return(p=h.animationState)===null||p===void 0?void 0:p.setActive(l,c)}),n[l].isActive=c;const u=o(d,l);for(const h in n)n[h].protectedKeys={};return u}return{animateChanges:o,setActive:a,setAnimateFunction:i,getState:()=>n}}function Q5(e,t){return typeof t=="string"?t!==e:Array.isArray(t)?!R0(t,e):!1}function Mn(e=!1){return{isActive:e,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function Z5(){return{animate:Mn(!0),whileInView:Mn(),whileHover:Mn(),whileTap:Mn(),whileDrag:Mn(),whileFocus:Mn(),exit:Mn()}}class J5 extends Tn{constructor(t){super(t),t.animationState||(t.animationState=X5(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();this.unmount(),Yo(t)&&(this.unmount=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){}}let e3=0;class t3 extends Tn{constructor(){super(...arguments),this.id=e3++}update(){if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n,custom:r}=this.node.presenceContext,{isPresent:s}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===s)return;const i=this.node.animationState.setActive("exit",!t,{custom:r??this.node.getProps().custom});n&&!t&&i.then(()=>n(this.id))}mount(){const{register:t}=this.node.presenceContext||{};t&&(this.unmount=t(this.id))}unmount(){}}const n3={animation:{Feature:J5},exit:{Feature:t3}},yf=(e,t)=>Math.abs(e-t);function r3(e,t){const n=yf(e.x,t.x),r=yf(e.y,t.y);return Math.sqrt(n**2+r**2)}class hg{constructor(t,n,{transformPagePoint:r,contextWindow:s,dragSnapToOrigin:i=!1}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const f=za(this.lastMoveEventInfo,this.history),u=this.startEvent!==null,h=r3(f.offset,{x:0,y:0})>=3;if(!u&&!h)return;const{point:p}=f,{timestamp:g}=De;this.history.push({...p,timestamp:g});const{onStart:w,onMove:v}=this.handlers;u||(w&&w(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),v&&v(this.lastMoveEvent,f)},this.handlePointerMove=(f,u)=>{this.lastMoveEvent=f,this.lastMoveEventInfo=Fa(u,this.transformPagePoint),se.update(this.updatePoint,!0)},this.handlePointerUp=(f,u)=>{this.end();const{onEnd:h,onSessionEnd:p,resumeAnimation:g}=this.handlers;if(this.dragSnapToOrigin&&g&&g(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const w=za(f.type==="pointercancel"?this.lastMoveEventInfo:Fa(u,this.transformPagePoint),this.history);this.startEvent&&h&&h(f,w),p&&p(f,w)},!M0(t))return;this.dragSnapToOrigin=i,this.handlers=n,this.transformPagePoint=r,this.contextWindow=s||window;const o=Qo(t),a=Fa(o,this.transformPagePoint),{point:l}=a,{timestamp:c}=De;this.history=[{...l,timestamp:c}];const{onSessionStart:d}=n;d&&d(t,za(a,this.history)),this.removeListeners=gn(Ft(this.contextWindow,"pointermove",this.handlePointerMove),Ft(this.contextWindow,"pointerup",this.handlePointerUp),Ft(this.contextWindow,"pointercancel",this.handlePointerUp))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),Ht(this.updatePoint)}}function Fa(e,t){return t?{point:t(e.point)}:e}function vf(e,t){return{x:e.x-t.x,y:e.y-t.y}}function za({point:e},t){return{point:e,delta:vf(e,pg(t)),offset:vf(e,s3(t)),velocity:i3(t,.1)}}function s3(e){return e[0]}function pg(e){return e[e.length-1]}function i3(e,t){if(e.length<2)return{x:0,y:0};let n=e.length-1,r=null;const s=pg(e);for(;n>=0&&(r=e[n],!(s.timestamp-r.timestamp>$n(t)));)n--;if(!r)return{x:0,y:0};const i=zt(s.timestamp-r.timestamp);if(i===0)return{x:0,y:0};const o={x:(s.x-r.x)/i,y:(s.y-r.y)/i};return o.x===1/0&&(o.x=0),o.y===1/0&&(o.y=0),o}function Ze(e){return e.max-e.min}function eu(e,t=0,n=.01){return Math.abs(e-t)<=n}function xf(e,t,n,r=.5){e.origin=r,e.originPoint=ae(t.min,t.max,e.origin),e.scale=Ze(n)/Ze(t),(eu(e.scale,1,1e-4)||isNaN(e.scale))&&(e.scale=1),e.translate=ae(n.min,n.max,e.origin)-e.originPoint,(eu(e.translate)||isNaN(e.translate))&&(e.translate=0)}function vs(e,t,n,r){xf(e.x,t.x,n.x,r?r.originX:void 0),xf(e.y,t.y,n.y,r?r.originY:void 0)}function wf(e,t,n){e.min=n.min+t.min,e.max=e.min+Ze(t)}function o3(e,t,n){wf(e.x,t.x,n.x),wf(e.y,t.y,n.y)}function bf(e,t,n){e.min=t.min-n.min,e.max=e.min+Ze(t)}function xs(e,t,n){bf(e.x,t.x,n.x),bf(e.y,t.y,n.y)}function a3(e,{min:t,max:n},r){return t!==void 0&&en&&(e=r?ae(n,e,r.max):Math.min(e,n)),e}function Sf(e,t,n){return{min:t!==void 0?e.min+t:void 0,max:n!==void 0?e.max+n-(e.max-e.min):void 0}}function l3(e,{top:t,left:n,bottom:r,right:s}){return{x:Sf(e.x,n,s),y:Sf(e.y,t,r)}}function kf(e,t){let n=t.min-e.min,r=t.max-e.max;return t.max-t.minr?n=Us(t.min,t.max-r,e.min):r>s&&(n=Us(e.min,e.max-s,t.min)),xn(0,1,n)}function d3(e,t){const n={};return t.min!==void 0&&(n.min=t.min-e.min),t.max!==void 0&&(n.max=t.max-e.min),n}const tu=.35;function f3(e=tu){return e===!1?e=0:e===!0&&(e=tu),{x:Cf(e,"left","right"),y:Cf(e,"top","bottom")}}function Cf(e,t,n){return{min:Pf(e,t),max:Pf(e,n)}}function Pf(e,t){return typeof e=="number"?e:e[t]||0}const jf=()=>({translate:0,scale:1,origin:0,originPoint:0}),mr=()=>({x:jf(),y:jf()}),Ef=()=>({min:0,max:0}),ge=()=>({x:Ef(),y:Ef()});function rt(e){return[e("x"),e("y")]}function mg({top:e,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:e,max:r}}}function h3({x:e,y:t}){return{top:t.min,right:e.max,bottom:t.max,left:e.min}}function p3(e,t){if(!t)return e;const n=t({x:e.left,y:e.top}),r=t({x:e.right,y:e.bottom});return{top:n.y,left:n.x,bottom:r.y,right:r.x}}function Ia(e){return e===void 0||e===1}function nu({scale:e,scaleX:t,scaleY:n}){return!Ia(e)||!Ia(t)||!Ia(n)}function Ln(e){return nu(e)||gg(e)||e.z||e.rotate||e.rotateX||e.rotateY}function gg(e){return Tf(e.x)||Tf(e.y)}function Tf(e){return e&&e!=="0%"}function So(e,t,n){const r=e-n,s=t*r;return n+s}function Nf(e,t,n,r,s){return s!==void 0&&(e=So(e,s,r)),So(e,n,r)+t}function ru(e,t=0,n=1,r,s){e.min=Nf(e.min,t,n,r,s),e.max=Nf(e.max,t,n,r,s)}function yg(e,{x:t,y:n}){ru(e.x,t.translate,t.scale,t.originPoint),ru(e.y,n.translate,n.scale,n.originPoint)}function m3(e,t,n,r=!1){const s=n.length;if(!s)return;t.x=t.y=1;let i,o;for(let a=0;a1.0000000000001||e<.999999999999?e:1}function Jt(e,t){e.min=e.min+t,e.max=e.max+t}function _f(e,t,[n,r,s]){const i=t[s]!==void 0?t[s]:.5,o=ae(e.min,e.max,i);ru(e,t[n],t[r],o,t.scale)}const g3=["x","scaleX","originX"],y3=["y","scaleY","originY"];function gr(e,t){_f(e.x,t,g3),_f(e.y,t,y3)}function vg(e,t){return mg(p3(e.getBoundingClientRect(),t))}function v3(e,t,n){const r=vg(e,n),{scroll:s}=t;return s&&(Jt(r.x,s.offset.x),Jt(r.y,s.offset.y)),r}const xg=({current:e})=>e?e.ownerDocument.defaultView:null,x3=new WeakMap;class w3{constructor(t){this.openGlobalLock=null,this.isDragging=!1,this.currentDirection=null,this.originPoint={x:0,y:0},this.constraints=!1,this.hasMutatedConstraints=!1,this.elastic=ge(),this.visualElement=t}start(t,{snapToCursor:n=!1}={}){const{presenceContext:r}=this.visualElement;if(r&&r.isPresent===!1)return;const s=d=>{const{dragSnapToOrigin:f}=this.getProps();f?this.pauseAnimation():this.stopAnimation(),n&&this.snapToCursor(Qo(d,"page").point)},i=(d,f)=>{const{drag:u,dragPropagation:h,onDragStart:p}=this.getProps();if(u&&!h&&(this.openGlobalLock&&this.openGlobalLock(),this.openGlobalLock=A0(u),!this.openGlobalLock))return;this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),rt(w=>{let v=this.getAxisMotionValue(w).get()||0;if(Et.test(v)){const{projection:y}=this.visualElement;if(y&&y.layout){const x=y.layout.layoutBox[w];x&&(v=Ze(x)*(parseFloat(v)/100))}}this.originPoint[w]=v}),p&&se.update(()=>p(d,f),!1,!0);const{animationState:g}=this.visualElement;g&&g.setActive("whileDrag",!0)},o=(d,f)=>{const{dragPropagation:u,dragDirectionLock:h,onDirectionLock:p,onDrag:g}=this.getProps();if(!u&&!this.openGlobalLock)return;const{offset:w}=f;if(h&&this.currentDirection===null){this.currentDirection=b3(w),this.currentDirection!==null&&p&&p(this.currentDirection);return}this.updateAxis("x",f.point,w),this.updateAxis("y",f.point,w),this.visualElement.render(),g&&g(d,f)},a=(d,f)=>this.stop(d,f),l=()=>rt(d=>{var f;return this.getAnimationState(d)==="paused"&&((f=this.getAxisMotionValue(d).animation)===null||f===void 0?void 0:f.play())}),{dragSnapToOrigin:c}=this.getProps();this.panSession=new hg(t,{onSessionStart:s,onStart:i,onMove:o,onSessionEnd:a,resumeAnimation:l},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:c,contextWindow:xg(this.visualElement)})}stop(t,n){const r=this.isDragging;if(this.cancel(),!r)return;const{velocity:s}=n;this.startAnimation(s);const{onDragEnd:i}=this.getProps();i&&se.update(()=>i(t,n))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.panSession&&this.panSession.end(),this.panSession=void 0;const{dragPropagation:r}=this.getProps();!r&&this.openGlobalLock&&(this.openGlobalLock(),this.openGlobalLock=null),n&&n.setActive("whileDrag",!1)}updateAxis(t,n,r){const{drag:s}=this.getProps();if(!r||!Ci(t,s,this.currentDirection))return;const i=this.getAxisMotionValue(t);let o=this.originPoint[t]+r[t];this.constraints&&this.constraints[t]&&(o=a3(o,this.constraints[t],this.elastic[t])),i.set(o)}resolveConstraints(){var t;const{dragConstraints:n,dragElastic:r}=this.getProps(),s=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(t=this.visualElement.projection)===null||t===void 0?void 0:t.layout,i=this.constraints;n&&hr(n)?this.constraints||(this.constraints=this.resolveRefConstraints()):n&&s?this.constraints=l3(s.layoutBox,n):this.constraints=!1,this.elastic=f3(r),i!==this.constraints&&s&&this.constraints&&!this.hasMutatedConstraints&&rt(o=>{this.getAxisMotionValue(o)&&(this.constraints[o]=d3(s.layoutBox[o],this.constraints[o]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!hr(t))return!1;const r=t.current,{projection:s}=this.visualElement;if(!s||!s.layout)return!1;const i=v3(r,s.root,this.visualElement.getTransformPagePoint());let o=u3(s.layout.layoutBox,i);if(n){const a=n(h3(o));this.hasMutatedConstraints=!!a,a&&(o=mg(a))}return o}startAnimation(t){const{drag:n,dragMomentum:r,dragElastic:s,dragTransition:i,dragSnapToOrigin:o,onDragTransitionEnd:a}=this.getProps(),l=this.constraints||{},c=rt(d=>{if(!Ci(d,n,this.currentDirection))return;let f=l&&l[d]||{};o&&(f={min:0,max:0});const u=s?200:1e6,h=s?40:1e7,p={type:"inertia",velocity:r?t[d]:0,bounceStiffness:u,bounceDamping:h,timeConstant:750,restDelta:1,restSpeed:10,...i,...f};return this.startAxisValueAnimation(d,p)});return Promise.all(c).then(a)}startAxisValueAnimation(t,n){const r=this.getAxisMotionValue(t);return r.start(jc(t,r,0,n))}stopAnimation(){rt(t=>this.getAxisMotionValue(t).stop())}pauseAnimation(){rt(t=>{var n;return(n=this.getAxisMotionValue(t).animation)===null||n===void 0?void 0:n.pause()})}getAnimationState(t){var n;return(n=this.getAxisMotionValue(t).animation)===null||n===void 0?void 0:n.state}getAxisMotionValue(t){const n="_drag"+t.toUpperCase(),r=this.visualElement.getProps(),s=r[n];return s||this.visualElement.getValue(t,(r.initial?r.initial[t]:void 0)||0)}snapToCursor(t){rt(n=>{const{drag:r}=this.getProps();if(!Ci(n,r,this.currentDirection))return;const{projection:s}=this.visualElement,i=this.getAxisMotionValue(n);if(s&&s.layout){const{min:o,max:a}=s.layout.layoutBox[n];i.set(t[n]-ae(o,a,.5))}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:r}=this.visualElement;if(!hr(n)||!r||!this.constraints)return;this.stopAnimation();const s={x:0,y:0};rt(o=>{const a=this.getAxisMotionValue(o);if(a){const l=a.get();s[o]=c3({min:l,max:l},this.constraints[o])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.resolveConstraints(),rt(o=>{if(!Ci(o,t,null))return;const a=this.getAxisMotionValue(o),{min:l,max:c}=this.constraints[o];a.set(ae(l,c,s[o]))})}addListeners(){if(!this.visualElement.current)return;x3.set(this.visualElement,this);const t=this.visualElement.current,n=Ft(t,"pointerdown",l=>{const{drag:c,dragListener:d=!0}=this.getProps();c&&d&&this.start(l)}),r=()=>{const{dragConstraints:l}=this.getProps();hr(l)&&(this.constraints=this.resolveRefConstraints())},{projection:s}=this.visualElement,i=s.addEventListener("measure",r);s&&!s.layout&&(s.root&&s.root.updateScroll(),s.updateLayout()),r();const o=Rt(window,"resize",()=>this.scalePositionWithinConstraints()),a=s.addEventListener("didUpdate",({delta:l,hasLayoutChanged:c})=>{this.isDragging&&c&&(rt(d=>{const f=this.getAxisMotionValue(d);f&&(this.originPoint[d]+=l[d].translate,f.set(f.get()+l[d].translate))}),this.visualElement.render())});return()=>{o(),n(),i(),a&&a()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:r=!1,dragPropagation:s=!1,dragConstraints:i=!1,dragElastic:o=tu,dragMomentum:a=!0}=t;return{...t,drag:n,dragDirectionLock:r,dragPropagation:s,dragConstraints:i,dragElastic:o,dragMomentum:a}}}function Ci(e,t,n){return(t===!0||t===e)&&(n===null||n===e)}function b3(e,t=10){let n=null;return Math.abs(e.y)>t?n="y":Math.abs(e.x)>t&&(n="x"),n}class S3 extends Tn{constructor(t){super(t),this.removeGroupControls=pe,this.removeListeners=pe,this.controls=new w3(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||pe}unmount(){this.removeGroupControls(),this.removeListeners()}}const Af=e=>(t,n)=>{e&&se.update(()=>e(t,n))};class k3 extends Tn{constructor(){super(...arguments),this.removePointerDownListener=pe}onPointerDown(t){this.session=new hg(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:xg(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:r,onPanEnd:s}=this.node.getProps();return{onSessionStart:Af(t),onStart:Af(n),onMove:r,onEnd:(i,o)=>{delete this.session,s&&se.update(()=>s(i,o))}}}mount(){this.removePointerDownListener=Ft(this.node.current,"pointerdown",t=>this.onPointerDown(t))}update(){this.session&&this.session.updateHandlers(this.createPanHandlers())}unmount(){this.removePointerDownListener(),this.session&&this.session.end()}}function C3(){const e=k.useContext(uc);if(e===null)return[!0,null];const{isPresent:t,onExitComplete:n,register:r}=e,s=k.useId();return k.useEffect(()=>r(s),[]),!t&&n?[!1,()=>n&&n(s)]:[!0]}const $i={hasAnimatedSinceResize:!0,hasEverUpdated:!1};function Lf(e,t){return t.max===t.min?0:e/(t.max-t.min)*100}const Jr={correct:(e,t)=>{if(!t.target)return e;if(typeof e=="string")if(U.test(e))e=parseFloat(e);else return e;const n=Lf(e,t.target.x),r=Lf(e,t.target.y);return`${n}% ${r}%`}},P3={correct:(e,{treeScale:t,projectionDelta:n})=>{const r=e,s=wn.parse(e);if(s.length>5)return r;const i=wn.createTransformer(e),o=typeof s[0]!="number"?1:0,a=n.x.scale*t.x,l=n.y.scale*t.y;s[0+o]/=a,s[1+o]/=l;const c=ae(a,l,.5);return typeof s[2+o]=="number"&&(s[2+o]/=c),typeof s[3+o]=="number"&&(s[3+o]/=c),i(s)}};class j3 extends qs.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r,layoutId:s}=this.props,{projection:i}=t;A2(E3),i&&(n.group&&n.group.add(i),r&&r.register&&s&&r.register(i),i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,onExitComplete:()=>this.safeToRemove()})),$i.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:r,drag:s,isPresent:i}=this.props,o=r.projection;return o&&(o.isPresent=i,s||t.layoutDependency!==n||n===void 0?o.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?o.promote():o.relegate()||se.postRender(()=>{const a=o.getStack();(!a||!a.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{projection:t}=this.props.visualElement;t&&(t.root.didUpdate(),queueMicrotask(()=>{!t.currentAnimation&&t.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r}=this.props,{projection:s}=t;s&&(s.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(s),r&&r.deregister&&r.deregister(s))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function wg(e){const[t,n]=C3(),r=k.useContext(m0);return qs.createElement(j3,{...e,layoutGroup:r,switchLayoutGroup:k.useContext(g0),isPresent:t,safeToRemove:n})}const E3={borderRadius:{...Jr,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:Jr,borderTopRightRadius:Jr,borderBottomLeftRadius:Jr,borderBottomRightRadius:Jr,boxShadow:P3},bg=["TopLeft","TopRight","BottomLeft","BottomRight"],T3=bg.length,Df=e=>typeof e=="string"?parseFloat(e):e,Rf=e=>typeof e=="number"||U.test(e);function N3(e,t,n,r,s,i){s?(e.opacity=ae(0,n.opacity!==void 0?n.opacity:1,M3(r)),e.opacityExit=ae(t.opacity!==void 0?t.opacity:1,0,_3(r))):i&&(e.opacity=ae(t.opacity!==void 0?t.opacity:1,n.opacity!==void 0?n.opacity:1,r));for(let o=0;ort?1:n(Us(e,t,r))}function Ff(e,t){e.min=t.min,e.max=t.max}function nt(e,t){Ff(e.x,t.x),Ff(e.y,t.y)}function zf(e,t,n,r,s){return e-=t,e=So(e,1/n,r),s!==void 0&&(e=So(e,1/s,r)),e}function A3(e,t=0,n=1,r=.5,s,i=e,o=e){if(Et.test(t)&&(t=parseFloat(t),t=ae(o.min,o.max,t/100)-o.min),typeof t!="number")return;let a=ae(i.min,i.max,r);e===i&&(a-=t),e.min=zf(e.min,t,n,a,s),e.max=zf(e.max,t,n,a,s)}function If(e,t,[n,r,s],i,o){A3(e,t[n],t[r],t[s],t.scale,i,o)}const L3=["x","scaleX","originX"],D3=["y","scaleY","originY"];function Of(e,t,n,r){If(e.x,t,L3,n?n.x:void 0,r?r.x:void 0),If(e.y,t,D3,n?n.y:void 0,r?r.y:void 0)}function $f(e){return e.translate===0&&e.scale===1}function kg(e){return $f(e.x)&&$f(e.y)}function R3(e,t){return e.x.min===t.x.min&&e.x.max===t.x.max&&e.y.min===t.y.min&&e.y.max===t.y.max}function Cg(e,t){return Math.round(e.x.min)===Math.round(t.x.min)&&Math.round(e.x.max)===Math.round(t.x.max)&&Math.round(e.y.min)===Math.round(t.y.min)&&Math.round(e.y.max)===Math.round(t.y.max)}function Bf(e){return Ze(e.x)/Ze(e.y)}class V3{constructor(){this.members=[]}add(t){Ec(this.members,t),t.scheduleRender()}remove(t){if(Tc(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){const n=this.members.findIndex(s=>t===s);if(n===0)return!1;let r;for(let s=n;s>=0;s--){const i=this.members[s];if(i.isPresent!==!1){r=i;break}}return r?(this.promote(r),!0):!1}promote(t,n){const r=this.lead;if(t!==r&&(this.prevLead=r,this.lead=t,t.show(),r)){r.instance&&r.scheduleRender(),t.scheduleRender(),t.resumeFrom=r,n&&(t.resumeFrom.preserveOpacity=!0),r.snapshot&&(t.snapshot=r.snapshot,t.snapshot.latestValues=r.animationValues||r.latestValues),t.root&&t.root.isUpdating&&(t.isLayoutDirty=!0);const{crossfade:s}=t.options;s===!1&&r.hide()}}exitAnimationComplete(){this.members.forEach(t=>{const{options:n,resumingFrom:r}=t;n.onExitComplete&&n.onExitComplete(),r&&r.options.onExitComplete&&r.options.onExitComplete()})}scheduleRender(){this.members.forEach(t=>{t.instance&&t.scheduleRender(!1)})}removeLeadSnapshot(){this.lead&&this.lead.snapshot&&(this.lead.snapshot=void 0)}}function Uf(e,t,n){let r="";const s=e.x.translate/t.x,i=e.y.translate/t.y;if((s||i)&&(r=`translate3d(${s}px, ${i}px, 0) `),(t.x!==1||t.y!==1)&&(r+=`scale(${1/t.x}, ${1/t.y}) `),n){const{rotate:l,rotateX:c,rotateY:d}=n;l&&(r+=`rotate(${l}deg) `),c&&(r+=`rotateX(${c}deg) `),d&&(r+=`rotateY(${d}deg) `)}const o=e.x.scale*t.x,a=e.y.scale*t.y;return(o!==1||a!==1)&&(r+=`scale(${o}, ${a})`),r||"none"}const F3=(e,t)=>e.depth-t.depth;class z3{constructor(){this.children=[],this.isDirty=!1}add(t){Ec(this.children,t),this.isDirty=!0}remove(t){Tc(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(F3),this.isDirty=!1,this.children.forEach(t)}}function I3(e,t){const n=performance.now(),r=({timestamp:s})=>{const i=s-n;i>=t&&(Ht(r),e(i-t))};return se.read(r,!0),()=>Ht(r)}function O3(e){window.MotionDebug&&window.MotionDebug.record(e)}function $3(e){return e instanceof SVGElement&&e.tagName!=="svg"}function B3(e,t,n){const r=Ge(e)?e:Ar(e);return r.start(jc("",r,t,n)),r.animation}const Wf=["","X","Y","Z"],U3={visibility:"hidden"},Hf=1e3;let W3=0;const Dn={type:"projectionFrame",totalNodes:0,resolvedTargetDeltas:0,recalculatedProjection:0};function Pg({attachResizeListener:e,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:s}){return class{constructor(o={},a=t==null?void 0:t()){this.id=W3++,this.animationId=0,this.children=new Set,this.options={},this.isTreeAnimating=!1,this.isAnimationBlocked=!1,this.isLayoutDirty=!1,this.isProjectionDirty=!1,this.isSharedProjectionDirty=!1,this.isTransformDirty=!1,this.updateManuallyBlocked=!1,this.updateBlockedByResize=!1,this.isUpdating=!1,this.isSVG=!1,this.needsReset=!1,this.shouldResetTransform=!1,this.treeScale={x:1,y:1},this.eventHandlers=new Map,this.hasTreeAnimated=!1,this.updateScheduled=!1,this.projectionUpdateScheduled=!1,this.checkUpdateFailed=()=>{this.isUpdating&&(this.isUpdating=!1,this.clearAllSnapshots())},this.updateProjection=()=>{this.projectionUpdateScheduled=!1,Dn.totalNodes=Dn.resolvedTargetDeltas=Dn.recalculatedProjection=0,this.nodes.forEach(G3),this.nodes.forEach(Z3),this.nodes.forEach(J3),this.nodes.forEach(Y3),O3(Dn)},this.hasProjected=!1,this.isVisible=!0,this.animationProgress=0,this.sharedNodes=new Map,this.latestValues=o,this.root=a?a.root||a:this,this.path=a?[...a.path,a]:[],this.parent=a,this.depth=a?a.depth+1:0;for(let l=0;lthis.root.updateBlockedByResize=!1;e(o,()=>{this.root.updateBlockedByResize=!0,f&&f(),f=I3(u,250),$i.hasAnimatedSinceResize&&($i.hasAnimatedSinceResize=!1,this.nodes.forEach(Gf))})}l&&this.root.registerSharedNode(l,this),this.options.animate!==!1&&d&&(l||c)&&this.addEventListener("didUpdate",({delta:f,hasLayoutChanged:u,hasRelativeTargetChanged:h,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||s4,{onLayoutAnimationStart:w,onLayoutAnimationComplete:v}=d.getProps(),y=!this.targetLayout||!Cg(this.targetLayout,p)||h,x=!u&&h;if(this.options.layoutRoot||this.resumeFrom&&this.resumeFrom.instance||x||u&&(y||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0),this.setAnimationOrigin(f,x);const b={...Pc(g,"layout"),onPlay:w,onComplete:v};(d.shouldReduceMotion||this.options.layoutRoot)&&(b.delay=0,b.type=!1),this.startAnimation(b)}else u||Gf(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=p})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const o=this.getStack();o&&o.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,Ht(this.updateProjection)}blockUpdate(){this.updateManuallyBlocked=!0}unblockUpdate(){this.updateManuallyBlocked=!1}isUpdateBlocked(){return this.updateManuallyBlocked||this.updateBlockedByResize}isTreeAnimationBlocked(){return this.isAnimationBlocked||this.parent&&this.parent.isTreeAnimationBlocked()||!1}startUpdate(){this.isUpdateBlocked()||(this.isUpdating=!0,this.nodes&&this.nodes.forEach(e4),this.animationId++)}getTransformTemplate(){const{visualElement:o}=this.options;return o&&o.getProps().transformTemplate}willUpdate(o=!0){if(this.root.hasTreeAnimated=!0,this.root.isUpdateBlocked()){this.options.onExitComplete&&this.options.onExitComplete();return}if(!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let d=0;dthis.update()))}clearAllSnapshots(){this.nodes.forEach(K3),this.sharedNodes.forEach(t4)}scheduleUpdateProjection(){this.projectionUpdateScheduled||(this.projectionUpdateScheduled=!0,se.preRender(this.updateProjection,!1,!0))}scheduleCheckAfterUnmount(){se.postRender(()=>{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure())}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let l=0;l{const S=b/1e3;Yf(f.x,o.x,S),Yf(f.y,o.y,S),this.setTargetDelta(f),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(xs(u,this.layout.layoutBox,this.relativeParent.layout.layoutBox),n4(this.relativeTarget,this.relativeTargetOrigin,u,S),x&&R3(this.relativeTarget,x)&&(this.isProjectionDirty=!1),x||(x=ge()),nt(x,this.relativeTarget)),g&&(this.animationValues=d,N3(d,c,this.latestValues,S,y,v)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=S},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(o){this.notifyListeners("animationStart"),this.currentAnimation&&this.currentAnimation.stop(),this.resumingFrom&&this.resumingFrom.currentAnimation&&this.resumingFrom.currentAnimation.stop(),this.pendingAnimation&&(Ht(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=se.update(()=>{$i.hasAnimatedSinceResize=!0,this.currentAnimation=B3(0,Hf,{...o,onUpdate:a=>{this.mixTargetDelta(a),o.onUpdate&&o.onUpdate(a)},onComplete:()=>{o.onComplete&&o.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const o=this.getStack();o&&o.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(Hf),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const o=this.getLead();let{targetWithTransforms:a,target:l,layout:c,latestValues:d}=o;if(!(!a||!l||!c)){if(this!==o&&this.layout&&c&&jg(this.options.animationType,this.layout.layoutBox,c.layoutBox)){l=this.target||ge();const f=Ze(this.layout.layoutBox.x);l.x.min=o.target.x.min,l.x.max=l.x.min+f;const u=Ze(this.layout.layoutBox.y);l.y.min=o.target.y.min,l.y.max=l.y.min+u}nt(a,l),gr(a,d),vs(this.projectionDeltaWithTransform,this.layoutCorrected,a,d)}}registerSharedNode(o,a){this.sharedNodes.has(o)||this.sharedNodes.set(o,new V3),this.sharedNodes.get(o).add(a);const c=a.options.initialPromotionConfig;a.promote({transition:c?c.transition:void 0,preserveFollowOpacity:c&&c.shouldPreserveFollowOpacity?c.shouldPreserveFollowOpacity(a):void 0})}isLead(){const o=this.getStack();return o?o.lead===this:!0}getLead(){var o;const{layoutId:a}=this.options;return a?((o=this.getStack())===null||o===void 0?void 0:o.lead)||this:this}getPrevLead(){var o;const{layoutId:a}=this.options;return a?(o=this.getStack())===null||o===void 0?void 0:o.prevLead:void 0}getStack(){const{layoutId:o}=this.options;if(o)return this.root.sharedNodes.get(o)}promote({needsReset:o,transition:a,preserveFollowOpacity:l}={}){const c=this.getStack();c&&c.promote(this,l),o&&(this.projectionDelta=void 0,this.needsReset=!0),a&&this.setOptions({transition:a})}relegate(){const o=this.getStack();return o?o.relegate(this):!1}resetRotation(){const{visualElement:o}=this.options;if(!o)return;let a=!1;const{latestValues:l}=o;if((l.rotate||l.rotateX||l.rotateY||l.rotateZ)&&(a=!0),!a)return;const c={};for(let d=0;d{var a;return(a=o.currentAnimation)===null||a===void 0?void 0:a.stop()}),this.root.nodes.forEach(qf),this.root.sharedNodes.clear()}}}function H3(e){e.updateLayout()}function q3(e){var t;const n=((t=e.resumeFrom)===null||t===void 0?void 0:t.snapshot)||e.snapshot;if(e.isLead()&&e.layout&&n&&e.hasListeners("didUpdate")){const{layoutBox:r,measuredBox:s}=e.layout,{animationType:i}=e.options,o=n.source!==e.layout.source;i==="size"?rt(f=>{const u=o?n.measuredBox[f]:n.layoutBox[f],h=Ze(u);u.min=r[f].min,u.max=u.min+h}):jg(i,n.layoutBox,r)&&rt(f=>{const u=o?n.measuredBox[f]:n.layoutBox[f],h=Ze(r[f]);u.max=u.min+h,e.relativeTarget&&!e.currentAnimation&&(e.isProjectionDirty=!0,e.relativeTarget[f].max=e.relativeTarget[f].min+h)});const a=mr();vs(a,r,n.layoutBox);const l=mr();o?vs(l,e.applyTransform(s,!0),n.measuredBox):vs(l,r,n.layoutBox);const c=!kg(a);let d=!1;if(!e.resumeFrom){const f=e.getClosestProjectingParent();if(f&&!f.resumeFrom){const{snapshot:u,layout:h}=f;if(u&&h){const p=ge();xs(p,n.layoutBox,u.layoutBox);const g=ge();xs(g,r,h.layoutBox),Cg(p,g)||(d=!0),f.options.layoutRoot&&(e.relativeTarget=g,e.relativeTargetOrigin=p,e.relativeParent=f)}}}e.notifyListeners("didUpdate",{layout:r,snapshot:n,delta:l,layoutDelta:a,hasLayoutChanged:c,hasRelativeTargetChanged:d})}else if(e.isLead()){const{onExitComplete:r}=e.options;r&&r()}e.options.transition=void 0}function G3(e){Dn.totalNodes++,e.parent&&(e.isProjecting()||(e.isProjectionDirty=e.parent.isProjectionDirty),e.isSharedProjectionDirty||(e.isSharedProjectionDirty=!!(e.isProjectionDirty||e.parent.isProjectionDirty||e.parent.isSharedProjectionDirty)),e.isTransformDirty||(e.isTransformDirty=e.parent.isTransformDirty))}function Y3(e){e.isProjectionDirty=e.isSharedProjectionDirty=e.isTransformDirty=!1}function K3(e){e.clearSnapshot()}function qf(e){e.clearMeasurements()}function X3(e){e.isLayoutDirty=!1}function Q3(e){const{visualElement:t}=e.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),e.resetTransform()}function Gf(e){e.finishAnimation(),e.targetDelta=e.relativeTarget=e.target=void 0,e.isProjectionDirty=!0}function Z3(e){e.resolveTargetDelta()}function J3(e){e.calcProjection()}function e4(e){e.resetRotation()}function t4(e){e.removeLeadSnapshot()}function Yf(e,t,n){e.translate=ae(t.translate,0,n),e.scale=ae(t.scale,1,n),e.origin=t.origin,e.originPoint=t.originPoint}function Kf(e,t,n,r){e.min=ae(t.min,n.min,r),e.max=ae(t.max,n.max,r)}function n4(e,t,n,r){Kf(e.x,t.x,n.x,r),Kf(e.y,t.y,n.y,r)}function r4(e){return e.animationValues&&e.animationValues.opacityExit!==void 0}const s4={duration:.45,ease:[.4,0,.1,1]},Xf=e=>typeof navigator<"u"&&navigator.userAgent.toLowerCase().includes(e),Qf=Xf("applewebkit/")&&!Xf("chrome/")?Math.round:pe;function Zf(e){e.min=Qf(e.min),e.max=Qf(e.max)}function i4(e){Zf(e.x),Zf(e.y)}function jg(e,t,n){return e==="position"||e==="preserve-aspect"&&!eu(Bf(t),Bf(n),.2)}const o4=Pg({attachResizeListener:(e,t)=>Rt(e,"resize",t),measureScroll:()=>({x:document.documentElement.scrollLeft||document.body.scrollLeft,y:document.documentElement.scrollTop||document.body.scrollTop}),checkIsScrollRoot:()=>!0}),Oa={current:void 0},Eg=Pg({measureScroll:e=>({x:e.scrollLeft,y:e.scrollTop}),defaultParent:()=>{if(!Oa.current){const e=new o4({});e.mount(window),e.setOptions({layoutScroll:!0}),Oa.current=e}return Oa.current},resetTransform:(e,t)=>{e.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:e=>window.getComputedStyle(e).position==="fixed"}),a4={pan:{Feature:k3},drag:{Feature:S3,ProjectionNode:Eg,MeasureLayout:wg}},l4=/var\((--[a-zA-Z0-9-_]+),? ?([a-zA-Z0-9 ()%#.,-]+)?\)/;function u4(e){const t=l4.exec(e);if(!t)return[,];const[,n,r]=t;return[n,r]}function su(e,t,n=1){const[r,s]=u4(e);if(!r)return;const i=window.getComputedStyle(t).getPropertyValue(r);if(i){const o=i.trim();return ug(o)?parseFloat(o):o}else return Gl(s)?su(s,t,n+1):s}function c4(e,{...t},n){const r=e.current;if(!(r instanceof Element))return{target:t,transitionEnd:n};n&&(n={...n}),e.values.forEach(s=>{const i=s.get();if(!Gl(i))return;const o=su(i,r);o&&s.set(o)});for(const s in t){const i=t[s];if(!Gl(i))continue;const o=su(i,r);o&&(t[s]=o,n||(n={}),n[s]===void 0&&(n[s]=i))}return{target:t,transitionEnd:n}}const d4=new Set(["width","height","top","left","right","bottom","x","y","translateX","translateY"]),Tg=e=>d4.has(e),f4=e=>Object.keys(e).some(Tg),Jf=e=>e===Qn||e===U,eh=(e,t)=>parseFloat(e.split(", ")[t]),th=(e,t)=>(n,{transform:r})=>{if(r==="none"||!r)return 0;const s=r.match(/^matrix3d\((.+)\)$/);if(s)return eh(s[1],t);{const i=r.match(/^matrix\((.+)\)$/);return i?eh(i[1],e):0}},h4=new Set(["x","y","z"]),p4=Zs.filter(e=>!h4.has(e));function m4(e){const t=[];return p4.forEach(n=>{const r=e.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith("scale")?1:0))}),t.length&&e.render(),t}const Lr={width:({x:e},{paddingLeft:t="0",paddingRight:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),height:({y:e},{paddingTop:t="0",paddingBottom:n="0"})=>e.max-e.min-parseFloat(t)-parseFloat(n),top:(e,{top:t})=>parseFloat(t),left:(e,{left:t})=>parseFloat(t),bottom:({y:e},{top:t})=>parseFloat(t)+(e.max-e.min),right:({x:e},{left:t})=>parseFloat(t)+(e.max-e.min),x:th(4,13),y:th(5,14)};Lr.translateX=Lr.x;Lr.translateY=Lr.y;const g4=(e,t,n)=>{const r=t.measureViewportBox(),s=t.current,i=getComputedStyle(s),{display:o}=i,a={};o==="none"&&t.setStaticValue("display",e.display||"block"),n.forEach(c=>{a[c]=Lr[c](r,i)}),t.render();const l=t.measureViewportBox();return n.forEach(c=>{const d=t.getValue(c);d&&d.jump(a[c]),e[c]=Lr[c](l,i)}),e},y4=(e,t,n={},r={})=>{t={...t},r={...r};const s=Object.keys(t).filter(Tg);let i=[],o=!1;const a=[];if(s.forEach(l=>{const c=e.getValue(l);if(!e.hasValue(l))return;let d=n[l],f=Zr(d);const u=t[l];let h;if(yo(u)){const p=u.length,g=u[0]===null?1:0;d=u[g],f=Zr(d);for(let w=g;w=0?window.pageYOffset:null,c=g4(t,e,a);return i.length&&i.forEach(([d,f])=>{e.getValue(d).set(f)}),e.render(),Go&&l!==null&&window.scrollTo({top:l}),{target:c,transitionEnd:r}}else return{target:t,transitionEnd:r}};function v4(e,t,n,r){return f4(t)?y4(e,t,n,r):{target:t,transitionEnd:r}}const x4=(e,t,n,r)=>{const s=c4(e,t,r);return t=s.target,r=s.transitionEnd,v4(e,t,n,r)},iu={current:null},Ng={current:!1};function w4(){if(Ng.current=!0,!!Go)if(window.matchMedia){const e=window.matchMedia("(prefers-reduced-motion)"),t=()=>iu.current=e.matches;e.addListener(t),t()}else iu.current=!1}function b4(e,t,n){const{willChange:r}=t;for(const s in t){const i=t[s],o=n[s];if(Ge(i))e.addValue(s,i),bo(r)&&r.add(s);else if(Ge(o))e.addValue(s,Ar(i,{owner:e})),bo(r)&&r.remove(s);else if(o!==i)if(e.hasValue(s)){const a=e.getValue(s);!a.hasAnimated&&a.set(i)}else{const a=e.getStaticValue(s);e.addValue(s,Ar(a!==void 0?a:i,{owner:e}))}}for(const s in n)t[s]===void 0&&e.removeValue(s);return t}const nh=new WeakMap,Mg=Object.keys(Bs),S4=Mg.length,rh=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"],k4=fc.length;class C4{constructor({parent:t,props:n,presenceContext:r,reducedMotionConfig:s,visualState:i},o={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.values=new Map,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.scheduleRender=()=>se.render(this.render,!1,!0);const{latestValues:a,renderState:l}=i;this.latestValues=a,this.baseTarget={...a},this.initialValues=n.initial?{...a}:{},this.renderState=l,this.parent=t,this.props=n,this.presenceContext=r,this.depth=t?t.depth+1:0,this.reducedMotionConfig=s,this.options=o,this.isControllingVariants=Ko(n),this.isVariantNode=p0(n),this.isVariantNode&&(this.variantChildren=new Set),this.manuallyAnimateOnMount=!!(t&&t.current);const{willChange:c,...d}=this.scrapeMotionValuesFromProps(n,{});for(const f in d){const u=d[f];a[f]!==void 0&&Ge(u)&&(u.set(a[f],!1),bo(c)&&c.add(f))}}scrapeMotionValuesFromProps(t,n){return{}}mount(t){this.current=t,nh.set(t,this),this.projection&&!this.projection.instance&&this.projection.mount(t),this.parent&&this.isVariantNode&&!this.isControllingVariants&&(this.removeFromVariantTree=this.parent.addVariantChild(this)),this.values.forEach((n,r)=>this.bindToMotionValue(r,n)),Ng.current||w4(),this.shouldReduceMotion=this.reducedMotionConfig==="never"?!1:this.reducedMotionConfig==="always"?!0:iu.current,this.parent&&this.parent.children.add(this),this.update(this.props,this.presenceContext)}unmount(){nh.delete(this.current),this.projection&&this.projection.unmount(),Ht(this.notifyUpdate),Ht(this.render),this.valueSubscriptions.forEach(t=>t()),this.removeFromVariantTree&&this.removeFromVariantTree(),this.parent&&this.parent.children.delete(this);for(const t in this.events)this.events[t].clear();for(const t in this.features)this.features[t].unmount();this.current=null}bindToMotionValue(t,n){const r=Xn.has(t),s=n.on("change",o=>{this.latestValues[t]=o,this.props.onUpdate&&se.update(this.notifyUpdate,!1,!0),r&&this.projection&&(this.projection.isTransformDirty=!0)}),i=n.on("renderRequest",this.scheduleRender);this.valueSubscriptions.set(t,()=>{s(),i()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}loadFeatures({children:t,...n},r,s,i){let o,a;for(let l=0;lthis.scheduleRender(),animationType:typeof c=="string"?c:"both",initialPromotionConfig:i,layoutScroll:u,layoutRoot:h})}return a}updateFeatures(){for(const t in this.features){const n=this.features[t];n.isMounted?n.update():(n.mount(),n.isMounted=!0)}}triggerBuild(){this.build(this.renderState,this.latestValues,this.options,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):ge()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}makeTargetAnimatable(t,n=!0){return this.makeTargetAnimatableFromInstance(t,this.props,n)}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let r=0;rn.variantChildren.delete(t)}addValue(t,n){n!==this.values.get(t)&&(this.removeValue(t),this.bindToMotionValue(t,n)),this.values.set(t,n),this.latestValues[t]=n.get()}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let r=this.values.get(t);return r===void 0&&n!==void 0&&(r=Ar(n,{owner:this}),this.addValue(t,r)),r}readValue(t){var n;return this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:(n=this.getBaseTargetFromProps(this.props,t))!==null&&n!==void 0?n:this.readValueFromInstance(this.current,t,this.options)}setBaseTarget(t,n){this.baseTarget[t]=n}getBaseTarget(t){var n;const{initial:r}=this.props,s=typeof r=="string"||typeof r=="object"?(n=xc(this.props,r))===null||n===void 0?void 0:n[t]:void 0;if(r&&s!==void 0)return s;const i=this.getBaseTargetFromProps(this.props,t);return i!==void 0&&!Ge(i)?i:this.initialValues[t]!==void 0&&s===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new Nc),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}}class _g extends C4{sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){return t.style?t.style[n]:void 0}removeValueFromRenderState(t,{vars:n,style:r}){delete n[t],delete r[t]}makeTargetAnimatableFromInstance({transition:t,transitionEnd:n,...r},{transformValues:s},i){let o=$5(r,t||{},this);if(s&&(n&&(n=s(n)),r&&(r=s(r)),o&&(o=s(o))),i){I5(this,r,o);const a=x4(this,r,o,n);n=a.transitionEnd,r=a.target}return{transition:t,transitionEnd:n,...r}}}function P4(e){return window.getComputedStyle(e)}class j4 extends _g{constructor(){super(...arguments),this.type="html"}readValueFromInstance(t,n){if(Xn.has(n)){const r=Cc(n);return r&&r.default||0}else{const r=P4(t),s=(x0(n)?r.getPropertyValue(n):r[n])||0;return typeof s=="string"?s.trim():s}}measureInstanceViewportBox(t,{transformPagePoint:n}){return vg(t,n)}build(t,n,r,s){pc(t,n,r,s.transformTemplate)}scrapeMotionValuesFromProps(t,n){return vc(t,n)}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;Ge(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}renderInstance(t,n,r,s){P0(t,n,r,s)}}class E4 extends _g{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(Xn.has(n)){const r=Cc(n);return r&&r.default||0}return n=j0.has(n)?n:cc(n),t.getAttribute(n)}measureInstanceViewportBox(){return ge()}scrapeMotionValuesFromProps(t,n){return T0(t,n)}build(t,n,r,s){gc(t,n,r,this.isSVGTag,s.transformTemplate)}renderInstance(t,n,r,s){E0(t,n,r,s)}mount(t){this.isSVGTag=yc(t.tagName),super.mount(t)}}const T4=(e,t)=>hc(e)?new E4(t,{enableHardwareAcceleration:!1}):new j4(t,{enableHardwareAcceleration:!0}),N4={layout:{ProjectionNode:Eg,MeasureLayout:wg}},M4={...n3,...Sw,...a4,...N4},I=M2((e,t)=>uw(e,t,M4,T4)),_4={},sh=e=>{let t;const n=new Set,r=(d,f)=>{const u=typeof d=="function"?d(t):d;if(!Object.is(u,t)){const h=t;t=f??(typeof u!="object"||u===null)?u:Object.assign({},t,u),n.forEach(p=>p(t,h))}},s=()=>t,l={setState:r,getState:s,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(_4?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},c=t=e(r,s,l);return l},A4=e=>e?sh(e):sh;var Ag={exports:{}},Lg={},Dg={exports:{}},Rg={};/** - * @license React - * use-sync-external-store-shim.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Dr=k;function L4(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var D4=typeof Object.is=="function"?Object.is:L4,R4=Dr.useState,V4=Dr.useEffect,F4=Dr.useLayoutEffect,z4=Dr.useDebugValue;function I4(e,t){var n=t(),r=R4({inst:{value:n,getSnapshot:t}}),s=r[0].inst,i=r[1];return F4(function(){s.value=n,s.getSnapshot=t,$a(s)&&i({inst:s})},[e,n,t]),V4(function(){return $a(s)&&i({inst:s}),e(function(){$a(s)&&i({inst:s})})},[e]),z4(n),n}function $a(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!D4(e,n)}catch{return!0}}function O4(e,t){return t()}var $4=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?O4:I4;Rg.useSyncExternalStore=Dr.useSyncExternalStore!==void 0?Dr.useSyncExternalStore:$4;Dg.exports=Rg;var B4=Dg.exports;/** - * @license React - * use-sync-external-store-shim/with-selector.production.js - * - * Copyright (c) Meta Platforms, Inc. and affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */var Jo=k,U4=B4;function W4(e,t){return e===t&&(e!==0||1/e===1/t)||e!==e&&t!==t}var H4=typeof Object.is=="function"?Object.is:W4,q4=U4.useSyncExternalStore,G4=Jo.useRef,Y4=Jo.useEffect,K4=Jo.useMemo,X4=Jo.useDebugValue;Lg.useSyncExternalStoreWithSelector=function(e,t,n,r,s){var i=G4(null);if(i.current===null){var o={hasValue:!1,value:null};i.current=o}else o=i.current;i=K4(function(){function l(h){if(!c){if(c=!0,d=h,h=r(h),s!==void 0&&o.hasValue){var p=o.value;if(s(p,h))return f=p}return f=h}if(p=f,H4(d,h))return p;var g=r(h);return s!==void 0&&s(p,g)?(d=h,p):(d=h,f=g)}var c=!1,d,f,u=n===void 0?null:n;return[function(){return l(t())},u===null?void 0:function(){return l(u())}]},[t,n,r,s]);var a=q4(e,i[0],i[1]);return Y4(function(){o.hasValue=!0,o.value=a},[a]),X4(a),a};Ag.exports=Lg;var Q4=Ag.exports;const Z4=uu(Q4),Vg={},{useDebugValue:J4}=qs,{useSyncExternalStoreWithSelector:eb}=Z4;let ih=!1;const tb=e=>e;function nb(e,t=tb,n){(Vg?"production":void 0)!=="production"&&n&&!ih&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),ih=!0);const r=eb(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return J4(r),r}const rb=e=>{(Vg?"production":void 0)!=="production"&&typeof e!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const t=typeof e=="function"?A4(e):e,n=(r,s)=>nb(t,r,s);return Object.assign(n,t),n},sb=e=>rb,ib={};function ob(e,t){let n;try{n=e()}catch{return}return{getItem:s=>{var i;const o=l=>l===null?null:JSON.parse(l,void 0),a=(i=n.getItem(s))!=null?i:null;return a instanceof Promise?a.then(o):o(a)},setItem:(s,i)=>n.setItem(s,JSON.stringify(i,void 0)),removeItem:s=>n.removeItem(s)}}const Ws=e=>t=>{try{const n=e(t);return n instanceof Promise?n:{then(r){return Ws(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return Ws(r)(n)}}}},ab=(e,t)=>(n,r,s)=>{let i={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:w=>w,version:0,merge:(w,v)=>({...v,...w}),...t},o=!1;const a=new Set,l=new Set;let c;try{c=i.getStorage()}catch{}if(!c)return e((...w)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...w)},r,s);const d=Ws(i.serialize),f=()=>{const w=i.partialize({...r()});let v;const y=d({state:w,version:i.version}).then(x=>c.setItem(i.name,x)).catch(x=>{v=x});if(v)throw v;return y},u=s.setState;s.setState=(w,v)=>{u(w,v),f()};const h=e((...w)=>{n(...w),f()},r,s);let p;const g=()=>{var w;if(!c)return;o=!1,a.forEach(y=>y(r()));const v=((w=i.onRehydrateStorage)==null?void 0:w.call(i,r()))||void 0;return Ws(c.getItem.bind(c))(i.name).then(y=>{if(y)return i.deserialize(y)}).then(y=>{if(y)if(typeof y.version=="number"&&y.version!==i.version){if(i.migrate)return i.migrate(y.state,y.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return y.state}).then(y=>{var x;return p=i.merge(y,(x=r())!=null?x:h),n(p,!0),f()}).then(()=>{v==null||v(p,void 0),o=!0,l.forEach(y=>y(p))}).catch(y=>{v==null||v(void 0,y)})};return s.persist={setOptions:w=>{i={...i,...w},w.getStorage&&(c=w.getStorage())},clearStorage:()=>{c==null||c.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>g(),hasHydrated:()=>o,onHydrate:w=>(a.add(w),()=>{a.delete(w)}),onFinishHydration:w=>(l.add(w),()=>{l.delete(w)})},g(),p||h},lb=(e,t)=>(n,r,s)=>{let i={storage:ob(()=>localStorage),partialize:g=>g,version:0,merge:(g,w)=>({...w,...g}),...t},o=!1;const a=new Set,l=new Set;let c=i.storage;if(!c)return e((...g)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...g)},r,s);const d=()=>{const g=i.partialize({...r()});return c.setItem(i.name,{state:g,version:i.version})},f=s.setState;s.setState=(g,w)=>{f(g,w),d()};const u=e((...g)=>{n(...g),d()},r,s);s.getInitialState=()=>u;let h;const p=()=>{var g,w;if(!c)return;o=!1,a.forEach(y=>{var x;return y((x=r())!=null?x:u)});const v=((w=i.onRehydrateStorage)==null?void 0:w.call(i,(g=r())!=null?g:u))||void 0;return Ws(c.getItem.bind(c))(i.name).then(y=>{if(y)if(typeof y.version=="number"&&y.version!==i.version){if(i.migrate)return[!0,i.migrate(y.state,y.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,y.state];return[!1,void 0]}).then(y=>{var x;const[b,S]=y;if(h=i.merge(S,(x=r())!=null?x:u),n(h,!0),b)return d()}).then(()=>{v==null||v(h,void 0),h=r(),o=!0,l.forEach(y=>y(h))}).catch(y=>{v==null||v(void 0,y)})};return s.persist={setOptions:g=>{i={...i,...g},g.storage&&(c=g.storage)},clearStorage:()=>{c==null||c.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>p(),hasHydrated:()=>o,onHydrate:g=>(a.add(g),()=>{a.delete(g)}),onFinishHydration:g=>(l.add(g),()=>{l.delete(g)})},i.skipHydration||p(),h||u},ub=(e,t)=>"getStorage"in t||"serialize"in t||"deserialize"in t?((ib?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),ab(e,t)):lb(e,t),cb=ub,oh={currentUser:null,partnerUser:null,isLoading:!1,error:null,currentTrack:null,isPlaying:!1},ve=sb()(cb(e=>({...oh,mixedPlaylists:[],memoryLane:[],theme:"green",setCurrentUser:t=>e({currentUser:t}),setPartnerUser:t=>e({partnerUser:t}),logout:()=>e({currentUser:null,partnerUser:null,currentTrack:null,isPlaying:!1,mixedPlaylists:[],memoryLane:[],error:null}),setLoading:t=>e({isLoading:t}),setError:t=>e({error:t}),setCurrentTrack:t=>e({currentTrack:t}),setIsPlaying:t=>e({isPlaying:t}),addMixedPlaylist:t=>e(n=>({mixedPlaylists:[...n.mixedPlaylists,t]})),removeMixedPlaylist:t=>e(n=>({mixedPlaylists:n.mixedPlaylists.filter(r=>r.id!==t)})),addMemoryLaneItem:t=>e(n=>({memoryLane:[...n.memoryLane,t].sort((r,s)=>new Date(s.date).getTime()-new Date(r.date).getTime())})),removeMemoryLaneItem:t=>e(n=>({memoryLane:n.memoryLane.filter(r=>r.id!==t)})),setTheme:t=>e({theme:t}),clearAllData:()=>e({...oh,mixedPlaylists:[],memoryLane:[]})}),{name:"spotify-app-settings",partialize:e=>({theme:e.theme})})),Mc="/api";function Rr(){try{const e=localStorage.getItem("spotify-user");if(!e)return null;const t=JSON.parse(e);return(t==null?void 0:t.jwt)||(t==null?void 0:t.token)||null}catch{return null}}async function Ct(e,t,n){const r=await fetch(`${Mc}${e}`,{method:"POST",headers:{"Content-Type":"application/json",...n?{Authorization:`Bearer ${n}`}:Rr()?{Authorization:`Bearer ${Rr()}`}:{}},body:t?JSON.stringify(t):void 0});if(!r.ok){const s=await r.text();throw new Error(s||`Request failed: ${r.status}`)}return r.json()}async function ye(e,t){const n=await fetch(`${Mc}${e}`,{headers:{...Rr()?{Authorization:`Bearer ${Rr()}`}:{}}});if(!n.ok){const r=await n.text();throw new Error(r||`Request failed: ${n.status}`)}return n.json()}async function db(e,t,n){const r=await fetch(`${Mc}${e}`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",...Rr()?{Authorization:`Bearer ${Rr()}`}:{}},body:new URLSearchParams(t).toString()});if(!r.ok){const s=await r.text();throw new Error(s||`Request failed: ${r.status}`)}return r.json()}const Vr=e=>{const t={green:{primary:"bg-theme-green-primary text-white",secondary:"bg-theme-green-secondary text-white",accent:"bg-theme-green-accent text-white",border:"border-theme-green-primary",text:"text-theme-green-primary",gradient:"from-theme-green-primary to-theme-green-secondary",glass:"bg-theme-green-primary/10 border-theme-green-primary/30",hover:"hover:bg-theme-green-primary/20",cssVars:{primary:"#1db954",secondary:"#1ed760",accent:"#00e676"}},pink:{primary:"bg-theme-pink-primary text-white",secondary:"bg-theme-pink-secondary text-white",accent:"bg-theme-pink-accent text-white",border:"border-theme-pink-primary",text:"text-theme-pink-primary",gradient:"from-theme-pink-primary to-theme-pink-secondary",glass:"bg-theme-pink-primary/10 border-theme-pink-primary/30",hover:"hover:bg-theme-pink-primary/20",cssVars:{primary:"#ec4899",secondary:"#f472b6",accent:"#fb7185"}},blue:{primary:"bg-theme-blue-primary text-white",secondary:"bg-theme-blue-secondary text-white",accent:"bg-theme-blue-accent text-white",border:"border-theme-blue-primary",text:"text-theme-blue-primary",gradient:"from-theme-blue-primary to-theme-blue-secondary",glass:"bg-theme-blue-primary/10 border-theme-blue-primary/30",hover:"hover:bg-theme-blue-primary/20",cssVars:{primary:"#3b82f6",secondary:"#60a5fa",accent:"#93c5fd"}},red:{primary:"bg-theme-red-primary text-white",secondary:"bg-theme-red-secondary text-white",accent:"bg-theme-red-accent text-white",border:"border-theme-red-primary",text:"text-theme-red-primary",gradient:"from-theme-red-primary to-theme-red-secondary",glass:"bg-theme-red-primary/10 border-theme-red-primary/30",hover:"hover:bg-theme-red-primary/20",cssVars:{primary:"#dc2626",secondary:"#ef4444",accent:"#f87171"}},purple:{primary:"bg-theme-purple-primary text-white",secondary:"bg-theme-purple-secondary text-white",accent:"bg-theme-purple-accent text-white",border:"border-theme-purple-primary",text:"text-theme-purple-primary",gradient:"from-theme-purple-primary to-theme-purple-secondary",glass:"bg-theme-purple-primary/10 border-theme-purple-primary/30",hover:"hover:bg-theme-purple-primary/20",cssVars:{primary:"#8b5cf6",secondary:"#a78bfa",accent:"#c4b5fd"}},yellow:{primary:"bg-theme-yellow-primary text-black",secondary:"bg-theme-yellow-secondary text-black",accent:"bg-theme-yellow-accent text-black",border:"border-theme-yellow-primary",text:"text-theme-yellow-primary",gradient:"from-theme-yellow-primary to-theme-yellow-secondary",glass:"bg-theme-yellow-primary/10 border-theme-yellow-primary/30",hover:"hover:bg-theme-yellow-primary/20",cssVars:{primary:"#eab308",secondary:"#f59e0b",accent:"#fbbf24"}},turquoise:{primary:"bg-theme-turquoise-primary text-white",secondary:"bg-theme-turquoise-secondary text-white",accent:"bg-theme-turquoise-accent text-white",border:"border-theme-turquoise-primary",text:"text-theme-turquoise-primary",gradient:"from-theme-turquoise-primary to-theme-turquoise-secondary",glass:"bg-theme-turquoise-primary/10 border-theme-turquoise-primary/30",hover:"hover:bg-theme-turquoise-primary/20",cssVars:{primary:"#06b6d4",secondary:"#22d3ee",accent:"#67e8f9"}}},n=t[e]||t.green;if(typeof document<"u"){const r=document.documentElement;r.style.setProperty("--theme-primary",n.cssVars.primary),r.style.setProperty("--theme-secondary",n.cssVars.secondary),r.style.setProperty("--theme-accent",n.cssVars.accent)}return n},ah=e=>({green:120,pink:300,blue:360,red:245,purple:280,yellow:200,turquoise:40})[e]||120;function ws(e){let t=e[0],n=e[1],r=e[2];return Math.sqrt(t*t+n*n+r*r)}function ou(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e}function fb(e,t,n,r){return e[0]=t,e[1]=n,e[2]=r,e}function lh(e,t,n){return e[0]=t[0]+n[0],e[1]=t[1]+n[1],e[2]=t[2]+n[2],e}function uh(e,t,n){return e[0]=t[0]-n[0],e[1]=t[1]-n[1],e[2]=t[2]-n[2],e}function hb(e,t,n){return e[0]=t[0]*n[0],e[1]=t[1]*n[1],e[2]=t[2]*n[2],e}function pb(e,t,n){return e[0]=t[0]/n[0],e[1]=t[1]/n[1],e[2]=t[2]/n[2],e}function Ba(e,t,n){return e[0]=t[0]*n,e[1]=t[1]*n,e[2]=t[2]*n,e}function mb(e,t){let n=t[0]-e[0],r=t[1]-e[1],s=t[2]-e[2];return Math.sqrt(n*n+r*r+s*s)}function gb(e,t){let n=t[0]-e[0],r=t[1]-e[1],s=t[2]-e[2];return n*n+r*r+s*s}function ch(e){let t=e[0],n=e[1],r=e[2];return t*t+n*n+r*r}function yb(e,t){return e[0]=-t[0],e[1]=-t[1],e[2]=-t[2],e}function vb(e,t){return e[0]=1/t[0],e[1]=1/t[1],e[2]=1/t[2],e}function au(e,t){let n=t[0],r=t[1],s=t[2],i=n*n+r*r+s*s;return i>0&&(i=1/Math.sqrt(i)),e[0]=t[0]*i,e[1]=t[1]*i,e[2]=t[2]*i,e}function Fg(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}function dh(e,t,n){let r=t[0],s=t[1],i=t[2],o=n[0],a=n[1],l=n[2];return e[0]=s*l-i*a,e[1]=i*o-r*l,e[2]=r*a-s*o,e}function xb(e,t,n,r){let s=t[0],i=t[1],o=t[2];return e[0]=s+r*(n[0]-s),e[1]=i+r*(n[1]-i),e[2]=o+r*(n[2]-o),e}function wb(e,t,n,r,s){const i=Math.exp(-r*s);let o=t[0],a=t[1],l=t[2];return e[0]=n[0]+(o-n[0])*i,e[1]=n[1]+(a-n[1])*i,e[2]=n[2]+(l-n[2])*i,e}function bb(e,t,n){let r=t[0],s=t[1],i=t[2],o=n[3]*r+n[7]*s+n[11]*i+n[15];return o=o||1,e[0]=(n[0]*r+n[4]*s+n[8]*i+n[12])/o,e[1]=(n[1]*r+n[5]*s+n[9]*i+n[13])/o,e[2]=(n[2]*r+n[6]*s+n[10]*i+n[14])/o,e}function Sb(e,t,n){let r=t[0],s=t[1],i=t[2],o=n[3]*r+n[7]*s+n[11]*i+n[15];return o=o||1,e[0]=(n[0]*r+n[4]*s+n[8]*i)/o,e[1]=(n[1]*r+n[5]*s+n[9]*i)/o,e[2]=(n[2]*r+n[6]*s+n[10]*i)/o,e}function kb(e,t,n){let r=t[0],s=t[1],i=t[2];return e[0]=r*n[0]+s*n[3]+i*n[6],e[1]=r*n[1]+s*n[4]+i*n[7],e[2]=r*n[2]+s*n[5]+i*n[8],e}function Cb(e,t,n){let r=t[0],s=t[1],i=t[2],o=n[0],a=n[1],l=n[2],c=n[3],d=a*i-l*s,f=l*r-o*i,u=o*s-a*r,h=a*u-l*f,p=l*d-o*u,g=o*f-a*d,w=c*2;return d*=w,f*=w,u*=w,h*=2,p*=2,g*=2,e[0]=r+d+h,e[1]=s+f+p,e[2]=i+u+g,e}const Pb=function(){const e=[0,0,0],t=[0,0,0];return function(n,r){ou(e,n),ou(t,r),au(e,e),au(t,t);let s=Fg(e,t);return s>1?0:s<-1?Math.PI:Math.acos(s)}}();function jb(e,t){return e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]}class mt extends Array{constructor(t=0,n=t,r=t){return super(t,n,r),this}get x(){return this[0]}get y(){return this[1]}get z(){return this[2]}set x(t){this[0]=t}set y(t){this[1]=t}set z(t){this[2]=t}set(t,n=t,r=t){return t.length?this.copy(t):(fb(this,t,n,r),this)}copy(t){return ou(this,t),this}add(t,n){return n?lh(this,t,n):lh(this,this,t),this}sub(t,n){return n?uh(this,t,n):uh(this,this,t),this}multiply(t){return t.length?hb(this,this,t):Ba(this,this,t),this}divide(t){return t.length?pb(this,this,t):Ba(this,this,1/t),this}inverse(t=this){return vb(this,t),this}len(){return ws(this)}distance(t){return t?mb(this,t):ws(this)}squaredLen(){return ch(this)}squaredDistance(t){return t?gb(this,t):ch(this)}negate(t=this){return yb(this,t),this}cross(t,n){return n?dh(this,t,n):dh(this,this,t),this}scale(t){return Ba(this,this,t),this}normalize(){return au(this,this),this}dot(t){return Fg(this,t)}equals(t){return jb(this,t)}applyMatrix3(t){return kb(this,this,t),this}applyMatrix4(t){return bb(this,this,t),this}scaleRotateMatrix4(t){return Sb(this,this,t),this}applyQuaternion(t){return Cb(this,this,t),this}angle(t){return Pb(this,t)}lerp(t,n){return xb(this,this,t,n),this}smoothLerp(t,n,r){return wb(this,this,t,n,r),this}clone(){return new mt(this[0],this[1],this[2])}fromArray(t,n=0){return this[0]=t[n],this[1]=t[n+1],this[2]=t[n+2],this}toArray(t=[],n=0){return t[n]=this[0],t[n+1]=this[1],t[n+2]=this[2],t}transformDirection(t){const n=this[0],r=this[1],s=this[2];return this[0]=t[0]*n+t[4]*r+t[8]*s,this[1]=t[1]*n+t[5]*r+t[9]*s,this[2]=t[2]*n+t[6]*r+t[10]*s,this.normalize()}}const fh=new mt;let Eb=1,Tb=1,hh=!1;class Nb{constructor(t,n={}){t.canvas||console.error("gl not passed as first argument to Geometry"),this.gl=t,this.attributes=n,this.id=Eb++,this.VAOs={},this.drawRange={start:0,count:0},this.instancedCount=0,this.gl.renderer.bindVertexArray(null),this.gl.renderer.currentGeometry=null,this.glState=this.gl.renderer.state;for(let r in n)this.addAttribute(r,n[r])}addAttribute(t,n){if(this.attributes[t]=n,n.id=Tb++,n.size=n.size||1,n.type=n.type||(n.data.constructor===Float32Array?this.gl.FLOAT:n.data.constructor===Uint16Array?this.gl.UNSIGNED_SHORT:this.gl.UNSIGNED_INT),n.target=t==="index"?this.gl.ELEMENT_ARRAY_BUFFER:this.gl.ARRAY_BUFFER,n.normalized=n.normalized||!1,n.stride=n.stride||0,n.offset=n.offset||0,n.count=n.count||(n.stride?n.data.byteLength/n.stride:n.data.length/n.size),n.divisor=n.instanced||0,n.needsUpdate=!1,n.usage=n.usage||this.gl.STATIC_DRAW,n.buffer||this.updateAttribute(n),n.divisor){if(this.isInstanced=!0,this.instancedCount&&this.instancedCount!==n.count*n.divisor)return console.warn("geometry has multiple instanced buffers of different length"),this.instancedCount=Math.min(this.instancedCount,n.count*n.divisor);this.instancedCount=n.count*n.divisor}else t==="index"?this.drawRange.count=n.count:this.attributes.index||(this.drawRange.count=Math.max(this.drawRange.count,n.count))}updateAttribute(t){const n=!t.buffer;n&&(t.buffer=this.gl.createBuffer()),this.glState.boundBuffer!==t.buffer&&(this.gl.bindBuffer(t.target,t.buffer),this.glState.boundBuffer=t.buffer),n?this.gl.bufferData(t.target,t.data,t.usage):this.gl.bufferSubData(t.target,0,t.data),t.needsUpdate=!1}setIndex(t){this.addAttribute("index",t)}setDrawRange(t,n){this.drawRange.start=t,this.drawRange.count=n}setInstancedCount(t){this.instancedCount=t}createVAO(t){this.VAOs[t.attributeOrder]=this.gl.renderer.createVertexArray(),this.gl.renderer.bindVertexArray(this.VAOs[t.attributeOrder]),this.bindAttributes(t)}bindAttributes(t){t.attributeLocations.forEach((n,{name:r,type:s})=>{if(!this.attributes[r]){console.warn(`active attribute ${r} not being supplied`);return}const i=this.attributes[r];this.gl.bindBuffer(i.target,i.buffer),this.glState.boundBuffer=i.buffer;let o=1;s===35674&&(o=2),s===35675&&(o=3),s===35676&&(o=4);const a=i.size/o,l=o===1?0:o*o*4,c=o===1?0:o*4;for(let d=0;d{const a=this.attributes[o];a.needsUpdate&&this.updateAttribute(a)});let r=2;((s=this.attributes.index)==null?void 0:s.type)===this.gl.UNSIGNED_INT&&(r=4),this.isInstanced?this.attributes.index?this.gl.renderer.drawElementsInstanced(n,this.drawRange.count,this.attributes.index.type,this.attributes.index.offset+this.drawRange.start*r,this.instancedCount):this.gl.renderer.drawArraysInstanced(n,this.drawRange.start,this.drawRange.count,this.instancedCount):this.attributes.index?this.gl.drawElements(n,this.drawRange.count,this.attributes.index.type,this.attributes.index.offset+this.drawRange.start*r):this.gl.drawArrays(n,this.drawRange.start,this.drawRange.count)}getPosition(){const t=this.attributes.position;if(t.data)return t;if(!hh)return console.warn("No position buffer data found to compute bounds"),hh=!0}computeBoundingBox(t){t||(t=this.getPosition());const n=t.data,r=t.size;this.bounds||(this.bounds={min:new mt,max:new mt,center:new mt,scale:new mt,radius:1/0});const s=this.bounds.min,i=this.bounds.max,o=this.bounds.center,a=this.bounds.scale;s.set(1/0),i.set(-1/0);for(let l=0,c=n.length;l{let o=this.uniforms[i.uniformName];for(const a of i.nameComponents){if(!o)break;if(a in o)o=o[a];else{if(Array.isArray(o.value))break;o=void 0;break}}if(!o)return gh(`Active uniform ${i.name} has not been supplied`);if(o&&o.value===void 0)return gh(`${i.name} uniform is missing a value parameter`);if(o.value.texture)return n=n+1,o.value.update(n),Ua(this.gl,i.type,s,n);if(o.value.length&&o.value[0].texture){const a=[];return o.value.forEach(l=>{n=n+1,l.update(n),a.push(n)}),Ua(this.gl,i.type,s,a)}Ua(this.gl,i.type,s,o.value)}),this.applyState(),t&&this.gl.renderer.setFrontFace(this.frontFace===this.gl.CCW?this.gl.CW:this.gl.CCW)}remove(){this.gl.deleteProgram(this.program)}}function Ua(e,t,n,r){r=r.length?Ab(r):r;const s=e.renderer.state.uniformLocations.get(n);if(r.length)if(s===void 0||s.length!==r.length)e.renderer.state.uniformLocations.set(n,r.slice(0));else{if(Lb(s,r))return;s.set?s.set(r):Db(s,r),e.renderer.state.uniformLocations.set(n,s)}else{if(s===r)return;e.renderer.state.uniformLocations.set(n,r)}switch(t){case 5126:return r.length?e.uniform1fv(n,r):e.uniform1f(n,r);case 35664:return e.uniform2fv(n,r);case 35665:return e.uniform3fv(n,r);case 35666:return e.uniform4fv(n,r);case 35670:case 5124:case 35678:case 36306:case 35680:case 36289:return r.length?e.uniform1iv(n,r):e.uniform1i(n,r);case 35671:case 35667:return e.uniform2iv(n,r);case 35672:case 35668:return e.uniform3iv(n,r);case 35673:case 35669:return e.uniform4iv(n,r);case 35674:return e.uniformMatrix2fv(n,!1,r);case 35675:return e.uniformMatrix3fv(n,!1,r);case 35676:return e.uniformMatrix4fv(n,!1,r)}}function mh(e){let t=e.split(` -`);for(let n=0;n100||(console.warn(e),Wa++,Wa>100&&console.warn("More than 100 program warnings - stopping logs."))}const Ha=new mt;let Rb=1;class Vb{constructor({canvas:t=document.createElement("canvas"),width:n=300,height:r=150,dpr:s=1,alpha:i=!1,depth:o=!0,stencil:a=!1,antialias:l=!1,premultipliedAlpha:c=!1,preserveDrawingBuffer:d=!1,powerPreference:f="default",autoClear:u=!0,webgl:h=2}={}){const p={alpha:i,depth:o,stencil:a,antialias:l,premultipliedAlpha:c,preserveDrawingBuffer:d,powerPreference:f};this.dpr=s,this.alpha=i,this.color=!0,this.depth=o,this.stencil=a,this.premultipliedAlpha=c,this.autoClear=u,this.id=Rb++,h===2&&(this.gl=t.getContext("webgl2",p)),this.isWebgl2=!!this.gl,this.gl||(this.gl=t.getContext("webgl",p)),this.gl||console.error("unable to create webgl context"),this.gl.renderer=this,this.setSize(n,r),this.state={},this.state.blendFunc={src:this.gl.ONE,dst:this.gl.ZERO},this.state.blendEquation={modeRGB:this.gl.FUNC_ADD},this.state.cullFace=!1,this.state.frontFace=this.gl.CCW,this.state.depthMask=!0,this.state.depthFunc=this.gl.LEQUAL,this.state.premultiplyAlpha=!1,this.state.flipY=!1,this.state.unpackAlignment=4,this.state.framebuffer=null,this.state.viewport={x:0,y:0,width:null,height:null},this.state.textureUnits=[],this.state.activeTextureUnit=0,this.state.boundBuffer=null,this.state.uniformLocations=new Map,this.state.currentProgram=null,this.extensions={},this.isWebgl2?(this.getExtension("EXT_color_buffer_float"),this.getExtension("OES_texture_float_linear")):(this.getExtension("OES_texture_float"),this.getExtension("OES_texture_float_linear"),this.getExtension("OES_texture_half_float"),this.getExtension("OES_texture_half_float_linear"),this.getExtension("OES_element_index_uint"),this.getExtension("OES_standard_derivatives"),this.getExtension("EXT_sRGB"),this.getExtension("WEBGL_depth_texture"),this.getExtension("WEBGL_draw_buffers")),this.getExtension("WEBGL_compressed_texture_astc"),this.getExtension("EXT_texture_compression_bptc"),this.getExtension("WEBGL_compressed_texture_s3tc"),this.getExtension("WEBGL_compressed_texture_etc1"),this.getExtension("WEBGL_compressed_texture_pvrtc"),this.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),this.vertexAttribDivisor=this.getExtension("ANGLE_instanced_arrays","vertexAttribDivisor","vertexAttribDivisorANGLE"),this.drawArraysInstanced=this.getExtension("ANGLE_instanced_arrays","drawArraysInstanced","drawArraysInstancedANGLE"),this.drawElementsInstanced=this.getExtension("ANGLE_instanced_arrays","drawElementsInstanced","drawElementsInstancedANGLE"),this.createVertexArray=this.getExtension("OES_vertex_array_object","createVertexArray","createVertexArrayOES"),this.bindVertexArray=this.getExtension("OES_vertex_array_object","bindVertexArray","bindVertexArrayOES"),this.deleteVertexArray=this.getExtension("OES_vertex_array_object","deleteVertexArray","deleteVertexArrayOES"),this.drawBuffers=this.getExtension("WEBGL_draw_buffers","drawBuffers","drawBuffersWEBGL"),this.parameters={},this.parameters.maxTextureUnits=this.gl.getParameter(this.gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS),this.parameters.maxAnisotropy=this.getExtension("EXT_texture_filter_anisotropic")?this.gl.getParameter(this.getExtension("EXT_texture_filter_anisotropic").MAX_TEXTURE_MAX_ANISOTROPY_EXT):0}setSize(t,n){this.width=t,this.height=n,this.gl.canvas.width=t*this.dpr,this.gl.canvas.height=n*this.dpr,this.gl.canvas.style&&Object.assign(this.gl.canvas.style,{width:t+"px",height:n+"px"})}setViewport(t,n,r=0,s=0){this.state.viewport.width===t&&this.state.viewport.height===n||(this.state.viewport.width=t,this.state.viewport.height=n,this.state.viewport.x=r,this.state.viewport.y=s,this.gl.viewport(r,s,t,n))}setScissor(t,n,r=0,s=0){this.gl.scissor(r,s,t,n)}enable(t){this.state[t]!==!0&&(this.gl.enable(t),this.state[t]=!0)}disable(t){this.state[t]!==!1&&(this.gl.disable(t),this.state[t]=!1)}setBlendFunc(t,n,r,s){this.state.blendFunc.src===t&&this.state.blendFunc.dst===n&&this.state.blendFunc.srcAlpha===r&&this.state.blendFunc.dstAlpha===s||(this.state.blendFunc.src=t,this.state.blendFunc.dst=n,this.state.blendFunc.srcAlpha=r,this.state.blendFunc.dstAlpha=s,r!==void 0?this.gl.blendFuncSeparate(t,n,r,s):this.gl.blendFunc(t,n))}setBlendEquation(t,n){t=t||this.gl.FUNC_ADD,!(this.state.blendEquation.modeRGB===t&&this.state.blendEquation.modeAlpha===n)&&(this.state.blendEquation.modeRGB=t,this.state.blendEquation.modeAlpha=n,n!==void 0?this.gl.blendEquationSeparate(t,n):this.gl.blendEquation(t))}setCullFace(t){this.state.cullFace!==t&&(this.state.cullFace=t,this.gl.cullFace(t))}setFrontFace(t){this.state.frontFace!==t&&(this.state.frontFace=t,this.gl.frontFace(t))}setDepthMask(t){this.state.depthMask!==t&&(this.state.depthMask=t,this.gl.depthMask(t))}setDepthFunc(t){this.state.depthFunc!==t&&(this.state.depthFunc=t,this.gl.depthFunc(t))}setStencilMask(t){this.state.stencilMask!==t&&(this.state.stencilMask=t,this.gl.stencilMask(t))}setStencilFunc(t,n,r){this.state.stencilFunc===t&&this.state.stencilRef===n&&this.state.stencilFuncMask===r||(this.state.stencilFunc=t||this.gl.ALWAYS,this.state.stencilRef=n||0,this.state.stencilFuncMask=r||0,this.gl.stencilFunc(t||this.gl.ALWAYS,n||0,r||0))}setStencilOp(t,n,r){this.state.stencilFail===t&&this.state.stencilDepthFail===n&&this.state.stencilDepthPass===r||(this.state.stencilFail=t,this.state.stencilDepthFail=n,this.state.stencilDepthPass=r,this.gl.stencilOp(t,n,r))}activeTexture(t){this.state.activeTextureUnit!==t&&(this.state.activeTextureUnit=t,this.gl.activeTexture(this.gl.TEXTURE0+t))}bindFramebuffer({target:t=this.gl.FRAMEBUFFER,buffer:n=null}={}){this.state.framebuffer!==n&&(this.state.framebuffer=n,this.gl.bindFramebuffer(t,n))}getExtension(t,n,r){return n&&this.gl[n]?this.gl[n].bind(this.gl):(this.extensions[t]||(this.extensions[t]=this.gl.getExtension(t)),n?this.extensions[t]?this.extensions[t][r].bind(this.extensions[t]):null:this.extensions[t])}sortOpaque(t,n){return t.renderOrder!==n.renderOrder?t.renderOrder-n.renderOrder:t.program.id!==n.program.id?t.program.id-n.program.id:t.zDepth!==n.zDepth?t.zDepth-n.zDepth:n.id-t.id}sortTransparent(t,n){return t.renderOrder!==n.renderOrder?t.renderOrder-n.renderOrder:t.zDepth!==n.zDepth?n.zDepth-t.zDepth:n.id-t.id}sortUI(t,n){return t.renderOrder!==n.renderOrder?t.renderOrder-n.renderOrder:t.program.id!==n.program.id?t.program.id-n.program.id:n.id-t.id}getRenderList({scene:t,camera:n,frustumCull:r,sort:s}){let i=[];if(n&&r&&n.updateFrustum(),t.traverse(o=>{if(!o.visible)return!0;o.draw&&(r&&o.frustumCulled&&n&&!n.frustumIntersectsMesh(o)||i.push(o))}),s){const o=[],a=[],l=[];i.forEach(c=>{c.program.transparent?c.program.depthTest?a.push(c):l.push(c):o.push(c),c.zDepth=0,!(c.renderOrder!==0||!c.program.depthTest||!n)&&(c.worldMatrix.getTranslation(Ha),Ha.applyMatrix4(n.projectionViewMatrix),c.zDepth=Ha.z)}),o.sort(this.sortOpaque),a.sort(this.sortTransparent),l.sort(this.sortUI),i=o.concat(a,l)}return i}render({scene:t,camera:n,target:r=null,update:s=!0,sort:i=!0,frustumCull:o=!0,clear:a}){r===null?(this.bindFramebuffer(),this.setViewport(this.width*this.dpr,this.height*this.dpr)):(this.bindFramebuffer(r),this.setViewport(r.width,r.height)),(a||this.autoClear&&a!==!1)&&(this.depth&&(!r||r.depth)&&(this.enable(this.gl.DEPTH_TEST),this.setDepthMask(!0)),(this.stencil||!r||r.stencil)&&(this.enable(this.gl.STENCIL_TEST),this.setStencilMask(255)),this.gl.clear((this.color?this.gl.COLOR_BUFFER_BIT:0)|(this.depth?this.gl.DEPTH_BUFFER_BIT:0)|(this.stencil?this.gl.STENCIL_BUFFER_BIT:0))),s&&t.updateMatrixWorld(),n&&n.updateMatrixWorld(),this.getRenderList({scene:t,camera:n,frustumCull:o,sort:i}).forEach(c=>{c.draw({camera:n})})}}function Fb(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e}function zb(e,t,n,r,s){return e[0]=t,e[1]=n,e[2]=r,e[3]=s,e}function Ib(e,t){let n=t[0],r=t[1],s=t[2],i=t[3],o=n*n+r*r+s*s+i*i;return o>0&&(o=1/Math.sqrt(o)),e[0]=n*o,e[1]=r*o,e[2]=s*o,e[3]=i*o,e}function Ob(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3]}function $b(e){return e[0]=0,e[1]=0,e[2]=0,e[3]=1,e}function Bb(e,t,n){n=n*.5;let r=Math.sin(n);return e[0]=r*t[0],e[1]=r*t[1],e[2]=r*t[2],e[3]=Math.cos(n),e}function yh(e,t,n){let r=t[0],s=t[1],i=t[2],o=t[3],a=n[0],l=n[1],c=n[2],d=n[3];return e[0]=r*d+o*a+s*c-i*l,e[1]=s*d+o*l+i*a-r*c,e[2]=i*d+o*c+r*l-s*a,e[3]=o*d-r*a-s*l-i*c,e}function Ub(e,t,n){n*=.5;let r=t[0],s=t[1],i=t[2],o=t[3],a=Math.sin(n),l=Math.cos(n);return e[0]=r*l+o*a,e[1]=s*l+i*a,e[2]=i*l-s*a,e[3]=o*l-r*a,e}function Wb(e,t,n){n*=.5;let r=t[0],s=t[1],i=t[2],o=t[3],a=Math.sin(n),l=Math.cos(n);return e[0]=r*l-i*a,e[1]=s*l+o*a,e[2]=i*l+r*a,e[3]=o*l-s*a,e}function Hb(e,t,n){n*=.5;let r=t[0],s=t[1],i=t[2],o=t[3],a=Math.sin(n),l=Math.cos(n);return e[0]=r*l+s*a,e[1]=s*l-r*a,e[2]=i*l+o*a,e[3]=o*l-i*a,e}function qb(e,t,n,r){let s=t[0],i=t[1],o=t[2],a=t[3],l=n[0],c=n[1],d=n[2],f=n[3],u,h,p,g,w;return h=s*l+i*c+o*d+a*f,h<0&&(h=-h,l=-l,c=-c,d=-d,f=-f),1-h>1e-6?(u=Math.acos(h),p=Math.sin(u),g=Math.sin((1-r)*u)/p,w=Math.sin(r*u)/p):(g=1-r,w=r),e[0]=g*s+w*l,e[1]=g*i+w*c,e[2]=g*o+w*d,e[3]=g*a+w*f,e}function Gb(e,t){let n=t[0],r=t[1],s=t[2],i=t[3],o=n*n+r*r+s*s+i*i,a=o?1/o:0;return e[0]=-n*a,e[1]=-r*a,e[2]=-s*a,e[3]=i*a,e}function Yb(e,t){return e[0]=-t[0],e[1]=-t[1],e[2]=-t[2],e[3]=t[3],e}function Kb(e,t){let n=t[0]+t[4]+t[8],r;if(n>0)r=Math.sqrt(n+1),e[3]=.5*r,r=.5/r,e[0]=(t[5]-t[7])*r,e[1]=(t[6]-t[2])*r,e[2]=(t[1]-t[3])*r;else{let s=0;t[4]>t[0]&&(s=1),t[8]>t[s*3+s]&&(s=2);let i=(s+1)%3,o=(s+2)%3;r=Math.sqrt(t[s*3+s]-t[i*3+i]-t[o*3+o]+1),e[s]=.5*r,r=.5/r,e[3]=(t[i*3+o]-t[o*3+i])*r,e[i]=(t[i*3+s]+t[s*3+i])*r,e[o]=(t[o*3+s]+t[s*3+o])*r}return e}function Xb(e,t,n="YXZ"){let r=Math.sin(t[0]*.5),s=Math.cos(t[0]*.5),i=Math.sin(t[1]*.5),o=Math.cos(t[1]*.5),a=Math.sin(t[2]*.5),l=Math.cos(t[2]*.5);return n==="XYZ"?(e[0]=r*o*l+s*i*a,e[1]=s*i*l-r*o*a,e[2]=s*o*a+r*i*l,e[3]=s*o*l-r*i*a):n==="YXZ"?(e[0]=r*o*l+s*i*a,e[1]=s*i*l-r*o*a,e[2]=s*o*a-r*i*l,e[3]=s*o*l+r*i*a):n==="ZXY"?(e[0]=r*o*l-s*i*a,e[1]=s*i*l+r*o*a,e[2]=s*o*a+r*i*l,e[3]=s*o*l-r*i*a):n==="ZYX"?(e[0]=r*o*l-s*i*a,e[1]=s*i*l+r*o*a,e[2]=s*o*a-r*i*l,e[3]=s*o*l+r*i*a):n==="YZX"?(e[0]=r*o*l+s*i*a,e[1]=s*i*l+r*o*a,e[2]=s*o*a-r*i*l,e[3]=s*o*l-r*i*a):n==="XZY"&&(e[0]=r*o*l-s*i*a,e[1]=s*i*l-r*o*a,e[2]=s*o*a+r*i*l,e[3]=s*o*l+r*i*a),e}const Qb=Fb,Zb=zb,Jb=Ob,eS=Ib;class tS extends Array{constructor(t=0,n=0,r=0,s=1){super(t,n,r,s),this.onChange=()=>{},this._target=this;const i=["0","1","2","3"];return new Proxy(this,{set(o,a){const l=Reflect.set(...arguments);return l&&i.includes(a)&&o.onChange(),l}})}get x(){return this[0]}get y(){return this[1]}get z(){return this[2]}get w(){return this[3]}set x(t){this._target[0]=t,this.onChange()}set y(t){this._target[1]=t,this.onChange()}set z(t){this._target[2]=t,this.onChange()}set w(t){this._target[3]=t,this.onChange()}identity(){return $b(this._target),this.onChange(),this}set(t,n,r,s){return t.length?this.copy(t):(Zb(this._target,t,n,r,s),this.onChange(),this)}rotateX(t){return Ub(this._target,this._target,t),this.onChange(),this}rotateY(t){return Wb(this._target,this._target,t),this.onChange(),this}rotateZ(t){return Hb(this._target,this._target,t),this.onChange(),this}inverse(t=this._target){return Gb(this._target,t),this.onChange(),this}conjugate(t=this._target){return Yb(this._target,t),this.onChange(),this}copy(t){return Qb(this._target,t),this.onChange(),this}normalize(t=this._target){return eS(this._target,t),this.onChange(),this}multiply(t,n){return n?yh(this._target,t,n):yh(this._target,this._target,t),this.onChange(),this}dot(t){return Jb(this._target,t)}fromMatrix3(t){return Kb(this._target,t),this.onChange(),this}fromEuler(t,n){return Xb(this._target,t,t.order),n||this.onChange(),this}fromAxisAngle(t,n){return Bb(this._target,t,n),this.onChange(),this}slerp(t,n){return qb(this._target,this._target,t,n),this.onChange(),this}fromArray(t,n=0){return this._target[0]=t[n],this._target[1]=t[n+1],this._target[2]=t[n+2],this._target[3]=t[n+3],this.onChange(),this}toArray(t=[],n=0){return t[n]=this[0],t[n+1]=this[1],t[n+2]=this[2],t[n+3]=this[3],t}}const nS=1e-6;function rS(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e[4]=t[4],e[5]=t[5],e[6]=t[6],e[7]=t[7],e[8]=t[8],e[9]=t[9],e[10]=t[10],e[11]=t[11],e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function sS(e,t,n,r,s,i,o,a,l,c,d,f,u,h,p,g,w){return e[0]=t,e[1]=n,e[2]=r,e[3]=s,e[4]=i,e[5]=o,e[6]=a,e[7]=l,e[8]=c,e[9]=d,e[10]=f,e[11]=u,e[12]=h,e[13]=p,e[14]=g,e[15]=w,e}function iS(e){return e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function oS(e,t){let n=t[0],r=t[1],s=t[2],i=t[3],o=t[4],a=t[5],l=t[6],c=t[7],d=t[8],f=t[9],u=t[10],h=t[11],p=t[12],g=t[13],w=t[14],v=t[15],y=n*a-r*o,x=n*l-s*o,b=n*c-i*o,S=r*l-s*a,C=r*c-i*a,P=s*c-i*l,j=d*g-f*p,_=d*w-u*p,T=d*v-h*p,F=f*w-u*g,L=f*v-h*g,W=u*v-h*w,A=y*W-x*L+b*F+S*T-C*_+P*j;return A?(A=1/A,e[0]=(a*W-l*L+c*F)*A,e[1]=(s*L-r*W-i*F)*A,e[2]=(g*P-w*C+v*S)*A,e[3]=(u*C-f*P-h*S)*A,e[4]=(l*T-o*W-c*_)*A,e[5]=(n*W-s*T+i*_)*A,e[6]=(w*b-p*P-v*x)*A,e[7]=(d*P-u*b+h*x)*A,e[8]=(o*L-a*T+c*j)*A,e[9]=(r*T-n*L-i*j)*A,e[10]=(p*C-g*b+v*y)*A,e[11]=(f*b-d*C-h*y)*A,e[12]=(a*_-o*F-l*j)*A,e[13]=(n*F-r*_+s*j)*A,e[14]=(g*x-p*S-w*y)*A,e[15]=(d*S-f*x+u*y)*A,e):null}function zg(e){let t=e[0],n=e[1],r=e[2],s=e[3],i=e[4],o=e[5],a=e[6],l=e[7],c=e[8],d=e[9],f=e[10],u=e[11],h=e[12],p=e[13],g=e[14],w=e[15],v=t*o-n*i,y=t*a-r*i,x=t*l-s*i,b=n*a-r*o,S=n*l-s*o,C=r*l-s*a,P=c*p-d*h,j=c*g-f*h,_=c*w-u*h,T=d*g-f*p,F=d*w-u*p,L=f*w-u*g;return v*L-y*F+x*T+b*_-S*j+C*P}function vh(e,t,n){let r=t[0],s=t[1],i=t[2],o=t[3],a=t[4],l=t[5],c=t[6],d=t[7],f=t[8],u=t[9],h=t[10],p=t[11],g=t[12],w=t[13],v=t[14],y=t[15],x=n[0],b=n[1],S=n[2],C=n[3];return e[0]=x*r+b*a+S*f+C*g,e[1]=x*s+b*l+S*u+C*w,e[2]=x*i+b*c+S*h+C*v,e[3]=x*o+b*d+S*p+C*y,x=n[4],b=n[5],S=n[6],C=n[7],e[4]=x*r+b*a+S*f+C*g,e[5]=x*s+b*l+S*u+C*w,e[6]=x*i+b*c+S*h+C*v,e[7]=x*o+b*d+S*p+C*y,x=n[8],b=n[9],S=n[10],C=n[11],e[8]=x*r+b*a+S*f+C*g,e[9]=x*s+b*l+S*u+C*w,e[10]=x*i+b*c+S*h+C*v,e[11]=x*o+b*d+S*p+C*y,x=n[12],b=n[13],S=n[14],C=n[15],e[12]=x*r+b*a+S*f+C*g,e[13]=x*s+b*l+S*u+C*w,e[14]=x*i+b*c+S*h+C*v,e[15]=x*o+b*d+S*p+C*y,e}function aS(e,t,n){let r=n[0],s=n[1],i=n[2],o,a,l,c,d,f,u,h,p,g,w,v;return t===e?(e[12]=t[0]*r+t[4]*s+t[8]*i+t[12],e[13]=t[1]*r+t[5]*s+t[9]*i+t[13],e[14]=t[2]*r+t[6]*s+t[10]*i+t[14],e[15]=t[3]*r+t[7]*s+t[11]*i+t[15]):(o=t[0],a=t[1],l=t[2],c=t[3],d=t[4],f=t[5],u=t[6],h=t[7],p=t[8],g=t[9],w=t[10],v=t[11],e[0]=o,e[1]=a,e[2]=l,e[3]=c,e[4]=d,e[5]=f,e[6]=u,e[7]=h,e[8]=p,e[9]=g,e[10]=w,e[11]=v,e[12]=o*r+d*s+p*i+t[12],e[13]=a*r+f*s+g*i+t[13],e[14]=l*r+u*s+w*i+t[14],e[15]=c*r+h*s+v*i+t[15]),e}function lS(e,t,n){let r=n[0],s=n[1],i=n[2];return e[0]=t[0]*r,e[1]=t[1]*r,e[2]=t[2]*r,e[3]=t[3]*r,e[4]=t[4]*s,e[5]=t[5]*s,e[6]=t[6]*s,e[7]=t[7]*s,e[8]=t[8]*i,e[9]=t[9]*i,e[10]=t[10]*i,e[11]=t[11]*i,e[12]=t[12],e[13]=t[13],e[14]=t[14],e[15]=t[15],e}function uS(e,t,n,r){let s=r[0],i=r[1],o=r[2],a=Math.hypot(s,i,o),l,c,d,f,u,h,p,g,w,v,y,x,b,S,C,P,j,_,T,F,L,W,A,O;return Math.abs(a)0?(v=Math.sqrt(w+1)*2,t[3]=.25*v,t[0]=(u-p)/v,t[1]=(h-c)/v,t[2]=(l-d)/v):a>f&&a>g?(v=Math.sqrt(1+a-f-g)*2,t[3]=(u-p)/v,t[0]=.25*v,t[1]=(l+d)/v,t[2]=(h+c)/v):f>g?(v=Math.sqrt(1+f-a-g)*2,t[3]=(h-c)/v,t[0]=(l+d)/v,t[1]=.25*v,t[2]=(u+p)/v):(v=Math.sqrt(1+g-a-f)*2,t[3]=(l-d)/v,t[0]=(h+c)/v,t[1]=(u+p)/v,t[2]=.25*v),t}}();function fS(e,t,n,r){let s=ws([e[0],e[1],e[2]]);const i=ws([e[4],e[5],e[6]]),o=ws([e[8],e[9],e[10]]);zg(e)<0&&(s=-s),n[0]=e[12],n[1]=e[13],n[2]=e[14];const l=e.slice(),c=1/s,d=1/i,f=1/o;l[0]*=c,l[1]*=c,l[2]*=c,l[4]*=d,l[5]*=d,l[6]*=d,l[8]*=f,l[9]*=f,l[10]*=f,Og(t,l),r[0]=s,r[1]=i,r[2]=o}function hS(e,t,n,r){const s=e,i=t[0],o=t[1],a=t[2],l=t[3],c=i+i,d=o+o,f=a+a,u=i*c,h=i*d,p=i*f,g=o*d,w=o*f,v=a*f,y=l*c,x=l*d,b=l*f,S=r[0],C=r[1],P=r[2];return s[0]=(1-(g+v))*S,s[1]=(h+b)*S,s[2]=(p-x)*S,s[3]=0,s[4]=(h-b)*C,s[5]=(1-(u+v))*C,s[6]=(w+y)*C,s[7]=0,s[8]=(p+x)*P,s[9]=(w-y)*P,s[10]=(1-(u+g))*P,s[11]=0,s[12]=n[0],s[13]=n[1],s[14]=n[2],s[15]=1,s}function pS(e,t){let n=t[0],r=t[1],s=t[2],i=t[3],o=n+n,a=r+r,l=s+s,c=n*o,d=r*o,f=r*a,u=s*o,h=s*a,p=s*l,g=i*o,w=i*a,v=i*l;return e[0]=1-f-p,e[1]=d+v,e[2]=u-w,e[3]=0,e[4]=d-v,e[5]=1-c-p,e[6]=h+g,e[7]=0,e[8]=u+w,e[9]=h-g,e[10]=1-c-f,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e}function mS(e,t,n,r,s){let i=1/Math.tan(t/2),o=1/(r-s);return e[0]=i/n,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=i,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=(s+r)*o,e[11]=-1,e[12]=0,e[13]=0,e[14]=2*s*r*o,e[15]=0,e}function gS(e,t,n,r,s,i,o){let a=1/(t-n),l=1/(r-s),c=1/(i-o);return e[0]=-2*a,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=-2*l,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=2*c,e[11]=0,e[12]=(t+n)*a,e[13]=(s+r)*l,e[14]=(o+i)*c,e[15]=1,e}function yS(e,t,n,r){let s=t[0],i=t[1],o=t[2],a=r[0],l=r[1],c=r[2],d=s-n[0],f=i-n[1],u=o-n[2],h=d*d+f*f+u*u;h===0?u=1:(h=1/Math.sqrt(h),d*=h,f*=h,u*=h);let p=l*u-c*f,g=c*d-a*u,w=a*f-l*d;return h=p*p+g*g+w*w,h===0&&(c?a+=1e-6:l?c+=1e-6:l+=1e-6,p=l*u-c*f,g=c*d-a*u,w=a*f-l*d,h=p*p+g*g+w*w),h=1/Math.sqrt(h),p*=h,g*=h,w*=h,e[0]=p,e[1]=g,e[2]=w,e[3]=0,e[4]=f*w-u*g,e[5]=u*p-d*w,e[6]=d*g-f*p,e[7]=0,e[8]=d,e[9]=f,e[10]=u,e[11]=0,e[12]=s,e[13]=i,e[14]=o,e[15]=1,e}function xh(e,t,n){return e[0]=t[0]+n[0],e[1]=t[1]+n[1],e[2]=t[2]+n[2],e[3]=t[3]+n[3],e[4]=t[4]+n[4],e[5]=t[5]+n[5],e[6]=t[6]+n[6],e[7]=t[7]+n[7],e[8]=t[8]+n[8],e[9]=t[9]+n[9],e[10]=t[10]+n[10],e[11]=t[11]+n[11],e[12]=t[12]+n[12],e[13]=t[13]+n[13],e[14]=t[14]+n[14],e[15]=t[15]+n[15],e}function wh(e,t,n){return e[0]=t[0]-n[0],e[1]=t[1]-n[1],e[2]=t[2]-n[2],e[3]=t[3]-n[3],e[4]=t[4]-n[4],e[5]=t[5]-n[5],e[6]=t[6]-n[6],e[7]=t[7]-n[7],e[8]=t[8]-n[8],e[9]=t[9]-n[9],e[10]=t[10]-n[10],e[11]=t[11]-n[11],e[12]=t[12]-n[12],e[13]=t[13]-n[13],e[14]=t[14]-n[14],e[15]=t[15]-n[15],e}function vS(e,t,n){return e[0]=t[0]*n,e[1]=t[1]*n,e[2]=t[2]*n,e[3]=t[3]*n,e[4]=t[4]*n,e[5]=t[5]*n,e[6]=t[6]*n,e[7]=t[7]*n,e[8]=t[8]*n,e[9]=t[9]*n,e[10]=t[10]*n,e[11]=t[11]*n,e[12]=t[12]*n,e[13]=t[13]*n,e[14]=t[14]*n,e[15]=t[15]*n,e}class ko extends Array{constructor(t=1,n=0,r=0,s=0,i=0,o=1,a=0,l=0,c=0,d=0,f=1,u=0,h=0,p=0,g=0,w=1){return super(t,n,r,s,i,o,a,l,c,d,f,u,h,p,g,w),this}get x(){return this[12]}get y(){return this[13]}get z(){return this[14]}get w(){return this[15]}set x(t){this[12]=t}set y(t){this[13]=t}set z(t){this[14]=t}set w(t){this[15]=t}set(t,n,r,s,i,o,a,l,c,d,f,u,h,p,g,w){return t.length?this.copy(t):(sS(this,t,n,r,s,i,o,a,l,c,d,f,u,h,p,g,w),this)}translate(t,n=this){return aS(this,n,t),this}rotate(t,n,r=this){return uS(this,r,t,n),this}scale(t,n=this){return lS(this,n,typeof t=="number"?[t,t,t]:t),this}add(t,n){return n?xh(this,t,n):xh(this,this,t),this}sub(t,n){return n?wh(this,t,n):wh(this,this,t),this}multiply(t,n){return t.length?n?vh(this,t,n):vh(this,this,t):vS(this,this,t),this}identity(){return iS(this),this}copy(t){return rS(this,t),this}fromPerspective({fov:t,aspect:n,near:r,far:s}={}){return mS(this,t,n,r,s),this}fromOrthogonal({left:t,right:n,bottom:r,top:s,near:i,far:o}){return gS(this,t,n,r,s,i,o),this}fromQuaternion(t){return pS(this,t),this}setPosition(t){return this.x=t[0],this.y=t[1],this.z=t[2],this}inverse(t=this){return oS(this,t),this}compose(t,n,r){return hS(this,t,n,r),this}decompose(t,n,r){return fS(this,t,n,r),this}getRotation(t){return Og(t,this),this}getTranslation(t){return cS(t,this),this}getScaling(t){return Ig(t,this),this}getMaxScaleOnAxis(){return dS(this)}lookAt(t,n,r){return yS(this,t,n,r),this}determinant(){return zg(this)}fromArray(t,n=0){return this[0]=t[n],this[1]=t[n+1],this[2]=t[n+2],this[3]=t[n+3],this[4]=t[n+4],this[5]=t[n+5],this[6]=t[n+6],this[7]=t[n+7],this[8]=t[n+8],this[9]=t[n+9],this[10]=t[n+10],this[11]=t[n+11],this[12]=t[n+12],this[13]=t[n+13],this[14]=t[n+14],this[15]=t[n+15],this}toArray(t=[],n=0){return t[n]=this[0],t[n+1]=this[1],t[n+2]=this[2],t[n+3]=this[3],t[n+4]=this[4],t[n+5]=this[5],t[n+6]=this[6],t[n+7]=this[7],t[n+8]=this[8],t[n+9]=this[9],t[n+10]=this[10],t[n+11]=this[11],t[n+12]=this[12],t[n+13]=this[13],t[n+14]=this[14],t[n+15]=this[15],t}}function xS(e,t,n="YXZ"){return n==="XYZ"?(e[1]=Math.asin(Math.min(Math.max(t[8],-1),1)),Math.abs(t[8])<.99999?(e[0]=Math.atan2(-t[9],t[10]),e[2]=Math.atan2(-t[4],t[0])):(e[0]=Math.atan2(t[6],t[5]),e[2]=0)):n==="YXZ"?(e[0]=Math.asin(-Math.min(Math.max(t[9],-1),1)),Math.abs(t[9])<.99999?(e[1]=Math.atan2(t[8],t[10]),e[2]=Math.atan2(t[1],t[5])):(e[1]=Math.atan2(-t[2],t[0]),e[2]=0)):n==="ZXY"?(e[0]=Math.asin(Math.min(Math.max(t[6],-1),1)),Math.abs(t[6])<.99999?(e[1]=Math.atan2(-t[2],t[10]),e[2]=Math.atan2(-t[4],t[5])):(e[1]=0,e[2]=Math.atan2(t[1],t[0]))):n==="ZYX"?(e[1]=Math.asin(-Math.min(Math.max(t[2],-1),1)),Math.abs(t[2])<.99999?(e[0]=Math.atan2(t[6],t[10]),e[2]=Math.atan2(t[1],t[0])):(e[0]=0,e[2]=Math.atan2(-t[4],t[5]))):n==="YZX"?(e[2]=Math.asin(Math.min(Math.max(t[1],-1),1)),Math.abs(t[1])<.99999?(e[0]=Math.atan2(-t[9],t[5]),e[1]=Math.atan2(-t[2],t[0])):(e[0]=0,e[1]=Math.atan2(t[8],t[10]))):n==="XZY"&&(e[2]=Math.asin(-Math.min(Math.max(t[4],-1),1)),Math.abs(t[4])<.99999?(e[0]=Math.atan2(t[6],t[5]),e[1]=Math.atan2(t[8],t[0])):(e[0]=Math.atan2(-t[9],t[10]),e[1]=0)),e}const bh=new ko;class wS extends Array{constructor(t=0,n=t,r=t,s="YXZ"){super(t,n,r),this.order=s,this.onChange=()=>{},this._target=this;const i=["0","1","2"];return new Proxy(this,{set(o,a){const l=Reflect.set(...arguments);return l&&i.includes(a)&&o.onChange(),l}})}get x(){return this[0]}get y(){return this[1]}get z(){return this[2]}set x(t){this._target[0]=t,this.onChange()}set y(t){this._target[1]=t,this.onChange()}set z(t){this._target[2]=t,this.onChange()}set(t,n=t,r=t){return t.length?this.copy(t):(this._target[0]=t,this._target[1]=n,this._target[2]=r,this.onChange(),this)}copy(t){return this._target[0]=t[0],this._target[1]=t[1],this._target[2]=t[2],this.onChange(),this}reorder(t){return this._target.order=t,this.onChange(),this}fromRotationMatrix(t,n=this.order){return xS(this._target,t,n),this.onChange(),this}fromQuaternion(t,n=this.order,r){return bh.fromQuaternion(t),this._target.fromRotationMatrix(bh,n),r||this.onChange(),this}fromArray(t,n=0){return this._target[0]=t[n],this._target[1]=t[n+1],this._target[2]=t[n+2],this}toArray(t=[],n=0){return t[n]=this[0],t[n+1]=this[1],t[n+2]=this[2],t}}class bS{constructor(){this.parent=null,this.children=[],this.visible=!0,this.matrix=new ko,this.worldMatrix=new ko,this.matrixAutoUpdate=!0,this.worldMatrixNeedsUpdate=!1,this.position=new mt,this.quaternion=new tS,this.scale=new mt(1),this.rotation=new wS,this.up=new mt(0,1,0),this.rotation._target.onChange=()=>this.quaternion.fromEuler(this.rotation,!0),this.quaternion._target.onChange=()=>this.rotation.fromQuaternion(this.quaternion,void 0,!0)}setParent(t,n=!0){this.parent&&t!==this.parent&&this.parent.removeChild(this,!1),this.parent=t,n&&t&&t.addChild(this,!1)}addChild(t,n=!0){~this.children.indexOf(t)||this.children.push(t),n&&t.setParent(this,!1)}removeChild(t,n=!0){~this.children.indexOf(t)&&this.children.splice(this.children.indexOf(t),1),n&&t.setParent(null,!1)}updateMatrixWorld(t){this.matrixAutoUpdate&&this.updateMatrix(),(this.worldMatrixNeedsUpdate||t)&&(this.parent===null?this.worldMatrix.copy(this.matrix):this.worldMatrix.multiply(this.parent.worldMatrix,this.matrix),this.worldMatrixNeedsUpdate=!1,t=!0);for(let n=0,r=this.children.length;nr&&r({mesh:this,camera:t}));let n=this.program.cullFace&&this.worldMatrix.determinant()<0;this.program.use({flipFaces:n}),this.geometry.draw({mode:this.mode,program:this.program}),this.afterRenderCallbacks.forEach(r=>r&&r({mesh:this,camera:t}))}}function RS(e,t){return e[0]=t[0],e[1]=t[1],e}function VS(e,t,n){return e[0]=t,e[1]=n,e}function kh(e,t,n){return e[0]=t[0]+n[0],e[1]=t[1]+n[1],e}function Ch(e,t,n){return e[0]=t[0]-n[0],e[1]=t[1]-n[1],e}function FS(e,t,n){return e[0]=t[0]*n[0],e[1]=t[1]*n[1],e}function zS(e,t,n){return e[0]=t[0]/n[0],e[1]=t[1]/n[1],e}function qa(e,t,n){return e[0]=t[0]*n,e[1]=t[1]*n,e}function IS(e,t){var n=t[0]-e[0],r=t[1]-e[1];return Math.sqrt(n*n+r*r)}function OS(e,t){var n=t[0]-e[0],r=t[1]-e[1];return n*n+r*r}function Ph(e){var t=e[0],n=e[1];return Math.sqrt(t*t+n*n)}function $S(e){var t=e[0],n=e[1];return t*t+n*n}function BS(e,t){return e[0]=-t[0],e[1]=-t[1],e}function US(e,t){return e[0]=1/t[0],e[1]=1/t[1],e}function WS(e,t){var n=t[0],r=t[1],s=n*n+r*r;return s>0&&(s=1/Math.sqrt(s)),e[0]=t[0]*s,e[1]=t[1]*s,e}function HS(e,t){return e[0]*t[0]+e[1]*t[1]}function jh(e,t){return e[0]*t[1]-e[1]*t[0]}function qS(e,t,n,r){var s=t[0],i=t[1];return e[0]=s+r*(n[0]-s),e[1]=i+r*(n[1]-i),e}function GS(e,t,n,r,s){const i=Math.exp(-r*s);let o=t[0],a=t[1];return e[0]=n[0]+(o-n[0])*i,e[1]=n[1]+(a-n[1])*i,e}function YS(e,t,n){var r=t[0],s=t[1];return e[0]=n[0]*r+n[3]*s+n[6],e[1]=n[1]*r+n[4]*s+n[7],e}function KS(e,t,n){let r=t[0],s=t[1];return e[0]=n[0]*r+n[4]*s+n[12],e[1]=n[1]*r+n[5]*s+n[13],e}function XS(e,t){return e[0]===t[0]&&e[1]===t[1]}class _c extends Array{constructor(t=0,n=t){return super(t,n),this}get x(){return this[0]}get y(){return this[1]}set x(t){this[0]=t}set y(t){this[1]=t}set(t,n=t){return t.length?this.copy(t):(VS(this,t,n),this)}copy(t){return RS(this,t),this}add(t,n){return n?kh(this,t,n):kh(this,this,t),this}sub(t,n){return n?Ch(this,t,n):Ch(this,this,t),this}multiply(t){return t.length?FS(this,this,t):qa(this,this,t),this}divide(t){return t.length?zS(this,this,t):qa(this,this,1/t),this}inverse(t=this){return US(this,t),this}len(){return Ph(this)}distance(t){return t?IS(this,t):Ph(this)}squaredLen(){return this.squaredDistance()}squaredDistance(t){return t?OS(this,t):$S(this)}negate(t=this){return BS(this,t),this}cross(t,n){return n?jh(t,n):jh(this,t)}scale(t){return qa(this,this,t),this}normalize(){return WS(this,this),this}dot(t){return HS(this,t)}equals(t){return XS(this,t)}applyMatrix3(t){return YS(this,this,t),this}applyMatrix4(t){return KS(this,this,t),this}lerp(t,n){return qS(this,this,t,n),this}smoothLerp(t,n,r){return GS(this,this,t,n,r),this}clone(){return new _c(this[0],this[1])}fromArray(t,n=0){return this[0]=t[n],this[1]=t[n+1],this}toArray(t=[],n=0){return t[n]=this[0],t[n+1]=this[1],t}}class QS extends Nb{constructor(t,{attributes:n={}}={}){Object.assign(n,{position:{size:2,data:new Float32Array([-1,-1,3,-1,-1,3])},uv:{size:2,data:new Float32Array([0,0,2,0,0,2])}}),super(t,n)}}const ZS=` -attribute vec2 position; -void main(){gl_Position=vec4(position,0.0,1.0);} -`,JS=` -#ifdef GL_ES -precision lowp float; -#endif -uniform vec2 uResolution; -uniform float uTime; -uniform float uHueShift; -uniform float uNoise; -uniform float uScan; -uniform float uScanFreq; -uniform float uWarp; -#define iTime uTime -#define iResolution uResolution - -vec4 buf[8]; -float rand(vec2 c){return fract(sin(dot(c,vec2(12.9898,78.233)))*43758.5453);} - -mat3 rgb2yiq=mat3(0.299,0.587,0.114,0.596,-0.274,-0.322,0.211,-0.523,0.312); -mat3 yiq2rgb=mat3(1.0,0.956,0.621,1.0,-0.272,-0.647,1.0,-1.106,1.703); - -vec3 hueShiftRGB(vec3 col,float deg){ - vec3 yiq=rgb2yiq*col; - float rad=radians(deg); - float cosh=cos(rad),sinh=sin(rad); - vec3 yiqShift=vec3(yiq.x,yiq.y*cosh-yiq.z*sinh,yiq.y*sinh+yiq.z*cosh); - return clamp(yiq2rgb*yiqShift,0.0,1.0); -} - -vec4 sigmoid(vec4 x){return 1./(1.+exp(-x));} - -vec4 cppn_fn(vec2 coordinate,float in0,float in1,float in2){ - buf[6]=vec4(coordinate.x,coordinate.y,0.3948333106474662+in0,0.36+in1); - buf[7]=vec4(0.14+in2,sqrt(coordinate.x*coordinate.x+coordinate.y*coordinate.y),0.,0.); - buf[0]=mat4(vec4(6.5404263,-3.6126034,0.7590882,-1.13613),vec4(2.4582713,3.1660357,1.2219609,0.06276096),vec4(-5.478085,-6.159632,1.8701609,-4.7742867),vec4(6.039214,-5.542865,-0.90925294,3.251348))*buf[6]+mat4(vec4(0.8473259,-5.722911,3.975766,1.6522468),vec4(-0.24321538,0.5839259,-1.7661959,-5.350116),vec4(0.,0.,0.,0.),vec4(0.,0.,0.,0.))*buf[7]+vec4(0.21808943,1.1243913,-1.7969975,5.0294676); - buf[1]=mat4(vec4(-3.3522482,-6.0612736,0.55641043,-4.4719114),vec4(0.8631464,1.7432913,5.643898,1.6106541),vec4(2.4941394,-3.5012043,1.7184316,6.357333),vec4(3.310376,8.209261,1.1355612,-1.165539))*buf[6]+mat4(vec4(5.24046,-13.034365,0.009859298,15.870829),vec4(2.987511,3.129433,-0.89023495,-1.6822904),vec4(0.,0.,0.,0.),vec4(0.,0.,0.,0.))*buf[7]+vec4(-5.9457836,-6.573602,-0.8812491,1.5436668); - buf[0]=sigmoid(buf[0]);buf[1]=sigmoid(buf[1]); - buf[2]=mat4(vec4(-15.219568,8.095543,-2.429353,-1.9381982),vec4(-5.951362,4.3115187,2.6393783,1.274315),vec4(-7.3145227,6.7297835,5.2473326,5.9411426),vec4(5.0796127,8.979051,-1.7278991,-1.158976))*buf[6]+mat4(vec4(-11.967154,-11.608155,6.1486754,11.237008),vec4(2.124141,-6.263192,-1.7050359,-0.7021966),vec4(0.,0.,0.,0.),vec4(0.,0.,0.,0.))*buf[7]+vec4(-4.17164,-3.2281182,-4.576417,-3.6401186); - buf[3]=mat4(vec4(3.1832156,-13.738922,1.879223,3.233465),vec4(0.64300746,12.768129,1.9141049,0.50990224),vec4(-0.049295485,4.4807224,1.4733979,1.801449),vec4(5.0039253,13.000481,3.3991797,-4.5561905))*buf[6]+mat4(vec4(-0.1285731,7.720628,-3.1425676,4.742367),vec4(0.6393625,3.714393,-0.8108378,-0.39174938),vec4(0.,0.,0.,0.),vec4(0.,0.,0.,0.))*buf[7]+vec4(-1.1811101,-21.621881,0.7851888,1.2329718); - buf[2]=sigmoid(buf[2]);buf[3]=sigmoid(buf[3]); - buf[4]=mat4(vec4(5.214916,-7.183024,2.7228765,2.6592617),vec4(-5.601878,-25.3591,4.067988,0.4602802),vec4(-10.57759,24.286327,21.102104,37.546658),vec4(4.3024497,-1.9625226,2.3458803,-1.372816))*buf[0]+mat4(vec4(-17.6526,-10.507558,2.2587414,12.462782),vec4(6.265566,-502.75443,-12.642513,0.9112289),vec4(-10.983244,20.741234,-9.701768,-0.7635988),vec4(5.383626,1.4819539,-4.1911616,-4.8444734))*buf[1]+mat4(vec4(12.785233,-16.345072,-0.39901125,1.7955981),vec4(-30.48365,-1.8345358,1.4542528,-1.1118771),vec4(19.872723,-7.337935,-42.941723,-98.52709),vec4(8.337645,-2.7312303,-2.2927687,-36.142323))*buf[2]+mat4(vec4(-16.298317,3.5471997,-0.44300047,-9.444417),vec4(57.5077,-35.609753,16.163465,-4.1534753),vec4(-0.07470326,-3.8656476,-7.0901804,3.1523974),vec4(-12.559385,-7.077619,1.490437,-0.8211543))*buf[3]+vec4(-7.67914,15.927437,1.3207729,-1.6686112); - buf[5]=mat4(vec4(-1.4109162,-0.372762,-3.770383,-21.367174),vec4(-6.2103205,-9.35908,0.92529047,8.82561),vec4(11.460242,-22.348068,13.625772,-18.693201),vec4(-0.3429052,-3.9905605,-2.4626114,-0.45033523))*buf[0]+mat4(vec4(7.3481627,-4.3661838,-6.3037653,-3.868115),vec4(1.5462853,6.5488915,1.9701879,-0.58291394),vec4(6.5858274,-2.2180402,3.7127688,-1.3730392),vec4(-5.7973905,10.134961,-2.3395722,-5.965605))*buf[1]+mat4(vec4(-2.5132585,-6.6685553,-1.4029363,-0.16285264),vec4(-0.37908727,0.53738135,4.389061,-1.3024765),vec4(-0.70647055,2.0111287,-5.1659346,-3.728635),vec4(-13.562562,10.487719,-0.9173751,-2.6487076))*buf[2]+mat4(vec4(-8.645013,6.5546675,-6.3944063,-5.5933375),vec4(-0.57783127,-1.077275,36.91025,5.736769),vec4(14.283112,3.7146652,7.1452246,-4.5958776),vec4(2.7192075,3.6021907,-4.366337,-2.3653464))*buf[3]+vec4(-5.9000807,-4.329569,1.2427121,8.59503); - buf[4]=sigmoid(buf[4]);buf[5]=sigmoid(buf[5]); - buf[6]=mat4(vec4(-1.61102,0.7970257,1.4675229,0.20917463),vec4(-28.793737,-7.1390953,1.5025433,4.656581),vec4(-10.94861,39.66238,0.74318546,-10.095605),vec4(-0.7229728,-1.5483948,0.7301322,2.1687684))*buf[0]+mat4(vec4(3.2547753,21.489103,-1.0194173,-3.3100595),vec4(-3.7316632,-3.3792162,-7.223193,-0.23685838),vec4(13.1804495,0.7916005,5.338587,5.687114),vec4(-4.167605,-17.798311,-6.815736,-1.6451967))*buf[1]+mat4(vec4(0.604885,-7.800309,-7.213122,-2.741014),vec4(-3.522382,-0.12359311,-0.5258442,0.43852118),vec4(9.6752825,-22.853785,2.062431,0.099892326),vec4(-4.3196306,-17.730087,2.5184598,5.30267))*buf[2]+mat4(vec4(-6.545563,-15.790176,-6.0438633,-5.415399),vec4(-43.591583,28.551912,-16.00161,18.84728),vec4(4.212382,8.394307,3.0958717,8.657522),vec4(-5.0237565,-4.450633,-4.4768,-5.5010443))*buf[3]+mat4(vec4(1.6985557,-67.05806,6.897715,1.9004834),vec4(1.8680354,2.3915145,2.5231109,4.081538),vec4(11.158006,1.7294737,2.0738268,7.386411),vec4(-4.256034,-306.24686,8.258898,-17.132736))*buf[4]+mat4(vec4(1.6889864,-4.5852966,3.8534803,-6.3482175),vec4(1.3543309,-1.2640043,9.932754,2.9079645),vec4(-5.2770967,0.07150358,-0.13962056,3.3269649),vec4(28.34703,-4.918278,6.1044083,4.085355))*buf[5]+vec4(6.6818056,12.522166,-3.7075126,-4.104386); - buf[7]=mat4(vec4(-8.265602,-4.7027016,5.098234,0.7509808),vec4(8.6507845,-17.15949,16.51939,-8.884479),vec4(-4.036479,-2.3946867,-2.6055532,-1.9866527),vec4(-2.2167742,-1.8135649,-5.9759874,4.8846445))*buf[0]+mat4(vec4(6.7790847,3.5076547,-2.8191125,-2.7028968),vec4(-5.743024,-0.27844876,1.4958696,-5.0517144),vec4(13.122226,15.735168,-2.9397483,-4.101023),vec4(-14.375265,-5.030483,-6.2599335,2.9848232))*buf[1]+mat4(vec4(4.0950394,-0.94011575,-5.674733,4.755022),vec4(4.3809423,4.8310084,1.7425908,-3.437416),vec4(2.117492,0.16342592,-104.56341,16.949184),vec4(-5.22543,-2.994248,3.8350096,-1.9364246))*buf[2]+mat4(vec4(-5.900337,1.7946124,-13.604192,-3.8060522),vec4(6.6583457,31.911177,25.164474,91.81147),vec4(11.840538,4.1503043,-0.7314397,6.768467),vec4(-6.3967767,4.034772,6.1714606,-0.32874924))*buf[3]+mat4(vec4(3.4992442,-196.91893,-8.923708,2.8142626),vec4(3.4806502,-3.1846354,5.1725626,5.1804223),vec4(-2.4009497,15.585794,1.2863957,2.0252278),vec4(-71.25271,-62.441242,-8.138444,0.50670296))*buf[4]+mat4(vec4(-12.291733,-11.176166,-7.3474145,4.390294),vec4(10.805477,5.6337385,-0.9385842,-4.7348723),vec4(-12.869276,-7.039391,5.3029537,7.5436664),vec4(1.4593618,8.91898,3.5101583,5.840625))*buf[5]+vec4(2.2415268,-6.705987,-0.98861027,-2.117676); - buf[6]=sigmoid(buf[6]);buf[7]=sigmoid(buf[7]); - buf[0]=mat4(vec4(1.6794263,1.3817469,2.9625452,0.),vec4(-1.8834411,-1.4806935,-3.5924516,0.),vec4(-1.3279216,-1.0918057,-2.3124623,0.),vec4(0.2662234,0.23235129,0.44178495,0.))*buf[0]+mat4(vec4(-0.6299101,-0.5945583,-0.9125601,0.),vec4(0.17828953,0.18300213,0.18182953,0.),vec4(-2.96544,-2.5819945,-4.9001055,0.),vec4(1.4195864,1.1868085,2.5176322,0.))*buf[1]+mat4(vec4(-1.2584374,-1.0552157,-2.1688404,0.),vec4(-0.7200217,-0.52666044,-1.438251,0.),vec4(0.15345335,0.15196142,0.272854,0.),vec4(0.945728,0.8861938,1.2766753,0.))*buf[2]+mat4(vec4(-2.4218085,-1.968602,-4.35166,0.),vec4(-22.683098,-18.0544,-41.954372,0.),vec4(0.63792,0.5470648,1.1078634,0.),vec4(-1.5489894,-1.3075932,-2.6444845,0.))*buf[3]+mat4(vec4(-0.49252132,-0.39877754,-0.91366625,0.),vec4(0.95609266,0.7923952,1.640221,0.),vec4(0.30616966,0.15693925,0.8639857,0.),vec4(1.1825981,0.94504964,2.176963,0.))*buf[4]+mat4(vec4(0.35446745,0.3293795,0.59547555,0.),vec4(-0.58784515,-0.48177817,-1.0614829,0.),vec4(2.5271258,1.9991658,4.6846647,0.),vec4(0.13042648,0.08864098,0.30187556,0.))*buf[5]+mat4(vec4(-1.7718065,-1.4033192,-3.3355875,0.),vec4(3.1664357,2.638297,5.378702,0.),vec4(-3.1724713,-2.6107926,-5.549295,0.),vec4(-2.851368,-2.249092,-5.3013067,0.))*buf[6]+mat4(vec4(1.5203838,1.2212278,2.8404984,0.),vec4(1.5210563,1.2651345,2.683903,0.),vec4(2.9789467,2.4364579,5.2347264,0.),vec4(2.2270417,1.8825914,3.8028636,0.))*buf[7]+vec4(-1.5468478,-3.6171484,0.24762098,0.); - buf[0]=sigmoid(buf[0]); - return vec4(buf[0].x,buf[0].y,buf[0].z,1.); -} - -void mainImage(out vec4 fragColor,in vec2 fragCoord){ - vec2 uv=fragCoord/uResolution.xy*2.-1.; - uv.y*=-1.; - uv+=uWarp*vec2(sin(uv.y*6.283+uTime*0.5),cos(uv.x*6.283+uTime*0.5))*0.05; - fragColor=cppn_fn(uv,0.1*sin(0.3*uTime),0.1*sin(0.69*uTime),0.1*sin(0.44*uTime)); -} - -void main(){ - vec4 col;mainImage(col,gl_FragCoord.xy); - col.rgb=hueShiftRGB(col.rgb,uHueShift); - float scanline_val=sin(gl_FragCoord.y*uScanFreq)*0.5+0.5; - col.rgb*=1.-(scanline_val*scanline_val)*uScan; - col.rgb+=(rand(gl_FragCoord.xy+uTime)-0.5)*uNoise; - gl_FragColor=vec4(clamp(col.rgb,0.0,1.0),1.0); -} -`;class ek extends k.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("ErrorBoundary caught an error:",t,n)}render(){return this.state.hasError?this.props.fallback||m.jsx("div",{style:{position:"fixed",top:0,left:0,width:"100%",height:"100%",background:"radial-gradient(circle at center, rgba(0,0,0,0.8) 0%, rgba(0,0,0,1) 100%)",zIndex:-1,pointerEvents:"none"}}):this.props.children}}function tk({hueShift:e=60,noiseIntensity:t=.03,scanlineIntensity:n=.08,speed:r=.4,scanlineFrequency:s=.6,warpAmount:i=.15,resolutionScale:o=1}){const a=k.useRef(null);return k.useEffect(()=>{const l=a.current;if(!l){console.error("DarkVeil: Canvas not found");return}let c,d,f;try{c=new Vb({dpr:Math.min(window.devicePixelRatio,2),canvas:l});const w=c.gl;if(!w){console.error("DarkVeil: WebGL context not available");return}const v=new QS(w);d=new _b(w,{vertex:ZS,fragment:JS,uniforms:{uTime:{value:0},uResolution:{value:new _c},uHueShift:{value:e},uNoise:{value:t},uScan:{value:n},uScanFreq:{value:s},uWarp:{value:i}}}),f=new DS(w,{geometry:v,program:d}),console.log("DarkVeil: Successfully initialized")}catch(w){console.error("DarkVeil: Initialization error:",w);return}const u=()=>{const w=window.innerWidth,v=window.innerHeight;c.setSize(w*o,v*o),d.uniforms.uResolution.value.set(w,v)};window.addEventListener("resize",u),u();const h=performance.now();let p=0;const g=()=>{d.uniforms.uTime.value=(performance.now()-h)/1e3*r,d.uniforms.uHueShift.value=e,d.uniforms.uNoise.value=t,d.uniforms.uScan.value=n,d.uniforms.uScanFreq.value=s,d.uniforms.uWarp.value=i,c.render({scene:f}),p=requestAnimationFrame(g)};return g(),()=>{cancelAnimationFrame(p),window.removeEventListener("resize",u)}},[e,t,n,r,s,i,o]),m.jsxs(m.Fragment,{children:[m.jsx("div",{style:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",background:"radial-gradient(circle at center, rgba(50,20,80,0.8) 0%, rgba(20,10,40,0.9) 50%, rgba(0,0,0,1) 100%)",zIndex:-10,pointerEvents:"none"}}),m.jsx("canvas",{ref:a,style:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",zIndex:-5,pointerEvents:"none",display:"block"}})]})}function Eh(e){return m.jsx(ek,{children:m.jsx(tk,{...e})})}/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */var nk={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const rk=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().trim(),ee=(e,t)=>{const n=k.forwardRef(({color:r="currentColor",size:s=24,strokeWidth:i=2,absoluteStrokeWidth:o,className:a="",children:l,...c},d)=>k.createElement("svg",{ref:d,...nk,width:s,height:s,stroke:r,strokeWidth:o?Number(i)*24/Number(s):i,className:["lucide",`lucide-${rk(e)}`,a].join(" "),...c},[...t.map(([f,u])=>k.createElement(f,u)),...Array.isArray(l)?l:[l]]));return n.displayName=`${e}`,n};/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const sk=ee("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ik=ee("Calendar",[["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",ry:"2",key:"eu3xkr"}],["line",{x1:"16",x2:"16",y1:"2",y2:"6",key:"m3sa8f"}],["line",{x1:"8",x2:"8",y1:"2",y2:"6",key:"18kwsl"}],["line",{x1:"3",x2:"21",y1:"10",y2:"10",key:"xt86sb"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ok=ee("Camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ak=ee("CheckCircle",[["path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14",key:"g774vq"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Co=ee("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const $g=ee("ExternalLink",[["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}],["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["line",{x1:"10",x2:"21",y1:"14",y2:"3",key:"18c3s4"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const at=ee("Heart",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const lk=ee("Loader2",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Th=ee("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const uk=ee("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const It=ee("Music",[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const ck=ee("Pause",[["rect",{width:"4",height:"16",x:"6",y:"4",key:"iffhe4"}],["rect",{width:"4",height:"16",x:"14",y:"4",key:"sjin7j"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Bg=ee("PlayCircle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polygon",{points:"10 8 16 12 10 16 10 8",key:"1cimsy"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Nh=ee("Play",[["polygon",{points:"5 3 19 12 5 21 5 3",key:"191637"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Ac=ee("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Mh=ee("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Gn=ee("Sparkles",[["path",{d:"m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z",key:"17u4zn"}],["path",{d:"M5 3v4",key:"bklmnn"}],["path",{d:"M19 17v4",key:"iiml17"}],["path",{d:"M3 5h4",key:"nem4j1"}],["path",{d:"M17 19h4",key:"lbex7p"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const dk=ee("Star",[["polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2",key:"8f66p6"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Ug=ee("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const fk=ee("TrendingUp",[["polyline",{points:"22 7 13.5 15.5 8.5 10.5 2 17",key:"126l90"}],["polyline",{points:"16 7 22 7 22 13",key:"kwv8wd"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const bs=ee("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const Wg=ee("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const hk=ee("Volume2",[["polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5",key:"16drj5"}],["path",{d:"M15.54 8.46a5 5 0 0 1 0 7.07",key:"ltjumu"}],["path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14",key:"1kegas"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const pk=ee("Wand2",[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72Z",key:"1bcowg"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const mk=ee("XCircle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** - * @license lucide-react v0.294.0 - ISC - * - * This source code is licensed under the ISC license. - * See the LICENSE file in the root directory of this source tree. - */const _h=ee("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);function Hg(e){var t,n,r="";if(typeof e=="string"||typeof e=="number")r+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(t=0;t{const t=xk(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:o=>{const a=o.split(Lc);return a[0]===""&&a.length!==1&&a.shift(),qg(a,t)||vk(o)},getConflictingClassGroupIds:(o,a)=>{const l=n[o]||[];return a&&r[o]?[...l,...r[o]]:l}}},qg=(e,t)=>{var o;if(e.length===0)return t.classGroupId;const n=e[0],r=t.nextPart.get(n),s=r?qg(e.slice(1),r):void 0;if(s)return s;if(t.validators.length===0)return;const i=e.join(Lc);return(o=t.validators.find(({validator:a})=>a(i)))==null?void 0:o.classGroupId},Ah=/^\[(.+)\]$/,vk=e=>{if(Ah.test(e)){const t=Ah.exec(e)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},xk=e=>{const{theme:t,prefix:n}=e,r={nextPart:new Map,validators:[]};return bk(Object.entries(e.classGroups),n).forEach(([i,o])=>{lu(o,r,i,t)}),r},lu=(e,t,n,r)=>{e.forEach(s=>{if(typeof s=="string"){const i=s===""?t:Lh(t,s);i.classGroupId=n;return}if(typeof s=="function"){if(wk(s)){lu(s(r),t,n,r);return}t.validators.push({validator:s,classGroupId:n});return}Object.entries(s).forEach(([i,o])=>{lu(o,Lh(t,i),n,r)})})},Lh=(e,t)=>{let n=e;return t.split(Lc).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},wk=e=>e.isThemeGetter,bk=(e,t)=>t?e.map(([n,r])=>{const s=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([o,a])=>[t+o,a])):i);return[n,s]}):e,Sk=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;const s=(i,o)=>{n.set(i,o),t++,t>e&&(t=0,r=n,n=new Map)};return{get(i){let o=n.get(i);if(o!==void 0)return o;if((o=r.get(i))!==void 0)return s(i,o),o},set(i,o){n.has(i)?n.set(i,o):s(i,o)}}},Gg="!",kk=e=>{const{separator:t,experimentalParseClassName:n}=e,r=t.length===1,s=t[0],i=t.length,o=a=>{const l=[];let c=0,d=0,f;for(let w=0;wd?f-d:void 0;return{modifiers:l,hasImportantModifier:h,baseClassName:p,maybePostfixModifierPosition:g}};return n?a=>n({className:a,parseClassName:o}):o},Ck=e=>{if(e.length<=1)return e;const t=[];let n=[];return e.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t},Pk=e=>({cache:Sk(e.cacheSize),parseClassName:kk(e),...yk(e)}),jk=/\s+/,Ek=(e,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:s}=t,i=[],o=e.trim().split(jk);let a="";for(let l=o.length-1;l>=0;l-=1){const c=o[l],{modifiers:d,hasImportantModifier:f,baseClassName:u,maybePostfixModifierPosition:h}=n(c);let p=!!h,g=r(p?u.substring(0,h):u);if(!g){if(!p){a=c+(a.length>0?" "+a:a);continue}if(g=r(u),!g){a=c+(a.length>0?" "+a:a);continue}p=!1}const w=Ck(d).join(":"),v=f?w+Gg:w,y=v+g;if(i.includes(y))continue;i.push(y);const x=s(g,p);for(let b=0;b0?" "+a:a)}return a};function Tk(){let e=0,t,n,r="";for(;e{if(typeof e=="string")return e;let t,n="";for(let r=0;rf(d),e());return n=Pk(c),r=n.cache.get,s=n.cache.set,i=a,a(l)}function a(l){const c=r(l);if(c)return c;const d=Ek(l,n);return s(l,d),d}return function(){return i(Tk.apply(null,arguments))}}const te=e=>{const t=n=>n[e]||[];return t.isThemeGetter=!0,t},Kg=/^\[(?:([a-z-]+):)?(.+)\]$/i,Mk=/^\d+\/\d+$/,_k=new Set(["px","full","screen"]),Ak=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Lk=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Dk=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,Rk=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Vk=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Nt=e=>kr(e)||_k.has(e)||Mk.test(e),Yt=e=>Br(e,"length",Wk),kr=e=>!!e&&!Number.isNaN(Number(e)),Ga=e=>Br(e,"number",kr),es=e=>!!e&&Number.isInteger(Number(e)),Fk=e=>e.endsWith("%")&&kr(e.slice(0,-1)),H=e=>Kg.test(e),Kt=e=>Ak.test(e),zk=new Set(["length","size","percentage"]),Ik=e=>Br(e,zk,Xg),Ok=e=>Br(e,"position",Xg),$k=new Set(["image","url"]),Bk=e=>Br(e,$k,qk),Uk=e=>Br(e,"",Hk),ts=()=>!0,Br=(e,t,n)=>{const r=Kg.exec(e);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1},Wk=e=>Lk.test(e)&&!Dk.test(e),Xg=()=>!1,Hk=e=>Rk.test(e),qk=e=>Vk.test(e),Gk=()=>{const e=te("colors"),t=te("spacing"),n=te("blur"),r=te("brightness"),s=te("borderColor"),i=te("borderRadius"),o=te("borderSpacing"),a=te("borderWidth"),l=te("contrast"),c=te("grayscale"),d=te("hueRotate"),f=te("invert"),u=te("gap"),h=te("gradientColorStops"),p=te("gradientColorStopPositions"),g=te("inset"),w=te("margin"),v=te("opacity"),y=te("padding"),x=te("saturate"),b=te("scale"),S=te("sepia"),C=te("skew"),P=te("space"),j=te("translate"),_=()=>["auto","contain","none"],T=()=>["auto","hidden","clip","visible","scroll"],F=()=>["auto",H,t],L=()=>[H,t],W=()=>["",Nt,Yt],A=()=>["auto",kr,H],O=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],B=()=>["solid","dashed","dotted","double","none"],K=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],M=()=>["start","end","center","between","around","evenly","stretch"],D=()=>["","0",H],z=()=>["auto","avoid","all","avoid-page","page","left","right","column"],R=()=>[kr,H];return{cacheSize:500,separator:":",theme:{colors:[ts],spacing:[Nt,Yt],blur:["none","",Kt,H],brightness:R(),borderColor:[e],borderRadius:["none","","full",Kt,H],borderSpacing:L(),borderWidth:W(),contrast:R(),grayscale:D(),hueRotate:R(),invert:D(),gap:L(),gradientColorStops:[e],gradientColorStopPositions:[Fk,Yt],inset:F(),margin:F(),opacity:R(),padding:L(),saturate:R(),scale:R(),sepia:D(),skew:R(),space:L(),translate:L()},classGroups:{aspect:[{aspect:["auto","square","video",H]}],container:["container"],columns:[{columns:[Kt]}],"break-after":[{"break-after":z()}],"break-before":[{"break-before":z()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...O(),H]}],overflow:[{overflow:T()}],"overflow-x":[{"overflow-x":T()}],"overflow-y":[{"overflow-y":T()}],overscroll:[{overscroll:_()}],"overscroll-x":[{"overscroll-x":_()}],"overscroll-y":[{"overscroll-y":_()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[g]}],"inset-x":[{"inset-x":[g]}],"inset-y":[{"inset-y":[g]}],start:[{start:[g]}],end:[{end:[g]}],top:[{top:[g]}],right:[{right:[g]}],bottom:[{bottom:[g]}],left:[{left:[g]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",es,H]}],basis:[{basis:F()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",H]}],grow:[{grow:D()}],shrink:[{shrink:D()}],order:[{order:["first","last","none",es,H]}],"grid-cols":[{"grid-cols":[ts]}],"col-start-end":[{col:["auto",{span:["full",es,H]},H]}],"col-start":[{"col-start":A()}],"col-end":[{"col-end":A()}],"grid-rows":[{"grid-rows":[ts]}],"row-start-end":[{row:["auto",{span:[es,H]},H]}],"row-start":[{"row-start":A()}],"row-end":[{"row-end":A()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",H]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",H]}],gap:[{gap:[u]}],"gap-x":[{"gap-x":[u]}],"gap-y":[{"gap-y":[u]}],"justify-content":[{justify:["normal",...M()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...M(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...M(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[y]}],px:[{px:[y]}],py:[{py:[y]}],ps:[{ps:[y]}],pe:[{pe:[y]}],pt:[{pt:[y]}],pr:[{pr:[y]}],pb:[{pb:[y]}],pl:[{pl:[y]}],m:[{m:[w]}],mx:[{mx:[w]}],my:[{my:[w]}],ms:[{ms:[w]}],me:[{me:[w]}],mt:[{mt:[w]}],mr:[{mr:[w]}],mb:[{mb:[w]}],ml:[{ml:[w]}],"space-x":[{"space-x":[P]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[P]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",H,t]}],"min-w":[{"min-w":[H,t,"min","max","fit"]}],"max-w":[{"max-w":[H,t,"none","full","min","max","fit","prose",{screen:[Kt]},Kt]}],h:[{h:[H,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[H,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[H,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[H,t,"auto","min","max","fit"]}],"font-size":[{text:["base",Kt,Yt]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Ga]}],"font-family":[{font:[ts]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",H]}],"line-clamp":[{"line-clamp":["none",kr,Ga]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Nt,H]}],"list-image":[{"list-image":["none",H]}],"list-style-type":[{list:["none","disc","decimal",H]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[e]}],"placeholder-opacity":[{"placeholder-opacity":[v]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[e]}],"text-opacity":[{"text-opacity":[v]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...B(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Nt,Yt]}],"underline-offset":[{"underline-offset":["auto",Nt,H]}],"text-decoration-color":[{decoration:[e]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:L()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",H]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",H]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[v]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...O(),Ok]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",Ik]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},Bk]}],"bg-color":[{bg:[e]}],"gradient-from-pos":[{from:[p]}],"gradient-via-pos":[{via:[p]}],"gradient-to-pos":[{to:[p]}],"gradient-from":[{from:[h]}],"gradient-via":[{via:[h]}],"gradient-to":[{to:[h]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[a]}],"border-w-x":[{"border-x":[a]}],"border-w-y":[{"border-y":[a]}],"border-w-s":[{"border-s":[a]}],"border-w-e":[{"border-e":[a]}],"border-w-t":[{"border-t":[a]}],"border-w-r":[{"border-r":[a]}],"border-w-b":[{"border-b":[a]}],"border-w-l":[{"border-l":[a]}],"border-opacity":[{"border-opacity":[v]}],"border-style":[{border:[...B(),"hidden"]}],"divide-x":[{"divide-x":[a]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[a]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[v]}],"divide-style":[{divide:B()}],"border-color":[{border:[s]}],"border-color-x":[{"border-x":[s]}],"border-color-y":[{"border-y":[s]}],"border-color-s":[{"border-s":[s]}],"border-color-e":[{"border-e":[s]}],"border-color-t":[{"border-t":[s]}],"border-color-r":[{"border-r":[s]}],"border-color-b":[{"border-b":[s]}],"border-color-l":[{"border-l":[s]}],"divide-color":[{divide:[s]}],"outline-style":[{outline:["",...B()]}],"outline-offset":[{"outline-offset":[Nt,H]}],"outline-w":[{outline:[Nt,Yt]}],"outline-color":[{outline:[e]}],"ring-w":[{ring:W()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[e]}],"ring-opacity":[{"ring-opacity":[v]}],"ring-offset-w":[{"ring-offset":[Nt,Yt]}],"ring-offset-color":[{"ring-offset":[e]}],shadow:[{shadow:["","inner","none",Kt,Uk]}],"shadow-color":[{shadow:[ts]}],opacity:[{opacity:[v]}],"mix-blend":[{"mix-blend":[...K(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":K()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[l]}],"drop-shadow":[{"drop-shadow":["","none",Kt,H]}],grayscale:[{grayscale:[c]}],"hue-rotate":[{"hue-rotate":[d]}],invert:[{invert:[f]}],saturate:[{saturate:[x]}],sepia:[{sepia:[S]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[l]}],"backdrop-grayscale":[{"backdrop-grayscale":[c]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[d]}],"backdrop-invert":[{"backdrop-invert":[f]}],"backdrop-opacity":[{"backdrop-opacity":[v]}],"backdrop-saturate":[{"backdrop-saturate":[x]}],"backdrop-sepia":[{"backdrop-sepia":[S]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[o]}],"border-spacing-x":[{"border-spacing-x":[o]}],"border-spacing-y":[{"border-spacing-y":[o]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",H]}],duration:[{duration:R()}],ease:[{ease:["linear","in","out","in-out",H]}],delay:[{delay:R()}],animate:[{animate:["none","spin","ping","pulse","bounce",H]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[b]}],"scale-x":[{"scale-x":[b]}],"scale-y":[{"scale-y":[b]}],rotate:[{rotate:[es,H]}],"translate-x":[{"translate-x":[j]}],"translate-y":[{"translate-y":[j]}],"skew-x":[{"skew-x":[C]}],"skew-y":[{"skew-y":[C]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",H]}],accent:[{accent:["auto",e]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",H]}],"caret-color":[{caret:[e]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":L()}],"scroll-mx":[{"scroll-mx":L()}],"scroll-my":[{"scroll-my":L()}],"scroll-ms":[{"scroll-ms":L()}],"scroll-me":[{"scroll-me":L()}],"scroll-mt":[{"scroll-mt":L()}],"scroll-mr":[{"scroll-mr":L()}],"scroll-mb":[{"scroll-mb":L()}],"scroll-ml":[{"scroll-ml":L()}],"scroll-p":[{"scroll-p":L()}],"scroll-px":[{"scroll-px":L()}],"scroll-py":[{"scroll-py":L()}],"scroll-ps":[{"scroll-ps":L()}],"scroll-pe":[{"scroll-pe":L()}],"scroll-pt":[{"scroll-pt":L()}],"scroll-pr":[{"scroll-pr":L()}],"scroll-pb":[{"scroll-pb":L()}],"scroll-pl":[{"scroll-pl":L()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",H]}],fill:[{fill:[e,"none"]}],"stroke-w":[{stroke:[Nt,Yt,Ga]}],stroke:[{stroke:[e,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},Yk=Nk(Gk);function Dh(...e){return Yk(gk(e))}function Qg(e){const t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${t}:${n.toString().padStart(2,"0")}`}function Cr(e){const t=new Date(e),r=(new Date().getTime()-t.getTime())/(1e3*60*60);return r<1?`${Math.floor(r*60)}m ago`:r<24?`${Math.floor(r)}h ago`:`${Math.floor(r/24)}d ago`}const Kk=()=>{var L,W,A,O,B,K,M,D,z,R;const[e,t]=k.useState(!1),[n,r]=k.useState(!1),[s,i]=k.useState({x:0,y:0}),[o,a]=k.useState(!1),[l,c]=k.useState({x:0,y:0}),{currentUser:d,partnerUser:f,logout:u,theme:h,setTheme:p,setPartnerUser:g}=ve(),[w,v]=k.useState(""),[y,x]=k.useState(!1),[b,S]=k.useState(!1),C=jn(),P=[{name:"Dashboard",href:"/",icon:at},{name:"Last Listened",href:"/last-listened",icon:It},{name:"Mixed Playlist",href:"/mixed-playlist",icon:Bg},{name:"Memory Lane",href:"/memory-lane",icon:Gn}],j=()=>{u(),localStorage.removeItem("spotify-user"),localStorage.removeItem("spotify-partner")},_=async()=>{var E,Y;if(!(!((E=d==null?void 0:d.user)!=null&&E.id)||!((Y=f==null?void 0:f.user)!=null&&Y.id))&&confirm(`Are you sure you want to remove ${f.user.display_name} as your partner?`)){S(!0);try{await Ct("/partners/remove",{partnerId:f.user.id})}catch(Q){try{await Ct("/partners/clear",{userId:d.user.id})}catch(ce){console.error("Failed to remove partner:",Q,ce)}}finally{g(null),localStorage.removeItem("spotify-partner"),S(!1)}}},T=Vr(h);k.useEffect(()=>{Vr(h)},[h]),k.useEffect(()=>{if(n){const E=Math.min(600,window.innerWidth-40),Y=Math.min(window.innerHeight*.9,800),Q=(window.innerWidth-E)/2,ce=(window.innerHeight-Y)/2;i({x:Q,y:ce})}},[n]),k.useEffect(()=>{const E=Q=>{o&&i({x:Q.clientX-l.x,y:Q.clientY-l.y})},Y=()=>{a(!1)};return o&&(document.addEventListener("mousemove",E),document.addEventListener("mouseup",Y)),()=>{document.removeEventListener("mousemove",E),document.removeEventListener("mouseup",Y)}},[o,l]);const F=E=>{a(!0),c({x:E.clientX-s.x,y:E.clientY-s.y})};return m.jsxs(I.nav,{initial:{y:-100,opacity:0},animate:{y:0,opacity:1},className:"sticky top-0 z-50",style:{background:"rgba(0, 0, 0, 0.8)",backdropFilter:"blur(20px)",borderBottom:"1px solid rgba(255, 255, 255, 0.05)"},children:[m.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8",children:[m.jsxs("div",{className:"flex justify-between items-center h-16",children:[m.jsxs(zi,{to:"/",className:"flex items-center space-x-2",children:[m.jsx(I.div,{whileHover:{scale:1.1,rotate:5},className:"w-8 h-8 rounded-full flex items-center justify-center",style:{background:`linear-gradient(135deg, ${((L=T.cssVars)==null?void 0:L.primary)||"#1db954"} 0%, ${((W=T.cssVars)==null?void 0:W.secondary)||"#1ed760"} 100%)`},children:m.jsx(at,{className:"w-5 h-5 text-white"})}),m.jsx("span",{className:"text-xl font-bold gradient-text",children:"Our Musical Journey"})]}),m.jsx("div",{className:"hidden md:flex items-center space-x-1",children:P.map(E=>{var Q,ce,G,we;const Y=C.pathname===E.href;return m.jsxs(zi,{to:E.href,className:Dh("flex items-center space-x-2 px-4 py-2 rounded-xl transition-all duration-300",Y?"text-white":"text-white/60 hover:text-white hover:bg-white/5"),style:Y?{background:`linear-gradient(135deg, ${((Q=T.cssVars)==null?void 0:Q.primary)||"#1db954"}15 0%, ${((ce=T.cssVars)==null?void 0:ce.secondary)||"#1ed760"}10 100%)`,border:`1px solid ${((G=T.cssVars)==null?void 0:G.primary)||"#1db954"}30`}:{},children:[m.jsx(E.icon,{className:"w-4 h-4",style:{color:Y?(we=T.cssVars)==null?void 0:we.primary:void 0}}),m.jsx("span",{className:"font-medium",children:E.name})]},E.name)})}),m.jsxs("div",{className:"hidden md:flex items-center space-x-4",children:[!f&&m.jsxs("div",{className:"flex items-center space-x-2",children:[m.jsx("input",{value:w,onChange:E=>v(E.target.value),placeholder:"Partner Spotify ID",className:"bg-white/10 text-white text-sm px-2 py-1 rounded"}),m.jsx("button",{disabled:y||!w,onClick:async()=>{var E;if(!(!((E=d==null?void 0:d.user)!=null&&E.id)||!w)){x(!0);try{await Ct("/partners/request",{toUid:w})}finally{x(!1)}}},className:`${T.primary} ${T.hover} text-white px-3 py-1 rounded text-sm disabled:opacity-50`,children:y?"Sending...":"Send Request"})]}),f&&m.jsxs(I.div,{initial:{scale:0},animate:{scale:1},className:"flex items-center space-x-2 text-sm text-white/70",children:[m.jsx(bs,{className:"w-4 h-4"}),m.jsxs("span",{children:["+ ",(A=f.user)==null?void 0:A.display_name]})]}),m.jsxs(I.button,{whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>r(!0),className:"flex items-center space-x-2 px-3 py-2 rounded-xl text-white/60 hover:text-white transition-all duration-300",style:{color:(O=T.cssVars)==null?void 0:O.primary},onMouseEnter:E=>{E.currentTarget.style.background="rgba(255, 255, 255, 0.05)"},onMouseLeave:E=>{E.currentTarget.style.background="transparent"},children:[m.jsx(Mh,{className:"w-4 h-4"}),m.jsx("span",{className:"hidden lg:block",children:"Settings"})]}),m.jsxs(I.button,{whileHover:{scale:1.05},whileTap:{scale:.95},onClick:j,className:"flex items-center space-x-2 px-3 py-2 rounded-xl text-white/60 hover:text-white transition-all duration-300",onMouseEnter:E=>{E.currentTarget.style.background="rgba(239, 68, 68, 0.1)"},onMouseLeave:E=>{E.currentTarget.style.background="transparent"},children:[m.jsx(Th,{className:"w-4 h-4"}),m.jsx("span",{className:"hidden lg:block",children:"Logout"})]})]}),m.jsx("button",{onClick:()=>t(!e),className:"md:hidden p-2 rounded-lg text-white/70 hover:text-white hover:bg-white/10 transition-all duration-300",children:e?m.jsx(_h,{className:"w-6 h-6"}):m.jsx(uk,{className:"w-6 h-6"})})]}),e&&m.jsx(I.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},className:"md:hidden py-4 border-t border-white/10",children:m.jsxs("div",{className:"space-y-2",children:[P.map(E=>{var Q,ce,G,we;const Y=C.pathname===E.href;return m.jsxs(zi,{to:E.href,onClick:()=>t(!1),className:Dh("flex items-center space-x-3 px-4 py-3 rounded-xl transition-all duration-300",Y?"text-white":"text-white/60 hover:text-white hover:bg-white/5"),style:Y?{background:`linear-gradient(135deg, ${((Q=T.cssVars)==null?void 0:Q.primary)||"#1db954"}15 0%, ${((ce=T.cssVars)==null?void 0:ce.secondary)||"#1ed760"}10 100%)`,border:`1px solid ${((G=T.cssVars)==null?void 0:G.primary)||"#1db954"}30`}:{},children:[m.jsx(E.icon,{className:"w-5 h-5",style:{color:Y?(we=T.cssVars)==null?void 0:we.primary:void 0}}),m.jsx("span",{className:"font-medium",children:E.name})]},E.name)}),m.jsxs("div",{className:"pt-4 border-t border-white/10",children:[f&&m.jsxs("div",{className:"flex items-center space-x-3 px-4 py-2 text-sm text-white/70",children:[m.jsx(bs,{className:"w-4 h-4"}),m.jsxs("span",{children:["Connected with ",(B=f.user)==null?void 0:B.display_name]})]}),m.jsxs("button",{onClick:()=>{r(!0),t(!1)},className:"w-full flex items-center space-x-3 px-4 py-3 rounded-xl text-white/60 hover:text-white transition-all duration-300",style:{color:(K=T.cssVars)==null?void 0:K.primary},onMouseEnter:E=>{E.currentTarget.style.background="rgba(255, 255, 255, 0.05)"},onMouseLeave:E=>{E.currentTarget.style.background="transparent"},children:[m.jsx(Mh,{className:"w-5 h-5"}),m.jsx("span",{className:"font-medium",children:"Settings"})]}),m.jsxs("button",{onClick:j,className:"w-full flex items-center space-x-3 px-4 py-3 rounded-xl text-white/60 hover:text-white transition-all duration-300",onMouseEnter:E=>{E.currentTarget.style.background="rgba(239, 68, 68, 0.1)"},onMouseLeave:E=>{E.currentTarget.style.background="transparent"},children:[m.jsx(Th,{className:"w-5 h-5"}),m.jsx("span",{className:"font-medium",children:"Logout"})]})]})]})})]}),n&&m.jsxs(m.Fragment,{children:[m.jsx(I.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 bg-black/50 backdrop-blur-md z-40",onClick:()=>r(!1)}),m.jsxs(I.div,{initial:{opacity:0,scale:.8,y:30},animate:{opacity:1,scale:1,y:0},exit:{opacity:0,scale:.8,y:30},className:"fixed z-50 overflow-hidden",style:{left:s.x,top:s.y,width:Math.min(600,window.innerWidth-40),height:Math.min(window.innerHeight*.9,800),background:"linear-gradient(135deg, rgba(0,0,0,0.9) 0%, rgba(20,20,20,0.95) 50%, rgba(0,0,0,0.9) 100%)",backdropFilter:"blur(24px) saturate(180%)",WebkitBackdropFilter:"blur(24px) saturate(180%)",border:"1px solid rgba(255,255,255,0.2)",borderRadius:"16px",boxShadow:"0 25px 50px rgba(0,0,0,0.5)",cursor:o?"grabbing":"default"},children:[m.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-white/20 cursor-grab active:cursor-grabbing select-none",onMouseDown:F,style:{background:"linear-gradient(135deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.02) 100%)"},children:[m.jsxs("div",{className:"flex items-center space-x-3",children:[m.jsxs("div",{className:"flex space-x-2",children:[m.jsx("div",{className:"w-3 h-3 rounded-full bg-red-500"}),m.jsx("div",{className:"w-3 h-3 rounded-full bg-yellow-500"}),m.jsx("div",{className:"w-3 h-3 rounded-full bg-green-500"})]}),m.jsx("h2",{className:"text-lg font-semibold text-white",children:"Settings"})]}),m.jsx("button",{onClick:()=>r(!1),className:"text-white/70 hover:text-white hover:bg-white/10 p-2 rounded-lg transition-all duration-200",children:m.jsx(_h,{className:"w-5 h-5"})})]}),m.jsx("div",{className:"overflow-y-auto p-4 sm:p-6",style:{height:"calc(100% - 60px)"},children:m.jsxs("div",{className:"space-y-4 sm:space-y-6",children:[(d==null?void 0:d.user)&&m.jsxs("div",{children:[m.jsx("h3",{className:"text-lg font-semibold text-white mb-4 drop-shadow-md",children:"Your Account"}),m.jsxs("div",{className:"rounded-xl p-4 border border-white/20 transition-all duration-300 hover:border-white/30 hover:shadow-lg hover:shadow-white/5",style:{background:"linear-gradient(135deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.02) 100%)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)"},onMouseEnter:E=>{E.currentTarget.style.background="linear-gradient(135deg, rgba(255,255,255,0.08) 0%, rgba(255,255,255,0.04) 100%)"},onMouseLeave:E=>{E.currentTarget.style.background="linear-gradient(135deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.02) 100%)"},children:[m.jsx("div",{className:"text-sm text-white/70 mb-2 font-medium",children:"Spotify ID"}),m.jsx("div",{className:"text-white font-mono text-sm break-all rounded-lg p-3 mb-3",style:{background:"rgba(0,0,0,0.4)",border:"1px solid rgba(255,255,255,0.1)"},children:d.user.id}),m.jsxs("div",{className:"text-sm text-white/80",children:["Display Name: ",m.jsx("span",{className:"text-white font-medium",children:d.user.display_name})]})]})]}),m.jsxs("div",{children:[m.jsx("h3",{className:"text-lg font-semibold text-white mb-4 drop-shadow-md",children:"Partner"}),f?m.jsx("div",{className:"rounded-xl p-4 border border-white/20 transition-all duration-300 hover:border-white/30 hover:shadow-lg hover:shadow-white/5",style:{background:"linear-gradient(135deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.02) 100%)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)"},onMouseEnter:E=>{E.currentTarget.style.background="linear-gradient(135deg, rgba(255,255,255,0.08) 0%, rgba(255,255,255,0.04) 100%)"},onMouseLeave:E=>{E.currentTarget.style.background="linear-gradient(135deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.02) 100%)"},children:m.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between space-y-3 sm:space-y-0",children:[m.jsxs("div",{className:"flex items-center space-x-3 sm:space-x-4",children:[m.jsx("div",{className:"w-10 h-10 sm:w-12 sm:h-12 bg-gradient-to-br from-purple-500 to-pink-500 rounded-full flex items-center justify-center shadow-lg",children:m.jsx(bs,{className:"w-5 h-5 sm:w-6 sm:h-6 text-white"})}),m.jsxs("div",{className:"flex-1 min-w-0",children:[m.jsx("div",{className:"text-white font-semibold text-base sm:text-lg truncate",children:(M=f.user)==null?void 0:M.display_name}),m.jsx("div",{className:"text-xs text-white/70 break-all rounded px-2 py-1 mt-1 inline-block",style:{background:"rgba(0,0,0,0.3)",border:"1px solid rgba(255,255,255,0.1)"},children:(D=f.user)==null?void 0:D.id}),m.jsx("div",{className:"text-sm text-green-400 font-medium mt-2",children:"✓ Connected"})]})]}),m.jsxs("button",{onClick:_,disabled:b,className:"flex items-center space-x-2 p-2 sm:p-3 text-red-400 hover:text-red-300 rounded-xl transition-all duration-200 disabled:opacity-50 self-start sm:self-auto",style:{background:"rgba(239, 68, 68, 0.1)"},onMouseEnter:E=>{E.currentTarget.style.background="rgba(239, 68, 68, 0.2)"},onMouseLeave:E=>{E.currentTarget.style.background="rgba(239, 68, 68, 0.1)"},children:[m.jsx(Ug,{className:"w-4 h-4 sm:w-5 sm:h-5"}),m.jsx("span",{className:"text-sm sm:hidden",children:"Remove"})]})]})}):m.jsxs("div",{className:"rounded-xl p-4 border border-white/20 space-y-4 transition-all duration-300 hover:border-white/30 hover:shadow-lg hover:shadow-white/5",style:{background:"linear-gradient(135deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.02) 100%)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)"},onMouseEnter:E=>{E.currentTarget.style.background="linear-gradient(135deg, rgba(255,255,255,0.08) 0%, rgba(255,255,255,0.04) 100%)"},onMouseLeave:E=>{E.currentTarget.style.background="linear-gradient(135deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.02) 100%)"},children:[m.jsxs("div",{children:[m.jsx("label",{className:"text-sm text-white/70 mb-2 block font-medium",children:"Partner Spotify ID"}),m.jsx("input",{value:w,onChange:E=>v(E.target.value),placeholder:"Enter partner's Spotify ID...",className:"w-full text-white text-sm px-4 py-3 rounded-xl placeholder-white/50 border focus:outline-none transition-all",style:{background:"rgba(0,0,0,0.4)",border:"1px solid rgba(255,255,255,0.2)"},onFocus:E=>{E.target.style.border="1px solid rgba(255,255,255,0.4)"},onBlur:E=>{E.target.style.border="1px solid rgba(255,255,255,0.2)"}})]}),m.jsx("button",{disabled:y||!w,onClick:async()=>{var E;if(!(!((E=d==null?void 0:d.user)!=null&&E.id)||!w)){x(!0);try{await Ct("/partners/request",{toUid:w}),v("")}finally{x(!1)}}},className:"w-full text-white px-4 py-3 rounded-xl text-sm disabled:opacity-50 transition-all duration-200 font-medium",style:{background:`linear-gradient(135deg, ${((z=T.cssVars)==null?void 0:z.primary)||"#1db954"} 0%, ${((R=T.cssVars)==null?void 0:R.secondary)||"#1ed760"} 100%)`},onMouseEnter:E=>{var Y;E.currentTarget.style.transform="translateY(-1px)",E.currentTarget.style.boxShadow=`0 8px 25px ${((Y=T.cssVars)==null?void 0:Y.primary)||"#1db954"}40`},onMouseLeave:E=>{E.currentTarget.style.transform="translateY(0)",E.currentTarget.style.boxShadow="none"},children:y?"Sending...":"Send Partner Request"})]})]}),m.jsxs("div",{children:[m.jsx("h3",{className:"text-lg font-semibold text-white mb-4 drop-shadow-md",children:"Color Theme"}),m.jsx("div",{className:"rounded-xl p-4 border border-white/20 transition-all duration-300 hover:border-white/30 hover:shadow-lg hover:shadow-white/5",style:{background:"linear-gradient(135deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.02) 100%)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)"},onMouseEnter:E=>{E.currentTarget.style.background="linear-gradient(135deg, rgba(255,255,255,0.08) 0%, rgba(255,255,255,0.04) 100%)"},onMouseLeave:E=>{E.currentTarget.style.background="linear-gradient(135deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.02) 100%)"},children:m.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 sm:gap-3",children:[{name:"Green",value:"green",color:"from-green-500 to-emerald-500"},{name:"Pink",value:"pink",color:"from-pink-500 to-rose-500"},{name:"Blue",value:"blue",color:"from-blue-400 to-cyan-400"},{name:"Red",value:"red",color:"from-red-600 to-red-800"},{name:"Purple",value:"purple",color:"from-purple-500 to-violet-600"},{name:"Yellow",value:"yellow",color:"from-yellow-400 to-orange-500"},{name:"Turquoise",value:"turquoise",color:"from-cyan-400 to-blue-500"}].map(E=>{var Y,Q,ce;return m.jsxs("button",{onClick:()=>p(E.value),className:"flex items-center space-x-3 p-3 rounded-xl border transition-all duration-200",style:{border:h===E.value?`2px solid ${((Y=T.cssVars)==null?void 0:Y.primary)||"#1db954"}`:"1px solid rgba(255,255,255,0.2)",background:h===E.value?`linear-gradient(135deg, ${((Q=T.cssVars)==null?void 0:Q.primary)||"#1db954"}15 0%, ${((ce=T.cssVars)==null?void 0:ce.secondary)||"#1ed760"}10 100%)`:"rgba(255,255,255,0.02)"},onMouseEnter:G=>{var we;h!==E.value?(G.currentTarget.style.background="rgba(255,255,255,0.08)",G.currentTarget.style.border="1px solid rgba(255,255,255,0.4)",G.currentTarget.style.transform="translateY(-2px)",G.currentTarget.style.boxShadow="0 4px 12px rgba(0,0,0,0.3)"):(G.currentTarget.style.transform="translateY(-1px)",G.currentTarget.style.boxShadow=`0 6px 20px ${((we=T.cssVars)==null?void 0:we.primary)||"#1db954"}30`)},onMouseLeave:G=>{h!==E.value?(G.currentTarget.style.background="rgba(255,255,255,0.02)",G.currentTarget.style.border="1px solid rgba(255,255,255,0.2)",G.currentTarget.style.transform="translateY(0)",G.currentTarget.style.boxShadow="none"):(G.currentTarget.style.transform="translateY(0)",G.currentTarget.style.boxShadow="none")},children:[m.jsx("div",{className:`w-5 h-5 rounded-full bg-gradient-to-r ${E.color} shadow-sm`}),m.jsx("span",{className:"text-white text-sm font-medium",children:E.name})]},E.value)})})})]})]})})]})]})]})};var Zg={exports:{}};(function(e){var t=function(){var n="https://api.spotify.com/v1",r=null,s=null,i=function(u,h){return u.abort=h,u},o=function(u,h){var p;if(s!==null){var g=s.defer();u(function(w){g.resolve(w)},function(w){g.reject(w)}),p=g.promise}else window.Promise&&(p=new window.Promise(u));return p?new i(p,h):null},a=function(){var u=Array.prototype.slice.call(arguments),h=u[0],p=u.slice(1);return h=h||{},p.forEach(function(g){for(var w in g)g.hasOwnProperty(w)&&(h[w]=g[w])}),h},l=function(u,h){var p="";for(var g in h)if(h.hasOwnProperty(g)){var w=h[g];p+=encodeURIComponent(g)+"="+encodeURIComponent(w)+"&"}return p.length>0&&(p=p.substring(0,p.length-1),u=u+"?"+p),u},c=function(u,h){var p=new XMLHttpRequest,g=function(w,v){function y(C){w&&w(C),h&&h(null,C)}function x(){v&&v(p),h&&h(p,null)}var b=u.type||"GET";if(p.open(b,l(u.url,u.params)),r&&p.setRequestHeader("Authorization","Bearer "+r),p.onreadystatechange=function(){if(p.readyState===4){var C=null;try{C=p.responseText?JSON.parse(p.responseText):""}catch(P){console.error(P)}p.status>=200&&p.status<300?y(C):x()}},b==="GET")p.send(null);else{var S=null;u.postData&&(u.contentType==="image/jpeg"?(S=u.postData,p.setRequestHeader("Content-Type",u.contentType)):(S=JSON.stringify(u.postData),p.setRequestHeader("Content-Type","application/json"))),p.send(S)}};return h?(g(),null):o(g,function(){p.abort()})},d=function(u,h,p,g){var w={},v=null;typeof h=="object"?(w=h,v=p):typeof h=="function"&&(v=h);var y=u.type||"GET";return y!=="GET"&&u.postData&&!g?u.postData=a(u.postData,w):u.params=a(u.params,w),c(u,v)},f=function(){};return f.prototype={constructor:t},f.prototype.getGeneric=function(u,h){var p={url:u};return d(p,h)},f.prototype.getMe=function(u,h){var p={url:n+"/me"};return d(p,u,h)},f.prototype.getMySavedTracks=function(u,h){var p={url:n+"/me/tracks"};return d(p,u,h)},f.prototype.addToMySavedTracks=function(u,h,p){var g={url:n+"/me/tracks",type:"PUT",postData:u};return d(g,h,p)},f.prototype.removeFromMySavedTracks=function(u,h,p){var g={url:n+"/me/tracks",type:"DELETE",postData:u};return d(g,h,p)},f.prototype.containsMySavedTracks=function(u,h,p){var g={url:n+"/me/tracks/contains",params:{ids:u.join(",")}};return d(g,h,p)},f.prototype.getMySavedAlbums=function(u,h){var p={url:n+"/me/albums"};return d(p,u,h)},f.prototype.addToMySavedAlbums=function(u,h,p){var g={url:n+"/me/albums",type:"PUT",postData:u};return d(g,h,p)},f.prototype.removeFromMySavedAlbums=function(u,h,p){var g={url:n+"/me/albums",type:"DELETE",postData:u};return d(g,h,p)},f.prototype.containsMySavedAlbums=function(u,h,p){var g={url:n+"/me/albums/contains",params:{ids:u.join(",")}};return d(g,h,p)},f.prototype.getMyTopArtists=function(u,h){var p={url:n+"/me/top/artists"};return d(p,u,h)},f.prototype.getMyTopTracks=function(u,h){var p={url:n+"/me/top/tracks"};return d(p,u,h)},f.prototype.getMyRecentlyPlayedTracks=function(u,h){var p={url:n+"/me/player/recently-played"};return d(p,u,h)},f.prototype.followUsers=function(u,h){var p={url:n+"/me/following/",type:"PUT",params:{ids:u.join(","),type:"user"}};return d(p,h)},f.prototype.followArtists=function(u,h){var p={url:n+"/me/following/",type:"PUT",params:{ids:u.join(","),type:"artist"}};return d(p,h)},f.prototype.followPlaylist=function(u,h,p){var g={url:n+"/playlists/"+u+"/followers",type:"PUT",postData:{}};return d(g,h,p)},f.prototype.unfollowUsers=function(u,h){var p={url:n+"/me/following/",type:"DELETE",params:{ids:u.join(","),type:"user"}};return d(p,h)},f.prototype.unfollowArtists=function(u,h){var p={url:n+"/me/following/",type:"DELETE",params:{ids:u.join(","),type:"artist"}};return d(p,h)},f.prototype.unfollowPlaylist=function(u,h){var p={url:n+"/playlists/"+u+"/followers",type:"DELETE"};return d(p,h)},f.prototype.isFollowingUsers=function(u,h){var p={url:n+"/me/following/contains",type:"GET",params:{ids:u.join(","),type:"user"}};return d(p,h)},f.prototype.isFollowingArtists=function(u,h){var p={url:n+"/me/following/contains",type:"GET",params:{ids:u.join(","),type:"artist"}};return d(p,h)},f.prototype.areFollowingPlaylist=function(u,h,p){var g={url:n+"/playlists/"+u+"/followers/contains",type:"GET",params:{ids:h.join(",")}};return d(g,p)},f.prototype.getFollowedArtists=function(u,h){var p={url:n+"/me/following",type:"GET",params:{type:"artist"}};return d(p,u,h)},f.prototype.getUser=function(u,h,p){var g={url:n+"/users/"+encodeURIComponent(u)};return d(g,h,p)},f.prototype.getUserPlaylists=function(u,h,p){var g;return typeof u=="string"?g={url:n+"/users/"+encodeURIComponent(u)+"/playlists"}:(g={url:n+"/me/playlists"},p=h,h=u),d(g,h,p)},f.prototype.getPlaylist=function(u,h,p){var g={url:n+"/playlists/"+u};return d(g,h,p)},f.prototype.getPlaylistTracks=function(u,h,p){var g={url:n+"/playlists/"+u+"/tracks"};return d(g,h,p)},f.prototype.getPlaylistCoverImage=function(u,h){var p={url:n+"/playlists/"+u+"/images"};return d(p,h)},f.prototype.createPlaylist=function(u,h,p){var g={url:n+"/users/"+encodeURIComponent(u)+"/playlists",type:"POST",postData:h};return d(g,h,p)},f.prototype.changePlaylistDetails=function(u,h,p){var g={url:n+"/playlists/"+u,type:"PUT",postData:h};return d(g,h,p)},f.prototype.addTracksToPlaylist=function(u,h,p,g){var w={url:n+"/playlists/"+u+"/tracks",type:"POST",postData:{uris:h}};return d(w,p,g,!0)},f.prototype.replaceTracksInPlaylist=function(u,h,p){var g={url:n+"/playlists/"+u+"/tracks",type:"PUT",postData:{uris:h}};return d(g,{},p)},f.prototype.reorderTracksInPlaylist=function(u,h,p,g,w){var v={url:n+"/playlists/"+u+"/tracks",type:"PUT",postData:{range_start:h,insert_before:p}};return d(v,g,w)},f.prototype.removeTracksFromPlaylist=function(u,h,p){var g=h.map(function(v){return typeof v=="string"?{uri:v}:v}),w={url:n+"/playlists/"+u+"/tracks",type:"DELETE",postData:{tracks:g}};return d(w,{},p)},f.prototype.removeTracksFromPlaylistWithSnapshotId=function(u,h,p,g){var w=h.map(function(y){return typeof y=="string"?{uri:y}:y}),v={url:n+"/playlists/"+u+"/tracks",type:"DELETE",postData:{tracks:w,snapshot_id:p}};return d(v,{},g)},f.prototype.removeTracksFromPlaylistInPositions=function(u,h,p,g){var w={url:n+"/playlists/"+u+"/tracks",type:"DELETE",postData:{positions:h,snapshot_id:p}};return d(w,{},g)},f.prototype.uploadCustomPlaylistCoverImage=function(u,h,p){var g={url:n+"/playlists/"+u+"/images",type:"PUT",postData:h.replace(/^data:image\/jpeg;base64,/,""),contentType:"image/jpeg"};return d(g,{},p)},f.prototype.getAlbum=function(u,h,p){var g={url:n+"/albums/"+u};return d(g,h,p)},f.prototype.getAlbumTracks=function(u,h,p){var g={url:n+"/albums/"+u+"/tracks"};return d(g,h,p)},f.prototype.getAlbums=function(u,h,p){var g={url:n+"/albums/",params:{ids:u.join(",")}};return d(g,h,p)},f.prototype.getTrack=function(u,h,p){var g={};return g.url=n+"/tracks/"+u,d(g,h,p)},f.prototype.getTracks=function(u,h,p){var g={url:n+"/tracks/",params:{ids:u.join(",")}};return d(g,h,p)},f.prototype.getArtist=function(u,h,p){var g={url:n+"/artists/"+u};return d(g,h,p)},f.prototype.getArtists=function(u,h,p){var g={url:n+"/artists/",params:{ids:u.join(",")}};return d(g,h,p)},f.prototype.getArtistAlbums=function(u,h,p){var g={url:n+"/artists/"+u+"/albums"};return d(g,h,p)},f.prototype.getArtistTopTracks=function(u,h,p,g){var w={url:n+"/artists/"+u+"/top-tracks",params:{country:h}};return d(w,p,g)},f.prototype.getArtistRelatedArtists=function(u,h,p){var g={url:n+"/artists/"+u+"/related-artists"};return d(g,h,p)},f.prototype.getFeaturedPlaylists=function(u,h){var p={url:n+"/browse/featured-playlists"};return d(p,u,h)},f.prototype.getNewReleases=function(u,h){var p={url:n+"/browse/new-releases"};return d(p,u,h)},f.prototype.getCategories=function(u,h){var p={url:n+"/browse/categories"};return d(p,u,h)},f.prototype.getCategory=function(u,h,p){var g={url:n+"/browse/categories/"+u};return d(g,h,p)},f.prototype.getCategoryPlaylists=function(u,h,p){var g={url:n+"/browse/categories/"+u+"/playlists"};return d(g,h,p)},f.prototype.search=function(u,h,p,g){var w={url:n+"/search/",params:{q:u,type:h.join(",")}};return d(w,p,g)},f.prototype.searchAlbums=function(u,h,p){return this.search(u,["album"],h,p)},f.prototype.searchArtists=function(u,h,p){return this.search(u,["artist"],h,p)},f.prototype.searchTracks=function(u,h,p){return this.search(u,["track"],h,p)},f.prototype.searchPlaylists=function(u,h,p){return this.search(u,["playlist"],h,p)},f.prototype.searchShows=function(u,h,p){return this.search(u,["show"],h,p)},f.prototype.searchEpisodes=function(u,h,p){return this.search(u,["episode"],h,p)},f.prototype.getAudioFeaturesForTrack=function(u,h){var p={};return p.url=n+"/audio-features/"+u,d(p,{},h)},f.prototype.getAudioFeaturesForTracks=function(u,h){var p={url:n+"/audio-features",params:{ids:u}};return d(p,{},h)},f.prototype.getAudioAnalysisForTrack=function(u,h){var p={};return p.url=n+"/audio-analysis/"+u,d(p,{},h)},f.prototype.getRecommendations=function(u,h){var p={url:n+"/recommendations"};return d(p,u,h)},f.prototype.getAvailableGenreSeeds=function(u){var h={url:n+"/recommendations/available-genre-seeds"};return d(h,{},u)},f.prototype.getMyDevices=function(u){var h={url:n+"/me/player/devices"};return d(h,{},u)},f.prototype.getMyCurrentPlaybackState=function(u,h){var p={url:n+"/me/player"};return d(p,u,h)},f.prototype.getMyCurrentPlayingTrack=function(u,h){var p={url:n+"/me/player/currently-playing"};return d(p,u,h)},f.prototype.transferMyPlayback=function(u,h,p){var g=h||{};g.device_ids=u;var w={type:"PUT",url:n+"/me/player",postData:g};return d(w,h,p)},f.prototype.play=function(u,h){u=u||{};var p="device_id"in u?{device_id:u.device_id}:null,g={};["context_uri","uris","offset","position_ms"].forEach(function(y){y in u&&(g[y]=u[y])});var w={type:"PUT",url:n+"/me/player/play",params:p,postData:g},v=typeof u=="function"?u:{};return d(w,v,h)},f.prototype.queue=function(u,h,p){h=h||{};var g="device_id"in h?{uri:u,device_id:h.device_id}:{uri:u},w={type:"POST",url:n+"/me/player/queue",params:g};return d(w,h,p)},f.prototype.pause=function(u,h){u=u||{};var p="device_id"in u?{device_id:u.device_id}:null,g={type:"PUT",url:n+"/me/player/pause",params:p};return d(g,u,h)},f.prototype.skipToNext=function(u,h){u=u||{};var p="device_id"in u?{device_id:u.device_id}:null,g={type:"POST",url:n+"/me/player/next",params:p};return d(g,u,h)},f.prototype.skipToPrevious=function(u,h){u=u||{};var p="device_id"in u?{device_id:u.device_id}:null,g={type:"POST",url:n+"/me/player/previous",params:p};return d(g,u,h)},f.prototype.seek=function(u,h,p){h=h||{};var g={position_ms:u};"device_id"in h&&(g.device_id=h.device_id);var w={type:"PUT",url:n+"/me/player/seek",params:g};return d(w,h,p)},f.prototype.setRepeat=function(u,h,p){h=h||{};var g={state:u};"device_id"in h&&(g.device_id=h.device_id);var w={type:"PUT",url:n+"/me/player/repeat",params:g};return d(w,h,p)},f.prototype.setVolume=function(u,h,p){h=h||{};var g={volume_percent:u};"device_id"in h&&(g.device_id=h.device_id);var w={type:"PUT",url:n+"/me/player/volume",params:g};return d(w,h,p)},f.prototype.setShuffle=function(u,h,p){h=h||{};var g={state:u};"device_id"in h&&(g.device_id=h.device_id);var w={type:"PUT",url:n+"/me/player/shuffle",params:g};return d(w,h,p)},f.prototype.getShow=function(u,h,p){var g={};return g.url=n+"/shows/"+u,d(g,h,p)},f.prototype.getShows=function(u,h,p){var g={url:n+"/shows/",params:{ids:u.join(",")}};return d(g,h,p)},f.prototype.getMySavedShows=function(u,h){var p={url:n+"/me/shows"};return d(p,u,h)},f.prototype.addToMySavedShows=function(u,h,p){var g={url:n+"/me/shows",type:"PUT",postData:u};return d(g,h,p)},f.prototype.removeFromMySavedShows=function(u,h,p){var g={url:n+"/me/shows",type:"DELETE",postData:u};return d(g,h,p)},f.prototype.containsMySavedShows=function(u,h,p){var g={url:n+"/me/shows/contains",params:{ids:u.join(",")}};return d(g,h,p)},f.prototype.getShowEpisodes=function(u,h,p){var g={url:n+"/shows/"+u+"/episodes"};return d(g,h,p)},f.prototype.getEpisode=function(u,h,p){var g={};return g.url=n+"/episodes/"+u,d(g,h,p)},f.prototype.getEpisodes=function(u,h,p){var g={url:n+"/episodes/",params:{ids:u.join(",")}};return d(g,h,p)},f.prototype.getAccessToken=function(){return r},f.prototype.setAccessToken=function(u){r=u},f.prototype.setPromiseImplementation=function(u){var h=!1;try{var p=new u(function(g){g()});typeof p.then=="function"&&typeof p.catch=="function"&&(h=!0)}catch(g){console.error(g)}if(h)s=u;else throw new Error("Unsupported implementation of Promises/A+")},f}();e.exports=t})(Zg);var Xk=Zg.exports;const Qk=uu(Xk),Zk="7cab80d02df44a5bb96725be60a45875",Jg="https://159.195.9.107:3443/callback.html";console.log("🔍 Debug - Current redirect URI:",Jg);console.log("🔍 Debug - Environment VITE_REDIRECT_URI:","https://159.195.9.107:3443/callback.html");const Po=new Qk,Jk=()=>{const e=["user-read-private","user-read-email","user-read-recently-played","user-top-read","playlist-read-private","playlist-read-collaborative","playlist-modify-public","playlist-modify-private","user-read-playback-state","user-modify-playback-state","user-read-currently-playing"].join(" "),n=`https://accounts.spotify.com/authorize?${new URLSearchParams({client_id:Zk,response_type:"code",redirect_uri:Jg,scope:e,show_dialog:"true"}).toString()}`;return console.log("🔍 Debug - Generated Spotify Auth URL:",n),n},e6=async(e,t)=>{Po.setAccessToken(e),await Po.play({uris:[t]})},t6=async e=>{Po.setAccessToken(e),await Po.pause()},n6=()=>{const[e,t]=k.useState(!1),n=()=>{t(!0),window.location.href=Jk()},r=[{icon:It,title:"Last Listened",description:"Discover what your partner is listening to right now and play it instantly"},{icon:Gn,title:"Mixed Playlist",description:"AI-powered playlists that blend your musical tastes perfectly"},{icon:at,title:"Memory Lane",description:"Create beautiful musical memories and shared experiences together"}];return m.jsx("div",{className:"min-h-screen flex items-center justify-center px-4 bg-black",children:m.jsxs("div",{className:"max-w-4xl w-full relative",children:[m.jsxs(I.div,{initial:{opacity:0,y:50},animate:{opacity:1,y:0},transition:{duration:.8},className:"text-center mb-12",children:[m.jsx(I.div,{initial:{scale:0},animate:{scale:1},transition:{delay:.2,type:"spring",stiffness:200},className:"w-20 h-20 mx-auto mb-6 bg-gradient-to-br from-pink-500 to-red-500 rounded-full flex items-center justify-center",children:m.jsx(at,{className:"w-10 h-10 text-white"})}),m.jsxs("h1",{className:"text-5xl md:text-6xl font-bold mb-4",children:[m.jsx("span",{className:"gradient-text",children:"Our Musical"}),m.jsx("br",{}),m.jsx("span",{className:"text-white",children:"Journey"})]}),m.jsx("p",{className:"text-xl text-white/70 max-w-2xl mx-auto leading-relaxed",children:"A private space where two hearts connect through music. Discover, share, and create beautiful musical memories together."})]}),m.jsx(I.div,{initial:{opacity:0,y:30},animate:{opacity:1,y:0},transition:{delay:.4,duration:.8},className:"grid md:grid-cols-3 gap-6 mb-12",children:r.map((s,i)=>m.jsxs(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.5+i*.1},whileHover:{y:-8,scale:1.03},className:"glass-bubble rounded-3xl p-8 text-center group cursor-pointer",children:[m.jsx(I.div,{whileHover:{rotate:15,scale:1.15},className:"w-16 h-16 mx-auto mb-6 bg-gradient-to-br from-purple-500/30 via-blue-500/30 to-pink-500/30 rounded-2xl flex items-center justify-center backdrop-blur-sm",children:m.jsx(s.icon,{className:"w-8 h-8 text-white"})}),m.jsx("h3",{className:"text-2xl font-bold text-white mb-3",children:s.title}),m.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:s.description})]},s.title))}),m.jsxs(I.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},transition:{delay:.8,duration:.6},className:"glass-fluid rounded-3xl p-10 max-w-lg mx-auto",children:[m.jsxs("div",{className:"text-center mb-8",children:[m.jsx(I.div,{initial:{scale:0},animate:{scale:1},transition:{delay:1,type:"spring",stiffness:200},className:"w-20 h-20 mx-auto mb-6 bg-gradient-to-br from-purple-500/30 via-blue-500/30 to-pink-500/30 rounded-2xl flex items-center justify-center backdrop-blur-sm",children:m.jsx(Wg,{className:"w-10 h-10 text-white"})}),m.jsx("h2",{className:"text-3xl font-bold text-white mb-3",children:"Begin Your Journey"}),m.jsx("p",{className:"text-white/70 text-lg",children:"Connect your Spotify account to start your musical love story"})]}),m.jsx(I.button,{whileHover:{scale:1.05,boxShadow:"0 15px 40px rgba(147, 51, 234, 0.4)"},whileTap:{scale:.95},onClick:n,disabled:e,className:"w-full bg-gradient-to-r from-purple-600 via-blue-600 to-pink-600 hover:from-purple-700 hover:via-blue-700 hover:to-pink-700 text-white font-bold py-5 px-8 rounded-2xl transition-all duration-300 flex items-center justify-center space-x-3 disabled:opacity-50 shadow-2xl",children:e?m.jsx("div",{className:"w-6 h-6 border-2 border-white border-t-transparent rounded-full animate-spin"}):m.jsxs(m.Fragment,{children:[m.jsx("span",{className:"text-lg",children:"Connect with Spotify"}),m.jsx(sk,{className:"w-6 h-6"})]})}),m.jsx("p",{className:"text-sm text-white/60 text-center mt-6 leading-relaxed",children:"We'll only access your listening history and playlist data to create your personalized musical journey"})]}),m.jsx(I.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1,duration:.6},className:"text-center mt-12",children:m.jsx("p",{className:"text-white/40 text-sm",children:"Made with 💕 for a special someone"})})]})})},r6=()=>{var P,j,_,T,F,L,W,A,O,B,K,M,D,z,R,E,Y,Q,ce,G,we,ni,Zn,Nn,xt,ea,Dc;const{currentUser:e,partnerUser:t,theme:n}=ve(),r=Vr(n),[s,i]=k.useState([]),[o,a]=k.useState(!1),[l,c]=k.useState(null),[d,f]=k.useState(""),[u,h]=k.useState(!1),[p,g]=k.useState(null),[w,v]=k.useState(null);k.useEffect(()=>{let $;const fe=async()=>{var Ce,Te,tt;try{const Jn=(Ce=e==null?void 0:e.user)==null?void 0:Ce.id;if(Jn){const ta=await ye(`/users/${Jn}/recently-played`),Ur=ve.getState().currentUser;Ur&&ve.getState().setCurrentUser({...Ur,recentlyPlayed:ta})}const Rc=(tt=(Te=ve.getState().partnerUser)==null?void 0:Te.user)==null?void 0:tt.id;if(Rc){const ta=await ye(`/users/${Rc}/recently-played`),Ur=ve.getState().partnerUser;Ur&&ve.getState().setPartnerUser({...Ur,recentlyPlayed:ta})}}catch{}$=setTimeout(fe,3e4)};return fe(),()=>clearTimeout($)},[(P=e==null?void 0:e.user)==null?void 0:P.id,(j=t==null?void 0:t.user)==null?void 0:j.id]),k.useEffect(()=>{(async()=>{var fe;if((fe=e==null?void 0:e.user)!=null&&fe.id){a(!0);try{const Ce=await ye(`/partners/requests/${e.user.id}`);i(Ce)}catch{i([])}finally{a(!1)}}})()},[(_=e==null?void 0:e.user)==null?void 0:_.id]),k.useEffect(()=>{let $;const fe=async()=>{var Te;if((Te=e==null?void 0:e.user)!=null&&Te.id)try{const tt=await ye(`/users/${e.user.id}/status`);c(tt)}catch{}},Ce=()=>{if(!(l!=null&&l.nextSyncAt)){f("");return}const Te=l.nextSyncAt-Date.now();if(Te<=0){f("now");return}const tt=Math.floor(Te/6e4),Jn=Math.floor(Te%6e4/1e3);f(`${tt}m ${Jn}s`)};return fe(),$=setInterval(()=>{Ce()},1e3),()=>clearInterval($)},[(T=e==null?void 0:e.user)==null?void 0:T.id,l==null?void 0:l.nextSyncAt]),k.useEffect(()=>{let $;const fe=async()=>{var Ce,Te;try{const tt=(Ce=e==null?void 0:e.user)==null?void 0:Ce.id;tt&&(g(await ye(`/users/${tt}/now-playing`)),(Te=t==null?void 0:t.user)!=null&&Te.id?v(await ye(`/users/${t.user.id}/now-playing`)):v(null))}catch{}$=setTimeout(fe,8e3)};return fe(),()=>clearTimeout($)},[(F=e==null?void 0:e.user)==null?void 0:F.id,(L=t==null?void 0:t.user)==null?void 0:L.id]);const y=async()=>{var $;if(($=e==null?void 0:e.user)!=null&&$.id){h(!0);try{await Ct(`/users/${e.user.id}/sync`);const fe=await ye(`/users/${e.user.id}/status`);c(fe);const[Ce,Te]=await Promise.all([ye(`/users/${e.user.id}/recently-played`),ye(`/users/${e.user.id}/top-tracks?time_range=short_term`)]),tt=ve.getState().currentUser;tt&&ve.getState().setCurrentUser({...tt,recentlyPlayed:Ce,topTracks:Te.map(Jn=>Jn.track)}),Pe.success("Synced latest data")}catch{Pe.error("Failed to sync")}finally{h(!1)}}},x=async $=>{await Ct(`/partners/requests/${$}/accept`),i(fe=>fe.filter(Ce=>Ce.id!==$))},b=async $=>{await Ct(`/partners/requests/${$}/decline`),i(fe=>fe.filter(Ce=>Ce.id!==$))},S=[{title:"Last Listened",description:"See what your partner is listening to right now",icon:It,href:"/last-listened",primaryColor:((W=r.cssVars)==null?void 0:W.primary)||"#1db954",secondaryColor:((A=r.cssVars)==null?void 0:A.secondary)||"#1ed760",accentColor:((O=r.cssVars)==null?void 0:O.accent)||"#00e676"},{title:"Mixed Playlist",description:"Create AI-powered playlists blending both your tastes",icon:Bg,href:"/mixed-playlist",primaryColor:((B=r.cssVars)==null?void 0:B.secondary)||"#1ed760",secondaryColor:((K=r.cssVars)==null?void 0:K.accent)||"#00e676",accentColor:((M=r.cssVars)==null?void 0:M.primary)||"#1db954"},{title:"Memory Lane",description:"Your shared musical journey and memories",icon:Gn,href:"/memory-lane",primaryColor:((D=r.cssVars)==null?void 0:D.accent)||"#00e676",secondaryColor:((z=r.cssVars)==null?void 0:z.primary)||"#1db954",accentColor:((R=r.cssVars)==null?void 0:R.secondary)||"#1ed760"}],C=()=>{var $;return($=e==null?void 0:e.recentlyPlayed)!=null&&$[0]?Cr(e.recentlyPlayed[0].played_at):null};return m.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8",children:[m.jsxs(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"mb-8",children:[m.jsxs("h1",{className:"text-4xl font-bold text-white mb-2",children:["Welcome back, ",m.jsx("span",{className:"gradient-text",children:(E=e==null?void 0:e.user)==null?void 0:E.display_name})]}),m.jsx("p",{className:"text-white/70 text-lg",children:"Ready to explore your musical connection together?"})]}),m.jsxs(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"grid md:grid-cols-2 gap-6 mb-8",children:[m.jsxs("div",{className:"glass rounded-2xl p-6",children:[m.jsx("div",{className:"text-white/70 mb-2",children:"You"}),p!=null&&p.is_playing&&(p!=null&&p.item)?m.jsxs("div",{className:"flex items-center gap-4",children:[m.jsx("img",{src:((ce=(Q=(Y=p.item.album)==null?void 0:Y.images)==null?void 0:Q[0])==null?void 0:ce.url)||"/placeholder-album.png",className:"w-14 h-14 rounded"}),m.jsxs("div",{className:"min-w-0",children:[m.jsx("div",{className:"text-white font-semibold truncate",children:p.item.name}),m.jsx("div",{className:"text-white/70 text-sm truncate",children:(G=p.item.artists)==null?void 0:G.map($=>$.name).join(", ")})]})]}):m.jsx("div",{className:"text-white/50",children:"Not playing"})]}),m.jsxs("div",{className:"glass rounded-2xl p-6",children:[m.jsx("div",{className:"text-white/70 mb-2",children:"Partner"}),w!=null&&w.is_playing&&(w!=null&&w.item)?m.jsxs("div",{className:"flex items-center gap-4",children:[m.jsx("img",{src:((Zn=(ni=(we=w.item.album)==null?void 0:we.images)==null?void 0:ni[0])==null?void 0:Zn.url)||"/placeholder-album.png",className:"w-14 h-14 rounded"}),m.jsxs("div",{className:"min-w-0",children:[m.jsx("div",{className:"text-white font-semibold truncate",children:w.item.name}),m.jsx("div",{className:"text-white/70 text-sm truncate",children:(Nn=w.item.artists)==null?void 0:Nn.map($=>$.name).join(", ")})]})]}):m.jsx("div",{className:"text-white/50",children:"Not playing"})]})]}),m.jsxs(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.1},className:"mb-8",children:[m.jsxs("div",{className:"flex items-center justify-between mb-4",children:[m.jsx("div",{className:"text-white/70 text-sm",children:(l==null?void 0:l.lastSyncedAt)&&m.jsxs("span",{children:["Last sync: ",new Date(l.lastSyncedAt).toLocaleTimeString()," • Next in: ",d||"—"]})}),m.jsx("button",{onClick:y,disabled:u,className:"bg-white/10 hover:bg-white/20 text-white px-4 py-2 rounded-lg text-sm disabled:opacity-50",children:u?"Refreshing…":"Hard Refresh"})]}),t?m.jsx("div",{className:"glass-bubble rounded-3xl p-8 border border-spotify-green/30 glow",children:m.jsxs("div",{className:"flex items-center space-x-6",children:[m.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-spotify-green to-green-600 rounded-2xl flex items-center justify-center",children:m.jsx(at,{className:"w-8 h-8 text-white"})}),m.jsxs("div",{children:[m.jsxs("h3",{className:"text-xl font-semibold text-white",children:["Connected with ",(xt=t.user)==null?void 0:xt.display_name]}),m.jsx("p",{className:"text-white/70",children:"Your musical journey is ready to begin! 💕"})]})]})}):m.jsx("div",{className:"glass-bubble rounded-3xl p-8 border border-orange-500/30",children:m.jsxs("div",{className:"flex items-center space-x-6",children:[m.jsx("div",{className:"w-16 h-16 bg-gradient-to-br from-orange-500 to-red-500 rounded-2xl flex items-center justify-center",children:m.jsx(Ac,{className:"w-8 h-8 text-white"})}),m.jsxs("div",{children:[m.jsx("h3",{className:"text-xl font-semibold text-white",children:"Invite your partner"}),m.jsx("p",{className:"text-white/70 mb-2",children:"Ask your partner to search you in the app and send a request."}),o?m.jsx("div",{className:"text-white/60",children:"Loading requests..."}):s.length>0?m.jsx("div",{className:"space-y-3",children:s.map($=>m.jsxs("div",{className:"flex items-center justify-between bg-white/5 rounded-lg p-3",children:[m.jsxs("div",{className:"text-white/80 text-sm",children:["Request from ",$.from_user_id]}),m.jsxs("div",{className:"space-x-2",children:[m.jsx("button",{onClick:()=>x($.id),className:"bg-spotify-green hover:bg-spotify-green/90 text-white px-3 py-1 rounded-md text-sm",children:"Accept"}),m.jsx("button",{onClick:()=>b($.id),className:"bg-white/10 hover:bg-white/20 text-white px-3 py-1 rounded-md text-sm",children:"Decline"})]})]},$.id))}):m.jsx("div",{className:"text-white/60 text-sm",children:"No incoming requests yet"})]})]})})]}),m.jsxs(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.2},className:"grid grid-cols-1 md:grid-cols-3 gap-6 mb-8",children:[m.jsx("div",{className:"glass-bubble rounded-2xl p-6",children:m.jsxs("div",{className:"flex items-center space-x-4",children:[m.jsx("div",{className:"w-12 h-12 bg-gradient-to-br from-blue-500/30 to-cyan-500/30 rounded-xl flex items-center justify-center",children:m.jsx(Co,{className:"w-6 h-6 text-blue-400"})}),m.jsxs("div",{children:[m.jsx("p",{className:"text-white/70 text-sm",children:"Your last played"}),m.jsx("p",{className:"text-white font-semibold",children:C()||"No recent plays"})]})]})}),m.jsx("div",{className:"glass-bubble rounded-2xl p-6",children:m.jsxs("div",{className:"flex items-center space-x-4",children:[m.jsx("div",{className:"w-12 h-12 bg-gradient-to-br from-green-500/30 to-emerald-500/30 rounded-xl flex items-center justify-center",children:m.jsx(fk,{className:"w-6 h-6 text-green-400"})}),m.jsxs("div",{children:[m.jsx("p",{className:"text-white/70 text-sm",children:"Top tracks analyzed"}),m.jsxs("p",{className:"text-white font-semibold",children:[((ea=e==null?void 0:e.topTracks)==null?void 0:ea.length)||0," songs"]})]})]})}),m.jsx("div",{className:"glass-bubble rounded-2xl p-6",children:m.jsxs("div",{className:"flex items-center space-x-4",children:[m.jsx("div",{className:"w-12 h-12 bg-gradient-to-br from-purple-500/30 to-pink-500/30 rounded-xl flex items-center justify-center",children:m.jsx(bs,{className:"w-6 h-6 text-purple-400"})}),m.jsxs("div",{children:[m.jsx("p",{className:"text-white/70 text-sm",children:"Recently played"}),m.jsxs("p",{className:"text-white font-semibold",children:[((Dc=e==null?void 0:e.recentlyPlayed)==null?void 0:Dc.length)||0," tracks"]})]})]})})]}),m.jsx(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},className:"grid md:grid-cols-3 gap-6",children:S.map(($,fe)=>m.jsx(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.4+fe*.1},whileHover:{y:-5,scale:1.02},children:m.jsx(zi,{to:$.href,children:m.jsxs("div",{className:`glass rounded-2xl p-6 h-full border ${$.borderColor} group cursor-pointer transition-all duration-300 hover:shadow-xl`,children:[m.jsx("div",{className:"w-12 h-12 rounded-xl flex items-center justify-center mb-4 group-hover:scale-110 transition-transform duration-300",style:{background:`linear-gradient(135deg, ${$.primaryColor}20 0%, ${$.secondaryColor}10 100%)`,border:`1px solid ${$.primaryColor}30`},children:m.jsx($.icon,{className:"w-6 h-6",style:{color:$.primaryColor}})}),m.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:$.title}),m.jsx("p",{className:"text-white/70 text-sm leading-relaxed mb-4",children:$.description}),m.jsx("div",{className:"w-full h-1 rounded-full opacity-0 group-hover:opacity-100 transition-opacity duration-300",style:{background:`linear-gradient(90deg, ${$.primaryColor} 0%, ${$.secondaryColor} 100%)`}})]})})},$.title))}),(e==null?void 0:e.recentlyPlayed)&&e.recentlyPlayed.length>0&&m.jsxs(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.6},className:"mt-8",children:[m.jsx("h2",{className:"text-2xl font-bold text-white mb-4",children:"Your Recent Activity"}),m.jsx("div",{className:"glass rounded-2xl p-6",children:m.jsx("div",{className:"space-y-4",children:e.recentlyPlayed.slice(0,3).map(($,fe)=>{var Ce,Te;return m.jsxs(I.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:.7+fe*.1},className:"flex items-center space-x-4 p-3 rounded-lg hover:bg-white/5 transition-colors",children:[m.jsx("img",{src:((Ce=$.track.album.images[0])==null?void 0:Ce.url)||"/placeholder-album.png",alt:$.track.album.name,className:"w-12 h-12 rounded-lg object-cover"}),m.jsxs("div",{className:"flex-1",children:[m.jsx("h4",{className:"text-white font-medium",children:$.track.name}),m.jsx("p",{className:"text-white/70 text-sm",children:(Te=$.track.artists[0])==null?void 0:Te.name})]}),m.jsx("div",{className:"text-white/50 text-sm",children:Cr($.played_at)})]},$.track.id)})})})]})]})};let Pi=!1;const Rh=()=>{const[e]=_x(),t=Uo(),{setCurrentUser:n,setPartnerUser:r,currentUser:s}=ve(),[i,o]=k.useState("loading"),[a,l]=k.useState("");k.useEffect(()=>{(async()=>{if(Pi){console.log("🔍 CallbackPage - Already processing globally, skipping...");return}Pi=!0,console.log("🔍 CallbackPage - Global processing flag set to TRUE");try{const u=e.get("code"),h=e.get("error");if(console.log("🔍 CallbackPage - Code:",u),console.log("🔍 CallbackPage - Error:",h),h)throw new Error("Spotify authorization was denied");if(!u)throw new Error("No authorization code received");l("Exchanging authorization code..."),console.log("🔍 CallbackPage - Exchanging code with backend...");const p=await db("/auth/exchange",{code:u});l("Syncing your music data..."),await Ct(`/users/${p.uid}/sync`,void 0,p.token),l("Loading your profile...");const[g,w,v]=await Promise.all([ye(`/users/${p.uid}`),ye(`/users/${p.uid}/recently-played`),ye(`/users/${p.uid}/top-tracks?time_range=short_term`)]),y={user:g,accessToken:p.access_token,refreshToken:p.refresh_token,isAuthenticated:!0,recentlyPlayed:w,topTracks:v.map(x=>x.track),topArtists:[],jwt:p.token};localStorage.setItem("spotify-user",JSON.stringify(y)),s?(r(y),localStorage.setItem("spotify-partner",JSON.stringify(y)),l("Partner connected! Your musical journey begins...")):(n(y),l("Welcome! Setting up your musical journey...")),o("success"),Pe.success(s?"Partner connected successfully!":"Successfully connected to Spotify!",{duration:3e3}),setTimeout(()=>{t("/"),setTimeout(()=>{Pi=!1,console.log("🔍 CallbackPage - Global processing flag set to FALSE (after success)")},1e3)},2e3)}catch(u){console.error("🔍 CallbackPage - ERROR:",u),console.error("🔍 CallbackPage - Error details:",{message:u instanceof Error?u.message:"Unknown error",stack:u instanceof Error?u.stack:void 0}),o("error"),l(u instanceof Error?u.message:"An unexpected error occurred"),Pe.error("Failed to connect to Spotify. Please try again."),setTimeout(()=>{t("/"),setTimeout(()=>{Pi=!1,console.log("🔍 CallbackPage - Global processing flag set to FALSE (after error)")},1e3)},3e3)}})()},[e,t,n,r,s]);const c=()=>{switch(i){case"loading":return m.jsx(lk,{className:"w-12 h-12 text-spotify-green animate-spin"});case"success":return m.jsx(ak,{className:"w-12 h-12 text-green-400"});case"error":return m.jsx(mk,{className:"w-12 h-12 text-red-400"})}},d=()=>{switch(i){case"loading":return"border-spotify-green/30";case"success":return"border-green-400/30";case"error":return"border-red-400/30"}};return m.jsx("div",{className:"min-h-screen flex items-center justify-center px-4 bg-black",children:m.jsxs(I.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},className:"glass-fluid rounded-3xl p-10 max-w-md w-full text-center",children:[m.jsx(I.div,{initial:{scale:0},animate:{scale:1},transition:{delay:.2,type:"spring",stiffness:200},className:`w-20 h-20 mx-auto mb-6 rounded-full border-2 flex items-center justify-center ${d()}`,children:c()}),m.jsxs(I.h2,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},className:"text-2xl font-bold text-white mb-4",children:[i==="loading"&&"Connecting...",i==="success"&&"Success!",i==="error"&&"Connection Failed"]}),m.jsx(I.p,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.4},className:"text-white/70 mb-6",children:a}),i==="loading"&&m.jsx(I.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.5},className:"w-full bg-white/10 rounded-full h-2 mb-4",children:m.jsx(I.div,{className:"bg-spotify-green h-2 rounded-full",initial:{width:0},animate:{width:"100%"},transition:{duration:3,ease:"easeInOut"}})}),i==="error"&&m.jsx(I.button,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.5},whileHover:{scale:1.05},whileTap:{scale:.95},onClick:()=>t("/"),className:"bg-spotify-green hover:bg-spotify-green/90 text-white font-semibold py-3 px-6 rounded-lg transition-all duration-300",children:"Try Again"}),i==="success"&&m.jsx(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.5},className:"text-spotify-green text-sm",children:"Redirecting you to your musical journey..."})]})})},s6=()=>{var g,w,v;const{currentUser:e,partnerUser:t,currentTrack:n,isPlaying:r,setCurrentTrack:s,setIsPlaying:i,theme:o}=ve(),a=Vr(o),[l,c]=k.useState(!1),[d,f]=k.useState(null),u=k.useMemo(()=>{const y=((e==null?void 0:e.recentlyPlayed)||[]).map(P=>({who:"you",played_at:new Date(P.played_at).getTime(),track:P.track,key:`you-${P.track.id}-${P.played_at}`})),x=((t==null?void 0:t.recentlyPlayed)||[]).map(P=>({who:"partner",played_at:new Date(P.played_at).getTime(),track:P.track,key:`partner-${P.track.id}-${P.played_at}`})),b=[...y,...x].sort((P,j)=>j.played_at-P.played_at).slice(0,30),S=new Set,C=new Set;return b.forEach(P=>{const j=P.track.id;S.has(j)?C.add(j):S.add(j)}),{items:b,overlaps:C}},[e==null?void 0:e.recentlyPlayed,t==null?void 0:t.recentlyPlayed]),h=async(y,x)=>{var b,S;if(!(e!=null&&e.accessToken)){Pe.error("Not authenticated with Spotify");return}try{c(!0),f(x),r&&d===x?(await t6(e.accessToken),i(!1),s(null),f(null)):(await e6(e.accessToken,y),i(!0),s(((S=(b=e.recentlyPlayed)==null?void 0:b.find(C=>C.track.id===x))==null?void 0:S.track)||null)),Pe.success(r&&d===x?"Paused":"Now playing")}catch(C){console.error("Playback error:",C),Pe.error("Failed to play track. Make sure Spotify is open on your device.")}finally{c(!1)}},p=({user:y,title:x,isPartner:b=!1})=>{var C,P,j,_,T;if(!((C=y==null?void 0:y.recentlyPlayed)!=null&&C.length))return m.jsxs(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"glass rounded-2xl p-8 text-center",children:[m.jsx(It,{className:"w-16 h-16 mx-auto mb-4 text-white/30"}),m.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:"No recent activity"}),m.jsxs("p",{className:"text-white/70",children:[b?"Your partner":"You"," haven't played any music recently"]})]});const S=y.recentlyPlayed[0];return m.jsxs(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"glass rounded-2xl p-6",children:[m.jsxs("div",{className:"flex items-center space-x-4 mb-6",children:[m.jsx("div",{className:`w-12 h-12 rounded-full flex items-center justify-center ${b?"bg-gradient-to-br from-pink-500 to-purple-600":"bg-gradient-to-br from-blue-500 to-cyan-600"}`,children:m.jsx(bs,{className:"w-6 h-6 text-white"})}),m.jsxs("div",{children:[m.jsx("h2",{className:"text-2xl font-bold text-white",children:x}),m.jsxs("p",{className:"text-white/70",children:["Last played: ",Cr(S.played_at)]})]})]}),m.jsx(I.div,{whileHover:{scale:1.02},className:"bg-white/5 rounded-xl p-6 mb-6 border border-white/10",children:m.jsxs("div",{className:"flex items-center space-x-6",children:[m.jsxs("div",{className:"relative",children:[m.jsx("img",{src:((P=S.track.album.images[0])==null?void 0:P.url)||"/placeholder-album.png",alt:S.track.album.name,className:"w-20 h-20 rounded-lg object-cover"}),r&&d===S.track.id&&m.jsx("div",{className:"absolute inset-0 rounded-lg flex items-center justify-center",style:{backgroundColor:`${((j=a.cssVars)==null?void 0:j.primary)||"#1db954"}20`},children:m.jsx(hk,{className:"w-6 h-6",style:{color:((_=a.cssVars)==null?void 0:_.primary)||"#1db954"}})})]}),m.jsxs("div",{className:"flex-1",children:[m.jsx("h3",{className:"text-xl font-semibold text-white mb-1",children:S.track.name}),m.jsx("p",{className:"text-white/70 mb-2",children:S.track.artists.map(F=>F.name).join(", ")}),m.jsxs("p",{className:"text-white/50 text-sm",children:[S.track.album.name," • ",Qg(S.track.duration_ms)]})]}),m.jsxs("div",{className:"flex items-center space-x-3",children:[m.jsx("button",{onClick:()=>h(S.track.external_urls.spotify,S.track.id),disabled:l,className:"w-12 h-12 rounded-full flex items-center justify-center transition-all duration-300 text-white disabled:opacity-50",style:{backgroundColor:r&&d===S.track.id?"#ef4444":((T=a.cssVars)==null?void 0:T.primary)||"#1db954"},onMouseEnter:F=>{l||(F.currentTarget.style.opacity="0.9")},onMouseLeave:F=>{l||(F.currentTarget.style.opacity="1")},children:l&&d===S.track.id?m.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"}):r&&d===S.track.id?m.jsx(ck,{className:"w-5 h-5"}):m.jsx(Nh,{className:"w-5 h-5 ml-0.5"})}),m.jsx("a",{href:S.track.external_urls.spotify,target:"_blank",rel:"noopener noreferrer",className:"w-10 h-10 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center transition-colors",children:m.jsx($g,{className:"w-4 h-4 text-white"})})]})]})}),m.jsxs("div",{children:[m.jsxs("h3",{className:"text-lg font-semibold text-white mb-4 flex items-center space-x-2",children:[m.jsx(Co,{className:"w-5 h-5"}),m.jsx("span",{children:"Recent History"})]}),m.jsx("div",{className:"space-y-3",children:y.recentlyPlayed.slice(0,5).map((F,L)=>{var W,A,O;return m.jsxs(I.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:L*.1},className:"flex items-center space-x-4 p-3 rounded-lg hover:bg-white/5 transition-colors group",children:[m.jsx("img",{src:((W=F.track.album.images[0])==null?void 0:W.url)||"/placeholder-album.png",alt:F.track.album.name,className:"w-12 h-12 rounded-lg object-cover"}),m.jsxs("div",{className:"flex-1",children:[m.jsx("h4",{className:"text-white font-medium group-hover:text-spotify-green transition-colors",children:F.track.name}),m.jsx("p",{className:"text-white/70 text-sm",children:(A=F.track.artists[0])==null?void 0:A.name})]}),m.jsx("div",{className:"text-white/50 text-sm",children:Cr(F.played_at)}),m.jsx("button",{onClick:()=>h(F.track.external_urls.spotify,F.track.id),disabled:l,className:"opacity-0 group-hover:opacity-100 w-8 h-8 rounded-full flex items-center justify-center transition-all disabled:opacity-50",style:{backgroundColor:((O=a.cssVars)==null?void 0:O.primary)||"#1db954"},onMouseEnter:B=>{l||(B.currentTarget.style.opacity="0.9")},onMouseLeave:B=>{l||(B.currentTarget.style.opacity="1")},children:m.jsx(Nh,{className:"w-4 h-4 text-white ml-0.5"})})]},F.track.id)})})]})]})};return m.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8",children:[m.jsxs(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"mb-8",children:[m.jsxs("h1",{className:"text-4xl font-bold text-white mb-2 flex items-center space-x-3",children:[m.jsx(at,{className:"w-10 h-10",style:{color:((g=a.cssVars)==null?void 0:g.primary)||"#1db954"}}),m.jsx("span",{children:"What's Playing"})]}),m.jsx("p",{className:"text-white/70 text-lg",children:"Discover what you and your partner are listening to right now"})]}),m.jsxs("div",{className:"grid lg:grid-cols-2 gap-8",children:[e&&m.jsx(p,{user:e,title:`${(w=e.user)==null?void 0:w.display_name}'s Music`,isPartner:!1}),t&&m.jsx(p,{user:t,title:`${(v=t.user)==null?void 0:v.display_name}'s Music`,isPartner:!0}),!t&&m.jsxs(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"glass rounded-2xl p-8 text-center",children:[m.jsx(at,{className:"w-16 h-16 mx-auto mb-4 text-pink-400"}),m.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:"Waiting for your partner"}),m.jsx("p",{className:"text-white/70 mb-4",children:"Invite your partner to connect their Spotify account to see their music"}),m.jsx("button",{className:"bg-pink-500 hover:bg-pink-600 text-white px-6 py-3 rounded-lg transition-colors",children:"Send Invitation"})]})]}),e&&t&&m.jsxs(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"glass rounded-2xl p-8 mt-8",children:[m.jsxs("h3",{className:"text-lg font-semibold text-white mb-4 flex items-center space-x-2",children:[m.jsx(Co,{className:"w-5 h-5"}),m.jsx("span",{children:"Shared Timeline"})]}),m.jsx("div",{className:"space-y-3",children:u.items.map(y=>{var x,b,S,C,P;return m.jsxs("div",{className:"flex items-center gap-4 p-3 rounded-lg bg-white/5",children:[m.jsx("img",{src:((S=(b=(x=y.track.album)==null?void 0:x.images)==null?void 0:b[0])==null?void 0:S.url)||"/placeholder-album.png",alt:((C=y.track.album)==null?void 0:C.name)||"Album",className:"w-10 h-10 rounded"}),m.jsxs("div",{className:"flex-1 min-w-0",children:[m.jsxs("div",{className:"flex items-center gap-2",children:[m.jsx("span",{className:"text-white font-medium truncate",children:y.track.name}),u.overlaps.has(y.track.id)&&m.jsx("span",{className:"text-pink-400 text-sm",children:"💕"})]}),m.jsx("div",{className:"text-white/70 text-sm truncate",children:(P=y.track.artists)==null?void 0:P.map(j=>j.name).join(", ")})]}),m.jsxs("div",{className:"text-white/50 text-xs w-32 text-right",children:[Cr(new Date(y.played_at).toISOString()),m.jsx("div",{className:"text-white/60",children:y.who==="you"?"You":"Partner"})]})]},y.key)})})]})]})},i6=()=>{var F,L,W,A;const{currentUser:e,partnerUser:t,mixedPlaylists:n,addMixedPlaylist:r,removeMixedPlaylist:s,theme:i}=ve(),o=Vr(i),[a,l]=k.useState(!1),[c,d]=k.useState(!1),[f,u]=k.useState(null),[h,p]=k.useState(""),[g,w]=k.useState(""),[v,y]=k.useState(!0),[x,b]=k.useState(!1),S=g.split(",").map(O=>O.trim()).filter(O=>O.length>0),C=async()=>{var O,B,K,M,D,z;if(!f||!((O=e==null?void 0:e.user)!=null&&O.id)){Pe.error("Unable to create playlist");return}if(!(e!=null&&e.jwt)){Pe.error("Please login again");return}d(!0);try{const R={partnerId:((B=t==null?void 0:t.user)==null?void 0:B.id)||e.user.id,createForBoth:!1,includeKnown:!0,name:f.name,description:f.description},E=await Ct("/playlists/mixed",R,e.jwt);r({...f,spotifyId:(M=(K=E==null?void 0:E.createdFor)==null?void 0:K.creator)==null?void 0:M.playlistId,spotifyUrl:(z=(D=E==null?void 0:E.createdFor)==null?void 0:D.creator)==null?void 0:z.url}),Pe.success("Playlist created on Spotify!"),u(null)}catch(R){console.error("Spotify playlist creation error:",R),Pe.error("Failed to create playlist on Spotify")}finally{d(!1)}},P=async()=>{var O,B,K,M;if(!((O=e==null?void 0:e.user)!=null&&O.id)||!((B=t==null?void 0:t.user)!=null&&B.id)){Pe.error("Missing users");return}if(!(e!=null&&e.jwt)){Pe.error("Please login again");return}d(!0);try{const D={partnerId:t.user.id,createForBoth:x,includeKnown:v,vibe:h||void 0,genres:S.length?S:void 0,name:(f==null?void 0:f.name)||"Our Enhanced Mix",description:(f==null?void 0:f.description)||"An AI-blended mix with fresh recommendations"},z=await Ct("/playlists/mixed",D,e.jwt);Pe.success("Enhanced playlist created!"),(M=(K=z==null?void 0:z.createdFor)==null?void 0:K.creator)!=null&&M.url&&(r({...f||{id:Date.now().toString(),name:D.name,description:D.description,tracks:[],createdAt:new Date,createdBy:"AI Magic ✨"},spotifyId:z.createdFor.creator.playlistId,spotifyUrl:z.createdFor.creator.url}),u(null))}catch(D){console.error(D),Pe.error("Failed to create enhanced playlist")}finally{d(!1)}},j=()=>{f&&(r(f),u(null),Pe.success("Playlist saved locally!"))},_=({playlist:O,isNew:B=!1})=>m.jsxs(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},whileHover:{scale:1.02},className:`glass rounded-2xl p-6 ${B?"border-spotify-green/50":"border-white/10"}`,children:[m.jsxs("div",{className:"flex items-start justify-between mb-4",children:[m.jsxs("div",{className:"flex items-center space-x-4",children:[m.jsx("div",{className:`w-16 h-16 rounded-xl flex items-center justify-center ${B?"bg-gradient-to-br from-spotify-green to-green-600":"bg-gradient-to-br from-purple-500 to-pink-500"}`,children:B?m.jsx(Gn,{className:"w-8 h-8 text-white"}):m.jsx(It,{className:"w-8 h-8 text-white"})}),m.jsxs("div",{children:[m.jsx("h3",{className:"text-xl font-semibold text-white",children:O.name}),m.jsx("p",{className:"text-white/70 text-sm",children:O.description}),m.jsxs("p",{className:"text-white/50 text-xs mt-1",children:["Created ",B?"just now":new Date(O.createdAt).toLocaleDateString()," • ",O.tracks.length," tracks"]})]})]}),m.jsxs("div",{className:"flex items-center space-x-2",children:[O.spotifyUrl&&m.jsx("a",{href:O.spotifyUrl,target:"_blank",rel:"noopener noreferrer",className:"w-8 h-8 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center transition-colors",children:m.jsx($g,{className:"w-4 h-4 text-white"})}),!B&&m.jsx("button",{onClick:()=>s(O.id),className:"w-8 h-8 rounded-full bg-red-500/20 hover:bg-red-500/30 flex items-center justify-center transition-colors",children:m.jsx(Ug,{className:"w-4 h-4 text-red-400"})})]})]}),m.jsxs("div",{className:"space-y-3 max-h-64 overflow-y-auto",children:[O.tracks.slice(0,5).map((K,M)=>{var D,z,R,E,Y,Q;return m.jsxs(I.div,{initial:{opacity:0,x:-20},animate:{opacity:1,x:0},transition:{delay:M*.1},className:"flex items-center space-x-3 p-2 rounded-lg hover:bg-white/5 transition-colors",children:[m.jsx("img",{src:((R=(z=(D=K.album)==null?void 0:D.images)==null?void 0:z[0])==null?void 0:R.url)||"/placeholder-album.png",alt:((E=K.album)==null?void 0:E.name)||"Unknown Album",className:"w-10 h-10 rounded-lg object-cover"}),m.jsxs("div",{className:"flex-1 min-w-0",children:[m.jsx("h4",{className:"text-white font-medium truncate",children:K.name}),m.jsx("p",{className:"text-white/70 text-sm truncate",children:((Q=(Y=K.artists)==null?void 0:Y[0])==null?void 0:Q.name)||"Unknown Artist"})]}),m.jsx("div",{className:"text-white/50 text-sm",children:Qg(K.duration_ms)})]},K.id)}),O.tracks.length>5&&m.jsxs("div",{className:"text-center text-white/50 text-sm py-2",children:["+",O.tracks.length-5," more tracks"]})]}),B&&m.jsxs("div",{className:"flex items-center space-x-3 mt-6 pt-4 border-t border-white/10",children:[m.jsx("button",{onClick:C,disabled:c||x,className:"flex-1 bg-spotify-green hover:bg-spotify-green/90 text-white font-semibold py-3 px-4 rounded-lg transition-colors flex items-center justify-center space-x-2 disabled:opacity-50",children:c?m.jsx("div",{className:"w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"}):m.jsxs(m.Fragment,{children:[m.jsx(Ac,{className:"w-4 h-4"}),m.jsx("span",{children:x?"Disabled (using Create for both)":"Create on Spotify"})]})}),m.jsx("button",{onClick:j,className:"px-4 py-3 bg-white/10 hover:bg-white/20 text-white rounded-lg transition-colors",children:"Save Locally"})]})]}),T=(e==null?void 0:e.topTracks)&&(t==null?void 0:t.topTracks);return m.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8",children:[m.jsxs(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"mb-8",children:[m.jsxs("h1",{className:"text-4xl font-bold text-white mb-2 flex items-center space-x-3",children:[m.jsx(Gn,{className:"w-10 h-10",style:{color:((F=o.cssVars)==null?void 0:F.primary)||"#1db954"}}),m.jsx("span",{children:"Mixed Playlists"})]}),m.jsx("p",{className:"text-white/70 text-lg",children:"AI-powered playlists that perfectly blend your musical tastes together"})]}),T&&m.jsx(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.1},className:"mb-8",children:m.jsxs("div",{className:"glass rounded-2xl p-8 text-center",style:{borderColor:`${((L=o.cssVars)==null?void 0:L.primary)||"#1db954"}30`},children:[m.jsx("div",{className:"w-16 h-16 mx-auto mb-4 rounded-full flex items-center justify-center",style:{background:`linear-gradient(135deg, ${((W=o.cssVars)==null?void 0:W.primary)||"#1db954"} 0%, ${((A=o.cssVars)==null?void 0:A.secondary)||"#1ed760"} 100%)`},children:m.jsx(pk,{className:"w-8 h-8 text-white"})}),m.jsx("h2",{className:"text-2xl font-bold text-white mb-2",children:"Create Your Perfect Mix"}),m.jsx("p",{className:"text-white/70 mb-6 max-w-2xl mx-auto",children:"Our AI analyzes both your music tastes and creates a playlist that represents your unique musical connection"}),m.jsxs("div",{className:"mt-4 text-white/50 text-sm",children:["Analyzing ",e.topTracks.length+t.topTracks.length," tracks from both users"]}),m.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 text-left mt-8",children:[m.jsxs("div",{children:[m.jsx("label",{className:"block text-white/80 text-sm mb-1",children:"Vibe"}),m.jsxs("select",{className:"w-full bg-white/10 text-white rounded-lg p-2 appearance-none focus:outline-none focus:ring-2 focus:ring-spotify-green",value:h,onChange:O=>p(O.target.value),children:[m.jsx("option",{value:"",children:"Auto"}),m.jsx("option",{value:"energetic",children:"Energetic"}),m.jsx("option",{value:"chill",children:"Chill"}),m.jsx("option",{value:"happy",children:"Happy"}),m.jsx("option",{value:"sad",children:"Sad"}),m.jsx("option",{value:"party",children:"Party"}),m.jsx("option",{value:"focus",children:"Focus"})]})]}),m.jsxs("div",{children:[m.jsx("label",{className:"block text-white/80 text-sm mb-1",children:"Genres (comma-separated)"}),m.jsx("input",{className:"w-full bg-white/10 text-white rounded-lg p-2 placeholder-white/60 focus:outline-none focus:ring-2 focus:ring-spotify-green",placeholder:"pop, rock, edm",value:g,onChange:O=>w(O.target.value)})]}),m.jsxs("label",{className:"flex items-center space-x-2 text-white/80",children:[m.jsx("input",{type:"checkbox",checked:v,onChange:O=>y(O.target.checked)}),m.jsx("span",{children:"Include songs we already know"})]}),m.jsxs("label",{className:"flex items-center space-x-2 text-white/80",children:[m.jsx("input",{type:"checkbox",checked:x,onChange:O=>b(O.target.checked)}),m.jsx("span",{children:"Create playlist on both accounts"})]})]}),m.jsx("div",{className:"flex items-center justify-center gap-3 mt-6",children:m.jsx("button",{onClick:P,disabled:c,className:"bg-white/10 hover:bg-white/20 text-white font-semibold py-3 px-4 rounded-lg transition-colors disabled:opacity-50",children:"Create Enhanced Playlist"})})]})}),f&&m.jsxs(I.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},className:"mb-8",children:[m.jsx("h2",{className:"text-2xl font-bold text-white mb-4",children:"✨ Your New Playlist"}),m.jsx(_,{playlist:f,isNew:!0})]}),n.length>0&&m.jsxs(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.3},children:[m.jsx("h2",{className:"text-2xl font-bold text-white mb-4",children:"Your Mixed Playlists"}),m.jsx("div",{className:"grid gap-6",children:n.map(O=>m.jsx(_,{playlist:O},O.id))})]}),!T&&m.jsxs(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"glass rounded-2xl p-12 text-center",children:[m.jsx(at,{className:"w-16 h-16 mx-auto mb-4 text-pink-400"}),m.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:t?"Loading music data":"Waiting for your partner"}),m.jsx("p",{className:"text-white/70",children:t?"We need to analyze both your music tastes to create the perfect mixed playlist":"Invite your partner to connect their Spotify account to start creating mixed playlists"})]}),n.length===0&&T&&!f&&m.jsxs(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"glass rounded-2xl p-12 text-center",children:[m.jsx(It,{className:"w-16 h-16 mx-auto mb-4 text-white/30"}),m.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:"No playlists yet"}),m.jsx("p",{className:"text-white/70",children:"Create your first mixed playlist to start your musical journey together"})]})]})},o6=()=>{const{currentUser:e,partnerUser:t,memoryLane:n,addMemoryLaneItem:r}=ve(),[s,i]=k.useState(!1),[o,a]=k.useState({title:"",description:"",type:"milestone"});k.useEffect(()=>{var u,h,p,g,w,v,y,x,b,S,C,P;e&&t&&n.length===0&&[{id:"1",type:"milestone",title:"First Musical Connection",description:`${(u=e.user)==null?void 0:u.display_name} and ${(h=t.user)==null?void 0:h.display_name} discovered their shared love for music`,date:new Date(Date.now()-6048e5),users:[((p=e.user)==null?void 0:p.id)||"",((g=t.user)==null?void 0:g.id)||""]},{id:"2",type:"shared_track",title:"Shared Love for This Song",description:`Both of you have been listening to "${((v=(w=e.recentlyPlayed)==null?void 0:w[0])==null?void 0:v.track.name)||"Your favorite track"}" recently`,track:(x=(y=e.recentlyPlayed)==null?void 0:y[0])==null?void 0:x.track,date:new Date(Date.now()-2592e5),users:[((b=e.user)==null?void 0:b.id)||"",((S=t.user)==null?void 0:S.id)||""]},{id:"3",type:"playlist_created",title:"Our First Mixed Playlist",description:"Created a beautiful blend of your musical tastes",date:new Date(Date.now()-864e5),users:[((C=e.user)==null?void 0:C.id)||"",((P=t.user)==null?void 0:P.id)||""]}].forEach(_=>{r(_)})},[e,t,n.length,r]);const l=()=>{var h,p;if(!o.title.trim()||!o.description.trim()){Pe.error("Please fill in both title and description");return}const u={id:Date.now().toString(),...o,date:new Date,users:[((h=e==null?void 0:e.user)==null?void 0:h.id)||"",((p=t==null?void 0:t.user)==null?void 0:p.id)||""]};r(u),a({title:"",description:"",type:"milestone"}),i(!1),Pe.success("Memory added to your journey!")},c=u=>{switch(u){case"shared_track":return m.jsx(It,{className:"w-5 h-5"});case"playlist_created":return m.jsx(Gn,{className:"w-5 h-5"});case"milestone":return m.jsx(dk,{className:"w-5 h-5"});default:return m.jsx(at,{className:"w-5 h-5"})}},d=u=>{switch(u){case"shared_track":return"from-blue-500 to-cyan-500";case"playlist_created":return"from-purple-500 to-pink-500";case"milestone":return"from-yellow-500 to-orange-500";default:return"from-pink-500 to-red-500"}},f=({memory:u,index:h})=>{var p,g;return m.jsxs(I.div,{initial:{opacity:0,x:-50},animate:{opacity:1,x:0},transition:{delay:h*.1},className:"relative",children:[hi(!0),className:"bg-gradient-to-r from-pink-500 to-red-500 hover:from-pink-600 hover:to-red-600 text-white font-semibold py-3 px-6 rounded-xl transition-all duration-300 flex items-center space-x-2",children:[m.jsx(Ac,{className:"w-5 h-5"}),m.jsx("span",{children:"Add Memory"})]})]})}),s&&m.jsx(I.div,{initial:{opacity:0},animate:{opacity:1},className:"fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4",onClick:()=>i(!1),children:m.jsxs(I.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},onClick:u=>u.stopPropagation(),className:"glass rounded-2xl p-8 max-w-md w-full",children:[m.jsx("h3",{className:"text-2xl font-bold text-white mb-6",children:"Add a New Memory"}),m.jsxs("div",{className:"space-y-4",children:[m.jsxs("div",{children:[m.jsx("label",{className:"block text-white/70 text-sm font-medium mb-2",children:"Title"}),m.jsx("input",{type:"text",value:o.title,onChange:u=>a({...o,title:u.target.value}),className:"w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:border-spotify-green",placeholder:"What's this memory about?"})]}),m.jsxs("div",{children:[m.jsx("label",{className:"block text-white/70 text-sm font-medium mb-2",children:"Description"}),m.jsx("textarea",{value:o.description,onChange:u=>a({...o,description:u.target.value}),className:"w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white placeholder-white/50 focus:outline-none focus:border-spotify-green h-24 resize-none",placeholder:"Tell the story of this memory..."})]}),m.jsxs("div",{children:[m.jsx("label",{className:"block text-white/70 text-sm font-medium mb-2",children:"Type"}),m.jsxs("select",{value:o.type,onChange:u=>a({...o,type:u.target.value}),className:"w-full px-4 py-3 bg-white/10 border border-white/20 rounded-lg text-white focus:outline-none focus:border-spotify-green",children:[m.jsx("option",{value:"milestone",children:"Milestone"}),m.jsx("option",{value:"shared_track",children:"Shared Track"}),m.jsx("option",{value:"playlist_created",children:"Playlist Created"})]})]})]}),m.jsxs("div",{className:"flex items-center space-x-3 mt-6",children:[m.jsx("button",{onClick:l,className:"flex-1 bg-spotify-green hover:bg-spotify-green/90 text-white font-semibold py-3 px-4 rounded-lg transition-colors",children:"Add Memory"}),m.jsx("button",{onClick:()=>i(!1),className:"px-4 py-3 bg-white/10 hover:bg-white/20 text-white rounded-lg transition-colors",children:"Cancel"})]})]})}),m.jsx("div",{className:"space-y-8",children:n.length>0?n.map((u,h)=>m.jsx(f,{memory:u,index:h},u.id)):m.jsxs(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"glass rounded-2xl p-12 text-center",children:[m.jsx(ok,{className:"w-16 h-16 mx-auto mb-4 text-white/30"}),m.jsx("h3",{className:"text-xl font-semibold text-white mb-2",children:"No memories yet"}),m.jsx("p",{className:"text-white/70 mb-6",children:"Start creating beautiful musical memories together"}),m.jsx("button",{onClick:()=>i(!0),className:"bg-gradient-to-r from-pink-500 to-red-500 hover:from-pink-600 hover:to-red-600 text-white font-semibold py-3 px-6 rounded-xl transition-all duration-300",children:"Create First Memory"})]})}),n.length>0&&m.jsxs(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:.5},className:"mt-12 grid grid-cols-1 md:grid-cols-3 gap-6",children:[m.jsxs("div",{className:"glass rounded-2xl p-6 text-center",children:[m.jsx("div",{className:"w-12 h-12 mx-auto mb-3 bg-gradient-to-br from-pink-500 to-red-500 rounded-full flex items-center justify-center",children:m.jsx(at,{className:"w-6 h-6 text-white"})}),m.jsx("h4",{className:"text-2xl font-bold text-white mb-1",children:n.length}),m.jsx("p",{className:"text-white/70 text-sm",children:"Memories Created"})]}),m.jsxs("div",{className:"glass rounded-2xl p-6 text-center",children:[m.jsx("div",{className:"w-12 h-12 mx-auto mb-3 bg-gradient-to-br from-blue-500 to-cyan-500 rounded-full flex items-center justify-center",children:m.jsx(It,{className:"w-6 h-6 text-white"})}),m.jsx("h4",{className:"text-2xl font-bold text-white mb-1",children:n.filter(u=>u.type==="shared_track").length}),m.jsx("p",{className:"text-white/70 text-sm",children:"Shared Tracks"})]}),m.jsxs("div",{className:"glass rounded-2xl p-6 text-center",children:[m.jsx("div",{className:"w-12 h-12 mx-auto mb-3 bg-gradient-to-br from-purple-500 to-pink-500 rounded-full flex items-center justify-center",children:m.jsx(Gn,{className:"w-6 h-6 text-white"})}),m.jsx("h4",{className:"text-2xl font-bold text-white mb-1",children:n.filter(u=>u.type==="playlist_created").length}),m.jsx("p",{className:"text-white/70 text-sm",children:"Playlists Created"})]})]})]})};function a6(e,t){if(!e||!t)return 0;const n=["energy","valence"];let r=0,s=0;for(const i of n)typeof e[i]=="number"&&typeof t[i]=="number"&&(r+=1-Math.min(1,Math.abs(e[i]-t[i])),s++);return s?Math.round(r/s*100):0}const l6=()=>{var u,h;const{currentUser:e,partnerUser:t}=ve(),[n,r]=k.useState(null),[s,i]=k.useState(null),[o,a]=k.useState(null),[l,c]=k.useState(null);k.useEffect(()=>{let p;const g=async()=>{var w,v,y,x;try{const b=(w=e==null?void 0:e.user)==null?void 0:w.id;if(b){const C=await ye(`/users/${b}/now-playing`);r(C);const P=(v=C==null?void 0:C.item)==null?void 0:v.id;if(P){const j=await ye(`/users/${b}/audio-features?ids=${P}`);a(((j==null?void 0:j.audio_features)||[])[0]||null)}}const S=(y=t==null?void 0:t.user)==null?void 0:y.id;if(S){const C=await ye(`/users/${S}/now-playing`);i(C);const P=(x=C==null?void 0:C.item)==null?void 0:x.id;if(P){const j=await ye(`/users/${S}/audio-features?ids=${P}`);c(((j==null?void 0:j.audio_features)||[])[0]||null)}}}catch{}p=setTimeout(g,8e3)};return g(),()=>clearTimeout(p)},[(u=e==null?void 0:e.user)==null?void 0:u.id,(h=t==null?void 0:t.user)==null?void 0:h.id]);const d=k.useMemo(()=>a6(o,l),[o,l]),f=({data:p,who:g})=>{var v,y,x;if(!(p!=null&&p.is_playing)||!(p!=null&&p.item))return m.jsxs("div",{className:"glass rounded-2xl p-6 text-white/70",children:[g," is not playing"]});const w=p.item;return m.jsxs("div",{className:"glass rounded-2xl p-6 flex items-center gap-4",children:[m.jsx("img",{src:((x=(y=(v=w==null?void 0:w.album)==null?void 0:v.images)==null?void 0:y[0])==null?void 0:x.url)||"/placeholder-album.png",alt:w==null?void 0:w.name,className:"w-16 h-16 rounded"}),m.jsxs("div",{className:"flex-1 min-w-0",children:[m.jsx("div",{className:"text-white font-semibold truncate",children:w==null?void 0:w.name}),m.jsx("div",{className:"text-white/70 text-sm truncate",children:((w==null?void 0:w.artists)||[]).map(b=>b.name).join(", ")})]}),m.jsx("div",{className:"flex gap-1",children:[...Array(12)].map((b,S)=>m.jsx("div",{className:"w-1 bg-spotify-green/60 animate-pulse",style:{height:`${(Math.sin(S)*.5+.5)*32+8}px`,animationDelay:`${S*50}ms`}},S))})]})};return m.jsxs("div",{className:"max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8",children:[m.jsxs(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"mb-6",children:[m.jsx("h1",{className:"text-3xl font-bold text-white",children:"Live Dashboard"}),m.jsx("p",{className:"text-white/70",children:"See what you are both playing right now"})]}),m.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[m.jsx(f,{data:n,who:"You"}),m.jsx(f,{data:s,who:"Partner"})]}),(n==null?void 0:n.is_playing)&&(s==null?void 0:s.is_playing)&&m.jsxs(I.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},className:"glass rounded-2xl p-6 mt-6 text-center",children:[m.jsx("div",{className:"text-white/80",children:"Harmony Match"}),m.jsxs("div",{className:"text-4xl font-extrabold text-white mt-1",children:[d,"%"]})]})]})};function u6(){var o;const{currentUser:e,partnerUser:t,isLoading:n,theme:r}=ve(),s=jn();console.log("🔍 App - Current location:",s.pathname),k.useEffect(()=>{Vr(r)},[r]),k.useEffect(()=>{const a=localStorage.getItem("spotify-user"),l=localStorage.getItem("spotify-partner");if(a)try{const c=JSON.parse(a);ve.getState().setCurrentUser(c)}catch(c){console.error("Failed to parse stored user data:",c),localStorage.removeItem("spotify-user")}if(l)try{const c=JSON.parse(l);ve.getState().setPartnerUser(c)}catch(c){console.error("Failed to parse stored partner data:",c),localStorage.removeItem("spotify-partner")}},[]),k.useEffect(()=>{(async()=>{var c,d;const l=(d=(c=ve.getState().currentUser)==null?void 0:c.user)==null?void 0:d.id;if(l&&!ve.getState().partnerUser)try{const f=await ye(`/partners/partner/${l}`);if(f.partnerId){const[u,h,p]=await Promise.all([ye(`/users/${f.partnerId}`),ye(`/users/${f.partnerId}/recently-played`),ye(`/users/${f.partnerId}/top-tracks?time_range=short_term`)]);ve.getState().setPartnerUser({user:u,accessToken:null,refreshToken:null,isAuthenticated:!0,recentlyPlayed:h,topTracks:p.map(g=>g.track),topArtists:[]})}}catch{}})()},[(o=e==null?void 0:e.user)==null?void 0:o.id]);const i=(e==null?void 0:e.isAuthenticated)||!1;return n?m.jsxs("div",{className:"min-h-screen flex items-center justify-center relative",children:[m.jsx(Eh,{hueShift:ah(r)}),m.jsxs(I.div,{initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},className:"glass-fluid rounded-3xl p-10 flex flex-col items-center space-y-6 relative z-20",children:[m.jsx("div",{className:"w-16 h-16 border-4 border-t-transparent rounded-full animate-spin",style:{borderColor:"var(--theme-primary) var(--theme-primary) var(--theme-primary) transparent"}}),m.jsx("p",{className:"text-white font-medium text-lg",children:"Loading your musical journey..."})]})]}):m.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[m.jsx(Eh,{hueShift:ah(r)}),m.jsxs("div",{className:"relative z-20",children:[i&&m.jsx(Kk,{}),m.jsxs(xx,{children:[m.jsx(Mt,{path:"/",element:i?m.jsx(r6,{}):m.jsx(n6,{})}),m.jsx(Mt,{path:"/callback",element:m.jsx(Rh,{})}),m.jsx(Mt,{path:"/callback.html",element:m.jsx(Rh,{})}),i&&m.jsxs(m.Fragment,{children:[m.jsx(Mt,{path:"/last-listened",element:m.jsx(s6,{})}),m.jsx(Mt,{path:"/mixed-playlist",element:m.jsx(i6,{})}),m.jsx(Mt,{path:"/memory-lane",element:m.jsx(o6,{})}),m.jsx(Mt,{path:"/live",element:m.jsx(l6,{})})]}),m.jsx(Mt,{path:"*",element:m.jsx(yx,{to:"/",replace:!0})})]})]})]})}Ya.createRoot(document.getElementById("root")).render(m.jsx(qs.StrictMode,{children:m.jsxs(Ex,{children:[m.jsx(u6,{}),m.jsx(x2,{position:"top-right",toastOptions:{duration:4e3,style:{background:"rgba(255, 255, 255, 0.1)",backdropFilter:"blur(20px)",border:"1px solid rgba(255, 255, 255, 0.2)",color:"#fff"}}})]})})); diff --git a/dist/assets/index-DifsL9Ku.css b/dist/assets/index-DifsL9Ku.css deleted file mode 100644 index a845733..0000000 --- a/dist/assets/index-DifsL9Ku.css +++ /dev/null @@ -1 +0,0 @@ -@import"https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap";*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{top:0;right:0;bottom:0;left:0}.bottom-20{bottom:5rem}.bottom-32{bottom:8rem}.left-1\/4{left:25%}.left-10{left:2.5rem}.left-8{left:2rem}.right-1\/3{right:33.333333%}.right-20{right:5rem}.top-0{top:0}.top-16{top:4rem}.top-20{top:5rem}.top-40{top:10rem}.z-10{z-index:10}.z-20{z-index:20}.z-40{z-index:40}.z-50{z-index:50}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-12{margin-bottom:3rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-0\.5{margin-left:.125rem}.mt-1{margin-top:.25rem}.mt-12{margin-top:3rem}.mt-2{margin-top:.5rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.h-1{height:.25rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-14{height:3.5rem}.h-16{height:4rem}.h-2{height:.5rem}.h-20{height:5rem}.h-24{height:6rem}.h-3{height:.75rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-8{height:2rem}.h-full{height:100%}.max-h-64{max-height:16rem}.min-h-screen{min-height:100vh}.w-0\.5{width:.125rem}.w-1{width:.25rem}.w-10{width:2.5rem}.w-12{width:3rem}.w-14{width:3.5rem}.w-16{width:4rem}.w-20{width:5rem}.w-3{width:.75rem}.w-32{width:8rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-8{width:2rem}.w-full{width:100%}.min-w-0{min-width:0px}.max-w-2xl{max-width:42rem}.max-w-4xl{max-width:56rem}.max-w-6xl{max-width:72rem}.max-w-7xl{max-width:80rem}.max-w-lg{max-width:32rem}.max-w-md{max-width:28rem}.flex-1{flex:1 1 0%}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-grab{cursor:grab}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize-none{resize:none}.resize{resize:both}.appearance-none{-webkit-appearance:none;-moz-appearance:none;appearance:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.flex-col{flex-direction:column}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.gap-8{gap:2rem}.space-x-1>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.25rem * var(--tw-space-x-reverse));margin-left:calc(.25rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-6>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1.5rem * var(--tw-space-x-reverse));margin-left:calc(1.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.space-y-8>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(2rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(2rem * var(--tw-space-y-reverse))}.self-start{align-self:flex-start}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-3xl{border-radius:1.5rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-4{border-width:4px}.border-b{border-bottom-width:1px}.border-t{border-top-width:1px}.border-green-400\/30{border-color:#4ade804d}.border-orange-500\/30{border-color:#f973164d}.border-red-400\/30{border-color:#f871714d}.border-spotify-green\/30{border-color:#1db9544d}.border-spotify-green\/50{border-color:#1db95480}.border-theme-blue-primary{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-theme-blue-primary\/30{border-color:#3b82f64d}.border-theme-green-primary{--tw-border-opacity: 1;border-color:rgb(29 185 84 / var(--tw-border-opacity, 1))}.border-theme-green-primary\/30{border-color:#1db9544d}.border-theme-pink-primary{--tw-border-opacity: 1;border-color:rgb(236 72 153 / var(--tw-border-opacity, 1))}.border-theme-pink-primary\/30{border-color:#ec48994d}.border-theme-purple-primary{--tw-border-opacity: 1;border-color:rgb(139 92 246 / var(--tw-border-opacity, 1))}.border-theme-purple-primary\/30{border-color:#8b5cf64d}.border-theme-red-primary{--tw-border-opacity: 1;border-color:rgb(220 38 38 / var(--tw-border-opacity, 1))}.border-theme-red-primary\/30{border-color:#dc26264d}.border-theme-turquoise-primary{--tw-border-opacity: 1;border-color:rgb(6 182 212 / var(--tw-border-opacity, 1))}.border-theme-turquoise-primary\/30{border-color:#06b6d44d}.border-theme-yellow-primary{--tw-border-opacity: 1;border-color:rgb(234 179 8 / var(--tw-border-opacity, 1))}.border-theme-yellow-primary\/30{border-color:#eab3084d}.border-white{--tw-border-opacity: 1;border-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.border-white\/10{border-color:#ffffff1a}.border-white\/20{border-color:#fff3}.border-t-transparent{border-top-color:transparent}.bg-black{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.bg-black\/50{background-color:#00000080}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-pink-500{--tw-bg-opacity: 1;background-color:rgb(236 72 153 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-red-500\/20{background-color:#ef444433}.bg-spotify-green{--tw-bg-opacity: 1;background-color:rgb(29 185 84 / var(--tw-bg-opacity, 1))}.bg-spotify-green\/60{background-color:#1db95499}.bg-theme-blue-accent{--tw-bg-opacity: 1;background-color:rgb(147 197 253 / var(--tw-bg-opacity, 1))}.bg-theme-blue-primary{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-theme-blue-primary\/10{background-color:#3b82f61a}.bg-theme-blue-secondary{--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity, 1))}.bg-theme-green-accent{--tw-bg-opacity: 1;background-color:rgb(0 230 118 / var(--tw-bg-opacity, 1))}.bg-theme-green-primary{--tw-bg-opacity: 1;background-color:rgb(29 185 84 / var(--tw-bg-opacity, 1))}.bg-theme-green-primary\/10{background-color:#1db9541a}.bg-theme-green-secondary{--tw-bg-opacity: 1;background-color:rgb(30 215 96 / var(--tw-bg-opacity, 1))}.bg-theme-pink-accent{--tw-bg-opacity: 1;background-color:rgb(251 113 133 / var(--tw-bg-opacity, 1))}.bg-theme-pink-primary{--tw-bg-opacity: 1;background-color:rgb(236 72 153 / var(--tw-bg-opacity, 1))}.bg-theme-pink-primary\/10{background-color:#ec48991a}.bg-theme-pink-secondary{--tw-bg-opacity: 1;background-color:rgb(244 114 182 / var(--tw-bg-opacity, 1))}.bg-theme-purple-accent{--tw-bg-opacity: 1;background-color:rgb(196 181 253 / var(--tw-bg-opacity, 1))}.bg-theme-purple-primary{--tw-bg-opacity: 1;background-color:rgb(139 92 246 / var(--tw-bg-opacity, 1))}.bg-theme-purple-primary\/10{background-color:#8b5cf61a}.bg-theme-purple-secondary{--tw-bg-opacity: 1;background-color:rgb(167 139 250 / var(--tw-bg-opacity, 1))}.bg-theme-red-accent{--tw-bg-opacity: 1;background-color:rgb(248 113 113 / var(--tw-bg-opacity, 1))}.bg-theme-red-primary{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.bg-theme-red-primary\/10{background-color:#dc26261a}.bg-theme-red-secondary{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-theme-turquoise-accent{--tw-bg-opacity: 1;background-color:rgb(103 232 249 / var(--tw-bg-opacity, 1))}.bg-theme-turquoise-primary{--tw-bg-opacity: 1;background-color:rgb(6 182 212 / var(--tw-bg-opacity, 1))}.bg-theme-turquoise-primary\/10{background-color:#06b6d41a}.bg-theme-turquoise-secondary{--tw-bg-opacity: 1;background-color:rgb(34 211 238 / var(--tw-bg-opacity, 1))}.bg-theme-yellow-accent{--tw-bg-opacity: 1;background-color:rgb(251 191 36 / var(--tw-bg-opacity, 1))}.bg-theme-yellow-primary{--tw-bg-opacity: 1;background-color:rgb(234 179 8 / var(--tw-bg-opacity, 1))}.bg-theme-yellow-primary\/10{background-color:#eab3081a}.bg-theme-yellow-secondary{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-white\/10{background-color:#ffffff1a}.bg-white\/5{background-color:#ffffff0d}.bg-yellow-500{--tw-bg-opacity: 1;background-color:rgb(234 179 8 / var(--tw-bg-opacity, 1))}.bg-gradient-to-b{background-image:linear-gradient(to bottom,var(--tw-gradient-stops))}.bg-gradient-to-br{background-image:linear-gradient(to bottom right,var(--tw-gradient-stops))}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.from-blue-400{--tw-gradient-from: #60a5fa var(--tw-gradient-from-position);--tw-gradient-to: rgb(96 165 250 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-500{--tw-gradient-from: #3b82f6 var(--tw-gradient-from-position);--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-500\/30{--tw-gradient-from: rgb(59 130 246 / .3) var(--tw-gradient-from-position);--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-cyan-400{--tw-gradient-from: #22d3ee var(--tw-gradient-from-position);--tw-gradient-to: rgb(34 211 238 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-500{--tw-gradient-from: #22c55e var(--tw-gradient-from-position);--tw-gradient-to: rgb(34 197 94 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-500\/30{--tw-gradient-from: rgb(34 197 94 / .3) var(--tw-gradient-from-position);--tw-gradient-to: rgb(34 197 94 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-orange-500{--tw-gradient-from: #f97316 var(--tw-gradient-from-position);--tw-gradient-to: rgb(249 115 22 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-pink-500{--tw-gradient-from: #ec4899 var(--tw-gradient-from-position);--tw-gradient-to: rgb(236 72 153 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-500{--tw-gradient-from: #a855f7 var(--tw-gradient-from-position);--tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-500\/20{--tw-gradient-from: rgb(168 85 247 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-500\/30{--tw-gradient-from: rgb(168 85 247 / .3) var(--tw-gradient-from-position);--tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-600{--tw-gradient-from: #9333ea var(--tw-gradient-from-position);--tw-gradient-to: rgb(147 51 234 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-red-600{--tw-gradient-from: #dc2626 var(--tw-gradient-from-position);--tw-gradient-to: rgb(220 38 38 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-spotify-green{--tw-gradient-from: #1db954 var(--tw-gradient-from-position);--tw-gradient-to: rgb(29 185 84 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-theme-blue-primary{--tw-gradient-from: #3b82f6 var(--tw-gradient-from-position);--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-theme-green-primary{--tw-gradient-from: #1db954 var(--tw-gradient-from-position);--tw-gradient-to: rgb(29 185 84 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-theme-pink-primary{--tw-gradient-from: #ec4899 var(--tw-gradient-from-position);--tw-gradient-to: rgb(236 72 153 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-theme-purple-primary{--tw-gradient-from: #8b5cf6 var(--tw-gradient-from-position);--tw-gradient-to: rgb(139 92 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-theme-red-primary{--tw-gradient-from: #dc2626 var(--tw-gradient-from-position);--tw-gradient-to: rgb(220 38 38 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-theme-turquoise-primary{--tw-gradient-from: #06b6d4 var(--tw-gradient-from-position);--tw-gradient-to: rgb(6 182 212 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-theme-yellow-primary{--tw-gradient-from: #eab308 var(--tw-gradient-from-position);--tw-gradient-to: rgb(234 179 8 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-white\/20{--tw-gradient-from: rgb(255 255 255 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(255 255 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-yellow-400{--tw-gradient-from: #facc15 var(--tw-gradient-from-position);--tw-gradient-to: rgb(250 204 21 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-yellow-500{--tw-gradient-from: #eab308 var(--tw-gradient-from-position);--tw-gradient-to: rgb(234 179 8 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.via-blue-500\/20{--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(59 130 246 / .2) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-blue-500\/30{--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(59 130 246 / .3) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-blue-600{--tw-gradient-to: rgb(37 99 235 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #2563eb var(--tw-gradient-via-position), var(--tw-gradient-to)}.to-blue-500{--tw-gradient-to: #3b82f6 var(--tw-gradient-to-position)}.to-cyan-400{--tw-gradient-to: #22d3ee var(--tw-gradient-to-position)}.to-cyan-500{--tw-gradient-to: #06b6d4 var(--tw-gradient-to-position)}.to-cyan-500\/30{--tw-gradient-to: rgb(6 182 212 / .3) var(--tw-gradient-to-position)}.to-cyan-600{--tw-gradient-to: #0891b2 var(--tw-gradient-to-position)}.to-emerald-500{--tw-gradient-to: #10b981 var(--tw-gradient-to-position)}.to-emerald-500\/30{--tw-gradient-to: rgb(16 185 129 / .3) var(--tw-gradient-to-position)}.to-green-600{--tw-gradient-to: #16a34a var(--tw-gradient-to-position)}.to-orange-500{--tw-gradient-to: #f97316 var(--tw-gradient-to-position)}.to-pink-500{--tw-gradient-to: #ec4899 var(--tw-gradient-to-position)}.to-pink-500\/20{--tw-gradient-to: rgb(236 72 153 / .2) var(--tw-gradient-to-position)}.to-pink-500\/30{--tw-gradient-to: rgb(236 72 153 / .3) var(--tw-gradient-to-position)}.to-pink-600{--tw-gradient-to: #db2777 var(--tw-gradient-to-position)}.to-purple-600{--tw-gradient-to: #9333ea var(--tw-gradient-to-position)}.to-red-500{--tw-gradient-to: #ef4444 var(--tw-gradient-to-position)}.to-red-800{--tw-gradient-to: #991b1b var(--tw-gradient-to-position)}.to-rose-500{--tw-gradient-to: #f43f5e var(--tw-gradient-to-position)}.to-theme-blue-secondary{--tw-gradient-to: #60a5fa var(--tw-gradient-to-position)}.to-theme-green-secondary{--tw-gradient-to: #1ed760 var(--tw-gradient-to-position)}.to-theme-pink-secondary{--tw-gradient-to: #f472b6 var(--tw-gradient-to-position)}.to-theme-purple-secondary{--tw-gradient-to: #a78bfa var(--tw-gradient-to-position)}.to-theme-red-secondary{--tw-gradient-to: #ef4444 var(--tw-gradient-to-position)}.to-theme-turquoise-secondary{--tw-gradient-to: #22d3ee var(--tw-gradient-to-position)}.to-theme-yellow-secondary{--tw-gradient-to: #f59e0b var(--tw-gradient-to-position)}.to-transparent{--tw-gradient-to: transparent var(--tw-gradient-to-position)}.to-violet-600{--tw-gradient-to: #7c3aed var(--tw-gradient-to-position)}.object-cover{-o-object-fit:cover;object-fit:cover}.p-10{padding:2.5rem}.p-12{padding:3rem}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-5{padding-top:1.25rem;padding-bottom:1.25rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pt-4{padding-top:1rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-5xl{font-size:3rem;line-height:1}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-extrabold{font-weight:800}.font-medium{font-weight:500}.font-semibold{font-weight:600}.leading-relaxed{line-height:1.625}.text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.text-blue-400{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.text-green-400{--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.text-pink-400{--tw-text-opacity: 1;color:rgb(244 114 182 / var(--tw-text-opacity, 1))}.text-purple-400{--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-spotify-green{--tw-text-opacity: 1;color:rgb(29 185 84 / var(--tw-text-opacity, 1))}.text-spotify-green\/20{color:#1db95433}.text-spotify-green\/25{color:#1db95440}.text-spotify-green\/30{color:#1db9544d}.text-theme-blue-primary{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-theme-green-primary{--tw-text-opacity: 1;color:rgb(29 185 84 / var(--tw-text-opacity, 1))}.text-theme-pink-primary{--tw-text-opacity: 1;color:rgb(236 72 153 / var(--tw-text-opacity, 1))}.text-theme-purple-primary{--tw-text-opacity: 1;color:rgb(139 92 246 / var(--tw-text-opacity, 1))}.text-theme-red-primary{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-theme-turquoise-primary{--tw-text-opacity: 1;color:rgb(6 182 212 / var(--tw-text-opacity, 1))}.text-theme-yellow-primary{--tw-text-opacity: 1;color:rgb(234 179 8 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-white\/30{color:#ffffff4d}.text-white\/40{color:#fff6}.text-white\/50{color:#ffffff80}.text-white\/60{color:#fff9}.text-white\/70{color:#ffffffb3}.text-white\/80{color:#fffc}.placeholder-white\/50::-moz-placeholder{color:#ffffff80}.placeholder-white\/50::placeholder{color:#ffffff80}.placeholder-white\/60::-moz-placeholder{color:#fff9}.placeholder-white\/60::placeholder{color:#fff9}.opacity-0{opacity:0}.opacity-10{opacity:.1}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_30px_rgba\(147\,51\,234\,0\.3\)\]{--tw-shadow: 0 0 30px rgba(147,51,234,.3);--tw-shadow-colored: 0 0 30px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.blur{--tw-blur: blur(8px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.drop-shadow-md{--tw-drop-shadow: drop-shadow(0 4px 3px rgb(0 0 0 / .07)) drop-shadow(0 2px 2px rgb(0 0 0 / .06));filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}:root{font-family:Inter,system-ui,Avenir,Helvetica,Arial,sans-serif;line-height:1.5;font-weight:400;color-scheme:dark;color:#ffffffde;background:transparent;font-synthesis:none;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-text-size-adjust:100%;--theme-primary: #1db954;--theme-secondary: #1ed760;--theme-accent: #00e676}*{box-sizing:border-box}html,body{margin:0;padding:0;height:100%;overflow-x:hidden}body{background:transparent;background-attachment:fixed;min-height:100vh}#root{min-height:100vh;position:relative}.glass{background:#ffffff1a;-webkit-backdrop-filter:blur(20px);backdrop-filter:blur(20px);border:1px solid rgba(255,255,255,.2);box-shadow:0 8px 32px #0000004d}.glass-dark{background:#0003;-webkit-backdrop-filter:blur(20px);backdrop-filter:blur(20px);border:1px solid rgba(255,255,255,.1);box-shadow:0 8px 32px #0006}.glass-theme{background:var(--theme-primary);-webkit-backdrop-filter:blur(20px);backdrop-filter:blur(20px);border:1px solid var(--theme-primary);box-shadow:0 8px 32px var(--theme-primary);opacity:.1}.glass-green{background:#1db9541a;-webkit-backdrop-filter:blur(20px);backdrop-filter:blur(20px);border:1px solid rgba(29,185,84,.3);box-shadow:0 8px 32px #1db95433}::-webkit-scrollbar{width:8px}::-webkit-scrollbar-track{background:#ffffff1a;border-radius:4px}::-webkit-scrollbar-thumb{background:var(--theme-primary);border-radius:4px;opacity:.6}::-webkit-scrollbar-thumb:hover{background:var(--theme-primary);opacity:.8}.particles{position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:-1}.particle{position:absolute;background:radial-gradient(circle,var(--theme-primary) 0%,transparent 70%);border-radius:50%;animation:float 20s infinite linear;opacity:.3}@keyframes float{0%{transform:translateY(100vh) rotate(0);opacity:0}10%{opacity:1}90%{opacity:1}to{transform:translateY(-100px) rotate(360deg);opacity:0}}.wave-bubble{position:absolute;border-radius:50%;background:radial-gradient(circle,var(--theme-primary) 0%,var(--theme-secondary) 50%,var(--theme-accent) 100%);filter:blur(40px);animation:wave-flow 8s ease-in-out infinite;opacity:.4}.light-cylinder{position:absolute;top:-30%;transform-origin:top center;width:400px;height:150vh;background:linear-gradient(to bottom,var(--theme-primary) 0%,var(--theme-secondary) 15%,var(--theme-accent) 30%,rgba(255,255,255,.4) 50%,rgba(255,255,255,.2) 70%,rgba(255,255,255,.1) 85%,transparent 100%);border-radius:200px;animation:liquid-flow 40s ease-in-out infinite;filter:blur(80px)}.light-cylinder-1{animation-delay:0s;left:10%;width:600px;height:160vh}.light-cylinder-2{animation-delay:13s;left:45%;width:550px;height:140vh}.light-cylinder-3{animation-delay:26s;left:70%;width:580px;height:150vh}@keyframes liquid-flow{0%{transform:translate(0) translateY(0) rotate(0) scale(1);opacity:.7;filter:blur(80px)}20%{transform:translate(40px) translateY(15px) rotate(2deg) scale(1.05);opacity:.75;filter:blur(85px)}40%{transform:translate(-25px) translateY(-8px) rotate(-1.5deg) scale(.95);opacity:.65;filter:blur(82px)}60%{transform:translate(60px) translateY(25px) rotate(3deg) scale(1.1);opacity:.8;filter:blur(88px)}80%{transform:translate(-15px) translateY(10px) rotate(-1deg) scale(.98);opacity:.75;filter:blur(84px)}to{transform:translate(0) translateY(0) rotate(0) scale(1);opacity:.7;filter:blur(80px)}}.wave-bubble:nth-child(1){width:300px;height:300px;top:10%;left:10%;animation-delay:0s;animation-duration:12s}.wave-bubble:nth-child(2){width:200px;height:200px;top:60%;right:15%;animation-delay:2s;animation-duration:10s}.wave-bubble:nth-child(3){width:250px;height:250px;bottom:20%;left:20%;animation-delay:4s;animation-duration:14s}.wave-bubble:nth-child(4){width:180px;height:180px;top:30%;right:40%;animation-delay:6s;animation-duration:9s}.wave-bubble:nth-child(5){width:320px;height:320px;bottom:40%;right:10%;animation-delay:8s;animation-duration:16s}@keyframes wave-flow{0%,to{transform:translateY(0) translate(0) scale(1);opacity:.3}25%{transform:translateY(-50px) translate(30px) scale(1.1);opacity:.6}50%{transform:translateY(-20px) translate(-20px) scale(.9);opacity:.4}75%{transform:translateY(-80px) translate(40px) scale(1.2);opacity:.7}}.soap-bubble{position:absolute;border-radius:50%;background:radial-gradient(circle at 30% 30%,#fffc,#fff6,#9333ea33,#3b82f64d,#ec489933,#ffffff1a);border:2px solid rgba(255,255,255,.3);box-shadow:inset 0 0 20px #fff3,inset 0 0 40px #9333ea1a,0 0 30px #ffffff1a;animation:bubble-float 8s ease-in-out infinite}.bubble-small{width:20px;height:20px;animation:bubble-rise 3s ease-out forwards}.bubble-medium{width:40px;height:40px;animation:bubble-float 6s ease-in-out infinite}.bubble-large{width:80px;height:80px;animation:bubble-float 10s ease-in-out infinite}@keyframes bubble-float{0%,to{transform:translateY(0) scale(1);opacity:.6}50%{transform:translateY(-20px) scale(1.1);opacity:.8}}@keyframes bubble-rise{0%{transform:translateY(0) scale(1);opacity:.8}to{transform:translateY(-150px) scale(.2);opacity:0}}.glass-fluid{background:#0000004d;-webkit-backdrop-filter:blur(30px);backdrop-filter:blur(30px);border:1px solid rgba(255,255,255,.1);box-shadow:0 8px 32px #00000080,inset 0 1px #ffffff1a}.glass-bubble{background:radial-gradient(circle at 30% 30%,#ffffff26,#ffffff14,#9333ea1a,#3b82f614,#ec48990f,#ffffff08);-webkit-backdrop-filter:blur(20px);backdrop-filter:blur(20px);border:1px solid rgba(255,255,255,.2);box-shadow:inset 0 0 20px #ffffff1a,inset 0 0 40px #9333ea0d,0 8px 32px #9333ea1a,0 0 20px #ffffff0d;transition:all .3s cubic-bezier(.4,0,.2,1)}.glass-bubble:hover{background:radial-gradient(circle at 30% 30%,#fff3,#ffffff1f,#9333ea26,#3b82f61f,#ec48991a,#ffffff0d);border:1px solid rgba(255,255,255,.3);box-shadow:inset 0 0 25px #ffffff26,inset 0 0 50px #9333ea14,0 12px 40px #9333ea33,0 0 30px #ffffff1a;transform:translateY(-2px)}.spotify-hover{transition:all .3s cubic-bezier(.4,0,.2,1)}.spotify-hover:hover{transform:translateY(-2px);box-shadow:0 12px 40px var(--theme-primary)}.gradient-text{background:linear-gradient(135deg,var(--theme-primary),var(--theme-secondary),var(--theme-primary));background-size:200% 200%;background-clip:text;-webkit-background-clip:text;-webkit-text-fill-color:transparent;animation:gradient-shift 3s ease infinite}@keyframes gradient-shift{0%,to{background-position:0% 50%}50%{background-position:100% 50%}}.pulse-play{animation:pulse-play 2s infinite}@keyframes pulse-play{0%{box-shadow:0 0 0 0 var(--theme-primary)}70%{box-shadow:0 0 0 10px var(--theme-primary)}to{box-shadow:0 0 0 0 var(--theme-primary)}}.hover\:border-white\/30:hover{border-color:#ffffff4d}.hover\:bg-pink-600:hover{--tw-bg-opacity: 1;background-color:rgb(219 39 119 / var(--tw-bg-opacity, 1))}.hover\:bg-red-500\/30:hover{background-color:#ef44444d}.hover\:bg-spotify-green\/90:hover{background-color:#1db954e6}.hover\:bg-theme-blue-primary\/20:hover{background-color:#3b82f633}.hover\:bg-theme-green-primary\/20:hover{background-color:#1db95433}.hover\:bg-theme-pink-primary\/20:hover{background-color:#ec489933}.hover\:bg-theme-purple-primary\/20:hover{background-color:#8b5cf633}.hover\:bg-theme-red-primary\/20:hover{background-color:#dc262633}.hover\:bg-theme-turquoise-primary\/20:hover{background-color:#06b6d433}.hover\:bg-theme-yellow-primary\/20:hover{background-color:#eab30833}.hover\:bg-white\/10:hover{background-color:#ffffff1a}.hover\:bg-white\/20:hover{background-color:#fff3}.hover\:bg-white\/5:hover{background-color:#ffffff0d}.hover\:from-pink-600:hover{--tw-gradient-from: #db2777 var(--tw-gradient-from-position);--tw-gradient-to: rgb(219 39 119 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:from-purple-700:hover{--tw-gradient-from: #7e22ce var(--tw-gradient-from-position);--tw-gradient-to: rgb(126 34 206 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:via-blue-700:hover{--tw-gradient-to: rgb(29 78 216 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #1d4ed8 var(--tw-gradient-via-position), var(--tw-gradient-to)}.hover\:to-pink-700:hover{--tw-gradient-to: #be185d var(--tw-gradient-to-position)}.hover\:to-red-600:hover{--tw-gradient-to: #dc2626 var(--tw-gradient-to-position)}.hover\:text-red-300:hover{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\:shadow-lg:hover{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-xl:hover{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-white\/5:hover{--tw-shadow-color: rgb(255 255 255 / .05);--tw-shadow: var(--tw-shadow-colored)}.focus\:border-spotify-green:focus{--tw-border-opacity: 1;border-color:rgb(29 185 84 / var(--tw-border-opacity, 1))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-spotify-green:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(29 185 84 / var(--tw-ring-opacity, 1))}.active\:cursor-grabbing:active{cursor:grabbing}.disabled\:opacity-50:disabled{opacity:.5}.group:hover .group-hover\:scale-110{--tw-scale-x: 1.1;--tw-scale-y: 1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:text-spotify-green{--tw-text-opacity: 1;color:rgb(29 185 84 / var(--tw-text-opacity, 1))}.group:hover .group-hover\:opacity-100{opacity:1}@media (min-width: 640px){.sm\:hidden{display:none}.sm\:h-12{height:3rem}.sm\:h-5{height:1.25rem}.sm\:h-6{height:1.5rem}.sm\:w-12{width:3rem}.sm\:w-5{width:1.25rem}.sm\:w-6{width:1.5rem}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}.sm\:gap-3{gap:.75rem}.sm\:space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(0px * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(0px * var(--tw-space-y-reverse))}.sm\:space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.sm\:self-auto{align-self:auto}.sm\:p-3{padding:.75rem}.sm\:p-6{padding:1.5rem}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\:text-lg{font-size:1.125rem;line-height:1.75rem}}@media (min-width: 768px){.md\:flex{display:flex}.md\:hidden{display:none}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:text-6xl{font-size:3.75rem;line-height:1}}@media (min-width: 1024px){.lg\:block{display:block}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:px-8{padding-left:2rem;padding-right:2rem}} diff --git a/dist/assets/index-HYQ6lVkA.css b/dist/assets/index-HYQ6lVkA.css new file mode 100644 index 0000000..7d74ed3 --- /dev/null +++ b/dist/assets/index-HYQ6lVkA.css @@ -0,0 +1 @@ +@import"https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap";*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.static{position:static}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.sticky{position:sticky}.inset-0{top:0;right:0;bottom:0;left:0}.bottom-20{bottom:5rem}.bottom-32{bottom:8rem}.left-1\/4{left:25%}.left-10{left:2.5rem}.left-8{left:2rem}.right-1\/3{right:33.333333%}.right-20{right:5rem}.top-0{top:0}.top-16{top:4rem}.top-20{top:5rem}.top-40{top:10rem}.z-10{z-index:10}.z-20{z-index:20}.z-40{z-index:40}.z-50{z-index:50}.mx-auto{margin-left:auto;margin-right:auto}.mb-1{margin-bottom:.25rem}.mb-12{margin-bottom:3rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-6{margin-bottom:1.5rem}.mb-8{margin-bottom:2rem}.ml-0\.5{margin-left:.125rem}.ml-2{margin-left:.5rem}.mt-1{margin-top:.25rem}.mt-12{margin-top:3rem}.mt-2{margin-top:.5rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.block{display:block}.inline-block{display:inline-block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.h-1{height:.25rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-14{height:3.5rem}.h-16{height:4rem}.h-2{height:.5rem}.h-20{height:5rem}.h-24{height:6rem}.h-3{height:.75rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-6{height:1.5rem}.h-8{height:2rem}.h-full{height:100%}.max-h-64{max-height:16rem}.min-h-screen{min-height:100vh}.w-0\.5{width:.125rem}.w-1{width:.25rem}.w-10{width:2.5rem}.w-12{width:3rem}.w-14{width:3.5rem}.w-16{width:4rem}.w-20{width:5rem}.w-3{width:.75rem}.w-32{width:8rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-6{width:1.5rem}.w-8{width:2rem}.w-full{width:100%}.min-w-0{min-width:0px}.max-w-2xl{max-width:42rem}.max-w-4xl{max-width:56rem}.max-w-6xl{max-width:72rem}.max-w-7xl{max-width:80rem}.max-w-lg{max-width:32rem}.max-w-md{max-width:28rem}.flex-1{flex:1 1 0%}.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes pulse{50%{opacity:.5}}.animate-pulse{animation:pulse 2s cubic-bezier(.4,0,.6,1) infinite}@keyframes spin{to{transform:rotate(360deg)}}.animate-spin{animation:spin 1s linear infinite}.cursor-grab{cursor:grab}.cursor-pointer{cursor:pointer}.select-none{-webkit-user-select:none;-moz-user-select:none;user-select:none}.resize-none{resize:none}.resize{resize:both}.appearance-none{-webkit-appearance:none;-moz-appearance:none;appearance:none}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-center{align-items:center}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-1{gap:.25rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-6{gap:1.5rem}.gap-8{gap:2rem}.space-x-1>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.25rem * var(--tw-space-x-reverse));margin-left:calc(.25rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-2>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.5rem * var(--tw-space-x-reverse));margin-left:calc(.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-3>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.space-x-6>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1.5rem * var(--tw-space-x-reverse));margin-left:calc(1.5rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.space-y-8>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(2rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(2rem * var(--tw-space-y-reverse))}.self-start{align-self:flex-start}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.break-all{word-break:break-all}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-3xl{border-radius:1.5rem}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:.5rem}.rounded-md{border-radius:.375rem}.rounded-xl{border-radius:.75rem}.border{border-width:1px}.border-2{border-width:2px}.border-4{border-width:4px}.border-b{border-bottom-width:1px}.border-t{border-top-width:1px}.border-green-400\/30{border-color:#4ade804d}.border-orange-500\/30{border-color:#f973164d}.border-red-400\/30{border-color:#f871714d}.border-spotify-green\/30{border-color:#1db9544d}.border-spotify-green\/50{border-color:#1db95480}.border-theme-blue-primary{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-theme-blue-primary\/30{border-color:#3b82f64d}.border-theme-green-primary{--tw-border-opacity: 1;border-color:rgb(29 185 84 / var(--tw-border-opacity, 1))}.border-theme-green-primary\/30{border-color:#1db9544d}.border-theme-pink-primary{--tw-border-opacity: 1;border-color:rgb(236 72 153 / var(--tw-border-opacity, 1))}.border-theme-pink-primary\/30{border-color:#ec48994d}.border-theme-purple-primary{--tw-border-opacity: 1;border-color:rgb(139 92 246 / var(--tw-border-opacity, 1))}.border-theme-purple-primary\/30{border-color:#8b5cf64d}.border-theme-red-primary{--tw-border-opacity: 1;border-color:rgb(220 38 38 / var(--tw-border-opacity, 1))}.border-theme-red-primary\/30{border-color:#dc26264d}.border-theme-turquoise-primary{--tw-border-opacity: 1;border-color:rgb(6 182 212 / var(--tw-border-opacity, 1))}.border-theme-turquoise-primary\/30{border-color:#06b6d44d}.border-theme-yellow-primary{--tw-border-opacity: 1;border-color:rgb(234 179 8 / var(--tw-border-opacity, 1))}.border-theme-yellow-primary\/30{border-color:#eab3084d}.border-white{--tw-border-opacity: 1;border-color:rgb(255 255 255 / var(--tw-border-opacity, 1))}.border-white\/10{border-color:#ffffff1a}.border-white\/20{border-color:#fff3}.border-t-transparent{border-top-color:transparent}.bg-black{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.bg-black\/50{background-color:#00000080}.bg-blue-500\/20{background-color:#3b82f633}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-green-500\/20{background-color:#22c55e33}.bg-pink-500{--tw-bg-opacity: 1;background-color:rgb(236 72 153 / var(--tw-bg-opacity, 1))}.bg-pink-500\/20{background-color:#ec489933}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-red-500\/20{background-color:#ef444433}.bg-spotify-green{--tw-bg-opacity: 1;background-color:rgb(29 185 84 / var(--tw-bg-opacity, 1))}.bg-spotify-green\/60{background-color:#1db95499}.bg-theme-blue-accent{--tw-bg-opacity: 1;background-color:rgb(147 197 253 / var(--tw-bg-opacity, 1))}.bg-theme-blue-primary{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-theme-blue-primary\/10{background-color:#3b82f61a}.bg-theme-blue-secondary{--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity, 1))}.bg-theme-green-accent{--tw-bg-opacity: 1;background-color:rgb(0 230 118 / var(--tw-bg-opacity, 1))}.bg-theme-green-primary{--tw-bg-opacity: 1;background-color:rgb(29 185 84 / var(--tw-bg-opacity, 1))}.bg-theme-green-primary\/10{background-color:#1db9541a}.bg-theme-green-secondary{--tw-bg-opacity: 1;background-color:rgb(30 215 96 / var(--tw-bg-opacity, 1))}.bg-theme-pink-accent{--tw-bg-opacity: 1;background-color:rgb(251 113 133 / var(--tw-bg-opacity, 1))}.bg-theme-pink-primary{--tw-bg-opacity: 1;background-color:rgb(236 72 153 / var(--tw-bg-opacity, 1))}.bg-theme-pink-primary\/10{background-color:#ec48991a}.bg-theme-pink-secondary{--tw-bg-opacity: 1;background-color:rgb(244 114 182 / var(--tw-bg-opacity, 1))}.bg-theme-purple-accent{--tw-bg-opacity: 1;background-color:rgb(196 181 253 / var(--tw-bg-opacity, 1))}.bg-theme-purple-primary{--tw-bg-opacity: 1;background-color:rgb(139 92 246 / var(--tw-bg-opacity, 1))}.bg-theme-purple-primary\/10{background-color:#8b5cf61a}.bg-theme-purple-secondary{--tw-bg-opacity: 1;background-color:rgb(167 139 250 / var(--tw-bg-opacity, 1))}.bg-theme-red-accent{--tw-bg-opacity: 1;background-color:rgb(248 113 113 / var(--tw-bg-opacity, 1))}.bg-theme-red-primary{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.bg-theme-red-primary\/10{background-color:#dc26261a}.bg-theme-red-secondary{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-theme-turquoise-accent{--tw-bg-opacity: 1;background-color:rgb(103 232 249 / var(--tw-bg-opacity, 1))}.bg-theme-turquoise-primary{--tw-bg-opacity: 1;background-color:rgb(6 182 212 / var(--tw-bg-opacity, 1))}.bg-theme-turquoise-primary\/10{background-color:#06b6d41a}.bg-theme-turquoise-secondary{--tw-bg-opacity: 1;background-color:rgb(34 211 238 / var(--tw-bg-opacity, 1))}.bg-theme-yellow-accent{--tw-bg-opacity: 1;background-color:rgb(251 191 36 / var(--tw-bg-opacity, 1))}.bg-theme-yellow-primary{--tw-bg-opacity: 1;background-color:rgb(234 179 8 / var(--tw-bg-opacity, 1))}.bg-theme-yellow-primary\/10{background-color:#eab3081a}.bg-theme-yellow-secondary{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-white\/10{background-color:#ffffff1a}.bg-white\/5{background-color:#ffffff0d}.bg-yellow-500{--tw-bg-opacity: 1;background-color:rgb(234 179 8 / var(--tw-bg-opacity, 1))}.bg-gradient-to-b{background-image:linear-gradient(to bottom,var(--tw-gradient-stops))}.bg-gradient-to-br{background-image:linear-gradient(to bottom right,var(--tw-gradient-stops))}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.from-amber-500{--tw-gradient-from: #f59e0b var(--tw-gradient-from-position);--tw-gradient-to: rgb(245 158 11 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-400{--tw-gradient-from: #60a5fa var(--tw-gradient-from-position);--tw-gradient-to: rgb(96 165 250 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-500{--tw-gradient-from: #3b82f6 var(--tw-gradient-from-position);--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-500\/30{--tw-gradient-from: rgb(59 130 246 / .3) var(--tw-gradient-from-position);--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-cyan-400{--tw-gradient-from: #22d3ee var(--tw-gradient-from-position);--tw-gradient-to: rgb(34 211 238 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-cyan-500{--tw-gradient-from: #06b6d4 var(--tw-gradient-from-position);--tw-gradient-to: rgb(6 182 212 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-gray-500{--tw-gradient-from: #6b7280 var(--tw-gradient-from-position);--tw-gradient-to: rgb(107 114 128 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-gray-600{--tw-gradient-from: #4b5563 var(--tw-gradient-from-position);--tw-gradient-to: rgb(75 85 99 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-500{--tw-gradient-from: #22c55e var(--tw-gradient-from-position);--tw-gradient-to: rgb(34 197 94 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-500\/30{--tw-gradient-from: rgb(34 197 94 / .3) var(--tw-gradient-from-position);--tw-gradient-to: rgb(34 197 94 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-green-600{--tw-gradient-from: #16a34a var(--tw-gradient-from-position);--tw-gradient-to: rgb(22 163 74 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-indigo-500{--tw-gradient-from: #6366f1 var(--tw-gradient-from-position);--tw-gradient-to: rgb(99 102 241 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-orange-500{--tw-gradient-from: #f97316 var(--tw-gradient-from-position);--tw-gradient-to: rgb(249 115 22 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-pink-500{--tw-gradient-from: #ec4899 var(--tw-gradient-from-position);--tw-gradient-to: rgb(236 72 153 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-500{--tw-gradient-from: #a855f7 var(--tw-gradient-from-position);--tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-500\/20{--tw-gradient-from: rgb(168 85 247 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-500\/30{--tw-gradient-from: rgb(168 85 247 / .3) var(--tw-gradient-from-position);--tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-600{--tw-gradient-from: #9333ea var(--tw-gradient-from-position);--tw-gradient-to: rgb(147 51 234 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-red-500{--tw-gradient-from: #ef4444 var(--tw-gradient-from-position);--tw-gradient-to: rgb(239 68 68 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-red-600{--tw-gradient-from: #dc2626 var(--tw-gradient-from-position);--tw-gradient-to: rgb(220 38 38 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-slate-500{--tw-gradient-from: #64748b var(--tw-gradient-from-position);--tw-gradient-to: rgb(100 116 139 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-spotify-green{--tw-gradient-from: #1db954 var(--tw-gradient-from-position);--tw-gradient-to: rgb(29 185 84 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-teal-500{--tw-gradient-from: #14b8a6 var(--tw-gradient-from-position);--tw-gradient-to: rgb(20 184 166 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-theme-blue-primary{--tw-gradient-from: #3b82f6 var(--tw-gradient-from-position);--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-theme-green-primary{--tw-gradient-from: #1db954 var(--tw-gradient-from-position);--tw-gradient-to: rgb(29 185 84 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-theme-pink-primary{--tw-gradient-from: #ec4899 var(--tw-gradient-from-position);--tw-gradient-to: rgb(236 72 153 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-theme-purple-primary{--tw-gradient-from: #8b5cf6 var(--tw-gradient-from-position);--tw-gradient-to: rgb(139 92 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-theme-red-primary{--tw-gradient-from: #dc2626 var(--tw-gradient-from-position);--tw-gradient-to: rgb(220 38 38 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-theme-turquoise-primary{--tw-gradient-from: #06b6d4 var(--tw-gradient-from-position);--tw-gradient-to: rgb(6 182 212 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-theme-yellow-primary{--tw-gradient-from: #eab308 var(--tw-gradient-from-position);--tw-gradient-to: rgb(234 179 8 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-white\/20{--tw-gradient-from: rgb(255 255 255 / .2) var(--tw-gradient-from-position);--tw-gradient-to: rgb(255 255 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-yellow-400{--tw-gradient-from: #facc15 var(--tw-gradient-from-position);--tw-gradient-to: rgb(250 204 21 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-yellow-500{--tw-gradient-from: #eab308 var(--tw-gradient-from-position);--tw-gradient-to: rgb(234 179 8 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.via-blue-500\/20{--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(59 130 246 / .2) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-blue-500\/30{--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), rgb(59 130 246 / .3) var(--tw-gradient-via-position), var(--tw-gradient-to)}.via-blue-600{--tw-gradient-to: rgb(37 99 235 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #2563eb var(--tw-gradient-via-position), var(--tw-gradient-to)}.to-black{--tw-gradient-to: #000 var(--tw-gradient-to-position)}.to-blue-500{--tw-gradient-to: #3b82f6 var(--tw-gradient-to-position)}.to-cyan-400{--tw-gradient-to: #22d3ee var(--tw-gradient-to-position)}.to-cyan-500{--tw-gradient-to: #06b6d4 var(--tw-gradient-to-position)}.to-cyan-500\/30{--tw-gradient-to: rgb(6 182 212 / .3) var(--tw-gradient-to-position)}.to-cyan-600{--tw-gradient-to: #0891b2 var(--tw-gradient-to-position)}.to-emerald-500{--tw-gradient-to: #10b981 var(--tw-gradient-to-position)}.to-emerald-500\/30{--tw-gradient-to: rgb(16 185 129 / .3) var(--tw-gradient-to-position)}.to-gray-600{--tw-gradient-to: #4b5563 var(--tw-gradient-to-position)}.to-green-500{--tw-gradient-to: #22c55e var(--tw-gradient-to-position)}.to-green-600{--tw-gradient-to: #16a34a var(--tw-gradient-to-position)}.to-lime-500{--tw-gradient-to: #84cc16 var(--tw-gradient-to-position)}.to-orange-500{--tw-gradient-to: #f97316 var(--tw-gradient-to-position)}.to-pink-500{--tw-gradient-to: #ec4899 var(--tw-gradient-to-position)}.to-pink-500\/20{--tw-gradient-to: rgb(236 72 153 / .2) var(--tw-gradient-to-position)}.to-pink-500\/30{--tw-gradient-to: rgb(236 72 153 / .3) var(--tw-gradient-to-position)}.to-pink-600{--tw-gradient-to: #db2777 var(--tw-gradient-to-position)}.to-purple-500{--tw-gradient-to: #a855f7 var(--tw-gradient-to-position)}.to-purple-600{--tw-gradient-to: #9333ea var(--tw-gradient-to-position)}.to-red-500{--tw-gradient-to: #ef4444 var(--tw-gradient-to-position)}.to-red-800{--tw-gradient-to: #991b1b var(--tw-gradient-to-position)}.to-rose-500{--tw-gradient-to: #f43f5e var(--tw-gradient-to-position)}.to-slate-500{--tw-gradient-to: #64748b var(--tw-gradient-to-position)}.to-teal-500{--tw-gradient-to: #14b8a6 var(--tw-gradient-to-position)}.to-theme-blue-secondary{--tw-gradient-to: #60a5fa var(--tw-gradient-to-position)}.to-theme-green-secondary{--tw-gradient-to: #1ed760 var(--tw-gradient-to-position)}.to-theme-pink-secondary{--tw-gradient-to: #f472b6 var(--tw-gradient-to-position)}.to-theme-purple-secondary{--tw-gradient-to: #a78bfa var(--tw-gradient-to-position)}.to-theme-red-secondary{--tw-gradient-to: #ef4444 var(--tw-gradient-to-position)}.to-theme-turquoise-secondary{--tw-gradient-to: #22d3ee var(--tw-gradient-to-position)}.to-theme-yellow-secondary{--tw-gradient-to: #f59e0b var(--tw-gradient-to-position)}.to-transparent{--tw-gradient-to: transparent var(--tw-gradient-to-position)}.to-violet-600{--tw-gradient-to: #7c3aed var(--tw-gradient-to-position)}.to-yellow-600{--tw-gradient-to: #ca8a04 var(--tw-gradient-to-position)}.object-cover{-o-object-fit:cover;object-fit:cover}.p-10{padding:2.5rem}.p-12{padding:3rem}.p-2{padding:.5rem}.p-3{padding:.75rem}.p-4{padding:1rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-5{padding-top:1.25rem;padding-bottom:1.25rem}.py-8{padding-top:2rem;padding-bottom:2rem}.pt-4{padding-top:1rem}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-5xl{font-size:3rem;line-height:1}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-extrabold{font-weight:800}.font-medium{font-weight:500}.font-semibold{font-weight:600}.leading-relaxed{line-height:1.625}.text-black{--tw-text-opacity: 1;color:rgb(0 0 0 / var(--tw-text-opacity, 1))}.text-blue-300{--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.text-blue-400{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.text-green-300{--tw-text-opacity: 1;color:rgb(134 239 172 / var(--tw-text-opacity, 1))}.text-green-400{--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.text-pink-400{--tw-text-opacity: 1;color:rgb(244 114 182 / var(--tw-text-opacity, 1))}.text-purple-400{--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-spotify-green{--tw-text-opacity: 1;color:rgb(29 185 84 / var(--tw-text-opacity, 1))}.text-spotify-green\/20{color:#1db95433}.text-spotify-green\/25{color:#1db95440}.text-spotify-green\/30{color:#1db9544d}.text-theme-blue-primary{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-theme-green-primary{--tw-text-opacity: 1;color:rgb(29 185 84 / var(--tw-text-opacity, 1))}.text-theme-pink-primary{--tw-text-opacity: 1;color:rgb(236 72 153 / var(--tw-text-opacity, 1))}.text-theme-purple-primary{--tw-text-opacity: 1;color:rgb(139 92 246 / var(--tw-text-opacity, 1))}.text-theme-red-primary{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-theme-turquoise-primary{--tw-text-opacity: 1;color:rgb(6 182 212 / var(--tw-text-opacity, 1))}.text-theme-yellow-primary{--tw-text-opacity: 1;color:rgb(234 179 8 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-white\/30{color:#ffffff4d}.text-white\/40{color:#fff6}.text-white\/50{color:#ffffff80}.text-white\/60{color:#fff9}.text-white\/70{color:#ffffffb3}.text-white\/80{color:#fffc}.placeholder-white\/50::-moz-placeholder{color:#ffffff80}.placeholder-white\/50::placeholder{color:#ffffff80}.placeholder-white\/60::-moz-placeholder{color:#fff9}.placeholder-white\/60::placeholder{color:#fff9}.opacity-0{opacity:0}.opacity-10{opacity:.1}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_30px_rgba\(147\,51\,234\,0\.3\)\]{--tw-shadow: 0 0 30px rgba(147,51,234,.3);--tw-shadow-colored: 0 0 30px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.blur{--tw-blur: blur(8px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.drop-shadow-md{--tw-drop-shadow: drop-shadow(0 4px 3px rgb(0 0 0 / .07)) drop-shadow(0 2px 2px rgb(0 0 0 / .06));filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-sm{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}:root{font-family:Inter,system-ui,Avenir,Helvetica,Arial,sans-serif;line-height:1.5;font-weight:400;color-scheme:dark;color:#ffffffde;background:transparent;font-synthesis:none;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-text-size-adjust:100%;--theme-primary: #1db954;--theme-secondary: #1ed760;--theme-accent: #00e676}*{box-sizing:border-box}html,body{margin:0;padding:0;height:100%;overflow-x:hidden}body{background:transparent;background-attachment:fixed;min-height:100vh}#root{min-height:100vh;position:relative}.glass{background:#ffffff1a;-webkit-backdrop-filter:blur(20px);backdrop-filter:blur(20px);border:1px solid rgba(255,255,255,.2);box-shadow:0 8px 32px #0000004d}.glass-dark{background:#0003;-webkit-backdrop-filter:blur(20px);backdrop-filter:blur(20px);border:1px solid rgba(255,255,255,.1);box-shadow:0 8px 32px #0006}.glass-theme{background:var(--theme-primary);-webkit-backdrop-filter:blur(20px);backdrop-filter:blur(20px);border:1px solid var(--theme-primary);box-shadow:0 8px 32px var(--theme-primary);opacity:.1}.glass-green{background:#1db9541a;-webkit-backdrop-filter:blur(20px);backdrop-filter:blur(20px);border:1px solid rgba(29,185,84,.3);box-shadow:0 8px 32px #1db95433}::-webkit-scrollbar{width:8px}::-webkit-scrollbar-track{background:#ffffff1a;border-radius:4px}::-webkit-scrollbar-thumb{background:var(--theme-primary);border-radius:4px;opacity:.6}::-webkit-scrollbar-thumb:hover{background:var(--theme-primary);opacity:.8}.particles{position:fixed;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:-1}.particle{position:absolute;background:radial-gradient(circle,var(--theme-primary) 0%,transparent 70%);border-radius:50%;animation:float 20s infinite linear;opacity:.3}@keyframes float{0%{transform:translateY(100vh) rotate(0);opacity:0}10%{opacity:1}90%{opacity:1}to{transform:translateY(-100px) rotate(360deg);opacity:0}}.wave-bubble{position:absolute;border-radius:50%;background:radial-gradient(circle,var(--theme-primary) 0%,var(--theme-secondary) 50%,var(--theme-accent) 100%);filter:blur(40px);animation:wave-flow 8s ease-in-out infinite;opacity:.4}.light-cylinder{position:absolute;top:-30%;transform-origin:top center;width:400px;height:150vh;background:linear-gradient(to bottom,var(--theme-primary) 0%,var(--theme-secondary) 15%,var(--theme-accent) 30%,rgba(255,255,255,.4) 50%,rgba(255,255,255,.2) 70%,rgba(255,255,255,.1) 85%,transparent 100%);border-radius:200px;animation:liquid-flow 40s ease-in-out infinite;filter:blur(80px)}.light-cylinder-1{animation-delay:0s;left:10%;width:600px;height:160vh}.light-cylinder-2{animation-delay:13s;left:45%;width:550px;height:140vh}.light-cylinder-3{animation-delay:26s;left:70%;width:580px;height:150vh}@keyframes liquid-flow{0%{transform:translate(0) translateY(0) rotate(0) scale(1);opacity:.7;filter:blur(80px)}20%{transform:translate(40px) translateY(15px) rotate(2deg) scale(1.05);opacity:.75;filter:blur(85px)}40%{transform:translate(-25px) translateY(-8px) rotate(-1.5deg) scale(.95);opacity:.65;filter:blur(82px)}60%{transform:translate(60px) translateY(25px) rotate(3deg) scale(1.1);opacity:.8;filter:blur(88px)}80%{transform:translate(-15px) translateY(10px) rotate(-1deg) scale(.98);opacity:.75;filter:blur(84px)}to{transform:translate(0) translateY(0) rotate(0) scale(1);opacity:.7;filter:blur(80px)}}.wave-bubble:nth-child(1){width:300px;height:300px;top:10%;left:10%;animation-delay:0s;animation-duration:12s}.wave-bubble:nth-child(2){width:200px;height:200px;top:60%;right:15%;animation-delay:2s;animation-duration:10s}.wave-bubble:nth-child(3){width:250px;height:250px;bottom:20%;left:20%;animation-delay:4s;animation-duration:14s}.wave-bubble:nth-child(4){width:180px;height:180px;top:30%;right:40%;animation-delay:6s;animation-duration:9s}.wave-bubble:nth-child(5){width:320px;height:320px;bottom:40%;right:10%;animation-delay:8s;animation-duration:16s}@keyframes wave-flow{0%,to{transform:translateY(0) translate(0) scale(1);opacity:.3}25%{transform:translateY(-50px) translate(30px) scale(1.1);opacity:.6}50%{transform:translateY(-20px) translate(-20px) scale(.9);opacity:.4}75%{transform:translateY(-80px) translate(40px) scale(1.2);opacity:.7}}.soap-bubble{position:absolute;border-radius:50%;background:radial-gradient(circle at 30% 30%,#fffc,#fff6,#9333ea33,#3b82f64d,#ec489933,#ffffff1a);border:2px solid rgba(255,255,255,.3);box-shadow:inset 0 0 20px #fff3,inset 0 0 40px #9333ea1a,0 0 30px #ffffff1a;animation:bubble-float 8s ease-in-out infinite}.bubble-small{width:20px;height:20px;animation:bubble-rise 3s ease-out forwards}.bubble-medium{width:40px;height:40px;animation:bubble-float 6s ease-in-out infinite}.bubble-large{width:80px;height:80px;animation:bubble-float 10s ease-in-out infinite}@keyframes bubble-float{0%,to{transform:translateY(0) scale(1);opacity:.6}50%{transform:translateY(-20px) scale(1.1);opacity:.8}}@keyframes bubble-rise{0%{transform:translateY(0) scale(1);opacity:.8}to{transform:translateY(-150px) scale(.2);opacity:0}}.glass-fluid{background:#0000004d;-webkit-backdrop-filter:blur(30px);backdrop-filter:blur(30px);border:1px solid rgba(255,255,255,.1);box-shadow:0 8px 32px #00000080,inset 0 1px #ffffff1a}.glass-bubble{background:radial-gradient(circle at 30% 30%,#ffffff26,#ffffff14,#9333ea1a,#3b82f614,#ec48990f,#ffffff08);-webkit-backdrop-filter:blur(20px);backdrop-filter:blur(20px);border:1px solid rgba(255,255,255,.2);box-shadow:inset 0 0 20px #ffffff1a,inset 0 0 40px #9333ea0d,0 8px 32px #9333ea1a,0 0 20px #ffffff0d;transition:all .3s cubic-bezier(.4,0,.2,1)}.glass-bubble:hover{background:radial-gradient(circle at 30% 30%,#fff3,#ffffff1f,#9333ea26,#3b82f61f,#ec48991a,#ffffff0d);border:1px solid rgba(255,255,255,.3);box-shadow:inset 0 0 25px #ffffff26,inset 0 0 50px #9333ea14,0 12px 40px #9333ea33,0 0 30px #ffffff1a;transform:translateY(-2px)}.spotify-hover{transition:all .3s cubic-bezier(.4,0,.2,1)}.spotify-hover:hover{transform:translateY(-2px);box-shadow:0 12px 40px var(--theme-primary)}.gradient-text{background:linear-gradient(135deg,var(--theme-primary),var(--theme-secondary),var(--theme-primary));background-size:200% 200%;background-clip:text;-webkit-background-clip:text;-webkit-text-fill-color:transparent;animation:gradient-shift 3s ease infinite}@keyframes gradient-shift{0%,to{background-position:0% 50%}50%{background-position:100% 50%}}.pulse-play{animation:pulse-play 2s infinite}@keyframes pulse-play{0%{box-shadow:0 0 0 0 var(--theme-primary)}70%{box-shadow:0 0 0 10px var(--theme-primary)}to{box-shadow:0 0 0 0 var(--theme-primary)}}.hover\:border-white\/30:hover{border-color:#ffffff4d}.hover\:bg-pink-500\/30:hover{background-color:#ec48994d}.hover\:bg-pink-600:hover{--tw-bg-opacity: 1;background-color:rgb(219 39 119 / var(--tw-bg-opacity, 1))}.hover\:bg-red-500\/30:hover{background-color:#ef44444d}.hover\:bg-spotify-green\/90:hover{background-color:#1db954e6}.hover\:bg-theme-blue-primary\/20:hover{background-color:#3b82f633}.hover\:bg-theme-green-primary\/20:hover{background-color:#1db95433}.hover\:bg-theme-pink-primary\/20:hover{background-color:#ec489933}.hover\:bg-theme-purple-primary\/20:hover{background-color:#8b5cf633}.hover\:bg-theme-red-primary\/20:hover{background-color:#dc262633}.hover\:bg-theme-turquoise-primary\/20:hover{background-color:#06b6d433}.hover\:bg-theme-yellow-primary\/20:hover{background-color:#eab30833}.hover\:bg-white\/10:hover{background-color:#ffffff1a}.hover\:bg-white\/20:hover{background-color:#fff3}.hover\:bg-white\/5:hover{background-color:#ffffff0d}.hover\:from-pink-600:hover{--tw-gradient-from: #db2777 var(--tw-gradient-from-position);--tw-gradient-to: rgb(219 39 119 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:from-purple-700:hover{--tw-gradient-from: #7e22ce var(--tw-gradient-from-position);--tw-gradient-to: rgb(126 34 206 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.hover\:via-blue-700:hover{--tw-gradient-to: rgb(29 78 216 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), #1d4ed8 var(--tw-gradient-via-position), var(--tw-gradient-to)}.hover\:to-pink-700:hover{--tw-gradient-to: #be185d var(--tw-gradient-to-position)}.hover\:to-red-600:hover{--tw-gradient-to: #dc2626 var(--tw-gradient-to-position)}.hover\:text-red-300:hover{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\:shadow-lg:hover{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-xl:hover{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-white\/5:hover{--tw-shadow-color: rgb(255 255 255 / .05);--tw-shadow: var(--tw-shadow-colored)}.focus\:border-spotify-green:focus{--tw-border-opacity: 1;border-color:rgb(29 185 84 / var(--tw-border-opacity, 1))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-spotify-green:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(29 185 84 / var(--tw-ring-opacity, 1))}.active\:cursor-grabbing:active{cursor:grabbing}.disabled\:opacity-50:disabled{opacity:.5}.group:hover .group-hover\:scale-110{--tw-scale-x: 1.1;--tw-scale-y: 1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group:hover .group-hover\:text-spotify-green{--tw-text-opacity: 1;color:rgb(29 185 84 / var(--tw-text-opacity, 1))}.group:hover .group-hover\:opacity-100{opacity:1}@media (min-width: 640px){.sm\:hidden{display:none}.sm\:h-12{height:3rem}.sm\:h-5{height:1.25rem}.sm\:h-6{height:1.5rem}.sm\:w-12{width:3rem}.sm\:w-5{width:1.25rem}.sm\:w-6{width:1.5rem}.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:flex-row{flex-direction:row}.sm\:items-center{align-items:center}.sm\:justify-between{justify-content:space-between}.sm\:gap-3{gap:.75rem}.sm\:space-x-4>:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(1rem * var(--tw-space-x-reverse));margin-left:calc(1rem * calc(1 - var(--tw-space-x-reverse)))}.sm\:space-y-0>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(0px * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(0px * var(--tw-space-y-reverse))}.sm\:space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.sm\:self-auto{align-self:auto}.sm\:p-3{padding:.75rem}.sm\:p-6{padding:1.5rem}.sm\:px-6{padding-left:1.5rem;padding-right:1.5rem}.sm\:text-lg{font-size:1.125rem;line-height:1.75rem}}@media (min-width: 768px){.md\:flex{display:flex}.md\:hidden{display:none}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:text-6xl{font-size:3.75rem;line-height:1}}@media (min-width: 1024px){.lg\:block{display:block}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:px-8{padding-left:2rem;padding-right:2rem}} diff --git a/dist/index.html b/dist/index.html index 7e7eccc..ad0342d 100644 --- a/dist/index.html +++ b/dist/index.html @@ -6,8 +6,8 @@ 💕 Our Musical Journey - - + +
diff --git a/frontend-dev.out b/frontend-dev.out new file mode 100644 index 0000000..97aec69 Binary files /dev/null and b/frontend-dev.out differ diff --git a/frontend-dev.pid b/frontend-dev.pid new file mode 100644 index 0000000..8ea0ecb --- /dev/null +++ b/frontend-dev.pid @@ -0,0 +1 @@ +589178 diff --git a/server-dev.out b/server-dev.out new file mode 100644 index 0000000..9396826 --- /dev/null +++ b/server-dev.out @@ -0,0 +1,415 @@ + +> spotify-backend@0.1.0 dev +> tsx watch src/index.ts + +API server (HTTP) listening on http://0.0.0.0:8081 +API server (HTTPS) listening on https://0.0.0.0:8082 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 122.661 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 124.347 ms - 20 +11:46:14 AM [tsx] change in ./src/lib/spotify.ts Restarting... +cAPI server (HTTP) listening on http://0.0.0.0:8081 +API server (HTTPS) listening on https://0.0.0.0:8082 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 116.462 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 84.068 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 44.734 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 50.038 ms - 20 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.182 ms - 133957 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 1.866 ms - 133957 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 1.901 ms - 133957 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.281 ms - 133957 +Selected random playlist cover: /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.30%20(1).jpeg +Failed to upload playlist image to Spotify: Request failed with status code 401 +Saving playlist to database: { + id: '402571a8-b5a8-4acd-ab3d-c95bf20ade4d', + name: 'Urban Harmony - Oct 16', + trackCount: 25, + trackUris: [ + 'spotify:track:6ls9KAHhzEoAZwniwREz4Y', + 'spotify:track:7ewUS7XNAWNmeVDtfGMkYS', + 'spotify:track:4cts1NKuolCnAx6EyUvXMp' + ] +} +POST /playlists/mixed 200 1833.840 ms - 1355 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.733 ms - 133957 +GET /api/placeholder-playlist-cover 200 3.367 ms - 563 +GET /api/placeholder-playlist-cover 200 0.903 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 1.933 ms - 133957 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 38.746 ms - 20 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.649 ms - 133957 +GET /api/placeholder-playlist-cover 200 2.809 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.022 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.779 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.753 ms - 133957 +GET /api/placeholder-playlist-cover 200 3.241 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.699 ms - 133957 +GET /api/placeholder-playlist-cover 200 3.093 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 5.518 ms - 133957 +GET /api/placeholder-playlist-cover 200 6.247 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.515 ms - 133957 +GET /api/placeholder-playlist-cover 200 3.173 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 3.225 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.443 ms - 563 +GET /api/placeholder-playlist-cover 200 1.314 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 3.308 ms - 133957 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 85.695 ms - 20 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.366 ms - 133957 +GET /api/placeholder-playlist-cover 200 2.061 ms - 563 +Selected random playlist cover: /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(3).jpeg +Failed to upload playlist image to Spotify: Request failed with status code 401 +Saving playlist to database: { + id: 'f8ec78d4-61fd-4ca6-ac89-7a68ca220707', + name: 'Energetic Vibes - Oct 16', + trackCount: 25, + trackUris: [ + 'spotify:track:3Iq8XToI0I9KSnqovkv1AV', + 'spotify:track:05od2qm2MTSKCHxy1GBp5W', + 'spotify:track:2ihCaVdNZmnHZWt0fvAM7B' + ] +} +POST /playlists/mixed 200 1598.434 ms - 1357 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 3.428 ms - 133957 +GET /api/placeholder-playlist-cover 200 3.715 ms - 563 +GET /api/placeholder-playlist-cover 200 0.455 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 1.955 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.449 ms - 563 +GET /api/placeholder-playlist-cover 200 0.435 ms - 563 +DELETE /playlists/mixed/402571a8-b5a8-4acd-ab3d-c95bf20ade4d 200 2.092 ms - 16 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.152 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.487 ms - 563 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 85.115 ms - 20 +DELETE /playlists/mixed/f8ec78d4-61fd-4ca6-ac89-7a68ca220707 200 2.102 ms - 16 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.068 ms - 133957 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.375 ms - 133957 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 1.782 ms - 133957 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 3.706 ms - 133957 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.041 ms - 133957 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 3.221 ms - 133957 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 1.811 ms - 133957 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 1.701 ms - 133957 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 3.402 ms - 133957 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 1.820 ms - 133957 +Selected random playlist cover: /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(5).jpeg +Failed to upload playlist image to Spotify: Request failed with status code 401 +Saving playlist to database: { + id: '8499a09c-65fb-4cc9-be27-8a4d124cf9b7', + name: 'Cosmic Rhythm - Oct 16', + trackCount: 25, + trackUris: [ + 'spotify:track:5IdsAZE15cZzXRG8sc5odK', + 'spotify:track:1tuQuawWDXfoc33NJdwvkd', + 'spotify:track:0xCmn4DDvatL81myxErTcR' + ] +} +POST /playlists/mixed 200 1429.947 ms - 1355 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 1.933 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.484 ms - 563 +GET /api/placeholder-playlist-cover 200 0.377 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 1.697 ms - 133957 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 74.662 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 51.461 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 51.903 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 54.336 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 84.966 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 44.583 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 49.930 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 89.645 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 85.998 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 83.312 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 37.621 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 52.736 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 60.872 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 52.101 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 54.628 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 34.661 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 93.374 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 53.185 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 89.281 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 87.633 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 86.173 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 85.098 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 38.095 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 89.413 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 57.037 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 53.259 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 86.496 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 32.286 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 52.538 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 86.311 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 54.530 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 113.127 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 45.480 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 46.395 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 56.122 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 109.522 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 80.657 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 35.693 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 94.003 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 45.205 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 46.407 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 93.980 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 32.058 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 88.262 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 44.547 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 83.242 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 88.258 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 57.022 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 87.483 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 46.228 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 84.729 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 37.597 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 52.872 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 53.307 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 85.058 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 48.571 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 59.094 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 52.266 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 51.166 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 85.000 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 47.374 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 80.154 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 49.615 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 99.950 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 85.954 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 53.544 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 88.140 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 82.217 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 53.072 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 56.040 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 104.363 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 32.945 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 86.977 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 48.330 ms - 20 +GET /partners/partner/91416peucsefexd7z3q9875hw 200 2.273 ms - 44 +GET /playlists/mixed 200 2.253 ms - 3317 +GET /partners/partner/91416peucsefexd7z3q9875hw 200 1.678 ms - 44 +GET /users/91416peucsefexd7z3q9875hw/recently-played 200 5.919 ms - 156666 +GET /users/91416peucsefexd7z3q9875hw/status 200 0.981 ms - 57 +GET /users/31at7552nbs34vogjfzmasypv6vy 200 0.824 ms - 238 +GET /users/31at7552nbs34vogjfzmasypv6vy/top-tracks?time_range=short_term 200 2.895 ms - 61623 +GET /users/31at7552nbs34vogjfzmasypv6vy/recently-played 200 7.728 ms - 156852 +GET /partners/requests/91416peucsefexd7z3q9875hw 200 2.900 ms - 2 +GET /users/31at7552nbs34vogjfzmasypv6vy 200 0.973 ms - 238 +GET /users/31at7552nbs34vogjfzmasypv6vy/top-tracks?time_range=short_term 200 3.326 ms - 61623 +GET /users/31at7552nbs34vogjfzmasypv6vy/recently-played 200 5.822 ms - 156852 +GET /users/91416peucsefexd7z3q9875hw/status 200 0.621 ms - 57 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 89.765 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/recently-played 200 6.333 ms - 156666 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 51.316 ms - 20 +GET /users/31at7552nbs34vogjfzmasypv6vy/recently-played 200 5.281 ms - 156852 +GET /users/31at7552nbs34vogjfzmasypv6vy/now-playing 200 1.790 ms - 20 +GET /api/placeholder-playlist-cover 200 0.592 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.319 ms - 133957 +GET /playlists/mixed 200 1.825 ms - 3317 +GET /api/placeholder-playlist-cover 200 1.095 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.954 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.566 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.067 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.854 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 4.463 ms - 133957 +GET /api/placeholder-playlist-cover 200 4.161 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 3.532 ms - 133957 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.069 ms - 133957 +GET /api/placeholder-playlist-cover 200 1.154 ms - 563 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 54.546 ms - 20 +Selected random playlist cover: /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg +Failed to upload playlist image to Spotify: Request failed with status code 401 +Saving playlist to database: { + id: 'a1d4d7d6-4cd0-4491-a0a3-9a00d79c1a67', + name: 'Dynamic Journey - Oct 16', + trackCount: 25, + trackUris: [ + 'spotify:track:04a44cx2PJthIbN2aLMXhl', + 'spotify:track:7ne4VBA60CxGM75vw0EYad', + 'spotify:track:3siwsiaEoU4Kuuc9WKMUy5' + ] +} +POST /playlists/mixed 200 1344.283 ms - 1357 +GET /api/placeholder-playlist-cover 200 0.697 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 3.052 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.485 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 1.895 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.446 ms - 563 +GET /api/placeholder-playlist-cover 200 0.597 ms - 563 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 36.743 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 57.805 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 48.784 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 116.291 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 68.737 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 54.825 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 82.917 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 32.735 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 83.209 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 83.340 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 48.658 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 53.279 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 46.485 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 51.319 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 60.172 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 57.074 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 88.420 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 32.737 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 54.118 ms - 20 +POST /auth/exchange 200 169.914 ms - 749 +POST /users/91416peucsefexd7z3q9875hw/sync 200 333.677 ms - 11 +GET /users/91416peucsefexd7z3q9875hw 200 1.782 ms - 232 +GET /users/91416peucsefexd7z3q9875hw/recently-played 200 9.057 ms - 156666 +GET /users/91416peucsefexd7z3q9875hw/top-tracks?time_range=short_term 200 3.977 ms - 73042 +GET /partners/partner/91416peucsefexd7z3q9875hw 200 2.235 ms - 44 +GET /users/31at7552nbs34vogjfzmasypv6vy 200 0.883 ms - 238 +GET /users/31at7552nbs34vogjfzmasypv6vy/recently-played 200 6.558 ms - 156852 +GET /users/31at7552nbs34vogjfzmasypv6vy/top-tracks?time_range=short_term 200 4.078 ms - 61623 +GET /playlists/mixed 200 2.564 ms - 4947 +GET /api/placeholder-playlist-cover 200 0.613 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.389 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.578 ms - 563 +GET /users/91416peucsefexd7z3q9875hw/recently-played 200 5.697 ms - 156666 +GET /partners/requests/91416peucsefexd7z3q9875hw 200 2.920 ms - 2 +GET /users/91416peucsefexd7z3q9875hw/status 200 0.912 ms - 57 +GET /users/91416peucsefexd7z3q9875hw/status 200 0.730 ms - 57 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 35.508 ms - 20 +GET /users/31at7552nbs34vogjfzmasypv6vy/recently-played 200 6.000 ms - 156852 +GET /users/31at7552nbs34vogjfzmasypv6vy/now-playing 200 1.662 ms - 20 +GET /api/placeholder-playlist-cover 200 0.685 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.455 ms - 133957 +GET /playlists/mixed 200 2.862 ms - 4947 +GET /api/placeholder-playlist-cover 200 0.631 ms - 563 +GET /api/placeholder-playlist-cover 200 0.459 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.043 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.562 ms - 563 +GET /api/placeholder-playlist-cover 200 0.526 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 1.909 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.513 ms - 563 +GET /api/placeholder-playlist-cover 200 0.470 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.081 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.445 ms - 563 +GET /api/placeholder-playlist-cover 200 0.966 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.980 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.598 ms - 563 +GET /api/placeholder-playlist-cover 200 0.660 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.422 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.597 ms - 563 +Selected random playlist cover: /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.30%20(2).jpeg +Failed to upload playlist image to Spotify: Request failed with status code 401 +Saving playlist to database: { + id: '018d648c-4bc5-4b77-a0d7-65ce22bd83c8', + name: 'Ethereal Journey - Oct 16', + trackCount: 25, + trackUris: [ + 'spotify:track:1I37Zz2g3hk9eWxaNkj031', + 'spotify:track:3siwsiaEoU4Kuuc9WKMUy5', + 'spotify:track:14F1zH9ZynOh2SuHCOskCO' + ] +} +POST /playlists/mixed 200 1501.613 ms - 1358 +GET /api/placeholder-playlist-cover 200 0.482 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.104 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.631 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 1.841 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.410 ms - 563 +GET /api/placeholder-playlist-cover 200 0.456 ms - 563 +GET /api/placeholder-playlist-cover 200 0.372 ms - 563 +GET /api/placeholder-playlist-cover 200 0.401 ms - 563 +GET / 404 1.896 ms - 139 +GET /partners/partner/91416peucsefexd7z3q9875hw 200 3.051 ms - 44 +GET /playlists/mixed 200 1.902 ms - 6578 +GET /partners/partner/91416peucsefexd7z3q9875hw 200 1.363 ms - 44 +GET /users/91416peucsefexd7z3q9875hw/recently-played 200 5.273 ms - 156666 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 46.904 ms - 20 +GET /users/31at7552nbs34vogjfzmasypv6vy/recently-played 200 4.157 ms - 156852 +GET /users/31at7552nbs34vogjfzmasypv6vy/top-tracks?time_range=short_term 200 3.537 ms - 61623 +GET /partners/requests/91416peucsefexd7z3q9875hw 200 2.761 ms - 2 +GET /users/91416peucsefexd7z3q9875hw/status 200 0.689 ms - 57 +GET /users/31at7552nbs34vogjfzmasypv6vy 200 0.847 ms - 238 +GET /users/31at7552nbs34vogjfzmasypv6vy 200 1.964 ms - 238 +GET /users/31at7552nbs34vogjfzmasypv6vy/recently-played 200 7.561 ms - 156852 +GET /users/31at7552nbs34vogjfzmasypv6vy/top-tracks?time_range=short_term 200 9.130 ms - 61623 +GET /users/91416peucsefexd7z3q9875hw/status 200 0.681 ms - 57 +GET /users/91416peucsefexd7z3q9875hw/recently-played 200 5.229 ms - 156666 +GET /users/31at7552nbs34vogjfzmasypv6vy/recently-played 200 4.413 ms - 156852 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 40.378 ms - 20 +GET /users/31at7552nbs34vogjfzmasypv6vy/now-playing 200 2.133 ms - 20 +GET /api/placeholder-playlist-cover 200 0.514 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 1.947 ms - 133957 +GET /playlists/mixed 200 1.735 ms - 6578 +GET /api/placeholder-playlist-cover 200 0.391 ms - 563 +GET /api/placeholder-playlist-cover 200 0.516 ms - 563 +GET /api/placeholder-playlist-cover 200 0.420 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.071 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.439 ms - 563 +GET /api/placeholder-playlist-cover 200 0.375 ms - 563 +1:05:52 PM [tsx] change in ./src/lib/spotify.ts Restarting... +cAPI server (HTTP) listening on http://0.0.0.0:8081 +API server (HTTPS) listening on https://0.0.0.0:8082 +GET /partners/partner/91416peucsefexd7z3q9875hw 200 7.651 ms - 44 +GET /playlists/mixed 200 2.752 ms - 6578 +GET /partners/partner/91416peucsefexd7z3q9875hw 200 2.748 ms - 44 +GET /users/91416peucsefexd7z3q9875hw/recently-played 200 6.800 ms - 156666 +GET /users/31at7552nbs34vogjfzmasypv6vy 200 1.442 ms - 238 +GET /users/31at7552nbs34vogjfzmasypv6vy/top-tracks?time_range=short_term 200 2.926 ms - 61623 +GET /partners/requests/91416peucsefexd7z3q9875hw 200 5.612 ms - 2 +GET /users/91416peucsefexd7z3q9875hw/status 200 1.290 ms - 57 +GET /users/31at7552nbs34vogjfzmasypv6vy 200 1.832 ms - 238 +GET /users/31at7552nbs34vogjfzmasypv6vy/recently-played 200 6.098 ms - 156852 +GET /users/31at7552nbs34vogjfzmasypv6vy/top-tracks?time_range=short_term 200 3.316 ms - 61623 +GET /users/91416peucsefexd7z3q9875hw/status 200 0.869 ms - 57 +GET /users/31at7552nbs34vogjfzmasypv6vy/recently-played 200 5.840 ms - 156852 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 96.801 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/recently-played 200 7.880 ms - 156666 +GET /users/31at7552nbs34vogjfzmasypv6vy/recently-played 200 5.679 ms - 156852 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 50.219 ms - 20 +GET /users/31at7552nbs34vogjfzmasypv6vy/now-playing 200 1.817 ms - 20 +GET /api/placeholder-playlist-cover 200 0.678 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.330 ms - 133957 +GET /playlists/mixed 200 2.275 ms - 6578 +GET /api/placeholder-playlist-cover 200 0.564 ms - 563 +GET /api/placeholder-playlist-cover 200 0.467 ms - 563 +GET /api/placeholder-playlist-cover 200 0.496 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.922 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.408 ms - 563 +GET /api/placeholder-playlist-cover 200 0.479 ms - 563 +GET /api/placeholder-playlist-cover 200 0.893 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.588 ms - 133957 +GET /api/placeholder-playlist-cover 200 1.053 ms - 563 +GET /api/placeholder-playlist-cover 200 0.609 ms - 563 +GET /api/placeholder-playlist-cover 200 0.981 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.881 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.573 ms - 563 +GET /api/placeholder-playlist-cover 200 0.568 ms - 563 +GET /api/placeholder-playlist-cover 200 0.651 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.128 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.565 ms - 563 +GET /api/placeholder-playlist-cover 200 0.872 ms - 563 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 94.920 ms - 20 +GET /api/placeholder-playlist-cover 200 0.541 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 3.378 ms - 133957 +GET /api/placeholder-playlist-cover 200 0.580 ms - 563 +GET /api/placeholder-playlist-cover 200 0.515 ms - 563 +Selected random playlist cover: /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(5).jpeg +Saving playlist to database: { + id: '4bed041d-6933-433a-9cb1-e7dd0bbff3f1', + name: 'Dynamic Wave - Oct 16', + trackCount: 25, + trackUris: [ + 'spotify:track:7tXyps7cXLdb9zhoA0PMHs', + 'spotify:track:4SejSRZpC6hsrhqchmyfzk', + 'spotify:track:4vGvTtEHVl1orcHzSbqeYm' + ] +} +POST /playlists/mixed 200 1361.987 ms - 1400 +GET /api/placeholder-playlist-cover 200 0.722 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.676 ms - 133957 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(5).jpeg 200 6.924 ms - 204401 +GET /api/placeholder-playlist-cover 200 0.607 ms - 563 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(1).jpeg 200 2.759 ms - 133957 +GET /api/playlist-covers/WhatsApp%20Image%202025-10-16%20at%2011.12.29%20(5).jpeg 200 7.878 ms - 204401 +GET /api/placeholder-playlist-cover 200 0.460 ms - 563 +GET /api/placeholder-playlist-cover 200 0.413 ms - 563 +GET /api/placeholder-playlist-cover 200 0.396 ms - 563 +GET /api/placeholder-playlist-cover 200 0.402 ms - 563 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 87.092 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 53.905 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 48.070 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 80.755 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 85.340 ms - 20 +GET /users/91416peucsefexd7z3q9875hw/now-playing 200 89.713 ms - 20 +GET /partners/events/91416peucsefexd7z3q9875hw?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiI5MTQxNnBldWNzZWZleGQ3ejNxOTg3NWh3IiwiaWF0IjoxNzYwNjA4ODMzLCJleHAiOjE3NjMyMDA4MzN9.WSdmfrirUCT-EqTtfisnlU3CdP1d8CMcGx52tNa5zSY 200 3.451 ms - - diff --git a/server-dev.pid b/server-dev.pid new file mode 100644 index 0000000..48c903f --- /dev/null +++ b/server-dev.pid @@ -0,0 +1 @@ +592323 diff --git a/server/dist/index.js b/server/dist/index.js new file mode 100644 index 0000000..5f40ff8 --- /dev/null +++ b/server/dist/index.js @@ -0,0 +1,145 @@ +import 'dotenv/config'; +import express from 'express'; +import cors from 'cors'; +import helmet from 'helmet'; +import morgan from 'morgan'; +import fs from 'fs'; +import path from 'path'; +import https from 'https'; +import { db } from './lib/db.js'; +import { authRouter } from './routes/auth.js'; +import { usersRouter } from './routes/users.js'; +import { partnersRouter } from './routes/partners.js'; +import { playlistsRouter } from './routes/playlists.js'; +import { syncUserData, captureNowPlaying } from './lib/sync.js'; +const app = express(); +app.use(helmet()); +app.use(cors({ origin: [ + 'http://localhost:3000', + 'https://159.195.9.107:3443', + 'http://159.195.9.107:3443' + ], credentials: true })); +// Add CORS headers to allow mixed content for development +app.use((req, res, next) => { + res.header('Access-Control-Allow-Origin', '*'); + res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); + res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization'); + next(); +}); +app.use(express.json({ limit: '1mb' })); +app.use(express.urlencoded({ extended: false })); +app.use(morgan('dev')); +// Serve static files from public directory +app.use(express.static('public')); +// Initialize DB +db.initialize(); +app.get('/health', (_req, res) => { + res.json({ ok: true }); +}); +// Placeholder playlist cover endpoint +app.get('/api/placeholder-playlist-cover', (_req, res) => { + // Return a simple SVG placeholder + const svg = ` + + + + + + + + + 🎵 + + `; + res.setHeader('Content-Type', 'image/svg+xml'); + res.send(svg); +}); +// Serve playlist cover images as base64 data URLs to avoid mixed content issues +app.get('/api/playlist-covers/:filename', (req, res) => { + try { + const filename = decodeURIComponent(req.params.filename); + const filePath = path.join(process.cwd(), 'public', 'playlist-covers', filename); + // Check if file exists + if (!fs.existsSync(filePath)) { + return res.status(404).json({ error: 'Image not found' }); + } + // Read file as base64 + const fileBuffer = fs.readFileSync(filePath); + const base64Data = fileBuffer.toString('base64'); + // Set appropriate content type based on file extension + const ext = path.extname(filename).toLowerCase(); + let contentType = 'image/jpeg'; // default + switch (ext) { + case '.png': + contentType = 'image/png'; + break; + case '.gif': + contentType = 'image/gif'; + break; + case '.webp': + contentType = 'image/webp'; + break; + case '.svg': + contentType = 'image/svg+xml'; + break; + case '.jpg': + case '.jpeg': + contentType = 'image/jpeg'; + break; + } + // Return base64 data URL + const dataUrl = `data:${contentType};base64,${base64Data}`; + res.setHeader('Content-Type', 'application/json'); + res.setHeader('Cache-Control', 'public, max-age=31536000'); // Cache for 1 year + res.json({ dataUrl }); + } + catch (error) { + console.error('Error serving playlist cover:', error); + res.status(500).json({ error: 'Failed to serve image' }); + } +}); +app.use('/auth', authRouter); +app.use('/users', usersRouter); +app.use('/partners', partnersRouter); +app.use('/playlists', playlistsRouter); +const PORT = process.env.PORT ? Number(process.env.PORT) : 8081; +const HTTPS_PORT = process.env.HTTPS_PORT ? Number(process.env.HTTPS_PORT) : 8082; +// Start HTTP server +app.listen(PORT, () => { + console.log(`API server (HTTP) listening on http://0.0.0.0:${PORT}`); +}); +// Start HTTPS server +try { + const httpsOptions = { + key: fs.readFileSync(path.join(process.cwd(), 'key.pem')), + cert: fs.readFileSync(path.join(process.cwd(), 'cert.pem')) + }; + https.createServer(httpsOptions, app).listen(HTTPS_PORT, () => { + console.log(`API server (HTTPS) listening on https://0.0.0.0:${HTTPS_PORT}`); + }); +} +catch (error) { + console.log('HTTPS server not started - SSL certificates not found'); +} +// Periodic refreshes +const REFRESH_INTERVAL_MS = 2 * 60 * 1000; // full sync +const NOWPLAYING_INTERVAL_MS = 20 * 1000; // capture now playing +setInterval(() => { + try { + const users = db.db.prepare('SELECT id FROM users').all(); + for (const u of users) { + syncUserData(u.id).catch(() => void 0); + } + } + catch (e) { + // ignore timer errors + } +}, REFRESH_INTERVAL_MS); +setInterval(() => { + try { + const users = db.db.prepare('SELECT id FROM users').all(); + for (const u of users) + captureNowPlaying(u.id).catch(() => void 0); + } + catch { } +}, NOWPLAYING_INTERVAL_MS); diff --git a/server/dist/lib/db.js b/server/dist/lib/db.js new file mode 100644 index 0000000..f8eea3f --- /dev/null +++ b/server/dist/lib/db.js @@ -0,0 +1,127 @@ +import Database from 'better-sqlite3'; +import path from 'path'; +import fs from 'fs'; +const DB_PATH = process.env.DB_PATH || path.resolve(process.cwd(), '..', 'spotify.db'); +class DBWrapper { + constructor() { + this.instance = null; + } + get db() { + if (!this.instance) { + this.instance = new Database(DB_PATH); + this.instance.pragma('journal_mode = WAL'); + this.instance.pragma('foreign_keys = ON'); + } + return this.instance; + } + initialize() { + // Ensure file exists + if (!fs.existsSync(DB_PATH)) { + fs.writeFileSync(DB_PATH, ''); + } + const sql = ` + CREATE TABLE IF NOT EXISTS users ( + id TEXT PRIMARY KEY, + display_name TEXT, + email TEXT, + avatar_url TEXT, + country TEXT, + product TEXT, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + access_token TEXT, + refresh_token TEXT, + token_expires_at INTEGER, + last_synced_at INTEGER + ); + + CREATE TABLE IF NOT EXISTS friendships ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_a_id TEXT NOT NULL, + user_b_id TEXT NOT NULL, + created_at INTEGER NOT NULL, + UNIQUE(user_a_id, user_b_id) + ); + + CREATE TABLE IF NOT EXISTS friend_requests ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + from_user_id TEXT NOT NULL, + to_user_id TEXT NOT NULL, + status TEXT NOT NULL CHECK(status IN ('pending','accepted','declined')), + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + UNIQUE(from_user_id, to_user_id) + ); + + CREATE TABLE IF NOT EXISTS recently_played ( + id TEXT PRIMARY KEY, + user_id TEXT NOT NULL, + played_at INTEGER NOT NULL, + track_json TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS top_tracks ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id TEXT NOT NULL, + time_range TEXT NOT NULL, + rank INTEGER NOT NULL, + track_json TEXT NOT NULL, + UNIQUE(user_id, time_range, rank) + ); + + CREATE TABLE IF NOT EXISTS top_artists ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id TEXT NOT NULL, + time_range TEXT NOT NULL, + rank INTEGER NOT NULL, + artist_json TEXT NOT NULL, + UNIQUE(user_id, time_range, rank) + ); + + CREATE TABLE IF NOT EXISTS mixed_playlists ( + id TEXT PRIMARY KEY, + creator_id TEXT NOT NULL, + partner_id TEXT NOT NULL, + name TEXT NOT NULL, + description TEXT, + vibe TEXT, + genres TEXT, -- JSON array of genres + track_uris TEXT, -- JSON array of track URIs + creator_spotify_id TEXT, + partner_spotify_id TEXT, + creator_spotify_url TEXT, + partner_spotify_url TEXT, + creator_spotify_image_url TEXT, + partner_spotify_image_url TEXT, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + FOREIGN KEY (creator_id) REFERENCES users(id), + FOREIGN KEY (partner_id) REFERENCES users(id) + ); + `; + this.db.exec(sql); + // Migrations for existing DBs + try { + const cols = this.db.prepare("PRAGMA table_info(users)").all(); + const hasLastSynced = cols.some(c => c.name === 'last_synced_at'); + if (!hasLastSynced) { + this.db.exec('ALTER TABLE users ADD COLUMN last_synced_at INTEGER'); + } + } + catch { } + // Migration for mixed_playlists table + try { + const playlistCols = this.db.prepare("PRAGMA table_info(mixed_playlists)").all(); + const hasCreatorImageUrl = playlistCols.some(c => c.name === 'creator_spotify_image_url'); + const hasPartnerImageUrl = playlistCols.some(c => c.name === 'partner_spotify_image_url'); + if (!hasCreatorImageUrl) { + this.db.exec('ALTER TABLE mixed_playlists ADD COLUMN creator_spotify_image_url TEXT'); + } + if (!hasPartnerImageUrl) { + this.db.exec('ALTER TABLE mixed_playlists ADD COLUMN partner_spotify_image_url TEXT'); + } + } + catch { } + } +} +export const db = new DBWrapper(); diff --git a/server/dist/lib/events.js b/server/dist/lib/events.js new file mode 100644 index 0000000..ccdf16c --- /dev/null +++ b/server/dist/lib/events.js @@ -0,0 +1,48 @@ +const clientsByUser = new Map(); +export function addSseClient(userId, res) { + const client = { + userId, + res, + write: (payload) => { + try { + res.write(`data: ${JSON.stringify(payload)}\n\n`); + } + catch { } + }, + }; + if (!clientsByUser.has(userId)) + clientsByUser.set(userId, new Set()); + clientsByUser.get(userId).add(client); + // Initial hello + client.write({ type: 'hello', at: Date.now() }); + // Heartbeat to keep connections alive through proxies + const heartbeat = setInterval(() => { + try { + res.write(`: ping\n\n`); + } + catch { } + }, 25000); + // Return cleanup + return () => { + clearInterval(heartbeat); + try { + res.end(); + } + catch { } + clientsByUser.get(userId)?.delete(client); + if (clientsByUser.get(userId)?.size === 0) + clientsByUser.delete(userId); + }; +} +export function sendEvent(userId, event) { + const set = clientsByUser.get(userId); + if (!set || set.size === 0) + return; + for (const client of set) + client.write(event); +} +export function sendToBoth(userA, userB, event) { + sendEvent(userA, event); + if (userB !== userA) + sendEvent(userB, event); +} diff --git a/server/dist/lib/spotify.js b/server/dist/lib/spotify.js new file mode 100644 index 0000000..38ff9db --- /dev/null +++ b/server/dist/lib/spotify.js @@ -0,0 +1,195 @@ +import axios from 'axios'; +import { db } from './db.js'; +import fs from 'fs'; +import path from 'path'; +// Generate a random local playlist cover image URL +function generateRandomPlaylistImage() { + try { + const coversDir = path.join(process.cwd(), 'public', 'playlist-covers'); + // Check if directory exists + if (!fs.existsSync(coversDir)) { + console.log('Playlist covers directory not found, creating it...'); + fs.mkdirSync(coversDir, { recursive: true }); + } + // Get all image files from the directory + const files = fs.readdirSync(coversDir).filter(file => { + const ext = path.extname(file).toLowerCase(); + return ['.jpg', '.jpeg', '.png', '.webp', '.gif'].includes(ext); + }); + if (files.length === 0) { + console.log('No playlist cover images found in public/playlist-covers/'); + return '/api/placeholder-playlist-cover'; + } + // Select a random image + const randomFile = files[Math.floor(Math.random() * files.length)]; + const imageUrl = `/api/playlist-covers/${encodeURIComponent(randomFile)}`; + console.log(`Selected random playlist cover: ${imageUrl}`); + return imageUrl; + } + catch (error) { + console.error('Error generating random playlist image:', error); + return '/api/placeholder-playlist-cover'; + } +} +export function getUserTokens(uid) { + const row = db.db + .prepare('SELECT access_token, refresh_token, token_expires_at FROM users WHERE id = ?') + .get(uid); + if (!row) + return null; + return { + access_token: row.access_token, + refresh_token: row.refresh_token, + token_expires_at: row.token_expires_at, + }; +} +export async function ensureValidAccessToken(uid) { + const tokens = getUserTokens(uid); + if (!tokens?.access_token) { + throw new Error('User not authenticated'); + } + const now = Date.now(); + if (tokens.token_expires_at && tokens.token_expires_at > now + 30000) { + return tokens.access_token; + } + if (!tokens.refresh_token) { + return tokens.access_token; + } + // Refresh token via Spotify + const clientId = process.env.SPOTIFY_CLIENT_ID || ''; + const clientSecret = process.env.SPOTIFY_CLIENT_SECRET || ''; + const resp = await axios.post('https://accounts.spotify.com/api/token', new URLSearchParams({ grant_type: 'refresh_token', refresh_token: tokens.refresh_token }), { + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + Authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`, + }, + }); + const { access_token, expires_in } = resp.data; + const token_expires_at = Date.now() + expires_in * 1000 - 60000; + db.db + .prepare('UPDATE users SET access_token = ?, token_expires_at = ?, updated_at=? WHERE id = ?') + .run(access_token, token_expires_at, Date.now(), uid); + return access_token; +} +export function vibeToTargets(vibe) { + switch (vibe) { + case 'energetic': + return { target_energy: 0.85, target_danceability: 0.7, target_tempo: 130 }; + case 'chill': + return { target_energy: 0.3, target_danceability: 0.4, target_tempo: 90 }; + case 'happy': + return { target_valence: 0.85, target_danceability: 0.6 }; + case 'sad': + return { target_valence: 0.2 }; + case 'party': + return { target_danceability: 0.85, target_energy: 0.8, target_tempo: 125 }; + case 'focus': + return { target_energy: 0.4, target_instrumentalness: 0.5 }; + default: + return {}; + } +} +export async function fetchRecommendations(accessToken, seeds, targets, limit = 25) { + // Legacy kept for compatibility; prefer fetchSimilarTrackUris below + return fetchSimilarTrackUris(accessToken, seeds.seed_tracks, seeds.seed_artists, seeds.seed_genres, targets, limit); +} +export async function createSpotifyPlaylist(accessToken, userId, name, description) { + const resp = await axios.post(`https://api.spotify.com/v1/users/${encodeURIComponent(userId)}/playlists`, { name, description, public: false }, { headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' } }); + const pl = resp.data; + // Generate a random local playlist cover image + const imageUrl = generateRandomPlaylistImage(); + return { id: pl.id, url: pl.external_urls?.spotify, imageUrl }; +} +export async function addTracks(accessToken, playlistId, trackUris) { + if (!trackUris.length) + return; + await axios.post(`https://api.spotify.com/v1/playlists/${encodeURIComponent(playlistId)}/tracks`, { uris: trackUris }, { headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' } }); +} +// ----- New: Similar tracks without recommendations endpoint ----- +async function getRelatedArtists(accessToken, artistId) { + const resp = await axios.get(`https://api.spotify.com/v1/artists/${encodeURIComponent(artistId)}/related-artists`, { + headers: { Authorization: `Bearer ${accessToken}` }, + }); + const artists = (resp.data?.artists || []); + return artists.map(a => a.id).filter(Boolean); +} +async function getArtistTopTracks(accessToken, artistId) { + const resp = await axios.get(`https://api.spotify.com/v1/artists/${encodeURIComponent(artistId)}/top-tracks?market=from_token`, { + headers: { Authorization: `Bearer ${accessToken}` }, + }); + const tracks = (resp.data?.tracks || []); + return tracks.map(t => t.uri || (t.id ? `spotify:track:${t.id}` : null)).filter((u) => !!u); +} +async function searchTracksByGenre(accessToken, genre, limit) { + const resp = await axios.get('https://api.spotify.com/v1/search', { + headers: { Authorization: `Bearer ${accessToken}` }, + params: { q: `genre:"${genre}"`, type: 'track', limit: Math.min(limit, 50) }, + }); + const tracks = (resp.data?.tracks?.items || []); + return tracks.map(t => t.uri || (t.id ? `spotify:track:${t.id}` : null)).filter((u) => !!u); +} +async function filterByTargets(accessToken, trackUris, targets) { + if (!trackUris.length || Object.keys(targets).length === 0) + return trackUris; + const ids = trackUris.map(u => u.split(':').pop()).filter(Boolean); + const resp = await axios.get('https://api.spotify.com/v1/audio-features', { + headers: { Authorization: `Bearer ${accessToken}` }, + params: { ids: ids.slice(0, 100).join(',') }, + }); + const features = (resp.data?.audio_features || []); + const pass = new Set(features + .filter(f => !!f && (!('target_energy' in targets) || Math.abs(targets.target_energy - f.energy) <= 0.4)) + .filter(f => !('target_danceability' in targets) || Math.abs(targets.target_danceability - f.danceability) <= 0.4) + .filter(f => !('target_valence' in targets) || Math.abs(targets.target_valence - f.valence) <= 0.5) + .filter(f => !('target_tempo' in targets) || Math.abs(targets.target_tempo - f.tempo) <= 30) + .filter(f => !('target_instrumentalness' in targets) || Math.abs(targets.target_instrumentalness - f.instrumentalness) <= 0.5) + .map(f => f.id)); + return trackUris.filter(u => pass.has(u.split(':').pop())); +} +export async function fetchSimilarTrackUris(accessToken, seedTrackUris, seedArtistIds, seedGenres, targets = {}, limit = 25) { + const candidateUris = new Set(); + // From seed artists and from artists of seed tracks + const trackIds = (seedTrackUris || []).map(u => u?.split(':').pop()).filter(Boolean); + const seedArtistSet = new Set(seedArtistIds || []); + // If we got tracks, fetch their artists to expand + if (trackIds.length) { + const tracksResp = await axios.get('https://api.spotify.com/v1/tracks', { + headers: { Authorization: `Bearer ${accessToken}` }, + params: { ids: trackIds.slice(0, 50).join(',') }, + }); + const tracks = (tracksResp.data?.tracks || []); + tracks.forEach(t => (t.artists || []).forEach(a => a?.id && seedArtistSet.add(a.id))); + } + // Expand via related artists and take top tracks + const seedArtists = Array.from(seedArtistSet).slice(0, 10); + for (const artistId of seedArtists) { + try { + const related = (await getRelatedArtists(accessToken, artistId)).slice(0, 10); + const pool = [artistId, ...related]; + for (const a of pool) { + const tops = await getArtistTopTracks(accessToken, a); + tops.forEach(u => candidateUris.add(u)); + if (candidateUris.size >= limit * 4) + break; + } + if (candidateUris.size >= limit * 4) + break; + } + catch { } + } + // Genre-based search fallback + for (const g of (seedGenres || []).slice(0, 3)) { + try { + const found = await searchTracksByGenre(accessToken, g, 50); + found.forEach(u => candidateUris.add(u)); + if (candidateUris.size >= limit * 4) + break; + } + catch { } + } + let uris = Array.from(candidateUris); + uris = await filterByTargets(accessToken, uris, targets); + // Shuffle and take limit + uris.sort(() => Math.random() - 0.5); + return uris.slice(0, limit); +} diff --git a/server/dist/lib/sync.js b/server/dist/lib/sync.js new file mode 100644 index 0000000..9f9dda6 --- /dev/null +++ b/server/dist/lib/sync.js @@ -0,0 +1,82 @@ +import axios from 'axios'; +import { db } from './db.js'; +import { ensureValidAccessToken } from './spotify.js'; +export async function syncUserData(uid) { + const accessToken = await ensureValidAccessToken(uid); + const headers = { Authorization: `Bearer ${accessToken}` }; + const [recentResp, topTracksShort, topTracksMed, topArtistsShort, topArtistsMed] = await Promise.all([ + axios.get('https://api.spotify.com/v1/me/player/recently-played?limit=20', { headers }), + axios.get('https://api.spotify.com/v1/me/top/tracks?time_range=short_term&limit=20', { headers }), + axios.get('https://api.spotify.com/v1/me/top/tracks?time_range=medium_term&limit=20', { headers }), + axios.get('https://api.spotify.com/v1/me/top/artists?time_range=short_term&limit=20', { headers }), + axios.get('https://api.spotify.com/v1/me/top/artists?time_range=medium_term&limit=20', { headers }) + ]); + const trx = db.db.transaction(() => { + const rpStmt = db.db.prepare('INSERT OR REPLACE INTO recently_played (id, user_id, played_at, track_json) VALUES (?, ?, ?, ?)'); + for (const item of recentResp.data.items) { + rpStmt.run(item.played_at + ':' + item.track.id, uid, new Date(item.played_at).getTime(), JSON.stringify(item.track)); + } + const ttDel = db.db.prepare('DELETE FROM top_tracks WHERE user_id=? AND time_range=?'); + const ttIns = db.db.prepare('INSERT INTO top_tracks (user_id, time_range, rank, track_json) VALUES (?, ?, ?, ?)'); + for (const [range, payload] of [ + ['short_term', topTracksShort.data], + ['medium_term', topTracksMed.data], + ]) { + ttDel.run(uid, range); + payload.items.forEach((t, idx) => ttIns.run(uid, range, idx + 1, JSON.stringify(t))); + } + const taDel = db.db.prepare('DELETE FROM top_artists WHERE user_id=? AND time_range=?'); + const taIns = db.db.prepare('INSERT INTO top_artists (user_id, time_range, rank, artist_json) VALUES (?, ?, ?, ?)'); + for (const [range, payload] of [ + ['short_term', topArtistsShort.data], + ['medium_term', topArtistsMed.data], + ]) { + taDel.run(uid, range); + payload.items.forEach((a, idx) => taIns.run(uid, range, idx + 1, JSON.stringify(a))); + } + }); + trx(); + db.db.prepare('UPDATE users SET last_synced_at=?, updated_at=? WHERE id=?').run(Date.now(), Date.now(), uid); +} +// Capture the user's current playback and persist as a recent play if changed +export async function captureNowPlaying(uid) { + try { + const accessToken = await ensureValidAccessToken(uid); + const headers = { Authorization: `Bearer ${accessToken}` }; + const resp = await axios.get('https://api.spotify.com/v1/me/player/currently-playing?additional_types=track', { + headers, + validateStatus: () => true, + }); + if (resp.status !== 200) + return; // nothing to record + const data = resp.data; + if (!data?.is_playing || !data?.item) + return; + const track = data.item; + const trackId = track?.id; + if (!trackId) + return; + // Deduplicate: update existing row if same track found recently + const recentRows = db.db.prepare('SELECT id, track_json, played_at FROM recently_played WHERE user_id=? ORDER BY played_at DESC LIMIT 50').all(uid); + for (const row of recentRows) { + try { + const rowTrack = JSON.parse(row.track_json); + if (rowTrack?.id === trackId) { + // If the last record for this track is within 15 minutes, treat as the same session; update timestamp + if (Date.now() - row.played_at < 15 * 60 * 1000) { + db.db.prepare('UPDATE recently_played SET played_at = ?, track_json = ? WHERE id = ?').run(Date.now(), JSON.stringify(track), row.id); + return; + } + break; + } + } + catch { } + } + db.db + .prepare('INSERT INTO recently_played (user_id, played_at, track_json) VALUES (?, ?, ?)') + .run(uid, Date.now(), JSON.stringify(track)); + } + catch { + // ignore errors while capturing now playing to keep background loop robust + } +} diff --git a/server/dist/middleware/auth.js b/server/dist/middleware/auth.js new file mode 100644 index 0000000..0d798b5 --- /dev/null +++ b/server/dist/middleware/auth.js @@ -0,0 +1,19 @@ +import jwt from 'jsonwebtoken'; +const JWT_SECRET = process.env.JWT_SECRET || 'dev-secret-change'; +export function requireAuth(req, res, next) { + const header = req.headers.authorization || ''; + let token = header.startsWith('Bearer ') ? header.slice(7) : null; + // Allow token via query param for SSE EventSource + if (!token && typeof req.query?.token === 'string') + token = String(req.query.token); + if (!token) + return res.status(401).json({ error: 'Missing token' }); + try { + const payload = jwt.verify(token, JWT_SECRET); + req.user = { uid: payload.uid }; + next(); + } + catch { + return res.status(401).json({ error: 'Invalid token' }); + } +} diff --git a/server/dist/routes/auth.js b/server/dist/routes/auth.js new file mode 100644 index 0000000..c23c237 --- /dev/null +++ b/server/dist/routes/auth.js @@ -0,0 +1,91 @@ +import { Router } from 'express'; +import axios from 'axios'; +import jwt from 'jsonwebtoken'; +import { db } from '../lib/db.js'; +export const authRouter = Router(); +const SPOTIFY_CLIENT_ID = process.env.SPOTIFY_CLIENT_ID || ''; +const SPOTIFY_CLIENT_SECRET = process.env.SPOTIFY_CLIENT_SECRET || ''; +const REDIRECT_URI = process.env.REDIRECT_URI || 'http://localhost:3000/callback'; +const JWT_SECRET = process.env.JWT_SECRET || 'dev-secret-change'; +authRouter.post('/exchange', async (req, res) => { + try { + const { code } = req.body; + if (!code) + return res.status(400).json({ error: 'Missing code' }); + const tokenResp = await axios.post('https://accounts.spotify.com/api/token', new URLSearchParams({ + grant_type: 'authorization_code', + code, + redirect_uri: REDIRECT_URI, + }), { + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + Authorization: `Basic ${Buffer.from(`${SPOTIFY_CLIENT_ID}:${SPOTIFY_CLIENT_SECRET}`).toString('base64')}`, + }, + }); + const { access_token, refresh_token, expires_in } = tokenResp.data; + const meResp = await axios.get('https://api.spotify.com/v1/me', { + headers: { Authorization: `Bearer ${access_token}` }, + }); + const profile = meResp.data; + const now = Date.now(); + const tokenExpiresAt = now + expires_in * 1000 - 60000; // refresh a bit early + db.db + .prepare(`INSERT INTO users (id, display_name, email, avatar_url, country, product, created_at, updated_at, access_token, refresh_token, token_expires_at) + VALUES (@id, @display_name, @email, @avatar_url, @country, @product, @created_at, @updated_at, @access_token, @refresh_token, @token_expires_at) + ON CONFLICT(id) DO UPDATE SET + display_name=excluded.display_name, + email=excluded.email, + avatar_url=excluded.avatar_url, + country=excluded.country, + product=excluded.product, + updated_at=excluded.updated_at, + access_token=excluded.access_token, + refresh_token=excluded.refresh_token, + token_expires_at=excluded.token_expires_at`) + .run({ + id: profile.id, + display_name: profile.display_name, + email: profile.email, + avatar_url: profile.images?.[0]?.url || null, + country: profile.country, + product: profile.product, + created_at: now, + updated_at: now, + access_token, + refresh_token, + token_expires_at: tokenExpiresAt, + }); + const jwtToken = jwt.sign({ uid: profile.id }, JWT_SECRET, { expiresIn: '30d' }); + // Return Spotify tokens to enable client-side playback controls + res.json({ token: jwtToken, uid: profile.id, access_token, refresh_token, expires_in }); + } + catch (err) { + const detail = err?.response?.data || err?.message || 'Unknown error'; + console.error('Auth exchange error:', detail); + res.status(500).json({ error: 'Auth exchange failed', detail }); + } +}); +authRouter.post('/refresh', async (req, res) => { + try { + const { uid } = req.body; + if (!uid) + return res.status(400).json({ error: 'Missing uid' }); + const row = db.db.prepare('SELECT refresh_token FROM users WHERE id = ?').get(uid); + if (!row?.refresh_token) + return res.status(404).json({ error: 'User not found' }); + const tokenResp = await axios.post('https://accounts.spotify.com/api/token', new URLSearchParams({ grant_type: 'refresh_token', refresh_token: row.refresh_token }), { + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + Authorization: `Basic ${Buffer.from(`${SPOTIFY_CLIENT_ID}:${SPOTIFY_CLIENT_SECRET}`).toString('base64')}`, + }, + }); + const { access_token, expires_in } = tokenResp.data; + const tokenExpiresAt = Date.now() + expires_in * 1000 - 60000; + db.db.prepare('UPDATE users SET access_token=?, token_expires_at=?, updated_at=? WHERE id=?').run(access_token, tokenExpiresAt, Date.now(), uid); + res.json({ ok: true }); + } + catch (err) { + console.error(err.response?.data || err.message); + res.status(500).json({ error: 'Refresh failed' }); + } +}); diff --git a/server/dist/routes/partners.js b/server/dist/routes/partners.js new file mode 100644 index 0000000..f0c553e --- /dev/null +++ b/server/dist/routes/partners.js @@ -0,0 +1,172 @@ +import { Router } from 'express'; +import { db } from '../lib/db.js'; +import { addSseClient, sendEvent, sendToBoth } from '../lib/events.js'; +import { requireAuth } from '../middleware/auth.js'; +export const partnersRouter = Router(); +// Send a partner request (not via link) by target uid +partnersRouter.post('/request', requireAuth, (req, res) => { + const { toUid } = req.body; + const fromUid = req.user?.uid; + if (!fromUid || !toUid || fromUid === toUid) + return res.status(400).json({ error: 'Invalid uids' }); + const now = Date.now(); + try { + db.db + .prepare(`INSERT INTO friend_requests (from_user_id, to_user_id, status, created_at, updated_at) + VALUES (?, ?, 'pending', ?, ?)`) + .run(fromUid, toUid, now, now); + // Notify the recipient about a new incoming request + sendEvent(toUid, { type: 'partner:request', fromUserId: fromUid, at: now }); + res.json({ ok: true }); + } + catch (e) { + if (e && String(e.message).includes('UNIQUE')) { + return res.status(409).json({ error: 'Request already exists' }); + } + throw e; + } +}); +// List incoming requests for a user +partnersRouter.get('/requests/:uid', requireAuth, (req, res) => { + const { uid } = req.params; + if (!req.user || req.user.uid !== uid) + return res.status(403).json({ error: 'Forbidden' }); + const rows = db.db + .prepare("SELECT id, from_user_id, to_user_id, status, created_at FROM friend_requests WHERE to_user_id = ? AND status = 'pending' ORDER BY created_at DESC") + .all(uid); + res.json(rows); +}); +// Accept a request +partnersRouter.post('/requests/:id/accept', requireAuth, (req, res) => { + const { id } = req.params; + const reqRow = db.db.prepare('SELECT * FROM friend_requests WHERE id = ?').get(id); + if (!reqRow) + return res.status(404).json({ error: 'Not found' }); + if (!req.user || req.user.uid !== reqRow.to_user_id) + return res.status(403).json({ error: 'Forbidden' }); + const now = Date.now(); + const userA = reqRow.from_user_id < reqRow.to_user_id ? reqRow.from_user_id : reqRow.to_user_id; + const userB = reqRow.from_user_id < reqRow.to_user_id ? reqRow.to_user_id : reqRow.from_user_id; + const txn = db.db.transaction(() => { + db.db.prepare("UPDATE friend_requests SET status='accepted', updated_at=? WHERE id=?").run(now, id); + db.db.prepare('INSERT OR IGNORE INTO friendships (user_a_id, user_b_id, created_at) VALUES (?, ?, ?)').run(userA, userB, now); + }); + txn(); + // Notify both users of partnership established + sendToBoth(userA, userB, { type: 'partner:connected', a: userA, b: userB, at: now }); + res.json({ ok: true }); +}); +// Decline a request +partnersRouter.post('/requests/:id/decline', requireAuth, (req, res) => { + const { id } = req.params; + const now = Date.now(); + const reqRow = db.db.prepare('SELECT * FROM friend_requests WHERE id = ?').get(id); + if (!reqRow) + return res.status(404).json({ error: 'Not found' }); + if (!req.user || req.user.uid !== reqRow.to_user_id) + return res.status(403).json({ error: 'Forbidden' }); + db.db.prepare("UPDATE friend_requests SET status='declined', updated_at=? WHERE id=?").run(now, id); + // Notify requester that their request was declined + sendEvent(reqRow.from_user_id, { type: 'partner:declined', byUserId: reqRow.to_user_id, requestId: reqRow.id, at: now }); + res.json({ ok: true }); +}); +// Check partnership between two users +partnersRouter.get('/status', (req, res) => { + const { a, b } = req.query; + if (!a || !b) + return res.status(400).json({ error: 'Missing params' }); + const [userA, userB] = a < b ? [a, b] : [b, a]; + const exists = db.db + .prepare('SELECT 1 FROM friendships WHERE user_a_id=? AND user_b_id=?') + .get(userA, userB); + res.json({ partnered: !!exists }); +}); +// Fetch partner for a user (if any) +partnersRouter.get('/partner/:uid', requireAuth, (req, res) => { + const { uid } = req.params; + if (!req.user || req.user.uid !== uid) + return res.status(403).json({ error: 'Forbidden' }); + const row = db.db + .prepare(`SELECT CASE WHEN user_a_id = ? THEN user_b_id ELSE user_a_id END as partner_id + FROM friendships + WHERE user_a_id = ? OR user_b_id = ? + LIMIT 1`) + .get(uid, uid, uid); + if (!row?.partner_id) + return res.json({ partnerId: null }); + return res.json({ partnerId: row.partner_id }); +}); +// SSE: subscribe to partner events for authed user +partnersRouter.get('/events/:uid', requireAuth, (req, res) => { + const { uid } = req.params; + if (!req.user || req.user.uid !== uid) + return res.status(403).json({ error: 'Forbidden' }); + res.setHeader('Content-Type', 'text/event-stream'); + res.setHeader('Cache-Control', 'no-cache'); + res.setHeader('Connection', 'keep-alive'); + res.flushHeaders?.(); + const cleanup = addSseClient(uid, res); + req.on('close', cleanup); +}); +// Remove an existing partnership between the authed user and a specific partner +partnersRouter.post('/remove', requireAuth, (req, res) => { + const { partnerId } = req.body; + const uid = req.user?.uid; + if (!uid || !partnerId || uid === partnerId) + return res.status(400).json({ error: 'Invalid partnerId' }); + const userA = uid < partnerId ? uid : partnerId; + const userB = uid < partnerId ? partnerId : uid; + const existing = db.db + .prepare('SELECT id FROM friendships WHERE user_a_id=? AND user_b_id=?') + .get(userA, userB); + if (!existing?.id) + return res.status(404).json({ error: 'No active partnership' }); + try { + const txn = db.db.transaction(() => { + db.db.prepare('DELETE FROM friendships WHERE user_a_id=? AND user_b_id=?').run(userA, userB); + // Remove any historical or pending requests between the two users so they can re-invite + db.db + .prepare('DELETE FROM friend_requests WHERE (from_user_id=? AND to_user_id=?) OR (from_user_id=? AND to_user_id=?)') + .run(uid, partnerId, partnerId, uid); + }); + txn(); + // Notify both users of disconnection + sendToBoth(userA, userB, { type: 'partner:disconnected', a: userA, b: userB, at: Date.now() }); + return res.json({ ok: true }); + } + catch (e) { + return res.status(500).json({ error: 'Failed to remove partnership' }); + } +}); +// Clear any existing partnership for the authed user (fallback helper) +partnersRouter.post('/clear', requireAuth, (req, res) => { + const { userId } = req.body; + const uid = req.user?.uid; + if (!uid || !userId || uid !== userId) + return res.status(403).json({ error: 'Forbidden' }); + try { + // Find all partners (normally only one) and delete links + requests + const partners = db.db + .prepare('SELECT CASE WHEN user_a_id = ? THEN user_b_id ELSE user_a_id END as partner_id FROM friendships WHERE user_a_id = ? OR user_b_id = ?') + .all(uid, uid, uid); + const txn = db.db.transaction(() => { + db.db.prepare('DELETE FROM friendships WHERE user_a_id=? OR user_b_id=?').run(uid, uid); + for (const row of partners) { + db.db + .prepare('DELETE FROM friend_requests WHERE (from_user_id=? AND to_user_id=?) OR (from_user_id=? AND to_user_id=?)') + .run(uid, row.partner_id, row.partner_id, uid); + } + }); + txn(); + // Notify the user and any former partners + for (const row of partners) { + const a = uid < row.partner_id ? uid : row.partner_id; + const b = uid < row.partner_id ? row.partner_id : uid; + sendToBoth(a, b, { type: 'partner:disconnected', a, b, at: Date.now() }); + } + return res.json({ ok: true }); + } + catch (e) { + return res.status(500).json({ error: 'Failed to clear partnership' }); + } +}); diff --git a/server/dist/routes/playlists.js b/server/dist/routes/playlists.js new file mode 100644 index 0000000..45f9738 --- /dev/null +++ b/server/dist/routes/playlists.js @@ -0,0 +1,185 @@ +import { Router } from 'express'; +import { requireAuth } from '../middleware/auth.js'; +import { addTracks, createSpotifyPlaylist, ensureValidAccessToken, fetchRecommendations, vibeToTargets } from '../lib/spotify.js'; +import { db } from '../lib/db.js'; +import { v4 as uuidv4 } from 'uuid'; +export const playlistsRouter = Router(); +// Helper function to generate unique playlist names +function generateUniquePlaylistName() { + const adjectives = ['Vibrant', 'Melodic', 'Harmonic', 'Rhythmic', 'Ethereal', 'Dynamic', 'Soulful', 'Electric', 'Acoustic', 'Cosmic', 'Urban', 'Chill', 'Energetic', 'Dreamy', 'Funky']; + const nouns = ['Fusion', 'Symphony', 'Vibes', 'Journey', 'Harmony', 'Blend', 'Mix', 'Soundscape', 'Melody', 'Rhythm', 'Groove', 'Beat', 'Tune', 'Sound', 'Wave']; + const adjective = adjectives[Math.floor(Math.random() * adjectives.length)]; + const noun = nouns[Math.floor(Math.random() * nouns.length)]; + const timestamp = new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric' }); + return `${adjective} ${noun} - ${timestamp}`; +} +// GET /playlists/mixed - Get all mixed playlists for a user +playlistsRouter.get('/mixed', requireAuth, async (req, res) => { + try { + const userId = req.user.uid; + const playlists = db.db.prepare(` + SELECT * FROM mixed_playlists + WHERE creator_id = ? OR partner_id = ? + ORDER BY created_at DESC + `).all(userId, userId); + res.json({ playlists }); + } + catch (err) { + console.error('Failed to fetch mixed playlists:', err); + res.status(500).json({ error: 'Failed to fetch playlists' }); + } +}); +// DELETE /playlists/mixed/:id - Delete a mixed playlist +playlistsRouter.delete('/mixed/:id', requireAuth, async (req, res) => { + try { + const userId = req.user.uid; + const playlistId = req.params.id; + // Check if user owns this playlist + const playlist = db.db.prepare('SELECT * FROM mixed_playlists WHERE id = ? AND (creator_id = ? OR partner_id = ?)').get(playlistId, userId, userId); + if (!playlist) { + return res.status(404).json({ error: 'Playlist not found' }); + } + // Delete from database + db.db.prepare('DELETE FROM mixed_playlists WHERE id = ?').run(playlistId); + res.json({ success: true }); + } + catch (err) { + console.error('Failed to delete playlist:', err); + res.status(500).json({ error: 'Failed to delete playlist' }); + } +}); +// POST /playlists/mixed +// body: { name?: string, description?: string, vibe?: string, genres?: string[], includeKnown?: boolean, partnerId?: string, createForBoth?: boolean, limit?: number } +playlistsRouter.post('/mixed', requireAuth, async (req, res) => { + try { + const creatorId = req.user.uid; + const { name, description, vibe, genres, includeKnown = true, partnerId, createForBoth = false, limit = 25 } = req.body || {}; + if (!partnerId) + return res.status(400).json({ error: 'partnerId required' }); + // Collect seeds from both users' top tracks + const seedRows1 = db.db.prepare('SELECT track_json FROM top_tracks WHERE user_id=? AND time_range=? ORDER BY rank ASC LIMIT 20').all(creatorId, 'short_term'); + const seedRows2 = db.db.prepare('SELECT track_json FROM top_tracks WHERE user_id=? AND time_range=? ORDER BY rank ASC LIMIT 20').all(partnerId, 'short_term'); + const tracks1 = seedRows1.map((r) => JSON.parse(r.track_json)); + const tracks2 = seedRows2.map((r) => JSON.parse(r.track_json)); + let seedTrackUris = [...tracks1, ...tracks2] + .map((t) => t.uri || (t.id ? `spotify:track:${t.id}` : null)) + .filter((u) => !!u); + // Fallback to artist seeds if track seeds are empty + let seedArtistIds = []; + if (seedTrackUris.length === 0) { + const artistIds = [...tracks1, ...tracks2] + .flatMap((t) => t.artists || []) + .map((a) => a?.id) + .filter((id) => !!id); + seedArtistIds = Array.from(new Set(artistIds)); + } + // Use at most 5 seeds of each type + seedTrackUris = seedTrackUris.slice(0, 5); + seedArtistIds = seedArtistIds.slice(0, 5); + const creatorToken = await ensureValidAccessToken(creatorId); + const targets = vibeToTargets(vibe); + // Always provide fallback genres if none specified + let finalGenres = genres; + if (!Array.isArray(genres) || genres.length === 0) { + // Analyze users' top tracks to determine appropriate genres + const allTracks = [...tracks1, ...tracks2]; + const genreCounts = {}; + // Count genres from top tracks + allTracks.forEach(track => { + if (track.artists && track.artists.length > 0) { + // Use common genres based on artist analysis + // This is a simplified approach - in a real implementation, you'd analyze track features + genreCounts['pop'] = (genreCounts['pop'] || 0) + 1; + genreCounts['rock'] = (genreCounts['rock'] || 0) + 1; + genreCounts['indie'] = (genreCounts['indie'] || 0) + 1; + genreCounts['alternative'] = (genreCounts['alternative'] || 0) + 1; + } + }); + // Use top genres or fallback to popular ones + const sortedGenres = Object.entries(genreCounts) + .sort(([, a], [, b]) => b - a) + .map(([genre]) => genre) + .slice(0, 4); + finalGenres = sortedGenres.length > 0 ? sortedGenres : ['pop', 'rock', 'indie', 'alternative']; + console.log('Using fallback genres:', finalGenres, 'based on track analysis'); + } + const recommendedUris = await fetchRecommendations(creatorToken, { + seed_tracks: seedTrackUris.length ? seedTrackUris : undefined, + seed_artists: seedArtistIds.length ? seedArtistIds : undefined, + seed_genres: finalGenres, + }, targets, limit); + // Optionally remove already listened tracks for both users (recently played) + let finalUris = recommendedUris; + if (!includeKnown) { + const recents1 = db.db.prepare('SELECT track_json FROM recently_played WHERE user_id=? ORDER BY played_at DESC LIMIT 100').all(creatorId); + const recents2 = db.db.prepare('SELECT track_json FROM recently_played WHERE user_id=? ORDER BY played_at DESC LIMIT 100').all(partnerId); + const recentUris = new Set([...recents1, ...recents2] + .map((r) => JSON.parse(r.track_json)) + .map((t) => t.uri || (t.id ? `spotify:track:${t.id}` : null)) + .filter((u) => !!u)); + finalUris = recommendedUris.filter((u) => !recentUris.has(u)); + } + // Generate unique playlist name if not provided + const playlistName = name || generateUniquePlaylistName(); + const playlistDesc = description || 'An AI-blended mix with fresh recommendations'; + // Always create for the creator + const creatorProfile = db.db.prepare('SELECT id FROM users WHERE id=?').get(creatorId); + const { id: creatorPlaylistId, url: creatorUrl, imageUrl: creatorImageUrl } = await createSpotifyPlaylist(creatorToken, creatorProfile.id, playlistName, playlistDesc); + await addTracks(creatorToken, creatorPlaylistId, finalUris); + let partnerResult = {}; + if (createForBoth) { + try { + const partnerToken = await ensureValidAccessToken(partnerId); + const partnerProfile = db.db.prepare('SELECT id FROM users WHERE id=?').get(partnerId); + if (!partnerProfile) { + throw new Error('Partner user not found'); + } + const partnerPlaylist = await createSpotifyPlaylist(partnerToken, partnerProfile.id, playlistName, playlistDesc); + partnerResult = partnerPlaylist; + await addTracks(partnerToken, partnerResult.id, finalUris); + console.log(`Successfully created partner playlist: ${partnerResult.id}`); + } + catch (e) { + // Partner creation may fail (revoked consent, user not found, etc.); still return creator playlist + const errorMessage = e?.response?.data?.error?.message || e?.message || 'Unknown error'; + console.error('Partner playlist creation failed:', errorMessage); + partnerResult.error = errorMessage; + } + } + // Save playlist to database + const playlistId = uuidv4(); + const now = Date.now(); + console.log('Saving playlist to database:', { + id: playlistId, + name: playlistName, + trackCount: finalUris.length, + trackUris: finalUris.slice(0, 3) // Log first 3 URIs for debugging + }); + db.db.prepare(` + INSERT INTO mixed_playlists ( + id, creator_id, partner_id, name, description, vibe, genres, + track_uris, creator_spotify_id, partner_spotify_id, + creator_spotify_url, partner_spotify_url, creator_spotify_image_url, partner_spotify_image_url, + created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `).run(playlistId, creatorId, partnerId, playlistName, playlistDesc, vibe || null, JSON.stringify(genres || []), JSON.stringify(finalUris), creatorPlaylistId, partnerResult.id || null, creatorUrl, partnerResult.url || null, creatorImageUrl || null, partnerResult.imageUrl || null, now, now); + res.json({ + id: playlistId, + name: playlistName, + description: playlistDesc, + trackUris: finalUris, + spotifyImageUrl: creatorImageUrl, + createdFor: { + creator: { playlistId: creatorPlaylistId, url: creatorUrl }, + partner: partnerResult.id ? { playlistId: partnerResult.id, url: partnerResult.url } : null, + partnerError: partnerResult.error || null, + }, + added: finalUris.length, + }); + } + catch (err) { + const detail = err?.response?.data || err?.message || 'Unknown error'; + console.error('Mixed playlist error:', detail); + res.status(500).json({ error: 'Failed to create mixed playlist', detail }); + } +}); diff --git a/server/dist/routes/users.js b/server/dist/routes/users.js new file mode 100644 index 0000000..3ddd1ab --- /dev/null +++ b/server/dist/routes/users.js @@ -0,0 +1,128 @@ +import { Router } from 'express'; +import { db } from '../lib/db.js'; +import axios from 'axios'; +import { requireAuth } from '../middleware/auth.js'; +import { syncUserData } from '../lib/sync.js'; +import { ensureValidAccessToken } from '../lib/spotify.js'; +export const usersRouter = Router(); +// Fetch and store user data (recently played, top tracks/artists) +usersRouter.post('/:uid/sync', requireAuth, async (req, res) => { + try { + const { uid } = req.params; + if (!req.user || req.user.uid !== uid) + return res.status(403).json({ error: 'Forbidden' }); + await syncUserData(uid); + res.json({ ok: true }); + } + catch (err) { + console.error(err.response?.data || err.message); + res.status(500).json({ error: 'Sync failed' }); + } +}); +usersRouter.get('/:uid', (req, res) => { + const { uid } = req.params; + const user = db.db.prepare('SELECT id, display_name, email, avatar_url, country, product, created_at, updated_at, last_synced_at FROM users WHERE id = ?').get(uid); + if (!user) + return res.status(404).json({ error: 'Not found' }); + res.json(user); +}); +// Simple search by display_name (substring, case-insensitive) +usersRouter.get('/search/q', (req, res) => { + const q = String(req.query.q || '').trim(); + if (!q) + return res.json([]); + const rows = db.db + .prepare('SELECT id, display_name, avatar_url FROM users WHERE lower(display_name) LIKE ? LIMIT 20') + .all(`%${q.toLowerCase()}%`); + res.json(rows); +}); +usersRouter.get('/:uid/recently-played', (req, res) => { + const { uid } = req.params; + const rows = db.db.prepare('SELECT id, user_id, played_at, track_json FROM recently_played WHERE user_id = ? ORDER BY played_at DESC LIMIT 50').all(uid); + res.json(rows.map((r) => ({ id: r.id, user_id: r.user_id, played_at: r.played_at, track: JSON.parse(r.track_json) }))); +}); +usersRouter.get('/:uid/top-tracks', (req, res) => { + const { uid } = req.params; + const range = req.query.time_range || 'short_term'; + const rows = db.db.prepare('SELECT rank, track_json FROM top_tracks WHERE user_id = ? AND time_range = ? ORDER BY rank ASC').all(uid, range); + res.json(rows.map((r) => ({ rank: r.rank, track: JSON.parse(r.track_json) }))); +}); +usersRouter.get('/:uid/top-artists', (req, res) => { + const { uid } = req.params; + const range = req.query.time_range || 'short_term'; + const rows = db.db.prepare('SELECT rank, artist_json FROM top_artists WHERE user_id = ? AND time_range = ? ORDER BY rank ASC').all(uid, range); + res.json(rows.map((r) => ({ rank: r.rank, artist: JSON.parse(r.artist_json) }))); +}); +// status: last sync time and next scheduled time (based on 10 min interval) +usersRouter.get('/:uid/status', (req, res) => { + const { uid } = req.params; + const row = db.db.prepare('SELECT last_synced_at FROM users WHERE id = ?').get(uid); + const last = row?.last_synced_at || null; + // Match backend full sync interval (2 minutes) + const next = last ? last + 2 * 60 * 1000 : null; + res.json({ lastSyncedAt: last, nextSyncAt: next }); +}); +// Now playing (with token refresh) +usersRouter.get('/:uid/now-playing', requireAuth, async (req, res) => { + try { + const { uid } = req.params; + if (!req.user) + return res.status(403).json({ error: 'Forbidden' }); + if (req.user.uid !== uid) { + // allow if users are partnered + const paired = db.db.prepare('SELECT 1 FROM friendships WHERE (user1_id=? AND user2_id=?) OR (user1_id=? AND user2_id=?)').get(req.user.uid, uid, uid, req.user.uid); + if (!paired) + return res.status(403).json({ error: 'Forbidden' }); + } + // Try DB-captured snapshot first (last 60s) + const recent = db.db.prepare('SELECT played_at, track_json FROM recently_played WHERE user_id=? ORDER BY played_at DESC LIMIT 1').get(uid); + if (recent?.played_at && Date.now() - recent.played_at < 60000 && recent?.track_json) { + try { + const item = JSON.parse(recent.track_json); + return res.json({ is_playing: true, item, source: 'db' }); + } + catch { } + } + const accessToken = await ensureValidAccessToken(uid); + const resp = await axios.get('https://api.spotify.com/v1/me/player/currently-playing?additional_types=track', { + headers: { Authorization: `Bearer ${accessToken}` }, + validateStatus: () => true, + }); + if (resp.status === 204) + return res.json({ is_playing: false }); + if (resp.status >= 400) { + // Return a benign payload rather than 500 to avoid breaking UI when Spotify returns errors + return res.json({ is_playing: false }); + } + return res.status(200).json(resp.data); + } + catch (e) { + res.status(200).json({ is_playing: false }); + } +}); +// Audio features bulk +usersRouter.get('/:uid/audio-features', requireAuth, async (req, res) => { + try { + const { uid } = req.params; + const ids = String(req.query.ids || '').split(',').map(s => s.trim()).filter(Boolean); + if (!req.user) + return res.status(403).json({ error: 'Forbidden' }); + if (req.user.uid !== uid) { + const paired = db.db.prepare('SELECT 1 FROM friendships WHERE (user1_id=? AND user2_id=?) OR (user1_id=? AND user2_id=?)').get(req.user.uid, uid, uid, req.user.uid); + if (!paired) + return res.status(403).json({ error: 'Forbidden' }); + } + if (!ids.length) + return res.json({ audio_features: [] }); + const accessToken = await ensureValidAccessToken(uid); + // Some tracks may be local or missing features; handle gracefully + const resp = await axios.get('https://api.spotify.com/v1/audio-features', { + headers: { Authorization: `Bearer ${accessToken}` }, + params: { ids: ids.slice(0, 100).join(',') }, + }); + res.json({ audio_features: Array.isArray(resp.data?.audio_features) ? resp.data.audio_features.filter(Boolean) : [] }); + } + catch (e) { + res.status(500).json({ error: 'Failed to fetch audio features', detail: e?.response?.data || e?.message }); + } +}); diff --git a/server/node_modules/.bin/uuid b/server/node_modules/.bin/uuid new file mode 120000 index 0000000..a0e681c --- /dev/null +++ b/server/node_modules/.bin/uuid @@ -0,0 +1 @@ +../uuid/dist-node/bin/uuid \ No newline at end of file diff --git a/server/node_modules/.package-lock.json b/server/node_modules/.package-lock.json index 0183561..3777df8 100644 --- a/server/node_modules/.package-lock.json +++ b/server/node_modules/.package-lock.json @@ -21,6 +21,63 @@ "node": ">=18" } }, + "node_modules/@img/colour": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.0.0.tgz", + "integrity": "sha512-A5P/LfWGFSl6nsckYtjw9da+19jB8hkJ6ACTGcDfEJ0aE+l2n2El7dsVM7UVHZQ9s2lmYMWlrS21YLy2IR1LUw==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.3.tgz", + "integrity": "sha512-3JU7LmR85K6bBiRzSUc/Ff9JBVIFVvq6bomKE0e63UXGeRw2HPVEjoJke1Yx+iU4rL7/7kUjES4dZ/81Qjhyxg==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.4.tgz", + "integrity": "sha512-ZfGtcp2xS51iG79c6Vhw9CWqQC8l2Ot8dygxoDoIQPTat/Ov3qAa8qpxSrtAEAJW+UjTXc4yxCjNfxm4h6Xm2A==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.2.3" + } + }, + "node_modules/@types/better-sqlite3": { + "version": "7.6.13", + "resolved": "https://registry.npmjs.org/@types/better-sqlite3/-/better-sqlite3-7.6.13.tgz", + "integrity": "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/body-parser": { "version": "1.19.6", "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", @@ -177,6 +234,12 @@ "@types/node": "*" } }, + "node_modules/@types/uuid": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz", + "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==", + "license": "MIT" + }, "node_modules/accepts": { "version": "1.3.8", "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", @@ -1550,6 +1613,48 @@ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", "license": "ISC" }, + "node_modules/sharp": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.4.tgz", + "integrity": "sha512-FUH39xp3SBPnxWvd5iib1X8XY7J0K0X7d93sie9CJg2PO8/7gmg89Nve6OjItK53/MlAushNNxteBYfM6DEuoA==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.0.0", + "detect-libc": "^2.1.0", + "semver": "^7.7.2" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.34.4", + "@img/sharp-darwin-x64": "0.34.4", + "@img/sharp-libvips-darwin-arm64": "1.2.3", + "@img/sharp-libvips-darwin-x64": "1.2.3", + "@img/sharp-libvips-linux-arm": "1.2.3", + "@img/sharp-libvips-linux-arm64": "1.2.3", + "@img/sharp-libvips-linux-ppc64": "1.2.3", + "@img/sharp-libvips-linux-s390x": "1.2.3", + "@img/sharp-libvips-linux-x64": "1.2.3", + "@img/sharp-libvips-linuxmusl-arm64": "1.2.3", + "@img/sharp-libvips-linuxmusl-x64": "1.2.3", + "@img/sharp-linux-arm": "0.34.4", + "@img/sharp-linux-arm64": "0.34.4", + "@img/sharp-linux-ppc64": "0.34.4", + "@img/sharp-linux-s390x": "0.34.4", + "@img/sharp-linux-x64": "0.34.4", + "@img/sharp-linuxmusl-arm64": "0.34.4", + "@img/sharp-linuxmusl-x64": "0.34.4", + "@img/sharp-wasm32": "0.34.4", + "@img/sharp-win32-arm64": "0.34.4", + "@img/sharp-win32-ia32": "0.34.4", + "@img/sharp-win32-x64": "0.34.4" + } + }, "node_modules/side-channel": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", @@ -1821,6 +1926,19 @@ "node": ">= 0.4.0" } }, + "node_modules/uuid": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-13.0.0.tgz", + "integrity": "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist-node/bin/uuid" + } + }, "node_modules/vary": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", diff --git a/server/node_modules/@img/colour/LICENSE.md b/server/node_modules/@img/colour/LICENSE.md new file mode 100644 index 0000000..292c550 --- /dev/null +++ b/server/node_modules/@img/colour/LICENSE.md @@ -0,0 +1,82 @@ +# Licensing + +## color + +Copyright (c) 2012 Heather Arthur + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +## color-convert + +Copyright (c) 2011-2016 Heather Arthur . +Copyright (c) 2016-2021 Josh Junon . + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +## color-string + +Copyright (c) 2011 Heather Arthur + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +## color-name + +The MIT License (MIT) +Copyright (c) 2015 Dmitry Ivanov + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/server/node_modules/@img/colour/README.md b/server/node_modules/@img/colour/README.md new file mode 100644 index 0000000..a33e4eb --- /dev/null +++ b/server/node_modules/@img/colour/README.md @@ -0,0 +1,15 @@ +# `@img/colour` + +The latest version of the +[color](https://www.npmjs.com/package/color) +package is now ESM-only, +however some JavaScript runtimes do not yet support this, +which includes versions of Node.js prior to 20.19.0. + +This package converts the `color` package and its dependencies, +all of which are MIT-licensed, to CommonJS. + +- [color](https://www.npmjs.com/package/color) +- [color-convert](https://www.npmjs.com/package/color-convert) +- [color-string](https://www.npmjs.com/package/color-string) +- [color-name](https://www.npmjs.com/package/color-name) diff --git a/server/node_modules/@img/colour/color.cjs b/server/node_modules/@img/colour/color.cjs new file mode 100644 index 0000000..ac055fa --- /dev/null +++ b/server/node_modules/@img/colour/color.cjs @@ -0,0 +1,1594 @@ +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// node_modules/color/index.js +var index_exports = {}; +__export(index_exports, { + default: () => index_default +}); +module.exports = __toCommonJS(index_exports); + +// node_modules/color-name/index.js +var color_name_default = { + aliceblue: [240, 248, 255], + antiquewhite: [250, 235, 215], + aqua: [0, 255, 255], + aquamarine: [127, 255, 212], + azure: [240, 255, 255], + beige: [245, 245, 220], + bisque: [255, 228, 196], + black: [0, 0, 0], + blanchedalmond: [255, 235, 205], + blue: [0, 0, 255], + blueviolet: [138, 43, 226], + brown: [165, 42, 42], + burlywood: [222, 184, 135], + cadetblue: [95, 158, 160], + chartreuse: [127, 255, 0], + chocolate: [210, 105, 30], + coral: [255, 127, 80], + cornflowerblue: [100, 149, 237], + cornsilk: [255, 248, 220], + crimson: [220, 20, 60], + cyan: [0, 255, 255], + darkblue: [0, 0, 139], + darkcyan: [0, 139, 139], + darkgoldenrod: [184, 134, 11], + darkgray: [169, 169, 169], + darkgreen: [0, 100, 0], + darkgrey: [169, 169, 169], + darkkhaki: [189, 183, 107], + darkmagenta: [139, 0, 139], + darkolivegreen: [85, 107, 47], + darkorange: [255, 140, 0], + darkorchid: [153, 50, 204], + darkred: [139, 0, 0], + darksalmon: [233, 150, 122], + darkseagreen: [143, 188, 143], + darkslateblue: [72, 61, 139], + darkslategray: [47, 79, 79], + darkslategrey: [47, 79, 79], + darkturquoise: [0, 206, 209], + darkviolet: [148, 0, 211], + deeppink: [255, 20, 147], + deepskyblue: [0, 191, 255], + dimgray: [105, 105, 105], + dimgrey: [105, 105, 105], + dodgerblue: [30, 144, 255], + firebrick: [178, 34, 34], + floralwhite: [255, 250, 240], + forestgreen: [34, 139, 34], + fuchsia: [255, 0, 255], + gainsboro: [220, 220, 220], + ghostwhite: [248, 248, 255], + gold: [255, 215, 0], + goldenrod: [218, 165, 32], + gray: [128, 128, 128], + green: [0, 128, 0], + greenyellow: [173, 255, 47], + grey: [128, 128, 128], + honeydew: [240, 255, 240], + hotpink: [255, 105, 180], + indianred: [205, 92, 92], + indigo: [75, 0, 130], + ivory: [255, 255, 240], + khaki: [240, 230, 140], + lavender: [230, 230, 250], + lavenderblush: [255, 240, 245], + lawngreen: [124, 252, 0], + lemonchiffon: [255, 250, 205], + lightblue: [173, 216, 230], + lightcoral: [240, 128, 128], + lightcyan: [224, 255, 255], + lightgoldenrodyellow: [250, 250, 210], + lightgray: [211, 211, 211], + lightgreen: [144, 238, 144], + lightgrey: [211, 211, 211], + lightpink: [255, 182, 193], + lightsalmon: [255, 160, 122], + lightseagreen: [32, 178, 170], + lightskyblue: [135, 206, 250], + lightslategray: [119, 136, 153], + lightslategrey: [119, 136, 153], + lightsteelblue: [176, 196, 222], + lightyellow: [255, 255, 224], + lime: [0, 255, 0], + limegreen: [50, 205, 50], + linen: [250, 240, 230], + magenta: [255, 0, 255], + maroon: [128, 0, 0], + mediumaquamarine: [102, 205, 170], + mediumblue: [0, 0, 205], + mediumorchid: [186, 85, 211], + mediumpurple: [147, 112, 219], + mediumseagreen: [60, 179, 113], + mediumslateblue: [123, 104, 238], + mediumspringgreen: [0, 250, 154], + mediumturquoise: [72, 209, 204], + mediumvioletred: [199, 21, 133], + midnightblue: [25, 25, 112], + mintcream: [245, 255, 250], + mistyrose: [255, 228, 225], + moccasin: [255, 228, 181], + navajowhite: [255, 222, 173], + navy: [0, 0, 128], + oldlace: [253, 245, 230], + olive: [128, 128, 0], + olivedrab: [107, 142, 35], + orange: [255, 165, 0], + orangered: [255, 69, 0], + orchid: [218, 112, 214], + palegoldenrod: [238, 232, 170], + palegreen: [152, 251, 152], + paleturquoise: [175, 238, 238], + palevioletred: [219, 112, 147], + papayawhip: [255, 239, 213], + peachpuff: [255, 218, 185], + peru: [205, 133, 63], + pink: [255, 192, 203], + plum: [221, 160, 221], + powderblue: [176, 224, 230], + purple: [128, 0, 128], + rebeccapurple: [102, 51, 153], + red: [255, 0, 0], + rosybrown: [188, 143, 143], + royalblue: [65, 105, 225], + saddlebrown: [139, 69, 19], + salmon: [250, 128, 114], + sandybrown: [244, 164, 96], + seagreen: [46, 139, 87], + seashell: [255, 245, 238], + sienna: [160, 82, 45], + silver: [192, 192, 192], + skyblue: [135, 206, 235], + slateblue: [106, 90, 205], + slategray: [112, 128, 144], + slategrey: [112, 128, 144], + snow: [255, 250, 250], + springgreen: [0, 255, 127], + steelblue: [70, 130, 180], + tan: [210, 180, 140], + teal: [0, 128, 128], + thistle: [216, 191, 216], + tomato: [255, 99, 71], + turquoise: [64, 224, 208], + violet: [238, 130, 238], + wheat: [245, 222, 179], + white: [255, 255, 255], + whitesmoke: [245, 245, 245], + yellow: [255, 255, 0], + yellowgreen: [154, 205, 50] +}; + +// node_modules/color-string/index.js +var reverseNames = /* @__PURE__ */ Object.create(null); +for (const name in color_name_default) { + if (Object.hasOwn(color_name_default, name)) { + reverseNames[color_name_default[name]] = name; + } +} +var cs = { + to: {}, + get: {} +}; +cs.get = function(string) { + const prefix = string.slice(0, 3).toLowerCase(); + let value; + let model; + switch (prefix) { + case "hsl": { + value = cs.get.hsl(string); + model = "hsl"; + break; + } + case "hwb": { + value = cs.get.hwb(string); + model = "hwb"; + break; + } + default: { + value = cs.get.rgb(string); + model = "rgb"; + break; + } + } + if (!value) { + return null; + } + return { model, value }; +}; +cs.get.rgb = function(string) { + if (!string) { + return null; + } + const abbr = /^#([a-f\d]{3,4})$/i; + const hex = /^#([a-f\d]{6})([a-f\d]{2})?$/i; + const rgba = /^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[\s,|/]\s*([+-]?[\d.]+)(%?)\s*)?\)$/; + const per = /^rgba?\(\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*(?:[\s,|/]\s*([+-]?[\d.]+)(%?)\s*)?\)$/; + const keyword = /^(\w+)$/; + let rgb = [0, 0, 0, 1]; + let match; + let i; + let hexAlpha; + if (match = string.match(hex)) { + hexAlpha = match[2]; + match = match[1]; + for (i = 0; i < 3; i++) { + const i2 = i * 2; + rgb[i] = Number.parseInt(match.slice(i2, i2 + 2), 16); + } + if (hexAlpha) { + rgb[3] = Number.parseInt(hexAlpha, 16) / 255; + } + } else if (match = string.match(abbr)) { + match = match[1]; + hexAlpha = match[3]; + for (i = 0; i < 3; i++) { + rgb[i] = Number.parseInt(match[i] + match[i], 16); + } + if (hexAlpha) { + rgb[3] = Number.parseInt(hexAlpha + hexAlpha, 16) / 255; + } + } else if (match = string.match(rgba)) { + for (i = 0; i < 3; i++) { + rgb[i] = Number.parseInt(match[i + 1], 10); + } + if (match[4]) { + rgb[3] = match[5] ? Number.parseFloat(match[4]) * 0.01 : Number.parseFloat(match[4]); + } + } else if (match = string.match(per)) { + for (i = 0; i < 3; i++) { + rgb[i] = Math.round(Number.parseFloat(match[i + 1]) * 2.55); + } + if (match[4]) { + rgb[3] = match[5] ? Number.parseFloat(match[4]) * 0.01 : Number.parseFloat(match[4]); + } + } else if (match = string.match(keyword)) { + if (match[1] === "transparent") { + return [0, 0, 0, 0]; + } + if (!Object.hasOwn(color_name_default, match[1])) { + return null; + } + rgb = color_name_default[match[1]]; + rgb[3] = 1; + return rgb; + } else { + return null; + } + for (i = 0; i < 3; i++) { + rgb[i] = clamp(rgb[i], 0, 255); + } + rgb[3] = clamp(rgb[3], 0, 1); + return rgb; +}; +cs.get.hsl = function(string) { + if (!string) { + return null; + } + const hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*(?:[,|/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; + const match = string.match(hsl); + if (match) { + const alpha = Number.parseFloat(match[4]); + const h = (Number.parseFloat(match[1]) % 360 + 360) % 360; + const s = clamp(Number.parseFloat(match[2]), 0, 100); + const l = clamp(Number.parseFloat(match[3]), 0, 100); + const a = clamp(Number.isNaN(alpha) ? 1 : alpha, 0, 1); + return [h, s, l, a]; + } + return null; +}; +cs.get.hwb = function(string) { + if (!string) { + return null; + } + const hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*[\s,]\s*([+-]?[\d.]+)%\s*[\s,]\s*([+-]?[\d.]+)%\s*(?:[\s,]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; + const match = string.match(hwb); + if (match) { + const alpha = Number.parseFloat(match[4]); + const h = (Number.parseFloat(match[1]) % 360 + 360) % 360; + const w = clamp(Number.parseFloat(match[2]), 0, 100); + const b = clamp(Number.parseFloat(match[3]), 0, 100); + const a = clamp(Number.isNaN(alpha) ? 1 : alpha, 0, 1); + return [h, w, b, a]; + } + return null; +}; +cs.to.hex = function(...rgba) { + return "#" + hexDouble(rgba[0]) + hexDouble(rgba[1]) + hexDouble(rgba[2]) + (rgba[3] < 1 ? hexDouble(Math.round(rgba[3] * 255)) : ""); +}; +cs.to.rgb = function(...rgba) { + return rgba.length < 4 || rgba[3] === 1 ? "rgb(" + Math.round(rgba[0]) + ", " + Math.round(rgba[1]) + ", " + Math.round(rgba[2]) + ")" : "rgba(" + Math.round(rgba[0]) + ", " + Math.round(rgba[1]) + ", " + Math.round(rgba[2]) + ", " + rgba[3] + ")"; +}; +cs.to.rgb.percent = function(...rgba) { + const r = Math.round(rgba[0] / 255 * 100); + const g = Math.round(rgba[1] / 255 * 100); + const b = Math.round(rgba[2] / 255 * 100); + return rgba.length < 4 || rgba[3] === 1 ? "rgb(" + r + "%, " + g + "%, " + b + "%)" : "rgba(" + r + "%, " + g + "%, " + b + "%, " + rgba[3] + ")"; +}; +cs.to.hsl = function(...hsla) { + return hsla.length < 4 || hsla[3] === 1 ? "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)" : "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, " + hsla[3] + ")"; +}; +cs.to.hwb = function(...hwba) { + let a = ""; + if (hwba.length >= 4 && hwba[3] !== 1) { + a = ", " + hwba[3]; + } + return "hwb(" + hwba[0] + ", " + hwba[1] + "%, " + hwba[2] + "%" + a + ")"; +}; +cs.to.keyword = function(...rgb) { + return reverseNames[rgb.slice(0, 3)]; +}; +function clamp(number_, min, max) { + return Math.min(Math.max(min, number_), max); +} +function hexDouble(number_) { + const string_ = Math.round(number_).toString(16).toUpperCase(); + return string_.length < 2 ? "0" + string_ : string_; +} +var color_string_default = cs; + +// node_modules/color-convert/conversions.js +var reverseKeywords = {}; +for (const key of Object.keys(color_name_default)) { + reverseKeywords[color_name_default[key]] = key; +} +var convert = { + rgb: { channels: 3, labels: "rgb" }, + hsl: { channels: 3, labels: "hsl" }, + hsv: { channels: 3, labels: "hsv" }, + hwb: { channels: 3, labels: "hwb" }, + cmyk: { channels: 4, labels: "cmyk" }, + xyz: { channels: 3, labels: "xyz" }, + lab: { channels: 3, labels: "lab" }, + oklab: { channels: 3, labels: ["okl", "oka", "okb"] }, + lch: { channels: 3, labels: "lch" }, + oklch: { channels: 3, labels: ["okl", "okc", "okh"] }, + hex: { channels: 1, labels: ["hex"] }, + keyword: { channels: 1, labels: ["keyword"] }, + ansi16: { channels: 1, labels: ["ansi16"] }, + ansi256: { channels: 1, labels: ["ansi256"] }, + hcg: { channels: 3, labels: ["h", "c", "g"] }, + apple: { channels: 3, labels: ["r16", "g16", "b16"] }, + gray: { channels: 1, labels: ["gray"] } +}; +var conversions_default = convert; +var LAB_FT = (6 / 29) ** 3; +function srgbNonlinearTransform(c) { + const cc = c > 31308e-7 ? 1.055 * c ** (1 / 2.4) - 0.055 : c * 12.92; + return Math.min(Math.max(0, cc), 1); +} +function srgbNonlinearTransformInv(c) { + return c > 0.04045 ? ((c + 0.055) / 1.055) ** 2.4 : c / 12.92; +} +for (const model of Object.keys(convert)) { + if (!("channels" in convert[model])) { + throw new Error("missing channels property: " + model); + } + if (!("labels" in convert[model])) { + throw new Error("missing channel labels property: " + model); + } + if (convert[model].labels.length !== convert[model].channels) { + throw new Error("channel and label counts mismatch: " + model); + } + const { channels, labels } = convert[model]; + delete convert[model].channels; + delete convert[model].labels; + Object.defineProperty(convert[model], "channels", { value: channels }); + Object.defineProperty(convert[model], "labels", { value: labels }); +} +convert.rgb.hsl = function(rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const min = Math.min(r, g, b); + const max = Math.max(r, g, b); + const delta = max - min; + let h; + let s; + switch (max) { + case min: { + h = 0; + break; + } + case r: { + h = (g - b) / delta; + break; + } + case g: { + h = 2 + (b - r) / delta; + break; + } + case b: { + h = 4 + (r - g) / delta; + break; + } + } + h = Math.min(h * 60, 360); + if (h < 0) { + h += 360; + } + const l = (min + max) / 2; + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta / (max + min); + } else { + s = delta / (2 - max - min); + } + return [h, s * 100, l * 100]; +}; +convert.rgb.hsv = function(rgb) { + let rdif; + let gdif; + let bdif; + let h; + let s; + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const v = Math.max(r, g, b); + const diff = v - Math.min(r, g, b); + const diffc = function(c) { + return (v - c) / 6 / diff + 1 / 2; + }; + if (diff === 0) { + h = 0; + s = 0; + } else { + s = diff / v; + rdif = diffc(r); + gdif = diffc(g); + bdif = diffc(b); + switch (v) { + case r: { + h = bdif - gdif; + break; + } + case g: { + h = 1 / 3 + rdif - bdif; + break; + } + case b: { + h = 2 / 3 + gdif - rdif; + break; + } + } + if (h < 0) { + h += 1; + } else if (h > 1) { + h -= 1; + } + } + return [ + h * 360, + s * 100, + v * 100 + ]; +}; +convert.rgb.hwb = function(rgb) { + const r = rgb[0]; + const g = rgb[1]; + let b = rgb[2]; + const h = convert.rgb.hsl(rgb)[0]; + const w = 1 / 255 * Math.min(r, Math.min(g, b)); + b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + return [h, w * 100, b * 100]; +}; +convert.rgb.oklab = function(rgb) { + const r = srgbNonlinearTransformInv(rgb[0] / 255); + const g = srgbNonlinearTransformInv(rgb[1] / 255); + const b = srgbNonlinearTransformInv(rgb[2] / 255); + const lp = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b); + const mp = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b); + const sp = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b); + const l = 0.2104542553 * lp + 0.793617785 * mp - 0.0040720468 * sp; + const aa = 1.9779984951 * lp - 2.428592205 * mp + 0.4505937099 * sp; + const bb = 0.0259040371 * lp + 0.7827717662 * mp - 0.808675766 * sp; + return [l * 100, aa * 100, bb * 100]; +}; +convert.rgb.cmyk = function(rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const k = Math.min(1 - r, 1 - g, 1 - b); + const c = (1 - r - k) / (1 - k) || 0; + const m = (1 - g - k) / (1 - k) || 0; + const y = (1 - b - k) / (1 - k) || 0; + return [c * 100, m * 100, y * 100, k * 100]; +}; +function comparativeDistance(x, y) { + return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2; +} +convert.rgb.keyword = function(rgb) { + const reversed = reverseKeywords[rgb]; + if (reversed) { + return reversed; + } + let currentClosestDistance = Number.POSITIVE_INFINITY; + let currentClosestKeyword; + for (const keyword of Object.keys(color_name_default)) { + const value = color_name_default[keyword]; + const distance = comparativeDistance(rgb, value); + if (distance < currentClosestDistance) { + currentClosestDistance = distance; + currentClosestKeyword = keyword; + } + } + return currentClosestKeyword; +}; +convert.keyword.rgb = function(keyword) { + return color_name_default[keyword]; +}; +convert.rgb.xyz = function(rgb) { + const r = srgbNonlinearTransformInv(rgb[0] / 255); + const g = srgbNonlinearTransformInv(rgb[1] / 255); + const b = srgbNonlinearTransformInv(rgb[2] / 255); + const x = r * 0.4124564 + g * 0.3575761 + b * 0.1804375; + const y = r * 0.2126729 + g * 0.7151522 + b * 0.072175; + const z = r * 0.0193339 + g * 0.119192 + b * 0.9503041; + return [x * 100, y * 100, z * 100]; +}; +convert.rgb.lab = function(rgb) { + const xyz = convert.rgb.xyz(rgb); + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; + x /= 95.047; + y /= 100; + z /= 108.883; + x = x > LAB_FT ? x ** (1 / 3) : 7.787 * x + 16 / 116; + y = y > LAB_FT ? y ** (1 / 3) : 7.787 * y + 16 / 116; + z = z > LAB_FT ? z ** (1 / 3) : 7.787 * z + 16 / 116; + const l = 116 * y - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); + return [l, a, b]; +}; +convert.hsl.rgb = function(hsl) { + const h = hsl[0] / 360; + const s = hsl[1] / 100; + const l = hsl[2] / 100; + let t3; + let value; + if (s === 0) { + value = l * 255; + return [value, value, value]; + } + const t2 = l < 0.5 ? l * (1 + s) : l + s - l * s; + const t1 = 2 * l - t2; + const rgb = [0, 0, 0]; + for (let i = 0; i < 3; i++) { + t3 = h + 1 / 3 * -(i - 1); + if (t3 < 0) { + t3++; + } + if (t3 > 1) { + t3--; + } + if (6 * t3 < 1) { + value = t1 + (t2 - t1) * 6 * t3; + } else if (2 * t3 < 1) { + value = t2; + } else if (3 * t3 < 2) { + value = t1 + (t2 - t1) * (2 / 3 - t3) * 6; + } else { + value = t1; + } + rgb[i] = value * 255; + } + return rgb; +}; +convert.hsl.hsv = function(hsl) { + const h = hsl[0]; + let s = hsl[1] / 100; + let l = hsl[2] / 100; + let smin = s; + const lmin = Math.max(l, 0.01); + l *= 2; + s *= l <= 1 ? l : 2 - l; + smin *= lmin <= 1 ? lmin : 2 - lmin; + const v = (l + s) / 2; + const sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); + return [h, sv * 100, v * 100]; +}; +convert.hsv.rgb = function(hsv) { + const h = hsv[0] / 60; + const s = hsv[1] / 100; + let v = hsv[2] / 100; + const hi = Math.floor(h) % 6; + const f = h - Math.floor(h); + const p = 255 * v * (1 - s); + const q = 255 * v * (1 - s * f); + const t = 255 * v * (1 - s * (1 - f)); + v *= 255; + switch (hi) { + case 0: { + return [v, t, p]; + } + case 1: { + return [q, v, p]; + } + case 2: { + return [p, v, t]; + } + case 3: { + return [p, q, v]; + } + case 4: { + return [t, p, v]; + } + case 5: { + return [v, p, q]; + } + } +}; +convert.hsv.hsl = function(hsv) { + const h = hsv[0]; + const s = hsv[1] / 100; + const v = hsv[2] / 100; + const vmin = Math.max(v, 0.01); + let sl; + let l; + l = (2 - s) * v; + const lmin = (2 - s) * vmin; + sl = s * vmin; + sl /= lmin <= 1 ? lmin : 2 - lmin; + sl = sl || 0; + l /= 2; + return [h, sl * 100, l * 100]; +}; +convert.hwb.rgb = function(hwb) { + const h = hwb[0] / 360; + let wh = hwb[1] / 100; + let bl = hwb[2] / 100; + const ratio = wh + bl; + let f; + if (ratio > 1) { + wh /= ratio; + bl /= ratio; + } + const i = Math.floor(6 * h); + const v = 1 - bl; + f = 6 * h - i; + if ((i & 1) !== 0) { + f = 1 - f; + } + const n = wh + f * (v - wh); + let r; + let g; + let b; + switch (i) { + default: + case 6: + case 0: { + r = v; + g = n; + b = wh; + break; + } + case 1: { + r = n; + g = v; + b = wh; + break; + } + case 2: { + r = wh; + g = v; + b = n; + break; + } + case 3: { + r = wh; + g = n; + b = v; + break; + } + case 4: { + r = n; + g = wh; + b = v; + break; + } + case 5: { + r = v; + g = wh; + b = n; + break; + } + } + return [r * 255, g * 255, b * 255]; +}; +convert.cmyk.rgb = function(cmyk) { + const c = cmyk[0] / 100; + const m = cmyk[1] / 100; + const y = cmyk[2] / 100; + const k = cmyk[3] / 100; + const r = 1 - Math.min(1, c * (1 - k) + k); + const g = 1 - Math.min(1, m * (1 - k) + k); + const b = 1 - Math.min(1, y * (1 - k) + k); + return [r * 255, g * 255, b * 255]; +}; +convert.xyz.rgb = function(xyz) { + const x = xyz[0] / 100; + const y = xyz[1] / 100; + const z = xyz[2] / 100; + let r; + let g; + let b; + r = x * 3.2404542 + y * -1.5371385 + z * -0.4985314; + g = x * -0.969266 + y * 1.8760108 + z * 0.041556; + b = x * 0.0556434 + y * -0.2040259 + z * 1.0572252; + r = srgbNonlinearTransform(r); + g = srgbNonlinearTransform(g); + b = srgbNonlinearTransform(b); + return [r * 255, g * 255, b * 255]; +}; +convert.xyz.lab = function(xyz) { + let x = xyz[0]; + let y = xyz[1]; + let z = xyz[2]; + x /= 95.047; + y /= 100; + z /= 108.883; + x = x > LAB_FT ? x ** (1 / 3) : 7.787 * x + 16 / 116; + y = y > LAB_FT ? y ** (1 / 3) : 7.787 * y + 16 / 116; + z = z > LAB_FT ? z ** (1 / 3) : 7.787 * z + 16 / 116; + const l = 116 * y - 16; + const a = 500 * (x - y); + const b = 200 * (y - z); + return [l, a, b]; +}; +convert.xyz.oklab = function(xyz) { + const x = xyz[0] / 100; + const y = xyz[1] / 100; + const z = xyz[2] / 100; + const lp = Math.cbrt(0.8189330101 * x + 0.3618667424 * y - 0.1288597137 * z); + const mp = Math.cbrt(0.0329845436 * x + 0.9293118715 * y + 0.0361456387 * z); + const sp = Math.cbrt(0.0482003018 * x + 0.2643662691 * y + 0.633851707 * z); + const l = 0.2104542553 * lp + 0.793617785 * mp - 0.0040720468 * sp; + const a = 1.9779984951 * lp - 2.428592205 * mp + 0.4505937099 * sp; + const b = 0.0259040371 * lp + 0.7827717662 * mp - 0.808675766 * sp; + return [l * 100, a * 100, b * 100]; +}; +convert.oklab.oklch = function(oklab) { + return convert.lab.lch(oklab); +}; +convert.oklab.xyz = function(oklab) { + const ll = oklab[0] / 100; + const a = oklab[1] / 100; + const b = oklab[2] / 100; + const l = (0.999999998 * ll + 0.396337792 * a + 0.215803758 * b) ** 3; + const m = (1.000000008 * ll - 0.105561342 * a - 0.063854175 * b) ** 3; + const s = (1.000000055 * ll - 0.089484182 * a - 1.291485538 * b) ** 3; + const x = 1.227013851 * l - 0.55779998 * m + 0.281256149 * s; + const y = -0.040580178 * l + 1.11225687 * m - 0.071676679 * s; + const z = -0.076381285 * l - 0.421481978 * m + 1.58616322 * s; + return [x * 100, y * 100, z * 100]; +}; +convert.oklab.rgb = function(oklab) { + const ll = oklab[0] / 100; + const aa = oklab[1] / 100; + const bb = oklab[2] / 100; + const l = (ll + 0.3963377774 * aa + 0.2158037573 * bb) ** 3; + const m = (ll - 0.1055613458 * aa - 0.0638541728 * bb) ** 3; + const s = (ll - 0.0894841775 * aa - 1.291485548 * bb) ** 3; + const r = srgbNonlinearTransform(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s); + const g = srgbNonlinearTransform(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s); + const b = srgbNonlinearTransform(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s); + return [r * 255, g * 255, b * 255]; +}; +convert.oklch.oklab = function(oklch) { + return convert.lch.lab(oklch); +}; +convert.lab.xyz = function(lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let x; + let y; + let z; + y = (l + 16) / 116; + x = a / 500 + y; + z = y - b / 200; + const y2 = y ** 3; + const x2 = x ** 3; + const z2 = z ** 3; + y = y2 > LAB_FT ? y2 : (y - 16 / 116) / 7.787; + x = x2 > LAB_FT ? x2 : (x - 16 / 116) / 7.787; + z = z2 > LAB_FT ? z2 : (z - 16 / 116) / 7.787; + x *= 95.047; + y *= 100; + z *= 108.883; + return [x, y, z]; +}; +convert.lab.lch = function(lab) { + const l = lab[0]; + const a = lab[1]; + const b = lab[2]; + let h; + const hr = Math.atan2(b, a); + h = hr * 360 / 2 / Math.PI; + if (h < 0) { + h += 360; + } + const c = Math.sqrt(a * a + b * b); + return [l, c, h]; +}; +convert.lch.lab = function(lch) { + const l = lch[0]; + const c = lch[1]; + const h = lch[2]; + const hr = h / 360 * 2 * Math.PI; + const a = c * Math.cos(hr); + const b = c * Math.sin(hr); + return [l, a, b]; +}; +convert.rgb.ansi16 = function(args, saturation = null) { + const [r, g, b] = args; + let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; + value = Math.round(value / 50); + if (value === 0) { + return 30; + } + let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); + if (value === 2) { + ansi += 60; + } + return ansi; +}; +convert.hsv.ansi16 = function(args) { + return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); +}; +convert.rgb.ansi256 = function(args) { + const r = args[0]; + const g = args[1]; + const b = args[2]; + if (r >> 4 === g >> 4 && g >> 4 === b >> 4) { + if (r < 8) { + return 16; + } + if (r > 248) { + return 231; + } + return Math.round((r - 8) / 247 * 24) + 232; + } + const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5); + return ansi; +}; +convert.ansi16.rgb = function(args) { + args = args[0]; + let color = args % 10; + if (color === 0 || color === 7) { + if (args > 50) { + color += 3.5; + } + color = color / 10.5 * 255; + return [color, color, color]; + } + const mult = (Math.trunc(args > 50) + 1) * 0.5; + const r = (color & 1) * mult * 255; + const g = (color >> 1 & 1) * mult * 255; + const b = (color >> 2 & 1) * mult * 255; + return [r, g, b]; +}; +convert.ansi256.rgb = function(args) { + args = args[0]; + if (args >= 232) { + const c = (args - 232) * 10 + 8; + return [c, c, c]; + } + args -= 16; + let rem; + const r = Math.floor(args / 36) / 5 * 255; + const g = Math.floor((rem = args % 36) / 6) / 5 * 255; + const b = rem % 6 / 5 * 255; + return [r, g, b]; +}; +convert.rgb.hex = function(args) { + const integer = ((Math.round(args[0]) & 255) << 16) + ((Math.round(args[1]) & 255) << 8) + (Math.round(args[2]) & 255); + const string = integer.toString(16).toUpperCase(); + return "000000".slice(string.length) + string; +}; +convert.hex.rgb = function(args) { + const match = args.toString(16).match(/[a-f\d]{6}|[a-f\d]{3}/i); + if (!match) { + return [0, 0, 0]; + } + let colorString = match[0]; + if (match[0].length === 3) { + colorString = [...colorString].map((char) => char + char).join(""); + } + const integer = Number.parseInt(colorString, 16); + const r = integer >> 16 & 255; + const g = integer >> 8 & 255; + const b = integer & 255; + return [r, g, b]; +}; +convert.rgb.hcg = function(rgb) { + const r = rgb[0] / 255; + const g = rgb[1] / 255; + const b = rgb[2] / 255; + const max = Math.max(Math.max(r, g), b); + const min = Math.min(Math.min(r, g), b); + const chroma = max - min; + let hue; + const grayscale = chroma < 1 ? min / (1 - chroma) : 0; + if (chroma <= 0) { + hue = 0; + } else if (max === r) { + hue = (g - b) / chroma % 6; + } else if (max === g) { + hue = 2 + (b - r) / chroma; + } else { + hue = 4 + (r - g) / chroma; + } + hue /= 6; + hue %= 1; + return [hue * 360, chroma * 100, grayscale * 100]; +}; +convert.hsl.hcg = function(hsl) { + const s = hsl[1] / 100; + const l = hsl[2] / 100; + const c = l < 0.5 ? 2 * s * l : 2 * s * (1 - l); + let f = 0; + if (c < 1) { + f = (l - 0.5 * c) / (1 - c); + } + return [hsl[0], c * 100, f * 100]; +}; +convert.hsv.hcg = function(hsv) { + const s = hsv[1] / 100; + const v = hsv[2] / 100; + const c = s * v; + let f = 0; + if (c < 1) { + f = (v - c) / (1 - c); + } + return [hsv[0], c * 100, f * 100]; +}; +convert.hcg.rgb = function(hcg) { + const h = hcg[0] / 360; + const c = hcg[1] / 100; + const g = hcg[2] / 100; + if (c === 0) { + return [g * 255, g * 255, g * 255]; + } + const pure = [0, 0, 0]; + const hi = h % 1 * 6; + const v = hi % 1; + const w = 1 - v; + let mg = 0; + switch (Math.floor(hi)) { + case 0: { + pure[0] = 1; + pure[1] = v; + pure[2] = 0; + break; + } + case 1: { + pure[0] = w; + pure[1] = 1; + pure[2] = 0; + break; + } + case 2: { + pure[0] = 0; + pure[1] = 1; + pure[2] = v; + break; + } + case 3: { + pure[0] = 0; + pure[1] = w; + pure[2] = 1; + break; + } + case 4: { + pure[0] = v; + pure[1] = 0; + pure[2] = 1; + break; + } + default: { + pure[0] = 1; + pure[1] = 0; + pure[2] = w; + } + } + mg = (1 - c) * g; + return [ + (c * pure[0] + mg) * 255, + (c * pure[1] + mg) * 255, + (c * pure[2] + mg) * 255 + ]; +}; +convert.hcg.hsv = function(hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const v = c + g * (1 - c); + let f = 0; + if (v > 0) { + f = c / v; + } + return [hcg[0], f * 100, v * 100]; +}; +convert.hcg.hsl = function(hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const l = g * (1 - c) + 0.5 * c; + let s = 0; + if (l > 0 && l < 0.5) { + s = c / (2 * l); + } else if (l >= 0.5 && l < 1) { + s = c / (2 * (1 - l)); + } + return [hcg[0], s * 100, l * 100]; +}; +convert.hcg.hwb = function(hcg) { + const c = hcg[1] / 100; + const g = hcg[2] / 100; + const v = c + g * (1 - c); + return [hcg[0], (v - c) * 100, (1 - v) * 100]; +}; +convert.hwb.hcg = function(hwb) { + const w = hwb[1] / 100; + const b = hwb[2] / 100; + const v = 1 - b; + const c = v - w; + let g = 0; + if (c < 1) { + g = (v - c) / (1 - c); + } + return [hwb[0], c * 100, g * 100]; +}; +convert.apple.rgb = function(apple) { + return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; +}; +convert.rgb.apple = function(rgb) { + return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; +}; +convert.gray.rgb = function(args) { + return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; +}; +convert.gray.hsl = function(args) { + return [0, 0, args[0]]; +}; +convert.gray.hsv = convert.gray.hsl; +convert.gray.hwb = function(gray) { + return [0, 100, gray[0]]; +}; +convert.gray.cmyk = function(gray) { + return [0, 0, 0, gray[0]]; +}; +convert.gray.lab = function(gray) { + return [gray[0], 0, 0]; +}; +convert.gray.hex = function(gray) { + const value = Math.round(gray[0] / 100 * 255) & 255; + const integer = (value << 16) + (value << 8) + value; + const string = integer.toString(16).toUpperCase(); + return "000000".slice(string.length) + string; +}; +convert.rgb.gray = function(rgb) { + const value = (rgb[0] + rgb[1] + rgb[2]) / 3; + return [value / 255 * 100]; +}; + +// node_modules/color-convert/route.js +function buildGraph() { + const graph = {}; + const models2 = Object.keys(conversions_default); + for (let { length } = models2, i = 0; i < length; i++) { + graph[models2[i]] = { + // http://jsperf.com/1-vs-infinity + // micro-opt, but this is simple. + distance: -1, + parent: null + }; + } + return graph; +} +function deriveBFS(fromModel) { + const graph = buildGraph(); + const queue = [fromModel]; + graph[fromModel].distance = 0; + while (queue.length > 0) { + const current = queue.pop(); + const adjacents = Object.keys(conversions_default[current]); + for (let { length } = adjacents, i = 0; i < length; i++) { + const adjacent = adjacents[i]; + const node = graph[adjacent]; + if (node.distance === -1) { + node.distance = graph[current].distance + 1; + node.parent = current; + queue.unshift(adjacent); + } + } + } + return graph; +} +function link(from, to) { + return function(args) { + return to(from(args)); + }; +} +function wrapConversion(toModel, graph) { + const path = [graph[toModel].parent, toModel]; + let fn = conversions_default[graph[toModel].parent][toModel]; + let cur = graph[toModel].parent; + while (graph[cur].parent) { + path.unshift(graph[cur].parent); + fn = link(conversions_default[graph[cur].parent][cur], fn); + cur = graph[cur].parent; + } + fn.conversion = path; + return fn; +} +function route(fromModel) { + const graph = deriveBFS(fromModel); + const conversion = {}; + const models2 = Object.keys(graph); + for (let { length } = models2, i = 0; i < length; i++) { + const toModel = models2[i]; + const node = graph[toModel]; + if (node.parent === null) { + continue; + } + conversion[toModel] = wrapConversion(toModel, graph); + } + return conversion; +} +var route_default = route; + +// node_modules/color-convert/index.js +var convert2 = {}; +var models = Object.keys(conversions_default); +function wrapRaw(fn) { + const wrappedFn = function(...args) { + const arg0 = args[0]; + if (arg0 === void 0 || arg0 === null) { + return arg0; + } + if (arg0.length > 1) { + args = arg0; + } + return fn(args); + }; + if ("conversion" in fn) { + wrappedFn.conversion = fn.conversion; + } + return wrappedFn; +} +function wrapRounded(fn) { + const wrappedFn = function(...args) { + const arg0 = args[0]; + if (arg0 === void 0 || arg0 === null) { + return arg0; + } + if (arg0.length > 1) { + args = arg0; + } + const result = fn(args); + if (typeof result === "object") { + for (let { length } = result, i = 0; i < length; i++) { + result[i] = Math.round(result[i]); + } + } + return result; + }; + if ("conversion" in fn) { + wrappedFn.conversion = fn.conversion; + } + return wrappedFn; +} +for (const fromModel of models) { + convert2[fromModel] = {}; + Object.defineProperty(convert2[fromModel], "channels", { value: conversions_default[fromModel].channels }); + Object.defineProperty(convert2[fromModel], "labels", { value: conversions_default[fromModel].labels }); + const routes = route_default(fromModel); + const routeModels = Object.keys(routes); + for (const toModel of routeModels) { + const fn = routes[toModel]; + convert2[fromModel][toModel] = wrapRounded(fn); + convert2[fromModel][toModel].raw = wrapRaw(fn); + } +} +var color_convert_default = convert2; + +// node_modules/color/index.js +var skippedModels = [ + // To be honest, I don't really feel like keyword belongs in color convert, but eh. + "keyword", + // Gray conflicts with some method names, and has its own method defined. + "gray", + // Shouldn't really be in color-convert either... + "hex" +]; +var hashedModelKeys = {}; +for (const model of Object.keys(color_convert_default)) { + hashedModelKeys[[...color_convert_default[model].labels].sort().join("")] = model; +} +var limiters = {}; +function Color(object, model) { + if (!(this instanceof Color)) { + return new Color(object, model); + } + if (model && model in skippedModels) { + model = null; + } + if (model && !(model in color_convert_default)) { + throw new Error("Unknown model: " + model); + } + let i; + let channels; + if (object == null) { + this.model = "rgb"; + this.color = [0, 0, 0]; + this.valpha = 1; + } else if (object instanceof Color) { + this.model = object.model; + this.color = [...object.color]; + this.valpha = object.valpha; + } else if (typeof object === "string") { + const result = color_string_default.get(object); + if (result === null) { + throw new Error("Unable to parse color from string: " + object); + } + this.model = result.model; + channels = color_convert_default[this.model].channels; + this.color = result.value.slice(0, channels); + this.valpha = typeof result.value[channels] === "number" ? result.value[channels] : 1; + } else if (object.length > 0) { + this.model = model || "rgb"; + channels = color_convert_default[this.model].channels; + const newArray = Array.prototype.slice.call(object, 0, channels); + this.color = zeroArray(newArray, channels); + this.valpha = typeof object[channels] === "number" ? object[channels] : 1; + } else if (typeof object === "number") { + this.model = "rgb"; + this.color = [ + object >> 16 & 255, + object >> 8 & 255, + object & 255 + ]; + this.valpha = 1; + } else { + this.valpha = 1; + const keys = Object.keys(object); + if ("alpha" in object) { + keys.splice(keys.indexOf("alpha"), 1); + this.valpha = typeof object.alpha === "number" ? object.alpha : 0; + } + const hashedKeys = keys.sort().join(""); + if (!(hashedKeys in hashedModelKeys)) { + throw new Error("Unable to parse color from object: " + JSON.stringify(object)); + } + this.model = hashedModelKeys[hashedKeys]; + const { labels } = color_convert_default[this.model]; + const color = []; + for (i = 0; i < labels.length; i++) { + color.push(object[labels[i]]); + } + this.color = zeroArray(color); + } + if (limiters[this.model]) { + channels = color_convert_default[this.model].channels; + for (i = 0; i < channels; i++) { + const limit = limiters[this.model][i]; + if (limit) { + this.color[i] = limit(this.color[i]); + } + } + } + this.valpha = Math.max(0, Math.min(1, this.valpha)); + if (Object.freeze) { + Object.freeze(this); + } +} +Color.prototype = { + toString() { + return this.string(); + }, + toJSON() { + return this[this.model](); + }, + string(places) { + let self = this.model in color_string_default.to ? this : this.rgb(); + self = self.round(typeof places === "number" ? places : 1); + const arguments_ = self.valpha === 1 ? self.color : [...self.color, this.valpha]; + return color_string_default.to[self.model](...arguments_); + }, + percentString(places) { + const self = this.rgb().round(typeof places === "number" ? places : 1); + const arguments_ = self.valpha === 1 ? self.color : [...self.color, this.valpha]; + return color_string_default.to.rgb.percent(...arguments_); + }, + array() { + return this.valpha === 1 ? [...this.color] : [...this.color, this.valpha]; + }, + object() { + const result = {}; + const { channels } = color_convert_default[this.model]; + const { labels } = color_convert_default[this.model]; + for (let i = 0; i < channels; i++) { + result[labels[i]] = this.color[i]; + } + if (this.valpha !== 1) { + result.alpha = this.valpha; + } + return result; + }, + unitArray() { + const rgb = this.rgb().color; + rgb[0] /= 255; + rgb[1] /= 255; + rgb[2] /= 255; + if (this.valpha !== 1) { + rgb.push(this.valpha); + } + return rgb; + }, + unitObject() { + const rgb = this.rgb().object(); + rgb.r /= 255; + rgb.g /= 255; + rgb.b /= 255; + if (this.valpha !== 1) { + rgb.alpha = this.valpha; + } + return rgb; + }, + round(places) { + places = Math.max(places || 0, 0); + return new Color([...this.color.map(roundToPlace(places)), this.valpha], this.model); + }, + alpha(value) { + if (value !== void 0) { + return new Color([...this.color, Math.max(0, Math.min(1, value))], this.model); + } + return this.valpha; + }, + // Rgb + red: getset("rgb", 0, maxfn(255)), + green: getset("rgb", 1, maxfn(255)), + blue: getset("rgb", 2, maxfn(255)), + hue: getset(["hsl", "hsv", "hsl", "hwb", "hcg"], 0, (value) => (value % 360 + 360) % 360), + saturationl: getset("hsl", 1, maxfn(100)), + lightness: getset("hsl", 2, maxfn(100)), + saturationv: getset("hsv", 1, maxfn(100)), + value: getset("hsv", 2, maxfn(100)), + chroma: getset("hcg", 1, maxfn(100)), + gray: getset("hcg", 2, maxfn(100)), + white: getset("hwb", 1, maxfn(100)), + wblack: getset("hwb", 2, maxfn(100)), + cyan: getset("cmyk", 0, maxfn(100)), + magenta: getset("cmyk", 1, maxfn(100)), + yellow: getset("cmyk", 2, maxfn(100)), + black: getset("cmyk", 3, maxfn(100)), + x: getset("xyz", 0, maxfn(95.047)), + y: getset("xyz", 1, maxfn(100)), + z: getset("xyz", 2, maxfn(108.833)), + l: getset("lab", 0, maxfn(100)), + a: getset("lab", 1), + b: getset("lab", 2), + keyword(value) { + if (value !== void 0) { + return new Color(value); + } + return color_convert_default[this.model].keyword(this.color); + }, + hex(value) { + if (value !== void 0) { + return new Color(value); + } + return color_string_default.to.hex(...this.rgb().round().color); + }, + hexa(value) { + if (value !== void 0) { + return new Color(value); + } + const rgbArray = this.rgb().round().color; + let alphaHex = Math.round(this.valpha * 255).toString(16).toUpperCase(); + if (alphaHex.length === 1) { + alphaHex = "0" + alphaHex; + } + return color_string_default.to.hex(...rgbArray) + alphaHex; + }, + rgbNumber() { + const rgb = this.rgb().color; + return (rgb[0] & 255) << 16 | (rgb[1] & 255) << 8 | rgb[2] & 255; + }, + luminosity() { + const rgb = this.rgb().color; + const lum = []; + for (const [i, element] of rgb.entries()) { + const chan = element / 255; + lum[i] = chan <= 0.04045 ? chan / 12.92 : ((chan + 0.055) / 1.055) ** 2.4; + } + return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2]; + }, + contrast(color2) { + const lum1 = this.luminosity(); + const lum2 = color2.luminosity(); + if (lum1 > lum2) { + return (lum1 + 0.05) / (lum2 + 0.05); + } + return (lum2 + 0.05) / (lum1 + 0.05); + }, + level(color2) { + const contrastRatio = this.contrast(color2); + if (contrastRatio >= 7) { + return "AAA"; + } + return contrastRatio >= 4.5 ? "AA" : ""; + }, + isDark() { + const rgb = this.rgb().color; + const yiq = (rgb[0] * 2126 + rgb[1] * 7152 + rgb[2] * 722) / 1e4; + return yiq < 128; + }, + isLight() { + return !this.isDark(); + }, + negate() { + const rgb = this.rgb(); + for (let i = 0; i < 3; i++) { + rgb.color[i] = 255 - rgb.color[i]; + } + return rgb; + }, + lighten(ratio) { + const hsl = this.hsl(); + hsl.color[2] += hsl.color[2] * ratio; + return hsl; + }, + darken(ratio) { + const hsl = this.hsl(); + hsl.color[2] -= hsl.color[2] * ratio; + return hsl; + }, + saturate(ratio) { + const hsl = this.hsl(); + hsl.color[1] += hsl.color[1] * ratio; + return hsl; + }, + desaturate(ratio) { + const hsl = this.hsl(); + hsl.color[1] -= hsl.color[1] * ratio; + return hsl; + }, + whiten(ratio) { + const hwb = this.hwb(); + hwb.color[1] += hwb.color[1] * ratio; + return hwb; + }, + blacken(ratio) { + const hwb = this.hwb(); + hwb.color[2] += hwb.color[2] * ratio; + return hwb; + }, + grayscale() { + const rgb = this.rgb().color; + const value = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11; + return Color.rgb(value, value, value); + }, + fade(ratio) { + return this.alpha(this.valpha - this.valpha * ratio); + }, + opaquer(ratio) { + return this.alpha(this.valpha + this.valpha * ratio); + }, + rotate(degrees) { + const hsl = this.hsl(); + let hue = hsl.color[0]; + hue = (hue + degrees) % 360; + hue = hue < 0 ? 360 + hue : hue; + hsl.color[0] = hue; + return hsl; + }, + mix(mixinColor, weight) { + if (!mixinColor || !mixinColor.rgb) { + throw new Error('Argument to "mix" was not a Color instance, but rather an instance of ' + typeof mixinColor); + } + const color1 = mixinColor.rgb(); + const color2 = this.rgb(); + const p = weight === void 0 ? 0.5 : weight; + const w = 2 * p - 1; + const a = color1.alpha() - color2.alpha(); + const w1 = ((w * a === -1 ? w : (w + a) / (1 + w * a)) + 1) / 2; + const w2 = 1 - w1; + return Color.rgb( + w1 * color1.red() + w2 * color2.red(), + w1 * color1.green() + w2 * color2.green(), + w1 * color1.blue() + w2 * color2.blue(), + color1.alpha() * p + color2.alpha() * (1 - p) + ); + } +}; +for (const model of Object.keys(color_convert_default)) { + if (skippedModels.includes(model)) { + continue; + } + const { channels } = color_convert_default[model]; + Color.prototype[model] = function(...arguments_) { + if (this.model === model) { + return new Color(this); + } + if (arguments_.length > 0) { + return new Color(arguments_, model); + } + return new Color([...assertArray(color_convert_default[this.model][model].raw(this.color)), this.valpha], model); + }; + Color[model] = function(...arguments_) { + let color = arguments_[0]; + if (typeof color === "number") { + color = zeroArray(arguments_, channels); + } + return new Color(color, model); + }; +} +function roundTo(number, places) { + return Number(number.toFixed(places)); +} +function roundToPlace(places) { + return function(number) { + return roundTo(number, places); + }; +} +function getset(model, channel, modifier) { + model = Array.isArray(model) ? model : [model]; + for (const m of model) { + (limiters[m] ||= [])[channel] = modifier; + } + model = model[0]; + return function(value) { + let result; + if (value !== void 0) { + if (modifier) { + value = modifier(value); + } + result = this[model](); + result.color[channel] = value; + return result; + } + result = this[model]().color[channel]; + if (modifier) { + result = modifier(result); + } + return result; + }; +} +function maxfn(max) { + return function(v) { + return Math.max(0, Math.min(max, v)); + }; +} +function assertArray(value) { + return Array.isArray(value) ? value : [value]; +} +function zeroArray(array, length) { + for (let i = 0; i < length; i++) { + if (typeof array[i] !== "number") { + array[i] = 0; + } + } + return array; +} +var index_default = Color; diff --git a/server/node_modules/@img/colour/index.cjs b/server/node_modules/@img/colour/index.cjs new file mode 100644 index 0000000..25596b2 --- /dev/null +++ b/server/node_modules/@img/colour/index.cjs @@ -0,0 +1 @@ +module.exports = require("./color.cjs").default; diff --git a/server/node_modules/@img/colour/package.json b/server/node_modules/@img/colour/package.json new file mode 100644 index 0000000..dc991b2 --- /dev/null +++ b/server/node_modules/@img/colour/package.json @@ -0,0 +1,45 @@ +{ + "name": "@img/colour", + "version": "1.0.0", + "description": "The ESM-only 'color' package made compatible for use with CommonJS runtimes", + "license": "MIT", + "main": "index.cjs", + "authors": [ + "Heather Arthur ", + "Josh Junon ", + "Maxime Thirouin", + "Dyma Ywanov ", + "LitoMore (https://github.com/LitoMore)" + ], + "engines": { + "node": ">=18" + }, + "files": [ + "color.cjs" + ], + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/lovell/colour.git" + }, + "type": "commonjs", + "keywords": [ + "color", + "colour", + "cjs", + "commonjs" + ], + "scripts": { + "build": "esbuild node_modules/color/index.js --bundle --platform=node --outfile=color.cjs", + "test": "node --test" + }, + "devDependencies": { + "color": "5.0.0", + "color-convert": "3.1.0", + "color-name": "2.0.0", + "color-string": "2.1.0", + "esbuild": "^0.25.9" + } +} diff --git a/server/node_modules/@img/sharp-libvips-linux-x64/README.md b/server/node_modules/@img/sharp-libvips-linux-x64/README.md new file mode 100644 index 0000000..9b2ce93 --- /dev/null +++ b/server/node_modules/@img/sharp-libvips-linux-x64/README.md @@ -0,0 +1,46 @@ +# `@img/sharp-libvips-linux-x64` + +Prebuilt libvips and dependencies for use with sharp on Linux (glibc) x64. + +## Licensing + +This software contains third-party libraries +used under the terms of the following licences: + +| Library | Used under the terms of | +|---------------|-----------------------------------------------------------------------------------------------------------| +| aom | BSD 2-Clause + [Alliance for Open Media Patent License 1.0](https://aomedia.org/license/patent-license/) | +| cairo | Mozilla Public License 2.0 | +| cgif | MIT Licence | +| expat | MIT Licence | +| fontconfig | [fontconfig Licence](https://gitlab.freedesktop.org/fontconfig/fontconfig/blob/main/COPYING) (BSD-like) | +| freetype | [freetype Licence](https://git.savannah.gnu.org/cgit/freetype/freetype2.git/tree/docs/FTL.TXT) (BSD-like) | +| fribidi | LGPLv3 | +| glib | LGPLv3 | +| harfbuzz | MIT Licence | +| highway | Apache-2.0 License, BSD 3-Clause | +| lcms | MIT Licence | +| libarchive | BSD 2-Clause | +| libexif | LGPLv3 | +| libffi | MIT Licence | +| libheif | LGPLv3 | +| libimagequant | [BSD 2-Clause](https://github.com/lovell/libimagequant/blob/main/COPYRIGHT) | +| libnsgif | MIT Licence | +| libpng | [libpng License](https://github.com/pnggroup/libpng/blob/master/LICENSE) | +| librsvg | LGPLv3 | +| libspng | [BSD 2-Clause, libpng License](https://github.com/randy408/libspng/blob/master/LICENSE) | +| libtiff | [libtiff License](https://gitlab.com/libtiff/libtiff/blob/master/LICENSE.md) (BSD-like) | +| libvips | LGPLv3 | +| libwebp | New BSD License | +| libxml2 | MIT Licence | +| mozjpeg | [zlib License, IJG License, BSD-3-Clause](https://github.com/mozilla/mozjpeg/blob/master/LICENSE.md) | +| pango | LGPLv3 | +| pixman | MIT Licence | +| proxy-libintl | LGPLv3 | +| zlib-ng | [zlib Licence](https://github.com/zlib-ng/zlib-ng/blob/develop/LICENSE.md) | + +Use of libraries under the terms of the LGPLv3 is via the +"any later version" clause of the LGPLv2 or LGPLv2.1. + +Please report any errors or omissions via +https://github.com/lovell/sharp-libvips/issues/new diff --git a/server/node_modules/@img/sharp-libvips-linux-x64/lib/glib-2.0/include/glibconfig.h b/server/node_modules/@img/sharp-libvips-linux-x64/lib/glib-2.0/include/glibconfig.h new file mode 100644 index 0000000..17473b8 --- /dev/null +++ b/server/node_modules/@img/sharp-libvips-linux-x64/lib/glib-2.0/include/glibconfig.h @@ -0,0 +1,221 @@ +/* glibconfig.h + * + * This is a generated file. Please modify 'glibconfig.h.in' + */ + +#ifndef __GLIBCONFIG_H__ +#define __GLIBCONFIG_H__ + +#include + +#include +#include +#define GLIB_HAVE_ALLOCA_H + +#define GLIB_STATIC_COMPILATION 1 +#define GOBJECT_STATIC_COMPILATION 1 +#define GIO_STATIC_COMPILATION 1 +#define GMODULE_STATIC_COMPILATION 1 +#define GI_STATIC_COMPILATION 1 +#define G_INTL_STATIC_COMPILATION 1 +#define FFI_STATIC_BUILD 1 + +/* Specifies that GLib's g_print*() functions wrap the + * system printf functions. This is useful to know, for example, + * when using glibc's register_printf_function(). + */ +#define GLIB_USING_SYSTEM_PRINTF + +G_BEGIN_DECLS + +#define G_MINFLOAT FLT_MIN +#define G_MAXFLOAT FLT_MAX +#define G_MINDOUBLE DBL_MIN +#define G_MAXDOUBLE DBL_MAX +#define G_MINSHORT SHRT_MIN +#define G_MAXSHORT SHRT_MAX +#define G_MAXUSHORT USHRT_MAX +#define G_MININT INT_MIN +#define G_MAXINT INT_MAX +#define G_MAXUINT UINT_MAX +#define G_MINLONG LONG_MIN +#define G_MAXLONG LONG_MAX +#define G_MAXULONG ULONG_MAX + +typedef signed char gint8; +typedef unsigned char guint8; + +typedef signed short gint16; +typedef unsigned short guint16; + +#define G_GINT16_MODIFIER "h" +#define G_GINT16_FORMAT "hi" +#define G_GUINT16_FORMAT "hu" + + +typedef signed int gint32; +typedef unsigned int guint32; + +#define G_GINT32_MODIFIER "" +#define G_GINT32_FORMAT "i" +#define G_GUINT32_FORMAT "u" + + +#define G_HAVE_GINT64 1 /* deprecated, always true */ + +typedef signed long gint64; +typedef unsigned long guint64; + +#define G_GINT64_CONSTANT(val) (val##L) +#define G_GUINT64_CONSTANT(val) (val##UL) + +#define G_GINT64_MODIFIER "l" +#define G_GINT64_FORMAT "li" +#define G_GUINT64_FORMAT "lu" + + +#define GLIB_SIZEOF_VOID_P 8 +#define GLIB_SIZEOF_LONG 8 +#define GLIB_SIZEOF_SIZE_T 8 +#define GLIB_SIZEOF_SSIZE_T 8 + +typedef signed long gssize; +typedef unsigned long gsize; +#define G_GSIZE_MODIFIER "l" +#define G_GSSIZE_MODIFIER "l" +#define G_GSIZE_FORMAT "lu" +#define G_GSSIZE_FORMAT "li" + +#define G_MAXSIZE G_MAXULONG +#define G_MINSSIZE G_MINLONG +#define G_MAXSSIZE G_MAXLONG + +typedef gint64 goffset; +#define G_MINOFFSET G_MININT64 +#define G_MAXOFFSET G_MAXINT64 + +#define G_GOFFSET_MODIFIER G_GINT64_MODIFIER +#define G_GOFFSET_FORMAT G_GINT64_FORMAT +#define G_GOFFSET_CONSTANT(val) G_GINT64_CONSTANT(val) + +#define G_POLLFD_FORMAT "%d" + +#define GPOINTER_TO_INT(p) ((gint) (glong) (p)) +#define GPOINTER_TO_UINT(p) ((guint) (gulong) (p)) + +#define GINT_TO_POINTER(i) ((gpointer) (glong) (i)) +#define GUINT_TO_POINTER(u) ((gpointer) (gulong) (u)) + +typedef signed long gintptr; +typedef unsigned long guintptr; + +#define G_GINTPTR_MODIFIER "l" +#define G_GINTPTR_FORMAT "li" +#define G_GUINTPTR_FORMAT "lu" + +#define GLIB_MAJOR_VERSION 2 +#define GLIB_MINOR_VERSION 86 +#define GLIB_MICRO_VERSION 0 + +#define G_OS_UNIX + +#define G_VA_COPY va_copy + +#define G_VA_COPY_AS_ARRAY 1 + +#define G_HAVE_ISO_VARARGS 1 + +/* gcc-2.95.x supports both gnu style and ISO varargs, but if -ansi + * is passed ISO vararg support is turned off, and there is no work + * around to turn it on, so we unconditionally turn it off. + */ +#if __GNUC__ == 2 && __GNUC_MINOR__ == 95 +# undef G_HAVE_ISO_VARARGS +#endif + +#define G_HAVE_GROWING_STACK 0 + +#ifndef _MSC_VER +# define G_HAVE_GNUC_VARARGS 1 +#endif + +#if defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590) +#define G_GNUC_INTERNAL __attribute__((visibility("hidden"))) +#elif defined(__SUNPRO_C) && (__SUNPRO_C >= 0x550) +#define G_GNUC_INTERNAL __hidden +#elif defined (__GNUC__) && defined (G_HAVE_GNUC_VISIBILITY) +#define G_GNUC_INTERNAL __attribute__((visibility("hidden"))) +#else +#define G_GNUC_INTERNAL +#endif + +#define G_THREADS_ENABLED +#define G_THREADS_IMPL_POSIX + +#define G_ATOMIC_LOCK_FREE + +#define GINT16_TO_LE(val) ((gint16) (val)) +#define GUINT16_TO_LE(val) ((guint16) (val)) +#define GINT16_TO_BE(val) ((gint16) GUINT16_SWAP_LE_BE (val)) +#define GUINT16_TO_BE(val) (GUINT16_SWAP_LE_BE (val)) + +#define GINT32_TO_LE(val) ((gint32) (val)) +#define GUINT32_TO_LE(val) ((guint32) (val)) +#define GINT32_TO_BE(val) ((gint32) GUINT32_SWAP_LE_BE (val)) +#define GUINT32_TO_BE(val) (GUINT32_SWAP_LE_BE (val)) + +#define GINT64_TO_LE(val) ((gint64) (val)) +#define GUINT64_TO_LE(val) ((guint64) (val)) +#define GINT64_TO_BE(val) ((gint64) GUINT64_SWAP_LE_BE (val)) +#define GUINT64_TO_BE(val) (GUINT64_SWAP_LE_BE (val)) + +#define GLONG_TO_LE(val) ((glong) GINT64_TO_LE (val)) +#define GULONG_TO_LE(val) ((gulong) GUINT64_TO_LE (val)) +#define GLONG_TO_BE(val) ((glong) GINT64_TO_BE (val)) +#define GULONG_TO_BE(val) ((gulong) GUINT64_TO_BE (val)) +#define GINT_TO_LE(val) ((gint) GINT32_TO_LE (val)) +#define GUINT_TO_LE(val) ((guint) GUINT32_TO_LE (val)) +#define GINT_TO_BE(val) ((gint) GINT32_TO_BE (val)) +#define GUINT_TO_BE(val) ((guint) GUINT32_TO_BE (val)) +#define GSIZE_TO_LE(val) ((gsize) GUINT64_TO_LE (val)) +#define GSSIZE_TO_LE(val) ((gssize) GINT64_TO_LE (val)) +#define GSIZE_TO_BE(val) ((gsize) GUINT64_TO_BE (val)) +#define GSSIZE_TO_BE(val) ((gssize) GINT64_TO_BE (val)) +#define G_BYTE_ORDER G_LITTLE_ENDIAN + +#define GLIB_SYSDEF_POLLIN =1 +#define GLIB_SYSDEF_POLLOUT =4 +#define GLIB_SYSDEF_POLLPRI =2 +#define GLIB_SYSDEF_POLLHUP =16 +#define GLIB_SYSDEF_POLLERR =8 +#define GLIB_SYSDEF_POLLNVAL =32 + +/* No way to disable deprecation warnings for macros, so only emit deprecation + * warnings on platforms where usage of this macro is broken */ +#if defined(__APPLE__) || defined(_MSC_VER) || defined(__CYGWIN__) +#define G_MODULE_SUFFIX "so" GLIB_DEPRECATED_MACRO_IN_2_76 +#else +#define G_MODULE_SUFFIX "so" +#endif + +typedef int GPid; +#define G_PID_FORMAT "i" + +#define GLIB_SYSDEF_AF_UNIX 1 +#define GLIB_SYSDEF_AF_INET 2 +#define GLIB_SYSDEF_AF_INET6 10 + +#define GLIB_SYSDEF_MSG_OOB 1 +#define GLIB_SYSDEF_MSG_PEEK 2 +#define GLIB_SYSDEF_MSG_DONTROUTE 4 + +#define G_DIR_SEPARATOR '/' +#define G_DIR_SEPARATOR_S "/" +#define G_SEARCHPATH_SEPARATOR ':' +#define G_SEARCHPATH_SEPARATOR_S ":" + +#undef G_HAVE_FREE_SIZED + +G_END_DECLS + +#endif /* __GLIBCONFIG_H__ */ diff --git a/server/node_modules/@img/sharp-libvips-linux-x64/lib/index.js b/server/node_modules/@img/sharp-libvips-linux-x64/lib/index.js new file mode 100644 index 0000000..5092b4d --- /dev/null +++ b/server/node_modules/@img/sharp-libvips-linux-x64/lib/index.js @@ -0,0 +1 @@ +module.exports = __dirname; diff --git a/server/node_modules/@img/sharp-libvips-linux-x64/lib/libvips-cpp.so.8.17.2 b/server/node_modules/@img/sharp-libvips-linux-x64/lib/libvips-cpp.so.8.17.2 new file mode 100644 index 0000000..fadfe3c Binary files /dev/null and b/server/node_modules/@img/sharp-libvips-linux-x64/lib/libvips-cpp.so.8.17.2 differ diff --git a/server/node_modules/@img/sharp-libvips-linux-x64/package.json b/server/node_modules/@img/sharp-libvips-linux-x64/package.json new file mode 100644 index 0000000..e20ce53 --- /dev/null +++ b/server/node_modules/@img/sharp-libvips-linux-x64/package.json @@ -0,0 +1,42 @@ +{ + "name": "@img/sharp-libvips-linux-x64", + "version": "1.2.3", + "description": "Prebuilt libvips and dependencies for use with sharp on Linux (glibc) x64", + "author": "Lovell Fuller ", + "homepage": "https://sharp.pixelplumbing.com", + "repository": { + "type": "git", + "url": "git+https://github.com/lovell/sharp-libvips.git", + "directory": "npm/linux-x64" + }, + "license": "LGPL-3.0-or-later", + "funding": { + "url": "https://opencollective.com/libvips" + }, + "preferUnplugged": true, + "publishConfig": { + "access": "public" + }, + "files": [ + "lib", + "versions.json" + ], + "type": "commonjs", + "exports": { + "./lib": "./lib/index.js", + "./package": "./package.json", + "./versions": "./versions.json" + }, + "config": { + "glibc": ">=2.26" + }, + "os": [ + "linux" + ], + "libc": [ + "glibc" + ], + "cpu": [ + "x64" + ] +} diff --git a/server/node_modules/@img/sharp-libvips-linux-x64/versions.json b/server/node_modules/@img/sharp-libvips-linux-x64/versions.json new file mode 100644 index 0000000..d9cced1 --- /dev/null +++ b/server/node_modules/@img/sharp-libvips-linux-x64/versions.json @@ -0,0 +1,30 @@ +{ + "aom": "3.13.1", + "archive": "3.8.1", + "cairo": "1.18.4", + "cgif": "0.5.0", + "exif": "0.6.25", + "expat": "2.7.2", + "ffi": "3.5.2", + "fontconfig": "2.17.1", + "freetype": "2.14.1", + "fribidi": "1.0.16", + "glib": "2.86.0", + "harfbuzz": "11.5.0", + "heif": "1.20.2", + "highway": "1.3.0", + "imagequant": "2.4.1", + "lcms": "2.17", + "mozjpeg": "4.1.5", + "pango": "1.57.0", + "pixman": "0.46.4", + "png": "1.6.50", + "proxy-libintl": "0.5", + "rsvg": "2.61.1", + "spng": "0.7.4", + "tiff": "4.7.0", + "vips": "8.17.2", + "webp": "1.6.0", + "xml2": "2.15.0", + "zlib-ng": "2.2.5" +} \ No newline at end of file diff --git a/server/node_modules/@img/sharp-linux-x64/LICENSE b/server/node_modules/@img/sharp-linux-x64/LICENSE new file mode 100644 index 0000000..37ec93a --- /dev/null +++ b/server/node_modules/@img/sharp-linux-x64/LICENSE @@ -0,0 +1,191 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +"Object" form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of +this License; and +You must cause any modified files to carry prominent notices stating that You +changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets "[]" replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same "printed page" as the copyright notice for easier identification within +third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/server/node_modules/@img/sharp-linux-x64/README.md b/server/node_modules/@img/sharp-linux-x64/README.md new file mode 100644 index 0000000..cae31de --- /dev/null +++ b/server/node_modules/@img/sharp-linux-x64/README.md @@ -0,0 +1,18 @@ +# `@img/sharp-linux-x64` + +Prebuilt sharp for use with Linux (glibc) x64. + +## Licensing + +Copyright 2013 Lovell Fuller and others. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +[https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0) + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/server/node_modules/@img/sharp-linux-x64/lib/sharp-linux-x64.node b/server/node_modules/@img/sharp-linux-x64/lib/sharp-linux-x64.node new file mode 100644 index 0000000..563aaef Binary files /dev/null and b/server/node_modules/@img/sharp-linux-x64/lib/sharp-linux-x64.node differ diff --git a/server/node_modules/@img/sharp-linux-x64/package.json b/server/node_modules/@img/sharp-linux-x64/package.json new file mode 100644 index 0000000..20996aa --- /dev/null +++ b/server/node_modules/@img/sharp-linux-x64/package.json @@ -0,0 +1,46 @@ +{ + "name": "@img/sharp-linux-x64", + "version": "0.34.4", + "description": "Prebuilt sharp for use with Linux (glibc) x64", + "author": "Lovell Fuller ", + "homepage": "https://sharp.pixelplumbing.com", + "repository": { + "type": "git", + "url": "git+https://github.com/lovell/sharp.git", + "directory": "npm/linux-x64" + }, + "license": "Apache-2.0", + "funding": { + "url": "https://opencollective.com/libvips" + }, + "preferUnplugged": true, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.2.3" + }, + "files": [ + "lib" + ], + "publishConfig": { + "access": "public" + }, + "type": "commonjs", + "exports": { + "./sharp.node": "./lib/sharp-linux-x64.node", + "./package": "./package.json" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "config": { + "glibc": ">=2.26" + }, + "os": [ + "linux" + ], + "libc": [ + "glibc" + ], + "cpu": [ + "x64" + ] +} diff --git a/server/node_modules/@types/better-sqlite3/LICENSE b/server/node_modules/@types/better-sqlite3/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/server/node_modules/@types/better-sqlite3/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/server/node_modules/@types/better-sqlite3/README.md b/server/node_modules/@types/better-sqlite3/README.md new file mode 100644 index 0000000..e9948c9 --- /dev/null +++ b/server/node_modules/@types/better-sqlite3/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/better-sqlite3` + +# Summary +This package contains type definitions for better-sqlite3 (https://github.com/JoshuaWise/better-sqlite3). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/better-sqlite3. + +### Additional Details + * Last updated: Fri, 04 Apr 2025 18:38:14 GMT + * Dependencies: [@types/node](https://npmjs.com/package/@types/node) + +# Credits +These definitions were written by [Ben Davies](https://github.com/Morfent), [Mathew Rumsey](https://github.com/matrumz), [Santiago Aguilar](https://github.com/sant123), [Alessandro Vergani](https://github.com/loghorn), [Andrew Kaiser](https://github.com/andykais), [Mark Stewart](https://github.com/mrkstwrt), [Florian Stamer](https://github.com/stamerf), and [Beeno Tung](https://github.com/beenotung). diff --git a/server/node_modules/@types/better-sqlite3/index.d.ts b/server/node_modules/@types/better-sqlite3/index.d.ts new file mode 100644 index 0000000..e7f4f54 --- /dev/null +++ b/server/node_modules/@types/better-sqlite3/index.d.ts @@ -0,0 +1,159 @@ +/// + +// FIXME: Is this `any` really necessary? +type VariableArgFunction = (...params: any[]) => unknown; +type ArgumentTypes = F extends (...args: infer A) => unknown ? A : never; +type ElementOf = T extends Array ? E : T; + +declare namespace BetterSqlite3 { + interface Statement { + database: Database; + source: string; + reader: boolean; + readonly: boolean; + busy: boolean; + + run(...params: BindParameters): Database.RunResult; + get(...params: BindParameters): Result | undefined; + all(...params: BindParameters): Result[]; + iterate(...params: BindParameters): IterableIterator; + pluck(toggleState?: boolean): this; + expand(toggleState?: boolean): this; + raw(toggleState?: boolean): this; + bind(...params: BindParameters): this; + columns(): ColumnDefinition[]; + safeIntegers(toggleState?: boolean): this; + } + + interface ColumnDefinition { + name: string; + column: string | null; + table: string | null; + database: string | null; + type: string | null; + } + + interface Transaction { + (...params: ArgumentTypes): ReturnType; + default(...params: ArgumentTypes): ReturnType; + deferred(...params: ArgumentTypes): ReturnType; + immediate(...params: ArgumentTypes): ReturnType; + exclusive(...params: ArgumentTypes): ReturnType; + } + + interface VirtualTableOptions { + rows: (...params: unknown[]) => Generator; + columns: string[]; + parameters?: string[] | undefined; + safeIntegers?: boolean | undefined; + directOnly?: boolean | undefined; + } + + interface Database { + memory: boolean; + readonly: boolean; + name: string; + open: boolean; + inTransaction: boolean; + + prepare( + source: string, + ): BindParameters extends unknown[] ? Statement : Statement<[BindParameters], Result>; + transaction(fn: F): Transaction; + exec(source: string): this; + pragma(source: string, options?: Database.PragmaOptions): unknown; + function( + name: string, + cb: (...params: any[]) => any, + ): this; + function( + name: string, + options: Database.RegistrationOptions, + cb: (...params: any[]) => any, + ): this; + aggregate( + name: string, + options: Database.RegistrationOptions & { + start?: T | (() => T); + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + step: (total: T, next: ElementOf) => T | void; + inverse?: ((total: T, dropped: T) => T) | undefined; + result?: ((total: T) => unknown) | undefined; + }, + ): this; + loadExtension(path: string): this; + close(): this; + defaultSafeIntegers(toggleState?: boolean): this; + backup(destinationFile: string, options?: Database.BackupOptions): Promise; + table(name: string, options: VirtualTableOptions): this; + unsafeMode(unsafe?: boolean): this; + serialize(options?: Database.SerializeOptions): Buffer; + } + + interface DatabaseConstructor { + new(filename?: string | Buffer, options?: Database.Options): Database; + (filename?: string, options?: Database.Options): Database; + prototype: Database; + SqliteError: SqliteErrorType; + } +} + +declare class SqliteErrorClass extends Error { + name: string; + message: string; + code: string; + constructor(message: string, code: string); +} + +type SqliteErrorType = typeof SqliteErrorClass; + +declare namespace Database { + interface RunResult { + changes: number; + lastInsertRowid: number | bigint; + } + + interface Options { + readonly?: boolean | undefined; + fileMustExist?: boolean | undefined; + timeout?: number | undefined; + verbose?: ((message?: unknown, ...additionalArgs: unknown[]) => void) | undefined; + nativeBinding?: string | undefined; + } + + interface SerializeOptions { + attached?: string; + } + + interface PragmaOptions { + simple?: boolean | undefined; + } + + interface RegistrationOptions { + varargs?: boolean | undefined; + deterministic?: boolean | undefined; + safeIntegers?: boolean | undefined; + directOnly?: boolean | undefined; + } + + type AggregateOptions = Parameters[1]; + + interface BackupMetadata { + totalPages: number; + remainingPages: number; + } + interface BackupOptions { + progress: (info: BackupMetadata) => number; + } + + type SqliteError = SqliteErrorType; + type Statement = BindParameters extends + unknown[] ? BetterSqlite3.Statement + : BetterSqlite3.Statement<[BindParameters], Result>; + type ColumnDefinition = BetterSqlite3.ColumnDefinition; + type Transaction = BetterSqlite3.Transaction; + type Database = BetterSqlite3.Database; +} + +declare const Database: BetterSqlite3.DatabaseConstructor; +export = Database; diff --git a/server/node_modules/@types/better-sqlite3/package.json b/server/node_modules/@types/better-sqlite3/package.json new file mode 100644 index 0000000..f92cf5a --- /dev/null +++ b/server/node_modules/@types/better-sqlite3/package.json @@ -0,0 +1,63 @@ +{ + "name": "@types/better-sqlite3", + "version": "7.6.13", + "description": "TypeScript definitions for better-sqlite3", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/better-sqlite3", + "license": "MIT", + "contributors": [ + { + "name": "Ben Davies", + "githubUsername": "Morfent", + "url": "https://github.com/Morfent" + }, + { + "name": "Mathew Rumsey", + "githubUsername": "matrumz", + "url": "https://github.com/matrumz" + }, + { + "name": "Santiago Aguilar", + "githubUsername": "sant123", + "url": "https://github.com/sant123" + }, + { + "name": "Alessandro Vergani", + "githubUsername": "loghorn", + "url": "https://github.com/loghorn" + }, + { + "name": "Andrew Kaiser", + "githubUsername": "andykais", + "url": "https://github.com/andykais" + }, + { + "name": "Mark Stewart", + "githubUsername": "mrkstwrt", + "url": "https://github.com/mrkstwrt" + }, + { + "name": "Florian Stamer", + "githubUsername": "stamerf", + "url": "https://github.com/stamerf" + }, + { + "name": "Beeno Tung", + "githubUsername": "beenotung", + "url": "https://github.com/beenotung" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/better-sqlite3" + }, + "scripts": {}, + "dependencies": { + "@types/node": "*" + }, + "peerDependencies": {}, + "typesPublisherContentHash": "d3573b172a1ed98c5e63d112a1d270bef2b683e7f13829155088694326b5fbac", + "typeScriptVersion": "5.1" +} \ No newline at end of file diff --git a/server/node_modules/@types/uuid/LICENSE b/server/node_modules/@types/uuid/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/server/node_modules/@types/uuid/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/server/node_modules/@types/uuid/README.md b/server/node_modules/@types/uuid/README.md new file mode 100644 index 0000000..946ff99 --- /dev/null +++ b/server/node_modules/@types/uuid/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/uuid` + +# Summary +This package contains type definitions for uuid (https://github.com/uuidjs/uuid). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/uuid. + +### Additional Details + * Last updated: Thu, 20 Jun 2024 21:07:25 GMT + * Dependencies: none + +# Credits +These definitions were written by [Oliver Hoffmann](https://github.com/iamolivinius), [Felipe Ochoa](https://github.com/felipeochoa), [Chris Barth](https://github.com/cjbarth), [Linus Unnebäck](https://github.com/LinusU), and [Christoph Tavan](https://github.com/ctavan). diff --git a/server/node_modules/@types/uuid/index.d.mts b/server/node_modules/@types/uuid/index.d.mts new file mode 100644 index 0000000..84bc5bd --- /dev/null +++ b/server/node_modules/@types/uuid/index.d.mts @@ -0,0 +1,19 @@ +import uuid from "./index.js"; +export import v1 = uuid.v1; +export import v1ToV6 = uuid.v1ToV6; +export import v3 = uuid.v3; +export import v4 = uuid.v4; +export import v5 = uuid.v5; +export import v6 = uuid.v6; +export import v6ToV1 = uuid.v6ToV1; +export import v7 = uuid.v7; +export import NIL = uuid.NIL; +export import MAX = uuid.MAX; +export import version = uuid.version; +export import validate = uuid.validate; +export import stringify = uuid.stringify; +export import parse = uuid.parse; +export import V1Options = uuid.V1Options; +export import V4Options = uuid.V4Options; +export import V6Options = uuid.V6Options; +export import V7Options = uuid.V7Options; diff --git a/server/node_modules/@types/uuid/index.d.ts b/server/node_modules/@types/uuid/index.d.ts new file mode 100644 index 0000000..4a2edac --- /dev/null +++ b/server/node_modules/@types/uuid/index.d.ts @@ -0,0 +1,113 @@ +// disable automatic export +export {}; + +// Uses ArrayLike to admit Uint8 and co. +type OutputBuffer = ArrayLike; +type InputBuffer = ArrayLike; + +interface RandomOptions { + /** `Array` of 16 random bytes (0-255) */ + random?: InputBuffer | undefined; +} +interface RngOptions { + /** Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) */ + rng?: (() => InputBuffer) | undefined; +} + +interface V1BaseOptions { + /** RFC "node" field as an `Array[6]` of byte values (per 4.1.6) */ + node?: InputBuffer | undefined; + /** RFC "clock sequence" as a `Number` between 0 - 0x3fff */ + clockseq?: number | undefined; + /** RFC "timestamp" field (`Number` of milliseconds, unix epoch) */ + msecs?: number | Date | undefined; + /** RFC "timestamp" field (`Number` of nanoseconds to add to msecs, should be 0-10,000) */ + nsecs?: number | undefined; +} +interface V1RandomOptions extends V1BaseOptions, RandomOptions {} +interface V1RngOptions extends V1BaseOptions, RngOptions {} + +export type V1Options = V1RandomOptions | V1RngOptions; +export type V4Options = RandomOptions | RngOptions; +export type V6Options = V1Options; + +interface V7BaseOptions { + msecs?: number | Date | undefined; + seq?: number; +} +export type V7Options = (RandomOptions | RngOptions) & V7BaseOptions; + +type VToV = ((uuid: string) => string) & ((uuid: OutputBuffer) => Uint8Array); + +type v1String = (options?: V1Options) => string; +type v1Buffer = (options: V1Options | null | undefined, buffer: T, offset?: number) => T; +type v1 = v1Buffer & v1String; + +type v1ToV6 = VToV; + +type v4String = (options?: V4Options) => string; +type v4Buffer = (options: V4Options | null | undefined, buffer: T, offset?: number) => T; +type v4 = v4Buffer & v4String; + +type v3String = (name: string | InputBuffer, namespace: string | InputBuffer) => string; +type v3Buffer = ( + name: string | InputBuffer, + namespace: string | InputBuffer, + buffer: T, + offset?: number, +) => T; +interface v3Static { + // https://github.com/uuidjs/uuid/blob/master/src/v35.js#L16 + DNS: string; + // https://github.com/uuidjs/uuid/blob/master/src/v35.js#L17 + URL: string; +} +type v3 = v3Buffer & v3String & v3Static; + +type v5String = (name: string | InputBuffer, namespace: string | InputBuffer) => string; +type v5Buffer = ( + name: string | InputBuffer, + namespace: string | InputBuffer, + buffer: T, + offset?: number, +) => T; +interface v5Static { + // https://github.com/uuidjs/uuid/blob/master/src/v35.js#L16 + DNS: string; + // https://github.com/uuidjs/uuid/blob/master/src/v35.js#L17 + URL: string; +} +type v5 = v5Buffer & v5String & v5Static; + +type v6String = (options?: V6Options) => string; +type v6Buffer = (options: V6Options | null | undefined, buffer: T, offset?: number) => T; +type v6 = v6Buffer & v6String; + +type v6ToV1 = VToV; + +type v7String = (options?: V7Options) => string; +type v7Buffer = (options: V7Options | null | undefined, buffer: T, offset?: number) => T; +type v7 = v7Buffer & v7String; + +type NIL = string; +type MAX = string; + +type parse = (uuid: string) => Uint8Array; +type stringify = (buffer: InputBuffer, offset?: number) => string; +type validate = (uuid: string) => boolean; +type version = (uuid: string) => number; + +export const NIL: NIL; +export const MAX: MAX; +export const parse: parse; +export const stringify: stringify; +export const v1: v1; +export const v1ToV6: v1ToV6; +export const v3: v3; +export const v4: v4; +export const v5: v5; +export const v6: v6; +export const v6ToV1: v6ToV1; +export const v7: v7; +export const validate: validate; +export const version: version; diff --git a/server/node_modules/@types/uuid/package.json b/server/node_modules/@types/uuid/package.json new file mode 100644 index 0000000..56acf25 --- /dev/null +++ b/server/node_modules/@types/uuid/package.json @@ -0,0 +1,54 @@ +{ + "name": "@types/uuid", + "version": "10.0.0", + "description": "TypeScript definitions for uuid", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/uuid", + "license": "MIT", + "contributors": [ + { + "name": "Oliver Hoffmann", + "githubUsername": "iamolivinius", + "url": "https://github.com/iamolivinius" + }, + { + "name": "Felipe Ochoa", + "githubUsername": "felipeochoa", + "url": "https://github.com/felipeochoa" + }, + { + "name": "Chris Barth", + "githubUsername": "cjbarth", + "url": "https://github.com/cjbarth" + }, + { + "name": "Linus Unnebäck", + "githubUsername": "LinusU", + "url": "https://github.com/LinusU" + }, + { + "name": "Christoph Tavan", + "githubUsername": "ctavan", + "url": "https://github.com/ctavan" + } + ], + "main": "", + "types": "index.d.ts", + "exports": { + "./package.json": "./package.json", + ".": { + "types": { + "import": "./index.d.mts", + "default": "./index.d.ts" + } + } + }, + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/uuid" + }, + "scripts": {}, + "dependencies": {}, + "typesPublisherContentHash": "08fbc5ff7d23aaac1e81b5acf98181d2544ce6ffd5578e9879e2a75f0c087d54", + "typeScriptVersion": "4.7" +} \ No newline at end of file diff --git a/server/node_modules/sharp/LICENSE b/server/node_modules/sharp/LICENSE new file mode 100644 index 0000000..37ec93a --- /dev/null +++ b/server/node_modules/sharp/LICENSE @@ -0,0 +1,191 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +"Object" form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of +this License; and +You must cause any modified files to carry prominent notices stating that You +changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work + +To apply the Apache License to your work, attach the following boilerplate +notice, with the fields enclosed by brackets "[]" replaced with your own +identifying information. (Don't include the brackets!) The text should be +enclosed in the appropriate comment syntax for the file format. We also +recommend that a file or class name and description of purpose be included on +the same "printed page" as the copyright notice for easier identification within +third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/server/node_modules/sharp/README.md b/server/node_modules/sharp/README.md new file mode 100644 index 0000000..47da52e --- /dev/null +++ b/server/node_modules/sharp/README.md @@ -0,0 +1,118 @@ +# sharp + +sharp logo + +The typical use case for this high speed Node-API module +is to convert large images in common formats to +smaller, web-friendly JPEG, PNG, WebP, GIF and AVIF images of varying dimensions. + +It can be used with all JavaScript runtimes +that provide support for Node-API v9, including +Node.js (^18.17.0 or >= 20.3.0), Deno and Bun. + +Resizing an image is typically 4x-5x faster than using the +quickest ImageMagick and GraphicsMagick settings +due to its use of [libvips](https://github.com/libvips/libvips). + +Colour spaces, embedded ICC profiles and alpha transparency channels are all handled correctly. +Lanczos resampling ensures quality is not sacrificed for speed. + +As well as image resizing, operations such as +rotation, extraction, compositing and gamma correction are available. + +Most modern macOS, Windows and Linux systems +do not require any additional install or runtime dependencies. + +## Documentation + +Visit [sharp.pixelplumbing.com](https://sharp.pixelplumbing.com/) for complete +[installation instructions](https://sharp.pixelplumbing.com/install), +[API documentation](https://sharp.pixelplumbing.com/api-constructor), +[benchmark tests](https://sharp.pixelplumbing.com/performance) and +[changelog](https://sharp.pixelplumbing.com/changelog). + +## Examples + +```sh +npm install sharp +``` + +```javascript +const sharp = require('sharp'); +``` + +### Callback + +```javascript +sharp(inputBuffer) + .resize(320, 240) + .toFile('output.webp', (err, info) => { ... }); +``` + +### Promise + +```javascript +sharp('input.jpg') + .rotate() + .resize(200) + .jpeg({ mozjpeg: true }) + .toBuffer() + .then( data => { ... }) + .catch( err => { ... }); +``` + +### Async/await + +```javascript +const semiTransparentRedPng = await sharp({ + create: { + width: 48, + height: 48, + channels: 4, + background: { r: 255, g: 0, b: 0, alpha: 0.5 } + } +}) + .png() + .toBuffer(); +``` + +### Stream + +```javascript +const roundedCorners = Buffer.from( + '' +); + +const roundedCornerResizer = + sharp() + .resize(200, 200) + .composite([{ + input: roundedCorners, + blend: 'dest-in' + }]) + .png(); + +readableStream + .pipe(roundedCornerResizer) + .pipe(writableStream); +``` + +## Contributing + +A [guide for contributors](https://github.com/lovell/sharp/blob/main/.github/CONTRIBUTING.md) +covers reporting bugs, requesting features and submitting code changes. + +## Licensing + +Copyright 2013 Lovell Fuller and others. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at +[https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0) + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/server/node_modules/sharp/install/check.js b/server/node_modules/sharp/install/check.js new file mode 100644 index 0000000..0e00133 --- /dev/null +++ b/server/node_modules/sharp/install/check.js @@ -0,0 +1,41 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +try { + const { useGlobalLibvips, globalLibvipsVersion, log, spawnRebuild } = require('../lib/libvips'); + + const buildFromSource = (msg) => { + log(msg); + log('Attempting to build from source via node-gyp'); + try { + const addonApi = require('node-addon-api'); + log(`Found node-addon-api ${addonApi.version || ''}`); + } catch (err) { + log('Please add node-addon-api to your dependencies'); + return; + } + try { + const gyp = require('node-gyp'); + log(`Found node-gyp ${gyp().version}`); + } catch (err) { + log('Please add node-gyp to your dependencies'); + return; + } + log('See https://sharp.pixelplumbing.com/install#building-from-source'); + const status = spawnRebuild(); + if (status !== 0) { + process.exit(status); + } + }; + + if (useGlobalLibvips(log)) { + buildFromSource(`Detected globally-installed libvips v${globalLibvipsVersion()}`); + } else if (process.env.npm_config_build_from_source) { + buildFromSource('Detected --build-from-source flag'); + } +} catch (err) { + const summary = err.message.split(/\n/).slice(0, 1); + console.log(`sharp: skipping install check: ${summary}`); +} diff --git a/server/node_modules/sharp/lib/channel.js b/server/node_modules/sharp/lib/channel.js new file mode 100644 index 0000000..b6381ae --- /dev/null +++ b/server/node_modules/sharp/lib/channel.js @@ -0,0 +1,177 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const is = require('./is'); + +/** + * Boolean operations for bandbool. + * @private + */ +const bool = { + and: 'and', + or: 'or', + eor: 'eor' +}; + +/** + * Remove alpha channels, if any. This is a no-op if the image does not have an alpha channel. + * + * See also {@link /api-operation#flatten|flatten}. + * + * @example + * sharp('rgba.png') + * .removeAlpha() + * .toFile('rgb.png', function(err, info) { + * // rgb.png is a 3 channel image without an alpha channel + * }); + * + * @returns {Sharp} + */ +function removeAlpha () { + this.options.removeAlpha = true; + return this; +} + +/** + * Ensure the output image has an alpha transparency channel. + * If missing, the added alpha channel will have the specified + * transparency level, defaulting to fully-opaque (1). + * This is a no-op if the image already has an alpha channel. + * + * @since 0.21.2 + * + * @example + * // rgba.png will be a 4 channel image with a fully-opaque alpha channel + * await sharp('rgb.jpg') + * .ensureAlpha() + * .toFile('rgba.png') + * + * @example + * // rgba is a 4 channel image with a fully-transparent alpha channel + * const rgba = await sharp(rgb) + * .ensureAlpha(0) + * .toBuffer(); + * + * @param {number} [alpha=1] - alpha transparency level (0=fully-transparent, 1=fully-opaque) + * @returns {Sharp} + * @throws {Error} Invalid alpha transparency level + */ +function ensureAlpha (alpha) { + if (is.defined(alpha)) { + if (is.number(alpha) && is.inRange(alpha, 0, 1)) { + this.options.ensureAlpha = alpha; + } else { + throw is.invalidParameterError('alpha', 'number between 0 and 1', alpha); + } + } else { + this.options.ensureAlpha = 1; + } + return this; +} + +/** + * Extract a single channel from a multi-channel image. + * + * The output colourspace will be either `b-w` (8-bit) or `grey16` (16-bit). + * + * @example + * // green.jpg is a greyscale image containing the green channel of the input + * await sharp(input) + * .extractChannel('green') + * .toFile('green.jpg'); + * + * @example + * // red1 is the red value of the first pixel, red2 the second pixel etc. + * const [red1, red2, ...] = await sharp(input) + * .extractChannel(0) + * .raw() + * .toBuffer(); + * + * @param {number|string} channel - zero-indexed channel/band number to extract, or `red`, `green`, `blue` or `alpha`. + * @returns {Sharp} + * @throws {Error} Invalid channel + */ +function extractChannel (channel) { + const channelMap = { red: 0, green: 1, blue: 2, alpha: 3 }; + if (Object.keys(channelMap).includes(channel)) { + channel = channelMap[channel]; + } + if (is.integer(channel) && is.inRange(channel, 0, 4)) { + this.options.extractChannel = channel; + } else { + throw is.invalidParameterError('channel', 'integer or one of: red, green, blue, alpha', channel); + } + return this; +} + +/** + * Join one or more channels to the image. + * The meaning of the added channels depends on the output colourspace, set with `toColourspace()`. + * By default the output image will be web-friendly sRGB, with additional channels interpreted as alpha channels. + * Channel ordering follows vips convention: + * - sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha. + * - CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha. + * + * Buffers may be any of the image formats supported by sharp. + * For raw pixel input, the `options` object should contain a `raw` attribute, which follows the format of the attribute of the same name in the `sharp()` constructor. + * + * @param {Array|string|Buffer} images - one or more images (file paths, Buffers). + * @param {Object} options - image options, see `sharp()` constructor. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function joinChannel (images, options) { + if (Array.isArray(images)) { + images.forEach(function (image) { + this.options.joinChannelIn.push(this._createInputDescriptor(image, options)); + }, this); + } else { + this.options.joinChannelIn.push(this._createInputDescriptor(images, options)); + } + return this; +} + +/** + * Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image. + * + * @example + * sharp('3-channel-rgb-input.png') + * .bandbool(sharp.bool.and) + * .toFile('1-channel-output.png', function (err, info) { + * // The output will be a single channel image where each pixel `P = R & G & B`. + * // If `I(1,1) = [247, 170, 14] = [0b11110111, 0b10101010, 0b00001111]` + * // then `O(1,1) = 0b11110111 & 0b10101010 & 0b00001111 = 0b00000010 = 2`. + * }); + * + * @param {string} boolOp - one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function bandbool (boolOp) { + if (is.string(boolOp) && is.inArray(boolOp, ['and', 'or', 'eor'])) { + this.options.bandBoolOp = boolOp; + } else { + throw is.invalidParameterError('boolOp', 'one of: and, or, eor', boolOp); + } + return this; +} + +/** + * Decorate the Sharp prototype with channel-related functions. + * @module Sharp + * @private + */ +module.exports = function (Sharp) { + Object.assign(Sharp.prototype, { + // Public instance functions + removeAlpha, + ensureAlpha, + extractChannel, + joinChannel, + bandbool + }); + // Class attributes + Sharp.bool = bool; +}; diff --git a/server/node_modules/sharp/lib/colour.js b/server/node_modules/sharp/lib/colour.js new file mode 100644 index 0000000..e17b77b --- /dev/null +++ b/server/node_modules/sharp/lib/colour.js @@ -0,0 +1,192 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const color = require('@img/colour'); +const is = require('./is'); + +/** + * Colourspaces. + * @private + */ +const colourspace = { + multiband: 'multiband', + 'b-w': 'b-w', + bw: 'b-w', + cmyk: 'cmyk', + srgb: 'srgb' +}; + +/** + * Tint the image using the provided colour. + * An alpha channel may be present and will be unchanged by the operation. + * + * @example + * const output = await sharp(input) + * .tint({ r: 255, g: 240, b: 16 }) + * .toBuffer(); + * + * @param {string|Object} tint - Parsed by the [color](https://www.npmjs.org/package/color) module. + * @returns {Sharp} + * @throws {Error} Invalid parameter + */ +function tint (tint) { + this._setBackgroundColourOption('tint', tint); + return this; +} + +/** + * Convert to 8-bit greyscale; 256 shades of grey. + * This is a linear operation. If the input image is in a non-linear colour space such as sRGB, use `gamma()` with `greyscale()` for the best results. + * By default the output image will be web-friendly sRGB and contain three (identical) colour channels. + * This may be overridden by other sharp operations such as `toColourspace('b-w')`, + * which will produce an output image containing one colour channel. + * An alpha channel may be present, and will be unchanged by the operation. + * + * @example + * const output = await sharp(input).greyscale().toBuffer(); + * + * @param {Boolean} [greyscale=true] + * @returns {Sharp} + */ +function greyscale (greyscale) { + this.options.greyscale = is.bool(greyscale) ? greyscale : true; + return this; +} + +/** + * Alternative spelling of `greyscale`. + * @param {Boolean} [grayscale=true] + * @returns {Sharp} + */ +function grayscale (grayscale) { + return this.greyscale(grayscale); +} + +/** + * Set the pipeline colourspace. + * + * The input image will be converted to the provided colourspace at the start of the pipeline. + * All operations will use this colourspace before converting to the output colourspace, + * as defined by {@link #tocolourspace|toColourspace}. + * + * @since 0.29.0 + * + * @example + * // Run pipeline in 16 bits per channel RGB while converting final result to 8 bits per channel sRGB. + * await sharp(input) + * .pipelineColourspace('rgb16') + * .toColourspace('srgb') + * .toFile('16bpc-pipeline-to-8bpc-output.png') + * + * @param {string} [colourspace] - pipeline colourspace e.g. `rgb16`, `scrgb`, `lab`, `grey16` [...](https://github.com/libvips/libvips/blob/41cff4e9d0838498487a00623462204eb10ee5b8/libvips/iofuncs/enumtypes.c#L774) + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function pipelineColourspace (colourspace) { + if (!is.string(colourspace)) { + throw is.invalidParameterError('colourspace', 'string', colourspace); + } + this.options.colourspacePipeline = colourspace; + return this; +} + +/** + * Alternative spelling of `pipelineColourspace`. + * @param {string} [colorspace] - pipeline colorspace. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function pipelineColorspace (colorspace) { + return this.pipelineColourspace(colorspace); +} + +/** + * Set the output colourspace. + * By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels. + * + * @example + * // Output 16 bits per pixel RGB + * await sharp(input) + * .toColourspace('rgb16') + * .toFile('16-bpp.png') + * + * @param {string} [colourspace] - output colourspace e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://github.com/libvips/libvips/blob/3c0bfdf74ce1dc37a6429bed47fa76f16e2cd70a/libvips/iofuncs/enumtypes.c#L777-L794) + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function toColourspace (colourspace) { + if (!is.string(colourspace)) { + throw is.invalidParameterError('colourspace', 'string', colourspace); + } + this.options.colourspace = colourspace; + return this; +} + +/** + * Alternative spelling of `toColourspace`. + * @param {string} [colorspace] - output colorspace. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function toColorspace (colorspace) { + return this.toColourspace(colorspace); +} + +/** + * Create a RGBA colour array from a given value. + * @private + * @param {string|Object} value + * @throws {Error} Invalid value + */ +function _getBackgroundColourOption (value) { + if (is.object(value) || is.string(value)) { + const colour = color(value); + return [ + colour.red(), + colour.green(), + colour.blue(), + Math.round(colour.alpha() * 255) + ]; + } else { + throw is.invalidParameterError('background', 'object or string', value); + } +} + +/** + * Update a colour attribute of the this.options Object. + * @private + * @param {string} key + * @param {string|Object} value + * @throws {Error} Invalid value + */ +function _setBackgroundColourOption (key, value) { + if (is.defined(value)) { + this.options[key] = _getBackgroundColourOption(value); + } +} + +/** + * Decorate the Sharp prototype with colour-related functions. + * @module Sharp + * @private + */ +module.exports = function (Sharp) { + Object.assign(Sharp.prototype, { + // Public + tint, + greyscale, + grayscale, + pipelineColourspace, + pipelineColorspace, + toColourspace, + toColorspace, + // Private + _getBackgroundColourOption, + _setBackgroundColourOption + }); + // Class attributes + Sharp.colourspace = colourspace; + Sharp.colorspace = colourspace; +}; diff --git a/server/node_modules/sharp/lib/composite.js b/server/node_modules/sharp/lib/composite.js new file mode 100644 index 0000000..98f8aef --- /dev/null +++ b/server/node_modules/sharp/lib/composite.js @@ -0,0 +1,212 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const is = require('./is'); + +/** + * Blend modes. + * @member + * @private + */ +const blend = { + clear: 'clear', + source: 'source', + over: 'over', + in: 'in', + out: 'out', + atop: 'atop', + dest: 'dest', + 'dest-over': 'dest-over', + 'dest-in': 'dest-in', + 'dest-out': 'dest-out', + 'dest-atop': 'dest-atop', + xor: 'xor', + add: 'add', + saturate: 'saturate', + multiply: 'multiply', + screen: 'screen', + overlay: 'overlay', + darken: 'darken', + lighten: 'lighten', + 'colour-dodge': 'colour-dodge', + 'color-dodge': 'colour-dodge', + 'colour-burn': 'colour-burn', + 'color-burn': 'colour-burn', + 'hard-light': 'hard-light', + 'soft-light': 'soft-light', + difference: 'difference', + exclusion: 'exclusion' +}; + +/** + * Composite image(s) over the processed (resized, extracted etc.) image. + * + * The images to composite must be the same size or smaller than the processed image. + * If both `top` and `left` options are provided, they take precedence over `gravity`. + * + * Other operations in the same processing pipeline (e.g. resize, rotate, flip, + * flop, extract) will always be applied to the input image before composition. + * + * The `blend` option can be one of `clear`, `source`, `over`, `in`, `out`, `atop`, + * `dest`, `dest-over`, `dest-in`, `dest-out`, `dest-atop`, + * `xor`, `add`, `saturate`, `multiply`, `screen`, `overlay`, `darken`, `lighten`, + * `colour-dodge`, `color-dodge`, `colour-burn`,`color-burn`, + * `hard-light`, `soft-light`, `difference`, `exclusion`. + * + * More information about blend modes can be found at + * https://www.libvips.org/API/current/libvips-conversion.html#VipsBlendMode + * and https://www.cairographics.org/operators/ + * + * @since 0.22.0 + * + * @example + * await sharp(background) + * .composite([ + * { input: layer1, gravity: 'northwest' }, + * { input: layer2, gravity: 'southeast' }, + * ]) + * .toFile('combined.png'); + * + * @example + * const output = await sharp('input.gif', { animated: true }) + * .composite([ + * { input: 'overlay.png', tile: true, blend: 'saturate' } + * ]) + * .toBuffer(); + * + * @example + * sharp('input.png') + * .rotate(180) + * .resize(300) + * .flatten( { background: '#ff6600' } ) + * .composite([{ input: 'overlay.png', gravity: 'southeast' }]) + * .sharpen() + * .withMetadata() + * .webp( { quality: 90 } ) + * .toBuffer() + * .then(function(outputBuffer) { + * // outputBuffer contains upside down, 300px wide, alpha channel flattened + * // onto orange background, composited with overlay.png with SE gravity, + * // sharpened, with metadata, 90% quality WebP image data. Phew! + * }); + * + * @param {Object[]} images - Ordered list of images to composite + * @param {Buffer|String} [images[].input] - Buffer containing image data, String containing the path to an image file, or Create object (see below) + * @param {Object} [images[].input.create] - describes a blank overlay to be created. + * @param {Number} [images[].input.create.width] + * @param {Number} [images[].input.create.height] + * @param {Number} [images[].input.create.channels] - 3-4 + * @param {String|Object} [images[].input.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. + * @param {Object} [images[].input.text] - describes a new text image to be created. + * @param {string} [images[].input.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `LeMonde`. + * @param {string} [images[].input.text.font] - font name to render with. + * @param {string} [images[].input.text.fontfile] - absolute filesystem path to a font file that can be used by `font`. + * @param {number} [images[].input.text.width=0] - integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. + * @param {number} [images[].input.text.height=0] - integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. + * @param {string} [images[].input.text.align='left'] - text alignment (`'left'`, `'centre'`, `'center'`, `'right'`). + * @param {boolean} [images[].input.text.justify=false] - set this to true to apply justification to the text. + * @param {number} [images[].input.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified. + * @param {boolean} [images[].input.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for Pango markup features like `Red!`. + * @param {number} [images[].input.text.spacing=0] - text line height in points. Will use the font line height if none is specified. + * @param {Boolean} [images[].autoOrient=false] - set to true to use EXIF orientation data, if present, to orient the image. + * @param {String} [images[].blend='over'] - how to blend this image with the image below. + * @param {String} [images[].gravity='centre'] - gravity at which to place the overlay. + * @param {Number} [images[].top] - the pixel offset from the top edge. + * @param {Number} [images[].left] - the pixel offset from the left edge. + * @param {Boolean} [images[].tile=false] - set to true to repeat the overlay image across the entire image with the given `gravity`. + * @param {Boolean} [images[].premultiplied=false] - set to true to avoid premultiplying the image below. Equivalent to the `--premultiplied` vips option. + * @param {Number} [images[].density=72] - number representing the DPI for vector overlay image. + * @param {Object} [images[].raw] - describes overlay when using raw pixel data. + * @param {Number} [images[].raw.width] + * @param {Number} [images[].raw.height] + * @param {Number} [images[].raw.channels] + * @param {boolean} [images[].animated=false] - Set to `true` to read all frames/pages of an animated image. + * @param {string} [images[].failOn='warning'] - @see {@link /api-constructor#parameters|constructor parameters} + * @param {number|boolean} [images[].limitInputPixels=268402689] - @see {@link /api-constructor#parameters|constructor parameters} + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function composite (images) { + if (!Array.isArray(images)) { + throw is.invalidParameterError('images to composite', 'array', images); + } + this.options.composite = images.map(image => { + if (!is.object(image)) { + throw is.invalidParameterError('image to composite', 'object', image); + } + const inputOptions = this._inputOptionsFromObject(image); + const composite = { + input: this._createInputDescriptor(image.input, inputOptions, { allowStream: false }), + blend: 'over', + tile: false, + left: 0, + top: 0, + hasOffset: false, + gravity: 0, + premultiplied: false + }; + if (is.defined(image.blend)) { + if (is.string(blend[image.blend])) { + composite.blend = blend[image.blend]; + } else { + throw is.invalidParameterError('blend', 'valid blend name', image.blend); + } + } + if (is.defined(image.tile)) { + if (is.bool(image.tile)) { + composite.tile = image.tile; + } else { + throw is.invalidParameterError('tile', 'boolean', image.tile); + } + } + if (is.defined(image.left)) { + if (is.integer(image.left)) { + composite.left = image.left; + } else { + throw is.invalidParameterError('left', 'integer', image.left); + } + } + if (is.defined(image.top)) { + if (is.integer(image.top)) { + composite.top = image.top; + } else { + throw is.invalidParameterError('top', 'integer', image.top); + } + } + if (is.defined(image.top) !== is.defined(image.left)) { + throw new Error('Expected both left and top to be set'); + } else { + composite.hasOffset = is.integer(image.top) && is.integer(image.left); + } + if (is.defined(image.gravity)) { + if (is.integer(image.gravity) && is.inRange(image.gravity, 0, 8)) { + composite.gravity = image.gravity; + } else if (is.string(image.gravity) && is.integer(this.constructor.gravity[image.gravity])) { + composite.gravity = this.constructor.gravity[image.gravity]; + } else { + throw is.invalidParameterError('gravity', 'valid gravity', image.gravity); + } + } + if (is.defined(image.premultiplied)) { + if (is.bool(image.premultiplied)) { + composite.premultiplied = image.premultiplied; + } else { + throw is.invalidParameterError('premultiplied', 'boolean', image.premultiplied); + } + } + return composite; + }); + return this; +} + +/** + * Decorate the Sharp prototype with composite-related functions. + * @module Sharp + * @private + */ +module.exports = function (Sharp) { + Sharp.prototype.composite = composite; + Sharp.blend = blend; +}; diff --git a/server/node_modules/sharp/lib/constructor.js b/server/node_modules/sharp/lib/constructor.js new file mode 100644 index 0000000..a349f42 --- /dev/null +++ b/server/node_modules/sharp/lib/constructor.js @@ -0,0 +1,495 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const util = require('node:util'); +const stream = require('node:stream'); +const is = require('./is'); + +require('./sharp'); + +// Use NODE_DEBUG=sharp to enable libvips warnings +const debuglog = util.debuglog('sharp'); + +/** + * Constructor factory to create an instance of `sharp`, to which further methods are chained. + * + * JPEG, PNG, WebP, GIF, AVIF or TIFF format image data can be streamed out from this object. + * When using Stream based output, derived attributes are available from the `info` event. + * + * Non-critical problems encountered during processing are emitted as `warning` events. + * + * Implements the [stream.Duplex](http://nodejs.org/api/stream.html#stream_class_stream_duplex) class. + * + * When loading more than one page/frame of an animated image, + * these are combined as a vertically-stacked "toilet roll" image + * where the overall height is the `pageHeight` multiplied by the number of `pages`. + * + * @constructs Sharp + * + * @emits Sharp#info + * @emits Sharp#warning + * + * @example + * sharp('input.jpg') + * .resize(300, 200) + * .toFile('output.jpg', function(err) { + * // output.jpg is a 300 pixels wide and 200 pixels high image + * // containing a scaled and cropped version of input.jpg + * }); + * + * @example + * // Read image data from remote URL, + * // resize to 300 pixels wide, + * // emit an 'info' event with calculated dimensions + * // and finally write image data to writableStream + * const { body } = fetch('https://...'); + * const readableStream = Readable.fromWeb(body); + * const transformer = sharp() + * .resize(300) + * .on('info', ({ height }) => { + * console.log(`Image height is ${height}`); + * }); + * readableStream.pipe(transformer).pipe(writableStream); + * + * @example + * // Create a blank 300x200 PNG image of semi-translucent red pixels + * sharp({ + * create: { + * width: 300, + * height: 200, + * channels: 4, + * background: { r: 255, g: 0, b: 0, alpha: 0.5 } + * } + * }) + * .png() + * .toBuffer() + * .then( ... ); + * + * @example + * // Convert an animated GIF to an animated WebP + * await sharp('in.gif', { animated: true }).toFile('out.webp'); + * + * @example + * // Read a raw array of pixels and save it to a png + * const input = Uint8Array.from([255, 255, 255, 0, 0, 0]); // or Uint8ClampedArray + * const image = sharp(input, { + * // because the input does not contain its dimensions or how many channels it has + * // we need to specify it in the constructor options + * raw: { + * width: 2, + * height: 1, + * channels: 3 + * } + * }); + * await image.toFile('my-two-pixels.png'); + * + * @example + * // Generate RGB Gaussian noise + * await sharp({ + * create: { + * width: 300, + * height: 200, + * channels: 3, + * noise: { + * type: 'gaussian', + * mean: 128, + * sigma: 30 + * } + * } + * }).toFile('noise.png'); + * + * @example + * // Generate an image from text + * await sharp({ + * text: { + * text: 'Hello, world!', + * width: 400, // max width + * height: 300 // max height + * } + * }).toFile('text_bw.png'); + * + * @example + * // Generate an rgba image from text using pango markup and font + * await sharp({ + * text: { + * text: 'Red!blue', + * font: 'sans', + * rgba: true, + * dpi: 300 + * } + * }).toFile('text_rgba.png'); + * + * @example + * // Join four input images as a 2x2 grid with a 4 pixel gutter + * const data = await sharp( + * [image1, image2, image3, image4], + * { join: { across: 2, shim: 4 } } + * ).toBuffer(); + * + * @example + * // Generate a two-frame animated image from emoji + * const images = ['😀', '😛'].map(text => ({ + * text: { text, width: 64, height: 64, channels: 4, rgba: true } + * })); + * await sharp(images, { join: { animated: true } }).toFile('out.gif'); + * + * @param {(Buffer|ArrayBuffer|Uint8Array|Uint8ClampedArray|Int8Array|Uint16Array|Int16Array|Uint32Array|Int32Array|Float32Array|Float64Array|string|Array)} [input] - if present, can be + * a Buffer / ArrayBuffer / Uint8Array / Uint8ClampedArray containing JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image data, or + * a TypedArray containing raw pixel image data, or + * a String containing the filesystem path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file. + * An array of inputs can be provided, and these will be joined together. + * JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data can be streamed into the object when not present. + * @param {Object} [options] - if present, is an Object with optional attributes. + * @param {string} [options.failOn='warning'] - When to abort processing of invalid pixel data, one of (in order of sensitivity, least to most): 'none', 'truncated', 'error', 'warning'. Higher levels imply lower levels. Invalid metadata will always abort. + * @param {number|boolean} [options.limitInputPixels=268402689] - Do not process input images where the number of pixels + * (width x height) exceeds this limit. Assumes image dimensions contained in the input metadata can be trusted. + * An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). + * @param {boolean} [options.unlimited=false] - Set this to `true` to remove safety features that help prevent memory exhaustion (JPEG, PNG, SVG, HEIF). + * @param {boolean} [options.autoOrient=false] - Set this to `true` to rotate/flip the image to match EXIF `Orientation`, if any. + * @param {boolean} [options.sequentialRead=true] - Set this to `false` to use random access rather than sequential read. Some operations will do this automatically. + * @param {number} [options.density=72] - number representing the DPI for vector images in the range 1 to 100000. + * @param {number} [options.ignoreIcc=false] - should the embedded ICC profile, if any, be ignored. + * @param {number} [options.pages=1] - Number of pages to extract for multi-page input (GIF, WebP, TIFF), use -1 for all pages. + * @param {number} [options.page=0] - Page number to start extracting from for multi-page input (GIF, WebP, TIFF), zero based. + * @param {boolean} [options.animated=false] - Set to `true` to read all frames/pages of an animated image (GIF, WebP, TIFF), equivalent of setting `pages` to `-1`. + * @param {Object} [options.raw] - describes raw pixel input image data. See `raw()` for pixel ordering. + * @param {number} [options.raw.width] - integral number of pixels wide. + * @param {number} [options.raw.height] - integral number of pixels high. + * @param {number} [options.raw.channels] - integral number of channels, between 1 and 4. + * @param {boolean} [options.raw.premultiplied] - specifies that the raw input has already been premultiplied, set to `true` + * to avoid sharp premultiplying the image. (optional, default `false`) + * @param {number} [options.raw.pageHeight] - The pixel height of each page/frame for animated images, must be an integral factor of `raw.height`. + * @param {Object} [options.create] - describes a new image to be created. + * @param {number} [options.create.width] - integral number of pixels wide. + * @param {number} [options.create.height] - integral number of pixels high. + * @param {number} [options.create.channels] - integral number of channels, either 3 (RGB) or 4 (RGBA). + * @param {string|Object} [options.create.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. + * @param {number} [options.create.pageHeight] - The pixel height of each page/frame for animated images, must be an integral factor of `create.height`. + * @param {Object} [options.create.noise] - describes a noise to be created. + * @param {string} [options.create.noise.type] - type of generated noise, currently only `gaussian` is supported. + * @param {number} [options.create.noise.mean=128] - Mean value of pixels in the generated noise. + * @param {number} [options.create.noise.sigma=30] - Standard deviation of pixel values in the generated noise. + * @param {Object} [options.text] - describes a new text image to be created. + * @param {string} [options.text.text] - text to render as a UTF-8 string. It can contain Pango markup, for example `LeMonde`. + * @param {string} [options.text.font] - font name to render with. + * @param {string} [options.text.fontfile] - absolute filesystem path to a font file that can be used by `font`. + * @param {number} [options.text.width=0] - Integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. + * @param {number} [options.text.height=0] - Maximum integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. + * @param {string} [options.text.align='left'] - Alignment style for multi-line text (`'left'`, `'centre'`, `'center'`, `'right'`). + * @param {boolean} [options.text.justify=false] - set this to true to apply justification to the text. + * @param {number} [options.text.dpi=72] - the resolution (size) at which to render the text. Does not take effect if `height` is specified. + * @param {boolean} [options.text.rgba=false] - set this to true to enable RGBA output. This is useful for colour emoji rendering, or support for pango markup features like `Red!`. + * @param {number} [options.text.spacing=0] - text line height in points. Will use the font line height if none is specified. + * @param {string} [options.text.wrap='word'] - word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none'. + * @param {Object} [options.join] - describes how an array of input images should be joined. + * @param {number} [options.join.across=1] - number of images to join horizontally. + * @param {boolean} [options.join.animated=false] - set this to `true` to join the images as an animated image. + * @param {number} [options.join.shim=0] - number of pixels to insert between joined images. + * @param {string|Object} [options.join.background] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. + * @param {string} [options.join.halign='left'] - horizontal alignment style for images joined horizontally (`'left'`, `'centre'`, `'center'`, `'right'`). + * @param {string} [options.join.valign='top'] - vertical alignment style for images joined vertically (`'top'`, `'centre'`, `'center'`, `'bottom'`). + * @param {Object} [options.tiff] - Describes TIFF specific options. + * @param {number} [options.tiff.subifd=-1] - Sub Image File Directory to extract for OME-TIFF, defaults to main image. + * @param {Object} [options.svg] - Describes SVG specific options. + * @param {string} [options.svg.stylesheet] - Custom CSS for SVG input, applied with a User Origin during the CSS cascade. + * @param {boolean} [options.svg.highBitdepth=false] - Set to `true` to render SVG input at 32-bits per channel (128-bit) instead of 8-bits per channel (32-bit) RGBA. + * @param {Object} [options.pdf] - Describes PDF specific options. Requires the use of a globally-installed libvips compiled with support for PDFium, Poppler, ImageMagick or GraphicsMagick. + * @param {string|Object} [options.pdf.background] - Background colour to use when PDF is partially transparent. Parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. + * @param {Object} [options.openSlide] - Describes OpenSlide specific options. Requires the use of a globally-installed libvips compiled with support for OpenSlide. + * @param {number} [options.openSlide.level=0] - Level to extract from a multi-level input, zero based. + * @param {Object} [options.jp2] - Describes JPEG 2000 specific options. Requires the use of a globally-installed libvips compiled with support for OpenJPEG. + * @param {boolean} [options.jp2.oneshot=false] - Set to `true` to decode tiled JPEG 2000 images in a single operation, improving compatibility. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +const Sharp = function (input, options) { + if (arguments.length === 1 && !is.defined(input)) { + throw new Error('Invalid input'); + } + if (!(this instanceof Sharp)) { + return new Sharp(input, options); + } + stream.Duplex.call(this); + this.options = { + // resize options + topOffsetPre: -1, + leftOffsetPre: -1, + widthPre: -1, + heightPre: -1, + topOffsetPost: -1, + leftOffsetPost: -1, + widthPost: -1, + heightPost: -1, + width: -1, + height: -1, + canvas: 'crop', + position: 0, + resizeBackground: [0, 0, 0, 255], + angle: 0, + rotationAngle: 0, + rotationBackground: [0, 0, 0, 255], + rotateBefore: false, + orientBefore: false, + flip: false, + flop: false, + extendTop: 0, + extendBottom: 0, + extendLeft: 0, + extendRight: 0, + extendBackground: [0, 0, 0, 255], + extendWith: 'background', + withoutEnlargement: false, + withoutReduction: false, + affineMatrix: [], + affineBackground: [0, 0, 0, 255], + affineIdx: 0, + affineIdy: 0, + affineOdx: 0, + affineOdy: 0, + affineInterpolator: this.constructor.interpolators.bilinear, + kernel: 'lanczos3', + fastShrinkOnLoad: true, + // operations + tint: [-1, 0, 0, 0], + flatten: false, + flattenBackground: [0, 0, 0], + unflatten: false, + negate: false, + negateAlpha: true, + medianSize: 0, + blurSigma: 0, + precision: 'integer', + minAmpl: 0.2, + sharpenSigma: 0, + sharpenM1: 1, + sharpenM2: 2, + sharpenX1: 2, + sharpenY2: 10, + sharpenY3: 20, + threshold: 0, + thresholdGrayscale: true, + trimBackground: [], + trimThreshold: -1, + trimLineArt: false, + dilateWidth: 0, + erodeWidth: 0, + gamma: 0, + gammaOut: 0, + greyscale: false, + normalise: false, + normaliseLower: 1, + normaliseUpper: 99, + claheWidth: 0, + claheHeight: 0, + claheMaxSlope: 3, + brightness: 1, + saturation: 1, + hue: 0, + lightness: 0, + booleanBufferIn: null, + booleanFileIn: '', + joinChannelIn: [], + extractChannel: -1, + removeAlpha: false, + ensureAlpha: -1, + colourspace: 'srgb', + colourspacePipeline: 'last', + composite: [], + // output + fileOut: '', + formatOut: 'input', + streamOut: false, + keepMetadata: 0, + withMetadataOrientation: -1, + withMetadataDensity: 0, + withIccProfile: '', + withExif: {}, + withExifMerge: true, + withXmp: '', + resolveWithObject: false, + loop: -1, + delay: [], + // output format + jpegQuality: 80, + jpegProgressive: false, + jpegChromaSubsampling: '4:2:0', + jpegTrellisQuantisation: false, + jpegOvershootDeringing: false, + jpegOptimiseScans: false, + jpegOptimiseCoding: true, + jpegQuantisationTable: 0, + pngProgressive: false, + pngCompressionLevel: 6, + pngAdaptiveFiltering: false, + pngPalette: false, + pngQuality: 100, + pngEffort: 7, + pngBitdepth: 8, + pngDither: 1, + jp2Quality: 80, + jp2TileHeight: 512, + jp2TileWidth: 512, + jp2Lossless: false, + jp2ChromaSubsampling: '4:4:4', + webpQuality: 80, + webpAlphaQuality: 100, + webpLossless: false, + webpNearLossless: false, + webpSmartSubsample: false, + webpSmartDeblock: false, + webpPreset: 'default', + webpEffort: 4, + webpMinSize: false, + webpMixed: false, + gifBitdepth: 8, + gifEffort: 7, + gifDither: 1, + gifInterFrameMaxError: 0, + gifInterPaletteMaxError: 3, + gifKeepDuplicateFrames: false, + gifReuse: true, + gifProgressive: false, + tiffQuality: 80, + tiffCompression: 'jpeg', + tiffPredictor: 'horizontal', + tiffPyramid: false, + tiffMiniswhite: false, + tiffBitdepth: 8, + tiffTile: false, + tiffTileHeight: 256, + tiffTileWidth: 256, + tiffXres: 1.0, + tiffYres: 1.0, + tiffResolutionUnit: 'inch', + heifQuality: 50, + heifLossless: false, + heifCompression: 'av1', + heifEffort: 4, + heifChromaSubsampling: '4:4:4', + heifBitdepth: 8, + jxlDistance: 1, + jxlDecodingTier: 0, + jxlEffort: 7, + jxlLossless: false, + rawDepth: 'uchar', + tileSize: 256, + tileOverlap: 0, + tileContainer: 'fs', + tileLayout: 'dz', + tileFormat: 'last', + tileDepth: 'last', + tileAngle: 0, + tileSkipBlanks: -1, + tileBackground: [255, 255, 255, 255], + tileCentre: false, + tileId: 'https://example.com/iiif', + tileBasename: '', + timeoutSeconds: 0, + linearA: [], + linearB: [], + pdfBackground: [255, 255, 255, 255], + // Function to notify of libvips warnings + debuglog: warning => { + this.emit('warning', warning); + debuglog(warning); + }, + // Function to notify of queue length changes + queueListener: function (queueLength) { + Sharp.queue.emit('change', queueLength); + } + }; + this.options.input = this._createInputDescriptor(input, options, { allowStream: true }); + return this; +}; +Object.setPrototypeOf(Sharp.prototype, stream.Duplex.prototype); +Object.setPrototypeOf(Sharp, stream.Duplex); + +/** + * Take a "snapshot" of the Sharp instance, returning a new instance. + * Cloned instances inherit the input of their parent instance. + * This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream. + * + * @example + * const pipeline = sharp().rotate(); + * pipeline.clone().resize(800, 600).pipe(firstWritableStream); + * pipeline.clone().extract({ left: 20, top: 20, width: 100, height: 100 }).pipe(secondWritableStream); + * readableStream.pipe(pipeline); + * // firstWritableStream receives auto-rotated, resized readableStream + * // secondWritableStream receives auto-rotated, extracted region of readableStream + * + * @example + * // Create a pipeline that will download an image, resize it and format it to different files + * // Using Promises to know when the pipeline is complete + * const fs = require("fs"); + * const got = require("got"); + * const sharpStream = sharp({ failOn: 'none' }); + * + * const promises = []; + * + * promises.push( + * sharpStream + * .clone() + * .jpeg({ quality: 100 }) + * .toFile("originalFile.jpg") + * ); + * + * promises.push( + * sharpStream + * .clone() + * .resize({ width: 500 }) + * .jpeg({ quality: 80 }) + * .toFile("optimized-500.jpg") + * ); + * + * promises.push( + * sharpStream + * .clone() + * .resize({ width: 500 }) + * .webp({ quality: 80 }) + * .toFile("optimized-500.webp") + * ); + * + * // https://github.com/sindresorhus/got/blob/main/documentation/3-streams.md + * got.stream("https://www.example.com/some-file.jpg").pipe(sharpStream); + * + * Promise.all(promises) + * .then(res => { console.log("Done!", res); }) + * .catch(err => { + * console.error("Error processing files, let's clean it up", err); + * try { + * fs.unlinkSync("originalFile.jpg"); + * fs.unlinkSync("optimized-500.jpg"); + * fs.unlinkSync("optimized-500.webp"); + * } catch (e) {} + * }); + * + * @returns {Sharp} + */ +function clone () { + // Clone existing options + const clone = this.constructor.call(); + const { debuglog, queueListener, ...options } = this.options; + clone.options = structuredClone(options); + clone.options.debuglog = debuglog; + clone.options.queueListener = queueListener; + // Pass 'finish' event to clone for Stream-based input + if (this._isStreamInput()) { + this.on('finish', () => { + // Clone inherits input data + this._flattenBufferIn(); + clone.options.input.buffer = this.options.input.buffer; + clone.emit('finish'); + }); + } + return clone; +} +Object.assign(Sharp.prototype, { clone }); + +/** + * Export constructor. + * @module Sharp + * @private + */ +module.exports = Sharp; diff --git a/server/node_modules/sharp/lib/index.d.ts b/server/node_modules/sharp/lib/index.d.ts new file mode 100644 index 0000000..4123634 --- /dev/null +++ b/server/node_modules/sharp/lib/index.d.ts @@ -0,0 +1,1964 @@ +/** + * Copyright 2017 François Nguyen and others. + * + * Billy Kwok + * Bradley Odell + * Espen Hovlandsdal + * Floris de Bijl + * François Nguyen + * Jamie Woodbury + * Wooseop Kim + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + * documentation files (the "Software"), to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all copies or substantial portions of + * the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +// SPDX-License-Identifier: MIT + +/// + +import { Duplex } from 'stream'; + +//#region Constructor functions + +/** + * Creates a sharp instance from an image + * @param input Buffer containing JPEG, PNG, WebP, AVIF, GIF, SVG, TIFF or raw pixel image data, or String containing the path to an JPEG, PNG, WebP, AVIF, GIF, SVG or TIFF image file. + * @param options Object with optional attributes. + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ +declare function sharp(options?: sharp.SharpOptions): sharp.Sharp; +declare function sharp( + input?: sharp.SharpInput | Array, + options?: sharp.SharpOptions, +): sharp.Sharp; + +declare namespace sharp { + /** Object containing nested boolean values representing the available input and output formats/methods. */ + const format: FormatEnum; + + /** An Object containing the version numbers of sharp, libvips and its dependencies. */ + const versions: { + aom?: string | undefined; + archive?: string | undefined; + cairo?: string | undefined; + cgif?: string | undefined; + exif?: string | undefined; + expat?: string | undefined; + ffi?: string | undefined; + fontconfig?: string | undefined; + freetype?: string | undefined; + fribidi?: string | undefined; + glib?: string | undefined; + harfbuzz?: string | undefined; + heif?: string | undefined; + highway?: string | undefined; + imagequant?: string | undefined; + lcms?: string | undefined; + mozjpeg?: string | undefined; + pango?: string | undefined; + pixman?: string | undefined; + png?: string | undefined; + "proxy-libintl"?: string | undefined; + rsvg?: string | undefined; + sharp: string; + spng?: string | undefined; + tiff?: string | undefined; + vips: string; + webp?: string | undefined; + xml?: string | undefined; + "zlib-ng"?: string | undefined; + }; + + /** An Object containing the available interpolators and their proper values */ + const interpolators: Interpolators; + + /** An EventEmitter that emits a change event when a task is either queued, waiting for libuv to provide a worker thread, complete */ + const queue: NodeJS.EventEmitter; + + //#endregion + + //#region Utility functions + + /** + * Gets or, when options are provided, sets the limits of libvips' operation cache. + * Existing entries in the cache will be trimmed after any change in limits. + * This method always returns cache statistics, useful for determining how much working memory is required for a particular task. + * @param options Object with the following attributes, or Boolean where true uses default cache settings and false removes all caching (optional, default true) + * @returns The cache results. + */ + function cache(options?: boolean | CacheOptions): CacheResult; + + /** + * Gets or sets the number of threads libvips' should create to process each image. + * The default value is the number of CPU cores. A value of 0 will reset to this default. + * The maximum number of images that can be processed in parallel is limited by libuv's UV_THREADPOOL_SIZE environment variable. + * @param concurrency The new concurrency value. + * @returns The current concurrency value. + */ + function concurrency(concurrency?: number): number; + + /** + * Provides access to internal task counters. + * @returns Object containing task counters + */ + function counters(): SharpCounters; + + /** + * Get and set use of SIMD vector unit instructions. Requires libvips to have been compiled with highway support. + * Improves the performance of resize, blur and sharpen operations by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON. + * @param enable enable or disable use of SIMD vector unit instructions + * @returns true if usage of SIMD vector unit instructions is enabled + */ + function simd(enable?: boolean): boolean; + + /** + * Block libvips operations at runtime. + * + * This is in addition to the `VIPS_BLOCK_UNTRUSTED` environment variable, + * which when set will block all "untrusted" operations. + * + * @since 0.32.4 + * + * @example Block all TIFF input. + * sharp.block({ + * operation: ['VipsForeignLoadTiff'] + * }); + * + * @param {Object} options + * @param {Array} options.operation - List of libvips low-level operation names to block. + */ + function block(options: { operation: string[] }): void; + + /** + * Unblock libvips operations at runtime. + * + * This is useful for defining a list of allowed operations. + * + * @since 0.32.4 + * + * @example Block all input except WebP from the filesystem. + * sharp.block({ + * operation: ['VipsForeignLoad'] + * }); + * sharp.unblock({ + * operation: ['VipsForeignLoadWebpFile'] + * }); + * + * @example Block all input except JPEG and PNG from a Buffer or Stream. + * sharp.block({ + * operation: ['VipsForeignLoad'] + * }); + * sharp.unblock({ + * operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer'] + * }); + * + * @param {Object} options + * @param {Array} options.operation - List of libvips low-level operation names to unblock. + */ + function unblock(options: { operation: string[] }): void; + + //#endregion + + const gravity: GravityEnum; + const strategy: StrategyEnum; + const kernel: KernelEnum; + const fit: FitEnum; + const bool: BoolEnum; + + interface Sharp extends Duplex { + //#region Channel functions + + /** + * Remove alpha channel, if any. This is a no-op if the image does not have an alpha channel. + * @returns A sharp instance that can be used to chain operations + */ + removeAlpha(): Sharp; + + /** + * Ensure alpha channel, if missing. The added alpha channel will be fully opaque. This is a no-op if the image already has an alpha channel. + * @param alpha transparency level (0=fully-transparent, 1=fully-opaque) (optional, default 1). + * @returns A sharp instance that can be used to chain operations + */ + ensureAlpha(alpha?: number): Sharp; + + /** + * Extract a single channel from a multi-channel image. + * @param channel zero-indexed channel/band number to extract, or red, green, blue or alpha. + * @throws {Error} Invalid channel + * @returns A sharp instance that can be used to chain operations + */ + extractChannel(channel: 0 | 1 | 2 | 3 | 'red' | 'green' | 'blue' | 'alpha'): Sharp; + + /** + * Join one or more channels to the image. The meaning of the added channels depends on the output colourspace, set with toColourspace(). + * By default the output image will be web-friendly sRGB, with additional channels interpreted as alpha channels. Channel ordering follows vips convention: + * - sRGB: 0: Red, 1: Green, 2: Blue, 3: Alpha. + * - CMYK: 0: Magenta, 1: Cyan, 2: Yellow, 3: Black, 4: Alpha. + * + * Buffers may be any of the image formats supported by sharp. + * For raw pixel input, the options object should contain a raw attribute, which follows the format of the attribute of the same name in the sharp() constructor. + * @param images one or more images (file paths, Buffers). + * @param options image options, see sharp() constructor. + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + joinChannel(images: string | Buffer | ArrayLike, options?: SharpOptions): Sharp; + + /** + * Perform a bitwise boolean operation on all input image channels (bands) to produce a single channel output image. + * @param boolOp one of "and", "or" or "eor" to perform that bitwise operation, like the C logic operators &, | and ^ respectively. + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + bandbool(boolOp: keyof BoolEnum): Sharp; + + //#endregion + + //#region Color functions + + /** + * Tint the image using the provided colour. + * An alpha channel may be present and will be unchanged by the operation. + * @param tint Parsed by the color module. + * @returns A sharp instance that can be used to chain operations + */ + tint(tint: Colour | Color): Sharp; + + /** + * Convert to 8-bit greyscale; 256 shades of grey. + * This is a linear operation. + * If the input image is in a non-linear colour space such as sRGB, use gamma() with greyscale() for the best results. + * By default the output image will be web-friendly sRGB and contain three (identical) colour channels. + * This may be overridden by other sharp operations such as toColourspace('b-w'), which will produce an output image containing one colour channel. + * An alpha channel may be present, and will be unchanged by the operation. + * @param greyscale true to enable and false to disable (defaults to true) + * @returns A sharp instance that can be used to chain operations + */ + greyscale(greyscale?: boolean): Sharp; + + /** + * Alternative spelling of greyscale(). + * @param grayscale true to enable and false to disable (defaults to true) + * @returns A sharp instance that can be used to chain operations + */ + grayscale(grayscale?: boolean): Sharp; + + /** + * Set the pipeline colourspace. + * The input image will be converted to the provided colourspace at the start of the pipeline. + * All operations will use this colourspace before converting to the output colourspace, as defined by toColourspace. + * This feature is experimental and has not yet been fully-tested with all operations. + * + * @param colourspace pipeline colourspace e.g. rgb16, scrgb, lab, grey16 ... + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + pipelineColourspace(colourspace?: string): Sharp; + + /** + * Alternative spelling of pipelineColourspace + * @param colorspace pipeline colourspace e.g. rgb16, scrgb, lab, grey16 ... + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + pipelineColorspace(colorspace?: string): Sharp; + + /** + * Set the output colourspace. + * By default output image will be web-friendly sRGB, with additional channels interpreted as alpha channels. + * @param colourspace output colourspace e.g. srgb, rgb, cmyk, lab, b-w ... + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + toColourspace(colourspace?: string): Sharp; + + /** + * Alternative spelling of toColourspace(). + * @param colorspace output colorspace e.g. srgb, rgb, cmyk, lab, b-w ... + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + toColorspace(colorspace: string): Sharp; + + //#endregion + + //#region Composite functions + + /** + * Composite image(s) over the processed (resized, extracted etc.) image. + * + * The images to composite must be the same size or smaller than the processed image. + * If both `top` and `left` options are provided, they take precedence over `gravity`. + * @param images - Ordered list of images to composite + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + composite(images: OverlayOptions[]): Sharp; + + //#endregion + + //#region Input functions + + /** + * Take a "snapshot" of the Sharp instance, returning a new instance. + * Cloned instances inherit the input of their parent instance. + * This allows multiple output Streams and therefore multiple processing pipelines to share a single input Stream. + * @returns A sharp instance that can be used to chain operations + */ + clone(): Sharp; + + /** + * Fast access to (uncached) image metadata without decoding any compressed image data. + * @returns A sharp instance that can be used to chain operations + */ + metadata(callback: (err: Error, metadata: Metadata) => void): Sharp; + + /** + * Fast access to (uncached) image metadata without decoding any compressed image data. + * @returns A promise that resolves with a metadata object + */ + metadata(): Promise; + + /** + * Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image. + * @returns A sharp instance that can be used to chain operations + */ + keepMetadata(): Sharp; + + /** + * Access to pixel-derived image statistics for every channel in the image. + * @returns A sharp instance that can be used to chain operations + */ + stats(callback: (err: Error, stats: Stats) => void): Sharp; + + /** + * Access to pixel-derived image statistics for every channel in the image. + * @returns A promise that resolves with a stats object + */ + stats(): Promise; + + //#endregion + + //#region Operation functions + + /** + * Rotate the output image by either an explicit angle + * or auto-orient based on the EXIF `Orientation` tag. + * + * If an angle is provided, it is converted to a valid positive degree rotation. + * For example, `-450` will produce a 270 degree rotation. + * + * When rotating by an angle other than a multiple of 90, + * the background colour can be provided with the `background` option. + * + * If no angle is provided, it is determined from the EXIF data. + * Mirroring is supported and may infer the use of a flip operation. + * + * The use of `rotate` without an angle will remove the EXIF `Orientation` tag, if any. + * + * Only one rotation can occur per pipeline (aside from an initial call without + * arguments to orient via EXIF data). Previous calls to `rotate` in the same + * pipeline will be ignored. + * + * Multi-page images can only be rotated by 180 degrees. + * + * Method order is important when rotating, resizing and/or extracting regions, + * for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`. + * + * @example + * const pipeline = sharp() + * .rotate() + * .resize(null, 200) + * .toBuffer(function (err, outputBuffer, info) { + * // outputBuffer contains 200px high JPEG image data, + * // auto-rotated using EXIF Orientation tag + * // info.width and info.height contain the dimensions of the resized image + * }); + * readableStream.pipe(pipeline); + * + * @example + * const rotateThenResize = await sharp(input) + * .rotate(90) + * .resize({ width: 16, height: 8, fit: 'fill' }) + * .toBuffer(); + * const resizeThenRotate = await sharp(input) + * .resize({ width: 16, height: 8, fit: 'fill' }) + * .rotate(90) + * .toBuffer(); + * + * @param {number} [angle=auto] angle of rotation. + * @param {Object} [options] - if present, is an Object with optional attributes. + * @param {string|Object} [options.background="#000000"] parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ + rotate(angle?: number, options?: RotateOptions): Sharp; + + /** + * Alias for calling `rotate()` with no arguments, which orients the image based + * on EXIF orientsion. + * + * This operation is aliased to emphasize its purpose, helping to remove any + * confusion between rotation and orientation. + * + * @example + * const output = await sharp(input).autoOrient().toBuffer(); + * + * @returns {Sharp} + */ + autoOrient(): Sharp + + /** + * Flip the image about the vertical Y axis. This always occurs after rotation, if any. + * The use of flip implies the removal of the EXIF Orientation tag, if any. + * @param flip true to enable and false to disable (defaults to true) + * @returns A sharp instance that can be used to chain operations + */ + flip(flip?: boolean): Sharp; + + /** + * Flop the image about the horizontal X axis. This always occurs after rotation, if any. + * The use of flop implies the removal of the EXIF Orientation tag, if any. + * @param flop true to enable and false to disable (defaults to true) + * @returns A sharp instance that can be used to chain operations + */ + flop(flop?: boolean): Sharp; + + /** + * Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any. + * You must provide an array of length 4 or a 2x2 affine transformation matrix. + * By default, new pixels are filled with a black background. You can provide a background colour with the `background` option. + * A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`. + * + * In the case of a 2x2 matrix, the transform is: + * X = matrix[0, 0] * (x + idx) + matrix[0, 1] * (y + idy) + odx + * Y = matrix[1, 0] * (x + idx) + matrix[1, 1] * (y + idy) + ody + * + * where: + * + * x and y are the coordinates in input image. + * X and Y are the coordinates in output image. + * (0,0) is the upper left corner. + * + * @param matrix Affine transformation matrix, may either by a array of length four or a 2x2 matrix array + * @param options if present, is an Object with optional attributes. + * + * @returns A sharp instance that can be used to chain operations + */ + affine(matrix: [number, number, number, number] | Matrix2x2, options?: AffineOptions): Sharp; + + /** + * Sharpen the image. + * When used without parameters, performs a fast, mild sharpen of the output image. + * When a sigma is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space. + * Fine-grained control over the level of sharpening in "flat" (m1) and "jagged" (m2) areas is available. + * @param options if present, is an Object with optional attributes + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + sharpen(options?: SharpenOptions): Sharp; + + /** + * Sharpen the image. + * When used without parameters, performs a fast, mild sharpen of the output image. + * When a sigma is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space. + * Fine-grained control over the level of sharpening in "flat" (m1) and "jagged" (m2) areas is available. + * @param sigma the sigma of the Gaussian mask, where sigma = 1 + radius / 2. + * @param flat the level of sharpening to apply to "flat" areas. (optional, default 1.0) + * @param jagged the level of sharpening to apply to "jagged" areas. (optional, default 2.0) + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + * + * @deprecated Use the object parameter `sharpen({sigma, m1, m2, x1, y2, y3})` instead + */ + sharpen(sigma?: number, flat?: number, jagged?: number): Sharp; + + /** + * Apply median filter. When used without parameters the default window is 3x3. + * @param size square mask size: size x size (optional, default 3) + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + median(size?: number): Sharp; + + /** + * Blur the image. + * When used without parameters, performs a fast, mild blur of the output image. + * When a sigma is provided, performs a slower, more accurate Gaussian blur. + * When a boolean sigma is provided, ether blur mild or disable blur + * @param sigma a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where sigma = 1 + radius / 2. + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + blur(sigma?: number | boolean | BlurOptions): Sharp; + + /** + * Expand foreground objects using the dilate morphological operator. + * @param {Number} [width=1] dilation width in pixels. + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + dilate(width?: number): Sharp; + + /** + * Shrink foreground objects using the erode morphological operator. + * @param {Number} [width=1] erosion width in pixels. + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + erode(width?: number): Sharp; + + /** + * Merge alpha transparency channel, if any, with background. + * @param flatten true to enable and false to disable (defaults to true) + * @returns A sharp instance that can be used to chain operations + */ + flatten(flatten?: boolean | FlattenOptions): Sharp; + + /** + * Ensure the image has an alpha channel with all white pixel values made fully transparent. + * Existing alpha channel values for non-white pixels remain unchanged. + * @returns A sharp instance that can be used to chain operations + */ + unflatten(): Sharp; + + /** + * Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of 1/gamma then increasing the encoding (brighten) post-resize at a factor of gamma. + * This can improve the perceived brightness of a resized image in non-linear colour spaces. + * JPEG and WebP input images will not take advantage of the shrink-on-load performance optimisation when applying a gamma correction. + * Supply a second argument to use a different output gamma value, otherwise the first value is used in both cases. + * @param gamma value between 1.0 and 3.0. (optional, default 2.2) + * @param gammaOut value between 1.0 and 3.0. (optional, defaults to same as gamma) + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + gamma(gamma?: number, gammaOut?: number): Sharp; + + /** + * Produce the "negative" of the image. + * @param negate true to enable and false to disable, or an object of options (defaults to true) + * @returns A sharp instance that can be used to chain operations + */ + negate(negate?: boolean | NegateOptions): Sharp; + + /** + * Enhance output image contrast by stretching its luminance to cover a full dynamic range. + * + * Uses a histogram-based approach, taking a default range of 1% to 99% to reduce sensitivity to noise at the extremes. + * + * Luminance values below the `lower` percentile will be underexposed by clipping to zero. + * Luminance values above the `upper` percentile will be overexposed by clipping to the max pixel value. + * + * @param normalise options + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + normalise(normalise?: NormaliseOptions): Sharp; + + /** + * Alternative spelling of normalise. + * @param normalize options + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + normalize(normalize?: NormaliseOptions): Sharp; + + /** + * Perform contrast limiting adaptive histogram equalization (CLAHE) + * + * This will, in general, enhance the clarity of the image by bringing out + * darker details. Please read more about CLAHE here: + * https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE + * + * @param options clahe options + */ + clahe(options: ClaheOptions): Sharp; + + /** + * Convolve the image with the specified kernel. + * @param kernel the specified kernel + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + convolve(kernel: Kernel): Sharp; + + /** + * Any pixel value greather than or equal to the threshold value will be set to 255, otherwise it will be set to 0. + * @param threshold a value in the range 0-255 representing the level at which the threshold will be applied. (optional, default 128) + * @param options threshold options + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + threshold(threshold?: number, options?: ThresholdOptions): Sharp; + + /** + * Perform a bitwise boolean operation with operand image. + * This operation creates an output image where each pixel is the result of the selected bitwise boolean operation between the corresponding pixels of the input images. + * @param operand Buffer containing image data or String containing the path to an image file. + * @param operator one of "and", "or" or "eor" to perform that bitwise operation, like the C logic operators &, | and ^ respectively. + * @param options describes operand when using raw pixel data. + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + boolean(operand: string | Buffer, operator: keyof BoolEnum, options?: { raw: Raw }): Sharp; + + /** + * Apply the linear formula a * input + b to the image (levels adjustment) + * @param a multiplier (optional, default 1.0) + * @param b offset (optional, default 0.0) + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + linear(a?: number | number[] | null, b?: number | number[]): Sharp; + + /** + * Recomb the image with the specified matrix. + * @param inputMatrix 3x3 Recombination matrix or 4x4 Recombination matrix + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + recomb(inputMatrix: Matrix3x3 | Matrix4x4): Sharp; + + /** + * Transforms the image using brightness, saturation, hue rotation and lightness. + * Brightness and lightness both operate on luminance, with the difference being that brightness is multiplicative whereas lightness is additive. + * @param options describes the modulation + * @returns A sharp instance that can be used to chain operations + */ + modulate(options?: { + brightness?: number | undefined; + saturation?: number | undefined; + hue?: number | undefined; + lightness?: number | undefined; + }): Sharp; + + //#endregion + + //#region Output functions + + /** + * Write output image data to a file. + * If an explicit output format is not selected, it will be inferred from the extension, with JPEG, PNG, WebP, AVIF, TIFF, DZI, and libvips' V format supported. + * Note that raw pixel data is only supported for buffer output. + * @param fileOut The path to write the image data to. + * @param callback Callback function called on completion with two arguments (err, info). info contains the output image format, size (bytes), width, height and channels. + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + toFile(fileOut: string, callback: (err: Error, info: OutputInfo) => void): Sharp; + + /** + * Write output image data to a file. + * @param fileOut The path to write the image data to. + * @throws {Error} Invalid parameters + * @returns A promise that fulfills with an object containing information on the resulting file + */ + toFile(fileOut: string): Promise; + + /** + * Write output to a Buffer. JPEG, PNG, WebP, AVIF, TIFF, GIF and RAW output are supported. + * By default, the format will match the input image, except SVG input which becomes PNG output. + * @param callback Callback function called on completion with three arguments (err, buffer, info). + * @returns A sharp instance that can be used to chain operations + */ + toBuffer(callback: (err: Error, buffer: Buffer, info: OutputInfo) => void): Sharp; + + /** + * Write output to a Buffer. JPEG, PNG, WebP, AVIF, TIFF, GIF and RAW output are supported. + * By default, the format will match the input image, except SVG input which becomes PNG output. + * @param options resolve options + * @param options.resolveWithObject Resolve the Promise with an Object containing data and info properties instead of resolving only with data. + * @returns A promise that resolves with the Buffer data. + */ + toBuffer(options?: { resolveWithObject: false }): Promise; + + /** + * Write output to a Buffer. JPEG, PNG, WebP, AVIF, TIFF, GIF and RAW output are supported. + * By default, the format will match the input image, except SVG input which becomes PNG output. + * @param options resolve options + * @param options.resolveWithObject Resolve the Promise with an Object containing data and info properties instead of resolving only with data. + * @returns A promise that resolves with an object containing the Buffer data and an info object containing the output image format, size (bytes), width, height and channels + */ + toBuffer(options: { resolveWithObject: true }): Promise<{ data: Buffer; info: OutputInfo }>; + + /** + * Keep all EXIF metadata from the input image in the output image. + * EXIF metadata is unsupported for TIFF output. + * @returns A sharp instance that can be used to chain operations + */ + keepExif(): Sharp; + + /** + * Set EXIF metadata in the output image, ignoring any EXIF in the input image. + * @param {Exif} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. + * @returns A sharp instance that can be used to chain operations + * @throws {Error} Invalid parameters + */ + withExif(exif: Exif): Sharp; + + /** + * Update EXIF metadata from the input image in the output image. + * @param {Exif} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. + * @returns A sharp instance that can be used to chain operations + * @throws {Error} Invalid parameters + */ + withExifMerge(exif: Exif): Sharp; + + /** + * Keep ICC profile from the input image in the output image where possible. + * @returns A sharp instance that can be used to chain operations + */ + keepIccProfile(): Sharp; + + /** + * Transform using an ICC profile and attach to the output image. + * @param {string} icc - Absolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk). + * @returns A sharp instance that can be used to chain operations + * @throws {Error} Invalid parameters + */ + withIccProfile(icc: string, options?: WithIccProfileOptions): Sharp; + + /** + * Keep all XMP metadata from the input image in the output image. + * @returns A sharp instance that can be used to chain operations + */ + keepXmp(): Sharp; + + /** + * Set XMP metadata in the output image. + * @param {string} xmp - String containing XMP metadata to be embedded in the output image. + * @returns A sharp instance that can be used to chain operations + * @throws {Error} Invalid parameters + */ + withXmp(xmp: string): Sharp; + + /** + * Include all metadata (EXIF, XMP, IPTC) from the input image in the output image. + * The default behaviour, when withMetadata is not used, is to strip all metadata and convert to the device-independent sRGB colour space. + * This will also convert to and add a web-friendly sRGB ICC profile. + * @param withMetadata + * @throws {Error} Invalid parameters. + */ + withMetadata(withMetadata?: WriteableMetadata): Sharp; + + /** + * Use these JPEG options for output image. + * @param options Output options. + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + jpeg(options?: JpegOptions): Sharp; + + /** + * Use these JP2 (JPEG 2000) options for output image. + * @param options Output options. + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + jp2(options?: Jp2Options): Sharp; + + /** + * Use these JPEG-XL (JXL) options for output image. + * This feature is experimental, please do not use in production systems. + * Requires libvips compiled with support for libjxl. + * The prebuilt binaries do not include this. + * Image metadata (EXIF, XMP) is unsupported. + * @param options Output options. + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + jxl(options?: JxlOptions): Sharp; + + /** + * Use these PNG options for output image. + * PNG output is always full colour at 8 or 16 bits per pixel. + * Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel. + * @param options Output options. + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + png(options?: PngOptions): Sharp; + + /** + * Use these WebP options for output image. + * @param options Output options. + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + webp(options?: WebpOptions): Sharp; + + /** + * Use these GIF options for output image. + * Requires libvips compiled with support for ImageMagick or GraphicsMagick. The prebuilt binaries do not include this - see installing a custom libvips. + * @param options Output options. + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + gif(options?: GifOptions): Sharp; + + /** + * Use these AVIF options for output image. + * @param options Output options. + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + avif(options?: AvifOptions): Sharp; + + /** + * Use these HEIF options for output image. + * Support for patent-encumbered HEIC images requires the use of a globally-installed libvips compiled with support for libheif, libde265 and x265. + * @param options Output options. + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + heif(options?: HeifOptions): Sharp; + + /** + * Use these TIFF options for output image. + * @param options Output options. + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + tiff(options?: TiffOptions): Sharp; + + /** + * Force output to be raw, uncompressed uint8 pixel data. + * @param options Raw output options. + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + raw(options?: RawOptions): Sharp; + + /** + * Force output to a given format. + * @param format a String or an Object with an 'id' attribute + * @param options output options + * @throws {Error} Unsupported format or options + * @returns A sharp instance that can be used to chain operations + */ + toFormat( + format: keyof FormatEnum | AvailableFormatInfo, + options?: + | OutputOptions + | JpegOptions + | PngOptions + | WebpOptions + | AvifOptions + | HeifOptions + | JxlOptions + | GifOptions + | Jp2Options + | TiffOptions, + ): Sharp; + + /** + * Use tile-based deep zoom (image pyramid) output. + * Set the format and options for tile images via the toFormat, jpeg, png or webp functions. + * Use a .zip or .szi file extension with toFile to write to a compressed archive file format. + * @param tile tile options + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + tile(tile?: TileOptions): Sharp; + + /** + * Set a timeout for processing, in seconds. Use a value of zero to continue processing indefinitely, the default behaviour. + * The clock starts when libvips opens an input image for processing. Time spent waiting for a libuv thread to become available is not included. + * @param options Object with a `seconds` attribute between 0 and 3600 (number) + * @throws {Error} Invalid options + * @returns A sharp instance that can be used to chain operations + */ + timeout(options: TimeoutOptions): Sharp; + + //#endregion + + //#region Resize functions + + /** + * Resize image to width, height or width x height. + * + * When both a width and height are provided, the possible methods by which the image should fit these are: + * - cover: Crop to cover both provided dimensions (the default). + * - contain: Embed within both provided dimensions. + * - fill: Ignore the aspect ratio of the input and stretch to both provided dimensions. + * - inside: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified. + * - outside: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified. + * Some of these values are based on the object-fit CSS property. + * + * When using a fit of cover or contain, the default position is centre. Other options are: + * - sharp.position: top, right top, right, right bottom, bottom, left bottom, left, left top. + * - sharp.gravity: north, northeast, east, southeast, south, southwest, west, northwest, center or centre. + * - sharp.strategy: cover only, dynamically crop using either the entropy or attention strategy. Some of these values are based on the object-position CSS property. + * + * The experimental strategy-based approach resizes so one dimension is at its target length then repeatedly ranks edge regions, + * discarding the edge with the lowest score based on the selected strategy. + * - entropy: focus on the region with the highest Shannon entropy. + * - attention: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones. + * + * Possible interpolation kernels are: + * - nearest: Use nearest neighbour interpolation. + * - cubic: Use a Catmull-Rom spline. + * - lanczos2: Use a Lanczos kernel with a=2. + * - lanczos3: Use a Lanczos kernel with a=3 (the default). + * + * @param width pixels wide the resultant image should be. Use null or undefined to auto-scale the width to match the height. + * @param height pixels high the resultant image should be. Use null or undefined to auto-scale the height to match the width. + * @param options resize options + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + resize(widthOrOptions?: number | ResizeOptions | null, height?: number | null, options?: ResizeOptions): Sharp; + + /** + * Shorthand for resize(null, null, options); + * + * @param options resize options + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + resize(options: ResizeOptions): Sharp; + + /** + * Extend / pad / extrude one or more edges of the image with either + * the provided background colour or pixels derived from the image. + * This operation will always occur after resizing and extraction, if any. + * @param extend single pixel count to add to all edges or an Object with per-edge counts + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + extend(extend: number | ExtendOptions): Sharp; + + /** + * Extract a region of the image. + * - Use extract() before resize() for pre-resize extraction. + * - Use extract() after resize() for post-resize extraction. + * - Use extract() before and after for both. + * + * @param region The region to extract + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + extract(region: Region): Sharp; + + /** + * Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel. + * Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels. + * The info response Object will contain trimOffsetLeft and trimOffsetTop properties. + * @param options trim options + * @throws {Error} Invalid parameters + * @returns A sharp instance that can be used to chain operations + */ + trim(options?: TrimOptions): Sharp; + + //#endregion + } + + type SharpInput = Buffer + | ArrayBuffer + | Uint8Array + | Uint8ClampedArray + | Int8Array + | Uint16Array + | Int16Array + | Uint32Array + | Int32Array + | Float32Array + | Float64Array + | string; + + interface SharpOptions { + /** + * Auto-orient based on the EXIF `Orientation` tag, if present. + * Mirroring is supported and may infer the use of a flip operation. + * + * Using this option will remove the EXIF `Orientation` tag, if any. + */ + autoOrient?: boolean | undefined; + /** + * When to abort processing of invalid pixel data, one of (in order of sensitivity): + * 'none' (least), 'truncated', 'error' or 'warning' (most), highers level imply lower levels, invalid metadata will always abort. (optional, default 'warning') + */ + failOn?: FailOnOptions | undefined; + /** + * By default halt processing and raise an error when loading invalid images. + * Set this flag to false if you'd rather apply a "best effort" to decode images, + * even if the data is corrupt or invalid. (optional, default true) + * + * @deprecated Use `failOn` instead + */ + failOnError?: boolean | undefined; + /** + * Do not process input images where the number of pixels (width x height) exceeds this limit. + * Assumes image dimensions contained in the input metadata can be trusted. + * An integral Number of pixels, zero or false to remove limit, true to use default limit of 268402689 (0x3FFF x 0x3FFF). (optional, default 268402689) + */ + limitInputPixels?: number | boolean | undefined; + /** Set this to true to remove safety features that help prevent memory exhaustion (SVG, PNG). (optional, default false) */ + unlimited?: boolean | undefined; + /** Set this to false to use random access rather than sequential read. Some operations will do this automatically. */ + sequentialRead?: boolean | undefined; + /** Number representing the DPI for vector images in the range 1 to 100000. (optional, default 72) */ + density?: number | undefined; + /** Should the embedded ICC profile, if any, be ignored. */ + ignoreIcc?: boolean | undefined; + /** Number of pages to extract for multi-page input (GIF, TIFF, PDF), use -1 for all pages */ + pages?: number | undefined; + /** Page number to start extracting from for multi-page input (GIF, TIFF, PDF), zero based. (optional, default 0) */ + page?: number | undefined; + /** TIFF specific input options */ + tiff?: TiffInputOptions | undefined; + /** SVG specific input options */ + svg?: SvgInputOptions | undefined; + /** PDF specific input options */ + pdf?: PdfInputOptions | undefined; + /** OpenSlide specific input options */ + openSlide?: OpenSlideInputOptions | undefined; + /** JPEG 2000 specific input options */ + jp2?: Jp2InputOptions | undefined; + /** Deprecated: use tiff.subifd instead */ + subifd?: number | undefined; + /** Deprecated: use pdf.background instead */ + pdfBackground?: Colour | Color | undefined; + /** Deprecated: use openSlide.level instead */ + level?: number | undefined; + /** Set to `true` to read all frames/pages of an animated image (equivalent of setting `pages` to `-1`). (optional, default false) */ + animated?: boolean | undefined; + /** Describes raw pixel input image data. See raw() for pixel ordering. */ + raw?: CreateRaw | undefined; + /** Describes a new image to be created. */ + create?: Create | undefined; + /** Describes a new text image to be created. */ + text?: CreateText | undefined; + /** Describes how array of input images should be joined. */ + join?: Join | undefined; + } + + interface CacheOptions { + /** Is the maximum memory in MB to use for this cache (optional, default 50) */ + memory?: number | undefined; + /** Is the maximum number of files to hold open (optional, default 20) */ + files?: number | undefined; + /** Is the maximum number of operations to cache (optional, default 100) */ + items?: number | undefined; + } + + interface TimeoutOptions { + /** Number of seconds after which processing will be stopped (default 0, eg disabled) */ + seconds: number; + } + + interface SharpCounters { + /** The number of tasks this module has queued waiting for libuv to provide a worker thread from its pool. */ + queue: number; + /** The number of resize tasks currently being processed. */ + process: number; + } + + interface Raw { + width: number; + height: number; + channels: Channels; + } + + interface CreateRaw extends Raw { + /** Specifies that the raw input has already been premultiplied, set to true to avoid sharp premultiplying the image. (optional, default false) */ + premultiplied?: boolean | undefined; + /** The height of each page/frame for animated images, must be an integral factor of the overall image height. */ + pageHeight?: number | undefined; + } + + type CreateChannels = 3 | 4; + + interface Create { + /** Number of pixels wide. */ + width: number; + /** Number of pixels high. */ + height: number; + /** Number of bands, 3 for RGB, 4 for RGBA */ + channels: CreateChannels; + /** Parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. */ + background: Colour | Color; + /** Describes a noise to be created. */ + noise?: Noise | undefined; + /** The height of each page/frame for animated images, must be an integral factor of the overall image height. */ + pageHeight?: number | undefined; + + } + + interface CreateText { + /** Text to render as a UTF-8 string. It can contain Pango markup, for example `LeMonde`. */ + text: string; + /** Font name to render with. */ + font?: string; + /** Absolute filesystem path to a font file that can be used by `font`. */ + fontfile?: string; + /** Integral number of pixels to word-wrap at. Lines of text wider than this will be broken at word boundaries. (optional, default `0`) */ + width?: number; + /** + * Integral number of pixels high. When defined, `dpi` will be ignored and the text will automatically fit the pixel resolution + * defined by `width` and `height`. Will be ignored if `width` is not specified or set to 0. (optional, default `0`) + */ + height?: number; + /** Text alignment ('left', 'centre', 'center', 'right'). (optional, default 'left') */ + align?: TextAlign; + /** Set this to true to apply justification to the text. (optional, default `false`) */ + justify?: boolean; + /** The resolution (size) at which to render the text. Does not take effect if `height` is specified. (optional, default `72`) */ + dpi?: number; + /** + * Set this to true to enable RGBA output. This is useful for colour emoji rendering, + * or support for pango markup features like `Red!`. (optional, default `false`) + */ + rgba?: boolean; + /** Text line height in points. Will use the font line height if none is specified. (optional, default `0`) */ + spacing?: number; + /** Word wrapping style when width is provided, one of: 'word', 'char', 'word-char' (prefer word, fallback to char) or 'none' */ + wrap?: TextWrap; + } + + interface Join { + /** Number of images per row. */ + across?: number | undefined; + /** Treat input as frames of an animated image. */ + animated?: boolean | undefined; + /** Space between images, in pixels. */ + shim?: number | undefined; + /** Background colour. */ + background?: Colour | Color | undefined; + /** Horizontal alignment. */ + halign?: HorizontalAlignment | undefined; + /** Vertical alignment. */ + valign?: VerticalAlignment | undefined; + } + + interface TiffInputOptions { + /** Sub Image File Directory to extract, defaults to main image. Use -1 for all subifds. */ + subifd?: number | undefined; + } + + interface SvgInputOptions { + /** Custom CSS for SVG input, applied with a User Origin during the CSS cascade. */ + stylesheet?: string | undefined; + /** Set to `true` to render SVG input at 32-bits per channel (128-bit) instead of 8-bits per channel (32-bit) RGBA. */ + highBitdepth?: boolean | undefined; + } + + interface PdfInputOptions { + /** Background colour to use when PDF is partially transparent. Requires the use of a globally-installed libvips compiled with support for PDFium, Poppler, ImageMagick or GraphicsMagick. */ + background?: Colour | Color | undefined; + } + + interface OpenSlideInputOptions { + /** Level to extract from a multi-level input, zero based. (optional, default 0) */ + level?: number | undefined; + } + + interface Jp2InputOptions { + /** Set to `true` to load JPEG 2000 images using [oneshot mode](https://github.com/libvips/libvips/issues/4205) */ + oneshot?: boolean | undefined; + } + + interface ExifDir { + [k: string]: string; + } + + interface Exif { + 'IFD0'?: ExifDir; + 'IFD1'?: ExifDir; + 'IFD2'?: ExifDir; + 'IFD3'?: ExifDir; + } + + interface WriteableMetadata { + /** Number of pixels per inch (DPI) */ + density?: number | undefined; + /** Value between 1 and 8, used to update the EXIF Orientation tag. */ + orientation?: number | undefined; + /** + * Filesystem path to output ICC profile, defaults to sRGB. + * @deprecated Use `withIccProfile()` instead. + */ + icc?: string | undefined; + /** + * Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. + * @deprecated Use `withExif()` or `withExifMerge()` instead. + */ + exif?: Exif | undefined; + } + + interface Metadata { + /** Number value of the EXIF Orientation header, if present */ + orientation?: number | undefined; + /** Name of decoder used to decompress image data e.g. jpeg, png, webp, gif, svg */ + format: keyof FormatEnum; + /** Total size of image in bytes, for Stream and Buffer input only */ + size?: number | undefined; + /** Number of pixels wide (EXIF orientation is not taken into consideration) */ + width: number; + /** Number of pixels high (EXIF orientation is not taken into consideration) */ + height: number; + /** Any changed metadata after the image orientation is applied. */ + autoOrient: { + /** Number of pixels wide (EXIF orientation is taken into consideration) */ + width: number; + /** Number of pixels high (EXIF orientation is taken into consideration) */ + height: number; + }; + /** Name of colour space interpretation */ + space: keyof ColourspaceEnum; + /** Number of bands e.g. 3 for sRGB, 4 for CMYK */ + channels: Channels; + /** Name of pixel depth format e.g. uchar, char, ushort, float ... */ + depth: keyof DepthEnum; + /** Number of pixels per inch (DPI), if present */ + density?: number | undefined; + /** String containing JPEG chroma subsampling, 4:2:0 or 4:4:4 for RGB, 4:2:0:4 or 4:4:4:4 for CMYK */ + chromaSubsampling?: string | undefined; + /** Boolean indicating whether the image is interlaced using a progressive scan */ + isProgressive: boolean; + /** Boolean indicating whether the image is palette-based (GIF, PNG). */ + isPalette: boolean; + /** Number of bits per sample for each channel (GIF, PNG). */ + bitsPerSample?: number | undefined; + /** Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP */ + pages?: number | undefined; + /** Number of pixels high each page in a multi-page image will be. */ + pageHeight?: number | undefined; + /** Number of times to loop an animated image, zero refers to a continuous loop. */ + loop?: number | undefined; + /** Delay in ms between each page in an animated image, provided as an array of integers. */ + delay?: number[] | undefined; + /** Number of the primary page in a HEIF image */ + pagePrimary?: number | undefined; + /** Boolean indicating the presence of an embedded ICC profile */ + hasProfile: boolean; + /** Boolean indicating the presence of an alpha transparency channel */ + hasAlpha: boolean; + /** Buffer containing raw EXIF data, if present */ + exif?: Buffer | undefined; + /** Buffer containing raw ICC profile data, if present */ + icc?: Buffer | undefined; + /** Buffer containing raw IPTC data, if present */ + iptc?: Buffer | undefined; + /** Buffer containing raw XMP data, if present */ + xmp?: Buffer | undefined; + /** String containing XMP data, if valid UTF-8 */ + xmpAsString?: string | undefined; + /** Buffer containing raw TIFFTAG_PHOTOSHOP data, if present */ + tifftagPhotoshop?: Buffer | undefined; + /** The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC) */ + compression?: 'av1' | 'hevc'; + /** Default background colour, if present, for PNG (bKGD) and GIF images */ + background?: { r: number; g: number; b: number } | { gray: number }; + /** Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide */ + levels?: LevelMetadata[] | undefined; + /** Number of Sub Image File Directories in an OME-TIFF image */ + subifds?: number | undefined; + /** The unit of resolution (density) */ + resolutionUnit?: 'inch' | 'cm' | undefined; + /** String containing format for images loaded via *magick */ + formatMagick?: string | undefined; + /** Array of keyword/text pairs representing PNG text blocks, if present. */ + comments?: CommentsMetadata[] | undefined; + } + + interface LevelMetadata { + width: number; + height: number; + } + + interface CommentsMetadata { + keyword: string; + text: string; + } + + interface Stats { + /** Array of channel statistics for each channel in the image. */ + channels: ChannelStats[]; + /** Value to identify if the image is opaque or transparent, based on the presence and use of alpha channel */ + isOpaque: boolean; + /** Histogram-based estimation of greyscale entropy, discarding alpha channel if any (experimental) */ + entropy: number; + /** Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any (experimental) */ + sharpness: number; + /** Object containing most dominant sRGB colour based on a 4096-bin 3D histogram (experimental) */ + dominant: { r: number; g: number; b: number }; + } + + interface ChannelStats { + /** minimum value in the channel */ + min: number; + /** maximum value in the channel */ + max: number; + /** sum of all values in a channel */ + sum: number; + /** sum of squared values in a channel */ + squaresSum: number; + /** mean of the values in a channel */ + mean: number; + /** standard deviation for the values in a channel */ + stdev: number; + /** x-coordinate of one of the pixel where the minimum lies */ + minX: number; + /** y-coordinate of one of the pixel where the minimum lies */ + minY: number; + /** x-coordinate of one of the pixel where the maximum lies */ + maxX: number; + /** y-coordinate of one of the pixel where the maximum lies */ + maxY: number; + } + + interface OutputOptions { + /** Force format output, otherwise attempt to use input format (optional, default true) */ + force?: boolean | undefined; + } + + interface WithIccProfileOptions { + /** Should the ICC profile be included in the output image metadata? (optional, default true) */ + attach?: boolean | undefined; + } + + interface JpegOptions extends OutputOptions { + /** Quality, integer 1-100 (optional, default 80) */ + quality?: number | undefined; + /** Use progressive (interlace) scan (optional, default false) */ + progressive?: boolean | undefined; + /** Set to '4:4:4' to prevent chroma subsampling when quality <= 90 (optional, default '4:2:0') */ + chromaSubsampling?: string | undefined; + /** Apply trellis quantisation (optional, default false) */ + trellisQuantisation?: boolean | undefined; + /** Apply overshoot deringing (optional, default false) */ + overshootDeringing?: boolean | undefined; + /** Optimise progressive scans, forces progressive (optional, default false) */ + optimiseScans?: boolean | undefined; + /** Alternative spelling of optimiseScans (optional, default false) */ + optimizeScans?: boolean | undefined; + /** Optimise Huffman coding tables (optional, default true) */ + optimiseCoding?: boolean | undefined; + /** Alternative spelling of optimiseCoding (optional, default true) */ + optimizeCoding?: boolean | undefined; + /** Quantization table to use, integer 0-8 (optional, default 0) */ + quantisationTable?: number | undefined; + /** Alternative spelling of quantisationTable (optional, default 0) */ + quantizationTable?: number | undefined; + /** Use mozjpeg defaults (optional, default false) */ + mozjpeg?: boolean | undefined; + } + + interface Jp2Options extends OutputOptions { + /** Quality, integer 1-100 (optional, default 80) */ + quality?: number; + /** Use lossless compression mode (optional, default false) */ + lossless?: boolean; + /** Horizontal tile size (optional, default 512) */ + tileWidth?: number; + /** Vertical tile size (optional, default 512) */ + tileHeight?: number; + /** Set to '4:2:0' to enable chroma subsampling (optional, default '4:4:4') */ + chromaSubsampling?: '4:4:4' | '4:2:0'; + } + + interface JxlOptions extends OutputOptions { + /** Maximum encoding error, between 0 (highest quality) and 15 (lowest quality) (optional, default 1.0) */ + distance?: number; + /** Calculate distance based on JPEG-like quality, between 1 and 100, overrides distance if specified */ + quality?: number; + /** Target decode speed tier, between 0 (highest quality) and 4 (lowest quality) (optional, default 0) */ + decodingTier?: number; + /** Use lossless compression (optional, default false) */ + lossless?: boolean; + /** CPU effort, between 3 (fastest) and 9 (slowest) (optional, default 7) */ + effort?: number | undefined; + } + + interface WebpOptions extends OutputOptions, AnimationOptions { + /** Quality, integer 1-100 (optional, default 80) */ + quality?: number | undefined; + /** Quality of alpha layer, number from 0-100 (optional, default 100) */ + alphaQuality?: number | undefined; + /** Use lossless compression mode (optional, default false) */ + lossless?: boolean | undefined; + /** Use near_lossless compression mode (optional, default false) */ + nearLossless?: boolean | undefined; + /** Use high quality chroma subsampling (optional, default false) */ + smartSubsample?: boolean | undefined; + /** Auto-adjust the deblocking filter, slow but can improve low contrast edges (optional, default false) */ + smartDeblock?: boolean | undefined; + /** Level of CPU effort to reduce file size, integer 0-6 (optional, default 4) */ + effort?: number | undefined; + /** Prevent use of animation key frames to minimise file size (slow) (optional, default false) */ + minSize?: boolean; + /** Allow mixture of lossy and lossless animation frames (slow) (optional, default false) */ + mixed?: boolean; + /** Preset options: one of default, photo, picture, drawing, icon, text (optional, default 'default') */ + preset?: keyof PresetEnum | undefined; + } + + interface AvifOptions extends OutputOptions { + /** quality, integer 1-100 (optional, default 50) */ + quality?: number | undefined; + /** use lossless compression (optional, default false) */ + lossless?: boolean | undefined; + /** Level of CPU effort to reduce file size, between 0 (fastest) and 9 (slowest) (optional, default 4) */ + effort?: number | undefined; + /** set to '4:2:0' to use chroma subsampling, requires libvips v8.11.0 (optional, default '4:4:4') */ + chromaSubsampling?: string | undefined; + /** Set bitdepth to 8, 10 or 12 bit (optional, default 8) */ + bitdepth?: 8 | 10 | 12 | undefined; + } + + interface HeifOptions extends OutputOptions { + /** quality, integer 1-100 (optional, default 50) */ + quality?: number | undefined; + /** compression format: av1, hevc (optional, default 'av1') */ + compression?: 'av1' | 'hevc' | undefined; + /** use lossless compression (optional, default false) */ + lossless?: boolean | undefined; + /** Level of CPU effort to reduce file size, between 0 (fastest) and 9 (slowest) (optional, default 4) */ + effort?: number | undefined; + /** set to '4:2:0' to use chroma subsampling (optional, default '4:4:4') */ + chromaSubsampling?: string | undefined; + /** Set bitdepth to 8, 10 or 12 bit (optional, default 8) */ + bitdepth?: 8 | 10 | 12 | undefined; + } + + interface GifOptions extends OutputOptions, AnimationOptions { + /** Re-use existing palette, otherwise generate new (slow) */ + reuse?: boolean | undefined; + /** Use progressive (interlace) scan */ + progressive?: boolean | undefined; + /** Maximum number of palette entries, including transparency, between 2 and 256 (optional, default 256) */ + colours?: number | undefined; + /** Alternative spelling of "colours". Maximum number of palette entries, including transparency, between 2 and 256 (optional, default 256) */ + colors?: number | undefined; + /** Level of CPU effort to reduce file size, between 1 (fastest) and 10 (slowest) (optional, default 7) */ + effort?: number | undefined; + /** Level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) (optional, default 1.0) */ + dither?: number | undefined; + /** Maximum inter-frame error for transparency, between 0 (lossless) and 32 (optional, default 0) */ + interFrameMaxError?: number | undefined; + /** Maximum inter-palette error for palette reuse, between 0 and 256 (optional, default 3) */ + interPaletteMaxError?: number | undefined; + /** Keep duplicate frames in the output instead of combining them (optional, default false) */ + keepDuplicateFrames?: boolean | undefined; + } + + interface TiffOptions extends OutputOptions { + /** Quality, integer 1-100 (optional, default 80) */ + quality?: number | undefined; + /** Compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k (optional, default 'jpeg') */ + compression?: string | undefined; + /** Compression predictor options: none, horizontal, float (optional, default 'horizontal') */ + predictor?: string | undefined; + /** Write an image pyramid (optional, default false) */ + pyramid?: boolean | undefined; + /** Write a tiled tiff (optional, default false) */ + tile?: boolean | undefined; + /** Horizontal tile size (optional, default 256) */ + tileWidth?: number | undefined; + /** Vertical tile size (optional, default 256) */ + tileHeight?: number | undefined; + /** Horizontal resolution in pixels/mm (optional, default 1.0) */ + xres?: number | undefined; + /** Vertical resolution in pixels/mm (optional, default 1.0) */ + yres?: number | undefined; + /** Reduce bitdepth to 1, 2 or 4 bit (optional, default 8) */ + bitdepth?: 1 | 2 | 4 | 8 | undefined; + /** Write 1-bit images as miniswhite (optional, default false) */ + miniswhite?: boolean | undefined; + /** Resolution unit options: inch, cm (optional, default 'inch') */ + resolutionUnit?: 'inch' | 'cm' | undefined; + } + + interface PngOptions extends OutputOptions { + /** Use progressive (interlace) scan (optional, default false) */ + progressive?: boolean | undefined; + /** zlib compression level, 0-9 (optional, default 6) */ + compressionLevel?: number | undefined; + /** Use adaptive row filtering (optional, default false) */ + adaptiveFiltering?: boolean | undefined; + /** Use the lowest number of colours needed to achieve given quality (optional, default `100`) */ + quality?: number | undefined; + /** Level of CPU effort to reduce file size, between 1 (fastest) and 10 (slowest), sets palette to true (optional, default 7) */ + effort?: number | undefined; + /** Quantise to a palette-based image with alpha transparency support (optional, default false) */ + palette?: boolean | undefined; + /** Maximum number of palette entries (optional, default 256) */ + colours?: number | undefined; + /** Alternative Spelling of "colours". Maximum number of palette entries (optional, default 256) */ + colors?: number | undefined; + /** Level of Floyd-Steinberg error diffusion (optional, default 1.0) */ + dither?: number | undefined; + } + + interface RotateOptions { + /** parsed by the color module to extract values for red, green, blue and alpha. (optional, default "#000000") */ + background?: Colour | Color | undefined; + } + + type Precision = 'integer' | 'float' | 'approximate'; + + interface BlurOptions { + /** A value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2` */ + sigma: number; + /** A value between 0.001 and 1. A smaller value will generate a larger, more accurate mask. */ + minAmplitude?: number; + /** How accurate the operation should be, one of: integer, float, approximate. (optional, default "integer") */ + precision?: Precision | undefined; + } + + interface FlattenOptions { + /** background colour, parsed by the color module, defaults to black. (optional, default {r:0,g:0,b:0}) */ + background?: Colour | Color | undefined; + } + + interface NegateOptions { + /** whether or not to negate any alpha channel. (optional, default true) */ + alpha?: boolean | undefined; + } + + interface NormaliseOptions { + /** Percentile below which luminance values will be underexposed. */ + lower?: number | undefined; + /** Percentile above which luminance values will be overexposed. */ + upper?: number | undefined; + } + + interface ResizeOptions { + /** Alternative means of specifying width. If both are present this takes priority. */ + width?: number | undefined; + /** Alternative means of specifying height. If both are present this takes priority. */ + height?: number | undefined; + /** How the image should be resized to fit both provided dimensions, one of cover, contain, fill, inside or outside. (optional, default 'cover') */ + fit?: keyof FitEnum | undefined; + /** Position, gravity or strategy to use when fit is cover or contain. (optional, default 'centre') */ + position?: number | string | undefined; + /** Background colour when using a fit of contain, parsed by the color module, defaults to black without transparency. (optional, default {r:0,g:0,b:0,alpha:1}) */ + background?: Colour | Color | undefined; + /** The kernel to use for image reduction. (optional, default 'lanczos3') */ + kernel?: keyof KernelEnum | undefined; + /** Do not enlarge if the width or height are already less than the specified dimensions, equivalent to GraphicsMagick's > geometry option. (optional, default false) */ + withoutEnlargement?: boolean | undefined; + /** Do not reduce if the width or height are already greater than the specified dimensions, equivalent to GraphicsMagick's < geometry option. (optional, default false) */ + withoutReduction?: boolean | undefined; + /** Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern on some images. (optional, default true) */ + fastShrinkOnLoad?: boolean | undefined; + } + + interface Region { + /** zero-indexed offset from left edge */ + left: number; + /** zero-indexed offset from top edge */ + top: number; + /** dimension of extracted image */ + width: number; + /** dimension of extracted image */ + height: number; + } + + interface Noise { + /** type of generated noise, currently only gaussian is supported. */ + type: 'gaussian'; + /** mean of pixels in generated noise. */ + mean?: number | undefined; + /** standard deviation of pixels in generated noise. */ + sigma?: number | undefined; + } + + type ExtendWith = 'background' | 'copy' | 'repeat' | 'mirror'; + + interface ExtendOptions { + /** single pixel count to top edge (optional, default 0) */ + top?: number | undefined; + /** single pixel count to left edge (optional, default 0) */ + left?: number | undefined; + /** single pixel count to bottom edge (optional, default 0) */ + bottom?: number | undefined; + /** single pixel count to right edge (optional, default 0) */ + right?: number | undefined; + /** background colour, parsed by the color module, defaults to black without transparency. (optional, default {r:0,g:0,b:0,alpha:1}) */ + background?: Colour | Color | undefined; + /** how the extension is done, one of: "background", "copy", "repeat", "mirror" (optional, default `'background'`) */ + extendWith?: ExtendWith | undefined; + } + + interface TrimOptions { + /** Background colour, parsed by the color module, defaults to that of the top-left pixel. (optional) */ + background?: Colour | Color | undefined; + /** Allowed difference from the above colour, a positive number. (optional, default 10) */ + threshold?: number | undefined; + /** Does the input more closely resemble line art (e.g. vector) rather than being photographic? (optional, default false) */ + lineArt?: boolean | undefined; + } + + interface RawOptions { + depth?: 'char' | 'uchar' | 'short' | 'ushort' | 'int' | 'uint' | 'float' | 'complex' | 'double' | 'dpcomplex'; + } + + /** 1 for grayscale, 2 for grayscale + alpha, 3 for sRGB, 4 for CMYK or RGBA */ + type Channels = 1 | 2 | 3 | 4; + + interface RGBA { + r?: number | undefined; + g?: number | undefined; + b?: number | undefined; + alpha?: number | undefined; + } + + type Colour = string | RGBA; + type Color = Colour; + + interface Kernel { + /** width of the kernel in pixels. */ + width: number; + /** height of the kernel in pixels. */ + height: number; + /** Array of length width*height containing the kernel values. */ + kernel: ArrayLike; + /** the scale of the kernel in pixels. (optional, default sum) */ + scale?: number | undefined; + /** the offset of the kernel in pixels. (optional, default 0) */ + offset?: number | undefined; + } + + interface ClaheOptions { + /** width of the region */ + width: number; + /** height of the region */ + height: number; + /** max slope of the cumulative contrast. A value of 0 disables contrast limiting. Valid values are integers in the range 0-100 (inclusive) (optional, default 3) */ + maxSlope?: number | undefined; + } + + interface ThresholdOptions { + /** convert to single channel greyscale. (optional, default true) */ + greyscale?: boolean | undefined; + /** alternative spelling for greyscale. (optional, default true) */ + grayscale?: boolean | undefined; + } + + interface OverlayOptions extends SharpOptions { + /** Buffer containing image data, String containing the path to an image file, or Create object */ + input?: string | Buffer | { create: Create } | { text: CreateText } | { raw: CreateRaw } | undefined; + /** how to blend this image with the image below. (optional, default `'over'`) */ + blend?: Blend | undefined; + /** gravity at which to place the overlay. (optional, default 'centre') */ + gravity?: Gravity | undefined; + /** the pixel offset from the top edge. */ + top?: number | undefined; + /** the pixel offset from the left edge. */ + left?: number | undefined; + /** set to true to repeat the overlay image across the entire image with the given gravity. (optional, default false) */ + tile?: boolean | undefined; + /** Set to true to avoid premultipling the image below. Equivalent to the --premultiplied vips option. */ + premultiplied?: boolean | undefined; + /** number representing the DPI for vector overlay image. (optional, default 72)*/ + density?: number | undefined; + /** Set to true to read all frames/pages of an animated image. (optional, default false) */ + animated?: boolean | undefined; + /** see sharp() constructor, (optional, default 'warning') */ + failOn?: FailOnOptions | undefined; + /** see sharp() constructor, (optional, default 268402689) */ + limitInputPixels?: number | boolean | undefined; + /** see sharp() constructor, (optional, default false) */ + autoOrient?: boolean | undefined; + } + + interface TileOptions { + /** Tile size in pixels, a value between 1 and 8192. (optional, default 256) */ + size?: number | undefined; + /** Tile overlap in pixels, a value between 0 and 8192. (optional, default 0) */ + overlap?: number | undefined; + /** Tile angle of rotation, must be a multiple of 90. (optional, default 0) */ + angle?: number | undefined; + /** background colour, parsed by the color module, defaults to white without transparency. (optional, default {r:255,g:255,b:255,alpha:1}) */ + background?: string | RGBA | undefined; + /** How deep to make the pyramid, possible values are "onepixel", "onetile" or "one" (default based on layout) */ + depth?: string | undefined; + /** Threshold to skip tile generation, a value 0 - 255 for 8-bit images or 0 - 65535 for 16-bit images */ + skipBlanks?: number | undefined; + /** Tile container, with value fs (filesystem) or zip (compressed file). (optional, default 'fs') */ + container?: TileContainer | undefined; + /** Filesystem layout, possible values are dz, iiif, iiif3, zoomify or google. (optional, default 'dz') */ + layout?: TileLayout | undefined; + /** Centre image in tile. (optional, default false) */ + centre?: boolean | undefined; + /** Alternative spelling of centre. (optional, default false) */ + center?: boolean | undefined; + /** When layout is iiif/iiif3, sets the @id/id attribute of info.json (optional, default 'https://example.com/iiif') */ + id?: string | undefined; + /** The name of the directory within the zip file when container is `zip`. */ + basename?: string | undefined; + } + + interface AnimationOptions { + /** Number of animation iterations, a value between 0 and 65535. Use 0 for infinite animation. (optional, default 0) */ + loop?: number | undefined; + /** delay(s) between animation frames (in milliseconds), each value between 0 and 65535. (optional) */ + delay?: number | number[] | undefined; + } + + interface SharpenOptions { + /** The sigma of the Gaussian mask, where sigma = 1 + radius / 2, between 0.000001 and 10000 */ + sigma: number; + /** The level of sharpening to apply to "flat" areas, between 0 and 1000000 (optional, default 1.0) */ + m1?: number | undefined; + /** The level of sharpening to apply to "jagged" areas, between 0 and 1000000 (optional, default 2.0) */ + m2?: number | undefined; + /** Threshold between "flat" and "jagged", between 0 and 1000000 (optional, default 2.0) */ + x1?: number | undefined; + /** Maximum amount of brightening, between 0 and 1000000 (optional, default 10.0) */ + y2?: number | undefined; + /** Maximum amount of darkening, between 0 and 1000000 (optional, default 20.0) */ + y3?: number | undefined; + } + + interface AffineOptions { + /** Parsed by the color module to extract values for red, green, blue and alpha. (optional, default "#000000") */ + background?: string | object | undefined; + /** Input horizontal offset (optional, default 0) */ + idx?: number | undefined; + /** Input vertical offset (optional, default 0) */ + idy?: number | undefined; + /** Output horizontal offset (optional, default 0) */ + odx?: number | undefined; + /** Output horizontal offset (optional, default 0) */ + ody?: number | undefined; + /** Interpolator (optional, default sharp.interpolators.bicubic) */ + interpolator?: Interpolators[keyof Interpolators] | undefined; + } + + interface OutputInfo { + format: string; + size: number; + width: number; + height: number; + channels: Channels; + /** indicating if premultiplication was used */ + premultiplied: boolean; + /** Only defined when using a crop strategy */ + cropOffsetLeft?: number | undefined; + /** Only defined when using a crop strategy */ + cropOffsetTop?: number | undefined; + /** Only defined when using a trim method */ + trimOffsetLeft?: number | undefined; + /** Only defined when using a trim method */ + trimOffsetTop?: number | undefined; + /** DPI the font was rendered at, only defined when using `text` input */ + textAutofitDpi?: number | undefined; + /** When using the attention crop strategy, the focal point of the cropped region */ + attentionX?: number | undefined; + attentionY?: number | undefined; + /** Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP */ + pages?: number | undefined; + /** Number of pixels high each page in a multi-page image will be. */ + pageHeight?: number | undefined; + } + + interface AvailableFormatInfo { + id: string; + input: { file: boolean; buffer: boolean; stream: boolean; fileSuffix?: string[] }; + output: { file: boolean; buffer: boolean; stream: boolean; alias?: string[] }; + } + + interface FitEnum { + contain: 'contain'; + cover: 'cover'; + fill: 'fill'; + inside: 'inside'; + outside: 'outside'; + } + + interface KernelEnum { + nearest: 'nearest'; + cubic: 'cubic'; + linear: 'linear'; + mitchell: 'mitchell'; + lanczos2: 'lanczos2'; + lanczos3: 'lanczos3'; + mks2013: 'mks2013'; + mks2021: 'mks2021'; + } + + interface PresetEnum { + default: 'default'; + picture: 'picture'; + photo: 'photo'; + drawing: 'drawing'; + icon: 'icon'; + text: 'text'; + } + + interface BoolEnum { + and: 'and'; + or: 'or'; + eor: 'eor'; + } + + interface ColourspaceEnum { + 'b-w': string; + cmc: string; + cmyk: string; + fourier: string; + grey16: string; + histogram: string; + hsv: string; + lab: string; + labq: string; + labs: string; + lch: string; + matrix: string; + multiband: string; + rgb: string; + rgb16: string; + scrgb: string; + srgb: string; + xyz: string; + yxy: string; + } + + interface DepthEnum { + char: string; + complex: string; + double: string; + dpcomplex: string; + float: string; + int: string; + short: string; + uchar: string; + uint: string; + ushort: string; + } + + type FailOnOptions = 'none' | 'truncated' | 'error' | 'warning'; + + type TextAlign = 'left' | 'centre' | 'center' | 'right'; + + type TextWrap = 'word' | 'char' | 'word-char' | 'none'; + + type HorizontalAlignment = 'left' | 'centre' | 'center' | 'right'; + + type VerticalAlignment = 'top' | 'centre' | 'center' | 'bottom'; + + type TileContainer = 'fs' | 'zip'; + + type TileLayout = 'dz' | 'iiif' | 'iiif3' | 'zoomify' | 'google'; + + type Blend = + | 'clear' + | 'source' + | 'over' + | 'in' + | 'out' + | 'atop' + | 'dest' + | 'dest-over' + | 'dest-in' + | 'dest-out' + | 'dest-atop' + | 'xor' + | 'add' + | 'saturate' + | 'multiply' + | 'screen' + | 'overlay' + | 'darken' + | 'lighten' + | 'color-dodge' + | 'colour-dodge' + | 'color-burn' + | 'colour-burn' + | 'hard-light' + | 'soft-light' + | 'difference' + | 'exclusion'; + + type Gravity = number | string; + + interface GravityEnum { + north: number; + northeast: number; + southeast: number; + south: number; + southwest: number; + west: number; + northwest: number; + east: number; + center: number; + centre: number; + } + + interface StrategyEnum { + entropy: number; + attention: number; + } + + interface FormatEnum { + avif: AvailableFormatInfo; + dcraw: AvailableFormatInfo; + dz: AvailableFormatInfo; + exr: AvailableFormatInfo; + fits: AvailableFormatInfo; + gif: AvailableFormatInfo; + heif: AvailableFormatInfo; + input: AvailableFormatInfo; + jpeg: AvailableFormatInfo; + jpg: AvailableFormatInfo; + jp2: AvailableFormatInfo; + jxl: AvailableFormatInfo; + magick: AvailableFormatInfo; + openslide: AvailableFormatInfo; + pdf: AvailableFormatInfo; + png: AvailableFormatInfo; + ppm: AvailableFormatInfo; + rad: AvailableFormatInfo; + raw: AvailableFormatInfo; + svg: AvailableFormatInfo; + tiff: AvailableFormatInfo; + tif: AvailableFormatInfo; + v: AvailableFormatInfo; + webp: AvailableFormatInfo; + } + + interface CacheResult { + memory: { current: number; high: number; max: number }; + files: { current: number; max: number }; + items: { current: number; max: number }; + } + + interface Interpolators { + /** [Nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). Suitable for image enlargement only. */ + nearest: 'nearest'; + /** [Bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation). Faster than bicubic but with less smooth results. */ + bilinear: 'bilinear'; + /** [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) (the default). */ + bicubic: 'bicubic'; + /** + * [LBB interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100). + * Prevents some "[acutance](http://en.wikipedia.org/wiki/Acutance)" but typically reduces performance by a factor of 2. + */ + locallyBoundedBicubic: 'lbb'; + /** [Nohalo interpolation](http://eprints.soton.ac.uk/268086/). Prevents acutance but typically reduces performance by a factor of 3. */ + nohalo: 'nohalo'; + /** [VSQBS interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents "staircasing" when enlarging. */ + vertexSplitQuadraticBasisSpline: 'vsqbs'; + } + + type Matrix2x2 = [[number, number], [number, number]]; + type Matrix3x3 = [[number, number, number], [number, number, number], [number, number, number]]; + type Matrix4x4 = [[number, number, number, number], [number, number, number, number], [number, number, number, number], [number, number, number, number]]; +} + +export = sharp; diff --git a/server/node_modules/sharp/lib/index.js b/server/node_modules/sharp/lib/index.js new file mode 100644 index 0000000..8cfc08a --- /dev/null +++ b/server/node_modules/sharp/lib/index.js @@ -0,0 +1,16 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const Sharp = require('./constructor'); +require('./input')(Sharp); +require('./resize')(Sharp); +require('./composite')(Sharp); +require('./operation')(Sharp); +require('./colour')(Sharp); +require('./channel')(Sharp); +require('./output')(Sharp); +require('./utility')(Sharp); + +module.exports = Sharp; diff --git a/server/node_modules/sharp/lib/input.js b/server/node_modules/sharp/lib/input.js new file mode 100644 index 0000000..aca0b16 --- /dev/null +++ b/server/node_modules/sharp/lib/input.js @@ -0,0 +1,811 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const is = require('./is'); +const sharp = require('./sharp'); + +/** + * Justification alignment + * @member + * @private + */ +const align = { + left: 'low', + top: 'low', + low: 'low', + center: 'centre', + centre: 'centre', + right: 'high', + bottom: 'high', + high: 'high' +}; + +const inputStreamParameters = [ + // Limits and error handling + 'failOn', 'limitInputPixels', 'unlimited', + // Format-generic + 'animated', 'autoOrient', 'density', 'ignoreIcc', 'page', 'pages', 'sequentialRead', + // Format-specific + 'jp2', 'openSlide', 'pdf', 'raw', 'svg', 'tiff', + // Deprecated + 'failOnError', 'openSlideLevel', 'pdfBackground', 'tiffSubifd' +]; + +/** + * Extract input options, if any, from an object. + * @private + */ +function _inputOptionsFromObject (obj) { + const params = inputStreamParameters + .filter(p => is.defined(obj[p])) + .map(p => ([p, obj[p]])); + return params.length + ? Object.fromEntries(params) + : undefined; +} + +/** + * Create Object containing input and input-related options. + * @private + */ +function _createInputDescriptor (input, inputOptions, containerOptions) { + const inputDescriptor = { + autoOrient: false, + failOn: 'warning', + limitInputPixels: Math.pow(0x3FFF, 2), + ignoreIcc: false, + unlimited: false, + sequentialRead: true + }; + if (is.string(input)) { + // filesystem + inputDescriptor.file = input; + } else if (is.buffer(input)) { + // Buffer + if (input.length === 0) { + throw Error('Input Buffer is empty'); + } + inputDescriptor.buffer = input; + } else if (is.arrayBuffer(input)) { + if (input.byteLength === 0) { + throw Error('Input bit Array is empty'); + } + inputDescriptor.buffer = Buffer.from(input, 0, input.byteLength); + } else if (is.typedArray(input)) { + if (input.length === 0) { + throw Error('Input Bit Array is empty'); + } + inputDescriptor.buffer = Buffer.from(input.buffer, input.byteOffset, input.byteLength); + } else if (is.plainObject(input) && !is.defined(inputOptions)) { + // Plain Object descriptor, e.g. create + inputOptions = input; + if (_inputOptionsFromObject(inputOptions)) { + // Stream with options + inputDescriptor.buffer = []; + } + } else if (!is.defined(input) && !is.defined(inputOptions) && is.object(containerOptions) && containerOptions.allowStream) { + // Stream without options + inputDescriptor.buffer = []; + } else if (Array.isArray(input)) { + if (input.length > 1) { + // Join images together + if (!this.options.joining) { + this.options.joining = true; + this.options.join = input.map(i => this._createInputDescriptor(i)); + } else { + throw new Error('Recursive join is unsupported'); + } + } else { + throw new Error('Expected at least two images to join'); + } + } else { + throw new Error(`Unsupported input '${input}' of type ${typeof input}${ + is.defined(inputOptions) ? ` when also providing options of type ${typeof inputOptions}` : '' + }`); + } + if (is.object(inputOptions)) { + // Deprecated: failOnError + if (is.defined(inputOptions.failOnError)) { + if (is.bool(inputOptions.failOnError)) { + inputDescriptor.failOn = inputOptions.failOnError ? 'warning' : 'none'; + } else { + throw is.invalidParameterError('failOnError', 'boolean', inputOptions.failOnError); + } + } + // failOn + if (is.defined(inputOptions.failOn)) { + if (is.string(inputOptions.failOn) && is.inArray(inputOptions.failOn, ['none', 'truncated', 'error', 'warning'])) { + inputDescriptor.failOn = inputOptions.failOn; + } else { + throw is.invalidParameterError('failOn', 'one of: none, truncated, error, warning', inputOptions.failOn); + } + } + // autoOrient + if (is.defined(inputOptions.autoOrient)) { + if (is.bool(inputOptions.autoOrient)) { + inputDescriptor.autoOrient = inputOptions.autoOrient; + } else { + throw is.invalidParameterError('autoOrient', 'boolean', inputOptions.autoOrient); + } + } + // Density + if (is.defined(inputOptions.density)) { + if (is.inRange(inputOptions.density, 1, 100000)) { + inputDescriptor.density = inputOptions.density; + } else { + throw is.invalidParameterError('density', 'number between 1 and 100000', inputOptions.density); + } + } + // Ignore embeddded ICC profile + if (is.defined(inputOptions.ignoreIcc)) { + if (is.bool(inputOptions.ignoreIcc)) { + inputDescriptor.ignoreIcc = inputOptions.ignoreIcc; + } else { + throw is.invalidParameterError('ignoreIcc', 'boolean', inputOptions.ignoreIcc); + } + } + // limitInputPixels + if (is.defined(inputOptions.limitInputPixels)) { + if (is.bool(inputOptions.limitInputPixels)) { + inputDescriptor.limitInputPixels = inputOptions.limitInputPixels + ? Math.pow(0x3FFF, 2) + : 0; + } else if (is.integer(inputOptions.limitInputPixels) && is.inRange(inputOptions.limitInputPixels, 0, Number.MAX_SAFE_INTEGER)) { + inputDescriptor.limitInputPixels = inputOptions.limitInputPixels; + } else { + throw is.invalidParameterError('limitInputPixels', 'positive integer', inputOptions.limitInputPixels); + } + } + // unlimited + if (is.defined(inputOptions.unlimited)) { + if (is.bool(inputOptions.unlimited)) { + inputDescriptor.unlimited = inputOptions.unlimited; + } else { + throw is.invalidParameterError('unlimited', 'boolean', inputOptions.unlimited); + } + } + // sequentialRead + if (is.defined(inputOptions.sequentialRead)) { + if (is.bool(inputOptions.sequentialRead)) { + inputDescriptor.sequentialRead = inputOptions.sequentialRead; + } else { + throw is.invalidParameterError('sequentialRead', 'boolean', inputOptions.sequentialRead); + } + } + // Raw pixel input + if (is.defined(inputOptions.raw)) { + if ( + is.object(inputOptions.raw) && + is.integer(inputOptions.raw.width) && inputOptions.raw.width > 0 && + is.integer(inputOptions.raw.height) && inputOptions.raw.height > 0 && + is.integer(inputOptions.raw.channels) && is.inRange(inputOptions.raw.channels, 1, 4) + ) { + inputDescriptor.rawWidth = inputOptions.raw.width; + inputDescriptor.rawHeight = inputOptions.raw.height; + inputDescriptor.rawChannels = inputOptions.raw.channels; + switch (input.constructor) { + case Uint8Array: + case Uint8ClampedArray: + inputDescriptor.rawDepth = 'uchar'; + break; + case Int8Array: + inputDescriptor.rawDepth = 'char'; + break; + case Uint16Array: + inputDescriptor.rawDepth = 'ushort'; + break; + case Int16Array: + inputDescriptor.rawDepth = 'short'; + break; + case Uint32Array: + inputDescriptor.rawDepth = 'uint'; + break; + case Int32Array: + inputDescriptor.rawDepth = 'int'; + break; + case Float32Array: + inputDescriptor.rawDepth = 'float'; + break; + case Float64Array: + inputDescriptor.rawDepth = 'double'; + break; + default: + inputDescriptor.rawDepth = 'uchar'; + break; + } + } else { + throw new Error('Expected width, height and channels for raw pixel input'); + } + inputDescriptor.rawPremultiplied = false; + if (is.defined(inputOptions.raw.premultiplied)) { + if (is.bool(inputOptions.raw.premultiplied)) { + inputDescriptor.rawPremultiplied = inputOptions.raw.premultiplied; + } else { + throw is.invalidParameterError('raw.premultiplied', 'boolean', inputOptions.raw.premultiplied); + } + } + inputDescriptor.rawPageHeight = 0; + if (is.defined(inputOptions.raw.pageHeight)) { + if (is.integer(inputOptions.raw.pageHeight) && inputOptions.raw.pageHeight > 0 && inputOptions.raw.pageHeight <= inputOptions.raw.height) { + if (inputOptions.raw.height % inputOptions.raw.pageHeight !== 0) { + throw new Error(`Expected raw.height ${inputOptions.raw.height} to be a multiple of raw.pageHeight ${inputOptions.raw.pageHeight}`); + } + inputDescriptor.rawPageHeight = inputOptions.raw.pageHeight; + } else { + throw is.invalidParameterError('raw.pageHeight', 'positive integer', inputOptions.raw.pageHeight); + } + } + } + // Multi-page input (GIF, TIFF, PDF) + if (is.defined(inputOptions.animated)) { + if (is.bool(inputOptions.animated)) { + inputDescriptor.pages = inputOptions.animated ? -1 : 1; + } else { + throw is.invalidParameterError('animated', 'boolean', inputOptions.animated); + } + } + if (is.defined(inputOptions.pages)) { + if (is.integer(inputOptions.pages) && is.inRange(inputOptions.pages, -1, 100000)) { + inputDescriptor.pages = inputOptions.pages; + } else { + throw is.invalidParameterError('pages', 'integer between -1 and 100000', inputOptions.pages); + } + } + if (is.defined(inputOptions.page)) { + if (is.integer(inputOptions.page) && is.inRange(inputOptions.page, 0, 100000)) { + inputDescriptor.page = inputOptions.page; + } else { + throw is.invalidParameterError('page', 'integer between 0 and 100000', inputOptions.page); + } + } + // OpenSlide specific options + if (is.object(inputOptions.openSlide) && is.defined(inputOptions.openSlide.level)) { + if (is.integer(inputOptions.openSlide.level) && is.inRange(inputOptions.openSlide.level, 0, 256)) { + inputDescriptor.openSlideLevel = inputOptions.openSlide.level; + } else { + throw is.invalidParameterError('openSlide.level', 'integer between 0 and 256', inputOptions.openSlide.level); + } + } else if (is.defined(inputOptions.level)) { + // Deprecated + if (is.integer(inputOptions.level) && is.inRange(inputOptions.level, 0, 256)) { + inputDescriptor.openSlideLevel = inputOptions.level; + } else { + throw is.invalidParameterError('level', 'integer between 0 and 256', inputOptions.level); + } + } + // TIFF specific options + if (is.object(inputOptions.tiff) && is.defined(inputOptions.tiff.subifd)) { + if (is.integer(inputOptions.tiff.subifd) && is.inRange(inputOptions.tiff.subifd, -1, 100000)) { + inputDescriptor.tiffSubifd = inputOptions.tiff.subifd; + } else { + throw is.invalidParameterError('tiff.subifd', 'integer between -1 and 100000', inputOptions.tiff.subifd); + } + } else if (is.defined(inputOptions.subifd)) { + // Deprecated + if (is.integer(inputOptions.subifd) && is.inRange(inputOptions.subifd, -1, 100000)) { + inputDescriptor.tiffSubifd = inputOptions.subifd; + } else { + throw is.invalidParameterError('subifd', 'integer between -1 and 100000', inputOptions.subifd); + } + } + // SVG specific options + if (is.object(inputOptions.svg)) { + if (is.defined(inputOptions.svg.stylesheet)) { + if (is.string(inputOptions.svg.stylesheet)) { + inputDescriptor.svgStylesheet = inputOptions.svg.stylesheet; + } else { + throw is.invalidParameterError('svg.stylesheet', 'string', inputOptions.svg.stylesheet); + } + } + if (is.defined(inputOptions.svg.highBitdepth)) { + if (is.bool(inputOptions.svg.highBitdepth)) { + inputDescriptor.svgHighBitdepth = inputOptions.svg.highBitdepth; + } else { + throw is.invalidParameterError('svg.highBitdepth', 'boolean', inputOptions.svg.highBitdepth); + } + } + } + // PDF specific options + if (is.object(inputOptions.pdf) && is.defined(inputOptions.pdf.background)) { + inputDescriptor.pdfBackground = this._getBackgroundColourOption(inputOptions.pdf.background); + } else if (is.defined(inputOptions.pdfBackground)) { + // Deprecated + inputDescriptor.pdfBackground = this._getBackgroundColourOption(inputOptions.pdfBackground); + } + // JPEG 2000 specific options + if (is.object(inputOptions.jp2) && is.defined(inputOptions.jp2.oneshot)) { + if (is.bool(inputOptions.jp2.oneshot)) { + inputDescriptor.jp2Oneshot = inputOptions.jp2.oneshot; + } else { + throw is.invalidParameterError('jp2.oneshot', 'boolean', inputOptions.jp2.oneshot); + } + } + // Create new image + if (is.defined(inputOptions.create)) { + if ( + is.object(inputOptions.create) && + is.integer(inputOptions.create.width) && inputOptions.create.width > 0 && + is.integer(inputOptions.create.height) && inputOptions.create.height > 0 && + is.integer(inputOptions.create.channels) + ) { + inputDescriptor.createWidth = inputOptions.create.width; + inputDescriptor.createHeight = inputOptions.create.height; + inputDescriptor.createChannels = inputOptions.create.channels; + inputDescriptor.createPageHeight = 0; + if (is.defined(inputOptions.create.pageHeight)) { + if (is.integer(inputOptions.create.pageHeight) && inputOptions.create.pageHeight > 0 && inputOptions.create.pageHeight <= inputOptions.create.height) { + if (inputOptions.create.height % inputOptions.create.pageHeight !== 0) { + throw new Error(`Expected create.height ${inputOptions.create.height} to be a multiple of create.pageHeight ${inputOptions.create.pageHeight}`); + } + inputDescriptor.createPageHeight = inputOptions.create.pageHeight; + } else { + throw is.invalidParameterError('create.pageHeight', 'positive integer', inputOptions.create.pageHeight); + } + } + // Noise + if (is.defined(inputOptions.create.noise)) { + if (!is.object(inputOptions.create.noise)) { + throw new Error('Expected noise to be an object'); + } + if (inputOptions.create.noise.type !== 'gaussian') { + throw new Error('Only gaussian noise is supported at the moment'); + } + inputDescriptor.createNoiseType = inputOptions.create.noise.type; + if (!is.inRange(inputOptions.create.channels, 1, 4)) { + throw is.invalidParameterError('create.channels', 'number between 1 and 4', inputOptions.create.channels); + } + inputDescriptor.createNoiseMean = 128; + if (is.defined(inputOptions.create.noise.mean)) { + if (is.number(inputOptions.create.noise.mean) && is.inRange(inputOptions.create.noise.mean, 0, 10000)) { + inputDescriptor.createNoiseMean = inputOptions.create.noise.mean; + } else { + throw is.invalidParameterError('create.noise.mean', 'number between 0 and 10000', inputOptions.create.noise.mean); + } + } + inputDescriptor.createNoiseSigma = 30; + if (is.defined(inputOptions.create.noise.sigma)) { + if (is.number(inputOptions.create.noise.sigma) && is.inRange(inputOptions.create.noise.sigma, 0, 10000)) { + inputDescriptor.createNoiseSigma = inputOptions.create.noise.sigma; + } else { + throw is.invalidParameterError('create.noise.sigma', 'number between 0 and 10000', inputOptions.create.noise.sigma); + } + } + } else if (is.defined(inputOptions.create.background)) { + if (!is.inRange(inputOptions.create.channels, 3, 4)) { + throw is.invalidParameterError('create.channels', 'number between 3 and 4', inputOptions.create.channels); + } + inputDescriptor.createBackground = this._getBackgroundColourOption(inputOptions.create.background); + } else { + throw new Error('Expected valid noise or background to create a new input image'); + } + delete inputDescriptor.buffer; + } else { + throw new Error('Expected valid width, height and channels to create a new input image'); + } + } + // Create a new image with text + if (is.defined(inputOptions.text)) { + if (is.object(inputOptions.text) && is.string(inputOptions.text.text)) { + inputDescriptor.textValue = inputOptions.text.text; + if (is.defined(inputOptions.text.height) && is.defined(inputOptions.text.dpi)) { + throw new Error('Expected only one of dpi or height'); + } + if (is.defined(inputOptions.text.font)) { + if (is.string(inputOptions.text.font)) { + inputDescriptor.textFont = inputOptions.text.font; + } else { + throw is.invalidParameterError('text.font', 'string', inputOptions.text.font); + } + } + if (is.defined(inputOptions.text.fontfile)) { + if (is.string(inputOptions.text.fontfile)) { + inputDescriptor.textFontfile = inputOptions.text.fontfile; + } else { + throw is.invalidParameterError('text.fontfile', 'string', inputOptions.text.fontfile); + } + } + if (is.defined(inputOptions.text.width)) { + if (is.integer(inputOptions.text.width) && inputOptions.text.width > 0) { + inputDescriptor.textWidth = inputOptions.text.width; + } else { + throw is.invalidParameterError('text.width', 'positive integer', inputOptions.text.width); + } + } + if (is.defined(inputOptions.text.height)) { + if (is.integer(inputOptions.text.height) && inputOptions.text.height > 0) { + inputDescriptor.textHeight = inputOptions.text.height; + } else { + throw is.invalidParameterError('text.height', 'positive integer', inputOptions.text.height); + } + } + if (is.defined(inputOptions.text.align)) { + if (is.string(inputOptions.text.align) && is.string(this.constructor.align[inputOptions.text.align])) { + inputDescriptor.textAlign = this.constructor.align[inputOptions.text.align]; + } else { + throw is.invalidParameterError('text.align', 'valid alignment', inputOptions.text.align); + } + } + if (is.defined(inputOptions.text.justify)) { + if (is.bool(inputOptions.text.justify)) { + inputDescriptor.textJustify = inputOptions.text.justify; + } else { + throw is.invalidParameterError('text.justify', 'boolean', inputOptions.text.justify); + } + } + if (is.defined(inputOptions.text.dpi)) { + if (is.integer(inputOptions.text.dpi) && is.inRange(inputOptions.text.dpi, 1, 1000000)) { + inputDescriptor.textDpi = inputOptions.text.dpi; + } else { + throw is.invalidParameterError('text.dpi', 'integer between 1 and 1000000', inputOptions.text.dpi); + } + } + if (is.defined(inputOptions.text.rgba)) { + if (is.bool(inputOptions.text.rgba)) { + inputDescriptor.textRgba = inputOptions.text.rgba; + } else { + throw is.invalidParameterError('text.rgba', 'bool', inputOptions.text.rgba); + } + } + if (is.defined(inputOptions.text.spacing)) { + if (is.integer(inputOptions.text.spacing) && is.inRange(inputOptions.text.spacing, -1000000, 1000000)) { + inputDescriptor.textSpacing = inputOptions.text.spacing; + } else { + throw is.invalidParameterError('text.spacing', 'integer between -1000000 and 1000000', inputOptions.text.spacing); + } + } + if (is.defined(inputOptions.text.wrap)) { + if (is.string(inputOptions.text.wrap) && is.inArray(inputOptions.text.wrap, ['word', 'char', 'word-char', 'none'])) { + inputDescriptor.textWrap = inputOptions.text.wrap; + } else { + throw is.invalidParameterError('text.wrap', 'one of: word, char, word-char, none', inputOptions.text.wrap); + } + } + delete inputDescriptor.buffer; + } else { + throw new Error('Expected a valid string to create an image with text.'); + } + } + // Join images together + if (is.defined(inputOptions.join)) { + if (is.defined(this.options.join)) { + if (is.defined(inputOptions.join.animated)) { + if (is.bool(inputOptions.join.animated)) { + inputDescriptor.joinAnimated = inputOptions.join.animated; + } else { + throw is.invalidParameterError('join.animated', 'boolean', inputOptions.join.animated); + } + } + if (is.defined(inputOptions.join.across)) { + if (is.integer(inputOptions.join.across) && is.inRange(inputOptions.join.across, 1, 1000000)) { + inputDescriptor.joinAcross = inputOptions.join.across; + } else { + throw is.invalidParameterError('join.across', 'integer between 1 and 100000', inputOptions.join.across); + } + } + if (is.defined(inputOptions.join.shim)) { + if (is.integer(inputOptions.join.shim) && is.inRange(inputOptions.join.shim, 0, 1000000)) { + inputDescriptor.joinShim = inputOptions.join.shim; + } else { + throw is.invalidParameterError('join.shim', 'integer between 0 and 100000', inputOptions.join.shim); + } + } + if (is.defined(inputOptions.join.background)) { + inputDescriptor.joinBackground = this._getBackgroundColourOption(inputOptions.join.background); + } + if (is.defined(inputOptions.join.halign)) { + if (is.string(inputOptions.join.halign) && is.string(this.constructor.align[inputOptions.join.halign])) { + inputDescriptor.joinHalign = this.constructor.align[inputOptions.join.halign]; + } else { + throw is.invalidParameterError('join.halign', 'valid alignment', inputOptions.join.halign); + } + } + if (is.defined(inputOptions.join.valign)) { + if (is.string(inputOptions.join.valign) && is.string(this.constructor.align[inputOptions.join.valign])) { + inputDescriptor.joinValign = this.constructor.align[inputOptions.join.valign]; + } else { + throw is.invalidParameterError('join.valign', 'valid alignment', inputOptions.join.valign); + } + } + } else { + throw new Error('Expected input to be an array of images to join'); + } + } + } else if (is.defined(inputOptions)) { + throw new Error('Invalid input options ' + inputOptions); + } + return inputDescriptor; +} + +/** + * Handle incoming Buffer chunk on Writable Stream. + * @private + * @param {Buffer} chunk + * @param {string} encoding - unused + * @param {Function} callback + */ +function _write (chunk, encoding, callback) { + /* istanbul ignore else */ + if (Array.isArray(this.options.input.buffer)) { + /* istanbul ignore else */ + if (is.buffer(chunk)) { + if (this.options.input.buffer.length === 0) { + this.on('finish', () => { + this.streamInFinished = true; + }); + } + this.options.input.buffer.push(chunk); + callback(); + } else { + callback(new Error('Non-Buffer data on Writable Stream')); + } + } else { + callback(new Error('Unexpected data on Writable Stream')); + } +} + +/** + * Flattens the array of chunks accumulated in input.buffer. + * @private + */ +function _flattenBufferIn () { + if (this._isStreamInput()) { + this.options.input.buffer = Buffer.concat(this.options.input.buffer); + } +} + +/** + * Are we expecting Stream-based input? + * @private + * @returns {boolean} + */ +function _isStreamInput () { + return Array.isArray(this.options.input.buffer); +} + +/** + * Fast access to (uncached) image metadata without decoding any compressed pixel data. + * + * This is read from the header of the input image. + * It does not take into consideration any operations to be applied to the output image, + * such as resize or rotate. + * + * Dimensions in the response will respect the `page` and `pages` properties of the + * {@link /api-constructor#parameters|constructor parameters}. + * + * A `Promise` is returned when `callback` is not provided. + * + * - `format`: Name of decoder used to decompress image data e.g. `jpeg`, `png`, `webp`, `gif`, `svg` + * - `size`: Total size of image in bytes, for Stream and Buffer input only + * - `width`: Number of pixels wide (EXIF orientation is not taken into consideration, see example below) + * - `height`: Number of pixels high (EXIF orientation is not taken into consideration, see example below) + * - `space`: Name of colour space interpretation e.g. `srgb`, `rgb`, `cmyk`, `lab`, `b-w` [...](https://www.libvips.org/API/current/VipsImage.html#VipsInterpretation) + * - `channels`: Number of bands e.g. `3` for sRGB, `4` for CMYK + * - `depth`: Name of pixel depth format e.g. `uchar`, `char`, `ushort`, `float` [...](https://www.libvips.org/API/current/VipsImage.html#VipsBandFormat) + * - `density`: Number of pixels per inch (DPI), if present + * - `chromaSubsampling`: String containing JPEG chroma subsampling, `4:2:0` or `4:4:4` for RGB, `4:2:0:4` or `4:4:4:4` for CMYK + * - `isProgressive`: Boolean indicating whether the image is interlaced using a progressive scan + * - `isPalette`: Boolean indicating whether the image is palette-based (GIF, PNG). + * - `bitsPerSample`: Number of bits per sample for each channel (GIF, PNG, HEIF). + * - `pages`: Number of pages/frames contained within the image, with support for TIFF, HEIF, PDF, animated GIF and animated WebP + * - `pageHeight`: Number of pixels high each page in a multi-page image will be. + * - `loop`: Number of times to loop an animated image, zero refers to a continuous loop. + * - `delay`: Delay in ms between each page in an animated image, provided as an array of integers. + * - `pagePrimary`: Number of the primary page in a HEIF image + * - `levels`: Details of each level in a multi-level image provided as an array of objects, requires libvips compiled with support for OpenSlide + * - `subifds`: Number of Sub Image File Directories in an OME-TIFF image + * - `background`: Default background colour, if present, for PNG (bKGD) and GIF images + * - `compression`: The encoder used to compress an HEIF file, `av1` (AVIF) or `hevc` (HEIC) + * - `resolutionUnit`: The unit of resolution (density), either `inch` or `cm`, if present + * - `hasProfile`: Boolean indicating the presence of an embedded ICC profile + * - `hasAlpha`: Boolean indicating the presence of an alpha transparency channel + * - `orientation`: Number value of the EXIF Orientation header, if present + * - `exif`: Buffer containing raw EXIF data, if present + * - `icc`: Buffer containing raw [ICC](https://www.npmjs.com/package/icc) profile data, if present + * - `iptc`: Buffer containing raw IPTC data, if present + * - `xmp`: Buffer containing raw XMP data, if present + * - `xmpAsString`: String containing XMP data, if valid UTF-8. + * - `tifftagPhotoshop`: Buffer containing raw TIFFTAG_PHOTOSHOP data, if present + * - `formatMagick`: String containing format for images loaded via *magick + * - `comments`: Array of keyword/text pairs representing PNG text blocks, if present. + * + * @example + * const metadata = await sharp(input).metadata(); + * + * @example + * const image = sharp(inputJpg); + * image + * .metadata() + * .then(function(metadata) { + * return image + * .resize(Math.round(metadata.width / 2)) + * .webp() + * .toBuffer(); + * }) + * .then(function(data) { + * // data contains a WebP image half the width and height of the original JPEG + * }); + * + * @example + * // Get dimensions taking EXIF Orientation into account. + * const { autoOrient } = await sharp(input).metadata(); + * const { width, height } = autoOrient; + * + * @param {Function} [callback] - called with the arguments `(err, metadata)` + * @returns {Promise|Sharp} + */ +function metadata (callback) { + const stack = Error(); + if (is.fn(callback)) { + if (this._isStreamInput()) { + this.on('finish', () => { + this._flattenBufferIn(); + sharp.metadata(this.options, (err, metadata) => { + if (err) { + callback(is.nativeError(err, stack)); + } else { + callback(null, metadata); + } + }); + }); + } else { + sharp.metadata(this.options, (err, metadata) => { + if (err) { + callback(is.nativeError(err, stack)); + } else { + callback(null, metadata); + } + }); + } + return this; + } else { + if (this._isStreamInput()) { + return new Promise((resolve, reject) => { + const finished = () => { + this._flattenBufferIn(); + sharp.metadata(this.options, (err, metadata) => { + if (err) { + reject(is.nativeError(err, stack)); + } else { + resolve(metadata); + } + }); + }; + if (this.writableFinished) { + finished(); + } else { + this.once('finish', finished); + } + }); + } else { + return new Promise((resolve, reject) => { + sharp.metadata(this.options, (err, metadata) => { + if (err) { + reject(is.nativeError(err, stack)); + } else { + resolve(metadata); + } + }); + }); + } + } +} + +/** + * Access to pixel-derived image statistics for every channel in the image. + * A `Promise` is returned when `callback` is not provided. + * + * - `channels`: Array of channel statistics for each channel in the image. Each channel statistic contains + * - `min` (minimum value in the channel) + * - `max` (maximum value in the channel) + * - `sum` (sum of all values in a channel) + * - `squaresSum` (sum of squared values in a channel) + * - `mean` (mean of the values in a channel) + * - `stdev` (standard deviation for the values in a channel) + * - `minX` (x-coordinate of one of the pixel where the minimum lies) + * - `minY` (y-coordinate of one of the pixel where the minimum lies) + * - `maxX` (x-coordinate of one of the pixel where the maximum lies) + * - `maxY` (y-coordinate of one of the pixel where the maximum lies) + * - `isOpaque`: Is the image fully opaque? Will be `true` if the image has no alpha channel or if every pixel is fully opaque. + * - `entropy`: Histogram-based estimation of greyscale entropy, discarding alpha channel if any. + * - `sharpness`: Estimation of greyscale sharpness based on the standard deviation of a Laplacian convolution, discarding alpha channel if any. + * - `dominant`: Object containing most dominant sRGB colour based on a 4096-bin 3D histogram. + * + * **Note**: Statistics are derived from the original input image. Any operations performed on the image must first be + * written to a buffer in order to run `stats` on the result (see third example). + * + * @example + * const image = sharp(inputJpg); + * image + * .stats() + * .then(function(stats) { + * // stats contains the channel-wise statistics array and the isOpaque value + * }); + * + * @example + * const { entropy, sharpness, dominant } = await sharp(input).stats(); + * const { r, g, b } = dominant; + * + * @example + * const image = sharp(input); + * // store intermediate result + * const part = await image.extract(region).toBuffer(); + * // create new instance to obtain statistics of extracted region + * const stats = await sharp(part).stats(); + * + * @param {Function} [callback] - called with the arguments `(err, stats)` + * @returns {Promise} + */ +function stats (callback) { + const stack = Error(); + if (is.fn(callback)) { + if (this._isStreamInput()) { + this.on('finish', () => { + this._flattenBufferIn(); + sharp.stats(this.options, (err, stats) => { + if (err) { + callback(is.nativeError(err, stack)); + } else { + callback(null, stats); + } + }); + }); + } else { + sharp.stats(this.options, (err, stats) => { + if (err) { + callback(is.nativeError(err, stack)); + } else { + callback(null, stats); + } + }); + } + return this; + } else { + if (this._isStreamInput()) { + return new Promise((resolve, reject) => { + this.on('finish', function () { + this._flattenBufferIn(); + sharp.stats(this.options, (err, stats) => { + if (err) { + reject(is.nativeError(err, stack)); + } else { + resolve(stats); + } + }); + }); + }); + } else { + return new Promise((resolve, reject) => { + sharp.stats(this.options, (err, stats) => { + if (err) { + reject(is.nativeError(err, stack)); + } else { + resolve(stats); + } + }); + }); + } + } +} + +/** + * Decorate the Sharp prototype with input-related functions. + * @module Sharp + * @private + */ +module.exports = function (Sharp) { + Object.assign(Sharp.prototype, { + // Private + _inputOptionsFromObject, + _createInputDescriptor, + _write, + _flattenBufferIn, + _isStreamInput, + // Public + metadata, + stats + }); + // Class attributes + Sharp.align = align; +}; diff --git a/server/node_modules/sharp/lib/is.js b/server/node_modules/sharp/lib/is.js new file mode 100644 index 0000000..a63cb20 --- /dev/null +++ b/server/node_modules/sharp/lib/is.js @@ -0,0 +1,169 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +/** + * Is this value defined and not null? + * @private + */ +const defined = function (val) { + return typeof val !== 'undefined' && val !== null; +}; + +/** + * Is this value an object? + * @private + */ +const object = function (val) { + return typeof val === 'object'; +}; + +/** + * Is this value a plain object? + * @private + */ +const plainObject = function (val) { + return Object.prototype.toString.call(val) === '[object Object]'; +}; + +/** + * Is this value a function? + * @private + */ +const fn = function (val) { + return typeof val === 'function'; +}; + +/** + * Is this value a boolean? + * @private + */ +const bool = function (val) { + return typeof val === 'boolean'; +}; + +/** + * Is this value a Buffer object? + * @private + */ +const buffer = function (val) { + return val instanceof Buffer; +}; + +/** + * Is this value a typed array object?. E.g. Uint8Array or Uint8ClampedArray? + * @private + */ +const typedArray = function (val) { + if (defined(val)) { + switch (val.constructor) { + case Uint8Array: + case Uint8ClampedArray: + case Int8Array: + case Uint16Array: + case Int16Array: + case Uint32Array: + case Int32Array: + case Float32Array: + case Float64Array: + return true; + } + } + + return false; +}; + +/** + * Is this value an ArrayBuffer object? + * @private + */ +const arrayBuffer = function (val) { + return val instanceof ArrayBuffer; +}; + +/** + * Is this value a non-empty string? + * @private + */ +const string = function (val) { + return typeof val === 'string' && val.length > 0; +}; + +/** + * Is this value a real number? + * @private + */ +const number = function (val) { + return typeof val === 'number' && !Number.isNaN(val); +}; + +/** + * Is this value an integer? + * @private + */ +const integer = function (val) { + return Number.isInteger(val); +}; + +/** + * Is this value within an inclusive given range? + * @private + */ +const inRange = function (val, min, max) { + return val >= min && val <= max; +}; + +/** + * Is this value within the elements of an array? + * @private + */ +const inArray = function (val, list) { + return list.includes(val); +}; + +/** + * Create an Error with a message relating to an invalid parameter. + * + * @param {string} name - parameter name. + * @param {string} expected - description of the type/value/range expected. + * @param {*} actual - the value received. + * @returns {Error} Containing the formatted message. + * @private + */ +const invalidParameterError = function (name, expected, actual) { + return new Error( + `Expected ${expected} for ${name} but received ${actual} of type ${typeof actual}` + ); +}; + +/** + * Ensures an Error from C++ contains a JS stack. + * + * @param {Error} native - Error with message from C++. + * @param {Error} context - Error with stack from JS. + * @returns {Error} Error with message and stack. + * @private + */ +const nativeError = function (native, context) { + context.message = native.message; + return context; +}; + +module.exports = { + defined, + object, + plainObject, + fn, + bool, + buffer, + typedArray, + arrayBuffer, + string, + number, + integer, + inRange, + inArray, + invalidParameterError, + nativeError +}; diff --git a/server/node_modules/sharp/lib/libvips.js b/server/node_modules/sharp/lib/libvips.js new file mode 100644 index 0000000..1bab0ca --- /dev/null +++ b/server/node_modules/sharp/lib/libvips.js @@ -0,0 +1,205 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const { spawnSync } = require('node:child_process'); +const { createHash } = require('node:crypto'); +const semverCoerce = require('semver/functions/coerce'); +const semverGreaterThanOrEqualTo = require('semver/functions/gte'); +const semverSatisfies = require('semver/functions/satisfies'); +const detectLibc = require('detect-libc'); + +const { config, engines, optionalDependencies } = require('../package.json'); + +const minimumLibvipsVersionLabelled = process.env.npm_package_config_libvips || /* istanbul ignore next */ + config.libvips; +const minimumLibvipsVersion = semverCoerce(minimumLibvipsVersionLabelled).version; + +const prebuiltPlatforms = [ + 'darwin-arm64', 'darwin-x64', + 'linux-arm', 'linux-arm64', 'linux-ppc64', 'linux-s390x', 'linux-x64', + 'linuxmusl-arm64', 'linuxmusl-x64', + 'win32-arm64', 'win32-ia32', 'win32-x64' +]; + +const spawnSyncOptions = { + encoding: 'utf8', + shell: true +}; + +const log = (item) => { + if (item instanceof Error) { + console.error(`sharp: Installation error: ${item.message}`); + } else { + console.log(`sharp: ${item}`); + } +}; + +/* istanbul ignore next */ +const runtimeLibc = () => detectLibc.isNonGlibcLinuxSync() ? detectLibc.familySync() : ''; + +const runtimePlatformArch = () => `${process.platform}${runtimeLibc()}-${process.arch}`; + +/* istanbul ignore next */ +const buildPlatformArch = () => { + if (isEmscripten()) { + return 'wasm32'; + } + /* eslint camelcase: ["error", { allow: ["^npm_config_"] }] */ + const { npm_config_arch, npm_config_platform, npm_config_libc } = process.env; + const libc = typeof npm_config_libc === 'string' ? npm_config_libc : runtimeLibc(); + return `${npm_config_platform || process.platform}${libc}-${npm_config_arch || process.arch}`; +}; + +const buildSharpLibvipsIncludeDir = () => { + try { + return require(`@img/sharp-libvips-dev-${buildPlatformArch()}/include`); + } catch { + try { + return require('@img/sharp-libvips-dev/include'); + } catch {} + } + /* istanbul ignore next */ + return ''; +}; + +const buildSharpLibvipsCPlusPlusDir = () => { + try { + return require('@img/sharp-libvips-dev/cplusplus'); + } catch {} + /* istanbul ignore next */ + return ''; +}; + +const buildSharpLibvipsLibDir = () => { + try { + return require(`@img/sharp-libvips-dev-${buildPlatformArch()}/lib`); + } catch { + try { + return require(`@img/sharp-libvips-${buildPlatformArch()}/lib`); + } catch {} + } + /* istanbul ignore next */ + return ''; +}; + +const isUnsupportedNodeRuntime = () => { + /* istanbul ignore next */ + if (process.release?.name === 'node' && process.versions) { + if (!semverSatisfies(process.versions.node, engines.node)) { + return { found: process.versions.node, expected: engines.node }; + } + } +}; + +/* istanbul ignore next */ +const isEmscripten = () => { + const { CC } = process.env; + return Boolean(CC && CC.endsWith('/emcc')); +}; + +const isRosetta = () => { + /* istanbul ignore next */ + if (process.platform === 'darwin' && process.arch === 'x64') { + const translated = spawnSync('sysctl sysctl.proc_translated', spawnSyncOptions).stdout; + return (translated || '').trim() === 'sysctl.proc_translated: 1'; + } + return false; +}; + +const sha512 = (s) => createHash('sha512').update(s).digest('hex'); + +const yarnLocator = () => { + try { + const identHash = sha512(`imgsharp-libvips-${buildPlatformArch()}`); + const npmVersion = semverCoerce(optionalDependencies[`@img/sharp-libvips-${buildPlatformArch()}`], { + includePrerelease: true + }).version; + return sha512(`${identHash}npm:${npmVersion}`).slice(0, 10); + } catch {} + return ''; +}; + +/* istanbul ignore next */ +const spawnRebuild = () => + spawnSync(`node-gyp rebuild --directory=src ${isEmscripten() ? '--nodedir=emscripten' : ''}`, { + ...spawnSyncOptions, + stdio: 'inherit' + }).status; + +const globalLibvipsVersion = () => { + if (process.platform !== 'win32') { + const globalLibvipsVersion = spawnSync('pkg-config --modversion vips-cpp', { + ...spawnSyncOptions, + env: { + ...process.env, + PKG_CONFIG_PATH: pkgConfigPath() + } + }).stdout; + /* istanbul ignore next */ + return (globalLibvipsVersion || '').trim(); + } else { + return ''; + } +}; + +/* istanbul ignore next */ +const pkgConfigPath = () => { + if (process.platform !== 'win32') { + const brewPkgConfigPath = spawnSync( + 'which brew >/dev/null 2>&1 && brew environment --plain | grep PKG_CONFIG_LIBDIR | cut -d" " -f2', + spawnSyncOptions + ).stdout || ''; + return [ + brewPkgConfigPath.trim(), + process.env.PKG_CONFIG_PATH, + '/usr/local/lib/pkgconfig', + '/usr/lib/pkgconfig', + '/usr/local/libdata/pkgconfig', + '/usr/libdata/pkgconfig' + ].filter(Boolean).join(':'); + } else { + return ''; + } +}; + +const skipSearch = (status, reason, logger) => { + if (logger) { + logger(`Detected ${reason}, skipping search for globally-installed libvips`); + } + return status; +}; + +const useGlobalLibvips = (logger) => { + if (Boolean(process.env.SHARP_IGNORE_GLOBAL_LIBVIPS) === true) { + return skipSearch(false, 'SHARP_IGNORE_GLOBAL_LIBVIPS', logger); + } + if (Boolean(process.env.SHARP_FORCE_GLOBAL_LIBVIPS) === true) { + return skipSearch(true, 'SHARP_FORCE_GLOBAL_LIBVIPS', logger); + } + /* istanbul ignore next */ + if (isRosetta()) { + return skipSearch(false, 'Rosetta', logger); + } + const globalVipsVersion = globalLibvipsVersion(); + return !!globalVipsVersion && /* istanbul ignore next */ + semverGreaterThanOrEqualTo(globalVipsVersion, minimumLibvipsVersion); +}; + +module.exports = { + minimumLibvipsVersion, + prebuiltPlatforms, + buildPlatformArch, + buildSharpLibvipsIncludeDir, + buildSharpLibvipsCPlusPlusDir, + buildSharpLibvipsLibDir, + isUnsupportedNodeRuntime, + runtimePlatformArch, + log, + yarnLocator, + spawnRebuild, + globalLibvipsVersion, + pkgConfigPath, + useGlobalLibvips +}; diff --git a/server/node_modules/sharp/lib/operation.js b/server/node_modules/sharp/lib/operation.js new file mode 100644 index 0000000..f76f65d --- /dev/null +++ b/server/node_modules/sharp/lib/operation.js @@ -0,0 +1,1018 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const is = require('./is'); + +/** + * How accurate an operation should be. + * @member + * @private + */ +const vipsPrecision = { + integer: 'integer', + float: 'float', + approximate: 'approximate' +}; + +/** + * Rotate the output image. + * + * The provided angle is converted to a valid positive degree rotation. + * For example, `-450` will produce a 270 degree rotation. + * + * When rotating by an angle other than a multiple of 90, + * the background colour can be provided with the `background` option. + * + * For backwards compatibility, if no angle is provided, `.autoOrient()` will be called. + * + * Only one rotation can occur per pipeline (aside from an initial call without + * arguments to orient via EXIF data). Previous calls to `rotate` in the same + * pipeline will be ignored. + * + * Multi-page images can only be rotated by 180 degrees. + * + * Method order is important when rotating, resizing and/or extracting regions, + * for example `.rotate(x).extract(y)` will produce a different result to `.extract(y).rotate(x)`. + * + * @example + * const rotateThenResize = await sharp(input) + * .rotate(90) + * .resize({ width: 16, height: 8, fit: 'fill' }) + * .toBuffer(); + * const resizeThenRotate = await sharp(input) + * .resize({ width: 16, height: 8, fit: 'fill' }) + * .rotate(90) + * .toBuffer(); + * + * @param {number} [angle=auto] angle of rotation. + * @param {Object} [options] - if present, is an Object with optional attributes. + * @param {string|Object} [options.background="#000000"] parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function rotate (angle, options) { + if (!is.defined(angle)) { + return this.autoOrient(); + } + if (this.options.angle || this.options.rotationAngle) { + this.options.debuglog('ignoring previous rotate options'); + this.options.angle = 0; + this.options.rotationAngle = 0; + } + if (is.integer(angle) && !(angle % 90)) { + this.options.angle = angle; + } else if (is.number(angle)) { + this.options.rotationAngle = angle; + if (is.object(options) && options.background) { + this._setBackgroundColourOption('rotationBackground', options.background); + } + } else { + throw is.invalidParameterError('angle', 'numeric', angle); + } + return this; +} + +/** + * Auto-orient based on the EXIF `Orientation` tag, then remove the tag. + * Mirroring is supported and may infer the use of a flip operation. + * + * Previous or subsequent use of `rotate(angle)` and either `flip()` or `flop()` + * will logically occur after auto-orientation, regardless of call order. + * + * @example + * const output = await sharp(input).autoOrient().toBuffer(); + * + * @example + * const pipeline = sharp() + * .autoOrient() + * .resize(null, 200) + * .toBuffer(function (err, outputBuffer, info) { + * // outputBuffer contains 200px high JPEG image data, + * // auto-oriented using EXIF Orientation tag + * // info.width and info.height contain the dimensions of the resized image + * }); + * readableStream.pipe(pipeline); + * + * @returns {Sharp} + */ +function autoOrient () { + this.options.input.autoOrient = true; + return this; +} + +/** + * Mirror the image vertically (up-down) about the x-axis. + * This always occurs before rotation, if any. + * + * This operation does not work correctly with multi-page images. + * + * @example + * const output = await sharp(input).flip().toBuffer(); + * + * @param {Boolean} [flip=true] + * @returns {Sharp} + */ +function flip (flip) { + this.options.flip = is.bool(flip) ? flip : true; + return this; +} + +/** + * Mirror the image horizontally (left-right) about the y-axis. + * This always occurs before rotation, if any. + * + * @example + * const output = await sharp(input).flop().toBuffer(); + * + * @param {Boolean} [flop=true] + * @returns {Sharp} + */ +function flop (flop) { + this.options.flop = is.bool(flop) ? flop : true; + return this; +} + +/** + * Perform an affine transform on an image. This operation will always occur after resizing, extraction and rotation, if any. + * + * You must provide an array of length 4 or a 2x2 affine transformation matrix. + * By default, new pixels are filled with a black background. You can provide a background colour with the `background` option. + * A particular interpolator may also be specified. Set the `interpolator` option to an attribute of the `sharp.interpolators` Object e.g. `sharp.interpolators.nohalo`. + * + * In the case of a 2x2 matrix, the transform is: + * - X = `matrix[0, 0]` \* (x + `idx`) + `matrix[0, 1]` \* (y + `idy`) + `odx` + * - Y = `matrix[1, 0]` \* (x + `idx`) + `matrix[1, 1]` \* (y + `idy`) + `ody` + * + * where: + * - x and y are the coordinates in input image. + * - X and Y are the coordinates in output image. + * - (0,0) is the upper left corner. + * + * @since 0.27.0 + * + * @example + * const pipeline = sharp() + * .affine([[1, 0.3], [0.1, 0.7]], { + * background: 'white', + * interpolator: sharp.interpolators.nohalo + * }) + * .toBuffer((err, outputBuffer, info) => { + * // outputBuffer contains the transformed image + * // info.width and info.height contain the new dimensions + * }); + * + * inputStream + * .pipe(pipeline); + * + * @param {Array>|Array} matrix - affine transformation matrix + * @param {Object} [options] - if present, is an Object with optional attributes. + * @param {String|Object} [options.background="#000000"] - parsed by the [color](https://www.npmjs.org/package/color) module to extract values for red, green, blue and alpha. + * @param {Number} [options.idx=0] - input horizontal offset + * @param {Number} [options.idy=0] - input vertical offset + * @param {Number} [options.odx=0] - output horizontal offset + * @param {Number} [options.ody=0] - output vertical offset + * @param {String} [options.interpolator=sharp.interpolators.bicubic] - interpolator + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function affine (matrix, options) { + const flatMatrix = [].concat(...matrix); + if (flatMatrix.length === 4 && flatMatrix.every(is.number)) { + this.options.affineMatrix = flatMatrix; + } else { + throw is.invalidParameterError('matrix', '1x4 or 2x2 array', matrix); + } + + if (is.defined(options)) { + if (is.object(options)) { + this._setBackgroundColourOption('affineBackground', options.background); + if (is.defined(options.idx)) { + if (is.number(options.idx)) { + this.options.affineIdx = options.idx; + } else { + throw is.invalidParameterError('options.idx', 'number', options.idx); + } + } + if (is.defined(options.idy)) { + if (is.number(options.idy)) { + this.options.affineIdy = options.idy; + } else { + throw is.invalidParameterError('options.idy', 'number', options.idy); + } + } + if (is.defined(options.odx)) { + if (is.number(options.odx)) { + this.options.affineOdx = options.odx; + } else { + throw is.invalidParameterError('options.odx', 'number', options.odx); + } + } + if (is.defined(options.ody)) { + if (is.number(options.ody)) { + this.options.affineOdy = options.ody; + } else { + throw is.invalidParameterError('options.ody', 'number', options.ody); + } + } + if (is.defined(options.interpolator)) { + if (is.inArray(options.interpolator, Object.values(this.constructor.interpolators))) { + this.options.affineInterpolator = options.interpolator; + } else { + throw is.invalidParameterError('options.interpolator', 'valid interpolator name', options.interpolator); + } + } + } else { + throw is.invalidParameterError('options', 'object', options); + } + } + + return this; +} + +/** + * Sharpen the image. + * + * When used without parameters, performs a fast, mild sharpen of the output image. + * + * When a `sigma` is provided, performs a slower, more accurate sharpen of the L channel in the LAB colour space. + * Fine-grained control over the level of sharpening in "flat" (m1) and "jagged" (m2) areas is available. + * + * See {@link https://www.libvips.org/API/current/libvips-convolution.html#vips-sharpen|libvips sharpen} operation. + * + * @example + * const data = await sharp(input).sharpen().toBuffer(); + * + * @example + * const data = await sharp(input).sharpen({ sigma: 2 }).toBuffer(); + * + * @example + * const data = await sharp(input) + * .sharpen({ + * sigma: 2, + * m1: 0, + * m2: 3, + * x1: 3, + * y2: 15, + * y3: 15, + * }) + * .toBuffer(); + * + * @param {Object|number} [options] - if present, is an Object with attributes + * @param {number} [options.sigma] - the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`, between 0.000001 and 10 + * @param {number} [options.m1=1.0] - the level of sharpening to apply to "flat" areas, between 0 and 1000000 + * @param {number} [options.m2=2.0] - the level of sharpening to apply to "jagged" areas, between 0 and 1000000 + * @param {number} [options.x1=2.0] - threshold between "flat" and "jagged", between 0 and 1000000 + * @param {number} [options.y2=10.0] - maximum amount of brightening, between 0 and 1000000 + * @param {number} [options.y3=20.0] - maximum amount of darkening, between 0 and 1000000 + * @param {number} [flat] - (deprecated) see `options.m1`. + * @param {number} [jagged] - (deprecated) see `options.m2`. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function sharpen (options, flat, jagged) { + if (!is.defined(options)) { + // No arguments: default to mild sharpen + this.options.sharpenSigma = -1; + } else if (is.bool(options)) { + // Deprecated boolean argument: apply mild sharpen? + this.options.sharpenSigma = options ? -1 : 0; + } else if (is.number(options) && is.inRange(options, 0.01, 10000)) { + // Deprecated numeric argument: specific sigma + this.options.sharpenSigma = options; + // Deprecated control over flat areas + if (is.defined(flat)) { + if (is.number(flat) && is.inRange(flat, 0, 10000)) { + this.options.sharpenM1 = flat; + } else { + throw is.invalidParameterError('flat', 'number between 0 and 10000', flat); + } + } + // Deprecated control over jagged areas + if (is.defined(jagged)) { + if (is.number(jagged) && is.inRange(jagged, 0, 10000)) { + this.options.sharpenM2 = jagged; + } else { + throw is.invalidParameterError('jagged', 'number between 0 and 10000', jagged); + } + } + } else if (is.plainObject(options)) { + if (is.number(options.sigma) && is.inRange(options.sigma, 0.000001, 10)) { + this.options.sharpenSigma = options.sigma; + } else { + throw is.invalidParameterError('options.sigma', 'number between 0.000001 and 10', options.sigma); + } + if (is.defined(options.m1)) { + if (is.number(options.m1) && is.inRange(options.m1, 0, 1000000)) { + this.options.sharpenM1 = options.m1; + } else { + throw is.invalidParameterError('options.m1', 'number between 0 and 1000000', options.m1); + } + } + if (is.defined(options.m2)) { + if (is.number(options.m2) && is.inRange(options.m2, 0, 1000000)) { + this.options.sharpenM2 = options.m2; + } else { + throw is.invalidParameterError('options.m2', 'number between 0 and 1000000', options.m2); + } + } + if (is.defined(options.x1)) { + if (is.number(options.x1) && is.inRange(options.x1, 0, 1000000)) { + this.options.sharpenX1 = options.x1; + } else { + throw is.invalidParameterError('options.x1', 'number between 0 and 1000000', options.x1); + } + } + if (is.defined(options.y2)) { + if (is.number(options.y2) && is.inRange(options.y2, 0, 1000000)) { + this.options.sharpenY2 = options.y2; + } else { + throw is.invalidParameterError('options.y2', 'number between 0 and 1000000', options.y2); + } + } + if (is.defined(options.y3)) { + if (is.number(options.y3) && is.inRange(options.y3, 0, 1000000)) { + this.options.sharpenY3 = options.y3; + } else { + throw is.invalidParameterError('options.y3', 'number between 0 and 1000000', options.y3); + } + } + } else { + throw is.invalidParameterError('sigma', 'number between 0.01 and 10000', options); + } + return this; +} + +/** + * Apply median filter. + * When used without parameters the default window is 3x3. + * + * @example + * const output = await sharp(input).median().toBuffer(); + * + * @example + * const output = await sharp(input).median(5).toBuffer(); + * + * @param {number} [size=3] square mask size: size x size + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function median (size) { + if (!is.defined(size)) { + // No arguments: default to 3x3 + this.options.medianSize = 3; + } else if (is.integer(size) && is.inRange(size, 1, 1000)) { + // Numeric argument: specific sigma + this.options.medianSize = size; + } else { + throw is.invalidParameterError('size', 'integer between 1 and 1000', size); + } + return this; +} + +/** + * Blur the image. + * + * When used without parameters, performs a fast 3x3 box blur (equivalent to a box linear filter). + * + * When a `sigma` is provided, performs a slower, more accurate Gaussian blur. + * + * @example + * const boxBlurred = await sharp(input) + * .blur() + * .toBuffer(); + * + * @example + * const gaussianBlurred = await sharp(input) + * .blur(5) + * .toBuffer(); + * + * @param {Object|number|Boolean} [options] + * @param {number} [options.sigma] a value between 0.3 and 1000 representing the sigma of the Gaussian mask, where `sigma = 1 + radius / 2`. + * @param {string} [options.precision='integer'] How accurate the operation should be, one of: integer, float, approximate. + * @param {number} [options.minAmplitude=0.2] A value between 0.001 and 1. A smaller value will generate a larger, more accurate mask. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function blur (options) { + let sigma; + if (is.number(options)) { + sigma = options; + } else if (is.plainObject(options)) { + if (!is.number(options.sigma)) { + throw is.invalidParameterError('options.sigma', 'number between 0.3 and 1000', sigma); + } + sigma = options.sigma; + if ('precision' in options) { + if (is.string(vipsPrecision[options.precision])) { + this.options.precision = vipsPrecision[options.precision]; + } else { + throw is.invalidParameterError('precision', 'one of: integer, float, approximate', options.precision); + } + } + if ('minAmplitude' in options) { + if (is.number(options.minAmplitude) && is.inRange(options.minAmplitude, 0.001, 1)) { + this.options.minAmpl = options.minAmplitude; + } else { + throw is.invalidParameterError('minAmplitude', 'number between 0.001 and 1', options.minAmplitude); + } + } + } + + if (!is.defined(options)) { + // No arguments: default to mild blur + this.options.blurSigma = -1; + } else if (is.bool(options)) { + // Boolean argument: apply mild blur? + this.options.blurSigma = options ? -1 : 0; + } else if (is.number(sigma) && is.inRange(sigma, 0.3, 1000)) { + // Numeric argument: specific sigma + this.options.blurSigma = sigma; + } else { + throw is.invalidParameterError('sigma', 'number between 0.3 and 1000', sigma); + } + + return this; +} + +/** + * Expand foreground objects using the dilate morphological operator. + * + * @example + * const output = await sharp(input) + * .dilate() + * .toBuffer(); + * + * @param {Number} [width=1] dilation width in pixels. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function dilate (width) { + if (!is.defined(width)) { + this.options.dilateWidth = 1; + } else if (is.integer(width) && width > 0) { + this.options.dilateWidth = width; + } else { + throw is.invalidParameterError('dilate', 'positive integer', dilate); + } + return this; +} + +/** + * Shrink foreground objects using the erode morphological operator. + * + * @example + * const output = await sharp(input) + * .erode() + * .toBuffer(); + * + * @param {Number} [width=1] erosion width in pixels. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function erode (width) { + if (!is.defined(width)) { + this.options.erodeWidth = 1; + } else if (is.integer(width) && width > 0) { + this.options.erodeWidth = width; + } else { + throw is.invalidParameterError('erode', 'positive integer', erode); + } + return this; +} + +/** + * Merge alpha transparency channel, if any, with a background, then remove the alpha channel. + * + * See also {@link /api-channel#removealpha|removeAlpha}. + * + * @example + * await sharp(rgbaInput) + * .flatten({ background: '#F0A703' }) + * .toBuffer(); + * + * @param {Object} [options] + * @param {string|Object} [options.background={r: 0, g: 0, b: 0}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black. + * @returns {Sharp} + */ +function flatten (options) { + this.options.flatten = is.bool(options) ? options : true; + if (is.object(options)) { + this._setBackgroundColourOption('flattenBackground', options.background); + } + return this; +} + +/** + * Ensure the image has an alpha channel + * with all white pixel values made fully transparent. + * + * Existing alpha channel values for non-white pixels remain unchanged. + * + * This feature is experimental and the API may change. + * + * @since 0.32.1 + * + * @example + * await sharp(rgbInput) + * .unflatten() + * .toBuffer(); + * + * @example + * await sharp(rgbInput) + * .threshold(128, { grayscale: false }) // converter bright pixels to white + * .unflatten() + * .toBuffer(); + */ +function unflatten () { + this.options.unflatten = true; + return this; +} + +/** + * Apply a gamma correction by reducing the encoding (darken) pre-resize at a factor of `1/gamma` + * then increasing the encoding (brighten) post-resize at a factor of `gamma`. + * This can improve the perceived brightness of a resized image in non-linear colour spaces. + * JPEG and WebP input images will not take advantage of the shrink-on-load performance optimisation + * when applying a gamma correction. + * + * Supply a second argument to use a different output gamma value, otherwise the first value is used in both cases. + * + * @param {number} [gamma=2.2] value between 1.0 and 3.0. + * @param {number} [gammaOut] value between 1.0 and 3.0. (optional, defaults to same as `gamma`) + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function gamma (gamma, gammaOut) { + if (!is.defined(gamma)) { + // Default gamma correction of 2.2 (sRGB) + this.options.gamma = 2.2; + } else if (is.number(gamma) && is.inRange(gamma, 1, 3)) { + this.options.gamma = gamma; + } else { + throw is.invalidParameterError('gamma', 'number between 1.0 and 3.0', gamma); + } + if (!is.defined(gammaOut)) { + // Default gamma correction for output is same as input + this.options.gammaOut = this.options.gamma; + } else if (is.number(gammaOut) && is.inRange(gammaOut, 1, 3)) { + this.options.gammaOut = gammaOut; + } else { + throw is.invalidParameterError('gammaOut', 'number between 1.0 and 3.0', gammaOut); + } + return this; +} + +/** + * Produce the "negative" of the image. + * + * @example + * const output = await sharp(input) + * .negate() + * .toBuffer(); + * + * @example + * const output = await sharp(input) + * .negate({ alpha: false }) + * .toBuffer(); + * + * @param {Object} [options] + * @param {Boolean} [options.alpha=true] Whether or not to negate any alpha channel + * @returns {Sharp} + */ +function negate (options) { + this.options.negate = is.bool(options) ? options : true; + if (is.plainObject(options) && 'alpha' in options) { + if (!is.bool(options.alpha)) { + throw is.invalidParameterError('alpha', 'should be boolean value', options.alpha); + } else { + this.options.negateAlpha = options.alpha; + } + } + return this; +} + +/** + * Enhance output image contrast by stretching its luminance to cover a full dynamic range. + * + * Uses a histogram-based approach, taking a default range of 1% to 99% to reduce sensitivity to noise at the extremes. + * + * Luminance values below the `lower` percentile will be underexposed by clipping to zero. + * Luminance values above the `upper` percentile will be overexposed by clipping to the max pixel value. + * + * @example + * const output = await sharp(input) + * .normalise() + * .toBuffer(); + * + * @example + * const output = await sharp(input) + * .normalise({ lower: 0, upper: 100 }) + * .toBuffer(); + * + * @param {Object} [options] + * @param {number} [options.lower=1] - Percentile below which luminance values will be underexposed. + * @param {number} [options.upper=99] - Percentile above which luminance values will be overexposed. + * @returns {Sharp} + */ +function normalise (options) { + if (is.plainObject(options)) { + if (is.defined(options.lower)) { + if (is.number(options.lower) && is.inRange(options.lower, 0, 99)) { + this.options.normaliseLower = options.lower; + } else { + throw is.invalidParameterError('lower', 'number between 0 and 99', options.lower); + } + } + if (is.defined(options.upper)) { + if (is.number(options.upper) && is.inRange(options.upper, 1, 100)) { + this.options.normaliseUpper = options.upper; + } else { + throw is.invalidParameterError('upper', 'number between 1 and 100', options.upper); + } + } + } + if (this.options.normaliseLower >= this.options.normaliseUpper) { + throw is.invalidParameterError('range', 'lower to be less than upper', + `${this.options.normaliseLower} >= ${this.options.normaliseUpper}`); + } + this.options.normalise = true; + return this; +} + +/** + * Alternative spelling of normalise. + * + * @example + * const output = await sharp(input) + * .normalize() + * .toBuffer(); + * + * @param {Object} [options] + * @param {number} [options.lower=1] - Percentile below which luminance values will be underexposed. + * @param {number} [options.upper=99] - Percentile above which luminance values will be overexposed. + * @returns {Sharp} + */ +function normalize (options) { + return this.normalise(options); +} + +/** + * Perform contrast limiting adaptive histogram equalization + * {@link https://en.wikipedia.org/wiki/Adaptive_histogram_equalization#Contrast_Limited_AHE|CLAHE}. + * + * This will, in general, enhance the clarity of the image by bringing out darker details. + * + * @since 0.28.3 + * + * @example + * const output = await sharp(input) + * .clahe({ + * width: 3, + * height: 3, + * }) + * .toBuffer(); + * + * @param {Object} options + * @param {number} options.width - Integral width of the search window, in pixels. + * @param {number} options.height - Integral height of the search window, in pixels. + * @param {number} [options.maxSlope=3] - Integral level of brightening, between 0 and 100, where 0 disables contrast limiting. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function clahe (options) { + if (is.plainObject(options)) { + if (is.integer(options.width) && options.width > 0) { + this.options.claheWidth = options.width; + } else { + throw is.invalidParameterError('width', 'integer greater than zero', options.width); + } + if (is.integer(options.height) && options.height > 0) { + this.options.claheHeight = options.height; + } else { + throw is.invalidParameterError('height', 'integer greater than zero', options.height); + } + if (is.defined(options.maxSlope)) { + if (is.integer(options.maxSlope) && is.inRange(options.maxSlope, 0, 100)) { + this.options.claheMaxSlope = options.maxSlope; + } else { + throw is.invalidParameterError('maxSlope', 'integer between 0 and 100', options.maxSlope); + } + } + } else { + throw is.invalidParameterError('options', 'plain object', options); + } + return this; +} + +/** + * Convolve the image with the specified kernel. + * + * @example + * sharp(input) + * .convolve({ + * width: 3, + * height: 3, + * kernel: [-1, 0, 1, -2, 0, 2, -1, 0, 1] + * }) + * .raw() + * .toBuffer(function(err, data, info) { + * // data contains the raw pixel data representing the convolution + * // of the input image with the horizontal Sobel operator + * }); + * + * @param {Object} kernel + * @param {number} kernel.width - width of the kernel in pixels. + * @param {number} kernel.height - height of the kernel in pixels. + * @param {Array} kernel.kernel - Array of length `width*height` containing the kernel values. + * @param {number} [kernel.scale=sum] - the scale of the kernel in pixels. + * @param {number} [kernel.offset=0] - the offset of the kernel in pixels. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function convolve (kernel) { + if (!is.object(kernel) || !Array.isArray(kernel.kernel) || + !is.integer(kernel.width) || !is.integer(kernel.height) || + !is.inRange(kernel.width, 3, 1001) || !is.inRange(kernel.height, 3, 1001) || + kernel.height * kernel.width !== kernel.kernel.length + ) { + // must pass in a kernel + throw new Error('Invalid convolution kernel'); + } + // Default scale is sum of kernel values + if (!is.integer(kernel.scale)) { + kernel.scale = kernel.kernel.reduce(function (a, b) { + return a + b; + }, 0); + } + // Clip scale to a minimum value of 1 + if (kernel.scale < 1) { + kernel.scale = 1; + } + if (!is.integer(kernel.offset)) { + kernel.offset = 0; + } + this.options.convKernel = kernel; + return this; +} + +/** + * Any pixel value greater than or equal to the threshold value will be set to 255, otherwise it will be set to 0. + * @param {number} [threshold=128] - a value in the range 0-255 representing the level at which the threshold will be applied. + * @param {Object} [options] + * @param {Boolean} [options.greyscale=true] - convert to single channel greyscale. + * @param {Boolean} [options.grayscale=true] - alternative spelling for greyscale. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function threshold (threshold, options) { + if (!is.defined(threshold)) { + this.options.threshold = 128; + } else if (is.bool(threshold)) { + this.options.threshold = threshold ? 128 : 0; + } else if (is.integer(threshold) && is.inRange(threshold, 0, 255)) { + this.options.threshold = threshold; + } else { + throw is.invalidParameterError('threshold', 'integer between 0 and 255', threshold); + } + if (!is.object(options) || options.greyscale === true || options.grayscale === true) { + this.options.thresholdGrayscale = true; + } else { + this.options.thresholdGrayscale = false; + } + return this; +} + +/** + * Perform a bitwise boolean operation with operand image. + * + * This operation creates an output image where each pixel is the result of + * the selected bitwise boolean `operation` between the corresponding pixels of the input images. + * + * @param {Buffer|string} operand - Buffer containing image data or string containing the path to an image file. + * @param {string} operator - one of `and`, `or` or `eor` to perform that bitwise operation, like the C logic operators `&`, `|` and `^` respectively. + * @param {Object} [options] + * @param {Object} [options.raw] - describes operand when using raw pixel data. + * @param {number} [options.raw.width] + * @param {number} [options.raw.height] + * @param {number} [options.raw.channels] + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function boolean (operand, operator, options) { + this.options.boolean = this._createInputDescriptor(operand, options); + if (is.string(operator) && is.inArray(operator, ['and', 'or', 'eor'])) { + this.options.booleanOp = operator; + } else { + throw is.invalidParameterError('operator', 'one of: and, or, eor', operator); + } + return this; +} + +/** + * Apply the linear formula `a` * input + `b` to the image to adjust image levels. + * + * When a single number is provided, it will be used for all image channels. + * When an array of numbers is provided, the array length must match the number of channels. + * + * @example + * await sharp(input) + * .linear(0.5, 2) + * .toBuffer(); + * + * @example + * await sharp(rgbInput) + * .linear( + * [0.25, 0.5, 0.75], + * [150, 100, 50] + * ) + * .toBuffer(); + * + * @param {(number|number[])} [a=[]] multiplier + * @param {(number|number[])} [b=[]] offset + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function linear (a, b) { + if (!is.defined(a) && is.number(b)) { + a = 1.0; + } else if (is.number(a) && !is.defined(b)) { + b = 0.0; + } + if (!is.defined(a)) { + this.options.linearA = []; + } else if (is.number(a)) { + this.options.linearA = [a]; + } else if (Array.isArray(a) && a.length && a.every(is.number)) { + this.options.linearA = a; + } else { + throw is.invalidParameterError('a', 'number or array of numbers', a); + } + if (!is.defined(b)) { + this.options.linearB = []; + } else if (is.number(b)) { + this.options.linearB = [b]; + } else if (Array.isArray(b) && b.length && b.every(is.number)) { + this.options.linearB = b; + } else { + throw is.invalidParameterError('b', 'number or array of numbers', b); + } + if (this.options.linearA.length !== this.options.linearB.length) { + throw new Error('Expected a and b to be arrays of the same length'); + } + return this; +} + +/** + * Recombine the image with the specified matrix. + * + * @since 0.21.1 + * + * @example + * sharp(input) + * .recomb([ + * [0.3588, 0.7044, 0.1368], + * [0.2990, 0.5870, 0.1140], + * [0.2392, 0.4696, 0.0912], + * ]) + * .raw() + * .toBuffer(function(err, data, info) { + * // data contains the raw pixel data after applying the matrix + * // With this example input, a sepia filter has been applied + * }); + * + * @param {Array>} inputMatrix - 3x3 or 4x4 Recombination matrix + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function recomb (inputMatrix) { + if (!Array.isArray(inputMatrix)) { + throw is.invalidParameterError('inputMatrix', 'array', inputMatrix); + } + if (inputMatrix.length !== 3 && inputMatrix.length !== 4) { + throw is.invalidParameterError('inputMatrix', '3x3 or 4x4 array', inputMatrix.length); + } + const recombMatrix = inputMatrix.flat().map(Number); + if (recombMatrix.length !== 9 && recombMatrix.length !== 16) { + throw is.invalidParameterError('inputMatrix', 'cardinality of 9 or 16', recombMatrix.length); + } + this.options.recombMatrix = recombMatrix; + return this; +} + +/** + * Transforms the image using brightness, saturation, hue rotation, and lightness. + * Brightness and lightness both operate on luminance, with the difference being that + * brightness is multiplicative whereas lightness is additive. + * + * @since 0.22.1 + * + * @example + * // increase brightness by a factor of 2 + * const output = await sharp(input) + * .modulate({ + * brightness: 2 + * }) + * .toBuffer(); + * + * @example + * // hue-rotate by 180 degrees + * const output = await sharp(input) + * .modulate({ + * hue: 180 + * }) + * .toBuffer(); + * + * @example + * // increase lightness by +50 + * const output = await sharp(input) + * .modulate({ + * lightness: 50 + * }) + * .toBuffer(); + * + * @example + * // decrease brightness and saturation while also hue-rotating by 90 degrees + * const output = await sharp(input) + * .modulate({ + * brightness: 0.5, + * saturation: 0.5, + * hue: 90, + * }) + * .toBuffer(); + * + * @param {Object} [options] + * @param {number} [options.brightness] Brightness multiplier + * @param {number} [options.saturation] Saturation multiplier + * @param {number} [options.hue] Degrees for hue rotation + * @param {number} [options.lightness] Lightness addend + * @returns {Sharp} + */ +function modulate (options) { + if (!is.plainObject(options)) { + throw is.invalidParameterError('options', 'plain object', options); + } + if ('brightness' in options) { + if (is.number(options.brightness) && options.brightness >= 0) { + this.options.brightness = options.brightness; + } else { + throw is.invalidParameterError('brightness', 'number above zero', options.brightness); + } + } + if ('saturation' in options) { + if (is.number(options.saturation) && options.saturation >= 0) { + this.options.saturation = options.saturation; + } else { + throw is.invalidParameterError('saturation', 'number above zero', options.saturation); + } + } + if ('hue' in options) { + if (is.integer(options.hue)) { + this.options.hue = options.hue % 360; + } else { + throw is.invalidParameterError('hue', 'number', options.hue); + } + } + if ('lightness' in options) { + if (is.number(options.lightness)) { + this.options.lightness = options.lightness; + } else { + throw is.invalidParameterError('lightness', 'number', options.lightness); + } + } + return this; +} + +/** + * Decorate the Sharp prototype with operation-related functions. + * @module Sharp + * @private + */ +module.exports = function (Sharp) { + Object.assign(Sharp.prototype, { + autoOrient, + rotate, + flip, + flop, + affine, + sharpen, + erode, + dilate, + median, + blur, + flatten, + unflatten, + gamma, + negate, + normalise, + normalize, + clahe, + convolve, + threshold, + boolean, + linear, + recomb, + modulate + }); +}; diff --git a/server/node_modules/sharp/lib/output.js b/server/node_modules/sharp/lib/output.js new file mode 100644 index 0000000..f1cdaf8 --- /dev/null +++ b/server/node_modules/sharp/lib/output.js @@ -0,0 +1,1655 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const path = require('node:path'); +const is = require('./is'); +const sharp = require('./sharp'); + +const formats = new Map([ + ['heic', 'heif'], + ['heif', 'heif'], + ['avif', 'avif'], + ['jpeg', 'jpeg'], + ['jpg', 'jpeg'], + ['jpe', 'jpeg'], + ['tile', 'tile'], + ['dz', 'tile'], + ['png', 'png'], + ['raw', 'raw'], + ['tiff', 'tiff'], + ['tif', 'tiff'], + ['webp', 'webp'], + ['gif', 'gif'], + ['jp2', 'jp2'], + ['jpx', 'jp2'], + ['j2k', 'jp2'], + ['j2c', 'jp2'], + ['jxl', 'jxl'] +]); + +const jp2Regex = /\.(jp[2x]|j2[kc])$/i; + +const errJp2Save = () => new Error('JP2 output requires libvips with support for OpenJPEG'); + +const bitdepthFromColourCount = (colours) => 1 << 31 - Math.clz32(Math.ceil(Math.log2(colours))); + +/** + * Write output image data to a file. + * + * If an explicit output format is not selected, it will be inferred from the extension, + * with JPEG, PNG, WebP, AVIF, TIFF, GIF, DZI, and libvips' V format supported. + * Note that raw pixel data is only supported for buffer output. + * + * By default all metadata will be removed, which includes EXIF-based orientation. + * See {@link #withmetadata|withMetadata} for control over this. + * + * The caller is responsible for ensuring directory structures and permissions exist. + * + * A `Promise` is returned when `callback` is not provided. + * + * @example + * sharp(input) + * .toFile('output.png', (err, info) => { ... }); + * + * @example + * sharp(input) + * .toFile('output.png') + * .then(info => { ... }) + * .catch(err => { ... }); + * + * @param {string} fileOut - the path to write the image data to. + * @param {Function} [callback] - called on completion with two arguments `(err, info)`. + * `info` contains the output image `format`, `size` (bytes), `width`, `height`, + * `channels` and `premultiplied` (indicating if premultiplication was used). + * When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`. + * When using the attention crop strategy also contains `attentionX` and `attentionY`, the focal point of the cropped region. + * Animated output will also contain `pageHeight` and `pages`. + * May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text. + * @returns {Promise} - when no callback is provided + * @throws {Error} Invalid parameters + */ +function toFile (fileOut, callback) { + let err; + if (!is.string(fileOut)) { + err = new Error('Missing output file path'); + } else if (is.string(this.options.input.file) && path.resolve(this.options.input.file) === path.resolve(fileOut)) { + err = new Error('Cannot use same file for input and output'); + } else if (jp2Regex.test(path.extname(fileOut)) && !this.constructor.format.jp2k.output.file) { + err = errJp2Save(); + } + if (err) { + if (is.fn(callback)) { + callback(err); + } else { + return Promise.reject(err); + } + } else { + this.options.fileOut = fileOut; + const stack = Error(); + return this._pipeline(callback, stack); + } + return this; +} + +/** + * Write output to a Buffer. + * JPEG, PNG, WebP, AVIF, TIFF, GIF and raw pixel data output are supported. + * + * Use {@link #toformat|toFormat} or one of the format-specific functions such as {@link jpeg}, {@link png} etc. to set the output format. + * + * If no explicit format is set, the output format will match the input image, except SVG input which becomes PNG output. + * + * By default all metadata will be removed, which includes EXIF-based orientation. + * See {@link #withmetadata|withMetadata} for control over this. + * + * `callback`, if present, gets three arguments `(err, data, info)` where: + * - `err` is an error, if any. + * - `data` is the output image data. + * - `info` contains the output image `format`, `size` (bytes), `width`, `height`, + * `channels` and `premultiplied` (indicating if premultiplication was used). + * When using a crop strategy also contains `cropOffsetLeft` and `cropOffsetTop`. + * Animated output will also contain `pageHeight` and `pages`. + * May also contain `textAutofitDpi` (dpi the font was rendered at) if image was created from text. + * + * A `Promise` is returned when `callback` is not provided. + * + * @example + * sharp(input) + * .toBuffer((err, data, info) => { ... }); + * + * @example + * sharp(input) + * .toBuffer() + * .then(data => { ... }) + * .catch(err => { ... }); + * + * @example + * sharp(input) + * .png() + * .toBuffer({ resolveWithObject: true }) + * .then(({ data, info }) => { ... }) + * .catch(err => { ... }); + * + * @example + * const { data, info } = await sharp('my-image.jpg') + * // output the raw pixels + * .raw() + * .toBuffer({ resolveWithObject: true }); + * + * // create a more type safe way to work with the raw pixel data + * // this will not copy the data, instead it will change `data`s underlying ArrayBuffer + * // so `data` and `pixelArray` point to the same memory location + * const pixelArray = new Uint8ClampedArray(data.buffer); + * + * // When you are done changing the pixelArray, sharp takes the `pixelArray` as an input + * const { width, height, channels } = info; + * await sharp(pixelArray, { raw: { width, height, channels } }) + * .toFile('my-changed-image.jpg'); + * + * @param {Object} [options] + * @param {boolean} [options.resolveWithObject] Resolve the Promise with an Object containing `data` and `info` properties instead of resolving only with `data`. + * @param {Function} [callback] + * @returns {Promise} - when no callback is provided + */ +function toBuffer (options, callback) { + if (is.object(options)) { + this._setBooleanOption('resolveWithObject', options.resolveWithObject); + } else if (this.options.resolveWithObject) { + this.options.resolveWithObject = false; + } + this.options.fileOut = ''; + const stack = Error(); + return this._pipeline(is.fn(options) ? options : callback, stack); +} + +/** + * Keep all EXIF metadata from the input image in the output image. + * + * EXIF metadata is unsupported for TIFF output. + * + * @since 0.33.0 + * + * @example + * const outputWithExif = await sharp(inputWithExif) + * .keepExif() + * .toBuffer(); + * + * @returns {Sharp} + */ +function keepExif () { + this.options.keepMetadata |= 0b00001; + return this; +} + +/** + * Set EXIF metadata in the output image, ignoring any EXIF in the input image. + * + * @since 0.33.0 + * + * @example + * const dataWithExif = await sharp(input) + * .withExif({ + * IFD0: { + * Copyright: 'The National Gallery' + * }, + * IFD3: { + * GPSLatitudeRef: 'N', + * GPSLatitude: '51/1 30/1 3230/100', + * GPSLongitudeRef: 'W', + * GPSLongitude: '0/1 7/1 4366/100' + * } + * }) + * .toBuffer(); + * + * @param {Object>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function withExif (exif) { + if (is.object(exif)) { + for (const [ifd, entries] of Object.entries(exif)) { + if (is.object(entries)) { + for (const [k, v] of Object.entries(entries)) { + if (is.string(v)) { + this.options.withExif[`exif-${ifd.toLowerCase()}-${k}`] = v; + } else { + throw is.invalidParameterError(`${ifd}.${k}`, 'string', v); + } + } + } else { + throw is.invalidParameterError(ifd, 'object', entries); + } + } + } else { + throw is.invalidParameterError('exif', 'object', exif); + } + this.options.withExifMerge = false; + return this.keepExif(); +} + +/** + * Update EXIF metadata from the input image in the output image. + * + * @since 0.33.0 + * + * @example + * const dataWithMergedExif = await sharp(inputWithExif) + * .withExifMerge({ + * IFD0: { + * Copyright: 'The National Gallery' + * } + * }) + * .toBuffer(); + * + * @param {Object>} exif Object keyed by IFD0, IFD1 etc. of key/value string pairs to write as EXIF data. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function withExifMerge (exif) { + this.withExif(exif); + this.options.withExifMerge = true; + return this; +} + +/** + * Keep ICC profile from the input image in the output image. + * + * Where necessary, will attempt to convert the output colour space to match the profile. + * + * @since 0.33.0 + * + * @example + * const outputWithIccProfile = await sharp(inputWithIccProfile) + * .keepIccProfile() + * .toBuffer(); + * + * @returns {Sharp} + */ +function keepIccProfile () { + this.options.keepMetadata |= 0b01000; + return this; +} + +/** + * Transform using an ICC profile and attach to the output image. + * + * This can either be an absolute filesystem path or + * built-in profile name (`srgb`, `p3`, `cmyk`). + * + * @since 0.33.0 + * + * @example + * const outputWithP3 = await sharp(input) + * .withIccProfile('p3') + * .toBuffer(); + * + * @param {string} icc - Absolute filesystem path to output ICC profile or built-in profile name (srgb, p3, cmyk). + * @param {Object} [options] + * @param {number} [options.attach=true] Should the ICC profile be included in the output image metadata? + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function withIccProfile (icc, options) { + if (is.string(icc)) { + this.options.withIccProfile = icc; + } else { + throw is.invalidParameterError('icc', 'string', icc); + } + this.keepIccProfile(); + if (is.object(options)) { + if (is.defined(options.attach)) { + if (is.bool(options.attach)) { + if (!options.attach) { + this.options.keepMetadata &= ~0b01000; + } + } else { + throw is.invalidParameterError('attach', 'boolean', options.attach); + } + } + } + return this; +} + +/** + * Keep XMP metadata from the input image in the output image. + * + * @since 0.34.3 + * + * @example + * const outputWithXmp = await sharp(inputWithXmp) + * .keepXmp() + * .toBuffer(); + * + * @returns {Sharp} + */ +function keepXmp () { + this.options.keepMetadata |= 0b00010; + return this; +} + +/** + * Set XMP metadata in the output image. + * + * Supported by PNG, JPEG, WebP, and TIFF output. + * + * @since 0.34.3 + * + * @example + * const xmpString = ` + * + * + * + * + * John Doe + * + * + * `; + * + * const data = await sharp(input) + * .withXmp(xmpString) + * .toBuffer(); + * + * @param {string} xmp String containing XMP metadata to be embedded in the output image. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function withXmp (xmp) { + if (is.string(xmp) && xmp.length > 0) { + this.options.withXmp = xmp; + this.options.keepMetadata |= 0b00010; + } else { + throw is.invalidParameterError('xmp', 'non-empty string', xmp); + } + return this; +} + +/** + * Keep all metadata (EXIF, ICC, XMP, IPTC) from the input image in the output image. + * + * The default behaviour, when `keepMetadata` is not used, is to convert to the device-independent + * sRGB colour space and strip all metadata, including the removal of any ICC profile. + * + * @since 0.33.0 + * + * @example + * const outputWithMetadata = await sharp(inputWithMetadata) + * .keepMetadata() + * .toBuffer(); + * + * @returns {Sharp} + */ +function keepMetadata () { + this.options.keepMetadata = 0b11111; + return this; +} + +/** + * Keep most metadata (EXIF, XMP, IPTC) from the input image in the output image. + * + * This will also convert to and add a web-friendly sRGB ICC profile if appropriate. + * + * Allows orientation and density to be set or updated. + * + * @example + * const outputSrgbWithMetadata = await sharp(inputRgbWithMetadata) + * .withMetadata() + * .toBuffer(); + * + * @example + * // Set output metadata to 96 DPI + * const data = await sharp(input) + * .withMetadata({ density: 96 }) + * .toBuffer(); + * + * @param {Object} [options] + * @param {number} [options.orientation] Used to update the EXIF `Orientation` tag, integer between 1 and 8. + * @param {number} [options.density] Number of pixels per inch (DPI). + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function withMetadata (options) { + this.keepMetadata(); + this.withIccProfile('srgb'); + if (is.object(options)) { + if (is.defined(options.orientation)) { + if (is.integer(options.orientation) && is.inRange(options.orientation, 1, 8)) { + this.options.withMetadataOrientation = options.orientation; + } else { + throw is.invalidParameterError('orientation', 'integer between 1 and 8', options.orientation); + } + } + if (is.defined(options.density)) { + if (is.number(options.density) && options.density > 0) { + this.options.withMetadataDensity = options.density; + } else { + throw is.invalidParameterError('density', 'positive number', options.density); + } + } + if (is.defined(options.icc)) { + this.withIccProfile(options.icc); + } + if (is.defined(options.exif)) { + this.withExifMerge(options.exif); + } + } + return this; +} + +/** + * Force output to a given format. + * + * @example + * // Convert any input to PNG output + * const data = await sharp(input) + * .toFormat('png') + * .toBuffer(); + * + * @param {(string|Object)} format - as a string or an Object with an 'id' attribute + * @param {Object} options - output options + * @returns {Sharp} + * @throws {Error} unsupported format or options + */ +function toFormat (format, options) { + const actualFormat = formats.get((is.object(format) && is.string(format.id) ? format.id : format).toLowerCase()); + if (!actualFormat) { + throw is.invalidParameterError('format', `one of: ${[...formats.keys()].join(', ')}`, format); + } + return this[actualFormat](options); +} + +/** + * Use these JPEG options for output image. + * + * @example + * // Convert any input to very high quality JPEG output + * const data = await sharp(input) + * .jpeg({ + * quality: 100, + * chromaSubsampling: '4:4:4' + * }) + * .toBuffer(); + * + * @example + * // Use mozjpeg to reduce output JPEG file size (slower) + * const data = await sharp(input) + * .jpeg({ mozjpeg: true }) + * .toBuffer(); + * + * @param {Object} [options] - output options + * @param {number} [options.quality=80] - quality, integer 1-100 + * @param {boolean} [options.progressive=false] - use progressive (interlace) scan + * @param {string} [options.chromaSubsampling='4:2:0'] - set to '4:4:4' to prevent chroma subsampling otherwise defaults to '4:2:0' chroma subsampling + * @param {boolean} [options.optimiseCoding=true] - optimise Huffman coding tables + * @param {boolean} [options.optimizeCoding=true] - alternative spelling of optimiseCoding + * @param {boolean} [options.mozjpeg=false] - use mozjpeg defaults, equivalent to `{ trellisQuantisation: true, overshootDeringing: true, optimiseScans: true, quantisationTable: 3 }` + * @param {boolean} [options.trellisQuantisation=false] - apply trellis quantisation + * @param {boolean} [options.overshootDeringing=false] - apply overshoot deringing + * @param {boolean} [options.optimiseScans=false] - optimise progressive scans, forces progressive + * @param {boolean} [options.optimizeScans=false] - alternative spelling of optimiseScans + * @param {number} [options.quantisationTable=0] - quantization table to use, integer 0-8 + * @param {number} [options.quantizationTable=0] - alternative spelling of quantisationTable + * @param {boolean} [options.force=true] - force JPEG output, otherwise attempt to use input format + * @returns {Sharp} + * @throws {Error} Invalid options + */ +function jpeg (options) { + if (is.object(options)) { + if (is.defined(options.quality)) { + if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { + this.options.jpegQuality = options.quality; + } else { + throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); + } + } + if (is.defined(options.progressive)) { + this._setBooleanOption('jpegProgressive', options.progressive); + } + if (is.defined(options.chromaSubsampling)) { + if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) { + this.options.jpegChromaSubsampling = options.chromaSubsampling; + } else { + throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling); + } + } + const optimiseCoding = is.bool(options.optimizeCoding) ? options.optimizeCoding : options.optimiseCoding; + if (is.defined(optimiseCoding)) { + this._setBooleanOption('jpegOptimiseCoding', optimiseCoding); + } + if (is.defined(options.mozjpeg)) { + if (is.bool(options.mozjpeg)) { + if (options.mozjpeg) { + this.options.jpegTrellisQuantisation = true; + this.options.jpegOvershootDeringing = true; + this.options.jpegOptimiseScans = true; + this.options.jpegProgressive = true; + this.options.jpegQuantisationTable = 3; + } + } else { + throw is.invalidParameterError('mozjpeg', 'boolean', options.mozjpeg); + } + } + const trellisQuantisation = is.bool(options.trellisQuantization) ? options.trellisQuantization : options.trellisQuantisation; + if (is.defined(trellisQuantisation)) { + this._setBooleanOption('jpegTrellisQuantisation', trellisQuantisation); + } + if (is.defined(options.overshootDeringing)) { + this._setBooleanOption('jpegOvershootDeringing', options.overshootDeringing); + } + const optimiseScans = is.bool(options.optimizeScans) ? options.optimizeScans : options.optimiseScans; + if (is.defined(optimiseScans)) { + this._setBooleanOption('jpegOptimiseScans', optimiseScans); + if (optimiseScans) { + this.options.jpegProgressive = true; + } + } + const quantisationTable = is.number(options.quantizationTable) ? options.quantizationTable : options.quantisationTable; + if (is.defined(quantisationTable)) { + if (is.integer(quantisationTable) && is.inRange(quantisationTable, 0, 8)) { + this.options.jpegQuantisationTable = quantisationTable; + } else { + throw is.invalidParameterError('quantisationTable', 'integer between 0 and 8', quantisationTable); + } + } + } + return this._updateFormatOut('jpeg', options); +} + +/** + * Use these PNG options for output image. + * + * By default, PNG output is full colour at 8 bits per pixel. + * + * Indexed PNG input at 1, 2 or 4 bits per pixel is converted to 8 bits per pixel. + * Set `palette` to `true` for slower, indexed PNG output. + * + * For 16 bits per pixel output, convert to `rgb16` via + * {@link /api-colour#tocolourspace|toColourspace}. + * + * @example + * // Convert any input to full colour PNG output + * const data = await sharp(input) + * .png() + * .toBuffer(); + * + * @example + * // Convert any input to indexed PNG output (slower) + * const data = await sharp(input) + * .png({ palette: true }) + * .toBuffer(); + * + * @example + * // Output 16 bits per pixel RGB(A) + * const data = await sharp(input) + * .toColourspace('rgb16') + * .png() + * .toBuffer(); + * + * @param {Object} [options] + * @param {boolean} [options.progressive=false] - use progressive (interlace) scan + * @param {number} [options.compressionLevel=6] - zlib compression level, 0 (fastest, largest) to 9 (slowest, smallest) + * @param {boolean} [options.adaptiveFiltering=false] - use adaptive row filtering + * @param {boolean} [options.palette=false] - quantise to a palette-based image with alpha transparency support + * @param {number} [options.quality=100] - use the lowest number of colours needed to achieve given quality, sets `palette` to `true` + * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest), sets `palette` to `true` + * @param {number} [options.colours=256] - maximum number of palette entries, sets `palette` to `true` + * @param {number} [options.colors=256] - alternative spelling of `options.colours`, sets `palette` to `true` + * @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, sets `palette` to `true` + * @param {boolean} [options.force=true] - force PNG output, otherwise attempt to use input format + * @returns {Sharp} + * @throws {Error} Invalid options + */ +function png (options) { + if (is.object(options)) { + if (is.defined(options.progressive)) { + this._setBooleanOption('pngProgressive', options.progressive); + } + if (is.defined(options.compressionLevel)) { + if (is.integer(options.compressionLevel) && is.inRange(options.compressionLevel, 0, 9)) { + this.options.pngCompressionLevel = options.compressionLevel; + } else { + throw is.invalidParameterError('compressionLevel', 'integer between 0 and 9', options.compressionLevel); + } + } + if (is.defined(options.adaptiveFiltering)) { + this._setBooleanOption('pngAdaptiveFiltering', options.adaptiveFiltering); + } + const colours = options.colours || options.colors; + if (is.defined(colours)) { + if (is.integer(colours) && is.inRange(colours, 2, 256)) { + this.options.pngBitdepth = bitdepthFromColourCount(colours); + } else { + throw is.invalidParameterError('colours', 'integer between 2 and 256', colours); + } + } + if (is.defined(options.palette)) { + this._setBooleanOption('pngPalette', options.palette); + } else if ([options.quality, options.effort, options.colours, options.colors, options.dither].some(is.defined)) { + this._setBooleanOption('pngPalette', true); + } + if (this.options.pngPalette) { + if (is.defined(options.quality)) { + if (is.integer(options.quality) && is.inRange(options.quality, 0, 100)) { + this.options.pngQuality = options.quality; + } else { + throw is.invalidParameterError('quality', 'integer between 0 and 100', options.quality); + } + } + if (is.defined(options.effort)) { + if (is.integer(options.effort) && is.inRange(options.effort, 1, 10)) { + this.options.pngEffort = options.effort; + } else { + throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort); + } + } + if (is.defined(options.dither)) { + if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) { + this.options.pngDither = options.dither; + } else { + throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither); + } + } + } + } + return this._updateFormatOut('png', options); +} + +/** + * Use these WebP options for output image. + * + * @example + * // Convert any input to lossless WebP output + * const data = await sharp(input) + * .webp({ lossless: true }) + * .toBuffer(); + * + * @example + * // Optimise the file size of an animated WebP + * const outputWebp = await sharp(inputWebp, { animated: true }) + * .webp({ effort: 6 }) + * .toBuffer(); + * + * @param {Object} [options] - output options + * @param {number} [options.quality=80] - quality, integer 1-100 + * @param {number} [options.alphaQuality=100] - quality of alpha layer, integer 0-100 + * @param {boolean} [options.lossless=false] - use lossless compression mode + * @param {boolean} [options.nearLossless=false] - use near_lossless compression mode + * @param {boolean} [options.smartSubsample=false] - use high quality chroma subsampling + * @param {boolean} [options.smartDeblock=false] - auto-adjust the deblocking filter, can improve low contrast edges (slow) + * @param {string} [options.preset='default'] - named preset for preprocessing/filtering, one of: default, photo, picture, drawing, icon, text + * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 6 (slowest) + * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation + * @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds) + * @param {boolean} [options.minSize=false] - prevent use of animation key frames to minimise file size (slow) + * @param {boolean} [options.mixed=false] - allow mixture of lossy and lossless animation frames (slow) + * @param {boolean} [options.force=true] - force WebP output, otherwise attempt to use input format + * @returns {Sharp} + * @throws {Error} Invalid options + */ +function webp (options) { + if (is.object(options)) { + if (is.defined(options.quality)) { + if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { + this.options.webpQuality = options.quality; + } else { + throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); + } + } + if (is.defined(options.alphaQuality)) { + if (is.integer(options.alphaQuality) && is.inRange(options.alphaQuality, 0, 100)) { + this.options.webpAlphaQuality = options.alphaQuality; + } else { + throw is.invalidParameterError('alphaQuality', 'integer between 0 and 100', options.alphaQuality); + } + } + if (is.defined(options.lossless)) { + this._setBooleanOption('webpLossless', options.lossless); + } + if (is.defined(options.nearLossless)) { + this._setBooleanOption('webpNearLossless', options.nearLossless); + } + if (is.defined(options.smartSubsample)) { + this._setBooleanOption('webpSmartSubsample', options.smartSubsample); + } + if (is.defined(options.smartDeblock)) { + this._setBooleanOption('webpSmartDeblock', options.smartDeblock); + } + if (is.defined(options.preset)) { + if (is.string(options.preset) && is.inArray(options.preset, ['default', 'photo', 'picture', 'drawing', 'icon', 'text'])) { + this.options.webpPreset = options.preset; + } else { + throw is.invalidParameterError('preset', 'one of: default, photo, picture, drawing, icon, text', options.preset); + } + } + if (is.defined(options.effort)) { + if (is.integer(options.effort) && is.inRange(options.effort, 0, 6)) { + this.options.webpEffort = options.effort; + } else { + throw is.invalidParameterError('effort', 'integer between 0 and 6', options.effort); + } + } + if (is.defined(options.minSize)) { + this._setBooleanOption('webpMinSize', options.minSize); + } + if (is.defined(options.mixed)) { + this._setBooleanOption('webpMixed', options.mixed); + } + } + trySetAnimationOptions(options, this.options); + return this._updateFormatOut('webp', options); +} + +/** + * Use these GIF options for the output image. + * + * The first entry in the palette is reserved for transparency. + * + * The palette of the input image will be re-used if possible. + * + * @since 0.30.0 + * + * @example + * // Convert PNG to GIF + * await sharp(pngBuffer) + * .gif() + * .toBuffer(); + * + * @example + * // Convert animated WebP to animated GIF + * await sharp('animated.webp', { animated: true }) + * .toFile('animated.gif'); + * + * @example + * // Create a 128x128, cropped, non-dithered, animated thumbnail of an animated GIF + * const out = await sharp('in.gif', { animated: true }) + * .resize({ width: 128, height: 128 }) + * .gif({ dither: 0 }) + * .toBuffer(); + * + * @example + * // Lossy file size reduction of animated GIF + * await sharp('in.gif', { animated: true }) + * .gif({ interFrameMaxError: 8 }) + * .toFile('optim.gif'); + * + * @param {Object} [options] - output options + * @param {boolean} [options.reuse=true] - re-use existing palette, otherwise generate new (slow) + * @param {boolean} [options.progressive=false] - use progressive (interlace) scan + * @param {number} [options.colours=256] - maximum number of palette entries, including transparency, between 2 and 256 + * @param {number} [options.colors=256] - alternative spelling of `options.colours` + * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 10 (slowest) + * @param {number} [options.dither=1.0] - level of Floyd-Steinberg error diffusion, between 0 (least) and 1 (most) + * @param {number} [options.interFrameMaxError=0] - maximum inter-frame error for transparency, between 0 (lossless) and 32 + * @param {number} [options.interPaletteMaxError=3] - maximum inter-palette error for palette reuse, between 0 and 256 + * @param {boolean} [options.keepDuplicateFrames=false] - keep duplicate frames in the output instead of combining them + * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation + * @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds) + * @param {boolean} [options.force=true] - force GIF output, otherwise attempt to use input format + * @returns {Sharp} + * @throws {Error} Invalid options + */ +function gif (options) { + if (is.object(options)) { + if (is.defined(options.reuse)) { + this._setBooleanOption('gifReuse', options.reuse); + } + if (is.defined(options.progressive)) { + this._setBooleanOption('gifProgressive', options.progressive); + } + const colours = options.colours || options.colors; + if (is.defined(colours)) { + if (is.integer(colours) && is.inRange(colours, 2, 256)) { + this.options.gifBitdepth = bitdepthFromColourCount(colours); + } else { + throw is.invalidParameterError('colours', 'integer between 2 and 256', colours); + } + } + if (is.defined(options.effort)) { + if (is.number(options.effort) && is.inRange(options.effort, 1, 10)) { + this.options.gifEffort = options.effort; + } else { + throw is.invalidParameterError('effort', 'integer between 1 and 10', options.effort); + } + } + if (is.defined(options.dither)) { + if (is.number(options.dither) && is.inRange(options.dither, 0, 1)) { + this.options.gifDither = options.dither; + } else { + throw is.invalidParameterError('dither', 'number between 0.0 and 1.0', options.dither); + } + } + if (is.defined(options.interFrameMaxError)) { + if (is.number(options.interFrameMaxError) && is.inRange(options.interFrameMaxError, 0, 32)) { + this.options.gifInterFrameMaxError = options.interFrameMaxError; + } else { + throw is.invalidParameterError('interFrameMaxError', 'number between 0.0 and 32.0', options.interFrameMaxError); + } + } + if (is.defined(options.interPaletteMaxError)) { + if (is.number(options.interPaletteMaxError) && is.inRange(options.interPaletteMaxError, 0, 256)) { + this.options.gifInterPaletteMaxError = options.interPaletteMaxError; + } else { + throw is.invalidParameterError('interPaletteMaxError', 'number between 0.0 and 256.0', options.interPaletteMaxError); + } + } + if (is.defined(options.keepDuplicateFrames)) { + if (is.bool(options.keepDuplicateFrames)) { + this._setBooleanOption('gifKeepDuplicateFrames', options.keepDuplicateFrames); + } else { + throw is.invalidParameterError('keepDuplicateFrames', 'boolean', options.keepDuplicateFrames); + } + } + } + trySetAnimationOptions(options, this.options); + return this._updateFormatOut('gif', options); +} + +/* istanbul ignore next */ +/** + * Use these JP2 options for output image. + * + * Requires libvips compiled with support for OpenJPEG. + * The prebuilt binaries do not include this - see + * {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}. + * + * @example + * // Convert any input to lossless JP2 output + * const data = await sharp(input) + * .jp2({ lossless: true }) + * .toBuffer(); + * + * @example + * // Convert any input to very high quality JP2 output + * const data = await sharp(input) + * .jp2({ + * quality: 100, + * chromaSubsampling: '4:4:4' + * }) + * .toBuffer(); + * + * @since 0.29.1 + * + * @param {Object} [options] - output options + * @param {number} [options.quality=80] - quality, integer 1-100 + * @param {boolean} [options.lossless=false] - use lossless compression mode + * @param {number} [options.tileWidth=512] - horizontal tile size + * @param {number} [options.tileHeight=512] - vertical tile size + * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling + * @returns {Sharp} + * @throws {Error} Invalid options + */ +function jp2 (options) { + if (!this.constructor.format.jp2k.output.buffer) { + throw errJp2Save(); + } + if (is.object(options)) { + if (is.defined(options.quality)) { + if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { + this.options.jp2Quality = options.quality; + } else { + throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); + } + } + if (is.defined(options.lossless)) { + if (is.bool(options.lossless)) { + this.options.jp2Lossless = options.lossless; + } else { + throw is.invalidParameterError('lossless', 'boolean', options.lossless); + } + } + if (is.defined(options.tileWidth)) { + if (is.integer(options.tileWidth) && is.inRange(options.tileWidth, 1, 32768)) { + this.options.jp2TileWidth = options.tileWidth; + } else { + throw is.invalidParameterError('tileWidth', 'integer between 1 and 32768', options.tileWidth); + } + } + if (is.defined(options.tileHeight)) { + if (is.integer(options.tileHeight) && is.inRange(options.tileHeight, 1, 32768)) { + this.options.jp2TileHeight = options.tileHeight; + } else { + throw is.invalidParameterError('tileHeight', 'integer between 1 and 32768', options.tileHeight); + } + } + if (is.defined(options.chromaSubsampling)) { + if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) { + this.options.jp2ChromaSubsampling = options.chromaSubsampling; + } else { + throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling); + } + } + } + return this._updateFormatOut('jp2', options); +} + +/** + * Set animation options if available. + * @private + * + * @param {Object} [source] - output options + * @param {number} [source.loop=0] - number of animation iterations, use 0 for infinite animation + * @param {number[]} [source.delay] - list of delays between animation frames (in milliseconds) + * @param {Object} [target] - target object for valid options + * @throws {Error} Invalid options + */ +function trySetAnimationOptions (source, target) { + if (is.object(source) && is.defined(source.loop)) { + if (is.integer(source.loop) && is.inRange(source.loop, 0, 65535)) { + target.loop = source.loop; + } else { + throw is.invalidParameterError('loop', 'integer between 0 and 65535', source.loop); + } + } + if (is.object(source) && is.defined(source.delay)) { + // We allow singular values as well + if (is.integer(source.delay) && is.inRange(source.delay, 0, 65535)) { + target.delay = [source.delay]; + } else if ( + Array.isArray(source.delay) && + source.delay.every(is.integer) && + source.delay.every(v => is.inRange(v, 0, 65535))) { + target.delay = source.delay; + } else { + throw is.invalidParameterError('delay', 'integer or an array of integers between 0 and 65535', source.delay); + } + } +} + +/** + * Use these TIFF options for output image. + * + * The `density` can be set in pixels/inch via {@link #withmetadata|withMetadata} + * instead of providing `xres` and `yres` in pixels/mm. + * + * @example + * // Convert SVG input to LZW-compressed, 1 bit per pixel TIFF output + * sharp('input.svg') + * .tiff({ + * compression: 'lzw', + * bitdepth: 1 + * }) + * .toFile('1-bpp-output.tiff') + * .then(info => { ... }); + * + * @param {Object} [options] - output options + * @param {number} [options.quality=80] - quality, integer 1-100 + * @param {boolean} [options.force=true] - force TIFF output, otherwise attempt to use input format + * @param {string} [options.compression='jpeg'] - compression options: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k + * @param {string} [options.predictor='horizontal'] - compression predictor options: none, horizontal, float + * @param {boolean} [options.pyramid=false] - write an image pyramid + * @param {boolean} [options.tile=false] - write a tiled tiff + * @param {number} [options.tileWidth=256] - horizontal tile size + * @param {number} [options.tileHeight=256] - vertical tile size + * @param {number} [options.xres=1.0] - horizontal resolution in pixels/mm + * @param {number} [options.yres=1.0] - vertical resolution in pixels/mm + * @param {string} [options.resolutionUnit='inch'] - resolution unit options: inch, cm + * @param {number} [options.bitdepth=8] - reduce bitdepth to 1, 2 or 4 bit + * @param {boolean} [options.miniswhite=false] - write 1-bit images as miniswhite + * @returns {Sharp} + * @throws {Error} Invalid options + */ +function tiff (options) { + if (is.object(options)) { + if (is.defined(options.quality)) { + if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { + this.options.tiffQuality = options.quality; + } else { + throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); + } + } + if (is.defined(options.bitdepth)) { + if (is.integer(options.bitdepth) && is.inArray(options.bitdepth, [1, 2, 4, 8])) { + this.options.tiffBitdepth = options.bitdepth; + } else { + throw is.invalidParameterError('bitdepth', '1, 2, 4 or 8', options.bitdepth); + } + } + // tiling + if (is.defined(options.tile)) { + this._setBooleanOption('tiffTile', options.tile); + } + if (is.defined(options.tileWidth)) { + if (is.integer(options.tileWidth) && options.tileWidth > 0) { + this.options.tiffTileWidth = options.tileWidth; + } else { + throw is.invalidParameterError('tileWidth', 'integer greater than zero', options.tileWidth); + } + } + if (is.defined(options.tileHeight)) { + if (is.integer(options.tileHeight) && options.tileHeight > 0) { + this.options.tiffTileHeight = options.tileHeight; + } else { + throw is.invalidParameterError('tileHeight', 'integer greater than zero', options.tileHeight); + } + } + // miniswhite + if (is.defined(options.miniswhite)) { + this._setBooleanOption('tiffMiniswhite', options.miniswhite); + } + // pyramid + if (is.defined(options.pyramid)) { + this._setBooleanOption('tiffPyramid', options.pyramid); + } + // resolution + if (is.defined(options.xres)) { + if (is.number(options.xres) && options.xres > 0) { + this.options.tiffXres = options.xres; + } else { + throw is.invalidParameterError('xres', 'number greater than zero', options.xres); + } + } + if (is.defined(options.yres)) { + if (is.number(options.yres) && options.yres > 0) { + this.options.tiffYres = options.yres; + } else { + throw is.invalidParameterError('yres', 'number greater than zero', options.yres); + } + } + // compression + if (is.defined(options.compression)) { + if (is.string(options.compression) && is.inArray(options.compression, ['none', 'jpeg', 'deflate', 'packbits', 'ccittfax4', 'lzw', 'webp', 'zstd', 'jp2k'])) { + this.options.tiffCompression = options.compression; + } else { + throw is.invalidParameterError('compression', 'one of: none, jpeg, deflate, packbits, ccittfax4, lzw, webp, zstd, jp2k', options.compression); + } + } + // predictor + if (is.defined(options.predictor)) { + if (is.string(options.predictor) && is.inArray(options.predictor, ['none', 'horizontal', 'float'])) { + this.options.tiffPredictor = options.predictor; + } else { + throw is.invalidParameterError('predictor', 'one of: none, horizontal, float', options.predictor); + } + } + // resolutionUnit + if (is.defined(options.resolutionUnit)) { + if (is.string(options.resolutionUnit) && is.inArray(options.resolutionUnit, ['inch', 'cm'])) { + this.options.tiffResolutionUnit = options.resolutionUnit; + } else { + throw is.invalidParameterError('resolutionUnit', 'one of: inch, cm', options.resolutionUnit); + } + } + } + return this._updateFormatOut('tiff', options); +} + +/** + * Use these AVIF options for output image. + * + * AVIF image sequences are not supported. + * Prebuilt binaries support a bitdepth of 8 only. + * + * This feature is experimental on the Windows ARM64 platform + * and requires a CPU with ARM64v8.4 or later. + * + * @example + * const data = await sharp(input) + * .avif({ effort: 2 }) + * .toBuffer(); + * + * @example + * const data = await sharp(input) + * .avif({ lossless: true }) + * .toBuffer(); + * + * @since 0.27.0 + * + * @param {Object} [options] - output options + * @param {number} [options.quality=50] - quality, integer 1-100 + * @param {boolean} [options.lossless=false] - use lossless compression + * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest) + * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling + * @param {number} [options.bitdepth=8] - set bitdepth to 8, 10 or 12 bit + * @returns {Sharp} + * @throws {Error} Invalid options + */ +function avif (options) { + return this.heif({ ...options, compression: 'av1' }); +} + +/** + * Use these HEIF options for output image. + * + * Support for patent-encumbered HEIC images using `hevc` compression requires the use of a + * globally-installed libvips compiled with support for libheif, libde265 and x265. + * + * @example + * const data = await sharp(input) + * .heif({ compression: 'hevc' }) + * .toBuffer(); + * + * @since 0.23.0 + * + * @param {Object} options - output options + * @param {string} options.compression - compression format: av1, hevc + * @param {number} [options.quality=50] - quality, integer 1-100 + * @param {boolean} [options.lossless=false] - use lossless compression + * @param {number} [options.effort=4] - CPU effort, between 0 (fastest) and 9 (slowest) + * @param {string} [options.chromaSubsampling='4:4:4'] - set to '4:2:0' to use chroma subsampling + * @param {number} [options.bitdepth=8] - set bitdepth to 8, 10 or 12 bit + * @returns {Sharp} + * @throws {Error} Invalid options + */ +function heif (options) { + if (is.object(options)) { + if (is.string(options.compression) && is.inArray(options.compression, ['av1', 'hevc'])) { + this.options.heifCompression = options.compression; + } else { + throw is.invalidParameterError('compression', 'one of: av1, hevc', options.compression); + } + if (is.defined(options.quality)) { + if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { + this.options.heifQuality = options.quality; + } else { + throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); + } + } + if (is.defined(options.lossless)) { + if (is.bool(options.lossless)) { + this.options.heifLossless = options.lossless; + } else { + throw is.invalidParameterError('lossless', 'boolean', options.lossless); + } + } + if (is.defined(options.effort)) { + if (is.integer(options.effort) && is.inRange(options.effort, 0, 9)) { + this.options.heifEffort = options.effort; + } else { + throw is.invalidParameterError('effort', 'integer between 0 and 9', options.effort); + } + } + if (is.defined(options.chromaSubsampling)) { + if (is.string(options.chromaSubsampling) && is.inArray(options.chromaSubsampling, ['4:2:0', '4:4:4'])) { + this.options.heifChromaSubsampling = options.chromaSubsampling; + } else { + throw is.invalidParameterError('chromaSubsampling', 'one of: 4:2:0, 4:4:4', options.chromaSubsampling); + } + } + if (is.defined(options.bitdepth)) { + if (is.integer(options.bitdepth) && is.inArray(options.bitdepth, [8, 10, 12])) { + if (options.bitdepth !== 8 && this.constructor.versions.heif) { + throw is.invalidParameterError('bitdepth when using prebuilt binaries', 8, options.bitdepth); + } + this.options.heifBitdepth = options.bitdepth; + } else { + throw is.invalidParameterError('bitdepth', '8, 10 or 12', options.bitdepth); + } + } + } else { + throw is.invalidParameterError('options', 'Object', options); + } + return this._updateFormatOut('heif', options); +} + +/** + * Use these JPEG-XL (JXL) options for output image. + * + * This feature is experimental, please do not use in production systems. + * + * Requires libvips compiled with support for libjxl. + * The prebuilt binaries do not include this - see + * {@link https://sharp.pixelplumbing.com/install#custom-libvips installing a custom libvips}. + * + * @since 0.31.3 + * + * @param {Object} [options] - output options + * @param {number} [options.distance=1.0] - maximum encoding error, between 0 (highest quality) and 15 (lowest quality) + * @param {number} [options.quality] - calculate `distance` based on JPEG-like quality, between 1 and 100, overrides distance if specified + * @param {number} [options.decodingTier=0] - target decode speed tier, between 0 (highest quality) and 4 (lowest quality) + * @param {boolean} [options.lossless=false] - use lossless compression + * @param {number} [options.effort=7] - CPU effort, between 1 (fastest) and 9 (slowest) + * @param {number} [options.loop=0] - number of animation iterations, use 0 for infinite animation + * @param {number|number[]} [options.delay] - delay(s) between animation frames (in milliseconds) + * @returns {Sharp} + * @throws {Error} Invalid options + */ +function jxl (options) { + if (is.object(options)) { + if (is.defined(options.quality)) { + if (is.integer(options.quality) && is.inRange(options.quality, 1, 100)) { + // https://github.com/libjxl/libjxl/blob/0aeea7f180bafd6893c1db8072dcb67d2aa5b03d/tools/cjxl_main.cc#L640-L644 + this.options.jxlDistance = options.quality >= 30 + ? 0.1 + (100 - options.quality) * 0.09 + : 53 / 3000 * options.quality * options.quality - 23 / 20 * options.quality + 25; + } else { + throw is.invalidParameterError('quality', 'integer between 1 and 100', options.quality); + } + } else if (is.defined(options.distance)) { + if (is.number(options.distance) && is.inRange(options.distance, 0, 15)) { + this.options.jxlDistance = options.distance; + } else { + throw is.invalidParameterError('distance', 'number between 0.0 and 15.0', options.distance); + } + } + if (is.defined(options.decodingTier)) { + if (is.integer(options.decodingTier) && is.inRange(options.decodingTier, 0, 4)) { + this.options.jxlDecodingTier = options.decodingTier; + } else { + throw is.invalidParameterError('decodingTier', 'integer between 0 and 4', options.decodingTier); + } + } + if (is.defined(options.lossless)) { + if (is.bool(options.lossless)) { + this.options.jxlLossless = options.lossless; + } else { + throw is.invalidParameterError('lossless', 'boolean', options.lossless); + } + } + if (is.defined(options.effort)) { + if (is.integer(options.effort) && is.inRange(options.effort, 1, 9)) { + this.options.jxlEffort = options.effort; + } else { + throw is.invalidParameterError('effort', 'integer between 1 and 9', options.effort); + } + } + } + trySetAnimationOptions(options, this.options); + return this._updateFormatOut('jxl', options); +} + +/** + * Force output to be raw, uncompressed pixel data. + * Pixel ordering is left-to-right, top-to-bottom, without padding. + * Channel ordering will be RGB or RGBA for non-greyscale colourspaces. + * + * @example + * // Extract raw, unsigned 8-bit RGB pixel data from JPEG input + * const { data, info } = await sharp('input.jpg') + * .raw() + * .toBuffer({ resolveWithObject: true }); + * + * @example + * // Extract alpha channel as raw, unsigned 16-bit pixel data from PNG input + * const data = await sharp('input.png') + * .ensureAlpha() + * .extractChannel(3) + * .toColourspace('b-w') + * .raw({ depth: 'ushort' }) + * .toBuffer(); + * + * @param {Object} [options] - output options + * @param {string} [options.depth='uchar'] - bit depth, one of: char, uchar (default), short, ushort, int, uint, float, complex, double, dpcomplex + * @returns {Sharp} + * @throws {Error} Invalid options + */ +function raw (options) { + if (is.object(options)) { + if (is.defined(options.depth)) { + if (is.string(options.depth) && is.inArray(options.depth, + ['char', 'uchar', 'short', 'ushort', 'int', 'uint', 'float', 'complex', 'double', 'dpcomplex'] + )) { + this.options.rawDepth = options.depth; + } else { + throw is.invalidParameterError('depth', 'one of: char, uchar, short, ushort, int, uint, float, complex, double, dpcomplex', options.depth); + } + } + } + return this._updateFormatOut('raw'); +} + +/** + * Use tile-based deep zoom (image pyramid) output. + * + * Set the format and options for tile images via the `toFormat`, `jpeg`, `png` or `webp` functions. + * Use a `.zip` or `.szi` file extension with `toFile` to write to a compressed archive file format. + * + * The container will be set to `zip` when the output is a Buffer or Stream, otherwise it will default to `fs`. + * + * @example + * sharp('input.tiff') + * .png() + * .tile({ + * size: 512 + * }) + * .toFile('output.dz', function(err, info) { + * // output.dzi is the Deep Zoom XML definition + * // output_files contains 512x512 tiles grouped by zoom level + * }); + * + * @example + * const zipFileWithTiles = await sharp(input) + * .tile({ basename: "tiles" }) + * .toBuffer(); + * + * @example + * const iiififier = sharp().tile({ layout: "iiif" }); + * readableStream + * .pipe(iiififier) + * .pipe(writeableStream); + * + * @param {Object} [options] + * @param {number} [options.size=256] tile size in pixels, a value between 1 and 8192. + * @param {number} [options.overlap=0] tile overlap in pixels, a value between 0 and 8192. + * @param {number} [options.angle=0] tile angle of rotation, must be a multiple of 90. + * @param {string|Object} [options.background={r: 255, g: 255, b: 255, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to white without transparency. + * @param {string} [options.depth] how deep to make the pyramid, possible values are `onepixel`, `onetile` or `one`, default based on layout. + * @param {number} [options.skipBlanks=-1] Threshold to skip tile generation. Range is 0-255 for 8-bit images, 0-65535 for 16-bit images. Default is 5 for `google` layout, -1 (no skip) otherwise. + * @param {string} [options.container='fs'] tile container, with value `fs` (filesystem) or `zip` (compressed file). + * @param {string} [options.layout='dz'] filesystem layout, possible values are `dz`, `iiif`, `iiif3`, `zoomify` or `google`. + * @param {boolean} [options.centre=false] centre image in tile. + * @param {boolean} [options.center=false] alternative spelling of centre. + * @param {string} [options.id='https://example.com/iiif'] when `layout` is `iiif`/`iiif3`, sets the `@id`/`id` attribute of `info.json` + * @param {string} [options.basename] the name of the directory within the zip file when container is `zip`. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function tile (options) { + if (is.object(options)) { + // Size of square tiles, in pixels + if (is.defined(options.size)) { + if (is.integer(options.size) && is.inRange(options.size, 1, 8192)) { + this.options.tileSize = options.size; + } else { + throw is.invalidParameterError('size', 'integer between 1 and 8192', options.size); + } + } + // Overlap of tiles, in pixels + if (is.defined(options.overlap)) { + if (is.integer(options.overlap) && is.inRange(options.overlap, 0, 8192)) { + if (options.overlap > this.options.tileSize) { + throw is.invalidParameterError('overlap', `<= size (${this.options.tileSize})`, options.overlap); + } + this.options.tileOverlap = options.overlap; + } else { + throw is.invalidParameterError('overlap', 'integer between 0 and 8192', options.overlap); + } + } + // Container + if (is.defined(options.container)) { + if (is.string(options.container) && is.inArray(options.container, ['fs', 'zip'])) { + this.options.tileContainer = options.container; + } else { + throw is.invalidParameterError('container', 'one of: fs, zip', options.container); + } + } + // Layout + if (is.defined(options.layout)) { + if (is.string(options.layout) && is.inArray(options.layout, ['dz', 'google', 'iiif', 'iiif3', 'zoomify'])) { + this.options.tileLayout = options.layout; + } else { + throw is.invalidParameterError('layout', 'one of: dz, google, iiif, iiif3, zoomify', options.layout); + } + } + // Angle of rotation, + if (is.defined(options.angle)) { + if (is.integer(options.angle) && !(options.angle % 90)) { + this.options.tileAngle = options.angle; + } else { + throw is.invalidParameterError('angle', 'positive/negative multiple of 90', options.angle); + } + } + // Background colour + this._setBackgroundColourOption('tileBackground', options.background); + // Depth of tiles + if (is.defined(options.depth)) { + if (is.string(options.depth) && is.inArray(options.depth, ['onepixel', 'onetile', 'one'])) { + this.options.tileDepth = options.depth; + } else { + throw is.invalidParameterError('depth', 'one of: onepixel, onetile, one', options.depth); + } + } + // Threshold to skip blank tiles + if (is.defined(options.skipBlanks)) { + if (is.integer(options.skipBlanks) && is.inRange(options.skipBlanks, -1, 65535)) { + this.options.tileSkipBlanks = options.skipBlanks; + } else { + throw is.invalidParameterError('skipBlanks', 'integer between -1 and 255/65535', options.skipBlanks); + } + } else if (is.defined(options.layout) && options.layout === 'google') { + this.options.tileSkipBlanks = 5; + } + // Center image in tile + const centre = is.bool(options.center) ? options.center : options.centre; + if (is.defined(centre)) { + this._setBooleanOption('tileCentre', centre); + } + // @id attribute for IIIF layout + if (is.defined(options.id)) { + if (is.string(options.id)) { + this.options.tileId = options.id; + } else { + throw is.invalidParameterError('id', 'string', options.id); + } + } + // Basename for zip container + if (is.defined(options.basename)) { + if (is.string(options.basename)) { + this.options.tileBasename = options.basename; + } else { + throw is.invalidParameterError('basename', 'string', options.basename); + } + } + } + // Format + if (is.inArray(this.options.formatOut, ['jpeg', 'png', 'webp'])) { + this.options.tileFormat = this.options.formatOut; + } else if (this.options.formatOut !== 'input') { + throw is.invalidParameterError('format', 'one of: jpeg, png, webp', this.options.formatOut); + } + return this._updateFormatOut('dz'); +} + +/** + * Set a timeout for processing, in seconds. + * Use a value of zero to continue processing indefinitely, the default behaviour. + * + * The clock starts when libvips opens an input image for processing. + * Time spent waiting for a libuv thread to become available is not included. + * + * @example + * // Ensure processing takes no longer than 3 seconds + * try { + * const data = await sharp(input) + * .blur(1000) + * .timeout({ seconds: 3 }) + * .toBuffer(); + * } catch (err) { + * if (err.message.includes('timeout')) { ... } + * } + * + * @since 0.29.2 + * + * @param {Object} options + * @param {number} options.seconds - Number of seconds after which processing will be stopped + * @returns {Sharp} + */ +function timeout (options) { + if (!is.plainObject(options)) { + throw is.invalidParameterError('options', 'object', options); + } + if (is.integer(options.seconds) && is.inRange(options.seconds, 0, 3600)) { + this.options.timeoutSeconds = options.seconds; + } else { + throw is.invalidParameterError('seconds', 'integer between 0 and 3600', options.seconds); + } + return this; +} + +/** + * Update the output format unless options.force is false, + * in which case revert to input format. + * @private + * @param {string} formatOut + * @param {Object} [options] + * @param {boolean} [options.force=true] - force output format, otherwise attempt to use input format + * @returns {Sharp} + */ +function _updateFormatOut (formatOut, options) { + if (!(is.object(options) && options.force === false)) { + this.options.formatOut = formatOut; + } + return this; +} + +/** + * Update a boolean attribute of the this.options Object. + * @private + * @param {string} key + * @param {boolean} val + * @throws {Error} Invalid key + */ +function _setBooleanOption (key, val) { + if (is.bool(val)) { + this.options[key] = val; + } else { + throw is.invalidParameterError(key, 'boolean', val); + } +} + +/** + * Called by a WriteableStream to notify us it is ready for data. + * @private + */ +function _read () { + /* istanbul ignore else */ + if (!this.options.streamOut) { + this.options.streamOut = true; + const stack = Error(); + this._pipeline(undefined, stack); + } +} + +/** + * Invoke the C++ image processing pipeline + * Supports callback, stream and promise variants + * @private + */ +function _pipeline (callback, stack) { + if (typeof callback === 'function') { + // output=file/buffer + if (this._isStreamInput()) { + // output=file/buffer, input=stream + this.on('finish', () => { + this._flattenBufferIn(); + sharp.pipeline(this.options, (err, data, info) => { + if (err) { + callback(is.nativeError(err, stack)); + } else { + callback(null, data, info); + } + }); + }); + } else { + // output=file/buffer, input=file/buffer + sharp.pipeline(this.options, (err, data, info) => { + if (err) { + callback(is.nativeError(err, stack)); + } else { + callback(null, data, info); + } + }); + } + return this; + } else if (this.options.streamOut) { + // output=stream + if (this._isStreamInput()) { + // output=stream, input=stream + this.once('finish', () => { + this._flattenBufferIn(); + sharp.pipeline(this.options, (err, data, info) => { + if (err) { + this.emit('error', is.nativeError(err, stack)); + } else { + this.emit('info', info); + this.push(data); + } + this.push(null); + this.on('end', () => this.emit('close')); + }); + }); + if (this.streamInFinished) { + this.emit('finish'); + } + } else { + // output=stream, input=file/buffer + sharp.pipeline(this.options, (err, data, info) => { + if (err) { + this.emit('error', is.nativeError(err, stack)); + } else { + this.emit('info', info); + this.push(data); + } + this.push(null); + this.on('end', () => this.emit('close')); + }); + } + return this; + } else { + // output=promise + if (this._isStreamInput()) { + // output=promise, input=stream + return new Promise((resolve, reject) => { + this.once('finish', () => { + this._flattenBufferIn(); + sharp.pipeline(this.options, (err, data, info) => { + if (err) { + reject(is.nativeError(err, stack)); + } else { + if (this.options.resolveWithObject) { + resolve({ data, info }); + } else { + resolve(data); + } + } + }); + }); + }); + } else { + // output=promise, input=file/buffer + return new Promise((resolve, reject) => { + sharp.pipeline(this.options, (err, data, info) => { + if (err) { + reject(is.nativeError(err, stack)); + } else { + if (this.options.resolveWithObject) { + resolve({ data, info }); + } else { + resolve(data); + } + } + }); + }); + } + } +} + +/** + * Decorate the Sharp prototype with output-related functions. + * @module Sharp + * @private + */ +module.exports = function (Sharp) { + Object.assign(Sharp.prototype, { + // Public + toFile, + toBuffer, + keepExif, + withExif, + withExifMerge, + keepIccProfile, + withIccProfile, + keepXmp, + withXmp, + keepMetadata, + withMetadata, + toFormat, + jpeg, + jp2, + png, + webp, + tiff, + avif, + heif, + jxl, + gif, + raw, + tile, + timeout, + // Private + _updateFormatOut, + _setBooleanOption, + _read, + _pipeline + }); +}; diff --git a/server/node_modules/sharp/lib/resize.js b/server/node_modules/sharp/lib/resize.js new file mode 100644 index 0000000..9e4aa78 --- /dev/null +++ b/server/node_modules/sharp/lib/resize.js @@ -0,0 +1,595 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const is = require('./is'); + +/** + * Weighting to apply when using contain/cover fit. + * @member + * @private + */ +const gravity = { + center: 0, + centre: 0, + north: 1, + east: 2, + south: 3, + west: 4, + northeast: 5, + southeast: 6, + southwest: 7, + northwest: 8 +}; + +/** + * Position to apply when using contain/cover fit. + * @member + * @private + */ +const position = { + top: 1, + right: 2, + bottom: 3, + left: 4, + 'right top': 5, + 'right bottom': 6, + 'left bottom': 7, + 'left top': 8 +}; + +/** + * How to extend the image. + * @member + * @private + */ +const extendWith = { + background: 'background', + copy: 'copy', + repeat: 'repeat', + mirror: 'mirror' +}; + +/** + * Strategies for automagic cover behaviour. + * @member + * @private + */ +const strategy = { + entropy: 16, + attention: 17 +}; + +/** + * Reduction kernels. + * @member + * @private + */ +const kernel = { + nearest: 'nearest', + linear: 'linear', + cubic: 'cubic', + mitchell: 'mitchell', + lanczos2: 'lanczos2', + lanczos3: 'lanczos3', + mks2013: 'mks2013', + mks2021: 'mks2021' +}; + +/** + * Methods by which an image can be resized to fit the provided dimensions. + * @member + * @private + */ +const fit = { + contain: 'contain', + cover: 'cover', + fill: 'fill', + inside: 'inside', + outside: 'outside' +}; + +/** + * Map external fit property to internal canvas property. + * @member + * @private + */ +const mapFitToCanvas = { + contain: 'embed', + cover: 'crop', + fill: 'ignore_aspect', + inside: 'max', + outside: 'min' +}; + +/** + * @private + */ +function isRotationExpected (options) { + return (options.angle % 360) !== 0 || options.rotationAngle !== 0; +} + +/** + * @private + */ +function isResizeExpected (options) { + return options.width !== -1 || options.height !== -1; +} + +/** + * Resize image to `width`, `height` or `width x height`. + * + * When both a `width` and `height` are provided, the possible methods by which the image should **fit** these are: + * - `cover`: (default) Preserving aspect ratio, attempt to ensure the image covers both provided dimensions by cropping/clipping to fit. + * - `contain`: Preserving aspect ratio, contain within both provided dimensions using "letterboxing" where necessary. + * - `fill`: Ignore the aspect ratio of the input and stretch to both provided dimensions. + * - `inside`: Preserving aspect ratio, resize the image to be as large as possible while ensuring its dimensions are less than or equal to both those specified. + * - `outside`: Preserving aspect ratio, resize the image to be as small as possible while ensuring its dimensions are greater than or equal to both those specified. + * + * Some of these values are based on the [object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit) CSS property. + * + * Examples of various values for the fit property when resizing + * + * When using a **fit** of `cover` or `contain`, the default **position** is `centre`. Other options are: + * - `sharp.position`: `top`, `right top`, `right`, `right bottom`, `bottom`, `left bottom`, `left`, `left top`. + * - `sharp.gravity`: `north`, `northeast`, `east`, `southeast`, `south`, `southwest`, `west`, `northwest`, `center` or `centre`. + * - `sharp.strategy`: `cover` only, dynamically crop using either the `entropy` or `attention` strategy. + * + * Some of these values are based on the [object-position](https://developer.mozilla.org/en-US/docs/Web/CSS/object-position) CSS property. + * + * The strategy-based approach initially resizes so one dimension is at its target length + * then repeatedly ranks edge regions, discarding the edge with the lowest score based on the selected strategy. + * - `entropy`: focus on the region with the highest [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_%28information_theory%29). + * - `attention`: focus on the region with the highest luminance frequency, colour saturation and presence of skin tones. + * + * Possible downsizing kernels are: + * - `nearest`: Use [nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). + * - `linear`: Use a [triangle filter](https://en.wikipedia.org/wiki/Triangular_function). + * - `cubic`: Use a [Catmull-Rom spline](https://en.wikipedia.org/wiki/Centripetal_Catmull%E2%80%93Rom_spline). + * - `mitchell`: Use a [Mitchell-Netravali spline](https://www.cs.utexas.edu/~fussell/courses/cs384g-fall2013/lectures/mitchell/Mitchell.pdf). + * - `lanczos2`: Use a [Lanczos kernel](https://en.wikipedia.org/wiki/Lanczos_resampling#Lanczos_kernel) with `a=2`. + * - `lanczos3`: Use a Lanczos kernel with `a=3` (the default). + * - `mks2013`: Use a [Magic Kernel Sharp](https://johncostella.com/magic/mks.pdf) 2013 kernel, as adopted by Facebook. + * - `mks2021`: Use a Magic Kernel Sharp 2021 kernel, with more accurate (reduced) sharpening than the 2013 version. + * + * When upsampling, these kernels map to `nearest`, `linear` and `cubic` interpolators. + * Downsampling kernels without a matching upsampling interpolator map to `cubic`. + * + * Only one resize can occur per pipeline. + * Previous calls to `resize` in the same pipeline will be ignored. + * + * @example + * sharp(input) + * .resize({ width: 100 }) + * .toBuffer() + * .then(data => { + * // 100 pixels wide, auto-scaled height + * }); + * + * @example + * sharp(input) + * .resize({ height: 100 }) + * .toBuffer() + * .then(data => { + * // 100 pixels high, auto-scaled width + * }); + * + * @example + * sharp(input) + * .resize(200, 300, { + * kernel: sharp.kernel.nearest, + * fit: 'contain', + * position: 'right top', + * background: { r: 255, g: 255, b: 255, alpha: 0.5 } + * }) + * .toFile('output.png') + * .then(() => { + * // output.png is a 200 pixels wide and 300 pixels high image + * // containing a nearest-neighbour scaled version + * // contained within the north-east corner of a semi-transparent white canvas + * }); + * + * @example + * const transformer = sharp() + * .resize({ + * width: 200, + * height: 200, + * fit: sharp.fit.cover, + * position: sharp.strategy.entropy + * }); + * // Read image data from readableStream + * // Write 200px square auto-cropped image data to writableStream + * readableStream + * .pipe(transformer) + * .pipe(writableStream); + * + * @example + * sharp(input) + * .resize(200, 200, { + * fit: sharp.fit.inside, + * withoutEnlargement: true + * }) + * .toFormat('jpeg') + * .toBuffer() + * .then(function(outputBuffer) { + * // outputBuffer contains JPEG image data + * // no wider and no higher than 200 pixels + * // and no larger than the input image + * }); + * + * @example + * sharp(input) + * .resize(200, 200, { + * fit: sharp.fit.outside, + * withoutReduction: true + * }) + * .toFormat('jpeg') + * .toBuffer() + * .then(function(outputBuffer) { + * // outputBuffer contains JPEG image data + * // of at least 200 pixels wide and 200 pixels high while maintaining aspect ratio + * // and no smaller than the input image + * }); + * + * @example + * const scaleByHalf = await sharp(input) + * .metadata() + * .then(({ width }) => sharp(input) + * .resize(Math.round(width * 0.5)) + * .toBuffer() + * ); + * + * @param {number} [width] - How many pixels wide the resultant image should be. Use `null` or `undefined` to auto-scale the width to match the height. + * @param {number} [height] - How many pixels high the resultant image should be. Use `null` or `undefined` to auto-scale the height to match the width. + * @param {Object} [options] + * @param {number} [options.width] - An alternative means of specifying `width`. If both are present this takes priority. + * @param {number} [options.height] - An alternative means of specifying `height`. If both are present this takes priority. + * @param {String} [options.fit='cover'] - How the image should be resized/cropped to fit the target dimension(s), one of `cover`, `contain`, `fill`, `inside` or `outside`. + * @param {String} [options.position='centre'] - A position, gravity or strategy to use when `fit` is `cover` or `contain`. + * @param {String|Object} [options.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour when `fit` is `contain`, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency. + * @param {String} [options.kernel='lanczos3'] - The kernel to use for image reduction and the inferred interpolator to use for upsampling. Use the `fastShrinkOnLoad` option to control kernel vs shrink-on-load. + * @param {Boolean} [options.withoutEnlargement=false] - Do not scale up if the width *or* height are already less than the target dimensions, equivalent to GraphicsMagick's `>` geometry option. This may result in output dimensions smaller than the target dimensions. + * @param {Boolean} [options.withoutReduction=false] - Do not scale down if the width *or* height are already greater than the target dimensions, equivalent to GraphicsMagick's `<` geometry option. This may still result in a crop to reach the target dimensions. + * @param {Boolean} [options.fastShrinkOnLoad=true] - Take greater advantage of the JPEG and WebP shrink-on-load feature, which can lead to a slight moiré pattern or round-down of an auto-scaled dimension. + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function resize (widthOrOptions, height, options) { + if (isResizeExpected(this.options)) { + this.options.debuglog('ignoring previous resize options'); + } + if (this.options.widthPost !== -1) { + this.options.debuglog('operation order will be: extract, resize, extract'); + } + if (is.defined(widthOrOptions)) { + if (is.object(widthOrOptions) && !is.defined(options)) { + options = widthOrOptions; + } else if (is.integer(widthOrOptions) && widthOrOptions > 0) { + this.options.width = widthOrOptions; + } else { + throw is.invalidParameterError('width', 'positive integer', widthOrOptions); + } + } else { + this.options.width = -1; + } + if (is.defined(height)) { + if (is.integer(height) && height > 0) { + this.options.height = height; + } else { + throw is.invalidParameterError('height', 'positive integer', height); + } + } else { + this.options.height = -1; + } + if (is.object(options)) { + // Width + if (is.defined(options.width)) { + if (is.integer(options.width) && options.width > 0) { + this.options.width = options.width; + } else { + throw is.invalidParameterError('width', 'positive integer', options.width); + } + } + // Height + if (is.defined(options.height)) { + if (is.integer(options.height) && options.height > 0) { + this.options.height = options.height; + } else { + throw is.invalidParameterError('height', 'positive integer', options.height); + } + } + // Fit + if (is.defined(options.fit)) { + const canvas = mapFitToCanvas[options.fit]; + if (is.string(canvas)) { + this.options.canvas = canvas; + } else { + throw is.invalidParameterError('fit', 'valid fit', options.fit); + } + } + // Position + if (is.defined(options.position)) { + const pos = is.integer(options.position) + ? options.position + : strategy[options.position] || position[options.position] || gravity[options.position]; + if (is.integer(pos) && (is.inRange(pos, 0, 8) || is.inRange(pos, 16, 17))) { + this.options.position = pos; + } else { + throw is.invalidParameterError('position', 'valid position/gravity/strategy', options.position); + } + } + // Background + this._setBackgroundColourOption('resizeBackground', options.background); + // Kernel + if (is.defined(options.kernel)) { + if (is.string(kernel[options.kernel])) { + this.options.kernel = kernel[options.kernel]; + } else { + throw is.invalidParameterError('kernel', 'valid kernel name', options.kernel); + } + } + // Without enlargement + if (is.defined(options.withoutEnlargement)) { + this._setBooleanOption('withoutEnlargement', options.withoutEnlargement); + } + // Without reduction + if (is.defined(options.withoutReduction)) { + this._setBooleanOption('withoutReduction', options.withoutReduction); + } + // Shrink on load + if (is.defined(options.fastShrinkOnLoad)) { + this._setBooleanOption('fastShrinkOnLoad', options.fastShrinkOnLoad); + } + } + if (isRotationExpected(this.options) && isResizeExpected(this.options)) { + this.options.rotateBefore = true; + } + return this; +} + +/** + * Extend / pad / extrude one or more edges of the image with either + * the provided background colour or pixels derived from the image. + * This operation will always occur after resizing and extraction, if any. + * + * @example + * // Resize to 140 pixels wide, then add 10 transparent pixels + * // to the top, left and right edges and 20 to the bottom edge + * sharp(input) + * .resize(140) + * .extend({ + * top: 10, + * bottom: 20, + * left: 10, + * right: 10, + * background: { r: 0, g: 0, b: 0, alpha: 0 } + * }) + * ... + * +* @example + * // Add a row of 10 red pixels to the bottom + * sharp(input) + * .extend({ + * bottom: 10, + * background: 'red' + * }) + * ... + * + * @example + * // Extrude image by 8 pixels to the right, mirroring existing right hand edge + * sharp(input) + * .extend({ + * right: 8, + * background: 'mirror' + * }) + * ... + * + * @param {(number|Object)} extend - single pixel count to add to all edges or an Object with per-edge counts + * @param {number} [extend.top=0] + * @param {number} [extend.left=0] + * @param {number} [extend.bottom=0] + * @param {number} [extend.right=0] + * @param {String} [extend.extendWith='background'] - populate new pixels using this method, one of: background, copy, repeat, mirror. + * @param {String|Object} [extend.background={r: 0, g: 0, b: 0, alpha: 1}] - background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to black without transparency. + * @returns {Sharp} + * @throws {Error} Invalid parameters +*/ +function extend (extend) { + if (is.integer(extend) && extend > 0) { + this.options.extendTop = extend; + this.options.extendBottom = extend; + this.options.extendLeft = extend; + this.options.extendRight = extend; + } else if (is.object(extend)) { + if (is.defined(extend.top)) { + if (is.integer(extend.top) && extend.top >= 0) { + this.options.extendTop = extend.top; + } else { + throw is.invalidParameterError('top', 'positive integer', extend.top); + } + } + if (is.defined(extend.bottom)) { + if (is.integer(extend.bottom) && extend.bottom >= 0) { + this.options.extendBottom = extend.bottom; + } else { + throw is.invalidParameterError('bottom', 'positive integer', extend.bottom); + } + } + if (is.defined(extend.left)) { + if (is.integer(extend.left) && extend.left >= 0) { + this.options.extendLeft = extend.left; + } else { + throw is.invalidParameterError('left', 'positive integer', extend.left); + } + } + if (is.defined(extend.right)) { + if (is.integer(extend.right) && extend.right >= 0) { + this.options.extendRight = extend.right; + } else { + throw is.invalidParameterError('right', 'positive integer', extend.right); + } + } + this._setBackgroundColourOption('extendBackground', extend.background); + if (is.defined(extend.extendWith)) { + if (is.string(extendWith[extend.extendWith])) { + this.options.extendWith = extendWith[extend.extendWith]; + } else { + throw is.invalidParameterError('extendWith', 'one of: background, copy, repeat, mirror', extend.extendWith); + } + } + } else { + throw is.invalidParameterError('extend', 'integer or object', extend); + } + return this; +} + +/** + * Extract/crop a region of the image. + * + * - Use `extract` before `resize` for pre-resize extraction. + * - Use `extract` after `resize` for post-resize extraction. + * - Use `extract` twice and `resize` once for extract-then-resize-then-extract in a fixed operation order. + * + * @example + * sharp(input) + * .extract({ left: left, top: top, width: width, height: height }) + * .toFile(output, function(err) { + * // Extract a region of the input image, saving in the same format. + * }); + * @example + * sharp(input) + * .extract({ left: leftOffsetPre, top: topOffsetPre, width: widthPre, height: heightPre }) + * .resize(width, height) + * .extract({ left: leftOffsetPost, top: topOffsetPost, width: widthPost, height: heightPost }) + * .toFile(output, function(err) { + * // Extract a region, resize, then extract from the resized image + * }); + * + * @param {Object} options - describes the region to extract using integral pixel values + * @param {number} options.left - zero-indexed offset from left edge + * @param {number} options.top - zero-indexed offset from top edge + * @param {number} options.width - width of region to extract + * @param {number} options.height - height of region to extract + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function extract (options) { + const suffix = isResizeExpected(this.options) || this.options.widthPre !== -1 ? 'Post' : 'Pre'; + if (this.options[`width${suffix}`] !== -1) { + this.options.debuglog('ignoring previous extract options'); + } + ['left', 'top', 'width', 'height'].forEach(function (name) { + const value = options[name]; + if (is.integer(value) && value >= 0) { + this.options[name + (name === 'left' || name === 'top' ? 'Offset' : '') + suffix] = value; + } else { + throw is.invalidParameterError(name, 'integer', value); + } + }, this); + // Ensure existing rotation occurs before pre-resize extraction + if (isRotationExpected(this.options) && !isResizeExpected(this.options)) { + if (this.options.widthPre === -1 || this.options.widthPost === -1) { + this.options.rotateBefore = true; + } + } + if (this.options.input.autoOrient) { + this.options.orientBefore = true; + } + return this; +} + +/** + * Trim pixels from all edges that contain values similar to the given background colour, which defaults to that of the top-left pixel. + * + * Images with an alpha channel will use the combined bounding box of alpha and non-alpha channels. + * + * If the result of this operation would trim an image to nothing then no change is made. + * + * The `info` response Object will contain `trimOffsetLeft` and `trimOffsetTop` properties. + * + * @example + * // Trim pixels with a colour similar to that of the top-left pixel. + * await sharp(input) + * .trim() + * .toFile(output); + * + * @example + * // Trim pixels with the exact same colour as that of the top-left pixel. + * await sharp(input) + * .trim({ + * threshold: 0 + * }) + * .toFile(output); + * + * @example + * // Assume input is line art and trim only pixels with a similar colour to red. + * const output = await sharp(input) + * .trim({ + * background: "#FF0000", + * lineArt: true + * }) + * .toBuffer(); + * + * @example + * // Trim all "yellow-ish" pixels, being more lenient with the higher threshold. + * const output = await sharp(input) + * .trim({ + * background: "yellow", + * threshold: 42, + * }) + * .toBuffer(); + * + * @param {Object} [options] + * @param {string|Object} [options.background='top-left pixel'] - Background colour, parsed by the [color](https://www.npmjs.org/package/color) module, defaults to that of the top-left pixel. + * @param {number} [options.threshold=10] - Allowed difference from the above colour, a positive number. + * @param {boolean} [options.lineArt=false] - Does the input more closely resemble line art (e.g. vector) rather than being photographic? + * @returns {Sharp} + * @throws {Error} Invalid parameters + */ +function trim (options) { + this.options.trimThreshold = 10; + if (is.defined(options)) { + if (is.object(options)) { + if (is.defined(options.background)) { + this._setBackgroundColourOption('trimBackground', options.background); + } + if (is.defined(options.threshold)) { + if (is.number(options.threshold) && options.threshold >= 0) { + this.options.trimThreshold = options.threshold; + } else { + throw is.invalidParameterError('threshold', 'positive number', options.threshold); + } + } + if (is.defined(options.lineArt)) { + this._setBooleanOption('trimLineArt', options.lineArt); + } + } else { + throw is.invalidParameterError('trim', 'object', options); + } + } + if (isRotationExpected(this.options)) { + this.options.rotateBefore = true; + } + return this; +} + +/** + * Decorate the Sharp prototype with resize-related functions. + * @module Sharp + * @private + */ +module.exports = function (Sharp) { + Object.assign(Sharp.prototype, { + resize, + extend, + extract, + trim + }); + // Class attributes + Sharp.gravity = gravity; + Sharp.strategy = strategy; + Sharp.kernel = kernel; + Sharp.fit = fit; + Sharp.position = position; +}; diff --git a/server/node_modules/sharp/lib/sharp.js b/server/node_modules/sharp/lib/sharp.js new file mode 100644 index 0000000..78853e9 --- /dev/null +++ b/server/node_modules/sharp/lib/sharp.js @@ -0,0 +1,122 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +// Inspects the runtime environment and exports the relevant sharp.node binary + +const { familySync, versionSync } = require('detect-libc'); + +const { runtimePlatformArch, isUnsupportedNodeRuntime, prebuiltPlatforms, minimumLibvipsVersion } = require('./libvips'); +const runtimePlatform = runtimePlatformArch(); + +const paths = [ + `../src/build/Release/sharp-${runtimePlatform}.node`, + '../src/build/Release/sharp-wasm32.node', + `@img/sharp-${runtimePlatform}/sharp.node`, + '@img/sharp-wasm32/sharp.node' +]; + +let path, sharp; +const errors = []; +for (path of paths) { + try { + sharp = require(path); + break; + } catch (err) { + /* istanbul ignore next */ + errors.push(err); + } +} + +/* istanbul ignore next */ +if (sharp && path.startsWith('@img/sharp-linux-x64') && !sharp._isUsingX64V2()) { + const err = new Error('Prebuilt binaries for linux-x64 require v2 microarchitecture'); + err.code = 'Unsupported CPU'; + errors.push(err); + sharp = null; +} + +/* istanbul ignore next */ +if (sharp) { + module.exports = sharp; +} else { + const [isLinux, isMacOs, isWindows] = ['linux', 'darwin', 'win32'].map(os => runtimePlatform.startsWith(os)); + + const help = [`Could not load the "sharp" module using the ${runtimePlatform} runtime`]; + errors.forEach(err => { + if (err.code !== 'MODULE_NOT_FOUND') { + help.push(`${err.code}: ${err.message}`); + } + }); + const messages = errors.map(err => err.message).join(' '); + help.push('Possible solutions:'); + // Common error messages + if (isUnsupportedNodeRuntime()) { + const { found, expected } = isUnsupportedNodeRuntime(); + help.push( + '- Please upgrade Node.js:', + ` Found ${found}`, + ` Requires ${expected}` + ); + } else if (prebuiltPlatforms.includes(runtimePlatform)) { + const [os, cpu] = runtimePlatform.split('-'); + const libc = os.endsWith('musl') ? ' --libc=musl' : ''; + help.push( + '- Ensure optional dependencies can be installed:', + ' npm install --include=optional sharp', + '- Ensure your package manager supports multi-platform installation:', + ' See https://sharp.pixelplumbing.com/install#cross-platform', + '- Add platform-specific dependencies:', + ` npm install --os=${os.replace('musl', '')}${libc} --cpu=${cpu} sharp` + ); + } else { + help.push( + `- Manually install libvips >= ${minimumLibvipsVersion}`, + '- Add experimental WebAssembly-based dependencies:', + ' npm install --cpu=wasm32 sharp', + ' npm install @img/sharp-wasm32' + ); + } + if (isLinux && /(symbol not found|CXXABI_)/i.test(messages)) { + try { + const { config } = require(`@img/sharp-libvips-${runtimePlatform}/package`); + const libcFound = `${familySync()} ${versionSync()}`; + const libcRequires = `${config.musl ? 'musl' : 'glibc'} ${config.musl || config.glibc}`; + help.push( + '- Update your OS:', + ` Found ${libcFound}`, + ` Requires ${libcRequires}` + ); + } catch (errEngines) {} + } + if (isLinux && /\/snap\/core[0-9]{2}/.test(messages)) { + help.push( + '- Remove the Node.js Snap, which does not support native modules', + ' snap remove node' + ); + } + if (isMacOs && /Incompatible library version/.test(messages)) { + help.push( + '- Update Homebrew:', + ' brew update && brew upgrade vips' + ); + } + if (errors.some(err => err.code === 'ERR_DLOPEN_DISABLED')) { + help.push('- Run Node.js without using the --no-addons flag'); + } + // Link to installation docs + if (isWindows && /The specified procedure could not be found/.test(messages)) { + help.push( + '- Using the canvas package on Windows?', + ' See https://sharp.pixelplumbing.com/install#canvas-and-windows', + '- Check for outdated versions of sharp in the dependency tree:', + ' npm ls sharp' + ); + } + help.push( + '- Consult the installation documentation:', + ' See https://sharp.pixelplumbing.com/install' + ); + throw new Error(help.join('\n')); +} diff --git a/server/node_modules/sharp/lib/utility.js b/server/node_modules/sharp/lib/utility.js new file mode 100644 index 0000000..4b11892 --- /dev/null +++ b/server/node_modules/sharp/lib/utility.js @@ -0,0 +1,291 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const events = require('node:events'); +const detectLibc = require('detect-libc'); + +const is = require('./is'); +const { runtimePlatformArch } = require('./libvips'); +const sharp = require('./sharp'); + +const runtimePlatform = runtimePlatformArch(); +const libvipsVersion = sharp.libvipsVersion(); + +/** + * An Object containing nested boolean values representing the available input and output formats/methods. + * @member + * @example + * console.log(sharp.format); + * @returns {Object} + */ +const format = sharp.format(); +format.heif.output.alias = ['avif', 'heic']; +format.jpeg.output.alias = ['jpe', 'jpg']; +format.tiff.output.alias = ['tif']; +format.jp2k.output.alias = ['j2c', 'j2k', 'jp2', 'jpx']; + +/** + * An Object containing the available interpolators and their proper values + * @readonly + * @enum {string} + */ +const interpolators = { + /** [Nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). Suitable for image enlargement only. */ + nearest: 'nearest', + /** [Bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation). Faster than bicubic but with less smooth results. */ + bilinear: 'bilinear', + /** [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) (the default). */ + bicubic: 'bicubic', + /** [LBB interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100). Prevents some "[acutance](http://en.wikipedia.org/wiki/Acutance)" but typically reduces performance by a factor of 2. */ + locallyBoundedBicubic: 'lbb', + /** [Nohalo interpolation](http://eprints.soton.ac.uk/268086/). Prevents acutance but typically reduces performance by a factor of 3. */ + nohalo: 'nohalo', + /** [VSQBS interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents "staircasing" when enlarging. */ + vertexSplitQuadraticBasisSpline: 'vsqbs' +}; + +/** + * An Object containing the version numbers of sharp, libvips + * and (when using prebuilt binaries) its dependencies. + * + * @member + * @example + * console.log(sharp.versions); + */ +let versions = { + vips: libvipsVersion.semver +}; +/* istanbul ignore next */ +if (!libvipsVersion.isGlobal) { + if (!libvipsVersion.isWasm) { + try { + versions = require(`@img/sharp-${runtimePlatform}/versions`); + } catch (_) { + try { + versions = require(`@img/sharp-libvips-${runtimePlatform}/versions`); + } catch (_) {} + } + } else { + try { + versions = require('@img/sharp-wasm32/versions'); + } catch (_) {} + } +} +versions.sharp = require('../package.json').version; + +/* istanbul ignore next */ +if (versions.heif && format.heif) { + // Prebuilt binaries provide AV1 + format.heif.input.fileSuffix = ['.avif']; + format.heif.output.alias = ['avif']; +} + +/** + * Gets or, when options are provided, sets the limits of _libvips'_ operation cache. + * Existing entries in the cache will be trimmed after any change in limits. + * This method always returns cache statistics, + * useful for determining how much working memory is required for a particular task. + * + * @example + * const stats = sharp.cache(); + * @example + * sharp.cache( { items: 200 } ); + * sharp.cache( { files: 0 } ); + * sharp.cache(false); + * + * @param {Object|boolean} [options=true] - Object with the following attributes, or boolean where true uses default cache settings and false removes all caching + * @param {number} [options.memory=50] - is the maximum memory in MB to use for this cache + * @param {number} [options.files=20] - is the maximum number of files to hold open + * @param {number} [options.items=100] - is the maximum number of operations to cache + * @returns {Object} + */ +function cache (options) { + if (is.bool(options)) { + if (options) { + // Default cache settings of 50MB, 20 files, 100 items + return sharp.cache(50, 20, 100); + } else { + return sharp.cache(0, 0, 0); + } + } else if (is.object(options)) { + return sharp.cache(options.memory, options.files, options.items); + } else { + return sharp.cache(); + } +} +cache(true); + +/** + * Gets or, when a concurrency is provided, sets + * the maximum number of threads _libvips_ should use to process _each image_. + * These are from a thread pool managed by glib, + * which helps avoid the overhead of creating new threads. + * + * This method always returns the current concurrency. + * + * The default value is the number of CPU cores, + * except when using glibc-based Linux without jemalloc, + * where the default is `1` to help reduce memory fragmentation. + * + * A value of `0` will reset this to the number of CPU cores. + * + * Some image format libraries spawn additional threads, + * e.g. libaom manages its own 4 threads when encoding AVIF images, + * and these are independent of the value set here. + * + * :::note + * Further {@link /performance|control over performance} is available. + * ::: + * + * @example + * const threads = sharp.concurrency(); // 4 + * sharp.concurrency(2); // 2 + * sharp.concurrency(0); // 4 + * + * @param {number} [concurrency] + * @returns {number} concurrency + */ +function concurrency (concurrency) { + return sharp.concurrency(is.integer(concurrency) ? concurrency : null); +} +/* istanbul ignore next */ +if (detectLibc.familySync() === detectLibc.GLIBC && !sharp._isUsingJemalloc()) { + // Reduce default concurrency to 1 when using glibc memory allocator + sharp.concurrency(1); +} else if (detectLibc.familySync() === detectLibc.MUSL && sharp.concurrency() === 1024) { + // Reduce default concurrency when musl thread over-subscription detected + sharp.concurrency(require('node:os').availableParallelism()); +} + +/** + * An EventEmitter that emits a `change` event when a task is either: + * - queued, waiting for _libuv_ to provide a worker thread + * - complete + * @member + * @example + * sharp.queue.on('change', function(queueLength) { + * console.log('Queue contains ' + queueLength + ' task(s)'); + * }); + */ +const queue = new events.EventEmitter(); + +/** + * Provides access to internal task counters. + * - queue is the number of tasks this module has queued waiting for _libuv_ to provide a worker thread from its pool. + * - process is the number of resize tasks currently being processed. + * + * @example + * const counters = sharp.counters(); // { queue: 2, process: 4 } + * + * @returns {Object} + */ +function counters () { + return sharp.counters(); +} + +/** + * Get and set use of SIMD vector unit instructions. + * Requires libvips to have been compiled with highway support. + * + * Improves the performance of `resize`, `blur` and `sharpen` operations + * by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON. + * + * @example + * const simd = sharp.simd(); + * // simd is `true` if the runtime use of highway is currently enabled + * @example + * const simd = sharp.simd(false); + * // prevent libvips from using highway at runtime + * + * @param {boolean} [simd=true] + * @returns {boolean} + */ +function simd (simd) { + return sharp.simd(is.bool(simd) ? simd : null); +} + +/** + * Block libvips operations at runtime. + * + * This is in addition to the `VIPS_BLOCK_UNTRUSTED` environment variable, + * which when set will block all "untrusted" operations. + * + * @since 0.32.4 + * + * @example Block all TIFF input. + * sharp.block({ + * operation: ['VipsForeignLoadTiff'] + * }); + * + * @param {Object} options + * @param {Array} options.operation - List of libvips low-level operation names to block. + */ +function block (options) { + if (is.object(options)) { + if (Array.isArray(options.operation) && options.operation.every(is.string)) { + sharp.block(options.operation, true); + } else { + throw is.invalidParameterError('operation', 'Array', options.operation); + } + } else { + throw is.invalidParameterError('options', 'object', options); + } +} + +/** + * Unblock libvips operations at runtime. + * + * This is useful for defining a list of allowed operations. + * + * @since 0.32.4 + * + * @example Block all input except WebP from the filesystem. + * sharp.block({ + * operation: ['VipsForeignLoad'] + * }); + * sharp.unblock({ + * operation: ['VipsForeignLoadWebpFile'] + * }); + * + * @example Block all input except JPEG and PNG from a Buffer or Stream. + * sharp.block({ + * operation: ['VipsForeignLoad'] + * }); + * sharp.unblock({ + * operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer'] + * }); + * + * @param {Object} options + * @param {Array} options.operation - List of libvips low-level operation names to unblock. + */ +function unblock (options) { + if (is.object(options)) { + if (Array.isArray(options.operation) && options.operation.every(is.string)) { + sharp.block(options.operation, false); + } else { + throw is.invalidParameterError('operation', 'Array', options.operation); + } + } else { + throw is.invalidParameterError('options', 'object', options); + } +} + +/** + * Decorate the Sharp class with utility-related functions. + * @module Sharp + * @private + */ +module.exports = function (Sharp) { + Sharp.cache = cache; + Sharp.concurrency = concurrency; + Sharp.counters = counters; + Sharp.simd = simd; + Sharp.format = format; + Sharp.interpolators = interpolators; + Sharp.versions = versions; + Sharp.queue = queue; + Sharp.block = block; + Sharp.unblock = unblock; +}; diff --git a/server/node_modules/sharp/package.json b/server/node_modules/sharp/package.json new file mode 100644 index 0000000..39547c8 --- /dev/null +++ b/server/node_modules/sharp/package.json @@ -0,0 +1,220 @@ +{ + "name": "sharp", + "description": "High performance Node.js image processing, the fastest module to resize JPEG, PNG, WebP, GIF, AVIF and TIFF images", + "version": "0.34.4", + "author": "Lovell Fuller ", + "homepage": "https://sharp.pixelplumbing.com", + "contributors": [ + "Pierre Inglebert ", + "Jonathan Ong ", + "Chanon Sajjamanochai ", + "Juliano Julio ", + "Daniel Gasienica ", + "Julian Walker ", + "Amit Pitaru ", + "Brandon Aaron ", + "Andreas Lind ", + "Maurus Cuelenaere ", + "Linus Unnebäck ", + "Victor Mateevitsi ", + "Alaric Holloway ", + "Bernhard K. Weisshuhn ", + "Chris Riley ", + "David Carley ", + "John Tobin ", + "Kenton Gray ", + "Felix Bünemann ", + "Samy Al Zahrani ", + "Chintan Thakkar ", + "F. Orlando Galashan ", + "Kleis Auke Wolthuizen ", + "Matt Hirsch ", + "Matthias Thoemmes ", + "Patrick Paskaris ", + "Jérémy Lal ", + "Rahul Nanwani ", + "Alice Monday ", + "Kristo Jorgenson ", + "YvesBos ", + "Guy Maliar ", + "Nicolas Coden ", + "Matt Parrish ", + "Marcel Bretschneider ", + "Matthew McEachen ", + "Jarda Kotěšovec ", + "Kenric D'Souza ", + "Oleh Aleinyk ", + "Marcel Bretschneider ", + "Andrea Bianco ", + "Rik Heywood ", + "Thomas Parisot ", + "Nathan Graves ", + "Tom Lokhorst ", + "Espen Hovlandsdal ", + "Sylvain Dumont ", + "Alun Davies ", + "Aidan Hoolachan ", + "Axel Eirola ", + "Freezy ", + "Daiz ", + "Julian Aubourg ", + "Keith Belovay ", + "Michael B. Klein ", + "Jordan Prudhomme ", + "Ilya Ovdin ", + "Andargor ", + "Paul Neave ", + "Brendan Kennedy ", + "Brychan Bennett-Odlum ", + "Edward Silverton ", + "Roman Malieiev ", + "Tomas Szabo ", + "Robert O'Rourke ", + "Guillermo Alfonso Varela Chouciño ", + "Christian Flintrup ", + "Manan Jadhav ", + "Leon Radley ", + "alza54 ", + "Jacob Smith ", + "Michael Nutt ", + "Brad Parham ", + "Taneli Vatanen ", + "Joris Dugué ", + "Chris Banks ", + "Ompal Singh ", + "Brodan ", + "Ankur Parihar ", + "Brahim Ait elhaj ", + "Mart Jansink ", + "Lachlan Newman ", + "Dennis Beatty ", + "Ingvar Stepanyan ", + "Don Denton " + ], + "scripts": { + "install": "node install/check.js", + "clean": "rm -rf src/build/ .nyc_output/ coverage/ test/fixtures/output.*", + "test": "npm run test-lint && npm run test-unit && npm run test-licensing && npm run test-types", + "test-lint": "semistandard && cpplint", + "test-unit": "nyc --reporter=lcov --reporter=text --check-coverage --branches=100 mocha", + "test-licensing": "license-checker --production --summary --onlyAllow=\"Apache-2.0;BSD;ISC;LGPL-3.0-or-later;MIT\"", + "test-leak": "./test/leak/leak.sh", + "test-types": "tsd", + "package-from-local-build": "node npm/from-local-build.js", + "package-release-notes": "node npm/release-notes.js", + "docs-build": "node docs/build.mjs", + "docs-serve": "cd docs && npm start", + "docs-publish": "cd docs && npm run build && npx firebase-tools deploy --project pixelplumbing --only hosting:pixelplumbing-sharp" + }, + "type": "commonjs", + "main": "lib/index.js", + "types": "lib/index.d.ts", + "files": [ + "install", + "lib", + "src/*.{cc,h,gyp}" + ], + "repository": { + "type": "git", + "url": "git://github.com/lovell/sharp.git" + }, + "keywords": [ + "jpeg", + "png", + "webp", + "avif", + "tiff", + "gif", + "svg", + "jp2", + "dzi", + "image", + "resize", + "thumbnail", + "crop", + "embed", + "libvips", + "vips" + ], + "dependencies": { + "@img/colour": "^1.0.0", + "detect-libc": "^2.1.0", + "semver": "^7.7.2" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.34.4", + "@img/sharp-darwin-x64": "0.34.4", + "@img/sharp-libvips-darwin-arm64": "1.2.3", + "@img/sharp-libvips-darwin-x64": "1.2.3", + "@img/sharp-libvips-linux-arm": "1.2.3", + "@img/sharp-libvips-linux-arm64": "1.2.3", + "@img/sharp-libvips-linux-ppc64": "1.2.3", + "@img/sharp-libvips-linux-s390x": "1.2.3", + "@img/sharp-libvips-linux-x64": "1.2.3", + "@img/sharp-libvips-linuxmusl-arm64": "1.2.3", + "@img/sharp-libvips-linuxmusl-x64": "1.2.3", + "@img/sharp-linux-arm": "0.34.4", + "@img/sharp-linux-arm64": "0.34.4", + "@img/sharp-linux-ppc64": "0.34.4", + "@img/sharp-linux-s390x": "0.34.4", + "@img/sharp-linux-x64": "0.34.4", + "@img/sharp-linuxmusl-arm64": "0.34.4", + "@img/sharp-linuxmusl-x64": "0.34.4", + "@img/sharp-wasm32": "0.34.4", + "@img/sharp-win32-arm64": "0.34.4", + "@img/sharp-win32-ia32": "0.34.4", + "@img/sharp-win32-x64": "0.34.4" + }, + "devDependencies": { + "@emnapi/runtime": "^1.5.0", + "@img/sharp-libvips-dev": "1.2.3", + "@img/sharp-libvips-dev-wasm32": "1.2.3", + "@img/sharp-libvips-win32-arm64": "1.2.3", + "@img/sharp-libvips-win32-ia32": "1.2.3", + "@img/sharp-libvips-win32-x64": "1.2.3", + "@types/node": "*", + "cc": "^3.0.1", + "emnapi": "^1.5.0", + "exif-reader": "^2.0.2", + "extract-zip": "^2.0.1", + "icc": "^3.0.0", + "jsdoc-to-markdown": "^9.1.2", + "license-checker": "^25.0.1", + "mocha": "^11.7.2", + "node-addon-api": "^8.5.0", + "node-gyp": "^11.4.2", + "nyc": "^17.1.0", + "semistandard": "^17.0.0", + "tar-fs": "^3.1.1", + "tsd": "^0.33.0" + }, + "license": "Apache-2.0", + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "config": { + "libvips": ">=8.17.2" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "semistandard": { + "env": [ + "mocha" + ] + }, + "cc": { + "linelength": "120", + "filter": [ + "build/include" + ] + }, + "nyc": { + "include": [ + "lib" + ] + }, + "tsd": { + "directory": "test/types/" + } +} diff --git a/server/node_modules/sharp/src/binding.gyp b/server/node_modules/sharp/src/binding.gyp new file mode 100644 index 0000000..c4ec70c --- /dev/null +++ b/server/node_modules/sharp/src/binding.gyp @@ -0,0 +1,298 @@ +# Copyright 2013 Lovell Fuller and others. +# SPDX-License-Identifier: Apache-2.0 + +{ + 'variables': { + 'vips_version': ' +#include +#include +#include +#include +#include +#include // NOLINT(build/c++11) + +#include +#include + +#include "common.h" + +using vips::VImage; + +namespace sharp { + + // Convenience methods to access the attributes of a Napi::Object + bool HasAttr(Napi::Object obj, std::string attr) { + return obj.Has(attr); + } + std::string AttrAsStr(Napi::Object obj, std::string attr) { + return obj.Get(attr).As(); + } + std::string AttrAsStr(Napi::Object obj, unsigned int const attr) { + return obj.Get(attr).As(); + } + uint32_t AttrAsUint32(Napi::Object obj, std::string attr) { + return obj.Get(attr).As().Uint32Value(); + } + int32_t AttrAsInt32(Napi::Object obj, std::string attr) { + return obj.Get(attr).As().Int32Value(); + } + int32_t AttrAsInt32(Napi::Object obj, unsigned int const attr) { + return obj.Get(attr).As().Int32Value(); + } + int64_t AttrAsInt64(Napi::Object obj, std::string attr) { + return obj.Get(attr).As().Int64Value(); + } + double AttrAsDouble(Napi::Object obj, std::string attr) { + return obj.Get(attr).As().DoubleValue(); + } + double AttrAsDouble(Napi::Object obj, unsigned int const attr) { + return obj.Get(attr).As().DoubleValue(); + } + bool AttrAsBool(Napi::Object obj, std::string attr) { + return obj.Get(attr).As().Value(); + } + std::vector AttrAsVectorOfDouble(Napi::Object obj, std::string attr) { + Napi::Array napiArray = obj.Get(attr).As(); + std::vector vectorOfDouble(napiArray.Length()); + for (unsigned int i = 0; i < napiArray.Length(); i++) { + vectorOfDouble[i] = AttrAsDouble(napiArray, i); + } + return vectorOfDouble; + } + std::vector AttrAsInt32Vector(Napi::Object obj, std::string attr) { + Napi::Array array = obj.Get(attr).As(); + std::vector vector(array.Length()); + for (unsigned int i = 0; i < array.Length(); i++) { + vector[i] = AttrAsInt32(array, i); + } + return vector; + } + + // Create an InputDescriptor instance from a Napi::Object describing an input image + InputDescriptor* CreateInputDescriptor(Napi::Object input) { + InputDescriptor *descriptor = new InputDescriptor; + if (HasAttr(input, "file")) { + descriptor->file = AttrAsStr(input, "file"); + } else if (HasAttr(input, "buffer")) { + Napi::Buffer buffer = input.Get("buffer").As>(); + descriptor->bufferLength = buffer.Length(); + descriptor->buffer = buffer.Data(); + descriptor->isBuffer = true; + } + descriptor->failOn = AttrAsEnum(input, "failOn", VIPS_TYPE_FAIL_ON); + // Density for vector-based input + if (HasAttr(input, "density")) { + descriptor->density = AttrAsDouble(input, "density"); + } + // Should we ignore any embedded ICC profile + if (HasAttr(input, "ignoreIcc")) { + descriptor->ignoreIcc = AttrAsBool(input, "ignoreIcc"); + } + // Raw pixel input + if (HasAttr(input, "rawChannels")) { + descriptor->rawDepth = AttrAsEnum(input, "rawDepth", VIPS_TYPE_BAND_FORMAT); + descriptor->rawChannels = AttrAsUint32(input, "rawChannels"); + descriptor->rawWidth = AttrAsUint32(input, "rawWidth"); + descriptor->rawHeight = AttrAsUint32(input, "rawHeight"); + descriptor->rawPremultiplied = AttrAsBool(input, "rawPremultiplied"); + descriptor->rawPageHeight = AttrAsUint32(input, "rawPageHeight"); + } + // Multi-page input (GIF, TIFF, PDF) + if (HasAttr(input, "pages")) { + descriptor->pages = AttrAsInt32(input, "pages"); + } + if (HasAttr(input, "page")) { + descriptor->page = AttrAsUint32(input, "page"); + } + // SVG + if (HasAttr(input, "svgStylesheet")) { + descriptor->svgStylesheet = AttrAsStr(input, "svgStylesheet"); + } + if (HasAttr(input, "svgHighBitdepth")) { + descriptor->svgHighBitdepth = AttrAsBool(input, "svgHighBitdepth"); + } + // Multi-level input (OpenSlide) + if (HasAttr(input, "openSlideLevel")) { + descriptor->openSlideLevel = AttrAsUint32(input, "openSlideLevel"); + } + // subIFD (OME-TIFF) + if (HasAttr(input, "subifd")) { + descriptor->tiffSubifd = AttrAsInt32(input, "tiffSubifd"); + } + // // PDF background color + if (HasAttr(input, "pdfBackground")) { + descriptor->pdfBackground = AttrAsVectorOfDouble(input, "pdfBackground"); + } + // Use JPEG 2000 oneshot mode? + if (HasAttr(input, "jp2Oneshot")) { + descriptor->jp2Oneshot = AttrAsBool(input, "jp2Oneshot"); + } + // Create new image + if (HasAttr(input, "createChannels")) { + descriptor->createChannels = AttrAsUint32(input, "createChannels"); + descriptor->createWidth = AttrAsUint32(input, "createWidth"); + descriptor->createHeight = AttrAsUint32(input, "createHeight"); + descriptor->createPageHeight = AttrAsUint32(input, "createPageHeight"); + if (HasAttr(input, "createNoiseType")) { + descriptor->createNoiseType = AttrAsStr(input, "createNoiseType"); + descriptor->createNoiseMean = AttrAsDouble(input, "createNoiseMean"); + descriptor->createNoiseSigma = AttrAsDouble(input, "createNoiseSigma"); + } else { + descriptor->createBackground = AttrAsVectorOfDouble(input, "createBackground"); + } + } + // Create new image with text + if (HasAttr(input, "textValue")) { + descriptor->textValue = AttrAsStr(input, "textValue"); + if (HasAttr(input, "textFont")) { + descriptor->textFont = AttrAsStr(input, "textFont"); + } + if (HasAttr(input, "textFontfile")) { + descriptor->textFontfile = AttrAsStr(input, "textFontfile"); + } + if (HasAttr(input, "textWidth")) { + descriptor->textWidth = AttrAsUint32(input, "textWidth"); + } + if (HasAttr(input, "textHeight")) { + descriptor->textHeight = AttrAsUint32(input, "textHeight"); + } + if (HasAttr(input, "textAlign")) { + descriptor->textAlign = AttrAsEnum(input, "textAlign", VIPS_TYPE_ALIGN); + } + if (HasAttr(input, "textJustify")) { + descriptor->textJustify = AttrAsBool(input, "textJustify"); + } + if (HasAttr(input, "textDpi")) { + descriptor->textDpi = AttrAsUint32(input, "textDpi"); + } + if (HasAttr(input, "textRgba")) { + descriptor->textRgba = AttrAsBool(input, "textRgba"); + } + if (HasAttr(input, "textSpacing")) { + descriptor->textSpacing = AttrAsUint32(input, "textSpacing"); + } + if (HasAttr(input, "textWrap")) { + descriptor->textWrap = AttrAsEnum(input, "textWrap", VIPS_TYPE_TEXT_WRAP); + } + } + // Join images together + if (HasAttr(input, "joinAnimated")) { + descriptor->joinAnimated = AttrAsBool(input, "joinAnimated"); + } + if (HasAttr(input, "joinAcross")) { + descriptor->joinAcross = AttrAsUint32(input, "joinAcross"); + } + if (HasAttr(input, "joinShim")) { + descriptor->joinShim = AttrAsUint32(input, "joinShim"); + } + if (HasAttr(input, "joinBackground")) { + descriptor->joinBackground = AttrAsVectorOfDouble(input, "joinBackground"); + } + if (HasAttr(input, "joinHalign")) { + descriptor->joinHalign = AttrAsEnum(input, "joinHalign", VIPS_TYPE_ALIGN); + } + if (HasAttr(input, "joinValign")) { + descriptor->joinValign = AttrAsEnum(input, "joinValign", VIPS_TYPE_ALIGN); + } + // Limit input images to a given number of pixels, where pixels = width * height + descriptor->limitInputPixels = static_cast(AttrAsInt64(input, "limitInputPixels")); + if (HasAttr(input, "access")) { + descriptor->access = AttrAsBool(input, "sequentialRead") ? VIPS_ACCESS_SEQUENTIAL : VIPS_ACCESS_RANDOM; + } + // Remove safety features and allow unlimited input + descriptor->unlimited = AttrAsBool(input, "unlimited"); + // Use the EXIF orientation to auto orient the image + descriptor->autoOrient = AttrAsBool(input, "autoOrient"); + return descriptor; + } + + // How many tasks are in the queue? + std::atomic counterQueue{0}; + + // How many tasks are being processed? + std::atomic counterProcess{0}; + + // Filename extension checkers + static bool EndsWith(std::string const &str, std::string const &end) { + return str.length() >= end.length() && 0 == str.compare(str.length() - end.length(), end.length(), end); + } + bool IsJpeg(std::string const &str) { + return EndsWith(str, ".jpg") || EndsWith(str, ".jpeg") || EndsWith(str, ".JPG") || EndsWith(str, ".JPEG"); + } + bool IsPng(std::string const &str) { + return EndsWith(str, ".png") || EndsWith(str, ".PNG"); + } + bool IsWebp(std::string const &str) { + return EndsWith(str, ".webp") || EndsWith(str, ".WEBP"); + } + bool IsGif(std::string const &str) { + return EndsWith(str, ".gif") || EndsWith(str, ".GIF"); + } + bool IsJp2(std::string const &str) { + return EndsWith(str, ".jp2") || EndsWith(str, ".jpx") || EndsWith(str, ".j2k") || EndsWith(str, ".j2c") + || EndsWith(str, ".JP2") || EndsWith(str, ".JPX") || EndsWith(str, ".J2K") || EndsWith(str, ".J2C"); + } + bool IsTiff(std::string const &str) { + return EndsWith(str, ".tif") || EndsWith(str, ".tiff") || EndsWith(str, ".TIF") || EndsWith(str, ".TIFF"); + } + bool IsHeic(std::string const &str) { + return EndsWith(str, ".heic") || EndsWith(str, ".HEIC"); + } + bool IsHeif(std::string const &str) { + return EndsWith(str, ".heif") || EndsWith(str, ".HEIF") || IsHeic(str) || IsAvif(str); + } + bool IsAvif(std::string const &str) { + return EndsWith(str, ".avif") || EndsWith(str, ".AVIF"); + } + bool IsJxl(std::string const &str) { + return EndsWith(str, ".jxl") || EndsWith(str, ".JXL"); + } + bool IsDz(std::string const &str) { + return EndsWith(str, ".dzi") || EndsWith(str, ".DZI"); + } + bool IsDzZip(std::string const &str) { + return EndsWith(str, ".zip") || EndsWith(str, ".ZIP") || EndsWith(str, ".szi") || EndsWith(str, ".SZI"); + } + bool IsV(std::string const &str) { + return EndsWith(str, ".v") || EndsWith(str, ".V") || EndsWith(str, ".vips") || EndsWith(str, ".VIPS"); + } + + /* + Trim space from end of string. + */ + std::string TrimEnd(std::string const &str) { + return str.substr(0, str.find_last_not_of(" \n\r\f") + 1); + } + + /* + Provide a string identifier for the given image type. + */ + std::string ImageTypeId(ImageType const imageType) { + std::string id; + switch (imageType) { + case ImageType::JPEG: id = "jpeg"; break; + case ImageType::PNG: id = "png"; break; + case ImageType::WEBP: id = "webp"; break; + case ImageType::TIFF: id = "tiff"; break; + case ImageType::GIF: id = "gif"; break; + case ImageType::JP2: id = "jp2"; break; + case ImageType::SVG: id = "svg"; break; + case ImageType::HEIF: id = "heif"; break; + case ImageType::PDF: id = "pdf"; break; + case ImageType::MAGICK: id = "magick"; break; + case ImageType::OPENSLIDE: id = "openslide"; break; + case ImageType::PPM: id = "ppm"; break; + case ImageType::FITS: id = "fits"; break; + case ImageType::EXR: id = "exr"; break; + case ImageType::JXL: id = "jxl"; break; + case ImageType::RAD: id = "rad"; break; + case ImageType::DCRAW: id = "dcraw"; break; + case ImageType::VIPS: id = "vips"; break; + case ImageType::RAW: id = "raw"; break; + case ImageType::UNKNOWN: id = "unknown"; break; + case ImageType::MISSING: id = "missing"; break; + } + return id; + } + + /** + * Regenerate this table with something like: + * + * $ vips -l foreign | grep -i load | awk '{ print $2, $1; }' + * + * Plus a bit of editing. + */ + std::map loaderToType = { + { "VipsForeignLoadJpegFile", ImageType::JPEG }, + { "VipsForeignLoadJpegBuffer", ImageType::JPEG }, + { "VipsForeignLoadPngFile", ImageType::PNG }, + { "VipsForeignLoadPngBuffer", ImageType::PNG }, + { "VipsForeignLoadWebpFile", ImageType::WEBP }, + { "VipsForeignLoadWebpBuffer", ImageType::WEBP }, + { "VipsForeignLoadTiffFile", ImageType::TIFF }, + { "VipsForeignLoadTiffBuffer", ImageType::TIFF }, + { "VipsForeignLoadGifFile", ImageType::GIF }, + { "VipsForeignLoadGifBuffer", ImageType::GIF }, + { "VipsForeignLoadNsgifFile", ImageType::GIF }, + { "VipsForeignLoadNsgifBuffer", ImageType::GIF }, + { "VipsForeignLoadJp2kBuffer", ImageType::JP2 }, + { "VipsForeignLoadJp2kFile", ImageType::JP2 }, + { "VipsForeignLoadSvgFile", ImageType::SVG }, + { "VipsForeignLoadSvgBuffer", ImageType::SVG }, + { "VipsForeignLoadHeifFile", ImageType::HEIF }, + { "VipsForeignLoadHeifBuffer", ImageType::HEIF }, + { "VipsForeignLoadPdfFile", ImageType::PDF }, + { "VipsForeignLoadPdfBuffer", ImageType::PDF }, + { "VipsForeignLoadMagickFile", ImageType::MAGICK }, + { "VipsForeignLoadMagickBuffer", ImageType::MAGICK }, + { "VipsForeignLoadMagick7File", ImageType::MAGICK }, + { "VipsForeignLoadMagick7Buffer", ImageType::MAGICK }, + { "VipsForeignLoadOpenslideFile", ImageType::OPENSLIDE }, + { "VipsForeignLoadPpmFile", ImageType::PPM }, + { "VipsForeignLoadFitsFile", ImageType::FITS }, + { "VipsForeignLoadOpenexr", ImageType::EXR }, + { "VipsForeignLoadJxlFile", ImageType::JXL }, + { "VipsForeignLoadJxlBuffer", ImageType::JXL }, + { "VipsForeignLoadRadFile", ImageType::RAD }, + { "VipsForeignLoadRadBuffer", ImageType::RAD }, + { "VipsForeignLoadDcRawFile", ImageType::DCRAW }, + { "VipsForeignLoadDcRawBuffer", ImageType::DCRAW }, + { "VipsForeignLoadVips", ImageType::VIPS }, + { "VipsForeignLoadVipsFile", ImageType::VIPS }, + { "VipsForeignLoadRaw", ImageType::RAW } + }; + + /* + Determine image format of a buffer. + */ + ImageType DetermineImageType(void *buffer, size_t const length) { + ImageType imageType = ImageType::UNKNOWN; + char const *load = vips_foreign_find_load_buffer(buffer, length); + if (load != nullptr) { + auto it = loaderToType.find(load); + if (it != loaderToType.end()) { + imageType = it->second; + } + } + return imageType; + } + + /* + Determine image format, reads the first few bytes of the file + */ + ImageType DetermineImageType(char const *file) { + ImageType imageType = ImageType::UNKNOWN; + char const *load = vips_foreign_find_load(file); + if (load != nullptr) { + auto it = loaderToType.find(load); + if (it != loaderToType.end()) { + imageType = it->second; + } + } else { + if (EndsWith(vips::VError().what(), " does not exist\n")) { + imageType = ImageType::MISSING; + } + } + return imageType; + } + + /* + Does this image type support multiple pages? + */ + bool ImageTypeSupportsPage(ImageType imageType) { + return + imageType == ImageType::WEBP || + imageType == ImageType::MAGICK || + imageType == ImageType::GIF || + imageType == ImageType::JP2 || + imageType == ImageType::TIFF || + imageType == ImageType::HEIF || + imageType == ImageType::PDF; + } + + /* + Does this image type support removal of safety limits? + */ + bool ImageTypeSupportsUnlimited(ImageType imageType) { + return + imageType == ImageType::JPEG || + imageType == ImageType::PNG || + imageType == ImageType::SVG || + imageType == ImageType::TIFF || + imageType == ImageType::HEIF; + } + + /* + Format-specific options builder + */ + vips::VOption* GetOptionsForImageType(ImageType imageType, InputDescriptor *descriptor) { + vips::VOption *option = VImage::option() + ->set("access", descriptor->access) + ->set("fail_on", descriptor->failOn); + if (descriptor->unlimited && ImageTypeSupportsUnlimited(imageType)) { + option->set("unlimited", true); + } + if (ImageTypeSupportsPage(imageType)) { + option->set("n", descriptor->pages); + option->set("page", descriptor->page); + } + switch (imageType) { + case ImageType::SVG: + option->set("dpi", descriptor->density) + ->set("stylesheet", descriptor->svgStylesheet.data()) + ->set("high_bitdepth", descriptor->svgHighBitdepth); + break; + case ImageType::TIFF: + option->set("subifd", descriptor->tiffSubifd); + break; + case ImageType::PDF: + option->set("dpi", descriptor->density) + ->set("background", descriptor->pdfBackground); + break; + case ImageType::OPENSLIDE: + option->set("level", descriptor->openSlideLevel); + break; + case ImageType::JP2: + option->set("oneshot", descriptor->jp2Oneshot); + break; + case ImageType::MAGICK: + option->set("density", std::to_string(descriptor->density).data()); + break; + default: + break; + } + return option; + } + + /* + Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data) + */ + std::tuple OpenInput(InputDescriptor *descriptor) { + VImage image; + ImageType imageType; + if (descriptor->isBuffer) { + if (descriptor->rawChannels > 0) { + // Raw, uncompressed pixel data + bool const is8bit = vips_band_format_is8bit(descriptor->rawDepth); + image = VImage::new_from_memory(descriptor->buffer, descriptor->bufferLength, + descriptor->rawWidth, descriptor->rawHeight, descriptor->rawChannels, descriptor->rawDepth); + if (descriptor->rawChannels < 3) { + image.get_image()->Type = is8bit ? VIPS_INTERPRETATION_B_W : VIPS_INTERPRETATION_GREY16; + } else { + image.get_image()->Type = is8bit ? VIPS_INTERPRETATION_sRGB : VIPS_INTERPRETATION_RGB16; + } + if (descriptor->rawPageHeight > 0) { + image.set(VIPS_META_PAGE_HEIGHT, descriptor->rawPageHeight); + image.set(VIPS_META_N_PAGES, static_cast(descriptor->rawHeight / descriptor->rawPageHeight)); + } + if (descriptor->rawPremultiplied) { + image = image.unpremultiply(); + } + imageType = ImageType::RAW; + } else { + // Compressed data + imageType = DetermineImageType(descriptor->buffer, descriptor->bufferLength); + if (imageType != ImageType::UNKNOWN) { + try { + vips::VOption *option = GetOptionsForImageType(imageType, descriptor); + image = VImage::new_from_buffer(descriptor->buffer, descriptor->bufferLength, nullptr, option); + if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) { + image = SetDensity(image, descriptor->density); + } + } catch (vips::VError const &err) { + throw vips::VError(std::string("Input buffer has corrupt header: ") + err.what()); + } + } else { + throw vips::VError("Input buffer contains unsupported image format"); + } + } + } else { + int const channels = descriptor->createChannels; + if (channels > 0) { + // Create new image + if (descriptor->createNoiseType == "gaussian") { + std::vector bands = {}; + bands.reserve(channels); + for (int _band = 0; _band < channels; _band++) { + bands.push_back(VImage::gaussnoise(descriptor->createWidth, descriptor->createHeight, VImage::option() + ->set("mean", descriptor->createNoiseMean) + ->set("sigma", descriptor->createNoiseSigma))); + } + image = VImage::bandjoin(bands).copy(VImage::option()->set("interpretation", + channels < 3 ? VIPS_INTERPRETATION_B_W: VIPS_INTERPRETATION_sRGB)); + } else { + std::vector background = { + descriptor->createBackground[0], + descriptor->createBackground[1], + descriptor->createBackground[2] + }; + if (channels == 4) { + background.push_back(descriptor->createBackground[3]); + } + image = VImage::new_matrix(descriptor->createWidth, descriptor->createHeight) + .copy(VImage::option()->set("interpretation", + channels < 3 ? VIPS_INTERPRETATION_B_W : VIPS_INTERPRETATION_sRGB)) + .new_from_image(background); + } + if (descriptor->createPageHeight > 0) { + image.set(VIPS_META_PAGE_HEIGHT, descriptor->createPageHeight); + image.set(VIPS_META_N_PAGES, static_cast(descriptor->createHeight / descriptor->createPageHeight)); + } + image = image.cast(VIPS_FORMAT_UCHAR); + imageType = ImageType::RAW; + } else if (descriptor->textValue.length() > 0) { + // Create a new image with text + vips::VOption *textOptions = VImage::option() + ->set("align", descriptor->textAlign) + ->set("justify", descriptor->textJustify) + ->set("rgba", descriptor->textRgba) + ->set("spacing", descriptor->textSpacing) + ->set("wrap", descriptor->textWrap) + ->set("autofit_dpi", &descriptor->textAutofitDpi); + if (descriptor->textWidth > 0) { + textOptions->set("width", descriptor->textWidth); + } + // Ignore dpi if height is set + if (descriptor->textWidth > 0 && descriptor->textHeight > 0) { + textOptions->set("height", descriptor->textHeight); + } else if (descriptor->textDpi > 0) { + textOptions->set("dpi", descriptor->textDpi); + } + if (descriptor->textFont.length() > 0) { + textOptions->set("font", const_cast(descriptor->textFont.data())); + } + if (descriptor->textFontfile.length() > 0) { + textOptions->set("fontfile", const_cast(descriptor->textFontfile.data())); + } + image = VImage::text(const_cast(descriptor->textValue.data()), textOptions); + if (!descriptor->textRgba) { + image = image.copy(VImage::option()->set("interpretation", VIPS_INTERPRETATION_B_W)); + } + imageType = ImageType::RAW; + } else { + // From filesystem + imageType = DetermineImageType(descriptor->file.data()); + if (imageType == ImageType::MISSING) { + if (descriptor->file.find("file.substr(0, 8) + "...')?"); + } + throw vips::VError("Input file is missing: " + descriptor->file); + } + if (imageType != ImageType::UNKNOWN) { + try { + vips::VOption *option = GetOptionsForImageType(imageType, descriptor); + image = VImage::new_from_file(descriptor->file.data(), option); + if (imageType == ImageType::SVG || imageType == ImageType::PDF || imageType == ImageType::MAGICK) { + image = SetDensity(image, descriptor->density); + } + } catch (vips::VError const &err) { + throw vips::VError(std::string("Input file has corrupt header: ") + err.what()); + } + } else { + throw vips::VError("Input file contains unsupported image format"); + } + } + } + + // Limit input images to a given number of pixels, where pixels = width * height + if (descriptor->limitInputPixels > 0 && + static_cast(image.width()) * image.height() > descriptor->limitInputPixels) { + throw vips::VError("Input image exceeds pixel limit"); + } + return std::make_tuple(image, imageType); + } + + /* + Does this image have an embedded profile? + */ + bool HasProfile(VImage image) { + return image.get_typeof(VIPS_META_ICC_NAME) == VIPS_TYPE_BLOB; + } + + /* + Get copy of embedded profile. + */ + std::pair GetProfile(VImage image) { + std::pair icc(nullptr, 0); + if (HasProfile(image)) { + size_t length; + const void *data = image.get_blob(VIPS_META_ICC_NAME, &length); + icc.first = static_cast(g_malloc(length)); + icc.second = length; + memcpy(icc.first, data, length); + } + return icc; + } + + /* + Set embedded profile. + */ + VImage SetProfile(VImage image, std::pair icc) { + if (icc.first != nullptr) { + image = image.copy(); + image.set(VIPS_META_ICC_NAME, reinterpret_cast(vips_area_free_cb), icc.first, icc.second); + } + return image; + } + + static void* RemoveExifCallback(VipsImage *image, char const *field, GValue *value, void *data) { + std::vector *fieldNames = static_cast *>(data); + std::string fieldName(field); + if (fieldName.substr(0, 8) == ("exif-ifd")) { + fieldNames->push_back(fieldName); + } + return nullptr; + } + + /* + Remove all EXIF-related image fields. + */ + VImage RemoveExif(VImage image) { + std::vector fieldNames; + vips_image_map(image.get_image(), static_cast(RemoveExifCallback), &fieldNames); + for (const auto& f : fieldNames) { + image.remove(f.data()); + } + return image; + } + + /* + Get EXIF Orientation of image, if any. + */ + int ExifOrientation(VImage image) { + int orientation = 0; + if (image.get_typeof(VIPS_META_ORIENTATION) != 0) { + orientation = image.get_int(VIPS_META_ORIENTATION); + } + return orientation; + } + + /* + Set EXIF Orientation of image. + */ + VImage SetExifOrientation(VImage image, int const orientation) { + VImage copy = image.copy(); + copy.set(VIPS_META_ORIENTATION, orientation); + return copy; + } + + /* + Remove EXIF Orientation from image. + */ + VImage RemoveExifOrientation(VImage image) { + VImage copy = image.copy(); + copy.remove(VIPS_META_ORIENTATION); + copy.remove("exif-ifd0-Orientation"); + return copy; + } + + /* + Set animation properties if necessary. + */ + VImage SetAnimationProperties(VImage image, int nPages, int pageHeight, std::vector delay, int loop) { + bool hasDelay = !delay.empty(); + VImage copy = image.copy(); + + // Only set page-height if we have more than one page, or this could + // accidentally turn into an animated image later. + if (nPages > 1) copy.set(VIPS_META_PAGE_HEIGHT, pageHeight); + if (hasDelay) { + if (delay.size() == 1) { + // We have just one delay, repeat that value for all frames. + delay.insert(delay.end(), nPages - 1, delay[0]); + } + copy.set("delay", delay); + } + if (nPages == 1 && !hasDelay && loop == -1) { + loop = 1; + } + if (loop != -1) copy.set("loop", loop); + + return copy; + } + + /* + Remove animation properties from image. + */ + VImage RemoveAnimationProperties(VImage image) { + VImage copy = image.copy(); + copy.remove(VIPS_META_PAGE_HEIGHT); + copy.remove("delay"); + copy.remove("loop"); + return copy; + } + + /* + Remove GIF palette from image. + */ + VImage RemoveGifPalette(VImage image) { + VImage copy = image.copy(); + copy.remove("gif-palette"); + return copy; + } + + /* + Does this image have a non-default density? + */ + bool HasDensity(VImage image) { + return image.xres() > 1.0; + } + + /* + Get pixels/mm resolution as pixels/inch density. + */ + int GetDensity(VImage image) { + return static_cast(round(image.xres() * 25.4)); + } + + /* + Set pixels/mm resolution based on a pixels/inch density. + */ + VImage SetDensity(VImage image, const double density) { + const double pixelsPerMm = density / 25.4; + VImage copy = image.copy(); + copy.get_image()->Xres = pixelsPerMm; + copy.get_image()->Yres = pixelsPerMm; + return copy; + } + + /* + Multi-page images can have a page height. Fetch it, and sanity check it. + If page-height is not set, it defaults to the image height + */ + int GetPageHeight(VImage image) { + return vips_image_get_page_height(image.get_image()); + } + + /* + Check the proposed format supports the current dimensions. + */ + void AssertImageTypeDimensions(VImage image, ImageType const imageType) { + const int height = image.get_typeof(VIPS_META_PAGE_HEIGHT) == G_TYPE_INT + ? image.get_int(VIPS_META_PAGE_HEIGHT) + : image.height(); + if (imageType == ImageType::JPEG) { + if (image.width() > 65535 || height > 65535) { + throw vips::VError("Processed image is too large for the JPEG format"); + } + } else if (imageType == ImageType::WEBP) { + if (image.width() > 16383 || height > 16383) { + throw vips::VError("Processed image is too large for the WebP format"); + } + } else if (imageType == ImageType::GIF) { + if (image.width() > 65535 || height > 65535) { + throw vips::VError("Processed image is too large for the GIF format"); + } + } else if (imageType == ImageType::HEIF) { + if (image.width() > 16384 || height > 16384) { + throw vips::VError("Processed image is too large for the HEIF format"); + } + } + } + + /* + Called when a Buffer undergoes GC, required to support mixed runtime libraries in Windows + */ + std::function FreeCallback = [](void*, char* data) { + g_free(data); + }; + + /* + Temporary buffer of warnings + */ + std::queue vipsWarnings; + std::mutex vipsWarningsMutex; + + /* + Called with warnings from the glib-registered "VIPS" domain + */ + void VipsWarningCallback(char const* log_domain, GLogLevelFlags log_level, char const* message, void* ignore) { + std::lock_guard lock(vipsWarningsMutex); + vipsWarnings.emplace(message); + } + + /* + Pop the oldest warning message from the queue + */ + std::string VipsWarningPop() { + std::string warning; + std::lock_guard lock(vipsWarningsMutex); + if (!vipsWarnings.empty()) { + warning = vipsWarnings.front(); + vipsWarnings.pop(); + } + return warning; + } + + /* + Attach an event listener for progress updates, used to detect timeout + */ + void SetTimeout(VImage image, int const seconds) { + if (seconds > 0) { + VipsImage *im = image.get_image(); + if (im->progress_signal == NULL) { + int *timeout = VIPS_NEW(im, int); + *timeout = seconds; + g_signal_connect(im, "eval", G_CALLBACK(VipsProgressCallBack), timeout); + vips_image_set_progress(im, true); + } + } + } + + /* + Event listener for progress updates, used to detect timeout + */ + void VipsProgressCallBack(VipsImage *im, VipsProgress *progress, int *timeout) { + if (*timeout > 0 && progress->run >= *timeout) { + vips_image_set_kill(im, true); + vips_error("timeout", "%d%% complete", progress->percent); + *timeout = 0; + } + } + + /* + Calculate the (left, top) coordinates of the output image + within the input image, applying the given gravity during an embed. + + @Azurebyte: We are basically swapping the inWidth and outWidth, inHeight and outHeight from the CalculateCrop function. + */ + std::tuple CalculateEmbedPosition(int const inWidth, int const inHeight, + int const outWidth, int const outHeight, int const gravity) { + + int left = 0; + int top = 0; + switch (gravity) { + case 1: + // North + left = (outWidth - inWidth) / 2; + break; + case 2: + // East + left = outWidth - inWidth; + top = (outHeight - inHeight) / 2; + break; + case 3: + // South + left = (outWidth - inWidth) / 2; + top = outHeight - inHeight; + break; + case 4: + // West + top = (outHeight - inHeight) / 2; + break; + case 5: + // Northeast + left = outWidth - inWidth; + break; + case 6: + // Southeast + left = outWidth - inWidth; + top = outHeight - inHeight; + break; + case 7: + // Southwest + top = outHeight - inHeight; + break; + case 8: + // Northwest + // Which is the default is 0,0 so we do not assign anything here. + break; + default: + // Centre + left = (outWidth - inWidth) / 2; + top = (outHeight - inHeight) / 2; + } + return std::make_tuple(left, top); + } + + /* + Calculate the (left, top) coordinates of the output image + within the input image, applying the given gravity during a crop. + */ + std::tuple CalculateCrop(int const inWidth, int const inHeight, + int const outWidth, int const outHeight, int const gravity) { + + int left = 0; + int top = 0; + switch (gravity) { + case 1: + // North + left = (inWidth - outWidth + 1) / 2; + break; + case 2: + // East + left = inWidth - outWidth; + top = (inHeight - outHeight + 1) / 2; + break; + case 3: + // South + left = (inWidth - outWidth + 1) / 2; + top = inHeight - outHeight; + break; + case 4: + // West + top = (inHeight - outHeight + 1) / 2; + break; + case 5: + // Northeast + left = inWidth - outWidth; + break; + case 6: + // Southeast + left = inWidth - outWidth; + top = inHeight - outHeight; + break; + case 7: + // Southwest + top = inHeight - outHeight; + break; + case 8: + // Northwest + break; + default: + // Centre + left = (inWidth - outWidth + 1) / 2; + top = (inHeight - outHeight + 1) / 2; + } + return std::make_tuple(left, top); + } + + /* + Calculate the (left, top) coordinates of the output image + within the input image, applying the given x and y offsets. + */ + std::tuple CalculateCrop(int const inWidth, int const inHeight, + int const outWidth, int const outHeight, int const x, int const y) { + + // default values + int left = 0; + int top = 0; + + // assign only if valid + if (x < (inWidth - outWidth)) { + left = x; + } else if (x >= (inWidth - outWidth)) { + left = inWidth - outWidth; + } + + if (y < (inHeight - outHeight)) { + top = y; + } else if (y >= (inHeight - outHeight)) { + top = inHeight - outHeight; + } + + return std::make_tuple(left, top); + } + + /* + Are pixel values in this image 16-bit integer? + */ + bool Is16Bit(VipsInterpretation const interpretation) { + return interpretation == VIPS_INTERPRETATION_RGB16 || interpretation == VIPS_INTERPRETATION_GREY16; + } + + /* + Convert RGBA value to another colourspace + */ + std::vector GetRgbaAsColourspace(std::vector const rgba, + VipsInterpretation const interpretation, bool premultiply) { + int const bands = static_cast(rgba.size()); + if (bands < 3) { + return rgba; + } + VImage pixel = VImage::new_matrix(1, 1); + pixel.set("bands", bands); + pixel = pixel + .new_from_image(rgba) + .colourspace(interpretation, VImage::option()->set("source_space", VIPS_INTERPRETATION_sRGB)); + if (premultiply) { + pixel = pixel.premultiply(); + } + return pixel(0, 0); + } + + /* + Apply the alpha channel to a given colour + */ + std::tuple> ApplyAlpha(VImage image, std::vector colour, bool premultiply) { + // Scale up 8-bit values to match 16-bit input image + double const multiplier = sharp::Is16Bit(image.interpretation()) ? 256.0 : 1.0; + // Create alphaColour colour + std::vector alphaColour; + if (image.bands() > 2) { + alphaColour = { + multiplier * colour[0], + multiplier * colour[1], + multiplier * colour[2] + }; + } else { + // Convert sRGB to greyscale + alphaColour = { multiplier * ( + 0.2126 * colour[0] + + 0.7152 * colour[1] + + 0.0722 * colour[2]) + }; + } + // Add alpha channel(s) to alphaColour colour + if (colour[3] < 255.0 || image.has_alpha()) { + int extraBands = image.bands() > 4 ? image.bands() - 3 : 1; + alphaColour.insert(alphaColour.end(), extraBands, colour[3] * multiplier); + } + // Ensure alphaColour colour uses correct colourspace + alphaColour = sharp::GetRgbaAsColourspace(alphaColour, image.interpretation(), premultiply); + // Add non-transparent alpha channel, if required + if (colour[3] < 255.0 && !image.has_alpha()) { + image = image.bandjoin_const({ 255 * multiplier }); + } + return std::make_tuple(image, alphaColour); + } + + /* + Removes alpha channels, if any. + */ + VImage RemoveAlpha(VImage image) { + while (image.bands() > 1 && image.has_alpha()) { + image = image.extract_band(0, VImage::option()->set("n", image.bands() - 1)); + } + return image; + } + + /* + Ensures alpha channel, if missing. + */ + VImage EnsureAlpha(VImage image, double const value) { + if (!image.has_alpha()) { + image = image.bandjoin_const({ value * vips_interpretation_max_alpha(image.interpretation()) }); + } + return image; + } + + std::pair ResolveShrink(int width, int height, int targetWidth, int targetHeight, + Canvas canvas, bool withoutEnlargement, bool withoutReduction) { + double hshrink = 1.0; + double vshrink = 1.0; + + if (targetWidth > 0 && targetHeight > 0) { + // Fixed width and height + hshrink = static_cast(width) / targetWidth; + vshrink = static_cast(height) / targetHeight; + + switch (canvas) { + case Canvas::CROP: + case Canvas::MIN: + if (hshrink < vshrink) { + vshrink = hshrink; + } else { + hshrink = vshrink; + } + break; + case Canvas::EMBED: + case Canvas::MAX: + if (hshrink > vshrink) { + vshrink = hshrink; + } else { + hshrink = vshrink; + } + break; + case Canvas::IGNORE_ASPECT: + break; + } + } else if (targetWidth > 0) { + // Fixed width + hshrink = static_cast(width) / targetWidth; + + if (canvas != Canvas::IGNORE_ASPECT) { + // Auto height + vshrink = hshrink; + } + } else if (targetHeight > 0) { + // Fixed height + vshrink = static_cast(height) / targetHeight; + + if (canvas != Canvas::IGNORE_ASPECT) { + // Auto width + hshrink = vshrink; + } + } + + // We should not reduce or enlarge the output image, if + // withoutReduction or withoutEnlargement is specified. + if (withoutReduction) { + // Equivalent of VIPS_SIZE_UP + hshrink = std::min(1.0, hshrink); + vshrink = std::min(1.0, vshrink); + } else if (withoutEnlargement) { + // Equivalent of VIPS_SIZE_DOWN + hshrink = std::max(1.0, hshrink); + vshrink = std::max(1.0, vshrink); + } + + // We don't want to shrink so much that we send an axis to 0 + hshrink = std::min(hshrink, static_cast(width)); + vshrink = std::min(vshrink, static_cast(height)); + + return std::make_pair(hshrink, vshrink); + } + + /* + Ensure decoding remains sequential. + */ + VImage StaySequential(VImage image, bool condition) { + if (vips_image_is_sequential(image.get_image()) && condition) { + image = image.copy_memory().copy(); + image.remove(VIPS_META_SEQUENTIAL); + } + return image; + } +} // namespace sharp diff --git a/server/node_modules/sharp/src/common.h b/server/node_modules/sharp/src/common.h new file mode 100644 index 0000000..2bba5e1 --- /dev/null +++ b/server/node_modules/sharp/src/common.h @@ -0,0 +1,399 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#ifndef SRC_COMMON_H_ +#define SRC_COMMON_H_ + +#include +#include +#include +#include + +#include +#include + +// Verify platform and compiler compatibility + +#if (VIPS_MAJOR_VERSION < 8) || \ + (VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION < 17) || \ + (VIPS_MAJOR_VERSION == 8 && VIPS_MINOR_VERSION == 17 && VIPS_MICRO_VERSION < 2) +#error "libvips version 8.17.2+ is required - please see https://sharp.pixelplumbing.com/install" +#endif + +#if defined(__has_include) +#if !__has_include() +#error "C++17 compiler required - please see https://sharp.pixelplumbing.com/install" +#endif +#endif + +using vips::VImage; + +namespace sharp { + + struct InputDescriptor { // NOLINT(runtime/indentation_namespace) + std::string name; + std::string file; + bool autoOrient; + char *buffer; + VipsFailOn failOn; + uint64_t limitInputPixels; + bool unlimited; + VipsAccess access; + size_t bufferLength; + bool isBuffer; + double density; + bool ignoreIcc; + VipsBandFormat rawDepth; + int rawChannels; + int rawWidth; + int rawHeight; + bool rawPremultiplied; + int rawPageHeight; + int pages; + int page; + int createChannels; + int createWidth; + int createHeight; + int createPageHeight; + std::vector createBackground; + std::string createNoiseType; + double createNoiseMean; + double createNoiseSigma; + std::string textValue; + std::string textFont; + std::string textFontfile; + int textWidth; + int textHeight; + VipsAlign textAlign; + bool textJustify; + int textDpi; + bool textRgba; + int textSpacing; + VipsTextWrap textWrap; + int textAutofitDpi; + bool joinAnimated; + int joinAcross; + int joinShim; + std::vector joinBackground; + VipsAlign joinHalign; + VipsAlign joinValign; + std::string svgStylesheet; + bool svgHighBitdepth; + int tiffSubifd; + int openSlideLevel; + std::vector pdfBackground; + bool jp2Oneshot; + + InputDescriptor(): + autoOrient(false), + buffer(nullptr), + failOn(VIPS_FAIL_ON_WARNING), + limitInputPixels(0x3FFF * 0x3FFF), + unlimited(false), + access(VIPS_ACCESS_SEQUENTIAL), + bufferLength(0), + isBuffer(false), + density(72.0), + ignoreIcc(false), + rawDepth(VIPS_FORMAT_UCHAR), + rawChannels(0), + rawWidth(0), + rawHeight(0), + rawPremultiplied(false), + rawPageHeight(0), + pages(1), + page(0), + createChannels(0), + createWidth(0), + createHeight(0), + createPageHeight(0), + createBackground{ 0.0, 0.0, 0.0, 255.0 }, + createNoiseMean(0.0), + createNoiseSigma(0.0), + textWidth(0), + textHeight(0), + textAlign(VIPS_ALIGN_LOW), + textJustify(false), + textDpi(72), + textRgba(false), + textSpacing(0), + textWrap(VIPS_TEXT_WRAP_WORD), + textAutofitDpi(0), + joinAnimated(false), + joinAcross(1), + joinShim(0), + joinBackground{ 0.0, 0.0, 0.0, 255.0 }, + joinHalign(VIPS_ALIGN_LOW), + joinValign(VIPS_ALIGN_LOW), + svgHighBitdepth(false), + tiffSubifd(-1), + openSlideLevel(0), + pdfBackground{ 255.0, 255.0, 255.0, 255.0 }, + jp2Oneshot(false) {} + }; + + // Convenience methods to access the attributes of a Napi::Object + bool HasAttr(Napi::Object obj, std::string attr); + std::string AttrAsStr(Napi::Object obj, std::string attr); + std::string AttrAsStr(Napi::Object obj, unsigned int const attr); + uint32_t AttrAsUint32(Napi::Object obj, std::string attr); + int32_t AttrAsInt32(Napi::Object obj, std::string attr); + int32_t AttrAsInt32(Napi::Object obj, unsigned int const attr); + double AttrAsDouble(Napi::Object obj, std::string attr); + double AttrAsDouble(Napi::Object obj, unsigned int const attr); + bool AttrAsBool(Napi::Object obj, std::string attr); + std::vector AttrAsVectorOfDouble(Napi::Object obj, std::string attr); + std::vector AttrAsInt32Vector(Napi::Object obj, std::string attr); + template T AttrAsEnum(Napi::Object obj, std::string attr, GType type) { + return static_cast( + vips_enum_from_nick(nullptr, type, AttrAsStr(obj, attr).data())); + } + + // Create an InputDescriptor instance from a Napi::Object describing an input image + InputDescriptor* CreateInputDescriptor(Napi::Object input); + + enum class ImageType { + JPEG, + PNG, + WEBP, + JP2, + TIFF, + GIF, + SVG, + HEIF, + PDF, + MAGICK, + OPENSLIDE, + PPM, + FITS, + EXR, + JXL, + RAD, + DCRAW, + VIPS, + RAW, + UNKNOWN, + MISSING + }; + + enum class Canvas { + CROP, + EMBED, + MAX, + MIN, + IGNORE_ASPECT + }; + + // How many tasks are in the queue? + extern std::atomic counterQueue; + + // How many tasks are being processed? + extern std::atomic counterProcess; + + // Filename extension checkers + bool IsJpeg(std::string const &str); + bool IsPng(std::string const &str); + bool IsWebp(std::string const &str); + bool IsJp2(std::string const &str); + bool IsGif(std::string const &str); + bool IsTiff(std::string const &str); + bool IsHeic(std::string const &str); + bool IsHeif(std::string const &str); + bool IsAvif(std::string const &str); + bool IsJxl(std::string const &str); + bool IsDz(std::string const &str); + bool IsDzZip(std::string const &str); + bool IsV(std::string const &str); + + /* + Trim space from end of string. + */ + std::string TrimEnd(std::string const &str); + + /* + Provide a string identifier for the given image type. + */ + std::string ImageTypeId(ImageType const imageType); + + /* + Determine image format of a buffer. + */ + ImageType DetermineImageType(void *buffer, size_t const length); + + /* + Determine image format of a file. + */ + ImageType DetermineImageType(char const *file); + + /* + Format-specific options builder + */ + vips::VOption* GetOptionsForImageType(ImageType imageType, InputDescriptor *descriptor); + + /* + Open an image from the given InputDescriptor (filesystem, compressed buffer, raw pixel data) + */ + std::tuple OpenInput(InputDescriptor *descriptor); + + /* + Does this image have an embedded profile? + */ + bool HasProfile(VImage image); + + /* + Get copy of embedded profile. + */ + std::pair GetProfile(VImage image); + + /* + Set embedded profile. + */ + VImage SetProfile(VImage image, std::pair icc); + + /* + Remove all EXIF-related image fields. + */ + VImage RemoveExif(VImage image); + + /* + Get EXIF Orientation of image, if any. + */ + int ExifOrientation(VImage image); + + /* + Set EXIF Orientation of image. + */ + VImage SetExifOrientation(VImage image, int const orientation); + + /* + Remove EXIF Orientation from image. + */ + VImage RemoveExifOrientation(VImage image); + + /* + Set animation properties if necessary. + */ + VImage SetAnimationProperties(VImage image, int nPages, int pageHeight, std::vector delay, int loop); + + /* + Remove animation properties from image. + */ + VImage RemoveAnimationProperties(VImage image); + + /* + Remove GIF palette from image. + */ + VImage RemoveGifPalette(VImage image); + + /* + Does this image have a non-default density? + */ + bool HasDensity(VImage image); + + /* + Get pixels/mm resolution as pixels/inch density. + */ + int GetDensity(VImage image); + + /* + Set pixels/mm resolution based on a pixels/inch density. + */ + VImage SetDensity(VImage image, const double density); + + /* + Multi-page images can have a page height. Fetch it, and sanity check it. + If page-height is not set, it defaults to the image height + */ + int GetPageHeight(VImage image); + + /* + Check the proposed format supports the current dimensions. + */ + void AssertImageTypeDimensions(VImage image, ImageType const imageType); + + /* + Called when a Buffer undergoes GC, required to support mixed runtime libraries in Windows + */ + extern std::function FreeCallback; + + /* + Called with warnings from the glib-registered "VIPS" domain + */ + void VipsWarningCallback(char const* log_domain, GLogLevelFlags log_level, char const* message, void* ignore); + + /* + Pop the oldest warning message from the queue + */ + std::string VipsWarningPop(); + + /* + Attach an event listener for progress updates, used to detect timeout + */ + void SetTimeout(VImage image, int const timeoutSeconds); + + /* + Event listener for progress updates, used to detect timeout + */ + void VipsProgressCallBack(VipsImage *image, VipsProgress *progress, int *timeoutSeconds); + + /* + Calculate the (left, top) coordinates of the output image + within the input image, applying the given gravity during an embed. + */ + std::tuple CalculateEmbedPosition(int const inWidth, int const inHeight, + int const outWidth, int const outHeight, int const gravity); + + /* + Calculate the (left, top) coordinates of the output image + within the input image, applying the given gravity. + */ + std::tuple CalculateCrop(int const inWidth, int const inHeight, + int const outWidth, int const outHeight, int const gravity); + + /* + Calculate the (left, top) coordinates of the output image + within the input image, applying the given x and y offsets of the output image. + */ + std::tuple CalculateCrop(int const inWidth, int const inHeight, + int const outWidth, int const outHeight, int const x, int const y); + + /* + Are pixel values in this image 16-bit integer? + */ + bool Is16Bit(VipsInterpretation const interpretation); + + /* + Convert RGBA value to another colourspace + */ + std::vector GetRgbaAsColourspace(std::vector const rgba, + VipsInterpretation const interpretation, bool premultiply); + + /* + Apply the alpha channel to a given colour + */ + std::tuple> ApplyAlpha(VImage image, std::vector colour, bool premultiply); + + /* + Removes alpha channels, if any. + */ + VImage RemoveAlpha(VImage image); + + /* + Ensures alpha channel, if missing. + */ + VImage EnsureAlpha(VImage image, double const value); + + /* + Calculate the horizontal and vertical shrink factors, taking the canvas mode into account. + */ + std::pair ResolveShrink(int width, int height, int targetWidth, int targetHeight, + Canvas canvas, bool withoutEnlargement, bool withoutReduction); + + /* + Ensure decoding remains sequential. + */ + VImage StaySequential(VImage image, bool condition = true); + +} // namespace sharp + +#endif // SRC_COMMON_H_ diff --git a/server/node_modules/sharp/src/metadata.cc b/server/node_modules/sharp/src/metadata.cc new file mode 100644 index 0000000..788b712 --- /dev/null +++ b/server/node_modules/sharp/src/metadata.cc @@ -0,0 +1,342 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#include +#include +#include + +#include +#include + +#include "common.h" +#include "metadata.h" + +static void* readPNGComment(VipsImage *image, const char *field, GValue *value, void *p); + +class MetadataWorker : public Napi::AsyncWorker { + public: + MetadataWorker(Napi::Function callback, MetadataBaton *baton, Napi::Function debuglog) : + Napi::AsyncWorker(callback), baton(baton), debuglog(Napi::Persistent(debuglog)) {} + ~MetadataWorker() {} + + void Execute() { + // Decrement queued task counter + sharp::counterQueue--; + + vips::VImage image; + sharp::ImageType imageType = sharp::ImageType::UNKNOWN; + try { + std::tie(image, imageType) = OpenInput(baton->input); + } catch (vips::VError const &err) { + (baton->err).append(err.what()); + } + if (imageType != sharp::ImageType::UNKNOWN) { + // Image type + baton->format = sharp::ImageTypeId(imageType); + // VipsImage attributes + baton->width = image.width(); + baton->height = image.height(); + baton->space = vips_enum_nick(VIPS_TYPE_INTERPRETATION, image.interpretation()); + baton->channels = image.bands(); + baton->depth = vips_enum_nick(VIPS_TYPE_BAND_FORMAT, image.format()); + if (sharp::HasDensity(image)) { + baton->density = sharp::GetDensity(image); + } + if (image.get_typeof("jpeg-chroma-subsample") == VIPS_TYPE_REF_STRING) { + baton->chromaSubsampling = image.get_string("jpeg-chroma-subsample"); + } + if (image.get_typeof("interlaced") == G_TYPE_INT) { + baton->isProgressive = image.get_int("interlaced") == 1; + } + if (image.get_typeof(VIPS_META_PALETTE) == G_TYPE_INT) { + baton->isPalette = image.get_int(VIPS_META_PALETTE); + } + if (image.get_typeof(VIPS_META_BITS_PER_SAMPLE) == G_TYPE_INT) { + baton->bitsPerSample = image.get_int(VIPS_META_BITS_PER_SAMPLE); + } + if (image.get_typeof(VIPS_META_N_PAGES) == G_TYPE_INT) { + baton->pages = image.get_int(VIPS_META_N_PAGES); + } + if (image.get_typeof(VIPS_META_PAGE_HEIGHT) == G_TYPE_INT) { + baton->pageHeight = image.get_int(VIPS_META_PAGE_HEIGHT); + } + if (image.get_typeof("loop") == G_TYPE_INT) { + baton->loop = image.get_int("loop"); + } + if (image.get_typeof("delay") == VIPS_TYPE_ARRAY_INT) { + baton->delay = image.get_array_int("delay"); + } + if (image.get_typeof("heif-primary") == G_TYPE_INT) { + baton->pagePrimary = image.get_int("heif-primary"); + } + if (image.get_typeof("heif-compression") == VIPS_TYPE_REF_STRING) { + baton->compression = image.get_string("heif-compression"); + } + if (image.get_typeof(VIPS_META_RESOLUTION_UNIT) == VIPS_TYPE_REF_STRING) { + baton->resolutionUnit = image.get_string(VIPS_META_RESOLUTION_UNIT); + } + if (image.get_typeof("magick-format") == VIPS_TYPE_REF_STRING) { + baton->formatMagick = image.get_string("magick-format"); + } + if (image.get_typeof("openslide.level-count") == VIPS_TYPE_REF_STRING) { + int const levels = std::stoi(image.get_string("openslide.level-count")); + for (int l = 0; l < levels; l++) { + std::string prefix = "openslide.level[" + std::to_string(l) + "]."; + int const width = std::stoi(image.get_string((prefix + "width").data())); + int const height = std::stoi(image.get_string((prefix + "height").data())); + baton->levels.push_back(std::pair(width, height)); + } + } + if (image.get_typeof(VIPS_META_N_SUBIFDS) == G_TYPE_INT) { + baton->subifds = image.get_int(VIPS_META_N_SUBIFDS); + } + baton->hasProfile = sharp::HasProfile(image); + if (image.get_typeof("background") == VIPS_TYPE_ARRAY_DOUBLE) { + baton->background = image.get_array_double("background"); + } + // Derived attributes + baton->hasAlpha = image.has_alpha(); + baton->orientation = sharp::ExifOrientation(image); + // EXIF + if (image.get_typeof(VIPS_META_EXIF_NAME) == VIPS_TYPE_BLOB) { + size_t exifLength; + void const *exif = image.get_blob(VIPS_META_EXIF_NAME, &exifLength); + baton->exif = static_cast(g_malloc(exifLength)); + memcpy(baton->exif, exif, exifLength); + baton->exifLength = exifLength; + } + // ICC profile + if (image.get_typeof(VIPS_META_ICC_NAME) == VIPS_TYPE_BLOB) { + size_t iccLength; + void const *icc = image.get_blob(VIPS_META_ICC_NAME, &iccLength); + baton->icc = static_cast(g_malloc(iccLength)); + memcpy(baton->icc, icc, iccLength); + baton->iccLength = iccLength; + } + // IPTC + if (image.get_typeof(VIPS_META_IPTC_NAME) == VIPS_TYPE_BLOB) { + size_t iptcLength; + void const *iptc = image.get_blob(VIPS_META_IPTC_NAME, &iptcLength); + baton->iptc = static_cast(g_malloc(iptcLength)); + memcpy(baton->iptc, iptc, iptcLength); + baton->iptcLength = iptcLength; + } + // XMP + if (image.get_typeof(VIPS_META_XMP_NAME) == VIPS_TYPE_BLOB) { + size_t xmpLength; + void const *xmp = image.get_blob(VIPS_META_XMP_NAME, &xmpLength); + baton->xmp = static_cast(g_malloc(xmpLength)); + memcpy(baton->xmp, xmp, xmpLength); + baton->xmpLength = xmpLength; + } + // TIFFTAG_PHOTOSHOP + if (image.get_typeof(VIPS_META_PHOTOSHOP_NAME) == VIPS_TYPE_BLOB) { + size_t tifftagPhotoshopLength; + void const *tifftagPhotoshop = image.get_blob(VIPS_META_PHOTOSHOP_NAME, &tifftagPhotoshopLength); + baton->tifftagPhotoshop = static_cast(g_malloc(tifftagPhotoshopLength)); + memcpy(baton->tifftagPhotoshop, tifftagPhotoshop, tifftagPhotoshopLength); + baton->tifftagPhotoshopLength = tifftagPhotoshopLength; + } + // PNG comments + vips_image_map(image.get_image(), readPNGComment, &baton->comments); + } + + // Clean up + vips_error_clear(); + vips_thread_shutdown(); + } + + void OnOK() { + Napi::Env env = Env(); + Napi::HandleScope scope(env); + + // Handle warnings + std::string warning = sharp::VipsWarningPop(); + while (!warning.empty()) { + debuglog.Call(Receiver().Value(), { Napi::String::New(env, warning) }); + warning = sharp::VipsWarningPop(); + } + + if (baton->err.empty()) { + Napi::Object info = Napi::Object::New(env); + info.Set("format", baton->format); + if (baton->input->bufferLength > 0) { + info.Set("size", baton->input->bufferLength); + } + info.Set("width", baton->width); + info.Set("height", baton->height); + info.Set("space", baton->space); + info.Set("channels", baton->channels); + info.Set("depth", baton->depth); + if (baton->density > 0) { + info.Set("density", baton->density); + } + if (!baton->chromaSubsampling.empty()) { + info.Set("chromaSubsampling", baton->chromaSubsampling); + } + info.Set("isProgressive", baton->isProgressive); + info.Set("isPalette", baton->isPalette); + if (baton->bitsPerSample > 0) { + info.Set("bitsPerSample", baton->bitsPerSample); + if (baton->isPalette) { + // Deprecated, remove with libvips 8.17.0 + info.Set("paletteBitDepth", baton->bitsPerSample); + } + } + if (baton->pages > 0) { + info.Set("pages", baton->pages); + } + if (baton->pageHeight > 0) { + info.Set("pageHeight", baton->pageHeight); + } + if (baton->loop >= 0) { + info.Set("loop", baton->loop); + } + if (!baton->delay.empty()) { + int i = 0; + Napi::Array delay = Napi::Array::New(env, static_cast(baton->delay.size())); + for (int const d : baton->delay) { + delay.Set(i++, d); + } + info.Set("delay", delay); + } + if (baton->pagePrimary > -1) { + info.Set("pagePrimary", baton->pagePrimary); + } + if (!baton->compression.empty()) { + info.Set("compression", baton->compression); + } + if (!baton->resolutionUnit.empty()) { + info.Set("resolutionUnit", baton->resolutionUnit == "in" ? "inch" : baton->resolutionUnit); + } + if (!baton->formatMagick.empty()) { + info.Set("formatMagick", baton->formatMagick); + } + if (!baton->levels.empty()) { + int i = 0; + Napi::Array levels = Napi::Array::New(env, static_cast(baton->levels.size())); + for (std::pair const &l : baton->levels) { + Napi::Object level = Napi::Object::New(env); + level.Set("width", l.first); + level.Set("height", l.second); + levels.Set(i++, level); + } + info.Set("levels", levels); + } + if (baton->subifds > 0) { + info.Set("subifds", baton->subifds); + } + if (!baton->background.empty()) { + Napi::Object background = Napi::Object::New(env); + if (baton->background.size() == 3) { + background.Set("r", baton->background[0]); + background.Set("g", baton->background[1]); + background.Set("b", baton->background[2]); + } else { + background.Set("gray", round(baton->background[0] * 100 / 255)); + } + info.Set("background", background); + } + info.Set("hasProfile", baton->hasProfile); + info.Set("hasAlpha", baton->hasAlpha); + if (baton->orientation > 0) { + info.Set("orientation", baton->orientation); + } + Napi::Object autoOrient = Napi::Object::New(env); + info.Set("autoOrient", autoOrient); + if (baton->orientation >= 5) { + autoOrient.Set("width", baton->height); + autoOrient.Set("height", baton->width); + } else { + autoOrient.Set("width", baton->width); + autoOrient.Set("height", baton->height); + } + if (baton->exifLength > 0) { + info.Set("exif", Napi::Buffer::NewOrCopy(env, baton->exif, baton->exifLength, sharp::FreeCallback)); + } + if (baton->iccLength > 0) { + info.Set("icc", Napi::Buffer::NewOrCopy(env, baton->icc, baton->iccLength, sharp::FreeCallback)); + } + if (baton->iptcLength > 0) { + info.Set("iptc", Napi::Buffer::NewOrCopy(env, baton->iptc, baton->iptcLength, sharp::FreeCallback)); + } + if (baton->xmpLength > 0) { + if (g_utf8_validate(static_cast(baton->xmp), baton->xmpLength, nullptr)) { + info.Set("xmpAsString", + Napi::String::New(env, static_cast(baton->xmp), baton->xmpLength)); + } + info.Set("xmp", Napi::Buffer::NewOrCopy(env, baton->xmp, baton->xmpLength, sharp::FreeCallback)); + } + if (baton->tifftagPhotoshopLength > 0) { + info.Set("tifftagPhotoshop", + Napi::Buffer::NewOrCopy(env, baton->tifftagPhotoshop, + baton->tifftagPhotoshopLength, sharp::FreeCallback)); + } + if (baton->comments.size() > 0) { + int i = 0; + Napi::Array comments = Napi::Array::New(env, baton->comments.size()); + for (auto &c : baton->comments) { + Napi::Object comment = Napi::Object::New(env); + comment.Set("keyword", c.first); + comment.Set("text", c.second); + comments.Set(i++, comment); + } + info.Set("comments", comments); + } + Callback().Call(Receiver().Value(), { env.Null(), info }); + } else { + Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() }); + } + + delete baton->input; + delete baton; + } + + private: + MetadataBaton* baton; + Napi::FunctionReference debuglog; +}; + +/* + metadata(options, callback) +*/ +Napi::Value metadata(const Napi::CallbackInfo& info) { + // V8 objects are converted to non-V8 types held in the baton struct + MetadataBaton *baton = new MetadataBaton; + Napi::Object options = info[size_t(0)].As(); + + // Input + baton->input = sharp::CreateInputDescriptor(options.Get("input").As()); + + // Function to notify of libvips warnings + Napi::Function debuglog = options.Get("debuglog").As(); + + // Join queue for worker thread + Napi::Function callback = info[size_t(1)].As(); + MetadataWorker *worker = new MetadataWorker(callback, baton, debuglog); + worker->Receiver().Set("options", options); + worker->Queue(); + + // Increment queued task counter + sharp::counterQueue++; + + return info.Env().Undefined(); +} + +const char *PNG_COMMENT_START = "png-comment-"; +const int PNG_COMMENT_START_LEN = strlen(PNG_COMMENT_START); + +static void* readPNGComment(VipsImage *image, const char *field, GValue *value, void *p) { + MetadataComments *comments = static_cast(p); + + if (vips_isprefix(PNG_COMMENT_START, field)) { + const char *keyword = strchr(field + PNG_COMMENT_START_LEN, '-'); + const char *str; + if (keyword != NULL && !vips_image_get_string(image, field, &str)) { + keyword++; // Skip the hyphen + comments->push_back(std::make_pair(keyword, str)); + } + } + + return NULL; +} diff --git a/server/node_modules/sharp/src/metadata.h b/server/node_modules/sharp/src/metadata.h new file mode 100644 index 0000000..f93dd51 --- /dev/null +++ b/server/node_modules/sharp/src/metadata.h @@ -0,0 +1,87 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#ifndef SRC_METADATA_H_ +#define SRC_METADATA_H_ + +#include +#include + +#include "./common.h" + +typedef std::vector> MetadataComments; + +struct MetadataBaton { + // Input + sharp::InputDescriptor *input; + // Output + std::string format; + int width; + int height; + std::string space; + int channels; + std::string depth; + int density; + std::string chromaSubsampling; + bool isProgressive; + bool isPalette; + int bitsPerSample; + int pages; + int pageHeight; + int loop; + std::vector delay; + int pagePrimary; + std::string compression; + std::string resolutionUnit; + std::string formatMagick; + std::vector> levels; + int subifds; + std::vector background; + bool hasProfile; + bool hasAlpha; + int orientation; + char *exif; + size_t exifLength; + char *icc; + size_t iccLength; + char *iptc; + size_t iptcLength; + char *xmp; + size_t xmpLength; + char *tifftagPhotoshop; + size_t tifftagPhotoshopLength; + MetadataComments comments; + std::string err; + + MetadataBaton(): + input(nullptr), + width(0), + height(0), + channels(0), + density(0), + isProgressive(false), + isPalette(false), + bitsPerSample(0), + pages(0), + pageHeight(0), + loop(-1), + pagePrimary(-1), + subifds(0), + hasProfile(false), + hasAlpha(false), + orientation(0), + exif(nullptr), + exifLength(0), + icc(nullptr), + iccLength(0), + iptc(nullptr), + iptcLength(0), + xmp(nullptr), + xmpLength(0), + tifftagPhotoshop(nullptr), + tifftagPhotoshopLength(0) {} +}; + +Napi::Value metadata(const Napi::CallbackInfo& info); + +#endif // SRC_METADATA_H_ diff --git a/server/node_modules/sharp/src/operations.cc b/server/node_modules/sharp/src/operations.cc new file mode 100644 index 0000000..ba3a051 --- /dev/null +++ b/server/node_modules/sharp/src/operations.cc @@ -0,0 +1,497 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#include +#include +#include +#include +#include +#include + +#include "common.h" +#include "operations.h" + +using vips::VImage; +using vips::VError; + +namespace sharp { + /* + * Tint an image using the provided RGB. + */ + VImage Tint(VImage image, std::vector const tint) { + std::vector const tintLab = (VImage::black(1, 1) + tint) + .colourspace(VIPS_INTERPRETATION_LAB, VImage::option()->set("source_space", VIPS_INTERPRETATION_sRGB)) + .getpoint(0, 0); + // LAB identity function + VImage identityLab = VImage::identity(VImage::option()->set("bands", 3)) + .colourspace(VIPS_INTERPRETATION_LAB, VImage::option()->set("source_space", VIPS_INTERPRETATION_sRGB)); + // Scale luminance range, 0.0 to 1.0 + VImage l = identityLab[0] / 100; + // Weighting functions + VImage weightL = 1.0 - 4.0 * ((l - 0.5) * (l - 0.5)); + VImage weightAB = (weightL * tintLab).extract_band(1, VImage::option()->set("n", 2)); + identityLab = identityLab[0].bandjoin(weightAB); + // Convert lookup table to sRGB + VImage lut = identityLab.colourspace(VIPS_INTERPRETATION_sRGB, + VImage::option()->set("source_space", VIPS_INTERPRETATION_LAB)); + // Original colourspace + VipsInterpretation typeBeforeTint = image.interpretation(); + if (typeBeforeTint == VIPS_INTERPRETATION_RGB) { + typeBeforeTint = VIPS_INTERPRETATION_sRGB; + } + // Apply lookup table + if (image.has_alpha()) { + VImage alpha = image[image.bands() - 1]; + image = RemoveAlpha(image) + .colourspace(VIPS_INTERPRETATION_B_W) + .maplut(lut) + .colourspace(typeBeforeTint) + .bandjoin(alpha); + } else { + image = image + .colourspace(VIPS_INTERPRETATION_B_W) + .maplut(lut) + .colourspace(typeBeforeTint); + } + return image; + } + + /* + * Stretch luminance to cover full dynamic range. + */ + VImage Normalise(VImage image, int const lower, int const upper) { + // Get original colourspace + VipsInterpretation typeBeforeNormalize = image.interpretation(); + if (typeBeforeNormalize == VIPS_INTERPRETATION_RGB) { + typeBeforeNormalize = VIPS_INTERPRETATION_sRGB; + } + // Convert to LAB colourspace + VImage lab = image.colourspace(VIPS_INTERPRETATION_LAB); + // Extract luminance + VImage luminance = lab[0]; + + // Find luminance range + int const min = lower == 0 ? luminance.min() : luminance.percent(lower); + int const max = upper == 100 ? luminance.max() : luminance.percent(upper); + + if (std::abs(max - min) > 1) { + // Extract chroma + VImage chroma = lab.extract_band(1, VImage::option()->set("n", 2)); + // Calculate multiplication factor and addition + double f = 100.0 / (max - min); + double a = -(min * f); + // Scale luminance, join to chroma, convert back to original colourspace + VImage normalized = luminance.linear(f, a).bandjoin(chroma).colourspace(typeBeforeNormalize); + // Attach original alpha channel, if any + if (image.has_alpha()) { + // Extract original alpha channel + VImage alpha = image[image.bands() - 1]; + // Join alpha channel to normalised image + return normalized.bandjoin(alpha); + } else { + return normalized; + } + } + return image; + } + + /* + * Contrast limiting adapative histogram equalization (CLAHE) + */ + VImage Clahe(VImage image, int const width, int const height, int const maxSlope) { + return image.hist_local(width, height, VImage::option()->set("max_slope", maxSlope)); + } + + /* + * Gamma encoding/decoding + */ + VImage Gamma(VImage image, double const exponent) { + if (image.has_alpha()) { + // Separate alpha channel + VImage alpha = image[image.bands() - 1]; + return RemoveAlpha(image).gamma(VImage::option()->set("exponent", exponent)).bandjoin(alpha); + } else { + return image.gamma(VImage::option()->set("exponent", exponent)); + } + } + + /* + * Flatten image to remove alpha channel + */ + VImage Flatten(VImage image, std::vector flattenBackground) { + double const multiplier = sharp::Is16Bit(image.interpretation()) ? 256.0 : 1.0; + std::vector background { + flattenBackground[0] * multiplier, + flattenBackground[1] * multiplier, + flattenBackground[2] * multiplier + }; + return image.flatten(VImage::option()->set("background", background)); + } + + /** + * Produce the "negative" of the image. + */ + VImage Negate(VImage image, bool const negateAlpha) { + if (image.has_alpha() && !negateAlpha) { + // Separate alpha channel + VImage alpha = image[image.bands() - 1]; + return RemoveAlpha(image).invert().bandjoin(alpha); + } else { + return image.invert(); + } + } + + /* + * Gaussian blur. Use sigma of -1.0 for fast blur. + */ + VImage Blur(VImage image, double const sigma, VipsPrecision precision, double const minAmpl) { + if (sigma == -1.0) { + // Fast, mild blur - averages neighbouring pixels + VImage blur = VImage::new_matrixv(3, 3, + 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0, + 1.0, 1.0, 1.0); + blur.set("scale", 9.0); + return image.conv(blur); + } else { + // Slower, accurate Gaussian blur + return StaySequential(image).gaussblur(sigma, VImage::option() + ->set("precision", precision) + ->set("min_ampl", minAmpl)); + } + } + + /* + * Convolution with a kernel. + */ + VImage Convolve(VImage image, int const width, int const height, + double const scale, double const offset, + std::vector const &kernel_v + ) { + VImage kernel = VImage::new_from_memory( + static_cast(const_cast(kernel_v.data())), + width * height * sizeof(double), + width, + height, + 1, + VIPS_FORMAT_DOUBLE); + kernel.set("scale", scale); + kernel.set("offset", offset); + + return image.conv(kernel); + } + + /* + * Recomb with a Matrix of the given bands/channel size. + * Eg. RGB will be a 3x3 matrix. + */ + VImage Recomb(VImage image, std::vector const& matrix) { + double* m = const_cast(matrix.data()); + image = image.colourspace(VIPS_INTERPRETATION_sRGB); + if (matrix.size() == 9) { + return image + .recomb(image.bands() == 3 + ? VImage::new_matrix(3, 3, m, 9) + : VImage::new_matrixv(4, 4, + m[0], m[1], m[2], 0.0, + m[3], m[4], m[5], 0.0, + m[6], m[7], m[8], 0.0, + 0.0, 0.0, 0.0, 1.0)); + } else { + return image.recomb(VImage::new_matrix(4, 4, m, 16)); + } + } + + VImage Modulate(VImage image, double const brightness, double const saturation, + int const hue, double const lightness) { + VipsInterpretation colourspaceBeforeModulate = image.interpretation(); + if (image.has_alpha()) { + // Separate alpha channel + VImage alpha = image[image.bands() - 1]; + return RemoveAlpha(image) + .colourspace(VIPS_INTERPRETATION_LCH) + .linear( + { brightness, saturation, 1}, + { lightness, 0.0, static_cast(hue) } + ) + .colourspace(colourspaceBeforeModulate) + .bandjoin(alpha); + } else { + return image + .colourspace(VIPS_INTERPRETATION_LCH) + .linear( + { brightness, saturation, 1 }, + { lightness, 0.0, static_cast(hue) } + ) + .colourspace(colourspaceBeforeModulate); + } + } + + /* + * Sharpen flat and jagged areas. Use sigma of -1.0 for fast sharpen. + */ + VImage Sharpen(VImage image, double const sigma, double const m1, double const m2, + double const x1, double const y2, double const y3) { + if (sigma == -1.0) { + // Fast, mild sharpen + VImage sharpen = VImage::new_matrixv(3, 3, + -1.0, -1.0, -1.0, + -1.0, 32.0, -1.0, + -1.0, -1.0, -1.0); + sharpen.set("scale", 24.0); + return image.conv(sharpen); + } else { + // Slow, accurate sharpen in LAB colour space, with control over flat vs jagged areas + VipsInterpretation colourspaceBeforeSharpen = image.interpretation(); + if (colourspaceBeforeSharpen == VIPS_INTERPRETATION_RGB) { + colourspaceBeforeSharpen = VIPS_INTERPRETATION_sRGB; + } + return image + .sharpen(VImage::option() + ->set("sigma", sigma) + ->set("m1", m1) + ->set("m2", m2) + ->set("x1", x1) + ->set("y2", y2) + ->set("y3", y3)) + .colourspace(colourspaceBeforeSharpen); + } + } + + VImage Threshold(VImage image, double const threshold, bool const thresholdGrayscale) { + if (!thresholdGrayscale) { + return image >= threshold; + } + return image.colourspace(VIPS_INTERPRETATION_B_W) >= threshold; + } + + /* + Perform boolean/bitwise operation on image color channels - results in one channel image + */ + VImage Bandbool(VImage image, VipsOperationBoolean const boolean) { + image = image.bandbool(boolean); + return image.copy(VImage::option()->set("interpretation", VIPS_INTERPRETATION_B_W)); + } + + /* + Perform bitwise boolean operation between images + */ + VImage Boolean(VImage image, VImage imageR, VipsOperationBoolean const boolean) { + return image.boolean(imageR, boolean); + } + + /* + Trim an image + */ + VImage Trim(VImage image, std::vector background, double threshold, bool const lineArt) { + if (image.width() < 3 && image.height() < 3) { + throw VError("Image to trim must be at least 3x3 pixels"); + } + if (background.size() == 0) { + // Top-left pixel provides the default background colour if none is given + background = image.extract_area(0, 0, 1, 1)(0, 0); + } else if (sharp::Is16Bit(image.interpretation())) { + for (size_t i = 0; i < background.size(); i++) { + background[i] *= 256.0; + } + threshold *= 256.0; + } + std::vector backgroundAlpha({ background.back() }); + if (image.has_alpha()) { + background.pop_back(); + } else { + background.resize(image.bands()); + } + int left, top, width, height; + left = image.find_trim(&top, &width, &height, VImage::option() + ->set("background", background) + ->set("line_art", lineArt) + ->set("threshold", threshold)); + if (image.has_alpha()) { + // Search alpha channel (A) + int leftA, topA, widthA, heightA; + VImage alpha = image[image.bands() - 1]; + leftA = alpha.find_trim(&topA, &widthA, &heightA, VImage::option() + ->set("background", backgroundAlpha) + ->set("line_art", lineArt) + ->set("threshold", threshold)); + if (widthA > 0 && heightA > 0) { + if (width > 0 && height > 0) { + // Combined bounding box (B) + int const leftB = std::min(left, leftA); + int const topB = std::min(top, topA); + int const widthB = std::max(left + width, leftA + widthA) - leftB; + int const heightB = std::max(top + height, topA + heightA) - topB; + return image.extract_area(leftB, topB, widthB, heightB); + } else { + // Use alpha only + return image.extract_area(leftA, topA, widthA, heightA); + } + } + } + if (width > 0 && height > 0) { + return image.extract_area(left, top, width, height); + } + return image; + } + + /* + * Calculate (a * in + b) + */ + VImage Linear(VImage image, std::vector const a, std::vector const b) { + size_t const bands = static_cast(image.bands()); + if (a.size() > bands) { + throw VError("Band expansion using linear is unsupported"); + } + bool const uchar = !Is16Bit(image.interpretation()); + if (image.has_alpha() && a.size() != bands && (a.size() == 1 || a.size() == bands - 1 || bands - 1 == 1)) { + // Separate alpha channel + VImage alpha = image[bands - 1]; + return RemoveAlpha(image).linear(a, b, VImage::option()->set("uchar", uchar)).bandjoin(alpha); + } else { + return image.linear(a, b, VImage::option()->set("uchar", uchar)); + } + } + + /* + * Unflatten + */ + VImage Unflatten(VImage image) { + if (image.has_alpha()) { + VImage alpha = image[image.bands() - 1]; + VImage noAlpha = RemoveAlpha(image); + return noAlpha.bandjoin(alpha & (noAlpha.colourspace(VIPS_INTERPRETATION_B_W) < 255)); + } else { + return image.bandjoin(image.colourspace(VIPS_INTERPRETATION_B_W) < 255); + } + } + + /* + * Ensure the image is in a given colourspace + */ + VImage EnsureColourspace(VImage image, VipsInterpretation colourspace) { + if (colourspace != VIPS_INTERPRETATION_LAST && image.interpretation() != colourspace) { + image = image.colourspace(colourspace, + VImage::option()->set("source_space", image.interpretation())); + } + return image; + } + + /* + * Split and crop each frame, reassemble, and update pageHeight. + */ + VImage CropMultiPage(VImage image, int left, int top, int width, int height, + int nPages, int *pageHeight) { + if (top == 0 && height == *pageHeight) { + // Fast path; no need to adjust the height of the multi-page image + return image.extract_area(left, 0, width, image.height()); + } else { + std::vector pages; + pages.reserve(nPages); + + // Split the image into cropped frames + image = StaySequential(image); + for (int i = 0; i < nPages; i++) { + pages.push_back( + image.extract_area(left, *pageHeight * i + top, width, height)); + } + + // Reassemble the frames into a tall, thin image + VImage assembled = VImage::arrayjoin(pages, + VImage::option()->set("across", 1)); + + // Update the page height + *pageHeight = height; + + return assembled; + } + } + + /* + * Split into frames, embed each frame, reassemble, and update pageHeight. + */ + VImage EmbedMultiPage(VImage image, int left, int top, int width, int height, + VipsExtend extendWith, std::vector background, int nPages, int *pageHeight) { + if (top == 0 && height == *pageHeight) { + // Fast path; no need to adjust the height of the multi-page image + return image.embed(left, 0, width, image.height(), VImage::option() + ->set("extend", extendWith) + ->set("background", background)); + } else if (left == 0 && width == image.width()) { + // Fast path; no need to adjust the width of the multi-page image + std::vector pages; + pages.reserve(nPages); + + // Rearrange the tall image into a vertical grid + image = image.grid(*pageHeight, nPages, 1); + + // Do the embed on the wide image + image = image.embed(0, top, image.width(), height, VImage::option() + ->set("extend", extendWith) + ->set("background", background)); + + // Split the wide image into frames + for (int i = 0; i < nPages; i++) { + pages.push_back( + image.extract_area(width * i, 0, width, height)); + } + + // Reassemble the frames into a tall, thin image + VImage assembled = VImage::arrayjoin(pages, + VImage::option()->set("across", 1)); + + // Update the page height + *pageHeight = height; + + return assembled; + } else { + std::vector pages; + pages.reserve(nPages); + + // Split the image into frames + for (int i = 0; i < nPages; i++) { + pages.push_back( + image.extract_area(0, *pageHeight * i, image.width(), *pageHeight)); + } + + // Embed each frame in the target size + for (int i = 0; i < nPages; i++) { + pages[i] = pages[i].embed(left, top, width, height, VImage::option() + ->set("extend", extendWith) + ->set("background", background)); + } + + // Reassemble the frames into a tall, thin image + VImage assembled = VImage::arrayjoin(pages, + VImage::option()->set("across", 1)); + + // Update the page height + *pageHeight = height; + + return assembled; + } + } + + /* + * Dilate an image + */ + VImage Dilate(VImage image, int const width) { + int const maskWidth = 2 * width + 1; + VImage mask = VImage::new_matrix(maskWidth, maskWidth); + return image.morph( + mask, + VIPS_OPERATION_MORPHOLOGY_DILATE).invert(); + } + + /* + * Erode an image + */ + VImage Erode(VImage image, int const width) { + int const maskWidth = 2 * width + 1; + VImage mask = VImage::new_matrix(maskWidth, maskWidth); + return image.morph( + mask, + VIPS_OPERATION_MORPHOLOGY_ERODE).invert(); + } + +} // namespace sharp diff --git a/server/node_modules/sharp/src/operations.h b/server/node_modules/sharp/src/operations.h new file mode 100644 index 0000000..22ff46f --- /dev/null +++ b/server/node_modules/sharp/src/operations.h @@ -0,0 +1,134 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#ifndef SRC_OPERATIONS_H_ +#define SRC_OPERATIONS_H_ + +#include +#include +#include +#include +#include + +using vips::VImage; + +namespace sharp { + + /* + * Tint an image using the provided RGB. + */ + VImage Tint(VImage image, std::vector const tint); + + /* + * Stretch luminance to cover full dynamic range. + */ + VImage Normalise(VImage image, int const lower, int const upper); + + /* + * Contrast limiting adapative histogram equalization (CLAHE) + */ + VImage Clahe(VImage image, int const width, int const height, int const maxSlope); + + /* + * Gamma encoding/decoding + */ + VImage Gamma(VImage image, double const exponent); + + /* + * Flatten image to remove alpha channel + */ + VImage Flatten(VImage image, std::vector flattenBackground); + + /* + * Produce the "negative" of the image. + */ + VImage Negate(VImage image, bool const negateAlpha); + + /* + * Gaussian blur. Use sigma of -1.0 for fast blur. + */ + VImage Blur(VImage image, double const sigma, VipsPrecision precision, double const minAmpl); + + /* + * Convolution with a kernel. + */ + VImage Convolve(VImage image, int const width, int const height, + double const scale, double const offset, std::vector const &kernel_v); + + /* + * Sharpen flat and jagged areas. Use sigma of -1.0 for fast sharpen. + */ + VImage Sharpen(VImage image, double const sigma, double const m1, double const m2, + double const x1, double const y2, double const y3); + + /* + Threshold an image + */ + VImage Threshold(VImage image, double const threshold, bool const thresholdColor); + + /* + Perform boolean/bitwise operation on image color channels - results in one channel image + */ + VImage Bandbool(VImage image, VipsOperationBoolean const boolean); + + /* + Perform bitwise boolean operation between images + */ + VImage Boolean(VImage image, VImage imageR, VipsOperationBoolean const boolean); + + /* + Trim an image + */ + VImage Trim(VImage image, std::vector background, double threshold, bool const lineArt); + + /* + * Linear adjustment (a * in + b) + */ + VImage Linear(VImage image, std::vector const a, std::vector const b); + + /* + * Unflatten + */ + VImage Unflatten(VImage image); + + /* + * Recomb with a Matrix of the given bands/channel size. + * Eg. RGB will be a 3x3 matrix. + */ + VImage Recomb(VImage image, std::vector const &matrix); + + /* + * Modulate brightness, saturation, hue and lightness + */ + VImage Modulate(VImage image, double const brightness, double const saturation, + int const hue, double const lightness); + + /* + * Ensure the image is in a given colourspace + */ + VImage EnsureColourspace(VImage image, VipsInterpretation colourspace); + + /* + * Split and crop each frame, reassemble, and update pageHeight. + */ + VImage CropMultiPage(VImage image, int left, int top, int width, int height, + int nPages, int *pageHeight); + + /* + * Split into frames, embed each frame, reassemble, and update pageHeight. + */ + VImage EmbedMultiPage(VImage image, int left, int top, int width, int height, + VipsExtend extendWith, std::vector background, int nPages, int *pageHeight); + + /* + * Dilate an image + */ + VImage Dilate(VImage image, int const maskWidth); + + /* + * Erode an image + */ + VImage Erode(VImage image, int const maskWidth); +} // namespace sharp + +#endif // SRC_OPERATIONS_H_ diff --git a/server/node_modules/sharp/src/pipeline.cc b/server/node_modules/sharp/src/pipeline.cc new file mode 100644 index 0000000..e2dd118 --- /dev/null +++ b/server/node_modules/sharp/src/pipeline.cc @@ -0,0 +1,1813 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "common.h" +#include "operations.h" +#include "pipeline.h" + +class PipelineWorker : public Napi::AsyncWorker { + public: + PipelineWorker(Napi::Function callback, PipelineBaton *baton, + Napi::Function debuglog, Napi::Function queueListener) : + Napi::AsyncWorker(callback), + baton(baton), + debuglog(Napi::Persistent(debuglog)), + queueListener(Napi::Persistent(queueListener)) {} + ~PipelineWorker() {} + + // libuv worker + void Execute() { + // Decrement queued task counter + sharp::counterQueue--; + // Increment processing task counter + sharp::counterProcess++; + + try { + // Open input + vips::VImage image; + sharp::ImageType inputImageType; + if (baton->join.empty()) { + std::tie(image, inputImageType) = sharp::OpenInput(baton->input); + } else { + std::vector images; + bool hasAlpha = false; + for (auto &join : baton->join) { + std::tie(image, inputImageType) = sharp::OpenInput(join); + image = sharp::EnsureColourspace(image, baton->colourspacePipeline); + images.push_back(image); + hasAlpha |= image.has_alpha(); + } + if (hasAlpha) { + for (auto &image : images) { + if (!image.has_alpha()) { + image = sharp::EnsureAlpha(image, 1); + } + } + } else { + baton->input->joinBackground.pop_back(); + } + inputImageType = sharp::ImageType::PNG; + image = VImage::arrayjoin(images, VImage::option() + ->set("across", baton->input->joinAcross) + ->set("shim", baton->input->joinShim) + ->set("background", baton->input->joinBackground) + ->set("halign", baton->input->joinHalign) + ->set("valign", baton->input->joinValign)); + if (baton->input->joinAnimated) { + image = image.copy(); + image.set(VIPS_META_N_PAGES, static_cast(images.size())); + image.set(VIPS_META_PAGE_HEIGHT, static_cast(image.height() / images.size())); + } + } + VipsAccess access = baton->input->access; + image = sharp::EnsureColourspace(image, baton->colourspacePipeline); + + int nPages = baton->input->pages; + if (nPages == -1) { + // Resolve the number of pages if we need to render until the end of the document + nPages = image.get_typeof(VIPS_META_N_PAGES) != 0 + ? image.get_int(VIPS_META_N_PAGES) - baton->input->page + : 1; + } + + // Get pre-resize page height + int pageHeight = sharp::GetPageHeight(image); + + // Calculate angle of rotation + VipsAngle rotation = VIPS_ANGLE_D0; + VipsAngle autoRotation = VIPS_ANGLE_D0; + bool autoFlop = false; + + if (baton->input->autoOrient) { + // Rotate and flip image according to Exif orientation + std::tie(autoRotation, autoFlop) = CalculateExifRotationAndFlop(sharp::ExifOrientation(image)); + } + + rotation = CalculateAngleRotation(baton->angle); + + bool const shouldRotateBefore = baton->rotateBefore && + (rotation != VIPS_ANGLE_D0 || baton->flip || baton->flop || baton->rotationAngle != 0.0); + bool const shouldOrientBefore = (shouldRotateBefore || baton->orientBefore) && + (autoRotation != VIPS_ANGLE_D0 || autoFlop); + + if (shouldOrientBefore) { + image = sharp::StaySequential(image, autoRotation != VIPS_ANGLE_D0); + if (autoRotation != VIPS_ANGLE_D0) { + if (autoRotation != VIPS_ANGLE_D180) { + MultiPageUnsupported(nPages, "Rotate"); + } + image = image.rot(autoRotation); + autoRotation = VIPS_ANGLE_D0; + } + if (autoFlop) { + image = image.flip(VIPS_DIRECTION_HORIZONTAL); + autoFlop = false; + } + } + + if (shouldRotateBefore) { + image = sharp::StaySequential(image, rotation != VIPS_ANGLE_D0 || baton->flip || baton->rotationAngle != 0.0); + if (baton->flip) { + image = image.flip(VIPS_DIRECTION_VERTICAL); + baton->flip = false; + } + if (baton->flop) { + image = image.flip(VIPS_DIRECTION_HORIZONTAL); + baton->flop = false; + } + if (rotation != VIPS_ANGLE_D0) { + if (rotation != VIPS_ANGLE_D180) { + MultiPageUnsupported(nPages, "Rotate"); + } + image = image.rot(rotation); + rotation = VIPS_ANGLE_D0; + } + if (baton->rotationAngle != 0.0) { + MultiPageUnsupported(nPages, "Rotate"); + std::vector background; + std::tie(image, background) = sharp::ApplyAlpha(image, baton->rotationBackground, false); + image = image.rotate(baton->rotationAngle, VImage::option()->set("background", background)).copy_memory(); + baton->rotationAngle = 0.0; + } + } + + // Trim + if (baton->trimThreshold >= 0.0) { + MultiPageUnsupported(nPages, "Trim"); + image = sharp::StaySequential(image); + image = sharp::Trim(image, baton->trimBackground, baton->trimThreshold, baton->trimLineArt); + baton->trimOffsetLeft = image.xoffset(); + baton->trimOffsetTop = image.yoffset(); + } + + // Pre extraction + if (baton->topOffsetPre != -1) { + image = nPages > 1 + ? sharp::CropMultiPage(image, + baton->leftOffsetPre, baton->topOffsetPre, baton->widthPre, baton->heightPre, nPages, &pageHeight) + : image.extract_area(baton->leftOffsetPre, baton->topOffsetPre, baton->widthPre, baton->heightPre); + } + + // Get pre-resize image width and height + int inputWidth = image.width(); + int inputHeight = image.height(); + + // Is there just one page? Shrink to inputHeight instead + if (nPages == 1) { + pageHeight = inputHeight; + } + + // Scaling calculations + double hshrink; + double vshrink; + int targetResizeWidth = baton->width; + int targetResizeHeight = baton->height; + + // When auto-rotating by 90 or 270 degrees, swap the target width and + // height to ensure the behavior aligns with how it would have been if + // the rotation had taken place *before* resizing. + if (autoRotation == VIPS_ANGLE_D90 || autoRotation == VIPS_ANGLE_D270) { + std::swap(targetResizeWidth, targetResizeHeight); + } + + // Shrink to pageHeight, so we work for multi-page images + std::tie(hshrink, vshrink) = sharp::ResolveShrink( + inputWidth, pageHeight, targetResizeWidth, targetResizeHeight, + baton->canvas, baton->withoutEnlargement, baton->withoutReduction); + + // The jpeg preload shrink. + int jpegShrinkOnLoad = 1; + + // WebP, PDF, SVG scale + double scale = 1.0; + + // Try to reload input using shrink-on-load for JPEG, WebP, SVG and PDF, when: + // - the width or height parameters are specified; + // - gamma correction doesn't need to be applied; + // - trimming or pre-resize extract isn't required; + // - input colourspace is not specified; + bool const shouldPreShrink = (targetResizeWidth > 0 || targetResizeHeight > 0) && + baton->gamma == 0 && baton->topOffsetPre == -1 && baton->trimThreshold < 0.0 && + baton->colourspacePipeline == VIPS_INTERPRETATION_LAST && !(shouldOrientBefore || shouldRotateBefore); + + if (shouldPreShrink) { + // The common part of the shrink: the bit by which both axes must be shrunk + double shrink = std::min(hshrink, vshrink); + + if (inputImageType == sharp::ImageType::JPEG) { + // Leave at least a factor of two for the final resize step, when fastShrinkOnLoad: false + // for more consistent results and to avoid extra sharpness to the image + int factor = baton->fastShrinkOnLoad ? 1 : 2; + if (shrink >= 8 * factor) { + jpegShrinkOnLoad = 8; + } else if (shrink >= 4 * factor) { + jpegShrinkOnLoad = 4; + } else if (shrink >= 2 * factor) { + jpegShrinkOnLoad = 2; + } + // Lower shrink-on-load for known libjpeg rounding errors + if (jpegShrinkOnLoad > 1 && static_cast(shrink) == jpegShrinkOnLoad) { + jpegShrinkOnLoad /= 2; + } + } else if (inputImageType == sharp::ImageType::WEBP && baton->fastShrinkOnLoad && shrink > 1.0) { + // Avoid upscaling via webp + scale = 1.0 / shrink; + } else if (inputImageType == sharp::ImageType::SVG || + inputImageType == sharp::ImageType::PDF) { + scale = 1.0 / shrink; + } + } + + // Reload input using shrink-on-load, it'll be an integer shrink + // factor for jpegload*, a double scale factor for webpload*, + // pdfload* and svgload* + if (jpegShrinkOnLoad > 1) { + vips::VOption *option = GetOptionsForImageType(inputImageType, baton->input)->set("shrink", jpegShrinkOnLoad); + if (baton->input->buffer != nullptr) { + // Reload JPEG buffer + VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength); + image = VImage::jpegload_buffer(blob, option); + vips_area_unref(reinterpret_cast(blob)); + } else { + // Reload JPEG file + image = VImage::jpegload(const_cast(baton->input->file.data()), option); + } + } else if (scale != 1.0) { + vips::VOption *option = GetOptionsForImageType(inputImageType, baton->input)->set("scale", scale); + if (inputImageType == sharp::ImageType::WEBP) { + if (baton->input->buffer != nullptr) { + // Reload WebP buffer + VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength); + image = VImage::webpload_buffer(blob, option); + vips_area_unref(reinterpret_cast(blob)); + } else { + // Reload WebP file + image = VImage::webpload(const_cast(baton->input->file.data()), option); + } + } else if (inputImageType == sharp::ImageType::SVG) { + if (baton->input->buffer != nullptr) { + // Reload SVG buffer + VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength); + image = VImage::svgload_buffer(blob, option); + vips_area_unref(reinterpret_cast(blob)); + } else { + // Reload SVG file + image = VImage::svgload(const_cast(baton->input->file.data()), option); + } + sharp::SetDensity(image, baton->input->density); + if (image.width() > 32767 || image.height() > 32767) { + throw vips::VError("Input SVG image will exceed 32767x32767 pixel limit when scaled"); + } + } else if (inputImageType == sharp::ImageType::PDF) { + if (baton->input->buffer != nullptr) { + // Reload PDF buffer + VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength); + image = VImage::pdfload_buffer(blob, option); + vips_area_unref(reinterpret_cast(blob)); + } else { + // Reload PDF file + image = VImage::pdfload(const_cast(baton->input->file.data()), option); + } + sharp::SetDensity(image, baton->input->density); + } + } else { + if (inputImageType == sharp::ImageType::SVG && (image.width() > 32767 || image.height() > 32767)) { + throw vips::VError("Input SVG image exceeds 32767x32767 pixel limit"); + } + } + if (baton->input->autoOrient) { + image = sharp::RemoveExifOrientation(image); + } + + // Any pre-shrinking may already have been done + inputWidth = image.width(); + inputHeight = image.height(); + + // After pre-shrink, but before the main shrink stage + // Reuse the initial pageHeight if we didn't pre-shrink + if (shouldPreShrink) { + pageHeight = sharp::GetPageHeight(image); + } + + // Shrink to pageHeight, so we work for multi-page images + std::tie(hshrink, vshrink) = sharp::ResolveShrink( + inputWidth, pageHeight, targetResizeWidth, targetResizeHeight, + baton->canvas, baton->withoutEnlargement, baton->withoutReduction); + + int targetHeight = static_cast(std::rint(static_cast(pageHeight) / vshrink)); + int targetPageHeight = targetHeight; + + // In toilet-roll mode, we must adjust vshrink so that we exactly hit + // pageHeight or we'll have pixels straddling pixel boundaries + if (inputHeight > pageHeight) { + targetHeight *= nPages; + vshrink = static_cast(inputHeight) / targetHeight; + } + + // Ensure we're using a device-independent colour space + std::pair inputProfile(nullptr, 0); + if ((baton->keepMetadata & VIPS_FOREIGN_KEEP_ICC) && baton->withIccProfile.empty()) { + // Cache input profile for use with output + inputProfile = sharp::GetProfile(image); + baton->input->ignoreIcc = true; + } + char const *processingProfile = image.interpretation() == VIPS_INTERPRETATION_RGB16 ? "p3" : "srgb"; + if ( + sharp::HasProfile(image) && + image.interpretation() != VIPS_INTERPRETATION_LABS && + image.interpretation() != VIPS_INTERPRETATION_GREY16 && + baton->colourspacePipeline != VIPS_INTERPRETATION_CMYK && + !baton->input->ignoreIcc + ) { + // Convert to sRGB/P3 using embedded profile + try { + image = image.icc_transform(processingProfile, VImage::option() + ->set("embedded", true) + ->set("depth", sharp::Is16Bit(image.interpretation()) ? 16 : 8) + ->set("intent", VIPS_INTENT_PERCEPTUAL)); + } catch(...) { + sharp::VipsWarningCallback(nullptr, G_LOG_LEVEL_WARNING, "Invalid embedded profile", nullptr); + } + } else if ( + image.interpretation() == VIPS_INTERPRETATION_CMYK && + baton->colourspacePipeline != VIPS_INTERPRETATION_CMYK + ) { + image = image.icc_transform(processingProfile, VImage::option() + ->set("input_profile", "cmyk") + ->set("intent", VIPS_INTENT_PERCEPTUAL)); + } + + // Flatten image to remove alpha channel + if (baton->flatten && image.has_alpha()) { + image = sharp::Flatten(image, baton->flattenBackground); + } + + // Gamma encoding (darken) + if (baton->gamma >= 1 && baton->gamma <= 3) { + image = sharp::Gamma(image, 1.0 / baton->gamma); + } + + // Convert to greyscale (linear, therefore after gamma encoding, if any) + if (baton->greyscale) { + image = image.colourspace(VIPS_INTERPRETATION_B_W); + } + + bool const shouldResize = hshrink != 1.0 || vshrink != 1.0; + bool const shouldBlur = baton->blurSigma != 0.0; + bool const shouldConv = baton->convKernelWidth * baton->convKernelHeight > 0; + bool const shouldSharpen = baton->sharpenSigma != 0.0; + bool const shouldComposite = !baton->composite.empty(); + + if (shouldComposite && !image.has_alpha()) { + image = sharp::EnsureAlpha(image, 1); + } + + VipsBandFormat premultiplyFormat = image.format(); + bool const shouldPremultiplyAlpha = image.has_alpha() && + (shouldResize || shouldBlur || shouldConv || shouldSharpen); + + if (shouldPremultiplyAlpha) { + image = image.premultiply().cast(premultiplyFormat); + } + + // Resize + if (shouldResize) { + image = image.resize(1.0 / hshrink, VImage::option() + ->set("vscale", 1.0 / vshrink) + ->set("kernel", baton->kernel)); + } + + image = sharp::StaySequential(image, + autoRotation != VIPS_ANGLE_D0 || + baton->flip || + rotation != VIPS_ANGLE_D0); + // Auto-rotate post-extract + if (autoRotation != VIPS_ANGLE_D0) { + if (autoRotation != VIPS_ANGLE_D180) { + MultiPageUnsupported(nPages, "Rotate"); + } + image = image.rot(autoRotation); + } + // Mirror vertically (up-down) about the x-axis + if (baton->flip) { + image = image.flip(VIPS_DIRECTION_VERTICAL); + } + // Mirror horizontally (left-right) about the y-axis + if (baton->flop != autoFlop) { + image = image.flip(VIPS_DIRECTION_HORIZONTAL); + } + // Rotate post-extract 90-angle + if (rotation != VIPS_ANGLE_D0) { + if (rotation != VIPS_ANGLE_D180) { + MultiPageUnsupported(nPages, "Rotate"); + } + image = image.rot(rotation); + } + + // Join additional color channels to the image + if (!baton->joinChannelIn.empty()) { + VImage joinImage; + sharp::ImageType joinImageType = sharp::ImageType::UNKNOWN; + + for (unsigned int i = 0; i < baton->joinChannelIn.size(); i++) { + baton->joinChannelIn[i]->access = access; + std::tie(joinImage, joinImageType) = sharp::OpenInput(baton->joinChannelIn[i]); + joinImage = sharp::EnsureColourspace(joinImage, baton->colourspacePipeline); + image = image.bandjoin(joinImage); + } + image = image.copy(VImage::option()->set("interpretation", baton->colourspace)); + image = sharp::RemoveGifPalette(image); + } + + inputWidth = image.width(); + inputHeight = nPages > 1 ? targetPageHeight : image.height(); + + // Resolve dimensions + if (baton->width <= 0) { + baton->width = inputWidth; + } + if (baton->height <= 0) { + baton->height = inputHeight; + } + + // Crop/embed + if (inputWidth != baton->width || inputHeight != baton->height) { + if (baton->canvas == sharp::Canvas::EMBED) { + std::vector background; + std::tie(image, background) = sharp::ApplyAlpha(image, baton->resizeBackground, shouldPremultiplyAlpha); + + // Embed + int left; + int top; + std::tie(left, top) = sharp::CalculateEmbedPosition( + inputWidth, inputHeight, baton->width, baton->height, baton->position); + int width = std::max(inputWidth, baton->width); + int height = std::max(inputHeight, baton->height); + + image = nPages > 1 + ? sharp::EmbedMultiPage(image, + left, top, width, height, VIPS_EXTEND_BACKGROUND, background, nPages, &targetPageHeight) + : image.embed(left, top, width, height, VImage::option() + ->set("extend", VIPS_EXTEND_BACKGROUND) + ->set("background", background)); + } else if (baton->canvas == sharp::Canvas::CROP) { + if (baton->width > inputWidth) { + baton->width = inputWidth; + } + if (baton->height > inputHeight) { + baton->height = inputHeight; + } + + // Crop + if (baton->position < 9) { + // Gravity-based crop + int left; + int top; + + std::tie(left, top) = sharp::CalculateCrop( + inputWidth, inputHeight, baton->width, baton->height, baton->position); + int width = std::min(inputWidth, baton->width); + int height = std::min(inputHeight, baton->height); + + image = nPages > 1 + ? sharp::CropMultiPage(image, + left, top, width, height, nPages, &targetPageHeight) + : image.extract_area(left, top, width, height); + } else { + int attention_x; + int attention_y; + + // Attention-based or Entropy-based crop + MultiPageUnsupported(nPages, "Resize strategy"); + image = sharp::StaySequential(image); + image = image.smartcrop(baton->width, baton->height, VImage::option() + ->set("interesting", baton->position == 16 ? VIPS_INTERESTING_ENTROPY : VIPS_INTERESTING_ATTENTION) + ->set("premultiplied", shouldPremultiplyAlpha) + ->set("attention_x", &attention_x) + ->set("attention_y", &attention_y)); + baton->hasCropOffset = true; + baton->cropOffsetLeft = static_cast(image.xoffset()); + baton->cropOffsetTop = static_cast(image.yoffset()); + baton->hasAttentionCenter = true; + baton->attentionX = static_cast(attention_x * jpegShrinkOnLoad / scale); + baton->attentionY = static_cast(attention_y * jpegShrinkOnLoad / scale); + } + } + } + + // Rotate post-extract non-90 angle + if (!baton->rotateBefore && baton->rotationAngle != 0.0) { + MultiPageUnsupported(nPages, "Rotate"); + image = sharp::StaySequential(image); + std::vector background; + std::tie(image, background) = sharp::ApplyAlpha(image, baton->rotationBackground, shouldPremultiplyAlpha); + image = image.rotate(baton->rotationAngle, VImage::option()->set("background", background)); + } + + // Post extraction + if (baton->topOffsetPost != -1) { + if (nPages > 1) { + image = sharp::CropMultiPage(image, + baton->leftOffsetPost, baton->topOffsetPost, baton->widthPost, baton->heightPost, + nPages, &targetPageHeight); + + // heightPost is used in the info object, so update to reflect the number of pages + baton->heightPost *= nPages; + } else { + image = image.extract_area( + baton->leftOffsetPost, baton->topOffsetPost, baton->widthPost, baton->heightPost); + } + } + + // Affine transform + if (!baton->affineMatrix.empty()) { + MultiPageUnsupported(nPages, "Affine"); + image = sharp::StaySequential(image); + std::vector background; + std::tie(image, background) = sharp::ApplyAlpha(image, baton->affineBackground, shouldPremultiplyAlpha); + vips::VInterpolate interp = vips::VInterpolate::new_from_name( + const_cast(baton->affineInterpolator.data())); + image = image.affine(baton->affineMatrix, VImage::option()->set("background", background) + ->set("idx", baton->affineIdx) + ->set("idy", baton->affineIdy) + ->set("odx", baton->affineOdx) + ->set("ody", baton->affineOdy) + ->set("interpolate", interp)); + } + + // Extend edges + if (baton->extendTop > 0 || baton->extendBottom > 0 || baton->extendLeft > 0 || baton->extendRight > 0) { + // Embed + baton->width = image.width() + baton->extendLeft + baton->extendRight; + baton->height = (nPages > 1 ? targetPageHeight : image.height()) + baton->extendTop + baton->extendBottom; + + if (baton->extendWith == VIPS_EXTEND_BACKGROUND) { + std::vector background; + std::tie(image, background) = sharp::ApplyAlpha(image, baton->extendBackground, shouldPremultiplyAlpha); + + image = sharp::StaySequential(image, nPages > 1); + image = nPages > 1 + ? sharp::EmbedMultiPage(image, + baton->extendLeft, baton->extendTop, baton->width, baton->height, + baton->extendWith, background, nPages, &targetPageHeight) + : image.embed(baton->extendLeft, baton->extendTop, baton->width, baton->height, + VImage::option()->set("extend", baton->extendWith)->set("background", background)); + } else { + std::vector ignoredBackground(1); + image = sharp::StaySequential(image); + image = nPages > 1 + ? sharp::EmbedMultiPage(image, + baton->extendLeft, baton->extendTop, baton->width, baton->height, + baton->extendWith, ignoredBackground, nPages, &targetPageHeight) + : image.embed(baton->extendLeft, baton->extendTop, baton->width, baton->height, + VImage::option()->set("extend", baton->extendWith)); + } + } + // Median - must happen before blurring, due to the utility of blurring after thresholding + if (baton->medianSize > 0) { + image = image.median(baton->medianSize); + } + + // Threshold - must happen before blurring, due to the utility of blurring after thresholding + // Threshold - must happen before unflatten to enable non-white unflattening + if (baton->threshold != 0) { + image = sharp::Threshold(image, baton->threshold, baton->thresholdGrayscale); + } + + // Dilate - must happen before blurring, due to the utility of dilating after thresholding + if (baton->dilateWidth != 0) { + image = sharp::Dilate(image, baton->dilateWidth); + } + + // Erode - must happen before blurring, due to the utility of eroding after thresholding + if (baton->erodeWidth != 0) { + image = sharp::Erode(image, baton->erodeWidth); + } + + // Blur + if (shouldBlur) { + image = sharp::Blur(image, baton->blurSigma, baton->precision, baton->minAmpl); + } + + // Unflatten the image + if (baton->unflatten) { + image = sharp::Unflatten(image); + } + + // Convolve + if (shouldConv) { + image = sharp::Convolve(image, + baton->convKernelWidth, baton->convKernelHeight, + baton->convKernelScale, baton->convKernelOffset, + baton->convKernel); + } + + // Recomb + if (!baton->recombMatrix.empty()) { + image = sharp::Recomb(image, baton->recombMatrix); + } + + // Modulate + if (baton->brightness != 1.0 || baton->saturation != 1.0 || baton->hue != 0.0 || baton->lightness != 0.0) { + image = sharp::Modulate(image, baton->brightness, baton->saturation, baton->hue, baton->lightness); + } + + // Sharpen + if (shouldSharpen) { + image = sharp::Sharpen(image, baton->sharpenSigma, baton->sharpenM1, baton->sharpenM2, + baton->sharpenX1, baton->sharpenY2, baton->sharpenY3); + } + + // Reverse premultiplication after all transformations + if (shouldPremultiplyAlpha) { + image = image.unpremultiply().cast(premultiplyFormat); + } + baton->premultiplied = shouldPremultiplyAlpha; + + // Composite + if (shouldComposite) { + std::vector images = { image }; + std::vector modes, xs, ys; + for (Composite *composite : baton->composite) { + VImage compositeImage; + sharp::ImageType compositeImageType = sharp::ImageType::UNKNOWN; + composite->input->access = access; + std::tie(compositeImage, compositeImageType) = sharp::OpenInput(composite->input); + + if (composite->input->autoOrient) { + // Respect EXIF Orientation + VipsAngle compositeAutoRotation = VIPS_ANGLE_D0; + bool compositeAutoFlop = false; + std::tie(compositeAutoRotation, compositeAutoFlop) = + CalculateExifRotationAndFlop(sharp::ExifOrientation(compositeImage)); + + compositeImage = sharp::RemoveExifOrientation(compositeImage); + compositeImage = sharp::StaySequential(compositeImage, compositeAutoRotation != VIPS_ANGLE_D0); + + if (compositeAutoRotation != VIPS_ANGLE_D0) { + compositeImage = compositeImage.rot(compositeAutoRotation); + } + if (compositeAutoFlop) { + compositeImage = compositeImage.flip(VIPS_DIRECTION_HORIZONTAL); + } + } + + // Verify within current dimensions + if (compositeImage.width() > image.width() || compositeImage.height() > image.height()) { + throw vips::VError("Image to composite must have same dimensions or smaller"); + } + // Check if overlay is tiled + if (composite->tile) { + int across = 0; + int down = 0; + // Use gravity in overlay + if (compositeImage.width() <= image.width()) { + across = static_cast(ceil(static_cast(image.width()) / compositeImage.width())); + // Ensure odd number of tiles across when gravity is centre, north or south + if (composite->gravity == 0 || composite->gravity == 1 || composite->gravity == 3) { + across |= 1; + } + } + if (compositeImage.height() <= image.height()) { + down = static_cast(ceil(static_cast(image.height()) / compositeImage.height())); + // Ensure odd number of tiles down when gravity is centre, east or west + if (composite->gravity == 0 || composite->gravity == 2 || composite->gravity == 4) { + down |= 1; + } + } + if (across != 0 || down != 0) { + int left; + int top; + compositeImage = sharp::StaySequential(compositeImage).replicate(across, down); + if (composite->hasOffset) { + std::tie(left, top) = sharp::CalculateCrop( + compositeImage.width(), compositeImage.height(), image.width(), image.height(), + composite->left, composite->top); + } else { + std::tie(left, top) = sharp::CalculateCrop( + compositeImage.width(), compositeImage.height(), image.width(), image.height(), composite->gravity); + } + compositeImage = compositeImage.extract_area(left, top, image.width(), image.height()); + } + // gravity was used for extract_area, set it back to its default value of 0 + composite->gravity = 0; + } + // Ensure image to composite is with unpremultiplied alpha + compositeImage = sharp::EnsureAlpha(compositeImage, 1); + if (composite->premultiplied) compositeImage = compositeImage.unpremultiply(); + // Calculate position + int left; + int top; + if (composite->hasOffset) { + // Composite image at given offsets + if (composite->tile) { + std::tie(left, top) = sharp::CalculateCrop(image.width(), image.height(), + compositeImage.width(), compositeImage.height(), composite->left, composite->top); + } else { + left = composite->left; + top = composite->top; + } + } else { + // Composite image with given gravity + std::tie(left, top) = sharp::CalculateCrop(image.width(), image.height(), + compositeImage.width(), compositeImage.height(), composite->gravity); + } + images.push_back(compositeImage); + modes.push_back(composite->mode); + xs.push_back(left); + ys.push_back(top); + } + image = VImage::composite(images, modes, VImage::option() + ->set("compositing_space", baton->colourspacePipeline == VIPS_INTERPRETATION_LAST + ? VIPS_INTERPRETATION_sRGB + : baton->colourspacePipeline) + ->set("x", xs) + ->set("y", ys)); + image = sharp::RemoveGifPalette(image); + } + + // Gamma decoding (brighten) + if (baton->gammaOut >= 1 && baton->gammaOut <= 3) { + image = sharp::Gamma(image, baton->gammaOut); + } + + // Linear adjustment (a * in + b) + if (!baton->linearA.empty()) { + image = sharp::Linear(image, baton->linearA, baton->linearB); + } + + // Apply normalisation - stretch luminance to cover full dynamic range + if (baton->normalise) { + image = sharp::StaySequential(image); + image = sharp::Normalise(image, baton->normaliseLower, baton->normaliseUpper); + } + + // Apply contrast limiting adaptive histogram equalization (CLAHE) + if (baton->claheWidth != 0 && baton->claheHeight != 0) { + image = sharp::StaySequential(image); + image = sharp::Clahe(image, baton->claheWidth, baton->claheHeight, baton->claheMaxSlope); + } + + // Apply bitwise boolean operation between images + if (baton->boolean != nullptr) { + VImage booleanImage; + sharp::ImageType booleanImageType = sharp::ImageType::UNKNOWN; + baton->boolean->access = access; + std::tie(booleanImage, booleanImageType) = sharp::OpenInput(baton->boolean); + booleanImage = sharp::EnsureColourspace(booleanImage, baton->colourspacePipeline); + image = sharp::Boolean(image, booleanImage, baton->booleanOp); + image = sharp::RemoveGifPalette(image); + } + + // Apply per-channel Bandbool bitwise operations after all other operations + if (baton->bandBoolOp >= VIPS_OPERATION_BOOLEAN_AND && baton->bandBoolOp < VIPS_OPERATION_BOOLEAN_LAST) { + image = sharp::Bandbool(image, baton->bandBoolOp); + } + + // Tint the image + if (baton->tint[0] >= 0.0) { + image = sharp::Tint(image, baton->tint); + } + + // Remove alpha channel, if any + if (baton->removeAlpha) { + image = sharp::RemoveAlpha(image); + } + + // Ensure alpha channel, if missing + if (baton->ensureAlpha != -1) { + image = sharp::EnsureAlpha(image, baton->ensureAlpha); + } + + // Convert image to sRGB, if not already + if (sharp::Is16Bit(image.interpretation())) { + image = image.cast(VIPS_FORMAT_USHORT); + } + if (image.interpretation() != baton->colourspace) { + // Convert colourspace, pass the current known interpretation so libvips doesn't have to guess + image = image.colourspace(baton->colourspace, VImage::option()->set("source_space", image.interpretation())); + // Transform colours from embedded profile to output profile + if ((baton->keepMetadata & VIPS_FOREIGN_KEEP_ICC) && baton->colourspacePipeline != VIPS_INTERPRETATION_CMYK && + baton->withIccProfile.empty() && sharp::HasProfile(image)) { + image = image.icc_transform(processingProfile, VImage::option() + ->set("embedded", true) + ->set("depth", sharp::Is16Bit(image.interpretation()) ? 16 : 8) + ->set("intent", VIPS_INTENT_PERCEPTUAL)); + } + } + + // Extract channel + if (baton->extractChannel > -1) { + if (baton->extractChannel >= image.bands()) { + if (baton->extractChannel == 3 && image.has_alpha()) { + baton->extractChannel = image.bands() - 1; + } else { + (baton->err) + .append("Cannot extract channel ").append(std::to_string(baton->extractChannel)) + .append(" from image with channels 0-").append(std::to_string(image.bands() - 1)); + return Error(); + } + } + VipsInterpretation colourspace = sharp::Is16Bit(image.interpretation()) + ? VIPS_INTERPRETATION_GREY16 + : VIPS_INTERPRETATION_B_W; + image = image + .extract_band(baton->extractChannel) + .copy(VImage::option()->set("interpretation", colourspace)); + } + + // Apply output ICC profile + if (!baton->withIccProfile.empty()) { + try { + image = image.icc_transform(const_cast(baton->withIccProfile.data()), VImage::option() + ->set("input_profile", processingProfile) + ->set("embedded", true) + ->set("depth", sharp::Is16Bit(image.interpretation()) ? 16 : 8) + ->set("intent", VIPS_INTENT_PERCEPTUAL)); + } catch(...) { + sharp::VipsWarningCallback(nullptr, G_LOG_LEVEL_WARNING, "Invalid profile", nullptr); + } + } else if (baton->keepMetadata & VIPS_FOREIGN_KEEP_ICC) { + image = sharp::SetProfile(image, inputProfile); + } + + // Negate the colours in the image + if (baton->negate) { + image = sharp::Negate(image, baton->negateAlpha); + } + + // Override EXIF Orientation tag + if (baton->withMetadataOrientation != -1) { + image = sharp::SetExifOrientation(image, baton->withMetadataOrientation); + } + // Override pixel density + if (baton->withMetadataDensity > 0) { + image = sharp::SetDensity(image, baton->withMetadataDensity); + } + // EXIF key/value pairs + if (baton->keepMetadata & VIPS_FOREIGN_KEEP_EXIF) { + image = image.copy(); + if (!baton->withExifMerge) { + image = sharp::RemoveExif(image); + } + for (const auto& s : baton->withExif) { + image.set(s.first.data(), s.second.data()); + } + } + // XMP buffer + if ((baton->keepMetadata & VIPS_FOREIGN_KEEP_XMP) && !baton->withXmp.empty()) { + image = image.copy(); + image.set(VIPS_META_XMP_NAME, nullptr, + const_cast(static_cast(baton->withXmp.c_str())), baton->withXmp.size()); + } + // Number of channels used in output image + baton->channels = image.bands(); + baton->width = image.width(); + baton->height = image.height(); + + image = sharp::SetAnimationProperties( + image, nPages, targetPageHeight, baton->delay, baton->loop); + + if (image.get_typeof(VIPS_META_PAGE_HEIGHT) == G_TYPE_INT) { + baton->pageHeightOut = image.get_int(VIPS_META_PAGE_HEIGHT); + baton->pagesOut = image.get_int(VIPS_META_N_PAGES); + } + + // Output + sharp::SetTimeout(image, baton->timeoutSeconds); + if (baton->fileOut.empty()) { + // Buffer output + if (baton->formatOut == "jpeg" || (baton->formatOut == "input" && inputImageType == sharp::ImageType::JPEG)) { + // Write JPEG to buffer + sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG); + VipsArea *area = reinterpret_cast(image.jpegsave_buffer(VImage::option() + ->set("keep", baton->keepMetadata) + ->set("Q", baton->jpegQuality) + ->set("interlace", baton->jpegProgressive) + ->set("subsample_mode", baton->jpegChromaSubsampling == "4:4:4" + ? VIPS_FOREIGN_SUBSAMPLE_OFF + : VIPS_FOREIGN_SUBSAMPLE_ON) + ->set("trellis_quant", baton->jpegTrellisQuantisation) + ->set("quant_table", baton->jpegQuantisationTable) + ->set("overshoot_deringing", baton->jpegOvershootDeringing) + ->set("optimize_scans", baton->jpegOptimiseScans) + ->set("optimize_coding", baton->jpegOptimiseCoding))); + baton->bufferOut = static_cast(area->data); + baton->bufferOutLength = area->length; + area->free_fn = nullptr; + vips_area_unref(area); + baton->formatOut = "jpeg"; + if (baton->colourspace == VIPS_INTERPRETATION_CMYK) { + baton->channels = std::min(baton->channels, 4); + } else { + baton->channels = std::min(baton->channels, 3); + } + } else if (baton->formatOut == "jp2" || (baton->formatOut == "input" + && inputImageType == sharp::ImageType::JP2)) { + // Write JP2 to Buffer + sharp::AssertImageTypeDimensions(image, sharp::ImageType::JP2); + VipsArea *area = reinterpret_cast(image.jp2ksave_buffer(VImage::option() + ->set("Q", baton->jp2Quality) + ->set("lossless", baton->jp2Lossless) + ->set("subsample_mode", baton->jp2ChromaSubsampling == "4:4:4" + ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON) + ->set("tile_height", baton->jp2TileHeight) + ->set("tile_width", baton->jp2TileWidth))); + baton->bufferOut = static_cast(area->data); + baton->bufferOutLength = area->length; + area->free_fn = nullptr; + vips_area_unref(area); + baton->formatOut = "jp2"; + } else if (baton->formatOut == "png" || (baton->formatOut == "input" && + (inputImageType == sharp::ImageType::PNG || inputImageType == sharp::ImageType::SVG))) { + // Write PNG to buffer + sharp::AssertImageTypeDimensions(image, sharp::ImageType::PNG); + VipsArea *area = reinterpret_cast(image.pngsave_buffer(VImage::option() + ->set("keep", baton->keepMetadata) + ->set("interlace", baton->pngProgressive) + ->set("compression", baton->pngCompressionLevel) + ->set("filter", baton->pngAdaptiveFiltering ? VIPS_FOREIGN_PNG_FILTER_ALL : VIPS_FOREIGN_PNG_FILTER_NONE) + ->set("palette", baton->pngPalette) + ->set("Q", baton->pngQuality) + ->set("effort", baton->pngEffort) + ->set("bitdepth", sharp::Is16Bit(image.interpretation()) ? 16 : baton->pngBitdepth) + ->set("dither", baton->pngDither))); + baton->bufferOut = static_cast(area->data); + baton->bufferOutLength = area->length; + area->free_fn = nullptr; + vips_area_unref(area); + baton->formatOut = "png"; + } else if (baton->formatOut == "webp" || + (baton->formatOut == "input" && inputImageType == sharp::ImageType::WEBP)) { + // Write WEBP to buffer + sharp::AssertImageTypeDimensions(image, sharp::ImageType::WEBP); + VipsArea *area = reinterpret_cast(image.webpsave_buffer(VImage::option() + ->set("keep", baton->keepMetadata) + ->set("Q", baton->webpQuality) + ->set("lossless", baton->webpLossless) + ->set("near_lossless", baton->webpNearLossless) + ->set("smart_subsample", baton->webpSmartSubsample) + ->set("smart_deblock", baton->webpSmartDeblock) + ->set("preset", baton->webpPreset) + ->set("effort", baton->webpEffort) + ->set("min_size", baton->webpMinSize) + ->set("mixed", baton->webpMixed) + ->set("alpha_q", baton->webpAlphaQuality))); + baton->bufferOut = static_cast(area->data); + baton->bufferOutLength = area->length; + area->free_fn = nullptr; + vips_area_unref(area); + baton->formatOut = "webp"; + } else if (baton->formatOut == "gif" || + (baton->formatOut == "input" && inputImageType == sharp::ImageType::GIF)) { + // Write GIF to buffer + sharp::AssertImageTypeDimensions(image, sharp::ImageType::GIF); + VipsArea *area = reinterpret_cast(image.gifsave_buffer(VImage::option() + ->set("keep", baton->keepMetadata) + ->set("bitdepth", baton->gifBitdepth) + ->set("effort", baton->gifEffort) + ->set("reuse", baton->gifReuse) + ->set("interlace", baton->gifProgressive) + ->set("interframe_maxerror", baton->gifInterFrameMaxError) + ->set("interpalette_maxerror", baton->gifInterPaletteMaxError) + ->set("keep_duplicate_frames", baton->gifKeepDuplicateFrames) + ->set("dither", baton->gifDither))); + baton->bufferOut = static_cast(area->data); + baton->bufferOutLength = area->length; + area->free_fn = nullptr; + vips_area_unref(area); + baton->formatOut = "gif"; + } else if (baton->formatOut == "tiff" || + (baton->formatOut == "input" && inputImageType == sharp::ImageType::TIFF)) { + // Write TIFF to buffer + if (baton->tiffCompression == VIPS_FOREIGN_TIFF_COMPRESSION_JPEG) { + sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG); + baton->channels = std::min(baton->channels, 3); + } + // Cast pixel values to float, if required + if (baton->tiffPredictor == VIPS_FOREIGN_TIFF_PREDICTOR_FLOAT) { + image = image.cast(VIPS_FORMAT_FLOAT); + } + VipsArea *area = reinterpret_cast(image.tiffsave_buffer(VImage::option() + ->set("keep", baton->keepMetadata) + ->set("Q", baton->tiffQuality) + ->set("bitdepth", baton->tiffBitdepth) + ->set("compression", baton->tiffCompression) + ->set("miniswhite", baton->tiffMiniswhite) + ->set("predictor", baton->tiffPredictor) + ->set("pyramid", baton->tiffPyramid) + ->set("tile", baton->tiffTile) + ->set("tile_height", baton->tiffTileHeight) + ->set("tile_width", baton->tiffTileWidth) + ->set("xres", baton->tiffXres) + ->set("yres", baton->tiffYres) + ->set("resunit", baton->tiffResolutionUnit))); + baton->bufferOut = static_cast(area->data); + baton->bufferOutLength = area->length; + area->free_fn = nullptr; + vips_area_unref(area); + baton->formatOut = "tiff"; + } else if (baton->formatOut == "heif" || + (baton->formatOut == "input" && inputImageType == sharp::ImageType::HEIF)) { + // Write HEIF to buffer + sharp::AssertImageTypeDimensions(image, sharp::ImageType::HEIF); + image = sharp::RemoveAnimationProperties(image); + VipsArea *area = reinterpret_cast(image.heifsave_buffer(VImage::option() + ->set("keep", baton->keepMetadata) + ->set("Q", baton->heifQuality) + ->set("compression", baton->heifCompression) + ->set("effort", baton->heifEffort) + ->set("bitdepth", baton->heifBitdepth) + ->set("subsample_mode", baton->heifChromaSubsampling == "4:4:4" + ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON) + ->set("lossless", baton->heifLossless))); + baton->bufferOut = static_cast(area->data); + baton->bufferOutLength = area->length; + area->free_fn = nullptr; + vips_area_unref(area); + baton->formatOut = "heif"; + } else if (baton->formatOut == "dz") { + // Write DZ to buffer + baton->tileContainer = VIPS_FOREIGN_DZ_CONTAINER_ZIP; + if (!image.has_alpha()) { + baton->tileBackground.pop_back(); + } + image = sharp::StaySequential(image, baton->tileAngle != 0); + vips::VOption *options = BuildOptionsDZ(baton); + VipsArea *area = reinterpret_cast(image.dzsave_buffer(options)); + baton->bufferOut = static_cast(area->data); + baton->bufferOutLength = area->length; + area->free_fn = nullptr; + vips_area_unref(area); + baton->formatOut = "dz"; + } else if (baton->formatOut == "jxl" || + (baton->formatOut == "input" && inputImageType == sharp::ImageType::JXL)) { + // Write JXL to buffer + image = sharp::RemoveAnimationProperties(image); + VipsArea *area = reinterpret_cast(image.jxlsave_buffer(VImage::option() + ->set("keep", baton->keepMetadata) + ->set("distance", baton->jxlDistance) + ->set("tier", baton->jxlDecodingTier) + ->set("effort", baton->jxlEffort) + ->set("lossless", baton->jxlLossless))); + baton->bufferOut = static_cast(area->data); + baton->bufferOutLength = area->length; + area->free_fn = nullptr; + vips_area_unref(area); + baton->formatOut = "jxl"; + } else if (baton->formatOut == "raw" || + (baton->formatOut == "input" && inputImageType == sharp::ImageType::RAW)) { + // Write raw, uncompressed image data to buffer + if (baton->greyscale || image.interpretation() == VIPS_INTERPRETATION_B_W) { + // Extract first band for greyscale image + image = image[0]; + baton->channels = 1; + } + if (image.format() != baton->rawDepth) { + // Cast pixels to requested format + image = image.cast(baton->rawDepth); + } + // Get raw image data + baton->bufferOut = static_cast(image.write_to_memory(&baton->bufferOutLength)); + if (baton->bufferOut == nullptr) { + (baton->err).append("Could not allocate enough memory for raw output"); + return Error(); + } + baton->formatOut = "raw"; + } else { + // Unsupported output format + (baton->err).append("Unsupported output format "); + if (baton->formatOut == "input") { + (baton->err).append("when trying to match input format of "); + (baton->err).append(ImageTypeId(inputImageType)); + } else { + (baton->err).append(baton->formatOut); + } + return Error(); + } + } else { + // File output + bool const isJpeg = sharp::IsJpeg(baton->fileOut); + bool const isPng = sharp::IsPng(baton->fileOut); + bool const isWebp = sharp::IsWebp(baton->fileOut); + bool const isGif = sharp::IsGif(baton->fileOut); + bool const isTiff = sharp::IsTiff(baton->fileOut); + bool const isJp2 = sharp::IsJp2(baton->fileOut); + bool const isHeif = sharp::IsHeif(baton->fileOut); + bool const isJxl = sharp::IsJxl(baton->fileOut); + bool const isDz = sharp::IsDz(baton->fileOut); + bool const isDzZip = sharp::IsDzZip(baton->fileOut); + bool const isV = sharp::IsV(baton->fileOut); + bool const mightMatchInput = baton->formatOut == "input"; + bool const willMatchInput = mightMatchInput && + !(isJpeg || isPng || isWebp || isGif || isTiff || isJp2 || isHeif || isDz || isDzZip || isV); + + if (baton->formatOut == "jpeg" || (mightMatchInput && isJpeg) || + (willMatchInput && inputImageType == sharp::ImageType::JPEG)) { + // Write JPEG to file + sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG); + image.jpegsave(const_cast(baton->fileOut.data()), VImage::option() + ->set("keep", baton->keepMetadata) + ->set("Q", baton->jpegQuality) + ->set("interlace", baton->jpegProgressive) + ->set("subsample_mode", baton->jpegChromaSubsampling == "4:4:4" + ? VIPS_FOREIGN_SUBSAMPLE_OFF + : VIPS_FOREIGN_SUBSAMPLE_ON) + ->set("trellis_quant", baton->jpegTrellisQuantisation) + ->set("quant_table", baton->jpegQuantisationTable) + ->set("overshoot_deringing", baton->jpegOvershootDeringing) + ->set("optimize_scans", baton->jpegOptimiseScans) + ->set("optimize_coding", baton->jpegOptimiseCoding)); + baton->formatOut = "jpeg"; + baton->channels = std::min(baton->channels, 3); + } else if (baton->formatOut == "jp2" || (mightMatchInput && isJp2) || + (willMatchInput && (inputImageType == sharp::ImageType::JP2))) { + // Write JP2 to file + sharp::AssertImageTypeDimensions(image, sharp::ImageType::JP2); + image.jp2ksave(const_cast(baton->fileOut.data()), VImage::option() + ->set("Q", baton->jp2Quality) + ->set("lossless", baton->jp2Lossless) + ->set("subsample_mode", baton->jp2ChromaSubsampling == "4:4:4" + ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON) + ->set("tile_height", baton->jp2TileHeight) + ->set("tile_width", baton->jp2TileWidth)); + baton->formatOut = "jp2"; + } else if (baton->formatOut == "png" || (mightMatchInput && isPng) || (willMatchInput && + (inputImageType == sharp::ImageType::PNG || inputImageType == sharp::ImageType::SVG))) { + // Write PNG to file + sharp::AssertImageTypeDimensions(image, sharp::ImageType::PNG); + image.pngsave(const_cast(baton->fileOut.data()), VImage::option() + ->set("keep", baton->keepMetadata) + ->set("interlace", baton->pngProgressive) + ->set("compression", baton->pngCompressionLevel) + ->set("filter", baton->pngAdaptiveFiltering ? VIPS_FOREIGN_PNG_FILTER_ALL : VIPS_FOREIGN_PNG_FILTER_NONE) + ->set("palette", baton->pngPalette) + ->set("Q", baton->pngQuality) + ->set("bitdepth", sharp::Is16Bit(image.interpretation()) ? 16 : baton->pngBitdepth) + ->set("effort", baton->pngEffort) + ->set("dither", baton->pngDither)); + baton->formatOut = "png"; + } else if (baton->formatOut == "webp" || (mightMatchInput && isWebp) || + (willMatchInput && inputImageType == sharp::ImageType::WEBP)) { + // Write WEBP to file + sharp::AssertImageTypeDimensions(image, sharp::ImageType::WEBP); + image.webpsave(const_cast(baton->fileOut.data()), VImage::option() + ->set("keep", baton->keepMetadata) + ->set("Q", baton->webpQuality) + ->set("lossless", baton->webpLossless) + ->set("near_lossless", baton->webpNearLossless) + ->set("smart_subsample", baton->webpSmartSubsample) + ->set("smart_deblock", baton->webpSmartDeblock) + ->set("preset", baton->webpPreset) + ->set("effort", baton->webpEffort) + ->set("min_size", baton->webpMinSize) + ->set("mixed", baton->webpMixed) + ->set("alpha_q", baton->webpAlphaQuality)); + baton->formatOut = "webp"; + } else if (baton->formatOut == "gif" || (mightMatchInput && isGif) || + (willMatchInput && inputImageType == sharp::ImageType::GIF)) { + // Write GIF to file + sharp::AssertImageTypeDimensions(image, sharp::ImageType::GIF); + image.gifsave(const_cast(baton->fileOut.data()), VImage::option() + ->set("keep", baton->keepMetadata) + ->set("bitdepth", baton->gifBitdepth) + ->set("effort", baton->gifEffort) + ->set("reuse", baton->gifReuse) + ->set("interlace", baton->gifProgressive) + ->set("interframe_maxerror", baton->gifInterFrameMaxError) + ->set("interpalette_maxerror", baton->gifInterPaletteMaxError) + ->set("keep_duplicate_frames", baton->gifKeepDuplicateFrames) + ->set("dither", baton->gifDither)); + baton->formatOut = "gif"; + } else if (baton->formatOut == "tiff" || (mightMatchInput && isTiff) || + (willMatchInput && inputImageType == sharp::ImageType::TIFF)) { + // Write TIFF to file + if (baton->tiffCompression == VIPS_FOREIGN_TIFF_COMPRESSION_JPEG) { + sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG); + baton->channels = std::min(baton->channels, 3); + } + // Cast pixel values to float, if required + if (baton->tiffPredictor == VIPS_FOREIGN_TIFF_PREDICTOR_FLOAT) { + image = image.cast(VIPS_FORMAT_FLOAT); + } + image.tiffsave(const_cast(baton->fileOut.data()), VImage::option() + ->set("keep", baton->keepMetadata) + ->set("Q", baton->tiffQuality) + ->set("bitdepth", baton->tiffBitdepth) + ->set("compression", baton->tiffCompression) + ->set("miniswhite", baton->tiffMiniswhite) + ->set("predictor", baton->tiffPredictor) + ->set("pyramid", baton->tiffPyramid) + ->set("tile", baton->tiffTile) + ->set("tile_height", baton->tiffTileHeight) + ->set("tile_width", baton->tiffTileWidth) + ->set("xres", baton->tiffXres) + ->set("yres", baton->tiffYres) + ->set("resunit", baton->tiffResolutionUnit)); + baton->formatOut = "tiff"; + } else if (baton->formatOut == "heif" || (mightMatchInput && isHeif) || + (willMatchInput && inputImageType == sharp::ImageType::HEIF)) { + // Write HEIF to file + sharp::AssertImageTypeDimensions(image, sharp::ImageType::HEIF); + image = sharp::RemoveAnimationProperties(image); + image.heifsave(const_cast(baton->fileOut.data()), VImage::option() + ->set("keep", baton->keepMetadata) + ->set("Q", baton->heifQuality) + ->set("compression", baton->heifCompression) + ->set("effort", baton->heifEffort) + ->set("bitdepth", baton->heifBitdepth) + ->set("subsample_mode", baton->heifChromaSubsampling == "4:4:4" + ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON) + ->set("lossless", baton->heifLossless)); + baton->formatOut = "heif"; + } else if (baton->formatOut == "jxl" || (mightMatchInput && isJxl) || + (willMatchInput && inputImageType == sharp::ImageType::JXL)) { + // Write JXL to file + image = sharp::RemoveAnimationProperties(image); + image.jxlsave(const_cast(baton->fileOut.data()), VImage::option() + ->set("keep", baton->keepMetadata) + ->set("distance", baton->jxlDistance) + ->set("tier", baton->jxlDecodingTier) + ->set("effort", baton->jxlEffort) + ->set("lossless", baton->jxlLossless)); + baton->formatOut = "jxl"; + } else if (baton->formatOut == "dz" || isDz || isDzZip) { + // Write DZ to file + if (isDzZip) { + baton->tileContainer = VIPS_FOREIGN_DZ_CONTAINER_ZIP; + } + if (!image.has_alpha()) { + baton->tileBackground.pop_back(); + } + image = sharp::StaySequential(image, baton->tileAngle != 0); + vips::VOption *options = BuildOptionsDZ(baton); + image.dzsave(const_cast(baton->fileOut.data()), options); + baton->formatOut = "dz"; + } else if (baton->formatOut == "v" || (mightMatchInput && isV) || + (willMatchInput && inputImageType == sharp::ImageType::VIPS)) { + // Write V to file + image.vipssave(const_cast(baton->fileOut.data()), VImage::option() + ->set("keep", baton->keepMetadata)); + baton->formatOut = "v"; + } else { + // Unsupported output format + (baton->err).append("Unsupported output format " + baton->fileOut); + return Error(); + } + } + } catch (vips::VError const &err) { + char const *what = err.what(); + if (what && what[0]) { + (baton->err).append(what); + } else { + (baton->err).append("Unknown error"); + } + } + // Clean up libvips' per-request data and threads + vips_error_clear(); + vips_thread_shutdown(); + } + + void OnOK() { + Napi::Env env = Env(); + Napi::HandleScope scope(env); + + // Handle warnings + std::string warning = sharp::VipsWarningPop(); + while (!warning.empty()) { + debuglog.Call(Receiver().Value(), { Napi::String::New(env, warning) }); + warning = sharp::VipsWarningPop(); + } + + if (baton->err.empty()) { + int width = baton->width; + int height = baton->height; + if (baton->topOffsetPre != -1 && (baton->width == -1 || baton->height == -1)) { + width = baton->widthPre; + height = baton->heightPre; + } + if (baton->topOffsetPost != -1) { + width = baton->widthPost; + height = baton->heightPost; + } + // Info Object + Napi::Object info = Napi::Object::New(env); + info.Set("format", baton->formatOut); + info.Set("width", static_cast(width)); + info.Set("height", static_cast(height)); + info.Set("channels", static_cast(baton->channels)); + if (baton->formatOut == "raw") { + info.Set("depth", vips_enum_nick(VIPS_TYPE_BAND_FORMAT, baton->rawDepth)); + } + info.Set("premultiplied", baton->premultiplied); + if (baton->hasCropOffset) { + info.Set("cropOffsetLeft", static_cast(baton->cropOffsetLeft)); + info.Set("cropOffsetTop", static_cast(baton->cropOffsetTop)); + } + if (baton->hasAttentionCenter) { + info.Set("attentionX", static_cast(baton->attentionX)); + info.Set("attentionY", static_cast(baton->attentionY)); + } + if (baton->trimThreshold >= 0.0) { + info.Set("trimOffsetLeft", static_cast(baton->trimOffsetLeft)); + info.Set("trimOffsetTop", static_cast(baton->trimOffsetTop)); + } + if (baton->input->textAutofitDpi) { + info.Set("textAutofitDpi", static_cast(baton->input->textAutofitDpi)); + } + if (baton->pageHeightOut) { + info.Set("pageHeight", static_cast(baton->pageHeightOut)); + info.Set("pages", static_cast(baton->pagesOut)); + } + + if (baton->bufferOutLength > 0) { + // Add buffer size to info + info.Set("size", static_cast(baton->bufferOutLength)); + // Pass ownership of output data to Buffer instance + Napi::Buffer data = Napi::Buffer::NewOrCopy(env, static_cast(baton->bufferOut), + baton->bufferOutLength, sharp::FreeCallback); + Callback().Call(Receiver().Value(), { env.Null(), data, info }); + } else { + // Add file size to info + if (baton->formatOut != "dz" || sharp::IsDzZip(baton->fileOut)) { + try { + uint32_t const size = static_cast( + std::filesystem::file_size(std::filesystem::u8path(baton->fileOut))); + info.Set("size", size); + } catch (...) {} + } + Callback().Call(Receiver().Value(), { env.Null(), info }); + } + } else { + Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() }); + } + + // Delete baton + delete baton->input; + delete baton->boolean; + for (Composite *composite : baton->composite) { + delete composite->input; + delete composite; + } + for (sharp::InputDescriptor *input : baton->joinChannelIn) { + delete input; + } + for (sharp::InputDescriptor *input : baton->join) { + delete input; + } + delete baton; + + // Decrement processing task counter + sharp::counterProcess--; + Napi::Number queueLength = Napi::Number::New(env, static_cast(sharp::counterQueue)); + queueListener.Call(Receiver().Value(), { queueLength }); + } + + private: + PipelineBaton *baton; + Napi::FunctionReference debuglog; + Napi::FunctionReference queueListener; + + void MultiPageUnsupported(int const pages, std::string op) { + if (pages > 1) { + throw vips::VError(op + " is not supported for multi-page images"); + } + } + + /* + Calculate the angle of rotation and need-to-flip for the given Exif orientation + By default, returns zero, i.e. no rotation. + */ + std::tuple + CalculateExifRotationAndFlop(int const exifOrientation) { + VipsAngle rotate = VIPS_ANGLE_D0; + bool flop = false; + switch (exifOrientation) { + case 6: rotate = VIPS_ANGLE_D90; break; + case 3: rotate = VIPS_ANGLE_D180; break; + case 8: rotate = VIPS_ANGLE_D270; break; + case 2: flop = true; break; + case 7: flop = true; rotate = VIPS_ANGLE_D270; break; + case 4: flop = true; rotate = VIPS_ANGLE_D180; break; + case 5: flop = true; rotate = VIPS_ANGLE_D90; break; + } + return std::make_tuple(rotate, flop); + } + + /* + Calculate the rotation for the given angle. + Supports any positive or negative angle that is a multiple of 90. + */ + VipsAngle + CalculateAngleRotation(int angle) { + angle = angle % 360; + if (angle < 0) + angle = 360 + angle; + switch (angle) { + case 90: return VIPS_ANGLE_D90; + case 180: return VIPS_ANGLE_D180; + case 270: return VIPS_ANGLE_D270; + } + return VIPS_ANGLE_D0; + } + + /* + Assemble the suffix argument to dzsave, which is the format (by extname) + alongside comma-separated arguments to the corresponding `formatsave` vips + action. + */ + std::string + AssembleSuffixString(std::string extname, std::vector> options) { + std::string argument; + for (auto const &option : options) { + if (!argument.empty()) { + argument += ","; + } + argument += option.first + "=" + option.second; + } + return extname + "[" + argument + "]"; + } + + /* + Build VOption for dzsave + */ + vips::VOption* + BuildOptionsDZ(PipelineBaton *baton) { + // Forward format options through suffix + std::string suffix; + if (baton->tileFormat == "png") { + std::vector> options { + {"interlace", baton->pngProgressive ? "true" : "false"}, + {"compression", std::to_string(baton->pngCompressionLevel)}, + {"filter", baton->pngAdaptiveFiltering ? "all" : "none"} + }; + suffix = AssembleSuffixString(".png", options); + } else if (baton->tileFormat == "webp") { + std::vector> options { + {"Q", std::to_string(baton->webpQuality)}, + {"alpha_q", std::to_string(baton->webpAlphaQuality)}, + {"lossless", baton->webpLossless ? "true" : "false"}, + {"near_lossless", baton->webpNearLossless ? "true" : "false"}, + {"smart_subsample", baton->webpSmartSubsample ? "true" : "false"}, + {"smart_deblock", baton->webpSmartDeblock ? "true" : "false"}, + {"preset", vips_enum_nick(VIPS_TYPE_FOREIGN_WEBP_PRESET, baton->webpPreset)}, + {"min_size", baton->webpMinSize ? "true" : "false"}, + {"mixed", baton->webpMixed ? "true" : "false"}, + {"effort", std::to_string(baton->webpEffort)} + }; + suffix = AssembleSuffixString(".webp", options); + } else { + std::vector> options { + {"Q", std::to_string(baton->jpegQuality)}, + {"interlace", baton->jpegProgressive ? "true" : "false"}, + {"subsample_mode", baton->jpegChromaSubsampling == "4:4:4" ? "off" : "on"}, + {"trellis_quant", baton->jpegTrellisQuantisation ? "true" : "false"}, + {"quant_table", std::to_string(baton->jpegQuantisationTable)}, + {"overshoot_deringing", baton->jpegOvershootDeringing ? "true": "false"}, + {"optimize_scans", baton->jpegOptimiseScans ? "true": "false"}, + {"optimize_coding", baton->jpegOptimiseCoding ? "true": "false"} + }; + std::string extname = baton->tileLayout == VIPS_FOREIGN_DZ_LAYOUT_DZ ? ".jpeg" : ".jpg"; + suffix = AssembleSuffixString(extname, options); + } + vips::VOption *options = VImage::option() + ->set("keep", baton->keepMetadata) + ->set("tile_size", baton->tileSize) + ->set("overlap", baton->tileOverlap) + ->set("container", baton->tileContainer) + ->set("layout", baton->tileLayout) + ->set("suffix", const_cast(suffix.data())) + ->set("angle", CalculateAngleRotation(baton->tileAngle)) + ->set("background", baton->tileBackground) + ->set("centre", baton->tileCentre) + ->set("id", const_cast(baton->tileId.data())) + ->set("skip_blanks", baton->tileSkipBlanks); + if (baton->tileDepth < VIPS_FOREIGN_DZ_DEPTH_LAST) { + options->set("depth", baton->tileDepth); + } + if (!baton->tileBasename.empty()) { + options->set("basename", const_cast(baton->tileBasename.data())); + } + return options; + } + + /* + Clear all thread-local data. + */ + void Error() { + // Clean up libvips' per-request data and threads + vips_error_clear(); + vips_thread_shutdown(); + } +}; + +/* + pipeline(options, output, callback) +*/ +Napi::Value pipeline(const Napi::CallbackInfo& info) { + // V8 objects are converted to non-V8 types held in the baton struct + PipelineBaton *baton = new PipelineBaton; + Napi::Object options = info[size_t(0)].As(); + + // Input + baton->input = sharp::CreateInputDescriptor(options.Get("input").As()); + // Join images together + if (sharp::HasAttr(options, "join")) { + Napi::Array join = options.Get("join").As(); + for (unsigned int i = 0; i < join.Length(); i++) { + baton->join.push_back( + sharp::CreateInputDescriptor(join.Get(i).As())); + } + } + // Extract image options + baton->topOffsetPre = sharp::AttrAsInt32(options, "topOffsetPre"); + baton->leftOffsetPre = sharp::AttrAsInt32(options, "leftOffsetPre"); + baton->widthPre = sharp::AttrAsInt32(options, "widthPre"); + baton->heightPre = sharp::AttrAsInt32(options, "heightPre"); + baton->topOffsetPost = sharp::AttrAsInt32(options, "topOffsetPost"); + baton->leftOffsetPost = sharp::AttrAsInt32(options, "leftOffsetPost"); + baton->widthPost = sharp::AttrAsInt32(options, "widthPost"); + baton->heightPost = sharp::AttrAsInt32(options, "heightPost"); + // Output image dimensions + baton->width = sharp::AttrAsInt32(options, "width"); + baton->height = sharp::AttrAsInt32(options, "height"); + // Canvas option + std::string canvas = sharp::AttrAsStr(options, "canvas"); + if (canvas == "crop") { + baton->canvas = sharp::Canvas::CROP; + } else if (canvas == "embed") { + baton->canvas = sharp::Canvas::EMBED; + } else if (canvas == "max") { + baton->canvas = sharp::Canvas::MAX; + } else if (canvas == "min") { + baton->canvas = sharp::Canvas::MIN; + } else if (canvas == "ignore_aspect") { + baton->canvas = sharp::Canvas::IGNORE_ASPECT; + } + // Composite + Napi::Array compositeArray = options.Get("composite").As(); + for (unsigned int i = 0; i < compositeArray.Length(); i++) { + Napi::Object compositeObject = compositeArray.Get(i).As(); + Composite *composite = new Composite; + composite->input = sharp::CreateInputDescriptor(compositeObject.Get("input").As()); + composite->mode = sharp::AttrAsEnum(compositeObject, "blend", VIPS_TYPE_BLEND_MODE); + composite->gravity = sharp::AttrAsUint32(compositeObject, "gravity"); + composite->left = sharp::AttrAsInt32(compositeObject, "left"); + composite->top = sharp::AttrAsInt32(compositeObject, "top"); + composite->hasOffset = sharp::AttrAsBool(compositeObject, "hasOffset"); + composite->tile = sharp::AttrAsBool(compositeObject, "tile"); + composite->premultiplied = sharp::AttrAsBool(compositeObject, "premultiplied"); + baton->composite.push_back(composite); + } + // Resize options + baton->withoutEnlargement = sharp::AttrAsBool(options, "withoutEnlargement"); + baton->withoutReduction = sharp::AttrAsBool(options, "withoutReduction"); + baton->position = sharp::AttrAsInt32(options, "position"); + baton->resizeBackground = sharp::AttrAsVectorOfDouble(options, "resizeBackground"); + baton->kernel = sharp::AttrAsEnum(options, "kernel", VIPS_TYPE_KERNEL); + baton->fastShrinkOnLoad = sharp::AttrAsBool(options, "fastShrinkOnLoad"); + // Join Channel Options + if (options.Has("joinChannelIn")) { + Napi::Array joinChannelArray = options.Get("joinChannelIn").As(); + for (unsigned int i = 0; i < joinChannelArray.Length(); i++) { + baton->joinChannelIn.push_back( + sharp::CreateInputDescriptor(joinChannelArray.Get(i).As())); + } + } + // Operators + baton->flatten = sharp::AttrAsBool(options, "flatten"); + baton->flattenBackground = sharp::AttrAsVectorOfDouble(options, "flattenBackground"); + baton->unflatten = sharp::AttrAsBool(options, "unflatten"); + baton->negate = sharp::AttrAsBool(options, "negate"); + baton->negateAlpha = sharp::AttrAsBool(options, "negateAlpha"); + baton->blurSigma = sharp::AttrAsDouble(options, "blurSigma"); + baton->precision = sharp::AttrAsEnum(options, "precision", VIPS_TYPE_PRECISION); + baton->minAmpl = sharp::AttrAsDouble(options, "minAmpl"); + baton->brightness = sharp::AttrAsDouble(options, "brightness"); + baton->saturation = sharp::AttrAsDouble(options, "saturation"); + baton->hue = sharp::AttrAsInt32(options, "hue"); + baton->lightness = sharp::AttrAsDouble(options, "lightness"); + baton->medianSize = sharp::AttrAsUint32(options, "medianSize"); + baton->sharpenSigma = sharp::AttrAsDouble(options, "sharpenSigma"); + baton->sharpenM1 = sharp::AttrAsDouble(options, "sharpenM1"); + baton->sharpenM2 = sharp::AttrAsDouble(options, "sharpenM2"); + baton->sharpenX1 = sharp::AttrAsDouble(options, "sharpenX1"); + baton->sharpenY2 = sharp::AttrAsDouble(options, "sharpenY2"); + baton->sharpenY3 = sharp::AttrAsDouble(options, "sharpenY3"); + baton->threshold = sharp::AttrAsInt32(options, "threshold"); + baton->thresholdGrayscale = sharp::AttrAsBool(options, "thresholdGrayscale"); + baton->trimBackground = sharp::AttrAsVectorOfDouble(options, "trimBackground"); + baton->trimThreshold = sharp::AttrAsDouble(options, "trimThreshold"); + baton->trimLineArt = sharp::AttrAsBool(options, "trimLineArt"); + baton->gamma = sharp::AttrAsDouble(options, "gamma"); + baton->gammaOut = sharp::AttrAsDouble(options, "gammaOut"); + baton->linearA = sharp::AttrAsVectorOfDouble(options, "linearA"); + baton->linearB = sharp::AttrAsVectorOfDouble(options, "linearB"); + baton->dilateWidth = sharp::AttrAsUint32(options, "dilateWidth"); + baton->erodeWidth = sharp::AttrAsUint32(options, "erodeWidth"); + baton->greyscale = sharp::AttrAsBool(options, "greyscale"); + baton->normalise = sharp::AttrAsBool(options, "normalise"); + baton->normaliseLower = sharp::AttrAsUint32(options, "normaliseLower"); + baton->normaliseUpper = sharp::AttrAsUint32(options, "normaliseUpper"); + baton->tint = sharp::AttrAsVectorOfDouble(options, "tint"); + baton->claheWidth = sharp::AttrAsUint32(options, "claheWidth"); + baton->claheHeight = sharp::AttrAsUint32(options, "claheHeight"); + baton->claheMaxSlope = sharp::AttrAsUint32(options, "claheMaxSlope"); + baton->angle = sharp::AttrAsInt32(options, "angle"); + baton->rotationAngle = sharp::AttrAsDouble(options, "rotationAngle"); + baton->rotationBackground = sharp::AttrAsVectorOfDouble(options, "rotationBackground"); + baton->rotateBefore = sharp::AttrAsBool(options, "rotateBefore"); + baton->orientBefore = sharp::AttrAsBool(options, "orientBefore"); + baton->flip = sharp::AttrAsBool(options, "flip"); + baton->flop = sharp::AttrAsBool(options, "flop"); + baton->extendTop = sharp::AttrAsInt32(options, "extendTop"); + baton->extendBottom = sharp::AttrAsInt32(options, "extendBottom"); + baton->extendLeft = sharp::AttrAsInt32(options, "extendLeft"); + baton->extendRight = sharp::AttrAsInt32(options, "extendRight"); + baton->extendBackground = sharp::AttrAsVectorOfDouble(options, "extendBackground"); + baton->extendWith = sharp::AttrAsEnum(options, "extendWith", VIPS_TYPE_EXTEND); + baton->extractChannel = sharp::AttrAsInt32(options, "extractChannel"); + baton->affineMatrix = sharp::AttrAsVectorOfDouble(options, "affineMatrix"); + baton->affineBackground = sharp::AttrAsVectorOfDouble(options, "affineBackground"); + baton->affineIdx = sharp::AttrAsDouble(options, "affineIdx"); + baton->affineIdy = sharp::AttrAsDouble(options, "affineIdy"); + baton->affineOdx = sharp::AttrAsDouble(options, "affineOdx"); + baton->affineOdy = sharp::AttrAsDouble(options, "affineOdy"); + baton->affineInterpolator = sharp::AttrAsStr(options, "affineInterpolator"); + baton->removeAlpha = sharp::AttrAsBool(options, "removeAlpha"); + baton->ensureAlpha = sharp::AttrAsDouble(options, "ensureAlpha"); + if (options.Has("boolean")) { + baton->boolean = sharp::CreateInputDescriptor(options.Get("boolean").As()); + baton->booleanOp = sharp::AttrAsEnum(options, "booleanOp", VIPS_TYPE_OPERATION_BOOLEAN); + } + if (options.Has("bandBoolOp")) { + baton->bandBoolOp = sharp::AttrAsEnum(options, "bandBoolOp", VIPS_TYPE_OPERATION_BOOLEAN); + } + if (options.Has("convKernel")) { + Napi::Object kernel = options.Get("convKernel").As(); + baton->convKernelWidth = sharp::AttrAsUint32(kernel, "width"); + baton->convKernelHeight = sharp::AttrAsUint32(kernel, "height"); + baton->convKernelScale = sharp::AttrAsDouble(kernel, "scale"); + baton->convKernelOffset = sharp::AttrAsDouble(kernel, "offset"); + size_t const kernelSize = static_cast(baton->convKernelWidth * baton->convKernelHeight); + baton->convKernel.resize(kernelSize); + Napi::Array kdata = kernel.Get("kernel").As(); + for (unsigned int i = 0; i < kernelSize; i++) { + baton->convKernel[i] = sharp::AttrAsDouble(kdata, i); + } + } + if (options.Has("recombMatrix")) { + Napi::Array recombMatrix = options.Get("recombMatrix").As(); + unsigned int matrixElements = recombMatrix.Length(); + baton->recombMatrix.resize(matrixElements); + for (unsigned int i = 0; i < matrixElements; i++) { + baton->recombMatrix[i] = sharp::AttrAsDouble(recombMatrix, i); + } + } + baton->colourspacePipeline = sharp::AttrAsEnum( + options, "colourspacePipeline", VIPS_TYPE_INTERPRETATION); + if (baton->colourspacePipeline == VIPS_INTERPRETATION_ERROR) { + baton->colourspacePipeline = VIPS_INTERPRETATION_LAST; + } + baton->colourspace = sharp::AttrAsEnum(options, "colourspace", VIPS_TYPE_INTERPRETATION); + if (baton->colourspace == VIPS_INTERPRETATION_ERROR) { + baton->colourspace = VIPS_INTERPRETATION_sRGB; + } + // Output + baton->formatOut = sharp::AttrAsStr(options, "formatOut"); + baton->fileOut = sharp::AttrAsStr(options, "fileOut"); + baton->keepMetadata = sharp::AttrAsUint32(options, "keepMetadata"); + baton->withMetadataOrientation = sharp::AttrAsUint32(options, "withMetadataOrientation"); + baton->withMetadataDensity = sharp::AttrAsDouble(options, "withMetadataDensity"); + baton->withIccProfile = sharp::AttrAsStr(options, "withIccProfile"); + Napi::Object withExif = options.Get("withExif").As(); + Napi::Array withExifKeys = withExif.GetPropertyNames(); + for (unsigned int i = 0; i < withExifKeys.Length(); i++) { + std::string k = sharp::AttrAsStr(withExifKeys, i); + if (withExif.HasOwnProperty(k)) { + baton->withExif.insert(std::make_pair(k, sharp::AttrAsStr(withExif, k))); + } + } + baton->withExifMerge = sharp::AttrAsBool(options, "withExifMerge"); + baton->withXmp = sharp::AttrAsStr(options, "withXmp"); + baton->timeoutSeconds = sharp::AttrAsUint32(options, "timeoutSeconds"); + baton->loop = sharp::AttrAsUint32(options, "loop"); + baton->delay = sharp::AttrAsInt32Vector(options, "delay"); + // Format-specific + baton->jpegQuality = sharp::AttrAsUint32(options, "jpegQuality"); + baton->jpegProgressive = sharp::AttrAsBool(options, "jpegProgressive"); + baton->jpegChromaSubsampling = sharp::AttrAsStr(options, "jpegChromaSubsampling"); + baton->jpegTrellisQuantisation = sharp::AttrAsBool(options, "jpegTrellisQuantisation"); + baton->jpegQuantisationTable = sharp::AttrAsUint32(options, "jpegQuantisationTable"); + baton->jpegOvershootDeringing = sharp::AttrAsBool(options, "jpegOvershootDeringing"); + baton->jpegOptimiseScans = sharp::AttrAsBool(options, "jpegOptimiseScans"); + baton->jpegOptimiseCoding = sharp::AttrAsBool(options, "jpegOptimiseCoding"); + baton->pngProgressive = sharp::AttrAsBool(options, "pngProgressive"); + baton->pngCompressionLevel = sharp::AttrAsUint32(options, "pngCompressionLevel"); + baton->pngAdaptiveFiltering = sharp::AttrAsBool(options, "pngAdaptiveFiltering"); + baton->pngPalette = sharp::AttrAsBool(options, "pngPalette"); + baton->pngQuality = sharp::AttrAsUint32(options, "pngQuality"); + baton->pngEffort = sharp::AttrAsUint32(options, "pngEffort"); + baton->pngBitdepth = sharp::AttrAsUint32(options, "pngBitdepth"); + baton->pngDither = sharp::AttrAsDouble(options, "pngDither"); + baton->jp2Quality = sharp::AttrAsUint32(options, "jp2Quality"); + baton->jp2Lossless = sharp::AttrAsBool(options, "jp2Lossless"); + baton->jp2TileHeight = sharp::AttrAsUint32(options, "jp2TileHeight"); + baton->jp2TileWidth = sharp::AttrAsUint32(options, "jp2TileWidth"); + baton->jp2ChromaSubsampling = sharp::AttrAsStr(options, "jp2ChromaSubsampling"); + baton->webpQuality = sharp::AttrAsUint32(options, "webpQuality"); + baton->webpAlphaQuality = sharp::AttrAsUint32(options, "webpAlphaQuality"); + baton->webpLossless = sharp::AttrAsBool(options, "webpLossless"); + baton->webpNearLossless = sharp::AttrAsBool(options, "webpNearLossless"); + baton->webpSmartSubsample = sharp::AttrAsBool(options, "webpSmartSubsample"); + baton->webpSmartDeblock = sharp::AttrAsBool(options, "webpSmartDeblock"); + baton->webpPreset = sharp::AttrAsEnum(options, "webpPreset", VIPS_TYPE_FOREIGN_WEBP_PRESET); + baton->webpEffort = sharp::AttrAsUint32(options, "webpEffort"); + baton->webpMinSize = sharp::AttrAsBool(options, "webpMinSize"); + baton->webpMixed = sharp::AttrAsBool(options, "webpMixed"); + baton->gifBitdepth = sharp::AttrAsUint32(options, "gifBitdepth"); + baton->gifEffort = sharp::AttrAsUint32(options, "gifEffort"); + baton->gifDither = sharp::AttrAsDouble(options, "gifDither"); + baton->gifInterFrameMaxError = sharp::AttrAsDouble(options, "gifInterFrameMaxError"); + baton->gifInterPaletteMaxError = sharp::AttrAsDouble(options, "gifInterPaletteMaxError"); + baton->gifKeepDuplicateFrames = sharp::AttrAsBool(options, "gifKeepDuplicateFrames"); + baton->gifReuse = sharp::AttrAsBool(options, "gifReuse"); + baton->gifProgressive = sharp::AttrAsBool(options, "gifProgressive"); + baton->tiffQuality = sharp::AttrAsUint32(options, "tiffQuality"); + baton->tiffPyramid = sharp::AttrAsBool(options, "tiffPyramid"); + baton->tiffMiniswhite = sharp::AttrAsBool(options, "tiffMiniswhite"); + baton->tiffBitdepth = sharp::AttrAsUint32(options, "tiffBitdepth"); + baton->tiffTile = sharp::AttrAsBool(options, "tiffTile"); + baton->tiffTileWidth = sharp::AttrAsUint32(options, "tiffTileWidth"); + baton->tiffTileHeight = sharp::AttrAsUint32(options, "tiffTileHeight"); + baton->tiffXres = sharp::AttrAsDouble(options, "tiffXres"); + baton->tiffYres = sharp::AttrAsDouble(options, "tiffYres"); + if (baton->tiffXres == 1.0 && baton->tiffYres == 1.0 && baton->withMetadataDensity > 0) { + baton->tiffXres = baton->tiffYres = baton->withMetadataDensity / 25.4; + } + baton->tiffCompression = sharp::AttrAsEnum( + options, "tiffCompression", VIPS_TYPE_FOREIGN_TIFF_COMPRESSION); + baton->tiffPredictor = sharp::AttrAsEnum( + options, "tiffPredictor", VIPS_TYPE_FOREIGN_TIFF_PREDICTOR); + baton->tiffResolutionUnit = sharp::AttrAsEnum( + options, "tiffResolutionUnit", VIPS_TYPE_FOREIGN_TIFF_RESUNIT); + baton->heifQuality = sharp::AttrAsUint32(options, "heifQuality"); + baton->heifLossless = sharp::AttrAsBool(options, "heifLossless"); + baton->heifCompression = sharp::AttrAsEnum( + options, "heifCompression", VIPS_TYPE_FOREIGN_HEIF_COMPRESSION); + baton->heifEffort = sharp::AttrAsUint32(options, "heifEffort"); + baton->heifChromaSubsampling = sharp::AttrAsStr(options, "heifChromaSubsampling"); + baton->heifBitdepth = sharp::AttrAsUint32(options, "heifBitdepth"); + baton->jxlDistance = sharp::AttrAsDouble(options, "jxlDistance"); + baton->jxlDecodingTier = sharp::AttrAsUint32(options, "jxlDecodingTier"); + baton->jxlEffort = sharp::AttrAsUint32(options, "jxlEffort"); + baton->jxlLossless = sharp::AttrAsBool(options, "jxlLossless"); + baton->rawDepth = sharp::AttrAsEnum(options, "rawDepth", VIPS_TYPE_BAND_FORMAT); + baton->tileSize = sharp::AttrAsUint32(options, "tileSize"); + baton->tileOverlap = sharp::AttrAsUint32(options, "tileOverlap"); + baton->tileAngle = sharp::AttrAsInt32(options, "tileAngle"); + baton->tileBackground = sharp::AttrAsVectorOfDouble(options, "tileBackground"); + baton->tileSkipBlanks = sharp::AttrAsInt32(options, "tileSkipBlanks"); + baton->tileContainer = sharp::AttrAsEnum( + options, "tileContainer", VIPS_TYPE_FOREIGN_DZ_CONTAINER); + baton->tileLayout = sharp::AttrAsEnum(options, "tileLayout", VIPS_TYPE_FOREIGN_DZ_LAYOUT); + baton->tileFormat = sharp::AttrAsStr(options, "tileFormat"); + baton->tileDepth = sharp::AttrAsEnum(options, "tileDepth", VIPS_TYPE_FOREIGN_DZ_DEPTH); + baton->tileCentre = sharp::AttrAsBool(options, "tileCentre"); + baton->tileId = sharp::AttrAsStr(options, "tileId"); + baton->tileBasename = sharp::AttrAsStr(options, "tileBasename"); + + // Function to notify of libvips warnings + Napi::Function debuglog = options.Get("debuglog").As(); + + // Function to notify of queue length changes + Napi::Function queueListener = options.Get("queueListener").As(); + + // Join queue for worker thread + Napi::Function callback = info[size_t(1)].As(); + PipelineWorker *worker = new PipelineWorker(callback, baton, debuglog, queueListener); + worker->Receiver().Set("options", options); + worker->Queue(); + + // Increment queued task counter + Napi::Number queueLength = Napi::Number::New(info.Env(), static_cast(++sharp::counterQueue)); + queueListener.Call(info.This(), { queueLength }); + + return info.Env().Undefined(); +} diff --git a/server/node_modules/sharp/src/pipeline.h b/server/node_modules/sharp/src/pipeline.h new file mode 100644 index 0000000..8edfff5 --- /dev/null +++ b/server/node_modules/sharp/src/pipeline.h @@ -0,0 +1,402 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#ifndef SRC_PIPELINE_H_ +#define SRC_PIPELINE_H_ + +#include +#include +#include +#include + +#include +#include + +#include "./common.h" + +Napi::Value pipeline(const Napi::CallbackInfo& info); + +struct Composite { + sharp::InputDescriptor *input; + VipsBlendMode mode; + int gravity; + int left; + int top; + bool hasOffset; + bool tile; + bool premultiplied; + + Composite(): + input(nullptr), + mode(VIPS_BLEND_MODE_OVER), + gravity(0), + left(0), + top(0), + hasOffset(false), + tile(false), + premultiplied(false) {} +}; + +struct PipelineBaton { + sharp::InputDescriptor *input; + std::vector join; + std::string formatOut; + std::string fileOut; + void *bufferOut; + size_t bufferOutLength; + int pageHeightOut; + int pagesOut; + std::vector composite; + std::vector joinChannelIn; + int topOffsetPre; + int leftOffsetPre; + int widthPre; + int heightPre; + int topOffsetPost; + int leftOffsetPost; + int widthPost; + int heightPost; + int width; + int height; + int channels; + VipsKernel kernel; + sharp::Canvas canvas; + int position; + std::vector resizeBackground; + bool hasCropOffset; + int cropOffsetLeft; + int cropOffsetTop; + bool hasAttentionCenter; + int attentionX; + int attentionY; + bool premultiplied; + bool tileCentre; + bool fastShrinkOnLoad; + std::vector tint; + bool flatten; + std::vector flattenBackground; + bool unflatten; + bool negate; + bool negateAlpha; + double blurSigma; + VipsPrecision precision; + double minAmpl; + double brightness; + double saturation; + int hue; + double lightness; + int medianSize; + double sharpenSigma; + double sharpenM1; + double sharpenM2; + double sharpenX1; + double sharpenY2; + double sharpenY3; + int threshold; + bool thresholdGrayscale; + std::vector trimBackground; + double trimThreshold; + bool trimLineArt; + int trimOffsetLeft; + int trimOffsetTop; + std::vector linearA; + std::vector linearB; + int dilateWidth; + int erodeWidth; + double gamma; + double gammaOut; + bool greyscale; + bool normalise; + int normaliseLower; + int normaliseUpper; + int claheWidth; + int claheHeight; + int claheMaxSlope; + int angle; + double rotationAngle; + std::vector rotationBackground; + bool rotateBefore; + bool orientBefore; + bool flip; + bool flop; + int extendTop; + int extendBottom; + int extendLeft; + int extendRight; + std::vector extendBackground; + VipsExtend extendWith; + bool withoutEnlargement; + bool withoutReduction; + std::vector affineMatrix; + std::vector affineBackground; + double affineIdx; + double affineIdy; + double affineOdx; + double affineOdy; + std::string affineInterpolator; + int jpegQuality; + bool jpegProgressive; + std::string jpegChromaSubsampling; + bool jpegTrellisQuantisation; + int jpegQuantisationTable; + bool jpegOvershootDeringing; + bool jpegOptimiseScans; + bool jpegOptimiseCoding; + bool pngProgressive; + int pngCompressionLevel; + bool pngAdaptiveFiltering; + bool pngPalette; + int pngQuality; + int pngEffort; + int pngBitdepth; + double pngDither; + int jp2Quality; + bool jp2Lossless; + int jp2TileHeight; + int jp2TileWidth; + std::string jp2ChromaSubsampling; + int webpQuality; + int webpAlphaQuality; + bool webpNearLossless; + bool webpLossless; + bool webpSmartSubsample; + bool webpSmartDeblock; + VipsForeignWebpPreset webpPreset; + int webpEffort; + bool webpMinSize; + bool webpMixed; + int gifBitdepth; + int gifEffort; + double gifDither; + double gifInterFrameMaxError; + double gifInterPaletteMaxError; + bool gifKeepDuplicateFrames; + bool gifReuse; + bool gifProgressive; + int tiffQuality; + VipsForeignTiffCompression tiffCompression; + VipsForeignTiffPredictor tiffPredictor; + bool tiffPyramid; + int tiffBitdepth; + bool tiffMiniswhite; + bool tiffTile; + int tiffTileHeight; + int tiffTileWidth; + double tiffXres; + double tiffYres; + VipsForeignTiffResunit tiffResolutionUnit; + int heifQuality; + VipsForeignHeifCompression heifCompression; + int heifEffort; + std::string heifChromaSubsampling; + bool heifLossless; + int heifBitdepth; + double jxlDistance; + int jxlDecodingTier; + int jxlEffort; + bool jxlLossless; + VipsBandFormat rawDepth; + std::string err; + int keepMetadata; + int withMetadataOrientation; + double withMetadataDensity; + std::string withIccProfile; + std::unordered_map withExif; + bool withExifMerge; + std::string withXmp; + int timeoutSeconds; + std::vector convKernel; + int convKernelWidth; + int convKernelHeight; + double convKernelScale; + double convKernelOffset; + sharp::InputDescriptor *boolean; + VipsOperationBoolean booleanOp; + VipsOperationBoolean bandBoolOp; + int extractChannel; + bool removeAlpha; + double ensureAlpha; + VipsInterpretation colourspacePipeline; + VipsInterpretation colourspace; + std::vector delay; + int loop; + int tileSize; + int tileOverlap; + VipsForeignDzContainer tileContainer; + VipsForeignDzLayout tileLayout; + std::string tileFormat; + int tileAngle; + std::vector tileBackground; + int tileSkipBlanks; + VipsForeignDzDepth tileDepth; + std::string tileId; + std::string tileBasename; + std::vector recombMatrix; + + PipelineBaton(): + input(nullptr), + bufferOutLength(0), + pageHeightOut(0), + pagesOut(0), + topOffsetPre(-1), + topOffsetPost(-1), + channels(0), + kernel(VIPS_KERNEL_LANCZOS3), + canvas(sharp::Canvas::CROP), + position(0), + resizeBackground{ 0.0, 0.0, 0.0, 255.0 }, + hasCropOffset(false), + cropOffsetLeft(0), + cropOffsetTop(0), + hasAttentionCenter(false), + attentionX(0), + attentionY(0), + premultiplied(false), + tint{ -1.0, 0.0, 0.0, 0.0 }, + flatten(false), + flattenBackground{ 0.0, 0.0, 0.0 }, + unflatten(false), + negate(false), + negateAlpha(true), + blurSigma(0.0), + brightness(1.0), + saturation(1.0), + hue(0), + lightness(0), + medianSize(0), + sharpenSigma(0.0), + sharpenM1(1.0), + sharpenM2(2.0), + sharpenX1(2.0), + sharpenY2(10.0), + sharpenY3(20.0), + threshold(0), + thresholdGrayscale(true), + trimBackground{}, + trimThreshold(-1.0), + trimLineArt(false), + trimOffsetLeft(0), + trimOffsetTop(0), + linearA{}, + linearB{}, + dilateWidth(0), + erodeWidth(0), + gamma(0.0), + greyscale(false), + normalise(false), + normaliseLower(1), + normaliseUpper(99), + claheWidth(0), + claheHeight(0), + claheMaxSlope(3), + angle(0), + rotationAngle(0.0), + rotationBackground{ 0.0, 0.0, 0.0, 255.0 }, + flip(false), + flop(false), + extendTop(0), + extendBottom(0), + extendLeft(0), + extendRight(0), + extendBackground{ 0.0, 0.0, 0.0, 255.0 }, + extendWith(VIPS_EXTEND_BACKGROUND), + withoutEnlargement(false), + withoutReduction(false), + affineMatrix{ 1.0, 0.0, 0.0, 1.0 }, + affineBackground{ 0.0, 0.0, 0.0, 255.0 }, + affineIdx(0), + affineIdy(0), + affineOdx(0), + affineOdy(0), + affineInterpolator("bicubic"), + jpegQuality(80), + jpegProgressive(false), + jpegChromaSubsampling("4:2:0"), + jpegTrellisQuantisation(false), + jpegQuantisationTable(0), + jpegOvershootDeringing(false), + jpegOptimiseScans(false), + jpegOptimiseCoding(true), + pngProgressive(false), + pngCompressionLevel(6), + pngAdaptiveFiltering(false), + pngPalette(false), + pngQuality(100), + pngEffort(7), + pngBitdepth(8), + pngDither(1.0), + jp2Quality(80), + jp2Lossless(false), + jp2TileHeight(512), + jp2TileWidth(512), + jp2ChromaSubsampling("4:4:4"), + webpQuality(80), + webpAlphaQuality(100), + webpNearLossless(false), + webpLossless(false), + webpSmartSubsample(false), + webpSmartDeblock(false), + webpPreset(VIPS_FOREIGN_WEBP_PRESET_DEFAULT), + webpEffort(4), + webpMinSize(false), + webpMixed(false), + gifBitdepth(8), + gifEffort(7), + gifDither(1.0), + gifInterFrameMaxError(0.0), + gifInterPaletteMaxError(3.0), + gifKeepDuplicateFrames(false), + gifReuse(true), + gifProgressive(false), + tiffQuality(80), + tiffCompression(VIPS_FOREIGN_TIFF_COMPRESSION_JPEG), + tiffPredictor(VIPS_FOREIGN_TIFF_PREDICTOR_HORIZONTAL), + tiffPyramid(false), + tiffBitdepth(8), + tiffMiniswhite(false), + tiffTile(false), + tiffTileHeight(256), + tiffTileWidth(256), + tiffXres(1.0), + tiffYres(1.0), + tiffResolutionUnit(VIPS_FOREIGN_TIFF_RESUNIT_INCH), + heifQuality(50), + heifCompression(VIPS_FOREIGN_HEIF_COMPRESSION_AV1), + heifEffort(4), + heifChromaSubsampling("4:4:4"), + heifLossless(false), + heifBitdepth(8), + jxlDistance(1.0), + jxlDecodingTier(0), + jxlEffort(7), + jxlLossless(false), + rawDepth(VIPS_FORMAT_UCHAR), + keepMetadata(0), + withMetadataOrientation(-1), + withMetadataDensity(0.0), + withExifMerge(true), + timeoutSeconds(0), + convKernelWidth(0), + convKernelHeight(0), + convKernelScale(0.0), + convKernelOffset(0.0), + boolean(nullptr), + booleanOp(VIPS_OPERATION_BOOLEAN_LAST), + bandBoolOp(VIPS_OPERATION_BOOLEAN_LAST), + extractChannel(-1), + removeAlpha(false), + ensureAlpha(-1.0), + colourspacePipeline(VIPS_INTERPRETATION_LAST), + colourspace(VIPS_INTERPRETATION_LAST), + loop(-1), + tileSize(256), + tileOverlap(0), + tileContainer(VIPS_FOREIGN_DZ_CONTAINER_FS), + tileLayout(VIPS_FOREIGN_DZ_LAYOUT_DZ), + tileAngle(0), + tileBackground{ 255.0, 255.0, 255.0, 255.0 }, + tileSkipBlanks(-1), + tileDepth(VIPS_FOREIGN_DZ_DEPTH_LAST) {} +}; + +#endif // SRC_PIPELINE_H_ diff --git a/server/node_modules/sharp/src/sharp.cc b/server/node_modules/sharp/src/sharp.cc new file mode 100644 index 0000000..ed54c50 --- /dev/null +++ b/server/node_modules/sharp/src/sharp.cc @@ -0,0 +1,41 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#include // NOLINT(build/c++11) + +#include +#include + +#include "common.h" +#include "metadata.h" +#include "pipeline.h" +#include "utilities.h" +#include "stats.h" + +Napi::Object init(Napi::Env env, Napi::Object exports) { + static std::once_flag sharp_vips_init_once; + std::call_once(sharp_vips_init_once, []() { + vips_init("sharp"); + }); + + g_log_set_handler("VIPS", static_cast(G_LOG_LEVEL_WARNING), + static_cast(sharp::VipsWarningCallback), nullptr); + + // Methods available to JavaScript + exports.Set("metadata", Napi::Function::New(env, metadata)); + exports.Set("pipeline", Napi::Function::New(env, pipeline)); + exports.Set("cache", Napi::Function::New(env, cache)); + exports.Set("concurrency", Napi::Function::New(env, concurrency)); + exports.Set("counters", Napi::Function::New(env, counters)); + exports.Set("simd", Napi::Function::New(env, simd)); + exports.Set("libvipsVersion", Napi::Function::New(env, libvipsVersion)); + exports.Set("format", Napi::Function::New(env, format)); + exports.Set("block", Napi::Function::New(env, block)); + exports.Set("_maxColourDistance", Napi::Function::New(env, _maxColourDistance)); + exports.Set("_isUsingJemalloc", Napi::Function::New(env, _isUsingJemalloc)); + exports.Set("_isUsingX64V2", Napi::Function::New(env, _isUsingX64V2)); + exports.Set("stats", Napi::Function::New(env, stats)); + return exports; +} + +NODE_API_MODULE(sharp, init) diff --git a/server/node_modules/sharp/src/stats.cc b/server/node_modules/sharp/src/stats.cc new file mode 100644 index 0000000..bc9b243 --- /dev/null +++ b/server/node_modules/sharp/src/stats.cc @@ -0,0 +1,183 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#include +#include +#include + +#include +#include + +#include "common.h" +#include "stats.h" + +class StatsWorker : public Napi::AsyncWorker { + public: + StatsWorker(Napi::Function callback, StatsBaton *baton, Napi::Function debuglog) : + Napi::AsyncWorker(callback), baton(baton), debuglog(Napi::Persistent(debuglog)) {} + ~StatsWorker() {} + + const int STAT_MIN_INDEX = 0; + const int STAT_MAX_INDEX = 1; + const int STAT_SUM_INDEX = 2; + const int STAT_SQ_SUM_INDEX = 3; + const int STAT_MEAN_INDEX = 4; + const int STAT_STDEV_INDEX = 5; + const int STAT_MINX_INDEX = 6; + const int STAT_MINY_INDEX = 7; + const int STAT_MAXX_INDEX = 8; + const int STAT_MAXY_INDEX = 9; + + void Execute() { + // Decrement queued task counter + sharp::counterQueue--; + + vips::VImage image; + sharp::ImageType imageType = sharp::ImageType::UNKNOWN; + try { + std::tie(image, imageType) = OpenInput(baton->input); + } catch (vips::VError const &err) { + (baton->err).append(err.what()); + } + if (imageType != sharp::ImageType::UNKNOWN) { + try { + vips::VImage stats = image.stats(); + int const bands = image.bands(); + for (int b = 1; b <= bands; b++) { + ChannelStats cStats( + static_cast(stats.getpoint(STAT_MIN_INDEX, b).front()), + static_cast(stats.getpoint(STAT_MAX_INDEX, b).front()), + stats.getpoint(STAT_SUM_INDEX, b).front(), + stats.getpoint(STAT_SQ_SUM_INDEX, b).front(), + stats.getpoint(STAT_MEAN_INDEX, b).front(), + stats.getpoint(STAT_STDEV_INDEX, b).front(), + static_cast(stats.getpoint(STAT_MINX_INDEX, b).front()), + static_cast(stats.getpoint(STAT_MINY_INDEX, b).front()), + static_cast(stats.getpoint(STAT_MAXX_INDEX, b).front()), + static_cast(stats.getpoint(STAT_MAXY_INDEX, b).front())); + baton->channelStats.push_back(cStats); + } + // Image is not opaque when alpha layer is present and contains a non-mamixa value + if (image.has_alpha()) { + double const minAlpha = static_cast(stats.getpoint(STAT_MIN_INDEX, bands).front()); + if (minAlpha != vips_interpretation_max_alpha(image.interpretation())) { + baton->isOpaque = false; + } + } + // Convert to greyscale + vips::VImage greyscale = image.colourspace(VIPS_INTERPRETATION_B_W)[0]; + // Estimate entropy via histogram of greyscale value frequency + baton->entropy = std::abs(greyscale.hist_find().hist_entropy()); + // Estimate sharpness via standard deviation of greyscale laplacian + if (image.width() > 1 || image.height() > 1) { + VImage laplacian = VImage::new_matrixv(3, 3, + 0.0, 1.0, 0.0, + 1.0, -4.0, 1.0, + 0.0, 1.0, 0.0); + laplacian.set("scale", 9.0); + baton->sharpness = greyscale.conv(laplacian).deviate(); + } + // Most dominant sRGB colour via 4096-bin 3D histogram + vips::VImage hist = sharp::RemoveAlpha(image) + .colourspace(VIPS_INTERPRETATION_sRGB) + .hist_find_ndim(VImage::option()->set("bins", 16)); + std::complex maxpos = hist.maxpos(); + int const dx = static_cast(std::real(maxpos)); + int const dy = static_cast(std::imag(maxpos)); + std::vector pel = hist(dx, dy); + int const dz = std::distance(pel.begin(), std::find(pel.begin(), pel.end(), hist.max())); + baton->dominantRed = dx * 16 + 8; + baton->dominantGreen = dy * 16 + 8; + baton->dominantBlue = dz * 16 + 8; + } catch (vips::VError const &err) { + (baton->err).append(err.what()); + } + } + + // Clean up + vips_error_clear(); + vips_thread_shutdown(); + } + + void OnOK() { + Napi::Env env = Env(); + Napi::HandleScope scope(env); + + // Handle warnings + std::string warning = sharp::VipsWarningPop(); + while (!warning.empty()) { + debuglog.Call(Receiver().Value(), { Napi::String::New(env, warning) }); + warning = sharp::VipsWarningPop(); + } + + if (baton->err.empty()) { + // Stats Object + Napi::Object info = Napi::Object::New(env); + Napi::Array channels = Napi::Array::New(env); + + std::vector::iterator it; + int i = 0; + for (it = baton->channelStats.begin(); it < baton->channelStats.end(); it++, i++) { + Napi::Object channelStat = Napi::Object::New(env); + channelStat.Set("min", it->min); + channelStat.Set("max", it->max); + channelStat.Set("sum", it->sum); + channelStat.Set("squaresSum", it->squaresSum); + channelStat.Set("mean", it->mean); + channelStat.Set("stdev", it->stdev); + channelStat.Set("minX", it->minX); + channelStat.Set("minY", it->minY); + channelStat.Set("maxX", it->maxX); + channelStat.Set("maxY", it->maxY); + channels.Set(i, channelStat); + } + + info.Set("channels", channels); + info.Set("isOpaque", baton->isOpaque); + info.Set("entropy", baton->entropy); + info.Set("sharpness", baton->sharpness); + Napi::Object dominant = Napi::Object::New(env); + dominant.Set("r", baton->dominantRed); + dominant.Set("g", baton->dominantGreen); + dominant.Set("b", baton->dominantBlue); + info.Set("dominant", dominant); + Callback().Call(Receiver().Value(), { env.Null(), info }); + } else { + Callback().Call(Receiver().Value(), { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() }); + } + + delete baton->input; + delete baton; + } + + private: + StatsBaton* baton; + Napi::FunctionReference debuglog; +}; + +/* + stats(options, callback) +*/ +Napi::Value stats(const Napi::CallbackInfo& info) { + // V8 objects are converted to non-V8 types held in the baton struct + StatsBaton *baton = new StatsBaton; + Napi::Object options = info[size_t(0)].As(); + + // Input + baton->input = sharp::CreateInputDescriptor(options.Get("input").As()); + baton->input->access = VIPS_ACCESS_RANDOM; + + // Function to notify of libvips warnings + Napi::Function debuglog = options.Get("debuglog").As(); + + // Join queue for worker thread + Napi::Function callback = info[size_t(1)].As(); + StatsWorker *worker = new StatsWorker(callback, baton, debuglog); + worker->Receiver().Set("options", options); + worker->Queue(); + + // Increment queued task counter + sharp::counterQueue++; + + return info.Env().Undefined(); +} diff --git a/server/node_modules/sharp/src/stats.h b/server/node_modules/sharp/src/stats.h new file mode 100644 index 0000000..c80e65f --- /dev/null +++ b/server/node_modules/sharp/src/stats.h @@ -0,0 +1,59 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#ifndef SRC_STATS_H_ +#define SRC_STATS_H_ + +#include +#include + +#include "./common.h" + +struct ChannelStats { + // stats per channel + int min; + int max; + double sum; + double squaresSum; + double mean; + double stdev; + int minX; + int minY; + int maxX; + int maxY; + + ChannelStats(int minVal, int maxVal, double sumVal, double squaresSumVal, + double meanVal, double stdevVal, int minXVal, int minYVal, int maxXVal, int maxYVal): + min(minVal), max(maxVal), sum(sumVal), squaresSum(squaresSumVal), + mean(meanVal), stdev(stdevVal), minX(minXVal), minY(minYVal), maxX(maxXVal), maxY(maxYVal) {} +}; + +struct StatsBaton { + // Input + sharp::InputDescriptor *input; + + // Output + std::vector channelStats; + bool isOpaque; + double entropy; + double sharpness; + int dominantRed; + int dominantGreen; + int dominantBlue; + + std::string err; + + StatsBaton(): + input(nullptr), + isOpaque(true), + entropy(0.0), + sharpness(0.0), + dominantRed(0), + dominantGreen(0), + dominantBlue(0) + {} +}; + +Napi::Value stats(const Napi::CallbackInfo& info); + +#endif // SRC_STATS_H_ diff --git a/server/node_modules/sharp/src/utilities.cc b/server/node_modules/sharp/src/utilities.cc new file mode 100644 index 0000000..1f78cdd --- /dev/null +++ b/server/node_modules/sharp/src/utilities.cc @@ -0,0 +1,286 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#include +#include +#include + +#include +#include +#include + +#include "common.h" +#include "operations.h" +#include "utilities.h" + +/* + Get and set cache limits +*/ +Napi::Value cache(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + + // Set memory limit + if (info[size_t(0)].IsNumber()) { + vips_cache_set_max_mem(info[size_t(0)].As().Int32Value() * 1048576); + } + // Set file limit + if (info[size_t(1)].IsNumber()) { + vips_cache_set_max_files(info[size_t(1)].As().Int32Value()); + } + // Set items limit + if (info[size_t(2)].IsNumber()) { + vips_cache_set_max(info[size_t(2)].As().Int32Value()); + } + + // Get memory stats + Napi::Object memory = Napi::Object::New(env); + memory.Set("current", round(vips_tracked_get_mem() / 1048576)); + memory.Set("high", round(vips_tracked_get_mem_highwater() / 1048576)); + memory.Set("max", round(vips_cache_get_max_mem() / 1048576)); + // Get file stats + Napi::Object files = Napi::Object::New(env); + files.Set("current", vips_tracked_get_files()); + files.Set("max", vips_cache_get_max_files()); + + // Get item stats + Napi::Object items = Napi::Object::New(env); + items.Set("current", vips_cache_get_size()); + items.Set("max", vips_cache_get_max()); + + Napi::Object cache = Napi::Object::New(env); + cache.Set("memory", memory); + cache.Set("files", files); + cache.Set("items", items); + return cache; +} + +/* + Get and set size of thread pool +*/ +Napi::Value concurrency(const Napi::CallbackInfo& info) { + // Set concurrency + if (info[size_t(0)].IsNumber()) { + vips_concurrency_set(info[size_t(0)].As().Int32Value()); + } + // Get concurrency + return Napi::Number::New(info.Env(), vips_concurrency_get()); +} + +/* + Get internal counters (queued tasks, processing tasks) +*/ +Napi::Value counters(const Napi::CallbackInfo& info) { + Napi::Object counters = Napi::Object::New(info.Env()); + counters.Set("queue", static_cast(sharp::counterQueue)); + counters.Set("process", static_cast(sharp::counterProcess)); + return counters; +} + +/* + Get and set use of SIMD vector unit instructions +*/ +Napi::Value simd(const Napi::CallbackInfo& info) { + // Set state + if (info[size_t(0)].IsBoolean()) { + vips_vector_set_enabled(info[size_t(0)].As().Value()); + } + // Get state + return Napi::Boolean::New(info.Env(), vips_vector_isenabled()); +} + +/* + Get libvips version +*/ +Napi::Value libvipsVersion(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + Napi::Object version = Napi::Object::New(env); + + char semver[9]; + std::snprintf(semver, sizeof(semver), "%d.%d.%d", vips_version(0), vips_version(1), vips_version(2)); + version.Set("semver", Napi::String::New(env, semver)); +#ifdef SHARP_USE_GLOBAL_LIBVIPS + version.Set("isGlobal", Napi::Boolean::New(env, true)); +#else + version.Set("isGlobal", Napi::Boolean::New(env, false)); +#endif +#ifdef __EMSCRIPTEN__ + version.Set("isWasm", Napi::Boolean::New(env, true)); +#else + version.Set("isWasm", Napi::Boolean::New(env, false)); +#endif + return version; +} + +/* + Get available input/output file/buffer/stream formats +*/ +Napi::Value format(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + Napi::Object format = Napi::Object::New(env); + for (std::string const f : { + "jpeg", "png", "webp", "tiff", "magick", "openslide", "dz", + "ppm", "fits", "gif", "svg", "heif", "pdf", "vips", "jp2k", "jxl", "rad", "dcraw" + }) { + // Input + const VipsObjectClass *oc = vips_class_find("VipsOperation", (f + "load").c_str()); + Napi::Boolean hasInputFile = Napi::Boolean::New(env, oc); + Napi::Boolean hasInputBuffer = + Napi::Boolean::New(env, vips_type_find("VipsOperation", (f + "load_buffer").c_str())); + Napi::Object input = Napi::Object::New(env); + input.Set("file", hasInputFile); + input.Set("buffer", hasInputBuffer); + input.Set("stream", hasInputBuffer); + if (hasInputFile) { + const VipsForeignClass *fc = VIPS_FOREIGN_CLASS(oc); + if (fc->suffs) { + Napi::Array fileSuffix = Napi::Array::New(env); + const char **suffix = fc->suffs; + for (int i = 0; *suffix; i++, suffix++) { + fileSuffix.Set(i, Napi::String::New(env, *suffix)); + } + input.Set("fileSuffix", fileSuffix); + } + } + // Output + Napi::Boolean hasOutputFile = + Napi::Boolean::New(env, vips_type_find("VipsOperation", (f + "save").c_str())); + Napi::Boolean hasOutputBuffer = + Napi::Boolean::New(env, vips_type_find("VipsOperation", (f + "save_buffer").c_str())); + Napi::Object output = Napi::Object::New(env); + output.Set("file", hasOutputFile); + output.Set("buffer", hasOutputBuffer); + output.Set("stream", hasOutputBuffer); + // Other attributes + Napi::Object container = Napi::Object::New(env); + container.Set("id", f); + container.Set("input", input); + container.Set("output", output); + // Add to set of formats + format.Set(f, container); + } + + // Raw, uncompressed data + Napi::Boolean supported = Napi::Boolean::New(env, true); + Napi::Boolean unsupported = Napi::Boolean::New(env, false); + Napi::Object rawInput = Napi::Object::New(env); + rawInput.Set("file", unsupported); + rawInput.Set("buffer", supported); + rawInput.Set("stream", supported); + Napi::Object rawOutput = Napi::Object::New(env); + rawOutput.Set("file", unsupported); + rawOutput.Set("buffer", supported); + rawOutput.Set("stream", supported); + Napi::Object raw = Napi::Object::New(env); + raw.Set("id", "raw"); + raw.Set("input", rawInput); + raw.Set("output", rawOutput); + format.Set("raw", raw); + + return format; +} + +/* + (Un)block libvips operations at runtime. +*/ +void block(const Napi::CallbackInfo& info) { + Napi::Array ops = info[size_t(0)].As(); + bool const state = info[size_t(1)].As().Value(); + for (unsigned int i = 0; i < ops.Length(); i++) { + vips_operation_block_set(ops.Get(i).As().Utf8Value().c_str(), state); + } +} + +/* + Synchronous, internal-only method used by some of the functional tests. + Calculates the maximum colour distance using the DE2000 algorithm + between two images of the same dimensions and number of channels. +*/ +Napi::Value _maxColourDistance(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + + // Open input files + VImage image1; + sharp::ImageType imageType1 = sharp::DetermineImageType(info[size_t(0)].As().Utf8Value().data()); + if (imageType1 != sharp::ImageType::UNKNOWN) { + try { + image1 = VImage::new_from_file(info[size_t(0)].As().Utf8Value().c_str()); + } catch (...) { + throw Napi::Error::New(env, "Input file 1 has corrupt header"); + } + } else { + throw Napi::Error::New(env, "Input file 1 is of an unsupported image format"); + } + VImage image2; + sharp::ImageType imageType2 = sharp::DetermineImageType(info[size_t(1)].As().Utf8Value().data()); + if (imageType2 != sharp::ImageType::UNKNOWN) { + try { + image2 = VImage::new_from_file(info[size_t(1)].As().Utf8Value().c_str()); + } catch (...) { + throw Napi::Error::New(env, "Input file 2 has corrupt header"); + } + } else { + throw Napi::Error::New(env, "Input file 2 is of an unsupported image format"); + } + // Ensure same number of channels + if (image1.bands() != image2.bands()) { + throw Napi::Error::New(env, "mismatchedBands"); + } + // Ensure same dimensions + if (image1.width() != image2.width() || image1.height() != image2.height()) { + throw Napi::Error::New(env, "mismatchedDimensions"); + } + + double maxColourDistance; + try { + // Premultiply and remove alpha + if (image1.has_alpha()) { + image1 = image1.premultiply().extract_band(1, VImage::option()->set("n", image1.bands() - 1)); + } + if (image2.has_alpha()) { + image2 = image2.premultiply().extract_band(1, VImage::option()->set("n", image2.bands() - 1)); + } + // Calculate colour distance + maxColourDistance = image1.dE00(image2).max(); + } catch (vips::VError const &err) { + throw Napi::Error::New(env, err.what()); + } + + // Clean up libvips' per-request data and threads + vips_error_clear(); + vips_thread_shutdown(); + + return Napi::Number::New(env, maxColourDistance); +} + +#if defined(__GNUC__) +// mallctl will be resolved by the runtime linker when jemalloc is being used +extern "C" { + int mallctl(const char *name, void *oldp, size_t *oldlenp, void *newp, size_t newlen) __attribute__((weak)); +} +Napi::Value _isUsingJemalloc(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + return Napi::Boolean::New(env, mallctl != nullptr); +} +#else +Napi::Value _isUsingJemalloc(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + return Napi::Boolean::New(env, false); +} +#endif + +#if defined(__GNUC__) && defined(__x86_64__) +// Are SSE 4.2 intrinsics available at runtime? +Napi::Value _isUsingX64V2(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + unsigned int eax, ebx, ecx, edx; + __asm__ __volatile__("cpuid" + : "=a"(eax), "=b"(ebx), "=c"(ecx), "=d"(edx) + : "a"(1)); + return Napi::Boolean::New(env, (ecx & 1U << 20) != 0); +} +#else +Napi::Value _isUsingX64V2(const Napi::CallbackInfo& info) { + Napi::Env env = info.Env(); + return Napi::Boolean::New(env, false); +} +#endif diff --git a/server/node_modules/sharp/src/utilities.h b/server/node_modules/sharp/src/utilities.h new file mode 100644 index 0000000..9272f95 --- /dev/null +++ b/server/node_modules/sharp/src/utilities.h @@ -0,0 +1,20 @@ +// Copyright 2013 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +#ifndef SRC_UTILITIES_H_ +#define SRC_UTILITIES_H_ + +#include + +Napi::Value cache(const Napi::CallbackInfo& info); +Napi::Value concurrency(const Napi::CallbackInfo& info); +Napi::Value counters(const Napi::CallbackInfo& info); +Napi::Value simd(const Napi::CallbackInfo& info); +Napi::Value libvipsVersion(const Napi::CallbackInfo& info); +Napi::Value format(const Napi::CallbackInfo& info); +void block(const Napi::CallbackInfo& info); +Napi::Value _maxColourDistance(const Napi::CallbackInfo& info); +Napi::Value _isUsingJemalloc(const Napi::CallbackInfo& info); +Napi::Value _isUsingX64V2(const Napi::CallbackInfo& info); + +#endif // SRC_UTILITIES_H_ diff --git a/server/node_modules/uuid/LICENSE.md b/server/node_modules/uuid/LICENSE.md new file mode 100644 index 0000000..3934168 --- /dev/null +++ b/server/node_modules/uuid/LICENSE.md @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2010-2020 Robert Kieffer and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/server/node_modules/uuid/README.md b/server/node_modules/uuid/README.md new file mode 100644 index 0000000..9bd966a --- /dev/null +++ b/server/node_modules/uuid/README.md @@ -0,0 +1,499 @@ + + +# uuid [![CI](https://github.com/uuidjs/uuid/workflows/CI/badge.svg)](https://github.com/uuidjs/uuid/actions?query=workflow%3ACI) [![Browser](https://github.com/uuidjs/uuid/workflows/Browser/badge.svg)](https://github.com/uuidjs/uuid/actions/workflows/browser.yml) + +For the creation of [RFC9562](https://www.rfc-editor.org/rfc/rfc9562.html) (formerly [RFC4122](https://www.rfc-editor.org/rfc/rfc4122.html)) UUIDs + +- **Complete** - Support for all RFC9562 UUID versions +- **Cross-platform** - Support for... + - [Typescript](#support) + - [Chrome, Safari, Firefox, and Edge](#support) + - [NodeJS](#support) + - [React Native / Expo](#react-native--expo) +- **Secure** - Uses modern `crypto` API for random values +- **Compact** - Zero-dependency, [tree-shakable](https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking) +- **CLI** - [`uuid` command line](#command-line) utility + + +> [!NOTE] +> +> Starting with `uuid@12` CommonJS is no longer supported. See [implications](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c) and [motivation](https://github.com/uuidjs/uuid/issues/881) for details. + +## Quickstart + +**1. Install** + +```shell +npm install uuid +``` + +**2. Create a UUID** + +```javascript +import { v4 as uuidv4 } from 'uuid'; + +uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' +``` + +For timestamp UUIDs, namespace UUIDs, and other options read on ... + +## API Summary + +| | | | +| --- | --- | --- | +| [`uuid.NIL`](#uuidnil) | The nil UUID string (all zeros) | New in `uuid@8.3` | +| [`uuid.MAX`](#uuidmax) | The max UUID string (all ones) | New in `uuid@9.1` | +| [`uuid.parse()`](#uuidparsestr) | Convert UUID string to array of bytes | New in `uuid@8.3` | +| [`uuid.stringify()`](#uuidstringifyarr-offset) | Convert array of bytes to UUID string | New in `uuid@8.3` | +| [`uuid.v1()`](#uuidv1options-buffer-offset) | Create a version 1 (timestamp) UUID | | +| [`uuid.v1ToV6()`](#uuidv1tov6uuid) | Create a version 6 UUID from a version 1 UUID | New in `uuid@10` | +| [`uuid.v3()`](#uuidv3name-namespace-buffer-offset) | Create a version 3 (namespace w/ MD5) UUID | | +| [`uuid.v4()`](#uuidv4options-buffer-offset) | Create a version 4 (random) UUID | | +| [`uuid.v5()`](#uuidv5name-namespace-buffer-offset) | Create a version 5 (namespace w/ SHA-1) UUID | | +| [`uuid.v6()`](#uuidv6options-buffer-offset) | Create a version 6 (timestamp, reordered) UUID | New in `uuid@10` | +| [`uuid.v6ToV1()`](#uuidv6tov1uuid) | Create a version 1 UUID from a version 6 UUID | New in `uuid@10` | +| [`uuid.v7()`](#uuidv7options-buffer-offset) | Create a version 7 (Unix Epoch time-based) UUID | New in `uuid@10` | +| ~~[`uuid.v8()`](#uuidv8)~~ | "Intentionally left blank" | | +| [`uuid.validate()`](#uuidvalidatestr) | Test a string to see if it is a valid UUID | New in `uuid@8.3` | +| [`uuid.version()`](#uuidversionstr) | Detect RFC version of a UUID | New in `uuid@8.3` | + +## API + +### uuid.NIL + +The nil UUID string (all zeros). + +Example: + +```javascript +import { NIL as NIL_UUID } from 'uuid'; + +NIL_UUID; // ⇨ '00000000-0000-0000-0000-000000000000' +``` + +### uuid.MAX + +The max UUID string (all ones). + +Example: + +```javascript +import { MAX as MAX_UUID } from 'uuid'; + +MAX_UUID; // ⇨ 'ffffffff-ffff-ffff-ffff-ffffffffffff' +``` + +### uuid.parse(str) + +Convert UUID string to array of bytes + +| | | +| --------- | ---------------------------------------- | +| `str` | A valid UUID `String` | +| _returns_ | `Uint8Array[16]` | +| _throws_ | `TypeError` if `str` is not a valid UUID | + + +> [!NOTE] +> Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left ↠ right order of hex-pairs in UUID strings. As shown in the example below. + +Example: + +```javascript +import { parse as uuidParse } from 'uuid'; + +// Parse a UUID +uuidParse('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ +// Uint8Array(16) [ +// 110, 192, 189, 127, 17, +// 192, 67, 218, 151, 94, +// 42, 138, 217, 235, 174, +// 11 +// ] +``` + +### uuid.stringify(arr[, offset]) + +Convert array of bytes to UUID string + +| | | +| -------------- | ---------------------------------------------------------------------------- | +| `arr` | `Array`-like collection of 16 values (starting from `offset`) between 0-255. | +| [`offset` = 0] | `Number` Starting index in the Array | +| _returns_ | `String` | +| _throws_ | `TypeError` if a valid UUID string cannot be generated | + + +> [!NOTE] +> Ordering of values in the byte arrays used by `parse()` and `stringify()` follows the left ↠ right order of hex-pairs in UUID strings. As shown in the example below. + +Example: + +```javascript +import { stringify as uuidStringify } from 'uuid'; + +const uuidBytes = Uint8Array.of( + 0x6e, + 0xc0, + 0xbd, + 0x7f, + 0x11, + 0xc0, + 0x43, + 0xda, + 0x97, + 0x5e, + 0x2a, + 0x8a, + 0xd9, + 0xeb, + 0xae, + 0x0b +); + +uuidStringify(uuidBytes); // ⇨ '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b' +``` + +### uuid.v1([options[, buffer[, offset]]]) + +Create an RFC version 1 (timestamp) UUID + +| | | +| --- | --- | +| [`options`] | `Object` with one or more of the following properties: | +| [`options.node = (random)` ] | RFC "node" field as an `Array[6]` of byte values (per 4.1.6) | +| [`options.clockseq = (random)`] | RFC "clock sequence" as a `Number` between 0 - 0x3fff | +| [`options.msecs = (current time)`] | RFC "timestamp" field (`Number` of milliseconds, unix epoch) | +| [`options.nsecs = 0`] | RFC "timestamp" field (`Number` of nanoseconds to add to `msecs`, should be 0-10,000) | +| [`options.random = (random)`] | `Array` of 16 random bytes (0-255) used to generate other fields, above | +| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | +| [`buffer`] | `Uint8Array` or `Uint8Array` subtype (e.g. Node.js `Buffer`). If provided, binary UUID is written into the array, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | +| _throws_ | `Error` if more than 10M UUIDs/sec are requested | + + +> [!NOTE] +> The default [node id](https://datatracker.ietf.org/doc/html/rfc9562#section-5.1) (the last 12 digits in the UUID) is generated once, randomly, on process startup, and then remains unchanged for the duration of the process. + + +> [!NOTE] +> `options.random` and `options.rng` are only meaningful on the very first call to `v1()`, where they may be passed to initialize the internal `node` and `clockseq` fields. + +Example: + +```javascript +import { v1 as uuidv1 } from 'uuid'; + +uuidv1(); // ⇨ '2c5ea4c0-4067-11e9-9b5d-ab8dfbbd4bed' +``` + +Example using `options`: + +```javascript +import { v1 as uuidv1 } from 'uuid'; + +const options = { + node: Uint8Array.of(0x01, 0x23, 0x45, 0x67, 0x89, 0xab), + clockseq: 0x1234, + msecs: new Date('2011-11-01').getTime(), + nsecs: 5678, +}; +uuidv1(options); // ⇨ '710b962e-041c-11e1-9234-0123456789ab' +``` + +### uuid.v1ToV6(uuid) + +Convert a UUID from version 1 to version 6 + +```javascript +import { v1ToV6 } from 'uuid'; + +v1ToV6('92f62d9e-22c4-11ef-97e9-325096b39f47'); // ⇨ '1ef22c49-2f62-6d9e-97e9-325096b39f47' +``` + +### uuid.v3(name, namespace[, buffer[, offset]]) + +Create an RFC version 3 (namespace w/ MD5) UUID + +API is identical to `v5()`, but uses "v3" instead. + + +> [!IMPORTANT] +> Per the RFC, "_If backward compatibility is not an issue, SHA-1 [Version 5] is preferred_." + +### uuid.v4([options[, buffer[, offset]]]) + +Create an RFC version 4 (random) UUID + +| | | +| --- | --- | +| [`options`] | `Object` with one or more of the following properties: | +| [`options.random`] | `Array` of 16 random bytes (0-255) | +| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | +| [`buffer`] | `Uint8Array` or `Uint8Array` subtype (e.g. Node.js `Buffer`). If provided, binary UUID is written into the array, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | + +Example: + +```javascript +import { v4 as uuidv4 } from 'uuid'; + +uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed' +``` + +Example using predefined `random` values: + +```javascript +import { v4 as uuidv4 } from 'uuid'; + +const v4options = { + random: Uint8Array.of( + 0x10, + 0x91, + 0x56, + 0xbe, + 0xc4, + 0xfb, + 0xc1, + 0xea, + 0x71, + 0xb4, + 0xef, + 0xe1, + 0x67, + 0x1c, + 0x58, + 0x36 + ), +}; +uuidv4(v4options); // ⇨ '109156be-c4fb-41ea-b1b4-efe1671c5836' +``` + +### uuid.v5(name, namespace[, buffer[, offset]]) + +Create an RFC version 5 (namespace w/ SHA-1) UUID + +| | | +| --- | --- | +| `name` | `String \| Array` | +| `namespace` | `String \| Array[16]` Namespace UUID | +| [`buffer`] | `Uint8Array` or `Uint8Array` subtype (e.g. Node.js `Buffer`). If provided, binary UUID is written into the array, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | + + +> [!NOTE] +> The RFC `DNS` and `URL` namespaces are available as `v5.DNS` and `v5.URL`. + +Example with custom namespace: + +```javascript +import { v5 as uuidv5 } from 'uuid'; + +// Define a custom namespace. Readers, create your own using something like +// https://www.uuidgenerator.net/ +const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341'; + +uuidv5('Hello, World!', MY_NAMESPACE); // ⇨ '630eb68f-e0fa-5ecc-887a-7c7a62614681' +``` + +Example with RFC `URL` namespace: + +```javascript +import { v5 as uuidv5 } from 'uuid'; + +uuidv5('https://www.w3.org/', uuidv5.URL); // ⇨ 'c106a26a-21bb-5538-8bf2-57095d1976c1' +``` + +### uuid.v6([options[, buffer[, offset]]]) + +Create an RFC version 6 (timestamp, reordered) UUID + +This method takes the same arguments as uuid.v1(). + +```javascript +import { v6 as uuidv6 } from 'uuid'; + +uuidv6(); // ⇨ '1e940672-c5ea-64c1-9bdd-2b0d7b3dcb6d' +``` + +Example using `options`: + +```javascript +import { v6 as uuidv6 } from 'uuid'; + +const options = { + node: [0x01, 0x23, 0x45, 0x67, 0x89, 0xab], + clockseq: 0x1234, + msecs: new Date('2011-11-01').getTime(), + nsecs: 5678, +}; +uuidv6(options); // ⇨ '1e1041c7-10b9-662e-9234-0123456789ab' +``` + +### uuid.v6ToV1(uuid) + +Convert a UUID from version 6 to version 1 + +```javascript +import { v6ToV1 } from 'uuid'; + +v6ToV1('1ef22c49-2f62-6d9e-97e9-325096b39f47'); // ⇨ '92f62d9e-22c4-11ef-97e9-325096b39f47' +``` + +### uuid.v7([options[, buffer[, offset]]]) + +Create an RFC version 7 (random) UUID + +| | | +| --- | --- | +| [`options`] | `Object` with one or more of the following properties: | +| [`options.msecs = (current time)`] | RFC "timestamp" field (`Number` of milliseconds, unix epoch) | +| [`options.random = (random)`] | `Array` of 16 random bytes (0-255) used to generate other fields, above | +| [`options.rng`] | Alternative to `options.random`, a `Function` that returns an `Array` of 16 random bytes (0-255) | +| [`options.seq = (random)`] | 32-bit sequence `Number` between 0 - 0xffffffff. This may be provided to help ensure uniqueness for UUIDs generated within the same millisecond time interval. Default = random value. | +| [`buffer`] | `Uint8Array` or `Uint8Array` subtype (e.g. Node.js `Buffer`). If provided, binary UUID is written into the array, starting at `offset` | +| [`offset` = 0] | `Number` Index to start writing UUID bytes in `buffer` | +| _returns_ | UUID `String` if no `buffer` is specified, otherwise returns `buffer` | + +Example: + +```javascript +import { v7 as uuidv7 } from 'uuid'; + +uuidv7(); // ⇨ '01695553-c90c-745a-b76f-770d7b3dcb6d' +``` + +### ~~uuid.v8()~~ + +**_"Intentionally left blank"_** + + +> [!NOTE] +> Version 8 (experimental) UUIDs are "[for experimental or vendor-specific use cases](https://www.rfc-editor.org/rfc/rfc9562.html#name-uuid-version-8)". The RFC does not define a creation algorithm for them, which is why this package does not offer a `v8()` method. The `validate()` and `version()` methods do work with such UUIDs, however. + +### uuid.validate(str) + +Test a string to see if it is a valid UUID + +| | | +| --------- | --------------------------------------------------- | +| `str` | `String` to validate | +| _returns_ | `true` if string is a valid UUID, `false` otherwise | + +Example: + +```javascript +import { validate as uuidValidate } from 'uuid'; + +uuidValidate('not a UUID'); // ⇨ false +uuidValidate('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ true +``` + +Using `validate` and `version` together it is possible to do per-version validation, e.g. validate for only v4 UUIds. + +```javascript +import { version as uuidVersion } from 'uuid'; +import { validate as uuidValidate } from 'uuid'; + +function uuidValidateV4(uuid) { + return uuidValidate(uuid) && uuidVersion(uuid) === 4; +} + +const v1Uuid = 'd9428888-122b-11e1-b85c-61cd3cbb3210'; +const v4Uuid = '109156be-c4fb-41ea-b1b4-efe1671c5836'; + +uuidValidateV4(v4Uuid); // ⇨ true +uuidValidateV4(v1Uuid); // ⇨ false +``` + +### uuid.version(str) + +Detect RFC version of a UUID + +| | | +| --------- | ---------------------------------------- | +| `str` | A valid UUID `String` | +| _returns_ | `Number` The RFC version of the UUID | +| _throws_ | `TypeError` if `str` is not a valid UUID | + +Example: + +```javascript +import { version as uuidVersion } from 'uuid'; + +uuidVersion('45637ec4-c85f-11ea-87d0-0242ac130003'); // ⇨ 1 +uuidVersion('6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'); // ⇨ 4 +``` + + +> [!NOTE] +> This method returns `0` for the `NIL` UUID, and `15` for the `MAX` UUID. + +## Command Line + +UUIDs can be generated from the command line using `uuid`. + +```shell +$ npx uuid +ddeb27fb-d9a0-4624-be4d-4615062daed4 +``` + +The default is to generate version 4 UUIDS, however the other versions are supported. Type `uuid --help` for details: + +```shell +$ npx uuid --help + +Usage: + uuid + uuid v1 + uuid v3 + uuid v4 + uuid v5 + uuid v7 + uuid --help + +Note: may be "URL" or "DNS" to use the corresponding UUIDs +defined by RFC9562 +``` + +## `options` Handling for Timestamp UUIDs + +Prior to `uuid@11`, it was possible for `options` state to interfere with the internal state used to ensure uniqueness of timestamp-based UUIDs (the `v1()`, `v6()`, and `v7()` methods). Starting with `uuid@11`, this issue has been addressed by using the presence of the `options` argument as a flag to select between two possible behaviors: + +- Without `options`: Internal state is utilized to improve UUID uniqueness. +- With `options`: Internal state is **NOT** used and, instead, appropriate defaults are applied as needed. + +## Support + +**Browsers**: `uuid` [builds are tested](/uuidjs/uuid/blob/main/wdio.conf.js) against the latest version of desktop Chrome, Safari, Firefox, and Edge. Mobile versions of these same browsers are expected to work but aren't currently tested. + +**Node**: `uuid` [builds are tested](https://github.com/uuidjs/uuid/blob/main/.github/workflows/ci.yml#L26-L27) against node ([LTS releases](https://github.com/nodejs/Release)), plus one prior. E.g. At the time of this writing `node@20` is the "maintenance" release and `node@24` is the "current" release, so `uuid` supports `node@18`-`node@24`. + +**Typescript**: TS versions released within the past two years are supported. [source](https://github.com/microsoft/TypeScript/issues/49088#issuecomment-2468723715) + +## Known issues + + + +### "getRandomValues() not supported" + +This error occurs in environments where the standard [`crypto.getRandomValues()`](https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues) API is not supported. This issue can be resolved by adding an appropriate polyfill: + +#### React Native / Expo + +1. Install [`react-native-get-random-values`](https://github.com/LinusU/react-native-get-random-values#readme) +1. Import it _before_ `uuid`. Since `uuid` might also appear as a transitive dependency of some other imports it's safest to just import `react-native-get-random-values` as the very first thing in your entry point: + +```javascript +import 'react-native-get-random-values'; +import { v4 as uuidv4 } from 'uuid'; +``` + +--- + +Markdown generated from [README_js.md](README_js.md) by diff --git a/server/node_modules/uuid/dist-node/bin/uuid b/server/node_modules/uuid/dist-node/bin/uuid new file mode 100755 index 0000000..b4f612d --- /dev/null +++ b/server/node_modules/uuid/dist-node/bin/uuid @@ -0,0 +1,2 @@ +#!/usr/bin/env node +import '../uuid-bin.js'; diff --git a/server/node_modules/uuid/dist-node/index.js b/server/node_modules/uuid/dist-node/index.js new file mode 100644 index 0000000..3193e9a --- /dev/null +++ b/server/node_modules/uuid/dist-node/index.js @@ -0,0 +1,14 @@ +export { default as MAX } from './max.js'; +export { default as NIL } from './nil.js'; +export { default as parse } from './parse.js'; +export { default as stringify } from './stringify.js'; +export { default as v1 } from './v1.js'; +export { default as v1ToV6 } from './v1ToV6.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as v6 } from './v6.js'; +export { default as v6ToV1 } from './v6ToV1.js'; +export { default as v7 } from './v7.js'; +export { default as validate } from './validate.js'; +export { default as version } from './version.js'; diff --git a/server/node_modules/uuid/dist-node/max.js b/server/node_modules/uuid/dist-node/max.js new file mode 100644 index 0000000..58951f6 --- /dev/null +++ b/server/node_modules/uuid/dist-node/max.js @@ -0,0 +1 @@ +export default 'ffffffff-ffff-ffff-ffff-ffffffffffff'; diff --git a/server/node_modules/uuid/dist-node/md5.js b/server/node_modules/uuid/dist-node/md5.js new file mode 100644 index 0000000..4fae485 --- /dev/null +++ b/server/node_modules/uuid/dist-node/md5.js @@ -0,0 +1,11 @@ +import { createHash } from 'node:crypto'; +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } + else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + return createHash('md5').update(bytes).digest(); +} +export default md5; diff --git a/server/node_modules/uuid/dist-node/native.js b/server/node_modules/uuid/dist-node/native.js new file mode 100644 index 0000000..7f8062b --- /dev/null +++ b/server/node_modules/uuid/dist-node/native.js @@ -0,0 +1,2 @@ +import { randomUUID } from 'node:crypto'; +export default { randomUUID }; diff --git a/server/node_modules/uuid/dist-node/nil.js b/server/node_modules/uuid/dist-node/nil.js new file mode 100644 index 0000000..de6f830 --- /dev/null +++ b/server/node_modules/uuid/dist-node/nil.js @@ -0,0 +1 @@ +export default '00000000-0000-0000-0000-000000000000'; diff --git a/server/node_modules/uuid/dist-node/parse.js b/server/node_modules/uuid/dist-node/parse.js new file mode 100644 index 0000000..64ac401 --- /dev/null +++ b/server/node_modules/uuid/dist-node/parse.js @@ -0,0 +1,9 @@ +import validate from './validate.js'; +function parse(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + let v; + return Uint8Array.of((v = parseInt(uuid.slice(0, 8), 16)) >>> 24, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff, (v = parseInt(uuid.slice(9, 13), 16)) >>> 8, v & 0xff, (v = parseInt(uuid.slice(14, 18), 16)) >>> 8, v & 0xff, (v = parseInt(uuid.slice(19, 23), 16)) >>> 8, v & 0xff, ((v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000) & 0xff, (v / 0x100000000) & 0xff, (v >>> 24) & 0xff, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff); +} +export default parse; diff --git a/server/node_modules/uuid/dist-node/regex.js b/server/node_modules/uuid/dist-node/regex.js new file mode 100644 index 0000000..3e38591 --- /dev/null +++ b/server/node_modules/uuid/dist-node/regex.js @@ -0,0 +1 @@ +export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; diff --git a/server/node_modules/uuid/dist-node/rng.js b/server/node_modules/uuid/dist-node/rng.js new file mode 100644 index 0000000..5dcaf3c --- /dev/null +++ b/server/node_modules/uuid/dist-node/rng.js @@ -0,0 +1,10 @@ +import { randomFillSync } from 'node:crypto'; +const rnds8Pool = new Uint8Array(256); +let poolPtr = rnds8Pool.length; +export default function rng() { + if (poolPtr > rnds8Pool.length - 16) { + randomFillSync(rnds8Pool); + poolPtr = 0; + } + return rnds8Pool.slice(poolPtr, (poolPtr += 16)); +} diff --git a/server/node_modules/uuid/dist-node/sha1.js b/server/node_modules/uuid/dist-node/sha1.js new file mode 100644 index 0000000..7dfd27c --- /dev/null +++ b/server/node_modules/uuid/dist-node/sha1.js @@ -0,0 +1,11 @@ +import { createHash } from 'node:crypto'; +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } + else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + return createHash('sha1').update(bytes).digest(); +} +export default sha1; diff --git a/server/node_modules/uuid/dist-node/stringify.js b/server/node_modules/uuid/dist-node/stringify.js new file mode 100644 index 0000000..962738c --- /dev/null +++ b/server/node_modules/uuid/dist-node/stringify.js @@ -0,0 +1,35 @@ +import validate from './validate.js'; +const byteToHex = []; +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} +export function unsafeStringify(arr, offset = 0) { + return (byteToHex[arr[offset + 0]] + + byteToHex[arr[offset + 1]] + + byteToHex[arr[offset + 2]] + + byteToHex[arr[offset + 3]] + + '-' + + byteToHex[arr[offset + 4]] + + byteToHex[arr[offset + 5]] + + '-' + + byteToHex[arr[offset + 6]] + + byteToHex[arr[offset + 7]] + + '-' + + byteToHex[arr[offset + 8]] + + byteToHex[arr[offset + 9]] + + '-' + + byteToHex[arr[offset + 10]] + + byteToHex[arr[offset + 11]] + + byteToHex[arr[offset + 12]] + + byteToHex[arr[offset + 13]] + + byteToHex[arr[offset + 14]] + + byteToHex[arr[offset + 15]]).toLowerCase(); +} +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); + if (!validate(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + return uuid; +} +export default stringify; diff --git a/server/node_modules/uuid/dist-node/types.js b/server/node_modules/uuid/dist-node/types.js new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/server/node_modules/uuid/dist-node/types.js @@ -0,0 +1 @@ +export {}; diff --git a/server/node_modules/uuid/dist-node/uuid-bin.js b/server/node_modules/uuid/dist-node/uuid-bin.js new file mode 100644 index 0000000..aa4d4ac --- /dev/null +++ b/server/node_modules/uuid/dist-node/uuid-bin.js @@ -0,0 +1,70 @@ +import * as assert from 'node:assert/strict'; +import v1 from './v1.js'; +import v3 from './v3.js'; +import v4 from './v4.js'; +import v5 from './v5.js'; +import v6 from './v6.js'; +import v7 from './v7.js'; +function usage() { + console.log('Usage:'); + console.log(' uuid'); + console.log(' uuid v1'); + console.log(' uuid v3 '); + console.log(' uuid v4'); + console.log(' uuid v5 '); + console.log(' uuid v6'); + console.log(' uuid v7'); + console.log(' uuid --help'); + console.log('\nNote: may be "URL" or "DNS" to use the corresponding UUIDs defined by RFC9562'); +} +const args = process.argv.slice(2); +if (args.indexOf('--help') >= 0) { + usage(); + process.exit(0); +} +const version = args.shift() || 'v4'; +switch (version) { + case 'v1': + console.log(v1()); + break; + case 'v3': { + const name = args.shift(); + let namespace = args.shift(); + assert.ok(name != null, 'v3 name not specified'); + assert.ok(namespace != null, 'v3 namespace not specified'); + if (namespace === 'URL') { + namespace = v3.URL; + } + if (namespace === 'DNS') { + namespace = v3.DNS; + } + console.log(v3(name, namespace)); + break; + } + case 'v4': + console.log(v4()); + break; + case 'v5': { + const name = args.shift(); + let namespace = args.shift(); + assert.ok(name != null, 'v5 name not specified'); + assert.ok(namespace != null, 'v5 namespace not specified'); + if (namespace === 'URL') { + namespace = v5.URL; + } + if (namespace === 'DNS') { + namespace = v5.DNS; + } + console.log(v5(name, namespace)); + break; + } + case 'v6': + console.log(v6()); + break; + case 'v7': + console.log(v7()); + break; + default: + usage(); + process.exit(1); +} diff --git a/server/node_modules/uuid/dist-node/v1.js b/server/node_modules/uuid/dist-node/v1.js new file mode 100644 index 0000000..65e3f68 --- /dev/null +++ b/server/node_modules/uuid/dist-node/v1.js @@ -0,0 +1,83 @@ +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; +const _state = {}; +function v1(options, buf, offset) { + let bytes; + const isV6 = options?._v6 ?? false; + if (options) { + const optionsKeys = Object.keys(options); + if (optionsKeys.length === 1 && optionsKeys[0] === '_v6') { + options = undefined; + } + } + if (options) { + bytes = v1Bytes(options.random ?? options.rng?.() ?? rng(), options.msecs, options.nsecs, options.clockseq, options.node, buf, offset); + } + else { + const now = Date.now(); + const rnds = rng(); + updateV1State(_state, now, rnds); + bytes = v1Bytes(rnds, _state.msecs, _state.nsecs, isV6 ? undefined : _state.clockseq, isV6 ? undefined : _state.node, buf, offset); + } + return buf ?? unsafeStringify(bytes); +} +export function updateV1State(state, now, rnds) { + state.msecs ??= -Infinity; + state.nsecs ??= 0; + if (now === state.msecs) { + state.nsecs++; + if (state.nsecs >= 10000) { + state.node = undefined; + state.nsecs = 0; + } + } + else if (now > state.msecs) { + state.nsecs = 0; + } + else if (now < state.msecs) { + state.node = undefined; + } + if (!state.node) { + state.node = rnds.slice(10, 16); + state.node[0] |= 0x01; + state.clockseq = ((rnds[8] << 8) | rnds[9]) & 0x3fff; + } + state.msecs = now; + return state; +} +function v1Bytes(rnds, msecs, nsecs, clockseq, node, buf, offset = 0) { + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + if (!buf) { + buf = new Uint8Array(16); + offset = 0; + } + else { + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + } + msecs ??= Date.now(); + nsecs ??= 0; + clockseq ??= ((rnds[8] << 8) | rnds[9]) & 0x3fff; + node ??= rnds.slice(10, 16); + msecs += 12219292800000; + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + buf[offset++] = (tl >>> 24) & 0xff; + buf[offset++] = (tl >>> 16) & 0xff; + buf[offset++] = (tl >>> 8) & 0xff; + buf[offset++] = tl & 0xff; + const tmh = ((msecs / 0x100000000) * 10000) & 0xfffffff; + buf[offset++] = (tmh >>> 8) & 0xff; + buf[offset++] = tmh & 0xff; + buf[offset++] = ((tmh >>> 24) & 0xf) | 0x10; + buf[offset++] = (tmh >>> 16) & 0xff; + buf[offset++] = (clockseq >>> 8) | 0x80; + buf[offset++] = clockseq & 0xff; + for (let n = 0; n < 6; ++n) { + buf[offset++] = node[n]; + } + return buf; +} +export default v1; diff --git a/server/node_modules/uuid/dist-node/v1ToV6.js b/server/node_modules/uuid/dist-node/v1ToV6.js new file mode 100644 index 0000000..da0f763 --- /dev/null +++ b/server/node_modules/uuid/dist-node/v1ToV6.js @@ -0,0 +1,10 @@ +import parse from './parse.js'; +import { unsafeStringify } from './stringify.js'; +export default function v1ToV6(uuid) { + const v1Bytes = typeof uuid === 'string' ? parse(uuid) : uuid; + const v6Bytes = _v1ToV6(v1Bytes); + return typeof uuid === 'string' ? unsafeStringify(v6Bytes) : v6Bytes; +} +function _v1ToV6(v1Bytes) { + return Uint8Array.of(((v1Bytes[6] & 0x0f) << 4) | ((v1Bytes[7] >> 4) & 0x0f), ((v1Bytes[7] & 0x0f) << 4) | ((v1Bytes[4] & 0xf0) >> 4), ((v1Bytes[4] & 0x0f) << 4) | ((v1Bytes[5] & 0xf0) >> 4), ((v1Bytes[5] & 0x0f) << 4) | ((v1Bytes[0] & 0xf0) >> 4), ((v1Bytes[0] & 0x0f) << 4) | ((v1Bytes[1] & 0xf0) >> 4), ((v1Bytes[1] & 0x0f) << 4) | ((v1Bytes[2] & 0xf0) >> 4), 0x60 | (v1Bytes[2] & 0x0f), v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]); +} diff --git a/server/node_modules/uuid/dist-node/v3.js b/server/node_modules/uuid/dist-node/v3.js new file mode 100644 index 0000000..b5c3781 --- /dev/null +++ b/server/node_modules/uuid/dist-node/v3.js @@ -0,0 +1,9 @@ +import md5 from './md5.js'; +import v35, { DNS, URL } from './v35.js'; +export { DNS, URL } from './v35.js'; +function v3(value, namespace, buf, offset) { + return v35(0x30, md5, value, namespace, buf, offset); +} +v3.DNS = DNS; +v3.URL = URL; +export default v3; diff --git a/server/node_modules/uuid/dist-node/v35.js b/server/node_modules/uuid/dist-node/v35.js new file mode 100644 index 0000000..3fe6573 --- /dev/null +++ b/server/node_modules/uuid/dist-node/v35.js @@ -0,0 +1,36 @@ +import parse from './parse.js'; +import { unsafeStringify } from './stringify.js'; +export function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); + const bytes = new Uint8Array(str.length); + for (let i = 0; i < str.length; ++i) { + bytes[i] = str.charCodeAt(i); + } + return bytes; +} +export const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +export const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +export default function v35(version, hash, value, namespace, buf, offset) { + const valueBytes = typeof value === 'string' ? stringToBytes(value) : value; + const namespaceBytes = typeof namespace === 'string' ? parse(namespace) : namespace; + if (typeof namespace === 'string') { + namespace = parse(namespace); + } + if (namespace?.length !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } + let bytes = new Uint8Array(16 + valueBytes.length); + bytes.set(namespaceBytes); + bytes.set(valueBytes, namespaceBytes.length); + bytes = hash(bytes); + bytes[6] = (bytes[6] & 0x0f) | version; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + if (buf) { + offset = offset || 0; + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + return buf; + } + return unsafeStringify(bytes); +} diff --git a/server/node_modules/uuid/dist-node/v4.js b/server/node_modules/uuid/dist-node/v4.js new file mode 100644 index 0000000..cc9dc2d --- /dev/null +++ b/server/node_modules/uuid/dist-node/v4.js @@ -0,0 +1,30 @@ +import native from './native.js'; +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; +function _v4(options, buf, offset) { + options = options || {}; + const rnds = options.random ?? options.rng?.() ?? rng(); + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; + if (buf) { + offset = offset || 0; + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + return buf; + } + return unsafeStringify(rnds); +} +function v4(options, buf, offset) { + if (native.randomUUID && !buf && !options) { + return native.randomUUID(); + } + return _v4(options, buf, offset); +} +export default v4; diff --git a/server/node_modules/uuid/dist-node/v5.js b/server/node_modules/uuid/dist-node/v5.js new file mode 100644 index 0000000..bd470a4 --- /dev/null +++ b/server/node_modules/uuid/dist-node/v5.js @@ -0,0 +1,9 @@ +import sha1 from './sha1.js'; +import v35, { DNS, URL } from './v35.js'; +export { DNS, URL } from './v35.js'; +function v5(value, namespace, buf, offset) { + return v35(0x50, sha1, value, namespace, buf, offset); +} +v5.DNS = DNS; +v5.URL = URL; +export default v5; diff --git a/server/node_modules/uuid/dist-node/v6.js b/server/node_modules/uuid/dist-node/v6.js new file mode 100644 index 0000000..278a339 --- /dev/null +++ b/server/node_modules/uuid/dist-node/v6.js @@ -0,0 +1,17 @@ +import { unsafeStringify } from './stringify.js'; +import v1 from './v1.js'; +import v1ToV6 from './v1ToV6.js'; +function v6(options, buf, offset) { + options ??= {}; + offset ??= 0; + let bytes = v1({ ...options, _v6: true }, new Uint8Array(16)); + bytes = v1ToV6(bytes); + if (buf) { + for (let i = 0; i < 16; i++) { + buf[offset + i] = bytes[i]; + } + return buf; + } + return unsafeStringify(bytes); +} +export default v6; diff --git a/server/node_modules/uuid/dist-node/v6ToV1.js b/server/node_modules/uuid/dist-node/v6ToV1.js new file mode 100644 index 0000000..bfd942f --- /dev/null +++ b/server/node_modules/uuid/dist-node/v6ToV1.js @@ -0,0 +1,10 @@ +import parse from './parse.js'; +import { unsafeStringify } from './stringify.js'; +export default function v6ToV1(uuid) { + const v6Bytes = typeof uuid === 'string' ? parse(uuid) : uuid; + const v1Bytes = _v6ToV1(v6Bytes); + return typeof uuid === 'string' ? unsafeStringify(v1Bytes) : v1Bytes; +} +function _v6ToV1(v6Bytes) { + return Uint8Array.of(((v6Bytes[3] & 0x0f) << 4) | ((v6Bytes[4] >> 4) & 0x0f), ((v6Bytes[4] & 0x0f) << 4) | ((v6Bytes[5] & 0xf0) >> 4), ((v6Bytes[5] & 0x0f) << 4) | (v6Bytes[6] & 0x0f), v6Bytes[7], ((v6Bytes[1] & 0x0f) << 4) | ((v6Bytes[2] & 0xf0) >> 4), ((v6Bytes[2] & 0x0f) << 4) | ((v6Bytes[3] & 0xf0) >> 4), 0x10 | ((v6Bytes[0] & 0xf0) >> 4), ((v6Bytes[0] & 0x0f) << 4) | ((v6Bytes[1] & 0xf0) >> 4), v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]); +} diff --git a/server/node_modules/uuid/dist-node/v7.js b/server/node_modules/uuid/dist-node/v7.js new file mode 100644 index 0000000..276c9bf --- /dev/null +++ b/server/node_modules/uuid/dist-node/v7.js @@ -0,0 +1,65 @@ +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; +const _state = {}; +function v7(options, buf, offset) { + let bytes; + if (options) { + bytes = v7Bytes(options.random ?? options.rng?.() ?? rng(), options.msecs, options.seq, buf, offset); + } + else { + const now = Date.now(); + const rnds = rng(); + updateV7State(_state, now, rnds); + bytes = v7Bytes(rnds, _state.msecs, _state.seq, buf, offset); + } + return buf ?? unsafeStringify(bytes); +} +export function updateV7State(state, now, rnds) { + state.msecs ??= -Infinity; + state.seq ??= 0; + if (now > state.msecs) { + state.seq = (rnds[6] << 23) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9]; + state.msecs = now; + } + else { + state.seq = (state.seq + 1) | 0; + if (state.seq === 0) { + state.msecs++; + } + } + return state; +} +function v7Bytes(rnds, msecs, seq, buf, offset = 0) { + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + if (!buf) { + buf = new Uint8Array(16); + offset = 0; + } + else { + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + } + msecs ??= Date.now(); + seq ??= ((rnds[6] * 0x7f) << 24) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9]; + buf[offset++] = (msecs / 0x10000000000) & 0xff; + buf[offset++] = (msecs / 0x100000000) & 0xff; + buf[offset++] = (msecs / 0x1000000) & 0xff; + buf[offset++] = (msecs / 0x10000) & 0xff; + buf[offset++] = (msecs / 0x100) & 0xff; + buf[offset++] = msecs & 0xff; + buf[offset++] = 0x70 | ((seq >>> 28) & 0x0f); + buf[offset++] = (seq >>> 20) & 0xff; + buf[offset++] = 0x80 | ((seq >>> 14) & 0x3f); + buf[offset++] = (seq >>> 6) & 0xff; + buf[offset++] = ((seq << 2) & 0xff) | (rnds[10] & 0x03); + buf[offset++] = rnds[11]; + buf[offset++] = rnds[12]; + buf[offset++] = rnds[13]; + buf[offset++] = rnds[14]; + buf[offset++] = rnds[15]; + return buf; +} +export default v7; diff --git a/server/node_modules/uuid/dist-node/validate.js b/server/node_modules/uuid/dist-node/validate.js new file mode 100644 index 0000000..444a1a2 --- /dev/null +++ b/server/node_modules/uuid/dist-node/validate.js @@ -0,0 +1,5 @@ +import REGEX from './regex.js'; +function validate(uuid) { + return typeof uuid === 'string' && REGEX.test(uuid); +} +export default validate; diff --git a/server/node_modules/uuid/dist-node/version.js b/server/node_modules/uuid/dist-node/version.js new file mode 100644 index 0000000..bae91d3 --- /dev/null +++ b/server/node_modules/uuid/dist-node/version.js @@ -0,0 +1,8 @@ +import validate from './validate.js'; +function version(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + return parseInt(uuid.slice(14, 15), 16); +} +export default version; diff --git a/server/node_modules/uuid/dist/index.d.ts b/server/node_modules/uuid/dist/index.d.ts new file mode 100644 index 0000000..d7d4edc --- /dev/null +++ b/server/node_modules/uuid/dist/index.d.ts @@ -0,0 +1,15 @@ +export type * from './types.js'; +export { default as MAX } from './max.js'; +export { default as NIL } from './nil.js'; +export { default as parse } from './parse.js'; +export { default as stringify } from './stringify.js'; +export { default as v1 } from './v1.js'; +export { default as v1ToV6 } from './v1ToV6.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as v6 } from './v6.js'; +export { default as v6ToV1 } from './v6ToV1.js'; +export { default as v7 } from './v7.js'; +export { default as validate } from './validate.js'; +export { default as version } from './version.js'; diff --git a/server/node_modules/uuid/dist/index.js b/server/node_modules/uuid/dist/index.js new file mode 100644 index 0000000..3193e9a --- /dev/null +++ b/server/node_modules/uuid/dist/index.js @@ -0,0 +1,14 @@ +export { default as MAX } from './max.js'; +export { default as NIL } from './nil.js'; +export { default as parse } from './parse.js'; +export { default as stringify } from './stringify.js'; +export { default as v1 } from './v1.js'; +export { default as v1ToV6 } from './v1ToV6.js'; +export { default as v3 } from './v3.js'; +export { default as v4 } from './v4.js'; +export { default as v5 } from './v5.js'; +export { default as v6 } from './v6.js'; +export { default as v6ToV1 } from './v6ToV1.js'; +export { default as v7 } from './v7.js'; +export { default as validate } from './validate.js'; +export { default as version } from './version.js'; diff --git a/server/node_modules/uuid/dist/max.d.ts b/server/node_modules/uuid/dist/max.d.ts new file mode 100644 index 0000000..7a1e972 --- /dev/null +++ b/server/node_modules/uuid/dist/max.d.ts @@ -0,0 +1,2 @@ +declare const _default: "ffffffff-ffff-ffff-ffff-ffffffffffff"; +export default _default; diff --git a/server/node_modules/uuid/dist/max.js b/server/node_modules/uuid/dist/max.js new file mode 100644 index 0000000..58951f6 --- /dev/null +++ b/server/node_modules/uuid/dist/max.js @@ -0,0 +1 @@ +export default 'ffffffff-ffff-ffff-ffff-ffffffffffff'; diff --git a/server/node_modules/uuid/dist/md5.d.ts b/server/node_modules/uuid/dist/md5.d.ts new file mode 100644 index 0000000..5a55f51 --- /dev/null +++ b/server/node_modules/uuid/dist/md5.d.ts @@ -0,0 +1,2 @@ +declare function md5(bytes: Uint8Array): Uint8Array; +export default md5; diff --git a/server/node_modules/uuid/dist/md5.js b/server/node_modules/uuid/dist/md5.js new file mode 100644 index 0000000..918be8c --- /dev/null +++ b/server/node_modules/uuid/dist/md5.js @@ -0,0 +1,135 @@ +function md5(bytes) { + const words = uint8ToUint32(bytes); + const md5Bytes = wordsToMd5(words, bytes.length * 8); + return uint32ToUint8(md5Bytes); +} +function uint32ToUint8(input) { + const bytes = new Uint8Array(input.length * 4); + for (let i = 0; i < input.length * 4; i++) { + bytes[i] = (input[i >> 2] >>> ((i % 4) * 8)) & 0xff; + } + return bytes; +} +function getOutputLength(inputLength8) { + return (((inputLength8 + 64) >>> 9) << 4) + 14 + 1; +} +function wordsToMd5(x, len) { + const xpad = new Uint32Array(getOutputLength(len)).fill(0); + xpad.set(x); + xpad[len >> 5] |= 0x80 << len % 32; + xpad[xpad.length - 1] = len; + x = xpad; + let a = 1732584193; + let b = -271733879; + let c = -1732584194; + let d = 271733878; + for (let i = 0; i < x.length; i += 16) { + const olda = a; + const oldb = b; + const oldc = c; + const oldd = d; + a = md5ff(a, b, c, d, x[i], 7, -680876936); + d = md5ff(d, a, b, c, x[i + 1], 12, -389564586); + c = md5ff(c, d, a, b, x[i + 2], 17, 606105819); + b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330); + a = md5ff(a, b, c, d, x[i + 4], 7, -176418897); + d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426); + c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341); + b = md5ff(b, c, d, a, x[i + 7], 22, -45705983); + a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416); + d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417); + c = md5ff(c, d, a, b, x[i + 10], 17, -42063); + b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162); + a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682); + d = md5ff(d, a, b, c, x[i + 13], 12, -40341101); + c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290); + b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329); + a = md5gg(a, b, c, d, x[i + 1], 5, -165796510); + d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632); + c = md5gg(c, d, a, b, x[i + 11], 14, 643717713); + b = md5gg(b, c, d, a, x[i], 20, -373897302); + a = md5gg(a, b, c, d, x[i + 5], 5, -701558691); + d = md5gg(d, a, b, c, x[i + 10], 9, 38016083); + c = md5gg(c, d, a, b, x[i + 15], 14, -660478335); + b = md5gg(b, c, d, a, x[i + 4], 20, -405537848); + a = md5gg(a, b, c, d, x[i + 9], 5, 568446438); + d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690); + c = md5gg(c, d, a, b, x[i + 3], 14, -187363961); + b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501); + a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467); + d = md5gg(d, a, b, c, x[i + 2], 9, -51403784); + c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473); + b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734); + a = md5hh(a, b, c, d, x[i + 5], 4, -378558); + d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463); + c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562); + b = md5hh(b, c, d, a, x[i + 14], 23, -35309556); + a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060); + d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353); + c = md5hh(c, d, a, b, x[i + 7], 16, -155497632); + b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640); + a = md5hh(a, b, c, d, x[i + 13], 4, 681279174); + d = md5hh(d, a, b, c, x[i], 11, -358537222); + c = md5hh(c, d, a, b, x[i + 3], 16, -722521979); + b = md5hh(b, c, d, a, x[i + 6], 23, 76029189); + a = md5hh(a, b, c, d, x[i + 9], 4, -640364487); + d = md5hh(d, a, b, c, x[i + 12], 11, -421815835); + c = md5hh(c, d, a, b, x[i + 15], 16, 530742520); + b = md5hh(b, c, d, a, x[i + 2], 23, -995338651); + a = md5ii(a, b, c, d, x[i], 6, -198630844); + d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415); + c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905); + b = md5ii(b, c, d, a, x[i + 5], 21, -57434055); + a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571); + d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606); + c = md5ii(c, d, a, b, x[i + 10], 15, -1051523); + b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799); + a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359); + d = md5ii(d, a, b, c, x[i + 15], 10, -30611744); + c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380); + b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649); + a = md5ii(a, b, c, d, x[i + 4], 6, -145523070); + d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379); + c = md5ii(c, d, a, b, x[i + 2], 15, 718787259); + b = md5ii(b, c, d, a, x[i + 9], 21, -343485551); + a = safeAdd(a, olda); + b = safeAdd(b, oldb); + c = safeAdd(c, oldc); + d = safeAdd(d, oldd); + } + return Uint32Array.of(a, b, c, d); +} +function uint8ToUint32(input) { + if (input.length === 0) { + return new Uint32Array(); + } + const output = new Uint32Array(getOutputLength(input.length * 8)).fill(0); + for (let i = 0; i < input.length; i++) { + output[i >> 2] |= (input[i] & 0xff) << ((i % 4) * 8); + } + return output; +} +function safeAdd(x, y) { + const lsw = (x & 0xffff) + (y & 0xffff); + const msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return (msw << 16) | (lsw & 0xffff); +} +function bitRotateLeft(num, cnt) { + return (num << cnt) | (num >>> (32 - cnt)); +} +function md5cmn(q, a, b, x, s, t) { + return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b); +} +function md5ff(a, b, c, d, x, s, t) { + return md5cmn((b & c) | (~b & d), a, b, x, s, t); +} +function md5gg(a, b, c, d, x, s, t) { + return md5cmn((b & d) | (c & ~d), a, b, x, s, t); +} +function md5hh(a, b, c, d, x, s, t) { + return md5cmn(b ^ c ^ d, a, b, x, s, t); +} +function md5ii(a, b, c, d, x, s, t) { + return md5cmn(c ^ (b | ~d), a, b, x, s, t); +} +export default md5; diff --git a/server/node_modules/uuid/dist/native.d.ts b/server/node_modules/uuid/dist/native.d.ts new file mode 100644 index 0000000..9418fd3 --- /dev/null +++ b/server/node_modules/uuid/dist/native.d.ts @@ -0,0 +1,4 @@ +declare const _default: { + randomUUID: false | (() => `${string}-${string}-${string}-${string}-${string}`); +}; +export default _default; diff --git a/server/node_modules/uuid/dist/native.js b/server/node_modules/uuid/dist/native.js new file mode 100644 index 0000000..76f44f9 --- /dev/null +++ b/server/node_modules/uuid/dist/native.js @@ -0,0 +1,2 @@ +const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto); +export default { randomUUID }; diff --git a/server/node_modules/uuid/dist/nil.d.ts b/server/node_modules/uuid/dist/nil.d.ts new file mode 100644 index 0000000..b03bb98 --- /dev/null +++ b/server/node_modules/uuid/dist/nil.d.ts @@ -0,0 +1,2 @@ +declare const _default: "00000000-0000-0000-0000-000000000000"; +export default _default; diff --git a/server/node_modules/uuid/dist/nil.js b/server/node_modules/uuid/dist/nil.js new file mode 100644 index 0000000..de6f830 --- /dev/null +++ b/server/node_modules/uuid/dist/nil.js @@ -0,0 +1 @@ +export default '00000000-0000-0000-0000-000000000000'; diff --git a/server/node_modules/uuid/dist/parse.d.ts b/server/node_modules/uuid/dist/parse.d.ts new file mode 100644 index 0000000..a316fb1 --- /dev/null +++ b/server/node_modules/uuid/dist/parse.d.ts @@ -0,0 +1,2 @@ +declare function parse(uuid: string): Uint8Array; +export default parse; diff --git a/server/node_modules/uuid/dist/parse.js b/server/node_modules/uuid/dist/parse.js new file mode 100644 index 0000000..64ac401 --- /dev/null +++ b/server/node_modules/uuid/dist/parse.js @@ -0,0 +1,9 @@ +import validate from './validate.js'; +function parse(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + let v; + return Uint8Array.of((v = parseInt(uuid.slice(0, 8), 16)) >>> 24, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff, (v = parseInt(uuid.slice(9, 13), 16)) >>> 8, v & 0xff, (v = parseInt(uuid.slice(14, 18), 16)) >>> 8, v & 0xff, (v = parseInt(uuid.slice(19, 23), 16)) >>> 8, v & 0xff, ((v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000) & 0xff, (v / 0x100000000) & 0xff, (v >>> 24) & 0xff, (v >>> 16) & 0xff, (v >>> 8) & 0xff, v & 0xff); +} +export default parse; diff --git a/server/node_modules/uuid/dist/regex.d.ts b/server/node_modules/uuid/dist/regex.d.ts new file mode 100644 index 0000000..d39fa3f --- /dev/null +++ b/server/node_modules/uuid/dist/regex.d.ts @@ -0,0 +1,2 @@ +declare const _default: RegExp; +export default _default; diff --git a/server/node_modules/uuid/dist/regex.js b/server/node_modules/uuid/dist/regex.js new file mode 100644 index 0000000..3e38591 --- /dev/null +++ b/server/node_modules/uuid/dist/regex.js @@ -0,0 +1 @@ +export default /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; diff --git a/server/node_modules/uuid/dist/rng.d.ts b/server/node_modules/uuid/dist/rng.d.ts new file mode 100644 index 0000000..73e60cf --- /dev/null +++ b/server/node_modules/uuid/dist/rng.d.ts @@ -0,0 +1 @@ +export default function rng(): Uint8Array; diff --git a/server/node_modules/uuid/dist/rng.js b/server/node_modules/uuid/dist/rng.js new file mode 100644 index 0000000..770f2e2 --- /dev/null +++ b/server/node_modules/uuid/dist/rng.js @@ -0,0 +1,11 @@ +let getRandomValues; +const rnds8 = new Uint8Array(16); +export default function rng() { + if (!getRandomValues) { + if (typeof crypto === 'undefined' || !crypto.getRandomValues) { + throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported'); + } + getRandomValues = crypto.getRandomValues.bind(crypto); + } + return getRandomValues(rnds8); +} diff --git a/server/node_modules/uuid/dist/sha1.d.ts b/server/node_modules/uuid/dist/sha1.d.ts new file mode 100644 index 0000000..a6552e5 --- /dev/null +++ b/server/node_modules/uuid/dist/sha1.d.ts @@ -0,0 +1,2 @@ +declare function sha1(bytes: Uint8Array): Uint8Array; +export default sha1; diff --git a/server/node_modules/uuid/dist/sha1.js b/server/node_modules/uuid/dist/sha1.js new file mode 100644 index 0000000..dbb78ae --- /dev/null +++ b/server/node_modules/uuid/dist/sha1.js @@ -0,0 +1,70 @@ +function f(s, x, y, z) { + switch (s) { + case 0: + return (x & y) ^ (~x & z); + case 1: + return x ^ y ^ z; + case 2: + return (x & y) ^ (x & z) ^ (y & z); + case 3: + return x ^ y ^ z; + } +} +function ROTL(x, n) { + return (x << n) | (x >>> (32 - n)); +} +function sha1(bytes) { + const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6]; + const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0]; + const newBytes = new Uint8Array(bytes.length + 1); + newBytes.set(bytes); + newBytes[bytes.length] = 0x80; + bytes = newBytes; + const l = bytes.length / 4 + 2; + const N = Math.ceil(l / 16); + const M = new Array(N); + for (let i = 0; i < N; ++i) { + const arr = new Uint32Array(16); + for (let j = 0; j < 16; ++j) { + arr[j] = + (bytes[i * 64 + j * 4] << 24) | + (bytes[i * 64 + j * 4 + 1] << 16) | + (bytes[i * 64 + j * 4 + 2] << 8) | + bytes[i * 64 + j * 4 + 3]; + } + M[i] = arr; + } + M[N - 1][14] = ((bytes.length - 1) * 8) / Math.pow(2, 32); + M[N - 1][14] = Math.floor(M[N - 1][14]); + M[N - 1][15] = ((bytes.length - 1) * 8) & 0xffffffff; + for (let i = 0; i < N; ++i) { + const W = new Uint32Array(80); + for (let t = 0; t < 16; ++t) { + W[t] = M[i][t]; + } + for (let t = 16; t < 80; ++t) { + W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1); + } + let a = H[0]; + let b = H[1]; + let c = H[2]; + let d = H[3]; + let e = H[4]; + for (let t = 0; t < 80; ++t) { + const s = Math.floor(t / 20); + const T = (ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t]) >>> 0; + e = d; + d = c; + c = ROTL(b, 30) >>> 0; + b = a; + a = T; + } + H[0] = (H[0] + a) >>> 0; + H[1] = (H[1] + b) >>> 0; + H[2] = (H[2] + c) >>> 0; + H[3] = (H[3] + d) >>> 0; + H[4] = (H[4] + e) >>> 0; + } + return Uint8Array.of(H[0] >> 24, H[0] >> 16, H[0] >> 8, H[0], H[1] >> 24, H[1] >> 16, H[1] >> 8, H[1], H[2] >> 24, H[2] >> 16, H[2] >> 8, H[2], H[3] >> 24, H[3] >> 16, H[3] >> 8, H[3], H[4] >> 24, H[4] >> 16, H[4] >> 8, H[4]); +} +export default sha1; diff --git a/server/node_modules/uuid/dist/stringify.d.ts b/server/node_modules/uuid/dist/stringify.d.ts new file mode 100644 index 0000000..16cb008 --- /dev/null +++ b/server/node_modules/uuid/dist/stringify.d.ts @@ -0,0 +1,3 @@ +export declare function unsafeStringify(arr: Uint8Array, offset?: number): string; +declare function stringify(arr: Uint8Array, offset?: number): string; +export default stringify; diff --git a/server/node_modules/uuid/dist/stringify.js b/server/node_modules/uuid/dist/stringify.js new file mode 100644 index 0000000..962738c --- /dev/null +++ b/server/node_modules/uuid/dist/stringify.js @@ -0,0 +1,35 @@ +import validate from './validate.js'; +const byteToHex = []; +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} +export function unsafeStringify(arr, offset = 0) { + return (byteToHex[arr[offset + 0]] + + byteToHex[arr[offset + 1]] + + byteToHex[arr[offset + 2]] + + byteToHex[arr[offset + 3]] + + '-' + + byteToHex[arr[offset + 4]] + + byteToHex[arr[offset + 5]] + + '-' + + byteToHex[arr[offset + 6]] + + byteToHex[arr[offset + 7]] + + '-' + + byteToHex[arr[offset + 8]] + + byteToHex[arr[offset + 9]] + + '-' + + byteToHex[arr[offset + 10]] + + byteToHex[arr[offset + 11]] + + byteToHex[arr[offset + 12]] + + byteToHex[arr[offset + 13]] + + byteToHex[arr[offset + 14]] + + byteToHex[arr[offset + 15]]).toLowerCase(); +} +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); + if (!validate(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + return uuid; +} +export default stringify; diff --git a/server/node_modules/uuid/dist/types.d.ts b/server/node_modules/uuid/dist/types.d.ts new file mode 100644 index 0000000..ecaed97 --- /dev/null +++ b/server/node_modules/uuid/dist/types.d.ts @@ -0,0 +1,21 @@ +export type UUIDTypes = string | TBuf; +export type Version1Options = { + node?: Uint8Array; + clockseq?: number; + random?: Uint8Array; + rng?: () => Uint8Array; + msecs?: number; + nsecs?: number; + _v6?: boolean; +}; +export type Version4Options = { + random?: Uint8Array; + rng?: () => Uint8Array; +}; +export type Version6Options = Version1Options; +export type Version7Options = { + random?: Uint8Array; + msecs?: number; + seq?: number; + rng?: () => Uint8Array; +}; diff --git a/server/node_modules/uuid/dist/types.js b/server/node_modules/uuid/dist/types.js new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/server/node_modules/uuid/dist/types.js @@ -0,0 +1 @@ +export {}; diff --git a/server/node_modules/uuid/dist/uuid-bin.d.ts b/server/node_modules/uuid/dist/uuid-bin.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/server/node_modules/uuid/dist/uuid-bin.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/server/node_modules/uuid/dist/uuid-bin.js b/server/node_modules/uuid/dist/uuid-bin.js new file mode 100644 index 0000000..aa4d4ac --- /dev/null +++ b/server/node_modules/uuid/dist/uuid-bin.js @@ -0,0 +1,70 @@ +import * as assert from 'node:assert/strict'; +import v1 from './v1.js'; +import v3 from './v3.js'; +import v4 from './v4.js'; +import v5 from './v5.js'; +import v6 from './v6.js'; +import v7 from './v7.js'; +function usage() { + console.log('Usage:'); + console.log(' uuid'); + console.log(' uuid v1'); + console.log(' uuid v3 '); + console.log(' uuid v4'); + console.log(' uuid v5 '); + console.log(' uuid v6'); + console.log(' uuid v7'); + console.log(' uuid --help'); + console.log('\nNote: may be "URL" or "DNS" to use the corresponding UUIDs defined by RFC9562'); +} +const args = process.argv.slice(2); +if (args.indexOf('--help') >= 0) { + usage(); + process.exit(0); +} +const version = args.shift() || 'v4'; +switch (version) { + case 'v1': + console.log(v1()); + break; + case 'v3': { + const name = args.shift(); + let namespace = args.shift(); + assert.ok(name != null, 'v3 name not specified'); + assert.ok(namespace != null, 'v3 namespace not specified'); + if (namespace === 'URL') { + namespace = v3.URL; + } + if (namespace === 'DNS') { + namespace = v3.DNS; + } + console.log(v3(name, namespace)); + break; + } + case 'v4': + console.log(v4()); + break; + case 'v5': { + const name = args.shift(); + let namespace = args.shift(); + assert.ok(name != null, 'v5 name not specified'); + assert.ok(namespace != null, 'v5 namespace not specified'); + if (namespace === 'URL') { + namespace = v5.URL; + } + if (namespace === 'DNS') { + namespace = v5.DNS; + } + console.log(v5(name, namespace)); + break; + } + case 'v6': + console.log(v6()); + break; + case 'v7': + console.log(v7()); + break; + default: + usage(); + process.exit(1); +} diff --git a/server/node_modules/uuid/dist/v1.d.ts b/server/node_modules/uuid/dist/v1.d.ts new file mode 100644 index 0000000..d8ecee0 --- /dev/null +++ b/server/node_modules/uuid/dist/v1.d.ts @@ -0,0 +1,11 @@ +import { Version1Options } from './types.js'; +type V1State = { + node?: Uint8Array; + clockseq?: number; + msecs?: number; + nsecs?: number; +}; +declare function v1(options?: Version1Options, buf?: undefined, offset?: number): string; +declare function v1(options: Version1Options | undefined, buf: Buf, offset?: number): Buf; +export declare function updateV1State(state: V1State, now: number, rnds: Uint8Array): V1State; +export default v1; diff --git a/server/node_modules/uuid/dist/v1.js b/server/node_modules/uuid/dist/v1.js new file mode 100644 index 0000000..65e3f68 --- /dev/null +++ b/server/node_modules/uuid/dist/v1.js @@ -0,0 +1,83 @@ +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; +const _state = {}; +function v1(options, buf, offset) { + let bytes; + const isV6 = options?._v6 ?? false; + if (options) { + const optionsKeys = Object.keys(options); + if (optionsKeys.length === 1 && optionsKeys[0] === '_v6') { + options = undefined; + } + } + if (options) { + bytes = v1Bytes(options.random ?? options.rng?.() ?? rng(), options.msecs, options.nsecs, options.clockseq, options.node, buf, offset); + } + else { + const now = Date.now(); + const rnds = rng(); + updateV1State(_state, now, rnds); + bytes = v1Bytes(rnds, _state.msecs, _state.nsecs, isV6 ? undefined : _state.clockseq, isV6 ? undefined : _state.node, buf, offset); + } + return buf ?? unsafeStringify(bytes); +} +export function updateV1State(state, now, rnds) { + state.msecs ??= -Infinity; + state.nsecs ??= 0; + if (now === state.msecs) { + state.nsecs++; + if (state.nsecs >= 10000) { + state.node = undefined; + state.nsecs = 0; + } + } + else if (now > state.msecs) { + state.nsecs = 0; + } + else if (now < state.msecs) { + state.node = undefined; + } + if (!state.node) { + state.node = rnds.slice(10, 16); + state.node[0] |= 0x01; + state.clockseq = ((rnds[8] << 8) | rnds[9]) & 0x3fff; + } + state.msecs = now; + return state; +} +function v1Bytes(rnds, msecs, nsecs, clockseq, node, buf, offset = 0) { + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + if (!buf) { + buf = new Uint8Array(16); + offset = 0; + } + else { + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + } + msecs ??= Date.now(); + nsecs ??= 0; + clockseq ??= ((rnds[8] << 8) | rnds[9]) & 0x3fff; + node ??= rnds.slice(10, 16); + msecs += 12219292800000; + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + buf[offset++] = (tl >>> 24) & 0xff; + buf[offset++] = (tl >>> 16) & 0xff; + buf[offset++] = (tl >>> 8) & 0xff; + buf[offset++] = tl & 0xff; + const tmh = ((msecs / 0x100000000) * 10000) & 0xfffffff; + buf[offset++] = (tmh >>> 8) & 0xff; + buf[offset++] = tmh & 0xff; + buf[offset++] = ((tmh >>> 24) & 0xf) | 0x10; + buf[offset++] = (tmh >>> 16) & 0xff; + buf[offset++] = (clockseq >>> 8) | 0x80; + buf[offset++] = clockseq & 0xff; + for (let n = 0; n < 6; ++n) { + buf[offset++] = node[n]; + } + return buf; +} +export default v1; diff --git a/server/node_modules/uuid/dist/v1ToV6.d.ts b/server/node_modules/uuid/dist/v1ToV6.d.ts new file mode 100644 index 0000000..38eaaf0 --- /dev/null +++ b/server/node_modules/uuid/dist/v1ToV6.d.ts @@ -0,0 +1,2 @@ +export default function v1ToV6(uuid: string): string; +export default function v1ToV6(uuid: Uint8Array): Uint8Array; diff --git a/server/node_modules/uuid/dist/v1ToV6.js b/server/node_modules/uuid/dist/v1ToV6.js new file mode 100644 index 0000000..da0f763 --- /dev/null +++ b/server/node_modules/uuid/dist/v1ToV6.js @@ -0,0 +1,10 @@ +import parse from './parse.js'; +import { unsafeStringify } from './stringify.js'; +export default function v1ToV6(uuid) { + const v1Bytes = typeof uuid === 'string' ? parse(uuid) : uuid; + const v6Bytes = _v1ToV6(v1Bytes); + return typeof uuid === 'string' ? unsafeStringify(v6Bytes) : v6Bytes; +} +function _v1ToV6(v1Bytes) { + return Uint8Array.of(((v1Bytes[6] & 0x0f) << 4) | ((v1Bytes[7] >> 4) & 0x0f), ((v1Bytes[7] & 0x0f) << 4) | ((v1Bytes[4] & 0xf0) >> 4), ((v1Bytes[4] & 0x0f) << 4) | ((v1Bytes[5] & 0xf0) >> 4), ((v1Bytes[5] & 0x0f) << 4) | ((v1Bytes[0] & 0xf0) >> 4), ((v1Bytes[0] & 0x0f) << 4) | ((v1Bytes[1] & 0xf0) >> 4), ((v1Bytes[1] & 0x0f) << 4) | ((v1Bytes[2] & 0xf0) >> 4), 0x60 | (v1Bytes[2] & 0x0f), v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]); +} diff --git a/server/node_modules/uuid/dist/v3.d.ts b/server/node_modules/uuid/dist/v3.d.ts new file mode 100644 index 0000000..5d1c434 --- /dev/null +++ b/server/node_modules/uuid/dist/v3.d.ts @@ -0,0 +1,9 @@ +import { UUIDTypes } from './types.js'; +export { DNS, URL } from './v35.js'; +declare function v3(value: string | Uint8Array, namespace: UUIDTypes, buf?: undefined, offset?: number): string; +declare function v3(value: string | Uint8Array, namespace: UUIDTypes, buf: TBuf, offset?: number): TBuf; +declare namespace v3 { + var DNS: string; + var URL: string; +} +export default v3; diff --git a/server/node_modules/uuid/dist/v3.js b/server/node_modules/uuid/dist/v3.js new file mode 100644 index 0000000..b5c3781 --- /dev/null +++ b/server/node_modules/uuid/dist/v3.js @@ -0,0 +1,9 @@ +import md5 from './md5.js'; +import v35, { DNS, URL } from './v35.js'; +export { DNS, URL } from './v35.js'; +function v3(value, namespace, buf, offset) { + return v35(0x30, md5, value, namespace, buf, offset); +} +v3.DNS = DNS; +v3.URL = URL; +export default v3; diff --git a/server/node_modules/uuid/dist/v35.d.ts b/server/node_modules/uuid/dist/v35.d.ts new file mode 100644 index 0000000..4e6e9d5 --- /dev/null +++ b/server/node_modules/uuid/dist/v35.d.ts @@ -0,0 +1,7 @@ +import { UUIDTypes } from './types.js'; +export declare function stringToBytes(str: string): Uint8Array; +export declare const DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; +export declare const URL = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"; +type HashFunction = (bytes: Uint8Array) => Uint8Array; +export default function v35(version: 0x30 | 0x50, hash: HashFunction, value: string | Uint8Array, namespace: UUIDTypes, buf?: TBuf, offset?: number): UUIDTypes; +export {}; diff --git a/server/node_modules/uuid/dist/v35.js b/server/node_modules/uuid/dist/v35.js new file mode 100644 index 0000000..3fe6573 --- /dev/null +++ b/server/node_modules/uuid/dist/v35.js @@ -0,0 +1,36 @@ +import parse from './parse.js'; +import { unsafeStringify } from './stringify.js'; +export function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); + const bytes = new Uint8Array(str.length); + for (let i = 0; i < str.length; ++i) { + bytes[i] = str.charCodeAt(i); + } + return bytes; +} +export const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +export const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +export default function v35(version, hash, value, namespace, buf, offset) { + const valueBytes = typeof value === 'string' ? stringToBytes(value) : value; + const namespaceBytes = typeof namespace === 'string' ? parse(namespace) : namespace; + if (typeof namespace === 'string') { + namespace = parse(namespace); + } + if (namespace?.length !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } + let bytes = new Uint8Array(16 + valueBytes.length); + bytes.set(namespaceBytes); + bytes.set(valueBytes, namespaceBytes.length); + bytes = hash(bytes); + bytes[6] = (bytes[6] & 0x0f) | version; + bytes[8] = (bytes[8] & 0x3f) | 0x80; + if (buf) { + offset = offset || 0; + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + return buf; + } + return unsafeStringify(bytes); +} diff --git a/server/node_modules/uuid/dist/v4.d.ts b/server/node_modules/uuid/dist/v4.d.ts new file mode 100644 index 0000000..8205333 --- /dev/null +++ b/server/node_modules/uuid/dist/v4.d.ts @@ -0,0 +1,4 @@ +import { Version4Options } from './types.js'; +declare function v4(options?: Version4Options, buf?: undefined, offset?: number): string; +declare function v4(options: Version4Options | undefined, buf: TBuf, offset?: number): TBuf; +export default v4; diff --git a/server/node_modules/uuid/dist/v4.js b/server/node_modules/uuid/dist/v4.js new file mode 100644 index 0000000..cc9dc2d --- /dev/null +++ b/server/node_modules/uuid/dist/v4.js @@ -0,0 +1,30 @@ +import native from './native.js'; +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; +function _v4(options, buf, offset) { + options = options || {}; + const rnds = options.random ?? options.rng?.() ?? rng(); + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; + if (buf) { + offset = offset || 0; + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + return buf; + } + return unsafeStringify(rnds); +} +function v4(options, buf, offset) { + if (native.randomUUID && !buf && !options) { + return native.randomUUID(); + } + return _v4(options, buf, offset); +} +export default v4; diff --git a/server/node_modules/uuid/dist/v5.d.ts b/server/node_modules/uuid/dist/v5.d.ts new file mode 100644 index 0000000..0e2ff2f --- /dev/null +++ b/server/node_modules/uuid/dist/v5.d.ts @@ -0,0 +1,9 @@ +import { UUIDTypes } from './types.js'; +export { DNS, URL } from './v35.js'; +declare function v5(value: string | Uint8Array, namespace: UUIDTypes, buf?: undefined, offset?: number): string; +declare function v5(value: string | Uint8Array, namespace: UUIDTypes, buf: TBuf, offset?: number): TBuf; +declare namespace v5 { + var DNS: string; + var URL: string; +} +export default v5; diff --git a/server/node_modules/uuid/dist/v5.js b/server/node_modules/uuid/dist/v5.js new file mode 100644 index 0000000..bd470a4 --- /dev/null +++ b/server/node_modules/uuid/dist/v5.js @@ -0,0 +1,9 @@ +import sha1 from './sha1.js'; +import v35, { DNS, URL } from './v35.js'; +export { DNS, URL } from './v35.js'; +function v5(value, namespace, buf, offset) { + return v35(0x50, sha1, value, namespace, buf, offset); +} +v5.DNS = DNS; +v5.URL = URL; +export default v5; diff --git a/server/node_modules/uuid/dist/v6.d.ts b/server/node_modules/uuid/dist/v6.d.ts new file mode 100644 index 0000000..cabf4a0 --- /dev/null +++ b/server/node_modules/uuid/dist/v6.d.ts @@ -0,0 +1,4 @@ +import { Version6Options } from './types.js'; +declare function v6(options?: Version6Options, buf?: undefined, offset?: number): string; +declare function v6(options: Version6Options | undefined, buf: TBuf, offset?: number): TBuf; +export default v6; diff --git a/server/node_modules/uuid/dist/v6.js b/server/node_modules/uuid/dist/v6.js new file mode 100644 index 0000000..278a339 --- /dev/null +++ b/server/node_modules/uuid/dist/v6.js @@ -0,0 +1,17 @@ +import { unsafeStringify } from './stringify.js'; +import v1 from './v1.js'; +import v1ToV6 from './v1ToV6.js'; +function v6(options, buf, offset) { + options ??= {}; + offset ??= 0; + let bytes = v1({ ...options, _v6: true }, new Uint8Array(16)); + bytes = v1ToV6(bytes); + if (buf) { + for (let i = 0; i < 16; i++) { + buf[offset + i] = bytes[i]; + } + return buf; + } + return unsafeStringify(bytes); +} +export default v6; diff --git a/server/node_modules/uuid/dist/v6ToV1.d.ts b/server/node_modules/uuid/dist/v6ToV1.d.ts new file mode 100644 index 0000000..3b3ffc2 --- /dev/null +++ b/server/node_modules/uuid/dist/v6ToV1.d.ts @@ -0,0 +1,2 @@ +export default function v6ToV1(uuid: string): string; +export default function v6ToV1(uuid: Uint8Array): Uint8Array; diff --git a/server/node_modules/uuid/dist/v6ToV1.js b/server/node_modules/uuid/dist/v6ToV1.js new file mode 100644 index 0000000..bfd942f --- /dev/null +++ b/server/node_modules/uuid/dist/v6ToV1.js @@ -0,0 +1,10 @@ +import parse from './parse.js'; +import { unsafeStringify } from './stringify.js'; +export default function v6ToV1(uuid) { + const v6Bytes = typeof uuid === 'string' ? parse(uuid) : uuid; + const v1Bytes = _v6ToV1(v6Bytes); + return typeof uuid === 'string' ? unsafeStringify(v1Bytes) : v1Bytes; +} +function _v6ToV1(v6Bytes) { + return Uint8Array.of(((v6Bytes[3] & 0x0f) << 4) | ((v6Bytes[4] >> 4) & 0x0f), ((v6Bytes[4] & 0x0f) << 4) | ((v6Bytes[5] & 0xf0) >> 4), ((v6Bytes[5] & 0x0f) << 4) | (v6Bytes[6] & 0x0f), v6Bytes[7], ((v6Bytes[1] & 0x0f) << 4) | ((v6Bytes[2] & 0xf0) >> 4), ((v6Bytes[2] & 0x0f) << 4) | ((v6Bytes[3] & 0xf0) >> 4), 0x10 | ((v6Bytes[0] & 0xf0) >> 4), ((v6Bytes[0] & 0x0f) << 4) | ((v6Bytes[1] & 0xf0) >> 4), v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]); +} diff --git a/server/node_modules/uuid/dist/v7.d.ts b/server/node_modules/uuid/dist/v7.d.ts new file mode 100644 index 0000000..f49b03d --- /dev/null +++ b/server/node_modules/uuid/dist/v7.d.ts @@ -0,0 +1,9 @@ +import { Version7Options } from './types.js'; +type V7State = { + msecs?: number; + seq?: number; +}; +declare function v7(options?: Version7Options, buf?: undefined, offset?: number): string; +declare function v7(options: Version7Options | undefined, buf: TBuf, offset?: number): TBuf; +export declare function updateV7State(state: V7State, now: number, rnds: Uint8Array): V7State; +export default v7; diff --git a/server/node_modules/uuid/dist/v7.js b/server/node_modules/uuid/dist/v7.js new file mode 100644 index 0000000..276c9bf --- /dev/null +++ b/server/node_modules/uuid/dist/v7.js @@ -0,0 +1,65 @@ +import rng from './rng.js'; +import { unsafeStringify } from './stringify.js'; +const _state = {}; +function v7(options, buf, offset) { + let bytes; + if (options) { + bytes = v7Bytes(options.random ?? options.rng?.() ?? rng(), options.msecs, options.seq, buf, offset); + } + else { + const now = Date.now(); + const rnds = rng(); + updateV7State(_state, now, rnds); + bytes = v7Bytes(rnds, _state.msecs, _state.seq, buf, offset); + } + return buf ?? unsafeStringify(bytes); +} +export function updateV7State(state, now, rnds) { + state.msecs ??= -Infinity; + state.seq ??= 0; + if (now > state.msecs) { + state.seq = (rnds[6] << 23) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9]; + state.msecs = now; + } + else { + state.seq = (state.seq + 1) | 0; + if (state.seq === 0) { + state.msecs++; + } + } + return state; +} +function v7Bytes(rnds, msecs, seq, buf, offset = 0) { + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + if (!buf) { + buf = new Uint8Array(16); + offset = 0; + } + else { + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + } + msecs ??= Date.now(); + seq ??= ((rnds[6] * 0x7f) << 24) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9]; + buf[offset++] = (msecs / 0x10000000000) & 0xff; + buf[offset++] = (msecs / 0x100000000) & 0xff; + buf[offset++] = (msecs / 0x1000000) & 0xff; + buf[offset++] = (msecs / 0x10000) & 0xff; + buf[offset++] = (msecs / 0x100) & 0xff; + buf[offset++] = msecs & 0xff; + buf[offset++] = 0x70 | ((seq >>> 28) & 0x0f); + buf[offset++] = (seq >>> 20) & 0xff; + buf[offset++] = 0x80 | ((seq >>> 14) & 0x3f); + buf[offset++] = (seq >>> 6) & 0xff; + buf[offset++] = ((seq << 2) & 0xff) | (rnds[10] & 0x03); + buf[offset++] = rnds[11]; + buf[offset++] = rnds[12]; + buf[offset++] = rnds[13]; + buf[offset++] = rnds[14]; + buf[offset++] = rnds[15]; + return buf; +} +export default v7; diff --git a/server/node_modules/uuid/dist/validate.d.ts b/server/node_modules/uuid/dist/validate.d.ts new file mode 100644 index 0000000..57da03d --- /dev/null +++ b/server/node_modules/uuid/dist/validate.d.ts @@ -0,0 +1,2 @@ +declare function validate(uuid: unknown): boolean; +export default validate; diff --git a/server/node_modules/uuid/dist/validate.js b/server/node_modules/uuid/dist/validate.js new file mode 100644 index 0000000..444a1a2 --- /dev/null +++ b/server/node_modules/uuid/dist/validate.js @@ -0,0 +1,5 @@ +import REGEX from './regex.js'; +function validate(uuid) { + return typeof uuid === 'string' && REGEX.test(uuid); +} +export default validate; diff --git a/server/node_modules/uuid/dist/version.d.ts b/server/node_modules/uuid/dist/version.d.ts new file mode 100644 index 0000000..f1948dc --- /dev/null +++ b/server/node_modules/uuid/dist/version.d.ts @@ -0,0 +1,2 @@ +declare function version(uuid: string): number; +export default version; diff --git a/server/node_modules/uuid/dist/version.js b/server/node_modules/uuid/dist/version.js new file mode 100644 index 0000000..bae91d3 --- /dev/null +++ b/server/node_modules/uuid/dist/version.js @@ -0,0 +1,8 @@ +import validate from './validate.js'; +function version(uuid) { + if (!validate(uuid)) { + throw TypeError('Invalid UUID'); + } + return parseInt(uuid.slice(14, 15), 16); +} +export default version; diff --git a/server/node_modules/uuid/package.json b/server/node_modules/uuid/package.json new file mode 100644 index 0000000..ebc7c2b --- /dev/null +++ b/server/node_modules/uuid/package.json @@ -0,0 +1,119 @@ +{ + "name": "uuid", + "version": "13.0.0", + "description": "RFC9562 UUIDs", + "type": "module", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "commitlint": { + "extends": [ + "@commitlint/config-conventional" + ] + }, + "keywords": [ + "uuid", + "guid", + "rfc4122", + "rfc9562" + ], + "license": "MIT", + "bin": { + "uuid": "./dist-node/bin/uuid" + }, + "sideEffects": false, + "types": "./dist/index.d.ts", + "exports": { + ".": { + "node": "./dist-node/index.js", + "default": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "files": [ + "dist", + "dist-node", + "!**/test" + ], + "devDependencies": { + "@babel/eslint-parser": "7.27.1", + "@commitlint/cli": "19.8.0", + "@commitlint/config-conventional": "19.8.0", + "@eslint/js": "9.26.0", + "bundlewatch": "0.4.1", + "commander": "13.1.0", + "eslint": "9.26.0", + "eslint-config-prettier": "10.1.2", + "eslint-plugin-prettier": "5.4.0", + "globals": "16.0.0", + "husky": "9.1.7", + "jest": "29.7.0", + "lint-staged": "15.5.2", + "neostandard": "0.12.1", + "npm-run-all": "4.1.5", + "prettier": "3.5.3", + "release-please": "17.0.0", + "runmd": "1.4.1", + "standard-version": "9.5.0", + "typescript": "5.2.2", + "typescript-eslint": "8.32.0" + }, + "optionalDevDependencies": { + "@wdio/browserstack-service": "9.2.1", + "@wdio/cli": "9.2.1", + "@wdio/jasmine-framework": "9.2.1", + "@wdio/local-runner": "9.2.1", + "@wdio/spec-reporter": "9.1.3", + "@wdio/static-server-service": "9.1.3" + }, + "scripts": { + "build": "./scripts/build.sh", + "build:watch": "tsc --watch -p tsconfig.json", + "bundlewatch": "npm run pretest:browser && bundlewatch --config bundlewatch.config.json", + "docs:diff": "npm run docs && git diff --quiet -I \"[0-9a-f-]{36}\" README.md", + "docs": "npm run build && npx runmd --output=README.md README_js.md", + "eslint:check": "eslint src/ test/ examples/ *.[jt]s", + "eslint:fix": "eslint --fix src/ test/ examples/ *.[jt]s", + "examples:browser:rollup:build": "cd examples/browser-rollup && npm run build", + "examples:browser:webpack:build": "cd examples/browser-webpack && npm run build", + "examples:node:esmodules:test": "cd examples/node-esmodules && npm test", + "examples:node:jest:test": "cd examples/node-jest && npm test", + "examples:node:typescript:test": "cd examples/typescript && npm test", + "lint": "npm run eslint:check && npm run prettier:check", + "md": "runmd --watch --output=README.md README_js.md", + "prepack": "npm run build -- --no-pack", + "prepare": "husky", + "prepublishOnly": "npm run build", + "pretest:benchmark": "npm run build", + "pretest:browser": "./scripts/iodd && npm run build && npm-run-all --parallel examples:browser:**", + "pretest:node": "npm run build", + "pretest": "npm run build", + "prettier:check": "prettier --check .", + "prettier:fix": "prettier --write .", + "release": "standard-version --no-verify", + "test:benchmark": "cd examples/benchmark && npm test", + "test:browser": "wdio run ./wdio.conf.js", + "test:node": "npm-run-all --parallel examples:node:**", + "test:watch": "node --test --enable-source-maps --watch dist-node/test/*.js", + "test": "node --test --enable-source-maps dist-node/test/*.js" + }, + "repository": { + "type": "git", + "url": "https://github.com/uuidjs/uuid.git" + }, + "lint-staged": { + "*": [ + "prettier --no-error-on-unmatched-pattern --write" + ], + "*.{js,jsx}": [ + "eslint --no-error-on-unmatched-pattern --fix" + ] + }, + "standard-version": { + "scripts": { + "postchangelog": "prettier --write CHANGELOG.md" + } + }, + "packageManager": "npm@11.3.0" +} diff --git a/server/package-lock.json b/server/package-lock.json index c47a797..d2f5250 100644 --- a/server/package-lock.json +++ b/server/package-lock.json @@ -8,6 +8,7 @@ "name": "spotify-backend", "version": "0.1.0", "dependencies": { + "@types/uuid": "^10.0.0", "axios": "^1.7.2", "better-sqlite3": "^9.4.3", "cors": "^2.8.5", @@ -15,9 +16,12 @@ "express": "^4.19.2", "helmet": "^7.1.0", "jsonwebtoken": "^9.0.2", - "morgan": "^1.10.0" + "morgan": "^1.10.0", + "sharp": "^0.34.4", + "uuid": "^13.0.0" }, "devDependencies": { + "@types/better-sqlite3": "^7.6.13", "@types/cors": "^2.8.17", "@types/express": "^4.17.21", "@types/jsonwebtoken": "^9.0.6", @@ -26,6 +30,16 @@ "typescript": "^5.6.3" } }, + "node_modules/@emnapi/runtime": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.5.0.tgz", + "integrity": "sha512-97/BJ3iXHww3djw6hYIfErCZFee7qCtrneuLa20UXFCOTCfBM2cvQHjWJ2EG0s0MtdNwInarqCTz35i4wWXHsQ==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.25.10", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.10.tgz", @@ -468,6 +482,443 @@ "node": ">=18" } }, + "node_modules/@img/colour": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.0.0.tgz", + "integrity": "sha512-A5P/LfWGFSl6nsckYtjw9da+19jB8hkJ6ACTGcDfEJ0aE+l2n2El7dsVM7UVHZQ9s2lmYMWlrS21YLy2IR1LUw==", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.4.tgz", + "integrity": "sha512-sitdlPzDVyvmINUdJle3TNHl+AG9QcwiAMsXmccqsCOMZNIdW2/7S26w0LyU8euiLVzFBL3dXPwVCq/ODnf2vA==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.2.3" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.4.tgz", + "integrity": "sha512-rZheupWIoa3+SOdF/IcUe1ah4ZDpKBGWcsPX6MT0lYniH9micvIU7HQkYTfrx5Xi8u+YqwLtxC/3vl8TQN6rMg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.2.3" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.3.tgz", + "integrity": "sha512-QzWAKo7kpHxbuHqUC28DZ9pIKpSi2ts2OJnoIGI26+HMgq92ZZ4vk8iJd4XsxN+tYfNJxzH6W62X5eTcsBymHw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.3.tgz", + "integrity": "sha512-Ju+g2xn1E2AKO6YBhxjj+ACcsPQRHT0bhpglxcEf+3uyPY+/gL8veniKoo96335ZaPo03bdDXMv0t+BBFAbmRA==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.3.tgz", + "integrity": "sha512-x1uE93lyP6wEwGvgAIV0gP6zmaL/a0tGzJs/BIDDG0zeBhMnuUPm7ptxGhUbcGs4okDJrk4nxgrmxpib9g6HpA==", + "cpu": [ + "arm" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.3.tgz", + "integrity": "sha512-I4RxkXU90cpufazhGPyVujYwfIm9Nk1QDEmiIsaPwdnm013F7RIceaCc87kAH+oUB1ezqEvC6ga4m7MSlqsJvQ==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.3.tgz", + "integrity": "sha512-Y2T7IsQvJLMCBM+pmPbM3bKT/yYJvVtLJGfCs4Sp95SjvnFIjynbjzsa7dY1fRJX45FTSfDksbTp6AGWudiyCg==", + "cpu": [ + "ppc64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.3.tgz", + "integrity": "sha512-RgWrs/gVU7f+K7P+KeHFaBAJlNkD1nIZuVXdQv6S+fNA6syCcoboNjsV2Pou7zNlVdNQoQUpQTk8SWDHUA3y/w==", + "cpu": [ + "s390x" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.3.tgz", + "integrity": "sha512-3JU7LmR85K6bBiRzSUc/Ff9JBVIFVvq6bomKE0e63UXGeRw2HPVEjoJke1Yx+iU4rL7/7kUjES4dZ/81Qjhyxg==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.3.tgz", + "integrity": "sha512-F9q83RZ8yaCwENw1GieztSfj5msz7GGykG/BA+MOUefvER69K/ubgFHNeSyUu64amHIYKGDs4sRCMzXVj8sEyw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.3.tgz", + "integrity": "sha512-U5PUY5jbc45ANM6tSJpsgqmBF/VsL6LnxJmIf11kB7J5DctHgqm0SkuXzVWtIY90GnJxKnC/JT251TDnk1fu/g==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.4.tgz", + "integrity": "sha512-Xyam4mlqM0KkTHYVSuc6wXRmM7LGN0P12li03jAnZ3EJWZqj83+hi8Y9UxZUbxsgsK1qOEwg7O0Bc0LjqQVtxA==", + "cpu": [ + "arm" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.2.3" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.4.tgz", + "integrity": "sha512-YXU1F/mN/Wu786tl72CyJjP/Ngl8mGHN1hST4BGl+hiW5jhCnV2uRVTNOcaYPs73NeT/H8Upm3y9582JVuZHrQ==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.2.3" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.4.tgz", + "integrity": "sha512-F4PDtF4Cy8L8hXA2p3TO6s4aDt93v+LKmpcYFLAVdkkD3hSxZzee0rh6/+94FpAynsuMpLX5h+LRsSG3rIciUQ==", + "cpu": [ + "ppc64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.2.3" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.4.tgz", + "integrity": "sha512-qVrZKE9Bsnzy+myf7lFKvng6bQzhNUAYcVORq2P7bDlvmF6u2sCmK2KyEQEBdYk+u3T01pVsPrkj943T1aJAsw==", + "cpu": [ + "s390x" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.2.3" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.4.tgz", + "integrity": "sha512-ZfGtcp2xS51iG79c6Vhw9CWqQC8l2Ot8dygxoDoIQPTat/Ov3qAa8qpxSrtAEAJW+UjTXc4yxCjNfxm4h6Xm2A==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.2.3" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.4.tgz", + "integrity": "sha512-8hDVvW9eu4yHWnjaOOR8kHVrew1iIX+MUgwxSuH2XyYeNRtLUe4VNioSqbNkB7ZYQJj9rUTT4PyRscyk2PXFKA==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.2.3" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.4.tgz", + "integrity": "sha512-lU0aA5L8QTlfKjpDCEFOZsTYGn3AEiO6db8W5aQDxj0nQkVrZWmN3ZP9sYKWJdtq3PWPhUNlqehWyXpYDcI9Sg==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.2.3" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.4.tgz", + "integrity": "sha512-33QL6ZO/qpRyG7woB/HUALz28WnTMI2W1jgX3Nu2bypqLIKx/QKMILLJzJjI+SIbvXdG9fUnmrxR7vbi1sTBeA==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.5.0" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.4.tgz", + "integrity": "sha512-2Q250do/5WXTwxW3zjsEuMSv5sUU4Tq9VThWKlU2EYLm4MB7ZeMwF+SFJutldYODXF6jzc6YEOC+VfX0SZQPqA==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.4.tgz", + "integrity": "sha512-3ZeLue5V82dT92CNL6rsal6I2weKw1cYu+rGKm8fOCCtJTR2gYeUfY3FqUnIJsMUPIH68oS5jmZ0NiJ508YpEw==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.4.tgz", + "integrity": "sha512-xIyj4wpYs8J18sVN3mSQjwrw7fKUqRw+Z5rnHNCy5fYTxigBz81u5mOMPmFumwjcn8+ld1ppptMBCLic1nz6ig==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@types/better-sqlite3": { + "version": "7.6.13", + "resolved": "https://registry.npmjs.org/@types/better-sqlite3/-/better-sqlite3-7.6.13.tgz", + "integrity": "sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/body-parser": { "version": "1.19.6", "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz", @@ -624,6 +1075,12 @@ "@types/node": "*" } }, + "node_modules/@types/uuid": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-10.0.0.tgz", + "integrity": "sha512-7gqG38EyHgyP1S+7+xomFtL+ZNHcKv6DwNaCZmJmo1vgMugyF3TCnXVg4t1uk89mLNwnLtnY3TpOpCOyp1/xHQ==", + "license": "MIT" + }, "node_modules/accepts": { "version": "1.3.8", "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", @@ -2012,6 +2469,48 @@ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", "license": "ISC" }, + "node_modules/sharp": { + "version": "0.34.4", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.4.tgz", + "integrity": "sha512-FUH39xp3SBPnxWvd5iib1X8XY7J0K0X7d93sie9CJg2PO8/7gmg89Nve6OjItK53/MlAushNNxteBYfM6DEuoA==", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "@img/colour": "^1.0.0", + "detect-libc": "^2.1.0", + "semver": "^7.7.2" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.34.4", + "@img/sharp-darwin-x64": "0.34.4", + "@img/sharp-libvips-darwin-arm64": "1.2.3", + "@img/sharp-libvips-darwin-x64": "1.2.3", + "@img/sharp-libvips-linux-arm": "1.2.3", + "@img/sharp-libvips-linux-arm64": "1.2.3", + "@img/sharp-libvips-linux-ppc64": "1.2.3", + "@img/sharp-libvips-linux-s390x": "1.2.3", + "@img/sharp-libvips-linux-x64": "1.2.3", + "@img/sharp-libvips-linuxmusl-arm64": "1.2.3", + "@img/sharp-libvips-linuxmusl-x64": "1.2.3", + "@img/sharp-linux-arm": "0.34.4", + "@img/sharp-linux-arm64": "0.34.4", + "@img/sharp-linux-ppc64": "0.34.4", + "@img/sharp-linux-s390x": "0.34.4", + "@img/sharp-linux-x64": "0.34.4", + "@img/sharp-linuxmusl-arm64": "0.34.4", + "@img/sharp-linuxmusl-x64": "0.34.4", + "@img/sharp-wasm32": "0.34.4", + "@img/sharp-win32-arm64": "0.34.4", + "@img/sharp-win32-ia32": "0.34.4", + "@img/sharp-win32-x64": "0.34.4" + } + }, "node_modules/side-channel": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", @@ -2193,6 +2692,13 @@ "node": ">=0.6" } }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD", + "optional": true + }, "node_modules/tsx": { "version": "4.20.6", "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.20.6.tgz", @@ -2283,6 +2789,19 @@ "node": ">= 0.4.0" } }, + "node_modules/uuid": { + "version": "13.0.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-13.0.0.tgz", + "integrity": "sha512-XQegIaBTVUjSHliKqcnFqYypAd4S+WCYt5NIeRs6w/UAry7z8Y9j5ZwRRL4kzq9U3sD6v+85er9FvkEaBpji2w==", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist-node/bin/uuid" + } + }, "node_modules/vary": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", diff --git a/server/package.json b/server/package.json index 0d9ab68..988c520 100644 --- a/server/package.json +++ b/server/package.json @@ -9,16 +9,20 @@ "start": "node dist/index.js" }, "dependencies": { + "@types/uuid": "^10.0.0", "axios": "^1.7.2", + "better-sqlite3": "^9.4.3", "cors": "^2.8.5", "dotenv": "^16.4.5", "express": "^4.19.2", "helmet": "^7.1.0", "jsonwebtoken": "^9.0.2", "morgan": "^1.10.0", - "better-sqlite3": "^9.4.3" + "sharp": "^0.34.4", + "uuid": "^13.0.0" }, "devDependencies": { + "@types/better-sqlite3": "^7.6.13", "@types/cors": "^2.8.17", "@types/express": "^4.17.21", "@types/jsonwebtoken": "^9.0.6", @@ -27,5 +31,3 @@ "typescript": "^5.6.3" } } - - diff --git a/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.29 (1).jpeg b/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.29 (1).jpeg new file mode 100644 index 0000000..75b4477 Binary files /dev/null and b/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.29 (1).jpeg differ diff --git a/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.29 (2).jpeg b/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.29 (2).jpeg new file mode 100644 index 0000000..442836f Binary files /dev/null and b/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.29 (2).jpeg differ diff --git a/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.29 (3).jpeg b/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.29 (3).jpeg new file mode 100644 index 0000000..4674a4e Binary files /dev/null and b/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.29 (3).jpeg differ diff --git a/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.29 (4).jpeg b/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.29 (4).jpeg new file mode 100644 index 0000000..4ae2587 Binary files /dev/null and b/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.29 (4).jpeg differ diff --git a/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.29 (5).jpeg b/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.29 (5).jpeg new file mode 100644 index 0000000..5c6275b Binary files /dev/null and b/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.29 (5).jpeg differ diff --git a/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.29.jpeg b/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.29.jpeg new file mode 100644 index 0000000..e5b2d9a Binary files /dev/null and b/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.29.jpeg differ diff --git a/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.30 (1).jpeg b/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.30 (1).jpeg new file mode 100644 index 0000000..0fbbf77 Binary files /dev/null and b/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.30 (1).jpeg differ diff --git a/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.30 (2).jpeg b/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.30 (2).jpeg new file mode 100644 index 0000000..f8b2d46 Binary files /dev/null and b/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.30 (2).jpeg differ diff --git a/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.30.jpeg b/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.30.jpeg new file mode 100644 index 0000000..dacdb60 Binary files /dev/null and b/server/public/playlist-covers/WhatsApp Image 2025-10-16 at 11.12.30.jpeg differ diff --git a/server/public/playlist-covers/cover1.svg b/server/public/playlist-covers/cover1.svg new file mode 100644 index 0000000..38210d6 --- /dev/null +++ b/server/public/playlist-covers/cover1.svg @@ -0,0 +1,10 @@ + + + + + + + + + 🎵 + diff --git a/server/public/playlist-covers/cover2.svg b/server/public/playlist-covers/cover2.svg new file mode 100644 index 0000000..855d9c4 --- /dev/null +++ b/server/public/playlist-covers/cover2.svg @@ -0,0 +1,10 @@ + + + + + + + + + 🎶 + diff --git a/server/public/playlist-covers/cover3.svg b/server/public/playlist-covers/cover3.svg new file mode 100644 index 0000000..6eac30f --- /dev/null +++ b/server/public/playlist-covers/cover3.svg @@ -0,0 +1,10 @@ + + + + + + + + + 🎤 + diff --git a/server/public/playlist-covers/cover4.svg b/server/public/playlist-covers/cover4.svg new file mode 100644 index 0000000..688ace4 --- /dev/null +++ b/server/public/playlist-covers/cover4.svg @@ -0,0 +1,10 @@ + + + + + + + + + 🎸 + diff --git a/server/public/playlist-covers/cover5.svg b/server/public/playlist-covers/cover5.svg new file mode 100644 index 0000000..d1beb86 --- /dev/null +++ b/server/public/playlist-covers/cover5.svg @@ -0,0 +1,10 @@ + + + + + + + + + 🎹 + diff --git a/server/src/index.ts b/server/src/index.ts index c393641..8f811a2 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -3,6 +3,9 @@ import express from 'express'; import cors from 'cors'; import helmet from 'helmet'; import morgan from 'morgan'; +import fs from 'fs'; +import path from 'path'; +import https from 'https'; import { db } from './lib/db.js'; import { authRouter } from './routes/auth.js'; import { usersRouter } from './routes/users.js'; @@ -15,12 +18,24 @@ const app = express(); app.use(helmet()); app.use(cors({ origin: [ 'http://localhost:3000', - 'https://159.195.9.107:3443' + 'https://159.195.9.107:3443', + 'http://159.195.9.107:3443' ], credentials: true })); + +// Add CORS headers to allow mixed content for development +app.use((req, res, next) => { + res.header('Access-Control-Allow-Origin', '*'); + res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); + res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization'); + next(); +}); app.use(express.json({ limit: '1mb' })); app.use(express.urlencoded({ extended: false })); app.use(morgan('dev')); +// Serve static files from public directory +app.use(express.static('public')); + // Initialize DB db.initialize(); @@ -28,16 +43,103 @@ app.get('/health', (_req, res) => { res.json({ ok: true }); }); +// Placeholder playlist cover endpoint +app.get('/api/placeholder-playlist-cover', (_req, res) => { + // Return a simple SVG placeholder + const svg = ` + + + + + + + + + 🎵 + + `; + res.setHeader('Content-Type', 'image/svg+xml'); + res.send(svg); +}); + +// Serve playlist cover images as base64 data URLs to avoid mixed content issues +app.get('/api/playlist-covers/:filename', (req, res) => { + try { + const filename = decodeURIComponent(req.params.filename); + const filePath = path.join(process.cwd(), 'public', 'playlist-covers', filename); + + // Check if file exists + if (!fs.existsSync(filePath)) { + return res.status(404).json({ error: 'Image not found' }); + } + + // Read file as base64 + const fileBuffer = fs.readFileSync(filePath); + const base64Data = fileBuffer.toString('base64'); + + // Set appropriate content type based on file extension + const ext = path.extname(filename).toLowerCase(); + let contentType = 'image/jpeg'; // default + + switch (ext) { + case '.png': + contentType = 'image/png'; + break; + case '.gif': + contentType = 'image/gif'; + break; + case '.webp': + contentType = 'image/webp'; + break; + case '.svg': + contentType = 'image/svg+xml'; + break; + case '.jpg': + case '.jpeg': + contentType = 'image/jpeg'; + break; + } + + // Return base64 data URL + const dataUrl = `data:${contentType};base64,${base64Data}`; + + res.setHeader('Content-Type', 'application/json'); + res.setHeader('Cache-Control', 'public, max-age=31536000'); // Cache for 1 year + res.json({ dataUrl }); + + } catch (error) { + console.error('Error serving playlist cover:', error); + res.status(500).json({ error: 'Failed to serve image' }); + } +}); + app.use('/auth', authRouter); app.use('/users', usersRouter); app.use('/partners', partnersRouter); app.use('/playlists', playlistsRouter); -const PORT = process.env.PORT ? Number(process.env.PORT) : 8080; +const PORT = process.env.PORT ? Number(process.env.PORT) : 8081; +const HTTPS_PORT = process.env.HTTPS_PORT ? Number(process.env.HTTPS_PORT) : 8082; + +// Start HTTP server app.listen(PORT, () => { - console.log(`API server listening on http://0.0.0.0:${PORT}`); + console.log(`API server (HTTP) listening on http://0.0.0.0:${PORT}`); }); +// Start HTTPS server +try { + const httpsOptions = { + key: fs.readFileSync(path.join(process.cwd(), 'key.pem')), + cert: fs.readFileSync(path.join(process.cwd(), 'cert.pem')) + }; + + https.createServer(httpsOptions, app).listen(HTTPS_PORT, () => { + console.log(`API server (HTTPS) listening on https://0.0.0.0:${HTTPS_PORT}`); + }); +} catch (error) { + console.log('HTTPS server not started - SSL certificates not found'); +} + // Periodic refreshes const REFRESH_INTERVAL_MS = 2 * 60 * 1000; // full sync const NOWPLAYING_INTERVAL_MS = 20 * 1000; // capture now playing diff --git a/server/src/lib/db.ts b/server/src/lib/db.ts index 4fffa00..29f03c3 100644 --- a/server/src/lib/db.ts +++ b/server/src/lib/db.ts @@ -80,6 +80,27 @@ class DBWrapper { artist_json TEXT NOT NULL, UNIQUE(user_id, time_range, rank) ); + + CREATE TABLE IF NOT EXISTS mixed_playlists ( + id TEXT PRIMARY KEY, + creator_id TEXT NOT NULL, + partner_id TEXT NOT NULL, + name TEXT NOT NULL, + description TEXT, + vibe TEXT, + genres TEXT, -- JSON array of genres + track_uris TEXT, -- JSON array of track URIs + creator_spotify_id TEXT, + partner_spotify_id TEXT, + creator_spotify_url TEXT, + partner_spotify_url TEXT, + creator_spotify_image_url TEXT, + partner_spotify_image_url TEXT, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL, + FOREIGN KEY (creator_id) REFERENCES users(id), + FOREIGN KEY (partner_id) REFERENCES users(id) + ); `; this.db.exec(sql); @@ -92,6 +113,20 @@ class DBWrapper { this.db.exec('ALTER TABLE users ADD COLUMN last_synced_at INTEGER'); } } catch {} + + // Migration for mixed_playlists table + try { + const playlistCols = this.db.prepare("PRAGMA table_info(mixed_playlists)").all() as Array<{ name: string }>; + const hasCreatorImageUrl = playlistCols.some(c => c.name === 'creator_spotify_image_url'); + const hasPartnerImageUrl = playlistCols.some(c => c.name === 'partner_spotify_image_url'); + + if (!hasCreatorImageUrl) { + this.db.exec('ALTER TABLE mixed_playlists ADD COLUMN creator_spotify_image_url TEXT'); + } + if (!hasPartnerImageUrl) { + this.db.exec('ALTER TABLE mixed_playlists ADD COLUMN partner_spotify_image_url TEXT'); + } + } catch {} } } diff --git a/server/src/lib/events.ts b/server/src/lib/events.ts new file mode 100644 index 0000000..a2d890f --- /dev/null +++ b/server/src/lib/events.ts @@ -0,0 +1,51 @@ +type Client = { + userId: string; + write: (payload: any) => void; + res: any; +}; + +const clientsByUser: Map> = new Map(); + +export function addSseClient(userId: string, res: any): () => void { + const client: Client = { + userId, + res, + write: (payload: any) => { + try { + res.write(`data: ${JSON.stringify(payload)}\n\n`); + } catch {} + }, + }; + + if (!clientsByUser.has(userId)) clientsByUser.set(userId, new Set()); + clientsByUser.get(userId)!.add(client); + + // Initial hello + client.write({ type: 'hello', at: Date.now() }); + + // Heartbeat to keep connections alive through proxies + const heartbeat = setInterval(() => { + try { res.write(`: ping\n\n`); } catch {} + }, 25000); + + // Return cleanup + return () => { + clearInterval(heartbeat); + try { res.end(); } catch {} + clientsByUser.get(userId)?.delete(client); + if (clientsByUser.get(userId)?.size === 0) clientsByUser.delete(userId); + }; +} + +export function sendEvent(userId: string, event: any): void { + const set = clientsByUser.get(userId); + if (!set || set.size === 0) return; + for (const client of set) client.write(event); +} + +export function sendToBoth(userA: string, userB: string, event: any): void { + sendEvent(userA, event); + if (userB !== userA) sendEvent(userB, event); +} + + diff --git a/server/src/lib/spotify.ts b/server/src/lib/spotify.ts index e4e9e14..1160969 100644 --- a/server/src/lib/spotify.ts +++ b/server/src/lib/spotify.ts @@ -1,5 +1,42 @@ import axios from 'axios'; import { db } from './db.js'; +import fs from 'fs'; +import path from 'path'; + +// Generate a random local playlist cover image URL +function generateRandomPlaylistImage(): string { + try { + const coversDir = path.join(process.cwd(), 'public', 'playlist-covers'); + + // Check if directory exists + if (!fs.existsSync(coversDir)) { + console.log('Playlist covers directory not found, creating it...'); + fs.mkdirSync(coversDir, { recursive: true }); + } + + // Get all image files from the directory + const files = fs.readdirSync(coversDir).filter(file => { + const ext = path.extname(file).toLowerCase(); + return ['.jpg', '.jpeg', '.png', '.webp', '.gif'].includes(ext); + }); + + if (files.length === 0) { + console.log('No playlist cover images found in public/playlist-covers/'); + return '/api/placeholder-playlist-cover'; + } + + // Select a random image + const randomFile = files[Math.floor(Math.random() * files.length)]; + const imageUrl = `/api/playlist-covers/${encodeURIComponent(randomFile)}`; + + console.log(`Selected random playlist cover: ${imageUrl}`); + return imageUrl; + + } catch (error) { + console.error('Error generating random playlist image:', error); + return '/api/placeholder-playlist-cover'; + } +} type SpotifyTokenSet = { access_token: string; @@ -92,14 +129,18 @@ export async function createSpotifyPlaylist( userId: string, name: string, description: string -): Promise<{ id: string; url: string }> { +): Promise<{ id: string; url: string; imageUrl?: string }> { const resp = await axios.post( `https://api.spotify.com/v1/users/${encodeURIComponent(userId)}/playlists`, { name, description, public: false }, { headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' } } ); const pl = resp.data as any; - return { id: pl.id, url: pl.external_urls?.spotify }; + + // Generate a random local playlist cover image + const imageUrl = generateRandomPlaylistImage(); + + return { id: pl.id, url: pl.external_urls?.spotify, imageUrl }; } export async function addTracks( diff --git a/server/src/middleware/auth.ts b/server/src/middleware/auth.ts index 08a65e4..1d69578 100644 --- a/server/src/middleware/auth.ts +++ b/server/src/middleware/auth.ts @@ -9,7 +9,9 @@ export interface AuthedRequest extends Request { export function requireAuth(req: AuthedRequest, res: Response, next: NextFunction) { const header = req.headers.authorization || ''; - const token = header.startsWith('Bearer ') ? header.slice(7) : null; + let token = header.startsWith('Bearer ') ? header.slice(7) : null; + // Allow token via query param for SSE EventSource + if (!token && typeof req.query?.token === 'string') token = String(req.query.token); if (!token) return res.status(401).json({ error: 'Missing token' }); try { const payload = jwt.verify(token, JWT_SECRET) as { uid: string }; diff --git a/server/src/routes/partners.ts b/server/src/routes/partners.ts index 29f2ad6..af20118 100644 --- a/server/src/routes/partners.ts +++ b/server/src/routes/partners.ts @@ -1,5 +1,6 @@ import { Router } from 'express'; import { db } from '../lib/db.js'; +import { addSseClient, sendEvent, sendToBoth } from '../lib/events.js'; import { requireAuth, AuthedRequest } from '../middleware/auth.js'; export const partnersRouter = Router(); @@ -18,6 +19,8 @@ partnersRouter.post('/request', requireAuth, (req: AuthedRequest, res) => { VALUES (?, ?, 'pending', ?, ?)` ) .run(fromUid, toUid, now, now); + // Notify the recipient about a new incoming request + sendEvent(toUid, { type: 'partner:request', fromUserId: fromUid, at: now }); res.json({ ok: true }); } catch (e: any) { if (e && String(e.message).includes('UNIQUE')) { @@ -54,6 +57,8 @@ partnersRouter.post('/requests/:id/accept', requireAuth, (req: AuthedRequest, re }); txn(); + // Notify both users of partnership established + sendToBoth(userA, userB, { type: 'partner:connected', a: userA, b: userB, at: now }); res.json({ ok: true }); }); @@ -65,6 +70,8 @@ partnersRouter.post('/requests/:id/decline', requireAuth, (req: AuthedRequest, r if (!reqRow) return res.status(404).json({ error: 'Not found' }); if (!req.user || req.user.uid !== reqRow.to_user_id) return res.status(403).json({ error: 'Forbidden' }); db.db.prepare("UPDATE friend_requests SET status='declined', updated_at=? WHERE id=?").run(now, id); + // Notify requester that their request was declined + sendEvent(reqRow.from_user_id, { type: 'partner:declined', byUserId: reqRow.to_user_id, requestId: reqRow.id, at: now }); res.json({ ok: true }); }); @@ -95,4 +102,87 @@ partnersRouter.get('/partner/:uid', requireAuth, (req: AuthedRequest, res) => { return res.json({ partnerId: row.partner_id }); }); +// SSE: subscribe to partner events for authed user +partnersRouter.get('/events/:uid', requireAuth, (req: AuthedRequest, res) => { + const { uid } = req.params; + if (!req.user || req.user.uid !== uid) return res.status(403).json({ error: 'Forbidden' }); + res.setHeader('Content-Type', 'text/event-stream'); + res.setHeader('Cache-Control', 'no-cache'); + res.setHeader('Connection', 'keep-alive'); + res.flushHeaders?.(); + const cleanup = addSseClient(uid, res); + req.on('close', cleanup); +}); + +// Remove an existing partnership between the authed user and a specific partner +partnersRouter.post('/remove', requireAuth, (req: AuthedRequest, res) => { + const { partnerId } = req.body as { partnerId?: string }; + const uid = req.user?.uid; + if (!uid || !partnerId || uid === partnerId) return res.status(400).json({ error: 'Invalid partnerId' }); + + const userA = uid < partnerId ? uid : partnerId; + const userB = uid < partnerId ? partnerId : uid; + + const existing = db.db + .prepare('SELECT id FROM friendships WHERE user_a_id=? AND user_b_id=?') + .get(userA, userB) as { id?: number } | undefined; + + if (!existing?.id) return res.status(404).json({ error: 'No active partnership' }); + + try { + const txn = db.db.transaction(() => { + db.db.prepare('DELETE FROM friendships WHERE user_a_id=? AND user_b_id=?').run(userA, userB); + // Remove any historical or pending requests between the two users so they can re-invite + db.db + .prepare( + 'DELETE FROM friend_requests WHERE (from_user_id=? AND to_user_id=?) OR (from_user_id=? AND to_user_id=?)' + ) + .run(uid, partnerId, partnerId, uid); + }); + txn(); + // Notify both users of disconnection + sendToBoth(userA, userB, { type: 'partner:disconnected', a: userA, b: userB, at: Date.now() }); + return res.json({ ok: true }); + } catch (e) { + return res.status(500).json({ error: 'Failed to remove partnership' }); + } +}); + +// Clear any existing partnership for the authed user (fallback helper) +partnersRouter.post('/clear', requireAuth, (req: AuthedRequest, res) => { + const { userId } = req.body as { userId?: string }; + const uid = req.user?.uid; + if (!uid || !userId || uid !== userId) return res.status(403).json({ error: 'Forbidden' }); + + try { + // Find all partners (normally only one) and delete links + requests + const partners = db.db + .prepare( + 'SELECT CASE WHEN user_a_id = ? THEN user_b_id ELSE user_a_id END as partner_id FROM friendships WHERE user_a_id = ? OR user_b_id = ?' + ) + .all(uid, uid, uid) as Array<{ partner_id: string }>; + + const txn = db.db.transaction(() => { + db.db.prepare('DELETE FROM friendships WHERE user_a_id=? OR user_b_id=?').run(uid, uid); + for (const row of partners) { + db.db + .prepare( + 'DELETE FROM friend_requests WHERE (from_user_id=? AND to_user_id=?) OR (from_user_id=? AND to_user_id=?)' + ) + .run(uid, row.partner_id, row.partner_id, uid); + } + }); + txn(); + // Notify the user and any former partners + for (const row of partners) { + const a = uid < row.partner_id ? uid : row.partner_id; + const b = uid < row.partner_id ? row.partner_id : uid; + sendToBoth(a, b, { type: 'partner:disconnected', a, b, at: Date.now() }); + } + return res.json({ ok: true }); + } catch (e) { + return res.status(500).json({ error: 'Failed to clear partnership' }); + } +}); + diff --git a/server/src/routes/playlists.ts b/server/src/routes/playlists.ts index 9a1abe8..2ba80b6 100644 --- a/server/src/routes/playlists.ts +++ b/server/src/routes/playlists.ts @@ -2,9 +2,63 @@ import { Router } from 'express'; import { requireAuth, AuthedRequest } from '../middleware/auth.js'; import { addTracks, createSpotifyPlaylist, ensureValidAccessToken, fetchRecommendations, vibeToTargets } from '../lib/spotify.js'; import { db } from '../lib/db.js'; +import { v4 as uuidv4 } from 'uuid'; export const playlistsRouter = Router(); +// Helper function to generate unique playlist names +function generateUniquePlaylistName(): string { + const adjectives = ['Vibrant', 'Melodic', 'Harmonic', 'Rhythmic', 'Ethereal', 'Dynamic', 'Soulful', 'Electric', 'Acoustic', 'Cosmic', 'Urban', 'Chill', 'Energetic', 'Dreamy', 'Funky']; + const nouns = ['Fusion', 'Symphony', 'Vibes', 'Journey', 'Harmony', 'Blend', 'Mix', 'Soundscape', 'Melody', 'Rhythm', 'Groove', 'Beat', 'Tune', 'Sound', 'Wave']; + + const adjective = adjectives[Math.floor(Math.random() * adjectives.length)]; + const noun = nouns[Math.floor(Math.random() * nouns.length)]; + const timestamp = new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric' }); + + return `${adjective} ${noun} - ${timestamp}`; +} + +// GET /playlists/mixed - Get all mixed playlists for a user +playlistsRouter.get('/mixed', requireAuth, async (req: AuthedRequest, res) => { + try { + const userId = req.user!.uid; + + const playlists = db.db.prepare(` + SELECT * FROM mixed_playlists + WHERE creator_id = ? OR partner_id = ? + ORDER BY created_at DESC + `).all(userId, userId); + + res.json({ playlists }); + } catch (err: any) { + console.error('Failed to fetch mixed playlists:', err); + res.status(500).json({ error: 'Failed to fetch playlists' }); + } +}); + +// DELETE /playlists/mixed/:id - Delete a mixed playlist +playlistsRouter.delete('/mixed/:id', requireAuth, async (req: AuthedRequest, res) => { + try { + const userId = req.user!.uid; + const playlistId = req.params.id; + + // Check if user owns this playlist + const playlist = db.db.prepare('SELECT * FROM mixed_playlists WHERE id = ? AND (creator_id = ? OR partner_id = ?)').get(playlistId, userId, userId); + + if (!playlist) { + return res.status(404).json({ error: 'Playlist not found' }); + } + + // Delete from database + db.db.prepare('DELETE FROM mixed_playlists WHERE id = ?').run(playlistId); + + res.json({ success: true }); + } catch (err: any) { + console.error('Failed to delete playlist:', err); + res.status(500).json({ error: 'Failed to delete playlist' }); + } +}); + // POST /playlists/mixed // body: { name?: string, description?: string, vibe?: string, genres?: string[], includeKnown?: boolean, partnerId?: string, createForBoth?: boolean, limit?: number } playlistsRouter.post('/mixed', requireAuth, async (req: AuthedRequest, res) => { @@ -39,12 +93,41 @@ playlistsRouter.post('/mixed', requireAuth, async (req: AuthedRequest, res) => { const creatorToken = await ensureValidAccessToken(creatorId); const targets = vibeToTargets(vibe); + // Always provide fallback genres if none specified + let finalGenres = genres; + if (!Array.isArray(genres) || (genres as string[]).length === 0) { + // Analyze users' top tracks to determine appropriate genres + const allTracks = [...tracks1, ...tracks2]; + const genreCounts: Record = {}; + + // Count genres from top tracks + allTracks.forEach(track => { + if (track.artists && track.artists.length > 0) { + // Use common genres based on artist analysis + // This is a simplified approach - in a real implementation, you'd analyze track features + genreCounts['pop'] = (genreCounts['pop'] || 0) + 1; + genreCounts['rock'] = (genreCounts['rock'] || 0) + 1; + genreCounts['indie'] = (genreCounts['indie'] || 0) + 1; + genreCounts['alternative'] = (genreCounts['alternative'] || 0) + 1; + } + }); + + // Use top genres or fallback to popular ones + const sortedGenres = Object.entries(genreCounts) + .sort(([,a], [,b]) => b - a) + .map(([genre]) => genre) + .slice(0, 4); + + finalGenres = sortedGenres.length > 0 ? sortedGenres : ['pop', 'rock', 'indie', 'alternative']; + console.log('Using fallback genres:', finalGenres, 'based on track analysis'); + } + const recommendedUris = await fetchRecommendations( creatorToken, { seed_tracks: seedTrackUris.length ? seedTrackUris : undefined, seed_artists: seedArtistIds.length ? seedArtistIds : undefined, - seed_genres: Array.isArray(genres) && (genres as string[]).length ? (genres as string[]) : (!seedTrackUris.length && !seedArtistIds.length ? ['pop'] : undefined), + seed_genres: finalGenres, }, targets, limit @@ -62,31 +145,85 @@ playlistsRouter.post('/mixed', requireAuth, async (req: AuthedRequest, res) => { finalUris = recommendedUris.filter((u) => !recentUris.has(u)); } - const playlistName = name || 'Our Enhanced Mix'; + // Generate unique playlist name if not provided + const playlistName = name || generateUniquePlaylistName(); const playlistDesc = description || 'An AI-blended mix with fresh recommendations'; // Always create for the creator const creatorProfile = db.db.prepare('SELECT id FROM users WHERE id=?').get(creatorId) as { id: string }; - const { id: creatorPlaylistId, url: creatorUrl } = await createSpotifyPlaylist(creatorToken, creatorProfile.id, playlistName, playlistDesc); + const { id: creatorPlaylistId, url: creatorUrl, imageUrl: creatorImageUrl } = await createSpotifyPlaylist(creatorToken, creatorProfile.id, playlistName, playlistDesc); await addTracks(creatorToken, creatorPlaylistId, finalUris); - let partnerResult: { id?: string; url?: string } = {}; + let partnerResult: { id?: string; url?: string; imageUrl?: string; error?: string } = {}; if (createForBoth) { try { const partnerToken = await ensureValidAccessToken(partnerId); const partnerProfile = db.db.prepare('SELECT id FROM users WHERE id=?').get(partnerId) as { id: string }; - partnerResult = await createSpotifyPlaylist(partnerToken, partnerProfile.id, playlistName, playlistDesc); + + if (!partnerProfile) { + throw new Error('Partner user not found'); + } + + const partnerPlaylist = await createSpotifyPlaylist(partnerToken, partnerProfile.id, playlistName, playlistDesc); + partnerResult = partnerPlaylist; await addTracks(partnerToken, partnerResult.id!, finalUris); + + console.log(`Successfully created partner playlist: ${partnerResult.id}`); } catch (e) { - // Partner creation may fail (revoked consent); still return creator playlist - console.error('Partner playlist creation failed:', (e as any)?.response?.data || (e as any)?.message); + // Partner creation may fail (revoked consent, user not found, etc.); still return creator playlist + const errorMessage = (e as any)?.response?.data?.error?.message || (e as any)?.message || 'Unknown error'; + console.error('Partner playlist creation failed:', errorMessage); + partnerResult.error = errorMessage; } } + // Save playlist to database + const playlistId = uuidv4(); + const now = Date.now(); + + console.log('Saving playlist to database:', { + id: playlistId, + name: playlistName, + trackCount: finalUris.length, + trackUris: finalUris.slice(0, 3) // Log first 3 URIs for debugging + }); + + db.db.prepare(` + INSERT INTO mixed_playlists ( + id, creator_id, partner_id, name, description, vibe, genres, + track_uris, creator_spotify_id, partner_spotify_id, + creator_spotify_url, partner_spotify_url, creator_spotify_image_url, partner_spotify_image_url, + created_at, updated_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `).run( + playlistId, + creatorId, + partnerId, + playlistName, + playlistDesc, + vibe || null, + JSON.stringify(genres || []), + JSON.stringify(finalUris), + creatorPlaylistId, + partnerResult.id || null, + creatorUrl, + partnerResult.url || null, + creatorImageUrl || null, + partnerResult.imageUrl || null, + now, + now + ); + res.json({ + id: playlistId, + name: playlistName, + description: playlistDesc, + trackUris: finalUris, + spotifyImageUrl: creatorImageUrl, createdFor: { creator: { playlistId: creatorPlaylistId, url: creatorUrl }, partner: partnerResult.id ? { playlistId: partnerResult.id, url: partnerResult.url } : null, + partnerError: partnerResult.error || null, }, added: finalUris.length, }); diff --git a/server/src/routes/users.ts b/server/src/routes/users.ts index 6b26f68..af51acc 100644 --- a/server/src/routes/users.ts +++ b/server/src/routes/users.ts @@ -40,21 +40,21 @@ usersRouter.get('/search/q', (req, res) => { usersRouter.get('/:uid/recently-played', (req, res) => { const { uid } = req.params; const rows = db.db.prepare('SELECT id, user_id, played_at, track_json FROM recently_played WHERE user_id = ? ORDER BY played_at DESC LIMIT 50').all(uid); - res.json(rows.map(r => ({ id: r.id, user_id: r.user_id, played_at: r.played_at, track: JSON.parse(r.track_json) }))); + res.json(rows.map((r: any) => ({ id: r.id, user_id: r.user_id, played_at: r.played_at, track: JSON.parse(r.track_json) }))); }); usersRouter.get('/:uid/top-tracks', (req, res) => { const { uid } = req.params; const range = (req.query.time_range as string) || 'short_term'; const rows = db.db.prepare('SELECT rank, track_json FROM top_tracks WHERE user_id = ? AND time_range = ? ORDER BY rank ASC').all(uid, range); - res.json(rows.map(r => ({ rank: r.rank, track: JSON.parse(r.track_json) }))); + res.json(rows.map((r: any) => ({ rank: r.rank, track: JSON.parse(r.track_json) }))); }); usersRouter.get('/:uid/top-artists', (req, res) => { const { uid } = req.params; const range = (req.query.time_range as string) || 'short_term'; const rows = db.db.prepare('SELECT rank, artist_json FROM top_artists WHERE user_id = ? AND time_range = ? ORDER BY rank ASC').all(uid, range); - res.json(rows.map(r => ({ rank: r.rank, artist: JSON.parse(r.artist_json) }))); + res.json(rows.map((r: any) => ({ rank: r.rank, artist: JSON.parse(r.artist_json) }))); }); // status: last sync time and next scheduled time (based on 10 min interval) diff --git a/spotify.db b/spotify.db index 5602654..8722fa7 100644 Binary files a/spotify.db and b/spotify.db differ diff --git a/spotify.db-shm b/spotify.db-shm index c74d9b7..0eaf464 100644 Binary files a/spotify.db-shm and b/spotify.db-shm differ diff --git a/spotify.db-wal b/spotify.db-wal index 746f2ec..3b07afb 100644 Binary files a/spotify.db-wal and b/spotify.db-wal differ diff --git a/src/App.tsx b/src/App.tsx index 3f8b48f..abf3e8d 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -2,7 +2,7 @@ import { Routes, Route, Navigate, useLocation } from 'react-router-dom'; import { useEffect } from 'react'; import { motion } from 'framer-motion'; import { useStore } from './store/useStore'; -import { apiGet } from './utils/api'; +import { apiGet, apiEvents } from './utils/api'; import { getThemeClasses, getThemeHueShift } from './utils/theme'; import DarkVeil from './components/DarkVeil'; import { Navbar } from './components/Navbar'; @@ -81,6 +81,56 @@ function App() { loadPartner(); }, [currentUser?.user?.id]); + useEffect(() => { + // Real-time partner updates via SSE + const uid = useStore.getState().currentUser?.user?.id; + if (!uid) return; + const es = apiEvents(`/partners/events/${uid}`); + es.onmessage = async (evt) => { + if (!evt.data) return; + try { + const payload = JSON.parse(evt.data); + if (payload?.type === 'partner:connected' || payload?.type === 'partner:disconnected') { + // Re-fetch current partner state and hydrate/clear + const status = await apiGet<{ partnerId: string | null }>(`/partners/partner/${uid}`); + const currentPartnerId = useStore.getState().partnerUser?.user?.id || null; + if (!status?.partnerId && currentPartnerId) { + useStore.getState().setPartnerUser(null as any); + localStorage.removeItem('spotify-partner'); + return; + } + if (status?.partnerId && status.partnerId !== currentPartnerId) { + try { + const [userProfile, recentlyPlayed, topTracks] = await Promise.all([ + apiGet(`/users/${status.partnerId}`), + apiGet(`/users/${status.partnerId}/recently-played`), + apiGet(`/users/${status.partnerId}/top-tracks?time_range=short_term`), + ]); + useStore.getState().setPartnerUser({ + user: userProfile, + accessToken: null, + refreshToken: null, + isAuthenticated: true, + recentlyPlayed, + topTracks: (topTracks as any[]).map((item: any) => item.track), + topArtists: [], + } as any); + } catch {} + } + } + if (payload?.type === 'partner:request' || payload?.type === 'partner:declined') { + // Could trigger re-query of requests list if needed + } + } catch {} + }; + es.onerror = () => { + try { es.close(); } catch {} + }; + return () => { + try { es.close(); } catch {} + }; + }, [currentUser?.user?.id]); + const isAuthenticated = currentUser?.isAuthenticated || false; if (isLoading) { diff --git a/src/pages/MixedPlaylistPage.tsx b/src/pages/MixedPlaylistPage.tsx index f42d596..92522db 100644 --- a/src/pages/MixedPlaylistPage.tsx +++ b/src/pages/MixedPlaylistPage.tsx @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { useState, useEffect } from 'react'; import { motion } from 'framer-motion'; import { Sparkles, @@ -14,13 +14,131 @@ import { } from 'lucide-react'; import { useStore } from '../store/useStore'; import { generateMixedPlaylist, createPlaylist, addTracksToPlaylist } from '../utils/spotify'; -import { apiPost } from '../utils/api'; +import { apiPost, apiGet, apiDelete, API_BASE } from '../utils/api'; import { formatDuration } from '../utils/cn'; import { getThemeClasses } from '../utils/theme'; import toast from 'react-hot-toast'; +// PlaylistImage component to handle image loading with fallback +const PlaylistImage = ({ imageUrl, alt, fallbackGradient }: { imageUrl: string; alt: string; fallbackGradient: string }) => { + const [src, setSrc] = useState(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(false); + + useEffect(() => { + if (imageUrl.startsWith('http')) { + // Direct HTTP/HTTPS URL + setSrc(imageUrl); + setLoading(false); + } else { + // API endpoint - fetch as base64 via same-protocol API_BASE to avoid mixed content + const fetchImage = async () => { + try { + const response = await fetch(`${API_BASE}${imageUrl}`); + if (response.ok) { + const data = await response.json(); + setSrc(data.dataUrl); + } else { + setError(true); + } + } catch (e) { + setError(true); + } finally { + setLoading(false); + } + }; + fetchImage(); + } + }, [imageUrl]); + + if (loading) { + return ( +
+ +
+ ); + } + + if (error || !src) { + return ( +
+ +
+ ); + } + + return ( + {alt} setError(true)} + /> + ); +}; + +// Generate beautiful gradients based on playlist vibe and genres +function getPlaylistGradient(playlist: any): string { + const vibe = playlist.vibe?.toLowerCase(); + const genres = playlist.genres || []; + + // Vibe-based gradients + if (vibe) { + switch (vibe) { + case 'energetic': + return 'bg-gradient-to-br from-red-500 to-orange-500'; + case 'chill': + return 'bg-gradient-to-br from-blue-500 to-teal-500'; + case 'romantic': + return 'bg-gradient-to-br from-pink-500 to-rose-500'; + case 'party': + return 'bg-gradient-to-br from-purple-500 to-pink-500'; + case 'workout': + return 'bg-gradient-to-br from-green-500 to-lime-500'; + case 'study': + return 'bg-gradient-to-br from-indigo-500 to-blue-500'; + case 'sad': + return 'bg-gradient-to-br from-gray-500 to-slate-500'; + case 'happy': + return 'bg-gradient-to-br from-yellow-500 to-orange-500'; + } + } + + // Genre-based gradients + if (genres.length > 0) { + const primaryGenre = genres[0].toLowerCase(); + switch (primaryGenre) { + case 'pop': + return 'bg-gradient-to-br from-pink-500 to-purple-500'; + case 'rock': + return 'bg-gradient-to-br from-red-500 to-black'; + case 'hip-hop': + case 'rap': + return 'bg-gradient-to-br from-yellow-500 to-red-500'; + case 'electronic': + case 'edm': + return 'bg-gradient-to-br from-cyan-500 to-blue-500'; + case 'jazz': + return 'bg-gradient-to-br from-amber-500 to-orange-500'; + case 'classical': + return 'bg-gradient-to-br from-slate-500 to-gray-600'; + case 'country': + return 'bg-gradient-to-br from-green-600 to-yellow-600'; + case 'r&b': + return 'bg-gradient-to-br from-purple-600 to-pink-600'; + case 'indie': + return 'bg-gradient-to-br from-teal-500 to-green-500'; + case 'alternative': + return 'bg-gradient-to-br from-gray-600 to-purple-600'; + } + } + + // Default gradient + return 'bg-gradient-to-br from-purple-500 to-pink-500'; +} + export const MixedPlaylistPage = () => { - const { currentUser, partnerUser, mixedPlaylists, addMixedPlaylist, removeMixedPlaylist, theme } = useStore(); + const { currentUser, partnerUser, mixedPlaylists, addMixedPlaylist, removeMixedPlaylist, setMixedPlaylists, theme } = useStore(); const themeClasses = getThemeClasses(theme); const [isGenerating, setIsGenerating] = useState(false); const [isCreating, setIsCreating] = useState(false); @@ -35,6 +153,49 @@ export const MixedPlaylistPage = () => { .map(g => g.trim()) .filter(g => g.length > 0); + // Load playlists from database on component mount + useEffect(() => { + const loadPlaylists = async () => { + if (!currentUser?.jwt) return; + + try { + console.log('Loading playlists from database...'); + const response = await apiGet<{ playlists: any[] }>('/playlists/mixed', currentUser.jwt); + console.log('Loaded playlists:', response.playlists); + + // Convert database playlists to frontend format + const convertedPlaylists = response.playlists.map((dbPlaylist: any) => { + const trackUris = dbPlaylist.track_uris ? JSON.parse(dbPlaylist.track_uris) : []; + console.log('Processing playlist:', dbPlaylist.name, 'track_uris count:', trackUris.length, 'raw track_uris:', dbPlaylist.track_uris?.substring(0, 100) + '...'); + return { + id: dbPlaylist.id, + name: dbPlaylist.name, + description: dbPlaylist.description, + tracks: [], // We don't store full track objects in DB, just URIs + createdAt: new Date(dbPlaylist.created_at), + createdBy: 'AI Magic ✨', + spotifyId: dbPlaylist.creator_spotify_id, + spotifyUrl: dbPlaylist.creator_spotify_url, + partnerSpotifyId: dbPlaylist.partner_spotify_id, + partnerSpotifyUrl: dbPlaylist.partner_spotify_url, + vibe: dbPlaylist.vibe, + genres: dbPlaylist.genres ? JSON.parse(dbPlaylist.genres) : [], + trackUris: trackUris, + spotifyImageUrl: dbPlaylist.creator_spotify_image_url, + }; + }); + + // Update store with loaded playlists (replace existing ones) + setMixedPlaylists(convertedPlaylists); + } catch (error) { + console.error('Failed to load playlists:', error); + // Don't show error toast for this - it's not critical + } + }; + + loadPlaylists(); + }, [currentUser?.jwt]); + const handleGeneratePlaylist = async () => { if (!currentUser?.topTracks || !partnerUser?.topTracks) { toast.error('Both users need to have their music data loaded'); @@ -124,28 +285,42 @@ export const MixedPlaylistPage = () => { includeKnown, vibe: vibe || undefined, genres: parsedGenres.length ? parsedGenres : undefined, - name: newPlaylist?.name || 'Our Enhanced Mix', + // Don't pass name - let server generate unique name + // name: newPlaylist?.name || 'Our Enhanced Mix', description: newPlaylist?.description || 'An AI-blended mix with fresh recommendations', }; const result = await apiPost('/playlists/mixed', body, currentUser.jwt); - toast.success('Enhanced playlist created!'); - // Optionally attach URLs to local card for quick open - if (result?.createdFor?.creator?.url) { - addMixedPlaylist({ - ...(newPlaylist || { - id: Date.now().toString(), - name: body.name, - description: body.description, - tracks: [], - createdAt: new Date(), - createdBy: 'AI Magic ✨', - }), - spotifyId: result.createdFor.creator.playlistId, - spotifyUrl: result.createdFor.creator.url, - }); - setNewPlaylist(null); + + // Show appropriate success/error messages + if (createForBoth && result.createdFor.partnerError) { + toast.success('Your playlist created! Partner sync failed: ' + result.createdFor.partnerError); + } else if (createForBoth && result.createdFor.partner) { + toast.success('Enhanced playlist created on both accounts!'); + } else { + toast.success('Enhanced playlist created!'); } + + // Create playlist object for local store + const playlistData = { + id: result.id, + name: result.name, // Use name from server response + description: body.description, + tracks: [], + createdAt: new Date(), + createdBy: 'AI Magic ✨', + spotifyId: result.createdFor.creator.playlistId, + spotifyUrl: result.createdFor.creator.url, + partnerSpotifyId: result.createdFor.partner?.playlistId, + partnerSpotifyUrl: result.createdFor.partner?.url, + vibe: body.vibe, + genres: body.genres || [], + trackUris: result.trackUris || [], // Use track URIs from server response + spotifyImageUrl: result.spotifyImageUrl, // Use image URL from server response + }; + + addMixedPlaylist(playlistData); + setNewPlaylist(null); } catch (e) { console.error(e); toast.error('Failed to create enhanced playlist'); @@ -171,16 +346,48 @@ export const MixedPlaylistPage = () => { >
-
- {isNew ? : } + {isNew ? ( + + ) : playlist.spotifyImageUrl ? ( + + ) : null} + {!isNew && ( +
+ +
+ )}

{playlist.name}

{playlist.description}

-

- Created {isNew ? 'just now' : new Date(playlist.createdAt).toLocaleDateString()} • {playlist.tracks.length} tracks +

+ {playlist.vibe && ( + + {playlist.vibe} + + )} + {playlist.genres && playlist.genres.length > 0 && playlist.genres.slice(0, 2).map((genre: string, index: number) => ( + + {genre} + + ))} +
+

+ Created {isNew ? 'just now' : new Date(playlist.createdAt).toLocaleDateString()} • {playlist.tracks.length || playlist.trackUris?.length || 0} tracks

@@ -192,14 +399,37 @@ export const MixedPlaylistPage = () => { target="_blank" rel="noopener noreferrer" className="w-8 h-8 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center transition-colors" + title="Open in Spotify" > )} + {playlist.partnerSpotifyUrl && ( + + + + )} {!isNew && (