playlist-data-engine 1.6.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/analysis.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var Bn=Object.create;var dt=Object.defineProperty;var An=Object.getOwnPropertyDescriptor;var _n=Object.getOwnPropertyNames;var Nn=Object.getPrototypeOf,kn=Object.prototype.hasOwnProperty;var Pn=(v,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of _n(e))!kn.call(v,r)&&r!==t&&dt(v,r,{get:()=>e[r],enumerable:!(n=An(e,r))||n.enumerable});return v};var Fn=(v,e,t)=>(t=v!=null?Bn(Nn(v)):{},Pn(e||!v||!v.__esModule?dt(t,"default",{value:v,enumerable:!0}):t,v));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const x=require("./unifyBeatMap-sIbIw5OX.cjs"),xn=require("@tensorflow/tfjs"),K=require("./arweaveGatewayManager-CeW9SP2P.cjs");function zn(v){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(v){for(const t in v)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(v,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>v[t]})}}return e.default=v,Object.freeze(e)}const G=zn(xn);function pe(v){throw new Error('Could not dynamically require "'+v+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Fe={exports:{}};var ht;function Ln(){return ht||(ht=1,(function(v,e){(function(t){v.exports=t()})(function(){return(function t(n,r,o){function i(u,f){if(!r[u]){if(!n[u]){var d=typeof pe=="function"&&pe;if(!f&&d)return d(u,!0);if(s)return s(u,!0);var g=new Error("Cannot find module '"+u+"'");throw g.code="MODULE_NOT_FOUND",g}var b=r[u]={exports:{}};n[u][0].call(b.exports,function(S){var R=n[u][1][S];return i(R||S)},b,b.exports,t,n,r,o)}return r[u].exports}for(var s=typeof pe=="function"&&pe,c=0;c<o.length;c++)i(o[c]);return i})({1:[function(t,n,r){(function(o){var i=o.MutationObserver||o.WebKitMutationObserver,s;if(i){var c=0,u=new i(S),f=o.document.createTextNode("");u.observe(f,{characterData:!0}),s=function(){f.data=c=++c%2}}else if(!o.setImmediate&&typeof o.MessageChannel<"u"){var d=new o.MessageChannel;d.port1.onmessage=S,s=function(){d.port2.postMessage(0)}}else"document"in o&&"onreadystatechange"in o.document.createElement("script")?s=function(){var I=o.document.createElement("script");I.onreadystatechange=function(){S(),I.onreadystatechange=null,I.parentNode.removeChild(I),I=null},o.document.documentElement.appendChild(I)}:s=function(){setTimeout(S,0)};var g,b=[];function S(){g=!0;for(var I,A,B=b.length;B;){for(A=b,b=[],I=-1;++I<B;)A[I]();B=b.length}g=!1}n.exports=R;function R(I){b.push(I)===1&&!g&&s()}}).call(this,typeof x.commonjsGlobal<"u"?x.commonjsGlobal:typeof self<"u"?self:typeof window<"u"?window:{})},{}],2:[function(t,n,r){var o=t(1);function i(){}var s={},c=["REJECTED"],u=["FULFILLED"],f=["PENDING"];n.exports=d;function d(C){if(typeof C!="function")throw new TypeError("resolver must be a function");this.state=f,this.queue=[],this.outcome=void 0,C!==i&&R(this,C)}d.prototype.catch=function(C){return this.then(null,C)},d.prototype.then=function(C,F){if(typeof C!="function"&&this.state===u||typeof F!="function"&&this.state===c)return this;var P=new this.constructor(i);if(this.state!==f){var L=this.state===u?C:F;b(P,L,this.outcome)}else this.queue.push(new g(P,C,F));return P};function g(C,F,P){this.promise=C,typeof F=="function"&&(this.onFulfilled=F,this.callFulfilled=this.otherCallFulfilled),typeof P=="function"&&(this.onRejected=P,this.callRejected=this.otherCallRejected)}g.prototype.callFulfilled=function(C){s.resolve(this.promise,C)},g.prototype.otherCallFulfilled=function(C){b(this.promise,this.onFulfilled,C)},g.prototype.callRejected=function(C){s.reject(this.promise,C)},g.prototype.otherCallRejected=function(C){b(this.promise,this.onRejected,C)};function b(C,F,P){o(function(){var L;try{L=F(P)}catch(H){return s.reject(C,H)}L===C?s.reject(C,new TypeError("Cannot resolve promise with itself")):s.resolve(C,L)})}s.resolve=function(C,F){var P=I(S,F);if(P.status==="error")return s.reject(C,P.value);var L=P.value;if(L)R(C,L);else{C.state=u,C.outcome=F;for(var H=-1,$=C.queue.length;++H<$;)C.queue[H].callFulfilled(F)}return C},s.reject=function(C,F){C.state=c,C.outcome=F;for(var P=-1,L=C.queue.length;++P<L;)C.queue[P].callRejected(F);return C};function S(C){var F=C&&C.then;if(C&&(typeof C=="object"||typeof C=="function")&&typeof F=="function")return function(){F.apply(C,arguments)}}function R(C,F){var P=!1;function L(j){P||(P=!0,s.reject(C,j))}function H(j){P||(P=!0,s.resolve(C,j))}function $(){F(H,L)}var V=I($);V.status==="error"&&L(V.value)}function I(C,F){var P={};try{P.value=C(F),P.status="success"}catch(L){P.status="error",P.value=L}return P}d.resolve=A;function A(C){return C instanceof this?C:s.resolve(new this(i),C)}d.reject=B;function B(C){var F=new this(i);return s.reject(F,C)}d.all=N;function N(C){var F=this;if(Object.prototype.toString.call(C)!=="[object Array]")return this.reject(new TypeError("must be an array"));var P=C.length,L=!1;if(!P)return this.resolve([]);for(var H=new Array(P),$=0,V=-1,j=new this(i);++V<P;)Y(C[V],V);return j;function Y(oe,fe){F.resolve(oe).then(De,function(ee){L||(L=!0,s.reject(j,ee))});function De(ee){H[fe]=ee,++$===P&&!L&&(L=!0,s.resolve(j,H))}}}d.race=k;function k(C){var F=this;if(Object.prototype.toString.call(C)!=="[object Array]")return this.reject(new TypeError("must be an array"));var P=C.length,L=!1;if(!P)return this.resolve([]);for(var H=-1,$=new this(i);++H<P;)V(C[H]);return $;function V(j){F.resolve(j).then(function(Y){L||(L=!0,s.resolve($,Y))},function(Y){L||(L=!0,s.reject($,Y))})}}},{1:1}],3:[function(t,n,r){(function(o){typeof o.Promise!="function"&&(o.Promise=t(2))}).call(this,typeof x.commonjsGlobal<"u"?x.commonjsGlobal:typeof self<"u"?self:typeof window<"u"?window:{})},{2:2}],4:[function(t,n,r){var o=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(a){return typeof a}:function(a){return a&&typeof Symbol=="function"&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a};function i(a,h){if(!(a instanceof h))throw new TypeError("Cannot call a class as a function")}function s(){try{if(typeof indexedDB<"u")return indexedDB;if(typeof webkitIndexedDB<"u")return webkitIndexedDB;if(typeof mozIndexedDB<"u")return mozIndexedDB;if(typeof OIndexedDB<"u")return OIndexedDB;if(typeof msIndexedDB<"u")return msIndexedDB}catch{return}}var c=s();function u(){try{if(!c||!c.open)return!1;var a=typeof openDatabase<"u"&&/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&!/BlackBerry/.test(navigator.platform),h=typeof fetch=="function"&&fetch.toString().indexOf("[native code")!==-1;return(!a||h)&&typeof indexedDB<"u"&&typeof IDBKeyRange<"u"}catch{return!1}}function f(a,h){a=a||[],h=h||{};try{return new Blob(a,h)}catch(m){if(m.name!=="TypeError")throw m;for(var l=typeof BlobBuilder<"u"?BlobBuilder:typeof MSBlobBuilder<"u"?MSBlobBuilder:typeof MozBlobBuilder<"u"?MozBlobBuilder:WebKitBlobBuilder,p=new l,y=0;y<a.length;y+=1)p.append(a[y]);return p.getBlob(h.type)}}typeof Promise>"u"&&t(3);var d=Promise;function g(a,h){h&&a.then(function(l){h(null,l)},function(l){h(l)})}function b(a,h,l){typeof h=="function"&&a.then(h),typeof l=="function"&&a.catch(l)}function S(a){return typeof a!="string"&&(console.warn(a+" used as a key, but it is not a string."),a=String(a)),a}function R(){if(arguments.length&&typeof arguments[arguments.length-1]=="function")return arguments[arguments.length-1]}var I="local-forage-detect-blob-support",A=void 0,B={},N=Object.prototype.toString,k="readonly",C="readwrite";function F(a){for(var h=a.length,l=new ArrayBuffer(h),p=new Uint8Array(l),y=0;y<h;y++)p[y]=a.charCodeAt(y);return l}function P(a){return new d(function(h){var l=a.transaction(I,C),p=f([""]);l.objectStore(I).put(p,"key"),l.onabort=function(y){y.preventDefault(),y.stopPropagation(),h(!1)},l.oncomplete=function(){var y=navigator.userAgent.match(/Chrome\/(\d+)/),m=navigator.userAgent.match(/Edge\//);h(m||!y||parseInt(y[1],10)>=43)}}).catch(function(){return!1})}function L(a){return typeof A=="boolean"?d.resolve(A):P(a).then(function(h){return A=h,A})}function H(a){var h=B[a.name],l={};l.promise=new d(function(p,y){l.resolve=p,l.reject=y}),h.deferredOperations.push(l),h.dbReady?h.dbReady=h.dbReady.then(function(){return l.promise}):h.dbReady=l.promise}function $(a){var h=B[a.name],l=h.deferredOperations.pop();if(l)return l.resolve(),l.promise}function V(a,h){var l=B[a.name],p=l.deferredOperations.pop();if(p)return p.reject(h),p.promise}function j(a,h){return new d(function(l,p){if(B[a.name]=B[a.name]||$e(),a.db)if(h)H(a),a.db.close();else return l(a.db);var y=[a.name];h&&y.push(a.version);var m=c.open.apply(c,y);h&&(m.onupgradeneeded=function(w){var M=m.result;try{M.createObjectStore(a.storeName),w.oldVersion<=1&&M.createObjectStore(I)}catch(E){if(E.name==="ConstraintError")console.warn('The database "'+a.name+'" has been upgraded from version '+w.oldVersion+" to version "+w.newVersion+', but the storage "'+a.storeName+'" already exists.');else throw E}}),m.onerror=function(w){w.preventDefault(),p(m.error)},m.onsuccess=function(){var w=m.result;w.onversionchange=function(M){M.target.close()},l(w),$(a)}})}function Y(a){return j(a,!1)}function oe(a){return j(a,!0)}function fe(a,h){if(!a.db)return!0;var l=!a.db.objectStoreNames.contains(a.storeName),p=a.version<a.db.version,y=a.version>a.db.version;if(p&&(a.version!==h&&console.warn('The database "'+a.name+`" can't be downgraded from version `+a.db.version+" to version "+a.version+"."),a.version=a.db.version),y||l){if(l){var m=a.db.version+1;m>a.version&&(a.version=m)}return!0}return!1}function De(a){return new d(function(h,l){var p=new FileReader;p.onerror=l,p.onloadend=function(y){var m=btoa(y.target.result||"");h({__local_forage_encoded_blob:!0,data:m,type:a.type})},p.readAsBinaryString(a)})}function ee(a){var h=F(atob(a.data));return f([h],{type:a.type})}function Ge(a){return a&&a.__local_forage_encoded_blob}function Bt(a){var h=this,l=h._initReady().then(function(){var p=B[h._dbInfo.name];if(p&&p.dbReady)return p.dbReady});return b(l,a,a),l}function At(a){H(a);for(var h=B[a.name],l=h.forages,p=0;p<l.length;p++){var y=l[p];y._dbInfo.db&&(y._dbInfo.db.close(),y._dbInfo.db=null)}return a.db=null,Y(a).then(function(m){return a.db=m,fe(a)?oe(a):m}).then(function(m){a.db=h.db=m;for(var w=0;w<l.length;w++)l[w]._dbInfo.db=m}).catch(function(m){throw V(a,m),m})}function Z(a,h,l,p){p===void 0&&(p=1);try{var y=a.db.transaction(a.storeName,h);l(null,y)}catch(m){if(p>0&&(!a.db||m.name==="InvalidStateError"||m.name==="NotFoundError"))return d.resolve().then(function(){if(!a.db||m.name==="NotFoundError"&&!a.db.objectStoreNames.contains(a.storeName)&&a.version<=a.db.version)return a.db&&(a.version=a.db.version+1),oe(a)}).then(function(){return At(a).then(function(){Z(a,h,l,p-1)})}).catch(l);l(m)}}function $e(){return{forages:[],db:null,dbReady:null,deferredOperations:[]}}function _t(a){var h=this,l={db:null};if(a)for(var p in a)l[p]=a[p];var y=B[l.name];y||(y=$e(),B[l.name]=y),y.forages.push(h),h._initReady||(h._initReady=h.ready,h.ready=Bt);var m=[];function w(){return d.resolve()}for(var M=0;M<y.forages.length;M++){var E=y.forages[M];E!==h&&m.push(E._initReady().catch(w))}var D=y.forages.slice(0);return d.all(m).then(function(){return l.db=y.db,Y(l)}).then(function(T){return l.db=T,fe(l,h._defaultConfig.version)?oe(l):T}).then(function(T){l.db=y.db=T,h._dbInfo=l;for(var _=0;_<D.length;_++){var z=D[_];z!==h&&(z._dbInfo.db=l.db,z._dbInfo.version=l.version)}})}function Nt(a,h){var l=this;a=S(a);var p=new d(function(y,m){l.ready().then(function(){Z(l._dbInfo,k,function(w,M){if(w)return m(w);try{var E=M.objectStore(l._dbInfo.storeName),D=E.get(a);D.onsuccess=function(){var T=D.result;T===void 0&&(T=null),Ge(T)&&(T=ee(T)),y(T)},D.onerror=function(){m(D.error)}}catch(T){m(T)}})}).catch(m)});return g(p,h),p}function kt(a,h){var l=this,p=new d(function(y,m){l.ready().then(function(){Z(l._dbInfo,k,function(w,M){if(w)return m(w);try{var E=M.objectStore(l._dbInfo.storeName),D=E.openCursor(),T=1;D.onsuccess=function(){var _=D.result;if(_){var z=_.value;Ge(z)&&(z=ee(z));var U=a(z,_.key,T++);U!==void 0?y(U):_.continue()}else y()},D.onerror=function(){m(D.error)}}catch(_){m(_)}})}).catch(m)});return g(p,h),p}function Pt(a,h,l){var p=this;a=S(a);var y=new d(function(m,w){var M;p.ready().then(function(){return M=p._dbInfo,N.call(h)==="[object Blob]"?L(M.db).then(function(E){return E?h:De(h)}):h}).then(function(E){Z(p._dbInfo,C,function(D,T){if(D)return w(D);try{var _=T.objectStore(p._dbInfo.storeName);E===null&&(E=void 0);var z=_.put(E,a);T.oncomplete=function(){E===void 0&&(E=null),m(E)},T.onabort=T.onerror=function(){var U=z.error?z.error:z.transaction.error;w(U)}}catch(U){w(U)}})}).catch(w)});return g(y,l),y}function Ft(a,h){var l=this;a=S(a);var p=new d(function(y,m){l.ready().then(function(){Z(l._dbInfo,C,function(w,M){if(w)return m(w);try{var E=M.objectStore(l._dbInfo.storeName),D=E.delete(a);M.oncomplete=function(){y()},M.onerror=function(){m(D.error)},M.onabort=function(){var T=D.error?D.error:D.transaction.error;m(T)}}catch(T){m(T)}})}).catch(m)});return g(p,h),p}function xt(a){var h=this,l=new d(function(p,y){h.ready().then(function(){Z(h._dbInfo,C,function(m,w){if(m)return y(m);try{var M=w.objectStore(h._dbInfo.storeName),E=M.clear();w.oncomplete=function(){p()},w.onabort=w.onerror=function(){var D=E.error?E.error:E.transaction.error;y(D)}}catch(D){y(D)}})}).catch(y)});return g(l,a),l}function zt(a){var h=this,l=new d(function(p,y){h.ready().then(function(){Z(h._dbInfo,k,function(m,w){if(m)return y(m);try{var M=w.objectStore(h._dbInfo.storeName),E=M.count();E.onsuccess=function(){p(E.result)},E.onerror=function(){y(E.error)}}catch(D){y(D)}})}).catch(y)});return g(l,a),l}function Lt(a,h){var l=this,p=new d(function(y,m){if(a<0){y(null);return}l.ready().then(function(){Z(l._dbInfo,k,function(w,M){if(w)return m(w);try{var E=M.objectStore(l._dbInfo.storeName),D=!1,T=E.openKeyCursor();T.onsuccess=function(){var _=T.result;if(!_){y(null);return}a===0||D?y(_.key):(D=!0,_.advance(a))},T.onerror=function(){m(T.error)}}catch(_){m(_)}})}).catch(m)});return g(p,h),p}function Ut(a){var h=this,l=new d(function(p,y){h.ready().then(function(){Z(h._dbInfo,k,function(m,w){if(m)return y(m);try{var M=w.objectStore(h._dbInfo.storeName),E=M.openKeyCursor(),D=[];E.onsuccess=function(){var T=E.result;if(!T){p(D);return}D.push(T.key),T.continue()},E.onerror=function(){y(E.error)}}catch(T){y(T)}})}).catch(y)});return g(l,a),l}function Ot(a,h){h=R.apply(this,arguments);var l=this.config();a=typeof a!="function"&&a||{},a.name||(a.name=a.name||l.name,a.storeName=a.storeName||l.storeName);var p=this,y;if(!a.name)y=d.reject("Invalid arguments");else{var m=a.name===l.name&&p._dbInfo.db,w=m?d.resolve(p._dbInfo.db):Y(a).then(function(M){var E=B[a.name],D=E.forages;E.db=M;for(var T=0;T<D.length;T++)D[T]._dbInfo.db=M;return M});a.storeName?y=w.then(function(M){if(M.objectStoreNames.contains(a.storeName)){var E=M.version+1;H(a);var D=B[a.name],T=D.forages;M.close();for(var _=0;_<T.length;_++){var z=T[_];z._dbInfo.db=null,z._dbInfo.version=E}var U=new d(function(O,W){var q=c.open(a.name,E);q.onerror=function(J){var se=q.result;se.close(),W(J)},q.onupgradeneeded=function(){var J=q.result;J.deleteObjectStore(a.storeName)},q.onsuccess=function(){var J=q.result;J.close(),O(J)}});return U.then(function(O){D.db=O;for(var W=0;W<T.length;W++){var q=T[W];q._dbInfo.db=O,$(q._dbInfo)}}).catch(function(O){throw(V(a,O)||d.resolve()).catch(function(){}),O})}}):y=w.then(function(M){H(a);var E=B[a.name],D=E.forages;M.close();for(var T=0;T<D.length;T++){var _=D[T];_._dbInfo.db=null}var z=new d(function(U,O){var W=c.deleteDatabase(a.name);W.onerror=function(){var q=W.result;q&&q.close(),O(W.error)},W.onblocked=function(){console.warn('dropInstance blocked for database "'+a.name+'" until all open connections are closed')},W.onsuccess=function(){var q=W.result;q&&q.close(),U(q)}});return z.then(function(U){E.db=U;for(var O=0;O<D.length;O++){var W=D[O];$(W._dbInfo)}}).catch(function(U){throw(V(a,U)||d.resolve()).catch(function(){}),U})})}return g(y,h),y}var qt={_driver:"asyncStorage",_initStorage:_t,_support:u(),iterate:kt,getItem:Nt,setItem:Pt,removeItem:Ft,clear:xt,length:zt,key:Lt,keys:Ut,dropInstance:Ot};function Wt(){return typeof openDatabase=="function"}var Q="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ht="~~local_forage_type~",Ve=/^~~local_forage_type~([^~]+)~/,me="__lfsc__:",Te=me.length,Re="arbf",Ie="blob",je="si08",Je="ui08",Ke="uic8",Ye="si16",Ze="si32",Qe="ur16",Xe="ui32",et="fl32",tt="fl64",nt=Te+Re.length,rt=Object.prototype.toString;function it(a){var h=a.length*.75,l=a.length,p,y=0,m,w,M,E;a[a.length-1]==="="&&(h--,a[a.length-2]==="="&&h--);var D=new ArrayBuffer(h),T=new Uint8Array(D);for(p=0;p<l;p+=4)m=Q.indexOf(a[p]),w=Q.indexOf(a[p+1]),M=Q.indexOf(a[p+2]),E=Q.indexOf(a[p+3]),T[y++]=m<<2|w>>4,T[y++]=(w&15)<<4|M>>2,T[y++]=(M&3)<<6|E&63;return D}function Be(a){var h=new Uint8Array(a),l="",p;for(p=0;p<h.length;p+=3)l+=Q[h[p]>>2],l+=Q[(h[p]&3)<<4|h[p+1]>>4],l+=Q[(h[p+1]&15)<<2|h[p+2]>>6],l+=Q[h[p+2]&63];return h.length%3===2?l=l.substring(0,l.length-1)+"=":h.length%3===1&&(l=l.substring(0,l.length-2)+"=="),l}function Gt(a,h){var l="";if(a&&(l=rt.call(a)),a&&(l==="[object ArrayBuffer]"||a.buffer&&rt.call(a.buffer)==="[object ArrayBuffer]")){var p,y=me;a instanceof ArrayBuffer?(p=a,y+=Re):(p=a.buffer,l==="[object Int8Array]"?y+=je:l==="[object Uint8Array]"?y+=Je:l==="[object Uint8ClampedArray]"?y+=Ke:l==="[object Int16Array]"?y+=Ye:l==="[object Uint16Array]"?y+=Qe:l==="[object Int32Array]"?y+=Ze:l==="[object Uint32Array]"?y+=Xe:l==="[object Float32Array]"?y+=et:l==="[object Float64Array]"?y+=tt:h(new Error("Failed to get type for BinaryArray"))),h(y+Be(p))}else if(l==="[object Blob]"){var m=new FileReader;m.onload=function(){var w=Ht+a.type+"~"+Be(this.result);h(me+Ie+w)},m.readAsArrayBuffer(a)}else try{h(JSON.stringify(a))}catch(w){console.error("Couldn't convert value into a JSON string: ",a),h(null,w)}}function $t(a){if(a.substring(0,Te)!==me)return JSON.parse(a);var h=a.substring(nt),l=a.substring(Te,nt),p;if(l===Ie&&Ve.test(h)){var y=h.match(Ve);p=y[1],h=h.substring(y[0].length)}var m=it(h);switch(l){case Re:return m;case Ie:return f([m],{type:p});case je:return new Int8Array(m);case Je:return new Uint8Array(m);case Ke:return new Uint8ClampedArray(m);case Ye:return new Int16Array(m);case Qe:return new Uint16Array(m);case Ze:return new Int32Array(m);case Xe:return new Uint32Array(m);case et:return new Float32Array(m);case tt:return new Float64Array(m);default:throw new Error("Unkown type: "+l)}}var Ae={serialize:Gt,deserialize:$t,stringToBuffer:it,bufferToString:Be};function ot(a,h,l,p){a.executeSql("CREATE TABLE IF NOT EXISTS "+h.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],l,p)}function Vt(a){var h=this,l={db:null};if(a)for(var p in a)l[p]=typeof a[p]!="string"?a[p].toString():a[p];var y=new d(function(m,w){try{l.db=openDatabase(l.name,String(l.version),l.description,l.size)}catch(M){return w(M)}l.db.transaction(function(M){ot(M,l,function(){h._dbInfo=l,m()},function(E,D){w(D)})},w)});return l.serializer=Ae,y}function X(a,h,l,p,y,m){a.executeSql(l,p,y,function(w,M){M.code===M.SYNTAX_ERR?w.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[h.storeName],function(E,D){D.rows.length?m(E,M):ot(E,h,function(){E.executeSql(l,p,y,m)},m)},m):m(w,M)},m)}function jt(a,h){var l=this;a=S(a);var p=new d(function(y,m){l.ready().then(function(){var w=l._dbInfo;w.db.transaction(function(M){X(M,w,"SELECT * FROM "+w.storeName+" WHERE key = ? LIMIT 1",[a],function(E,D){var T=D.rows.length?D.rows.item(0).value:null;T&&(T=w.serializer.deserialize(T)),y(T)},function(E,D){m(D)})})}).catch(m)});return g(p,h),p}function Jt(a,h){var l=this,p=new d(function(y,m){l.ready().then(function(){var w=l._dbInfo;w.db.transaction(function(M){X(M,w,"SELECT * FROM "+w.storeName,[],function(E,D){for(var T=D.rows,_=T.length,z=0;z<_;z++){var U=T.item(z),O=U.value;if(O&&(O=w.serializer.deserialize(O)),O=a(O,U.key,z+1),O!==void 0){y(O);return}}y()},function(E,D){m(D)})})}).catch(m)});return g(p,h),p}function at(a,h,l,p){var y=this;a=S(a);var m=new d(function(w,M){y.ready().then(function(){h===void 0&&(h=null);var E=h,D=y._dbInfo;D.serializer.serialize(h,function(T,_){_?M(_):D.db.transaction(function(z){X(z,D,"INSERT OR REPLACE INTO "+D.storeName+" (key, value) VALUES (?, ?)",[a,T],function(){w(E)},function(U,O){M(O)})},function(z){if(z.code===z.QUOTA_ERR){if(p>0){w(at.apply(y,[a,E,l,p-1]));return}M(z)}})})}).catch(M)});return g(m,l),m}function Kt(a,h,l){return at.apply(this,[a,h,l,1])}function Yt(a,h){var l=this;a=S(a);var p=new d(function(y,m){l.ready().then(function(){var w=l._dbInfo;w.db.transaction(function(M){X(M,w,"DELETE FROM "+w.storeName+" WHERE key = ?",[a],function(){y()},function(E,D){m(D)})})}).catch(m)});return g(p,h),p}function Zt(a){var h=this,l=new d(function(p,y){h.ready().then(function(){var m=h._dbInfo;m.db.transaction(function(w){X(w,m,"DELETE FROM "+m.storeName,[],function(){p()},function(M,E){y(E)})})}).catch(y)});return g(l,a),l}function Qt(a){var h=this,l=new d(function(p,y){h.ready().then(function(){var m=h._dbInfo;m.db.transaction(function(w){X(w,m,"SELECT COUNT(key) as c FROM "+m.storeName,[],function(M,E){var D=E.rows.item(0).c;p(D)},function(M,E){y(E)})})}).catch(y)});return g(l,a),l}function Xt(a,h){var l=this,p=new d(function(y,m){l.ready().then(function(){var w=l._dbInfo;w.db.transaction(function(M){X(M,w,"SELECT key FROM "+w.storeName+" WHERE id = ? LIMIT 1",[a+1],function(E,D){var T=D.rows.length?D.rows.item(0).key:null;y(T)},function(E,D){m(D)})})}).catch(m)});return g(p,h),p}function en(a){var h=this,l=new d(function(p,y){h.ready().then(function(){var m=h._dbInfo;m.db.transaction(function(w){X(w,m,"SELECT key FROM "+m.storeName,[],function(M,E){for(var D=[],T=0;T<E.rows.length;T++)D.push(E.rows.item(T).key);p(D)},function(M,E){y(E)})})}).catch(y)});return g(l,a),l}function tn(a){return new d(function(h,l){a.transaction(function(p){p.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'",[],function(y,m){for(var w=[],M=0;M<m.rows.length;M++)w.push(m.rows.item(M).name);h({db:a,storeNames:w})},function(y,m){l(m)})},function(p){l(p)})})}function nn(a,h){h=R.apply(this,arguments);var l=this.config();a=typeof a!="function"&&a||{},a.name||(a.name=a.name||l.name,a.storeName=a.storeName||l.storeName);var p=this,y;return a.name?y=new d(function(m){var w;a.name===l.name?w=p._dbInfo.db:w=openDatabase(a.name,"","",0),a.storeName?m({db:w,storeNames:[a.storeName]}):m(tn(w))}).then(function(m){return new d(function(w,M){m.db.transaction(function(E){function D(U){return new d(function(O,W){E.executeSql("DROP TABLE IF EXISTS "+U,[],function(){O()},function(q,J){W(J)})})}for(var T=[],_=0,z=m.storeNames.length;_<z;_++)T.push(D(m.storeNames[_]));d.all(T).then(function(){w()}).catch(function(U){M(U)})},function(E){M(E)})})}):y=d.reject("Invalid arguments"),g(y,h),y}var rn={_driver:"webSQLStorage",_initStorage:Vt,_support:Wt(),iterate:Jt,getItem:jt,setItem:Kt,removeItem:Yt,clear:Zt,length:Qt,key:Xt,keys:en,dropInstance:nn};function on(){try{return typeof localStorage<"u"&&"setItem"in localStorage&&!!localStorage.setItem}catch{return!1}}function st(a,h){var l=a.name+"/";return a.storeName!==h.storeName&&(l+=a.storeName+"/"),l}function an(){var a="_localforage_support_test";try{return localStorage.setItem(a,!0),localStorage.removeItem(a),!1}catch{return!0}}function sn(){return!an()||localStorage.length>0}function cn(a){var h=this,l={};if(a)for(var p in a)l[p]=a[p];return l.keyPrefix=st(a,h._defaultConfig),sn()?(h._dbInfo=l,l.serializer=Ae,d.resolve()):d.reject()}function ln(a){var h=this,l=h.ready().then(function(){for(var p=h._dbInfo.keyPrefix,y=localStorage.length-1;y>=0;y--){var m=localStorage.key(y);m.indexOf(p)===0&&localStorage.removeItem(m)}});return g(l,a),l}function un(a,h){var l=this;a=S(a);var p=l.ready().then(function(){var y=l._dbInfo,m=localStorage.getItem(y.keyPrefix+a);return m&&(m=y.serializer.deserialize(m)),m});return g(p,h),p}function dn(a,h){var l=this,p=l.ready().then(function(){for(var y=l._dbInfo,m=y.keyPrefix,w=m.length,M=localStorage.length,E=1,D=0;D<M;D++){var T=localStorage.key(D);if(T.indexOf(m)===0){var _=localStorage.getItem(T);if(_&&(_=y.serializer.deserialize(_)),_=a(_,T.substring(w),E++),_!==void 0)return _}}});return g(p,h),p}function hn(a,h){var l=this,p=l.ready().then(function(){var y=l._dbInfo,m;try{m=localStorage.key(a)}catch{m=null}return m&&(m=m.substring(y.keyPrefix.length)),m});return g(p,h),p}function fn(a){var h=this,l=h.ready().then(function(){for(var p=h._dbInfo,y=localStorage.length,m=[],w=0;w<y;w++){var M=localStorage.key(w);M.indexOf(p.keyPrefix)===0&&m.push(M.substring(p.keyPrefix.length))}return m});return g(l,a),l}function mn(a){var h=this,l=h.keys().then(function(p){return p.length});return g(l,a),l}function gn(a,h){var l=this;a=S(a);var p=l.ready().then(function(){var y=l._dbInfo;localStorage.removeItem(y.keyPrefix+a)});return g(p,h),p}function pn(a,h,l){var p=this;a=S(a);var y=p.ready().then(function(){h===void 0&&(h=null);var m=h;return new d(function(w,M){var E=p._dbInfo;E.serializer.serialize(h,function(D,T){if(T)M(T);else try{localStorage.setItem(E.keyPrefix+a,D),w(m)}catch(_){(_.name==="QuotaExceededError"||_.name==="NS_ERROR_DOM_QUOTA_REACHED")&&M(_),M(_)}})})});return g(y,l),y}function yn(a,h){if(h=R.apply(this,arguments),a=typeof a!="function"&&a||{},!a.name){var l=this.config();a.name=a.name||l.name,a.storeName=a.storeName||l.storeName}var p=this,y;return a.name?y=new d(function(m){a.storeName?m(st(a,p._defaultConfig)):m(a.name+"/")}).then(function(m){for(var w=localStorage.length-1;w>=0;w--){var M=localStorage.key(w);M.indexOf(m)===0&&localStorage.removeItem(M)}}):y=d.reject("Invalid arguments"),g(y,h),y}var vn={_driver:"localStorageWrapper",_initStorage:cn,_support:on(),iterate:dn,getItem:un,setItem:pn,removeItem:gn,clear:ln,length:mn,key:hn,keys:fn,dropInstance:yn},bn=function(h,l){return h===l||typeof h=="number"&&typeof l=="number"&&isNaN(h)&&isNaN(l)},wn=function(h,l){for(var p=h.length,y=0;y<p;){if(bn(h[y],l))return!0;y++}return!1},ct=Array.isArray||function(a){return Object.prototype.toString.call(a)==="[object Array]"},ae={},lt={},te={INDEXEDDB:qt,WEBSQL:rn,LOCALSTORAGE:vn},Mn=[te.INDEXEDDB._driver,te.WEBSQL._driver,te.LOCALSTORAGE._driver],ge=["dropInstance"],_e=["clear","getItem","iterate","key","keys","length","removeItem","setItem"].concat(ge),Sn={description:"",driver:Mn.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1};function Cn(a,h){a[h]=function(){var l=arguments;return a.ready().then(function(){return a[h].apply(a,l)})}}function Ne(){for(var a=1;a<arguments.length;a++){var h=arguments[a];if(h)for(var l in h)h.hasOwnProperty(l)&&(ct(h[l])?arguments[0][l]=h[l].slice():arguments[0][l]=h[l])}return arguments[0]}var En=(function(){function a(h){i(this,a);for(var l in te)if(te.hasOwnProperty(l)){var p=te[l],y=p._driver;this[l]=y,ae[y]||this.defineDriver(p)}this._defaultConfig=Ne({},Sn),this._config=Ne({},this._defaultConfig,h),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver).catch(function(){})}return a.prototype.config=function(l){if((typeof l>"u"?"undefined":o(l))==="object"){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var p in l){if(p==="storeName"&&(l[p]=l[p].replace(/\W/g,"_")),p==="version"&&typeof l[p]!="number")return new Error("Database version must be a number.");this._config[p]=l[p]}return"driver"in l&&l.driver?this.setDriver(this._config.driver):!0}else return typeof l=="string"?this._config[l]:this._config},a.prototype.defineDriver=function(l,p,y){var m=new d(function(w,M){try{var E=l._driver,D=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!l._driver){M(D);return}for(var T=_e.concat("_initStorage"),_=0,z=T.length;_<z;_++){var U=T[_],O=!wn(ge,U);if((O||l[U])&&typeof l[U]!="function"){M(D);return}}var W=function(){for(var se=function(Rn){return function(){var In=new Error("Method "+Rn+" is not implemented by the current driver"),ut=d.reject(In);return g(ut,arguments[arguments.length-1]),ut}},ke=0,Tn=ge.length;ke<Tn;ke++){var Pe=ge[ke];l[Pe]||(l[Pe]=se(Pe))}};W();var q=function(se){ae[E]&&console.info("Redefining LocalForage driver: "+E),ae[E]=l,lt[E]=se,w()};"_support"in l?l._support&&typeof l._support=="function"?l._support().then(q,M):q(!!l._support):q(!0)}catch(J){M(J)}});return b(m,p,y),m},a.prototype.driver=function(){return this._driver||null},a.prototype.getDriver=function(l,p,y){var m=ae[l]?d.resolve(ae[l]):d.reject(new Error("Driver not found."));return b(m,p,y),m},a.prototype.getSerializer=function(l){var p=d.resolve(Ae);return b(p,l),p},a.prototype.ready=function(l){var p=this,y=p._driverSet.then(function(){return p._ready===null&&(p._ready=p._initDriver()),p._ready});return b(y,l,l),y},a.prototype.setDriver=function(l,p,y){var m=this;ct(l)||(l=[l]);var w=this._getSupportedDrivers(l);function M(){m._config.driver=m.driver()}function E(_){return m._extend(_),M(),m._ready=m._initStorage(m._config),m._ready}function D(_){return function(){var z=0;function U(){for(;z<_.length;){var O=_[z];return z++,m._dbInfo=null,m._ready=null,m.getDriver(O).then(E).catch(U)}M();var W=new Error("No available storage method found.");return m._driverSet=d.reject(W),m._driverSet}return U()}}var T=this._driverSet!==null?this._driverSet.catch(function(){return d.resolve()}):d.resolve();return this._driverSet=T.then(function(){var _=w[0];return m._dbInfo=null,m._ready=null,m.getDriver(_).then(function(z){m._driver=z._driver,M(),m._wrapLibraryMethodsWithReady(),m._initDriver=D(w)})}).catch(function(){M();var _=new Error("No available storage method found.");return m._driverSet=d.reject(_),m._driverSet}),b(this._driverSet,p,y),this._driverSet},a.prototype.supports=function(l){return!!lt[l]},a.prototype._extend=function(l){Ne(this,l)},a.prototype._getSupportedDrivers=function(l){for(var p=[],y=0,m=l.length;y<m;y++){var w=l[y];this.supports(w)&&p.push(w)}return p},a.prototype._wrapLibraryMethodsWithReady=function(){for(var l=0,p=_e.length;l<p;l++)Cn(this,_e[l])},a.prototype.createInstance=function(l){return new a(l)},a})(),Dn=new En;n.exports=Dn},{3:3}]},{},[4])(4)})})(Fe)),Fe.exports}var Un=Ln();const On=x.getDefaultExportFromCjs(Un);function ne(v){return`model:${v}`}function qn(v){const e=v.lastIndexOf("/");return e>=0?v.substring(0,e+1):""}async function Wn(v,e=3,t=1e3){let n=null;for(let r=0;r<e;r++)try{const o=await fetch(v);if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);return o}catch(o){if(n=o,r===e-1)throw o;const i=t*Math.pow(2,r);console.warn(`[ModelCache] Fetch failed (attempt ${r+1}/${e}), retrying in ${i}ms...`,{url:v,error:String(o)}),await new Promise(s=>setTimeout(s,i))}throw n}async function ft(v,e,t,n=3,r=1e3){let o=null;for(let i=0;i<n;i++){const s=e?await e(v):v;try{const c=await fetch(s);if(!c.ok)throw new Error(`HTTP ${c.status}: ${c.statusText}`);const u=await c.text(),f=JSON.parse(u),d=qn(s),g={},b=[];if(f.weightsManifest&&Array.isArray(f.weightsManifest)){for(const R of f.weightsManifest)if(R.paths&&Array.isArray(R.paths))for(const I of R.paths)b.push(I)}const S=b.map(async R=>{const I=d+R,A=await Wn(I,n,r);g[R]=await A.arrayBuffer()});return await Promise.all(S),{manifest:u,weights:g,savedAt:Date.now(),originalUrl:v}}catch(c){if(o=c,i===n-1)throw c;t?.(v);const u=r*Math.pow(2,i);console.warn(`[ModelCache] Model fetch failed (attempt ${i+1}/${n}), re-resolving and retrying in ${u}ms...`,{url:v,resolvedUrl:s,error:String(c)}),await new Promise(f=>setTimeout(f,u))}}throw o}function xe(v,e){return JSON.parse(e.manifest),{load:async()=>vt(e)}}function vt(v){const e=JSON.parse(v.manifest),t=[],n=[];if(e.weightsManifest&&Array.isArray(e.weightsManifest))for(const r of e.weightsManifest){if(r.weights&&Array.isArray(r.weights))for(const o of r.weights)n.push(o);if(r.paths&&Array.isArray(r.paths))for(const o of r.paths){const i=v.weights[o];if(!i)throw new Error(`[ModelCache] Weight shard "${o}" not found in cache`);t.push(i)}}return{modelTopology:e.modelTopology,format:e.format??"graph-model",generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightSpecs:n.length>0?n:void 0,weightData:t.length>0?t.length===1?t[0]:t:void 0}}const bt=new Map;let mt=!1;function Hn(){mt||(mt=!0,import("@tensorflow/tfjs").then(v=>{v.io.registerLoadRouter((e=>{if(typeof e=="string"&&e.startsWith("cached://")){const t=bt.get(e);if(t)return{load:async()=>{const n=await t.store.getItem(t.key);if(!n)throw new Error(`[ModelCache] Model not in cache: ${e}`);return vt(n)}}}return null}))}))}Hn();class wt{constructor(e={}){this.store=On.createInstance({name:e.storeName??"playlist-data-engine-models",description:e.description??"Cached TF.js model artifacts for playlist-data-engine"})}async has(e){return await this.store.getItem(ne(e))!=null}async getCacheInfo(e){const t=await this.store.getItem(ne(e));if(!t)return{cached:!1};let n=t.manifest.length;for(const r of Object.values(t.weights))n+=r.byteLength;return{cached:!0,savedAt:t.savedAt,size:n}}async loadFromCache(e,t){const n=await this.store.getItem(ne(t));if(!n)throw new Error(`[ModelCache] Model not cached: ${t}`);return e.loadGraphModel(xe(e,n))}async getOrFetchGraphModel(e,t,n={}){const r=ne(t);try{const i=await this.store.getItem(r);if(i)return console.info(`[ModelCache] Loading model from cache: ${t}`),await e.loadGraphModel(xe(e,i))}catch(i){console.warn("[ModelCache] Cache load failed, clearing and re-fetching:",i),await this.store.removeItem(r)}console.info(`[ModelCache] Downloading model: ${t}`);const o=await ft(t,n.resolveUrl,n.invalidateUrlCache,n.maxRetries??3,n.baseDelayMs??1e3);return await this.store.setItem(r,o),console.info(`[ModelCache] Model cached: ${t} (${Object.keys(o.weights).length} shards)`),e.loadGraphModel(xe(e,o))}async getOrFetchEssentiaUrl(e,t={}){const n=ne(e),r=`cached://${e}`;if(await this.store.getItem(n))console.info(`[ModelCache] Loading Essentia model from cache: ${e}`);else{console.info(`[ModelCache] Downloading model for Essentia: ${e}`);const i=await ft(e,t.resolveUrl,t.invalidateUrlCache,t.maxRetries??3,t.baseDelayMs??1e3);await this.store.setItem(n,i),console.info(`[ModelCache] Model cached: ${e} (${Object.keys(i.weights).length} shards)`)}return bt.set(r,{store:this.store,key:n}),r}async clear(e){e?(await this.store.removeItem(ne(e)),console.info(`[ModelCache] Cleared cache for: ${e}`)):(await this.store.clear(),console.info("[ModelCache] Cleared all cached models"))}async listCachedModels(){return(await this.store.keys()).filter(t=>t.startsWith("model:")).map(t=>t.replace("model:",""))}async totalCacheSize(){let e=0;return await this.store.iterate(t=>{if(t){e+=t.manifest.length;for(const n of Object.values(t.weights))e+=n.byteLength}}),e}}const ie=new wt,Se="https://arweave.net/_HoMwkbF0JUamTiVGWNnCCC5yDjcPry-ENhzN6Xn3U0/model.json",gt={algorithm:"pitch_melodia",minFrequency:80,maxFrequency:2e4,frameSize:2048,hopSize:128,targetSampleRate:44100,crepeModelUrl:Se},Gn=69,$n=440,Vn=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];class he{constructor(e){this.essentiaWASM=null,this.algorithms=null,this.crepeModel=null,this.initialized=!1,this.resolvedUrlCache=new Map,this.config={...gt,...e}}static async create(e={}){const t={...gt,...e};t.resolveUrl||(t.resolveUrl=K.arweaveGatewayManager.resolveUrl.bind(K.arweaveGatewayManager));const n=new he(t);return await n.initializeEssentia(),t.algorithm==="pitch_crepe"&&await n.loadCrepeModel(t.crepeModelUrl),n}getConfig(){return{...this.config}}async initializeEssentia(){if(this.initialized)return;const t=(await Promise.resolve().then(()=>require("./essentia-wasm.es-7mXF1zkQ.cjs"))).EssentiaWASM;await t.ready,this.essentiaWASM=t,this.algorithms=new t.EssentiaJS(!1),this.initialized=!0}async loadCrepeModel(e){if(this.config.enableModelCache!==!1)this.crepeModel=await ie.getOrFetchGraphModel(G,e,{resolveUrl:this.config.resolveUrl,invalidateUrlCache:n=>K.arweaveGatewayManager.invalidateCacheForUrl(n),maxRetries:3,baseDelayMs:1e3});else{const n=await this.resolveUrlWithCache(e);let r=null;for(let o=0;o<3;o++)try{this.crepeModel=await G.loadGraphModel(n);break}catch(i){r=i;const s=String(i).toLowerCase();if(!(s.includes("fetch")||s.includes("network")||s.includes("timeout")||s.includes("failed to fetch")||s.includes("networkerror"))||o===2)throw i;const u=1e3*Math.pow(2,o);console.warn(`[EssentiaPitchDetector] CREPE model load failed (attempt ${o+1}/3), retrying in ${u}ms...`,{originalUrl:e,resolvedUrl:n,error:String(i)}),await new Promise(f=>setTimeout(f,u))}if(!this.crepeModel)throw new Error(`Failed to load CREPE model from ${e}: ${r?.message??String(r)}`)}const t=G.zeros([1,1024]);G.tidy(()=>{this.crepeModel.execute(t)}),t.dispose(),console.log("[EssentiaPitchDetector] CREPE model loaded")}async resolveUrlWithCache(e){if(this.resolvedUrlCache.has(e))return this.resolvedUrlCache.get(e);if(!this.config.resolveUrl)return e;try{const t=await this.config.resolveUrl(e);return this.resolvedUrlCache.set(e,t),t!==e&&console.info("[EssentiaPitchDetector] Resolved URL to alternate gateway",{originalUrl:e,resolvedUrl:t}),t}catch(t){return console.warn("[EssentiaPitchDetector] URL resolution failed, using original URL",{url:e,error:String(t)}),this.resolvedUrlCache.set(e,e),e}}detectSignal(e,t){if(!this.initialized)throw new Error("EssentiaPitchDetector not initialized. Use create() factory method.");if(e.length===0)return[];switch(this.config.algorithm){case"predominant_melodia":return this.runPredominantMelodia(e,t);case"pitch_melodia":return this.runPitchMelodia(e,t);case"pitch_yin_probabilistic":return this.runPitchYinProbabilistic(e,t);case"multipitch_melodia":return this.runMultiPitchMelodia(e,t);case"multipitch_klapuri":return this.runMultiPitchKlapuri(e,t);case"pitch_crepe":return this.runCrepe(e,t);default:throw new Error(`Unknown algorithm: ${this.config.algorithm}`)}}runPredominantMelodia(e,t){const n=this.essentiaWASM.arrayToVector(e),r=this.algorithms.PredominantPitchMelodia(n,10,3,this.config.frameSize,!1,.8,this.config.hopSize,1,40,this.config.maxFrequency,100,this.config.minFrequency,20,.9,.9,27.5625,55,t,100,!1,.2),o=Array.from(this.essentiaWASM.vectorToArray(r.pitch)),i=Array.from(this.essentiaWASM.vectorToArray(r.pitchConfidence)),s=this.config.hopSize/t;return this.mapSingleF0(o,i,s)}runPitchMelodia(e,t){const n=this.essentiaWASM.arrayToVector(e),r=this.algorithms.PitchMelodia(n,10,3,this.config.frameSize,!1,.8,this.config.hopSize,1,40,this.config.maxFrequency,100,this.config.minFrequency,20,.9,.9,27.5625,55,t,100),o=Array.from(this.essentiaWASM.vectorToArray(r.pitch)),i=Array.from(this.essentiaWASM.vectorToArray(r.pitchConfidence)),s=this.config.hopSize/t;return this.mapSingleF0(o,i,s)}runPitchYinProbabilistic(e,t){const n=this.essentiaWASM.arrayToVector(e),r=this.algorithms.PitchYinProbabilistic(n,this.config.frameSize,this.config.hopSize,.1,"negative",!1,t),o=Array.from(this.essentiaWASM.vectorToArray(r.pitch)),i=Array.from(this.essentiaWASM.vectorToArray(r.voicedProbabilities)),s=this.config.hopSize/t;return o.map((c,u)=>{const f=u*s;if(c>0&&i[u]>.5){const g=Math.round(this.frequencyToMidi(c));return{timestamp:f,frequency:c,probability:i[u],isVoiced:!0,midiNote:g,noteName:this.midiToNoteName(g)}}return{timestamp:f,frequency:0,probability:0,isVoiced:!1,midiNote:null,noteName:null}})}runMultiPitchMelodia(e,t){const n=this.essentiaWASM.arrayToVector(e),r=this.algorithms.MultiPitchMelodia(n,10,3,this.config.frameSize,!1,.8,this.config.hopSize,1,40,this.config.maxFrequency,100,this.config.minFrequency,20,.9,.9,27.5625,55,t,100);return this.mapMultiPitch(r.pitch,t)}runMultiPitchKlapuri(e,t){const n=this.essentiaWASM.arrayToVector(e),r=this.algorithms.MultiPitchKlapuri(n,10,this.config.frameSize,.8,this.config.hopSize,1,40,this.config.maxFrequency,this.config.minFrequency,10,55,t);return this.mapMultiPitch(r.pitch,t)}runCrepe(e,t){if(!this.crepeModel)throw new Error('CREPE model not loaded. Ensure algorithm is "pitch_crepe" and model URL is valid.');const n=16e3,r=1024,o=256,i=this.resampleSignal(e,t,n),s=Math.floor((i.length-r)/o)+1,c=o/n,u=32.7,f=[];for(let d=0;d<s;d++){const g=d*o,b=i.slice(g,g+r),S=d*c;let R;try{const A=G.tidy(()=>{const C=G.tensor(b,[1,r]);return this.crepeModel.execute(C).dataSync().slice()});let B=0,N=0,k=0;for(let C=0;C<360;C++){const F=A[C];B+=C*10*F,N+=F,F>k&&(k=F)}if(N>0&&k>.3){const C=B/N,F=u*Math.pow(2,C/1200),P=Math.round(this.frequencyToMidi(F));R={timestamp:S,frequency:F,probability:k,isVoiced:!0,midiNote:P,noteName:this.midiToNoteName(P)}}else R={timestamp:S,frequency:0,probability:0,isVoiced:!1,midiNote:null,noteName:null}}catch(I){console.error(`[EssentiaPitchDetector] CREPE inference error at frame ${d}:`,I),R={timestamp:S,frequency:0,probability:0,isVoiced:!1,midiNote:null,noteName:null}}f.push(R)}return f}mapSingleF0(e,t,n){return e.map((r,o)=>{const i=o*n;if(r>0){const s=Math.round(this.frequencyToMidi(r));return{timestamp:i,frequency:r,probability:t[o]??0,isVoiced:!0,midiNote:s,noteName:this.midiToNoteName(s)}}return{timestamp:i,frequency:0,probability:0,isVoiced:!1,midiNote:null,noteName:null}})}mapMultiPitch(e,t){const n=e.size(),r=this.config.hopSize/t,o=[];for(let i=0;i<n;i++){const s=e.get(i),u=Array.from(this.essentiaWASM.vectorToArray(s)).filter(d=>d>0).sort((d,g)=>d-g),f=i*r;if(u.length>0){const d=u[0],g=Math.round(this.frequencyToMidi(d)),b=u.slice(1).map(S=>({frequency:S,probability:1}));o.push({timestamp:f,frequency:d,probability:1,isVoiced:!0,midiNote:g,noteName:this.midiToNoteName(g),...b.length>0?{alternativeHypotheses:b}:{}})}else o.push({timestamp:f,frequency:0,probability:0,isVoiced:!1,midiNote:null,noteName:null})}return o}resampleSignal(e,t,n){if(t===n)return e;const r=t/n,o=Math.round(e.length/r),i=new Float32Array(o);for(let s=0;s<o;s++){const c=s*r,u=Math.floor(c),f=Math.min(u+1,e.length-1),d=c-u;i[s]=e[u]*(1-d)+e[f]*d}return i}frequencyToMidi(e){return Gn+12*Math.log2(e/$n)}midiToNoteName(e){const t=Math.floor(e/12)-1,n=Math.round(e)%12;return`${Vn[n]}${t}`}}const pt={targetSampleRate:44100,pitchDetector:{},pitchAlgorithm:"pitch_melodia",crepeModelUrl:Se};class Mt{constructor(e={}){this.essentiaDetector=null,this.config={...pt,...e,pitchDetector:{...pt.pitchDetector,...e.pitchDetector}},this.fullSpectrumDetector=new x.PitchDetector({...this.config.pitchDetector,minFrequency:this.config.pitchDetector.minFrequency??80,maxFrequency:this.config.pitchDetector.maxFrequency??1e3,targetSampleRate:this.config.targetSampleRate,yinThreshold:this.config.pitchDetector.yinThreshold??.4})}getConfig(){return{...this.config}}async linkWithComposite(e,t){const n=this.config.targetSampleRate,o=x.resampleAudio(t,n).data;let i,s;this.config.pitchAlgorithm==="pyin_legacy"?(i=this.fullSpectrumDetector.detectSignalRaw(o,n),s=this.fullSpectrumDetector.getConfig().hopSize/n):(this.essentiaDetector||(this.essentiaDetector=await he.create({algorithm:this.config.pitchAlgorithm,minFrequency:this.config.pitchDetector.minFrequency??80,maxFrequency:this.config.pitchDetector.maxFrequency??2e4,crepeModelUrl:this.config.crepeModelUrl,resolveUrl:this.config.resolveUrl}),console.log(`[PitchBeatLinker] Essentia detector initialized: ${this.config.pitchAlgorithm}`)),i=this.essentiaDetector.detectSignal(o,n),s=this.essentiaDetector.getConfig().hopSize/n),console.debug("[PitchBeatLinker] Full-spectrum analysis:",{detector:this.config.pitchAlgorithm==="pyin_legacy"?"pYIN":`essentia/${this.config.pitchAlgorithm}`,totalFrames:i.length,voicedFrames:i.filter(u=>u.isVoiced).length,signalLength:o.length,signalSampleRate:n});const c=[];for(const u of e.beats){const f=u.detectedTimestamp??u.timestamp,d=Math.round(f/s);let g=null,b=1/0,S=0;for(let R=0;R<i.length;R++){const I=i[R];if(!I.isVoiced)continue;const A=Math.abs(R-d);(A<b||A===b&&I.probability>S)&&(b=A,S=I.probability,g=I)}c.push({beatIndex:u.beatIndex,timestamp:u.timestamp,band:u.sourceBand,pitch:g,direction:"none",intervalFromPrevious:0})}return c}deriveVariantPitches(e,t){const n=[],r=new Map;for(const o of t){const i=Math.round(o.timestamp*1e3);r.set(i,o)}for(const o of e.beats){const i=Math.round(o.timestamp*1e3);let s=r.get(i);if(!s)for(let c=-2;c<=2&&(s=r.get(i+c),!s);c++);s?n.push({beatIndex:o.beatIndex,timestamp:o.timestamp,band:o.sourceBand,pitch:s.pitch,direction:s.direction,intervalFromPrevious:s.intervalFromPrevious,intervalCategory:s.intervalCategory}):n.push({beatIndex:o.beatIndex,timestamp:o.timestamp,band:o.sourceBand,pitch:null,direction:"none",intervalFromPrevious:0})}return n}deriveAllVariantPitches(e,t){return{easy:this.deriveVariantPitches(e.easy,t),medium:this.deriveVariantPitches(e.medium,t),hard:this.deriveVariantPitches(e.hard,t)}}}const jn={maxTimeGapForConsecutive:.5};function St(v){return v===0?"unison":v<=2?"small":v<=4?"medium":v<=7?"large":"very_large"}function Jn(v,e){return Math.abs(v-e)}function Kn(v,e){return v===null||e===null?"none":v>e?"up":v<e?"down":"stable"}function Yn(v){if(v.length===0)return"stable";let e=0,t=0,n=0;for(const s of v)s.direction==="up"?e++:s.direction==="down"?t++:n++;if(e===0&&t===0)return"stable";const r=e-t,i=(e+t+n)*.2;return Math.abs(r)<=i?"mixed":e>t?"ascending":t>e?"descending":"stable"}function yt(v){const e=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],t=Math.floor(v/12)-1,n=v%12;return`${e[n]}${t}`}class Zn{constructor(e={}){this.config={...jn,...e}}getConfig(){return{...this.config}}analyze(e){const t=this.analyzeBandPitches(e),{directionStats:n,intervalStats:r,metadata:o}=this.calculateStatistics(t),i=this.buildMelodyContour(t);return{pitchByBeat:t,melodyContour:i,directionStats:n,intervalStats:r,metadata:o}}analyzeBandPitches(e){if(e.length===0)return[];const t=[];for(let n=0;n<e.length;n++){const r=e[n],o=n>0?e[n-1]:null,i=o!==null&&r.timestamp-o.timestamp<=this.config.maxTimeGapForConsecutive;let s,c,u;if(!i||!o||!o.pitch||!r.pitch)s="none",c=0,u="unison";else{const f=r.pitch.midiNote,d=o.pitch.midiNote;f===null||d===null?(s="none",c=0,u="unison"):(s=Kn(f,d),c=Jn(f,d),u=St(c))}t.push({...r,direction:s,intervalFromPrevious:c,intervalCategory:u})}return t}buildMelodyContour(e){const t=e.filter(b=>b.pitch?.isVoiced);if(t.length===0)return{segments:[],direction:"stable",range:{minNote:"N/A",maxNote:"N/A",semitones:0},shortTermDirection:"stable",mediumTermDirection:"stable",longTermDirection:"stable"};const n=t.map(b=>b.pitch?.midiNote).filter(b=>b!==null);if(n.length===0)return{segments:[],direction:"stable",range:{minNote:"N/A",maxNote:"N/A",semitones:0},shortTermDirection:"stable",mediumTermDirection:"stable",longTermDirection:"stable"};const r=Math.min(...n),o=Math.max(...n),i=yt(r),s=yt(o),c=this.buildSegments(t),u=Yn(c),f=this.calculateTimeWindowDirection(e,1,2),d=this.calculateTimeWindowDirection(e,4,8),g=this.calculateTimeWindowDirection(e,16,1/0);return{segments:c,direction:u,range:{minNote:i,maxNote:s,semitones:o-r},shortTermDirection:f,mediumTermDirection:d,longTermDirection:g}}calculateTimeWindowDirection(e,t,n){if(e.length===0||t<1)return"stable";const r=Math.min(n,Math.max(t,e.length)),o=e.slice(-r);if(o.length===0)return"stable";let i=0,s=0,c=0;for(const u of o)u.direction==="up"?i++:u.direction==="down"?s++:u.direction==="stable"&&c++;return this.determineOverallDirectionFromCounts(i,s,c)}determineOverallDirectionFromCounts(e,t,n){const r=e+t+n;if(r===0)return"stable";const o=r*.2,i=e-t;return Math.abs(i)<=o?"mixed":e>t?"ascending":t>e?"descending":"stable"}buildSegments(e){if(e.length===0)return[];const t=[];let n=null;for(const r of e){const o=r.direction;if(o==="none"){n&&(t.push({startTime:n.startTime,endTime:n.endTime,startPitch:n.startPitch,endPitch:n.endPitch,direction:n.direction,interval:Math.abs(n.endMidi-n.startMidi)}),n=null);continue}if(!n||n.direction!==o){n&&t.push({startTime:n.startTime,endTime:n.endTime,startPitch:n.startPitch,endPitch:n.endPitch,direction:n.direction,interval:Math.abs(n.endMidi-n.startMidi)});const i=r.pitch?.noteName??"N/A",s=r.pitch?.midiNote??60;n={startTime:r.timestamp,endTime:r.timestamp,startPitch:i,endPitch:i,direction:o,startMidi:s,endMidi:s}}else{const i=r.pitch?.midiNote??n.endMidi,s=r.pitch?.noteName??n.endPitch;n.endTime=r.timestamp,n.endPitch=s,n.endMidi=i}}return n&&t.push({startTime:n.startTime,endTime:n.endTime,startPitch:n.startPitch,endPitch:n.endPitch,direction:n.direction,interval:Math.abs(n.endMidi-n.startMidi)}),t}calculateStatistics(e){const t={up:0,down:0,stable:0,none:0},n={unison:0,small:0,medium:0,large:0,very_large:0};let r=0,o=0;for(const i of e)i.pitch?.isVoiced&&r++,t[i.direction]++,i.direction!=="none"&&o++,i.intervalCategory&&n[i.intervalCategory]++;return{directionStats:t,intervalStats:n,metadata:{totalBeats:e.length,voicedBeats:r,directionCalculatedBeats:o}}}}const Qn={algorithm:"pitch_melodia",minFrequency:80,maxFrequency:2e4,sampleRate:44100,hopSize:1024,crepeModelUrl:Se,resolveUrl:K.arweaveGatewayManager.resolveUrl.bind(K.arweaveGatewayManager),includeContour:!0,onProgress:void 0},Xn=69,er=440,tr=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];class nr{constructor(e={}){this.config={...Qn,...e}}getConfig(){return{...this.config}}async analyze(e){const{onProgress:t}=this.config;t?.("fetching",0);const{signal:n,sampleRate:r,duration:o}=await this.fetchAndDecodeAudio(e);t?.("fetching",1),t?.("detecting",0);const i=this.resolveDefaults(this.config),s=await this.detectPitch(n,r,i);t?.("detecting",1);const c=this.computeSummary(s);let u,f,d;if(this.config.includeContour!==!1){const g=this.computeContour(s);u=g.contour,f=g.directionStats,d=g.intervalStats}return{pitchResults:s,contour:u,voicingRatio:c.voicingRatio,averageFrequency:c.averageFrequency,medianFrequency:c.medianFrequency,minFrequency:c.minFrequency,maxFrequency:c.maxFrequency,pitchRangeSemitones:c.pitchRangeSemitones,lowestNote:c.lowestNote,highestNote:c.highestNote,noteDistribution:c.noteDistribution,totalFrames:c.totalFrames,voicedFrames:c.voicedFrames,directionStats:f,intervalStats:d,analysis_metadata:{algorithm_used:this.config.algorithm,analyzed_at:new Date().toISOString(),duration_analyzed:o}}}async fetchAndDecodeAudio(e){const t=this.config.resolveUrl?await this.config.resolveUrl(e):e,n=await fetch(t);if(!n.ok)throw new Error(`Failed to fetch audio: ${n.statusText}`);const r=await n.arrayBuffer(),o=globalThis.AudioContext||globalThis.window?.AudioContext;if(!o)throw new Error("AudioContext not available in this environment");const i=new o,s=await new Promise((u,f)=>{i.decodeAudioData(r,u,f)}),c=new Float32Array(s.length);for(let u=0;u<s.numberOfChannels;u++){const f=s.getChannelData(u);for(let d=0;d<s.length;d++)c[d]+=f[d]/s.numberOfChannels}return{signal:c,sampleRate:s.sampleRate,duration:s.duration}}resolveDefaults(e){const t={...e};return e.maxFrequency===void 0&&(e.algorithm==="pyin_legacy"?t.maxFrequency=1e3:t.maxFrequency=2e4),t}async detectPitch(e,t,n){const r=n.algorithm??"pitch_melodia";return r==="pyin_legacy"?new x.PitchDetector({minFrequency:n.minFrequency??80,maxFrequency:n.maxFrequency??1e3,targetSampleRate:n.sampleRate??44100,hopSize:n.hopSize??1024}).detectSignal(e,t):(await he.create({algorithm:r,minFrequency:n.minFrequency??80,maxFrequency:n.maxFrequency??2e4,targetSampleRate:n.sampleRate??44100,hopSize:n.hopSize??1024,crepeModelUrl:n.crepeModelUrl,resolveUrl:n.resolveUrl})).detectSignal(e,t)}computeSummary(e){const t=e.length,n=e.filter(N=>N.isVoiced&&N.frequency>0),r=n.length;if(r===0)return{voicingRatio:0,averageFrequency:0,medianFrequency:0,minFrequency:0,maxFrequency:0,pitchRangeSemitones:0,lowestNote:null,highestNote:null,noteDistribution:[],totalFrames:t,voicedFrames:0};const o=n.map(N=>N.frequency),i=[...o].sort((N,k)=>N-k),s=o.reduce((N,k)=>N+k,0)/o.length,c=Math.floor(i.length/2),u=i.length%2!==0?i[c]:(i[c-1]+i[c])/2,f=i[0],d=i[i.length-1],g=this.frequencyToMidi(f),b=this.frequencyToMidi(d),S=Math.abs(b-g),R=this.midiToNoteName(Math.round(g)),I=this.midiToNoteName(Math.round(b)),A=new Map;for(const N of n)N.noteName&&A.set(N.noteName,(A.get(N.noteName)??0)+1);const B=Array.from(A.entries()).map(([N,k])=>({note:N,count:k,percentage:k/r*100})).sort((N,k)=>k.count-N.count);return{voicingRatio:r/t,averageFrequency:s,medianFrequency:u,minFrequency:f,maxFrequency:d,pitchRangeSemitones:S,lowestNote:R,highestNote:I,noteDistribution:B,totalFrames:t,voicedFrames:r}}computeContour(e){const t=e.filter(A=>A.isVoiced&&A.midiNote!==null);if(t.length===0)return{contour:{direction:"stable",range:{minNote:"N/A",maxNote:"N/A",semitones:0},segments:[],shortTermDirection:"stable",mediumTermDirection:"stable",longTermDirection:"stable"},directionStats:{up:0,down:0,stable:0,none:e.length},intervalStats:{unison:0,small:0,medium:0,large:0,very_large:0}};const n=t.map(A=>A.midiNote).filter(A=>A!==null),r=Math.min(...n),o=Math.max(...n),i=this.midiToNoteName(r),s=this.midiToNoteName(o),c={up:0,down:0,stable:0,none:0},u={unison:0,small:0,medium:0,large:0,very_large:0},f=[];let d=null,g=null;for(const A of t){const B=A.midiNote;if(B===null){c.none++;continue}if(g===null){g=B;continue}let N;const k=Math.abs(B-g);B>g?(N="up",c.up++):B<g?(N="down",c.down++):(N="stable",c.stable++);const C=St(k);u[C]++,!d||d.direction!==N?(d&&f.push({startTime:d.startTime,endTime:d.endTime,startNote:d.startNote,endNote:d.endNote,direction:d.direction,interval:Math.abs(d.endMidi-d.startMidi)}),d={startTime:A.timestamp,endTime:A.timestamp,startNote:this.midiToNoteName(g),endNote:this.midiToNoteName(B),direction:N,startMidi:g,endMidi:B}):(d.endTime=A.timestamp,d.endNote=this.midiToNoteName(B),d.endMidi=B),g=B}d&&f.push({startTime:d.startTime,endTime:d.endTime,startNote:d.startNote,endNote:d.endNote,direction:d.direction,interval:Math.abs(d.endMidi-d.startMidi)});const b=this.determineOverallDirection(f),S=this.calculateTimeWindowDirection(e,1,2),R=this.calculateTimeWindowDirection(e,4,8),I=this.calculateTimeWindowDirection(e,16,1/0);return{contour:{direction:b,range:{minNote:i,maxNote:s,semitones:o-r},segments:f,shortTermDirection:S,mediumTermDirection:R,longTermDirection:I},directionStats:c,intervalStats:u}}determineOverallDirection(e){if(e.length===0)return"stable";let t=0,n=0,r=0;for(const c of e)c.direction==="up"?t++:c.direction==="down"?n++:r++;if(t===0&&n===0)return"stable";const o=t-n,s=(t+n+r)*.2;return Math.abs(o)<=s?"mixed":t>n?"ascending":n>t?"descending":"stable"}calculateTimeWindowDirection(e,t,n){const r=e.filter(d=>d.isVoiced&&d.midiNote!==null);if(r.length===0||t<1)return"stable";const o=Math.min(n,Math.max(t,r.length)),i=r.slice(-o);if(i.length===0)return"stable";let s=0,c=0,u=0,f=null;for(const d of i){const g=d.midiNote;g!==null&&(f!==null&&(g>f?s++:g<f?c++:u++),f=g)}return this.determineOverallDirectionFromCounts(s,c,u)}determineOverallDirectionFromCounts(e,t,n){const r=e+t+n;if(r===0)return"stable";const o=r*.2,i=e-t;return Math.abs(i)<=o?"mixed":e>t?"ascending":t>e?"descending":"stable"}frequencyToMidi(e){return Xn+12*Math.log2(e/er)}midiToNoteName(e){const t=Math.floor(e/12)-1,n=Math.round(e)%12;return`${tr[n]}${t}`}}const Ct={up:{ascending:{unison:"up",small:"up",medium:"right",large:"right",very_large:"left"},descending:{unison:"up",small:"left",medium:"right",large:"down",very_large:"down"},stable:"up"},right:{ascending:{unison:"right",small:"up",medium:"up",large:"up",very_large:"left"},descending:{unison:"right",small:"down",medium:"down",large:"down",very_large:"left"},stable:"right"},down:{ascending:{unison:"down",small:"left",medium:"right",large:"up",very_large:"up"},descending:{unison:"down",small:"down",medium:"left",large:"left",very_large:"right"},stable:"down"},left:{ascending:{unison:"left",small:"up",medium:"up",large:"up",very_large:"right"},descending:{unison:"left",small:"down",medium:"down",large:"down",very_large:"right"},stable:"left"}},rr={up:{ascending:"up",descending:"left",stable:"up"},right:{ascending:"up",descending:"down",stable:"right"},down:{ascending:"right",descending:"down",stable:"down"},left:{ascending:"up",descending:"down",stable:"left"}},Et={1:{ascending:{unison:1,small:2,medium:2,large:3,very_large:3},descending:{unison:1,small:4,medium:4,large:3,very_large:3},stable:1},2:{ascending:{unison:2,small:3,medium:3,large:4,very_large:4},descending:{unison:2,small:1,medium:1,large:4,very_large:4},stable:2},3:{ascending:{unison:3,small:4,medium:4,large:5,very_large:5},descending:{unison:3,small:2,medium:2,large:1,very_large:1},stable:3},4:{ascending:{unison:4,small:5,medium:5,large:2,very_large:2},descending:{unison:4,small:3,medium:3,large:2,very_large:1},stable:4},5:{ascending:{unison:5,small:2,medium:2,large:3,very_large:3},descending:{unison:5,small:4,medium:4,large:3,very_large:2},stable:5}},ir={1:{ascending:2,descending:1,stable:1},2:{ascending:3,descending:1,stable:2},3:{ascending:4,descending:2,stable:3},4:{ascending:5,descending:3,stable:4},5:{ascending:5,descending:4,stable:5}};function Dt(v){return v.intervalCategory??"small"}function or(v,e,t){const n=e??"left";if(v.direction==="stable"||v.intervalCategory==="unison")return n;if(t==="easy"){const s=rr[n];return v.direction==="up"?s.ascending:s.descending}const r=Ct[n],o=v.direction==="up"?"ascending":"descending",i=Dt(v);return r[o][i]}function ar(v,e,t){const n=e??3;if(v.direction==="stable"||v.intervalCategory==="unison")return n;if(t==="easy"){const s=ir[n];return v.direction==="up"?s.ascending:s.descending}const r=Et[n],o=v.direction==="up"?"ascending":"descending",i=Dt(v);return r[o][i]}function sr(v,e,t,n){const r=new Map;if(e)for(const c of e){const u=Math.round(c.timestamp*1e3);r.set(u,c)}const o=[],i=[];let s=null;for(const c of v){const u=Math.round(c.timestamp*1e3);let f=null;for(let b=-2;b<=2&&(f=r.get(u+b)??null,!f);b++);let d=null,g=0;f&&f.direction!=="none"&&(d=t==="ddr"?or(f,s,n):ar(f,s,n),g=f.pitch?.probability??.5),o.push(d),i.push(g),s=d}return{pitchKeys:o,probabilities:i}}function cr(v){const e=[];let t=-1;for(let n=0;n<=v.length;n++){const r=n<v.length&&v[n]===null;if(r&&t===-1)t=n;else if(!r&&t!==-1){const o=t>0?v[t-1]:null,i=n<v.length?v[n]:null;e.push({startIndex:t,endIndex:n,length:n-t,previousKey:o,nextKey:i}),t=-1}}return e}function ye(v,e,t,n,r){if(v.keys.length===0||t+v.keys.length>e.length)return!1;const o=v.keys[0],i=v.keys[v.keys.length-1];if(n!==null&&o===n)return!1;if(r!==null){if(typeof i=="string"&&typeof r=="string"&&!le[i]?.includes(r)&&i!==r)return!1;if(typeof i=="number"&&typeof r=="number"){if(n!==null&&typeof n=="number"){if(!(n<r&&i>=n&&i<=r||n>r&&i<=n&&i>=r)&&i!==r)return!1}else if(Math.abs(i-r)>1)return!1}}return!0}function lr(v,e,t,n,r){const o=[],i=e.filter(g=>g.difficulty<=t&&g.keys.length>0);i.sort((g,b)=>b.keys.length-g.keys.length);const s=i[0]?.controllerMode??"ddr";let c=0,u=v.previousKey,f=null,d=null;for(;c<v.length;){const g=v.length-c;let b;const S=i.filter(R=>R.keys.length===g);if(b=ze(S,v,c,u,v.nextKey,f,d,n,r),!b){const R=i.filter(I=>I.keys.length<=g);b=ze(R,v,c,u,null,f,d,n,r)}if(!b){const R=i.filter(I=>I.keys.length<=g);b=ze(R,v,c,u,null,null,null,null,r)}if(b)o.push({pattern:b,startIndex:v.startIndex+c,filledLength:b.keys.length}),u=b.keys[b.keys.length-1],f=b.id,d=b.category,c+=b.keys.length;else{const R=c===v.length-1?v.nextKey:null,I=Tt(u,R);o.push({pattern:{id:"__interpolated__",name:"Interpolated",controllerMode:s,keys:[I],measures:0,tags:["interpolated"],category:"transition",difficulty:1},startIndex:v.startIndex+c,filledLength:1}),u=I,c++}}return o}function ze(v,e,t,n,r,o,i,s,c=Math.random){const u=v.filter(b=>ye(b,e,t,n,r)&&b.id!==o&&b.category!==i&&!s?.has(b.id));if(u.length>0)return ve(u,c);const f=v.filter(b=>ye(b,e,t,n,r)&&b.id!==o&&!s?.has(b.id));if(f.length>0)return ve(f,c);const d=v.filter(b=>ye(b,e,t,n,r)&&b.id!==o);if(d.length>0)return ve(d,c);const g=v.filter(b=>ye(b,e,t,n,r));if(g.length>0)return ve(g,c)}function ve(v,e=Math.random){const t=v[0].keys.length,n=v.filter(r=>r.keys.length===t);return n[Math.floor(e()*n.length)]}function ur(v,e,t){const n=v.length,r=[...v],o=new Array(n).fill(void 0);for(let i=0;i<e.length;i++){const s=t[i];for(const c of s)for(let u=0;u<c.filledLength;u++){const f=c.startIndex+u;if(f>=n)break;r[f]=c.pattern.keys[u],o[f]=c.pattern.id}}for(let i=0;i<n;i++)if(r[i]===null){const s=i>0?r[i-1]:null,c=i<n-1?r[i+1]:null;r[i]=Tt(s,c)}return{keys:r,patternIds:o}}function dr(v,e){const t=[];if(e<=0||v.length===0)return{positions:t};let n=1;const r=v[0];for(let o=1;o<v.length;o++)v[o]===r?(n++,n>e&&t.push(o)):n=1;return{positions:t}}function hr(v,e,t,n=Math.random){const r=e.filter(s=>s.difficulty<=t);if(r.length===0)return v;const o=r.filter(s=>s.keys[0]!==v),i=o.length>0?o:r;return i[Math.floor(n()*i.length)].keys[0]}const le={up:["left","right"],down:["left","right"],left:["up","down"],right:["up","down"]};function Tt(v,e){if(v===null)return e===null?typeof e=="string"?"left":3:typeof e=="string"?le[e][0]:Math.max(1,e-1);if(e===null)return v;if(typeof v=="string"&&typeof e=="string"){const t=v,n=e;if(t===n)return v;if(le[t].includes(n))return e;const o=le[t],i=le[n];for(const s of o)if(i.includes(s))return s;return o[0]}if(typeof v=="number"&&typeof e=="number"){const t=v,n=e;return t===n?v:n>t?Math.min(5,t+1):Math.max(1,t-1)}return v}class be{constructor(e){this.config=x.mergeButtonMappingConfig(e);const t=x.validateButtonMappingConfig(this.config);if(!t.valid)throw new Error(`Invalid button mapping config: ${t.errors.join(", ")}`)}seededRandom(e){return this.config.seed?x.hashSeedToFloat(x.deriveSeed(this.config.seed,e)):Math.random()}getConfig(){return{...this.config}}mapVariant(e,t,n){const r=this.mapButtons(e,n,e.difficulty),o=this.buildMetadata(r,n),i=new Map,s=new Map,c=new Map;for(const u of r)i.set(u.beatIndex,String(u.key)),s.set(u.beatIndex,u.source),c.set(u.beatIndex,u.patternId);return{variant:e,rhythmMetadata:t,buttonMetadata:o,keyAssignments:i,mappingSources:s,mappingPatternIds:c}}map(e,t,n){const r=e.difficultyVariants[t];return this.mapVariant(r,e.metadata,n)}mapAll(e,t){return{easy:this.map(e,"easy",t),medium:this.map(e,"medium",t),hard:this.map(e,"hard",t)}}mapButtons(e,t,n){const r=e.beats;if(this.config.controllerMode==="tap")return r.map((B,N)=>({beatIndex:N,timestamp:B.timestamp,key:"tap",source:"pattern",patternId:void 0,probability:void 0}));const o=[],i=this.getMaxPatternDifficulty(n);let s=0;const{pitchKeys:c,probabilities:u}=sr(r,t,this.config.controllerMode,n),f=this.classifyPitchVsPattern(c,u,this.config.pitchInfluenceWeight),d=c.map((B,N)=>B!==null&&f[N]?B:null),g=this.config.controllerMode==="ddr"?x.DDR_PATTERN_LIBRARY.patterns:x.GUITAR_HERO_PATTERN_LIBRARY.patterns,b=cr(d),S=new Set,R=b.map((B,N)=>{const k=lr(B,g,i,S,()=>this.seededRandom(`run:${N}:pick:${s++}`));for(const C of k)C.pattern.id!=="__interpolated__"&&S.add(C.pattern.id);return k}),{keys:I,patternIds:A}=ur(d,b,R);for(let B=0;B<r.length;B++){const N=d[B]!==null;o.push({beatIndex:B,timestamp:r[B].timestamp,key:I[B],source:N?"pitch":"pattern",patternId:N?void 0:A[B],probability:u[B]})}return this.config.consecutiveSameKeyLimit>0&&this.applyConsecutiveLimit(o,g,i),o}classifyPitchVsPattern(e,t,n){const r=new Array(e.length).fill(!1),o=e.map((c,u)=>({index:u,probability:t[u],hasPitch:c!==null})).filter(c=>c.hasPitch);o.sort((c,u)=>c.probability-u.probability);const i=Math.floor(o.length*(1-n)),s=new Set(o.slice(0,i).map(c=>c.index));for(let c=0;c<e.length;c++)e[c]===null||s.has(c)?r[c]=!1:r[c]=!0;return r}getMaxPatternDifficulty(e){switch(e){case"easy":return 3;case"medium":return 6;case"hard":return 10;case"natural":return 10;case"custom":return 6}}applyConsecutiveLimit(e,t,n){const r=e.map(s=>s.key),o=this.config.consecutiveSameKeyLimit,{positions:i}=dr(r,o);for(let s=0;s<i.length;s++){const c=i[s],u=hr(e[c].key,t,n,()=>this.seededRandom(`var:${c}:${s}`));u!==e[c].key&&(e[c].key=u,e[c].source="pattern",e[c].patternId="consecutive_limit_fix")}}buildMetadata(e,t){const n=new Set,r=new Map;let o=0,i=0;const s=new Set;for(const S of e){const R=String(S.key);n.add(R),r.set(R,(r.get(R)??0)+1),S.source==="pitch"?o++:i++,S.patternId&&s.add(S.patternId)}let c,u,f;if(t&&t.length>0){c={up:0,down:0,stable:0,none:0},u={unison:0,small:0,medium:0,large:0,very_large:0},f={low:0,mid:0,high:0};for(const S of t)c[S.direction]++,S.intervalCategory&&u[S.intervalCategory]++,S.band&&f[S.band]++}const d=[];let g,b=0;for(let S=0;S<e.length;S++){const R=e[S].patternId;R&&R===g||(g&&d.push({patternId:g,startIndex:b,length:S-b}),g=R,b=S)}return g&&d.push({patternId:g,startIndex:b,length:e.length-b}),{controllerMode:this.config.controllerMode,keysUsed:Array.from(n),pitchInfluencedBeats:o,patternInfluencedBeats:i,patternsUsed:Array.from(s),buttonDistribution:r,directionStats:c,intervalStats:u,bandStats:f,patternPlacements:d}}static getDDRTransitions(){return Ct}static getGuitarHeroTransitions(){return Et}getAvailableButtons(){return this.config.controllerMode==="ddr"?["up","down","left","right"]:[1,2,3,4,5]}isValidButton(e){return this.config.controllerMode==="ddr"?["up","down","left","right"].includes(e):[1,2,3,4,5].includes(e)}}class Ce{convertToChartedBeatMap(e,t,n,r,o,i){const s=[],c=[];for(let f=0;f<e.beats.length;f++){const d=e.beats[f],g=this.convertBeat(d,t,n.get(f),f,o?.get(f),i?.get(f));s.push(g),g.isDetected&&c.push(f)}const u=this.buildChartMetadata(e,r,s,n);return{audioId:t.audioId,duration:t.duration,beats:s,detectedBeatIndices:c,downbeatConfig:t.downbeatConfig,quarterNoteInterval:t.quarterNoteInterval,bpm:t.quarterNoteBpm,chartMetadata:u}}convertWithOptions(e,t){const n={version:"1.0.0",algorithm:"procedural-generation",minBpm:60,maxBpm:200,sensitivity:1,filter:.5,noiseFloorThreshold:.01,hopSizeMs:10,fftSize:2048,dpAlpha:.5,melBands:40,highPassCutoff:80,gaussianSmoothMs:20,tempoCenter:.5,tempoWidth:.5,useOctaveResolution:!1,useTripleMeter:!1,generatedAt:new Date().toISOString()},r={audioId:t.audioId,duration:t.duration,beats:[],detectedBeatIndices:[],quarterNoteInterval:t.quarterNoteInterval,quarterNoteBpm:60/t.quarterNoteInterval,downbeatConfig:t.downbeatConfig,originalMetadata:n};return this.convertToChartedBeatMap(e,r,t.keyAssignments,t.metadata)}convertBeat(e,t,n,r,o,i){const s=e.beatIndex,c=this.getParentBeat(t,s),u=this.calculateBeatInMeasure(c,e.gridPosition,e.gridType),f=this.isBeatDetected(e),d=this.mapGridToSubdivision(e.gridType),g=this.calculateConfidence(e,f);return{timestamp:e.timestamp,beatInMeasure:u,isDownbeat:(c?.isDownbeat??!1)&&e.gridPosition===0,measureNumber:c?.measureNumber??0,intensity:e.intensity,confidence:g,requiredKey:n,quarterNoteIndex:s,subdivisionPosition:e.gridPosition,isDetected:f,subdivisionType:d,sourceBand:e.sourceBand,quantizationError:e.quantizationError,mappingSource:o,patternId:i}}getParentBeat(e,t){return t<0||t>=e.beats.length?null:e.beats[t]}calculateBeatInMeasure(e,t,n){const r=e?.beatInMeasure??0;return x.calculateBeatInMeasure(r,t,n)}isBeatDetected(e){return e.quantizationError===void 0?!0:e.quantizationError<10}mapGridToSubdivision(e){return x.mapGridToSubdivision(e)}calculateConfidence(e,t){return t?Math.min(1,.8+e.intensity*.2):.8}buildChartMetadata(e,t,n,r){const o=t.pitchInfluencedBeats??0,i=this.getUniqueKeys(n);return this.getSubdivisionTypesUsed(n),{difficulty:e.difficulty,keysUsed:i,pitchInfluencedBeats:o,patternsUsed:t.patternsUsed??[],rhythmMetadata:t.rhythmMetadata??this.createDefaultRhythmMetadata(e),pitchMetadata:t.pitchMetadata??null,generatedAt:t.generatedAt??new Date().toISOString(),seed:t.seed}}getUniqueKeys(e){const t=new Set;for(const n of e)n.requiredKey!==void 0&&t.add(n.requiredKey);return Array.from(t).sort()}getSubdivisionTypesUsed(e){const t=new Set;for(const n of e)t.add(n.subdivisionType);return Array.from(t)}createDefaultRhythmMetadata(e){return{difficulty:e.difficulty,bandsAnalyzed:["low","mid","high"],transientsDetected:e.beats.length,averageDensity:e.beats.length/180,naturalDifficulty:e.difficulty}}static fromMappedResult(e,t,n,r,o,i,s){const c=o??new Map;if(c.size===0&&n.keysUsed.length>0)for(let b=0;b<e.beats.length;b++)c.set(b,n.keysUsed[b%n.keysUsed.length]);const u=new Ce,f={difficulty:r.difficulty,bandsAnalyzed:r.bandsAnalyzed,transientsDetected:r.transientsDetected,averageDensity:r.averageDensity,naturalDifficulty:r.naturalDifficulty},d=n.directionStats?{melodyRange:null,directionStats:n.directionStats,intervalStats:n.intervalStats??null}:null,g={difficulty:e.difficulty,keysUsed:n.keysUsed,pitchInfluencedBeats:n.pitchInfluencedBeats,patternsUsed:n.patternsUsed,rhythmMetadata:f,pitchMetadata:d,generatedAt:new Date().toISOString()};return u.convertToChartedBeatMap(e,t,c,g,i,s)}}const ce={difficulty:"medium",controllerMode:"ddr",rhythm:{},buttons:{},enableCache:!0,cacheMaxAge:1800*1e3};class Ee{constructor(e={}){this.cache=new Map,this.cacheHits=0,this.cacheMisses=0,this.options={...ce,...e,rhythm:{...ce.rhythm,...e.rhythm},buttons:{...ce.buttons,...e.buttons}},this.buttonConfig=x.mergeButtonMappingConfig({...this.options.buttons,difficulty:this.options.difficulty,controllerMode:this.options.controllerMode,seed:this.options.seed})}getOptions(){return{...this.options}}generateCacheKey(e,t,n){return`${e}:${t}:${n}`}createConfigFingerprint(e){const t=this.options.rhythm||{};return e==="rhythm"?JSON.stringify({measureStartOffset:t.measureStartOffset,minimumTransientIntensity:t.minimumTransientIntensity,seed:t.seed}):e==="pitch"?JSON.stringify({pitchAlgorithm:this.options.pitchAlgorithm,crepeModelUrl:this.options.crepeModelUrl,voicingThreshold:this.options.voicingThreshold}):"default"}getFromCache(e){if(!this.options.enableCache)return null;const t=this.cache.get(e);if(!t)return this.cacheMisses++,null;const n=Date.now()-t.timestamp,r=this.options.cacheMaxAge??ce.cacheMaxAge;return n>r?(this.cache.delete(e),this.cacheMisses++,null):(this.cacheHits++,t.result)}setCache(e,t){this.options.enableCache&&this.cache.set(e,{result:t,timestamp:Date.now(),key:e})}clearCache(){this.cache.clear(),this.cacheHits=0,this.cacheMisses=0}pruneExpiredCache(){const e=Date.now(),t=this.options.cacheMaxAge??ce.cacheMaxAge;for(const[n,r]of this.cache.entries())e-r.timestamp>t&&this.cache.delete(n)}getCacheStats(){const e=[];for(const[t]of this.cache.entries()){const n=t.split(":")[1];e.includes(n)||e.push(n)}return{entryCount:this.cache.size,cachedPhases:e,hits:this.cacheHits,misses:this.cacheMisses}}isCached(e,t){const n=this.createConfigFingerprint(t),r=this.generateCacheKey(e,t,n);return this.cache.has(r)}getCacheHitRatio(){const e=this.cacheHits+this.cacheMisses;return e===0?0:this.cacheHits/e}async generate(e,t,n,r){const o=(g,b,S)=>{n?.({stage:g,progress:b,message:S})};r?.throwIfAborted();const i=t.audioId;o("rhythm",0,"Starting rhythm generation...");let s=null;if(this.options.cachedRhythm)s=this.options.cachedRhythm,o("rhythm",1,"Using pre-generated rhythm from store");else{const g=this.generateCacheKey(i,"rhythm",this.createConfigFingerprint("rhythm"));s=this.getFromCache(g),s?o("rhythm",1,"Rhythm loaded from cache"):(s=await this.generateRhythm(e,t,(b,S,R)=>{o("rhythm",S,`[${b}] ${R}`)},r),this.setCache(g,s),o("rhythm",1,"Rhythm generation complete"))}r?.throwIfAborted();let c=null;if(this.buttonConfig.pitchInfluenceWeight>0&&this.buttonConfig.controllerMode!=="tap"){const g=this.generateCacheKey(i,"pitch",this.createConfigFingerprint("pitch"));c=this.getFromCache(g),c?o("pitch",1,"Pitch analysis loaded from cache"):(o("pitch",0,"Starting pitch analysis..."),c=await this.analyzePitch(e,s,(b,S)=>{o("pitch",b,S)}),this.setCache(g,c),o("pitch",1,"Pitch analysis complete"))}else o("pitch",1,"Pitch analysis skipped");r?.throwIfAborted(),o("buttons",0,"Starting button mapping...");const u=this.mapButtons(s,c);o("buttons",1,"Button mapping complete"),r?.throwIfAborted(),o("conversion",0,"Converting to playable chart...");const f=this.convertToChart(u,t);o("conversion",1,"Chart conversion complete"),r?.throwIfAborted(),o("finalizing",0,"Finalizing level...");const d=this.buildLevel(f,u,s,c);return o("finalizing",1,"Level generation complete"),d}async generateAllDifficulties(e,t,n,r){const o=["easy","medium","hard","natural"],i={easy:null,medium:null,hard:null,natural:null};r?.throwIfAborted();const s=t.audioId;let c=null;if(this.options.cachedRhythm)c=this.options.cachedRhythm;else{const f=this.generateCacheKey(s,"rhythm",this.createConfigFingerprint("rhythm"));c=this.getFromCache(f),c||(c=await this.generateRhythm(e,t,void 0,r),this.setCache(f,c))}r?.throwIfAborted();let u=null;if(this.buttonConfig.pitchInfluenceWeight>0&&this.buttonConfig.controllerMode!=="tap"){const f=this.generateCacheKey(s,"pitch",this.createConfigFingerprint("pitch"));u=this.getFromCache(f),u||(u=await this.analyzePitch(e,c),this.setCache(f,u))}r?.throwIfAborted();for(let f=0;f<o.length;f++){const d=o[f];n?.({stage:"buttons",progress:f/o.length,message:`Generating ${d} chart...`}),r?.throwIfAborted();const g=new Ee({...this.options,difficulty:d,buttons:{...this.options.buttons,difficulty:d}}),b=g.mapButtons(c,u),S=g.convertToChart(b,t),R=g.buildLevel(S,b,c,u);i[d]=R}return{easy:i.easy,medium:i.medium,hard:i.hard,natural:i.natural}}async generateAtDensity(e,t,n,r,o){const i=(A,B,N)=>{r?.({stage:A,progress:B,message:N})};o?.throwIfAborted();const s=t.audioId;i("rhythm",0,"Starting rhythm generation...");let c=null;if(this.options.cachedRhythm)c=this.options.cachedRhythm,i("rhythm",1,"Using pre-generated rhythm from store");else{const A=this.generateCacheKey(s,"rhythm",this.createConfigFingerprint("rhythm"));c=this.getFromCache(A),c?i("rhythm",1,"Rhythm loaded from cache"):(c=await this.generateRhythm(e,t,(B,N,k)=>{i("rhythm",N,`[${B}] ${k}`)},o,!0),this.setCache(A,c),i("rhythm",1,"Rhythm generation complete"))}o?.throwIfAborted(),i("buttons",0,"Generating density-based variant...");const u=this.collectGridDecisions(c.analysis.quantizationResult),d=new x.DifficultyVariantGenerator({seed:this.options.seed}).generateAtDensity(c.composite,n,t,c.analysis.phraseAnalysis,u);i("buttons",.3,"Density variant generated");let g=null;if(this.buttonConfig.pitchInfluenceWeight>0&&this.buttonConfig.controllerMode!=="tap"){const A=this.generateCacheKey(s,"pitch",this.createConfigFingerprint("pitch"));g=this.getFromCache(A),g?i("pitch",.5,"Pitch analysis loaded from cache"):(i("pitch",0,"Starting pitch analysis..."),g=await this.analyzePitch(e,c,(B,N)=>{i("pitch",B,N)}),this.setCache(A,g),i("pitch",1,"Pitch analysis complete"))}else i("pitch",1,"Pitch analysis skipped");o?.throwIfAborted(),i("buttons",.6,"Mapping buttons...");const S=new be(this.buttonConfig).mapVariant(d,c.metadata,g?.pitchByBeat);i("buttons",1,"Button mapping complete"),o?.throwIfAborted(),i("conversion",0,"Converting to playable chart...");const R=this.convertToChart(S,t);i("conversion",1,"Chart conversion complete"),o?.throwIfAborted(),i("finalizing",0,"Finalizing level...");const I=this.buildLevel(R,S,c,g,"custom");return i("finalizing",1,"Level generation complete"),I}async generateAtDensities(e,t,n,r,o){const i=new Map;o?.throwIfAborted();const s=t.audioId;r?.({stage:"rhythm",progress:0,message:"Starting rhythm generation..."});let c=null;if(this.options.cachedRhythm)c=this.options.cachedRhythm,r?.({stage:"rhythm",progress:1,message:"Using pre-generated rhythm from store"});else{const g=this.generateCacheKey(s,"rhythm",this.createConfigFingerprint("rhythm"));c=this.getFromCache(g),c?r?.({stage:"rhythm",progress:1,message:"Rhythm loaded from cache"}):(c=await this.generateRhythm(e,t,void 0,o,!0),this.setCache(g,c),r?.({stage:"rhythm",progress:1,message:"Rhythm generation complete"}))}o?.throwIfAborted();let u=null;if(this.buttonConfig.pitchInfluenceWeight>0&&this.buttonConfig.controllerMode!=="tap"){const g=this.generateCacheKey(s,"pitch",this.createConfigFingerprint("pitch"));u=this.getFromCache(g),u?r?.({stage:"pitch",progress:1,message:"Pitch analysis loaded from cache"}):(r?.({stage:"pitch",progress:0,message:"Starting pitch analysis..."}),u=await this.analyzePitch(e,c),this.setCache(g,u),r?.({stage:"pitch",progress:1,message:"Pitch analysis complete"}))}o?.throwIfAborted();const f=this.collectGridDecisions(c.analysis.quantizationResult),d=new x.DifficultyVariantGenerator({seed:this.options.seed});for(let g=0;g<n.length;g++){const{label:b,config:S}=n[g];r?.({stage:"buttons",progress:g/n.length,message:`Generating ${b} density variant...`}),o?.throwIfAborted();const R=d.generateAtDensity(c.composite,S,t,c.analysis.phraseAnalysis,f),A=new be(this.buttonConfig).mapVariant(R,c.metadata,u?.pitchByBeat),B=this.convertToChart(A,t),N=this.buildLevel(B,A,c,u,"custom");i.set(b,N)}return r?.({stage:"finalizing",progress:1,message:"All density variants generated"}),i}collectGridDecisions(e){const t=new Map,n=[...e.streams.low.gridDecisions,...e.streams.mid.gridDecisions,...e.streams.high.gridDecisions];for(const r of n){const o=t.get(r.beatIndex);(!o||r.confidence>o.confidence)&&t.set(r.beatIndex,r)}return t}async generateRhythm(e,t,n,r,o){return await new x.RhythmGenerator({...this.options.rhythm,skipDifficultyVariants:o}).generate(e,t,r,n?(c,u,f)=>{n(c,u,f)}:void 0)}async analyzePitch(e,t,n){n?.(.1,"Linking pitch to beats...");const r={};this.options.pitchAlgorithm!==void 0&&(r.pitchAlgorithm=this.options.pitchAlgorithm),this.options.crepeModelUrl!==void 0&&(r.crepeModelUrl=this.options.crepeModelUrl),this.options.resolveUrl!==void 0&&(r.resolveUrl=this.options.resolveUrl),this.options.voicingThreshold!==void 0&&(r.pitchDetector={...r.pitchDetector,voicingThreshold:this.options.voicingThreshold});const o=new Mt(r),i=await o.linkWithComposite(t.composite,e);n?.(.4,"Analyzing melody contour...");const c=new Zn().analyze(i);n?.(.8,"Deriving variant pitches...");let u;if(!t.difficultyVariants)u=c.pitchByBeat;else{const f=this.options.difficulty==="custom"?"medium":this.options.difficulty;u=o.deriveVariantPitches(t.difficultyVariants[f],c.pitchByBeat)}return{...c,pitchByBeat:u}}mapButtons(e,t){const n=new be(this.buttonConfig),r=this.options.difficulty==="custom"?"medium":this.options.difficulty;return n.map(e,r,t?.pitchByBeat)}convertToChart(e,t){return Ce.fromMappedResult(e.variant,t,e.buttonMetadata,e.rhythmMetadata,e.keyAssignments,e.mappingSources,e.mappingPatternIds)}buildLevel(e,t,n,r,o){const i={difficulty:o??this.options.difficulty,controllerMode:this.options.controllerMode,rhythmMetadata:t.rhythmMetadata,buttonMetadata:t.buttonMetadata,pitchMetadata:r?{melodyRange:r.melodyContour.range.minNote!=="N/A"?{min:r.melodyContour.range.minNote,max:r.melodyContour.range.maxNote}:null,directionStats:r.directionStats,intervalStats:r.intervalStats}:null,chartMetadata:{totalBeats:e.beats.length,detectedBeats:e.detectedBeatIndices.length,generatedBeats:e.beats.length-e.detectedBeatIndices.length},generationConfig:this.options};return{chart:e,variant:t.variant,rhythm:n,pitchAnalysis:r,metadata:i}}}class fr{static toExportData(e,t={}){const{chart:n,metadata:r,pitchAnalysis:o}=e,i=this.buildDetectedBeats(n),s=this.buildMergedBeats(n),c=this.buildInterpolatedMetadata(n),u=this.buildSubdivisionData(n),f=this.buildChartExportData(n,r),d=this.buildGenerationMetadata(r,o);return{version:1,format:"full-beatmap",audioId:n.audioId,audioTitle:t.includeAudioTitle?t.audioTitle:void 0,exportedAt:Date.now(),duration:n.duration,quarterNoteBpm:n.bpm,quarterNoteConfidence:n.chartMetadata.rhythmMetadata.averageDensity,detectedBeats:i,mergedBeats:s,interpolatedMetadata:c,subdivision:u,chart:f,trackReference:t.trackReference,generationSource:"procedural",generationMetadata:d}}static buildDetectedBeats(e){const t=[],n=new Set(e.detectedBeatIndices);for(let r=0;r<e.beats.length;r++){const o=e.beats[r];n.has(r)&&t.push({timestamp:o.timestamp,beatInMeasure:o.beatInMeasure,isDownbeat:o.isDownbeat,measureNumber:o.measureNumber,intensity:o.intensity,confidence:o.confidence,requiredKey:o.requiredKey})}return t}static buildMergedBeats(e){const t=new Set(e.detectedBeatIndices);return e.beats.map((n,r)=>({timestamp:n.timestamp,beatInMeasure:n.beatInMeasure,isDownbeat:n.isDownbeat,measureNumber:n.measureNumber,intensity:n.intensity,confidence:n.confidence,requiredKey:n.requiredKey,source:t.has(r)?"detected":"interpolated",distanceToAnchor:n.quantizationError}))}static buildInterpolatedMetadata(e){const t=e.detectedBeatIndices.length,n=e.beats.length;return{quarterNoteInterval:e.quarterNoteInterval,quarterNoteBpm:e.bpm,quarterNoteConfidence:.9,detectedBeatCount:t,mergedBeatCount:n}}static buildSubdivisionData(e){const t=e.beats.map((s,c)=>this.chartedBeatToExportBeat(s,c,e.detectedBeatIndices)),n=new Set,r=[];t.forEach((s,c)=>{n.add(s.subdivisionType),r.push([c,s.subdivisionType])});const o={beatSubdivisions:r,defaultSubdivision:"sixteenth"},i={originalBeatCount:e.beats.length-e.detectedBeatIndices.length,subdividedBeatCount:e.beats.length,averageDensityMultiplier:1,explicitBeatCount:e.detectedBeatIndices.length};return{config:o,beats:t,metadata:i}}static chartedBeatToExportBeat(e,t,n){const r=n.includes(t);return{timestamp:e.timestamp,beatInMeasure:e.beatInMeasure,isDownbeat:e.isDownbeat,measureNumber:e.measureNumber,intensity:e.intensity,confidence:e.confidence,requiredKey:e.requiredKey,isDetected:r,originalBeatIndex:r?t:void 0,subdivisionType:e.subdivisionType,quarterNoteIndex:e.quarterNoteIndex,subdivisionPosition:e.subdivisionPosition,sourceBand:e.sourceBand,quantizationError:e.quantizationError}}static buildChartExportData(e,t){const n=e.beats.map(o=>o.requiredKey).filter(o=>o!==void 0),r=[...new Set(n)];return r.length===0?null:{style:t.controllerMode==="ddr"?"ddr":t.controllerMode==="guitar_hero"?"guitar":"tap",keyCount:r.length,usedKeys:r}}static buildGenerationMetadata(e,t){const n=e.rhythmMetadata;return{difficulty:e.difficulty,pitchInfluenceWeight:e.generationConfig.buttons?.pitchInfluenceWeight??1,patternsUsed:e.buttonMetadata.patternsUsed,controllerMode:e.controllerMode,seed:e.generationConfig.seed,generatedAt:new Date().toISOString(),directionStats:t?.directionStats??void 0,intervalStats:t?.intervalStats??void 0,rhythmMetadata:{difficulty:n.difficulty,bandsAnalyzed:n.bandsAnalyzed,transientsDetected:n.transientsDetected,averageDensity:n.averageDensity}}}static fromExportData(e){const t=this.validate(e);if(!t.success||!t.data)throw new Error(`Invalid export data: ${t.error??"Unknown error"}`);const n=t.data,r=this.reconstructChart(n),o=this.reconstructVariant(n,r),i=this.reconstructRhythm(n,r),s=this.reconstructPitchAnalysis(n),c=this.reconstructMetadata(n,r);return{chart:r,variant:o,rhythm:i,pitchAnalysis:s,metadata:c}}static reconstructChart(e){if(!e.subdivision)return this.reconstructChartFromMergedBeats(e);const t=e.subdivision.beats.map((i,s)=>({timestamp:i.timestamp,beatInMeasure:i.beatInMeasure,isDownbeat:i.isDownbeat,measureNumber:i.measureNumber,intensity:i.intensity,confidence:i.confidence,requiredKey:i.requiredKey,quarterNoteIndex:i.quarterNoteIndex??0,subdivisionPosition:i.subdivisionPosition??0,isDetected:i.isDetected,subdivisionType:i.subdivisionType,sourceBand:i.sourceBand??"mid",quantizationError:i.quantizationError})),n=e.subdivision.beats.map((i,s)=>i.isDetected?s:-1).filter(i=>i>=0),r=this.reconstructDownbeatConfig(t),o=this.reconstructChartMetadata(e);return{audioId:e.audioId,duration:e.duration,beats:t,detectedBeatIndices:n,downbeatConfig:r,quarterNoteInterval:e.interpolatedMetadata.quarterNoteInterval,bpm:e.quarterNoteBpm,chartMetadata:o}}static reconstructChartFromMergedBeats(e){const t=e.mergedBeats.map((i,s)=>({timestamp:i.timestamp,beatInMeasure:i.beatInMeasure,isDownbeat:i.isDownbeat,measureNumber:i.measureNumber,intensity:i.intensity,confidence:i.confidence,requiredKey:i.requiredKey,quarterNoteIndex:s,subdivisionPosition:0,isDetected:i.source==="detected",subdivisionType:"quarter",sourceBand:"mid",quantizationError:i.distanceToAnchor})),n=e.mergedBeats.map((i,s)=>i.source==="detected"?s:-1).filter(i=>i>=0),r=this.reconstructDownbeatConfig(t),o=this.reconstructChartMetadata(e);return{audioId:e.audioId,duration:e.duration,beats:t,detectedBeatIndices:n,downbeatConfig:r,quarterNoteInterval:e.interpolatedMetadata.quarterNoteInterval,bpm:e.quarterNoteBpm,chartMetadata:o}}static reconstructDownbeatConfig(e){const t=e.filter(o=>o.isDownbeat);if(t.length===0)return{segments:[{startBeat:0,downbeatBeatIndex:0,timeSignature:{beatsPerMeasure:4}}]};const n={beatsPerMeasure:4};return{segments:[{startBeat:0,downbeatBeatIndex:t[0]?.measureNumber??0,timeSignature:n}]}}static reconstructChartMetadata(e){const t=e.generationMetadata;return{difficulty:this.parseDifficultyLevel(t?.difficulty),keysUsed:e.chart?.usedKeys??[],pitchInfluencedBeats:t?.pitchInfluenceWeight&&t.pitchInfluenceWeight>0?e.subdivision?.beats.filter(n=>n.requiredKey).length??0:0,patternsUsed:t?.patternsUsed??[],rhythmMetadata:{difficulty:t?.rhythmMetadata?.difficulty??"medium",bandsAnalyzed:t?.rhythmMetadata?.bandsAnalyzed??["low","mid","high"],transientsDetected:t?.rhythmMetadata?.transientsDetected??e.detectedBeats.length,averageDensity:t?.rhythmMetadata?.averageDensity??.5,naturalDifficulty:this.parseDifficultyLevel(t?.difficulty)},pitchMetadata:t?.directionStats||t?.intervalStats?{melodyRange:null,directionStats:t.directionStats??null,intervalStats:t.intervalStats??null}:null,generatedAt:t?.generatedAt??new Date().toISOString(),seed:t?.seed}}static parseDifficultyLevel(e){return e==="easy"||e==="medium"||e==="hard"||e==="natural"||e==="custom"?e:"medium"}static parseDifficultyPreset(e){return e==="easy"||e==="medium"||e==="hard"||e==="natural"||e==="custom"?e:"medium"}static reconstructVariant(e,t){const n=e.generationMetadata,r=this.parseDifficultyLevel(n?.difficulty),o=t.beats.map(i=>({timestamp:i.timestamp,beatIndex:i.quarterNoteIndex,gridPosition:i.subdivisionPosition,gridType:this.subdivisionTypeToGridType(i.subdivisionType),intensity:i.intensity,band:i.sourceBand,quantizationError:i.quantizationError,sourceBand:i.sourceBand}));return{difficulty:r,beats:o,isUnedited:!0,editType:"none",editAmount:0,patternsInserted:n?.patternsUsed}}static subdivisionTypeToGridType(e){switch(e){case"sixteenth":case"eighth":case"quarter":return"straight_16th";case"triplet8":case"triplet4":return"triplet_8th";default:return"straight_16th"}}static reconstructRhythm(e,t){const n=e.generationMetadata,r=this.parseDifficultyLevel(n?.difficulty),o=d=>({audioId:e.audioId,duration:e.duration,beats:t.beats.filter(g=>g.sourceBand===d).map(g=>({timestamp:g.timestamp,beatIndex:g.quarterNoteIndex,gridPosition:g.subdivisionPosition,gridType:this.subdivisionTypeToGridType(g.subdivisionType),intensity:g.intensity,band:d,quantizationError:g.quantizationError})),gridDecisions:[],quarterNoteInterval:e.interpolatedMetadata.quarterNoteInterval}),i={low:o("low"),mid:o("mid"),high:o("high")},s=this.reconstructVariant(e,t),c=t.beats.map(d=>({timestamp:d.timestamp,beatIndex:d.quarterNoteIndex,gridPosition:d.subdivisionPosition,gridType:this.subdivisionTypeToGridType(d.subdivisionType),intensity:d.intensity,band:d.sourceBand,quantizationError:d.quantizationError,sourceBand:d.sourceBand})),u={low:0,mid:0,high:0};for(const d of c)u[d.sourceBand]++;const f={beats:c,sections:[],naturalDifficulty:r,quarterNoteInterval:e.interpolatedMetadata.quarterNoteInterval,metadata:{totalBeats:c.length,sectionCount:0,beatsPerBand:u,sectionsPerBand:{low:0,mid:0,high:0}}};return{difficultyVariants:{easy:{...s,difficulty:"easy"},medium:{...s,difficulty:"medium"},hard:{...s,difficulty:"hard"},natural:{...s,difficulty:"natural"}},bandStreams:i,composite:f,analysis:{transientAnalysis:{transients:e.detectedBeats.map(d=>({timestamp:d.timestamp,intensity:d.intensity,band:"mid",detectionMethod:"energy"})),bandTransients:new Map([["low",[]],["mid",e.detectedBeats.map(d=>({timestamp:d.timestamp,intensity:d.intensity,band:"mid",detectionMethod:"energy"}))],["high",[]]]),metadata:{totalTransients:e.detectedBeats.length,transientsPerBand:new Map([["low",0],["mid",e.detectedBeats.length],["high",0]]),duration:e.duration,averageIntensity:.5,detectionMethodsUsed:["energy"]}},quantizationResult:{streams:i,metadata:{densityValidation:{isValid:!0,bands:{low:{band:"low",isValid:!0,minIntervalDetected:1/0,requiredMinInterval:.1,retryCount:0,sensitivityReduction:0,finalIntensityThreshold:0,transientsRemaining:0},mid:{band:"mid",isValid:!0,minIntervalDetected:.1,requiredMinInterval:.1,retryCount:0,sensitivityReduction:0,finalIntensityThreshold:0,transientsRemaining:e.detectedBeats.length},high:{band:"high",isValid:!0,minIntervalDetected:1/0,requiredMinInterval:.1,retryCount:0,sensitivityReduction:0,finalIntensityThreshold:0,transientsRemaining:0}},maxRetryCount:0,maxSensitivityReduction:0},transientsFilteredByIntensity:0,transientsFilteredByBand:{low:0,mid:0,high:0}}},phraseAnalysis:{phrases:[],phrasesByBand:new Map([["low",[]],["mid",[]],["high",[]]]),mostSignificantPhrases:[],phrasesBySize:new Map,patternLibrary:[],bandAnalysis:{low:{band:"low",phrases:[],phrasesBySize:new Map,phrasesWithVariation:[]},mid:{band:"mid",phrases:[],phrasesBySize:new Map,phrasesWithVariation:[]},high:{band:"high",phrases:[],phrasesBySize:new Map,phrasesWithVariation:[]}}},densityAnalysis:{sections:[],perBeatDensity:[],bandMetrics:{low:{band:"low",totalBeats:0,totalTransients:0,notesPerSecond:1,minNotesPerSecond:0,maxNotesPerSecond:2,variance:0,densityCategory:"moderate",naturalDifficulty:"medium",perBeatDensity:[]},mid:{band:"mid",totalBeats:e.mergedBeats.length,totalTransients:e.detectedBeats.length,notesPerSecond:1,minNotesPerSecond:0,maxNotesPerSecond:2,variance:0,densityCategory:"moderate",naturalDifficulty:r,perBeatDensity:[]},high:{band:"high",totalBeats:0,totalTransients:0,notesPerSecond:1,minNotesPerSecond:0,maxNotesPerSecond:2,variance:0,densityCategory:"moderate",naturalDifficulty:"medium",perBeatDensity:[]}},combinedMetrics:{totalTransients:e.detectedBeats.length,notesPerSecond:1,densityCategory:"moderate",naturalDifficulty:r}},scoringResult:{sectionScores:[],bandTotals:{low:0,mid:0,high:0},bandAverages:{low:0,mid:0,high:0},sectionWinners:[],config:{beatsPerSection:8,ioiVarianceWeight:.25,syncopationWeight:.25,phraseSignificanceWeight:.25,densityWeight:.25,offbeatGridPositions:{straight_16th:[1,3],triplet_8th:[1,2],straight_8th:[1]}}}},metadata:this.buildFullRhythmMetadata(e,r)}}static buildFullRhythmMetadata(e,t){const n=e.generationMetadata;return{difficulty:this.parseDifficultyPreset(n?.difficulty),bandsAnalyzed:["low","mid","high"],transientsDetected:e.detectedBeats.length,transientsFilteredByIntensity:0,densityValidationRetries:0,phrasesDetected:0,averageDensity:n?.rhythmMetadata?.averageDensity??.5,naturalDifficulty:t,generationConfig:{difficulty:this.parseDifficultyPreset(n?.difficulty),outputMode:"composite",measureStartOffset:0,minimumTransientIntensity:.1,transientConfig:void 0,rhythmicBalanceConfig:{strongBeatEmphasis:"natural",downbeatProximityRange:2,fillEmptyMeasures:!0,addedBeatIntensity:.45,marginSeconds:.5},seed:n?.seed,verbose:!1,enableCache:!0,cacheMaxAge:1800*1e3,skipDifficultyVariants:!1},duration:e.duration,totalBeats:e.mergedBeats.length}}static buildMinimalMelodyContour(){return{segments:[],direction:"stable",range:{minNote:"N/A",maxNote:"N/A",semitones:0},shortTermDirection:"stable",mediumTermDirection:"stable",longTermDirection:"stable"}}static reconstructPitchAnalysis(e){const t=e.generationMetadata;return!t||!t.directionStats&&!t.intervalStats?null:{pitchByBeat:[],melodyContour:this.buildMinimalMelodyContour(),directionStats:t.directionStats??{up:0,down:0,stable:0,none:0},intervalStats:t.intervalStats??{unison:0,small:0,medium:0,large:0,very_large:0},metadata:{totalBeats:0,voicedBeats:0,directionCalculatedBeats:0}}}static reconstructMetadata(e,t){const n=e.generationMetadata,r=this.parseDifficultyPreset(n?.difficulty),o=n?.controllerMode??"ddr";return{difficulty:r,controllerMode:o,rhythmMetadata:this.buildFullRhythmMetadata(e,this.parseDifficultyLevel(n?.difficulty)),buttonMetadata:{controllerMode:o,keysUsed:e.chart?.usedKeys??[],pitchInfluencedBeats:n?.pitchInfluenceWeight&&n.pitchInfluenceWeight>0?t.beats.filter(i=>i.requiredKey).length:0,patternInfluencedBeats:t.beats.filter(i=>i.requiredKey).length-(n?.pitchInfluenceWeight&&n.pitchInfluenceWeight>0?t.beats.filter(i=>i.requiredKey).length:0),patternsUsed:n?.patternsUsed??[],buttonDistribution:new Map},pitchMetadata:n?.directionStats||n?.intervalStats?{melodyRange:null,directionStats:n.directionStats??null,intervalStats:n.intervalStats??null}:null,chartMetadata:{totalBeats:t.beats.length,detectedBeats:t.detectedBeatIndices.length,generatedBeats:t.beats.length-t.detectedBeatIndices.length},generationConfig:{difficulty:r,controllerMode:o,rhythm:{},buttons:{pitchInfluenceWeight:n?.pitchInfluenceWeight??1},seed:n?.seed}}}static toJSON(e,t={}){const n=this.toExportData(e,t);return JSON.stringify(n,null,2)}static fromJSON(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`Invalid JSON: ${r instanceof Error?r.message:"Unknown error"}`)}const n=this.validate(t);if(!n.success||!n.data)throw new Error(`Invalid level data: ${n.error??"Unknown error"}`);return this.fromExportData(n.data)}static async saveToFile(e,t,n={}){const r=await Promise.resolve().then(()=>require("./__vite-browser-external-BcPniuRQ.cjs")),o=this.toJSON(e,n);await r.writeFile(t,o,"utf-8")}static async loadFromFile(e){const n=await(await Promise.resolve().then(()=>require("./__vite-browser-external-BcPniuRQ.cjs"))).readFile(e,"utf-8");return this.fromJSON(n)}static validate(e){const t=[];if(typeof e!="object"||e===null)return{success:!1,error:"Data must be a non-null object"};const n=e;if(n.version!==1)return{success:!1,error:`Unsupported version: ${n.version}. Expected 1.`};if(n.format!=="full-beatmap")return{success:!1,error:`Invalid format: ${n.format}. Expected 'full-beatmap'.`};const r=["audioId","duration","quarterNoteBpm","detectedBeats","mergedBeats"];for(const o of r)if(!(o in n))return{success:!1,error:`Missing required field: ${o}`};if(!Array.isArray(n.detectedBeats))return{success:!1,error:"detectedBeats must be an array"};if(!Array.isArray(n.mergedBeats))return{success:!1,error:"mergedBeats must be an array"};if(!n.subdivision||typeof n.subdivision!="object")t.push("No subdivision data - level may not be playable");else{const o=n.subdivision;if(!Array.isArray(o.beats))return{success:!1,error:"subdivision.beats must be an array"}}if(n.chart===null)t.push("No chart data - level has no key assignments");else if(n.chart!==void 0&&typeof n.chart!="object")return{success:!1,error:"chart must be an object or null"};return typeof n.interpolatedMetadata!="object"||n.interpolatedMetadata===null?{success:!1,error:"interpolatedMetadata must be an object"}:x.isFullBeatMapExportData(e)?{success:!0,data:e,warnings:t.length>0?t:void 0}:{success:!1,error:"Data does not match FullBeatMapExportData format",warnings:t.length>0?t:void 0}}static toPack(e,t={}){const n={};for(const[r,o]of Object.entries(e))if(o){const i={includeAudioTitle:t.includeAudioTitle,audioTitle:t.audioTitle};n[r]=this.toExportData(o,i)}return{version:1,format:"level-pack",exportedAt:Date.now(),trackReference:t.trackReference,difficulties:n}}static fromPack(e){const t={};for(const[n,r]of Object.entries(e.difficulties))if(r)try{t[n]=this.fromExportData(r)}catch{}return t}static packToJSON(e,t={}){const n=this.toPack(e,t);return JSON.stringify(n,null,2)}static packFromJSON(e){let t;try{t=JSON.parse(e)}catch(n){throw new Error(`Invalid JSON: ${n instanceof Error?n.message:"Unknown error"}`)}if(!x.isLevelPackExport(t))throw new Error("Data does not match LevelPackExport format");return this.fromPack(t)}static isProcedural(e){return e.generationSource==="procedural"}static getSummary(e){const t=[`Audio: ${e.audioId}`,`Duration: ${e.duration.toFixed(1)}s`,`BPM: ${e.quarterNoteBpm.toFixed(1)}`,`Beats: ${e.mergedBeats.length} (${e.detectedBeats.length} detected)`];return e.chart&&(t.push(`Keys: ${e.chart.keyCount} (${e.chart.style})`),t.push(`Keys used: ${e.chart.usedKeys.join(", ")}`)),e.generationMetadata&&(t.push(`Difficulty: ${e.generationMetadata.difficulty}`),t.push(`Controller: ${e.generationMetadata.controllerMode}`),t.push(`Pitch influence: ${(e.generationMetadata.pitchInfluenceWeight*100).toFixed(0)}%`)),t.join(`
1
+ "use strict";var Bn=Object.create;var dt=Object.defineProperty;var An=Object.getOwnPropertyDescriptor;var _n=Object.getOwnPropertyNames;var Nn=Object.getPrototypeOf,kn=Object.prototype.hasOwnProperty;var Pn=(v,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of _n(e))!kn.call(v,r)&&r!==t&&dt(v,r,{get:()=>e[r],enumerable:!(n=An(e,r))||n.enumerable});return v};var Fn=(v,e,t)=>(t=v!=null?Bn(Nn(v)):{},Pn(e||!v||!v.__esModule?dt(t,"default",{value:v,enumerable:!0}):t,v));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const x=require("./unifyBeatMap-DIsNlck4.cjs"),xn=require("@tensorflow/tfjs"),K=require("./arweaveGatewayManager-C9SIMDTd.cjs");function zn(v){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(v){for(const t in v)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(v,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>v[t]})}}return e.default=v,Object.freeze(e)}const G=zn(xn);function pe(v){throw new Error('Could not dynamically require "'+v+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Fe={exports:{}};var ht;function Ln(){return ht||(ht=1,(function(v,e){(function(t){v.exports=t()})(function(){return(function t(n,r,o){function i(u,f){if(!r[u]){if(!n[u]){var d=typeof pe=="function"&&pe;if(!f&&d)return d(u,!0);if(s)return s(u,!0);var g=new Error("Cannot find module '"+u+"'");throw g.code="MODULE_NOT_FOUND",g}var b=r[u]={exports:{}};n[u][0].call(b.exports,function(S){var R=n[u][1][S];return i(R||S)},b,b.exports,t,n,r,o)}return r[u].exports}for(var s=typeof pe=="function"&&pe,c=0;c<o.length;c++)i(o[c]);return i})({1:[function(t,n,r){(function(o){var i=o.MutationObserver||o.WebKitMutationObserver,s;if(i){var c=0,u=new i(S),f=o.document.createTextNode("");u.observe(f,{characterData:!0}),s=function(){f.data=c=++c%2}}else if(!o.setImmediate&&typeof o.MessageChannel<"u"){var d=new o.MessageChannel;d.port1.onmessage=S,s=function(){d.port2.postMessage(0)}}else"document"in o&&"onreadystatechange"in o.document.createElement("script")?s=function(){var I=o.document.createElement("script");I.onreadystatechange=function(){S(),I.onreadystatechange=null,I.parentNode.removeChild(I),I=null},o.document.documentElement.appendChild(I)}:s=function(){setTimeout(S,0)};var g,b=[];function S(){g=!0;for(var I,A,B=b.length;B;){for(A=b,b=[],I=-1;++I<B;)A[I]();B=b.length}g=!1}n.exports=R;function R(I){b.push(I)===1&&!g&&s()}}).call(this,typeof x.commonjsGlobal<"u"?x.commonjsGlobal:typeof self<"u"?self:typeof window<"u"?window:{})},{}],2:[function(t,n,r){var o=t(1);function i(){}var s={},c=["REJECTED"],u=["FULFILLED"],f=["PENDING"];n.exports=d;function d(C){if(typeof C!="function")throw new TypeError("resolver must be a function");this.state=f,this.queue=[],this.outcome=void 0,C!==i&&R(this,C)}d.prototype.catch=function(C){return this.then(null,C)},d.prototype.then=function(C,F){if(typeof C!="function"&&this.state===u||typeof F!="function"&&this.state===c)return this;var P=new this.constructor(i);if(this.state!==f){var L=this.state===u?C:F;b(P,L,this.outcome)}else this.queue.push(new g(P,C,F));return P};function g(C,F,P){this.promise=C,typeof F=="function"&&(this.onFulfilled=F,this.callFulfilled=this.otherCallFulfilled),typeof P=="function"&&(this.onRejected=P,this.callRejected=this.otherCallRejected)}g.prototype.callFulfilled=function(C){s.resolve(this.promise,C)},g.prototype.otherCallFulfilled=function(C){b(this.promise,this.onFulfilled,C)},g.prototype.callRejected=function(C){s.reject(this.promise,C)},g.prototype.otherCallRejected=function(C){b(this.promise,this.onRejected,C)};function b(C,F,P){o(function(){var L;try{L=F(P)}catch(H){return s.reject(C,H)}L===C?s.reject(C,new TypeError("Cannot resolve promise with itself")):s.resolve(C,L)})}s.resolve=function(C,F){var P=I(S,F);if(P.status==="error")return s.reject(C,P.value);var L=P.value;if(L)R(C,L);else{C.state=u,C.outcome=F;for(var H=-1,$=C.queue.length;++H<$;)C.queue[H].callFulfilled(F)}return C},s.reject=function(C,F){C.state=c,C.outcome=F;for(var P=-1,L=C.queue.length;++P<L;)C.queue[P].callRejected(F);return C};function S(C){var F=C&&C.then;if(C&&(typeof C=="object"||typeof C=="function")&&typeof F=="function")return function(){F.apply(C,arguments)}}function R(C,F){var P=!1;function L(j){P||(P=!0,s.reject(C,j))}function H(j){P||(P=!0,s.resolve(C,j))}function $(){F(H,L)}var V=I($);V.status==="error"&&L(V.value)}function I(C,F){var P={};try{P.value=C(F),P.status="success"}catch(L){P.status="error",P.value=L}return P}d.resolve=A;function A(C){return C instanceof this?C:s.resolve(new this(i),C)}d.reject=B;function B(C){var F=new this(i);return s.reject(F,C)}d.all=N;function N(C){var F=this;if(Object.prototype.toString.call(C)!=="[object Array]")return this.reject(new TypeError("must be an array"));var P=C.length,L=!1;if(!P)return this.resolve([]);for(var H=new Array(P),$=0,V=-1,j=new this(i);++V<P;)Y(C[V],V);return j;function Y(oe,fe){F.resolve(oe).then(De,function(ee){L||(L=!0,s.reject(j,ee))});function De(ee){H[fe]=ee,++$===P&&!L&&(L=!0,s.resolve(j,H))}}}d.race=k;function k(C){var F=this;if(Object.prototype.toString.call(C)!=="[object Array]")return this.reject(new TypeError("must be an array"));var P=C.length,L=!1;if(!P)return this.resolve([]);for(var H=-1,$=new this(i);++H<P;)V(C[H]);return $;function V(j){F.resolve(j).then(function(Y){L||(L=!0,s.resolve($,Y))},function(Y){L||(L=!0,s.reject($,Y))})}}},{1:1}],3:[function(t,n,r){(function(o){typeof o.Promise!="function"&&(o.Promise=t(2))}).call(this,typeof x.commonjsGlobal<"u"?x.commonjsGlobal:typeof self<"u"?self:typeof window<"u"?window:{})},{2:2}],4:[function(t,n,r){var o=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(a){return typeof a}:function(a){return a&&typeof Symbol=="function"&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a};function i(a,h){if(!(a instanceof h))throw new TypeError("Cannot call a class as a function")}function s(){try{if(typeof indexedDB<"u")return indexedDB;if(typeof webkitIndexedDB<"u")return webkitIndexedDB;if(typeof mozIndexedDB<"u")return mozIndexedDB;if(typeof OIndexedDB<"u")return OIndexedDB;if(typeof msIndexedDB<"u")return msIndexedDB}catch{return}}var c=s();function u(){try{if(!c||!c.open)return!1;var a=typeof openDatabase<"u"&&/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&!/BlackBerry/.test(navigator.platform),h=typeof fetch=="function"&&fetch.toString().indexOf("[native code")!==-1;return(!a||h)&&typeof indexedDB<"u"&&typeof IDBKeyRange<"u"}catch{return!1}}function f(a,h){a=a||[],h=h||{};try{return new Blob(a,h)}catch(m){if(m.name!=="TypeError")throw m;for(var l=typeof BlobBuilder<"u"?BlobBuilder:typeof MSBlobBuilder<"u"?MSBlobBuilder:typeof MozBlobBuilder<"u"?MozBlobBuilder:WebKitBlobBuilder,p=new l,y=0;y<a.length;y+=1)p.append(a[y]);return p.getBlob(h.type)}}typeof Promise>"u"&&t(3);var d=Promise;function g(a,h){h&&a.then(function(l){h(null,l)},function(l){h(l)})}function b(a,h,l){typeof h=="function"&&a.then(h),typeof l=="function"&&a.catch(l)}function S(a){return typeof a!="string"&&(console.warn(a+" used as a key, but it is not a string."),a=String(a)),a}function R(){if(arguments.length&&typeof arguments[arguments.length-1]=="function")return arguments[arguments.length-1]}var I="local-forage-detect-blob-support",A=void 0,B={},N=Object.prototype.toString,k="readonly",C="readwrite";function F(a){for(var h=a.length,l=new ArrayBuffer(h),p=new Uint8Array(l),y=0;y<h;y++)p[y]=a.charCodeAt(y);return l}function P(a){return new d(function(h){var l=a.transaction(I,C),p=f([""]);l.objectStore(I).put(p,"key"),l.onabort=function(y){y.preventDefault(),y.stopPropagation(),h(!1)},l.oncomplete=function(){var y=navigator.userAgent.match(/Chrome\/(\d+)/),m=navigator.userAgent.match(/Edge\//);h(m||!y||parseInt(y[1],10)>=43)}}).catch(function(){return!1})}function L(a){return typeof A=="boolean"?d.resolve(A):P(a).then(function(h){return A=h,A})}function H(a){var h=B[a.name],l={};l.promise=new d(function(p,y){l.resolve=p,l.reject=y}),h.deferredOperations.push(l),h.dbReady?h.dbReady=h.dbReady.then(function(){return l.promise}):h.dbReady=l.promise}function $(a){var h=B[a.name],l=h.deferredOperations.pop();if(l)return l.resolve(),l.promise}function V(a,h){var l=B[a.name],p=l.deferredOperations.pop();if(p)return p.reject(h),p.promise}function j(a,h){return new d(function(l,p){if(B[a.name]=B[a.name]||$e(),a.db)if(h)H(a),a.db.close();else return l(a.db);var y=[a.name];h&&y.push(a.version);var m=c.open.apply(c,y);h&&(m.onupgradeneeded=function(w){var M=m.result;try{M.createObjectStore(a.storeName),w.oldVersion<=1&&M.createObjectStore(I)}catch(E){if(E.name==="ConstraintError")console.warn('The database "'+a.name+'" has been upgraded from version '+w.oldVersion+" to version "+w.newVersion+', but the storage "'+a.storeName+'" already exists.');else throw E}}),m.onerror=function(w){w.preventDefault(),p(m.error)},m.onsuccess=function(){var w=m.result;w.onversionchange=function(M){M.target.close()},l(w),$(a)}})}function Y(a){return j(a,!1)}function oe(a){return j(a,!0)}function fe(a,h){if(!a.db)return!0;var l=!a.db.objectStoreNames.contains(a.storeName),p=a.version<a.db.version,y=a.version>a.db.version;if(p&&(a.version!==h&&console.warn('The database "'+a.name+`" can't be downgraded from version `+a.db.version+" to version "+a.version+"."),a.version=a.db.version),y||l){if(l){var m=a.db.version+1;m>a.version&&(a.version=m)}return!0}return!1}function De(a){return new d(function(h,l){var p=new FileReader;p.onerror=l,p.onloadend=function(y){var m=btoa(y.target.result||"");h({__local_forage_encoded_blob:!0,data:m,type:a.type})},p.readAsBinaryString(a)})}function ee(a){var h=F(atob(a.data));return f([h],{type:a.type})}function Ge(a){return a&&a.__local_forage_encoded_blob}function Bt(a){var h=this,l=h._initReady().then(function(){var p=B[h._dbInfo.name];if(p&&p.dbReady)return p.dbReady});return b(l,a,a),l}function At(a){H(a);for(var h=B[a.name],l=h.forages,p=0;p<l.length;p++){var y=l[p];y._dbInfo.db&&(y._dbInfo.db.close(),y._dbInfo.db=null)}return a.db=null,Y(a).then(function(m){return a.db=m,fe(a)?oe(a):m}).then(function(m){a.db=h.db=m;for(var w=0;w<l.length;w++)l[w]._dbInfo.db=m}).catch(function(m){throw V(a,m),m})}function Z(a,h,l,p){p===void 0&&(p=1);try{var y=a.db.transaction(a.storeName,h);l(null,y)}catch(m){if(p>0&&(!a.db||m.name==="InvalidStateError"||m.name==="NotFoundError"))return d.resolve().then(function(){if(!a.db||m.name==="NotFoundError"&&!a.db.objectStoreNames.contains(a.storeName)&&a.version<=a.db.version)return a.db&&(a.version=a.db.version+1),oe(a)}).then(function(){return At(a).then(function(){Z(a,h,l,p-1)})}).catch(l);l(m)}}function $e(){return{forages:[],db:null,dbReady:null,deferredOperations:[]}}function _t(a){var h=this,l={db:null};if(a)for(var p in a)l[p]=a[p];var y=B[l.name];y||(y=$e(),B[l.name]=y),y.forages.push(h),h._initReady||(h._initReady=h.ready,h.ready=Bt);var m=[];function w(){return d.resolve()}for(var M=0;M<y.forages.length;M++){var E=y.forages[M];E!==h&&m.push(E._initReady().catch(w))}var D=y.forages.slice(0);return d.all(m).then(function(){return l.db=y.db,Y(l)}).then(function(T){return l.db=T,fe(l,h._defaultConfig.version)?oe(l):T}).then(function(T){l.db=y.db=T,h._dbInfo=l;for(var _=0;_<D.length;_++){var z=D[_];z!==h&&(z._dbInfo.db=l.db,z._dbInfo.version=l.version)}})}function Nt(a,h){var l=this;a=S(a);var p=new d(function(y,m){l.ready().then(function(){Z(l._dbInfo,k,function(w,M){if(w)return m(w);try{var E=M.objectStore(l._dbInfo.storeName),D=E.get(a);D.onsuccess=function(){var T=D.result;T===void 0&&(T=null),Ge(T)&&(T=ee(T)),y(T)},D.onerror=function(){m(D.error)}}catch(T){m(T)}})}).catch(m)});return g(p,h),p}function kt(a,h){var l=this,p=new d(function(y,m){l.ready().then(function(){Z(l._dbInfo,k,function(w,M){if(w)return m(w);try{var E=M.objectStore(l._dbInfo.storeName),D=E.openCursor(),T=1;D.onsuccess=function(){var _=D.result;if(_){var z=_.value;Ge(z)&&(z=ee(z));var U=a(z,_.key,T++);U!==void 0?y(U):_.continue()}else y()},D.onerror=function(){m(D.error)}}catch(_){m(_)}})}).catch(m)});return g(p,h),p}function Pt(a,h,l){var p=this;a=S(a);var y=new d(function(m,w){var M;p.ready().then(function(){return M=p._dbInfo,N.call(h)==="[object Blob]"?L(M.db).then(function(E){return E?h:De(h)}):h}).then(function(E){Z(p._dbInfo,C,function(D,T){if(D)return w(D);try{var _=T.objectStore(p._dbInfo.storeName);E===null&&(E=void 0);var z=_.put(E,a);T.oncomplete=function(){E===void 0&&(E=null),m(E)},T.onabort=T.onerror=function(){var U=z.error?z.error:z.transaction.error;w(U)}}catch(U){w(U)}})}).catch(w)});return g(y,l),y}function Ft(a,h){var l=this;a=S(a);var p=new d(function(y,m){l.ready().then(function(){Z(l._dbInfo,C,function(w,M){if(w)return m(w);try{var E=M.objectStore(l._dbInfo.storeName),D=E.delete(a);M.oncomplete=function(){y()},M.onerror=function(){m(D.error)},M.onabort=function(){var T=D.error?D.error:D.transaction.error;m(T)}}catch(T){m(T)}})}).catch(m)});return g(p,h),p}function xt(a){var h=this,l=new d(function(p,y){h.ready().then(function(){Z(h._dbInfo,C,function(m,w){if(m)return y(m);try{var M=w.objectStore(h._dbInfo.storeName),E=M.clear();w.oncomplete=function(){p()},w.onabort=w.onerror=function(){var D=E.error?E.error:E.transaction.error;y(D)}}catch(D){y(D)}})}).catch(y)});return g(l,a),l}function zt(a){var h=this,l=new d(function(p,y){h.ready().then(function(){Z(h._dbInfo,k,function(m,w){if(m)return y(m);try{var M=w.objectStore(h._dbInfo.storeName),E=M.count();E.onsuccess=function(){p(E.result)},E.onerror=function(){y(E.error)}}catch(D){y(D)}})}).catch(y)});return g(l,a),l}function Lt(a,h){var l=this,p=new d(function(y,m){if(a<0){y(null);return}l.ready().then(function(){Z(l._dbInfo,k,function(w,M){if(w)return m(w);try{var E=M.objectStore(l._dbInfo.storeName),D=!1,T=E.openKeyCursor();T.onsuccess=function(){var _=T.result;if(!_){y(null);return}a===0||D?y(_.key):(D=!0,_.advance(a))},T.onerror=function(){m(T.error)}}catch(_){m(_)}})}).catch(m)});return g(p,h),p}function Ut(a){var h=this,l=new d(function(p,y){h.ready().then(function(){Z(h._dbInfo,k,function(m,w){if(m)return y(m);try{var M=w.objectStore(h._dbInfo.storeName),E=M.openKeyCursor(),D=[];E.onsuccess=function(){var T=E.result;if(!T){p(D);return}D.push(T.key),T.continue()},E.onerror=function(){y(E.error)}}catch(T){y(T)}})}).catch(y)});return g(l,a),l}function Ot(a,h){h=R.apply(this,arguments);var l=this.config();a=typeof a!="function"&&a||{},a.name||(a.name=a.name||l.name,a.storeName=a.storeName||l.storeName);var p=this,y;if(!a.name)y=d.reject("Invalid arguments");else{var m=a.name===l.name&&p._dbInfo.db,w=m?d.resolve(p._dbInfo.db):Y(a).then(function(M){var E=B[a.name],D=E.forages;E.db=M;for(var T=0;T<D.length;T++)D[T]._dbInfo.db=M;return M});a.storeName?y=w.then(function(M){if(M.objectStoreNames.contains(a.storeName)){var E=M.version+1;H(a);var D=B[a.name],T=D.forages;M.close();for(var _=0;_<T.length;_++){var z=T[_];z._dbInfo.db=null,z._dbInfo.version=E}var U=new d(function(O,W){var q=c.open(a.name,E);q.onerror=function(J){var se=q.result;se.close(),W(J)},q.onupgradeneeded=function(){var J=q.result;J.deleteObjectStore(a.storeName)},q.onsuccess=function(){var J=q.result;J.close(),O(J)}});return U.then(function(O){D.db=O;for(var W=0;W<T.length;W++){var q=T[W];q._dbInfo.db=O,$(q._dbInfo)}}).catch(function(O){throw(V(a,O)||d.resolve()).catch(function(){}),O})}}):y=w.then(function(M){H(a);var E=B[a.name],D=E.forages;M.close();for(var T=0;T<D.length;T++){var _=D[T];_._dbInfo.db=null}var z=new d(function(U,O){var W=c.deleteDatabase(a.name);W.onerror=function(){var q=W.result;q&&q.close(),O(W.error)},W.onblocked=function(){console.warn('dropInstance blocked for database "'+a.name+'" until all open connections are closed')},W.onsuccess=function(){var q=W.result;q&&q.close(),U(q)}});return z.then(function(U){E.db=U;for(var O=0;O<D.length;O++){var W=D[O];$(W._dbInfo)}}).catch(function(U){throw(V(a,U)||d.resolve()).catch(function(){}),U})})}return g(y,h),y}var qt={_driver:"asyncStorage",_initStorage:_t,_support:u(),iterate:kt,getItem:Nt,setItem:Pt,removeItem:Ft,clear:xt,length:zt,key:Lt,keys:Ut,dropInstance:Ot};function Wt(){return typeof openDatabase=="function"}var Q="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ht="~~local_forage_type~",Ve=/^~~local_forage_type~([^~]+)~/,me="__lfsc__:",Te=me.length,Re="arbf",Ie="blob",je="si08",Je="ui08",Ke="uic8",Ye="si16",Ze="si32",Qe="ur16",Xe="ui32",et="fl32",tt="fl64",nt=Te+Re.length,rt=Object.prototype.toString;function it(a){var h=a.length*.75,l=a.length,p,y=0,m,w,M,E;a[a.length-1]==="="&&(h--,a[a.length-2]==="="&&h--);var D=new ArrayBuffer(h),T=new Uint8Array(D);for(p=0;p<l;p+=4)m=Q.indexOf(a[p]),w=Q.indexOf(a[p+1]),M=Q.indexOf(a[p+2]),E=Q.indexOf(a[p+3]),T[y++]=m<<2|w>>4,T[y++]=(w&15)<<4|M>>2,T[y++]=(M&3)<<6|E&63;return D}function Be(a){var h=new Uint8Array(a),l="",p;for(p=0;p<h.length;p+=3)l+=Q[h[p]>>2],l+=Q[(h[p]&3)<<4|h[p+1]>>4],l+=Q[(h[p+1]&15)<<2|h[p+2]>>6],l+=Q[h[p+2]&63];return h.length%3===2?l=l.substring(0,l.length-1)+"=":h.length%3===1&&(l=l.substring(0,l.length-2)+"=="),l}function Gt(a,h){var l="";if(a&&(l=rt.call(a)),a&&(l==="[object ArrayBuffer]"||a.buffer&&rt.call(a.buffer)==="[object ArrayBuffer]")){var p,y=me;a instanceof ArrayBuffer?(p=a,y+=Re):(p=a.buffer,l==="[object Int8Array]"?y+=je:l==="[object Uint8Array]"?y+=Je:l==="[object Uint8ClampedArray]"?y+=Ke:l==="[object Int16Array]"?y+=Ye:l==="[object Uint16Array]"?y+=Qe:l==="[object Int32Array]"?y+=Ze:l==="[object Uint32Array]"?y+=Xe:l==="[object Float32Array]"?y+=et:l==="[object Float64Array]"?y+=tt:h(new Error("Failed to get type for BinaryArray"))),h(y+Be(p))}else if(l==="[object Blob]"){var m=new FileReader;m.onload=function(){var w=Ht+a.type+"~"+Be(this.result);h(me+Ie+w)},m.readAsArrayBuffer(a)}else try{h(JSON.stringify(a))}catch(w){console.error("Couldn't convert value into a JSON string: ",a),h(null,w)}}function $t(a){if(a.substring(0,Te)!==me)return JSON.parse(a);var h=a.substring(nt),l=a.substring(Te,nt),p;if(l===Ie&&Ve.test(h)){var y=h.match(Ve);p=y[1],h=h.substring(y[0].length)}var m=it(h);switch(l){case Re:return m;case Ie:return f([m],{type:p});case je:return new Int8Array(m);case Je:return new Uint8Array(m);case Ke:return new Uint8ClampedArray(m);case Ye:return new Int16Array(m);case Qe:return new Uint16Array(m);case Ze:return new Int32Array(m);case Xe:return new Uint32Array(m);case et:return new Float32Array(m);case tt:return new Float64Array(m);default:throw new Error("Unkown type: "+l)}}var Ae={serialize:Gt,deserialize:$t,stringToBuffer:it,bufferToString:Be};function ot(a,h,l,p){a.executeSql("CREATE TABLE IF NOT EXISTS "+h.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],l,p)}function Vt(a){var h=this,l={db:null};if(a)for(var p in a)l[p]=typeof a[p]!="string"?a[p].toString():a[p];var y=new d(function(m,w){try{l.db=openDatabase(l.name,String(l.version),l.description,l.size)}catch(M){return w(M)}l.db.transaction(function(M){ot(M,l,function(){h._dbInfo=l,m()},function(E,D){w(D)})},w)});return l.serializer=Ae,y}function X(a,h,l,p,y,m){a.executeSql(l,p,y,function(w,M){M.code===M.SYNTAX_ERR?w.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[h.storeName],function(E,D){D.rows.length?m(E,M):ot(E,h,function(){E.executeSql(l,p,y,m)},m)},m):m(w,M)},m)}function jt(a,h){var l=this;a=S(a);var p=new d(function(y,m){l.ready().then(function(){var w=l._dbInfo;w.db.transaction(function(M){X(M,w,"SELECT * FROM "+w.storeName+" WHERE key = ? LIMIT 1",[a],function(E,D){var T=D.rows.length?D.rows.item(0).value:null;T&&(T=w.serializer.deserialize(T)),y(T)},function(E,D){m(D)})})}).catch(m)});return g(p,h),p}function Jt(a,h){var l=this,p=new d(function(y,m){l.ready().then(function(){var w=l._dbInfo;w.db.transaction(function(M){X(M,w,"SELECT * FROM "+w.storeName,[],function(E,D){for(var T=D.rows,_=T.length,z=0;z<_;z++){var U=T.item(z),O=U.value;if(O&&(O=w.serializer.deserialize(O)),O=a(O,U.key,z+1),O!==void 0){y(O);return}}y()},function(E,D){m(D)})})}).catch(m)});return g(p,h),p}function at(a,h,l,p){var y=this;a=S(a);var m=new d(function(w,M){y.ready().then(function(){h===void 0&&(h=null);var E=h,D=y._dbInfo;D.serializer.serialize(h,function(T,_){_?M(_):D.db.transaction(function(z){X(z,D,"INSERT OR REPLACE INTO "+D.storeName+" (key, value) VALUES (?, ?)",[a,T],function(){w(E)},function(U,O){M(O)})},function(z){if(z.code===z.QUOTA_ERR){if(p>0){w(at.apply(y,[a,E,l,p-1]));return}M(z)}})})}).catch(M)});return g(m,l),m}function Kt(a,h,l){return at.apply(this,[a,h,l,1])}function Yt(a,h){var l=this;a=S(a);var p=new d(function(y,m){l.ready().then(function(){var w=l._dbInfo;w.db.transaction(function(M){X(M,w,"DELETE FROM "+w.storeName+" WHERE key = ?",[a],function(){y()},function(E,D){m(D)})})}).catch(m)});return g(p,h),p}function Zt(a){var h=this,l=new d(function(p,y){h.ready().then(function(){var m=h._dbInfo;m.db.transaction(function(w){X(w,m,"DELETE FROM "+m.storeName,[],function(){p()},function(M,E){y(E)})})}).catch(y)});return g(l,a),l}function Qt(a){var h=this,l=new d(function(p,y){h.ready().then(function(){var m=h._dbInfo;m.db.transaction(function(w){X(w,m,"SELECT COUNT(key) as c FROM "+m.storeName,[],function(M,E){var D=E.rows.item(0).c;p(D)},function(M,E){y(E)})})}).catch(y)});return g(l,a),l}function Xt(a,h){var l=this,p=new d(function(y,m){l.ready().then(function(){var w=l._dbInfo;w.db.transaction(function(M){X(M,w,"SELECT key FROM "+w.storeName+" WHERE id = ? LIMIT 1",[a+1],function(E,D){var T=D.rows.length?D.rows.item(0).key:null;y(T)},function(E,D){m(D)})})}).catch(m)});return g(p,h),p}function en(a){var h=this,l=new d(function(p,y){h.ready().then(function(){var m=h._dbInfo;m.db.transaction(function(w){X(w,m,"SELECT key FROM "+m.storeName,[],function(M,E){for(var D=[],T=0;T<E.rows.length;T++)D.push(E.rows.item(T).key);p(D)},function(M,E){y(E)})})}).catch(y)});return g(l,a),l}function tn(a){return new d(function(h,l){a.transaction(function(p){p.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'",[],function(y,m){for(var w=[],M=0;M<m.rows.length;M++)w.push(m.rows.item(M).name);h({db:a,storeNames:w})},function(y,m){l(m)})},function(p){l(p)})})}function nn(a,h){h=R.apply(this,arguments);var l=this.config();a=typeof a!="function"&&a||{},a.name||(a.name=a.name||l.name,a.storeName=a.storeName||l.storeName);var p=this,y;return a.name?y=new d(function(m){var w;a.name===l.name?w=p._dbInfo.db:w=openDatabase(a.name,"","",0),a.storeName?m({db:w,storeNames:[a.storeName]}):m(tn(w))}).then(function(m){return new d(function(w,M){m.db.transaction(function(E){function D(U){return new d(function(O,W){E.executeSql("DROP TABLE IF EXISTS "+U,[],function(){O()},function(q,J){W(J)})})}for(var T=[],_=0,z=m.storeNames.length;_<z;_++)T.push(D(m.storeNames[_]));d.all(T).then(function(){w()}).catch(function(U){M(U)})},function(E){M(E)})})}):y=d.reject("Invalid arguments"),g(y,h),y}var rn={_driver:"webSQLStorage",_initStorage:Vt,_support:Wt(),iterate:Jt,getItem:jt,setItem:Kt,removeItem:Yt,clear:Zt,length:Qt,key:Xt,keys:en,dropInstance:nn};function on(){try{return typeof localStorage<"u"&&"setItem"in localStorage&&!!localStorage.setItem}catch{return!1}}function st(a,h){var l=a.name+"/";return a.storeName!==h.storeName&&(l+=a.storeName+"/"),l}function an(){var a="_localforage_support_test";try{return localStorage.setItem(a,!0),localStorage.removeItem(a),!1}catch{return!0}}function sn(){return!an()||localStorage.length>0}function cn(a){var h=this,l={};if(a)for(var p in a)l[p]=a[p];return l.keyPrefix=st(a,h._defaultConfig),sn()?(h._dbInfo=l,l.serializer=Ae,d.resolve()):d.reject()}function ln(a){var h=this,l=h.ready().then(function(){for(var p=h._dbInfo.keyPrefix,y=localStorage.length-1;y>=0;y--){var m=localStorage.key(y);m.indexOf(p)===0&&localStorage.removeItem(m)}});return g(l,a),l}function un(a,h){var l=this;a=S(a);var p=l.ready().then(function(){var y=l._dbInfo,m=localStorage.getItem(y.keyPrefix+a);return m&&(m=y.serializer.deserialize(m)),m});return g(p,h),p}function dn(a,h){var l=this,p=l.ready().then(function(){for(var y=l._dbInfo,m=y.keyPrefix,w=m.length,M=localStorage.length,E=1,D=0;D<M;D++){var T=localStorage.key(D);if(T.indexOf(m)===0){var _=localStorage.getItem(T);if(_&&(_=y.serializer.deserialize(_)),_=a(_,T.substring(w),E++),_!==void 0)return _}}});return g(p,h),p}function hn(a,h){var l=this,p=l.ready().then(function(){var y=l._dbInfo,m;try{m=localStorage.key(a)}catch{m=null}return m&&(m=m.substring(y.keyPrefix.length)),m});return g(p,h),p}function fn(a){var h=this,l=h.ready().then(function(){for(var p=h._dbInfo,y=localStorage.length,m=[],w=0;w<y;w++){var M=localStorage.key(w);M.indexOf(p.keyPrefix)===0&&m.push(M.substring(p.keyPrefix.length))}return m});return g(l,a),l}function mn(a){var h=this,l=h.keys().then(function(p){return p.length});return g(l,a),l}function gn(a,h){var l=this;a=S(a);var p=l.ready().then(function(){var y=l._dbInfo;localStorage.removeItem(y.keyPrefix+a)});return g(p,h),p}function pn(a,h,l){var p=this;a=S(a);var y=p.ready().then(function(){h===void 0&&(h=null);var m=h;return new d(function(w,M){var E=p._dbInfo;E.serializer.serialize(h,function(D,T){if(T)M(T);else try{localStorage.setItem(E.keyPrefix+a,D),w(m)}catch(_){(_.name==="QuotaExceededError"||_.name==="NS_ERROR_DOM_QUOTA_REACHED")&&M(_),M(_)}})})});return g(y,l),y}function yn(a,h){if(h=R.apply(this,arguments),a=typeof a!="function"&&a||{},!a.name){var l=this.config();a.name=a.name||l.name,a.storeName=a.storeName||l.storeName}var p=this,y;return a.name?y=new d(function(m){a.storeName?m(st(a,p._defaultConfig)):m(a.name+"/")}).then(function(m){for(var w=localStorage.length-1;w>=0;w--){var M=localStorage.key(w);M.indexOf(m)===0&&localStorage.removeItem(M)}}):y=d.reject("Invalid arguments"),g(y,h),y}var vn={_driver:"localStorageWrapper",_initStorage:cn,_support:on(),iterate:dn,getItem:un,setItem:pn,removeItem:gn,clear:ln,length:mn,key:hn,keys:fn,dropInstance:yn},bn=function(h,l){return h===l||typeof h=="number"&&typeof l=="number"&&isNaN(h)&&isNaN(l)},wn=function(h,l){for(var p=h.length,y=0;y<p;){if(bn(h[y],l))return!0;y++}return!1},ct=Array.isArray||function(a){return Object.prototype.toString.call(a)==="[object Array]"},ae={},lt={},te={INDEXEDDB:qt,WEBSQL:rn,LOCALSTORAGE:vn},Mn=[te.INDEXEDDB._driver,te.WEBSQL._driver,te.LOCALSTORAGE._driver],ge=["dropInstance"],_e=["clear","getItem","iterate","key","keys","length","removeItem","setItem"].concat(ge),Sn={description:"",driver:Mn.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1};function Cn(a,h){a[h]=function(){var l=arguments;return a.ready().then(function(){return a[h].apply(a,l)})}}function Ne(){for(var a=1;a<arguments.length;a++){var h=arguments[a];if(h)for(var l in h)h.hasOwnProperty(l)&&(ct(h[l])?arguments[0][l]=h[l].slice():arguments[0][l]=h[l])}return arguments[0]}var En=(function(){function a(h){i(this,a);for(var l in te)if(te.hasOwnProperty(l)){var p=te[l],y=p._driver;this[l]=y,ae[y]||this.defineDriver(p)}this._defaultConfig=Ne({},Sn),this._config=Ne({},this._defaultConfig,h),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver).catch(function(){})}return a.prototype.config=function(l){if((typeof l>"u"?"undefined":o(l))==="object"){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var p in l){if(p==="storeName"&&(l[p]=l[p].replace(/\W/g,"_")),p==="version"&&typeof l[p]!="number")return new Error("Database version must be a number.");this._config[p]=l[p]}return"driver"in l&&l.driver?this.setDriver(this._config.driver):!0}else return typeof l=="string"?this._config[l]:this._config},a.prototype.defineDriver=function(l,p,y){var m=new d(function(w,M){try{var E=l._driver,D=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!l._driver){M(D);return}for(var T=_e.concat("_initStorage"),_=0,z=T.length;_<z;_++){var U=T[_],O=!wn(ge,U);if((O||l[U])&&typeof l[U]!="function"){M(D);return}}var W=function(){for(var se=function(Rn){return function(){var In=new Error("Method "+Rn+" is not implemented by the current driver"),ut=d.reject(In);return g(ut,arguments[arguments.length-1]),ut}},ke=0,Tn=ge.length;ke<Tn;ke++){var Pe=ge[ke];l[Pe]||(l[Pe]=se(Pe))}};W();var q=function(se){ae[E]&&console.info("Redefining LocalForage driver: "+E),ae[E]=l,lt[E]=se,w()};"_support"in l?l._support&&typeof l._support=="function"?l._support().then(q,M):q(!!l._support):q(!0)}catch(J){M(J)}});return b(m,p,y),m},a.prototype.driver=function(){return this._driver||null},a.prototype.getDriver=function(l,p,y){var m=ae[l]?d.resolve(ae[l]):d.reject(new Error("Driver not found."));return b(m,p,y),m},a.prototype.getSerializer=function(l){var p=d.resolve(Ae);return b(p,l),p},a.prototype.ready=function(l){var p=this,y=p._driverSet.then(function(){return p._ready===null&&(p._ready=p._initDriver()),p._ready});return b(y,l,l),y},a.prototype.setDriver=function(l,p,y){var m=this;ct(l)||(l=[l]);var w=this._getSupportedDrivers(l);function M(){m._config.driver=m.driver()}function E(_){return m._extend(_),M(),m._ready=m._initStorage(m._config),m._ready}function D(_){return function(){var z=0;function U(){for(;z<_.length;){var O=_[z];return z++,m._dbInfo=null,m._ready=null,m.getDriver(O).then(E).catch(U)}M();var W=new Error("No available storage method found.");return m._driverSet=d.reject(W),m._driverSet}return U()}}var T=this._driverSet!==null?this._driverSet.catch(function(){return d.resolve()}):d.resolve();return this._driverSet=T.then(function(){var _=w[0];return m._dbInfo=null,m._ready=null,m.getDriver(_).then(function(z){m._driver=z._driver,M(),m._wrapLibraryMethodsWithReady(),m._initDriver=D(w)})}).catch(function(){M();var _=new Error("No available storage method found.");return m._driverSet=d.reject(_),m._driverSet}),b(this._driverSet,p,y),this._driverSet},a.prototype.supports=function(l){return!!lt[l]},a.prototype._extend=function(l){Ne(this,l)},a.prototype._getSupportedDrivers=function(l){for(var p=[],y=0,m=l.length;y<m;y++){var w=l[y];this.supports(w)&&p.push(w)}return p},a.prototype._wrapLibraryMethodsWithReady=function(){for(var l=0,p=_e.length;l<p;l++)Cn(this,_e[l])},a.prototype.createInstance=function(l){return new a(l)},a})(),Dn=new En;n.exports=Dn},{3:3}]},{},[4])(4)})})(Fe)),Fe.exports}var Un=Ln();const On=x.getDefaultExportFromCjs(Un);function ne(v){return`model:${v}`}function qn(v){const e=v.lastIndexOf("/");return e>=0?v.substring(0,e+1):""}async function Wn(v,e=3,t=1e3){let n=null;for(let r=0;r<e;r++)try{const o=await fetch(v);if(!o.ok)throw new Error(`HTTP ${o.status}: ${o.statusText}`);return o}catch(o){if(n=o,r===e-1)throw o;const i=t*Math.pow(2,r);console.warn(`[ModelCache] Fetch failed (attempt ${r+1}/${e}), retrying in ${i}ms...`,{url:v,error:String(o)}),await new Promise(s=>setTimeout(s,i))}throw n}async function ft(v,e,t,n=3,r=1e3){let o=null;for(let i=0;i<n;i++){const s=e?await e(v):v;try{const c=await fetch(s);if(!c.ok)throw new Error(`HTTP ${c.status}: ${c.statusText}`);const u=await c.text(),f=JSON.parse(u),d=qn(s),g={},b=[];if(f.weightsManifest&&Array.isArray(f.weightsManifest)){for(const R of f.weightsManifest)if(R.paths&&Array.isArray(R.paths))for(const I of R.paths)b.push(I)}const S=b.map(async R=>{const I=d+R,A=await Wn(I,n,r);g[R]=await A.arrayBuffer()});return await Promise.all(S),{manifest:u,weights:g,savedAt:Date.now(),originalUrl:v}}catch(c){if(o=c,i===n-1)throw c;t?.(v);const u=r*Math.pow(2,i);console.warn(`[ModelCache] Model fetch failed (attempt ${i+1}/${n}), re-resolving and retrying in ${u}ms...`,{url:v,resolvedUrl:s,error:String(c)}),await new Promise(f=>setTimeout(f,u))}}throw o}function xe(v,e){return JSON.parse(e.manifest),{load:async()=>vt(e)}}function vt(v){const e=JSON.parse(v.manifest),t=[],n=[];if(e.weightsManifest&&Array.isArray(e.weightsManifest))for(const r of e.weightsManifest){if(r.weights&&Array.isArray(r.weights))for(const o of r.weights)n.push(o);if(r.paths&&Array.isArray(r.paths))for(const o of r.paths){const i=v.weights[o];if(!i)throw new Error(`[ModelCache] Weight shard "${o}" not found in cache`);t.push(i)}}return{modelTopology:e.modelTopology,format:e.format??"graph-model",generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightSpecs:n.length>0?n:void 0,weightData:t.length>0?t.length===1?t[0]:t:void 0}}const bt=new Map;let mt=!1;function Hn(){mt||(mt=!0,import("@tensorflow/tfjs").then(v=>{v.io.registerLoadRouter((e=>{if(typeof e=="string"&&e.startsWith("cached://")){const t=bt.get(e);if(t)return{load:async()=>{const n=await t.store.getItem(t.key);if(!n)throw new Error(`[ModelCache] Model not in cache: ${e}`);return vt(n)}}}return null}))}))}Hn();class wt{constructor(e={}){this.store=On.createInstance({name:e.storeName??"playlist-data-engine-models",description:e.description??"Cached TF.js model artifacts for playlist-data-engine"})}async has(e){return await this.store.getItem(ne(e))!=null}async getCacheInfo(e){const t=await this.store.getItem(ne(e));if(!t)return{cached:!1};let n=t.manifest.length;for(const r of Object.values(t.weights))n+=r.byteLength;return{cached:!0,savedAt:t.savedAt,size:n}}async loadFromCache(e,t){const n=await this.store.getItem(ne(t));if(!n)throw new Error(`[ModelCache] Model not cached: ${t}`);return e.loadGraphModel(xe(e,n))}async getOrFetchGraphModel(e,t,n={}){const r=ne(t);try{const i=await this.store.getItem(r);if(i)return console.info(`[ModelCache] Loading model from cache: ${t}`),await e.loadGraphModel(xe(e,i))}catch(i){console.warn("[ModelCache] Cache load failed, clearing and re-fetching:",i),await this.store.removeItem(r)}console.info(`[ModelCache] Downloading model: ${t}`);const o=await ft(t,n.resolveUrl,n.invalidateUrlCache,n.maxRetries??3,n.baseDelayMs??1e3);return await this.store.setItem(r,o),console.info(`[ModelCache] Model cached: ${t} (${Object.keys(o.weights).length} shards)`),e.loadGraphModel(xe(e,o))}async getOrFetchEssentiaUrl(e,t={}){const n=ne(e),r=`cached://${e}`;if(await this.store.getItem(n))console.info(`[ModelCache] Loading Essentia model from cache: ${e}`);else{console.info(`[ModelCache] Downloading model for Essentia: ${e}`);const i=await ft(e,t.resolveUrl,t.invalidateUrlCache,t.maxRetries??3,t.baseDelayMs??1e3);await this.store.setItem(n,i),console.info(`[ModelCache] Model cached: ${e} (${Object.keys(i.weights).length} shards)`)}return bt.set(r,{store:this.store,key:n}),r}async clear(e){e?(await this.store.removeItem(ne(e)),console.info(`[ModelCache] Cleared cache for: ${e}`)):(await this.store.clear(),console.info("[ModelCache] Cleared all cached models"))}async listCachedModels(){return(await this.store.keys()).filter(t=>t.startsWith("model:")).map(t=>t.replace("model:",""))}async totalCacheSize(){let e=0;return await this.store.iterate(t=>{if(t){e+=t.manifest.length;for(const n of Object.values(t.weights))e+=n.byteLength}}),e}}const ie=new wt,Se="https://arweave.net/_HoMwkbF0JUamTiVGWNnCCC5yDjcPry-ENhzN6Xn3U0/model.json",gt={algorithm:"pitch_melodia",minFrequency:80,maxFrequency:2e4,frameSize:2048,hopSize:128,targetSampleRate:44100,crepeModelUrl:Se},Gn=69,$n=440,Vn=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];class he{constructor(e){this.essentiaWASM=null,this.algorithms=null,this.crepeModel=null,this.initialized=!1,this.resolvedUrlCache=new Map,this.config={...gt,...e}}static async create(e={}){const t={...gt,...e};t.resolveUrl||(t.resolveUrl=K.arweaveGatewayManager.resolveUrl.bind(K.arweaveGatewayManager));const n=new he(t);return await n.initializeEssentia(),t.algorithm==="pitch_crepe"&&await n.loadCrepeModel(t.crepeModelUrl),n}getConfig(){return{...this.config}}async initializeEssentia(){if(this.initialized)return;const t=(await Promise.resolve().then(()=>require("./essentia-wasm.es-7mXF1zkQ.cjs"))).EssentiaWASM;await t.ready,this.essentiaWASM=t,this.algorithms=new t.EssentiaJS(!1),this.initialized=!0}async loadCrepeModel(e){if(this.config.enableModelCache!==!1)this.crepeModel=await ie.getOrFetchGraphModel(G,e,{resolveUrl:this.config.resolveUrl,invalidateUrlCache:n=>K.arweaveGatewayManager.invalidateCacheForUrl(n),maxRetries:3,baseDelayMs:1e3});else{const n=await this.resolveUrlWithCache(e);let r=null;for(let o=0;o<3;o++)try{this.crepeModel=await G.loadGraphModel(n);break}catch(i){r=i;const s=String(i).toLowerCase();if(!(s.includes("fetch")||s.includes("network")||s.includes("timeout")||s.includes("failed to fetch")||s.includes("networkerror"))||o===2)throw i;const u=1e3*Math.pow(2,o);console.warn(`[EssentiaPitchDetector] CREPE model load failed (attempt ${o+1}/3), retrying in ${u}ms...`,{originalUrl:e,resolvedUrl:n,error:String(i)}),await new Promise(f=>setTimeout(f,u))}if(!this.crepeModel)throw new Error(`Failed to load CREPE model from ${e}: ${r?.message??String(r)}`)}const t=G.zeros([1,1024]);G.tidy(()=>{this.crepeModel.execute(t)}),t.dispose(),console.log("[EssentiaPitchDetector] CREPE model loaded")}async resolveUrlWithCache(e){if(this.resolvedUrlCache.has(e))return this.resolvedUrlCache.get(e);if(!this.config.resolveUrl)return e;try{const t=await this.config.resolveUrl(e);return this.resolvedUrlCache.set(e,t),t!==e&&console.info("[EssentiaPitchDetector] Resolved URL to alternate gateway",{originalUrl:e,resolvedUrl:t}),t}catch(t){return console.warn("[EssentiaPitchDetector] URL resolution failed, using original URL",{url:e,error:String(t)}),this.resolvedUrlCache.set(e,e),e}}detectSignal(e,t){if(!this.initialized)throw new Error("EssentiaPitchDetector not initialized. Use create() factory method.");if(e.length===0)return[];switch(this.config.algorithm){case"predominant_melodia":return this.runPredominantMelodia(e,t);case"pitch_melodia":return this.runPitchMelodia(e,t);case"pitch_yin_probabilistic":return this.runPitchYinProbabilistic(e,t);case"multipitch_melodia":return this.runMultiPitchMelodia(e,t);case"multipitch_klapuri":return this.runMultiPitchKlapuri(e,t);case"pitch_crepe":return this.runCrepe(e,t);default:throw new Error(`Unknown algorithm: ${this.config.algorithm}`)}}runPredominantMelodia(e,t){const n=this.essentiaWASM.arrayToVector(e),r=this.algorithms.PredominantPitchMelodia(n,10,3,this.config.frameSize,!1,.8,this.config.hopSize,1,40,this.config.maxFrequency,100,this.config.minFrequency,20,.9,.9,27.5625,55,t,100,!1,.2),o=Array.from(this.essentiaWASM.vectorToArray(r.pitch)),i=Array.from(this.essentiaWASM.vectorToArray(r.pitchConfidence)),s=this.config.hopSize/t;return this.mapSingleF0(o,i,s)}runPitchMelodia(e,t){const n=this.essentiaWASM.arrayToVector(e),r=this.algorithms.PitchMelodia(n,10,3,this.config.frameSize,!1,.8,this.config.hopSize,1,40,this.config.maxFrequency,100,this.config.minFrequency,20,.9,.9,27.5625,55,t,100),o=Array.from(this.essentiaWASM.vectorToArray(r.pitch)),i=Array.from(this.essentiaWASM.vectorToArray(r.pitchConfidence)),s=this.config.hopSize/t;return this.mapSingleF0(o,i,s)}runPitchYinProbabilistic(e,t){const n=this.essentiaWASM.arrayToVector(e),r=this.algorithms.PitchYinProbabilistic(n,this.config.frameSize,this.config.hopSize,.1,"negative",!1,t),o=Array.from(this.essentiaWASM.vectorToArray(r.pitch)),i=Array.from(this.essentiaWASM.vectorToArray(r.voicedProbabilities)),s=this.config.hopSize/t;return o.map((c,u)=>{const f=u*s;if(c>0&&i[u]>.5){const g=Math.round(this.frequencyToMidi(c));return{timestamp:f,frequency:c,probability:i[u],isVoiced:!0,midiNote:g,noteName:this.midiToNoteName(g)}}return{timestamp:f,frequency:0,probability:0,isVoiced:!1,midiNote:null,noteName:null}})}runMultiPitchMelodia(e,t){const n=this.essentiaWASM.arrayToVector(e),r=this.algorithms.MultiPitchMelodia(n,10,3,this.config.frameSize,!1,.8,this.config.hopSize,1,40,this.config.maxFrequency,100,this.config.minFrequency,20,.9,.9,27.5625,55,t,100);return this.mapMultiPitch(r.pitch,t)}runMultiPitchKlapuri(e,t){const n=this.essentiaWASM.arrayToVector(e),r=this.algorithms.MultiPitchKlapuri(n,10,this.config.frameSize,.8,this.config.hopSize,1,40,this.config.maxFrequency,this.config.minFrequency,10,55,t);return this.mapMultiPitch(r.pitch,t)}runCrepe(e,t){if(!this.crepeModel)throw new Error('CREPE model not loaded. Ensure algorithm is "pitch_crepe" and model URL is valid.');const n=16e3,r=1024,o=256,i=this.resampleSignal(e,t,n),s=Math.floor((i.length-r)/o)+1,c=o/n,u=32.7,f=[];for(let d=0;d<s;d++){const g=d*o,b=i.slice(g,g+r),S=d*c;let R;try{const A=G.tidy(()=>{const C=G.tensor(b,[1,r]);return this.crepeModel.execute(C).dataSync().slice()});let B=0,N=0,k=0;for(let C=0;C<360;C++){const F=A[C];B+=C*10*F,N+=F,F>k&&(k=F)}if(N>0&&k>.3){const C=B/N,F=u*Math.pow(2,C/1200),P=Math.round(this.frequencyToMidi(F));R={timestamp:S,frequency:F,probability:k,isVoiced:!0,midiNote:P,noteName:this.midiToNoteName(P)}}else R={timestamp:S,frequency:0,probability:0,isVoiced:!1,midiNote:null,noteName:null}}catch(I){console.error(`[EssentiaPitchDetector] CREPE inference error at frame ${d}:`,I),R={timestamp:S,frequency:0,probability:0,isVoiced:!1,midiNote:null,noteName:null}}f.push(R)}return f}mapSingleF0(e,t,n){return e.map((r,o)=>{const i=o*n;if(r>0){const s=Math.round(this.frequencyToMidi(r));return{timestamp:i,frequency:r,probability:t[o]??0,isVoiced:!0,midiNote:s,noteName:this.midiToNoteName(s)}}return{timestamp:i,frequency:0,probability:0,isVoiced:!1,midiNote:null,noteName:null}})}mapMultiPitch(e,t){const n=e.size(),r=this.config.hopSize/t,o=[];for(let i=0;i<n;i++){const s=e.get(i),u=Array.from(this.essentiaWASM.vectorToArray(s)).filter(d=>d>0).sort((d,g)=>d-g),f=i*r;if(u.length>0){const d=u[0],g=Math.round(this.frequencyToMidi(d)),b=u.slice(1).map(S=>({frequency:S,probability:1}));o.push({timestamp:f,frequency:d,probability:1,isVoiced:!0,midiNote:g,noteName:this.midiToNoteName(g),...b.length>0?{alternativeHypotheses:b}:{}})}else o.push({timestamp:f,frequency:0,probability:0,isVoiced:!1,midiNote:null,noteName:null})}return o}resampleSignal(e,t,n){if(t===n)return e;const r=t/n,o=Math.round(e.length/r),i=new Float32Array(o);for(let s=0;s<o;s++){const c=s*r,u=Math.floor(c),f=Math.min(u+1,e.length-1),d=c-u;i[s]=e[u]*(1-d)+e[f]*d}return i}frequencyToMidi(e){return Gn+12*Math.log2(e/$n)}midiToNoteName(e){const t=Math.floor(e/12)-1,n=Math.round(e)%12;return`${Vn[n]}${t}`}}const pt={targetSampleRate:44100,pitchDetector:{},pitchAlgorithm:"pitch_melodia",crepeModelUrl:Se};class Mt{constructor(e={}){this.essentiaDetector=null,this.config={...pt,...e,pitchDetector:{...pt.pitchDetector,...e.pitchDetector}},this.fullSpectrumDetector=new x.PitchDetector({...this.config.pitchDetector,minFrequency:this.config.pitchDetector.minFrequency??80,maxFrequency:this.config.pitchDetector.maxFrequency??1e3,targetSampleRate:this.config.targetSampleRate,yinThreshold:this.config.pitchDetector.yinThreshold??.4})}getConfig(){return{...this.config}}async linkWithComposite(e,t){const n=this.config.targetSampleRate,o=x.resampleAudio(t,n).data;let i,s;this.config.pitchAlgorithm==="pyin_legacy"?(i=this.fullSpectrumDetector.detectSignalRaw(o,n),s=this.fullSpectrumDetector.getConfig().hopSize/n):(this.essentiaDetector||(this.essentiaDetector=await he.create({algorithm:this.config.pitchAlgorithm,minFrequency:this.config.pitchDetector.minFrequency??80,maxFrequency:this.config.pitchDetector.maxFrequency??2e4,crepeModelUrl:this.config.crepeModelUrl,resolveUrl:this.config.resolveUrl}),console.log(`[PitchBeatLinker] Essentia detector initialized: ${this.config.pitchAlgorithm}`)),i=this.essentiaDetector.detectSignal(o,n),s=this.essentiaDetector.getConfig().hopSize/n),console.debug("[PitchBeatLinker] Full-spectrum analysis:",{detector:this.config.pitchAlgorithm==="pyin_legacy"?"pYIN":`essentia/${this.config.pitchAlgorithm}`,totalFrames:i.length,voicedFrames:i.filter(u=>u.isVoiced).length,signalLength:o.length,signalSampleRate:n});const c=[];for(const u of e.beats){const f=u.detectedTimestamp??u.timestamp,d=Math.round(f/s);let g=null,b=1/0,S=0;for(let R=0;R<i.length;R++){const I=i[R];if(!I.isVoiced)continue;const A=Math.abs(R-d);(A<b||A===b&&I.probability>S)&&(b=A,S=I.probability,g=I)}c.push({beatIndex:u.beatIndex,timestamp:u.timestamp,band:u.sourceBand,pitch:g,direction:"none",intervalFromPrevious:0})}return c}deriveVariantPitches(e,t){const n=[],r=new Map;for(const o of t){const i=Math.round(o.timestamp*1e3);r.set(i,o)}for(const o of e.beats){const i=Math.round(o.timestamp*1e3);let s=r.get(i);if(!s)for(let c=-2;c<=2&&(s=r.get(i+c),!s);c++);s?n.push({beatIndex:o.beatIndex,timestamp:o.timestamp,band:o.sourceBand,pitch:s.pitch,direction:s.direction,intervalFromPrevious:s.intervalFromPrevious,intervalCategory:s.intervalCategory}):n.push({beatIndex:o.beatIndex,timestamp:o.timestamp,band:o.sourceBand,pitch:null,direction:"none",intervalFromPrevious:0})}return n}deriveAllVariantPitches(e,t){return{easy:this.deriveVariantPitches(e.easy,t),medium:this.deriveVariantPitches(e.medium,t),hard:this.deriveVariantPitches(e.hard,t)}}}const jn={maxTimeGapForConsecutive:.5};function St(v){return v===0?"unison":v<=2?"small":v<=4?"medium":v<=7?"large":"very_large"}function Jn(v,e){return Math.abs(v-e)}function Kn(v,e){return v===null||e===null?"none":v>e?"up":v<e?"down":"stable"}function Yn(v){if(v.length===0)return"stable";let e=0,t=0,n=0;for(const s of v)s.direction==="up"?e++:s.direction==="down"?t++:n++;if(e===0&&t===0)return"stable";const r=e-t,i=(e+t+n)*.2;return Math.abs(r)<=i?"mixed":e>t?"ascending":t>e?"descending":"stable"}function yt(v){const e=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],t=Math.floor(v/12)-1,n=v%12;return`${e[n]}${t}`}class Zn{constructor(e={}){this.config={...jn,...e}}getConfig(){return{...this.config}}analyze(e){const t=this.analyzeBandPitches(e),{directionStats:n,intervalStats:r,metadata:o}=this.calculateStatistics(t),i=this.buildMelodyContour(t);return{pitchByBeat:t,melodyContour:i,directionStats:n,intervalStats:r,metadata:o}}analyzeBandPitches(e){if(e.length===0)return[];const t=[];for(let n=0;n<e.length;n++){const r=e[n],o=n>0?e[n-1]:null,i=o!==null&&r.timestamp-o.timestamp<=this.config.maxTimeGapForConsecutive;let s,c,u;if(!i||!o||!o.pitch||!r.pitch)s="none",c=0,u="unison";else{const f=r.pitch.midiNote,d=o.pitch.midiNote;f===null||d===null?(s="none",c=0,u="unison"):(s=Kn(f,d),c=Jn(f,d),u=St(c))}t.push({...r,direction:s,intervalFromPrevious:c,intervalCategory:u})}return t}buildMelodyContour(e){const t=e.filter(b=>b.pitch?.isVoiced);if(t.length===0)return{segments:[],direction:"stable",range:{minNote:"N/A",maxNote:"N/A",semitones:0},shortTermDirection:"stable",mediumTermDirection:"stable",longTermDirection:"stable"};const n=t.map(b=>b.pitch?.midiNote).filter(b=>b!==null);if(n.length===0)return{segments:[],direction:"stable",range:{minNote:"N/A",maxNote:"N/A",semitones:0},shortTermDirection:"stable",mediumTermDirection:"stable",longTermDirection:"stable"};const r=Math.min(...n),o=Math.max(...n),i=yt(r),s=yt(o),c=this.buildSegments(t),u=Yn(c),f=this.calculateTimeWindowDirection(e,1,2),d=this.calculateTimeWindowDirection(e,4,8),g=this.calculateTimeWindowDirection(e,16,1/0);return{segments:c,direction:u,range:{minNote:i,maxNote:s,semitones:o-r},shortTermDirection:f,mediumTermDirection:d,longTermDirection:g}}calculateTimeWindowDirection(e,t,n){if(e.length===0||t<1)return"stable";const r=Math.min(n,Math.max(t,e.length)),o=e.slice(-r);if(o.length===0)return"stable";let i=0,s=0,c=0;for(const u of o)u.direction==="up"?i++:u.direction==="down"?s++:u.direction==="stable"&&c++;return this.determineOverallDirectionFromCounts(i,s,c)}determineOverallDirectionFromCounts(e,t,n){const r=e+t+n;if(r===0)return"stable";const o=r*.2,i=e-t;return Math.abs(i)<=o?"mixed":e>t?"ascending":t>e?"descending":"stable"}buildSegments(e){if(e.length===0)return[];const t=[];let n=null;for(const r of e){const o=r.direction;if(o==="none"){n&&(t.push({startTime:n.startTime,endTime:n.endTime,startPitch:n.startPitch,endPitch:n.endPitch,direction:n.direction,interval:Math.abs(n.endMidi-n.startMidi)}),n=null);continue}if(!n||n.direction!==o){n&&t.push({startTime:n.startTime,endTime:n.endTime,startPitch:n.startPitch,endPitch:n.endPitch,direction:n.direction,interval:Math.abs(n.endMidi-n.startMidi)});const i=r.pitch?.noteName??"N/A",s=r.pitch?.midiNote??60;n={startTime:r.timestamp,endTime:r.timestamp,startPitch:i,endPitch:i,direction:o,startMidi:s,endMidi:s}}else{const i=r.pitch?.midiNote??n.endMidi,s=r.pitch?.noteName??n.endPitch;n.endTime=r.timestamp,n.endPitch=s,n.endMidi=i}}return n&&t.push({startTime:n.startTime,endTime:n.endTime,startPitch:n.startPitch,endPitch:n.endPitch,direction:n.direction,interval:Math.abs(n.endMidi-n.startMidi)}),t}calculateStatistics(e){const t={up:0,down:0,stable:0,none:0},n={unison:0,small:0,medium:0,large:0,very_large:0};let r=0,o=0;for(const i of e)i.pitch?.isVoiced&&r++,t[i.direction]++,i.direction!=="none"&&o++,i.intervalCategory&&n[i.intervalCategory]++;return{directionStats:t,intervalStats:n,metadata:{totalBeats:e.length,voicedBeats:r,directionCalculatedBeats:o}}}}const Qn={algorithm:"pitch_melodia",minFrequency:80,maxFrequency:2e4,sampleRate:44100,hopSize:1024,crepeModelUrl:Se,resolveUrl:K.arweaveGatewayManager.resolveUrl.bind(K.arweaveGatewayManager),includeContour:!0,onProgress:void 0},Xn=69,er=440,tr=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"];class nr{constructor(e={}){this.config={...Qn,...e}}getConfig(){return{...this.config}}async analyze(e){const{onProgress:t}=this.config;t?.("fetching",0);const{signal:n,sampleRate:r,duration:o}=await this.fetchAndDecodeAudio(e);t?.("fetching",1),t?.("detecting",0);const i=this.resolveDefaults(this.config),s=await this.detectPitch(n,r,i);t?.("detecting",1);const c=this.computeSummary(s);let u,f,d;if(this.config.includeContour!==!1){const g=this.computeContour(s);u=g.contour,f=g.directionStats,d=g.intervalStats}return{pitchResults:s,contour:u,voicingRatio:c.voicingRatio,averageFrequency:c.averageFrequency,medianFrequency:c.medianFrequency,minFrequency:c.minFrequency,maxFrequency:c.maxFrequency,pitchRangeSemitones:c.pitchRangeSemitones,lowestNote:c.lowestNote,highestNote:c.highestNote,noteDistribution:c.noteDistribution,totalFrames:c.totalFrames,voicedFrames:c.voicedFrames,directionStats:f,intervalStats:d,analysis_metadata:{algorithm_used:this.config.algorithm,analyzed_at:new Date().toISOString(),duration_analyzed:o}}}async fetchAndDecodeAudio(e){const t=this.config.resolveUrl?await this.config.resolveUrl(e):e,n=await fetch(t);if(!n.ok)throw new Error(`Failed to fetch audio: ${n.statusText}`);const r=await n.arrayBuffer(),o=globalThis.AudioContext||globalThis.window?.AudioContext;if(!o)throw new Error("AudioContext not available in this environment");const i=new o,s=await new Promise((u,f)=>{i.decodeAudioData(r,u,f)}),c=new Float32Array(s.length);for(let u=0;u<s.numberOfChannels;u++){const f=s.getChannelData(u);for(let d=0;d<s.length;d++)c[d]+=f[d]/s.numberOfChannels}return{signal:c,sampleRate:s.sampleRate,duration:s.duration}}resolveDefaults(e){const t={...e};return e.maxFrequency===void 0&&(e.algorithm==="pyin_legacy"?t.maxFrequency=1e3:t.maxFrequency=2e4),t}async detectPitch(e,t,n){const r=n.algorithm??"pitch_melodia";return r==="pyin_legacy"?new x.PitchDetector({minFrequency:n.minFrequency??80,maxFrequency:n.maxFrequency??1e3,targetSampleRate:n.sampleRate??44100,hopSize:n.hopSize??1024}).detectSignal(e,t):(await he.create({algorithm:r,minFrequency:n.minFrequency??80,maxFrequency:n.maxFrequency??2e4,targetSampleRate:n.sampleRate??44100,hopSize:n.hopSize??1024,crepeModelUrl:n.crepeModelUrl,resolveUrl:n.resolveUrl})).detectSignal(e,t)}computeSummary(e){const t=e.length,n=e.filter(N=>N.isVoiced&&N.frequency>0),r=n.length;if(r===0)return{voicingRatio:0,averageFrequency:0,medianFrequency:0,minFrequency:0,maxFrequency:0,pitchRangeSemitones:0,lowestNote:null,highestNote:null,noteDistribution:[],totalFrames:t,voicedFrames:0};const o=n.map(N=>N.frequency),i=[...o].sort((N,k)=>N-k),s=o.reduce((N,k)=>N+k,0)/o.length,c=Math.floor(i.length/2),u=i.length%2!==0?i[c]:(i[c-1]+i[c])/2,f=i[0],d=i[i.length-1],g=this.frequencyToMidi(f),b=this.frequencyToMidi(d),S=Math.abs(b-g),R=this.midiToNoteName(Math.round(g)),I=this.midiToNoteName(Math.round(b)),A=new Map;for(const N of n)N.noteName&&A.set(N.noteName,(A.get(N.noteName)??0)+1);const B=Array.from(A.entries()).map(([N,k])=>({note:N,count:k,percentage:k/r*100})).sort((N,k)=>k.count-N.count);return{voicingRatio:r/t,averageFrequency:s,medianFrequency:u,minFrequency:f,maxFrequency:d,pitchRangeSemitones:S,lowestNote:R,highestNote:I,noteDistribution:B,totalFrames:t,voicedFrames:r}}computeContour(e){const t=e.filter(A=>A.isVoiced&&A.midiNote!==null);if(t.length===0)return{contour:{direction:"stable",range:{minNote:"N/A",maxNote:"N/A",semitones:0},segments:[],shortTermDirection:"stable",mediumTermDirection:"stable",longTermDirection:"stable"},directionStats:{up:0,down:0,stable:0,none:e.length},intervalStats:{unison:0,small:0,medium:0,large:0,very_large:0}};const n=t.map(A=>A.midiNote).filter(A=>A!==null),r=Math.min(...n),o=Math.max(...n),i=this.midiToNoteName(r),s=this.midiToNoteName(o),c={up:0,down:0,stable:0,none:0},u={unison:0,small:0,medium:0,large:0,very_large:0},f=[];let d=null,g=null;for(const A of t){const B=A.midiNote;if(B===null){c.none++;continue}if(g===null){g=B;continue}let N;const k=Math.abs(B-g);B>g?(N="up",c.up++):B<g?(N="down",c.down++):(N="stable",c.stable++);const C=St(k);u[C]++,!d||d.direction!==N?(d&&f.push({startTime:d.startTime,endTime:d.endTime,startNote:d.startNote,endNote:d.endNote,direction:d.direction,interval:Math.abs(d.endMidi-d.startMidi)}),d={startTime:A.timestamp,endTime:A.timestamp,startNote:this.midiToNoteName(g),endNote:this.midiToNoteName(B),direction:N,startMidi:g,endMidi:B}):(d.endTime=A.timestamp,d.endNote=this.midiToNoteName(B),d.endMidi=B),g=B}d&&f.push({startTime:d.startTime,endTime:d.endTime,startNote:d.startNote,endNote:d.endNote,direction:d.direction,interval:Math.abs(d.endMidi-d.startMidi)});const b=this.determineOverallDirection(f),S=this.calculateTimeWindowDirection(e,1,2),R=this.calculateTimeWindowDirection(e,4,8),I=this.calculateTimeWindowDirection(e,16,1/0);return{contour:{direction:b,range:{minNote:i,maxNote:s,semitones:o-r},segments:f,shortTermDirection:S,mediumTermDirection:R,longTermDirection:I},directionStats:c,intervalStats:u}}determineOverallDirection(e){if(e.length===0)return"stable";let t=0,n=0,r=0;for(const c of e)c.direction==="up"?t++:c.direction==="down"?n++:r++;if(t===0&&n===0)return"stable";const o=t-n,s=(t+n+r)*.2;return Math.abs(o)<=s?"mixed":t>n?"ascending":n>t?"descending":"stable"}calculateTimeWindowDirection(e,t,n){const r=e.filter(d=>d.isVoiced&&d.midiNote!==null);if(r.length===0||t<1)return"stable";const o=Math.min(n,Math.max(t,r.length)),i=r.slice(-o);if(i.length===0)return"stable";let s=0,c=0,u=0,f=null;for(const d of i){const g=d.midiNote;g!==null&&(f!==null&&(g>f?s++:g<f?c++:u++),f=g)}return this.determineOverallDirectionFromCounts(s,c,u)}determineOverallDirectionFromCounts(e,t,n){const r=e+t+n;if(r===0)return"stable";const o=r*.2,i=e-t;return Math.abs(i)<=o?"mixed":e>t?"ascending":t>e?"descending":"stable"}frequencyToMidi(e){return Xn+12*Math.log2(e/er)}midiToNoteName(e){const t=Math.floor(e/12)-1,n=Math.round(e)%12;return`${tr[n]}${t}`}}const Ct={up:{ascending:{unison:"up",small:"up",medium:"right",large:"right",very_large:"left"},descending:{unison:"up",small:"left",medium:"right",large:"down",very_large:"down"},stable:"up"},right:{ascending:{unison:"right",small:"up",medium:"up",large:"up",very_large:"left"},descending:{unison:"right",small:"down",medium:"down",large:"down",very_large:"left"},stable:"right"},down:{ascending:{unison:"down",small:"left",medium:"right",large:"up",very_large:"up"},descending:{unison:"down",small:"down",medium:"left",large:"left",very_large:"right"},stable:"down"},left:{ascending:{unison:"left",small:"up",medium:"up",large:"up",very_large:"right"},descending:{unison:"left",small:"down",medium:"down",large:"down",very_large:"right"},stable:"left"}},rr={up:{ascending:"up",descending:"left",stable:"up"},right:{ascending:"up",descending:"down",stable:"right"},down:{ascending:"right",descending:"down",stable:"down"},left:{ascending:"up",descending:"down",stable:"left"}},Et={1:{ascending:{unison:1,small:2,medium:2,large:3,very_large:3},descending:{unison:1,small:4,medium:4,large:3,very_large:3},stable:1},2:{ascending:{unison:2,small:3,medium:3,large:4,very_large:4},descending:{unison:2,small:1,medium:1,large:4,very_large:4},stable:2},3:{ascending:{unison:3,small:4,medium:4,large:5,very_large:5},descending:{unison:3,small:2,medium:2,large:1,very_large:1},stable:3},4:{ascending:{unison:4,small:5,medium:5,large:2,very_large:2},descending:{unison:4,small:3,medium:3,large:2,very_large:1},stable:4},5:{ascending:{unison:5,small:2,medium:2,large:3,very_large:3},descending:{unison:5,small:4,medium:4,large:3,very_large:2},stable:5}},ir={1:{ascending:2,descending:1,stable:1},2:{ascending:3,descending:1,stable:2},3:{ascending:4,descending:2,stable:3},4:{ascending:5,descending:3,stable:4},5:{ascending:5,descending:4,stable:5}};function Dt(v){return v.intervalCategory??"small"}function or(v,e,t){const n=e??"left";if(v.direction==="stable"||v.intervalCategory==="unison")return n;if(t==="easy"){const s=rr[n];return v.direction==="up"?s.ascending:s.descending}const r=Ct[n],o=v.direction==="up"?"ascending":"descending",i=Dt(v);return r[o][i]}function ar(v,e,t){const n=e??3;if(v.direction==="stable"||v.intervalCategory==="unison")return n;if(t==="easy"){const s=ir[n];return v.direction==="up"?s.ascending:s.descending}const r=Et[n],o=v.direction==="up"?"ascending":"descending",i=Dt(v);return r[o][i]}function sr(v,e,t,n){const r=new Map;if(e)for(const c of e){const u=Math.round(c.timestamp*1e3);r.set(u,c)}const o=[],i=[];let s=null;for(const c of v){const u=Math.round(c.timestamp*1e3);let f=null;for(let b=-2;b<=2&&(f=r.get(u+b)??null,!f);b++);let d=null,g=0;f&&f.direction!=="none"&&(d=t==="ddr"?or(f,s,n):ar(f,s,n),g=f.pitch?.probability??.5),o.push(d),i.push(g),s=d}return{pitchKeys:o,probabilities:i}}function cr(v){const e=[];let t=-1;for(let n=0;n<=v.length;n++){const r=n<v.length&&v[n]===null;if(r&&t===-1)t=n;else if(!r&&t!==-1){const o=t>0?v[t-1]:null,i=n<v.length?v[n]:null;e.push({startIndex:t,endIndex:n,length:n-t,previousKey:o,nextKey:i}),t=-1}}return e}function ye(v,e,t,n,r){if(v.keys.length===0||t+v.keys.length>e.length)return!1;const o=v.keys[0],i=v.keys[v.keys.length-1];if(n!==null&&o===n)return!1;if(r!==null){if(typeof i=="string"&&typeof r=="string"&&!le[i]?.includes(r)&&i!==r)return!1;if(typeof i=="number"&&typeof r=="number"){if(n!==null&&typeof n=="number"){if(!(n<r&&i>=n&&i<=r||n>r&&i<=n&&i>=r)&&i!==r)return!1}else if(Math.abs(i-r)>1)return!1}}return!0}function lr(v,e,t,n,r){const o=[],i=e.filter(g=>g.difficulty<=t&&g.keys.length>0);i.sort((g,b)=>b.keys.length-g.keys.length);const s=i[0]?.controllerMode??"ddr";let c=0,u=v.previousKey,f=null,d=null;for(;c<v.length;){const g=v.length-c;let b;const S=i.filter(R=>R.keys.length===g);if(b=ze(S,v,c,u,v.nextKey,f,d,n,r),!b){const R=i.filter(I=>I.keys.length<=g);b=ze(R,v,c,u,null,f,d,n,r)}if(!b){const R=i.filter(I=>I.keys.length<=g);b=ze(R,v,c,u,null,null,null,null,r)}if(b)o.push({pattern:b,startIndex:v.startIndex+c,filledLength:b.keys.length}),u=b.keys[b.keys.length-1],f=b.id,d=b.category,c+=b.keys.length;else{const R=c===v.length-1?v.nextKey:null,I=Tt(u,R);o.push({pattern:{id:"__interpolated__",name:"Interpolated",controllerMode:s,keys:[I],measures:0,tags:["interpolated"],category:"transition",difficulty:1},startIndex:v.startIndex+c,filledLength:1}),u=I,c++}}return o}function ze(v,e,t,n,r,o,i,s,c=Math.random){const u=v.filter(b=>ye(b,e,t,n,r)&&b.id!==o&&b.category!==i&&!s?.has(b.id));if(u.length>0)return ve(u,c);const f=v.filter(b=>ye(b,e,t,n,r)&&b.id!==o&&!s?.has(b.id));if(f.length>0)return ve(f,c);const d=v.filter(b=>ye(b,e,t,n,r)&&b.id!==o);if(d.length>0)return ve(d,c);const g=v.filter(b=>ye(b,e,t,n,r));if(g.length>0)return ve(g,c)}function ve(v,e=Math.random){const t=v[0].keys.length,n=v.filter(r=>r.keys.length===t);return n[Math.floor(e()*n.length)]}function ur(v,e,t){const n=v.length,r=[...v],o=new Array(n).fill(void 0);for(let i=0;i<e.length;i++){const s=t[i];for(const c of s)for(let u=0;u<c.filledLength;u++){const f=c.startIndex+u;if(f>=n)break;r[f]=c.pattern.keys[u],o[f]=c.pattern.id}}for(let i=0;i<n;i++)if(r[i]===null){const s=i>0?r[i-1]:null,c=i<n-1?r[i+1]:null;r[i]=Tt(s,c)}return{keys:r,patternIds:o}}function dr(v,e){const t=[];if(e<=0||v.length===0)return{positions:t};let n=1;const r=v[0];for(let o=1;o<v.length;o++)v[o]===r?(n++,n>e&&t.push(o)):n=1;return{positions:t}}function hr(v,e,t,n=Math.random){const r=e.filter(s=>s.difficulty<=t);if(r.length===0)return v;const o=r.filter(s=>s.keys[0]!==v),i=o.length>0?o:r;return i[Math.floor(n()*i.length)].keys[0]}const le={up:["left","right"],down:["left","right"],left:["up","down"],right:["up","down"]};function Tt(v,e){if(v===null)return e===null?typeof e=="string"?"left":3:typeof e=="string"?le[e][0]:Math.max(1,e-1);if(e===null)return v;if(typeof v=="string"&&typeof e=="string"){const t=v,n=e;if(t===n)return v;if(le[t].includes(n))return e;const o=le[t],i=le[n];for(const s of o)if(i.includes(s))return s;return o[0]}if(typeof v=="number"&&typeof e=="number"){const t=v,n=e;return t===n?v:n>t?Math.min(5,t+1):Math.max(1,t-1)}return v}class be{constructor(e){this.config=x.mergeButtonMappingConfig(e);const t=x.validateButtonMappingConfig(this.config);if(!t.valid)throw new Error(`Invalid button mapping config: ${t.errors.join(", ")}`)}seededRandom(e){return this.config.seed?x.hashSeedToFloat(x.deriveSeed(this.config.seed,e)):Math.random()}getConfig(){return{...this.config}}mapVariant(e,t,n){const r=this.mapButtons(e,n,e.difficulty),o=this.buildMetadata(r,n),i=new Map,s=new Map,c=new Map;for(const u of r)i.set(u.beatIndex,String(u.key)),s.set(u.beatIndex,u.source),c.set(u.beatIndex,u.patternId);return{variant:e,rhythmMetadata:t,buttonMetadata:o,keyAssignments:i,mappingSources:s,mappingPatternIds:c}}map(e,t,n){const r=e.difficultyVariants[t];return this.mapVariant(r,e.metadata,n)}mapAll(e,t){return{easy:this.map(e,"easy",t),medium:this.map(e,"medium",t),hard:this.map(e,"hard",t)}}mapButtons(e,t,n){const r=e.beats;if(this.config.controllerMode==="tap")return r.map((B,N)=>({beatIndex:N,timestamp:B.timestamp,key:"tap",source:"pattern",patternId:void 0,probability:void 0}));const o=[],i=this.getMaxPatternDifficulty(n);let s=0;const{pitchKeys:c,probabilities:u}=sr(r,t,this.config.controllerMode,n),f=this.classifyPitchVsPattern(c,u,this.config.pitchInfluenceWeight),d=c.map((B,N)=>B!==null&&f[N]?B:null),g=this.config.controllerMode==="ddr"?x.DDR_PATTERN_LIBRARY.patterns:x.GUITAR_HERO_PATTERN_LIBRARY.patterns,b=cr(d),S=new Set,R=b.map((B,N)=>{const k=lr(B,g,i,S,()=>this.seededRandom(`run:${N}:pick:${s++}`));for(const C of k)C.pattern.id!=="__interpolated__"&&S.add(C.pattern.id);return k}),{keys:I,patternIds:A}=ur(d,b,R);for(let B=0;B<r.length;B++){const N=d[B]!==null;o.push({beatIndex:B,timestamp:r[B].timestamp,key:I[B],source:N?"pitch":"pattern",patternId:N?void 0:A[B],probability:u[B]})}return this.config.consecutiveSameKeyLimit>0&&this.applyConsecutiveLimit(o,g,i),o}classifyPitchVsPattern(e,t,n){const r=new Array(e.length).fill(!1),o=e.map((c,u)=>({index:u,probability:t[u],hasPitch:c!==null})).filter(c=>c.hasPitch);o.sort((c,u)=>c.probability-u.probability);const i=Math.floor(o.length*(1-n)),s=new Set(o.slice(0,i).map(c=>c.index));for(let c=0;c<e.length;c++)e[c]===null||s.has(c)?r[c]=!1:r[c]=!0;return r}getMaxPatternDifficulty(e){switch(e){case"easy":return 3;case"medium":return 6;case"hard":return 10;case"natural":return 10;case"custom":return 6}}applyConsecutiveLimit(e,t,n){const r=e.map(s=>s.key),o=this.config.consecutiveSameKeyLimit,{positions:i}=dr(r,o);for(let s=0;s<i.length;s++){const c=i[s],u=hr(e[c].key,t,n,()=>this.seededRandom(`var:${c}:${s}`));u!==e[c].key&&(e[c].key=u,e[c].source="pattern",e[c].patternId="consecutive_limit_fix")}}buildMetadata(e,t){const n=new Set,r=new Map;let o=0,i=0;const s=new Set;for(const S of e){const R=String(S.key);n.add(R),r.set(R,(r.get(R)??0)+1),S.source==="pitch"?o++:i++,S.patternId&&s.add(S.patternId)}let c,u,f;if(t&&t.length>0){c={up:0,down:0,stable:0,none:0},u={unison:0,small:0,medium:0,large:0,very_large:0},f={low:0,mid:0,high:0};for(const S of t)c[S.direction]++,S.intervalCategory&&u[S.intervalCategory]++,S.band&&f[S.band]++}const d=[];let g,b=0;for(let S=0;S<e.length;S++){const R=e[S].patternId;R&&R===g||(g&&d.push({patternId:g,startIndex:b,length:S-b}),g=R,b=S)}return g&&d.push({patternId:g,startIndex:b,length:e.length-b}),{controllerMode:this.config.controllerMode,keysUsed:Array.from(n),pitchInfluencedBeats:o,patternInfluencedBeats:i,patternsUsed:Array.from(s),buttonDistribution:r,directionStats:c,intervalStats:u,bandStats:f,patternPlacements:d}}static getDDRTransitions(){return Ct}static getGuitarHeroTransitions(){return Et}getAvailableButtons(){return this.config.controllerMode==="ddr"?["up","down","left","right"]:[1,2,3,4,5]}isValidButton(e){return this.config.controllerMode==="ddr"?["up","down","left","right"].includes(e):[1,2,3,4,5].includes(e)}}class Ce{convertToChartedBeatMap(e,t,n,r,o,i){const s=[],c=[];for(let f=0;f<e.beats.length;f++){const d=e.beats[f],g=this.convertBeat(d,t,n.get(f),f,o?.get(f),i?.get(f));s.push(g),g.isDetected&&c.push(f)}const u=this.buildChartMetadata(e,r,s,n);return{audioId:t.audioId,duration:t.duration,beats:s,detectedBeatIndices:c,downbeatConfig:t.downbeatConfig,quarterNoteInterval:t.quarterNoteInterval,bpm:t.quarterNoteBpm,chartMetadata:u}}convertWithOptions(e,t){const n={version:"1.0.0",algorithm:"procedural-generation",minBpm:60,maxBpm:200,sensitivity:1,filter:.5,noiseFloorThreshold:.01,hopSizeMs:10,fftSize:2048,dpAlpha:.5,melBands:40,highPassCutoff:80,gaussianSmoothMs:20,tempoCenter:.5,tempoWidth:.5,useOctaveResolution:!1,useTripleMeter:!1,generatedAt:new Date().toISOString()},r={audioId:t.audioId,duration:t.duration,beats:[],detectedBeatIndices:[],quarterNoteInterval:t.quarterNoteInterval,quarterNoteBpm:60/t.quarterNoteInterval,downbeatConfig:t.downbeatConfig,originalMetadata:n};return this.convertToChartedBeatMap(e,r,t.keyAssignments,t.metadata)}convertBeat(e,t,n,r,o,i){const s=e.beatIndex,c=this.getParentBeat(t,s),u=this.calculateBeatInMeasure(c,e.gridPosition,e.gridType),f=this.isBeatDetected(e),d=this.mapGridToSubdivision(e.gridType),g=this.calculateConfidence(e,f);return{timestamp:e.timestamp,beatInMeasure:u,isDownbeat:(c?.isDownbeat??!1)&&e.gridPosition===0,measureNumber:c?.measureNumber??0,intensity:e.intensity,confidence:g,requiredKey:n,quarterNoteIndex:s,subdivisionPosition:e.gridPosition,isDetected:f,subdivisionType:d,sourceBand:e.sourceBand,quantizationError:e.quantizationError,mappingSource:o,patternId:i}}getParentBeat(e,t){return t<0||t>=e.beats.length?null:e.beats[t]}calculateBeatInMeasure(e,t,n){const r=e?.beatInMeasure??0;return x.calculateBeatInMeasure(r,t,n)}isBeatDetected(e){return e.quantizationError===void 0?!0:e.quantizationError<10}mapGridToSubdivision(e){return x.mapGridToSubdivision(e)}calculateConfidence(e,t){return t?Math.min(1,.8+e.intensity*.2):.8}buildChartMetadata(e,t,n,r){const o=t.pitchInfluencedBeats??0,i=this.getUniqueKeys(n);return this.getSubdivisionTypesUsed(n),{difficulty:e.difficulty,keysUsed:i,pitchInfluencedBeats:o,patternsUsed:t.patternsUsed??[],rhythmMetadata:t.rhythmMetadata??this.createDefaultRhythmMetadata(e),pitchMetadata:t.pitchMetadata??null,generatedAt:t.generatedAt??new Date().toISOString(),seed:t.seed}}getUniqueKeys(e){const t=new Set;for(const n of e)n.requiredKey!==void 0&&t.add(n.requiredKey);return Array.from(t).sort()}getSubdivisionTypesUsed(e){const t=new Set;for(const n of e)t.add(n.subdivisionType);return Array.from(t)}createDefaultRhythmMetadata(e){return{difficulty:e.difficulty,bandsAnalyzed:["low","mid","high"],transientsDetected:e.beats.length,averageDensity:e.beats.length/180,naturalDifficulty:e.difficulty}}static fromMappedResult(e,t,n,r,o,i,s){const c=o??new Map;if(c.size===0&&n.keysUsed.length>0)for(let b=0;b<e.beats.length;b++)c.set(b,n.keysUsed[b%n.keysUsed.length]);const u=new Ce,f={difficulty:r.difficulty,bandsAnalyzed:r.bandsAnalyzed,transientsDetected:r.transientsDetected,averageDensity:r.averageDensity,naturalDifficulty:r.naturalDifficulty},d=n.directionStats?{melodyRange:null,directionStats:n.directionStats,intervalStats:n.intervalStats??null}:null,g={difficulty:e.difficulty,keysUsed:n.keysUsed,pitchInfluencedBeats:n.pitchInfluencedBeats,patternsUsed:n.patternsUsed,rhythmMetadata:f,pitchMetadata:d,generatedAt:new Date().toISOString()};return u.convertToChartedBeatMap(e,t,c,g,i,s)}}const ce={difficulty:"medium",controllerMode:"ddr",rhythm:{},buttons:{},enableCache:!0,cacheMaxAge:1800*1e3};class Ee{constructor(e={}){this.cache=new Map,this.cacheHits=0,this.cacheMisses=0,this.options={...ce,...e,rhythm:{...ce.rhythm,...e.rhythm},buttons:{...ce.buttons,...e.buttons}},this.buttonConfig=x.mergeButtonMappingConfig({...this.options.buttons,difficulty:this.options.difficulty,controllerMode:this.options.controllerMode,seed:this.options.seed})}getOptions(){return{...this.options}}generateCacheKey(e,t,n){return`${e}:${t}:${n}`}createConfigFingerprint(e){const t=this.options.rhythm||{};return e==="rhythm"?JSON.stringify({measureStartOffset:t.measureStartOffset,minimumTransientIntensity:t.minimumTransientIntensity,seed:t.seed}):e==="pitch"?JSON.stringify({pitchAlgorithm:this.options.pitchAlgorithm,crepeModelUrl:this.options.crepeModelUrl,voicingThreshold:this.options.voicingThreshold}):"default"}getFromCache(e){if(!this.options.enableCache)return null;const t=this.cache.get(e);if(!t)return this.cacheMisses++,null;const n=Date.now()-t.timestamp,r=this.options.cacheMaxAge??ce.cacheMaxAge;return n>r?(this.cache.delete(e),this.cacheMisses++,null):(this.cacheHits++,t.result)}setCache(e,t){this.options.enableCache&&this.cache.set(e,{result:t,timestamp:Date.now(),key:e})}clearCache(){this.cache.clear(),this.cacheHits=0,this.cacheMisses=0}pruneExpiredCache(){const e=Date.now(),t=this.options.cacheMaxAge??ce.cacheMaxAge;for(const[n,r]of this.cache.entries())e-r.timestamp>t&&this.cache.delete(n)}getCacheStats(){const e=[];for(const[t]of this.cache.entries()){const n=t.split(":")[1];e.includes(n)||e.push(n)}return{entryCount:this.cache.size,cachedPhases:e,hits:this.cacheHits,misses:this.cacheMisses}}isCached(e,t){const n=this.createConfigFingerprint(t),r=this.generateCacheKey(e,t,n);return this.cache.has(r)}getCacheHitRatio(){const e=this.cacheHits+this.cacheMisses;return e===0?0:this.cacheHits/e}async generate(e,t,n,r){const o=(g,b,S)=>{n?.({stage:g,progress:b,message:S})};r?.throwIfAborted();const i=t.audioId;o("rhythm",0,"Starting rhythm generation...");let s=null;if(this.options.cachedRhythm)s=this.options.cachedRhythm,o("rhythm",1,"Using pre-generated rhythm from store");else{const g=this.generateCacheKey(i,"rhythm",this.createConfigFingerprint("rhythm"));s=this.getFromCache(g),s?o("rhythm",1,"Rhythm loaded from cache"):(s=await this.generateRhythm(e,t,(b,S,R)=>{o("rhythm",S,`[${b}] ${R}`)},r),this.setCache(g,s),o("rhythm",1,"Rhythm generation complete"))}r?.throwIfAborted();let c=null;if(this.buttonConfig.pitchInfluenceWeight>0&&this.buttonConfig.controllerMode!=="tap"){const g=this.generateCacheKey(i,"pitch",this.createConfigFingerprint("pitch"));c=this.getFromCache(g),c?o("pitch",1,"Pitch analysis loaded from cache"):(o("pitch",0,"Starting pitch analysis..."),c=await this.analyzePitch(e,s,(b,S)=>{o("pitch",b,S)}),this.setCache(g,c),o("pitch",1,"Pitch analysis complete"))}else o("pitch",1,"Pitch analysis skipped");r?.throwIfAborted(),o("buttons",0,"Starting button mapping...");const u=this.mapButtons(s,c);o("buttons",1,"Button mapping complete"),r?.throwIfAborted(),o("conversion",0,"Converting to playable chart...");const f=this.convertToChart(u,t);o("conversion",1,"Chart conversion complete"),r?.throwIfAborted(),o("finalizing",0,"Finalizing level...");const d=this.buildLevel(f,u,s,c);return o("finalizing",1,"Level generation complete"),d}async generateAllDifficulties(e,t,n,r){const o=["easy","medium","hard","natural"],i={easy:null,medium:null,hard:null,natural:null};r?.throwIfAborted();const s=t.audioId;let c=null;if(this.options.cachedRhythm)c=this.options.cachedRhythm;else{const f=this.generateCacheKey(s,"rhythm",this.createConfigFingerprint("rhythm"));c=this.getFromCache(f),c||(c=await this.generateRhythm(e,t,void 0,r),this.setCache(f,c))}r?.throwIfAborted();let u=null;if(this.buttonConfig.pitchInfluenceWeight>0&&this.buttonConfig.controllerMode!=="tap"){const f=this.generateCacheKey(s,"pitch",this.createConfigFingerprint("pitch"));u=this.getFromCache(f),u||(u=await this.analyzePitch(e,c),this.setCache(f,u))}r?.throwIfAborted();for(let f=0;f<o.length;f++){const d=o[f];n?.({stage:"buttons",progress:f/o.length,message:`Generating ${d} chart...`}),r?.throwIfAborted();const g=new Ee({...this.options,difficulty:d,buttons:{...this.options.buttons,difficulty:d}}),b=g.mapButtons(c,u),S=g.convertToChart(b,t),R=g.buildLevel(S,b,c,u);i[d]=R}return{easy:i.easy,medium:i.medium,hard:i.hard,natural:i.natural}}async generateAtDensity(e,t,n,r,o){const i=(A,B,N)=>{r?.({stage:A,progress:B,message:N})};o?.throwIfAborted();const s=t.audioId;i("rhythm",0,"Starting rhythm generation...");let c=null;if(this.options.cachedRhythm)c=this.options.cachedRhythm,i("rhythm",1,"Using pre-generated rhythm from store");else{const A=this.generateCacheKey(s,"rhythm",this.createConfigFingerprint("rhythm"));c=this.getFromCache(A),c?i("rhythm",1,"Rhythm loaded from cache"):(c=await this.generateRhythm(e,t,(B,N,k)=>{i("rhythm",N,`[${B}] ${k}`)},o,!0),this.setCache(A,c),i("rhythm",1,"Rhythm generation complete"))}o?.throwIfAborted(),i("buttons",0,"Generating density-based variant...");const u=this.collectGridDecisions(c.analysis.quantizationResult),d=new x.DifficultyVariantGenerator({seed:this.options.seed}).generateAtDensity(c.composite,n,t,c.analysis.phraseAnalysis,u);i("buttons",.3,"Density variant generated");let g=null;if(this.buttonConfig.pitchInfluenceWeight>0&&this.buttonConfig.controllerMode!=="tap"){const A=this.generateCacheKey(s,"pitch",this.createConfigFingerprint("pitch"));g=this.getFromCache(A),g?i("pitch",.5,"Pitch analysis loaded from cache"):(i("pitch",0,"Starting pitch analysis..."),g=await this.analyzePitch(e,c,(B,N)=>{i("pitch",B,N)}),this.setCache(A,g),i("pitch",1,"Pitch analysis complete"))}else i("pitch",1,"Pitch analysis skipped");o?.throwIfAborted(),i("buttons",.6,"Mapping buttons...");const S=new be(this.buttonConfig).mapVariant(d,c.metadata,g?.pitchByBeat);i("buttons",1,"Button mapping complete"),o?.throwIfAborted(),i("conversion",0,"Converting to playable chart...");const R=this.convertToChart(S,t);i("conversion",1,"Chart conversion complete"),o?.throwIfAborted(),i("finalizing",0,"Finalizing level...");const I=this.buildLevel(R,S,c,g,"custom");return i("finalizing",1,"Level generation complete"),I}async generateAtDensities(e,t,n,r,o){const i=new Map;o?.throwIfAborted();const s=t.audioId;r?.({stage:"rhythm",progress:0,message:"Starting rhythm generation..."});let c=null;if(this.options.cachedRhythm)c=this.options.cachedRhythm,r?.({stage:"rhythm",progress:1,message:"Using pre-generated rhythm from store"});else{const g=this.generateCacheKey(s,"rhythm",this.createConfigFingerprint("rhythm"));c=this.getFromCache(g),c?r?.({stage:"rhythm",progress:1,message:"Rhythm loaded from cache"}):(c=await this.generateRhythm(e,t,void 0,o,!0),this.setCache(g,c),r?.({stage:"rhythm",progress:1,message:"Rhythm generation complete"}))}o?.throwIfAborted();let u=null;if(this.buttonConfig.pitchInfluenceWeight>0&&this.buttonConfig.controllerMode!=="tap"){const g=this.generateCacheKey(s,"pitch",this.createConfigFingerprint("pitch"));u=this.getFromCache(g),u?r?.({stage:"pitch",progress:1,message:"Pitch analysis loaded from cache"}):(r?.({stage:"pitch",progress:0,message:"Starting pitch analysis..."}),u=await this.analyzePitch(e,c),this.setCache(g,u),r?.({stage:"pitch",progress:1,message:"Pitch analysis complete"}))}o?.throwIfAborted();const f=this.collectGridDecisions(c.analysis.quantizationResult),d=new x.DifficultyVariantGenerator({seed:this.options.seed});for(let g=0;g<n.length;g++){const{label:b,config:S}=n[g];r?.({stage:"buttons",progress:g/n.length,message:`Generating ${b} density variant...`}),o?.throwIfAborted();const R=d.generateAtDensity(c.composite,S,t,c.analysis.phraseAnalysis,f),A=new be(this.buttonConfig).mapVariant(R,c.metadata,u?.pitchByBeat),B=this.convertToChart(A,t),N=this.buildLevel(B,A,c,u,"custom");i.set(b,N)}return r?.({stage:"finalizing",progress:1,message:"All density variants generated"}),i}collectGridDecisions(e){const t=new Map,n=[...e.streams.low.gridDecisions,...e.streams.mid.gridDecisions,...e.streams.high.gridDecisions];for(const r of n){const o=t.get(r.beatIndex);(!o||r.confidence>o.confidence)&&t.set(r.beatIndex,r)}return t}async generateRhythm(e,t,n,r,o){return await new x.RhythmGenerator({...this.options.rhythm,skipDifficultyVariants:o}).generate(e,t,r,n?(c,u,f)=>{n(c,u,f)}:void 0)}async analyzePitch(e,t,n){n?.(.1,"Linking pitch to beats...");const r={};this.options.pitchAlgorithm!==void 0&&(r.pitchAlgorithm=this.options.pitchAlgorithm),this.options.crepeModelUrl!==void 0&&(r.crepeModelUrl=this.options.crepeModelUrl),this.options.resolveUrl!==void 0&&(r.resolveUrl=this.options.resolveUrl),this.options.voicingThreshold!==void 0&&(r.pitchDetector={...r.pitchDetector,voicingThreshold:this.options.voicingThreshold});const o=new Mt(r),i=await o.linkWithComposite(t.composite,e);n?.(.4,"Analyzing melody contour...");const c=new Zn().analyze(i);n?.(.8,"Deriving variant pitches...");let u;if(!t.difficultyVariants)u=c.pitchByBeat;else{const f=this.options.difficulty==="custom"?"medium":this.options.difficulty;u=o.deriveVariantPitches(t.difficultyVariants[f],c.pitchByBeat)}return{...c,pitchByBeat:u}}mapButtons(e,t){const n=new be(this.buttonConfig),r=this.options.difficulty==="custom"?"medium":this.options.difficulty;return n.map(e,r,t?.pitchByBeat)}convertToChart(e,t){return Ce.fromMappedResult(e.variant,t,e.buttonMetadata,e.rhythmMetadata,e.keyAssignments,e.mappingSources,e.mappingPatternIds)}buildLevel(e,t,n,r,o){const i={difficulty:o??this.options.difficulty,controllerMode:this.options.controllerMode,rhythmMetadata:t.rhythmMetadata,buttonMetadata:t.buttonMetadata,pitchMetadata:r?{melodyRange:r.melodyContour.range.minNote!=="N/A"?{min:r.melodyContour.range.minNote,max:r.melodyContour.range.maxNote}:null,directionStats:r.directionStats,intervalStats:r.intervalStats}:null,chartMetadata:{totalBeats:e.beats.length,detectedBeats:e.detectedBeatIndices.length,generatedBeats:e.beats.length-e.detectedBeatIndices.length},generationConfig:this.options};return{chart:e,variant:t.variant,rhythm:n,pitchAnalysis:r,metadata:i}}}class fr{static toExportData(e,t={}){const{chart:n,metadata:r,pitchAnalysis:o}=e,i=this.buildDetectedBeats(n),s=this.buildMergedBeats(n),c=this.buildInterpolatedMetadata(n),u=this.buildSubdivisionData(n),f=this.buildChartExportData(n,r),d=this.buildGenerationMetadata(r,o);return{version:1,format:"full-beatmap",audioId:n.audioId,audioTitle:t.includeAudioTitle?t.audioTitle:void 0,exportedAt:Date.now(),duration:n.duration,quarterNoteBpm:n.bpm,quarterNoteConfidence:n.chartMetadata.rhythmMetadata.averageDensity,detectedBeats:i,mergedBeats:s,interpolatedMetadata:c,subdivision:u,chart:f,trackReference:t.trackReference,generationSource:"procedural",generationMetadata:d}}static buildDetectedBeats(e){const t=[],n=new Set(e.detectedBeatIndices);for(let r=0;r<e.beats.length;r++){const o=e.beats[r];n.has(r)&&t.push({timestamp:o.timestamp,beatInMeasure:o.beatInMeasure,isDownbeat:o.isDownbeat,measureNumber:o.measureNumber,intensity:o.intensity,confidence:o.confidence,requiredKey:o.requiredKey})}return t}static buildMergedBeats(e){const t=new Set(e.detectedBeatIndices);return e.beats.map((n,r)=>({timestamp:n.timestamp,beatInMeasure:n.beatInMeasure,isDownbeat:n.isDownbeat,measureNumber:n.measureNumber,intensity:n.intensity,confidence:n.confidence,requiredKey:n.requiredKey,source:t.has(r)?"detected":"interpolated",distanceToAnchor:n.quantizationError}))}static buildInterpolatedMetadata(e){const t=e.detectedBeatIndices.length,n=e.beats.length;return{quarterNoteInterval:e.quarterNoteInterval,quarterNoteBpm:e.bpm,quarterNoteConfidence:.9,detectedBeatCount:t,mergedBeatCount:n}}static buildSubdivisionData(e){const t=e.beats.map((s,c)=>this.chartedBeatToExportBeat(s,c,e.detectedBeatIndices)),n=new Set,r=[];t.forEach((s,c)=>{n.add(s.subdivisionType),r.push([c,s.subdivisionType])});const o={beatSubdivisions:r,defaultSubdivision:"sixteenth"},i={originalBeatCount:e.beats.length-e.detectedBeatIndices.length,subdividedBeatCount:e.beats.length,averageDensityMultiplier:1,explicitBeatCount:e.detectedBeatIndices.length};return{config:o,beats:t,metadata:i}}static chartedBeatToExportBeat(e,t,n){const r=n.includes(t);return{timestamp:e.timestamp,beatInMeasure:e.beatInMeasure,isDownbeat:e.isDownbeat,measureNumber:e.measureNumber,intensity:e.intensity,confidence:e.confidence,requiredKey:e.requiredKey,isDetected:r,originalBeatIndex:r?t:void 0,subdivisionType:e.subdivisionType,quarterNoteIndex:e.quarterNoteIndex,subdivisionPosition:e.subdivisionPosition,sourceBand:e.sourceBand,quantizationError:e.quantizationError}}static buildChartExportData(e,t){const n=e.beats.map(o=>o.requiredKey).filter(o=>o!==void 0),r=[...new Set(n)];return r.length===0?null:{style:t.controllerMode==="ddr"?"ddr":t.controllerMode==="guitar_hero"?"guitar":"tap",keyCount:r.length,usedKeys:r}}static buildGenerationMetadata(e,t){const n=e.rhythmMetadata;return{difficulty:e.difficulty,pitchInfluenceWeight:e.generationConfig.buttons?.pitchInfluenceWeight??1,patternsUsed:e.buttonMetadata.patternsUsed,controllerMode:e.controllerMode,seed:e.generationConfig.seed,generatedAt:new Date().toISOString(),directionStats:t?.directionStats??void 0,intervalStats:t?.intervalStats??void 0,rhythmMetadata:{difficulty:n.difficulty,bandsAnalyzed:n.bandsAnalyzed,transientsDetected:n.transientsDetected,averageDensity:n.averageDensity}}}static fromExportData(e){const t=this.validate(e);if(!t.success||!t.data)throw new Error(`Invalid export data: ${t.error??"Unknown error"}`);const n=t.data,r=this.reconstructChart(n),o=this.reconstructVariant(n,r),i=this.reconstructRhythm(n,r),s=this.reconstructPitchAnalysis(n),c=this.reconstructMetadata(n,r);return{chart:r,variant:o,rhythm:i,pitchAnalysis:s,metadata:c}}static reconstructChart(e){if(!e.subdivision)return this.reconstructChartFromMergedBeats(e);const t=e.subdivision.beats.map((i,s)=>({timestamp:i.timestamp,beatInMeasure:i.beatInMeasure,isDownbeat:i.isDownbeat,measureNumber:i.measureNumber,intensity:i.intensity,confidence:i.confidence,requiredKey:i.requiredKey,quarterNoteIndex:i.quarterNoteIndex??0,subdivisionPosition:i.subdivisionPosition??0,isDetected:i.isDetected,subdivisionType:i.subdivisionType,sourceBand:i.sourceBand??"mid",quantizationError:i.quantizationError})),n=e.subdivision.beats.map((i,s)=>i.isDetected?s:-1).filter(i=>i>=0),r=this.reconstructDownbeatConfig(t),o=this.reconstructChartMetadata(e);return{audioId:e.audioId,duration:e.duration,beats:t,detectedBeatIndices:n,downbeatConfig:r,quarterNoteInterval:e.interpolatedMetadata.quarterNoteInterval,bpm:e.quarterNoteBpm,chartMetadata:o}}static reconstructChartFromMergedBeats(e){const t=e.mergedBeats.map((i,s)=>({timestamp:i.timestamp,beatInMeasure:i.beatInMeasure,isDownbeat:i.isDownbeat,measureNumber:i.measureNumber,intensity:i.intensity,confidence:i.confidence,requiredKey:i.requiredKey,quarterNoteIndex:s,subdivisionPosition:0,isDetected:i.source==="detected",subdivisionType:"quarter",sourceBand:"mid",quantizationError:i.distanceToAnchor})),n=e.mergedBeats.map((i,s)=>i.source==="detected"?s:-1).filter(i=>i>=0),r=this.reconstructDownbeatConfig(t),o=this.reconstructChartMetadata(e);return{audioId:e.audioId,duration:e.duration,beats:t,detectedBeatIndices:n,downbeatConfig:r,quarterNoteInterval:e.interpolatedMetadata.quarterNoteInterval,bpm:e.quarterNoteBpm,chartMetadata:o}}static reconstructDownbeatConfig(e){const t=e.filter(o=>o.isDownbeat);if(t.length===0)return{segments:[{startBeat:0,downbeatBeatIndex:0,timeSignature:{beatsPerMeasure:4}}]};const n={beatsPerMeasure:4};return{segments:[{startBeat:0,downbeatBeatIndex:t[0]?.measureNumber??0,timeSignature:n}]}}static reconstructChartMetadata(e){const t=e.generationMetadata;return{difficulty:this.parseDifficultyLevel(t?.difficulty),keysUsed:e.chart?.usedKeys??[],pitchInfluencedBeats:t?.pitchInfluenceWeight&&t.pitchInfluenceWeight>0?e.subdivision?.beats.filter(n=>n.requiredKey).length??0:0,patternsUsed:t?.patternsUsed??[],rhythmMetadata:{difficulty:t?.rhythmMetadata?.difficulty??"medium",bandsAnalyzed:t?.rhythmMetadata?.bandsAnalyzed??["low","mid","high"],transientsDetected:t?.rhythmMetadata?.transientsDetected??e.detectedBeats.length,averageDensity:t?.rhythmMetadata?.averageDensity??.5,naturalDifficulty:this.parseDifficultyLevel(t?.difficulty)},pitchMetadata:t?.directionStats||t?.intervalStats?{melodyRange:null,directionStats:t.directionStats??null,intervalStats:t.intervalStats??null}:null,generatedAt:t?.generatedAt??new Date().toISOString(),seed:t?.seed}}static parseDifficultyLevel(e){return e==="easy"||e==="medium"||e==="hard"||e==="natural"||e==="custom"?e:"medium"}static parseDifficultyPreset(e){return e==="easy"||e==="medium"||e==="hard"||e==="natural"||e==="custom"?e:"medium"}static reconstructVariant(e,t){const n=e.generationMetadata,r=this.parseDifficultyLevel(n?.difficulty),o=t.beats.map(i=>({timestamp:i.timestamp,beatIndex:i.quarterNoteIndex,gridPosition:i.subdivisionPosition,gridType:this.subdivisionTypeToGridType(i.subdivisionType),intensity:i.intensity,band:i.sourceBand,quantizationError:i.quantizationError,sourceBand:i.sourceBand}));return{difficulty:r,beats:o,isUnedited:!0,editType:"none",editAmount:0,patternsInserted:n?.patternsUsed}}static subdivisionTypeToGridType(e){switch(e){case"sixteenth":case"eighth":case"quarter":return"straight_16th";case"triplet8":case"triplet4":return"triplet_8th";default:return"straight_16th"}}static reconstructRhythm(e,t){const n=e.generationMetadata,r=this.parseDifficultyLevel(n?.difficulty),o=d=>({audioId:e.audioId,duration:e.duration,beats:t.beats.filter(g=>g.sourceBand===d).map(g=>({timestamp:g.timestamp,beatIndex:g.quarterNoteIndex,gridPosition:g.subdivisionPosition,gridType:this.subdivisionTypeToGridType(g.subdivisionType),intensity:g.intensity,band:d,quantizationError:g.quantizationError})),gridDecisions:[],quarterNoteInterval:e.interpolatedMetadata.quarterNoteInterval}),i={low:o("low"),mid:o("mid"),high:o("high")},s=this.reconstructVariant(e,t),c=t.beats.map(d=>({timestamp:d.timestamp,beatIndex:d.quarterNoteIndex,gridPosition:d.subdivisionPosition,gridType:this.subdivisionTypeToGridType(d.subdivisionType),intensity:d.intensity,band:d.sourceBand,quantizationError:d.quantizationError,sourceBand:d.sourceBand})),u={low:0,mid:0,high:0};for(const d of c)u[d.sourceBand]++;const f={beats:c,sections:[],naturalDifficulty:r,quarterNoteInterval:e.interpolatedMetadata.quarterNoteInterval,metadata:{totalBeats:c.length,sectionCount:0,beatsPerBand:u,sectionsPerBand:{low:0,mid:0,high:0}}};return{difficultyVariants:{easy:{...s,difficulty:"easy"},medium:{...s,difficulty:"medium"},hard:{...s,difficulty:"hard"},natural:{...s,difficulty:"natural"}},bandStreams:i,composite:f,analysis:{transientAnalysis:{transients:e.detectedBeats.map(d=>({timestamp:d.timestamp,intensity:d.intensity,band:"mid",detectionMethod:"energy"})),bandTransients:new Map([["low",[]],["mid",e.detectedBeats.map(d=>({timestamp:d.timestamp,intensity:d.intensity,band:"mid",detectionMethod:"energy"}))],["high",[]]]),metadata:{totalTransients:e.detectedBeats.length,transientsPerBand:new Map([["low",0],["mid",e.detectedBeats.length],["high",0]]),duration:e.duration,averageIntensity:.5,detectionMethodsUsed:["energy"]}},quantizationResult:{streams:i,metadata:{densityValidation:{isValid:!0,bands:{low:{band:"low",isValid:!0,minIntervalDetected:1/0,requiredMinInterval:.1,retryCount:0,sensitivityReduction:0,finalIntensityThreshold:0,transientsRemaining:0},mid:{band:"mid",isValid:!0,minIntervalDetected:.1,requiredMinInterval:.1,retryCount:0,sensitivityReduction:0,finalIntensityThreshold:0,transientsRemaining:e.detectedBeats.length},high:{band:"high",isValid:!0,minIntervalDetected:1/0,requiredMinInterval:.1,retryCount:0,sensitivityReduction:0,finalIntensityThreshold:0,transientsRemaining:0}},maxRetryCount:0,maxSensitivityReduction:0},transientsFilteredByIntensity:0,transientsFilteredByBand:{low:0,mid:0,high:0}}},phraseAnalysis:{phrases:[],phrasesByBand:new Map([["low",[]],["mid",[]],["high",[]]]),mostSignificantPhrases:[],phrasesBySize:new Map,patternLibrary:[],bandAnalysis:{low:{band:"low",phrases:[],phrasesBySize:new Map,phrasesWithVariation:[]},mid:{band:"mid",phrases:[],phrasesBySize:new Map,phrasesWithVariation:[]},high:{band:"high",phrases:[],phrasesBySize:new Map,phrasesWithVariation:[]}}},densityAnalysis:{sections:[],perBeatDensity:[],bandMetrics:{low:{band:"low",totalBeats:0,totalTransients:0,notesPerSecond:1,minNotesPerSecond:0,maxNotesPerSecond:2,variance:0,densityCategory:"moderate",naturalDifficulty:"medium",perBeatDensity:[]},mid:{band:"mid",totalBeats:e.mergedBeats.length,totalTransients:e.detectedBeats.length,notesPerSecond:1,minNotesPerSecond:0,maxNotesPerSecond:2,variance:0,densityCategory:"moderate",naturalDifficulty:r,perBeatDensity:[]},high:{band:"high",totalBeats:0,totalTransients:0,notesPerSecond:1,minNotesPerSecond:0,maxNotesPerSecond:2,variance:0,densityCategory:"moderate",naturalDifficulty:"medium",perBeatDensity:[]}},combinedMetrics:{totalTransients:e.detectedBeats.length,notesPerSecond:1,densityCategory:"moderate",naturalDifficulty:r}},scoringResult:{sectionScores:[],bandTotals:{low:0,mid:0,high:0},bandAverages:{low:0,mid:0,high:0},sectionWinners:[],config:{beatsPerSection:8,ioiVarianceWeight:.25,syncopationWeight:.25,phraseSignificanceWeight:.25,densityWeight:.25,offbeatGridPositions:{straight_16th:[1,3],triplet_8th:[1,2],straight_8th:[1]}}}},metadata:this.buildFullRhythmMetadata(e,r)}}static buildFullRhythmMetadata(e,t){const n=e.generationMetadata;return{difficulty:this.parseDifficultyPreset(n?.difficulty),bandsAnalyzed:["low","mid","high"],transientsDetected:e.detectedBeats.length,transientsFilteredByIntensity:0,densityValidationRetries:0,phrasesDetected:0,averageDensity:n?.rhythmMetadata?.averageDensity??.5,naturalDifficulty:t,generationConfig:{difficulty:this.parseDifficultyPreset(n?.difficulty),outputMode:"composite",measureStartOffset:0,minimumTransientIntensity:.1,transientConfig:void 0,rhythmicBalanceConfig:{strongBeatEmphasis:"natural",downbeatProximityRange:2,fillEmptyMeasures:!0,addedBeatIntensity:.45,marginSeconds:.5},seed:n?.seed,verbose:!1,enableCache:!0,cacheMaxAge:1800*1e3,skipDifficultyVariants:!1},duration:e.duration,totalBeats:e.mergedBeats.length}}static buildMinimalMelodyContour(){return{segments:[],direction:"stable",range:{minNote:"N/A",maxNote:"N/A",semitones:0},shortTermDirection:"stable",mediumTermDirection:"stable",longTermDirection:"stable"}}static reconstructPitchAnalysis(e){const t=e.generationMetadata;return!t||!t.directionStats&&!t.intervalStats?null:{pitchByBeat:[],melodyContour:this.buildMinimalMelodyContour(),directionStats:t.directionStats??{up:0,down:0,stable:0,none:0},intervalStats:t.intervalStats??{unison:0,small:0,medium:0,large:0,very_large:0},metadata:{totalBeats:0,voicedBeats:0,directionCalculatedBeats:0}}}static reconstructMetadata(e,t){const n=e.generationMetadata,r=this.parseDifficultyPreset(n?.difficulty),o=n?.controllerMode??"ddr";return{difficulty:r,controllerMode:o,rhythmMetadata:this.buildFullRhythmMetadata(e,this.parseDifficultyLevel(n?.difficulty)),buttonMetadata:{controllerMode:o,keysUsed:e.chart?.usedKeys??[],pitchInfluencedBeats:n?.pitchInfluenceWeight&&n.pitchInfluenceWeight>0?t.beats.filter(i=>i.requiredKey).length:0,patternInfluencedBeats:t.beats.filter(i=>i.requiredKey).length-(n?.pitchInfluenceWeight&&n.pitchInfluenceWeight>0?t.beats.filter(i=>i.requiredKey).length:0),patternsUsed:n?.patternsUsed??[],buttonDistribution:new Map},pitchMetadata:n?.directionStats||n?.intervalStats?{melodyRange:null,directionStats:n.directionStats??null,intervalStats:n.intervalStats??null}:null,chartMetadata:{totalBeats:t.beats.length,detectedBeats:t.detectedBeatIndices.length,generatedBeats:t.beats.length-t.detectedBeatIndices.length},generationConfig:{difficulty:r,controllerMode:o,rhythm:{},buttons:{pitchInfluenceWeight:n?.pitchInfluenceWeight??1},seed:n?.seed}}}static toJSON(e,t={}){const n=this.toExportData(e,t);return JSON.stringify(n,null,2)}static fromJSON(e){let t;try{t=JSON.parse(e)}catch(r){throw new Error(`Invalid JSON: ${r instanceof Error?r.message:"Unknown error"}`)}const n=this.validate(t);if(!n.success||!n.data)throw new Error(`Invalid level data: ${n.error??"Unknown error"}`);return this.fromExportData(n.data)}static async saveToFile(e,t,n={}){const r=await Promise.resolve().then(()=>require("./__vite-browser-external-BcPniuRQ.cjs")),o=this.toJSON(e,n);await r.writeFile(t,o,"utf-8")}static async loadFromFile(e){const n=await(await Promise.resolve().then(()=>require("./__vite-browser-external-BcPniuRQ.cjs"))).readFile(e,"utf-8");return this.fromJSON(n)}static validate(e){const t=[];if(typeof e!="object"||e===null)return{success:!1,error:"Data must be a non-null object"};const n=e;if(n.version!==1)return{success:!1,error:`Unsupported version: ${n.version}. Expected 1.`};if(n.format!=="full-beatmap")return{success:!1,error:`Invalid format: ${n.format}. Expected 'full-beatmap'.`};const r=["audioId","duration","quarterNoteBpm","detectedBeats","mergedBeats"];for(const o of r)if(!(o in n))return{success:!1,error:`Missing required field: ${o}`};if(!Array.isArray(n.detectedBeats))return{success:!1,error:"detectedBeats must be an array"};if(!Array.isArray(n.mergedBeats))return{success:!1,error:"mergedBeats must be an array"};if(!n.subdivision||typeof n.subdivision!="object")t.push("No subdivision data - level may not be playable");else{const o=n.subdivision;if(!Array.isArray(o.beats))return{success:!1,error:"subdivision.beats must be an array"}}if(n.chart===null)t.push("No chart data - level has no key assignments");else if(n.chart!==void 0&&typeof n.chart!="object")return{success:!1,error:"chart must be an object or null"};return typeof n.interpolatedMetadata!="object"||n.interpolatedMetadata===null?{success:!1,error:"interpolatedMetadata must be an object"}:x.isFullBeatMapExportData(e)?{success:!0,data:e,warnings:t.length>0?t:void 0}:{success:!1,error:"Data does not match FullBeatMapExportData format",warnings:t.length>0?t:void 0}}static toPack(e,t={}){const n={};for(const[r,o]of Object.entries(e))if(o){const i={includeAudioTitle:t.includeAudioTitle,audioTitle:t.audioTitle};n[r]=this.toExportData(o,i)}return{version:1,format:"level-pack",exportedAt:Date.now(),trackReference:t.trackReference,difficulties:n}}static fromPack(e){const t={};for(const[n,r]of Object.entries(e.difficulties))if(r)try{t[n]=this.fromExportData(r)}catch{}return t}static packToJSON(e,t={}){const n=this.toPack(e,t);return JSON.stringify(n,null,2)}static packFromJSON(e){let t;try{t=JSON.parse(e)}catch(n){throw new Error(`Invalid JSON: ${n instanceof Error?n.message:"Unknown error"}`)}if(!x.isLevelPackExport(t))throw new Error("Data does not match LevelPackExport format");return this.fromPack(t)}static isProcedural(e){return e.generationSource==="procedural"}static getSummary(e){const t=[`Audio: ${e.audioId}`,`Duration: ${e.duration.toFixed(1)}s`,`BPM: ${e.quarterNoteBpm.toFixed(1)}`,`Beats: ${e.mergedBeats.length} (${e.detectedBeats.length} detected)`];return e.chart&&(t.push(`Keys: ${e.chart.keyCount} (${e.chart.style})`),t.push(`Keys used: ${e.chart.usedKeys.join(", ")}`)),e.generationMetadata&&(t.push(`Difficulty: ${e.generationMetadata.difficulty}`),t.push(`Controller: ${e.generationMetadata.controllerMode}`),t.push(`Pitch influence: ${(e.generationMetadata.pitchInfluenceWeight*100).toFixed(0)}%`)),t.join(`
2
2
  `)}}const de=class de{constructor(e={}){this.options={includeAdvancedMetrics:!1,sampleRate:44100,fftSize:2048,trebleBoost:1,bassBoost:1,midBoost:1,...e}}async extractSonicFingerprint(e){const t=await this.fetchAndDecode(e),n=t.duration,r=n<3;let o;r?o=[0]:o=[.05,.4,.7];const i=[];for(const A of o){const B=await this.analyzeAtPosition(t,A,r);i.push(B)}const s=this.averageFrequencyBands(i);let c=x.SpectrumScanner.calculateDominance(s.bass,380),u=x.SpectrumScanner.calculateDominance(s.mid,3600),f=x.SpectrumScanner.calculateDominance(s.treble,1e4);c=c*this.options.bassBoost,u=u*this.options.midBoost,f=f*this.options.trebleBoost;const d=c+u+f;c=c/(d||1),u=u/(d||1),f=f/(d||1);const g=this.calculateAverageAmplitude(t),b=this.calculateRMS(t),R=this.calculatePeak(t)-b,I={bass_dominance:c,mid_dominance:u,treble_dominance:f,average_amplitude:g,analysis_metadata:{duration_analyzed:r?n:n*o.length*.01,full_buffer_analyzed:r,sample_positions:o,analyzed_at:new Date().toISOString()},rms_energy:b,dynamic_range:R};if(this.options.includeAdvancedMetrics){const A=[...s.bass,...s.mid,...s.treble];I.spectral_centroid=this.calculateSpectralCentroid(A),I.spectral_rolloff=this.calculateSpectralRolloff(A),I.zero_crossing_rate=this.calculateZeroCrossingRate(t)}return I}async analyzeTimeline(e,t){const n=await this.fetchAndDecode(e),r=n.duration,o=n.sampleRate,i=[];let s=[];if(t.type==="interval"){const c=t.intervalSeconds;for(let u=0;u<r;u+=c)s.push(u)}else{const c=t.count,u=r/c;for(let f=0;f<c;f++)s.push(f*u)}for(const c of s){const u=r-c,f=Math.min(1,u);if(f<=0)break;const d=Math.floor(c*o),g=Math.floor((c+f)*o),b=this.extractAudioSegment(n,d,g),S=this.performFFT(b,this.options.fftSize),R=new Uint8Array(S.length);for(let L=0;L<S.length;L++)R[L]=Math.min(255,Math.round(S[L]));const I=x.SpectrumScanner.separateFrequencyBands(R,o),A=x.SpectrumScanner.calculateDominance(I.bass)*this.options.bassBoost,B=x.SpectrumScanner.calculateDominance(I.mid)*this.options.midBoost,N=x.SpectrumScanner.calculateDominance(I.treble)*this.options.trebleBoost,k=A+B+N||1,C=this.calculateRMS(n,d,g),F=this.calculatePeak(n,d,g),P=[...I.bass,...I.mid,...I.treble];i.push({timestamp:c,duration:f,bass:A/k,mid:B/k,treble:N/k,amplitude:C,rms_energy:C,peak:F,dynamic_range:F-C,spectral_centroid:this.calculateSpectralCentroid(P),spectral_rolloff:this.calculateSpectralRolloff(P),zero_crossing_rate:this.calculateZeroCrossingRate(n,d,g)})}return i}async generateBeatMap(e,t,n,r,o){return new x.BeatMapGenerator(n).generateBeatMap(e,t,r,o)}async generateBeatMapFromBuffer(e,t,n,r,o){return new x.BeatMapGenerator(n).generateBeatMapFromBuffer(e,t,r,o)}createBeatStream(e,t,n){return new x.BeatStream(e,t,n)}interpolateBeatMap(e,t){return new x.BeatInterpolator(t).interpolate(e)}async generateBeatMapWithInterpolation(e,t,n,r,o,i){const s=await this.generateBeatMap(e,t,n,r,i);return this.interpolateBeatMap(s,o)}async generateBeatMapWithInterpolationFromBuffer(e,t,n,r,o,i){const s=await this.generateBeatMapFromBuffer(e,t,n,r,i);return this.interpolateBeatMap(s,o)}static beatMapToJSON(e){return x.BeatMapGenerator.toJSON(e)}static beatMapFromJSON(e){return x.BeatMapGenerator.fromJSON(e)}static async saveBeatMapToFile(e,t){return x.BeatMapGenerator.saveToFile(e,t)}static async loadBeatMapFromFile(e){return x.BeatMapGenerator.loadFromFile(e)}async generateRhythm(e,t,n,r,o,i){const s=await this.fetchAndDecode(e);return this.generateRhythmFromBuffer(s,t,n,r,o,i)}async generateRhythmFromBuffer(e,t,n,r,o,i){const s=await this.generateBeatMapWithInterpolationFromBuffer(e,t,r,o),c=x.unifyBeatMap(s);return new x.RhythmGenerator(n).generate(e,c,void 0,i)}async generateRhythmLevel(e,t,n,r,o,i){const s=await this.fetchAndDecode(e);return this.generateRhythmLevelFromBuffer(s,t,n,r,o,i)}async generateRhythmLevelFromBuffer(e,t,n,r,o,i){const s=await this.generateBeatMapWithInterpolationFromBuffer(e,t,r,o),c=x.unifyBeatMap(s);return new Ee(n).generate(e,c,i)}async generateRhythmLevelWithPreset(e,t,n,r,o,i){const s=de.LEVEL_PRESETS[n],c={difficulty:s.difficulty,controllerMode:s.controllerMode,buttons:s.buttons};return this.generateRhythmLevel(e,t,c,r,o,i)}async generateRhythmLevelWithPresetFromBuffer(e,t,n,r,o,i){const s=de.LEVEL_PRESETS[n],c={difficulty:s.difficulty,controllerMode:s.controllerMode,buttons:s.buttons};return this.generateRhythmLevelFromBuffer(e,t,c,r,o,i)}async fetchAndDecodeAudio(e){return this.fetchAndDecode(e)}async fetchAndDecode(e){const t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch audio: ${t.statusText}`);const n=await t.arrayBuffer(),r=globalThis.AudioContext||window?.AudioContext;if(!r)throw new Error("AudioContext not available in this environment");const o=new r;return await new Promise((i,s)=>{o.decodeAudioData(n,i,s)})}async analyzeAtPosition(e,t,n){const r=e.sampleRate,o=e.duration;let i,s;if(n)i=0,s=e.length;else{const d=o*t;i=Math.floor(d*r),s=Math.min(i+r,e.length)}const c=this.extractAudioSegment(e,i,s),u=this.performFFT(c,this.options.fftSize),f=new Uint8Array(u.length);for(let d=0;d<u.length;d++)f[d]=Math.min(255,Math.round(u[d]));return x.SpectrumScanner.separateFrequencyBands(f,r)}extractAudioSegment(e,t,n){const r=n-t,o=new Float32Array(r);for(let i=0;i<e.numberOfChannels;i++){const s=e.getChannelData(i);for(let c=0;c<r;c++)o[c]+=s[t+c]/e.numberOfChannels}return o}performFFT(e,t){const n=Math.pow(2,Math.ceil(Math.log2(Math.min(e.length,t)))),r=new Float32Array(n),o=new Float32Array(n);for(let u=0;u<Math.min(e.length,n);u++){const f=.5-.5*Math.cos(2*Math.PI*u/(n-1));r[u]=e[u]*f}this.fft(r,o);const i=new Array(n/2);for(let u=0;u<i.length;u++){const f=r[u],d=o[u];i[u]=Math.sqrt(f*f+d*d)}const s=Math.max(...i);return i.map(u=>{const f=u/(s||1);return 20*Math.log10(Math.max(f,.001))})}fft(e,t){const n=e.length;if(n<=1)return;let r=0;for(let i=0;i<n-1;i++){i<r&&([e[i],e[r]]=[e[r],e[i]],[t[i],t[r]]=[t[r],t[i]]);let s=n/2;for(;r>=s;)r-=s,s/=2;r+=s}let o=2;for(;o<=n;){const i=-2*Math.PI/o,s=Math.cos(i),c=Math.sin(i);for(let u=0;u<n;u+=o){let f=1,d=0;for(let g=0;g<o/2;g++){const b=u+g,S=u+g+o/2,R=e[S]*f-t[S]*d,I=e[S]*d+t[S]*f;e[S]=e[b]-R,t[S]=t[b]-I,e[b]+=R,t[b]+=I;const A=f*s-d*c;d=f*c+d*s,f=A}}o*=2}}averageFrequencyBands(e){if(e.length===0)return{bass:[],mid:[],treble:[]};if(e.length===1)return e[0];const t=Math.max(...e.map(i=>Math.max(i.bass.length,i.mid.length,i.treble.length))),n=[],r=[],o=[];for(let i=0;i<t;i++){const s=e.map(f=>f.bass[i]||0),c=e.map(f=>f.mid[i]||0),u=e.map(f=>f.treble[i]||0);n.push(s.reduce((f,d)=>f+d,0)/s.length),r.push(c.reduce((f,d)=>f+d,0)/c.length),o.push(u.reduce((f,d)=>f+d,0)/u.length)}return{bass:n,mid:r,treble:o}}calculateAverageAmplitude(e){let t=0,n=0;for(let r=0;r<e.numberOfChannels;r++){const o=e.getChannelData(r);for(let i=0;i<o.length;i++)t+=Math.abs(o[i]),n++}return n>0?t/n:0}calculateRMS(e,t=0,n=e.length){let r=0,o=0;for(let i=0;i<e.numberOfChannels;i++){const s=e.getChannelData(i),c=Math.min(n,s.length);for(let u=t;u<c;u++)r+=s[u]*s[u],o++}return o>0?Math.sqrt(r/o):0}calculatePeak(e,t=0,n=e.length){let r=0;for(let o=0;o<e.numberOfChannels;o++){const i=e.getChannelData(o),s=Math.min(n,i.length);for(let c=t;c<s;c++){const u=Math.abs(i[c]);u>r&&(r=u)}}return r}calculateSpectralCentroid(e){let t=0,n=0;for(let r=0;r<e.length;r++)t+=r*e[r],n+=e[r];return n>0?t/n:0}calculateSpectralRolloff(e){const n=e.reduce((o,i)=>o+i,0)*.85;let r=0;for(let o=0;o<e.length;o++)if(r+=e[o],r>=n)return o/e.length;return 1}calculateZeroCrossingRate(e,t=0,n=e.length){let r=0,o=0;for(let i=0;i<e.numberOfChannels;i++){const s=e.getChannelData(i),c=Math.min(n,s.length),u=Math.max(0,t);for(let f=Math.max(1,u+1);f<c;f++)(s[f-1]>=0&&s[f]<0||s[f-1]<0&&s[f]>=0)&&r++,o++}return o>0?r/o:0}};de.LEVEL_PRESETS={casual:{difficulty:"easy",controllerMode:"ddr",buttons:{pitchInfluenceWeight:.3},description:"Easy difficulty, low pitch influence - for relaxed gameplay"},standard:{difficulty:"medium",controllerMode:"ddr",buttons:{pitchInfluenceWeight:.7},description:"Medium difficulty, high pitch influence - balanced experience"},challenge:{difficulty:"hard",controllerMode:"ddr",buttons:{pitchInfluenceWeight:1},description:"Hard difficulty, full pitch influence - for skilled players"},insane:{difficulty:"hard",controllerMode:"ddr",buttons:{pitchInfluenceWeight:1,consecutiveSameKeyLimit:4},description:"Maximum difficulty with strict limits - for experts only"}};let Le=de;const mr=["60s","70s","80s","90s","acidjazz","alternative","alternativerock","ambient","atmospheric","blues","bluesrock","bossanova","bossa","celtic","chanson","chillout","choir","classical","classicrock","club","comedy","country","cuban","dance","darkambient","darkwave","deephouse","disco","downtempo","drumandbass","dub","dubstep","easylistening","edm","electronic","electro","electropop","ethno","eurodance","experimental","folk","funk","fusion","groove","grunge","hardcore","hardrock","hiphop","house","indie","indiepop","indierock","industrial","instrumentalpop","instrumentalrock","jazz","jazzfusion","latin","lounge","metal","minimal","newage"," orchestrall","pop","popfolk","poprock","postrock","progressive","psychedelic","punkrock","rap","reggae","rnb","rock","rockandroll","ska","soul","soundtrack","synthpop","techno","trance","trip","triphop","underground","world","worldbeat","worldmusic"],Ue=["Blues---Boogie Woogie","Blues---Chicago Blues","Blues---Country Blues","Blues---Delta Blues","Blues---Electric Blues","Blues---Harmonica Blues","Blues---Jump Blues","Blues---Louisiana Blues","Blues---Modern Electric Blues","Blues---Piano Blues","Blues---Rhythm & Blues","Blues---Texas Blues","Brass & Military---Brass Band","Brass & Military---Marches","Brass & Military---Military","Children's-- - Educational","Children's-- - Nursery Rhymes","Children's-- - Story","Classical---Baroque","Classical---Choral","Classical---Classical","Classical---Contemporary","Classical---Impressionist","Classical---Medieval","Classical---Modern","Classical---Neo-Classical","Classical---Neo-Romantic","Classical---Opera","Classical---Post-Modern","Classical---Renaissance","Classical---Romantic","Electronic---Abstract","Electronic---Acid","Electronic---Acid House","Electronic---Acid Jazz","Electronic---Ambient","Electronic---Bassline","Electronic---Beatdown","Electronic---Berlin-School","Electronic---Big Beat","Electronic---Bleep","Electronic---Breakbeat","Electronic---Breakcore","Electronic---Breaks","Electronic---Broken Beat","Electronic---Chillwave","Electronic---Chiptune","Electronic---Dance-pop","Electronic---Dark Ambient","Electronic---Darkwave","Electronic---Deep House","Electronic---Deep Techno","Electronic---Disco","Electronic---Disco Polo","Electronic---Donk","Electronic---Downtempo","Electronic---Drone","Electronic---Drum n Bass","Electronic---Dub","Electronic---Dub Techno","Electronic---Dubstep","Electronic---Dungeon Synth","Electronic---EBM","Electronic---Electro","Electronic---Electro House","Electronic---Electroclash","Electronic---Euro House","Electronic---Euro-Disco","Electronic---Eurobeat","Electronic---Eurodance","Electronic---Experimental","Electronic---Freestyle","Electronic---Future Jazz","Electronic---Gabber","Electronic---Garage House","Electronic---Ghetto","Electronic---Ghetto House","Electronic---Glitch","Electronic---Goa Trance","Electronic---Grime","Electronic---Halftime","Electronic---Hands Up","Electronic---Happy Hardcore","Electronic---Hard House","Electronic---Hard Techno","Electronic---Hard Trance","Electronic---Hardcore","Electronic---Hardstyle","Electronic---Hi NRG","Electronic---Hip Hop","Electronic---Hip-House","Electronic---House","Electronic---IDM","Electronic---Illbient","Electronic---Industrial","Electronic---Italo House","Electronic---Italo-Disco","Electronic---Italodance","Electronic---Jazzdance","Electronic---Juke","Electronic---Jumpstyle","Electronic---Jungle","Electronic---Latin","Electronic---Leftfield","Electronic---Makina","Electronic---Minimal","Electronic---Minimal Techno","Electronic---Modern Classical","Electronic---Musique Concrète","Electronic---Neofolk","Electronic---New Age","Electronic---New Beat","Electronic---New Wave","Electronic---Noise","Electronic---Nu-Disco","Electronic---Power Electronics","Electronic---Progressive Breaks","Electronic---Progressive House","Electronic---Progressive Trance","Electronic---Psy-Trance","Electronic---Rhythmic Noise","Electronic---Schranz","Electronic---Sound Collage","Electronic---Speed Garage","Electronic---Speedcore","Electronic---Synth-pop","Electronic---Synthwave","Electronic---Tech House","Electronic---Tech Trance","Electronic---Techno","Electronic---Trance","Electronic---Tribal","Electronic---Tribal House","Electronic---Trip Hop","Electronic---Tropical House","Electronic---UK Garage","Electronic---Vaporwave","Folk, World, & Country---African","Folk, World, & Country---Bluegrass","Folk, World, & Country---Cajun","Folk, World, & Country---Canzone Napoletana","Folk, World, & Country---Catalan Music","Folk, World, & Country---Celtic","Folk, World, & Country---Country","Folk, World, & Country---Fado","Folk, World, & Country---Flamenco","Folk, World, & Country---Folk","Folk, World, & Country---Gospel","Folk, World, & Country---Highlife","Folk, World, & Country---Hillbilly","Folk, World, & Country---Hindustani","Folk, World, & Country---Honky Tonk","Folk, World, & Country---Indian Classical","Folk, World, & Country---Laïkó","Folk, World, & Country---Nordic","Folk, World, & Country---Pacific","Folk, World, & Country---Polka","Folk, World, & Country---Raï","Folk, World, & Country---Romani","Folk, World, & Country---Soukous","Folk, World, & Country---Séga","Folk, World, & Country---Volksmusik","Folk, World, & Country---Zouk","Folk, World, & Country---Éntekhno","Funk / Soul---Afrobeat","Funk / Soul---Boogie","Funk / Soul---Contemporary R&B","Funk / Soul---Disco","Funk / Soul---Free Funk","Funk / Soul---Funk","Funk / Soul---Gospel","Funk / Soul---Neo Soul","Funk / Soul---New Jack Swing","Funk / Soul---P.Funk","Funk / Soul---Psychedelic","Funk / Soul---Rhythm & Blues","Funk / Soul---Soul","Funk / Soul---Swingbeat","Funk / Soul---UK Street Soul","Hip Hop---Bass Music","Hip Hop---Boom Bap","Hip Hop---Bounce","Hip Hop---Britcore","Hip Hop---Cloud Rap","Hip Hop---Conscious","Hip Hop---Crunk","Hip Hop---Cut-up/DJ","Hip Hop---DJ Battle Tool","Hip Hop---Electro","Hip Hop---G-Funk","Hip Hop---Gangsta","Hip Hop---Grime","Hip Hop---Hardcore Hip-Hop","Hip Hop---Horrorcore","Hip Hop---Instrumental","Hip Hop---Jazzy Hip-Hop","Hip Hop---Miami Bass","Hip Hop---Pop Rap","Hip Hop---Ragga HipHop","Hip Hop---RnB/Swing","Hip Hop---Screw","Hip Hop---Thug Rap","Hip Hop---Trap","Hip Hop---Trip Hop","Hip Hop---Turntablism","Jazz---Afro-Cuban Jazz","Jazz---Afrobeat","Jazz---Avant-garde Jazz","Jazz---Big Band","Jazz---Bop","Jazz---Bossa Nova","Jazz---Contemporary Jazz","Jazz---Cool Jazz","Jazz---Dixieland","Jazz---Easy Listening","Jazz---Free Improvisation","Jazz---Free Jazz","Jazz---Fusion","Jazz---Gypsy Jazz","Jazz---Hard Bop","Jazz---Jazz-Funk","Jazz---Jazz-Rock","Jazz---Latin Jazz","Jazz---Modal","Jazz---Post Bop","Jazz---Ragtime","Jazz---Smooth Jazz","Jazz---Soul-Jazz","Jazz---Space-Age","Jazz---Swing","Latin---Afro-Cuban","Latin---Baião","Latin---Batucada","Latin---Beguine","Latin---Bolero","Latin---Boogaloo","Latin---Bossanova","Latin---Cha-Cha","Latin---Charanga","Latin---Compas","Latin---Cubano","Latin---Cumbia","Latin---Descarga","Latin---Forró","Latin---Guaguancó","Latin---Guajira","Latin---Guaracha","Latin---MPB","Latin---Mambo","Latin---Mariachi","Latin---Merengue","Latin---Norteño","Latin---Nueva Cancion","Latin---Pachanga","Latin---Porro","Latin---Ranchera","Latin---Reggaeton","Latin---Rumba","Latin---Salsa","Latin---Samba","Latin---Son","Latin---Son Montuno","Latin---Tango","Latin---Tejano","Latin---Vallenato","Non-Music---Audiobook","Non-Music---Comedy","Non-Music---Dialogue","Non-Music---Education","Non-Music---Field Recording","Non-Music---Interview","Non-Music---Monolog","Non-Music---Poetry","Non-Music---Political","Non-Music---Promotional","Non-Music---Radioplay","Non-Music---Religious","Non-Music---Spoken Word","Pop---Ballad","Pop---Bollywood","Pop---Bubblegum","Pop---Chanson","Pop---City Pop","Pop---Europop","Pop---Indie Pop","Pop---J-pop","Pop---K-pop","Pop---Kayōkyoku","Pop---Light Music","Pop---Music Hall","Pop---Novelty","Pop---Parody","Pop---Schlager","Pop---Vocal","Reggae---Calypso","Reggae---Dancehall","Reggae---Dub","Reggae---Lovers Rock","Reggae---Ragga","Reggae---Reggae","Reggae---Reggae-Pop","Reggae---Rocksteady","Reggae---Roots Reggae","Reggae---Ska","Reggae---Soca","Rock---AOR","Rock---Acid Rock","Rock---Acoustic","Rock---Alternative Rock","Rock---Arena Rock","Rock---Art Rock","Rock---Atmospheric Black Metal","Rock---Avantgarde","Rock---Beat","Rock---Black Metal","Rock---Blues Rock","Rock---Brit Pop","Rock---Classic Rock","Rock---Coldwave","Rock---Country Rock","Rock---Crust","Rock---Death Metal","Rock---Deathcore","Rock---Deathrock","Rock---Depressive Black Metal","Rock---Doo Wop","Rock---Doom Metal","Rock---Dream Pop","Rock---Emo","Rock---Ethereal","Rock---Experimental","Rock---Folk Metal","Rock---Folk Rock","Rock---Funeral Doom Metal","Rock---Funk Metal","Rock---Garage Rock","Rock---Glam","Rock---Goregrind","Rock---Goth Rock","Rock---Gothic Metal","Rock---Grindcore","Rock---Grunge","Rock---Hard Rock","Rock---Hardcore","Rock---Heavy Metal","Rock---Indie Rock","Rock---Industrial","Rock---Krautrock","Rock---Lo-Fi","Rock---Lounge","Rock---Math Rock","Rock---Melodic Death Metal","Rock---Melodic Hardcore","Rock---Metalcore","Rock---Mod","Rock---Neofolk","Rock---New Wave","Rock---No Wave","Rock---Noise","Rock---Noisecore","Rock---Nu Metal","Rock---Oi","Rock---Parody","Rock---Pop Punk","Rock---Pop Rock","Rock---Pornogrind","Rock---Post Rock","Rock---Post-Hardcore","Rock---Post-Metal","Rock---Post-Punk","Rock---Power Metal","Rock---Power Pop","Rock---Power Violence","Rock---Prog Rock","Rock---Progressive Metal","Rock---Psychedelic Rock","Rock---Psychobilly","Rock---Pub Rock","Rock---Punk","Rock---Rock & Roll","Rock---Rockabilly","Rock---Shoegaze","Rock---Ska","Rock---Sludge Metal","Rock---Soft Rock","Rock---Southern Rock","Rock---Space Rock","Rock---Speed Metal","Rock---Stoner Rock","Rock---Surf","Rock---Symphonic Rock","Rock---Technical Death Metal","Rock---Thrash","Rock---Twist","Rock---Viking Metal","Rock---Yé-Yé","Stage & Screen---Musical","Stage & Screen---Score","Stage & Screen---Soundtrack","Stage & Screen---Theme"],gr=["Blues","Classical","Country","Disco","Hip-Hop","Jazz","Metal","Pop","Reggae","Rock"],pr=["guitar","classical","slow","techno","strings","drums","electronic","rock","fast","piano","ambient","beat","violin","vocal","synth","female","indian","opera","male","singing","vocals","no vocals","harpsichord","loud","quiet","flute","woman","male vocal","no vocal","pop","soft","sitar","solo","man","classic","choir","voice","new age","dance","male voice","female vocal","beats","harp","cello","no voice","weird","country","metal","female voice","choral"],yr=["happy","not happy"],vr=["action","adventure","advertising","background","ballad","calm","children","christmas","commercial","cool","corporate","dark","deep","documentary","drama","dramatic","dream","emotional","energetic","epic","fast","film","fun","funny","game","groovy","happy","heavy","holiday","hopeful","inspiring","love","meditative","melancholic","melodic","motivational","movie","nature","nostalgic","party","peaceful","positive","relaxing","retro","romantic","sad","scary","science","sea","sentimental","serene","sexy","space","sport","summer","suspense","trailer","travel","upbeat","uplifting","video","war"],br=["danceable","non-danceable"],wr=["voice","instrumental"],Mr=["acoustic","electronic"];function ue(v){return typeof v=="object"&&v!==null&&"embedding"in v&&"classifier"in v}function Oe(v){return typeof v=="object"&&v!==null&&"modelUrl"in v}function we(v,e){if(e)return e;const t=v.toLowerCase();return t.includes("effnet")||t.includes("discogs")?"effnet":t.includes("vggish")?"vggish":t.includes("tempocnn")||t.includes("tempo")&&!t.includes("temple")?"tempocnn":"musicnn"}function Rt(v,e){if(e)return e;const t=v.toLowerCase();return t.includes("jamendo")?"jamendo":t.includes("discogs400")||t.includes("discogs")?"discogs400":t.includes("tzanetakis")?"tzanetakis":t.includes("mtt_musicnn")?"mtt_musicnn":"jamendo"}function It(v){switch(v){case"jamendo":return mr;case"discogs400":return Ue;case"tzanetakis":return gr;case"mtt_musicnn":return pr;default:return Ue}}function re(v){return ue(v)?`${v.embedding} -> ${v.classifier}`:v.modelUrl}function Sr(v){if(!v||v.length===0)return[];const e=v[0].length;if(e===0)return[];const t=[];for(let n=0;n<e;n++){const r=v.reduce((o,i)=>o+(i[n]??0),0);t.push(r/v.length)}return t}const Me={genre:{embedding:"https://arweave.net/tVO0RIu2Ly_Di5cZccw_wB3x6Vs_2KSqxhl8bdhhimE/model.json",classifier:"https://arweave.net/ZY-GSfMe7crJUITAtHITcoLCNfNWVP1HMwywivZ_LAQ/model.json",embeddingType:"effnet",classifierType:"discogs400"},mood:{embedding:"https://arweave.net/tVO0RIu2Ly_Di5cZccw_wB3x6Vs_2KSqxhl8bdhhimE/model.json",classifier:"https://arweave.net/BUXf3AoFuIsrNDkV2hW6BhiwSVTuFllWOUQv5mu6qQ8/model.json",embeddingType:"effnet"},danceability:{modelUrl:"https://turbo-gateway.com/nX9KX1OVhEaT1dStNcsRiZKCQTWuHjAMl4MWprIFyZU/model.json",modelType:"musicnn"}},qe={discogs400:{embedding:"https://arweave.net/tVO0RIu2Ly_Di5cZccw_wB3x6Vs_2KSqxhl8bdhhimE/model.json",embeddingType:"effnet",classifier:"https://arweave.net/ZY-GSfMe7crJUITAtHITcoLCNfNWVP1HMwywivZ_LAQ/model.json",classifierType:"discogs400"},jamendo:{embedding:"https://arweave.net/tVO0RIu2Ly_Di5cZccw_wB3x6Vs_2KSqxhl8bdhhimE/model.json",embeddingType:"effnet",classifier:"https://arweave.net/MuhF5mek1BJPZLoPNY1TBTPUUBEXbVmMfAGgBp-_MyA/model.json",classifierType:"jamendo"},tzanetakis:{modelUrl:"https://arweave.net/7MQD4W5yJeUUK2tRg8TEdomew-ZY7s0K91nk35FxleM/model.json",modelType:"musicnn",genreType:"tzanetakis"},musicnn:{modelUrl:"https://arweave.net/KCZQ1geu4ymxp8axAql95FDY98VjnOzSymdkCiM9BXo/model.json",modelType:"musicnn",genreType:"mtt_musicnn"}},We={jamendo:{embedding:"https://arweave.net/tVO0RIu2Ly_Di5cZccw_wB3x6Vs_2KSqxhl8bdhhimE/model.json",embeddingType:"effnet",classifier:"https://arweave.net/BUXf3AoFuIsrNDkV2hW6BhiwSVTuFllWOUQv5mu6qQ8/model.json",classifierType:"jamendo"},happyMusicnn:{modelUrl:"https://arweave.net/kUIS-Xxr4k3MZ4K2gHdvMgZxK7aBYce_FPGIkGA_hjM/model.json",modelType:"musicnn"}},He={default:{modelUrl:"https://arweave.net/nX9KX1OVhEaT1dStNcsRiZKCQTWuHjAMl4MWprIFyZU/model.json",modelType:"musicnn"}},Cr={genre:Object.keys(qe),mood:Object.keys(We),danceability:Object.keys(He)};function Er(v){const e={};return v.genre&&(e.genre=qe[v.genre]),v.mood&&(e.mood=We[v.mood]),v.danceability&&(e.danceability=He[v.danceability]),e}class Dr{constructor(e={}){this.essentiaWASM=null,this.essentiaModel=null,this.extractor=null,this.initialized=!1,this.embeddingModelCache=new Map,this.classifierModelCache=new Map,this.resolvedUrlCache=new Map,this.extractors=new Map;const t=e.preset?Er(e.preset):{};this.options={models:{genre:Me.genre,mood:Me.mood,danceability:Me.danceability,...t,...e.models},topN:5,threshold:.05,cacheEmbeddings:!0,enableModelCache:!0,...e},this.options.resolveUrl||(this.options.resolveUrl=K.arweaveGatewayManager.resolveUrl.bind(K.arweaveGatewayManager)),delete this.options.preset}async initializeEssentia(){if(this.initialized)return;const t=(await Promise.resolve().then(()=>require("./essentia-wasm.es-7mXF1zkQ.cjs"))).EssentiaWASM;await t.ready,this.essentiaWASM=t;const n=await Promise.resolve().then(()=>require("./essentia.js-model.es-h47asA0k.cjs"));this.essentiaModel=n,this.extractor=new n.EssentiaTFInputExtractor(this.essentiaWASM,"musicnn");const r=new n.EssentiaTFInputExtractor(this.essentiaWASM,"vggish");this.extractors.set("vggish",r),this.initialized=!0}async resolveUrlWithCache(e){if(this.resolvedUrlCache.has(e))return this.resolvedUrlCache.get(e);if(!this.options.resolveUrl)return e;try{const t=await this.options.resolveUrl(e);return this.resolvedUrlCache.set(e,t),t!==e&&console.info("[MusicClassifier] Resolved URL to alternate gateway",{originalUrl:e,resolvedUrl:t}),t}catch(t){return console.warn("[MusicClassifier] URL resolution failed, using original URL",{url:e,error:String(t)}),this.resolvedUrlCache.set(e,e),e}}async loadModelWithRetry(e,t=3,n=1e3){if(this.options.enableModelCache)return ie.getOrFetchGraphModel(G,e,{resolveUrl:this.options.resolveUrl,invalidateUrlCache:i=>K.arweaveGatewayManager.invalidateCacheForUrl(i),maxRetries:t,baseDelayMs:n});let r=null;const o=await this.resolveUrlWithCache(e);for(let i=0;i<t;i++)try{return await G.loadGraphModel(o)}catch(s){r=s;const c=String(s).toLowerCase();if(!(c.includes("fetch")||c.includes("network")||c.includes("timeout")||c.includes("failed to fetch")||c.includes("networkerror"))||i===t-1)throw s;const f=n*Math.pow(2,i);console.warn(`[MusicClassifier] Model load failed (attempt ${i+1}/${t}), retrying in ${f}ms...`,{originalUrl:e,resolvedUrl:o,error:String(s)}),await new Promise(d=>setTimeout(d,f))}throw r}async initializeEssentiaModelWithRetry(e,t,n=3,r=1e3){for(let o=0;o<n;o++){const i=await this.resolveUrlWithCache(e),s=t==="vggish"?this.essentiaModel.TensorflowVGGish:this.essentiaModel.TensorflowMusiCNN,c=new s(G,i);try{return await c.initialize(),c}catch(u){const f=String(u).toLowerCase();if(!(f.includes("fetch")||f.includes("network")||f.includes("timeout")||f.includes("failed to fetch")||f.includes("networkerror")||f.includes("404"))||o===n-1)throw u;K.arweaveGatewayManager.invalidateCacheForUrl(e);const g=r*Math.pow(2,o);console.warn(`[MusicClassifier] Essentia model init failed (attempt ${o+1}/${n}), re-resolving and retrying in ${g}ms...`,{url:e,resolvedUrl:i,error:String(u)}),await new Promise(b=>setTimeout(b,g))}}throw new Error(`[MusicClassifier] Essentia model failed to load after ${n} retries: ${e}`)}async getEmbeddingModel(e,t){if(this.embeddingModelCache.has(e))return this.embeddingModelCache.get(e);const n=we(e,t);let r;if(n==="effnet")r=await this.loadModelWithRetry(e);else if(n==="vggish"){if(!this.essentiaModel)throw new Error("Essentia not initialized. Call initializeEssentia() first.");if(this.options.enableModelCache){const o=await ie.getOrFetchEssentiaUrl(e,{resolveUrl:this.options.resolveUrl,invalidateUrlCache:i=>K.arweaveGatewayManager.invalidateCacheForUrl(i)});r=new this.essentiaModel.TensorflowVGGish(G,o),await r.initialize()}else r=await this.initializeEssentiaModelWithRetry(e,"vggish")}else{if(!this.essentiaModel)throw new Error("Essentia not initialized. Call initializeEssentia() first.");if(this.options.enableModelCache){const o=await ie.getOrFetchEssentiaUrl(e,{resolveUrl:this.options.resolveUrl,invalidateUrlCache:i=>K.arweaveGatewayManager.invalidateCacheForUrl(i)});r=new this.essentiaModel.TensorflowMusiCNN(G,o),await r.initialize()}else r=await this.initializeEssentiaModelWithRetry(e,"musicnn")}return this.options.cacheEmbeddings&&this.embeddingModelCache.set(e,r),r}clearEmbeddingCache(){for(const e of this.embeddingModelCache.values())e.dispose?e.dispose():e.terminate&&e.terminate();this.embeddingModelCache.clear()}clearClassifierCache(){for(const e of this.classifierModelCache.values())e.terminate&&e.terminate();this.classifierModelCache.clear()}clearAllCaches(){this.clearEmbeddingCache(),this.clearClassifierCache(),this.resolvedUrlCache.clear()}getFeaturesForArchitecture(e,t){switch(t){case"effnet":return this.extractor.computeFrameWise(e,256).melSpectrum;case"vggish":const n=this.extractors.get("vggish");return n?n.computeFrameWise(e,160):(console.warn("VGGish extractor not initialized, falling back to default 96-band extractor."),this.extractor.computeFrameWise(e,256));case"tempocnn":return console.warn("TempoCNN architecture requested but using default 96-band extractor. Results may be suboptimal for TempoCNN models."),this.extractor.computeFrameWise(e,256);default:return this.extractor.computeFrameWise(e,256)}}sliceAudioSignal(e,t){if(!this.options.analysisDurationSeconds&&this.options.analysisStartPosition===void 0)return e;const n=e.length,r=n/t,o=Math.min(this.options.analysisDurationSeconds??r,r),i=this.options.analysisStartPosition??.5,s=Math.floor(o*t),c=n-s,u=Math.max(0,Math.floor(i*c)),f=Math.min(u+s,n);return console.info(`[MusicClassifier] Analyzing segment: ${o.toFixed(1)}s starting at ${i} (samples ${u}-${f} of ${n}, ${(u/t).toFixed(1)}s-${(f/t).toFixed(1)}s of ${r.toFixed(1)}s)`),e.slice(u,f)}async analyze(e){try{await this.initializeEssentia();let t;if(typeof e=="string"){const u=await(await fetch(e)).arrayBuffer(),f=typeof self<"u"?self:typeof globalThis<"u"?globalThis:{},d=f.AudioContext||f.webkitAudioContext,g=f.OfflineAudioContext||f.webkitOfflineAudioContext,b=d?new d:g?new g(1,44100,44100):(()=>{throw new Error("No Web Audio API available in this context")})(),S=await b.decodeAudioData(u);t=await this.extractor.downsampleAudioBuffer(S,b.sampleRate)}else t=e.audioSignal;const n=this.sliceAudioSignal(t,16e3),r=Math.max(0,Math.floor((n.length-512)/256)+1),o=[],i={genres:[],moods:[],mood_tags:[],vibe_metrics:{}};if(this.options.models?.genre){const s=this.options.models.genre,c=ue(s)?s.classifier:s.modelUrl;let u;ue(s)&&s.classifierType?u=s.classifierType:Oe(s)&&s.genreType?u=s.genreType:u=Rt(c);const f=It(u);i.genres=await this.runModelPrediction(s,n,f),i.primary_genre=i.genres.length>0?i.genres[0].name:"Unknown",o.push(re(s))}if(this.options.models?.mood){const s=this.options.models.mood,c=Oe(s)?yr:vr;i.moods=await this.runModelPrediction(s,n,c),i.mood_tags=i.moods.slice(0,3).map(u=>u.name),o.push(re(s))}if(this.options.models?.danceability){const s=this.options.models.danceability,u=(await this.runModelPrediction(s,n,br)).find(f=>f.name==="danceable");i.vibe_metrics.danceability=u?.confidence??0,o.push(re(s))}if(this.options.models?.voice){const s=this.options.models.voice,u=(await this.runModelPrediction(s,n,wr)).find(f=>f.name==="instrumental");i.vibe_metrics.instrumental_probability=u?.confidence??0,o.push(re(s))}if(this.options.models?.acoustic){const s=this.options.models.acoustic,u=(await this.runModelPrediction(s,n,Mr)).find(f=>f.name==="electronic");i.vibe_metrics.electronic_probability=u?.confidence??0,o.push(re(s))}if(i.moods){const s=i.moods.find(u=>u.name==="energetic"||u.name==="upbeat"||u.name==="epic"),c=i.moods.find(u=>u.name==="happy"||u.name==="positive"||u.name==="uplifting");s&&(i.vibe_metrics.energy=s.confidence),c&&(i.vibe_metrics.valence=c.confidence)}return{genres:i.genres||[],moods:i.moods||[],primary_genre:i.primary_genre||"Unknown",mood_tags:i.mood_tags||[],vibe_metrics:i.vibe_metrics,analysis_metadata:{models_used:o,model_used:o.length>0?o[0]:void 0,frames_analyzed:r,duration_analyzed:n.length/16e3,analyzed_at:new Date().toISOString()}}}catch(t){throw console.error("Music analysis failed:",t),t}}async runClassifierOnEmbeddings(e,t){if(t.length===0||t[0].length===0)return console.warn("Empty embeddings provided to classifier"),[];const n=await this.loadModelWithRetry(e),r=G.tensor2d(t);let o=[];try{const i=n.predict(r),s=await i.data(),c=i.shape,u=c[c.length-1],f=Math.max(1,Math.floor(s.length/u)),d=new Array(u).fill(0);for(let g=0;g<f;g++)for(let b=0;b<u;b++)d[b]+=s[g*u+b];o=d.map(g=>g/f),i.dispose()}finally{r.dispose(),n.dispose()}return o}async predictWithTwoStepModel(e,t){const n=we(e.embedding,e.embeddingType),r=this.getFeaturesForArchitecture(t,n);if(r.length===0)return console.warn("No features extracted from audio signal"),[];const o=await this.getEmbeddingModel(e.embedding,e.embeddingType);let i;return n==="effnet"?i=await this.runEffnetEmbedding(o,r):n==="vggish"?i=await this.runEssentiaEmbedding(o,r):i=await this.runEssentiaEmbedding(o,r),i.length===0?(console.warn("No embeddings produced by embedding model"),[]):await this.runClassifierOnEmbeddings(e.classifier,i)}getModelInputNames(e){const t=[];try{if(e.inputs&&Array.isArray(e.inputs))for(const n of e.inputs)n&&n.name&&t.push(n.name);if(t.length===0&&e.executor){const n=e.executor;if(n._signature&&n._signature.inputs)for(const r of Object.keys(n._signature.inputs))t.push(r)}if(t.length===0&&e.inputNodes){const n=e.inputNodes;Array.isArray(n)&&t.push(...n)}if(t.length===0&&e.metadata){const n=e.metadata;if(n.signature&&n.signature.inputs)for(const r of Object.keys(n.signature.inputs))t.push(r)}if(t.length===0){const n=e;if(n.graph&&n.graph.inputs)for(const r of Object.keys(n.graph.inputs))t.push(r)}}catch(n){console.warn("[MusicClassifier] Error discovering input names:",n)}return t}async runEffnetEmbedding(e,t){const n=t.length,r=64,o=128,i=96;if(n===0)return[];(t[0]?.length??0)!==i&&console.warn(`[MusicClassifier] EffNet expects ${i}-band mel features but got ${t[0]?.length}-band frames. Results will be unreliable.`);const s=[],c=Math.max(0,n-o),u=new Array(i).fill(0),f=new Float32Array(r*o*i);for(let g=0;g<r;g++){const b=Math.round(g*c/(r-1));for(let S=0;S<o;S++){const R=t[b+S]??u,I=(g*o+S)*i;for(let A=0;A<i;A++)f[I+A]=R[A]??0}}const d=G.tensor3d(f,[r,o,i]);try{const g=this.getModelInputNames(e);if(g.length===0)throw new Error("Could not discover model input names");const b={};for(const k of g)k.includes("melspectrogram")||k.includes("mel")||k.includes("spectrogram")?b[k]=d:k.includes("saver")||k.includes("filename")?b[k]=G.scalar(""):b[k]=d;const S=e.execute(b);let R;if(Array.isArray(S)?R=S[0]:S&&typeof S=="object"&&!("data"in S)?R=Object.values(S)[0]:R=S,!R||typeof R.data!="function")throw new Error("Model execution did not return a valid tensor");const I=await R.data(),A=R.shape,B=A[A.length-1],N=Math.max(1,Math.floor(I.length/B));for(let k=0;k<N;k++)s.push(Array.from(I.slice(k*B,(k+1)*B)));R.dispose();for(const[k,C]of Object.entries(b))C!==d&&C.dispose()}finally{d.dispose()}return s}async runEssentiaEmbedding(e,t){const n=await e.predict(t,!0);return!n||n.length===0?[]:n}async runModelPrediction(e,t,n){let r;if(ue(e))r=await this.predictWithTwoStepModel(e,t);else{const o=we(e.modelUrl,e.modelType),i=this.getFeaturesForArchitecture(t,o);r=await this.predictWithModel(e.modelUrl,i)}return this.mapPredictions(r,n)}async predictWithModel(e,t){if(!this.essentiaModel)throw new Error("Essentia not initialized. Call initializeEssentia() first.");let n;if(this.options.enableModelCache){const s=await ie.getOrFetchEssentiaUrl(e,{resolveUrl:this.options.resolveUrl,invalidateUrlCache:c=>K.arweaveGatewayManager.invalidateCacheForUrl(c)});n=new this.essentiaModel.TensorflowMusiCNN(G,s),await n.initialize()}else n=await this.initializeEssentiaModelWithRetry(e,"musicnn");const r=await n.predict(t,!0);if(!r||r.length===0)return[];const o=r[0].length,i=[];for(let s=0;s<o;s++){const c=r.reduce((u,f)=>u+f[s],0);i.push(c/r.length)}return n.terminate&&n.terminate(),i}mapPredictions(e,t){return e.length>0&&e.length!==t.length&&console.warn(`[MusicClassifier] Model returned ${e.length} outputs but ${t.length} labels are configured — tags may be mislabeled. Check that the label list matches the model.`),e.map((n,r)=>({name:t[r]||`unknown_${r}`,confidence:n})).sort((n,r)=>r.confidence-n.confidence).filter(n=>n.confidence>=this.options.threshold).slice(0,this.options.topN)}}exports.AVAILABLE_PRESETS=Cr;exports.AudioAnalyzer=Le;exports.BeatConverter=Ce;exports.ButtonMapper=be;exports.DANCEABILITY_PRESETS=He;exports.DEFAULT_ARWEAVE_MODELS=Me;exports.DEFAULT_CREPE_MODEL_URL=Se;exports.DISCOGS400_GENRES=Ue;exports.EssentiaPitchDetector=he;exports.GENRE_PRESETS=qe;exports.LevelGenerator=Ee;exports.LevelSerializer=fr;exports.MOOD_PRESETS=We;exports.ModelCache=wt;exports.MusicClassifier=Dr;exports.PitchAnalyzer=nr;exports.PitchBeatLinker=Mt;exports.averageEmbeddings=Sr;exports.detectGenreListType=Rt;exports.detectModelArchitecture=we;exports.formatModelForMetadata=re;exports.getGenreLabels=It;exports.isSingleStepModel=Oe;exports.isTwoStepModel=ue;exports.modelCache=ie;