21 lines
115 KiB
JavaScript
21 lines
115 KiB
JavaScript
// @sendspin/sendspin-js 5.0.0 (Apache-2.0), bundled with audited noble MIT dependencies.
|
|
// Modification: optional opus-encdec decoder imports disabled; this build negotiates PCM only.
|
|
// See licenses/vendor and THIRD-PARTY-NOTICES. No source maps or remote imports.
|
|
var lr=Object.defineProperty;var ur=(e,A)=>()=>(e&&(A=e(e=0)),A);var dr=(e,A)=>{for(var t in A)lr(e,t,{get:A[t],enumerable:!0})};var fe={};dr(fe,{default:()=>fr});var fr,pe=ur(()=>{throw new Error("Optional Opus fallback is not distributed; negotiate PCM");fr=void 0});var GA=class{constructor(A,t){this.webCodecsDecoder=null,this.webCodecsDecoderReady=null,this.webCodecsFormat=null,this.useNativeOpus=!0,this.nativeDecoderQueue=[],this.opusDecoder=null,this.opusDecoderModule=null,this.opusDecoderReady=null,this.flacDecodingContext=null,this.flacDecodingContextSampleRate=0,this.flacDecodingContextChannels=0,this.onDecodedChunk=A,this.currentGeneration=t}async handleBinaryMessage(A,t,n){if(new Uint8Array(A)[0]===4){let r=new DataView(A,1,8),i=Number(r.getBigInt64(0,!1)),a=A.slice(9);if(t.codec==="opus"&&this.useNativeOpus&&(await this.initWebCodecsDecoder(t),this.useNativeOpus&&this.webCodecsDecoder&&this.queueToNativeOpusDecoder(a,i,n)))return;try{let o=await this.decode(a,t);o&&n===this.currentGeneration()&&this.onDecodedChunk({samples:o.samples,sampleRate:o.sampleRate,serverTimeUs:i,generation:n})}catch(o){console.error("Sendspin: Failed to decode audio buffer:",o)}}}async decode(A,t){return t.codec==="opus"?this.decodeOpusWithEncdec(A,t):t.codec==="flac"?this.decodeFLAC(A,t):t.codec==="pcm"?this.decodePCM(A,t):null}decodePCM(A,t){let n=t.bit_depth??16;if(n!==16&&n!==24&&n!==32)return console.warn(`Sendspin: unsupported PCM bit_depth ${n}`),null;let s=n/8,r=new DataView(A),i=A.byteLength/(s*t.channels),a=[];for(let o=0;o<t.channels;o++)a.push(new Float32Array(i));for(let o=0;o<t.channels;o++){let h=a[o];for(let l=0;l<i;l++){let u=(l*t.channels+o)*s,c=0;if(n===16)c=r.getInt16(u,!0)/32768;else if(n===24){let f=r.getUint8(u),d=r.getUint8(u+1),m=r.getUint8(u+2)<<16|d<<8|f;m&8388608&&(m|=4278190080),c=m/8388608}else n===32&&(c=r.getInt32(u,!0)/2147483648);h[l]=c}}return{samples:a,sampleRate:t.sample_rate}}getFlacDecodingContext(A,t){return(!this.flacDecodingContext||this.flacDecodingContextSampleRate!==A||this.flacDecodingContextChannels!==t)&&(this.flacDecodingContext=new OfflineAudioContext(t,1,A),this.flacDecodingContextSampleRate=A,this.flacDecodingContextChannels=t),this.flacDecodingContext}async decodeFLAC(A,t){try{let n=A;if(t.codec_header){let a=Uint8Array.from(atob(t.codec_header),h=>h.charCodeAt(0)),o=new Uint8Array(a.length+A.byteLength);o.set(a,0),o.set(new Uint8Array(A),a.length),n=o.buffer}let r=await this.getFlacDecodingContext(t.sample_rate,t.channels).decodeAudioData(n),i=[];for(let a=0;a<r.numberOfChannels;a++)i.push(new Float32Array(r.getChannelData(a)));return{samples:i,sampleRate:r.sampleRate}}catch(n){return console.error("Error decoding FLAC data:",n),null}}async initWebCodecsDecoder(A){let t=()=>{if(!this.webCodecsDecoder)return!1;let n=!!this.webCodecsFormat&&this.webCodecsFormat.sample_rate===A.sample_rate&&this.webCodecsFormat.channels===A.channels;if(this.webCodecsDecoder.state==="configured"&&n)return!0;if(this.webCodecsDecoder.state==="closed")return!1;try{return this.webCodecsDecoder.configure({codec:"opus",sampleRate:A.sample_rate,numberOfChannels:A.channels}),this.webCodecsFormat=A,!0}catch{return!1}};if(!t()){if(this.webCodecsDecoderReady){if(await this.webCodecsDecoderReady,t())return;try{this.webCodecsDecoder?.close()}catch{}this.webCodecsDecoder=null,this.webCodecsDecoderReady=null,this.webCodecsFormat=null}if(this.webCodecsDecoderReady){await this.webCodecsDecoderReady;return}this.webCodecsDecoderReady=this.createWebCodecsDecoder(A),await this.webCodecsDecoderReady}}async createWebCodecsDecoder(A){if(typeof AudioDecoder>"u"){this.useNativeOpus=!1;return}try{if(!(await AudioDecoder.isConfigSupported({codec:"opus",sampleRate:A.sample_rate,numberOfChannels:A.channels})).supported){console.log("[NativeOpus] WebCodecs Opus not supported, will use fallback"),this.useNativeOpus=!1;return}this.webCodecsDecoder=new AudioDecoder({output:n=>this.handleAudioData(n),error:n=>{console.error("[NativeOpus] WebCodecs decoder error:",n)}}),this.webCodecsDecoder.configure({codec:"opus",sampleRate:A.sample_rate,numberOfChannels:A.channels}),this.webCodecsFormat=A,console.log(`[NativeOpus] Using WebCodecs AudioDecoder: ${A.sample_rate}Hz, ${A.channels}ch`)}catch(t){console.warn("[NativeOpus] WebCodecs init failed, will use fallback:",t),this.useNativeOpus=!1}}handleAudioData(A){try{let t=Number(A.timestamp),n=this.nativeDecoderQueue.shift();if(!n){console.warn(`[NativeOpus] Dropping frame with empty decode queue (out ts=${t})`),A.close();return}let{serverTimeUs:s,generation:r}=n,i=this.webCodecsFormat;if(!i){A.close();return}if(r!==this.currentGeneration()){console.warn(`[NativeOpus] Dropping old-stream frame (ts=${s}, gen=${r} != current=${this.currentGeneration()})`),A.close();return}let a=A.numberOfChannels,o=A.numberOfFrames,h=A.format,l=[];for(let u=0;u<a;u++)l.push(new Float32Array(o));if(h==="f32-planar")for(let u=0;u<a;u++)A.copyTo(l[u],{planeIndex:u});else if(h==="s16-planar"){let u=new Int16Array(o);for(let c=0;c<a;c++){A.copyTo(u,{planeIndex:c});let f=l[c];for(let d=0;d<o;d++)f[d]=u[d]/32768}}else if(h==="f32"){let u=new Float32Array(o*a);A.copyTo(u,{planeIndex:0});for(let c=0;c<a;c++){let f=l[c];for(let d=0;d<o;d++)f[d]=u[d*a+c]}}else if(h==="s16"){let u=new Int16Array(o*a);A.copyTo(u,{planeIndex:0});for(let c=0;c<a;c++){let f=l[c];for(let d=0;d<o;d++)f[d]=u[d*a+c]/32768}}else{console.warn(`[NativeOpus] Unsupported AudioData format: ${h}`),A.close();return}A.close(),this.onDecodedChunk({samples:l,sampleRate:i.sample_rate,serverTimeUs:s,generation:r})}catch(t){console.error("[NativeOpus] Error in output callback:",t),A.close()}}queueToNativeOpusDecoder(A,t,n){if(!this.webCodecsDecoder||this.webCodecsDecoder.state!=="configured")return!1;try{this.nativeDecoderQueue.push({serverTimeUs:t,generation:n});let s=new EncodedAudioChunk({type:"key",timestamp:t,data:A});return this.webCodecsDecoder.decode(s),!0}catch(s){return this.nativeDecoderQueue.length>0&&this.nativeDecoderQueue.pop(),console.error("[NativeOpus] WebCodecs queue error:",s),!1}}resolveOpusDecoderModule(A){let t=A?.default,n=A?.["module.exports"],s=t??n??A;if(!s||typeof s!="object")throw new Error("[Opus] Invalid libopus decoder module export");return s}resolveOggOpusDecoderClass(A){let t=A?.default,n=A?.["module.exports"],s=t??n??A,r=s?.OggOpusDecoder??s;if(typeof r!="function")throw new Error("[Opus] OggOpusDecoder class export not found");return r}async waitForOpusReady(A){if(!A.isReady){if(Object.isExtensible(A)){await new Promise(t=>{A.onready=()=>t()});return}for(;!A.isReady;)await new Promise(t=>setTimeout(t,20))}}async initOpusEncdecDecoder(A){if(this.opusDecoderReady){await this.opusDecoderReady;return}this.opusDecoderReady=(async()=>{console.log("[Opus] Initializing decoder (opus-encdec)...");let[t,n]=await Promise.all([Promise.resolve().then(()=>(pe(),fe)),Promise.resolve().then(()=>(pe(),fe))]);this.opusDecoderModule=this.resolveOpusDecoderModule(t);let s=this.resolveOggOpusDecoderClass(n);await this.waitForOpusReady(this.opusDecoderModule),this.opusDecoder=new s({rawOpus:!0,decoderSampleRate:A.sample_rate,outputBufferSampleRate:A.sample_rate,numberOfChannels:A.channels},this.opusDecoderModule),await this.waitForOpusReady(this.opusDecoder),console.log("[Opus] Decoder ready")})(),await this.opusDecoderReady}async decodeOpusWithEncdec(A,t){try{await this.initOpusEncdecDecoder(t);let n=new Uint8Array(A),s=[];if(this.opusDecoder.decodeRaw(n,o=>{s.push(new Float32Array(o))}),s.length===0)return console.warn("[Opus] Fallback decoder produced no samples"),null;let r=s[0],i=r.length/t.channels,a=[];for(let o=0;o<t.channels;o++){let h=new Float32Array(i);for(let l=0;l<i;l++)h[l]=r[l*t.channels+o];a.push(h)}return{samples:a,sampleRate:t.sample_rate}}catch(n){return console.error("[Opus] Decode error:",n),null}}clearState(){this.nativeDecoderQueue=[];try{this.webCodecsDecoder?.close()}catch{}this.webCodecsDecoder=null,this.webCodecsDecoderReady=null,this.webCodecsFormat=null}close(){this.clearState(),this.opusDecoder&&(this.opusDecoder=null,this.opusDecoderModule=null,this.opusDecoderReady=null),this.useNativeOpus=!0,this.flacDecodingContext=null,this.flacDecodingContextSampleRate=0,this.flacDecodingContextChannels=0}};var vt=class{constructor(A,t,n){this.sender=A,this.stateManager=t,this.timeFilter=n,this.timeSyncBurstActive=!1,this.timeSyncBurstSentCount=0,this.timeSyncInFlightClientTransmitted=null,this.timeSyncInFlightTimeout=null,this.timeSyncBurstSamples=[]}startAndSchedule(){this.stop(),this.startTimeSyncBurstIfIdle(),this.scheduleNextTimeSyncBurstTick()}scheduleNextTimeSyncBurstTick(){let A=globalThis.setTimeout(()=>{this.startTimeSyncBurstIfIdle(),this.scheduleNextTimeSyncBurstTick()},1e4);this.stateManager.setTimeSyncInterval(A)}startTimeSyncBurstIfIdle(){this.timeSyncBurstActive||(this.timeSyncBurstActive=!0,this.timeSyncBurstSentCount=0,this.timeSyncBurstSamples=[],this.timeSyncInFlightClientTransmitted=null,this.sendNextTimeSyncBurstProbe())}sendNextTimeSyncBurstProbe(){if(!this.timeSyncBurstActive||this.timeSyncInFlightClientTransmitted!==null)return;if(this.timeSyncBurstSentCount>=8){this.finalizeTimeSyncBurst();return}let A=this.sendTimeSync();this.timeSyncBurstSentCount+=1,this.timeSyncInFlightClientTransmitted=A,this.armTimeSyncProbeTimeout(A)}armTimeSyncProbeTimeout(A){this.clearTimeSyncProbeTimeout(),this.timeSyncInFlightTimeout=globalThis.setTimeout(()=>{this.handleTimeSyncProbeTimeout(A)},2e3)}clearTimeSyncProbeTimeout(){this.timeSyncInFlightTimeout!==null&&(clearTimeout(this.timeSyncInFlightTimeout),this.timeSyncInFlightTimeout=null)}handleTimeSyncProbeTimeout(A){!this.timeSyncBurstActive||this.timeSyncInFlightClientTransmitted!==A||(console.warn("Sendspin: Time sync probe timed out, aborting current burst"),this.abortTimeSyncBurst())}finalizeTimeSyncBurst(){this.clearTimeSyncProbeTimeout();let A=this.selectTimeSyncBurstCandidate();A&&this.timeFilter.update(A.measurement,A.maxError,A.t4),this.timeSyncBurstActive=!1,this.timeSyncBurstSentCount=0,this.timeSyncInFlightClientTransmitted=null,this.timeSyncBurstSamples=[]}selectTimeSyncBurstCandidate(){if(this.timeSyncBurstSamples.length===0)return null;let t=[...[...this.timeSyncBurstSamples].sort((n,s)=>n.rttTerm-s.rttTerm).slice(0,Math.min(3,this.timeSyncBurstSamples.length))].sort((n,s)=>n.measurement-s.measurement);return t[Math.floor(t.length/2)]}abortTimeSyncBurst(){this.clearTimeSyncProbeTimeout(),this.timeSyncBurstActive=!1,this.timeSyncBurstSentCount=0,this.timeSyncInFlightClientTransmitted=null,this.timeSyncBurstSamples=[]}stop(){this.stateManager.clearTimeSyncInterval(),this.abortTimeSyncBurst()}handleServerTime(A){if(!this.timeSyncBurstActive||this.timeSyncInFlightClientTransmitted===null)return;let t=A.payload.client_transmitted;if(t!==this.timeSyncInFlightClientTransmitted){console.warn("Sendspin: Ignoring out-of-order time response",t,this.timeSyncInFlightClientTransmitted);return}let n=Math.floor(performance.now()*1e3),s=A.payload.server_received,r=A.payload.server_transmitted,i=(s-t+(r-n))/2,a=Math.max(0,n-t-(r-s)),o=Math.max(1e3,a/2);if(this.timeSyncBurstSamples.push({measurement:i,maxError:o,t4:n,rttTerm:a}),this.clearTimeSyncProbeTimeout(),this.timeSyncInFlightClientTransmitted=null,this.timeSyncBurstSentCount>=8){this.finalizeTimeSyncBurst();return}this.sendNextTimeSyncBurstProbe()}sendTimeSync(A=Math.floor(performance.now()*1e3)){let t={type:"client/time",payload:{client_transmitted:A}};return this.sender.sendControl(t),A}};function pr(){let e=typeof navigator<"u"?navigator.userAgent:"",A=/^((?!chrome|android).)*safari/i.test(e),t=/firefox/i.test(e),n=typeof AudioDecoder<"u";return n||(typeof window<"u"&&!window.isSecureContext?console.warn("[Opus] Running in insecure context, falling back to FLAC/PCM"):console.warn("[Opus] Native decoder not available, falling back to FLAC/PCM")),A?new Set(["pcm","opus"]):t?new Set(["pcm","flac"]):n?new Set(["pcm","opus","flac"]):new Set(["pcm","flac"])}function It(e){let A=pr(),t=[];for(let n of e)A.has(n)&&(n==="opus"?t.push({codec:"opus",sample_rate:48e3,channels:2,bit_depth:16}):(t.push({codec:n,sample_rate:48e3,channels:2,bit_depth:16}),t.push({codec:n,sample_rate:44100,channels:2,bit_depth:16})));if(t.length===0)throw new Error(`No supported codecs: requested [${e.join(", ")}], browser supports [${[...A].join(", ")}]`);return t}function mr(e){let A=e.sample_rate*e.channels*Math.ceil(e.bit_depth/8);switch(e.codec){case"opus":return 64e3;case"flac":return A*1.02;default:return A}}function gn(e){let A=Math.max(...e.map(mr));return Math.ceil(A*30)}function gA(e){return isFinite(e)?Math.max(0,Math.min(5e3,Math.round(e))):0}var yn=5e3,gr=250,yr=250;function Jt(e,A){if(!isFinite(e)||e<0)throw new RangeError(`${A} must be a non-negative finite number`)}var Bt=class{constructor(A,t,n,s,r,i={}){this.sender=A,this.helloContext=t,this.streamHandler=n,this.stateManager=s,this.timeFilter=r,this.activated=!1,this.activeRoles=null,this.pairingSuspended=!1,this.lastSentPlayer=null,this.clientName=i.clientName??"Sendspin Player",this.productName=i.productName,this.codecs=i.codecs??["opus","flac","pcm"],this.bufferCapacity=i.bufferCapacity,this.requiredLeadTimeMs=i.requiredLeadTimeMs??gr,Jt(this.requiredLeadTimeMs,"requiredLeadTimeMs"),this.minBufferMs=i.minBufferMs??yr,Jt(this.minBufferMs,"minBufferMs"),this.useHardwareVolume=i.useHardwareVolume??!1,this.onVolumeCommand=i.onVolumeCommand,this.onDelayCommand=i.onDelayCommand,this.getExternalVolume=i.getExternalVolume,this.timeSyncManager=new vt(A,s,r)}handleServerMessage(A){switch(A.type){case"server/hello":this.handleServerHello();break;case"server/activate":this.handleServerActivate(A);break;case"server/time":this.timeSyncManager.handleServerTime(A);break;case"stream/start":this.handleStreamStart(A);break;case"stream/clear":this.handleStreamClear(A);break;case"stream/end":this.handleStreamEnd(A);break;case"server/command":this.handleServerCommand(A);break;case"server/state":this.stateManager.updateServerState(A.payload);break;case"group/update":this.stateManager.updateGroupState(A.payload);break}}handleServerHello(){console.log("Sendspin: Connected to server"),this.sendClientHello()}handleServerActivate(A){this.pairingSuspended=!1;let t=!1;if(A.payload.active_roles!==void 0){let s=new Set(A.payload.active_roles);t=this.activeRoles===null||s.size!==this.activeRoles.size||[...s].some(r=>!this.activeRoles.has(r)),this.activeRoles=s}if(this.activated){t&&this.sendStateUpdate();return}this.activated=!0,this.sendStateUpdate(),this.timeSyncManager.startAndSchedule();let n=globalThis.setInterval(()=>this.sendStateUpdate(),yn);this.stateManager.setStateUpdateInterval(n)}restartStateUpdateInterval(){let A=globalThis.setInterval(()=>this.sendStateUpdate(),yn);this.stateManager.setStateUpdateInterval(A)}stopTimeSync(){this.timeSyncManager.stop()}suspendForPairing(){this.pairingSuspended=!0,this.activated=!1,this.activeRoles=new Set,this.timeSyncManager.stop(),this.stateManager.clearStateUpdateInterval()}resetActivation(A=!1){this.pairingSuspended=!1,this.activated=!1,A||(this.activeRoles=null),this.timeSyncManager.stop(),this.stateManager.clearStateUpdateInterval()}handleStreamStart(A){let t=this.stateManager.currentStreamFormat!==null;this.stateManager.currentStreamFormat=A.payload.player,console.log(t?"Sendspin: Stream format updated":"Sendspin: Stream started",this.stateManager.currentStreamFormat),console.log(`Sendspin: Codec=${this.stateManager.currentStreamFormat.codec.toUpperCase()}, SampleRate=${this.stateManager.currentStreamFormat.sample_rate}Hz, Channels=${this.stateManager.currentStreamFormat.channels}, BitDepth=${this.stateManager.currentStreamFormat.bit_depth}bit`),this.streamHandler.handleStreamStart(this.stateManager.currentStreamFormat,t),this.stateManager.isPlaying=!0,typeof navigator<"u"&&navigator.mediaSession&&(navigator.mediaSession.playbackState="playing")}handleStreamClear(A){let t=A.payload.roles;(!t||t.includes("player"))&&(console.log("Sendspin: Stream clear (seek)"),this.streamHandler.handleStreamClear())}handleStreamEnd(A){let t=A.payload?.roles;(!t||t.includes("player"))&&(console.log("Sendspin: Stream ended"),this.streamHandler.handleStreamEnd(),this.stateManager.currentStreamFormat=null,this.stateManager.isPlaying=!1,typeof navigator<"u"&&navigator.mediaSession&&(navigator.mediaSession.playbackState="paused"),this.sendStateUpdate())}handleServerCommand(A){let t=A.payload.player;if(t){switch(t.command){case"volume":t.volume!==void 0&&(this.stateManager.volume=t.volume,this.streamHandler.handleVolumeUpdate(),this.useHardwareVolume&&this.onVolumeCommand&&this.onVolumeCommand(t.volume,this.stateManager.muted));break;case"mute":t.mute!==void 0&&(this.stateManager.muted=t.mute,this.streamHandler.handleVolumeUpdate(),this.useHardwareVolume&&this.onVolumeCommand&&this.onVolumeCommand(this.stateManager.volume,t.mute));break;case"set_static_delay":{let n=t.static_delay_ms;if(typeof n=="number"&&isFinite(n)){let s=gA(n);this.streamHandler.handleSyncDelayChange(s),this.onDelayCommand?.(s)}break}}this.restartStateUpdateInterval(),this.sendStateUpdate(!0)}}sendClientHello(){let A=It(this.codecs),t={type:"client/hello",payload:{name:this.clientName,supported_roles:["player@v1","controller@v1","metadata@v1"],trust_level:this.helloContext.trustLevel(),supported_pair_methods:this.helloContext.pairMethods(),unpaired_access:{enabled:this.helloContext.unpairedAccess},device_info:{product_name:this.productName,manufacturer:typeof navigator<"u"&&navigator.vendor||"Unknown",software_version:typeof navigator<"u"&&navigator.userAgent||"Unknown"},"player@v1_support":{supported_formats:A,buffer_capacity:this.bufferCapacity??gn(A),supported_commands:["volume","mute"]}}};this.lastSentPlayer=null,this.sender.sendControl(t)}setRequiredLeadTimeMs(A){Jt(A,"requiredLeadTimeMs"),this.requiredLeadTimeMs=A,this.sendStateUpdate()}setMinBufferMs(A){Jt(A,"minBufferMs"),this.minBufferMs=A,this.sendStateUpdate()}sendStateUpdate(A=!1){if(this.pairingSuspended)return;let t=this.stateManager.volume,n=this.stateManager.muted;if(!A&&this.useHardwareVolume&&this.getExternalVolume){let o=this.getExternalVolume();t=o.volume,n=o.muted}let s=this.streamHandler.getSyncDelayMs(),r=gA(s),i={available:!0};if(this.activeRoles===null||this.activeRoles.has("player@v1")){let o={volume:t,muted:n,static_delay_ms:r,required_lead_time_ms:this.requiredLeadTimeMs,min_buffer_ms:this.minBufferMs},h=this.lastSentPlayer;if(h===null)i.player={...o,supported_commands:["set_static_delay"]};else{let l={};o.static_delay_ms!==h.static_delay_ms&&(l.static_delay_ms=o.static_delay_ms),o.volume!==h.volume&&(l.volume=o.volume),o.muted!==h.muted&&(l.muted=o.muted),o.required_lead_time_ms!==h.required_lead_time_ms&&(l.required_lead_time_ms=o.required_lead_time_ms),o.min_buffer_ms!==h.min_buffer_ms&&(l.min_buffer_ms=o.min_buffer_ms),i.player=l}this.lastSentPlayer=o}let a={type:"client/state",payload:i};this.sender.sendControl(a)}sendGoodbye(A){this.sender.sendControl({type:"client/goodbye",payload:{reason:A}})}sendCommand(A,t){this.pairingSuspended||!this.activeRoles?.has("controller@v1")||this.sender.sendControl({type:"client/command",payload:{controller:{command:A,...t}}})}};function me(e,A){let t={...e};for(let n of Object.keys(A)){let s=A[n];if(s===null)delete t[n];else if(s!==void 0){let r=t[n];typeof s=="object"&&!Array.isArray(s)&&typeof r=="object"&&r!==null&&!Array.isArray(r)?t[n]=me(r,s):t[n]=s}}return t}var Pt=class{constructor(A){this._volume=100,this._muted=!1,this._playerState="synchronized",this._isPlaying=!1,this._currentStreamFormat=null,this._streamStartServerTime=0,this._streamStartAudioTime=0,this._streamGeneration=0,this._serverState={},this._groupState={},this.timeSyncInterval=null,this.stateUpdateInterval=null,this.onStateChangeCallback=A}get volume(){return this._volume}set volume(A){this._volume=Math.max(0,Math.min(100,A)),this.notifyStateChange()}get muted(){return this._muted}set muted(A){this._muted=A,this.notifyStateChange()}get playerState(){return this._playerState}set playerState(A){this._playerState=A,this.notifyStateChange()}get isPlaying(){return this._isPlaying}set isPlaying(A){this._isPlaying=A,this.notifyStateChange()}get currentStreamFormat(){return this._currentStreamFormat}set currentStreamFormat(A){this._currentStreamFormat=A}get streamStartServerTime(){return this._streamStartServerTime}set streamStartServerTime(A){this._streamStartServerTime=A}get streamStartAudioTime(){return this._streamStartAudioTime}set streamStartAudioTime(A){this._streamStartAudioTime=A}resetStreamAnchors(){this._streamStartServerTime=0,this._streamStartAudioTime=0,this._streamGeneration++}get streamGeneration(){return this._streamGeneration}setTimeSyncInterval(A){this.clearTimeSyncInterval(),this.timeSyncInterval=A}clearTimeSyncInterval(){this.timeSyncInterval!==null&&(clearTimeout(this.timeSyncInterval),this.timeSyncInterval=null)}setStateUpdateInterval(A){this.clearStateUpdateInterval(),this.stateUpdateInterval=A}clearStateUpdateInterval(){this.stateUpdateInterval!==null&&(clearInterval(this.stateUpdateInterval),this.stateUpdateInterval=null)}clearAllIntervals(){this.clearTimeSyncInterval(),this.clearStateUpdateInterval()}reset(){this._volume=100,this._muted=!1,this._playerState="synchronized",this._isPlaying=!1,this._currentStreamFormat=null,this._streamStartServerTime=0,this._streamStartAudioTime=0,this._serverState={},this._groupState={},this.clearAllIntervals()}notifyStateChange(){this.onStateChangeCallback&&this.onStateChangeCallback({isPlaying:this._isPlaying,volume:this._volume,muted:this._muted,playerState:this._playerState,serverState:this._serverState,groupState:this._groupState})}updateServerState(A){this._serverState=me(this._serverState,A),this.notifyStateChange()}updateGroupState(A){this._groupState=me(this._groupState,A),this.notifyStateChange()}get serverState(){return this._serverState}get groupState(){return this._groupState}};var Rt=class{constructor(A){this.ws=null,this.reconnectTimeout=null,this.shouldReconnect=!1,this.isReconnecting=!1,this.reconnectAttempt=0,this.baseDelayMs=Math.max(0,A?.baseDelayMs??1e3),this.maxDelayMs=Math.max(this.baseDelayMs,A?.maxDelayMs??15e3),this.maxAttempts=A?.maxAttempts===void 0?1/0:Math.max(0,A.maxAttempts),this.onReconnecting=A?.onReconnecting,this.onReconnected=A?.onReconnected,this.onExhausted=A?.onExhausted}adopt(A,t,n,s,r){if(A.readyState!==WebSocket.OPEN&&A.readyState!==WebSocket.CONNECTING)throw new Error(`Sendspin: Cannot adopt WebSocket in readyState ${A.readyState} (must be OPEN or CONNECTING)`);if(this.onOpenHandler=t,this.onMessageHandler=n,this.onErrorHandler=s,this.onCloseHandler=r,this.ws){let i=this.ws;i.onopen=null,i.onmessage=null,i.onerror=null,i.onclose=null,i.close(),this.ws=null}return this.ws=A,this.ws.binaryType="arraybuffer",this.shouldReconnect=!1,this.clearReconnectState(),this.ws.onmessage=i=>{this.onMessageHandler&&this.onMessageHandler(i)},this.ws.onerror=i=>{console.error("Sendspin: WebSocket error",i),this.onErrorHandler&&this.onErrorHandler(i)},this.ws.onclose=()=>{console.log("Sendspin: WebSocket disconnected"),this.onCloseHandler&&this.onCloseHandler()},new Promise((i,a)=>{let o=()=>{this.onOpenHandler&&this.onOpenHandler(),i()};if(A.readyState===WebSocket.OPEN){console.log("Sendspin: Adopted open WebSocket"),o();return}let h=this.ws.onclose;this.ws.onopen=()=>{console.log("Sendspin: Adopted WebSocket connected"),o()},this.ws.onclose=l=>{h&&h.call(this.ws,l),a(new Error("Sendspin: Adopted WebSocket closed before opening"))}})}async connect(A,t,n,s,r){if(this.onOpenHandler=t,this.onMessageHandler=n,this.onErrorHandler=s,this.onCloseHandler=r,this.shouldReconnect=!1,this.clearReconnectState(),this.ws){let i=this.ws;i.onopen=null,i.onmessage=null,i.onerror=null,i.onclose=null,i.close(),this.ws=null}return this.openSocket(A)}openSocket(A){return new Promise((t,n)=>{try{console.log("Sendspin: Connecting to",A),this.ws=new WebSocket(A),this.ws.binaryType="arraybuffer",this.shouldReconnect=!0;let s=!1;this.ws.onopen=()=>{console.log("Sendspin: WebSocket connected"),s=!0;let r=this.isReconnecting;this.isReconnecting=!1,this.reconnectAttempt=0,this.onOpenHandler&&this.onOpenHandler(),r&&this.onReconnected?.(),t()},this.ws.onmessage=r=>{this.onMessageHandler&&this.onMessageHandler(r)},this.ws.onerror=r=>{console.error("Sendspin: WebSocket error",r),this.onErrorHandler&&this.onErrorHandler(r),n(r)},this.ws.onclose=()=>{console.log("Sendspin: WebSocket disconnected"),s&&this.onCloseHandler&&this.onCloseHandler(),this.shouldReconnect&&this.scheduleReconnect(A)}}catch(s){console.error("Sendspin: Failed to connect",s),n(s)}})}getReconnectDelayMs(A){let t=this.baseDelayMs*2**(A-1);return Math.min(t,this.maxDelayMs)}scheduleReconnect(A){this.reconnectTimeout!==null&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null);let t=this.reconnectAttempt+1;if(t>this.maxAttempts){console.warn(`Sendspin: Reconnect exhausted after ${this.maxAttempts} attempt(s)`),this.shouldReconnect=!1,this.isReconnecting=!1,this.reconnectAttempt=0,this.onExhausted?.();return}this.reconnectAttempt=t,this.isReconnecting=!0;let n=this.getReconnectDelayMs(t);this.reconnectTimeout=globalThis.setTimeout(()=>{this.reconnectTimeout=null,this.shouldReconnect&&(this.onReconnecting?.(t),console.log(`Sendspin: Attempting to reconnect (attempt ${t}${this.maxAttempts===1/0?"":`/${this.maxAttempts}`})...`),this.openSocket(A).catch(s=>{console.error("Sendspin: Reconnection failed",s)}))},n)}clearReconnectState(){this.reconnectTimeout!==null&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.isReconnecting=!1,this.reconnectAttempt=0}disconnect(){this.shouldReconnect=!1,this.clearReconnectState(),this.ws&&(this.ws.close(),this.ws=null)}sendText(A){this.ws&&this.ws.readyState===WebSocket.OPEN?this.ws.send(A):console.warn("Sendspin: Cannot send text, WebSocket not connected")}sendBinary(A){this.ws&&this.ws.readyState===WebSocket.OPEN?this.ws.send(A):console.warn("Sendspin: Cannot send binary, WebSocket not connected")}isConnected(){return this.ws!==null&&this.ws.readyState===WebSocket.OPEN}getReadyState(){return this.ws?this.ws.readyState:WebSocket.CLOSED}};var nt=class{constructor(A=.01,t=1.1,n=2,s=0){this._last_update=0,this._count=0,this._measurements_processed=0,this._offset=0,this._drift=0,this._offset_covariance=1/0,this._offset_drift_covariance=0,this._drift_covariance=0,this._use_drift=!1,this._offset_process_variance=A*A,this._drift_process_variance=s*s,this._forget_variance_factor=t*t,this._drift_significance_threshold_squared=n*n,this._current_time_element=this._createDefaultTimeElement()}_createDefaultTimeElement(){return{last_update:0,offset:0,drift:0}}update(A,t,n){if(n<=this._last_update)return;let s=n-this._last_update;this._last_update=n,this._measurements_processed+=1;let r=t,i=r*r;if(this._count<=0){this._count+=1,this._offset=A,this._offset_covariance=i,this._drift=0,this._current_time_element={last_update:this._last_update,offset:this._offset,drift:this._drift},this._use_drift=!1;return}if(this._count===1){this._count+=1,this._drift=(A-this._offset)/s,this._offset=A,this._drift_covariance=(this._offset_covariance+i)/(s*s),this._offset_covariance=i,this._current_time_element={last_update:this._last_update,offset:this._offset,drift:this._drift},this._use_drift=!1;return}let a=this._offset+this._drift*s,o=s*s,h=s*this._drift_process_variance,l=this._drift_covariance+h,c=this._offset_drift_covariance+this._drift_covariance*s+0,f=s*this._offset_process_variance,d=this._offset_covariance+2*this._offset_drift_covariance*s+this._drift_covariance*o+f,g=A-a,m=t*2;this._count<100?this._count+=1:Math.abs(g)>m&&(l*=this._forget_variance_factor,c*=this._forget_variance_factor,d*=this._forget_variance_factor);let p=1/(d+i),y=d*p,S=c*p;this._offset=a+y*g,this._drift+=S*g,this._drift_covariance=l-S*c,this._offset_drift_covariance=c-S*d,this._offset_covariance=d-y*d;let _=this._drift*this._drift;this._use_drift=_>this._drift_significance_threshold_squared*this._drift_covariance,this._current_time_element={last_update:this._last_update,offset:this._offset,drift:this._drift}}computeServerTime(A){let t=A-this._current_time_element.last_update,n=this._use_drift?this._current_time_element.drift:0,s=Math.round(this._current_time_element.offset+n*t);return A+s}computeClientTime(A){let t=this._use_drift?this._current_time_element.drift:0;return Math.round((A-this._current_time_element.offset+t*this._current_time_element.last_update)/(1+t))}reset(){this._count=0,this._measurements_processed=0,this._last_update=0,this._offset=0,this._drift=0,this._offset_covariance=1/0,this._offset_drift_covariance=0,this._drift_covariance=0,this._use_drift=!1,this._current_time_element=this._createDefaultTimeElement()}get count(){return this._measurements_processed}get is_synchronized(){return this._count>=1&&isFinite(this._offset_covariance)}get error(){return Math.round(Math.sqrt(this._offset_covariance))}get covariance(){return Math.round(this._offset_covariance)}get offset(){return this._offset}get drift(){return this._drift}};var Sn="sendspin-static-delay-ms-v2",Ot=class{constructor(A){this.storage=A}load(){if(!this.storage)return null;try{let A=this.storage.getItem(Sn);if(A===null)return null;let t=parseFloat(A);return isNaN(t)?null:gA(t)}catch{return null}}save(A){if(this.storage)try{this.storage.setItem(Sn,A.toString())}catch{}}};var BA=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function PA(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function st(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function W(e,...A){if(!PA(e))throw new Error("Uint8Array expected");if(A.length>0&&!A.includes(e.length))throw new Error("Uint8Array expected of length "+A+", got length="+e.length)}function Cn(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");st(e.outputLen),st(e.blockLen)}function YA(e,A=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(A&&e.finished)throw new Error("Hash#digest() has already been called")}function wn(e,A){W(e);let t=A.outputLen;if(e.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function SA(...e){for(let A=0;A<e.length;A++)e[A].fill(0)}function Lt(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function nA(e,A){return e<<32-A|e>>>A}var kn=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Sr=Array.from({length:256},(e,A)=>A.toString(16).padStart(2,"0"));function RA(e){if(W(e),kn)return e.toHex();let A="";for(let t=0;t<e.length;t++)A+=Sr[e[t]];return A}var yA={_0:48,_9:57,A:65,F:70,a:97,f:102};function Mn(e){if(e>=yA._0&&e<=yA._9)return e-yA._0;if(e>=yA.A&&e<=yA.F)return e-(yA.A-10);if(e>=yA.a&&e<=yA.f)return e-(yA.a-10)}function Ut(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(kn)return Uint8Array.fromHex(e);let A=e.length,t=A/2;if(A%2)throw new Error("hex string expected, got unpadded hex of length "+A);let n=new Uint8Array(t);for(let s=0,r=0;s<t;s++,r+=2){let i=Mn(e.charCodeAt(r)),a=Mn(e.charCodeAt(r+1));if(i===void 0||a===void 0){let o=e[r]+e[r+1];throw new Error('hex string expected, got non-hex character "'+o+'" at index '+r)}n[s]=i*16+a}return n}function ge(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function rt(e){return typeof e=="string"&&(e=ge(e)),W(e),e}function qA(...e){let A=0;for(let n=0;n<e.length;n++){let s=e[n];W(s),A+=s.length}let t=new Uint8Array(A);for(let n=0,s=0;n<e.length;n++){let r=e[n];t.set(r,s),s+=r.length}return t}var ZA=class{};function ye(e){let A=n=>e().update(rt(n)).digest(),t=e();return A.outputLen=t.outputLen,A.blockLen=t.blockLen,A.create=()=>e(),A}function it(e=32){if(BA&&typeof BA.getRandomValues=="function")return BA.getRandomValues(new Uint8Array(e));if(BA&&typeof BA.randomBytes=="function")return Uint8Array.from(BA.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Mr(e,A,t,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(A,t,n);let s=BigInt(32),r=BigInt(4294967295),i=Number(t>>s&r),a=Number(t&r),o=n?4:0,h=n?0:4;e.setUint32(A+o,i,n),e.setUint32(A+h,a,n)}function _n(e,A,t){return e&A^~e&t}function xn(e,A,t){return e&A^e&t^A&t}var ot=class extends ZA{constructor(A,t,n,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=A,this.outputLen=t,this.padOffset=n,this.isLE=s,this.buffer=new Uint8Array(A),this.view=Lt(this.buffer)}update(A){YA(this),A=rt(A),W(A);let{view:t,buffer:n,blockLen:s}=this,r=A.length;for(let i=0;i<r;){let a=Math.min(s-this.pos,r-i);if(a===s){let o=Lt(A);for(;s<=r-i;i+=s)this.process(o,i);continue}n.set(A.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===s&&(this.process(t,0),this.pos=0)}return this.length+=A.length,this.roundClean(),this}digestInto(A){YA(this),wn(A,this),this.finished=!0;let{buffer:t,view:n,blockLen:s,isLE:r}=this,{pos:i}=this;t[i++]=128,SA(this.buffer.subarray(i)),this.padOffset>s-i&&(this.process(n,0),i=0);for(let u=i;u<s;u++)t[u]=0;Mr(n,s-8,BigInt(this.length*8),r),this.process(n,0);let a=Lt(A),o=this.outputLen;if(o%4)throw new Error("_sha2: outputLen should be aligned to 32bit");let h=o/4,l=this.get();if(h>l.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<h;u++)a.setUint32(4*u,l[u],r)}digest(){let{buffer:A,outputLen:t}=this;this.digestInto(A);let n=A.slice(0,t);return this.destroy(),n}_cloneInto(A){A||(A=new this.constructor),A.set(...this.get());let{blockLen:t,buffer:n,length:s,finished:r,destroyed:i,pos:a}=this;return A.destroyed=i,A.finished=r,A.length=s,A.pos=a,s%t&&A.buffer.set(n),A}clone(){return this._cloneInto()}},MA=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);var Z=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]);var zt=BigInt(4294967295),En=BigInt(32);function Cr(e,A=!1){return A?{h:Number(e&zt),l:Number(e>>En&zt)}:{h:Number(e>>En&zt)|0,l:Number(e&zt)|0}}function bn(e,A=!1){let t=e.length,n=new Uint32Array(t),s=new Uint32Array(t);for(let r=0;r<t;r++){let{h:i,l:a}=Cr(e[r],A);[n[r],s[r]]=[i,a]}return[n,s]}var Se=(e,A,t)=>e>>>t,Me=(e,A,t)=>e<<32-t|A>>>t,OA=(e,A,t)=>e>>>t|A<<32-t,LA=(e,A,t)=>e<<32-t|A>>>t,at=(e,A,t)=>e<<64-t|A>>>t-32,ct=(e,A,t)=>e>>>t-32|A<<64-t;function cA(e,A,t,n){let s=(A>>>0)+(n>>>0);return{h:e+t+(s/2**32|0)|0,l:s|0}}var Tn=(e,A,t)=>(e>>>0)+(A>>>0)+(t>>>0),Dn=(e,A,t,n)=>A+t+n+(e/2**32|0)|0,vn=(e,A,t,n)=>(e>>>0)+(A>>>0)+(t>>>0)+(n>>>0),In=(e,A,t,n,s)=>A+t+n+s+(e/2**32|0)|0,Jn=(e,A,t,n,s)=>(e>>>0)+(A>>>0)+(t>>>0)+(n>>>0)+(s>>>0),Bn=(e,A,t,n,s,r)=>A+t+n+s+r+(e/2**32|0)|0;var kr=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),bA=new Uint32Array(64),Ce=class extends ot{constructor(A=32){super(64,A,8,!1),this.A=MA[0]|0,this.B=MA[1]|0,this.C=MA[2]|0,this.D=MA[3]|0,this.E=MA[4]|0,this.F=MA[5]|0,this.G=MA[6]|0,this.H=MA[7]|0}get(){let{A,B:t,C:n,D:s,E:r,F:i,G:a,H:o}=this;return[A,t,n,s,r,i,a,o]}set(A,t,n,s,r,i,a,o){this.A=A|0,this.B=t|0,this.C=n|0,this.D=s|0,this.E=r|0,this.F=i|0,this.G=a|0,this.H=o|0}process(A,t){for(let u=0;u<16;u++,t+=4)bA[u]=A.getUint32(t,!1);for(let u=16;u<64;u++){let c=bA[u-15],f=bA[u-2],d=nA(c,7)^nA(c,18)^c>>>3,g=nA(f,17)^nA(f,19)^f>>>10;bA[u]=g+bA[u-7]+d+bA[u-16]|0}let{A:n,B:s,C:r,D:i,E:a,F:o,G:h,H:l}=this;for(let u=0;u<64;u++){let c=nA(a,6)^nA(a,11)^nA(a,25),f=l+c+_n(a,o,h)+kr[u]+bA[u]|0,g=(nA(n,2)^nA(n,13)^nA(n,22))+xn(n,s,r)|0;l=h,h=o,o=a,a=i+f|0,i=r,r=s,s=n,n=f+g|0}n=n+this.A|0,s=s+this.B|0,r=r+this.C|0,i=i+this.D|0,a=a+this.E|0,o=o+this.F|0,h=h+this.G|0,l=l+this.H|0,this.set(n,s,r,i,a,o,h,l)}roundClean(){SA(bA)}destroy(){this.set(0,0,0,0,0,0,0,0),SA(this.buffer)}};var Pn=bn(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),_r=Pn[0],xr=Pn[1],TA=new Uint32Array(80),DA=new Uint32Array(80),we=class extends ot{constructor(A=64){super(128,A,16,!1),this.Ah=Z[0]|0,this.Al=Z[1]|0,this.Bh=Z[2]|0,this.Bl=Z[3]|0,this.Ch=Z[4]|0,this.Cl=Z[5]|0,this.Dh=Z[6]|0,this.Dl=Z[7]|0,this.Eh=Z[8]|0,this.El=Z[9]|0,this.Fh=Z[10]|0,this.Fl=Z[11]|0,this.Gh=Z[12]|0,this.Gl=Z[13]|0,this.Hh=Z[14]|0,this.Hl=Z[15]|0}get(){let{Ah:A,Al:t,Bh:n,Bl:s,Ch:r,Cl:i,Dh:a,Dl:o,Eh:h,El:l,Fh:u,Fl:c,Gh:f,Gl:d,Hh:g,Hl:m}=this;return[A,t,n,s,r,i,a,o,h,l,u,c,f,d,g,m]}set(A,t,n,s,r,i,a,o,h,l,u,c,f,d,g,m){this.Ah=A|0,this.Al=t|0,this.Bh=n|0,this.Bl=s|0,this.Ch=r|0,this.Cl=i|0,this.Dh=a|0,this.Dl=o|0,this.Eh=h|0,this.El=l|0,this.Fh=u|0,this.Fl=c|0,this.Gh=f|0,this.Gl=d|0,this.Hh=g|0,this.Hl=m|0}process(A,t){for(let S=0;S<16;S++,t+=4)TA[S]=A.getUint32(t),DA[S]=A.getUint32(t+=4);for(let S=16;S<80;S++){let _=TA[S-15]|0,I=DA[S-15]|0,J=OA(_,I,1)^OA(_,I,8)^Se(_,I,7),B=LA(_,I,1)^LA(_,I,8)^Me(_,I,7),v=TA[S-2]|0,M=DA[S-2]|0,C=OA(v,M,19)^at(v,M,61)^Se(v,M,6),E=LA(v,M,19)^ct(v,M,61)^Me(v,M,6),T=vn(B,E,DA[S-7],DA[S-16]),w=In(T,J,C,TA[S-7],TA[S-16]);TA[S]=w|0,DA[S]=T|0}let{Ah:n,Al:s,Bh:r,Bl:i,Ch:a,Cl:o,Dh:h,Dl:l,Eh:u,El:c,Fh:f,Fl:d,Gh:g,Gl:m,Hh:p,Hl:y}=this;for(let S=0;S<80;S++){let _=OA(u,c,14)^OA(u,c,18)^at(u,c,41),I=LA(u,c,14)^LA(u,c,18)^ct(u,c,41),J=u&f^~u&g,B=c&d^~c&m,v=Jn(y,I,B,xr[S],DA[S]),M=Bn(v,p,_,J,_r[S],TA[S]),C=v|0,E=OA(n,s,28)^at(n,s,34)^at(n,s,39),T=LA(n,s,28)^ct(n,s,34)^ct(n,s,39),w=n&r^n&a^r&a,x=s&i^s&o^i&o;p=g|0,y=m|0,g=f|0,m=d|0,f=u|0,d=c|0,{h:u,l:c}=cA(h|0,l|0,M|0,C|0),h=a|0,l=o|0,a=r|0,o=i|0,r=n|0,i=s|0;let D=Tn(C,T,x);n=Dn(D,M,E,w),s=D|0}({h:n,l:s}=cA(this.Ah|0,this.Al|0,n|0,s|0)),{h:r,l:i}=cA(this.Bh|0,this.Bl|0,r|0,i|0),{h:a,l:o}=cA(this.Ch|0,this.Cl|0,a|0,o|0),{h,l}=cA(this.Dh|0,this.Dl|0,h|0,l|0),{h:u,l:c}=cA(this.Eh|0,this.El|0,u|0,c|0),{h:f,l:d}=cA(this.Fh|0,this.Fl|0,f|0,d|0),{h:g,l:m}=cA(this.Gh|0,this.Gl|0,g|0,m|0),{h:p,l:y}=cA(this.Hh|0,this.Hl|0,p|0,y|0),this.set(n,s,r,i,a,o,h,l,u,c,f,d,g,m,p,y)}roundClean(){SA(TA,DA)}destroy(){SA(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};var j=ye(()=>new Ce);var UA=ye(()=>new we);var xe=BigInt(0),_e=BigInt(1);function Qt(e,A=""){if(typeof e!="boolean"){let t=A&&`"${A}"`;throw new Error(t+"expected boolean, got type="+typeof e)}return e}function ht(e,A,t=""){let n=PA(e),s=e?.length,r=A!==void 0;if(!n||r&&s!==A){let i=t&&`"${t}" `,a=r?` of length ${A}`:"",o=n?`length=${s}`:`type=${typeof e}`;throw new Error(i+"expected Uint8Array"+a+", got "+o)}return e}function Rn(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?xe:BigInt("0x"+e)}function On(e){return Rn(RA(e))}function sA(e){return W(e),Rn(RA(Uint8Array.from(e).reverse()))}function Ee(e,A){return Ut(e.toString(16).padStart(A*2,"0"))}function Nt(e,A){return Ee(e,A).reverse()}function X(e,A,t){let n;if(typeof A=="string")try{n=Ut(A)}catch(r){throw new Error(e+" must be hex string or Uint8Array, cause: "+r)}else if(PA(A))n=Uint8Array.from(A);else throw new Error(e+" must be hex string or Uint8Array");let s=n.length;if(typeof t=="number"&&s!==t)throw new Error(e+" of length "+t+" expected, got "+s);return n}function Ln(e,A){if(e.length!==A.length)return!1;let t=0;for(let n=0;n<e.length;n++)t|=e[n]^A[n];return t===0}function be(e){return Uint8Array.from(e)}var ke=e=>typeof e=="bigint"&&xe<=e;function Er(e,A,t){return ke(e)&&ke(A)&&ke(t)&&A<=e&&e<t}function VA(e,A,t,n){if(!Er(A,t,n))throw new Error("expected valid "+e+": "+t+" <= n < "+n+", got "+A)}function Un(e){let A;for(A=0;e>xe;e>>=_e,A+=1);return A}var lt=e=>(_e<<BigInt(e))-_e;function zA(e,A,t={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function n(s,r,i){let a=e[s];if(i&&a===void 0)return;let o=typeof a;if(o!==r||a===null)throw new Error(`param "${s}" is invalid: expected ${r}, got ${o}`)}Object.entries(A).forEach(([s,r])=>n(s,r,!1)),Object.entries(t).forEach(([s,r])=>n(s,r,!0))}var Te=()=>{throw new Error("not implemented")};function De(e){let A=new WeakMap;return(t,...n)=>{let s=A.get(t);if(s!==void 0)return s;let r=e(t,...n);return A.set(t,r),r}}var AA=BigInt(0),$=BigInt(1),QA=BigInt(2),Nn=BigInt(3),Hn=BigInt(4),Kn=BigInt(5),br=BigInt(7),Fn=BigInt(8),Tr=BigInt(9),Gn=BigInt(16);function N(e,A){let t=e%A;return t>=AA?t:A+t}function tA(e,A,t){let n=e;for(;A-- >AA;)n*=n,n%=t;return n}function zn(e,A){if(e===AA)throw new Error("invert: expected non-zero number");if(A<=AA)throw new Error("invert: expected positive modulus, got "+A);let t=N(e,A),n=A,s=AA,r=$,i=$,a=AA;for(;t!==AA;){let h=n/t,l=n%t,u=s-i*h,c=r-a*h;n=t,t=l,s=i,r=a,i=u,a=c}if(n!==$)throw new Error("invert: does not exist");return N(s,A)}function ve(e,A,t){if(!e.eql(e.sqr(A),t))throw new Error("Cannot find square root")}function Zn(e,A){let t=(e.ORDER+$)/Hn,n=e.pow(A,t);return ve(e,n,A),n}function Dr(e,A){let t=(e.ORDER-Kn)/Fn,n=e.mul(A,QA),s=e.pow(n,t),r=e.mul(A,s),i=e.mul(e.mul(r,QA),s),a=e.mul(r,e.sub(i,e.ONE));return ve(e,a,A),a}function vr(e){let A=wA(e),t=Yn(e),n=t(A,A.neg(A.ONE)),s=t(A,n),r=t(A,A.neg(n)),i=(e+br)/Gn;return(a,o)=>{let h=a.pow(o,i),l=a.mul(h,n),u=a.mul(h,s),c=a.mul(h,r),f=a.eql(a.sqr(l),o),d=a.eql(a.sqr(u),o);h=a.cmov(h,l,f),l=a.cmov(c,u,d);let g=a.eql(a.sqr(l),o),m=a.cmov(h,l,g);return ve(a,m,o),m}}function Yn(e){if(e<Nn)throw new Error("sqrt is not defined for small field");let A=e-$,t=0;for(;A%QA===AA;)A/=QA,t++;let n=QA,s=wA(e);for(;Qn(s,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return Zn;let r=s.pow(n,A),i=(A+$)/QA;return function(o,h){if(o.is0(h))return h;if(Qn(o,h)!==1)throw new Error("Cannot find square root");let l=t,u=o.mul(o.ONE,r),c=o.pow(h,A),f=o.pow(h,i);for(;!o.eql(c,o.ONE);){if(o.is0(c))return o.ZERO;let d=1,g=o.sqr(c);for(;!o.eql(g,o.ONE);)if(d++,g=o.sqr(g),d===l)throw new Error("Cannot find square root");let m=$<<BigInt(l-d-1),p=o.pow(u,m);l=d,u=o.sqr(p),c=o.mul(c,u),f=o.mul(f,p)}return f}}function Ir(e){return e%Hn===Nn?Zn:e%Fn===Kn?Dr:e%Gn===Tr?vr(e):Yn(e)}var CA=(e,A)=>(N(e,A)&$)===$,Jr=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function qn(e){let A={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},t=Jr.reduce((n,s)=>(n[s]="function",n),A);return zA(e,t),e}function Br(e,A,t){if(t<AA)throw new Error("invalid exponent, negatives unsupported");if(t===AA)return e.ONE;if(t===$)return A;let n=e.ONE,s=A;for(;t>AA;)t&$&&(n=e.mul(n,s)),s=e.sqr(s),t>>=$;return n}function Ht(e,A,t=!1){let n=new Array(A.length).fill(t?e.ZERO:void 0),s=A.reduce((i,a,o)=>e.is0(a)?i:(n[o]=i,e.mul(i,a)),e.ONE),r=e.inv(s);return A.reduceRight((i,a,o)=>e.is0(a)?i:(n[o]=e.mul(i,n[o]),e.mul(i,a)),r),n}function Qn(e,A){let t=(e.ORDER-$)/QA,n=e.pow(A,t),s=e.eql(n,e.ONE),r=e.eql(n,e.ZERO),i=e.eql(n,e.neg(e.ONE));if(!s&&!r&&!i)throw new Error("invalid Legendre symbol result");return s?1:r?0:-1}function Vn(e,A){A!==void 0&&st(A);let t=A!==void 0?A:e.toString(2).length,n=Math.ceil(t/8);return{nBitLength:t,nByteLength:n}}function wA(e,A,t=!1,n={}){if(e<=AA)throw new Error("invalid field: expected ORDER > 0, got "+e);let s,r,i=!1,a;if(typeof A=="object"&&A!=null){if(n.sqrt||t)throw new Error("cannot specify opts in two arguments");let c=A;c.BITS&&(s=c.BITS),c.sqrt&&(r=c.sqrt),typeof c.isLE=="boolean"&&(t=c.isLE),typeof c.modFromBytes=="boolean"&&(i=c.modFromBytes),a=c.allowedLengths}else typeof A=="number"&&(s=A),n.sqrt&&(r=n.sqrt);let{nBitLength:o,nByteLength:h}=Vn(e,s);if(h>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l,u=Object.freeze({ORDER:e,isLE:t,BITS:o,BYTES:h,MASK:lt(o),ZERO:AA,ONE:$,allowedLengths:a,create:c=>N(c,e),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return AA<=c&&c<e},is0:c=>c===AA,isValidNot0:c=>!u.is0(c)&&u.isValid(c),isOdd:c=>(c&$)===$,neg:c=>N(-c,e),eql:(c,f)=>c===f,sqr:c=>N(c*c,e),add:(c,f)=>N(c+f,e),sub:(c,f)=>N(c-f,e),mul:(c,f)=>N(c*f,e),pow:(c,f)=>Br(u,c,f),div:(c,f)=>N(c*zn(f,e),e),sqrN:c=>c*c,addN:(c,f)=>c+f,subN:(c,f)=>c-f,mulN:(c,f)=>c*f,inv:c=>zn(c,e),sqrt:r||(c=>(l||(l=Ir(e)),l(u,c))),toBytes:c=>t?Nt(c,h):Ee(c,h),fromBytes:(c,f=!0)=>{if(a){if(!a.includes(c.length)||c.length>h)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+c.length);let g=new Uint8Array(h);g.set(c,t?0:g.length-c.length),c=g}if(c.length!==h)throw new Error("Field.fromBytes: expected "+h+" bytes, got "+c.length);let d=t?sA(c):On(c);if(i&&(d=N(d,e)),!f&&!u.isValid(d))throw new Error("invalid field element: outside of range 0..ORDER");return d},invertBatch:c=>Ht(u,c),cmov:(c,f,d)=>d?f:c});return Object.freeze(u)}var Kt=BigInt(0),Pe=BigInt(1);function Wn(e,A){let t=A.negate();return e?t:A}function ut(e,A){let t=Ht(e.Fp,A.map(n=>n.Z));return A.map((n,s)=>e.fromAffine(n.toAffine(t[s])))}function As(e,A){if(!Number.isSafeInteger(e)||e<=0||e>A)throw new Error("invalid window size, expected [1.."+A+"], got W="+e)}function Ie(e,A){As(e,A);let t=Math.ceil(A/e)+1,n=2**(e-1),s=2**e,r=lt(e),i=BigInt(e);return{windows:t,windowSize:n,mask:r,maxNumber:s,shiftBy:i}}function jn(e,A,t){let{windowSize:n,mask:s,maxNumber:r,shiftBy:i}=t,a=Number(e&s),o=e>>i;a>n&&(a-=r,o+=Pe);let h=A*n,l=h+Math.abs(a)-1,u=a===0,c=a<0,f=A%2!==0;return{nextN:o,offset:l,isZero:u,isNeg:c,isNegF:f,offsetF:h}}function Pr(e,A){if(!Array.isArray(e))throw new Error("array expected");e.forEach((t,n)=>{if(!(t instanceof A))throw new Error("invalid point at index "+n)})}function Rr(e,A){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((t,n)=>{if(!A.isValid(t))throw new Error("invalid scalar at index "+n)})}var Je=new WeakMap,ts=new WeakMap;function Be(e){return ts.get(e)||1}function Xn(e){if(e!==Kt)throw new Error("invalid wNAF")}var Ft=class{constructor(A,t){this.BASE=A.BASE,this.ZERO=A.ZERO,this.Fn=A.Fn,this.bits=t}_unsafeLadder(A,t,n=this.ZERO){let s=A;for(;t>Kt;)t&Pe&&(n=n.add(s)),s=s.double(),t>>=Pe;return n}precomputeWindow(A,t){let{windows:n,windowSize:s}=Ie(t,this.bits),r=[],i=A,a=i;for(let o=0;o<n;o++){a=i,r.push(a);for(let h=1;h<s;h++)a=a.add(i),r.push(a);i=a.double()}return r}wNAF(A,t,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let s=this.ZERO,r=this.BASE,i=Ie(A,this.bits);for(let a=0;a<i.windows;a++){let{nextN:o,offset:h,isZero:l,isNeg:u,isNegF:c,offsetF:f}=jn(n,a,i);n=o,l?r=r.add(Wn(c,t[f])):s=s.add(Wn(u,t[h]))}return Xn(n),{p:s,f:r}}wNAFUnsafe(A,t,n,s=this.ZERO){let r=Ie(A,this.bits);for(let i=0;i<r.windows&&n!==Kt;i++){let{nextN:a,offset:o,isZero:h,isNeg:l}=jn(n,i,r);if(n=a,!h){let u=t[o];s=s.add(l?u.negate():u)}}return Xn(n),s}getPrecomputes(A,t,n){let s=Je.get(t);return s||(s=this.precomputeWindow(t,A),A!==1&&(typeof n=="function"&&(s=n(s)),Je.set(t,s))),s}cached(A,t,n){let s=Be(A);return this.wNAF(s,this.getPrecomputes(s,A,n),t)}unsafe(A,t,n,s){let r=Be(A);return r===1?this._unsafeLadder(A,t,s):this.wNAFUnsafe(r,this.getPrecomputes(r,A,n),t,s)}createCache(A,t){As(t,this.bits),ts.set(A,t),Je.delete(A)}hasCache(A){return Be(A)!==1}};function Gt(e,A,t,n){Pr(t,e),Rr(n,A);let s=t.length,r=n.length;if(s!==r)throw new Error("arrays of points and scalars must have equal length");let i=e.ZERO,a=Un(BigInt(s)),o=1;a>12?o=a-3:a>4?o=a-2:a>0&&(o=2);let h=lt(o),l=new Array(Number(h)+1).fill(i),u=Math.floor((A.BITS-1)/o)*o,c=i;for(let f=u;f>=0;f-=o){l.fill(i);for(let g=0;g<r;g++){let m=n[g],p=Number(m>>BigInt(f)&h);l[p]=l[p].add(t[g])}let d=i;for(let g=l.length-1,m=i;g>0;g--)m=m.add(l[g]),d=d.add(m);if(c=c.add(d),f!==0)for(let g=0;g<o;g++)c=c.double()}return c}function $n(e,A,t){if(A){if(A.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return qn(A),A}else return wA(e,{isLE:t})}function es(e,A,t={},n){if(n===void 0&&(n=e==="edwards"),!A||typeof A!="object")throw new Error(`expected valid ${e} CURVE object`);for(let o of["p","n","h"]){let h=A[o];if(!(typeof h=="bigint"&&h>Kt))throw new Error(`CURVE.${o} must be positive bigint`)}let s=$n(A.p,t.Fp,n),r=$n(A.n,t.Fn,n),a=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(let o of a)if(!s.isValid(A[o]))throw new Error(`CURVE.${o} must be valid field element of CURVE.Fp`);return A=Object.freeze(Object.assign({},A)),{CURVE:A,Fp:s,Fn:r}}var vA=BigInt(0),G=BigInt(1),Re=BigInt(2),Or=BigInt(8);function Lr(e,A,t,n){let s=e.sqr(t),r=e.sqr(n),i=e.add(e.mul(A.a,s),r),a=e.add(e.ONE,e.mul(A.d,e.mul(s,r)));return e.eql(i,a)}function Ur(e,A={}){let t=es("edwards",e,A,A.FpFnLE),{Fp:n,Fn:s}=t,r=t.CURVE,{h:i}=r;zA(A,{},{uvRatio:"function"});let a=Re<<BigInt(s.BYTES*8)-G,o=m=>n.create(m),h=A.uvRatio||((m,p)=>{try{return{isValid:!0,value:n.sqrt(n.div(m,p))}}catch{return{isValid:!1,value:vA}}});if(!Lr(n,r,r.Gx,r.Gy))throw new Error("bad curve params: generator point");function l(m,p,y=!1){let S=y?G:vA;return VA("coordinate "+m,p,S,a),p}function u(m){if(!(m instanceof d))throw new Error("ExtendedPoint expected")}let c=De((m,p)=>{let{X:y,Y:S,Z:_}=m,I=m.is0();p==null&&(p=I?Or:n.inv(_));let J=o(y*p),B=o(S*p),v=n.mul(_,p);if(I)return{x:vA,y:G};if(v!==G)throw new Error("invZ was invalid");return{x:J,y:B}}),f=De(m=>{let{a:p,d:y}=r;if(m.is0())throw new Error("bad point: ZERO");let{X:S,Y:_,Z:I,T:J}=m,B=o(S*S),v=o(_*_),M=o(I*I),C=o(M*M),E=o(B*p),T=o(M*o(E+v)),w=o(C+o(y*o(B*v)));if(T!==w)throw new Error("bad point: equation left != right (1)");let x=o(S*_),D=o(I*J);if(x!==D)throw new Error("bad point: equation left != right (2)");return!0});class d{constructor(p,y,S,_){this.X=l("x",p),this.Y=l("y",y),this.Z=l("z",S,!0),this.T=l("t",_),Object.freeze(this)}static CURVE(){return r}static fromAffine(p){if(p instanceof d)throw new Error("extended point not allowed");let{x:y,y:S}=p||{};return l("x",y),l("y",S),new d(y,S,G,o(y*S))}static fromBytes(p,y=!1){let S=n.BYTES,{a:_,d:I}=r;p=be(ht(p,S,"point")),Qt(y,"zip215");let J=be(p),B=p[S-1];J[S-1]=B&-129;let v=sA(J),M=y?a:n.ORDER;VA("point.y",v,vA,M);let C=o(v*v),E=o(C-G),T=o(I*C-_),{isValid:w,value:x}=h(E,T);if(!w)throw new Error("bad point: invalid y coordinate");let D=(x&G)===G,P=(B&128)!==0;if(!y&&x===vA&&P)throw new Error("bad point: x=0 and x_0=1");return P!==D&&(x=o(-x)),d.fromAffine({x,y:v})}static fromHex(p,y=!1){return d.fromBytes(X("point",p),y)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(p=8,y=!0){return g.createCache(this,p),y||this.multiply(Re),this}assertValidity(){f(this)}equals(p){u(p);let{X:y,Y:S,Z:_}=this,{X:I,Y:J,Z:B}=p,v=o(y*B),M=o(I*_),C=o(S*B),E=o(J*_);return v===M&&C===E}is0(){return this.equals(d.ZERO)}negate(){return new d(o(-this.X),this.Y,this.Z,o(-this.T))}double(){let{a:p}=r,{X:y,Y:S,Z:_}=this,I=o(y*y),J=o(S*S),B=o(Re*o(_*_)),v=o(p*I),M=y+S,C=o(o(M*M)-I-J),E=v+J,T=E-B,w=v-J,x=o(C*T),D=o(E*w),P=o(C*w),R=o(T*E);return new d(x,D,R,P)}add(p){u(p);let{a:y,d:S}=r,{X:_,Y:I,Z:J,T:B}=this,{X:v,Y:M,Z:C,T:E}=p,T=o(_*v),w=o(I*M),x=o(B*S*E),D=o(J*C),P=o((_+I)*(v+M)-T-w),R=D-x,O=D+x,k=o(w-y*T),L=o(P*R),U=o(O*k),z=o(P*k),V=o(R*O);return new d(L,U,V,z)}subtract(p){return this.add(p.negate())}multiply(p){if(!s.isValidNot0(p))throw new Error("invalid scalar: expected 1 <= sc < curve.n");let{p:y,f:S}=g.cached(this,p,_=>ut(d,_));return ut(d,[y,S])[0]}multiplyUnsafe(p,y=d.ZERO){if(!s.isValid(p))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return p===vA?d.ZERO:this.is0()||p===G?this:g.unsafe(this,p,S=>ut(d,S),y)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}isTorsionFree(){return g.unsafe(this,r.n).is0()}toAffine(p){return c(this,p)}clearCofactor(){return i===G?this:this.multiplyUnsafe(i)}toBytes(){let{x:p,y}=this.toAffine(),S=n.toBytes(y);return S[S.length-1]|=p&G?128:0,S}toHex(){return RA(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(p){return ut(d,p)}static msm(p,y){return Gt(d,s,p,y)}_setWindowSize(p){this.precompute(p)}toRawBytes(){return this.toBytes()}}d.BASE=new d(r.Gx,r.Gy,G,o(r.Gx*r.Gy)),d.ZERO=new d(vA,G,G,vA),d.Fp=n,d.Fn=s;let g=new Ft(d,s.BITS);return d.BASE.precompute(8),d}var Zt=class{constructor(A){this.ep=A}static fromBytes(A){Te()}static fromHex(A){Te()}get x(){return this.toAffine().x}get y(){return this.toAffine().y}clearCofactor(){return this}assertValidity(){this.ep.assertValidity()}toAffine(A){return this.ep.toAffine(A)}toHex(){return RA(this.toBytes())}toString(){return this.toHex()}isTorsionFree(){return!0}isSmallOrder(){return!1}add(A){return this.assertSame(A),this.init(this.ep.add(A.ep))}subtract(A){return this.assertSame(A),this.init(this.ep.subtract(A.ep))}multiply(A){return this.init(this.ep.multiply(A))}multiplyUnsafe(A){return this.init(this.ep.multiplyUnsafe(A))}double(){return this.init(this.ep.double())}negate(){return this.init(this.ep.negate())}precompute(A,t){return this.init(this.ep.precompute(A,t))}toRawBytes(){return this.toBytes()}};function zr(e,A,t={}){if(typeof A!="function")throw new Error('"hash" function param is required');zA(t,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});let{prehash:n}=t,{BASE:s,Fp:r,Fn:i}=e,a=t.randomBytes||it,o=t.adjustScalarBytes||(M=>M),h=t.domain||((M,C,E)=>{if(Qt(E,"phflag"),C.length||E)throw new Error("Contexts/pre-hash are not supported");return M});function l(M){return i.create(sA(M))}function u(M){let C=S.secretKey;M=X("private key",M,C);let E=X("hashed private key",A(M),2*C),T=o(E.slice(0,C)),w=E.slice(C,2*C),x=l(T);return{head:T,prefix:w,scalar:x}}function c(M){let{head:C,prefix:E,scalar:T}=u(M),w=s.multiply(T),x=w.toBytes();return{head:C,prefix:E,scalar:T,point:w,pointBytes:x}}function f(M){return c(M).pointBytes}function d(M=Uint8Array.of(),...C){let E=qA(...C);return l(A(h(E,X("context",M),!!n)))}function g(M,C,E={}){M=X("message",M),n&&(M=n(M));let{prefix:T,scalar:w,pointBytes:x}=c(C),D=d(E.context,T,M),P=s.multiply(D).toBytes(),R=d(E.context,P,x,M),O=i.create(D+R*w);if(!i.isValid(O))throw new Error("sign failed: invalid s");let k=qA(P,i.toBytes(O));return ht(k,S.signature,"result")}let m={zip215:!0};function p(M,C,E,T=m){let{context:w,zip215:x}=T,D=S.signature;M=X("signature",M,D),C=X("message",C),E=X("publicKey",E,S.publicKey),x!==void 0&&Qt(x,"zip215"),n&&(C=n(C));let P=D/2,R=M.subarray(0,P),O=sA(M.subarray(P,D)),k,L,U;try{k=e.fromBytes(E,x),L=e.fromBytes(R,x),U=s.multiplyUnsafe(O)}catch{return!1}if(!x&&k.isSmallOrder())return!1;let z=d(w,L.toBytes(),k.toBytes(),C);return L.add(k.multiplyUnsafe(z)).subtract(U).clearCofactor().is0()}let y=r.BYTES,S={secretKey:y,publicKey:y,signature:2*y,seed:y};function _(M=a(S.seed)){return ht(M,S.seed,"seed")}function I(M){let C=v.randomSecretKey(M);return{secretKey:C,publicKey:f(C)}}function J(M){return PA(M)&&M.length===i.BYTES}function B(M,C){try{return!!e.fromBytes(M,C)}catch{return!1}}let v={getExtendedPublicKey:c,randomSecretKey:_,isValidSecretKey:J,isValidPublicKey:B,toMontgomery(M){let{y:C}=e.fromBytes(M),E=S.publicKey,T=E===32;if(!T&&E!==57)throw new Error("only defined for 25519 and 448");let w=T?r.div(G+C,G-C):r.div(C-G,C+G);return r.toBytes(w)},toMontgomerySecret(M){let C=S.secretKey;ht(M,C);let E=A(M.subarray(0,C));return o(E).subarray(0,C)},randomPrivateKey:_,precompute(M=8,C=e.BASE){return C.precompute(M,!1)}};return Object.freeze({keygen:I,getPublicKey:f,sign:g,verify:p,utils:v,Point:e,lengths:S})}function Qr(e){let A={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},t=e.Fp,n=wA(A.n,e.nBitLength,!0),s={Fp:t,Fn:n,uvRatio:e.uvRatio},r={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:A,curveOpts:s,hash:e.hash,eddsaOpts:r}}function Nr(e,A){let t=A.Point;return Object.assign({},A,{ExtendedPoint:t,CURVE:e,nBitLength:t.Fn.BITS,nByteLength:t.Fn.BYTES})}function ns(e){let{CURVE:A,curveOpts:t,hash:n,eddsaOpts:s}=Qr(e),r=Ur(A,t),i=zr(r,n,s);return Nr(e,i)}var dt=BigInt(0),WA=BigInt(1),Yt=BigInt(2);function Hr(e){return zA(e,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...e})}function ss(e){let A=Hr(e),{P:t,type:n,adjustScalarBytes:s,powPminus2:r,randomBytes:i}=A,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");let o=i||it,h=a?255:448,l=a?32:56,u=BigInt(a?9:5),c=BigInt(a?121665:39081),f=a?Yt**BigInt(254):Yt**BigInt(447),d=a?BigInt(8)*Yt**BigInt(251)-WA:BigInt(4)*Yt**BigInt(445)-WA,g=f+d+WA,m=w=>N(w,t),p=y(u);function y(w){return Nt(m(w),l)}function S(w){let x=X("u coordinate",w,l);return a&&(x[31]&=127),m(sA(x))}function _(w){return sA(s(X("scalar",w,l)))}function I(w,x){let D=v(S(x),_(w));if(D===dt)throw new Error("invalid private or public key received");return y(D)}function J(w){return I(w,p)}function B(w,x,D){let P=m(w*(x-D));return x=m(x-P),D=m(D+P),{x_2:x,x_3:D}}function v(w,x){VA("u",w,dt,t),VA("scalar",x,f,g);let D=x,P=w,R=WA,O=dt,k=w,L=WA,U=dt;for(let V=BigInt(h-1);V>=dt;V--){let rA=D>>V&WA;U^=rA,{x_2:R,x_3:k}=B(U,R,k),{x_2:O,x_3:L}=B(U,O,L),U=rA;let iA=R+O,oA=m(iA*iA),aA=R-O,pA=m(aA*aA),mA=oA-pA,cr=k+L,hr=k-L,dn=m(hr*iA),fn=m(cr*aA),pn=dn+fn,mn=dn-fn;k=m(pn*pn),L=m(P*m(mn*mn)),R=m(oA*pA),O=m(mA*(oA+m(c*mA)))}({x_2:R,x_3:k}=B(U,R,k)),{x_2:O,x_3:L}=B(U,O,L);let z=r(O);return m(R*z)}let M={secretKey:l,publicKey:l,seed:l},C=(w=o(l))=>(W(w,M.seed),w);function E(w){let x=C(w);return{secretKey:x,publicKey:J(x)}}return{keygen:E,getSharedSecret:(w,x)=>I(w,x),getPublicKey:w=>J(w),scalarMult:I,scalarMultBase:J,utils:{randomSecretKey:C,randomPrivateKey:C},GuBytes:p.slice(),lengths:M}}var Kr=BigInt(0),_A=BigInt(1),rs=BigInt(2),Fr=BigInt(3),Gr=BigInt(5),Zr=BigInt(8),jA=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),ft={p:jA,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Zr,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function as(e){let A=BigInt(10),t=BigInt(20),n=BigInt(40),s=BigInt(80),r=jA,a=e*e%r*e%r,o=tA(a,rs,r)*a%r,h=tA(o,_A,r)*e%r,l=tA(h,Gr,r)*h%r,u=tA(l,A,r)*l%r,c=tA(u,t,r)*u%r,f=tA(c,n,r)*c%r,d=tA(f,s,r)*f%r,g=tA(d,s,r)*f%r,m=tA(g,A,r)*l%r;return{pow_p_5_8:tA(m,rs,r)*e%r,b2:a}}function cs(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}var Oe=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function ze(e,A){let t=jA,n=N(A*A*A,t),s=N(n*n*A,t),r=as(e*s).pow_p_5_8,i=N(e*n*r,t),a=N(A*i*i,t),o=i,h=N(i*Oe,t),l=a===e,u=a===N(-e,t),c=a===N(-e*Oe,t);return l&&(i=o),(u||c)&&(i=h),CA(i,t)&&(i=N(-i,t)),{isValid:l||u,value:i}}var kA=wA(ft.p,{isLE:!0}),Yr=wA(ft.n,{isLE:!0}),qr={...ft,Fp:kA,hash:UA,adjustScalarBytes:cs,uvRatio:ze},NA=ns(qr);var HA=(()=>{let e=kA.ORDER;return ss({P:e,type:"x25519",powPminus2:A=>{let{pow_p_5_8:t,b2:n}=as(A);return N(tA(t,Fr,e)*n,e)},adjustScalarBytes:cs})})();var Le=Oe,Vr=BigInt("25063068953384623474111414158702152701244531502492656460079210482610430750235"),Wr=BigInt("54469307008909316920995813868745141605393597292927456921205312896311721017578"),jr=BigInt("1159843021668779879193775521855586647937357759715417654439879720876111806838"),Xr=BigInt("40440834346308536858101042469323190826248399146238708352240133220865137265952"),is=e=>ze(_A,e),$r=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),Ue=e=>NA.Point.Fp.create(sA(e)&$r);function os(e){let{d:A}=ft,t=jA,n=p=>kA.create(p),s=n(Le*e*e),r=n((s+_A)*jr),i=BigInt(-1),a=n((i-A*s)*n(s+A)),{isValid:o,value:h}=ze(r,a),l=n(h*e);CA(l,t)||(l=n(-l)),o||(h=l),o||(i=s);let u=n(i*(s-_A)*Xr-a),c=h*h,f=n((h+h)*a),d=n(u*Vr),g=n(_A-c),m=n(_A+c);return new NA.Point(n(f*m),n(g*d),n(d*m),n(f*g))}function Ai(e){W(e,64);let A=Ue(e.subarray(0,32)),t=os(A),n=Ue(e.subarray(32,64)),s=os(n);return new xA(t.add(s))}var xA=class e extends Zt{constructor(A){super(A)}static fromAffine(A){return new e(NA.Point.fromAffine(A))}assertSame(A){if(!(A instanceof e))throw new Error("RistrettoPoint expected")}init(A){return new e(A)}static hashToCurve(A){return Ai(X("ristrettoHash",A,64))}static fromBytes(A){W(A,32);let{a:t,d:n}=ft,s=jA,r=_=>kA.create(_),i=Ue(A);if(!Ln(kA.toBytes(i),A)||CA(i,s))throw new Error("invalid ristretto255 encoding 1");let a=r(i*i),o=r(_A+t*a),h=r(_A-t*a),l=r(o*o),u=r(h*h),c=r(t*n*l-u),{isValid:f,value:d}=is(r(c*u)),g=r(d*h),m=r(d*g*c),p=r((i+i)*g);CA(p,s)&&(p=r(-p));let y=r(o*m),S=r(p*y);if(!f||CA(S,s)||y===Kr)throw new Error("invalid ristretto255 encoding 2");return new e(new NA.Point(p,y,_A,S))}static fromHex(A){return e.fromBytes(X("ristrettoHex",A,32))}static msm(A,t){return Gt(e,NA.Point.Fn,A,t)}toBytes(){let{X:A,Y:t,Z:n,T:s}=this.ep,r=jA,i=m=>kA.create(m),a=i(i(n+t)*i(n-t)),o=i(A*t),h=i(o*o),{value:l}=is(i(a*h)),u=i(l*a),c=i(l*o),f=i(u*c*s),d;if(CA(s*f,r)){let m=i(t*Le),p=i(A*Le);A=m,t=p,d=i(u*Wr)}else d=c;CA(A*f,r)&&(t=i(-t));let g=i((n-t)*d);return CA(g,r)&&(g=i(-g)),kA.toBytes(g)}equals(A){this.assertSame(A);let{X:t,Y:n}=this.ep,{X:s,Y:r}=A.ep,i=h=>kA.create(h),a=i(t*r)===i(n*s),o=i(n*r)===i(t*s);return a||o}is0(){return this.equals(e.ZERO)}};xA.BASE=new xA(NA.Point.BASE);xA.ZERO=new xA(NA.Point.ZERO);xA.Fp=kA;xA.Fn=Yr;function hs(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Vt(e){if(typeof e!="boolean")throw new Error(`boolean expected, not ${e}`)}function Wt(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Q(e,...A){if(!hs(e))throw new Error("Uint8Array expected");if(A.length>0&&!A.includes(e.length))throw new Error("Uint8Array expected of length "+A+", got length="+e.length)}function IA(e,A=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(A&&e.finished)throw new Error("Hash#digest() has already been called")}function pt(e,A){Q(e);let t=A.outputLen;if(e.length<t)throw new Error("digestInto() expects output buffer of length at least "+t)}function ls(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function K(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function F(...e){for(let A=0;A<e.length;A++)e[A].fill(0)}function XA(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}var ti=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ei(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function hA(e){if(typeof e=="string")e=ei(e);else if(hs(e))e=lA(e);else throw new Error("Uint8Array expected, got "+typeof e);return e}function us(e,A){if(A==null||typeof A!="object")throw new Error("options must be defined");return Object.assign(e,A)}function jt(e,A){if(e.length!==A.length)return!1;let t=0;for(let n=0;n<e.length;n++)t|=e[n]^A[n];return t===0}var mt=(e,A)=>{function t(n,...s){if(Q(n),!ti)throw new Error("Non little-endian hardware is not yet supported");if(e.nonceLength!==void 0){let l=s[0];if(!l)throw new Error("nonce / iv required");e.varSizeNonce?Q(l):Q(l,e.nonceLength)}let r=e.tagLength;r&&s[1]!==void 0&&Q(s[1]);let i=A(n,...s),a=(l,u)=>{if(u!==void 0){if(l!==2)throw new Error("cipher output not supported");Q(u)}},o=!1;return{encrypt(l,u){if(o)throw new Error("cannot encrypt() twice with same key + nonce");return o=!0,Q(l),a(i.encrypt.length,u),i.encrypt(l,u)},decrypt(l,u){if(Q(l),r&&l.length<r)throw new Error("invalid ciphertext length: smaller than tagLength="+r);return a(i.decrypt.length,u),i.decrypt(l,u)}}}return Object.assign(t,e),t};function gt(e,A,t=!0){if(A===void 0)return new Uint8Array(e);if(A.length!==e)throw new Error("invalid output length, expected "+e+", got: "+A.length);if(t&&!yt(A))throw new Error("invalid output, must be aligned");return A}function qt(e,A,t,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(A,t,n);let s=BigInt(32),r=BigInt(4294967295),i=Number(t>>s&r),a=Number(t&r),o=n?4:0,h=n?0:4;e.setUint32(A+o,i,n),e.setUint32(A+h,a,n)}function Xt(e,A,t){Vt(t);let n=new Uint8Array(16),s=XA(n);return qt(s,0,BigInt(A),t),qt(s,8,BigInt(e),t),n}function yt(e){return e.byteOffset%4===0}function lA(e){return Uint8Array.from(e)}var fs=e=>Uint8Array.from(e.split("").map(A=>A.charCodeAt(0))),ni=fs("expand 16-byte k"),si=fs("expand 32-byte k"),ri=K(ni),ii=K(si);function b(e,A){return e<<A|e>>>32-A}function Qe(e){return e.byteOffset%4===0}var $t=64,oi=16,ps=2**32-1,ds=new Uint32Array;function ai(e,A,t,n,s,r,i,a){let o=s.length,h=new Uint8Array($t),l=K(h),u=Qe(s)&&Qe(r),c=u?K(s):ds,f=u?K(r):ds;for(let d=0;d<o;i++){if(e(A,t,n,l,i,a),i>=ps)throw new Error("arx: counter overflow");let g=Math.min($t,o-d);if(u&&g===$t){let m=d/4;if(d%4!==0)throw new Error("arx: invalid block position");for(let p=0,y;p<oi;p++)y=m+p,f[y]=c[y]^l[p];d+=$t;continue}for(let m=0,p;m<g;m++)p=d+m,r[p]=s[p]^h[m];d+=g}}function Ne(e,A){let{allowShortKeys:t,extendNonceFn:n,counterLength:s,counterRight:r,rounds:i}=us({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},A);if(typeof e!="function")throw new Error("core must be a function");return Wt(s),Wt(i),Vt(r),Vt(t),(a,o,h,l,u=0)=>{Q(a),Q(o),Q(h);let c=h.length;if(l===void 0&&(l=new Uint8Array(c)),Q(l),Wt(u),u<0||u>=ps)throw new Error("arx: counter overflow");if(l.length<c)throw new Error(`arx: output (${l.length}) is shorter than data (${c})`);let f=[],d=a.length,g,m;if(d===32)f.push(g=lA(a)),m=ii;else if(d===16&&t)g=new Uint8Array(32),g.set(a),g.set(a,16),m=ri,f.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${d}`);Qe(o)||f.push(o=lA(o));let p=K(g);if(n){if(o.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(m,p,K(o.subarray(0,16)),p),o=o.subarray(16)}let y=16-s;if(y!==o.length)throw new Error(`arx: nonce must be ${y} or 16 bytes`);if(y!==12){let _=new Uint8Array(12);_.set(o,r?0:12-o.length),o=_,f.push(o)}let S=K(o);return ai(e,m,p,S,h,l,u,i),F(...f),l}}var Y=(e,A)=>e[A++]&255|(e[A++]&255)<<8,He=class{constructor(A){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,A=hA(A),Q(A,32);let t=Y(A,0),n=Y(A,2),s=Y(A,4),r=Y(A,6),i=Y(A,8),a=Y(A,10),o=Y(A,12),h=Y(A,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|s<<6)&7939,this.r[3]=(s>>>7|r<<9)&8191,this.r[4]=(r>>>4|i<<12)&255,this.r[5]=i>>>1&8190,this.r[6]=(i>>>14|a<<2)&8191,this.r[7]=(a>>>11|o<<5)&8065,this.r[8]=(o>>>8|h<<8)&8191,this.r[9]=h>>>5&127;for(let l=0;l<8;l++)this.pad[l]=Y(A,16+2*l)}process(A,t,n=!1){let s=n?0:2048,{h:r,r:i}=this,a=i[0],o=i[1],h=i[2],l=i[3],u=i[4],c=i[5],f=i[6],d=i[7],g=i[8],m=i[9],p=Y(A,t+0),y=Y(A,t+2),S=Y(A,t+4),_=Y(A,t+6),I=Y(A,t+8),J=Y(A,t+10),B=Y(A,t+12),v=Y(A,t+14),M=r[0]+(p&8191),C=r[1]+((p>>>13|y<<3)&8191),E=r[2]+((y>>>10|S<<6)&8191),T=r[3]+((S>>>7|_<<9)&8191),w=r[4]+((_>>>4|I<<12)&8191),x=r[5]+(I>>>1&8191),D=r[6]+((I>>>14|J<<2)&8191),P=r[7]+((J>>>11|B<<5)&8191),R=r[8]+((B>>>8|v<<8)&8191),O=r[9]+(v>>>5|s),k=0,L=k+M*a+C*(5*m)+E*(5*g)+T*(5*d)+w*(5*f);k=L>>>13,L&=8191,L+=x*(5*c)+D*(5*u)+P*(5*l)+R*(5*h)+O*(5*o),k+=L>>>13,L&=8191;let U=k+M*o+C*a+E*(5*m)+T*(5*g)+w*(5*d);k=U>>>13,U&=8191,U+=x*(5*f)+D*(5*c)+P*(5*u)+R*(5*l)+O*(5*h),k+=U>>>13,U&=8191;let z=k+M*h+C*o+E*a+T*(5*m)+w*(5*g);k=z>>>13,z&=8191,z+=x*(5*d)+D*(5*f)+P*(5*c)+R*(5*u)+O*(5*l),k+=z>>>13,z&=8191;let V=k+M*l+C*h+E*o+T*a+w*(5*m);k=V>>>13,V&=8191,V+=x*(5*g)+D*(5*d)+P*(5*f)+R*(5*c)+O*(5*u),k+=V>>>13,V&=8191;let rA=k+M*u+C*l+E*h+T*o+w*a;k=rA>>>13,rA&=8191,rA+=x*(5*m)+D*(5*g)+P*(5*d)+R*(5*f)+O*(5*c),k+=rA>>>13,rA&=8191;let iA=k+M*c+C*u+E*l+T*h+w*o;k=iA>>>13,iA&=8191,iA+=x*a+D*(5*m)+P*(5*g)+R*(5*d)+O*(5*f),k+=iA>>>13,iA&=8191;let oA=k+M*f+C*c+E*u+T*l+w*h;k=oA>>>13,oA&=8191,oA+=x*o+D*a+P*(5*m)+R*(5*g)+O*(5*d),k+=oA>>>13,oA&=8191;let aA=k+M*d+C*f+E*c+T*u+w*l;k=aA>>>13,aA&=8191,aA+=x*h+D*o+P*a+R*(5*m)+O*(5*g),k+=aA>>>13,aA&=8191;let pA=k+M*g+C*d+E*f+T*c+w*u;k=pA>>>13,pA&=8191,pA+=x*l+D*h+P*o+R*a+O*(5*m),k+=pA>>>13,pA&=8191;let mA=k+M*m+C*g+E*d+T*f+w*c;k=mA>>>13,mA&=8191,mA+=x*u+D*l+P*h+R*o+O*a,k+=mA>>>13,mA&=8191,k=(k<<2)+k|0,k=k+L|0,L=k&8191,k=k>>>13,U+=k,r[0]=L,r[1]=U,r[2]=z,r[3]=V,r[4]=rA,r[5]=iA,r[6]=oA,r[7]=aA,r[8]=pA,r[9]=mA}finalize(){let{h:A,pad:t}=this,n=new Uint16Array(10),s=A[1]>>>13;A[1]&=8191;for(let a=2;a<10;a++)A[a]+=s,s=A[a]>>>13,A[a]&=8191;A[0]+=s*5,s=A[0]>>>13,A[0]&=8191,A[1]+=s,s=A[1]>>>13,A[1]&=8191,A[2]+=s,n[0]=A[0]+5,s=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=A[a]+s,s=n[a]>>>13,n[a]&=8191;n[9]-=8192;let r=(s^1)-1;for(let a=0;a<10;a++)n[a]&=r;r=~r;for(let a=0;a<10;a++)A[a]=A[a]&r|n[a];A[0]=(A[0]|A[1]<<13)&65535,A[1]=(A[1]>>>3|A[2]<<10)&65535,A[2]=(A[2]>>>6|A[3]<<7)&65535,A[3]=(A[3]>>>9|A[4]<<4)&65535,A[4]=(A[4]>>>12|A[5]<<1|A[6]<<14)&65535,A[5]=(A[6]>>>2|A[7]<<11)&65535,A[6]=(A[7]>>>5|A[8]<<8)&65535,A[7]=(A[8]>>>8|A[9]<<5)&65535;let i=A[0]+t[0];A[0]=i&65535;for(let a=1;a<8;a++)i=(A[a]+t[a]|0)+(i>>>16)|0,A[a]=i&65535;F(n)}update(A){IA(this),A=hA(A),Q(A);let{buffer:t,blockLen:n}=this,s=A.length;for(let r=0;r<s;){let i=Math.min(n-this.pos,s-r);if(i===n){for(;n<=s-r;r+=n)this.process(A,r);continue}t.set(A.subarray(r,r+i),this.pos),this.pos+=i,r+=i,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){F(this.h,this.r,this.buffer,this.pad)}digestInto(A){IA(this),pt(A,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:s}=this;if(s){for(t[s++]=1;s<16;s++)t[s]=0;this.process(t,0,!0)}this.finalize();let r=0;for(let i=0;i<8;i++)A[r++]=n[i]>>>0,A[r++]=n[i]>>>8;return A}digest(){let{buffer:A,outputLen:t}=this;this.digestInto(A);let n=A.slice(0,t);return this.destroy(),n}};function ci(e){let A=(n,s)=>e(s).update(hA(n)).digest(),t=e(new Uint8Array(32));return A.outputLen=t.outputLen,A.blockLen=t.blockLen,A.create=n=>e(n),A}var ms=ci(e=>new He(e));function Ss(e,A,t,n,s,r=20){let i=e[0],a=e[1],o=e[2],h=e[3],l=A[0],u=A[1],c=A[2],f=A[3],d=A[4],g=A[5],m=A[6],p=A[7],y=s,S=t[0],_=t[1],I=t[2],J=i,B=a,v=o,M=h,C=l,E=u,T=c,w=f,x=d,D=g,P=m,R=p,O=y,k=S,L=_,U=I;for(let V=0;V<r;V+=2)J=J+C|0,O=b(O^J,16),x=x+O|0,C=b(C^x,12),J=J+C|0,O=b(O^J,8),x=x+O|0,C=b(C^x,7),B=B+E|0,k=b(k^B,16),D=D+k|0,E=b(E^D,12),B=B+E|0,k=b(k^B,8),D=D+k|0,E=b(E^D,7),v=v+T|0,L=b(L^v,16),P=P+L|0,T=b(T^P,12),v=v+T|0,L=b(L^v,8),P=P+L|0,T=b(T^P,7),M=M+w|0,U=b(U^M,16),R=R+U|0,w=b(w^R,12),M=M+w|0,U=b(U^M,8),R=R+U|0,w=b(w^R,7),J=J+E|0,U=b(U^J,16),P=P+U|0,E=b(E^P,12),J=J+E|0,U=b(U^J,8),P=P+U|0,E=b(E^P,7),B=B+T|0,O=b(O^B,16),R=R+O|0,T=b(T^R,12),B=B+T|0,O=b(O^B,8),R=R+O|0,T=b(T^R,7),v=v+w|0,k=b(k^v,16),x=x+k|0,w=b(w^x,12),v=v+w|0,k=b(k^v,8),x=x+k|0,w=b(w^x,7),M=M+C|0,L=b(L^M,16),D=D+L|0,C=b(C^D,12),M=M+C|0,L=b(L^M,8),D=D+L|0,C=b(C^D,7);let z=0;n[z++]=i+J|0,n[z++]=a+B|0,n[z++]=o+v|0,n[z++]=h+M|0,n[z++]=l+C|0,n[z++]=u+E|0,n[z++]=c+T|0,n[z++]=f+w|0,n[z++]=d+x|0,n[z++]=g+D|0,n[z++]=m+P|0,n[z++]=p+R|0,n[z++]=y+O|0,n[z++]=S+k|0,n[z++]=_+L|0,n[z++]=I+U|0}function hi(e,A,t,n){let s=e[0],r=e[1],i=e[2],a=e[3],o=A[0],h=A[1],l=A[2],u=A[3],c=A[4],f=A[5],d=A[6],g=A[7],m=t[0],p=t[1],y=t[2],S=t[3];for(let I=0;I<20;I+=2)s=s+o|0,m=b(m^s,16),c=c+m|0,o=b(o^c,12),s=s+o|0,m=b(m^s,8),c=c+m|0,o=b(o^c,7),r=r+h|0,p=b(p^r,16),f=f+p|0,h=b(h^f,12),r=r+h|0,p=b(p^r,8),f=f+p|0,h=b(h^f,7),i=i+l|0,y=b(y^i,16),d=d+y|0,l=b(l^d,12),i=i+l|0,y=b(y^i,8),d=d+y|0,l=b(l^d,7),a=a+u|0,S=b(S^a,16),g=g+S|0,u=b(u^g,12),a=a+u|0,S=b(S^a,8),g=g+S|0,u=b(u^g,7),s=s+h|0,S=b(S^s,16),d=d+S|0,h=b(h^d,12),s=s+h|0,S=b(S^s,8),d=d+S|0,h=b(h^d,7),r=r+l|0,m=b(m^r,16),g=g+m|0,l=b(l^g,12),r=r+l|0,m=b(m^r,8),g=g+m|0,l=b(l^g,7),i=i+u|0,p=b(p^i,16),c=c+p|0,u=b(u^c,12),i=i+u|0,p=b(p^i,8),c=c+p|0,u=b(u^c,7),a=a+o|0,y=b(y^a,16),f=f+y|0,o=b(o^f,12),a=a+o|0,y=b(y^a,8),f=f+y|0,o=b(o^f,7);let _=0;n[_++]=s,n[_++]=r,n[_++]=i,n[_++]=a,n[_++]=m,n[_++]=p,n[_++]=y,n[_++]=S}var li=Ne(Ss,{counterRight:!1,counterLength:4,allowShortKeys:!1}),ui=Ne(Ss,{counterRight:!1,counterLength:8,extendNonceFn:hi,allowShortKeys:!1});var di=new Uint8Array(16),gs=(e,A)=>{e.update(A);let t=A.length%16;t&&e.update(di.subarray(t))},fi=new Uint8Array(32);function ys(e,A,t,n,s){let r=e(A,t,fi),i=ms.create(r);s&&gs(i,s),gs(i,n);let a=Xt(n.length,s?s.length:0,!0);i.update(a);let o=i.digest();return F(r,a),o}var Ms=e=>(A,t,n)=>({encrypt(r,i){let a=r.length;i=gt(a+16,i,!1),i.set(r);let o=i.subarray(0,-16);e(A,t,o,o,1);let h=ys(e,A,t,o,n);return i.set(h,a),F(h),i},decrypt(r,i){i=gt(r.length-16,i,!1);let a=r.subarray(0,-16),o=r.subarray(-16),h=ys(e,A,t,a,n);if(!jt(o,h))throw new Error("invalid tag");return i.set(r.subarray(0,-16)),e(A,t,i,i,1),F(h),i}}),Ke=mt({blockSize:64,nonceLength:12,tagLength:16},Ms(li)),oa=mt({blockSize:64,nonceLength:24,tagLength:16},Ms(ui));var EA=16,Ge=new Uint8Array(16),uA=K(Ge),pi=225,mi=(e,A,t,n)=>{let s=n&1;return{s3:t<<31|n>>>1,s2:A<<31|t>>>1,s1:e<<31|A>>>1,s0:e>>>1^pi<<24&-(s&1)}},eA=e=>(e>>>0&255)<<24|(e>>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255|0;function gi(e){e.reverse();let A=e[15]&1,t=0;for(let n=0;n<e.length;n++){let s=e[n];e[n]=s>>>1|t,t=(s&1)<<7}return e[0]^=-A&225,e}var yi=e=>e>64*1024?8:e>1024?4:2,Ae=class{constructor(A,t){this.blockLen=EA,this.outputLen=EA,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,A=hA(A),Q(A,16);let n=XA(A),s=n.getUint32(0,!1),r=n.getUint32(4,!1),i=n.getUint32(8,!1),a=n.getUint32(12,!1),o=[];for(let d=0;d<128;d++)o.push({s0:eA(s),s1:eA(r),s2:eA(i),s3:eA(a)}),{s0:s,s1:r,s2:i,s3:a}=mi(s,r,i,a);let h=yi(t||1024);if(![1,2,4,8].includes(h))throw new Error("ghash: invalid window size, expected 2, 4 or 8");this.W=h;let u=128/h,c=this.windowSize=2**h,f=[];for(let d=0;d<u;d++)for(let g=0;g<c;g++){let m=0,p=0,y=0,S=0;for(let _=0;_<h;_++){if(!(g>>>h-_-1&1))continue;let{s0:J,s1:B,s2:v,s3:M}=o[h*d+_];m^=J,p^=B,y^=v,S^=M}f.push({s0:m,s1:p,s2:y,s3:S})}this.t=f}_updateBlock(A,t,n,s){A^=this.s0,t^=this.s1,n^=this.s2,s^=this.s3;let{W:r,t:i,windowSize:a}=this,o=0,h=0,l=0,u=0,c=(1<<r)-1,f=0;for(let d of[A,t,n,s])for(let g=0;g<4;g++){let m=d>>>8*g&255;for(let p=8/r-1;p>=0;p--){let y=m>>>r*p&c,{s0:S,s1:_,s2:I,s3:J}=i[f*a+y];o^=S,h^=_,l^=I,u^=J,f+=1}}this.s0=o,this.s1=h,this.s2=l,this.s3=u}update(A){IA(this),A=hA(A),Q(A);let t=K(A),n=Math.floor(A.length/EA),s=A.length%EA;for(let r=0;r<n;r++)this._updateBlock(t[r*4+0],t[r*4+1],t[r*4+2],t[r*4+3]);return s&&(Ge.set(A.subarray(n*EA)),this._updateBlock(uA[0],uA[1],uA[2],uA[3]),F(uA)),this}destroy(){let{t:A}=this;for(let t of A)t.s0=0,t.s1=0,t.s2=0,t.s3=0}digestInto(A){IA(this),pt(A,this),this.finished=!0;let{s0:t,s1:n,s2:s,s3:r}=this,i=K(A);return i[0]=t,i[1]=n,i[2]=s,i[3]=r,A}digest(){let A=new Uint8Array(EA);return this.digestInto(A),this.destroy(),A}},Fe=class extends Ae{constructor(A,t){A=hA(A),Q(A);let n=gi(lA(A));super(n,t),F(n)}update(A){A=hA(A),IA(this);let t=K(A),n=A.length%EA,s=Math.floor(A.length/EA);for(let r=0;r<s;r++)this._updateBlock(eA(t[r*4+3]),eA(t[r*4+2]),eA(t[r*4+1]),eA(t[r*4+0]));return n&&(Ge.set(A.subarray(s*EA)),this._updateBlock(eA(uA[3]),eA(uA[2]),eA(uA[1]),eA(uA[0])),F(uA)),this}digestInto(A){IA(this),pt(A,this),this.finished=!0;let{s0:t,s1:n,s2:s,s3:r}=this,i=K(A);return i[0]=t,i[1]=n,i[2]=s,i[3]=r,A.reverse()}};function Cs(e){let A=(n,s)=>e(s,n.length).update(hA(n)).digest(),t=e(new Uint8Array(16),0);return A.outputLen=t.outputLen,A.blockLen=t.blockLen,A.create=(n,s)=>e(n,s),A}var Ze=Cs((e,A)=>new Ae(e,A)),Si=Cs((e,A)=>new Fe(e,A));var qe=16,Mi=4,te=new Uint8Array(qe),Ci=283;function Ve(e){return e<<1^Ci&-(e>>7)}function ws(e,A){let t=0;for(;A>0;A>>=1)t^=e&-(A&1),e=Ve(e);return t}var wi=(()=>{let e=new Uint8Array(256);for(let t=0,n=1;t<256;t++,n^=Ve(n))e[t]=n;let A=new Uint8Array(256);A[0]=99;for(let t=0;t<255;t++){let n=e[255-t];n|=n<<8,A[e[t]]=(n^n>>4^n>>5^n>>6^n>>7^99)&255}return F(e),A})();var ki=e=>e<<24|e>>>8,Ye=e=>e<<8|e>>>24;function _i(e,A){if(e.length!==256)throw new Error("Wrong sbox length");let t=new Uint32Array(256).map((h,l)=>A(e[l])),n=t.map(Ye),s=n.map(Ye),r=s.map(Ye),i=new Uint32Array(256*256),a=new Uint32Array(256*256),o=new Uint16Array(256*256);for(let h=0;h<256;h++)for(let l=0;l<256;l++){let u=h*256+l;i[u]=t[h]^n[l],a[u]=s[h]^r[l],o[u]=e[h]<<8|e[l]}return{sbox:e,sbox2:o,T0:t,T1:n,T2:s,T3:r,T01:i,T23:a}}var _s=_i(wi,e=>ws(e,3)<<24|e<<16|e<<8|ws(e,2));var xi=(()=>{let e=new Uint8Array(16);for(let A=0,t=1;A<16;A++,t=Ve(t))e[A]=t;return e})();function Ei(e){Q(e);let A=e.length;if(![16,24,32].includes(A))throw new Error("aes: invalid key size, should be 16, 24 or 32, got "+A);let{sbox2:t}=_s,n=[];yt(e)||n.push(e=lA(e));let s=K(e),r=s.length,i=o=>St(t,o,o,o,o),a=new Uint32Array(A+28);a.set(s);for(let o=r;o<a.length;o++){let h=a[o-1];o%r===0?h=i(ki(h))^xi[o/r-1]:r>6&&o%r===4&&(h=i(h)),a[o]=a[o-r]^h}return F(...n),a}function ee(e,A,t,n,s,r){return e[t<<8&65280|n>>>8&255]^A[s>>>8&65280|r>>>24&255]}function St(e,A,t,n,s){return e[A&255|t&65280]|e[n>>>16&255|s>>>16&65280]<<16}function ks(e,A,t,n,s){let{sbox2:r,T01:i,T23:a}=_s,o=0;A^=e[o++],t^=e[o++],n^=e[o++],s^=e[o++];let h=e.length/4-2;for(let d=0;d<h;d++){let g=e[o++]^ee(i,a,A,t,n,s),m=e[o++]^ee(i,a,t,n,s,A),p=e[o++]^ee(i,a,n,s,A,t),y=e[o++]^ee(i,a,s,A,t,n);A=g,t=m,n=p,s=y}let l=e[o++]^St(r,A,t,n,s),u=e[o++]^St(r,t,n,s,A),c=e[o++]^St(r,n,s,A,t),f=e[o++]^St(r,s,A,t,n);return{s0:l,s1:u,s2:c,s3:f}}function ne(e,A,t,n,s){Q(t,qe),Q(n),s=gt(n.length,s);let r=t,i=K(r),a=XA(r),o=K(n),h=K(s),l=A?0:12,u=n.length,c=a.getUint32(l,A),{s0:f,s1:d,s2:g,s3:m}=ks(e,i[0],i[1],i[2],i[3]);for(let y=0;y+4<=o.length;y+=4)h[y+0]=o[y+0]^f,h[y+1]=o[y+1]^d,h[y+2]=o[y+2]^g,h[y+3]=o[y+3]^m,c=c+1>>>0,a.setUint32(l,c,A),{s0:f,s1:d,s2:g,s3:m}=ks(e,i[0],i[1],i[2],i[3]);let p=qe*Math.floor(o.length/Mi);if(p<u){let y=new Uint32Array([f,d,g,m]),S=ls(y);for(let _=p,I=0;_<u;_++,I++)s[_]=n[_]^S[I];F(y)}return s}function bi(e,A,t,n,s){let r=s?s.length:0,i=e.create(t,n.length+r);s&&i.update(s);let a=Xt(8*n.length,8*r,A);i.update(n),i.update(a);let o=i.digest();return F(a),o}var We=mt({blockSize:16,nonceLength:12,tagLength:16,varSizeNonce:!0},function(A,t,n){if(t.length<8)throw new Error("aes/gcm: invalid nonce length");let s=16;function r(a,o,h){let l=bi(Ze,!1,a,h,n);for(let u=0;u<o.length;u++)l[u]^=o[u];return l}function i(){let a=Ei(A),o=te.slice(),h=te.slice();if(ne(a,!1,h,h,o),t.length===12)h.set(t);else{let u=te.slice(),c=XA(u);qt(c,8,BigInt(t.length*8),!1);let f=Ze.create(o).update(t).update(u);f.digestInto(h),f.destroy()}let l=ne(a,!1,h,te);return{xk:a,authKey:o,counter:h,tagMask:l}}return{encrypt(a){let{xk:o,authKey:h,counter:l,tagMask:u}=i(),c=new Uint8Array(a.length+s),f=[o,h,l,u];yt(a)||f.push(a=lA(a)),ne(o,!1,l,a,c.subarray(0,a.length));let d=r(h,u,c.subarray(0,c.length-s));return f.push(d),c.set(d,a.length),F(...f),c},decrypt(a){let{xk:o,authKey:h,counter:l,tagMask:u}=i(),c=[o,h,u,l];yt(a)||c.push(a=lA(a));let f=a.subarray(0,-s),d=a.subarray(-s),g=r(h,u,f);if(c.push(g),!jt(g,d))throw new Error("aes/gcm: invalid ghash tag");let m=ne(o,!1,l,f);return F(...c),m}}});var je=new Uint8Array(12),vs=new DataView(je.buffer);function xs(e){return vs.setBigUint64(4,e,!0),je}function Es(e){return vs.setBigUint64(4,e,!1),je}var bs=(e,A)=>HA.getSharedSecret(e,A),Ts=e=>HA.getPublicKey(e),Ds=()=>{let e=HA.utils.randomSecretKey();return{privateKey:e,publicKey:HA.getPublicKey(e)}},$A={chacha:{name:"ChaChaPoly",dhLen:32,dh:bs,generateKeypair:Ds,publicKey:Ts,hash:j,aeadEncrypt:(e,A,t,n)=>Ke(e,xs(A),t).encrypt(n),aeadDecrypt:(e,A,t,n)=>Ke(e,xs(A),t).decrypt(n)},aesgcm:{name:"AESGCM",dhLen:32,dh:bs,generateKeypair:Ds,publicKey:Ts,hash:j,aeadEncrypt:(e,A,t,n)=>We(e,Es(A),t).encrypt(n),aeadDecrypt:(e,A,t,n)=>We(e,Es(A),t).decrypt(n)}},Is={chacha:"25519_ChaChaPoly_SHA256",aesgcm:"25519_AESGCM_SHA256"};function H(e){let A="";for(let t=0;t<e.length;t++)A+=String.fromCharCode(e[t]);return btoa(A).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function q(e){let A=e.replace(/-/g,"+").replace(/_/g,"/"),t=atob(A),n=new Uint8Array(t.length);for(let s=0;s<t.length;s++)n[s]=t.charCodeAt(s);return n}var Js="sendspin-identity-sk",At=class e{constructor(A,t){this.privateKey=A,this.publicKey=t,this.clientId=H(t)}get keypair(){return{privateKey:this.privateKey,publicKey:this.publicKey}}static loadOrCreate(A){let t=$A.chacha;if(A){let s=A.getItem(Js);if(s)try{let i=q(s);return new e(i,t.publicKey(i))}catch{console.warn("Sendspin: stored identity key is invalid, generating a new one")}let r=t.generateKeypair();return A.setItem(Js,H(r.privateKey)),new e(r.privateKey,r.publicKey)}console.warn("Sendspin: no storage provided, using an ephemeral identity (client_id changes each session, pairing unavailable)");let n=t.generateKeypair();return new e(n.privateKey,n.publicKey)}};var Bs=new TextEncoder,se=j(Bs.encode("sendspin-sentinel-psk-v1")),Xe=Bs.encode("sendspin-psk-id-v1");function KA(e){let A=new Uint8Array(Xe.length+e.length);return A.set(Xe,0),A.set(e,Xe.length),H(j(A))}var Da=KA(se);function Ps(){return crypto.getRandomValues(new Uint8Array(32))}var $e="sendspin-psks",An="sendspin-pairing-psk",tt=class{constructor(A){this.storage=A,this.entries=new Map,this.add({psk:se,pskId:KA(se),category:"sentinel"}),this.loadPersisted()}add(A){this.entries.set(A.pskId,A)}loadPersisted(){if(!this.storage)return;let A=this.storage.getItem($e);if(A)try{let n=JSON.parse(A);for(let s of n){let r=q(s.psk);this.add({psk:r,pskId:KA(r),category:"long_term",serverId:s.serverId})}}catch{this.storage.setItem($e,"[]")}let t=this.storage.getItem(An);if(t)try{let n=q(t);this.add({psk:n,pskId:KA(n),category:"pairing"})}catch{this.storage.setItem(An,"")}}persistLongTerm(){if(!this.storage)return;let A=[];for(let t of this.entries.values())t.category==="long_term"&&A.push({psk:H(t.psk),serverId:t.serverId});this.storage.setItem($e,JSON.stringify(A))}lookup(A){return this.entries.get(A)??null}addLongTerm(A,t){let n={psk:A,pskId:KA(A),category:"long_term",serverId:t};return this.add(n),this.persistLongTerm(),n}removeByPskId(A){let t=this.entries.get(A);!t||t.category!=="long_term"||t.serverId===void 0||(this.entries.delete(A),this.persistLongTerm())}getOrCreatePairingPsk(){for(let A of this.entries.values())if(A.category==="pairing")return A.psk;return this.setPairingPsk(Ps())}rotatePairingPsk(){for(let[A,t]of this.entries)t.category==="pairing"&&this.entries.delete(A);return this.setPairingPsk(Ps())}setPairingPsk(A){return this.add({psk:A,pskId:KA(A),category:"pairing"}),this.storage?.setItem(An,H(A)),A}};var re=class extends ZA{constructor(A,t){super(),this.finished=!1,this.destroyed=!1,Cn(A);let n=rt(t);if(this.iHash=A.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let s=this.blockLen,r=new Uint8Array(s);r.set(n.length>s?A.create().update(n).digest():n);for(let i=0;i<r.length;i++)r[i]^=54;this.iHash.update(r),this.oHash=A.create();for(let i=0;i<r.length;i++)r[i]^=106;this.oHash.update(r),SA(r)}update(A){return YA(this),this.iHash.update(A),this}digestInto(A){YA(this),W(A,this.outputLen),this.finished=!0,this.iHash.digestInto(A),this.oHash.update(A),this.oHash.digestInto(A),this.destroy()}digest(){let A=new Uint8Array(this.oHash.outputLen);return this.digestInto(A),A}_cloneInto(A){A||(A=Object.create(Object.getPrototypeOf(this),{}));let{oHash:t,iHash:n,finished:s,destroyed:r,blockLen:i,outputLen:a}=this;return A=A,A.finished=s,A.destroyed=r,A.blockLen=i,A.outputLen=a,A.oHash=t._cloneInto(A.oHash),A.iHash=n._cloneInto(A.iHash),A}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}},JA=(e,A,t)=>new re(e,A).update(t).digest();JA.create=(e,A)=>new re(e,A);var Rs=new Uint8Array(0),et=class{constructor(A){this.suite=A,this.k=null,this.n=0n}initializeKey(A){this.k=A,this.n=0n}hasKey(){return this.k!==null}encryptWithAd(A,t){if(this.k===null)return t;let n=this.suite.aeadEncrypt(this.k,this.n,A,t);return this.n+=1n,n}decryptWithAd(A,t){if(this.k===null)return t;let n=this.suite.aeadDecrypt(this.k,this.n,A,t);return this.n+=1n,n}};var Os=32;function tn(e,A,t){let n=JA(j,e,A),s=JA(j,n,Uint8Array.of(1)),r=JA(j,n,en(s,Uint8Array.of(2)));if(t===2)return[s,r];let i=JA(j,n,en(r,Uint8Array.of(3)));return[s,r,i]}function en(...e){let A=e.reduce((s,r)=>s+r.length,0),t=new Uint8Array(A),n=0;for(let s of e)t.set(s,n),n+=s.length;return t}var ie=class{constructor(A){this.suite=A,this.cipher=new et(A)}initialize(A){let t=new TextEncoder().encode(A);if(t.length<=Os){let n=new Uint8Array(Os);n.set(t),this.h=n}else this.h=this.suite.hash(t);this.ck=this.h,this.cipher.initializeKey(null)}mixHash(A){this.h=this.suite.hash(en(this.h,A))}mixKey(A){let[t,n]=tn(this.ck,A,2);this.ck=t,this.cipher.initializeKey(n.slice(0,32))}mixKeyAndHash(A){let[t,n,s]=tn(this.ck,A,3);this.ck=t,this.mixHash(n),this.cipher.initializeKey(s.slice(0,32))}encryptAndHash(A){let t=this.cipher.encryptWithAd(this.h,A);return this.mixHash(t),t}decryptAndHash(A){let t=this.cipher.decryptWithAd(this.h,A);return this.mixHash(A),t}split(){let[A,t]=tn(this.ck,Rs,2),n=new et(this.suite),s=new et(this.suite);return n.initializeKey(A.slice(0,32)),s.initializeKey(t.slice(0,32)),[n,s]}};var sn=["e","es","ss"],rn=["e","ee","se","psk"];function nn(e,A){let t=new Uint8Array(e.length+A.length);return t.set(e,0),t.set(A,e.length),t}var Mt=class{constructor(A){this.suite=A.suite,this.role=A.role,this.s=A.s,this.rs=A.rs,this.psk=A.psk,this.fixedEphemeral=A.fixedEphemeral,this.sym=new ie(A.suite),this.sym.initialize(`Noise_KKpsk2_25519_${A.suite.name}_SHA256`),this.sym.mixHash(A.prologue);let t=A.role==="initiator"?A.s.publicKey:A.rs,n=A.role==="responder"?A.s.publicKey:A.rs;this.sym.mixHash(t),this.sym.mixHash(n)}get handshakeHash(){return this.sym.h}setPsk(A){this.psk=A}dhToken(A){let t=this.role==="initiator";switch(A){case"ee":return this.suite.dh(this.e.privateKey,this.re);case"ss":return this.suite.dh(this.s.privateKey,this.rs);case"es":return t?this.suite.dh(this.e.privateKey,this.rs):this.suite.dh(this.s.privateKey,this.re);case"se":return t?this.suite.dh(this.s.privateKey,this.re):this.suite.dh(this.e.privateKey,this.rs)}}processTokenWrite(A,t){A==="e"?(this.e=this.fixedEphemeral??this.suite.generateKeypair(),this.sym.mixHash(this.e.publicKey),this.sym.mixKey(this.e.publicKey),t.buf=nn(t.buf,this.e.publicKey)):A==="s"?t.buf=nn(t.buf,this.sym.encryptAndHash(this.s.publicKey)):A==="psk"?this.sym.mixKeyAndHash(this.psk):this.sym.mixKey(this.dhToken(A))}processTokenRead(A,t){if(A==="e")this.re=t.buf.slice(0,this.suite.dhLen),t.buf=t.buf.slice(this.suite.dhLen),this.sym.mixHash(this.re),this.sym.mixKey(this.re);else if(A==="s"){let n=this.suite.dhLen+16;this.sym.decryptAndHash(t.buf.slice(0,n)),t.buf=t.buf.slice(n)}else A==="psk"?this.sym.mixKeyAndHash(this.psk):this.sym.mixKey(this.dhToken(A))}writeMessage(A,t){let n={buf:new Uint8Array(0)};for(let s of A)this.processTokenWrite(s,n);return n.buf=nn(n.buf,this.sym.encryptAndHash(t)),n.buf}readMessage(A,t){let n={buf:t};for(let s of A)this.processTokenRead(s,n);return this.sym.decryptAndHash(n.buf)}split(){return this.sym.split()}};var Ls=new Uint8Array(0),Ct=class{constructor(A,t){let[n,s]=t;A==="initiator"?(this.sendCs=n,this.recvCs=s):(this.sendCs=s,this.recvCs=n)}encrypt(A){return this.sendCs.encryptWithAd(Ls,A)}decrypt(A){return this.recvCs.decryptWithAd(Ls,A)}};function Us(e,A,t){if(e==="long_term"){if(A.has("pairing"))return A.size===1;for(let n of A)if(n!=="playback"&&n!=="management")return!1;return!0}return e==="pairing"?A.size===1&&A.has("pairing"):A.size===0||A.size===1&&A.has("pairing")?!0:A.size===1&&A.has("playback")?t:!1}function zs(e,A,t,n){if(!Us(e,A,n))return!1;if(t){let s=new Set(A);if(s.add("playback"),!Us(e,s,n))return!1}return!0}function Qs(e,A,t,n){let s=new Set(A),r=!!t&&t.length>0;return zs(e,s,r,n)?{ok:!0}:e==="sentinel"&&!n&&zs(e,s,r,!0)?{ok:!1,goodbye:"pairing_required"}:{ok:!1,goodbye:"unauthorized"}}var wt=new TextEncoder,oe=new TextDecoder,Ti=3e4,Ks=65519,Di=Ks+16,Ns=4*1024*1024;function Hs(e,A){let t=new Uint8Array(e.length+A.length);return t.set(e,0),t.set(A,e.length),t}var kt=class e{constructor(A,t,n){this.wsManager=A,this.deps=t,this.cb=n,this.state="idle",this.hs=null,this.session=null,this.matched=null,this.serverId="",this.rawClientInit=new Uint8Array(0),this.rawServerInit=new Uint8Array(0),this.timeout=null,this.frag=null,this.lastHandshakeHash=new Uint8Array(0),this.quiesced=!1,this.outboundQueue=[],this.seenActivate=!1,this.effectiveActiveRoles=void 0}get suite(){return $A[this.deps.suiteId]}get ready(){return this.state==="transport"}get handshakeInfo(){return this.matched?{trustLevel:this.matched.category==="long_term"?"user":"none",category:this.matched.category,serverId:this.serverId,entry:this.matched}:null}get handshakeHash(){return this.lastHandshakeHash}start(){this.resetSession();let A=JSON.stringify({type:"client/init",payload:{client_id:this.deps.identity.clientId,version:1,suite:Is[this.deps.suiteId]}});this.rawClientInit=wt.encode(A),this.wsManager.sendText(A),this.state="await_server_init",this.armTimeout()}resetSession(){this.hs=null,this.session=null,this.matched=null,this.frag=null,this.serverId="",this.rawServerInit=new Uint8Array(0),this.quiesced=!1,this.outboundQueue=[],this.lastHandshakeHash=new Uint8Array(0),this.seenActivate=!1,this.effectiveActiveRoles=void 0}onSocketClosed(){this.clearTimeout(),this.resetSession(),this.state="idle"}close(){this.clearTimeout(),this.wsManager.disconnect()}handleRaw(A){if(this.state==="transport"){if(typeof A.data=="string")return this.fail();let t;try{let n=new Uint8Array(A.data);if(n.length>Di)return this.fail();t=this.session.decrypt(n)}catch{return this.fail()}if(t.length<1)return this.fail();try{this.dispatchPlain(t)}catch(n){console.warn("Sendspin: dropped malformed transport message",n)}return}try{if(typeof A.data!="string")return this.fail();this.handleHandshakeText(A.data)}catch{this.fail()}}handleHandshakeText(A){let t=JSON.parse(A);if(this.state==="await_server_init"&&t.type==="server/init"){if(t.payload.version!==1)return this.fail();this.serverId=String(t.payload.server_id),this.rawServerInit=wt.encode(A),this.hs=new Mt({suite:this.suite,role:"responder",prologue:Hs(this.rawClientInit,this.rawServerInit),s:this.deps.identity.keypair,rs:q(this.serverId)}),this.state="await_noise1",this.armTimeout();return}if(this.state==="await_noise1"&&t.type==="noise/handshake"){this.processNoise1(q(String(t.payload.data)));return}this.fail()}processNoise1(A){let t=this.hs.readMessage(sn,A),{psk_id:n}=JSON.parse(oe.decode(t)),s=this.deps.pskStore.lookup(n);if(!s)return this.fail();if(s.category==="long_term"&&s.serverId!==void 0&&s.serverId!==this.serverId)return this.fail();this.hs.setPsk(s.psk);let r=this.hs.writeMessage(rn,wt.encode("{}"));this.wsManager.sendText(JSON.stringify({type:"noise/handshake",payload:{data:H(r)}})),this.session=new Ct("responder",this.hs.split()),this.matched=s,this.state="transport",this.clearTimeout(),this.lastHandshakeHash=this.hs.handshakeHash,this.cb.onHandshakeComplete(this.handshakeInfo)}dispatchPlain(A){let t=A[0];t===0?this.handleControl(JSON.parse(oe.decode(A.subarray(1)))):t===2||t===3?this.handleFragment(t,A.subarray(1)):this.cb.onBinaryMessage(A)}handleFragment(A,t){if(A===2&&this.frag===null){if(t.length<1)return this.fail();if(t[0]===2||t[0]===3)return this.fail();let i=t.subarray(1);this.frag={origType:t[0],parts:[i],size:i.length};return}if(A===2)return this.frag.parts.push(t),this.frag.size+=t.length,this.frag.size>Ns?(this.frag=null,this.fail()):void 0;if(this.frag===null)return this.fail();if(this.frag.parts.push(t),this.frag.size+=t.length,this.frag.size>Ns)return this.frag=null,this.fail();let n=this.frag.origType,s=new Uint8Array(this.frag.size+1);s[0]=n;let r=1;for(let i of this.frag.parts)s.set(i,r),r+=i.length;this.frag=null,n===0?this.handleControl(JSON.parse(oe.decode(s.subarray(1)))):this.cb.onBinaryMessage(s)}handleControl(A){if(A.type==="noise/handshake"){this.handleRehandshake(A);return}if(A.type==="server/activate"){this.handleActivate(A);return}if(A.type==="server/unpair"){this.handleUnpair();return}this.cb.onControlMessage(A)}handleRehandshake(A){let t=new Mt({suite:this.suite,role:"responder",prologue:this.lastHandshakeHash,s:this.deps.identity.keypair,rs:q(this.serverId)}),n=t.readMessage(sn,q(A.payload.data)),{psk_id:s}=JSON.parse(oe.decode(n)),r=this.deps.pskStore.lookup(s);if(!r)return this.fail();if(r.category==="long_term"&&r.serverId!==void 0&&r.serverId!==this.serverId)return this.fail();t.setPsk(r.psk);let i=t.writeMessage(rn,wt.encode("{}"));this.quiesced=!0,this.armTimeout(),this.encryptSend({type:"noise/handshake",payload:{data:H(i)}}),this.session=new Ct("responder",t.split()),this.matched=r,this.lastHandshakeHash=t.handshakeHash,this.seenActivate=!1,this.effectiveActiveRoles=void 0,this.cb.onHandshakeComplete(this.handshakeInfo)}handleActivate(A){let t=A.payload.active_roles;if(!this.seenActivate&&t===void 0){this.sendGoodbyeAndClose("unauthorized");return}t!==void 0&&(this.effectiveActiveRoles=t),this.seenActivate=!0;let n=Qs(this.matched.category,A.payload.activities,this.effectiveActiveRoles,this.deps.unpairedAccess);if(!n.ok){this.sendGoodbyeAndClose(n.goodbye);return}this.clearTimeout();let s=!A.payload.activities.includes("pairing")&&this.effectiveActiveRoles?.includes("controller@v1")?this.outboundQueue.filter(r=>r.type==="client/command"):[];this.quiesced=!1,this.outboundQueue=[],this.cb.onControlMessage(A);for(let r of s)this.encryptSend(r)}handleUnpair(){this.matched?.category==="long_term"&&(this.deps.pskStore.removeByPskId(this.matched.pskId),this.sendGoodbyeAndClose("unpaired"))}sendGoodbyeAndClose(A){try{this.encryptSend({type:"client/goodbye",payload:{reason:A}})}catch{}this.close()}sendControl(A){if(this.state!=="transport"||!this.session){console.warn("Sendspin: sendControl before transport ready");return}let t=A.type;if(this.quiesced&&t!==void 0&&e.QUIESCED_TYPES.has(t)){this.outboundQueue.push(A);return}this.encryptSend(A)}encryptSend(A){let t=wt.encode(JSON.stringify(A)),n=Hs(Uint8Array.of(0),t);if(n.length>Ks)throw new Error("Sendspin: control message exceeds single-frame limit");this.wsManager.sendBinary(this.session.encrypt(n))}armTimeout(){this.clearTimeout(),this.timeout=globalThis.setTimeout(()=>this.fail(),Ti)}clearTimeout(){this.timeout!==null&&(clearTimeout(this.timeout),this.timeout=null)}fail(){this.clearTimeout(),this.wsManager.disconnect()}};kt.QUIESCED_TYPES=new Set(["client/command","client/time","client/state"]);var dA=2n**255n-19n,on=486662n,vi=2n,ae=32,ce=32,qs=64,Fs=cn("CPace255"),Ii=cn("CPace255_ISK"),Ji=cn("CPaceMac"),Bi=128,fA=class extends Error{};function cn(e){return new TextEncoder().encode(e)}function xt(...e){let A=new Uint8Array(e.reduce((n,s)=>n+s.length,0)),t=0;for(let n of e)A.set(n,t),t+=n.length;return A}function an(e){let A=e.length,t=[];for(;t.push(A<128?A:A&127|128),A>>=7,A!==0;);return xt(new Uint8Array(t),e)}function _t(...e){return xt(...e.map(an))}function Pi(e,A,t){let n=Math.max(0,Bi-1-an(e).length-an(Fs).length);return _t(Fs,e,new Uint8Array(n),A,t)}function FA(e,A){let t=e%A;return t<0n?t+A:t}function Vs(e,A,t){let n=1n,s=FA(e,t),r=A;for(;r>0n;)r&1n&&(n=n*s%t),s=s*s%t,r>>=1n;return n}function Gs(e,A){return Vs(e,A-2n,A)}function Ri(e){let A=e.slice();A[A.length-1]&=127;let t=0n;for(let n=A.length-1;n>=0;n--)t=t<<8n|BigInt(A[n]);return t}function Oi(e){let A=new Uint8Array(ae),t=e;for(let n=0;n<ae;n++)A[n]=Number(t&0xffn),t>>=8n;return A}function Li(e){let A=FA(e,dA),t=FA(-on*Gs(FA(1n+vi*A*A,dA),dA),dA),n=Vs(FA(t*t*t+on*t*t+t,dA),(dA-1n)/2n,dA),s=FA(n*t-FA(1n-n,dA)*on*Gs(2n,dA),dA);return Oi(s)}function Ui(e,A,t){let n=UA(Pi(e,A,t)).slice(0,ae);return Li(Ri(n))}function Zs(e,A,t){let n;try{n=HA.scalarMult(e,A)}catch{throw new fA(`${t} encodes a low-order point`)}if(n.every(s=>s===0))throw new fA(`${t} encodes a low-order point`);return n}function Ys(e,A){if(e.length!==A.length)return!1;let t=0;for(let n=0;n<e.length;n++)t|=e[n]^A[n];return t===0}var Et=class e{constructor(A,t,n,s,r,i){this.role=A,this.sid=n,this.ada=s,this.adb=r,this.macKey=null,this.initiatorShare=null,this.responderShare=null,this.iskValue=null,this.scalar=t,this.publicShare=Zs(t,i,"generator")}static start(A){let t=A.scalar??crypto.getRandomValues(new Uint8Array(ae)),n=Ui(A.prs,A.ci??new Uint8Array(0),A.sid);return new e(A.role,t,A.sid,A.ada??new Uint8Array(0),A.adb??new Uint8Array(0),n)}derive(A){if(!this.scalar)throw new fA("derive() may only be called once");let t=this.scalar;if(this.scalar=null,A.length!==ce)throw new fA(`peer share must be ${ce} bytes, got ${A.length}`);let n=Zs(t,A,"peer share");this.role==="initiator"?(this.initiatorShare=this.publicShare,this.responderShare=A):(this.initiatorShare=A,this.responderShare=this.publicShare);let s=xt(_t(this.initiatorShare,this.ada),_t(this.responderShare,this.adb));this.iskValue=UA(xt(_t(Ii,this.sid,n),s)),this.macKey=UA(xt(Ji,this.sid,this.iskValue))}get isk(){if(!this.iskValue)throw new fA("derive() must be called before reading the ISK");return this.iskValue}tag(){return this.mac(!0)}verify(A){let t=this.mac(!1);return Ys(t,this.mac(!0))?!1:Ys(A,t)}mac(A){if(!this.macKey||!this.initiatorShare||!this.responderShare)throw new fA("derive() must be called before confirmation tags");let t=A===(this.role==="initiator"),n=t?this.initiatorShare:this.responderShare,s=t?this.ada:this.adb;return JA(UA,this.macKey,_t(n,s))}};var bt=new TextEncoder().encode("sendspin-pin-derive-v1"),hn=new TextEncoder().encode("sendspin-pair-commit-v1"),ln=32,Ws=4,un=12,js=6,zi=8,Qi=new RegExp(`^[0-9]{${zi}}$`);function Xs(e){return Qi.test(e)}function $s(){return crypto.getRandomValues(new Uint8Array(ln))}function Ar(e){let A=new Uint8Array(hn.length+e.length);return A.set(hn,0),A.set(e,hn.length),j(A)}function tr(e,A,t,n){let s=new Uint8Array(bt.length+e.length+A.length+t.length);s.set(bt,0),s.set(e,bt.length),s.set(A,bt.length+e.length),s.set(t,bt.length+e.length+A.length);let r=j(s),i=0n;for(let o of r)i=i<<8n|BigInt(o);return(i%10n**BigInt(n)).toString().padStart(n,"0")}var le=e=>new TextEncoder().encode(e);function Ni(...e){let A=new Uint8Array(e.reduce((n,s)=>n+s.length,0)),t=0;for(let n of e)A.set(n,t),t+=n.length;return A}var Hi="sendspin-pair-pake-v1",Ki=le("sendspin-pair-psk-wrap-v1"),er=le("server"),nr=le("client"),Fi=12e4,Gi=3e5,Zi=10,Yi=6,sr="sendspin-pair-failures",qi=["dynamic_pin","static_pin"];function rr(e,A){return A?.length?{...e,locations:A}:e}function Vi(e){if(!(!Array.isArray(e)||e.length===0))return e.every(A=>typeof A=="string"&&A!=="")?e:void 0}var he=class{constructor(A){if(this.deps=A,this.pendingPsk=null,this.phase="idle",this.method=null,this.cpace=null,this.nonceB=null,this.attemptTimer=null,this.windowTimer=null,this.windowOpen=!1,this.currentSid=null,this.pairingActivateCount=0,this.attemptIndex=0,this.pinLength=null,A.staticPin!==void 0&&!Xs(A.staticPin))throw new Error("staticPin must be exactly 8 decimal digits");this.minPinLength=Math.min(un,Math.max(Ws,A.minPinLength??js)),!A.storage&&A.onPin&&console.warn("sendspin: dynamic PIN pairing is enabled without storage, so the failure counter will not persist across reboots."),this.failures=this.loadFailures()}descriptors(){let A=[rr({method:"pairing_psk"},this.deps.pairingPskLocations)];return this.deps.staticPin!==void 0&&A.push(rr({method:"static_pin"},this.deps.staticPinLocations)),this.deps.onPin&&A.push({method:"dynamic_pin",out_channels:this.deps.pinOutChannels??["display"],min_pin_length:this.minPinLength}),A}isDynamicPinEscalated(){return this.failures>=Zi}openPairingWindow(){if(this.phase==="await-window"){this.startAttempt();return}this.windowOpen=!0,this.windowTimer&&clearTimeout(this.windowTimer),this.windowTimer=setTimeout(()=>this.closeWindow(),Gi)}closeWindow(){this.windowOpen=!1,this.windowTimer&&clearTimeout(this.windowTimer),this.windowTimer=null}cancelPairing(){this.phase!=="idle"&&this.abort("user_cancelled")}onActivate(A,t){if(!A.includes("pairing"))return this.abandonAttempt("server_cancelled"),!1;this.abandonAttempt("superseded"),this.pairingActivateCount+=1,this.attemptIndex=this.pairingActivateCount;let s=t?.method,r=this.descriptors().map(a=>a.method),i=s==="pairing_psk"==(this.deps.matchedCategory()==="pairing");if(!s)return console.warn("sendspin: server/activate carried no pairing method, so the server is not speaking the current specification."),this.fail(),!0;if(!i||!r.includes(s))return this.abort("method_not_supported"),!0;if(this.method=s,s==="pairing_psk")return this.sendFinalize(),this.phase="await-finalize",this.armAttemptTimer(),this.deps.onEvent?.("started"),!0;if(s==="dynamic_pin"){let a=t.pin_length;if(typeof a!="number"||!Number.isInteger(a))return this.fail(),!0;if(a<this.minPinLength||a>un)return this.abort("pin_length_unacceptable"),!0;this.pinLength=a,this.languages=Vi(t.languages)}return this.isGestureGated()&&!this.windowOpen?(this.phase="await-window",this.deps.sendControl({type:"client/pair-pending",payload:{pairing_index:this.attemptIndex}}),this.deps.onEvent?.("pending"),!0):(this.startAttempt(),!0)}isGestureGated(){return this.method==="static_pin"?!0:this.method!=="dynamic_pin"?!1:this.isDynamicPinEscalated()||this.pinLength<Yi}onPairInit(A){if(this.phase==="idle")return;if(this.phase!=="await-init"||this.method!=="dynamic_pin")return this.fail();let t=this.decode(A.nonce_A,ln);if(!t)return this.fail();let n=this.deps.handshakeHash(),s=tr(n,t,this.nonceB,this.pinLength);this.currentSid=this.sid(n,this.attemptIndex),this.cpace=Et.start({role:"responder",prs:new TextEncoder().encode(s),sid:this.currentSid,ada:er,adb:nr}),this.phase="await-auth",this.deps.onPin?.(s,this.languages)}onPairAuth(A){if(this.phase==="idle")return;if(this.phase!=="await-auth"||!this.cpace)return this.fail();let t=this.decode(A.pake_msg_1,ce);if(!t)return this.fail();this.deps.sendControl({type:"client/pair-auth",payload:{pake_msg_2:H(this.cpace.publicShare)}});try{this.cpace.derive(t)}catch(n){if(n instanceof fA)return this.fail();throw n}this.phase="await-confirm"}onPairConfirm(A){if(this.phase==="idle")return;if(this.phase!=="await-confirm"||!this.cpace)return this.fail();let t=this.decode(A.server_kc,qs);if(!t)return this.fail();if(!this.cpace.verify(t))return this.method==="dynamic_pin"&&this.recordFailure(),this.abort("pin_mismatch");this.method==="dynamic_pin"&&this.resetFailures();let n={client_kc:H(this.cpace.tag())};this.method==="dynamic_pin"&&(n.nonce_B=H(this.nonceB)),this.deps.sendControl({type:"client/pair-confirm",payload:n}),this.phase="await-finalize",this.sendFinalize()}onPairFinalize(){this.pendingPsk&&(this.deps.pskStore.addLongTerm(this.pendingPsk,this.deps.serverId()),this.clearAttempt(),this.deps.onEvent?.("finalized"))}onAbort(A){this.phase==="idle"&&!this.pendingPsk||(this.clearAttempt(),this.deps.onEvent?.("aborted",A))}reset(){this.clearAttempt(),this.pairingActivateCount=0,this.attemptIndex=0}startAttempt(){if(this.closeWindow(),this.armAttemptTimer(),this.deps.onEvent?.("started"),this.method==="dynamic_pin"){this.nonceB=$s(),this.phase="await-init",this.deps.sendControl({type:"client/pair-init",payload:{pairing_index:this.attemptIndex,commit_B:H(Ar(this.nonceB))}});return}let A=this.deps.handshakeHash();this.currentSid=this.sid(A,this.attemptIndex),this.cpace=Et.start({role:"responder",prs:new TextEncoder().encode(this.deps.staticPin),sid:this.currentSid,ada:er,adb:nr}),this.phase="await-auth",this.deps.sendControl({type:"client/pair-init",payload:{pairing_index:this.attemptIndex}})}sendFinalize(){let A=crypto.getRandomValues(new Uint8Array(32));if(this.pendingPsk=A,this.cpace&&this.currentSid){let t=j(Ni(Ki,this.currentSid,this.cpace.isk)),n=this.deps.aeadSeal(t,A);this.deps.sendControl({type:"client/pair-finalize",payload:{wrapped_psk:H(n)}});return}this.deps.sendControl({type:"client/pair-finalize",payload:{long_term_psk:H(A)}})}sid(A,t){let n=le(Hi),s=new Uint8Array(n.length+A.length+4);return s.set(n,0),s.set(A,n.length),new DataView(s.buffer).setUint32(n.length+A.length,t,!1),s}armAttemptTimer(){this.attemptTimer=setTimeout(()=>this.abort("attempt_timeout"),Fi)}abort(A){this.clearAttempt(),this.deps.sendControl({type:"pair/abort",payload:{reason:A}}),this.deps.onEvent?.("aborted",A),A==="concurrent_attempt"&&this.deps.close()}fail(){this.clearAttempt(),this.deps.close()}clearAttempt(){this.attemptTimer&&clearTimeout(this.attemptTimer),this.attemptTimer=null,this.method&&qi.includes(this.method)&&this.deps.onPin?.(null),this.pendingPsk=null,this.phase="idle",this.method=null,this.cpace=null,this.currentSid=null,this.nonceB=null,this.pinLength=null,this.languages=void 0}abandonAttempt(A){this.phase==="idle"&&!this.pendingPsk||(this.clearAttempt(),this.deps.onEvent?.("aborted",A))}decode(A,t){if(typeof A!="string")return null;try{let n=q(A);return n.length===t?n:null}catch{return null}}loadFailures(){try{let A=this.deps.storage?.getItem(sr);return A?JSON.parse(A).dynamic_pin??0:0}catch{return 0}}saveFailures(){this.deps.storage?.setItem(sr,JSON.stringify({dynamic_pin:this.failures}))}recordFailure(){this.failures+=1,this.saveFailures()}resetFailures(){this.failures=0,this.saveFailures()}};var ir="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",ue=32;function Wi(e){let A=0,t=0,n="";for(let s of e){for(t=t<<8|s,A+=8;A>=5;)n+=ir[t>>>A-5&31],A-=5;t&=(1<<A)-1}return A>0&&(n+=ir[t<<5-A&31]),n}function de(e,A){let t=q(e),n=q(A);if(t.length!==ue)throw new Error(`clientId must decode to ${ue} bytes`);if(n.length!==ue)throw new Error(`pairingPsk must decode to ${ue} bytes`);let s=new Uint8Array(t.length+n.length);return s.set(t),s.set(n,t.length),`SP:0${Wi(s).replace(/2/g,"9")}`}var Tt=class{constructor(A){this.handshakeInfo=null,A.codecs&&It(A.codecs),this.hasStorage=(A.storage??null)!==null,this.identity=At.loadOrCreate(A.storage??null);let t=A.clientName??`Sendspin JS Client (${this.identity.clientId.slice(0,6)})`;this.config={...A,clientName:t},this.delayStore=new Ot(A.storage??null);let n=this.delayStore.load(),s=A.syncDelay??n??A.defaultSyncDelay??0;this._syncDelayMs=gA(s),this.timeFilter=new nt(0,1.1,2,1e-12),this.stateManager=new Pt(A.onStateChange),this.decoder=new GA(i=>this._onAudioData?.(i),()=>this.stateManager.streamGeneration),this.wsManager=new Rt(A.reconnect),this.pskStore=new tt(A.storage??null);for(let i of A.longTermPsks??[])this.pskStore.addLongTerm(q(i.psk),i.serverId);this.hasStorage&&this.pskStore.getOrCreatePairingPsk(),this.transport=new kt(this.wsManager,{identity:this.identity,pskStore:this.pskStore,suiteId:A.suite??"chacha",unpairedAccess:A.unpairedAccess??!0},{onHandshakeComplete:i=>{let a=this.handshakeInfo!==null;this.handshakeInfo=i,this.pairing.reset(),this.protocolHandler.resetActivation(a)},onControlMessage:i=>this.routeControl(i),onBinaryMessage:i=>this.handleBinaryMessage(i.buffer)}),this.pairing=new he({sendControl:i=>this.transport.sendControl(i),close:()=>this.transport.close(),pskStore:this.pskStore,serverId:()=>this.handshakeInfo?.serverId??"",matchedCategory:()=>this.handshakeInfo?.category??"sentinel",handshakeHash:()=>this.transport.handshakeHash,aeadSeal:(i,a)=>$A[A.suite??"chacha"].aeadEncrypt(i,0n,new Uint8Array(0),a),storage:A.storage??null,onPin:A.onPairingPin??null,pinOutChannels:A.pinOutChannels,minPinLength:A.minPinLength,staticPin:A.staticPin,staticPinLocations:A.staticPinLocations,pairingPskLocations:A.pairingPskLocations,onEvent:(i,a)=>this.config.onPairing?.(i,a)});let r={trustLevel:()=>this.handshakeInfo?.trustLevel??"none",pairMethods:()=>this.hasStorage?this.pairing.descriptors():[],unpairedAccess:A.unpairedAccess??!0};this.protocolHandler=new Bt(this.transport,r,this,this.stateManager,this.timeFilter,{clientName:t,productName:A.productName,codecs:A.codecs,bufferCapacity:A.bufferCapacity,requiredLeadTimeMs:A.requiredLeadTimeMs,minBufferMs:A.minBufferMs,useHardwareVolume:A.useHardwareVolume,onVolumeCommand:A.onVolumeCommand,onDelayCommand:A.onDelayCommand,getExternalVolume:A.getExternalVolume})}routeControl(A){if(A.type==="server/activate"){let t=A.payload??{};t.activities?.includes("pairing")&&this.protocolHandler.suspendForPairing(),this.pairing.onActivate(t.activities??[],t.pairing)||this.protocolHandler.handleServerMessage(A);return}if(A.type==="server/pair-init")return this.pairing.onPairInit(A.payload??{});if(A.type==="server/pair-auth")return this.pairing.onPairAuth(A.payload??{});if(A.type==="server/pair-confirm")return this.pairing.onPairConfirm(A.payload??{});if(A.type==="server/pair-finalize")return this.pairing.onPairFinalize();if(A.type==="pair/abort")return this.pairing.onAbort((A.payload??{}).reason??"");this.protocolHandler.handleServerMessage(A)}onTransportClose(){this.transport.onSocketClosed(),this.handshakeInfo=null,this.protocolHandler.stopTimeSync(),this.protocolHandler.resetActivation(),this.pairing.reset(),this.stateManager.clearStateUpdateInterval(),console.log("Sendspin: Connection closed"),this._onConnectionClose?.()}handleBinaryMessage(A){let t=this.stateManager.currentStreamFormat;if(!t){console.warn("Sendspin: Received audio chunk but no stream format set");return}let n=this.stateManager.streamGeneration;this.decoder.handleBinaryMessage(A,t,n)}handleStreamStart(A,t){t||this.decoder.clearState(),this._onStreamStart?.(A,t)}handleStreamClear(){this.decoder.clearState(),this._onStreamClear?.()}handleStreamEnd(){this.decoder.clearState(),this._onStreamEnd?.()}handleVolumeUpdate(){this._onVolumeUpdate?.()}applyDelay(A){this._syncDelayMs=gA(A),this.delayStore.save(this._syncDelayMs),this._onSyncDelayChange?.(this._syncDelayMs)}handleSyncDelayChange(A){this.applyDelay(A)}getSyncDelayMs(){return this._syncDelayMs}set onAudioData(A){this._onAudioData=A}set onStreamStart(A){this._onStreamStart=A}set onStreamClear(A){this._onStreamClear=A}set onStreamEnd(A){this._onStreamEnd=A}set onVolumeUpdate(A){this._onVolumeUpdate=A}set onSyncDelayChange(A){this._onSyncDelayChange=A}set onConnectionOpen(A){this._onConnectionOpen=A}set onConnectionClose(A){this._onConnectionClose=A}async connect(){let A=()=>{this._onConnectionOpen?.(),this.transport.start()},t=r=>{this.transport.handleRaw(r)},n=r=>{console.error("Sendspin: WebSocket error",r)},s=()=>this.onTransportClose();if(this.config.webSocket)await this.wsManager.adopt(this.config.webSocket,A,t,n,s);else{if(!this.config.baseUrl)throw new Error("SendspinCore requires either baseUrl or webSocket to be provided.");let r=new URL(this.config.baseUrl,typeof window<"u"?window.location.href:void 0),i=r.protocol==="https:"?"wss:":"ws:",a=r.pathname.replace(/\/$/,""),o=a.endsWith("/sendspin")?`${i}//${r.host}${a}`:`${i}//${r.host}${a}/sendspin`;await this.wsManager.connect(o,A,t,n,s)}}resetPlaybackState(){this.stateManager.isPlaying=!1,this.stateManager.currentStreamFormat=null}disconnect(A="restart"){this.transport.ready&&this.protocolHandler.sendGoodbye(A),this.protocolHandler.stopTimeSync(),this.stateManager.clearAllIntervals(),this.wsManager.disconnect(),this.decoder.close(),this.timeFilter.reset(),this.stateManager.reset()}setVolume(A){this.stateManager.volume=A,this._onVolumeUpdate?.(),this.protocolHandler.sendStateUpdate()}setMuted(A){this.stateManager.muted=A,this._onVolumeUpdate?.(),this.protocolHandler.sendStateUpdate()}setSyncDelay(A){this.applyDelay(A),this.protocolHandler.sendStateUpdate()}setRequiredLeadTimeMs(A){this.protocolHandler.setRequiredLeadTimeMs(A)}setMinBufferMs(A){this.protocolHandler.setMinBufferMs(A)}sendCommand(A,t){let n=this.stateManager.serverState.controller?.supported_commands;if(n&&!n.includes(A))throw new Error(`Command '${A}' is not supported by the server. Supported commands: ${n.join(", ")}`);this.protocolHandler.sendCommand(A,t)}get isPlaying(){return this.stateManager.isPlaying}get volume(){return this.stateManager.volume}get muted(){return this.stateManager.muted}get playerState(){return this.stateManager.playerState}get currentFormat(){return this.stateManager.currentStreamFormat}get isConnected(){return this.wsManager.isConnected()}get clientId(){return this.identity.clientId}get pairingPsk(){return this.hasStorage?H(this.pskStore.getOrCreatePairingPsk()):null}get pairingToken(){let A=this.pairingPsk;return A?de(this.clientId,A):null}rotatePairingPsk(){return this.hasStorage?(this.pskStore.rotatePairingPsk(),this.pairingPsk):null}openPairingWindow(){this.pairing.openPairingWindow()}cancelPairing(){this.pairing.cancelPairing()}isDynamicPinEscalated(){return this.pairing.isDynamicPinEscalated()}get timeSyncInfo(){return{synced:this.timeFilter.is_synchronized,offset:Math.round(this.timeFilter.offset/1e3),error:Math.round(this.timeFilter.error/1e3)}}getCurrentServerTimeUs(){return this.timeFilter.computeServerTime(Math.floor(performance.now()*1e3))}get trackProgress(){let A=this.stateManager.serverState.metadata;if(!A?.progress||A.timestamp===void 0)return null;let n=this.getCurrentServerTimeUs()-A.timestamp,s=A.progress.track_progress+n*A.progress.playback_speed/1e6,r=A.progress.track_duration;return{positionMs:r===0?Math.max(0,s):Math.max(0,Math.min(s,r)),durationMs:r,playbackSpeed:A.progress.playback_speed/1e3}}get _stateManager(){return this.stateManager}get _timeFilter(){return this.timeFilter}};var Dt=8,ji=1,Xi=Math.min(1,2*ji/Dt),$i=new Float32Array(Dt);for(let e=0;e<Dt;e++)$i[e]=(Dt-e)/(Dt+1)*Xi;var or;(function(e){e.CLIENT_HELLO="client/hello",e.SERVER_HELLO="server/hello",e.CLIENT_TIME="client/time",e.SERVER_TIME="server/time",e.CLIENT_STATE="client/state",e.SERVER_STATE="server/state",e.CLIENT_COMMAND="client/command",e.CLIENT_GOODBYE="client/goodbye",e.SERVER_COMMAND="server/command",e.STREAM_START="stream/start",e.STREAM_CLEAR="stream/clear",e.STREAM_REQUEST_FORMAT="stream/request-format",e.STREAM_END="stream/end",e.GROUP_UPDATE="group/update",e.CLIENT_INIT="client/init",e.SERVER_INIT="server/init",e.NOISE_HANDSHAKE="noise/handshake",e.SERVER_ACTIVATE="server/activate",e.CLIENT_PAIR_PENDING="client/pair-pending",e.CLIENT_PAIR_INIT="client/pair-init",e.SERVER_PAIR_INIT="server/pair-init",e.SERVER_PAIR_AUTH="server/pair-auth",e.CLIENT_PAIR_AUTH="client/pair-auth",e.SERVER_PAIR_CONFIRM="server/pair-confirm",e.CLIENT_PAIR_CONFIRM="client/pair-confirm",e.CLIENT_PAIR_FINALIZE="client/pair-finalize",e.SERVER_PAIR_FINALIZE="server/pair-finalize",e.PAIR_ABORT="pair/abort",e.SERVER_UNPAIR="server/unpair"})(or||(or={}));function ar(e){let A=null;e!==void 0?A=e:typeof localStorage<"u"&&(A=localStorage);let t=At.loadOrCreate(A),n=A?H(new tt(A).getOrCreatePairingPsk()):null;return{clientId:t.clientId,pairingPsk:n,pairingToken:n?de(t.clientId,n):null}}export{Tt as SendspinCore,GA as SendspinDecoder,ar as loadSendspinClientIdentity};
|
|
/*! Bundled license information:
|
|
|
|
@noble/hashes/esm/utils.js:
|
|
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
|
|
@noble/curves/esm/utils.js:
|
|
@noble/curves/esm/abstract/modular.js:
|
|
@noble/curves/esm/abstract/curve.js:
|
|
@noble/curves/esm/abstract/edwards.js:
|
|
@noble/curves/esm/abstract/montgomery.js:
|
|
@noble/curves/esm/ed25519.js:
|
|
(*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
|
|
|
|
@noble/ciphers/esm/utils.js:
|
|
(*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) *)
|
|
*/
|