@schmooky/zvuk 1.14.0 → 2.0.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/index.js CHANGED
@@ -1,8 +1,8 @@
1
- var _=class extends Error{constructor(t,e){super(t,e),this.name="ZvukError";}},x=class extends _{constructor(){super("Engine is closed. Create a new engine with createEngine()."),this.name="EngineClosedError";}};function ft(o){return o?` Did you mean "${o}"?`:""}var T=class extends _{constructor(t,e){super(`Bus "${t}" is not configured. Declare it in createEngine({ buses: { ... } }).${ft(e)}`),this.name="BusNotFoundError";}},A=class extends _{constructor(t,e){super(`Sound "${t}" is not loaded. Call engine.loadSound() or load a bank that contains it.${ft(e)}`),this.name="SoundNotFoundError";}};function tt(o){return o instanceof Error?o.message:String(o)}var M=class extends _{constructor(t,e,i){super(i??`Failed to decode audio at "${t}": ${tt(e)}`,{cause:e}),this.name="DecodeError";}},N=class extends _{failures;constructor(t){let e=t.map(i=>` - ${i.name}: ${tt(i.cause)}`).join(`
1
+ var O=class extends Error{constructor(t,e){super(t,e),this.name="ZvukError";}},x=class extends O{constructor(){super("Engine is closed. Create a new engine with createEngine()."),this.name="EngineClosedError";}};function Ot(n){return n?` Did you mean "${n}"?`:""}var P=class extends O{constructor(t,e){super(`Bus "${t}" is not configured. Declare it in createEngine({ buses: { ... } }).${Ot(e)}`),this.name="BusNotFoundError";}},k=class extends O{constructor(t,e){super(`Sound "${t}" is not loaded. Call engine.loadSound() or load a bank that contains it.${Ot(e)}`),this.name="SoundNotFoundError";}},G=class extends O{sprite;region;constructor(t,e,i){let s=i.length>0?` Regions: ${i.map(r=>`"${r}"`).join(", ")}.`:"";super(`Sprite "${t}" has no region "${e}".${s}`),this.name="SpriteRegionNotFoundError",this.sprite=t,this.region=e;}};function pt(n){return n instanceof Error?n.message:String(n)}var B=class extends O{constructor(t,e,i){super(i??`Failed to decode audio at "${t}": ${pt(e)}`,{cause:e}),this.name="DecodeError";}},z=class extends O{failures;constructor(t){let e=t.map(i=>` - ${i.name}: ${pt(i.cause)}`).join(`
2
2
  `);super(`Failed to preload ${t.length} item(s):
3
- ${e}`,{cause:t[0]?.cause}),this.name="PreloadError",this.failures=t;}},B=class extends M{attempts;constructor(t,e){let i=e[e.length-1],s=e.map(r=>` - ${r.url}: ${tt(r.cause)}`).join(`
3
+ ${e}`,{cause:t[0]?.cause}),this.name="PreloadError",this.failures=t;}},j=class extends B{attempts;constructor(t,e){let i=e[e.length-1],s=e.map(r=>` - ${r.url}: ${pt(r.cause)}`).join(`
4
4
  `);super(t[t.length-1]??"<empty>",i?.cause,`Failed to load any of ${t.length} fallback URLs:
5
- ${s}`),this.name="AggregateDecodeError",this.attempts=e;}};var et=class{input;output;compressor;makeup;ctx;_bypassed=false;constructor(t,e={}){this.ctx=t,this.input=t.createGain(),this.output=t.createGain(),this.compressor=t.createDynamicsCompressor(),this.makeup=t.createGain(),this.applyConfig(e),this.wire();}applyConfig(t){let e=this.ctx.currentTime;t.threshold!=null&&this.compressor.threshold.setValueAtTime(t.threshold,e),t.knee!=null&&this.compressor.knee.setValueAtTime(t.knee,e),t.ratio!=null&&this.compressor.ratio.setValueAtTime(t.ratio,e),t.attack!=null&&this.compressor.attack.setValueAtTime(t.attack,e),t.release!=null&&this.compressor.release.setValueAtTime(t.release,e),t.makeupGain!=null&&this.makeup.gain.setValueAtTime(10**(t.makeupGain/20),e);}get reduction(){return this.compressor.reduction}get bypassed(){return this._bypassed}set bypassed(t){this._bypassed!==t&&(this._bypassed=t,this.wire());}dispose(){try{this.input.disconnect(),this.compressor.disconnect(),this.makeup.disconnect(),this.output.disconnect();}catch{}}wire(){try{this.input.disconnect(),this.compressor.disconnect(),this.makeup.disconnect();}catch{}this._bypassed?this.input.connect(this.output):(this.input.connect(this.compressor),this.compressor.connect(this.makeup),this.makeup.connect(this.output));}};var it=class{input;output;gain;analyser;buf;rafId=null;lastTickMs=0;envelope=1;targetGain=1;ctx;cfg;_bypassed=false;sourceBus;constructor(t,e,i={}){this.ctx=t,this.sourceBus=e,this.cfg={amount:i.amount??.5,attack:i.attack??.08,release:i.release??.4,threshold:i.threshold??.05},this.input=t.createGain(),this.output=t.createGain(),this.gain=t.createGain(),this.input.connect(this.gain).connect(this.output),this.analyser=t.createAnalyser(),this.analyser.fftSize=1024,this.buf=new Float32Array(this.analyser.fftSize),e.output.connect(this.analyser),typeof document<"u"&&document.addEventListener("visibilitychange",this.handleVisibility),this.startLoop();}setAmount(t){this.cfg.amount=Math.max(0,Math.min(1,t));}setThreshold(t){this.cfg.threshold=Math.max(0,t);}get bypassed(){return this._bypassed}set bypassed(t){this._bypassed!==t&&(this._bypassed=t,t?(this.releaseToUnity(),this.stopLoop()):(this.resetEnvelope(),this.startLoop()));}dispose(){this.stopLoop(),typeof document<"u"&&document.removeEventListener("visibilitychange",this.handleVisibility);try{this.sourceBus.output.disconnect(this.analyser);}catch{}try{this.input.disconnect(),this.gain.disconnect(),this.analyser.disconnect(),this.output.disconnect();}catch{}}tick=t=>{let e=.016666666666666666;if(t!=null&&this.lastTickMs>0&&(e=Math.min(.1,Math.max(.001,(t-this.lastTickMs)/1e3))),t!=null&&(this.lastTickMs=t),this._bypassed){this.rafId=null;return}this.analyser.getFloatTimeDomainData(this.buf);let i=0;for(let l=0;l<this.buf.length;l++){let d=this.buf[l]??0;i+=d*d;}let s=Math.sqrt(i/this.buf.length),n=Math.max(0,s-this.cfg.threshold)>0?1-this.cfg.amount:1,u=(n<this.envelope?this.cfg.attack:this.cfg.release)||.001,c=1-Math.exp(-e/u);this.envelope=this.envelope+c*(n-this.envelope),Math.abs(this.envelope-this.targetGain)>.001&&(this.targetGain=this.envelope,this.gain.gain.setTargetAtTime(this.envelope,this.ctx.currentTime,.005)),this.rafId=requestAnimationFrame(this.tick);};handleVisibility=()=>{document.visibilityState==="visible"&&(this.resetEnvelope(),this._bypassed||this.startLoop());};resetEnvelope(){this.envelope=1,this.targetGain=1,this.lastTickMs=0,this.releaseToUnity();}releaseToUnity(){this.gain.gain.setTargetAtTime(1,this.ctx.currentTime,.005);}startLoop(){typeof requestAnimationFrame>"u"||this.rafId==null&&this.tick();}stopLoop(){this.rafId!=null&&cancelAnimationFrame(this.rafId),this.rafId=null;}};var st=class{input;output;filter;ctx;_bypassed=false;constructor(t,e={}){this.ctx=t,this.input=t.createGain(),this.output=t.createGain(),this.filter=t.createBiquadFilter(),this.filter.type=e.type??"lowpass",this.filter.frequency.value=e.frequency??1e3,this.filter.Q.value=e.q??1,this.filter.gain.value=e.gain??0,this.wire();}setFrequency(t){this.filter.frequency.setValueAtTime(t,this.ctx.currentTime);}setQ(t){this.filter.Q.setValueAtTime(t,this.ctx.currentTime);}setType(t){this.filter.type=t;}setGain(t){this.filter.gain.setValueAtTime(t,this.ctx.currentTime);}get bypassed(){return this._bypassed}set bypassed(t){this._bypassed!==t&&(this._bypassed=t,this.wire());}dispose(){try{this.input.disconnect(),this.filter.disconnect(),this.output.disconnect();}catch{}}wire(){try{this.input.disconnect(),this.filter.disconnect();}catch{}this._bypassed?this.input.connect(this.output):(this.input.connect(this.filter),this.filter.connect(this.output));}};var rt=class{input;output;dry;wet;convolver;preDelay;ctx;_bypassed=false;_wet;constructor(t,e={}){this.ctx=t,this.input=t.createGain(),this.output=t.createGain(),this.dry=t.createGain(),this.wet=t.createGain(),this.preDelay=t.createDelay(1),this.convolver=t.createConvolver();let i=e.wet??.3;this._wet=i,this.dry.gain.value=1-i,this.wet.gain.value=i,e.impulse?this.convolver.buffer=e.impulse:this.convolver.buffer=this.synthIR(e.decay?.seconds??1.5),this.preDelay.delayTime.value=e.decay?.preDelay??0,this.input.connect(this.dry).connect(this.output),this.input.connect(this.preDelay).connect(this.convolver).connect(this.wet).connect(this.output);}setWet(t){let e=Math.max(0,Math.min(1,t));if(this._wet=e,this._bypassed)return;let i=this.ctx.currentTime;this.dry.gain.setValueAtTime(1-e,i),this.wet.gain.setValueAtTime(e,i);}setImpulse(t){this.convolver.buffer=t;}get bypassed(){return this._bypassed}set bypassed(t){if(this._bypassed===t)return;this._bypassed=t;let e=this.ctx.currentTime;t?(this.dry.gain.setValueAtTime(1,e),this.wet.gain.setValueAtTime(0,e)):(this.dry.gain.setValueAtTime(1-this._wet,e),this.wet.gain.setValueAtTime(this._wet,e));}dispose(){try{this.input.disconnect(),this.dry.disconnect(),this.wet.disconnect(),this.preDelay.disconnect(),this.convolver.disconnect(),this.output.disconnect();}catch{}}synthIR(t){let e=this.ctx.sampleRate,i=Math.floor(e*t),s=this.ctx.createBuffer(2,i,e);for(let r=0;r<2;r++){let n=s.getChannelData(r);for(let a=0;a<i;a++){let u=a/i;n[a]=(Math.random()*2-1)*(1-u)**3;}}return s}};var ot=class o{factor;constructor(t=1){this.factor=t;}process(t){if(this.factor===1)return new Float32Array(t);let e=Math.floor(t.length/this.factor),i=new Float32Array(e),r=Math.max(160,Math.floor(4096/Math.sqrt(this.factor))),n=Math.max(48,Math.floor(r/4)),a=Math.max(1,r-n),u=Math.max(1,Math.floor(a/this.factor)),c=new Float32Array(n),l=new Float32Array(n);for(let p=0;p<n;p++){let b=p/(n-1),h=Math.sin(Math.PI*b/2),v=Math.cos(Math.PI*b/2);c[p]=h*h,l[p]=v*v;}let d=Math.max(0,Math.floor(a*.03)),m=0,g=0;for(;m+r<t.length&&g+r<e;){let p=m;if(this.factor<2.5&&g>=n){let f=-1/0,y=Math.min(64,a);for(let O=-y;O<=y;O+=4){let W=m+O;if(W>=0&&W+n<t.length){let J=0;for(let j=0;j<n;j++)J+=(i[g-n+j]??0)*(t[W+j]??0);J>f&&(f=J,p=W);}}}d>0&&(p=Math.max(0,Math.min(t.length-r,p+(Math.random()*2-1)*d|0)));let b=0,h=0;if(g>0)for(let f=0;f<n;f++){let y=i[g-n+f]??0,O=t[p+f]??0;b+=y*y,h+=O*O;}let v=1;h>1e-8&&b>0&&(v=Math.sqrt(b/h)),v=Math.min(1.1,Math.max(.9,v));for(let f=0;f<r&&g+f<e;f++){let y=t[p+f]??0;if(f<n&&g>0){let O=i[g+f]??0;i[g+f]=O*(l[f]??0)+y*v*(c[f]??0);}else i[g+f]=y;}m+=a,g+=u;}for(let p=g;p<e;p++){let b=p*this.factor,h=Math.floor(b),v=b-h;h>=0&&h+1<t.length?i[p]=(t[h]??0)*(1-v)+(t[h+1]??0)*v:i[p]=t[Math.min(t.length-1,Math.max(0,h))]??0;}if(this.factor>1){let p=Math.min(.12,Math.max(.05,.18/this.factor)),b=0;for(let h=0;h<i.length;h++){let v=i[h]??0;i[h]=v+p*(v-b),b=v;}}return i}static stretchBuffer(t,e,i){if(i===1)return e;let s=new o(i),r=[];for(let u=0;u<e.numberOfChannels;u++)r.push(s.process(e.getChannelData(u)));let n=Math.max(...r.map(u=>u.length)),a=t.createBuffer(e.numberOfChannels,n,e.sampleRate);for(let u=0;u<e.numberOfChannels;u++)a.copyToChannel(r[u],u);return a}};var gt="zvuk-realtime-stretch",mt=new WeakSet,Mt=`
5
+ ${s}`),this.name="AggregateDecodeError",this.attempts=e;}};function S(n,t,e,i,s){let r=Math.max(0,i),o=n.value;if(Wt(n,t,o),r===0){ft(n,e,()=>n.setValueAtTime(e,t));return}if(s==="linear"){ft(n,e,()=>n.linearRampToValueAtTime(e,t+r));return}let a=Bt(o,e,s,64);ft(n,e,()=>n.setValueCurveAtTime(a,t,r));}function Wt(n,t,e){let i=n;if(typeof i.cancelAndHoldAtTime=="function")try{i.cancelAndHoldAtTime(t);}catch{n.cancelScheduledValues(t);}else n.cancelScheduledValues(t);try{n.setValueAtTime(e,t);}catch{try{n.cancelScheduledValues(0),n.setValueAtTime(e,t);}catch{}}}function ft(n,t,e){try{e();}catch{try{n.value=t;}catch{}}}function kt(n,t,e=33){return Bt(n,t,"equal-power",e)}function st(n,t,e,i,s){try{s.fadeIn?(n.setValueAtTime(0,t),n.setValueCurveAtTime(kt(0,1),t,s.fadeInSec??i)):n.setValueAtTime(1,t);}catch{n.value=1;}if(!s.fadeOut)return;let r=t+e-i;try{n.setValueAtTime(1,r),n.setValueCurveAtTime(kt(1,0),r,i);}catch{}}function Bt(n,t,e,i){let s=new Float32Array(i),r=t>=n;for(let o=0;o<i;o++){let a=o/(i-1),u=Yt(a,e,r);s[o]=n+(t-n)*u;}return s}function Yt(n,t,e=true){switch(t){case "easeIn":return n*n;case "easeOut":return 1-(1-n)*(1-n);case "easeInOut":return n<.5?2*n*n:1-2*(1-n)*(1-n);case "equal-power":return e?Math.sin(n*Math.PI/2):1-Math.cos(n*Math.PI/2);default:return n}}function m(n,t,e,i){try{if(n.cancelScheduledValues(e),i<=0){n.setValueAtTime(t,e);return}n.setValueAtTime(n.value,e),n.setTargetAtTime(t,e,i);}catch{n.value=t;}}var E=.01,F=class{dry;wet;ctx;_bypassed;constructor(t,e,i,s,r){this.ctx=t,this._bypassed=false,this.dry=t.createGain(),this.wet=t.createGain(),this.dry.gain.value=0,this.wet.gain.value=1,e.connect(i),s.connect(this.wet).connect(r),e.connect(this.dry).connect(r);}get bypassed(){return this._bypassed}set bypassed(t){if(this._bypassed===t)return;this._bypassed=t;let e=this.ctx.currentTime;m(this.wet.gain,t?0:1,e,E),m(this.dry.gain,t?1:0,e,E);}dispose(){for(let t of [this.dry,this.wet])try{t.disconnect();}catch{}}};var mt=class{input;output;compressor;makeup;ctx;bypass;constructor(t,e={}){this.ctx=t,this.input=t.createGain(),this.output=t.createGain(),this.compressor=t.createDynamicsCompressor(),this.makeup=t.createGain(),this.applyConfig(e),this.compressor.connect(this.makeup),this.bypass=new F(t,this.input,this.compressor,this.makeup,this.output);}applyConfig(t){let e=this.ctx.currentTime;t.threshold!=null&&this.compressor.threshold.setValueAtTime(t.threshold,e),t.knee!=null&&this.compressor.knee.setValueAtTime(t.knee,e),t.ratio!=null&&this.compressor.ratio.setValueAtTime(t.ratio,e),t.attack!=null&&this.compressor.attack.setValueAtTime(t.attack,e),t.release!=null&&this.compressor.release.setValueAtTime(t.release,e),t.makeupGain!=null&&this.makeup.gain.setValueAtTime(10**(t.makeupGain/20),e);}get reduction(){return this.compressor.reduction}get bypassed(){return this.bypass.bypassed}set bypassed(t){this.bypass.bypassed=t;}dispose(){this.bypass.dispose();for(let t of [this.input,this.compressor,this.makeup,this.output])try{t.disconnect();}catch{}}};var q=class{input;output;gain;analyser;buf;rafId=null;lastTickMs=0;envelope=1;targetGain=1;ctx;cfg;_bypassed=false;sourceBus;constructor(t,e,i={}){this.ctx=t,this.sourceBus=e,this.cfg={amount:i.amount??.5,attack:i.attack??.08,release:i.release??.4,threshold:i.threshold??.05},this.input=t.createGain(),this.output=t.createGain(),this.gain=t.createGain(),this.input.connect(this.gain).connect(this.output),this.analyser=t.createAnalyser(),this.analyser.fftSize=1024,this.buf=new Float32Array(this.analyser.fftSize),e.output.connect(this.analyser),typeof document<"u"&&document.addEventListener("visibilitychange",this.handleVisibility),this.startLoop();}setAmount(t){this.cfg.amount=Math.max(0,Math.min(1,t));}setThreshold(t){this.cfg.threshold=Math.max(0,t);}get bypassed(){return this._bypassed}set bypassed(t){this._bypassed!==t&&(this._bypassed=t,t?(this.releaseToUnity(),this.stopLoop()):(this.resetEnvelope(),this.startLoop()));}dispose(){this.stopLoop(),typeof document<"u"&&document.removeEventListener("visibilitychange",this.handleVisibility);try{this.sourceBus.output.disconnect(this.analyser);}catch{}try{this.input.disconnect(),this.gain.disconnect(),this.analyser.disconnect(),this.output.disconnect();}catch{}}tick=t=>{let e=.016666666666666666;if(t!=null&&this.lastTickMs>0&&(e=Math.min(.1,Math.max(.001,(t-this.lastTickMs)/1e3))),t!=null&&(this.lastTickMs=t),this._bypassed){this.rafId=null;return}this.analyser.getFloatTimeDomainData(this.buf);let i=0;for(let l=0;l<this.buf.length;l++){let d=this.buf[l]??0;i+=d*d;}let s=Math.sqrt(i/this.buf.length),o=Math.max(0,s-this.cfg.threshold)>0?1-this.cfg.amount:1,u=(o<this.envelope?this.cfg.attack:this.cfg.release)||.001,c=1-Math.exp(-e/u);this.envelope=this.envelope+c*(o-this.envelope),Math.abs(this.envelope-this.targetGain)>.001&&(this.targetGain=this.envelope,this.gain.gain.setTargetAtTime(this.envelope,this.ctx.currentTime,.005)),this.rafId=requestAnimationFrame(this.tick);};handleVisibility=()=>{document.visibilityState==="visible"&&(this.resetEnvelope(),this._bypassed||this.startLoop());};resetEnvelope(){this.envelope=1,this.targetGain=1,this.lastTickMs=0,this.releaseToUnity();}releaseToUnity(){this.gain.gain.setTargetAtTime(1,this.ctx.currentTime,.005);}startLoop(){typeof requestAnimationFrame>"u"||this.rafId==null&&this.tick();}stopLoop(){this.rafId!=null&&cancelAnimationFrame(this.rafId),this.rafId=null;}};var gt=class{input;output;filter;ctx;bypass;constructor(t,e={}){this.ctx=t,this.input=t.createGain(),this.output=t.createGain(),this.filter=t.createBiquadFilter(),this.filter.type=e.type??"lowpass",this.filter.frequency.value=e.frequency??1e3,this.filter.Q.value=e.q??1,this.filter.gain.value=e.gain??0,this.bypass=new F(t,this.input,this.filter,this.filter,this.output);}setFrequency(t){m(this.filter.frequency,t,this.ctx.currentTime,E);}setQ(t){m(this.filter.Q,t,this.ctx.currentTime,E);}setType(t){this.filter.type=t;}setGain(t){m(this.filter.gain,t,this.ctx.currentTime,E);}get bypassed(){return this.bypass.bypassed}set bypassed(t){this.bypass.bypassed=t;}dispose(){this.bypass.dispose();for(let t of [this.input,this.filter,this.output])try{t.disconnect();}catch{}}};var bt=class{input;output;dry;wet;convolver;preDelay;ctx;_bypassed=false;_wet;constructor(t,e={}){this.ctx=t,this.input=t.createGain(),this.output=t.createGain(),this.dry=t.createGain(),this.wet=t.createGain(),this.preDelay=t.createDelay(1),this.convolver=t.createConvolver();let i=e.wet??.3;this._wet=i,this.dry.gain.value=1-i,this.wet.gain.value=i,e.impulse?this.convolver.buffer=e.impulse:this.convolver.buffer=this.synthIR(e.decay?.seconds??1.5),this.preDelay.delayTime.value=e.decay?.preDelay??0,this.input.connect(this.dry).connect(this.output),this.input.connect(this.preDelay).connect(this.convolver).connect(this.wet).connect(this.output);}setWet(t){let e=Math.max(0,Math.min(1,t));this._wet=e,!this._bypassed&&this.glideMix(1-e,e);}glideMix(t,e){let i=this.ctx.currentTime;m(this.dry.gain,t,i,E),m(this.wet.gain,e,i,E);}setImpulse(t){this.convolver.buffer=t;}get bypassed(){return this._bypassed}set bypassed(t){this._bypassed!==t&&(this._bypassed=t,t?this.glideMix(1,0):this.glideMix(1-this._wet,this._wet));}dispose(){try{this.input.disconnect(),this.dry.disconnect(),this.wet.disconnect(),this.preDelay.disconnect(),this.convolver.disconnect(),this.output.disconnect();}catch{}}synthIR(t){let e=this.ctx.sampleRate,i=Math.floor(e*t),s=this.ctx.createBuffer(2,i,e);for(let r=0;r<2;r++){let o=s.getChannelData(r);for(let a=0;a<i;a++){let u=a/i;o[a]=(Math.random()*2-1)*(1-u)**3;}}return s}};var vt=class n{factor;constructor(t=1){this.factor=t;}process(t){if(this.factor===1)return new Float32Array(t);let e=Math.floor(t.length/this.factor),i=new Float32Array(e),r=Math.max(160,Math.floor(4096/Math.sqrt(this.factor))),o=Math.max(48,Math.floor(r/4)),a=Math.max(1,r-o),u=Math.max(1,Math.floor(a/this.factor)),c=new Float32Array(o),l=new Float32Array(o);for(let h=0;h<o;h++){let g=h/(o-1),v=Math.sin(Math.PI*g/2),b=Math.cos(Math.PI*g/2);c[h]=v*v,l[h]=b*b;}let d=Math.max(0,Math.floor(a*.03)),f=0,p=0;for(;f+r<t.length&&p+r<e;){let h=f;if(this.factor<2.5&&p>=o){let y=-1/0,M=Math.min(64,a);for(let _=-M;_<=M;_+=4){let T=f+_;if(T>=0&&T+o<t.length){let L=0;for(let it=0;it<o;it++)L+=(i[p-o+it]??0)*(t[T+it]??0);L>y&&(y=L,h=T);}}}d>0&&(h=Math.max(0,Math.min(t.length-r,h+(Math.random()*2-1)*d|0)));let g=0,v=0;if(p>0)for(let y=0;y<o;y++){let M=i[p-o+y]??0,_=t[h+y]??0;g+=M*M,v+=_*_;}let b=1;v>1e-8&&g>0&&(b=Math.sqrt(g/v)),b=Math.min(1.1,Math.max(.9,b));for(let y=0;y<r&&p+y<e;y++){let M=t[h+y]??0;if(y<o&&p>0){let _=i[p+y]??0;i[p+y]=_*(l[y]??0)+M*b*(c[y]??0);}else i[p+y]=M;}f+=a,p+=u;}for(let h=p;h<e;h++){let g=h*this.factor,v=Math.floor(g),b=g-v;v>=0&&v+1<t.length?i[h]=(t[v]??0)*(1-b)+(t[v+1]??0)*b:i[h]=t[Math.min(t.length-1,Math.max(0,v))]??0;}if(this.factor>1){let h=Math.min(.12,Math.max(.05,.18/this.factor)),g=0;for(let v=0;v<i.length;v++){let b=i[v]??0;i[v]=b+h*(b-g),g=b;}}return i}static stretchBuffer(t,e,i){if(i===1)return e;let s=new n(i),r=[];for(let u=0;u<e.numberOfChannels;u++)r.push(s.process(e.getChannelData(u)));let o=Math.max(...r.map(u=>u.length)),a=t.createBuffer(e.numberOfChannels,o,e.sampleRate);for(let u=0;u<e.numberOfChannels;u++)a.copyToChannel(r[u],u);return a}};var Nt="zvuk-realtime-stretch",Et=new WeakSet,Xt=`
6
6
  class ZvukRealtimeStretchProcessor extends AudioWorkletProcessor {
7
7
  static get parameterDescriptors() {
8
8
  return [
@@ -66,6 +66,5 @@ class ZvukRealtimeStretchProcessor extends AudioWorkletProcessor {
66
66
  }
67
67
  }
68
68
 
69
- registerProcessor('${gt}', ZvukRealtimeStretchProcessor);
70
- `;async function Ot(o){if(mt.has(o))return;let t=o.audioWorklet;if(!t)throw new Error("AudioWorklet not supported in this context");let e=new Blob([Mt],{type:"application/javascript"}),i=URL.createObjectURL(e);try{await t.addModule(i);}finally{URL.revokeObjectURL(i);}mt.add(o);}function _t(o,t={}){let e=globalThis.AudioWorkletNode;if(!e)throw new Error("AudioWorkletNode not available");let i=new e(o,gt,{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[2],processorOptions:{grainSize:t.grainSize??1024}}),s=i.parameters.get("stretch");s&&t.stretchFactor!=null&&(s.value=t.stretchFactor);let r=i;return Object.defineProperty(r,"stretch",{value:s,enumerable:true}),r.dispose=()=>{try{i.disconnect();}catch{}},r}function w(o,t,e){let i=Math.max(0,t);if(i===0)return Promise.resolve();if(o.state!=="running")return Pt(i,e);let s=o.currentTime+i;return new Promise(r=>{let n=null,a=false,u=()=>{a||(a=true,n!=null&&clearTimeout(n),n=null,r());},c=()=>{if(n=null,a)return;let l=s-o.currentTime;if(l<=0){u();return}n=setTimeout(c,Math.min(l*1e3,250));};e&&e.then(u,u),n=setTimeout(c,i*1e3);})}function Pt(o,t){return new Promise(e=>{let i=setTimeout(e,o*1e3);t&&t.then(()=>{clearTimeout(i),e();},()=>{clearTimeout(i),e();});})}function S(o,t,e,i,s){let r=Math.max(0,i),n=o.value;if(kt(o,t,n),r===0){nt(o,e,()=>o.setValueAtTime(e,t));return}if(s==="linear"){nt(o,e,()=>o.linearRampToValueAtTime(e,t+r));return}let a=vt(n,e,s,64);nt(o,e,()=>o.setValueCurveAtTime(a,t,r));}function kt(o,t,e){let i=o;if(typeof i.cancelAndHoldAtTime=="function")try{i.cancelAndHoldAtTime(t);}catch{o.cancelScheduledValues(t);}else o.cancelScheduledValues(t);try{o.setValueAtTime(e,t);}catch{}}function nt(o,t,e){try{e();}catch{o.value=t;}}function P(o,t,e=33){return vt(o,t,"equal-power",e)}function vt(o,t,e,i){let s=new Float32Array(i),r=t>=o;for(let n=0;n<i;n++){let a=n/(i-1),u=Nt(a,e,r);s[n]=o+(t-o)*u;}return s}function Nt(o,t,e=true){switch(t){case "easeIn":return o*o;case "easeOut":return 1-(1-o)*(1-o);case "easeInOut":return o<.5?2*o*o:1-2*(1-o)*(1-o);case "equal-power":return e?Math.sin(o*Math.PI/2):1-Math.cos(o*Math.PI/2);default:return o}}var Z=class{source;target;post;gainNode;ctx;disposed=false;constructor(t,e,i,s){this.source=t,this.target=e,this.post=i.post??true,this.ctx=s,this.gainNode=s.createGain(),this.gainNode.gain.value=E(i.amount??1),(this.post?t.output:t.input).connect(this.gainNode),this.gainNode.connect(e.input);}get amount(){return this.gainNode.gain.value}set amount(t){this.disposed||S(this.gainNode.gain,this.ctx.currentTime,E(t),.01,"linear");}fadeTo(t,e,i="linear"){return this.disposed?Promise.resolve():(S(this.gainNode.gain,this.ctx.currentTime,E(t),e,i),w(this.ctx,e))}dispose(){if(!this.disposed){this.disposed=true;try{this.gainNode.disconnect();}catch{}}}},F=class{name;input;fxInput;output;_level;_muted;_soloed=false;_soloVeiled=false;ctx;_concurrency;_voices=new Set;_fxChain=[];_sends=[];_meterAnalyser=null;_meterBuf=null;notifySoloChange;constructor(t,e,i={}){this.ctx=t,this.name=e,this._level=i.level??1,this._muted=i.mute??false,this._concurrency=i.concurrency??null,this.input=t.createGain(),this.fxInput=t.createGain(),this.output=t.createGain(),this.input.connect(this.fxInput),this.fxInput.connect(this.output),this.output.gain.value=this._muted?0:this._level;}get level(){return this._level}set level(t){this._level=E(t),!this._muted&&!this._soloVeiled&&this.rampOutput(this._level,.01);}get muted(){return this._muted}set muted(t){this._muted!==t&&(this._muted=t,this.rampOutput(t||this._soloVeiled?0:this._level,.01));}fadeTo(t,e,i="linear"){let s=E(t);return this._level=s,this._muted||this._soloVeiled?w(this.ctx,e):this.ramp(s,e,i)}get voiceCount(){return this._voices.size}voices(){return Array.from(this._voices)}get concurrency(){return this._concurrency}setConcurrency(t){this._concurrency=t;}applyConcurrencyOnSpawn(t,e){let i=this._concurrency;if(!i||this._voices.size<=i.max)return null;let s=i.steal??"oldest";if(s==="none")return e(),null;let r=Bt(this._voices,s,t);return r?(r.stop(),r):(e(),null)}trackVoice(t){this._voices.add(t);}releaseVoice(t){this._voices.delete(t);}addFx(t){this._fxChain.push(t),this.rewireFxChain();}removeFx(t){let e=this._fxChain.indexOf(t);e!==-1&&(this._fxChain.splice(e,1),this.rewireFxChain());}fx(){return [...this._fxChain]}meter(){if(!this._meterAnalyser){let s=this.ctx.createAnalyser();s.fftSize=1024,this.output.connect(s),this._meterAnalyser=s,this._meterBuf=new Float32Array(s.fftSize);}let t=this._meterBuf;this._meterAnalyser.getFloatTimeDomainData(t);let e=0,i=0;for(let s=0;s<t.length;s++){let r=t[s]??0;e+=r*r;let n=Math.abs(r);n>i&&(i=n);}return {rms:Math.sqrt(e/t.length),peak:i}}send(t,e={}){let i=new Z(this,t,e,this.ctx);return this._sends.push(i),i}removeSend(t){let e=this._sends.indexOf(t);e!==-1&&(this._sends.splice(e,1),t.dispose());}sends(){return [...this._sends]}solo(t=true){this._soloed!==t&&(this._soloed=t,this.notifySoloChange?.(this,t));}unsolo(){this.solo(false);}get soloed(){return this._soloed}applySoloVeil(t){this._soloVeiled=t;let e=this._muted||t?0:this._level;this.rampOutput(e,.01);}rewireFxChain(){try{this.fxInput.disconnect();for(let e of this._fxChain)e.output.disconnect();}catch{}let t=this.fxInput;for(let e of this._fxChain)t.connect(e.input),t=e.output;t.connect(this.output);}rampOutput(t,e){this.ramp(t,e,"linear");}ramp(t,e,i){let s=this.output.gain,r=this.ctx.currentTime;return S(s,r,t,e,i),w(this.ctx,e)}dispose(){for(let t of this._sends)t.dispose();this._sends=[];for(let t of this._fxChain)t.dispose();this._fxChain=[];try{this.input.disconnect(),this.fxInput.disconnect(),this.output.disconnect(),this._meterAnalyser?.disconnect();}catch{}this._meterAnalyser=null,this._meterBuf=null;}};function E(o){return Number.isNaN(o)?0:Math.min(1,Math.max(0,o))}function Bt(o,t,e){let i=t==="quietest"?new Map:null;if(i)for(let r of o)r!==e&&i.set(r,r.levelHint());let s=null;for(let r of o)if(r!==e){if(!s){s=r;continue}switch(t){case "oldest":r.startedAt<s.startedAt&&(s=r);break;case "lowest-priority":r.priority<s.priority&&(s=r);break;case "quietest":{let n=i?.get(r)??0,a=i?.get(s)??0;n<a&&(s=r);break}}}return s}var L=class{name;members;constructor(t,e){this.name=t,this.members=e;}set level(t){for(let e of this.members)e.level=t;}get level(){if(this.members.length===0)return 0;let t=0;for(let e of this.members)t+=e.level;return t/this.members.length}set muted(t){for(let e of this.members)e.muted=t;}get muted(){return this.members.length===0?false:this.members.every(t=>t.muted)}fadeTo(t,e,i="linear"){return Promise.all(this.members.map(s=>s.fadeTo(t,e,i))).then(()=>{})}solo(t=true){for(let e of this.members)e.solo(t);}unsolo(){this.solo(false);}};var V=class{name;_value;subs=new Set;constructor(t,e){this.name=t,this._value=e;}get value(){return this._value}set(t){if(t!==this._value){this._value=t;for(let e of this.subs)e(t);}}subscribe(t){return this.subs.add(t),t(this._value),()=>this.subs.delete(t)}bindTo(t,e={}){let i=e.from??0,s=e.to??1,r=e.curve??"linear",n=s>=i;return this.subscribe(a=>{let u=Math.max(0,Math.min(1,a)),c=Et(u,r,n);t(i+(s-i)*c);})}};function Et(o,t,e=true){switch(t){case "easeIn":return o*o;case "easeOut":return 1-(1-o)*(1-o);case "easeInOut":return o<.5?2*o*o:1-2*(1-o)*(1-o);case "equal-power":return e?Math.sin(o*Math.PI/2):1-Math.cos(o*Math.PI/2);default:return o}}var Ft={webm:'audio/webm; codecs="opus"',opus:'audio/ogg; codecs="opus"',ogg:'audio/ogg; codecs="vorbis"',m4a:'audio/mp4; codecs="mp4a.40.2"',mp4:'audio/mp4; codecs="mp4a.40.2"',aac:'audio/mp4; codecs="mp4a.40.2"',mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac"},at=null;function ut(o){if(typeof document>"u")return true;if(!at)try{at=document.createElement("audio");}catch{return true}let t=at.canPlayType(o);return t==="probably"||t==="maybe"}function ct(o){let t=/\.([a-z0-9]+)(?:[?#]|$)/i.exec(o);return t?.[1]?Ft[t[1].toLowerCase()]??null:null}function lt(o){if(o.length===0)throw new Error("pickSource requires at least one URL");for(let t of o){let e=ct(t);if(e&&ut(e))return t}return o[0]}function ht(o){if(o.length===0)return o;let t=[],e=[];for(let i of o){let s=ct(i);s&&ut(s)?t.push(i):e.push(i);}return [...t,...e]}var X=class{_ctx=null;_state="cold";_unlocking=null;_listeners=new Set;opts;constructor(t={}){this.opts=t;}get state(){return this._state}touch(){if(this._state==="closed")throw new x;if(!this._ctx){let t={};this.opts.latencyHint!=null&&(t.latencyHint=this.opts.latencyHint);let e=Lt();this._ctx=new e(t),this.attachVisibilityHandler(),this.attachStateChangeHandler(this._ctx);}return this._ctx}peek(){return this._ctx}async unlock(){if(this._state==="closed")throw new x;if(this._unlocking)return this._unlocking;if(this._state==="live"&&this._ctx?.state==="running")return;this.setState("unlocking");let t=this.touch();return this._unlocking=(async()=>{try{t.state==="suspended"&&await t.resume(),this.setState("live");}catch(e){throw this.setState("cold"),e}finally{this._unlocking=null;}})(),this._unlocking}get now(){return this._ctx?.currentTime??0}onStateChange(t){return this._listeners.add(t),()=>this._listeners.delete(t)}async close(){this._state!=="closed"&&(typeof document<"u"&&document.removeEventListener("visibilitychange",this.handleVisibility),this._ctx&&(this._ctx.removeEventListener("statechange",this.handleCtxStateChange),this._ctx.state!=="closed"&&await this._ctx.close().catch(()=>{})),this._ctx=null,this.setState("closed"),this._listeners.clear());}setState(t){if(this._state!==t){this._state=t;for(let e of this._listeners)e(t);}}attachVisibilityHandler(){this.opts.autoPauseOnHidden!==false&&(typeof document>"u"||document.addEventListener("visibilitychange",this.handleVisibility));}handleVisibility=()=>{if(!this._ctx||this._state==="closed")return;document.visibilityState==="visible"?setTimeout(()=>{document.visibilityState==="visible"&&this._ctx?.state==="suspended"&&this._ctx.resume().catch(()=>{});},200):this._ctx.suspend().catch(()=>{});};attachStateChangeHandler(t){t.addEventListener("statechange",this.handleCtxStateChange);}handleCtxStateChange=()=>{let t=this._ctx;if(!t||this._state==="closed")return;let e=t.state;if(e==="interrupted"){this.setState("interrupted");return}if(e==="suspended"){if(this._state==="interrupted"){setTimeout(()=>{this._ctx===t&&t.state==="suspended"&&t.resume().catch(()=>{});},200);return}(this._state==="live"||this._state==="unlocking")&&this.setState("suspended");return}e==="running"&&this._state!=="live"&&this.setState("live");}};function Lt(){let o=globalThis,t=o.AudioContext??o.webkitAudioContext;if(!t)throw new Error("No AudioContext constructor available in this environment.");return t}var Vt=64*1024*1024,Dt=128;function It(o){return o.length*o.numberOfChannels*4}var Y=class{constructor(t,e={}){this.getCtx=t;let i=typeof e=="number"?{maxEntries:e}:e;this.maxBytes=Math.max(1,i.maxBytes??Vt),this.maxEntries=Math.max(1,i.maxEntries??Dt);}getCtx;cache=new Map;bytes=0;inflight=new Map;maxBytes;maxEntries;has(t){return this.cache.has(t)}get cachedBytes(){return this.bytes}async load(t,e={}){let i=this.cache.get(t);if(i)return this.touch(t,i.buffer),i.buffer;let s=this.inflight.get(t);if(s)return this.join(s,e.signal);let r=new AbortController,n;return n={promise:this.fetchAndDecode(t,r.signal,e.onProgress).finally(()=>{this.inflight.get(t)===n&&this.inflight.delete(t);}),controller:r,waiters:0},this.inflight.set(t,n),this.join(n,e.signal)}join(t,e){t.waiters++;let i=()=>{t.waiters--,t.waiters<=0&&t.controller.abort();};return e?e.aborted?(i(),Promise.reject(bt(e))):new Promise((s,r)=>{let n=false,a=()=>{n||(n=true,i(),r(bt(e)));};e.addEventListener("abort",a,{once:true}),t.promise.then(u=>{n||(n=true,t.waiters--,e.removeEventListener("abort",a),s(u));},u=>{n||(n=true,t.waiters--,e.removeEventListener("abort",a),r(u));});}):t.promise.finally(()=>t.waiters--)}async fetchAndDecode(t,e,i){let s;try{s=await fetch(t,{signal:e});}catch(u){throw u.name==="AbortError"?u:new M(t,u)}if(!s.ok)throw new M(t,new Error(`${s.status} ${s.statusText}`));let r=i?await Rt(s,i):await s.arrayBuffer(),n=this.getCtx(),a;try{a=await n.decodeAudioData(r);}catch(u){throw new M(t,u)}return this.touch(t,a),a}async loadFirst(t,e={}){if(t.length===0)throw new Error("loadFirst requires at least one URL");for(let s of t){let r=this.cache.get(s);if(r)return this.touch(s,r.buffer),r.buffer}let i=[];for(let s of t)try{return await this.load(s,e)}catch(r){if(r.name==="AbortError")throw r;i.push({url:s,cause:r});}if(t.length===1){let s=i[0]?.cause;throw s instanceof Error?s:new M(t[0],s)}throw new B(t,i)}evict(t){let e=this.cache.get(t);e&&(this.bytes-=e.bytes,this.cache.delete(t));}clear(){this.cache.clear(),this.bytes=0;}touch(t,e){this.evict(t);let i=It(e);for(this.cache.set(t,{buffer:e,bytes:i}),this.bytes+=i;this.cache.size>this.maxEntries||this.bytes>this.maxBytes&&this.cache.size>1;){let s=this.cache.keys().next().value;if(s===void 0)break;this.evict(s);}}};function bt(o){return o.reason??new DOMException("load aborted","AbortError")}async function Rt(o,t){let e=o.body;if(!e||typeof e.getReader!="function"){let d=await o.arrayBuffer();return t(d.byteLength,d.byteLength),d}let i=o.headers.get("content-length"),s=i?Number.parseInt(i,10):Number.NaN,r=Number.isFinite(s)?s:null,n=e.getReader(),a=[],u=0;for(;;){let{done:d,value:m}=await n.read();if(d)break;m&&(a.push(m),u+=m.byteLength,t(u,r));}let c=new Uint8Array(u),l=0;for(let d of a)c.set(d,l),l+=d.byteLength;return c.buffer}var Gt={targetRms:.1,peakCeiling:.99};function k(o,t,e){if(!t)return o;let i={...Gt,...typeof t=="object"?t:{}},s=yt(o,i);return Math.abs(s-1)<.001?o:qt(o,s,e)}function yt(o,t){let e=zt(o);if(e<=1e-6)return 1;let i=t.targetRms/e,s=Ut(o)*i;return s>t.peakCeiling&&(i*=t.peakCeiling/s),i}function zt(o){let t=0,e=0;for(let i=0;i<o.numberOfChannels;i++){let s=o.getChannelData(i);for(let r=0;r<s.length;r++)t+=s[r]*s[r];e+=s.length;}return e===0?0:Math.sqrt(t/e)}function Ut(o){let t=0;for(let e=0;e<o.numberOfChannels;e++){let i=o.getChannelData(e);for(let s=0;s<i.length;s++){let r=Math.abs(i[s]);r>t&&(t=r);}}return t}function qt(o,t,e){if(e){let i=e.createBuffer(o.numberOfChannels,o.length,o.sampleRate);for(let s=0;s<o.numberOfChannels;s++){let r=o.getChannelData(s),n=i.getChannelData(s);for(let a=0;a<r.length;a++)n[a]=r[a]*t;}return i}for(let i=0;i<o.numberOfChannels;i++){let s=o.getChannelData(i);for(let r=0;r<s.length;r++)s[r]=s[r]*t;}return o}var K=class{constructor(t,e){this.host=t;this.tickSource=e;}host;tickSource;tasks=[];cancelled=0;timer=null;unsubscribe=null;scheduleAt(t,e){let i={audioTime:t,fn:e,cancelled:false};return this.tasks.splice(this.insertionIndex(t),0,i),this.arm(),()=>{i.cancelled||(i.cancelled=true,this.cancelled++,this.cancelled>32&&this.cancelled*2>this.tasks.length&&this.compact());}}insertionIndex(t){let e=0,i=this.tasks.length;for(;e<i;){let s=e+i>>>1;this.tasks[s].audioTime<=t?e=s+1:i=s;}return e}compact(){this.tasks=this.tasks.filter(t=>!t.cancelled),this.cancelled=0;}arm(){if(this.tickSource){this.unsubscribe||(this.unsubscribe=this.tickSource.subscribe(()=>this.tick()));return}this.rearmTimer();}rearmTimer(){this.timer!=null&&(clearTimeout(this.timer),this.timer=null);let t=this.tasks.find(s=>!s.cancelled);if(!t)return;let e=this.host.now,i=Math.max(0,(t.audioTime-e)*1e3);this.timer=setTimeout(()=>this.tick(),i);}tick(){this.timer!=null&&(this.timer=null);let t=this.host.now,e=[],i=[];for(let s of this.tasks)s.cancelled||(s.audioTime<=t?e.push(s):i.push(s));this.tasks=i,this.cancelled=0;for(let s of e)try{s.fn();}catch(r){console.error("[zvuk] scheduled task threw",r);}if(this.tasks.length===0){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null);return}this.tickSource||this.rearmTimer();}dispose(){this.timer!=null&&clearTimeout(this.timer),this.timer=null,this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.tasks=[],this.cancelled=0;}};var Ht=.008,$t=.05,D=class{name;deps;live=new Set;constructor(t,e){this.name=t,this.deps=e;}get loopDuration(){return this.deps.buffers.loop.duration}get hasIntro(){return this.deps.buffers.intro!=null}get hasOutro(){return this.deps.buffers.outro!=null}play(t={}){let e=new Q({ctx:this.deps.ctx,buffers:this.deps.buffers,destination:this.deps.destination,loopCrossfade:this.deps.loopCrossfade,defaultStopFade:this.deps.defaultStopFade,options:t});return this.live.add(e),e.ended.then(()=>this.live.delete(e)),e}voices(){return Array.from(this.live)}stopAll(t={}){for(let e of Array.from(this.live))e.stop(t);this.live.clear();}},Q=class{ended;ctx;buffers;destination;gain;state="intro";done=false;resolveEnded;stopFade;loopCrossfadeSec;introSource=null;outroSource=null;loopChain=[];loopArmTimer=null;outroTimer=null;nextLoopBoundaryAt=Number.POSITIVE_INFINITY;constructor(t){this.ctx=t.ctx,this.buffers=t.buffers,this.destination=t.destination,this.loopCrossfadeSec=Math.max(0,t.loopCrossfade),this.stopFade=Math.max(0,t.defaultStopFade??Ht),this.gain=this.ctx.createGain();let e=St(t.options.volume??1),i=Math.max(0,t.options.fadeIn??0);i>0?(this.gain.gain.setValueAtTime(0,this.ctx.currentTime),this.gain.gain.linearRampToValueAtTime(e,this.ctx.currentTime+i)):this.gain.gain.value=e,this.gain.connect(this.destination),this.ended=new Promise(s=>{this.resolveEnded=s;}),this.start(this.ctx.currentTime);}get currentPart(){return this.state}fade(t){let e=this.gain.gain,i=this.ctx.currentTime;return S(e,i,St(t.to),t.duration,t.curve??"linear"),w(this.ctx,t.duration,this.ended)}stop(t={}){if(this.done)return;let e=Math.max(0,t.fade??this.stopFade);if(this.cancelTimers(),e===0){this.stopAllSources(0),this.finish();return}let i=this.ctx.currentTime,s=i+e;try{let r=this.gain.gain;r.cancelScheduledValues(i),r.setValueAtTime(r.value,i),r.linearRampToValueAtTime(0,s),this.stopAllSources(s);}catch{this.finish();return}setTimeout(()=>this.finish(),e*1e3);}skipToOutro(t={}){if(this.done||this.state==="outro"||this.state==="ended")return;if(!this.buffers.outro){this.stop();return}(t.at??"loop-end")==="now"?this.skipToOutroNow():this.skipToOutroAtLoopEnd();}start(t){this.buffers.intro?(this.scheduleIntro(t),this.scheduleLoopStart(t+this.buffers.intro.duration)):(this.state="loop",this.scheduleLoopStart(t));}scheduleIntro(t){let e=this.ctx.createBufferSource();e.buffer=this.buffers.intro,e.connect(this.gain),e.start(t),e.onended=()=>{this.introSource===e&&(this.introSource=null);},this.introSource=e;}scheduleLoopStart(t){if(this.done)return;let e=this.spawnLoopSegment(t,false);if(this.nextLoopBoundaryAt=t+this.buffers.loop.duration,this.loopCrossfadeSec>0&&this.crossfadeViable())this.armNextLoopSegment(t);else {e.source.loop=true;let i=this.buffers.loop;if(e.source.loopStart=0,e.source.loopEnd=i.duration,!this.buffers.intro)this.state="loop";else {let s=Math.max(0,(t-this.ctx.currentTime)*1e3);setTimeout(()=>{!this.done&&this.state==="intro"&&(this.state="loop");},s);}}}spawnLoopSegment(t,e){let i=this.ctx.createBufferSource();i.buffer=this.buffers.loop,i.loop=false;let s=this.ctx.createGain();if(e?(s.gain.setValueAtTime(0,t),s.gain.setValueCurveAtTime(P(0,1),t,this.loopCrossfadeSec)):s.gain.setValueAtTime(1,t),this.crossfadeViable()){let n=t+this.buffers.loop.duration-this.loopCrossfadeSec;s.gain.setValueAtTime(1,n),s.gain.setValueCurveAtTime(P(1,0),n,this.loopCrossfadeSec);}i.connect(s).connect(this.gain);try{this.crossfadeViable()?i.start(t,0,this.buffers.loop.duration):i.start(t);}catch{}i.onended=()=>this.releaseLoopSegment(i,s);let r={source:i,gain:s,startTime:t};return this.loopChain.push(r),r}armNextLoopSegment(t){this.loopArmTimer!=null&&(clearTimeout(this.loopArmTimer),this.loopArmTimer=null);let e=t+this.buffers.loop.duration-this.loopCrossfadeSec,s=Math.max(0,(e-this.ctx.currentTime)*1e3-50);this.loopArmTimer=setTimeout(()=>{this.loopArmTimer=null,!(this.done||this.state!=="loop"&&this.state!=="intro")&&(this.state="loop",this.spawnLoopSegment(e,true),this.nextLoopBoundaryAt=e+this.buffers.loop.duration,this.armNextLoopSegment(e));},s);}crossfadeViable(){return this.loopCrossfadeSec>0&&this.buffers.loop.duration>this.loopCrossfadeSec*2}releaseLoopSegment(t,e){let i=this.loopChain.findIndex(s=>s.source===t);i>=0&&this.loopChain.splice(i,1);try{t.disconnect(),e.disconnect();}catch{}}skipToOutroAtLoopEnd(){this.loopArmTimer!=null&&(clearTimeout(this.loopArmTimer),this.loopArmTimer=null);let t;this.state==="intro"?(t=this.ctx.currentTime+(this.buffers.intro?.duration??0),this.cancelLoopArm()):t=this.nextLoopBoundaryAt,this.stopLoopSourcesAt(t),this.scheduleOutro(t);}skipToOutroNow(){this.cancelLoopArm();let t=this.ctx.currentTime,e=t+$t;for(let i of this.loopChain){try{let s=i.gain.gain;s.cancelScheduledValues(t),s.setValueAtTime(s.value,t),s.linearRampToValueAtTime(0,e);}catch{}try{i.source.stop(e);}catch{}}if(this.introSource)try{this.introSource.stop(e);}catch{}this.scheduleOutro(e);}cancelLoopArm(){this.loopArmTimer!=null&&(clearTimeout(this.loopArmTimer),this.loopArmTimer=null);}stopLoopSourcesAt(t){for(let e of this.loopChain)try{e.source.stop(t);}catch{}}scheduleOutro(t){let e=this.buffers.outro;if(!e){let r=Math.max(0,(t-this.ctx.currentTime)*1e3);this.outroTimer=setTimeout(()=>this.finish(),r);return}let i=this.ctx.createBufferSource();i.buffer=e,i.connect(this.gain);try{i.start(t);}catch{}i.onended=()=>{this.outroSource===i&&(this.outroSource=null),this.finish();},this.outroSource=i;let s=Math.max(0,(t-this.ctx.currentTime)*1e3);this.outroTimer=setTimeout(()=>{this.outroTimer=null,this.done||(this.state="outro");},s);}cancelTimers(){this.loopArmTimer!=null&&(clearTimeout(this.loopArmTimer),this.loopArmTimer=null),this.outroTimer!=null&&(clearTimeout(this.outroTimer),this.outroTimer=null);}stopAllSources(t){let e=[];this.introSource&&e.push(this.introSource);for(let i of this.loopChain)e.push(i.source);this.outroSource&&e.push(this.outroSource);for(let i of e)try{i.onended=null,t===0?i.stop():i.stop(t);}catch{}}finish(){if(!this.done){this.done=true,this.state="ended",this.cancelTimers();try{this.introSource&&this.introSource.disconnect();for(let t of this.loopChain)t.source.disconnect(),t.gain.disconnect();this.outroSource&&this.outroSource.disconnect(),this.gain.disconnect();}catch{}this.introSource=null,this.outroSource=null,this.loopChain=[],this.resolveEnded();}}};function St(o){return Number.isNaN(o)?0:Math.min(1,Math.max(0,o))}var Wt=.008,I=class o{id;priority;bus;startedAt;sourceName;ended;ctx;gain;source;buffer;loop;basePitch;done=false;stopping=false;paused=false;resolveEnded;cueListeners=new Set;startCtxTime;pausedOffset=0;currentOffset=0;_spatializer;startOffset;regionDuration;loopStart;loopEnd;regionTimer=null;stopFade;crossfadeSec=0;crossfadeRegionStart=0;crossfadeRegionLen=0;crossfadeChain=[];crossfadeArmTimer=null;levelAnalyser=null;levelBuf=null;static nextId=1;constructor(t){let{ctx:e,buffer:i,destination:s,options:r}=t;this.id=o.nextId++,this.ctx=e,this.priority=r.priority??0,this.bus=r.bus,this.sourceName=t.sourceName,this.startedAt=e.currentTime,this.buffer=i,this.loop=r.loop??false,this.basePitch=xt(r.pitch??1,1),this._spatializer=t.spatializer,this.startOffset=r.offset??0,this.currentOffset=this.startOffset,this.regionDuration=r.duration,this.loopStart=r.loopStart,this.loopEnd=r.loopEnd,this.stopFade=Math.max(0,t.defaultStopFade??Wt),this.gain=e.createGain();let n=At(xt(r.volume??1)),a=Math.max(0,r.fadeIn??0);if(a>0?(this.gain.gain.setValueAtTime(0,e.currentTime),this.gain.gain.linearRampToValueAtTime(n,e.currentTime+a)):this.gain.gain.value=n,this.gain.connect(s),this.startCtxTime=e.currentTime,this.ended=new Promise(u=>{this.resolveEnded=u;}),r.signal&&(r.signal.aborted?queueMicrotask(()=>this.stop()):r.signal.addEventListener("abort",()=>this.stop(),{once:true})),this.shouldUseLoopCrossfade(r)){this.crossfadeSec=r.loopCrossfade,this.crossfadeRegionStart=r.loopStart??this.startOffset;let u=r.loopEnd??i.duration;this.crossfadeRegionLen=Math.max(0,u-this.crossfadeRegionStart),this.source=this.startCrossfadeChain(e.currentTime);}else {this.source=this.createSourceNode(this.basePitch),this.bindSourceLifecycle(this.source,()=>{});try{this.source.start(0,this.startOffset);}catch{}this.armRegionTimer(this.regionDuration);}queueMicrotask(()=>this.emit("started")),this.ended.then(()=>t.onEnded(this));}shouldUseLoopCrossfade(t){if(!this.loop)return false;let e=t.loopCrossfade;if(e==null||e<=0)return false;let i=t.loopStart??this.startOffset;return (t.loopEnd??this.buffer.duration)-i>e*2}fade(t){let e=this.gain.gain,i=this.ctx.currentTime;return S(e,i,At(t.to),t.duration,t.curve??"linear"),w(this.ctx,t.duration,this.ended)}stop(t={}){if(this.done||this.stopping)return;let e=Math.max(0,t.fade??this.stopFade);if(this.crossfadeArmTimer!=null&&(clearTimeout(this.crossfadeArmTimer),this.crossfadeArmTimer=null),e===0){this.stopAllSources(0),this.finish("ended");return}this.stopping=true;let i=this.ctx.currentTime,s=i+e;for(let r of this.activeSources())r.onended=null;this.regionTimer!=null&&(clearTimeout(this.regionTimer),this.regionTimer=null);try{let r=this.gain.gain;r.cancelScheduledValues(i),r.setValueAtTime(r.value,i),r.linearRampToValueAtTime(0,s),this.stopAllSources(s);}catch{this.finish("ended");return}setTimeout(()=>this.finish("ended"),e*1e3);}activeSources(){return this.inCrossfadeMode?this.crossfadeChain.map(t=>t.source):[this.source]}stopAllSources(t){for(let e of this.activeSources())try{t===0?e.stop():e.stop(t);}catch{}}pause(){if(this.done||this.paused)return;let t=this.computeOffset();this.pausedOffset=t,this.currentOffset=t,this.paused=true,this.regionTimer!=null&&(clearTimeout(this.regionTimer),this.regionTimer=null),this.crossfadeArmTimer!=null&&(clearTimeout(this.crossfadeArmTimer),this.crossfadeArmTimer=null);for(let e of this.activeSources()){try{e.onended=null,e.stop();}catch{}try{e.disconnect();}catch{}}this.inCrossfadeMode&&(this.crossfadeChain=[]),this.emit("paused");}resume(){if(!(this.done||!this.paused)){if(this.paused=false,this.startCtxTime=this.ctx.currentTime,this.inCrossfadeMode)this.source=this.startCrossfadeChain(this.startCtxTime);else {this.source=this.createSourceNode(this.basePitch),this.bindSourceLifecycle(this.source,()=>{});try{this.source.start(0,this.pausedOffset);}catch{}if(this.regionDuration!=null){let t=Math.max(0,this.pausedOffset-this.startOffset),e=Math.max(0,this.regionDuration-t);this.armRegionTimer(e);}}this.emit("resumed");}}get isPaused(){return this.paused}setPlaybackRate(t,e={}){if(this.done)return;let i=Math.max(0,t),s=Math.max(0,e.duration??0);if(this.paused||(this.currentOffset=this.computeOffset(),this.startCtxTime=this.ctx.currentTime),this.basePitch=i,!this.paused){if(this.regionTimer!=null&&this.regionDuration!=null){let r=Math.max(0,this.currentOffset-this.startOffset);this.armRegionTimer(Math.max(0,this.regionDuration-r));}for(let r of this.activeSources()){let n=r.playbackRate;s===0?n.value=i:S(n,this.ctx.currentTime,i,s,e.curve??"linear");}}}get playbackRate(){return this.basePitch}get spatializer(){return this._spatializer}level(){if(this.done)return {rms:0,peak:0};if(!this.levelAnalyser){let s=this.ctx.createAnalyser();s.fftSize=512,this.gain.connect(s),this.levelAnalyser=s,this.levelBuf=new Float32Array(s.fftSize);}let t=this.levelBuf;this.levelAnalyser.getFloatTimeDomainData(t);let e=0,i=0;for(let s=0;s<t.length;s++){let r=t[s]??0;e+=r*r;let n=Math.abs(r);n>i&&(i=n);}return {rms:Math.sqrt(e/t.length),peak:i}}levelHint(){return this.done?0:this.levelAnalyser?this.level().rms:this.gain.gain.value}async*cues(){if(this.done){yield "ended";return}let t=[],e=null,i=r=>{if(e){let n=e;e=null,n({value:r,done:false});}else t.push(r);},s=r=>i(r);this.cueListeners.add(s);try{for(;;){if(t.length>0){let n=t.shift();if(yield n,n==="ended")return;continue}if(this.done){yield "ended";return}let r=await new Promise(n=>{e=n;});if(r.done||(yield r.value,r.value==="ended"))return}}finally{this.cueListeners.delete(s);}}finish(t,e){if(!this.done){this.done=true,this.regionTimer!=null&&(clearTimeout(this.regionTimer),this.regionTimer=null),this.crossfadeArmTimer!=null&&(clearTimeout(this.crossfadeArmTimer),this.crossfadeArmTimer=null);try{for(let i of this.activeSources())i.disconnect();for(let i of this.crossfadeChain)i.gain.disconnect();this.levelAnalyser?.disconnect(),this.gain.disconnect();}catch{}this.levelAnalyser=null,this.levelBuf=null,this.crossfadeChain=[],this.emit(t),this.resolveEnded(),e?.(this);}}emit(t){for(let e of this.cueListeners)e(t);}createSourceNode(t){let e=this.ctx.createBufferSource();return e.buffer=this.buffer,e.loop=this.loop,this.loop&&this.loopStart!=null&&(e.loopStart=this.loopStart),this.loop&&this.loopEnd!=null&&(e.loopEnd=this.loopEnd),e.playbackRate.value=t,e.connect(this.gain),e}armRegionTimer(t){if(this.regionTimer!=null&&(clearTimeout(this.regionTimer),this.regionTimer=null),t==null||this.loop)return;let e=Math.max(0,t*1e3)/Math.max(1e-4,this.basePitch);this.regionTimer=setTimeout(()=>{this.regionTimer=null,this.done||this.stop();},e);}bindSourceLifecycle(t,e){t.onended=()=>{this.paused||t.loop||this.finish("ended",e);};}startCrossfadeChain(t){let e=this.spawnCrossfadeSegment(t,false);return this.armNextCrossfadeSegment(t),e.source}spawnCrossfadeSegment(t,e){let i=this.ctx.createBufferSource();i.buffer=this.buffer,i.loop=false,i.playbackRate.value=this.basePitch;let s=this.ctx.createGain();e?(s.gain.setValueAtTime(0,t),s.gain.setValueCurveAtTime(P(0,1),t,this.crossfadeSec)):s.gain.setValueAtTime(1,t);let r=t+this.crossfadeRegionLen-this.crossfadeSec;s.gain.setValueAtTime(1,r),s.gain.setValueCurveAtTime(P(1,0),r,this.crossfadeSec),i.connect(s).connect(this.gain);try{i.start(t,this.crossfadeRegionStart,this.crossfadeRegionLen);}catch{}i.onended=()=>this.releaseCrossfadeSegment(i,s);let n={source:i,gain:s,startTime:t};return this.crossfadeChain.push(n),n}armNextCrossfadeSegment(t){this.crossfadeArmTimer!=null&&(clearTimeout(this.crossfadeArmTimer),this.crossfadeArmTimer=null);let e=t+this.crossfadeRegionLen-this.crossfadeSec,s=Math.max(0,(e-this.ctx.currentTime)*1e3-50);this.crossfadeArmTimer=setTimeout(()=>{this.crossfadeArmTimer=null,!(this.done||this.stopping||this.paused)&&(this.spawnCrossfadeSegment(e,true),this.armNextCrossfadeSegment(e));},s);}releaseCrossfadeSegment(t,e){let i=this.crossfadeChain.findIndex(s=>s.source===t);i>=0&&this.crossfadeChain.splice(i,1);try{t.disconnect(),e.disconnect();}catch{}}get inCrossfadeMode(){return this.crossfadeSec>0}computeOffset(){if(this.paused)return this.pausedOffset;let t=(this.ctx.currentTime-this.startCtxTime)*this.basePitch,e=this.currentOffset+t;return this.loop?e=(e%this.buffer.duration+this.buffer.duration)%this.buffer.duration:e=Math.min(e,this.buffer.duration),e}};function xt(o,t=1){if(typeof o=="number")return o;if(!o)return t;let e=o.base??t;return o.jitter==null?e:e+(Math.random()*2-1)*o.jitter}function At(o){return Number.isNaN(o)?0:Math.min(1,Math.max(0,o))}var R=class{name;deps;constructor(t,e){this.name=t,this.deps=e;}get duration(){return this.deps.buffer.duration}play(t={}){let e=t.bus??this.deps.defaultBus,i=this.deps.resolveBusInput(e),s=this.deps.resolveSpatializer?.(e,t.spatializer),r=s?s.connectInto(i):i,n=new I({ctx:this.deps.ctx,buffer:this.deps.buffer,destination:r,options:{...t,bus:e},spatializer:s,sourceName:this.deps.sourceName??this.name,defaultStopFade:this.deps.defaultStopFade,onEnded:u=>{this.deps.releaseVoice(u,e),s?.dispose();}});return this.deps.trackVoice(n,e),(this.deps.applyConcurrency?.(n,e)??true)||n.stop(),n}};var G=class{name;regions;sound;constructor(t,e,i){this.name=t,this.sound=e,this.regions={...i};}list(){return Object.keys(this.regions)}has(t){return t in this.regions}region(t){let e=this.regions[t];if(!e)throw new A(`${this.name}#${t}`);return e}play(t,e={}){let i=this.region(t),s=e.loop??i.loop??false;return this.sound.play({...e,loop:s,offset:i.start,duration:i.duration,loopStart:i.start,loopEnd:i.start+i.duration})}};var z=class{name;ctx;url;destination;el=null;node=null;gain=null;disposed=false;constructor(t,e,i,s){this.name=t,this.ctx=e,this.url=i,this.destination=s;}ensure(){if(this.el||this.disposed||typeof document>"u"||typeof Audio>"u")return;let t=new Audio;t.src=this.url,t.crossOrigin="anonymous",t.preload="auto";let e=this.ctx.createMediaElementSource;if(typeof e!="function"){this.el=t;return}let i=e.call(this.ctx,t),s=this.ctx.createGain();i.connect(s),s.connect(this.destination),this.el=t,this.node=i,this.gain=s;}async play(t={}){if(this.ensure(),!!this.el){this.gain&&(this.gain.gain.value=dt(t.volume??1)),this.el.loop=t.loop??false;try{await this.el.play();}catch{}}}pause(){this.el?.pause();}stop(){if(this.el){this.el.pause();try{this.el.currentTime=0;}catch{}}}seek(t){if(this.el)try{this.el.currentTime=Math.max(0,t);}catch{}}get currentTime(){return this.el?.currentTime??0}get duration(){return this.el?.duration??0}get paused(){return this.el?.paused??true}setVolume(t){this.gain&&(this.gain.gain.value=dt(t));}fade(t){return this.gain?(S(this.gain.gain,this.ctx.currentTime,dt(t.to),t.duration,t.curve??"linear"),w(this.ctx,t.duration)):Promise.resolve()}dispose(){this.disposed=true;try{this.node?.disconnect(),this.gain?.disconnect();}catch{}this.el&&(this.el.pause(),this.el.src=""),this.el=null,this.node=null,this.gain=null;}};function dt(o){return Number.isNaN(o)?0:Math.min(1,Math.max(0,o))}var U=class{name;count;sounds;strategy;lastIndex=-1;bag=[];constructor(t,e,i={}){if(e.length===0)throw new Error(`Variants "${t}" requires at least one sound`);this.name=t,this.sounds=e,this.count=e.length,this.strategy=i.strategy??"no-repeat";}get lastPick(){return this.lastIndex}play(t={}){return this.sounds[this.pick()].play(t)}playIndex(t,e={}){let i=(t%this.count+this.count)%this.count;return this.lastIndex=i,this.sounds[i].play(e)}pick(){let t=this.count;if(t===1)return 0;if(this.strategy==="random"){let i=Math.floor(Math.random()*t);return this.lastIndex=i,i}if(this.strategy==="shuffle-bag"){if(this.bag.length===0){this.bag=Array.from({length:t},(s,r)=>r);for(let s=t-1;s>0;s--){let r=Math.floor(Math.random()*(s+1));[this.bag[s],this.bag[r]]=[this.bag[r],this.bag[s]];}t>1&&this.bag[0]===this.lastIndex&&([this.bag[0],this.bag[1]]=[this.bag[1],this.bag[0]]);}let i=this.bag.shift();return this.lastIndex=i,i}let e=Math.floor(Math.random()*(t-1));return e>=this.lastIndex&&e++,this.lastIndex=e,e}};var jt="inverse";var q=class{ctx;kind;input;output;stereoPan=null;panner=null;occlusionFilter=null;occlusionGain=null;constructor(t,e){if(this.ctx=t,e.position){let i=t.createPanner();i.panningModel="HRTF",i.distanceModel=e.distanceModel??jt,i.refDistance=e.refDistance??1,i.maxDistance=e.maxDistance??1e4,i.rolloffFactor=e.rolloffFactor??1;let[s,r,n]=e.position;this.setPanner3D(i,s,r,n);let a=t.createBiquadFilter();a.type="lowpass",a.frequency.value=22050,a.Q.value=Math.SQRT1_2;let u=t.createGain();u.gain.value=1,i.connect(a).connect(u),this.panner=i,this.occlusionFilter=a,this.occlusionGain=u,this.input=i,this.output=u,this.kind="3d",e.occlusion!=null&&this.setOcclusion(e.occlusion);}else {let i=t.createStereoPanner();i.pan.value=Ct(e.pan??0),this.stereoPan=i,this.input=i,this.output=i,this.kind="2d";}}setPan(t){this.kind!=="2d"||!this.stereoPan||(this.stereoPan.pan.value=Ct(t));}setPosition(t,e,i){this.kind!=="3d"||!this.panner||this.setPanner3D(this.panner,t,e,i);}setRefDistance(t){this.panner&&(this.panner.refDistance=Math.max(0,t));}setMaxDistance(t){this.panner&&(this.panner.maxDistance=Math.max(0,t));}setRolloffFactor(t){this.panner&&(this.panner.rolloffFactor=Math.max(0,t));}setDistanceModel(t){this.panner&&(this.panner.distanceModel=t);}setOcclusion(t){if(!this.occlusionFilter||!this.occlusionGain)return;let e=Zt(t),i=22050*(500/22050)**e,s=this.ctx.currentTime;this.occlusionFilter.frequency.setValueAtTime(i,s);let r=10**(-6*e/20);this.occlusionGain.gain.setValueAtTime(r,s);}connectInto(t){return this.output.connect(t),this.input}dispose(){try{this.input.disconnect(),this.occlusionFilter?.disconnect(),this.occlusionGain?.disconnect();}catch{}}setPanner3D(t,e,i,s){if(typeof t.positionX?.setValueAtTime=="function"){let r=this.ctx.currentTime;t.positionX.setValueAtTime(e,r),t.positionY.setValueAtTime(i,r),t.positionZ.setValueAtTime(s,r);}else t.setPosition?.(e,i,s);}};function Ct(o){return Math.max(-1,Math.min(1,o))}function Zt(o){return Number.isNaN(o)?0:Math.max(0,Math.min(1,o))}var H=class{input;headroomDb;ctx;limiterNode=null;limiterCfg;destination;_meterAnalyser=null;_meterBuf=null;constructor(t,e={}){this.ctx=t,this.input=t.createGain(),this.headroomDb=e.headroom??0,this.input.gain.value=Tt(this.headroomDb),this.destination=t.destination,this.limiterCfg=e.limiter??null,this.rewire();}setHeadroom(t){this.headroomDb=t,S(this.input.gain,this.ctx.currentTime,Tt(t),.01,"linear");}get headroom(){return this.headroomDb}setLimiter(t){this.limiterCfg=t,this.rewire();}get reduction(){return this.limiterNode?.reduction??0}meter(){if(!this._meterAnalyser){let s=this.ctx.createAnalyser();s.fftSize=1024,this.input.connect(s),this._meterAnalyser=s,this._meterBuf=new Float32Array(s.fftSize);}let t=this._meterBuf;this._meterAnalyser.getFloatTimeDomainData(t);let e=0,i=0;for(let s=0;s<t.length;s++){let r=t[s]??0;e+=r*r;let n=Math.abs(r);n>i&&(i=n);}return {rms:Math.sqrt(e/t.length),peak:i}}dispose(){try{this.input.disconnect(),this.limiterNode?.disconnect(),this._meterAnalyser?.disconnect();}catch{}this.limiterNode=null,this._meterAnalyser=null,this._meterBuf=null;}rewire(){try{this.input.disconnect(),this.limiterNode?.disconnect();}catch{}if(this.limiterNode=null,this.limiterCfg){let t=this.limiterCfg,e=this.ctx.createDynamicsCompressor();e.threshold.value=t.threshold??-1,e.knee.value=0,e.ratio.value=Math.max(20,t.ratio??20),e.attack.value=t.attack??.001,e.release.value=t.release??.05,this.input.connect(e),e.connect(this.destination),this.limiterNode=e;}else this.input.connect(this.destination);this._meterAnalyser&&this.input.connect(this._meterAnalyser);}};function Tt(o){return 10**(o/20)}var $=class{name;state;getBus;getParam;constructor(t,e,i,s){this.name=t,this.state=e,this.getBus=i,this.getParam=s;}apply(t={}){let e=t.fade??0,i=[];for(let[s,r]of Object.entries(this.state.buses)){let n=this.getBus(s);n&&(n.muted=r.muted,i.push(n.fadeTo(r.level,e)));}for(let[s,r]of Object.entries(this.state.parameters)){let n=this.getParam(s);n&&n.set(r);}return Promise.all(i).then(()=>{})}blendWith(t,e){let i=e<0?0:e>1?1:e,s=1-i;for(let[r,n]of Object.entries(this.state.buses)){let a=t.state.buses[r];if(!a)continue;let u=this.getBus(r);u&&(u.muted=i<.5?n.muted:a.muted,u.level=n.level*s+a.level*i);}for(let[r,n]of Object.entries(this.state.parameters)){let a=t.state.parameters[r];if(a===void 0)continue;let u=this.getParam(r);u&&u.set(n*s+a*i);}}};function Xt(o={}){return new pt(o)}var pt=class{host;decoder;scheduler=null;master=null;buses=new Map;busOrder=[];sounds=new Map;internalSounds=new Map;sprites=new Map;streams=new Map;musics=new Map;variantsByName=new Map;busGroups=new Map;soloedBuses=new Set;soundUrls=new Map;voices=new Map;parameters=new Map;config;constructor(t){this.config=t,this.host=new X({autoPauseOnHidden:t.autoPauseOnHidden,latencyHint:t.latencyHint}),this.decoder=new Y(()=>this.host.touch(),t.cache??{});let e=Object.keys(t.buses??{});this.busOrder=e.length>0?e:["default"];for(let i of this.busOrder)this.voices.set(i,new Set);}get state(){return this.host.state}get now(){return this.host.now}get context(){return this.host.touch()}async unlock(){await this.host.unlock(),this.ensureGraph();}async close(){if(this.host.state!=="closed"){for(let t of this.voices.values()){for(let e of t)e.stop();t.clear();}this.scheduler?.dispose(),this.scheduler=null;for(let t of this.buses.values()){for(let e of t.fx())e.dispose();t.dispose();}this.buses.clear(),this.master?.dispose(),this.master=null,this.sounds.clear(),this.internalSounds.clear(),this.sprites.clear();for(let t of this.musics.values())t.stopAll({fade:0});this.musics.clear(),this.variantsByName.clear(),this.busGroups.clear(),this.soloedBuses.clear(),this.soundUrls.clear();for(let t of this.streams.values())t.dispose();this.streams.clear(),this.parameters.clear(),this.decoder.clear(),await this.host.close();}}async loadSound(t,e,i={}){return this.loadSoundAs(t,t,e,i,false)}async loadSoundAs(t,e,i,s,r){if(this.host.state==="closed")throw new x;this.host.touch(),this.ensureGraph();let n={signal:s.signal},a=await this.resolveBuffer(t,i,n);return s.normalize&&(a=k(a,s.normalize,this.host.touch())),this.soundUrls.set(t,typeof i=="string"?[i]:[...i]),this.registerSound(t,e,a,{bus:s.bus},r)}async resolveBuffer(t,e,i){let s=this.config.resolveAsset;if(s){let n=await s({name:t,url:e,signal:i.signal});if(n!=null){if(n instanceof AudioBuffer)return n;if(n instanceof ArrayBuffer)return await this.host.touch().decodeAudioData(n.slice(0));if(typeof n=="string")return await this.decoder.load(n,i)}}let r=typeof e=="string"?[e]:ht(e);return await this.decoder.loadFirst(r,i)}async preload(t,e={}){if(this.host.state==="closed")throw new x;if(t.length===0)return;let i=Math.max(1,e.concurrency??wt),s=e.onProgress,r=e.signal,n=t.length,a=0,u=[],c=0,l=Math.min(i,n),d=[];for(let p=0;p<l;p++)d.push((async()=>{for(;;){let b=c++;if(b>=n)return;if(r?.aborted)throw r.reason??new DOMException("preload aborted","AbortError");let h=t[b],v=Kt(r,h.options?.signal),f={...h.options??{},signal:v};try{await this.loadSound(h.name,h.url,f),a++,s?.({name:h.name,status:"loaded",completed:a,total:n});}catch(y){if(y.name==="AbortError")throw y;a++,u.push({name:h.name,cause:y}),s?.({name:h.name,status:"failed",error:y,completed:a,total:n});}}})());let g=(await Promise.allSettled(d)).find(p=>p.status==="rejected");if(g&&g.status==="rejected")throw g.reason;if(u.length>0)throw new N(u)}async loadSprite(t,e,i,s={}){let r=await this.loadSoundAs(`__sprite:${t}`,t,e,s,true),n=new G(t,r,i);return this.sprites.set(t,n),n}sprite(t){let e=this.sprites.get(t);if(!e)throw new A(t,C(t,[...this.sprites.keys()]));return e}hasSprite(t){return this.sprites.has(t)}async loadVariants(t,e,i={}){if(e.length===0)throw new Error(`engine.loadVariants("${t}") requires at least one URL set`);let{strategy:s,...r}=i,n=await Yt(e,wt,(u,c)=>this.loadSoundAs(`__variant:${t}:${c}`,t,u,r,true)),a=new U(t,n,{strategy:s});return this.variantsByName.set(t,a),a}variants(t){let e=this.variantsByName.get(t);if(!e)throw new A(t,C(t,[...this.variantsByName.keys()]));return e}hasVariants(t){return this.variantsByName.has(t)}async loadMusic(t,e,i={}){if(this.host.state==="closed")throw new x;this.host.touch(),this.ensureGraph();let s={signal:i.signal},[r,n,a]=await Promise.all([this.resolveBuffer(`__music:${t}:loop`,e.loop,s),e.intro?this.resolveBuffer(`__music:${t}:intro`,e.intro,s):Promise.resolve(void 0),e.outro?this.resolveBuffer(`__music:${t}:outro`,e.outro,s):Promise.resolve(void 0)]),u=this.host.touch(),c={intro:n?i.normalize?k(n,i.normalize,u):n:void 0,loop:i.normalize?k(r,i.normalize,u):r,outro:a?i.normalize?k(a,i.normalize,u):a:void 0},l=i.bus??this.busOrder[0],d=this.buses.get(l);if(!d)throw new T(l,C(l,[...this.buses.keys()]));let m=new D(t,{ctx:this.host.touch(),buffers:c,destination:d.input,loopCrossfade:i.loopCrossfade??0,defaultStopFade:this.config.voice?.stopFade});return this.musics.set(t,m),m}music(t){let e=this.musics.get(t);if(!e)throw new A(t,C(t,[...this.musics.keys()]));return e}hasMusic(t){return this.musics.has(t)}loadStream(t,e,i={}){if(this.host.state==="closed")throw new x;this.host.touch(),this.ensureGraph();let s=typeof e=="string"?e:lt(e),r=i.bus??this.busOrder[0],n=this.buses.get(r);if(!n)throw new T(r,C(r,[...this.buses.keys()]));let a=new z(t,this.host.touch(),s,n.input);return this.streams.set(t,a),a}stream(t){let e=this.streams.get(t);if(!e)throw new A(t,C(t,[...this.streams.keys()]));return e}hasStream(t){return this.streams.has(t)}crossfade(t,e,i={}){let s=i.duration??1.5,r=i.curve??"equal-power",n=i.toVolume??1,u=this.sound(e).play({bus:i.bus,loop:i.loop??true,volume:0});u.fade({to:n,duration:s,curve:r}).catch(()=>{});let c=this.activeVoices().filter(l=>l!==u&&l.sourceName===t&&l.bus===u.bus);for(let l of c)l.fade({to:0,duration:s,curve:r}).then(()=>l.stop()).catch(()=>{});return u}createSound(t,e,i={}){return this.registerSound(t,t,e,i,false)}registerSound(t,e,i,s,r){if(this.host.state==="closed")throw new x;this.host.touch(),this.ensureGraph();let n=s.bus??this.busOrder[0];if(!this.buses.has(n))throw new T(n,C(n,[...this.buses.keys()]));let a=new R(t,{ctx:this.host.touch(),buffer:i,defaultBus:n,sourceName:e,defaultStopFade:this.config.voice?.stopFade,resolveBusInput:u=>{let c=this.buses.get(u);if(!c)throw new T(u,C(u,[...this.buses.keys()]));return c.input},resolveSpatializer:(u,c)=>{if(c)return new q(this.host.touch(),c)},trackVoice:(u,c)=>{this.voices.get(c)?.add(u),this.buses.get(c)?.trackVoice(u);},releaseVoice:(u,c)=>{this.voices.get(c)?.delete(u),this.buses.get(c)?.releaseVoice(u);},applyConcurrency:(u,c)=>{let l=this.buses.get(c);if(!l)return true;let d=false,m=l.applyConcurrencyOnSpawn(u,()=>{d=true;});return m&&(this.voices.get(c)?.delete(m),l.releaseVoice(m)),d&&(this.voices.get(c)?.delete(u),l.releaseVoice(u)),!d}});return (r?this.internalSounds:this.sounds).set(t,a),a}removeSound(t){this.sounds.delete(t);}unloadSound(t,e={}){if(this.sounds.delete(t),e.evictBuffer??true){let i=this.soundUrls.get(t);if(i)for(let s of i)this.decoder.evict(s);}this.soundUrls.delete(t);}hasSound(t){return this.sounds.has(t)}sound(t){let e=this.sounds.get(t);if(!e)throw new A(t,C(t,[...this.sounds.keys()]));return e}bus(t){this.ensureGraph();let e=this.buses.get(t);if(!e)throw new T(t,C(t,[...this.buses.keys()]));return e}busGroup(t,e){if(e!=null){let s=new L(t,e);return this.busGroups.set(t,s),s}let i=this.busGroups.get(t);if(!i)throw new T(t,C(t,[...this.busGroups.keys()]));return i}masterMeter(){return this.ensureGraph(),this.master.meter()}scheduleAt(t,e){return this.host.touch(),this.ensureGraph(),this.scheduler.scheduleAt(t,e)}activeVoices(){let t=[];for(let e of this.voices.values())for(let i of e)t.push(i);return t}onStateChange(t){return this.host.onStateChange(t)}parameter(t,e=0){let i=this.parameters.get(t);return i||(i=new V(t,e),this.parameters.set(t,i)),i}captureSnapshot(t){let e={};for(let[s,r]of this.buses)e[s]={level:r.level,muted:r.muted};let i={};for(let[s,r]of this.parameters)i[s]=r.value;return this.snapshot(t,{buses:e,parameters:i})}snapshot(t,e){return new $(t,e,i=>this.buses.get(i),i=>this.parameters.get(i))}blendSnapshots(t,e,i){t.blendWith(e,i);}ensureGraph(){if(this.master)return;let t=this.host.touch();this.master=new H(t,this.config.master),this.scheduler=new K(this.host,this.config.tickSource);for(let e of this.busOrder){let i=this.config.buses?.[e]??{},s=new F(t,e,i);s.output.connect(this.master.input),s.notifySoloChange=(r,n)=>this.handleSoloChange(r,n),this.buses.set(e,s),this.voices.has(e)||this.voices.set(e,new Set);}}handleSoloChange(t,e){e?this.soloedBuses.add(t):this.soloedBuses.delete(t);let i=this.soloedBuses.size>0;for(let s of this.buses.values())i?s.applySoloVeil(!this.soloedBuses.has(s)):s.applySoloVeil(false);}},wt=4;async function Yt(o,t,e){let i=new Array(o.length),s=0,r=async()=>{for(;;){let a=s++;if(a>=o.length)return;i[a]=await e(o[a],a);}},n=Array.from({length:Math.min(t,o.length)},r);return await Promise.all(n),i}function C(o,t){if(t.length===0)return null;let e=null,i=1/0;for(let n of t){let a=Qt(o,n);a<i&&(i=a,e=n);}let s=Math.max(o.length,e?.length??0),r=Math.max(1,Math.ceil(s/2));return e&&i<=r?e:null}function Kt(o,t){if(!o)return t;if(!t||o.aborted)return o;if(t.aborted)return t;let e=new AbortController,i=()=>{o.removeEventListener("abort",s),t.removeEventListener("abort",r);},s=()=>{i(),e.abort(o.reason);},r=()=>{i(),e.abort(t.reason);};return o.addEventListener("abort",s),t.addEventListener("abort",r),e.signal}function Qt(o,t){if(o===t)return 0;if(o.length===0)return t.length;if(t.length===0)return o.length;let e=new Array(t.length+1),i=new Array(t.length+1);for(let s=0;s<=t.length;s++)e[s]=s;for(let s=1;s<=o.length;s++){i[0]=s;for(let r=1;r<=t.length;r++){let n=o.charCodeAt(s-1)===t.charCodeAt(r-1)?0:1;i[r]=Math.min(i[r-1]+1,e[r]+1,e[r-1]+n);}for(let r=0;r<=t.length;r++)e[r]=i[r];}return e[t.length]}export{B as AggregateDecodeError,F as Bus,L as BusGroup,T as BusNotFoundError,et as Compressor,M as DecodeError,it as Ducker,x as EngineClosedError,st as Filter,H as Master,D as Music,Q as MusicVoice,V as Parameter,N as PreloadError,rt as Reverb,Z as Send,$ as Snapshot,R as Sound,A as SoundNotFoundError,q as Spatializer,G as Sprite,z as StreamSound,ot as StretchProcessor,U as Variants,I as Voice,_ as ZvukError,k as applyLoudnessNormalization,ut as canPlay,yt as computeNormalizationGain,Xt as createEngine,_t as createStretchWorkletNode,Ot as ensureStretchWorklet,ct as mimeForUrl,lt as pickSource,ht as pickSourceOrder};//# sourceMappingURL=index.js.map
71
- //# sourceMappingURL=index.js.map
69
+ registerProcessor('${Nt}', ZvukRealtimeStretchProcessor);
70
+ `;async function Zt(n){if(Et.has(n))return;let t=n.audioWorklet;if(!t)throw new Error("AudioWorklet not supported in this context");let e=new Blob([Xt],{type:"application/javascript"}),i=URL.createObjectURL(e);try{await t.addModule(i);}finally{URL.revokeObjectURL(i);}Et.add(n);}function Kt(n,t={}){let e=globalThis.AudioWorkletNode;if(!e)throw new Error("AudioWorkletNode not available");let i=new e(n,Nt,{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[2],processorOptions:{grainSize:t.grainSize??1024}}),s=i.parameters.get("stretch");s&&t.stretchFactor!=null&&(s.value=t.stretchFactor);let r=i;return Object.defineProperty(r,"stretch",{value:s,enumerable:true}),r.dispose=()=>{try{i.disconnect();}catch{}},r}function A(n,t,e){let i=Math.max(0,t);return i===0?Promise.resolve():new Promise(s=>{let r=null,o=false,a=()=>{o||(o=true,r?.(),r=null,s());};e&&e.then(a,a),r=C(n,i,a);})}function C(n,t,e){let i=Math.max(0,t);if(n.state!=="running"){let u=setTimeout(e,i*1e3);return ()=>clearTimeout(u)}let s=n.currentTime+i,r=null,o=false,a=()=>{if(r=null,o)return;let u=s-n.currentTime;if(u<=0||n.state==="closed"){e();return}r=setTimeout(a,Math.min(u*1e3,250));};return r=setTimeout(a,i*1e3),()=>{o=true,r!=null&&clearTimeout(r),r=null;}}var Qt={reject:false,victim:null},yt={reject:true,victim:null};function rt(n,t,e,i,s){if(t<e)return Qt;if(e<=0||i==="none")return yt;let r=null,o=0;for(let a of n){let u=i==="oldest"?a.startedAt:i==="quietest"?a.levelHint():a.priority;(r===null||u<o||u===o&&i!=="oldest"&&a.startedAt<r.startedAt)&&(r=a,o=u);}return !r||i==="lowest-priority"&&s.priority<r.priority?yt:{reject:false,victim:r}}var Jt={reject:false,victim:null},nt=class{source;target;post;gainNode;ctx;disposed=false;constructor(t,e,i,s){this.source=t,this.target=e,this.post=i.post??true,this.ctx=s,this.gainNode=s.createGain(),this.gainNode.gain.value=V(i.amount??1),(this.post?t.output:t.input).connect(this.gainNode),this.gainNode.connect(e.input);}get amount(){return this.gainNode.gain.value}set amount(t){this.disposed||S(this.gainNode.gain,this.ctx.currentTime,V(t),.01,"linear");}fadeTo(t,e,i="linear"){return this.disposed?Promise.resolve():(S(this.gainNode.gain,this.ctx.currentTime,V(t),e,i),A(this.ctx,e))}dispose(){if(!this.disposed){this.disposed=true;try{this.gainNode.disconnect();}catch{}}}},U=class{name;input;fxInput;output;_level;_muted;_soloed=false;_soloVeiled=false;ctx;_concurrency;_voices=new Set;_fxChain=[];_sends=[];duckNode;ducks=new Map;duckSeq=0;_meterAnalyser=null;_meterBuf=null;notifySoloChange;constructor(t,e,i={}){this.ctx=t,this.name=e,this._level=i.level??1,this._muted=i.mute??false,this._concurrency=i.concurrency??null,this.input=t.createGain(),this.fxInput=t.createGain(),this.duckNode=t.createGain(),this.output=t.createGain(),this.input.connect(this.fxInput),this.fxInput.connect(this.duckNode),this.duckNode.connect(this.output),this.output.gain.value=this._muted?0:this._level;}get level(){return this._level}set level(t){this._level=V(t),!this._muted&&!this._soloVeiled&&this.rampOutput(this._level,.01);}get muted(){return this._muted}set muted(t){this._muted!==t&&(this._muted=t,this.rampOutput(t||this._soloVeiled?0:this._level,.01));}fadeTo(t,e,i="linear"){let s=V(t);return this._level=s,this._muted||this._soloVeiled?A(this.ctx,e):this.ramp(s,e,i)}get voiceCount(){return this._voices.size}voices(){return Array.from(this._voices)}get concurrency(){return this._concurrency}setConcurrency(t){this._concurrency=t;}planConcurrency(t){let e=this._concurrency;return e?rt(this._voices,this._voices.size,e.max,e.steal??"oldest",t):Jt}duck(t,e=this.ctx.currentTime){let i=++this.duckSeq,s=1-V(t.amount??.5),r=Math.max(0,t.attack??.05),o=Math.max(0,t.release??.3);this.ducks.set(i,{depth:s,start:Math.max(e,this.ctx.currentTime),attack:r}),this.scheduleDucks(r);let a=false;return ()=>{a||(a=true,this.ducks.delete(i),this.scheduleDucks(o));}}get duckLevel(){return this.duckNode.gain.value}scheduleDucks(t){let e=this.ctx.currentTime,i=this.duckNode.gain,s=1,r=[];for(let a of this.ducks.values())a.start<=e?s=Math.min(s,a.depth):r.push(a);S(i,e,s,t,"linear"),r.sort((a,u)=>a.start-u.start);let o=e+t;for(let a of r){if(a.depth>=s)continue;s=a.depth;let u=Math.max(a.start,o);try{i.setValueAtTime(i.value,u);}catch{}try{i.linearRampToValueAtTime(s,u+a.attack);}catch{i.value=s;}o=u+a.attack;}}trackVoice(t){this._voices.add(t);}releaseVoice(t){this._voices.delete(t);}addFx(t){this._fxChain.push(t),this.rewireFxChain();}removeFx(t){let e=this._fxChain.indexOf(t);if(e!==-1){this._fxChain.splice(e,1);try{t.output.disconnect();}catch{}this.rewireFxChain();}}fx(){return [...this._fxChain]}meter(){if(!this._meterAnalyser){let s=this.ctx.createAnalyser();s.fftSize=1024,this.output.connect(s),this._meterAnalyser=s,this._meterBuf=new Float32Array(s.fftSize);}let t=this._meterBuf;this._meterAnalyser.getFloatTimeDomainData(t);let e=0,i=0;for(let s=0;s<t.length;s++){let r=t[s]??0;e+=r*r;let o=Math.abs(r);o>i&&(i=o);}return {rms:Math.sqrt(e/t.length),peak:i}}send(t,e={}){let i=new nt(this,t,e,this.ctx);return this._sends.push(i),i}removeSend(t){let e=this._sends.indexOf(t);e!==-1&&(this._sends.splice(e,1),t.dispose());}sends(){return [...this._sends]}solo(t=true){this._soloed!==t&&(this._soloed=t,this.notifySoloChange?.(this,t));}unsolo(){this.solo(false);}get soloed(){return this._soloed}applySoloVeil(t){this._soloVeiled=t;let e=this._muted||t?0:this._level;this.rampOutput(e,.01);}rewireFxChain(){for(let e of [this.fxInput,...this._fxChain.map(i=>i.output)])try{e.disconnect();}catch{}let t=this.fxInput;for(let e of this._fxChain)t.connect(e.input),t=e.output;t.connect(this.duckNode);}rampOutput(t,e){this.ramp(t,e,"linear");}ramp(t,e,i){let s=this.output.gain,r=this.ctx.currentTime;return S(s,r,t,e,i),A(this.ctx,e)}dispose(){for(let t of this._sends)t.dispose();this._sends=[];for(let t of this._fxChain)t.dispose();this._fxChain=[],this.ducks.clear();try{this.input.disconnect(),this.fxInput.disconnect(),this.duckNode.disconnect(),this.output.disconnect(),this._meterAnalyser?.disconnect();}catch{}this._meterAnalyser=null,this._meterBuf=null;}};function V(n){return Number.isNaN(n)?0:Math.min(1,Math.max(0,n))}var $=class{name;members;constructor(t,e){this.name=t,this.members=e;}set level(t){for(let e of this.members)e.level=t;}get level(){if(this.members.length===0)return 0;let t=0;for(let e of this.members)t+=e.level;return t/this.members.length}set muted(t){for(let e of this.members)e.muted=t;}get muted(){return this.members.length===0?false:this.members.every(t=>t.muted)}fadeTo(t,e,i="linear"){return Promise.all(this.members.map(s=>s.fadeTo(t,e,i))).then(()=>{})}solo(t=true){for(let e of this.members)e.solo(t);}unsolo(){this.solo(false);}};var H=class{name;_value;subs=new Set;glide=null;constructor(t,e){this.name=t,this._value=e;}get value(){return this._value}set(t){this.cancelGlide(),this.write(t);}get gliding(){return this.glide!=null}rampTo(t,e,i="linear"){this.cancelGlide();let s=Math.max(0,e);if(s===0||t===this._value)return this.write(t),Promise.resolve();let r=this._value,o=t>=r,a=Lt();return new Promise(u=>{let c={cancel:()=>{}},l=()=>{let d=Math.min(1,(Lt()-a)/(s*1e3)),f=Vt(d,i,o);if(this.write(r+(t-r)*f),d>=1){this.glide=null,u();return}c=Ft(l);};this.glide={cancel:()=>c.cancel(),resolve:u},c=Ft(l);})}cancelGlide(){let t=this.glide;t&&(this.glide=null,t.cancel(),t.resolve());}write(t){if(t!==this._value){this._value=t;for(let e of this.subs)e(t);}}subscribe(t){return this.subs.add(t),t(this._value),()=>this.subs.delete(t)}bindTo(t,e={}){let i=e.from??0,s=e.to??1,r=e.curve??"linear",o=s>=i;return this.subscribe(a=>{let u=Math.max(0,Math.min(1,a)),c=Vt(u,r,o);t(i+(s-i)*c);})}};function Lt(){return typeof performance<"u"?performance.now():Date.now()}function Ft(n){if(!(typeof document<"u"&&document.visibilityState==="hidden")&&typeof requestAnimationFrame=="function"){let i=requestAnimationFrame(()=>n());return {cancel:()=>cancelAnimationFrame(i)}}let e=setTimeout(n,16);return {cancel:()=>clearTimeout(e)}}function Vt(n,t,e=true){switch(t){case "easeIn":return n*n;case "easeOut":return 1-(1-n)*(1-n);case "easeInOut":return n<.5?2*n*n:1-2*(1-n)*(1-n);case "equal-power":return e?Math.sin(n*Math.PI/2):1-Math.cos(n*Math.PI/2);default:return n}}var te={webm:'audio/webm; codecs="opus"',opus:'audio/ogg; codecs="opus"',ogg:'audio/ogg; codecs="vorbis"',m4a:'audio/mp4; codecs="mp4a.40.2"',mp4:'audio/mp4; codecs="mp4a.40.2"',aac:'audio/mp4; codecs="mp4a.40.2"',mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac"},St=null;function xt(n){if(typeof document>"u")return true;if(!St)try{St=document.createElement("audio");}catch{return true}let t=St.canPlayType(n);return t==="probably"||t==="maybe"}function At(n){let t=/\.([a-z0-9]+)(?:[?#]|$)/i.exec(n);return t?.[1]?te[t[1].toLowerCase()]??null:null}function ee(n){if(n.length===0)throw new Error("pickSource requires at least one URL");for(let t of n){let e=At(t);if(e&&xt(e))return t}return n[0]}function ot(n){if(n.length===0)return n;let t=[],e=[];for(let i of n){let s=At(i);s&&xt(s)?t.push(i):e.push(i);}return [...t,...e]}var at=class{_ctx=null;_state="cold";_unlocking=null;_listeners=new Set;opts;_userSuspended=false;constructor(t={}){this.opts=t;}get state(){return this._state}touch(){if(this._state==="closed")throw new x;if(!this._ctx){let t={};this.opts.latencyHint!=null&&(t.latencyHint=this.opts.latencyHint);let e=ie();this._ctx=new e(t),this.attachVisibilityHandler(),this.attachStateChangeHandler(this._ctx);}return this._ctx}peek(){return this._ctx}get userSuspended(){return this._userSuspended}async suspend(){if(this._state==="closed")throw new x;this._userSuspended=true;let t=this._ctx;!t||t.state==="closed"||(t.state==="running"&&await t.suspend().catch(()=>{}),(this._state==="live"||this._state==="unlocking")&&this.setState("suspended"));}async resume(){return this.unlock()}async unlock(){if(this._state==="closed")throw new x;if(this._userSuspended=false,this._unlocking)return this._unlocking;if(this._state==="live"&&this._ctx?.state==="running")return;this.setState("unlocking");let t=this.touch();return this._unlocking=(async()=>{try{t.state==="suspended"&&await t.resume(),this.setState("live");}catch(e){throw this.setState("cold"),e}finally{this._unlocking=null;}})(),this._unlocking}get now(){return this._ctx?.currentTime??0}onStateChange(t){return this._listeners.add(t),()=>this._listeners.delete(t)}async close(){this._state!=="closed"&&(typeof document<"u"&&document.removeEventListener("visibilitychange",this.handleVisibility),this._ctx&&(this._ctx.removeEventListener("statechange",this.handleCtxStateChange),this._ctx.state!=="closed"&&await this._ctx.close().catch(()=>{})),this._ctx=null,this.setState("closed"),this._listeners.clear());}setState(t){if(this._state!==t){this._state=t;for(let e of this._listeners)e(t);}}attachVisibilityHandler(){this.opts.autoPauseOnHidden!==false&&(typeof document>"u"||document.addEventListener("visibilitychange",this.handleVisibility));}handleVisibility=()=>{if(!this._ctx||this._state==="closed")return;document.visibilityState==="visible"?setTimeout(()=>{document.visibilityState==="visible"&&!this._userSuspended&&this._ctx?.state==="suspended"&&this._ctx.resume().catch(()=>{});},200):this._ctx.suspend().catch(()=>{});};attachStateChangeHandler(t){t.addEventListener("statechange",this.handleCtxStateChange);}handleCtxStateChange=()=>{let t=this._ctx;if(!t||this._state==="closed")return;let e=t.state;if(e==="interrupted"){this.setState("interrupted");return}if(e==="suspended"){if(this._state==="interrupted"){setTimeout(()=>{this._ctx===t&&t.state==="suspended"&&!this._userSuspended&&t.resume().catch(()=>{});},200);return}(this._state==="live"||this._state==="unlocking")&&this.setState("suspended");return}e==="running"&&this._state!=="live"&&this.setState("live");}};function ie(){let n=globalThis,t=n.AudioContext??n.webkitAudioContext;if(!t)throw new Error("No AudioContext constructor available in this environment.");return t}var se=64*1024*1024,re=128;function ne(n){return n.length*n.numberOfChannels*4}var ut=class{constructor(t,e={}){this.getCtx=t;let i=typeof e=="number"?{maxEntries:e}:e;this.maxBytes=Math.max(1,i.maxBytes??se),this.maxEntries=Math.max(1,i.maxEntries??re);}getCtx;cache=new Map;bytes=0;inflight=new Map;maxBytes;maxEntries;has(t){return this.cache.has(t)}get cachedBytes(){return this.bytes}async load(t,e={}){let i=this.cache.get(t);if(i)return this.touch(t,i.buffer),i.buffer;let s=this.inflight.get(t);if(s)return this.join(s,e.signal);let r=new AbortController,o;return o={promise:this.fetchAndDecode(t,r.signal,e.onProgress).finally(()=>{this.inflight.get(t)===o&&this.inflight.delete(t);}),controller:r,waiters:0},this.inflight.set(t,o),this.join(o,e.signal)}join(t,e){t.waiters++;let i=()=>{if(t.waiters--,t.waiters<=0){t.controller.abort();for(let[s,r]of this.inflight)r===t&&this.inflight.delete(s);}};return e?e.aborted?(i(),Promise.reject(It(e))):new Promise((s,r)=>{let o=false,a=()=>{o||(o=true,i(),r(It(e)));};e.addEventListener("abort",a,{once:true}),t.promise.then(u=>{o||(o=true,t.waiters--,e.removeEventListener("abort",a),s(u));},u=>{o||(o=true,t.waiters--,e.removeEventListener("abort",a),r(u));});}):t.promise.finally(()=>t.waiters--)}async fetchAndDecode(t,e,i){let s;try{s=await fetch(t,{signal:e});}catch(u){throw u.name==="AbortError"?u:new B(t,u)}if(!s.ok)throw new B(t,new Error(`${s.status} ${s.statusText}`));let r=i?await oe(s,i):await s.arrayBuffer(),o=this.getCtx(),a;try{a=await o.decodeAudioData(r);}catch(u){throw new B(t,u)}return this.touch(t,a),a}async loadFirst(t,e={}){if(t.length===0)throw new Error("loadFirst requires at least one URL");for(let s of t){let r=this.cache.get(s);if(r)return this.touch(s,r.buffer),r.buffer}let i=[];for(let s of t)try{return await this.load(s,e)}catch(r){if(r.name==="AbortError")throw r;i.push({url:s,cause:r});}if(t.length===1){let s=i[0]?.cause;throw s instanceof Error?s:new B(t[0],s)}throw new j(t,i)}evict(t){let e=this.cache.get(t);e&&(this.bytes-=e.bytes,this.cache.delete(t));}clear(){this.cache.clear(),this.bytes=0;}touch(t,e){this.evict(t);let i=ne(e);for(this.cache.set(t,{buffer:e,bytes:i}),this.bytes+=i;this.cache.size>this.maxEntries||this.bytes>this.maxBytes&&this.cache.size>1;){let s=this.cache.keys().next().value;if(s===void 0)break;this.evict(s);}}};function It(n){return n.reason??new DOMException("load aborted","AbortError")}async function oe(n,t){let e=n.body;if(!e||typeof e.getReader!="function"){let d=await n.arrayBuffer();return t(d.byteLength,d.byteLength),d}let i=n.headers.get("content-length"),s=i?Number.parseInt(i,10):Number.NaN,r=Number.isFinite(s)?s:null,o=e.getReader(),a=[],u=0;for(;;){let{done:d,value:f}=await o.read();if(d)break;f&&(a.push(f),u+=f.byteLength,t(u,r));}let c=new Uint8Array(u),l=0;for(let d of a)c.set(d,l),l+=d.byteLength;return c.buffer}var ae={targetRms:.1,peakCeiling:.99};function I(n,t,e){if(!t)return n;let i={...ae,...typeof t=="object"?t:{}},s=Dt(n,i);return Math.abs(s-1)<.001?n:le(n,s,e)}function Dt(n,t){let e=ue(n);if(e<=1e-6)return 1;let i=t.targetRms/e,s=ce(n)*i;return s>t.peakCeiling&&(i*=t.peakCeiling/s),i}function ue(n){let t=0,e=0;for(let i=0;i<n.numberOfChannels;i++){let s=n.getChannelData(i);for(let r=0;r<s.length;r++)t+=s[r]*s[r];e+=s.length;}return e===0?0:Math.sqrt(t/e)}function ce(n){let t=0;for(let e=0;e<n.numberOfChannels;e++){let i=n.getChannelData(e);for(let s=0;s<i.length;s++){let r=Math.abs(i[s]);r>t&&(t=r);}}return t}function le(n,t,e){if(e){let i=e.createBuffer(n.numberOfChannels,n.length,n.sampleRate);for(let s=0;s<n.numberOfChannels;s++){let r=n.getChannelData(s),o=i.getChannelData(s);for(let a=0;a<r.length;a++)o[a]=r[a]*t;}return i}for(let i=0;i<n.numberOfChannels;i++){let s=n.getChannelData(i);for(let r=0;r<s.length;r++)s[r]=s[r]*t;}return n}var ct=class{constructor(t,e){this.host=t;this.tickSource=e;}host;tickSource;tasks=[];cancelled=0;timer=null;unsubscribe=null;scheduleAt(t,e){let i={audioTime:t,fn:e,cancelled:false};return this.tasks.splice(this.insertionIndex(t),0,i),this.arm(),()=>{i.cancelled||(i.cancelled=true,this.cancelled++,this.cancelled>32&&this.cancelled*2>this.tasks.length&&this.compact());}}insertionIndex(t){let e=0,i=this.tasks.length;for(;e<i;){let s=e+i>>>1;this.tasks[s].audioTime<=t?e=s+1:i=s;}return e}compact(){this.tasks=this.tasks.filter(t=>!t.cancelled),this.cancelled=0;}arm(){if(this.tickSource){this.unsubscribe||(this.unsubscribe=this.tickSource.subscribe(()=>this.tick()));return}this.rearmTimer();}rearmTimer(){this.timer!=null&&(clearTimeout(this.timer),this.timer=null);let t=this.tasks.find(s=>!s.cancelled);if(!t)return;let e=this.host.now,i=Math.max(0,(t.audioTime-e)*1e3);this.timer=setTimeout(()=>this.tick(),i);}tick(){this.timer!=null&&(this.timer=null);let t=this.host.now,e=[],i=[];for(let s of this.tasks)s.cancelled||(s.audioTime<=t?e.push(s):i.push(s));this.tasks=i,this.cancelled=0;for(let s of e)try{s.fn();}catch(r){console.error("[zvuk] scheduled task threw",r);}if(this.tasks.length===0){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null);return}this.tickSource||this.rearmTimer();}dispose(){this.timer!=null&&clearTimeout(this.timer),this.timer=null,this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null),this.tasks=[],this.cancelled=0;}};var de=.008,he=.05,pe=.01,Tt=.05,W=class{name;deps;live=new Set;constructor(t,e){this.name=t,this.deps=e;}get loopDuration(){return this.deps.buffers.loop.duration}get hasIntro(){return this.deps.buffers.intro!=null}get hasOutro(){return this.deps.buffers.outro!=null}get grid(){let t=this.deps.grid;if(t)return {bpm:t.bpm,beatsPerBar:t.beatsPerBar??4,offset:t.offset??this.deps.buffers.intro?.duration??0}}play(t={}){let e=new lt({ctx:this.deps.ctx,buffers:this.deps.buffers,destination:this.deps.destination,loopCrossfade:this.deps.loopCrossfade,defaultStopFade:this.deps.defaultStopFade,grid:this.grid,options:t});return this.live.add(e),e.ended.then(()=>this.live.delete(e)),e}voices(){return Array.from(this.live)}stopAll(t={}){for(let e of Array.from(this.live))e.stop(t);this.live.clear();}},lt=class{ended;ctx;buffers;destination;gain;state="intro";done=false;resolveEnded;stopFade;loopCrossfadeSec;grid;introSource=null;outroSource=null;loopChain=[];loopArmTimer=null;outroTimer=null;flipTimer=null;nextLoopBoundaryAt=Number.POSITIVE_INFINITY;loopAnchorAt=Number.POSITIVE_INFINITY;introStartAt=Number.NEGATIVE_INFINITY;introEndsAt=Number.NEGATIVE_INFINITY;outroStartAt=Number.POSITIVE_INFINITY;outroMode=null;loopDeadline=Number.POSITIVE_INFINITY;gridZero=0;paused=false;pausedAt=0;pausedPart="loop";pausedOffset=0;beatListeners=new Set;beatTimer=null;constructor(t){this.ctx=t.ctx,this.buffers=t.buffers,this.destination=t.destination,this.loopCrossfadeSec=Math.max(0,t.loopCrossfade),this.stopFade=Math.max(0,t.defaultStopFade??de),this.grid=t.grid&&t.grid.bpm>0?t.grid:void 0;let e=this.ctx.currentTime,i=t.options.at,s=i!=null&&Number.isFinite(i)&&i>e?i:e;this.gain=this.ctx.createGain();let r=Rt(t.options.volume??1),o=Math.max(0,t.options.fadeIn??0);o>0?(this.gain.gain.setValueAtTime(0,s),this.gain.gain.linearRampToValueAtTime(r,s+o)):this.gain.gain.value=r,this.gain.connect(this.destination),this.ended=new Promise(a=>{this.resolveEnded=a;}),this.gridZero=s+(this.grid?.offset??0),this.start(s);}get currentPart(){return this.state}get isPaused(){return this.paused}get tempo(){return this.grid}fade(t){if(this.done)return Promise.resolve();let e=this.gain.gain,i=this.ctx.currentTime;return S(e,i,Rt(t.to),t.duration,t.curve??"linear"),A(this.ctx,t.duration,this.ended)}stop(t={}){if(this.done)return;let e=Math.max(0,t.fade??this.stopFade);if(this.cancelTimers(),e===0||this.paused){this.stopAllSources(0),this.finish();return}let i=this.ctx.currentTime,s=i+e;try{let r=this.gain.gain;r.cancelScheduledValues(i),r.setValueAtTime(r.value,i),r.linearRampToValueAtTime(0,s),this.stopAllSources(s);}catch{this.finish();return}C(this.ctx,e,()=>this.finish());}pause(){if(this.done||this.paused)return;let t=this.ctx.currentTime,e=this.position(t);this.pausedPart=e.part,this.pausedOffset=e.offset,this.pausedAt=t;let i=this.outroMode!=null&&t<this.outroStartAt?this.outroMode:null;this.cancelTimers(),this.clearBeatTimer(),this.stopAllSources(0),this.disconnectSources(),this.outroMode=i,this.outroStartAt=Number.POSITIVE_INFINITY,this.loopDeadline=Number.POSITIVE_INFINITY,this.paused=true;}resume(){if(this.done||!this.paused)return;this.paused=false;let t=this.ctx.currentTime;this.gridZero+=t-this.pausedAt;let e=this.pausedOffset,i=this.outroMode;this.outroMode=null,this.pausedPart==="intro"&&this.buffers.intro?(this.state="intro",this.scheduleIntro(t,e),this.scheduleLoopStart(this.introEndsAt,0)):this.pausedPart==="outro"&&this.buffers.outro?(this.state="outro",this.playOutroFrom(t,e)):(this.state="loop",this.scheduleLoopStart(t,e)),i&&this.skipToOutro({at:i}),this.beatListeners.size>0&&this.armBeat();}skipToOutro(t={}){if(this.done||this.state==="outro"||this.state==="ended"||this.outroMode!=null)return;if(!this.buffers.outro){this.stop();return}let e=t.at??"loop-end";(e==="bar"||e==="beat")&&!this.grid&&(e="loop-end"),this.outroMode=e,!this.paused&&(e==="now"?this.skipToOutroNow():e==="loop-end"?this.skipToOutroAtLoopEnd():this.skipToOutroOnGrid(e==="bar"?this.nextBar():this.nextBeat()));}nextBeat(t=this.ctx.currentTime){if(this.grid)return this.nextGridPoint(t,60/this.grid.bpm)}nextBar(t=this.ctx.currentTime){if(this.grid)return this.nextGridPoint(t,60/this.grid.bpm*this.grid.beatsPerBar)}beatAt(t=this.ctx.currentTime){if(!this.grid)return;let e=this.paused?this.pausedAt:t,i=Math.max(0,(e-this.gridZero)/(60/this.grid.bpm)),s=Math.floor(i);return {beat:i,bar:Math.floor(s/this.grid.beatsPerBar),beatInBar:s%this.grid.beatsPerBar}}onBeat(t){return !this.grid||this.done?()=>{}:(this.beatListeners.add(t),this.beatListeners.size===1&&!this.paused&&this.armBeat(),()=>{this.beatListeners.delete(t),this.beatListeners.size===0&&this.clearBeatTimer();})}nextGridPoint(t,e){let i=this.paused?this.gridZero+(this.ctx.currentTime-this.pausedAt):this.gridZero;if(t<i)return i;let s=Math.floor((t-i)/e+1e-6)+1;return i+s*e}armBeat(){if(this.clearBeatTimer(),!this.grid||this.done||this.paused)return;let t=this.ctx.currentTime,e=60/this.grid.bpm,i=this.nextGridPoint(t+Tt-1e-4,e),s=Math.round((i-this.gridZero)/e);this.beatTimer=C(this.ctx,Math.max(0,i-t-Tt),()=>{this.beatTimer=null,this.fireBeat(i,s);});}fireBeat(t,e){if(this.done||this.paused||!this.grid)return;let i={time:t,beat:e,bar:Math.floor(e/this.grid.beatsPerBar),beatInBar:e%this.grid.beatsPerBar};for(let a of [...this.beatListeners])a(i);if(this.beatListeners.size===0||this.beatTimer)return;let s=60/this.grid.bpm,r=this.nextGridPoint(Math.max(this.ctx.currentTime,t)+1e-4,s),o=Math.round((r-this.gridZero)/s);this.beatTimer=C(this.ctx,Math.max(0,r-this.ctx.currentTime-Tt),()=>{this.beatTimer=null,this.fireBeat(r,o);});}clearBeatTimer(){this.beatTimer&&(this.beatTimer(),this.beatTimer=null);}start(t){this.buffers.intro?(this.scheduleIntro(t,0),this.scheduleLoopStart(this.introEndsAt,0)):(this.state="loop",this.scheduleLoopStart(t,0));}scheduleIntro(t,e){let i=this.buffers.intro,s=this.ctx.createBufferSource();s.buffer=i,s.connect(this.gain);try{s.start(t,e);}catch{}this.introStartAt=t-e,this.introEndsAt=t+(i.duration-e),s.onended=()=>{this.introSource===s&&(this.introSource=null);},this.introSource=s;}scheduleLoopStart(t,e){if(this.done)return;let i=this.buffers.loop.duration,s=Math.max(0,Math.min(e,i));this.crossfadeViable()&&i-s<=this.loopCrossfadeSec*2&&(s=0);let o=this.spawnLoopSegment(t,false,s).startTime;this.loopAnchorAt=o-s,this.nextLoopBoundaryAt=this.loopAnchorAt+i,this.crossfadeViable()?this.armNextLoopSegment(this.loopAnchorAt):this.state==="intro"?this.flipTimer=C(this.ctx,o-this.ctx.currentTime,()=>{this.flipTimer=null,!this.done&&this.state==="intro"&&(this.state="loop");}):this.state="loop";}spawnLoopSegment(t,e,i){let s=this.ctx.currentTime,r=Math.max(t,s),o=e&&s-t<this.loopCrossfadeSec,a=this.crossfadeViable(),u=this.buffers.loop.duration-i,c=this.ctx.createBufferSource();c.buffer=this.buffers.loop,c.loop=!a,a||(c.loopStart=0,c.loopEnd=this.buffers.loop.duration);let l=this.ctx.createGain();st(l.gain,r,u,this.loopCrossfadeSec,{fadeIn:o,fadeOut:a}),c.connect(l).connect(this.gain);try{a?c.start(r,i,u):c.start(r,i),Number.isFinite(this.loopDeadline)&&c.stop(this.loopDeadline);}catch{}c.onended=()=>this.releaseLoopSegment(c,l);let d={source:c,gain:l,startTime:r,offset:i};return this.loopChain.push(d),d}armNextLoopSegment(t){this.cancelLoopArm();let e=t+this.buffers.loop.duration-this.loopCrossfadeSec,s=Math.max(0,(e-this.ctx.currentTime)*1e3-50);this.loopArmTimer=setTimeout(()=>{if(this.loopArmTimer=null,this.done||this.paused||this.state!=="loop"&&this.state!=="intro"||e>=this.loopDeadline)return;this.state="loop";let r=e;try{r=this.spawnLoopSegment(e,!0,0).startTime;}finally{this.loopAnchorAt=r,this.nextLoopBoundaryAt=r+this.buffers.loop.duration,this.armNextLoopSegment(r);}},s);}crossfadeViable(){return this.loopCrossfadeSec>0&&this.buffers.loop.duration>this.loopCrossfadeSec*2}releaseLoopSegment(t,e){let i=this.loopChain.findIndex(s=>s.source===t);i>=0&&this.loopChain.splice(i,1);try{t.disconnect(),e.disconnect();}catch{}}nextLoopBoundary(){if(this.crossfadeViable())return this.nextLoopBoundaryAt;if(!Number.isFinite(this.loopAnchorAt))return this.loopAnchorAt;let t=this.ctx.currentTime-this.loopAnchorAt,e=this.buffers.loop.duration;return t<0||e<=0?this.loopAnchorAt+(t<0?e:0):this.loopAnchorAt+(Math.floor(t/e)+1)*e}position(t){if(this.outroSource&&t>=this.outroStartAt)return {part:"outro",offset:Math.max(0,t-this.outroStartAt)};if(this.buffers.intro&&t<this.introEndsAt)return {part:"intro",offset:Math.max(0,t-this.introStartAt)};let e=this.buffers.loop.duration;if(this.crossfadeViable()){let s=null;for(let r of this.loopChain)r.startTime<=t&&(!s||r.startTime>s.startTime)&&(s=r);if(s)return {part:"loop",offset:Math.min(e,s.offset+(t-s.startTime))}}return !Number.isFinite(this.loopAnchorAt)||e<=0?{part:"loop",offset:0}:{part:"loop",offset:Math.max(0,t-this.loopAnchorAt)%e}}skipToOutroAtLoopEnd(){this.cancelLoopArm();let t;this.state==="intro"?t=this.introEndsAt:t=this.nextLoopBoundary(),t=Math.max(t,this.ctx.currentTime),this.loopDeadline=t,this.stopLoopSourcesAt(t,0),this.scheduleOutro(t);}skipToOutroOnGrid(t){let e=Math.max(t,this.ctx.currentTime);if(this.loopDeadline=e,this.introSource&&e<this.introEndsAt)try{this.introSource.stop(e);}catch{}this.stopLoopSourcesAt(e,pe),this.scheduleOutro(e);}skipToOutroNow(){this.cancelLoopArm();let t=this.ctx.currentTime,e=t+he;this.loopDeadline=e;for(let i of this.loopChain){try{let s=i.gain.gain;s.cancelScheduledValues(t),s.setValueAtTime(s.value,t),s.linearRampToValueAtTime(0,e);}catch{}try{i.source.stop(e);}catch{}}if(this.introSource)try{this.introSource.stop(e);}catch{}this.scheduleOutro(e);}cancelLoopArm(){this.loopArmTimer!=null&&(clearTimeout(this.loopArmTimer),this.loopArmTimer=null);}stopLoopSourcesAt(t,e){for(let i of this.loopChain){if(e>0&&i.startTime<t){let s=Math.max(this.ctx.currentTime,t-e);try{i.gain.gain.setValueAtTime(i.gain.gain.value,s),i.gain.gain.linearRampToValueAtTime(0,t);}catch{}}try{i.source.stop(t);}catch{}}}scheduleOutro(t){this.outroStartAt=t,this.playOutroFrom(t,0);}playOutroFrom(t,e){let i=this.buffers.outro;if(!i){this.outroTimer=C(this.ctx,t-this.ctx.currentTime,()=>this.finish());return}this.outroStartAt=t-e;let s=this.ctx.createBufferSource();s.buffer=i,s.connect(this.gain);try{s.start(t,e);}catch{}if(s.onended=()=>{this.paused||(this.outroSource===s&&(this.outroSource=null),this.finish());},this.outroSource=s,e>0){this.state="outro";return}this.outroTimer=C(this.ctx,t-this.ctx.currentTime,()=>{this.outroTimer=null,this.done||(this.state="outro");});}cancelTimers(){this.cancelLoopArm(),this.outroTimer!=null&&(this.outroTimer(),this.outroTimer=null),this.flipTimer!=null&&(this.flipTimer(),this.flipTimer=null);}stopAllSources(t){let e=[];this.introSource&&e.push(this.introSource);for(let i of this.loopChain)e.push(i.source);this.outroSource&&e.push(this.outroSource);for(let i of e)try{i.onended=null,t===0?i.stop():i.stop(t);}catch{}}disconnectSources(){try{this.introSource&&this.introSource.disconnect();for(let t of this.loopChain)t.source.disconnect(),t.gain.disconnect();this.outroSource&&this.outroSource.disconnect();}catch{}this.introSource=null,this.outroSource=null,this.loopChain=[];}finish(){if(!this.done){this.done=true,this.state="ended",this.cancelTimers(),this.clearBeatTimer(),this.beatListeners.clear(),this.disconnectSources();try{this.gain.disconnect();}catch{}this.resolveEnded();}}};function Rt(n){return Number.isNaN(n)?0:Math.min(1,Math.max(0,n))}var fe=.008,me=.03,D=class n{id;priority;bus;startedAt;sourceName;rejected;ended;ctx;gain;source;buffer;loop;basePitch;done=false;stopping=false;paused=false;resolveEnded;cueListeners=new Set;startCtxTime;pausedOffset=0;currentOffset=0;_spatializer;startOffset;regionDuration;loopStart;loopEnd;regionTimer=null;startTimer=null;stopFade;signal;onAbort=null;crossfadeSec=0;crossfadeRegionStart=0;crossfadeRegionLen=0;crossfadeChain=[];crossfadeArmTimer=null;levelAnalyser=null;levelBuf=null;static nextId=1;constructor(t){let{ctx:e,buffer:i,destination:s,options:r}=t;this.id=n.nextId++,this.ctx=e,this.priority=r.priority??0,this.bus=r.bus,this.sourceName=t.sourceName;let o=e.currentTime,a=r.at,u=a!=null&&Number.isFinite(a)&&a>o?a:o;if(this.startedAt=u,this.startCtxTime=u,this.buffer=i,this.loop=r.loop??false,this.basePitch=Gt(r.pitch??1,1),this._spatializer=t.spatializer,this.startOffset=r.offset??0,this.currentOffset=this.startOffset,this.regionDuration=r.duration,this.loopStart=r.loopStart,this.loopEnd=r.loopEnd,this.stopFade=Math.max(0,t.defaultStopFade??fe),this.rejected=t.rejected===true,this.ended=new Promise(d=>{this.resolveEnded=d;}),this.rejected){this.done=true,this.resolveEnded();return}this.gain=e.createGain();let c=zt(Gt(r.volume??1)),l=Math.max(0,r.fadeIn??0);if(l>0?(this.gain.gain.setValueAtTime(0,u),this.gain.gain.linearRampToValueAtTime(c,u+l)):this.gain.gain.value=c,this.gain.connect(s),r.signal&&(r.signal.aborted?queueMicrotask(()=>this.stop()):(this.signal=r.signal,this.onAbort=()=>this.stop(),r.signal.addEventListener("abort",this.onAbort,{once:true}))),this.shouldUseLoopCrossfade(r)){this.crossfadeSec=r.loopCrossfade,this.crossfadeRegionStart=r.loopStart??this.startOffset;let d=r.loopEnd??i.duration;this.crossfadeRegionLen=Math.max(0,d-this.crossfadeRegionStart),this.source=this.startCrossfadeChain(u,0);}else {this.source=this.createSourceNode(this.basePitch),this.bindSourceLifecycle(this.source,()=>{});try{this.source.start(u,this.startOffset);}catch{}this.armRegionTimer(this.regionDuration,u-o);}u>o?this.startTimer=C(e,u-o,()=>{this.startTimer=null,this.done||this.emit("started");}):queueMicrotask(()=>this.emit("started")),this.ended.then(()=>t.onEnded(this));}shouldUseLoopCrossfade(t){if(!this.loop)return false;let e=t.loopCrossfade;if(e==null||e<=0)return false;let i=t.loopStart??this.startOffset;return (t.loopEnd??this.buffer.duration)-i>e*2}fade(t){if(this.done||this.stopping)return Promise.resolve();let e=this.gain.gain,i=this.ctx.currentTime;return S(e,i,zt(t.to),t.duration,t.curve??"linear"),A(this.ctx,t.duration,this.ended)}stop(t={}){if(this.done||this.stopping)return;let e=Math.max(0,t.fade??this.stopFade);if(this.clearArmTimer(),e===0){this.stopAllSources(0),this.finish("ended");return}this.stopping=true;let i=this.ctx.currentTime,s=i+e;for(let r of this.activeSources())r.onended=null;this.regionTimer!=null&&(this.regionTimer(),this.regionTimer=null);try{let r=this.gain.gain;r.cancelScheduledValues(i),r.setValueAtTime(r.value,i),r.linearRampToValueAtTime(0,s),this.stopAllSources(s);}catch{this.finish("ended");return}C(this.ctx,e,()=>this.finish("ended"));}activeSources(){return this.inCrossfadeMode?this.crossfadeChain.map(t=>t.source):this.source?[this.source]:[]}stopAllSources(t){for(let e of this.activeSources())try{t===0?e.stop():e.stop(t);}catch{}}pause(){if(this.done||this.paused)return;let t=this.computeOffset();this.pausedOffset=t,this.currentOffset=t,this.paused=true,this.regionTimer!=null&&(this.regionTimer(),this.regionTimer=null),this.clearArmTimer();for(let e of this.activeSources()){try{e.onended=null,e.stop();}catch{}try{e.disconnect();}catch{}}if(this.inCrossfadeMode){for(let e of this.crossfadeChain)N(e.gain);this.crossfadeChain=[];}this.emit("paused");}resume(){if(!(this.done||!this.paused)){if(this.paused=false,this.startCtxTime=this.ctx.currentTime,this.inCrossfadeMode){let t=this.pausedOffset-this.crossfadeRegionStart;this.source=this.startCrossfadeChain(this.startCtxTime,t);}else {this.source=this.createSourceNode(this.basePitch),this.bindSourceLifecycle(this.source,()=>{});try{this.source.start(0,this.pausedOffset);}catch{}if(this.regionDuration!=null){let t=Math.max(0,this.pausedOffset-this.startOffset),e=Math.max(0,this.regionDuration-t);this.armRegionTimer(e);}}this.emit("resumed");}}get isPaused(){return this.paused}get isDone(){return this.done}setPlaybackRate(t,e={}){if(this.done)return;let i=Math.max(0,t),s=Math.max(0,e.duration??0);if(this.paused){this.basePitch=i;return}if(this.inCrossfadeMode){if(i===this.basePitch||this.stopping){this.basePitch=i;return}this.reseamCrossfade(i);return}if(this.currentOffset=this.computeOffset(),this.startCtxTime=Math.max(this.ctx.currentTime,this.startCtxTime),this.basePitch=i,this.regionTimer!=null&&this.regionDuration!=null){let r=Math.max(0,this.currentOffset-this.startOffset);this.armRegionTimer(Math.max(0,this.regionDuration-r),this.startCtxTime-this.ctx.currentTime);}for(let r of this.activeSources()){let o=r.playbackRate;s===0?o.value=i:S(o,this.ctx.currentTime,i,s,e.curve??"linear");}}get playbackRate(){return this.basePitch}get spatializer(){return this._spatializer}level(){if(this.done)return {rms:0,peak:0};if(!this.levelAnalyser){let s=this.ctx.createAnalyser();s.fftSize=512,this.gain.connect(s),this.levelAnalyser=s,this.levelBuf=new Float32Array(s.fftSize);}let t=this.levelBuf;this.levelAnalyser.getFloatTimeDomainData(t);let e=0,i=0;for(let s=0;s<t.length;s++){let r=t[s]??0;e+=r*r;let o=Math.abs(r);o>i&&(i=o);}return {rms:Math.sqrt(e/t.length),peak:i}}levelHint(){return this.done?0:this.levelAnalyser?this.level().rms:this.gain.gain.value}async*cues(){if(this.done){yield "ended";return}let t=[],e=null,i=r=>{if(e){let o=e;e=null,o({value:r,done:false});}else t.push(r);},s=r=>i(r);this.cueListeners.add(s);try{for(;;){if(t.length>0){let o=t.shift();if(yield o,o==="ended")return;continue}if(this.done){yield "ended";return}let r=await new Promise(o=>{e=o;});if(r.done||(yield r.value,r.value==="ended"))return}}finally{this.cueListeners.delete(s);}}finish(t,e){if(!this.done){this.done=true,this.regionTimer!=null&&(this.regionTimer(),this.regionTimer=null),this.startTimer!=null&&(this.startTimer(),this.startTimer=null),this.clearArmTimer(),this.signal&&this.onAbort&&this.signal.removeEventListener("abort",this.onAbort),this.signal=void 0,this.onAbort=null;for(let i of this.activeSources())N(i);for(let i of this.crossfadeChain)N(i.gain);this.levelAnalyser&&N(this.levelAnalyser),N(this.gain),this.levelAnalyser=null,this.levelBuf=null,this.crossfadeChain=[],this.emit(t),this.resolveEnded(),e?.(this);}}emit(t){for(let e of this.cueListeners)e(t);}clearArmTimer(){this.crossfadeArmTimer!=null&&(clearTimeout(this.crossfadeArmTimer),this.crossfadeArmTimer=null);}createSourceNode(t){let e=this.ctx.createBufferSource();return e.buffer=this.buffer,e.loop=this.loop,this.loop&&this.loopStart!=null&&(e.loopStart=this.loopStart),this.loop&&this.loopEnd!=null&&(e.loopEnd=this.loopEnd),e.playbackRate.value=t,e.connect(this.gain),e}armRegionTimer(t,e=0){if(this.regionTimer!=null&&(this.regionTimer(),this.regionTimer=null),t==null||this.loop)return;let i=Math.max(0,e)+Math.max(0,t)/Math.max(1e-4,this.basePitch);this.regionTimer=C(this.ctx,i,()=>{this.regionTimer=null,this.done||this.stop();});}bindSourceLifecycle(t,e){t.onended=()=>{this.paused||t.loop||this.finish("ended",e);};}startCrossfadeChain(t,e,i){let s=Math.max(0,e),r=Math.max(1e-4,this.basePitch);(this.crossfadeRegionLen-s)/r<=this.segmentXf(r)*2&&(s=0);let o=this.spawnCrossfadeSegment(t,i!=null,s,i);return this.armNextCrossfadeSegment(o),o.source}segmentXf(t){return Math.min(this.crossfadeSec,this.crossfadeRegionLen/t/2.5)}spawnCrossfadeSegment(t,e,i,s){let r=this.ctx.currentTime,o=Math.max(t,r),a=Math.max(1e-4,this.basePitch),u=this.segmentXf(a),c=s??u,l=e&&r-t<c,d=Math.max(0,this.crossfadeRegionLen-i),f=d/a,p=this.ctx.createBufferSource();p.buffer=this.buffer,p.loop=false,p.playbackRate.value=a;let h=this.ctx.createGain();st(h.gain,o,f,u,{fadeIn:l,fadeOut:f-(l?c:0)>u,fadeInSec:c}),p.connect(h).connect(this.gain);try{p.start(o,this.crossfadeRegionStart+i,d);}catch{}p.onended=()=>this.releaseCrossfadeSegment(p,h);let g={source:p,gain:h,startTime:o,offset:i,rate:a,xf:u};return this.crossfadeChain.push(g),g}armNextCrossfadeSegment(t){this.clearArmTimer();let e=t.startTime+(this.crossfadeRegionLen-t.offset)/t.rate-t.xf,s=Math.max(0,(e-this.ctx.currentTime)*1e3-50);this.crossfadeArmTimer=setTimeout(()=>{if(this.crossfadeArmTimer=null,this.done||this.stopping||this.paused)return;let r=null;try{r=this.spawnCrossfadeSegment(e,!0,0,t.xf),this.source=r.source;}finally{this.armNextCrossfadeSegment(r??{...t,startTime:e,offset:0,rate:Math.max(1e-4,this.basePitch)});}},s);}reseamCrossfade(t){let e=this.ctx.currentTime,i=this.computeOffset()-this.crossfadeRegionStart;this.clearArmTimer();let s=Math.min(me,this.crossfadeSec);for(let r of this.crossfadeChain){S(r.gain.gain,e,0,s,"linear");try{r.source.stop(e+s);}catch{}}this.basePitch=t,this.source=this.startCrossfadeChain(e,i,s);}releaseCrossfadeSegment(t,e){let i=this.crossfadeChain.findIndex(s=>s.source===t);i>=0&&this.crossfadeChain.splice(i,1),N(t),N(e);}get inCrossfadeMode(){return this.crossfadeSec>0}computeOffset(){if(this.paused)return this.pausedOffset;let t=this.ctx.currentTime;if(this.inCrossfadeMode){let a=null;for(let c of this.crossfadeChain)c.startTime<=t&&(!a||c.startTime>a.startTime)&&(a=c);if(!a)return this.crossfadeRegionStart+(this.crossfadeChain[0]?.offset??0);let u=a.offset+(t-a.startTime)*a.rate;return this.crossfadeRegionStart+Math.min(this.crossfadeRegionLen,Math.max(0,u))}let e=Math.max(0,t-this.startCtxTime)*this.basePitch,i=this.currentOffset+e;if(!this.loop)return Math.min(i,this.buffer.duration);let s=this.loopStart??0,r=this.loopEnd!=null&&this.loopEnd>s?this.loopEnd:this.buffer.duration,o=r-s;return o<=0||i<r?i:s+(i-s)%o}};function N(n){try{n.disconnect();}catch{}}function Gt(n,t=1){if(typeof n=="number")return n;if(!n)return t;let e=n.base??t;return n.jitter==null?e:e+(Math.random()*2-1)*n.jitter}function zt(n){return Number.isNaN(n)?0:Math.min(1,Math.max(0,n))}var Ct={reject:false,victim:null},R=class{config;voices=new Set;lastStart=Number.NEGATIVE_INFINITY;constructor(t={}){this.config={...t};}get current(){return this.config}set(t){this.config={...t??{}};}get count(){return this.voices.size}plan(t,e){let{cooldown:i=0,max:s,steal:r="oldest"}=this.config;return i>0&&t-this.lastStart<i?{reject:true,victim:null}:s==null?Ct:rt(this.voices,this.voices.size,s,r,e)}admit(t,e){this.voices.add(t),this.lastStart=Math.max(this.lastStart,e),t.ended.then(()=>this.voices.delete(t));}release(t){this.voices.delete(t);}},Y=class{name;deps;limit;constructor(t,e){this.name=t,this.deps=e,this.limit=e.limit??new R;}get duration(){return this.deps.buffer.duration}get buffer(){return this.deps.buffer}setLimit(t){this.limit.set(t);}get soundLimit(){return this.limit.current}play(t={}){let e=t.bus??this.deps.defaultBus,i=this.deps.resolveBusInput(e),s=this.deps.ctx,r=s.currentTime,o=t.at!=null&&Number.isFinite(t.at)&&t.at>r?t.at:r,a={priority:t.priority??0},u=this.limit.plan(o,a),c=u.reject?Ct:this.deps.planBus?.(e,a)??Ct;if(u.reject||c.reject)return new D({ctx:s,buffer:this.deps.buffer,destination:i,options:{...t,bus:e},sourceName:this.deps.sourceName??this.name,rejected:true,onEnded:()=>{}});for(let p of new Set([u.victim,c.victim]))p&&(p.stop(),p.bus&&this.deps.releaseVoice(p,p.bus),this.limit.release(p));let l=this.deps.resolveSpatializer?.(e,t.spatializer),d=l?l.connectInto(i):i,f=new D({ctx:s,buffer:this.deps.buffer,destination:d,options:{...t,bus:e},spatializer:l,sourceName:this.deps.sourceName??this.name,defaultStopFade:this.deps.defaultStopFade,onEnded:p=>{this.deps.releaseVoice(p,e),l?.dispose();}});if(this.deps.trackVoice(f,e),this.limit.admit(f,o),t.duck&&this.deps.resolveBus){let h=this.deps.resolveBus(t.duck.bus).duck(t.duck,f.startedAt);f.ended.then(h);}return f}};var X=class{name;regions;sound;constructor(t,e,i){this.name=t,this.sound=e,this.regions={...i},ge(t,this.regions,e.duration);}setLimit(t){this.sound.setLimit(t);}get duration(){return this.sound.duration}list(){return Object.keys(this.regions)}has(t){return t in this.regions}region(t){let e=this.regions[t];if(!e)throw new G(this.name,t,Object.keys(this.regions));return e}play(t,e={}){let i=this.region(t),s=e.loop??i.loop??false;return this.sound.play({...e,loop:s,offset:i.start,duration:i.duration,loopStart:i.start,loopEnd:i.start+i.duration})}};function ge(n,t,e){for(let[s,r]of Object.entries(t))if(!Number.isFinite(r.start)||!Number.isFinite(r.duration)||r.start<0||r.duration<=0||r.start+r.duration>e+.05)throw new RangeError(`Sprite "${n}" region "${s}" (start ${r.start}, duration ${r.duration}) does not fit the ${e.toFixed(3)} s buffer. Regions need start >= 0, duration > 0 and start + duration within the buffer.`)}var Z=class{name;ctx;urls;urlIndex=0;destination;el=null;node=null;gain=null;disposed=false;wantPlaying=false;resolveEnded=null;_ended=Promise.resolve();constructor(t,e,i,s){if(this.name=t,this.ctx=e,this.urls=typeof i=="string"?[i]:[...i],this.urls.length===0)throw new Error(`Stream "${t}" needs at least one URL`);this.destination=s;}get url(){return this.urls[this.urlIndex]}get ended(){return this._ended}ensure(){if(this.el||this.disposed||typeof document>"u"||typeof Audio>"u")return;let t=new Audio;t.src=this.url,t.crossOrigin="anonymous",t.preload="auto",t.addEventListener("ended",()=>this.settleEnded()),t.addEventListener("error",()=>this.handleError());let e=this.ctx.createMediaElementSource;if(typeof e!="function"){this.el=t;return}let i=e.call(this.ctx,t),s=this.ctx.createGain();i.connect(s),s.connect(this.destination),this.el=t,this.node=i,this.gain=s;}async play(t={}){if(this.ensure(),!this.el)return false;this.gain&&(this.gain.gain.value=wt(t.volume??1)),this.el.loop=t.loop??false,this.resolveEnded||(this._ended=new Promise(e=>{this.resolveEnded=e;})),this.wantPlaying=true;try{return await this.el.play(),!0}catch{return this.wantPlaying=false,false}}pause(){this.wantPlaying=false,this.el?.pause();}stop(){if(this.wantPlaying=false,this.settleEnded(),!!this.el){this.el.pause();try{this.el.currentTime=0;}catch{}}}seek(t){if(this.el)try{this.el.currentTime=Math.max(0,t);}catch{}}get currentTime(){return this.el?.currentTime??0}get duration(){return this.el?.duration??0}get paused(){return this.el?.paused??true}setVolume(t){this.gain&&(this.gain.gain.value=wt(t));}fade(t){return this.gain?(S(this.gain.gain,this.ctx.currentTime,wt(t.to),t.duration,t.curve??"linear"),A(this.ctx,t.duration)):Promise.resolve()}settleEnded(){let t=this.resolveEnded;this.resolveEnded=null,t?.();}handleError(){let t=this.el;if(!(!t||this.disposed)){if(this.urlIndex>=this.urls.length-1){this.wantPlaying=false,this.settleEnded();return}this.urlIndex++,t.src=this.url,this.wantPlaying&&t.play().catch(()=>{});}}dispose(){this.disposed=true,this.wantPlaying=false,this.settleEnded();try{this.node?.disconnect(),this.gain?.disconnect();}catch{}this.el&&(this.el.pause(),this.el.src=""),this.el=null,this.node=null,this.gain=null;}};function wt(n){return Number.isNaN(n)?0:Math.min(1,Math.max(0,n))}var K=class{name;count;sounds;strategy;weights;lastIndex=-1;bag=[];constructor(t,e,i={}){if(e.length===0)throw new Error(`Variants "${t}" requires at least one sound`);this.name=t,this.sounds=e,this.count=e.length,this.strategy=i.strategy??"no-repeat",this.weights=jt(i.weights,e.length);}setLimit(t){this.sounds[0].setLimit(t);}get soundLimit(){return this.sounds[0].soundLimit}setWeights(t){this.weights=jt(t??void 0,this.count),this.bag=[];}get lastPick(){return this.lastIndex}play(t={}){return this.sounds[this.pick()].play(t)}playIndex(t,e={}){let i=(t%this.count+this.count)%this.count;return this.lastIndex=i,this.sounds[i].play(e)}pick(){let t=this.choose();return this.lastIndex=t,t}choose(){let t=this.count;if(t===1)return 0;if(this.strategy==="random")return qt(this.weights,-1);if(this.strategy==="shuffle-bag"){if(this.bag.length===0){let e=[];for(let i=0;i<t;i++){let s=Math.round(this.weights[i]);for(let r=0;r<s;r++)e.push(i);}if(e.length===0)for(let i=0;i<t;i++)e.push(i);for(let i=e.length-1;i>0;i--){let s=Math.floor(Math.random()*(i+1));[e[i],e[s]]=[e[s],e[i]];}if(e.length>1&&e[0]===this.lastIndex){let i=e.findIndex(s=>s!==this.lastIndex);i>0&&([e[0],e[i]]=[e[i],e[0]]);}this.bag=e;}return this.bag.shift()}return qt(this.weights,this.lastIndex)}};function jt(n,t){let e=Array.from({length:t},(i,s)=>{let r=n?.[s];return r==null||!Number.isFinite(r)?1:Math.max(0,r)});return e.some(i=>i>0)?e:e.map(()=>1)}function qt(n,t){let e=0;for(let s=0;s<n.length;s++)s!==t&&(e+=n[s]);if(e<=0){let s=n.map((r,o)=>o).filter(r=>r!==t);return s[Math.floor(Math.random()*s.length)]??0}let i=Math.random()*e;for(let s=0;s<n.length;s++)if(s!==t&&(i-=n[s],i<0))return s;for(let s=n.length-1;s>=0;s--)if(s!==t&&n[s]>0)return s;return 0}var Q=class{ctx;glide;constructor(t,e=.02){this.ctx=t,this.glide=Math.max(0,e);}setGlide(t){this.glide=Math.max(0,t);}setPosition(t,e,i){let s=this.ctx.listener;if(s.positionX){let r=this.ctx.currentTime;m(s.positionX,t,r,this.glide),m(s.positionY,e,r,this.glide),m(s.positionZ,i,r,this.glide);return}s.setPosition?.(t,e,i);}setOrientation(t,e=[0,1,0]){let i=this.ctx.listener;if(i.forwardX){let s=this.ctx.currentTime;m(i.forwardX,t[0],s,this.glide),m(i.forwardY,t[1],s,this.glide),m(i.forwardZ,t[2],s,this.glide),m(i.upX,e[0],s,this.glide),m(i.upY,e[1],s,this.glide),m(i.upZ,e[2],s,this.glide);return}i.setOrientation?.(t[0],t[1],t[2],e[0],e[1],e[2]);}get position(){let t=this.ctx.listener;return [t.positionX?.value??0,t.positionY?.value??0,t.positionZ?.value??0]}};var be=1,ve=1e4,ye=1,Se="inverse",Mt=22050,xe=500,Te=.02,J=class{ctx;kind;glide;input;output;stereoPan=null;panner=null;occlusionFilter=null;occlusionGain=null;constructor(t,e){if(this.ctx=t,this.glide=Math.max(0,e.glide??Te),e.position){let i=t.createPanner();i.panningModel=e.panningModel??"HRTF",i.distanceModel=e.distanceModel??Se,i.refDistance=e.refDistance??be,i.maxDistance=e.maxDistance??ve,i.rolloffFactor=e.rolloffFactor??ye;let[s,r,o]=e.position;this.setPanner3D(i,s,r,o,0);let a=t.createBiquadFilter();a.type="lowpass",a.frequency.value=Mt,a.Q.value=Math.SQRT1_2;let u=t.createGain();u.gain.value=1,i.connect(a).connect(u),this.panner=i,this.occlusionFilter=a,this.occlusionGain=u,this.input=i,this.output=u,this.kind="3d",e.occlusion!=null&&this.applyOcclusion(e.occlusion,0);}else {let i=t.createStereoPanner();i.pan.value=Ut(e.pan??0),this.stereoPan=i,this.input=i,this.output=i,this.kind="2d";}}setPan(t){this.kind!=="2d"||!this.stereoPan||m(this.stereoPan.pan,Ut(t),this.ctx.currentTime,this.glide);}setPosition(t,e,i){this.kind!=="3d"||!this.panner||this.setPanner3D(this.panner,t,e,i,this.glide);}setGlide(t){this.glide=Math.max(0,t);}setPanningModel(t){this.panner&&(this.panner.panningModel=t);}setRefDistance(t){this.panner&&(this.panner.refDistance=Math.max(0,t));}setMaxDistance(t){this.panner&&(this.panner.maxDistance=Math.max(0,t));}setRolloffFactor(t){this.panner&&(this.panner.rolloffFactor=Math.max(0,t));}setDistanceModel(t){this.panner&&(this.panner.distanceModel=t);}setOcclusion(t){this.applyOcclusion(t,this.glide);}applyOcclusion(t,e){if(!this.occlusionFilter||!this.occlusionGain)return;let i=Ce(t),s=Mt*(xe/Mt)**i,r=this.ctx.currentTime;m(this.occlusionFilter.frequency,s,r,e);let o=10**(-6*i/20);m(this.occlusionGain.gain,o,r,e);}connectInto(t){return this.output.connect(t),this.input}dispose(){try{this.input.disconnect(),this.occlusionFilter?.disconnect(),this.occlusionGain?.disconnect();}catch{}}setPanner3D(t,e,i,s,r){if(typeof t.positionX?.setValueAtTime=="function"){let o=this.ctx.currentTime;m(t.positionX,e,o,r),m(t.positionY,i,o,r),m(t.positionZ,s,o,r);}else t.setPosition?.(e,i,s);}};function Ut(n){return Math.max(-1,Math.min(1,n))}function Ce(n){return Number.isNaN(n)?0:Math.max(0,Math.min(1,n))}var tt=class{input;fader;_volume;_muted;headroomDb;ctx;limiterNode=null;limiterCfg;destination;_meterAnalyser=null;_meterBuf=null;constructor(t,e={}){this.ctx=t,this.input=t.createGain(),this.headroomDb=e.headroom??0,this.input.gain.value=$t(this.headroomDb),this.fader=t.createGain(),this._volume=Pt(e.volume??1),this._muted=e.mute??false,this.fader.gain.value=this._muted?0:this._volume,this.input.connect(this.fader),this.destination=t.destination,this.limiterCfg=e.limiter??null,this.rewire();}get volume(){return this._volume}set volume(t){this._volume=Pt(t),this._muted||S(this.fader.gain,this.ctx.currentTime,this._volume,.01,"linear");}get muted(){return this._muted}set muted(t){this._muted!==t&&(this._muted=t,S(this.fader.gain,this.ctx.currentTime,t?0:this._volume,.01,"linear"));}fadeTo(t,e,i="linear"){return this._volume=Pt(t),this._muted?A(this.ctx,e):(S(this.fader.gain,this.ctx.currentTime,this._volume,e,i),A(this.ctx,e))}setHeadroom(t){this.headroomDb=t,S(this.input.gain,this.ctx.currentTime,$t(t),.01,"linear");}get headroom(){return this.headroomDb}setLimiter(t){this.limiterCfg=t,this.rewire();}get reduction(){return this.limiterNode?.reduction??0}meter(){if(!this._meterAnalyser){let s=this.ctx.createAnalyser();s.fftSize=1024,this.input.connect(s),this._meterAnalyser=s,this._meterBuf=new Float32Array(s.fftSize);}let t=this._meterBuf;this._meterAnalyser.getFloatTimeDomainData(t);let e=0,i=0;for(let s=0;s<t.length;s++){let r=t[s]??0;e+=r*r;let o=Math.abs(r);o>i&&(i=o);}return {rms:Math.sqrt(e/t.length),peak:i}}dispose(){for(let t of [this.input,this.fader,this.limiterNode,this._meterAnalyser])try{t?.disconnect();}catch{}this.limiterNode=null,this._meterAnalyser=null,this._meterBuf=null;}rewire(){try{this.fader.disconnect();}catch{}try{this.limiterNode?.disconnect();}catch{}if(this.limiterNode=null,this.limiterCfg){let t=this.limiterCfg,e=this.ctx.createDynamicsCompressor();e.threshold.value=t.threshold??-1,e.knee.value=0,e.ratio.value=Math.max(20,t.ratio??20),e.attack.value=t.attack??.001,e.release.value=t.release??.05,this.fader.connect(e),e.connect(this.destination),this.limiterNode=e;}else this.fader.connect(this.destination);}};function $t(n){return 10**(n/20)}function Pt(n){return Number.isNaN(n)?0:Math.min(1,Math.max(0,n))}var et=class{name;state;getBus;getParam;allBuses;constructor(t,e,i,s,r=()=>[]){this.name=t,this.state=e,this.getBus=i,this.getParam=s,this.allBuses=r;}findSend(t,e){return this.getBus(t)?.sends().find(i=>i.target.name===e)}applyDiscrete(){for(let[t,e]of Object.entries(this.state.fx??{})){let i=this.getBus(t)?.fx()??[];e.forEach((s,r)=>{let o=i[r];o&&(o.bypassed=s);});}if(this.state.solo){let t=new Set(this.state.solo);for(let e of this.allBuses())e.solo(t.has(e.name));}}apply(t={}){let e=t.fade??0,i=[];for(let[s,r]of Object.entries(this.state.buses)){let o=this.getBus(s);o&&(o.muted=r.muted,i.push(o.fadeTo(r.level,e)));}for(let[s,r]of Object.entries(this.state.parameters)){let o=this.getParam(s);o&&(e>0?i.push(o.rampTo(r,e)):o.set(r));}for(let[s,r]of Object.entries(this.state.sends??{}))for(let[o,a]of Object.entries(r)){let u=this.findSend(s,o);u&&i.push(u.fadeTo(a,e));}return this.applyDiscrete(),Promise.all(i).then(()=>{})}blendWith(t,e){let i=e<0?0:e>1?1:e,s=1-i;for(let[r,o]of Object.entries(this.state.buses)){let a=t.state.buses[r];if(!a)continue;let u=this.getBus(r);u&&(u.muted=i<.5?o.muted:a.muted,u.level=o.level*s+a.level*i);}for(let[r,o]of Object.entries(this.state.parameters)){let a=t.state.parameters[r];if(a===void 0)continue;let u=this.getParam(r);u&&u.set(o*s+a*i);}for(let[r,o]of Object.entries(this.state.sends??{})){let a=t.state.sends?.[r];if(a)for(let[u,c]of Object.entries(o)){let l=a[u];if(l===void 0)continue;let d=this.findSend(r,u);d&&(d.amount=c*s+l*i);}}(i<.5?this:t).applyDiscrete();}};function we(n={}){return new _t(n)}var _t=class{host;decoder;scheduler=null;_master=null;_listener=null;buses=new Map;busOrder=[];sounds=new Map;internalSounds=new Map;sprites=new Map;streams=new Map;musics=new Map;variantsByName=new Map;busGroups=new Map;soloedBuses=new Set;soundUrls=new Map;voices=new Map;parameters=new Map;config;constructor(t){this.config=t,this.host=new at({autoPauseOnHidden:t.autoPauseOnHidden,latencyHint:t.latencyHint}),this.decoder=new ut(()=>this.host.touch(),t.cache??{});let e=Object.keys(t.buses??{});this.busOrder=e.length>0?e:["default"];for(let i of this.busOrder)this.voices.set(i,new Set);}get state(){return this.host.state}get now(){return this.host.now}get context(){return this.host.touch()}get master(){return this.ensureGraph(),this._master}get listener(){return this._listener||(this._listener=new Q(this.host.touch())),this._listener}async unlock(){await this.host.unlock(),this.ensureGraph();}suspend(){return this.host.suspend()}async resume(){await this.host.resume(),this.ensureGraph();}async close(){if(this.host.state!=="closed"){for(let t of this.voices.values()){for(let e of t)e.stop();t.clear();}this.scheduler?.dispose(),this.scheduler=null;for(let t of this.buses.values()){for(let e of t.fx())e.dispose();t.dispose();}this.buses.clear(),this._master?.dispose(),this._master=null,this._listener=null,this.sounds.clear(),this.internalSounds.clear(),this.sprites.clear();for(let t of this.musics.values())t.stopAll({fade:0});this.musics.clear(),this.variantsByName.clear(),this.busGroups.clear(),this.soloedBuses.clear(),this.soundUrls.clear();for(let t of this.streams.values())t.dispose();this.streams.clear(),this.parameters.clear(),this.decoder.clear(),await this.host.close();}}async loadSound(t,e,i={}){let s=await this.loadBuffer({name:t,kind:"sound",url:e},i);return this.soundUrls.set(t,dt(e)),this.registerSound(t,t,s,{bus:i.bus,limit:ht(i)},false)}async loadBuffer(t,e){if(this.host.state==="closed")throw new x;this.host.touch(),this.ensureGraph();let i={signal:e.signal,onProgress:e.onProgress},s=await this.resolveBuffer(t,i);return e.normalize&&(s=I(s,e.normalize,this.host.touch())),s}async resolveBuffer(t,e){let{url:i}=t,s=this.config.resolveAsset;if(s){let o=await s({...t,signal:e.signal});if(o!=null){if(o instanceof AudioBuffer)return o;if(o instanceof ArrayBuffer)return await this.host.touch().decodeAudioData(o.slice(0));if(typeof o=="string")return await this.decoder.load(o,e)}}let r=typeof i=="string"?[i]:ot(i);return await this.decoder.loadFirst(r,e)}async preload(t,e={}){if(this.host.state==="closed")throw new x;if(t.length===0)return;let i=Math.max(1,e.concurrency??Ht),s=e.onProgress,r=e.signal,o=e.onBytes,a=t.length,u=0,c=[],l=0,d=Math.min(i,a),f=[];for(let g=0;g<d;g++)f.push((async()=>{for(;;){let v=l++;if(v>=a)return;if(r?.aborted)throw r.reason??new DOMException("preload aborted","AbortError");let b=t[v],y=Pe(r,b.options?.signal),M=b.options?.onProgress,_=o||M?(T,L)=>{M?.(T,L),o?.({name:b.name,loadedBytes:T,totalBytes:L});}:void 0;try{await this.loadPreloadItem(b,y.signal,_),u++,s?.({name:b.name,status:"loaded",completed:u,total:a});}catch(T){if(T.name==="AbortError")throw T;u++,c.push({name:b.name,cause:T}),s?.({name:b.name,status:"failed",error:T,completed:u,total:a});}finally{y.dispose();}}})());let h=(await Promise.allSettled(f)).find(g=>g.status==="rejected");if(h&&h.status==="rejected")throw h.reason;if(c.length>0)throw new z(c)}loadPreloadItem(t,e,i){switch(t.kind){case "sprite":return this.loadSprite(t.name,t.url,t.regions,{...t.options,signal:e,onProgress:i});case "variants":return this.loadVariants(t.name,t.urls,{...t.options,signal:e,onProgress:i});case "music":return this.loadMusic(t.name,t.parts,{...t.options,signal:e,onProgress:i});default:return this.loadSound(t.name,t.url,{...t.options,signal:e,onProgress:i})}}async loadSprite(t,e,i,s={}){let r=await this.loadBuffer({name:t,kind:"sprite",url:e},s),o=`__sprite:${t}`,a=this.registerSound(o,t,r,{bus:s.bus,limit:ht(s)},true),u;try{u=new X(t,a,i);}catch(c){throw this.internalSounds.delete(o),c}return this.soundUrls.set(o,dt(e)),this.sprites.set(t,u),u}sprite(t){let e=this.sprites.get(t);if(!e)throw new k(t,w(t,[...this.sprites.keys()]));return e}hasSprite(t){return this.sprites.has(t)}async loadVariants(t,e,i={}){if(e.length===0)throw new Error(`engine.loadVariants("${t}") requires at least one URL set`);let{strategy:s,weights:r,limit:o,...a}=i,u=await Me(e,Ht,(p,h)=>this.loadBuffer({name:t,kind:"variants",part:h,url:p},a)),c=this.variantsByName.get(t);c&&this.dropVariantParts(t,c.count);let l=ht(i)??new R,d=u.map((p,h)=>{let g=`__variant:${t}:${h}`;return this.soundUrls.set(g,dt(e[h])),this.registerSound(g,t,p,{bus:i.bus,limit:l},true)}),f=new K(t,d,{strategy:s,weights:r});return this.variantsByName.set(t,f),f}dropVariantParts(t,e){for(let i=0;i<e;i++)this.internalSounds.delete(`__variant:${t}:${i}`),this.soundUrls.delete(`__variant:${t}:${i}`);}variants(t){let e=this.variantsByName.get(t);if(!e)throw new k(t,w(t,[...this.variantsByName.keys()]));return e}hasVariants(t){return this.variantsByName.has(t)}async loadMusic(t,e,i={}){if(this.host.state==="closed")throw new x;this.host.touch(),this.ensureGraph();let s={signal:i.signal,onProgress:i.onProgress},r=(h,g)=>this.resolveBuffer({name:t,kind:"music",part:h,url:g},s),[o,a,u]=await Promise.all([r("loop",e.loop),e.intro?r("intro",e.intro):Promise.resolve(void 0),e.outro?r("outro",e.outro):Promise.resolve(void 0)]),c=this.host.touch(),l={intro:a?i.normalize?I(a,i.normalize,c):a:void 0,loop:i.normalize?I(o,i.normalize,c):o,outro:u?i.normalize?I(u,i.normalize,c):u:void 0},d=i.bus??this.busOrder[0],f=this.buses.get(d);if(!f)throw new P(d,w(d,[...this.buses.keys()]));let p=new W(t,{ctx:this.host.touch(),buffers:l,destination:f.input,loopCrossfade:i.loopCrossfade??0,defaultStopFade:this.config.voice?.stopFade,grid:i.bpm!=null&&i.bpm>0?{bpm:i.bpm,beatsPerBar:i.beatsPerBar,offset:i.gridOffset}:void 0});return this.musics.get(t)?.stopAll(),this.musics.set(t,p),this.soundUrls.set(`__music:${t}`,[e.intro,e.loop,e.outro].flatMap(h=>h?dt(h):[])),p}music(t){let e=this.musics.get(t);if(!e)throw new k(t,w(t,[...this.musics.keys()]));return e}hasMusic(t){return this.musics.has(t)}loadStream(t,e,i={}){if(this.host.state==="closed")throw new x;this.host.touch(),this.ensureGraph();let s=typeof e=="string"?[e]:ot(e),r=i.bus??this.busOrder[0],o=this.buses.get(r);if(!o)throw new P(r,w(r,[...this.buses.keys()]));let a=new Z(t,this.host.touch(),s,o.input);return this.streams.get(t)?.dispose(),this.streams.set(t,a),a}stream(t){let e=this.streams.get(t);if(!e)throw new k(t,w(t,[...this.streams.keys()]));return e}hasStream(t){return this.streams.has(t)}crossfade(t,e,i={}){let s=i.duration??1.5,r=i.curve??"equal-power",o=i.toVolume??1,u=this.sound(e).play({bus:i.bus,loop:i.loop??true,volume:0});u.fade({to:o,duration:s,curve:r}).catch(()=>{});let c=this.activeVoices().filter(l=>l!==u&&l.sourceName===t&&l.bus===u.bus);for(let l of c)l.fade({to:0,duration:s,curve:r}).then(()=>l.stop()).catch(()=>{});return u}createSound(t,e,i={}){return this.registerSound(t,t,e,{bus:i.bus,limit:ht(i)},false)}registerSound(t,e,i,s,r){if(this.host.state==="closed")throw new x;this.host.touch(),this.ensureGraph();let o=s.bus??this.busOrder[0];if(!this.buses.has(o))throw new P(o,w(o,[...this.buses.keys()]));let a=new Y(t,{ctx:this.host.touch(),buffer:i,defaultBus:o,sourceName:e,defaultStopFade:this.config.voice?.stopFade,resolveBusInput:u=>{let c=this.buses.get(u);if(!c)throw new P(u,w(u,[...this.buses.keys()]));return c.input},resolveSpatializer:(u,c)=>{if(c)return new J(this.host.touch(),c)},trackVoice:(u,c)=>{this.voices.get(c)?.add(u),this.buses.get(c)?.trackVoice(u);},releaseVoice:(u,c)=>{this.voices.get(c)?.delete(u),this.buses.get(c)?.releaseVoice(u);},planBus:(u,c)=>this.buses.get(u)?.planConcurrency(c)??{reject:false,victim:null},resolveBus:u=>this.bus(u),limit:s.limit});return (r?this.internalSounds:this.sounds).set(t,a),a}removeSound(t){this.sounds.delete(t);}unload(t,e={}){let i=e.evictBuffer??true,s=[];this.sounds.delete(t)&&s.push(t),this.sprites.delete(t)&&(this.internalSounds.delete(`__sprite:${t}`),s.push(`__sprite:${t}`));let r=this.variantsByName.get(t);if(r){this.variantsByName.delete(t);for(let u=0;u<r.count;u++)this.internalSounds.delete(`__variant:${t}:${u}`),s.push(`__variant:${t}:${u}`);}let o=this.musics.get(t);o&&(o.stopAll(),this.musics.delete(t),s.push(`__music:${t}`));let a=this.streams.get(t);a&&(a.dispose(),this.streams.delete(t));for(let u of s){let c=this.soundUrls.get(u);if(i&&c)for(let l of c)this.decoder.evict(l);this.soundUrls.delete(u);}}unloadSound(t,e={}){if(this.sounds.delete(t),e.evictBuffer??true){let i=this.soundUrls.get(t);if(i)for(let s of i)this.decoder.evict(s);}this.soundUrls.delete(t);}hasSound(t){return this.sounds.has(t)}sound(t){let e=this.sounds.get(t);if(!e)throw new k(t,w(t,[...this.sounds.keys()]));return e}bus(t){this.ensureGraph();let e=this.buses.get(t);if(!e)throw new P(t,w(t,[...this.buses.keys()]));return e}busGroup(t,e){if(e!=null){let s=new $(t,e);return this.busGroups.set(t,s),s}let i=this.busGroups.get(t);if(!i)throw new P(t,w(t,[...this.busGroups.keys()]));return i}masterMeter(){return this.master.meter()}scheduleAt(t,e){return this.host.touch(),this.ensureGraph(),this.scheduler.scheduleAt(t,e)}activeVoices(){let t=[];for(let e of this.voices.values())for(let i of e)t.push(i);return t}onStateChange(t){return this.host.onStateChange(t)}parameter(t,e=0){let i=this.parameters.get(t);return i||(i=new H(t,e),this.parameters.set(t,i)),i}captureSnapshot(t){this.ensureGraph();let e={},i={},s={},r=[];for(let[a,u]of this.buses){e[a]={level:u.level,muted:u.muted};let c=u.sends();c.length>0&&(i[a]=Object.fromEntries(c.map(d=>[d.target.name,d.amount])));let l=u.fx();l.length>0&&(s[a]=l.map(d=>d.bypassed)),u.soloed&&r.push(a);}let o={};for(let[a,u]of this.parameters)o[a]=u.value;return this.snapshot(t,{buses:e,parameters:o,sends:i,fx:s,solo:r})}snapshot(t,e){return new et(t,e,i=>this.buses.get(i),i=>this.parameters.get(i),()=>this.buses.values())}blendSnapshots(t,e,i){t.blendWith(e,i);}ensureGraph(){if(this._master)return;let t=this.host.touch(),e=new tt(t,this.config.master);this._master=e,this.scheduler=new ct(this.host,this.config.tickSource);for(let i of this.busOrder){let s=this.config.buses?.[i]??{},r=new U(t,i,s);r.output.connect(e.input),r.notifySoloChange=(o,a)=>this.handleSoloChange(o,a),this.buses.set(i,r),this.voices.has(i)||this.voices.set(i,new Set);}for(let i of this.busOrder){let s=this.config.buses?.[i]?.sidechain;if(!s)continue;let r=this.buses.get(s.from);if(!r||s.from===i)throw new P(s.from,w(s.from,[...this.buses.keys()].filter(o=>o!==i)));this.buses.get(i).addFx(new q(t,r,{amount:s.amount,attack:s.attack,release:s.release,threshold:s.threshold}));}}handleSoloChange(t,e){e?this.soloedBuses.add(t):this.soloedBuses.delete(t);let i=this.soloedBuses.size>0;for(let s of this.buses.values())i?s.applySoloVeil(!this.soloedBuses.has(s)):s.applySoloVeil(false);}},Ht=4;async function Me(n,t,e){let i=new Array(n.length),s=0,r=async()=>{for(;;){let a=s++;if(a>=n.length)return;i[a]=await e(n[a],a);}},o=Array.from({length:Math.min(t,n.length)},r);return await Promise.all(o),i}function w(n,t){if(t.length===0)return null;let e=null,i=1/0;for(let o of t){let a=_e(n,o);a<i&&(i=a,e=o);}let s=Math.max(n.length,e?.length??0),r=Math.max(1,Math.ceil(s/2));return e&&i<=r?e:null}function Pe(n,t){let e=()=>{};if(!n)return {signal:t,dispose:e};if(!t)return {signal:n,dispose:e};if(n.aborted)return {signal:n,dispose:e};if(t.aborted)return {signal:t,dispose:e};let i=new AbortController,s=()=>{n.removeEventListener("abort",r),t.removeEventListener("abort",o);},r=()=>{s(),i.abort(n.reason);},o=()=>{s(),i.abort(t.reason);};return n.addEventListener("abort",r),t.addEventListener("abort",o),{signal:i.signal,dispose:s}}function dt(n){return typeof n=="string"?[n]:[...n]}function ht(n){return n.limit?new R(n.limit):void 0}function _e(n,t){if(n===t)return 0;if(n.length===0)return t.length;if(t.length===0)return n.length;let e=new Array(t.length+1),i=new Array(t.length+1);for(let s=0;s<=t.length;s++)e[s]=s;for(let s=1;s<=n.length;s++){i[0]=s;for(let r=1;r<=t.length;r++){let o=n.charCodeAt(s-1)===t.charCodeAt(r-1)?0:1;i[r]=Math.min(i[r-1]+1,e[r]+1,e[r-1]+o);}for(let r=0;r<=t.length;r++)e[r]=i[r];}return e[t.length]}export{j as AggregateDecodeError,U as Bus,$ as BusGroup,P as BusNotFoundError,mt as Compressor,B as DecodeError,q as Ducker,x as EngineClosedError,gt as Filter,Q as Listener,tt as Master,W as Music,lt as MusicVoice,H as Parameter,z as PreloadError,bt as Reverb,nt as Send,et as Snapshot,Y as Sound,k as SoundNotFoundError,J as Spatializer,X as Sprite,G as SpriteRegionNotFoundError,Z as StreamSound,vt as StretchProcessor,K as Variants,D as Voice,O as ZvukError,I as applyLoudnessNormalization,xt as canPlay,Dt as computeNormalizationGain,we as createEngine,Kt as createStretchWorkletNode,Zt as ensureStretchWorklet,At as mimeForUrl,ee as pickSource,ot as pickSourceOrder};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@schmooky/zvuk",
3
- "version": "1.14.0",
3
+ "version": "2.0.0",
4
4
  "description": "Audio Engine for the Web — Wwise-grade routing, sprites, sidechain ducking. Tiny, ESM-only, type-safe.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -11,15 +11,18 @@
11
11
  "types": "./dist/index.d.ts",
12
12
  "import": "./dist/index.js",
13
13
  "default": "./dist/index.js"
14
- }
14
+ },
15
+ "./package.json": "./package.json"
15
16
  },
16
17
  "publishConfig": {
17
18
  "access": "public"
18
19
  },
19
20
  "files": [
20
- "dist",
21
+ "dist/*.js",
22
+ "dist/*.d.ts",
21
23
  "README.md",
22
- "LICENSE"
24
+ "LICENSE",
25
+ "MIGRATION.md"
23
26
  ],
24
27
  "sideEffects": false,
25
28
  "repository": {
@@ -50,6 +53,7 @@
50
53
  "node": ">=20"
51
54
  },
52
55
  "devDependencies": {
56
+ "@arethetypeswrong/cli": "0.18.5",
53
57
  "@biomejs/biome": "^2.3.0",
54
58
  "@changesets/changelog-github": "^0.5.0",
55
59
  "@changesets/cli": "^2.27.10",
@@ -59,12 +63,16 @@
59
63
  "@vitest/coverage-v8": "^2.1.9",
60
64
  "happy-dom": "^15.11.6",
61
65
  "playwright": "^1.62.1",
66
+ "publint": "0.3.12",
62
67
  "size-limit": "^13.0.3",
63
68
  "tsup": "^8.3.5",
64
69
  "typescript": "^5.9.0",
65
70
  "vite": "^5.4.0",
66
71
  "vitest": "^2.1.8"
67
72
  },
73
+ "bin": {
74
+ "zvuk": "./dist/cli.js"
75
+ },
68
76
  "scripts": {
69
77
  "build": "tsup",
70
78
  "dev": "tsup --watch",
@@ -85,9 +93,7 @@
85
93
  "changeset:status": "changeset status",
86
94
  "version-packages": "changeset version && pnpm install --lockfile-only",
87
95
  "release": "pnpm build && changeset publish",
88
- "snapshot": "pnpm build && changeset version --snapshot \"${SNAPSHOT_TAG:-snapshot}\" && changeset publish --tag \"${SNAPSHOT_TAG:-snapshot}\" --no-git-tag"
89
- },
90
- "bin": {
91
- "zvuk": "./dist/cli.js"
96
+ "snapshot": "pnpm build && node scripts/snapshot-pre-guard.mjs && changeset version --snapshot \"${SNAPSHOT_TAG:-snapshot}\" && changeset publish --tag \"${SNAPSHOT_TAG:-snapshot}\" --no-git-tag",
97
+ "check:package": "pnpm build && node scripts/check-package.mjs"
92
98
  }
93
99
  }
package/dist/cli.d.ts DELETED
@@ -1 +0,0 @@
1
- #!/usr/bin/env node
package/dist/cli.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/cli/gen.ts","../src/cli/transcode.ts","../src/cli/index.ts"],"names":["runGen","argv","args","parseArgs","raw","readFile","manifest","entries","normalize","out","render","writeFile","i","a","resolve","name","entry","defaultBus","names","e","lines","url","opts","runTranscode","mkdir","expanded","expandInputs","input","basename","extname","fmt","target","join","codecArgs","runFfmpeg","list","s","patterns","p","abs","matches","expandGlob","pattern","stat","dir","dirname","base","re","readdir","n","res","rej","proc","spawn","code","USAGE","main","cmd","rest"],"mappings":"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","file":"cli.js","sourcesContent":["import { readFile, writeFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\n\ninterface BankEntry {\n name: string;\n url: string | string[];\n bus?: string;\n loop?: boolean;\n}\n\ninterface BankManifest {\n /** Optional default bus that all entries fall back to. */\n defaultBus?: string;\n /** Sound entries — keyed by name or as an array. */\n sounds: BankEntry[] | Record<string, Omit<BankEntry, 'name'>>;\n}\n\n/**\n * Read a sound manifest JSON and emit a typed module:\n *\n * - the union of every sound name (`SoundName`)\n * - a `loadBank(engine)` function that calls `engine.loadSound` for each\n *\n * Drop the generated file into your repo and `engine.sound(\"coin\")` will be\n * autocompleted as a literal type.\n */\nexport async function runGen(argv: string[]): Promise<void> {\n const args = parseArgs(argv);\n const raw = await readFile(args.input, 'utf-8');\n const manifest: BankManifest = JSON.parse(raw);\n const entries = normalize(manifest);\n const out = render(entries, manifest.defaultBus);\n await writeFile(args.out, out, 'utf-8');\n process.stdout.write(`Wrote ${args.out} (${entries.length} entries).\\n`);\n}\n\ninterface ParsedArgs {\n input: string;\n out: string;\n}\n\nfunction parseArgs(argv: string[]): ParsedArgs {\n const out: ParsedArgs = { input: '', out: 'bank.gen.ts' };\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i]!;\n if (a === '--out') out.out = argv[++i] ?? out.out;\n else out.input = a;\n }\n if (!out.input) {\n process.stderr.write('Usage: zvuk gen <bank.json> [--out bank.gen.ts]\\n');\n process.exit(1);\n }\n out.input = resolve(out.input);\n out.out = resolve(out.out);\n return out;\n}\n\nfunction normalize(manifest: BankManifest): BankEntry[] {\n if (Array.isArray(manifest.sounds)) return manifest.sounds;\n return Object.entries(manifest.sounds).map(([name, entry]) => ({ name, ...entry }));\n}\n\nfunction render(entries: BankEntry[], defaultBus: string | undefined): string {\n const names = entries.map((e) => e.name);\n const lines: string[] = [];\n lines.push('// AUTOGENERATED by `zvuk gen`. Do not edit.');\n lines.push(\"import type { Engine, LoadSoundOptions } from '@schmooky/zvuk';\");\n lines.push('');\n lines.push('export type SoundName =');\n for (let i = 0; i < names.length; i++) {\n lines.push(` | ${JSON.stringify(names[i])}${i === names.length - 1 ? ';' : ''}`);\n }\n lines.push('');\n lines.push('export const BANK = [');\n for (const e of entries) {\n const url = JSON.stringify(e.url);\n const opts: string[] = [];\n if (e.bus) opts.push(`bus: ${JSON.stringify(e.bus)}`);\n if (e.loop) opts.push('loop: true');\n lines.push(\n ` { name: ${JSON.stringify(e.name)}, url: ${url}${opts.length ? `, options: { ${opts.join(', ')} }` : ''} },`,\n );\n }\n lines.push('] as const;');\n lines.push('');\n lines.push('export interface BankLoadOptions extends Omit<LoadSoundOptions, \"bus\"> {}');\n lines.push('');\n lines.push(\n 'export async function loadBank(engine: Engine, options: BankLoadOptions = {}): Promise<void> {',\n );\n lines.push(' await Promise.all(');\n lines.push(' BANK.map((entry) =>');\n if (defaultBus) {\n lines.push(\n ` engine.loadSound(entry.name, entry.url, { bus: ${JSON.stringify(defaultBus)}, ...entry.options, ...options }),`,\n );\n } else {\n lines.push(' engine.loadSound(entry.name, entry.url, { ...entry.options, ...options }),');\n }\n lines.push(' ),');\n lines.push(' );');\n lines.push('}');\n lines.push('');\n return lines.join('\\n');\n}\n","import { spawn } from 'node:child_process';\nimport { mkdir, readdir, stat } from 'node:fs/promises';\nimport { basename, dirname, extname, join, resolve } from 'node:path';\n\ninterface TranscodeArgs {\n inputs: string[];\n out: string;\n bitrate: string;\n formats: ('webm' | 'm4a')[];\n}\n\n/**\n * The asset-formats guide ffmpeg loop, packaged. For each input file produces:\n * <name>.webm (libopus) — small, plays everywhere except old iOS Safari.\n * <name>.m4a (aac) — fallback for the codec ladder.\n *\n * Requires ffmpeg on PATH. The CLI is a thin wrapper — we don't bundle ffmpeg.\n */\nexport async function runTranscode(argv: string[]): Promise<void> {\n const args = parseArgs(argv);\n await mkdir(args.out, { recursive: true });\n const expanded = await expandInputs(args.inputs);\n if (expanded.length === 0) {\n process.stderr.write('No input files matched.\\n');\n process.exit(1);\n }\n for (const input of expanded) {\n const name = basename(input, extname(input));\n for (const fmt of args.formats) {\n const target = join(args.out, `${name}.${fmt}`);\n const codecArgs =\n fmt === 'webm'\n ? ['-c:a', 'libopus', '-b:a', args.bitrate, '-vn']\n : ['-c:a', 'aac', '-b:a', args.bitrate, '-vn'];\n await runFfmpeg(['-y', '-i', input, ...codecArgs, target]);\n process.stdout.write(` → ${target}\\n`);\n }\n }\n}\n\nfunction parseArgs(argv: string[]): TranscodeArgs {\n const out: TranscodeArgs = {\n inputs: [],\n out: 'dist',\n bitrate: '96k',\n formats: ['webm', 'm4a'],\n };\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i]!;\n if (a === '--out') {\n out.out = argv[++i] ?? out.out;\n } else if (a === '--bitrate') {\n out.bitrate = argv[++i] ?? out.bitrate;\n } else if (a === '--formats') {\n const list = (argv[++i] ?? '').split(',').map((s) => s.trim());\n out.formats = list.filter((s): s is 'webm' | 'm4a' => s === 'webm' || s === 'm4a');\n } else {\n out.inputs.push(a);\n }\n }\n return out;\n}\n\nasync function expandInputs(patterns: string[]): Promise<string[]> {\n const out: string[] = [];\n for (const p of patterns) {\n const abs = resolve(p);\n const matches = await expandGlob(abs);\n out.push(...matches);\n }\n return out;\n}\n\n/**\n * Minimal glob expander — handles `dir/*.wav` and explicit files only.\n * Avoids pulling in a glob dependency for a tool that's mostly an ffmpeg loop.\n */\nasync function expandGlob(pattern: string): Promise<string[]> {\n if (!pattern.includes('*')) {\n try {\n const s = await stat(pattern);\n return s.isFile() ? [pattern] : [];\n } catch {\n return [];\n }\n }\n const dir = dirname(pattern);\n const base = basename(pattern);\n const re = new RegExp(`^${base.replace(/\\./g, '\\\\.').replace(/\\*/g, '.*')}$`);\n try {\n const entries = await readdir(dir);\n return entries.filter((n) => re.test(n)).map((n) => join(dir, n));\n } catch {\n return [];\n }\n}\n\nfunction runFfmpeg(args: string[]): Promise<void> {\n return new Promise((res, rej) => {\n const proc = spawn('ffmpeg', args, { stdio: ['ignore', 'inherit', 'inherit'] });\n proc.on('error', rej);\n proc.on('exit', (code) => {\n if (code === 0) res();\n else rej(new Error(`ffmpeg exited with code ${code}`));\n });\n });\n}\n","#!/usr/bin/env node\nimport { runGen } from './gen';\nimport { runTranscode } from './transcode';\n\nconst USAGE = `zvuk — audio engine CLI\n\nUsage:\n zvuk transcode <glob> Run the standard ffmpeg ladder (webm/opus + m4a/aac) on each input.\n zvuk gen <bank.json> Emit a typed sound-name module from a manifest.\n\nOptions for \"transcode\":\n --out <dir> Output directory (default: dist).\n --bitrate <kbps> Audio bitrate, e.g. \"96k\" (default: 96k).\n --formats <list> Comma-separated formats: webm, m4a (default: webm,m4a).\n\nOptions for \"gen\":\n --out <file> Output .ts module path (default: bank.gen.ts).\n`;\n\nasync function main(): Promise<void> {\n const [, , cmd, ...rest] = process.argv;\n switch (cmd) {\n case 'transcode': {\n await runTranscode(rest);\n return;\n }\n case 'gen': {\n await runGen(rest);\n return;\n }\n case '--help':\n case '-h':\n case undefined: {\n process.stdout.write(USAGE);\n return;\n }\n default: {\n process.stderr.write(`Unknown command: ${cmd}\\n\\n${USAGE}`);\n process.exit(1);\n }\n }\n}\n\nmain().catch((e) => {\n process.stderr.write(`${(e as Error).stack ?? (e as Error).message}\\n`);\n process.exit(1);\n});\n"]}