@indiegems/gem-web-sdk 10.2.0 → 10.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,3 @@
1
- globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:10.2.0]";var f="gem-web-bridge",Z={min:1,max:1},fe=65536,Nn=8,et=5e3,Un=1024,jt=1e4;function Nt(n){return Object.freeze(Object.assign(Object.create(null),n))}var tt=Nt({"gem.handshake":30,"gem.handshake.accept":5,"gem.token":30,"gem.token.denied":30,"gem.player":12,"gem.pause":120,"gem.prefs":60,"gem.cohorts":12,"gem.earnAllowanceChanged":30,"gem.viewport":60,"gem.deviceSettings":12,"gem.willTerminate":10,"gem.roomEvent":120,"gem.socketState":12,"gem.seatedEvent":60,"gem.autoStartFailedEvent":30,"gem.signalEvent":1800,"gem.dedicatedEvent":120,"gem.partyResult":30,"gem.clusterTarget":12,"gem.devtools":30,"gem.screenshot":6,"gem.screenshot.denied":12,"gem.requestContext":12,"gem.gameContext":12,"gem.signal":1200,"gem.dedicatedOffer":60,"gem.partyRequest":12,"gem.ready":5,"gem.engaged":5,"gem.progress":600,"gem.requestToken":12,"gem.requestLocalServer":6,"gem.localServer":30,"gem.localServer.denied":30,"gem.exit":5,"gem.openExternal":6,"gem.requestFullscreen":30,"gem.audioState":120,"gem.rewardCue":60,"gem.walletDisplay":60,"gem.menu":60,"gem.menuSelect":60,"gem.requestShare":6,"gem.requestAvatarPicker":6,"gem.vibrate":600,"gem.frameStats":120,"gem.portraitBorders":60,"gem.error":60,"gem.requestPurchase":12,"gem.purchaseResult":30,"gem.deviceSettings.put":30,"gem.deviceSettings.result":30,"gem.requestAd":6,"gem.adResult":12,"gem.requestSignIn":6,"gem.signInResult":12,"gem.requestFriendChallenge":12,"gem.friendChallengeResult":30,__malformed:60}),ye="__malformed",Ba=["gem.handshake","gem.token","gem.token.denied","gem.player","gem.pause","gem.prefs","gem.cohorts","gem.earnAllowanceChanged","gem.viewport","gem.deviceSettings","gem.willTerminate","gem.roomEvent","gem.socketState","gem.seatedEvent","gem.autoStartFailedEvent","gem.signalEvent","gem.dedicatedEvent","gem.partyResult","gem.clusterTarget","gem.devtools","gem.screenshot","gem.requestContext","gem.localServer","gem.localServer.denied","gem.menuSelect","gem.error","gem.purchaseResult","gem.deviceSettings.result","gem.adResult","gem.signInResult","gem.friendChallengeResult"],Wa=["gem.handshake.accept","gem.screenshot.denied","gem.gameContext","gem.signal","gem.dedicatedOffer","gem.partyRequest","gem.ready","gem.engaged","gem.progress","gem.requestToken","gem.requestLocalServer","gem.exit","gem.openExternal","gem.requestFullscreen","gem.audioState","gem.rewardCue","gem.walletDisplay","gem.menu","gem.requestShare","gem.requestAvatarPicker","gem.vibrate","gem.frameStats","gem.portraitBorders","gem.error","gem.requestPurchase","gem.deviceSettings.put","gem.requestAd","gem.requestSignIn","gem.requestFriendChallenge"],yi=Nt({"gem.requestAd":"ads","gem.adResult":"ads","gem.requestSignIn":"signIn","gem.signInResult":"signIn","gem.requestPurchase":"purchases","gem.purchaseResult":"purchases","gem.requestFriendChallenge":"friendChallenges","gem.friendChallengeResult":"friendChallenges","gem.devtools":"devtools","gem.screenshot":"screenshot","gem.screenshot.denied":"screenshot","gem.requestContext":"feedbackContext","gem.gameContext":"feedbackContext","gem.roomEvent":"rooms","gem.signal":"p2p","gem.signalEvent":"p2p","gem.dedicatedOffer":"dedicated","gem.dedicatedEvent":"dedicated","gem.clusterTarget":"clusterTarget","gem.partyRequest":"parties","gem.partyResult":"parties","gem.autoStartFailedEvent":"autoStartFailure","gem.seatedEvent":"partySeating","gem.socketState":"socketState","gem.audioState":"audioState","gem.rewardCue":"rewardCue","gem.frameStats":"frameStats","gem.portraitBorders":"portraitBorders","gem.engaged":"engagement","gem.viewport":"viewport","gem.walletDisplay":"walletDisplay","gem.requestLocalServer":"localHost","gem.localServer":"localHost","gem.localServer.denied":"localHost","gem.cohorts":"cohorts","gem.earnAllowanceChanged":"earnAllowance","gem.deviceSettings":"deviceSettings","gem.deviceSettings.put":"deviceSettings","gem.deviceSettings.result":"deviceSettings","gem.requestShare":"share","gem.requestAvatarPicker":"avatarPicker","gem.vibrate":"vibration","gem.menu":"gameMenu","gem.menuSelect":"gameMenu"}),bi=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"]]);function nt(n){let e=yi[n];if(e!==void 0)return e;for(let[t,r]of bi)if(n.startsWith(t))return r}function rt(n){let e=/^([a-z][a-z0-9+.-]*):\/\/([a-z0-9.-]+|\[[0-9a-f:.]+\])(:([0-9]{1,5}))?$/i.exec(n);return e===null?false:e[4]===void 0||Number(e[4])<=65535}function _i(n){let e;try{e=new URL(n);}catch{return false}return e.username!==""||e.password!==""?false:e.protocol==="https:"?true:e.protocol==="http:"&&(e.hostname==="localhost"||e.hostname==="127.0.0.1")}function vi(n){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(n)}function wi(n){return /^[a-z_]+$/.test(n)}function Ft(n,e,t){if(e>Nn)return `nesting deeper than ${Nn}`;if(++t.nodes>et)return `more than ${et} values`;if(t.bytes>fe)return `over the ${fe} byte limit`;if(n==null)return t.bytes+=4,null;let r=typeof n;if(r==="boolean")return t.bytes+=5,null;if(r==="number")return t.bytes+=8,null;if(r==="string")return t.bytes+=n.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let i=n;if(t.seen.has(i))return "a repeated or cyclic object reference";if(t.seen.add(i),Array.isArray(n)){if(n.length>Un)return `an array of ${n.length} entries, over the ${Un} limit`;t.bytes+=2;for(let s of n){let l=Ft(s,e+1,t);if(l)return l}return null}let o=Object.getPrototypeOf(n);if(o!==Object.prototype&&o!==null)return "a value that is not a plain object";t.bytes+=2;let a=n;for(let s in a){if(!Object.prototype.hasOwnProperty.call(a,s))continue;if(++t.nodes>et)return `more than ${et} values`;if(t.bytes+=s.length*3+4,t.bytes>fe)return `over the ${fe} byte limit`;let l=Ft(a[s],e+1,t);if(l)return l}return null}function ki(n){let e={nodes:0,bytes:0,seen:new Set},t=Ft(n,0,e);return t?`message contains ${t}`:e.bytes>fe?`message is over the ${fe} byte limit`:null}var Ri={origin:[rt,"not a well-formed origin"],url:[_i,"not a safe absolute http(s) URL"],bcp47:[vi,"not a well-formed BCP 47 tag"],code:[wi,"not a code of lower-case letters and underscores"]};function Bn(n,e,t){for(let r of e){let i=t===""?r.n:`${t}.${r.n}`,o=n[r.n];if(o==null){if(r.o)continue;return `${i}: required`}let a=Wn(o,r,i);if(a)return a}return null}function Wn(n,e,t){switch(e.k){case "s":{if(typeof n!="string")return `${t}: expected string`;if(n.length>e.max)return `${t}: exceeds ${e.max} characters`;if(e.f){let[r,i]=Ri[e.f];if(!r(n))return `${t}: ${i}`}return null}case "i":return typeof n!="number"||!Number.isInteger(n)?`${t}: expected integer`:n<e.lo||n>e.hi?`${t}: out of range ${e.lo}..${e.hi}`:null;case "b":return typeof n=="boolean"?null:`${t}: expected boolean`;case "e":{let r=e.v;return r.includes(n)?null:`${t}: not one of ${r.join("|")}`}case "o":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected object`:Bn(n,e.fs,t);case "j":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected a plain object`:null;case "a":{if(!Array.isArray(n))return `${t}: expected array`;if(n.length>e.max)return `${t}: exceeds ${e.max} items`;let r=e.it,i=`${t}[]`;for(let o of n){if(o==null){if(r.o)continue;return `${i}: required`}let a=Wn(o,r,i);if(a)return a}return null}default:{let r=e.k;return `${t}: unknown kind ${String(r)}`}}}function y(n,e){return t=>{let r=ki(t);if(r)return r;if(typeof t!="object"||t===null||Array.isArray(t))return "message: expected object";let i=t;return i.gem!==f?"gem: wrong protocol marker":i.type!==n?`type: expected ${n}`:Bn(i,e,"")}}var Si=y("gem.handshake",[{n:"versions",k:"o",fs:[{n:"min",k:"i",lo:1,hi:1e3},{n:"max",k:"i",lo:1,hi:1e3}]},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}},{n:"embedder",k:"s",max:2048,f:"origin"},{n:"unbidden",k:"b",o:1}]),xi=y("gem.handshake.accept",[{n:"v",k:"i",lo:1,hi:1e3},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}}]),Ai=y("gem.token",[{n:"token",k:"s",max:4096},{n:"requestId",k:"s",o:1,max:64},{n:"generation",k:"i",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"s",o:1,max:512,f:"url"},{n:"playerId",k:"s",max:64},{n:"gameId",k:"s",max:64},{n:"channel",k:"e",v:["dev","test","release"]},{n:"gameVersion",k:"s",o:1,max:64},{n:"expiresAt",k:"i",lo:0,hi:4102444800},{n:"chainEndsAt",k:"i",lo:0,hi:4102444800},{n:"allowDevTools",k:"b",o:1}]),Pi=y("gem.token.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:36e5},{n:"reason",k:"e",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"s",max:64}]),Ei=y("gem.player",[{n:"untrusted",k:"o",fs:[{n:"displayName",k:"s",max:64},{n:"displayTag",k:"s",o:1,max:80},{n:"displayHandle",k:"s",max:80}]},{n:"playerId",k:"s",o:1,max:64},{n:"discriminator",k:"s",o:1,max:8},{n:"avatarIconUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatarIconId",k:"s",o:1,max:64},{n:"badges",k:"a",o:1,max:2,it:{n:"",k:"o",fs:[{n:"itemId",k:"s",max:64},{n:"iconUrl",k:"s",max:2048,f:"url"}]}},{n:"displayTag",k:"s",max:8},{n:"avatarUrl",k:"s",o:1,max:2048,f:"url"},{n:"boost",k:"o",o:1,fs:[{n:"multipliers",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"currencyId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"multiplierBp",k:"i",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"i",o:1,lo:1,hi:7}]}]),Ti=y("gem.pause",[{n:"paused",k:"b"}]),Ii=y("gem.prefs",[{n:"reducedMotion",k:"b"},{n:"muted",k:"b"},{n:"showFrameStats",k:"b",o:1},{n:"locale",k:"s",max:35,f:"bcp47"},{n:"recommended",k:"o",o:1,fs:[{n:"volume",k:"i",lo:0,hi:100},{n:"batterySaver",k:"b"},{n:"keyboardLayout",k:"e",v:["wasd","arrows"]},{n:"gamepadConfirm",k:"e",v:["south","east"]},{n:"vibration",k:"b"}]}]),Ci=y("gem.cohorts",[{n:"cohorts",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"experimentId",k:"s",max:36},{n:"variantKey",k:"s",max:32}]}}]),Mi=y("gem.earnAllowanceChanged",[]),Oi=y("gem.viewport",[{n:"insets",k:"o",fs:[{n:"top",k:"i",lo:0,hi:4096},{n:"right",k:"i",lo:0,hi:4096},{n:"bottom",k:"i",lo:0,hi:4096},{n:"left",k:"i",lo:0,hi:4096}]},{n:"reserved",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384},{n:"width",k:"i",lo:0,hi:16384},{n:"height",k:"i",lo:0,hi:16384}]}}]),Li=y("gem.deviceSettings",[{n:"settings",k:"j",o:1}]),Gi=y("gem.willTerminate",[{n:"reason",k:"e",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"i",lo:0,hi:6e4}]),Di=y("gem.roomEvent",[{n:"event",k:"e",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"s",max:64},{n:"matchId",k:"s",o:1,max:64},{n:"version",k:"i",o:1,lo:0,hi:2147483647},{n:"reason",k:"s",o:1,max:64},{n:"platform",k:"e",o:1,v:["universal","mobile"]}]),qi=y("gem.socketState",[{n:"connected",k:"b"},{n:"reason",k:"e",o:1,v:["connecting","dropped","watchdog","terminal"]}]),$i=y("gem.seatedEvent",[{n:"roomId",k:"s",max:64}]),Fi=y("gem.autoStartFailedEvent",[{n:"roomId",k:"s",max:64},{n:"code",k:"s",max:64}]),ji=y("gem.signalEvent",[{n:"event",k:"e",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}]),Ni=y("gem.dedicatedEvent",[{n:"event",k:"e",v:["answer","error","matchEnded"]},{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",o:1,max:10240},{n:"sessionId",k:"s",o:1,max:64},{n:"code",k:"s",o:1,max:64},{n:"message",k:"s",o:1,max:256},{n:"reason",k:"s",o:1,max:64}]),Ui=y("gem.partyResult",[{n:"requestId",k:"s",max:64},{n:"partyId",k:"s",o:1,max:64}]),Bi=y("gem.clusterTarget",[{n:"clusterTargetId",k:"s",max:64},{n:"clusterTargetIds",k:"a",o:1,max:3,it:{n:"",k:"s",max:64}}]),Wi=y("gem.devtools",[{n:"action",k:"e",v:["open","close","toggle"]}]),Vi=y("gem.screenshot",[{n:"maxWidth",k:"i",lo:1,hi:7680},{n:"maxHeight",k:"i",lo:1,hi:4320}]),Hi=y("gem.screenshot.denied",[{n:"reason",k:"e",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"b"}]),Ki=y("gem.requestContext",[]),Ji=y("gem.gameContext",[{n:"context",k:"j"}]),zi=y("gem.signal",[{n:"signal",k:"e",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}]),Xi=y("gem.dedicatedOffer",[{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",max:10240},{n:"intent",k:"e",v:["initial","ice_restart","full_reconnect"]}]),Yi=y("gem.partyRequest",[{n:"requestId",k:"s",max:64}]),Qi=y("gem.ready",[]),Zi=y("gem.engaged",[]),eo=y("gem.progress",[{n:"loaded",k:"i",lo:0,hi:1099511627776},{n:"total",k:"i",lo:0,hi:1099511627776}]),to=y("gem.requestToken",[{n:"requestId",k:"s",max:64},{n:"reason",k:"e",v:["initial","expiring","rejected"]}]),no=y("gem.requestLocalServer",[{n:"requestId",k:"s",max:64},{n:"gameRoomId",k:"s",max:64}]),ro=y("gem.localServer",[{n:"requestId",k:"s",max:64},{n:"serverId",k:"s",o:1,max:128}]),io=y("gem.localServer.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"reason",k:"e",v:["refused","unavailable"]}]),oo=y("gem.exit",[{n:"reason",k:"s",o:1,max:64}]),so=y("gem.openExternal",[{n:"url",k:"s",max:2048,f:"url"}]),ao=y("gem.requestFullscreen",[{n:"enabled",k:"b"}]),lo=y("gem.audioState",[{n:"muted",k:"b"}]),co=y("gem.rewardCue",[{n:"currencySlug",k:"s",max:32},{n:"expected",k:"i",o:1,lo:1,hi:1e9},{n:"origin",k:"o",o:1,fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384}]}]),uo=y("gem.walletDisplay",[{n:"visible",k:"b"},{n:"currencies",k:"a",o:1,max:8,it:{n:"",k:"s",max:64}},{n:"score",k:"b",o:1}]),mo=y("gem.menu",[{n:"settings",k:"b"},{n:"items",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"id",k:"s",max:32},{n:"label",k:"s",max:40}]}}]),po=y("gem.menuSelect",[{n:"entry",k:"e",v:["settings","item"]},{n:"id",k:"s",o:1,max:32}]),go=y("gem.requestShare",[{n:"params",k:"a",max:16,it:{n:"",k:"o",fs:[{n:"key",k:"s",max:64},{n:"value",k:"s",max:512}]}}]),ho=y("gem.requestAvatarPicker",[]),fo=y("gem.vibrate",[{n:"pattern",k:"a",max:99,it:{n:"",k:"i",lo:0,hi:1e4}}]),yo=y("gem.frameStats",[{n:"fps",k:"i",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"i",lo:0,hi:1e5}]),bo=y("gem.portraitBorders",[{n:"name",k:"s",o:1,max:40}]),_o=y("gem.error",[{n:"code",k:"e",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"s",o:1,max:256}]),vo=y("gem.requestPurchase",[{n:"requestId",k:"s",max:64},{n:"purchaseKind",k:"e",v:["item","recipe"]},{n:"targetId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"quantity",k:"i",o:1,lo:1,hi:10},{n:"catalogId",k:"s",o:1,max:64}]),wo=y("gem.purchaseResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["ok","declined","unavailable"]},{n:"reason",k:"s",o:1,max:64,f:"code"},{n:"purchaseId",k:"s",o:1,max:64}]),ko=y("gem.deviceSettings.put",[{n:"requestId",k:"s",max:64},{n:"settings",k:"j"}]),Ro=y("gem.deviceSettings.result",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["stored","too_large","unavailable"]}]),So=y("gem.requestAd",[{n:"requestId",k:"s",max:64},{n:"placement",k:"s",max:32},{n:"format",k:"e",v:["interstitial","rewarded"]}]),xo=y("gem.adResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["shown","no_ad","unavailable"]}]),Ao=y("gem.requestSignIn",[{n:"requestId",k:"s",max:64}]),Po=y("gem.signInResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["signed_in","declined","unavailable"]}]),Eo=y("gem.requestFriendChallenge",[{n:"requestId",k:"s",max:64},{n:"playerId",k:"s",max:64},{n:"template",k:"s",max:64},{n:"params",k:"j",o:1}]),To=y("gem.friendChallengeResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"s",o:1,max:64},{n:"param",k:"s",o:1,max:64},{n:"channel",k:"s",o:1,max:16},{n:"configVersion",k:"i",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:864e5},{n:"detail",k:"s",o:1,max:300}]),ae=Nt({"gem.handshake":Si,"gem.handshake.accept":xi,"gem.token":Ai,"gem.token.denied":Pi,"gem.player":Ei,"gem.pause":Ti,"gem.prefs":Ii,"gem.cohorts":Ci,"gem.earnAllowanceChanged":Mi,"gem.viewport":Oi,"gem.deviceSettings":Li,"gem.willTerminate":Gi,"gem.roomEvent":Di,"gem.socketState":qi,"gem.seatedEvent":$i,"gem.autoStartFailedEvent":Fi,"gem.signalEvent":ji,"gem.dedicatedEvent":Ni,"gem.partyResult":Ui,"gem.clusterTarget":Bi,"gem.devtools":Wi,"gem.screenshot":Vi,"gem.screenshot.denied":Hi,"gem.requestContext":Ki,"gem.gameContext":Ji,"gem.signal":zi,"gem.dedicatedOffer":Xi,"gem.partyRequest":Yi,"gem.ready":Qi,"gem.engaged":Zi,"gem.progress":eo,"gem.requestToken":to,"gem.requestLocalServer":no,"gem.localServer":ro,"gem.localServer.denied":io,"gem.exit":oo,"gem.openExternal":so,"gem.requestFullscreen":ao,"gem.audioState":lo,"gem.rewardCue":co,"gem.walletDisplay":uo,"gem.menu":mo,"gem.menuSelect":po,"gem.requestShare":go,"gem.requestAvatarPicker":ho,"gem.vibrate":fo,"gem.frameStats":yo,"gem.portraitBorders":bo,"gem.error":_o,"gem.requestPurchase":vo,"gem.purchaseResult":wo,"gem.deviceSettings.put":ko,"gem.deviceSettings.result":Ro,"gem.requestAd":So,"gem.adResult":xo,"gem.requestSignIn":Ao,"gem.signInResult":Po,"gem.requestFriendChallenge":Eo,"gem.friendChallengeResult":To});var it=3;function B(n){if(typeof n!="string")return;let e=n.trim();return e.length===0?void 0:e}function be(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=B(t);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var Io=2e3,Co=5e3;function Mo(n){let e=[],t=false,r=null,i=new Map,o=()=>{if(e.length>0)return Promise.resolve(e);if(t)return Promise.resolve([]);if(!n.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let a,s=new Promise(l=>{let d=false,m=null;a=u=>{d||(d=true,r=null,n.clock.clearTimeout(m),l(u));},m=n.clock.setTimeout(()=>{t=true,a([]);},n.timeoutMs??Io);});return r={promise:s,settle:a},s};return {resolveList:o,resolve(){return e.length>0||t||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):o().then(a=>a[0])},refresh(a){return !Vn(e,a)||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(s=>{let l=null,d=m=>{i.delete(d)&&(n.clock.clearTimeout(l),s(m));};i.set(d,a),l=n.clock.setTimeout(()=>d(e),n.refreshTimeoutMs??Co);})},accept(a,s){let l=be(s),d=B(a),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[u,p]of [...i])Vn(m,p)||u(m);}}}}function Vn(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var Oo=/^[a-z0-9][a-z0-9_-]{0,39}$/;function Ut(n){return typeof n=="string"&&Oo.test(n)}function Hn(n){if(n===null||Ut(n))return n;let e=typeof n=="string"?JSON.stringify(n.length>48?`${n.slice(0,48)}\u2026`:n):`a value of type ${typeof n}`;console.warn(`[gem] showPortraitBorders: ${e} is not a border name, so nothing was sent. A name is 1 to 40 of a-z, 0-9, _ and -, starting with a letter or digit, exactly as your store page declares it under media.portrait_borders. Pass null for no art.`);}var Oe=16384,ot=24;function R(n){return e=>typeof e=="string"&&e.length>0&&e.length<=n?e:void 0}function ee(n,e){return t=>typeof t=="number"&&Number.isInteger(t)&&t>=n&&t<=e?t:void 0}function _e(...n){return e=>typeof e=="string"&&n.includes(e)?e:void 0}function Kn(n){return typeof n=="boolean"?n:void 0}var L=R(64),Le=ee(0,2147483647);function Bt(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(e.length>=64)break;let r=L(t);typeof r=="string"&&e.push(r);}return e}function A(n,e,t){return {to:n,from:e,read:t,required:true}}function S(n,e,t){return {to:n,from:e,read:t,required:false}}function ve(n,e){let t={};for(let r of e){let i=r.read(n[r.from]);if(i===void 0){if(r.required)return null;continue}t[r.to]=i;}return t}function Ge(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let e=n;return typeof e.type!="string"||typeof e.data!="object"||e.data===null||Array.isArray(e.data)?null:{type:e.type,data:e.data}}var Jn=[A("sdp","sdp",R(10240)),A("signaling_intent","intent",_e("initial","ice_restart","full_reconnect"))];function st(n,e,t){if(typeof t!="object"||t===null||Array.isArray(t))return {reason:"offer: data must be an object"};let r=t,i=ve(r,Jn);return i===null?{reason:`offer: '${Jn.find(a=>a.read(r[a.from])===void 0)?.from??"?"}' is missing or out of bounds`}:{frame:{type:"webrtc_offer",match_id:n,game_id:e,...i}}}var Wt=Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"})),Lo=new Set(["error"]),Go=Object.freeze(Object.assign(Object.create(null),{answer:[A("sdp","sdp",R(10240)),S("sessionId","session_id",R(64))],error:[S("code","code",R(64)),S("message","message",R(256))],matchEnded:[S("reason","reason",R(64))]}));function at(n,e,t){let r=Ge(n);if(r===null)return null;let i=Wt[r.type];if(i===void 0)return null;let o=L(r.data.match_id);if(typeof o!="string"||!(Lo.has(i)?t(o):r.data.game_id===e))return null;let s=ve(r.data,Go[i]??[]);return s===null?null:{event:i,matchId:o,...s}}var Do=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=_e("disconnected","failed","closed")(e.iceState),r=ee(0,4102444800)(e.lastSeenAt);if(!(t===void 0&&r===void 0))return {...t===void 0?{}:{ice_state:t},...r===void 0?{}:{last_seen_timestamp:r}}},qo=Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[A("sdp","sdp",R(10240)),A("signaling_intent","intent",_e("initial","ice_restart","full_reconnect")),S("sdp_hash","sdpHash",R(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[A("peer_id","peerId",L),A("sdp","sdp",R(10240)),A("assigned_peer_id","assignedPeerId",ee(0,4294967295)),S("sdp_hash","sdpHash",R(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[A("peer_id","peerId",L),A("candidate","candidate",R(512)),S("sdp_mid","sdpMid",R(64)),S("sdp_mline_index","sdpMLineIndex",ee(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[A("host_epoch","hostEpoch",Le)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[A("host_epoch","hostEpoch",Le),S("evidence","evidence",Do)]}}));function lt(n,e,t,r){let i=qo[n];if(i===void 0)return {reason:`unknown signal '${n}'`};if(typeof r!="object"||r===null||Array.isArray(r))return {reason:`${n}: data must be an object`};let o=r,a=ve(o,i.args);if(a===null){let s=i.args.find(l=>l.required&&l.read(o[l.from])===void 0);return {reason:`${n}: '${s?.from??"?"}' is missing or out of bounds`}}return {frame:{type:i.type,match_id:e,...i.gameScoped?{game_id:t}:{},...a}}}var $o=Object.freeze(Object.assign(Object.create(null),{p2p_hello:"hello",p2p_sdp_offer:"offer",p2p_sdp_answer:"answer",p2p_ice_candidate:"ice",p2p_peer_joined:"peerJoined",p2p_peer_left:"peerLeft",p2p_host_migration:"migration",p2p_match_ended:"matchEnded",p2p_error:"error"})),Fo=new Set(["error"]),jo=Object.freeze(Object.assign(Object.create(null),{hello:[A("playerId","player_id",L),A("hostPlayerId","host_player_id",L),A("hostEpoch","host_epoch",Le),S("members","members",Bt)],offer:[A("fromPlayerId","from_player_id",L),A("sdp","sdp",R(10240)),S("sessionId","signaling_session_id",R(128)),S("sdpHash","sdp_hash",R(128)),S("iceUfrag","ice_ufrag",R(64)),S("intent","signaling_intent",_e("initial","ice_restart","full_reconnect"))],answer:[A("fromPlayerId","from_player_id",L),A("sdp","sdp",R(10240)),S("sessionId","signaling_session_id",R(128)),S("sdpHash","sdp_hash",R(128)),S("iceUfrag","ice_ufrag",R(64)),S("assignedPeerId","assigned_peer_id",ee(0,4294967295))],ice:[A("fromPlayerId","from_player_id",L),A("candidate","candidate",R(512)),S("sdpMid","sdp_mid",R(64)),S("sdpMLineIndex","sdp_m_line_index",ee(0,255)),S("sdpMLineIndexAlt","sdp_mline_index",ee(0,255))],peerJoined:[A("playerId","player_id",L)],peerLeft:[A("playerId","player_id",L),S("reason","reason",R(64))],migration:[A("hostPlayerId","new_host_player_id",L),A("hostEpoch","host_epoch",Le),S("reason","reason",R(64)),S("kickedPlayerIds","kicked_player_ids",Bt),S("migrationComplete","migration_complete",Kn)],matchEnded:[S("reason","reason",R(64))],error:[S("code","code",R(64)),S("message","message",R(256))]}));function dt(n,e,t){let r=Ge(n);if(r===null)return null;let i=$o[r.type];if(i===void 0)return null;let o=L(r.data.match_id);if(typeof o!="string"||!(Fo.has(i)?t(o):r.data.game_id===e))return null;let s=ve(r.data,jo[i]??[]);return s===null?null:{event:i,matchId:o,data:s}}var No=Object.freeze(Object.assign(Object.create(null),{party_invite_received:"inviteReceived",party_member_joined:"memberJoined",party_member_left:"memberLeft",party_member_kicked:"memberKicked",party_leader_transferred:"leaderTransferred",party_updated:"updated",party_disbanded:"disbanded",party_game_room_joined:"gameRoomJoined",party_game_room_left:"gameRoomLeft"}));function De(n){let e=Ge(n);if(e===null)return null;let t=No[e.type];if(t===void 0)return null;let r=e.data,i=L(r.party_id);if(typeof i!="string")return null;let o=ee(0,Number.MAX_SAFE_INTEGER)(r.version),a=L(r.game_room_id),s=L(r.game_id),l=L(r.inviter_player_id),d=R(80)(r.inviter_display_tag),m=R(64)(r.party_name);return {event:t,partyId:i,...o===void 0?{}:{version:o},...a===void 0?{}:{gameRoomId:a},...s===void 0?{}:{gameId:s},...l===void 0?{}:{inviterPlayerId:l},...d===void 0?{}:{inviterDisplayTag:d},...m===void 0?{}:{partyName:m}}}var re={now:()=>Date.now(),setTimeout:(n,e)=>setTimeout(n,e),clearTimeout:n=>clearTimeout(n)},te=class{constructor(e=re){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let t=tt[e];if(t===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??t,a=Math.max(0,r-i),s=Math.min(t,o+a*t/6e4);return s<1?(this.tokens.set(e,s),this.lastRefill.set(e,r),false):(this.tokens.set(e,s-1),this.lastRefill.set(e,r),true)}};function ke(n,e){return n.toLowerCase()===e.toLowerCase()}function ct(n){let e=n.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function Xn(n,e){if(typeof e!="string"||e==="")return false;let t,r;try{t=new URL(n),r=new URL(e);}catch{return false}return t.protocol!=="http:"&&t.protocol!=="https:"||r.protocol!=="http:"&&r.protocol!=="https:"||t.username!==""||t.password!==""||t.pathname!=="/"||t.search!==""||t.hash!==""||t.port===""?false:ct(t.hostname)&&ct(r.hostname)}function Vt(n,e){if(n.min>n.max||e.min>e.max)return null;let t=Math.min(n.max,e.max),r=Math.max(n.min,e.min);return t>=r?t:null}var Uo=7,Bo=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,Wo=["universal","mobile"],Vo={game_room_updated:"updated",game_room_match_started:"match_started",game_room_match_ready:"match_ready",game_room_match_failed:"match_failed",game_room_version_stale:"version_stale",match_ended:"updated",p2p_match_ended:"updated"},Ho=new Set(["match_ended","p2p_match_ended"]),Ko="game_room_auto_start_failed",Jo=/^[a-z][a-z0-9_]{0,63}$/,qe=64,zo=8,Kt=class{constructor(e,t){this.clock=e;this.limit=t;}clock;limit;windowStart=0;used=0;allow(){let e=this.clock.now();return e-this.windowStart>=1e3&&(this.windowStart=e,this.used=0),this.used>=this.limit?false:(this.used+=1,true)}};function ut(n){if(!(typeof n!="string"||n.length===0||n.length>qe))return n}function Xo(n){return n instanceof Error?n.message:String(n)}function Qn(n,e){if(!n.has(e)){if(n.size>=zo){let t=n.values().next().value;t!==void 0&&n.delete(t);}n.add(e);}}function Ht(){return new MessageChannel}var Yo=6e4/(tt["gem.handshake"]??1),Qo=6e4,Jt=class{constructor(e){this.options=e;if(!rt(e.frameOrigin))throw new Error(`GemHost: frameOrigin must be a concrete origin, got '${e.frameOrigin}'. '*' and 'null' are refused \u2014 the handshake transfers the MessagePort, so an imprecise targetOrigin gives the session away.`);if(!rt(e.embedderOrigin))throw new Error(`GemHost: embedderOrigin must be a concrete origin, got '${e.embedderOrigin}'.`);this.clock=e.clock??re,this.inbound=new te(this.clock),this.outbound=new te(this.clock),this.socketWindow=new Kt(this.clock,24);}options;state="idle";port=null;version=null;timeoutHandle=null;reofferHandle=null;makeChannel=Ht;offered=[];offersMade=0;localDenials=0;chainEndsAt=null;gameId=null;peerCapabilities=[];knownMatches=new Set;askedMatches=new Set;clock;inbound;outbound;socketWindow;get currentState(){return this.state}get frameCapabilities(){return this.peerCapabilities}frameSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}start(e=Ht){if(this.state!=="idle"){this.fail("handshake_duplicate",`cannot start from state '${this.state}'`);return}if(typeof e=="function")this.makeChannel=e;else if(e&&e.port1&&e.port2){let t=e,r=false;this.makeChannel=()=>r?Ht():(r=true,t);}else throw new Error("GemHost.start: pass a function returning { port1, port2 } \u2014 omit it entirely to get a fresh MessageChannel per offer, which is what an embedder normally wants.");this.transition("handshaking"),this.offer(),this.scheduleReoffer(),this.timeoutHandle=this.clock.setTimeout(()=>{this.timeoutHandle=null,this.state==="handshaking"&&this.fail("handshake_timeout",`no answer from ${this.options.frameOrigin} to ${this.offersMade} handshake ${this.offersMade===1?"offer":"offers"} in the first ${jt}ms; the offers continue for as long as this page holds the frame. This page presented embedder origin ${this.options.embedderOrigin}. A frame answers none of them if it carries no bridge at all, if it has not started listening yet, or if that origin is missing from the embedders it will accept \u2014 this side cannot tell which, and does not try.`);},jt);}offer(){if(!this.outbound.allow("gem.handshake"))return false;let e=this.makeChannel(),t=e.port1;return t.onmessage=r=>this.receive(r.data,t),t.start?.(),this.offered.push({port:t,at:this.clock.now()}),this.offersMade+=1,this.options.frame.postMessage({gem:f,type:"gem.handshake",versions:{min:Z.min,max:Z.max},embedder:this.options.embedderOrigin,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]},...this.options.unbidden===true?{unbidden:true}:{}},this.options.frameOrigin,[e.port2]),true}scheduleReoffer(){this.reofferHandle=this.clock.setTimeout(()=>{this.reofferHandle=null,this.state==="handshaking"&&(this.offer(),this.pruneStaleOffers(),this.scheduleReoffer());},Yo);}pruneStaleOffers(){let e=this.clock.now()-Qo;for(;this.offered.length>0&&(this.offered[0]?.at??e)<e;){let t=this.offered.shift();if(t===void 0)break;t.port.onmessage=null,t.port.close();}}adopt(e){for(let t of this.offered)t.port!==e&&(t.port.onmessage=null,t.port.close());this.offered.length=0,this.port=e;}static checkHandshakeOrigin(e,t,r){return ke(e.origin,t)?e.source!==r?"source is not the mounted frame":null:`origin '${e.origin}' is not the expected frame origin`}sendToken(e){if(!Number.isInteger(e.chainEndsAt)||e.chainEndsAt<0){this.fail("internal","refusing a grant whose chainEndsAt is not a whole number of seconds >= 0");return}let t=this.chainEndsAt??e.chainEndsAt;if(this.chainExpired()){this.fail("token_unavailable","token chain ceiling reached");return}this.send({gem:f,type:"gem.token",token:e.token,expiresAt:e.expiresAt,chainEndsAt:t,generation:e.generation,playerId:e.playerId,gameId:e.gameId,channel:e.channel,...e.gameVersion===void 0?{}:{gameVersion:e.gameVersion},...e.requestId===void 0?{}:{requestId:e.requestId},...e.apiBaseUrl===void 0?{}:{apiBaseUrl:e.apiBaseUrl},...e.allowDevTools===true?{allowDevTools:true}:{},...e.garden===void 0?{}:{garden:e.garden}})&&(this.chainEndsAt=t,this.gameId??=e.gameId);}relayRoomEvent(e){if(this.gameId===null||typeof e!="object"||e===null||Array.isArray(e))return false;let t=e;if(typeof t.type!="string")return false;let r=Vo[t.type];if(r===void 0||typeof t.data!="object"||t.data===null||Array.isArray(t.data))return false;let i=t.data;if(i.game_id!==this.gameId)return false;let o=ut(i.game_room_id);if(o===void 0)return false;let a=Ho.has(t.type)?void 0:ut(i.match_id);a!==void 0&&this.rememberMatch(a);let s=typeof i.version=="number"?i.version:void 0,l=typeof i.reason=="string"?i.reason.slice(0,qe):void 0,d=r==="version_stale"&&Wo.includes(i.platform)?i.platform:void 0;return this.sendRoomEvent({event:r,roomId:o,...a===void 0?{}:{matchId:a},...s===void 0?{}:{version:s},...l===void 0?{}:{reason:l},...d===void 0?{}:{platform:d}})}sendRoomEvent(e){return this.frameSupports("rooms")?this.send({gem:f,type:"gem.roomEvent",event:e.event,roomId:e.roomId,...e.matchId===void 0?{}:{matchId:e.matchId},...e.version===void 0?{}:{version:e.version},...e.reason===void 0?{}:{reason:e.reason},...e.platform===void 0?{}:{platform:e.platform}}):false}sendSocketState(e){return this.frameSupports("socketState")?this.send({gem:f,type:"gem.socketState",connected:e.connected,...e.connected?{}:{reason:e.reason}}):false}sendSeatedEvent(e){return this.frameSupports("partySeating")?this.send({gem:f,type:"gem.seatedEvent",roomId:e}):false}relaySeatedEvent(e){if(this.gameId===null)return false;let t=De(e);if(t===null||t.event!=="gameRoomJoined"||t.gameId!==this.gameId)return false;let r=ut(t.gameRoomId);return r===void 0?false:this.sendSeatedEvent(r)}sendAutoStartFailedEvent(e){return this.frameSupports("autoStartFailure")?this.send({gem:f,type:"gem.autoStartFailedEvent",roomId:e.roomId,code:e.code}):false}relayAutoStartFailedEvent(e){if(this.gameId===null||typeof e!="object"||e===null||Array.isArray(e))return false;let t=e;if(t.type!==Ko||typeof t.data!="object"||t.data===null||Array.isArray(t.data))return false;let r=t.data;if(r.game_id!==this.gameId)return false;let i=ut(r.game_room_id),o=typeof r.code=="string"&&Jo.test(r.code)?r.code:void 0;return i===void 0||o===void 0?false:this.sendAutoStartFailedEvent({roomId:i,code:o})}relaySocketEvent(e){let t=[];(this.relayRoomEvent(e)||this.relayAutoStartFailedEvent(e))&&t.push("room"),this.relaySignalEvent(e)&&t.push("signal"),this.relayDedicatedEvent(e)&&t.push("dedicated");let r=De(e);return r!==null&&(this.options.onPartyEvent?.(r),this.relaySeatedEvent(e),t.push("party")),t}relaySignalEvent(e){if(this.gameId===null)return false;let t=dt(e,this.gameId,r=>this.knowsMatch(r));return t===null?false:(t.event==="hello"&&this.rememberMatch(t.matchId),this.sendSignalEvent(t))}sendSignalEvent(e){return this.frameSupports("p2p")?this.send({gem:f,type:"gem.signalEvent",event:e.event,matchId:e.matchId,data:e.data}):false}relayDedicatedEvent(e){if(this.gameId===null)return false;let t=at(e,this.gameId,r=>this.knowsMatch(r));return t===null?false:this.sendDedicatedEvent(t)}sendDedicatedEvent(e){return this.frameSupports("dedicated")?this.send({gem:f,type:"gem.dedicatedEvent",event:e.event,matchId:e.matchId,...e.sdp===void 0?{}:{sdp:e.sdp},...e.sessionId===void 0?{}:{sessionId:e.sessionId},...e.code===void 0?{}:{code:e.code},...e.message===void 0?{}:{message:e.message},...e.reason===void 0?{}:{reason:e.reason}}):false}knowsMatch(e){return this.knownMatches.has(e)||this.askedMatches.has(e)}rememberMatch(e){Qn(this.knownMatches,e);}rememberAsked(e){Qn(this.askedMatches,e);}answerPartyRequest(e,t){return this.send({gem:f,type:"gem.partyResult",requestId:e,...t===void 0?{}:{partyId:t}})}answerPurchase(e,t,r,i){return this.send({gem:f,type:"gem.purchaseResult",requestId:e,outcome:t,...r===void 0||t!=="ok"?{}:{purchaseId:r},...i===void 0||t==="ok"?{}:{reason:i}})}answerDeviceSettingsPut(e,t){return this.send({gem:f,type:"gem.deviceSettings.result",requestId:e,outcome:t})}sendDeviceSettings(e){return this.frameSupports("deviceSettings")?this.send({gem:f,type:"gem.deviceSettings",...e===void 0?{}:{settings:e}}):false}sendMenuSelect(e){return this.frameSupports("gameMenu")?this.send(e==="settings"?{gem:f,type:"gem.menuSelect",entry:"settings"}:{gem:f,type:"gem.menuSelect",entry:"item",id:e.id}):false}answerAd(e,t){return this.send({gem:f,type:"gem.adResult",requestId:e,outcome:t})}answerSignIn(e,t){return this.send({gem:f,type:"gem.signInResult",requestId:e,outcome:t})}answerFriendChallenge(e,t,r={}){let i={};if(t==="invalid"){let{code:o,param:a,channel:s,configVersion:l,detail:d}=r;typeof o=="string"&&o.length<=64&&(i.code=o),typeof a=="string"&&a.length<=64&&(i.param=a),typeof s=="string"&&s.length<=16&&(i.channel=s),typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&(i.configVersion=l),typeof d=="string"&&(i.detail=d.slice(0,300));}else if(t==="rate_limited"){let o=r.retryAfterMs;typeof o=="number"&&Number.isFinite(o)&&(i.retryAfterMs=Math.min(864e5,Math.max(0,Math.round(o))));}return this.send({gem:f,type:"gem.friendChallengeResult",requestId:e,outcome:t,...i})}denyToken(e){this.send({gem:f,type:"gem.token.denied",requestId:e.requestId,retryable:e.retryable,reason:e.reason,correlationId:e.correlationId,...e.retryAfterMs===void 0?{}:{retryAfterMs:e.retryAfterMs}});}grantLocalServer(e){return this.frameSupports("localHost")?this.send({gem:f,type:"gem.localServer",requestId:e.requestId,...e.serverId===void 0?{}:{serverId:e.serverId}}):false}denyLocalServer(e){return this.frameSupports("localHost")?this.send({gem:f,type:"gem.localServer.denied",requestId:e.requestId,retryable:e.retryable,reason:e.reason}):false}sendClusterTarget(e){let t=typeof e=="string"?[e]:e,r=Array.isArray(t)?t.length===0?"[]":t.find(o=>typeof o!="string"||o.trim().length===0||o.length>qe):String(t);if(r!==void 0)return this.fail("internal",`refusing to send '${String(r)}' as a cluster target \u2014 each id must be a non-blank string of at most ${qe} characters, and a list must name at least one. Omit the message entirely when there is no answer: the frame then names no cluster and gem-api chooses.`),false;if(t.length>3)return this.fail("internal",`refusing to send ${t.length} cluster targets \u2014 at most ${3} acceptable clusters cross, best first.`),false;if(!this.frameSupports("clusterTarget"))return false;let[i]=t;return this.send({gem:f,type:"gem.clusterTarget",clusterTargetId:i,...typeof e=="string"?{}:{clusterTargetIds:[...t]}})}sendPlayer(e){let{displayName:t,displayTag:r}=e.untrusted,i=e.badges?.map(({itemId:l,iconUrl:d})=>({itemId:l,iconUrl:d})),o=e.boost&&{multipliers:e.boost.multipliers.map(({currencyId:l,currencySlug:d,multiplierBp:m})=>({currencyId:l,currencySlug:d,multiplierBp:m})),...e.boost.expiresInDays===void 0?{}:{expiresInDays:Math.min(Uo,e.boost.expiresInDays)}},a=e.discriminator!==void 0&&/^[0-9]{1,8}$/.test(e.discriminator)?e.discriminator:void 0,s=e.avatarIconId!==void 0&&Bo.test(e.avatarIconId)?e.avatarIconId:void 0;this.send({gem:f,type:"gem.player",untrusted:{displayName:t,...r===void 0?{}:{displayTag:r},displayHandle:r??t},...e.playerId===void 0?{}:{playerId:e.playerId},...a===void 0?{}:{discriminator:a},...e.avatarIconUrl===void 0?{}:{avatarIconUrl:e.avatarIconUrl},...s===void 0?{}:{avatarIconId:s},...i===void 0?{}:{badges:i},...o===void 0?{}:{boost:o},displayTag:a??"",...e.avatarIconUrl===void 0?{}:{avatarUrl:e.avatarIconUrl}});}chainExpired(){return this.chainEndsAt!==null&&this.clock.now()/1e3>=this.chainEndsAt}localCorrelationId(){return `local-${++this.localDenials}`}sendPause(e){this.send({gem:f,type:"gem.pause",paused:e});}sendDevtools(e){this.send({gem:f,type:"gem.devtools",action:e});}requestScreenshot(e,t){return this.frameSupports("screenshot")?this.send({gem:f,type:"gem.screenshot",maxWidth:t.maxWidth,maxHeight:t.maxHeight},[e]):false}requestContext(){return this.frameSupports("feedbackContext")?this.send({gem:f,type:"gem.requestContext"}):false}sendPrefs(e){this.send({gem:f,type:"gem.prefs",...e});}sendCohorts(e){return this.frameSupports("cohorts")?this.send({gem:f,type:"gem.cohorts",cohorts:e.map(t=>({experimentId:t.experimentId,variantKey:t.variantKey}))}):false}sendEarnAllowanceChanged(){return this.frameSupports("earnAllowance")?this.send({gem:f,type:"gem.earnAllowanceChanged"}):false}sendViewport(e){if(!this.frameSupports("viewport"))return false;let t=(e.reserved??[]).map(({x:o,y:a,width:s,height:l})=>({x:o,y:a,width:s,height:l})),r=this.frameSupports("reservedAreas"),i=e.insets.top;if(!r)for(let o of t)o.y===0&&(i=Math.max(i,o.height));return this.send({gem:f,type:"gem.viewport",insets:{top:i,right:e.insets.right,bottom:e.insets.bottom,left:e.insets.left},...r?{reserved:t}:{}})}sendWillTerminate(e,t){this.send({gem:f,type:"gem.willTerminate",reason:e,graceMs:t});}close(){this.timeoutHandle!==null&&(this.clock.clearTimeout(this.timeoutHandle),this.timeoutHandle=null),this.reofferHandle!==null&&(this.clock.clearTimeout(this.reofferHandle),this.reofferHandle=null);for(let e of this.offered)e.port.onmessage=null,e.port.close();this.offered.length=0,this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="unsupported"&&this.transition("closed");}transition(e){this.state!==e&&(this.state=e,this.options.onStateChange?.(e));}fail(e,t){this.options.onError?.(e,t);}send(e,t){if(this.state!=="connected"||!this.port)return this.options.onDropped?.("internal",`dropped ${String(e.type)} before connect`),false;let r=e.type;if(!this.outbound.allow(r))return this.fail("rate_limited",`parent exceeded its own limit for ${r}`),false;let i=ae[r]?.(e);return i?(this.fail("internal",`refusing to send malformed ${r}: ${i}`),false):(t===void 0?this.port.postMessage({...e,v:this.version}):this.port.postMessage({...e,v:this.version},t),true)}receive(e,t){if(this.state==="closed"||this.state==="unsupported")return;let r=typeof e=="object"&&e!==null?e.type:void 0;if(typeof r!="string"){this.refuseMalformed("invalid_message","message has no type");return}let i=ae[r];if(!i){this.refuseMalformed("unsupported",`unknown message type ${JSON.stringify(r.slice(0,qe))}`);return}if(!this.inbound.allow(r)){this.fail("rate_limited",`frame exceeded the limit for ${r}`);return}let o=nt(r);if(o!==void 0&&!this.options.capabilities?.includes(o)){this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this parent did not advertise`);return}let a=i(e);if(a){this.fail("invalid_message",`${r}: ${a}`);return}let s=e;r!=="gem.handshake.accept"&&!this.versionMatches(s,r)||this.dispatch(r,s,t);}refuseMalformed(e,t){if(!this.inbound.allow(ye)){this.options.onDropped?.(e,t);return}this.fail(e,t);}versionMatches(e,t){return e.v===this.version?true:(this.fail("invalid_message",`${t}: expected v ${String(this.version)}, got ${String(e.v)}`),false)}forwardSignal(e){let t=this.options.onSendSignal;if(t===void 0){this.fail("unsupported","this parent advertised `p2p` but wired no onSendSignal, so signaling has nowhere to go");return}if(this.gameId===null){this.options.onDropped?.("internal","gem.signal before any token was issued");return}if(e.signal!=="join"&&!this.knownMatches.has(e.matchId)){this.fail("unsupported",`gem.signal names match '${e.matchId}', which this player's socket has not mentioned`);return}if(!this.socketWindow.allow()){this.fail("rate_limited","signaling exceeded this parent per-second socket budget");return}let r=lt(e.signal,e.matchId,this.gameId,e.data);if("reason"in r){this.fail("invalid_message",`gem.signal: ${r.reason}`);return}this.withinFrameSize("gem.signal",r.frame,"Trickle ICE candidates rather than gathering them into the offer.")&&(this.rememberAsked(e.matchId),t(r.frame));}forwardDedicatedOffer(e){let t=this.options.onSendSignal;if(t===void 0){this.fail("unsupported","this parent advertised `dedicated` but wired no onSendSignal, so the offer has nowhere to go");return}if(this.gameId===null){this.options.onDropped?.("internal","gem.dedicatedOffer before any token was issued");return}if(!this.socketWindow.allow()){this.fail("rate_limited","signaling exceeded this parent per-second socket budget");return}let r=st(e.matchId,this.gameId,{sdp:e.sdp,intent:e.intent});if("reason"in r){this.fail("invalid_message",`gem.dedicatedOffer: ${r.reason}`);return}if(this.withinFrameSize("gem.dedicatedOffer",r.frame,"A complete gathered offer fits; one that does not is carrying media sections this path does not permit, or candidates from ICE servers this path does not use.")){this.rememberAsked(e.matchId);try{t(r.frame);}catch(i){this.sendDedicatedEvent({event:"error",matchId:e.matchId,code:"embedder_relay_unavailable",message:"the page could not put the offer on the player socket"}),this.fail("internal",`gem.dedicatedOffer: the socket refused the send: ${Xo(i)}`);}}}withinFrameSize(e,t,r){let i=JSON.stringify(t).length;return i<=16384?true:(this.fail("invalid_message",`${e} builds a ${i}-byte socket frame, over the ${16384}-byte limit gem-api enforces, so the socket would drop it and then fail to establish. ${r}`),false)}dispatch(e,t,r){if(e==="gem.handshake.accept"){if(this.state!=="handshaking"){this.fail("handshake_duplicate","handshake already settled");return}let i=t.v;if(i<Z.min||i>Z.max){this.transition("unsupported"),this.fail("version_mismatch",`frame chose v${i}, outside our supported range`),this.close();return}this.adopt(r),this.version=i,this.peerCapabilities=t.capabilities??[],this.timeoutHandle!==null&&(this.clock.clearTimeout(this.timeoutHandle),this.timeoutHandle=null),this.reofferHandle!==null&&(this.clock.clearTimeout(this.reofferHandle),this.reofferHandle=null),this.transition("connected");return}if(this.state!=="connected"){this.fail("invalid_message",`${e} received before the handshake completed`);return}switch(e){case "gem.ready":this.options.onReady?.();break;case "gem.engaged":this.options.onEngaged?.();break;case "gem.progress":this.options.onProgress?.(t);break;case "gem.requestToken":{let i=t;if(this.chainExpired()){this.denyToken({requestId:i.requestId,retryable:false,reason:"chain_exhausted",correlationId:this.localCorrelationId()});break}this.options.onRequestToken?.(i);break}case "gem.requestLocalServer":{this.options.onRequestLocalServer?.(t);break}case "gem.exit":this.options.onExit?.(t),this.close();break;case "gem.openExternal":this.options.onOpenExternal?.(t);break;case "gem.requestFullscreen":this.options.onRequestFullscreen?.(t);break;case "gem.audioState":this.options.onAudioState?.(t);break;case "gem.rewardCue":this.options.onRewardCue?.(t);break;case "gem.walletDisplay":this.options.onWalletDisplay?.(t);break;case "gem.menu":this.options.onMenu?.(t);break;case "gem.frameStats":this.options.onFrameStats?.(t);break;case "gem.portraitBorders":{let{name:i}=t;i==null?this.options.onPortraitBorders?.(null):Ut(i)&&this.options.onPortraitBorders?.(i);break}case "gem.screenshot.denied":this.options.onScreenshotDenied?.(t);break;case "gem.gameContext":this.options.onGameContext?.(t);break;case "gem.signal":this.forwardSignal(t);break;case "gem.dedicatedOffer":this.forwardDedicatedOffer(t);break;case "gem.partyRequest":{let i=t;if(this.options.onPartyRequest===void 0){this.answerPartyRequest(i.requestId);break}this.options.onPartyRequest(i);break}case "gem.requestPurchase":{let i=t;if(!this.frameSupports("purchases")){this.fail("unsupported_capability","refusing gem.requestPurchase: the frame did not advertise 'purchases', so it cannot receive gem.purchaseResult. Nothing was prompted and nothing was spent.");break}if(this.options.onRequestPurchase===void 0){this.answerPurchase(i.requestId,"unavailable");break}this.options.onRequestPurchase(i);break}case "gem.deviceSettings.put":{let i=t;if(!this.frameSupports("deviceSettings")){this.fail("unsupported_capability","refusing gem.deviceSettings.put: the frame did not advertise 'deviceSettings', so it cannot receive gem.deviceSettings.result. Nothing was stored.");break}if(this.options.onDeviceSettingsPut===void 0){this.answerDeviceSettingsPut(i.requestId,"unavailable");break}this.options.onDeviceSettingsPut(i);break}case "gem.requestAd":{let i=t;if(!this.frameSupports("ads")){this.fail("unsupported_capability","refusing gem.requestAd: the frame did not advertise 'ads', so it cannot receive gem.adResult. Nothing was rendered.");break}if(this.options.onRequestAd===void 0){this.answerAd(i.requestId,"no_ad");break}this.options.onRequestAd(i);break}case "gem.requestSignIn":{let i=t;if(!this.frameSupports("signIn")){this.fail("unsupported_capability","refusing gem.requestSignIn: the frame did not advertise 'signIn', so it cannot receive gem.signInResult. Nothing was rendered.");break}if(this.options.onRequestSignIn===void 0){this.answerSignIn(i.requestId,"unavailable");break}this.options.onRequestSignIn(i);break}case "gem.requestFriendChallenge":{let i=t;if(!this.frameSupports("friendChallenges")){this.fail("unsupported_capability","refusing gem.requestFriendChallenge: the frame did not advertise 'friendChallenges', so it cannot receive gem.friendChallengeResult. Nothing was previewed, rendered or sent.");break}if(this.options.onRequestFriendChallenge===void 0){this.answerFriendChallenge(i.requestId,"unavailable");break}this.options.onRequestFriendChallenge(i);break}case "gem.requestShare":if(!this.frameSupports("share")){this.fail("unsupported_capability","refusing gem.requestShare: the frame did not advertise 'share'. Nothing was shared.");break}this.options.onRequestShare?.(t);break;case "gem.requestAvatarPicker":if(!this.frameSupports("avatarPicker")){this.fail("unsupported_capability","refusing gem.requestAvatarPicker: the frame did not advertise 'avatarPicker'. Nothing was opened.");break}this.options.onRequestAvatarPicker?.();break;case "gem.vibrate":{if(!this.frameSupports("vibration")){this.fail("unsupported_capability","refusing gem.vibrate: the frame did not advertise 'vibration'. Nothing was played.");break}let i=t,o=i.pattern.reduce((a,s)=>a+s,0);if(o>1e4){this.fail("invalid_message",`refusing gem.vibrate: the pattern totals ${o} ms, over ${1e4}. Nothing was played.`);break}this.options.onVibrate?.(i);break}case "gem.error":this.fail(t.code,t.message);break;default:this.fail("unsupported",`no parent handler for '${e}'`);}}};var W=class{#e;constructor(e){this.#e=e,Object.freeze(this);}toString(){return "[gem: use gem.text.toPlain()]"}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function de(n){return new W(n)}var Zo={toPlain(n){return W.unwrap(n)},compare(n,e,t){let r=n instanceof W?W.unwrap(n):n,i=e instanceof W?W.unwrap(e):e,o;try{o=new Intl.Collator(t);}catch{o=new Intl.Collator;}return o.compare(r,i)},equals(n,e){let t=n instanceof W?W.unwrap(n):n,r=e instanceof W?W.unwrap(e):e;return t.normalize("NFC")===r.normalize("NFC")}};function Zn(n){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function es(n,e){if(n!==true)return {visible:false};let t=[],r=false;for(let i of Array.isArray(e)?e:[])i==="score"?r=true:typeof i=="string"&&i.length>0&&i.length<=64&&!t.includes(i)&&t.push(i);return !r&&t.length===0?{visible:true}:{visible:true,currencies:t.slice(0,8),score:r}}function ts(n,e){let t=[];for(let r of Array.isArray(e)?e:[]){if(t.length===4)break;if(typeof r!="object"||r===null)continue;let{id:i,label:o}=r;typeof i!="string"||i.length===0||i.length>32||typeof o!="string"||o.trim().length===0||t.some(a=>a.id===i)||t.push({id:i,label:o.trim().slice(0,40)});}return t.length===0?{settings:n===true}:{settings:n===true,items:t}}function er(n,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function ns(n){let e=n.untrusted,t=de(e.displayName),r=e.displayTag||e.displayHandle,i=r?de(r):void 0,o=n.discriminator||n.displayTag,a=o&&/^[0-9]{1,8}$/.test(o)?o:void 0,s=n.avatarIconUrl||n.avatarUrl,l=n.avatarIconId,d={displayName:t,displayHandle:i??t,badges:(n.badges??[]).map(h=>({itemId:h.itemId,iconUrl:h.iconUrl}))};n.playerId&&(d.playerId=n.playerId),a&&(d.discriminator=a),i&&(d.displayTag=i),s&&(d.avatarIconUrl=d.avatarUrl=s),l&&/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i.test(l)&&(d.avatarIconId=l);let m=n.boost,u=(m?.multipliers??[]).map(h=>({currencyId:h.currencyId,currencySlug:h.currencySlug,multiplier:h.multiplierBp/1e4})),p=u.some(h=>h.multiplier>1);return d.boost=p&&m?.expiresInDays?{active:p,multipliers:u,expiresInDays:m.expiresInDays}:{active:p,multipliers:u},d}var rs=1e4,zt=class{constructor(e){this.options=e;if(e.expectedSource===void 0||e.expectedSource===null)throw new Error("GemFrame: expectedSource is required and must not be null \u2014 pass window.parent. The handshake transfers the MessagePort, and origin alone does not say WHICH document on that origin sent it.");this.expectedSource=e.expectedSource,this.clock=e.clock??re,this.inbound=new te(this.clock),this.outbound=new te(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];unbidden=false;engagedSent=false;readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}get unbiddenLaunch(){return this.unbidden}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(s=>ke(s,e.origin))||Xn(e.origin,this.options.selfOrigin)))return this.refuse(e,`embedder '${e.origin}' is not in allowedEmbedders`),this.state==="waiting"&&this.transition("refused"),false;if(this.state==="connected")return this.fail("handshake_duplicate","this document already has a port"),false;if(this.state!=="waiting")return false;let r=ae["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!ke(i.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${i.embedder}' but arrived from '${e.origin}'`),false;let o=e.ports?.[0];if(!o)return this.refuse(e,"handshake transferred no MessagePort"),false;let a=Vt(Z,i.versions);return a===null?(o.onmessage=null,o.postMessage({gem:f,type:"gem.error",code:"version_mismatch",message:`frame supports v${Z.min}..v${Z.max}`}),o.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=o,this.version=a,o.onmessage=s=>this.receive(s.data,s.ports??[]),o.start?.(),this.peerCapabilities=i.capabilities??[],this.unbidden=i.unbidden===true,o.postMessage({gem:f,type:"gem.handshake.accept",v:a,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:f,type:"gem.ready"});}settled(e=rs){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(t=>{let r=o=>{this.clock.clearTimeout(i),t(o);},i=this.clock.setTimeout(()=>{let o=this.settleWaiters.indexOf(r);o>=0&&this.settleWaiters.splice(o,1),t(this.state);},e);this.settleWaiters.push(r);})}progress(e,t){this.send({gem:f,type:"gem.progress",loaded:e,total:t});}requestToken(e,t){this.send({gem:f,type:"gem.requestToken",requestId:e,reason:t});}requestLocalServer(e,t){return this.parentSupports("localHost")?(this.send({gem:f,type:"gem.requestLocalServer",requestId:e,gameRoomId:t}),true):false}exit(e){this.send(e===void 0?{gem:f,type:"gem.exit"}:{gem:f,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:f,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:f,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:f,type:"gem.audioState",muted:e}),true)}reportEngaged(){return this.engagedSent||this.state!=="connected"||!this.parentSupports("engagement")||!this.send({gem:f,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let t={gem:f,type:"gem.rewardCue",currencySlug:String(e.currencySlug).slice(0,32)};return e.expected!==void 0&&Number.isFinite(e.expected)&&e.expected>=1&&(t.expected=Math.min(1e9,Math.round(e.expected))),e.origin&&(t.origin={x:Zn(e.origin.x),y:Zn(e.origin.y)}),this.send(t),true}showPortraitBorders(e){let t=Hn(e);return t===void 0||this.state!=="connected"||!this.parentSupports("portraitBorders")?false:this.send(t===null?{gem:f,type:"gem.portraitBorders"}:{gem:f,type:"gem.portraitBorders",name:t})}setWalletVisible(e,t){return this.state!=="connected"||!this.parentSupports("walletDisplay")?false:this.send({gem:f,type:"gem.walletDisplay",...es(e,t?.only)})}setMenu(e,t){return this.state!=="connected"||!this.parentSupports("gameMenu")?false:this.send({gem:f,type:"gem.menu",...ts(e,t)})}requestShare(e){return this.state!=="connected"||!this.parentSupports("share")?false:this.send({gem:f,type:"gem.requestShare",params:e.map(({key:t,value:r})=>({key:t,value:r}))})}requestAvatarPicker(){return this.state!=="connected"||!this.parentSupports("avatarPicker")?false:this.send({gem:f,type:"gem.requestAvatarPicker"})}requestVibrate(e){return this.state!=="connected"||!this.parentSupports("vibration")?false:this.send({gem:f,type:"gem.vibrate",pattern:[...e]})}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:f,type:"gem.frameStats",fps:er(e.fps,1e3),frameTimeP95Ms:er(e.frameTimeP95Ms,1e5)}),true)}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:f,type:"gem.gameContext",context:e}),true)}signal(e,t,r){this.send({gem:f,type:"gem.signal",signal:e,matchId:t,data:r});}dedicatedOffer(e,t,r){this.send({gem:f,type:"gem.dedicatedOffer",matchId:e,sdp:t,intent:r});}requestParty(e){return this.send({gem:f,type:"gem.partyRequest",requestId:e})}requestPurchase(e,t,r,i,o,a){return this.send({gem:f,type:"gem.requestPurchase",requestId:e,purchaseKind:t,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...a===void 0?{}:{catalogId:a}})}putDeviceSettings(e,t){return this.send({gem:f,type:"gem.deviceSettings.put",requestId:e,settings:t})}requestAd(e,t,r){return this.send({gem:f,type:"gem.requestAd",requestId:e,placement:t,format:r})}requestSignIn(e){return this.send({gem:f,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,t,r,i){return this.send({gem:f,type:"gem.requestFriendChallenge",requestId:e,playerId:t,template:r,...i===void 0?{}:{params:i}})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let t of this.settleWaiters.splice(0))t(e);this.options.onStateChange?.(e);}}refuseMalformed(e,t){if(!this.inbound.allow(ye)){this.options.onDropped?.(e,t);return}this.fail(e,t);}dropUnknownType(e){this.inbound.allow(ye)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,t){e.ports?.[0]?.close?.(),this.inbound.allow(ye)&&this.options.onRefused?.(t);}fail(e,t){this.options.onError?.(e,t),this.state==="connected"&&this.port&&this.send({gem:f,type:"gem.error",code:e,...t===void 0?{}:{message:t}});}send(e){if(this.state!=="connected"||!this.port)return this.options.onDropped?.("internal",`dropped ${String(e.type)} before connect`),false;let t=e.type;if(!this.outbound.allow(t))return this.options.onError?.("rate_limited",`frame exceeded its own limit for ${t}`),false;let r=ae[t]?.(e);return r?(this.options.onError?.("internal",`refusing to send malformed ${t}: ${r}`),false):(this.port.postMessage(this.version===null?e:{...e,v:this.version}),true)}receive(e,t=[]){let r=false;try{r=this.dispatchInbound(e,t);}finally{r||tr(t);}}dispatchInbound(e,t){if(this.state!=="connected")return false;let r=typeof e=="object"&&e!==null?e.type:void 0;if(typeof r!="string")return this.refuseMalformed("invalid_message","message has no type"),false;let i=ae[r];if(!i)return this.dropUnknownType(r),false;if(!this.inbound.allow(r))return this.fail("rate_limited",`parent exceeded the limit for ${r}`),false;let o=nt(r);if(o!==void 0&&!this.options.capabilities?.includes(o))return this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this frame did not advertise`),false;let a=i(e);if(a)return this.fail("invalid_message",`${r}: ${a}`),false;let s=e;if(s.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(s);break;case "gem.pause":this.options.onPause?.(s);break;case "gem.menuSelect":this.options.onMenuSelect?.(s);break;case "gem.prefs":this.options.onPrefs?.(s);break;case "gem.cohorts":this.options.onCohorts?.(s);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(s);break;case "gem.willTerminate":this.options.onWillTerminate?.(s);break;case "gem.devtools":this.options.onDevtools?.(s.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=t[0];if(!l){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let d={maxWidth:s.maxWidth,maxHeight:s.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return tr(t.slice(1)),this.options.onScreenshot(d,l,(m,u)=>this.screenshotDenied(m,u)),true}case "gem.token.denied":this.options.onTokenDenied?.(s);break;case "gem.localServer":this.options.onLocalServer?.(s);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(s);break;case "gem.player":{this.options.onPlayer?.(ns(s));break}case "gem.roomEvent":this.options.onRoomEvent?.(s);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(s);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(s);break;case "gem.socketState":this.options.onSocketState?.(s);break;case "gem.signalEvent":this.options.onSignalEvent?.(s);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(s);break;case "gem.clusterTarget":this.options.onClusterTarget?.(s);break;case "gem.partyResult":this.options.onPartyResult?.(s);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(s);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(s);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(s);break;case "gem.adResult":this.options.onAdResult?.(s);break;case "gem.signInResult":this.options.onSignInResult?.(s);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(s);break;case "gem.error":this.options.onError?.(s.code,s.message);break;default:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,t){this.send({gem:f,type:"gem.screenshot.denied",reason:e,retryable:t});}};function tr(n){for(let e of n)try{e?.close?.();}catch{}}var is=16384;function os(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let e;try{e=JSON.stringify(n);}catch{return null}return typeof e!="string"?null:ss(e)}function ss(n){let e=0;for(let t=0;t<n.length;t+=1){let r=n.charCodeAt(t);if(r<128)e+=1;else if(r<2048)e+=2;else if(r>=55296&&r<=56319){let i=n.charCodeAt(t+1);i>=56320&&i<=57343?(e+=4,t+=1):e+=3;}else e+=3;}return e}var nr=["p2p","dedicated","unknown"],mt=["connection_setup_duration_seconds","reconnect_latency_seconds","datachannel_rtt_seconds","p2p_join_to_play_latency_seconds","ice_restart_outcome_total","connection_failures_total","transport_permanent_failures_total","transport_quality_score","host_migration_outcome_total","turn_relay_usage_ratio"];var ce=class{constructor(e){this.options=e;}options;async post(e,t){let r=this.options.gameId();if(r===null||r==="")return;let i=as(e,this.options.transport,(this.options.now??Date.now)());i.length!==0&&await this.options.client.post(`/v1/games/${encodeURIComponent(r)}/telemetry/p2p`,{events:i},t);}report(e){this.post(e).catch(()=>{});}};function as(n,e,t){let r=Math.floor(t/1e3);return n.filter(i=>mt.includes(i.type)).slice(0,100).map(i=>{let o=ls(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:i.value===void 0?{}:{value:i.value}}})}function ls(n){if(n!==void 0)return nr.includes(n)?n:"unknown"}function Xt(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}var j=class extends Error{constructor(t,r,i,o,a){super(`${t} (${r}): ${i}`);this.reason=t;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=a;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}};var cs=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),c=class extends Error{constructor(t,r,i){super(`${t}: ${r}`,i);this.reason=t;this.name="DedicatedServerError",this.retryable=cs.has(t),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var rr=["explicit","stale_cleanup","game_room_closed","replaced","migration_failed","host_left","insufficient_players","all_left","expired","migration_rate_exceeded","game_room_gone","failed","idle","reclaimed"],us=new Set(rr);function Re(n){return typeof n=="string"&&us.has(n)?n:"unknown"}var $e="webrtc_dedicated",Qt=["universal","mobile","web"];var ms="p2p_unavailable",ps="capacity_unavailable",gs=2,ir=3e4,or=1e3,sr=2e4;async function pt(n){let e=B(n.clusterTargetId),t=n.nextClusterTarget,r=0,i=n.clock??re,o=n.retry??{},a=o.budgetMs??ir,s=o.maxDelayMs??sr,l=o.initialDelayMs??or,d=i.now(),m=d+a,u=0;for(;;){u++;try{let p=await en(n.signal,"while allocating",()=>n.client.post(`${dr(n)}/start_match`,e===void 0?{}:{cluster_target_id:e},n.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!hs(p)||a<=0)throw p;if(p.status===503&&p.code===ms)throw new c("p2p_unavailable",`room ${n.roomId} starts a peer-to-peer match, which allocates no server \u2014 so this refusal is not capacity and waiting cannot help: ${p.message}`,{cause:p});if(r=p.code===ps?r+1:0,t!==void 0&&r>=gs){let M=t;t=void 0;let I=B(await M());I!==void 0&&(e=I,r=0);}let h=Math.min(s,l*2**(u-1)),b=Math.min(s,(p.retryAfterSeconds??0)*1e3),E=Math.max(h/2,b)+Math.random()*(h/2);if(i.now()+E>m)throw fs(n,p,u,i.now()-d,a);if(o.onWaiting?.({attempt:u,elapsedMs:i.now()-d,budgetMs:a,nextAttemptInMs:E,status:p.status,message:p.message}),await ft(i,E,n.signal),n.signal?.aborted)throw Yt("while waiting to allocate")}}}function hs(n){return n instanceof j?n.status===503?true:n.status===429&&n.code!=="too_many_concurrent_matches":false}function fs(n,e,t,r,i){let o=`${t} attempt${t===1?"":"s"} over ${r}ms of a ${i}ms budget`;return e.status===429?new c("start_rate_limited",`the platform was still limiting match starts for room ${n.roomId} after ${o}: ${e.message}`,{cause:e}):new c("no_server_ready",`the platform had no server ready for room ${n.roomId} after ${o}: ${e.message}`,{cause:e})}var ys=12e4,bs=1e3;async function gt(n){let{clock:e,matchId:t}=n,r=n.pollIntervalMs??bs,i=n.timeoutMs??ys,o=e.now()+i,a=ar(n),s={seen:n.knownToExist===true};for(;;){let l=await lr(n,a,s);if(l.outcome!==null)return l.outcome;if(e.now()+r>o)throw new c("timeout",`match ${t} was still ${l.status} after ${i}ms`);await ft(e,r,n.signal);}}async function Zt(n){return (await lr(n,ar(n),{seen:n.knownToExist===true})).outcome}function ar(n){let e=new URLSearchParams({platform:n.version.platform,game_version:n.version.gameVersion});return `${dr(n)}/matches/${encodeURIComponent(n.matchId)}/status?${e}`}async function lr(n,e,t){let{matchId:r}=n,i=n.clock.now(),o;try{o=await en(n.signal,"while polling match status",()=>n.client.get(e,n.signal));}catch(a){if(a instanceof j&&a.reason==="not_found")return {status:"not_found",outcome:t.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw a}if(t.seen=true,o.status==="ready")return {status:"ready",outcome:_s(r,o,i)};if(o.status==="failed"){let a=o.ended_reason;return typeof a=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:Re(a)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function ht(n){let e=await en(n.signal,"while listing cluster targets",()=>n.client.get("/v1/ping/targets",n.signal)),t=[];for(let r of e.targets??[]){let i=r?.cluster_target_id;typeof i!="string"||i.length===0||t.push({id:i,pressure:typeof r.pressure=="string"?r.pressure:"unknown"});}return t}async function en(n,e,t){if(n?.aborted)throw Yt(e);try{return await t()}catch(r){throw n?.aborted?Yt(e,r):r}}function Yt(n,e){return new c("aborted",`the caller aborted ${n}`,e===void 0?void 0:{cause:e})}function _s(n,e,t){let r=e.join_credential,i=e.expires_in_seconds,o=typeof r=="string"&&typeof i=="number";return {status:"ready",matchId:n,protocol:e.protocol??"unknown",...o?{joinCredential:r,credentialExpiresAt:t+i*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function dr(n){return `/v1/games/${encodeURIComponent(n.gameId)}/game-rooms/${encodeURIComponent(n.roomId)}`}function ft(n,e,t){return t?.aborted?Promise.resolve():new Promise(r=>{let i=()=>{n.clearTimeout(o),t?.removeEventListener("abort",i),r();},o=n.setTimeout(i,e);t?.addEventListener("abort",i);})}var vs=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),nn="embedder_relay_unavailable",ws="embedder_no_relay",ks=new Set([nn]),rn=new Set([ws]),yt=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new tn(this)}handleEvent(e){let t=this.pending.get(e.matchId);if(t!==void 0){if(e.event==="matchEnded"){t.refuse(new c("match_ended",`the match ended while the offer was in flight (${e.reason??"no reason given"}), so no server is left to answer it`));return}if(e.event==="answer"){if(typeof e.sdp!="string"||e.sdp.length===0){t.refuse(new c("signaling_failed","the parent relayed an answer with no SDP in it"));return}t.settle({sdp:e.sdp});return}t.refuse(Rs(e.code,e.message));}}register(e,t){this.pending.get(e)?.refuse(new c("signaling_failed","a newer offer for this match superseded the one in flight")),this.pending.set(e,t);}release(e,t){this.pending.get(e)===t&&this.pending.delete(e);}transport(){let e=this.options.bridge;if(e===null)throw new c("signaling_unavailable","this game is not running inside a page that holds the player's notification socket, so there is nothing to carry an offer. Dedicated signaling needs that socket and only the page can hold one \u2014 see docs/dedicated-server-flow.md \xA72.");if(!e.parentSupports("dedicated"))throw new c("signaling_unavailable","the page embedding this game did not advertise the `dedicated` capability, so it will not relay signaling for a dedicated server. See docs/dedicated-server-flow.md \xA72.");return e}};function Rs(n,e){let t=e??"the offer was refused",r=n===void 0?t:`${t} (${n})`;return new c(Ss(n),r,{platformCode:n})}function Ss(n){return n===void 0||ks.has(n)?"signaling_failed":rn.has(n)?"offer_refused":vs.has(n)?n==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var tn=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,t){if(this.closed)return Promise.reject(new c("signaling_unavailable","this signaling channel is closed"));let r;try{r=this.hub.transport();}catch(i){return Promise.reject(i)}return t?.aborted?Promise.reject(new c("aborted","the caller aborted before the offer was sent")):new Promise((i,o)=>{let a=()=>{s(),o(new c("aborted","the caller aborted the signaling exchange"));},s=()=>{t?.removeEventListener("abort",a),this.hub.release(e.matchId,l),this.teardown===s&&(this.teardown=null);},l={settle:d=>{s(),i(d);},refuse:d=>{s(),o(d);}};this.teardown=s,t?.addEventListener("abort",a),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof c?d:new c("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var cr="match_ended:",ur="server_shutdown:",mr="kicked:",xs=123;function As(n){if(typeof n!="string"||n.length===0||n.length>xs)return {kind:"other"};if(n.startsWith(cr)){let e=Re(n.slice(cr.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return n.startsWith(ur)?{kind:"server_shutdown",cause:n.slice(ur.length)}:n.startsWith(mr)?{kind:"kicked",detail:n.slice(mr.length)}:{kind:"other"}}function on(n,e,t){let r=As(t),i=r.kind==="kicked"?"kicked":"link_closed";n.notifyMatchDisconnected(i).catch(()=>{}),r.kind==="match_ended"&&n.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}var Ps="join",Es="welcome",Ts="rejected",sn=25e3,Is=1e3,an=1;function ln(n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0}var Cs={credential_expired:"credential_expired",credential_reused:"credential_reused",credential_timeout:"timeout",join_rate_limited:"join_rate_limited",expected_join:"join_refused",invalid_credential:"join_refused",credential_not_for_this_channel:"join_refused"};function dn(n){let e=typeof n=="string"?n:"unknown";return new c(Cs[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function Fe(n){let{channel:e,clock:t}=n;return new Promise((r,i)=>{let o=false,a=Math.min(n.credentialExpiresAt-t.now(),n.ceilingMs??sn),s=t.setTimeout(()=>P(new c("timeout","the server runtime sent no welcome before the join credential expired. The channel was open, so this is the runtime not answering rather than a connection that never came up.")),Math.max(a,Is)),l=E=>{let M=E.data;if(typeof M!="string"){u(M);return}let I;try{I=JSON.parse(M);}catch{u(M);return}if(o){u(M);return}if(I.t===Es){let g=ln(I.heartbeat_interval);b({...typeof I.player_id=="string"?{playerId:I.player_id}:{},...typeof I.match_id=="string"?{matchId:I.match_id}:{},...g===void 0?{}:{heartbeatIntervalMs:g}});return}if(I.t===Ts){P(dn(I.reason));return}u(M);},d=()=>{P(new c("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{P(new c("aborted","the caller aborted during the join exchange"));},u=E=>{o&&n.onMessage?.(E);},p=()=>{t.clearTimeout(s),e.removeEventListener("close",d),n.signal?.removeEventListener("abort",m);},h=()=>{e.removeEventListener("message",l);},b=E=>{o=true,p(),n.onMessage===void 0&&h(),r({welcome:E,detach:h});},P=E=>{o||(o=true,p(),h(),i(E));};if(e.addEventListener("message",l),e.addEventListener("close",d),n.signal?.aborted){m();return}n.signal?.addEventListener("abort",m);try{e.send(JSON.stringify({t:Ps,credential:n.credential,...n.wire===void 0?{}:{wire:n.wire},...n.heartbeat===!0?{heartbeat:an}:{}}));}catch(E){P(new c("connection_failed",`the join frame could not be sent on the open channel: ${String(E)}`,{cause:E}));}})}function bt(){return {exchange(){return Promise.reject(new c("signaling_unavailable","no signaling channel is wired. The exchange rides the notification WebSocket, and POST /v1/ws/ticket accepts only account credentials \u2014 a game frame holds a game-scoped token and cannot mint one \u2014 so it has to be relayed by the page embedding this game. Run inside a parent that advertises `dedicated`, or pass your own `signaling` implementation. See docs/dedicated-server-flow.md \xA72."))},close(){}}}var ue=1,je=2,cn=4,pn=8,Ms=2,Os=1e3,gn="heartbeat timeout",_t="gem-uu",vt=2,gr="gem_transports";function Ne(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){if(typeof t!="string")continue;let r=t.toLowerCase();!Ls(r)||e.includes(r)||e.push(r);}return e}function Ls(n){return n==="webtransport"||n==="webrtc"||n==="websocket"}function wt(n,e){if(typeof n!="object"||n===null)return null;let t=n[gr];if(typeof t!="object"||t===null)return null;let r=t;return typeof r.v!="number"||r.v<1||typeof r.host!="string"||typeof r.port!="number"||e!==void 0&&r.match_id!==e?null:r}function kt(n){return n instanceof Error?n.message===""?n.name:`${n.name}: ${n.message}`:String(n)}var hr=new TextEncoder,fr=new TextDecoder;function hn(n,e){let t=new Uint8Array(e.byteLength+1);return t[0]=n,t.set(e,1),t}function fn(n){let e=0;return n?.reliable===false&&(e|=ue),n?.ordered===false&&(e|=je),e}function yn(n){return {reliable:(n&ue)===0,ordered:(n&je)===0}}var bn={reliable:true,ordered:true};function yr(n){return JSON.stringify({t:"join",credential:n,wire:vt,heartbeat:an})}function br(n){let e;try{e=JSON.parse(n);}catch{throw new c("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let t=ln(e.heartbeat_interval);return {...e.player_id===void 0?{}:{playerId:e.player_id},...e.match_id===void 0?{}:{matchId:e.match_id},...t===void 0?{}:{heartbeatIntervalMs:t}}}throw e.t==="rejected"?dn(e.reason):new c("join_refused","the server answered the join out of protocol")}function _n(){return typeof globalThis.WebTransport=="function"&&vn===null}function Rt(){return vn}var vn=null;var pr="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Gs(n){let e=Xt(n);if(e.byteLength!==32)throw new c("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var un=class{buffered=new Uint8Array(0);push(e){let t=new Uint8Array(this.buffered.byteLength+e.byteLength);t.set(this.buffered,0),t.set(e,this.buffered.byteLength),this.buffered=t;let r=[];for(;!(this.buffered.byteLength<4);){let o=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(o===0||o>1<<20)throw new c("connection_failed",`a control-stream record claims ${o} bytes`);if(this.buffered.byteLength<4+o)break;let a=this.buffered.slice(4,4+o);this.buffered=this.buffered.slice(4+o),r.push({flags:a[0]??0,payload:a.slice(1)});}return r}};function mn(n,e){let t=new Uint8Array(5+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength+1,true),t[4]=n,t.set(e,5),t}async function Ue(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webTransport;if(t===void 0){let s=globalThis.WebTransport;if(s===void 0)throw new c("connection_failed","this environment has no WebTransport");t=n.certHashBase64===void 0?new s(n.url):new s(n.url,{serverCertificateHashes:[{algorithm:"sha-256",value:Gs(n.certHashBase64)}]});}let r=t,i=s=>{try{r.close();}catch{}throw s},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(vn=pr,i(new c("connection_failed",`${pr}; the rung is skipped for the rest of this page (a reload probes again)`)));let a=new Promise((s,l)=>{setTimeout(()=>l(new c("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,a]);let s=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([s.read(),a]);if(s.releaseLock(),l.done||l.value===void 0)return i(new c("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(mn(cn,hr.encode(yr(n.credential))));let u=new un,p=d.readable.getReader(),h;for(;h===void 0;){let b=await Promise.race([p.read(),a]);if(b.done||b.value===void 0)return i(new c("connection_failed","the control stream closed before the join was answered"));for(let P of u.push(b.value)){h=br(fr.decode(P.payload));break}}return {link:Ds(r,m,p,u,n.log??(b=>console.warn(b)),vr(h,n.clock)),welcome:h}}catch(s){return i(s)}}function Ds(n,e,t,r,i,o){let a,s,l=false,d=b=>{if(!l){l=true,m.stop();try{n.close();}catch{}s?.(b);}},m=kn(o,()=>d(gn)),u=(b,P)=>{m.heard(),(b&pn)===0&&a!==void 0&&((b&cn)!==0?a(fr.decode(P),bn):a(P,yn(b)));};(async()=>{try{for(;;){let b=await t.read();if(b.done||b.value===void 0)break;for(let P of r.push(b.value))u(P.flags,P.payload);}}catch{}d("stream closed");})();let p,h;try{let b=n.datagrams;if(b?.readable!==void 0&&b.writable!==void 0){let P=b.readable.getReader();h=b.writable.getWriter(),p=b,(async()=>{try{for(;;){let E=await P.read();if(E.done||E.value===void 0)break;let M=E.value;M.byteLength!==0&&u((M[0]??0)|ue|je,M.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(b){p=void 0,h=void 0,i(`[gem] webtransport datagram lane unusable (${kt(b)}); unreliable sends ride the stream`);}return n.closed.then(b=>d(_r(b?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(b,P){if(l)return;if(typeof b=="string"){e.write(mn(cn,hr.encode(b))).catch(()=>d("write failed"));return}let E=fn(P);if((E&ue)!==0&&h!==void 0){let M=hn(E,b),I=p?.maxDatagramSize;if(I===void 0||M.byteLength<=I){h.write(M).catch(()=>{});return}}e.write(mn(E,b)).catch(()=>d("write failed"));},onMessage(b){a=b;},onClose(b){s=b;},close(){d("closed");}}}function wn(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webSocket;if(t===void 0){let i=globalThis.WebSocket;if(i===void 0)return Promise.reject(new c("connection_failed","this environment has no WebSocket"));t=new i(n.url);}let r=t;return r.binaryType="arraybuffer",new Promise((i,o)=>{let a=false,s=setTimeout(()=>{a||(a=true,r.close(),o(new c("timeout","websocket did not come up in time")));},e),l=h=>{a||(a=true,clearTimeout(s),r.close(),o(h));},d=()=>{r.send(yr(n.credential));},m=h=>{if(a)return;if(typeof h.data!="string"){l(new c("join_refused","the server sent binary before answering the join"));return}let b;try{b=br(h.data);}catch(P){l(P);return}a=true,clearTimeout(s),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",u),r.removeEventListener("error",p),i({link:qs(r,vr(b,n.clock)),welcome:b});},u=()=>{l(new c("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new c("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",m),r.addEventListener("close",u),r.addEventListener("error",p),r.readyState===1&&d();})}function _r(n){return typeof n=="string"&&n.length>0?n:void 0}function vr(n,e){return n.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:n.heartbeatIntervalMs}}function kn(n,e){if(n===void 0)return {heard:()=>{},stop:()=>{}};let{clock:t}=n,r=Math.max(n.intervalMs,Os)*Ms,i=t.now(),o=null,a=()=>{o=null;let s=t.now()-i;if(s>=r){e();return}o=t.setTimeout(a,r-s);};return o=t.setTimeout(a,r),{heard:()=>{i=t.now();},stop:()=>{o!==null&&(t.clearTimeout(o),o=null);}}}function qs(n,e){let t,r,i=false,o=s=>{if(!i){i=true,a.stop();try{n.close();}catch{}r?.(s);}},a=kn(e,()=>o(gn));return n.addEventListener("message",(s=>{if(a.heard(),typeof s.data=="string"){t?.(s.data,bn);return}let l=new Uint8Array(s.data);if(l.byteLength===0)return;let d=l[0]??0;(d&pn)===0&&t?.(l.slice(1),yn(d));})),n.addEventListener("close",(s=>o(_r(s?.reason)??"socket closed"))),{transport:"websocket",send(s,l){if(!i){if(typeof s=="string"){n.send(s);return}n.send(hn(fn(l),s));}},onMessage(s){t=s;},onClose(s){r=s;},close(){o("closed");}}}function Rn(n,e,t,r){let i,o,a=false,s=t,l=u=>{if(!a){a=true,d.stop();try{n.close();}catch{}try{e.close();}catch{}o?.(u);}},d=kn(r,()=>l(gn)),m=(u,p)=>{if(d.heard(),typeof u=="string"){i?.(u,bn);return}let h=new Uint8Array(u);if(h.byteLength===0)return;let b=h[0]??0;(b&pn)===0&&i?.(h.slice(1),yn(b|p));};if(n.addEventListener("message",(u=>m(u.data,0))),n.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let u=e.connectionState;(u==="failed"||u==="closed")&&l(`connection ${u}`);})),s!==void 0){let u=s;u.addEventListener("message",(p=>m(p.data,ue|je))),u.addEventListener("close",(()=>{s=void 0;}));}return {transport:"webrtc",send(u,p){if(a)return;if(typeof u=="string"){n.send(u);return}let h=fn(p),b=hn(h,u);if((h&ue)!==0&&s!==void 0&&s.readyState==="open"){s.send(b);return}n.send(b);},onMessage(u){i=u;},onClose(u){o=u;},close(){l("closed");}}}var wr=10240,kr=2048,$s=new TextEncoder;function Rr(n){return $s.encode(n).length}function ie(n,e){let t=i=>{throw new c("invalid_sdp",`the ${e} ${i}`)},r=Rr(n);r>=wr&&t(`is ${r} bytes, over the ${wr} limit`+(e==="offer"?", which for an offer means an unusually wide candidate list":"")),n.startsWith("v=")||t("does not start with 'v=', so it is not SDP"),n.includes("\0")&&t("contains a null byte"),/\r(?!\n)/.test(n)&&t("contains a bare carriage return");for(let i of n.split(/\r\n|\n/)){let o=Rr(i);o>kr&&t(`has a ${o}-byte line, over the ${kr} limit`);}}function St(n){for(let e of n.split(/\r\n|\n/)){if(!e.startsWith("m="))continue;let[t,r="0"]=e.slice(2).trim().split(/\s+/);if(!(t!=="audio"&&t!=="video")&&r.split("/")[0]!=="0")return true}return false}var Fs=3e3,js=1e4,Ns=15e3;async function Be(n){let e=n.peerConnection;try{xr(n,"before the handshake started"),Sn(n);let t=e.createDataChannel(n.channelLabel??"gem",{ordered:!0});for(let a of n.extraChannels??[]){let s=e.createDataChannel(a.label,{...a.ordered===void 0?{}:{ordered:a.ordered},...a.maxRetransmits===void 0?{}:{maxRetransmits:a.maxRetransmits}});n.onExtraChannel?.(a.label,s);}let r=await e.createOffer();await e.setLocalDescription(r),await Ws(e,n),Sn(n);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new c("invalid_sdp","the offer carried no SDP");ie(i,"offer"),Sr(i,"offer");let o=await Bs(n,i);if(Sn(n),typeof o?.sdp!="string")throw new c("invalid_sdp","the signaling channel answered without an SDP");return ie(o.sdp,"answer"),Sr(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await Vs(t,n),xr(n,"before the channel opened"),t}catch(t){throw e.close(),Us(t)}}function Us(n){return n instanceof c?n:Er(n)?me():new c("connection_failed",Tr(n),{cause:n})}function Sr(n,e){if(St(n))throw new c("media_refused",`the ${e} carries an active audio or video section. This path carries a data channel only; voice belongs to the platform voice service.`)}async function Bs(n,e){let t=n.exchangeTimeoutMs??js,r=Pr(n,t),i=n.signaling.exchange({matchId:n.matchId,sdp:e,intent:n.intent??"initial"},n.signal).catch(o=>{throw o instanceof c?o:Er(o)?me():new c("signaling_failed",Tr(o),{cause:o})});return Hs(i,n,r,()=>r.exhausted?xn("while the offer was in flight"):new c("timeout",`no answer arrived within ${t}ms`))}function Ws(n,e){if(n.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:t}=e;return new Promise(r=>{let i=()=>{t.clearTimeout(a),n.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{n.iceGatheringState==="complete"&&i();},a=t.setTimeout(i,e.gatherTimeoutMs??Fs);n.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function Vs(n,e){if(e.signal?.aborted)return Promise.reject(me());if(n.readyState==="open")return Promise.resolve();if(n.readyState!=="connecting")return Promise.reject(new c("connection_failed",`the data channel was already '${n.readyState}' when the answer was applied`));let{clock:t}=e,r=e.openTimeoutMs??Ns,i=Pr(e,r);return new Promise((o,a)=>{let s=()=>{t.clearTimeout(p),n.removeEventListener("open",l),n.removeEventListener("close",d),n.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{s(),o();},d=h=>{s(),a(new c("connection_failed","the data channel failed before it opened",Ar(h)===void 0?void 0:{cause:Ar(h)}));},m=()=>{s(),a(me());},u=()=>{s(),a(i.exhausted?xn("while the channel was still opening"):new c("timeout",`the data channel did not open within ${r}ms`));},p=t.setTimeout(u,i.ms);n.addEventListener("open",l),n.addEventListener("close",d),n.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function Pr(n,e){if(n.credentialExpiresAt===void 0)return {ms:e,exhausted:false};let t=n.credentialExpiresAt-n.clock.now();return t<=e?{ms:Math.max(0,t),exhausted:true}:{ms:e,exhausted:false}}function Hs(n,e,t,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(me()):new Promise((a,s)=>{let l=u=>{i.clearTimeout(m),o?.removeEventListener("abort",d),u();},d=()=>l(()=>s(me())),m=i.setTimeout(()=>l(()=>s(r())),t.ms);o?.addEventListener("abort",d),n.then(u=>l(()=>a(u)),u=>l(()=>s(u)));})}function xr(n,e){if(n.credentialExpiresAt!==void 0&&!(n.clock.now()<n.credentialExpiresAt))throw xn(`already ${e}`)}function xn(n){return new c("credential_expired",`the join credential ran out ${n} \u2014 poll match status again for a fresh one`)}function Sn(n){if(n.signal?.aborted)throw me()}function me(){return new c("aborted","the caller aborted the connection attempt")}function Er(n){return n?.name==="AbortError"}function Ar(n){return n?.error}function Tr(n){return n instanceof Error?n.message:String(n)}var We="0.1.0-beta",Ir="0-beta",Se="web",Ks=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/;function Js(n){let e=Ks.exec(n),t=e?.[1],r=e?.[4];return t===void 0?null:r===void 0?t:`${t}-${r}`}function Cr(n,e){let t=zs(n.platform,e),r=n.engineVersion;if(r===void 0)return {...n,platform:t,engineVersion:We};let i=Js(r);if(i===null)throw new c("misconfigured",`${e} refused: engineVersion '${r}' is not semver, so no engine line can be derived from it and gem-api answers 400. Omit it \u2014 a browser game has no engine version of its own, and the SDK reports '${We}' for it.`);if(i!==Ir)throw new c("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${Ir}' is the only line a web dedicated-server fleet runs. gem-api uses the line \u2014 the semver major plus any prerelease tag \u2014 verbatim as the fleet's label selector, so a match on '${i}' would match nothing and be reported as a capacity shortfall rather than as this. Omit engineVersion: a browser game has no engine version of its own, and the SDK reports '${We}' for it.`);return {...n,platform:t,engineVersion:r}}function zs(n,e){if(n===void 0||n===Se)return Se;if(!Qt.includes(n))throw new c("misconfigured",`${e} refused: platform '${String(n)}' is not a client platform gem-api recognises \u2014 it knows ${Qt.map(t=>`'${t}'`).join(", ")}. Remove the field: the SDK reports '${Se}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${n}' was replaced with '${Se}' and is deprecated \u2014 remove the field. A browser game publishes its bundle in the web package dimension, so a client reporting anything else is version-checked against a dimension it has nothing in, and every blacklist, release and expiry check passes without looking at this build.`),Se}function Xs(n){let{client:e,clock:t,rooms:r}=n,i=n.signaling??bt,o=n.log??(g=>console.warn(g)),a=new ce({client:e,gameId:()=>r.gameId,transport:"dedicated"}),s=new Map,l=(g,_)=>{let k=s.get(g)??new Set;k.add(_),s.set(g,k);},d=(g,_)=>{let k=s.get(g);k!==void 0&&(k.delete(_),k.size===0&&s.delete(g));},m=async g=>{if(r.isHost&&!oa(r)&&r.currentRoom?.matchId===void 0){let _=B(g.clusterTargetId);await r.startMatch({..._===void 0?{}:{clusterTargetId:_},...g.retry===void 0?{}:{retry:g.retry},...g.signal===void 0?{}:{signal:g.signal}});}return qr(r.matchConnectionState==="suspended"?await r.reconnectToMatch(An(g)):await r.awaitMatch(An(g)))},u=async g=>qr(await r.pollMatchStatus(An(g))),p=async(g,_)=>{let k=false;try{let v=await m(g),G=r.currentRoom?.transports;if(G!==void 0&&!G.includes("webrtc"))throw new c("misconfigured",`the room template offers (${G.join(", ")||"no transports"}), not webrtc, which is all this path dials. Connect through gem.match.connect(), or pass \`transports: []\` here to negotiate across the template's list.`);let C=g.peerConnection??$r();k=!0;let D=await Be({peerConnection:C,signaling:_,clock:t,matchId:v.matchId,credentialExpiresAt:v.credentialExpiresAt,...xt(g,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),F=null;if(g.presentCredential!==!1)try{F=await Fe({channel:D,clock:t,credential:v.joinCredential,credentialExpiresAt:v.credentialExpiresAt,...xt(g,"onMessage","signal"),...g.welcomeTimeoutMs===void 0?{}:{ceilingMs:g.welcomeTimeoutMs}});}catch(N){throw K(D),K(C),N}return ia(r,v,D,C,_,g.reportDisconnect!==!1,g.reportConnected!==!1,F,{remember:l,forget:d},g.onMatchEnded)}catch(v){throw k&&Dr(a,v),K(_),v}},h=async(g,_,k,v,G,C)=>{if(g==="webtransport"){let O=v?.webtransport;if(O===void 0)throw new c("misconfigured","webtransport is not advertised");let X={credential:k.joinCredential,credentialExpiresAt:k.credentialExpiresAt,clock:t};if(typeof O.named_url=="string"&&O.named_url!==""){let ne=Math.max(Math.floor(C/2),1e3);try{return await Ue({url:O.named_url,timeoutMs:ne,log:o,...X})}catch(oe){if(Rt()!==null)throw oe;return o(`[gem] webtransport named dial failed (${kt(oe)}); retrying the pinned dial`),Ue({url:O.url,certHashBase64:O.cert_sha256_b64,timeoutMs:ne,log:o,...X})}}return Ue({url:O.url,certHashBase64:O.cert_sha256_b64,timeoutMs:C,...X})}if(g==="websocket"){let O=v?.websocket;if(O===void 0)throw new c("misconfigured","websocket is not advertised");return wn({url:O.url,credential:k.joinCredential,credentialExpiresAt:k.credentialExpiresAt,clock:t,timeoutMs:C})}let D=_.peerConnection??$r(),F,N=await Be({peerConnection:D,signaling:G,clock:t,matchId:k.matchId,credentialExpiresAt:k.credentialExpiresAt,extraChannels:[{label:_t,ordered:false,maxRetransmits:0}],onExtraChannel:(O,X)=>{O===_t&&(F=X);},...xt(_,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),..._.exchangeTimeoutMs===void 0&&_.redial===true?{exchangeTimeoutMs:Qs}:{}}),H;try{H=await Fe({channel:N,clock:t,credential:k.joinCredential,credentialExpiresAt:k.credentialExpiresAt,wire:vt,heartbeat:!0,...xt(_,"signal"),..._.welcomeTimeoutMs===void 0?{}:{ceilingMs:_.welcomeTimeoutMs}});}catch(O){throw K(N),K(D),O}let x=H.welcome.heartbeatIntervalMs;return {link:Rn(N,D,F,x===void 0?void 0:{clock:t,intervalMs:x}),welcome:H.welcome,channel:N,peerConnection:D}},b=(g,_,k,v,G)=>{let C=false,D;v.link.onClose(x=>{!C&&g.reportDisconnect!==false&&on(r,_.matchId,x),D?.(x);}),g.reportDisconnect!==false&&g.reportConnected!==false&&r.notifyMatchConnected(_.matchId);let F={transport:v.link.transport,send:(x,O)=>v.link.send(x,O),onMessage:x=>v.link.onMessage(x),onClose:x=>{D=x;},close:()=>v.link.close()},N=()=>{C||(C=true,K(v.link),K(G));},H=x=>{if(!C){try{g.onMatchEnded?.(x);}catch{}N();}};return l(_.matchId,H),{matchId:_.matchId,transport:k,link:F,joinCredential:_.joinCredential,credentialExpiresAt:_.credentialExpiresAt,welcome:v.welcome,...v.channel===void 0?{}:{channel:v.channel},...v.peerConnection===void 0?{}:{peerConnection:v.peerConnection},close(){d(_.matchId,H),N();}}},P=async(g,_)=>{let k=r.currentRoom?.id,v=r.gameId,G=()=>({advert:wt(r.currentRoom?.settings,g),template:r.currentRoom?.transports??null});if(k===void 0||v===null)return G();try{let C=await e.get(`/v2/games/${encodeURIComponent(v)}/game-rooms/${encodeURIComponent(k)}`,_);return {advert:wt(C.settings,g),template:Ne(C.transports)??r.currentRoom?.transports??null}}catch{return G()}},E=(g,_)=>{let k=g??Mr;return _.length===0?k:k.filter(v=>_.includes(v))},M=async(g,_,k)=>{try{let v=await m(g),{advert:G,template:C}=await P(v.matchId,g.signal),D=E(C,_),F=D.filter(q=>ta(q,G)),N=Rt();if(N!==null&&D.includes("webtransport")&&G?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${N} (learned on an earlier dial in this page)`),F.length===0){let q=C===null?`the default order (${Mr.join(", ")})`:`the room template's transports (${C.join(", ")||"none"})`;throw new c("misconfigured",`none of ${q}`+(_.length>0?`, narrowed to (${_.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let H=g.transportAttemptTimeoutMs??Ys,x=()=>g.deadlineAt===void 0?1/0:g.deadlineAt-t.now(),O=q=>n.signalingReady===void 0||q<=0?Promise.resolve(!0):n.signalingReady(q),X=[],ne=[];for(let q of F){if(x()<Lr){o(`[gem] ${q} rung not tried: the reconnect budget is spent`);break}ne.length>0&&v.credentialExpiresAt-t.now()<Gr&&(v=await u(g)),ne.push(q);let Fn=!1,jn=!1,Ze={attempts:0,waitedMs:0};for(;;){if(q==="webrtc"&&g.redial===!0){let Q=Math.min(Or,x());await O(Q)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(Q)}ms; offering anyway`);}let fi=Math.max(Math.min(H,x()),Lr);try{return b(g,v,q,await h(q,g,v,G,k,fi),k)}catch(Q){let U=Q instanceof c?Q:new c("connection_failed",Q instanceof Error?Q.message:String(Q),{cause:Q});if(q==="webrtc"&&Dr(a,U),(U.reason==="credential_expired"||U.reason==="credential_reused")&&!Fn){Fn=!0,v=await u(g);continue}if(q==="webrtc"&&U.reason==="signaling_failed"&&U.platformCode===nn&&!jn){jn=!0;let se=Math.min(Or,x());if(o(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(se)}ms for the socket before offering again`),await O(se))continue}if(U.reason==="join_rate_limited"){let se=ea(Ze,Math.random,x());if(se!==null){if(Ze.attempts+=1,Ze.waitedMs+=se,o(`[gem] ${q} rung: the server is rate-limiting this player's joins; waiting ${Math.round(se)}ms before presenting again (retry ${Ze.attempts} of ${jr.maxAttempts})`),await ft(t,se,g.signal),g.signal?.aborted)throw new c("aborted","the caller aborted while waiting out a join rate limit");v.credentialExpiresAt-t.now()<Gr&&(v=await u(g));continue}}if(Zs.has(U.reason)||U.reason==="credential_expired"||q==="webrtc"&&Fr(U)){o(`[gem] ${q} rung failed (${U.reason}): ${kt(U.cause??U)} \u2014 `+(ne.length<F.length?`falling through to ${F[ne.length]}`:"no rungs left")),X.push(U);break}throw o(`[gem] ${q} rung refused the session (${U.reason}): ${U.message}`),U}}}let oe=X[X.length-1];throw oe===void 0?new c("timeout",`the reconnect budget ran out before any transport (${F.join(", ")}) could be tried`):new c(oe.reason,`every transport tried (${ne.join(", ")}) failed; the last said: ${oe.message}`,{cause:X,platformCode:oe.platformCode})}catch(v){throw K(k),v}};return {listClusterTargets:async(g={})=>ht({client:e,...g}),handleMatchEnded(g,_){let k=s.get(g);if(k!==void 0){s.delete(g);for(let v of k)v(_);}},connect:(async(g={})=>{let _=g.signaling??i();return g.transports===void 0?p(g,_):M(g,g.transports,_)})}}var Mr=["webtransport","webrtc","websocket"],Ys=1e4,Qs=5e3,Or=3e3,Lr=1e3,Gr=1e4,Zs=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function Fr(n){return n.platformCode!==void 0&&rn.has(n.platformCode)}var jr={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function ea(n,e=Math.random,t=1/0){let r=jr;if(n.attempts>=r.maxAttempts)return null;let i=Math.min(r.budgetMs-n.waitedMs,t);if(i<r.initialDelayMs)return null;let o=r.initialDelayMs*r.factor**n.attempts;return Math.min(o+e()*r.jitterMs,i)}function ta(n,e){return n==="webrtc"?e===null||e.webrtc!==false:e===null?false:n==="webtransport"?e.webtransport!==void 0&&_n():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||na(e.websocket.url)}function na(n){if(typeof n!="string")return false;let e;try{e=new URL(n).hostname.toLowerCase();}catch{return false}return ct(e)}function An(n){return {...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.pollIntervalMs===void 0?{}:{pollIntervalMs:n.pollIntervalMs},...n.signal===void 0?{}:{signal:n.signal}}}var ra=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Dr(n,e){e instanceof c&&(!ra.has(e.reason)&&!Fr(e)||n.report([{type:"connection_failures_total",value:1}]));}function ia(n,e,t,r,i,o,a,s,l,d){let m=false,u=()=>{m||on(n,e.matchId,void 0);};o&&(t.addEventListener("close",u),a&&n.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,t.removeEventListener("close",u),s?.detach(),K(t),K(r),K(i));},h=b=>{if(!m){try{d?.(b);}catch{}p();}};return l.remember(e.matchId,h),{matchId:e.matchId,channel:t,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:s?.welcome??null,close(){l.forget(e.matchId,h),p();}}}function oa(n){let e=n.matchSession.phase;return e!=="none"&&e!=="ended"}function qr(n){if(n.status==="failed")throw new c("allocation_failed",`match ${n.matchId} did not come up: ${n.reason}`);if(n.status==="ended")throw new c("match_ended",`match ${n.matchId} ended (${n.reason}) before this side connected.`);if(n.protocol!==$e)throw new c("unsupported_protocol",`match ${n.matchId} speaks '${n.protocol}', which a browser cannot connect. Only '${$e}' is reachable from a frame; host and port on this response are advisory and must not be dialled.`);let{joinCredential:e,credentialExpiresAt:t}=n;if(e===void 0||t===void 0)throw new c("connection_failed",`match ${n.matchId} is ready but issued no join credential, so the server would refuse the channel once it opened \u2014 poll match status again.`);return {...n,joinCredential:e,credentialExpiresAt:t}}function $r(){let n=globalThis.RTCPeerConnection;if(!n)throw new c("misconfigured","this environment has no RTCPeerConnection. Pass `peerConnection` to connect against a stand-in, which is how the flow is tested outside a browser.");return new n({iceServers:[]})}function K(n){try{n.close();}catch{}}function xt(n,...e){let t={};for(let r of e)n[r]!==void 0&&(t[r]=n[r]);return t}var xe=class{constructor(e){this.options=e;this.reporter=new ce({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,t,r){let i=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:t},r);return {credential:At(i.credential)??"",hostFingerprint:At(i.host_fingerprint)??"",hostEpoch:Pt(i.host_epoch)??0,expiresAt:(Pt(i.expires_at)??0)*1e3}}async turnLease(e,t,r){let i=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:t},r),o=[];for(let l of Array.isArray(i.ice_servers)?i.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(u=>typeof u=="string"&&u.length>0);m.length!==0&&o.push({urls:m,username:At(d.username)??"",credential:At(d.credential)??""});}let a=Pt(i.expires_at),s=Pt(i.ttl_seconds);return {iceServers:o,expiresAt:a!==void 0?a*1e3:Date.now()+(s??0)*1e3}}async kick(e,t,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:t},r);}async leave(e,t=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:t});}async telemetry(e,t){await this.reporter.post(e,t);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}};function At(n){return typeof n=="string"&&n.length>0?n:void 0}function Pt(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}var sa=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),w=class extends Error{constructor(t,r,i){super(`${t}: ${r}`,i);this.reason=t;this.name="P2pError",this.retryable=sa.has(t);}reason;retryable};var Et=class{listeners=new Map;on(e,t){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>this.off(e,t)}off(e,t){this.listeners.get(e)?.delete(t);}once(e,t){let r=this.on(e,((...i)=>{r(),t(...i);}));return r}emit(e,...t){let r=this.listeners.get(e);if(r)for(let i of [...r])i(...t);}clear(){this.listeners.clear();}};var aa=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function pe(n){let e=null;for(let t of n.split(/\r\n|\n/)){if(!t.startsWith("a=fingerprint:"))continue;let r=Ve(t.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function Ve(n){let[e,...t]=n.trim().split(/\s+/);if(e===void 0||t.length===0)return null;let r=`${e.toLowerCase()} ${t.join("").toUpperCase()}`;return aa.test(r)?r:null}function Ae(n,e){if(n.length!==e.length)return false;let t=0;for(let r=0;r<n.length;r++)t|=n.charCodeAt(r)^e.charCodeAt(r);return t===0}var Pn=5e3,la=12e4+Pn,da=1024,ca=6e4,ua=1e4,Nr=64*1024,Ur=5;function Tt(n){let e=new Map,t=-1/0,r=null,i=(()=>{let s;try{s=new URL(`${n.baseUrl.replace(/\/+$/,"")}/oauth2/jwks`);}catch{return {ok:false,reason:"the configured API base is not a valid URL, so the JWKS endpoint cannot be reached. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}}return s.username!==""||s.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:s.href,shown:`${s.protocol}//${s.host}`}})(),o=()=>{let s=n.subtle??globalThis.crypto?.subtle;if(!s)throw new w("keys_unavailable","this environment has no WebCrypto, so a join credential cannot be verified. A page served over plain http on a non-loopback origin is the usual cause \u2014 crypto.subtle is only exposed in a secure context.");return s},a=async()=>{if(!i.ok)throw new w("keys_unavailable",i.reason);let s=n.fetch??((p,h)=>globalThis.fetch(p,h)),l;try{l=await s(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(ua)});}catch{throw new w("keys_unavailable",`the JWKS endpoint at ${i.shown} could not be reached \u2014 it timed out, refused a redirect, or the network failed.`)}if(!l.ok)throw new w("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let d;try{let p=await l.text();if(p.length>Nr)throw new w("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${Nr} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof w?p:new w("keys_unavailable",`the JWKS endpoint at ${i.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>Ur)throw new w("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${Ur} the platform declares. Refusing rather than verifying against a set of unknown size.`);let u=o();for(let p of m){let h=p;if(h.kty==="RSA"&&!(h.alg!==void 0&&h.alg!=="RS256")&&!(h.use!==void 0&&h.use!=="sig")&&!(typeof h.kid!="string"||h.kid.length===0))try{let b=await u.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(h.kid,b);}catch{}}};return {async key(s){let l=e.get(s);if(l)return l;if(!i.ok)throw new w("keys_unavailable",i.reason);if(r)return await r,e.get(s)??null;let d=n.now();if(!Number.isFinite(d))throw new w("keys_unavailable","the clock supplied to the SDK returned a non-finite time, so the JWKS throttle cannot be evaluated. This is a configuration fault, not a server failure.");return d<t&&(t=-1/0),d-t<ca?null:(t=d,r??=a().finally(()=>{r=null;}),await r,e.get(s)??null)}}}var He=class{seen=new Map;admit(e,t){for(let[r,i]of this.seen)i<=t&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=da){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,t+la),true}};function Wr(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return r}function Br(n){try{let e=new TextDecoder().decode(Wr(n)),t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch{return null}}async function It(n,e,t,r,i){let o=x=>{throw new w("peer_unauthenticated",`the peer's join credential is not usable: ${x}`)},a=n.split(".");a.length!==3&&o("it is not a three-part JWT");let[s,l,d]=a,m=Br(s);m===null&&o("its header does not decode"),m.alg!=="RS256"&&o(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let u=m.kid;(typeof u!="string"||u.length===0)&&o("it names no key");let p=await t.key(u);p===null&&o("it was signed by a key this build cannot resolve");let h=i.subtle??globalThis.crypto?.subtle;h||o("this environment has no WebCrypto");let b=new TextEncoder().encode(`${s}.${l}`),P;try{P=Wr(d);}catch{o("its signature does not decode");}await h.verify({name:"RSASSA-PKCS1-v1_5"},p,P,b)||o("its signature does not verify");let M=Br(l);M===null&&o("its payload does not decode");let I=M,g=x=>typeof I[x]=="string"?I[x]:"",_=x=>typeof I[x]=="number"&&Number.isFinite(I[x])?I[x]:NaN;g("iss")!==i.issuer&&o("it was issued by someone else"),g("aud")!==`${i.issuer}/p2p-match`&&o("its audience is not this platform"),g("match_id")!==e.matchId&&o("it is for another match"),g("game_id")!==e.gameId&&o("it is for another game");let k=_("exp")*1e3,v=_("nbf")*1e3;(!Number.isFinite(k)||e.now>k+Pn)&&o("it has expired"),Number.isFinite(v)&&e.now<v-Pn&&o("it is not valid yet");let G=g("role");G!=="host"&&G!=="client"&&o("it names no usable role");let C=_("host_epoch");C!==e.hostEpoch&&o("it names a different host epoch");let D=Ve(g("fingerprint"));D===null&&o("its fingerprint claim is malformed"),Ae(D,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let F=Ve(g("host_fingerprint"));F===null&&o("its host fingerprint claim is malformed"),Ae(F,e.hostFingerprint)||o("it was issued against a different host certificate");let N=g("jti");N.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit(N,e.now)||o("it has already been used");let H=g("sub");return H.length===0&&o("it names no player"),{playerId:H.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:C,role:G,fingerprint:D,hostFingerprint:F,jti:N,expiresAt:k}}var ge=32769;function En(n){let e=new TextEncoder().encode(n.jwt);if(e.length>8192)throw new Error(`[gem] a join credential of ${e.length} bytes exceeds the wire format's cap`);let t=new ArrayBuffer(3+e.length+4+4),r=new DataView(t);return r.setUint8(0,1),r.setUint16(1,e.length,true),new Uint8Array(t,3,e.length).set(e),r.setUint32(3+e.length,n.protocolVersion,true),r.setUint32(7+e.length,n.assignedPeerId,true),t}function Tn(n){let e=new ArrayBuffer(9),t=new DataView(e);return t.setUint8(0,2),t.setUint32(1,n.protocolVersion,true),t.setUint32(5,n.assignedPeerId,true),e}function In(n){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,3),t.setUint8(1,n),e}function Cn(n){if(n.byteLength<1)return null;let e=new DataView(n);switch(e.getUint8(0)){case 1:{if(n.byteLength<3)return null;let t=e.getUint16(1,true);return t>8192||n.byteLength<3+t+8?null:{kind:"join",jwt:new TextDecoder().decode(new Uint8Array(n,3,t)),protocolVersion:e.getUint32(3+t,true),assignedPeerId:e.getUint32(7+t,true)}}case 2:return n.byteLength<9?null:{kind:"admit",protocolVersion:e.getUint32(1,true),assignedPeerId:e.getUint32(5,true)};case 3:return n.byteLength<2?null:{kind:"reject",reason:e.getUint8(1)};default:return null}}function Vr(n){switch(n){case 1:return "the host did not accept this credential";case 2:return "the host speaks a different protocol version \u2014 an engine peer refuses a browser peer here, deliberately";case 3:return "the match is full";case 4:return "the host is rate-limiting joins";case 129:return "the host verified this credential but it names a different player than the one who signalled \u2014 the host has its own line saying which";case 130:return "the host has this player on the kicked list for the current host epoch";case 131:return "the host could not fetch the platform's signing keys, so it cannot verify anyone yet \u2014 the host's console says why";default:return `the host refused with an unrecognised code (${n})`}}function Hr(n){switch(n){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var Kr=3e4,Pe=class{constructor(e,t,r){this.localPlayerId=e;this.hostPlayerId=t,this.epoch=r;}localPlayerId;state="idle";epoch;hostPlayerId;kicked=new Set;startedAt=0;get currentState(){return this.state}get currentEpoch(){return this.epoch}get currentHostPlayerId(){return this.hostPlayerId}get isLocalHost(){return this.hostPlayerId===this.localPlayerId}isKicked(e){return this.kicked.has(e)}stalled(e){return this.state!=="idle"&&e-this.startedAt>3e4}apply(e,t){return !Number.isInteger(e.hostEpoch)||e.hostEpoch<0?{kind:"refused",why:`host epoch ${String(e.hostEpoch)} is not a whole number`}:e.hostEpoch===this.epoch?e.migrationComplete===true&&this.state!=="idle"?(this.state="idle",{kind:"completed"}):{kind:"duplicate"}:e.hostEpoch<this.epoch?{kind:"refused",why:`host epoch ${e.hostEpoch} is behind the current ${this.epoch}`}:e.hostPlayerId.length===0?{kind:"refused",why:"the migration named no new host"}:(this.kicked=new Set(e.kickedPlayerIds??[]),this.epoch=e.hostEpoch,this.hostPlayerId=e.hostPlayerId,this.startedAt=t,this.state=this.isLocalHost?"preparing":"reconnecting",{kind:"accepted",state:this.state})}complete(){this.state="idle";}};var Ct={reliable:{negotiated:true,id:0,ordered:true},ordered:{negotiated:true,id:1,ordered:true,maxRetransmits:0},unreliable:{negotiated:true,id:2,ordered:false,maxRetransmits:0}},Ke=["reliable","ordered","unreliable"];function Mt(n){let e=globalThis.RTCPeerConnection;if(!e)throw new Error("[gem] this environment has no RTCPeerConnection. Pass `peerConnectionFactory` to connect against a stand-in, which is how this flow is tested outside a browser.");return new e({iceServers:n.iceServers,...n.certificates===void 0?{}:{certificates:n.certificates}})}async function Ot(){let n=globalThis.RTCPeerConnection;return n?.generateCertificate?n.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var zr=1,fa=3e4,Xr=2e3,ya=5e3,Yr=6e4,ba=8,On=class{constructor(e=ba){this.perMinute=e;}perMinute;sent=[];delayUntilAllowed(e){return this.prune(e),this.sent.length<this.perMinute?0:Math.max(0,(this.sent[0]??e)+6e4-e)}record(e){this.prune(e),this.sent.push(e);}prune(e){let t=0;for(let r of this.sent)r<=e&&e-r<6e4&&(this.sent[t++]=r);this.sent.length=t;}},_a=new On,va=8,wa=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),Ee=class{constructor(e){this.options=e;this.keys=e.keys??Tt({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new Et;links=new Map;replays=new He;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=zr+1;ended=null;closed=false;ready=null;helloSeen=false;reportedUnreachableEpoch=-1;reportedStallEpoch=-1;counted=false;pendingOffers=new Map;answeredSessions=new Map;credentialGeneration=0;credentialDeadline=0;get matchId(){return this.options.matchId}get playerId(){return this.localPlayerId}get isHost(){return this.migration?.isLocalHost??false}get hostPlayerId(){return this.migration?.currentHostPlayerId??""}get hostEpoch(){return this.migration?.currentEpoch??0}get peers(){let e=[];for(let t of this.links.values())t.admitted&&e.push(this.expose(t));return e}peer(e){let t=this.links.get(e);return t&&t.admitted?this.expose(t):null}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t);}once(e,t){return this.emitter.once(e,t)}async start(e){let t=this.options.connectTimeoutMs??fa;this.credentialDeadline=this.options.clock.now()+t;let r=new Promise((s,l)=>{this.ready={resolve:s,reject:l};}),i=B(this.options.clusterTargetId);if(i!==void 0)try{let s=await this.options.api.turnLease(this.options.matchId,i,e);this.iceServers=s.iceServers,this.mark("turn leased");}catch(s){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${Mn(s)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let o=this.options.clock.setTimeout(()=>{this.fail(new w("timeout",`no usable P2P connection after ${t}ms. The parent relays signaling, so a silent failure here usually means the page is not putting frames on the socket.`));},t),a=()=>this.fail(new w("aborted","the caller aborted while connecting"));e?.aborted?a():e?.addEventListener("abort",a);try{await r;}finally{this.options.clock.clearTimeout(o),e?.removeEventListener("abort",a),this.ready=null;}}async kick(e){if(!this.isHost)throw new w("misconfigured","only the current host of this match can kick a peer");await this.options.api.kick(this.options.matchId,e);}async leave(){try{await this.options.api.leave(this.options.matchId);}catch{}this.close();}close(){if(!this.closed){this.closed=true,this.pendingOffers.clear();for(let e of [...this.links.values()])this.dropLink(e,"closed",false);this.options.signaling.close(),this.emitter.clear();}}report(e){this.options.api.telemetry(e).catch(()=>{});}notifyCandidatesDropped(e){this.emitter.emit("candidatesDropped",e);}handleSignal(e,t){this.closed||this.route(e,t).catch(r=>this.report_(r));}async route(e,t){switch(e){case "hello":return this.onHello(t);case "offer":return this.onOffer(t);case "answer":return this.onAnswer(t);case "ice":return this.onIce(t);case "peerLeft":return this.onPeerLeft(t);case "migration":return this.onMigration(t);case "matchEnded":return this.onMatchEnded(t);case "error":return this.onSignalingError(t);default:return}}async onHello(e){let t=$(e.playerId),r=$(e.hostPlayerId),i=Lt(e.hostEpoch);if(!(t===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=t,this.migration===null&&(this.migration=new Pe(t,r,i)),!this.helloSeen)){if(this.helloSeen=true,this.isHost){this.mark("host listening"),this.settle(),await this.drainPendingOffers();return}this.pendingOffers.clear(),await this.offerToHost("initial");}}async drainPendingOffers(){if(this.pendingOffers.size===0)return;let e=[...this.pendingOffers.values()];this.pendingOffers.clear(),this.mark("queued offer drained");for(let t of e)try{await this.onOffer(t);}catch(r){this.report_(r);}}async offerToHost(e){let t=this.hostPlayerId,r=this.openLink(t,zr),i=await r.connection.createOffer();await r.connection.setLocalDescription(i);let o=r.connection.localDescription?.sdp??i.sdp;if(!o)throw new w("invalid_sdp","the browser produced an offer with no SDP");ie(o,"offer"),this.refuseMedia(o,"offer"),this.options.signaling.offer(o,e),this.mark("offer sent"),this.fetchCredential().catch(a=>this.report_(a));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,i=r===void 0?null:pe(r);if(i===null)throw new w("invalid_sdp","this browser produced an offer with no usable DTLS fingerprint, so the platform cannot bind a credential to it");let o=this.options.credentialPacing??_a,a=()=>this.closed||e!==this.credentialGeneration,s=ya;for(;;){let l=o.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,a))return;o.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,i);if(a())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(a())return;let m=d.status,u;if(m===409)u=Xr;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?u=p*1e3:(u=s,s=Math.min(s*2,Yr)),u=Math.min(Math.max(u,Xr),Yr);}else throw d;if(!await this.waitForCredential(u,a))return}}}async waitForCredential(e,t){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!t())}async onOffer(e){let t=$(e.fromPlayerId),r=$(e.sdp);if(t===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(t),this.pendingOffers.size>=va){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(t,e);return}if(!this.isHost||this.migration.isKicked(t)===true)return;let i=$(e.sessionId);if(i!==null&&this.answeredSessions.get(t)===i)return;ie(r,"offer"),this.refuseMedia(r,"offer");let o=pe(r);if(o===null)throw new w("invalid_sdp",`the offer from ${t} carries no usable fingerprint`);this.mark("offer received"),i!==null&&this.answeredSessions.set(t,i);let a=this.links.get(t);a&&this.dropLink(a,"resignalled",false);let s=this.openLink(t,this.nextPeerId++);s.remoteFingerprint=o,await s.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(s);let l=await s.connection.createAnswer();await s.connection.setLocalDescription(l);let d=s.connection.localDescription?.sdp??l.sdp;if(!d)throw new w("invalid_sdp","the browser produced an answer with no SDP");ie(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(t,d,s.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let t=$(e.fromPlayerId),r=$(e.sdp);if(t===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||t!==this.hostPlayerId)return;ie(r,"answer"),this.refuseMedia(r,"answer");let o=pe(r);if(o===null)throw new w("invalid_sdp","the host's answer carries no usable fingerprint");this.mark("answer received"),i.remoteFingerprint=o,i.pendingAnswer=r,this.hostVerified(i)&&await this.applyAnswer(i,r);}hostVerified(e){let t=this.credential;return t===null||e.remoteFingerprint===null?false:Ae(t.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new w("peer_unauthenticated","the host's DTLS certificate is not the one the platform attested for this match. Refusing before the handshake, so no credential is presented.")),this.dropLink(e,"host_fingerprint_mismatch",false),false)}maybeAuthenticate(){if(this.isHost)return;let e=this.links.get(this.hostPlayerId);if(!e||e.remoteFingerprint===null||e.connection.remoteDescription!==null)return;let t=e.pendingAnswer;t!==void 0&&this.hostVerified(e)&&this.applyAnswer(e,t).catch(r=>this.report_(r));}async applyAnswer(e,t){this.mark("host verified"),e.pendingAnswer=void 0,await e.connection.setRemoteDescription({type:"answer",sdp:t}),this.flushCandidates(e);}async onIce(e){let t=$(e.fromPlayerId),r=$(e.candidate);if(t===null||r===null)return;let i=this.links.get(t);if(!i)return;let o=$(e.sdpMid),a=Lt(e.sdpMLineIndex)??Lt(e.sdpMLineIndexAlt),s={candidate:r,...o===null?{}:{sdpMid:o},...a===null?{}:{sdpMLineIndex:a}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(s);return}await i.connection.addIceCandidate(s);}onPeerLeft(e){let t=$(e.playerId);if(t===null)return;let r=$(e.reason)??"left";if(t===this.localPlayerId){this.fail(new w("kicked",`this player was removed from the match (${r})`)),this.close();return}let i=this.links.get(t);i&&this.dropLink(i,r,true);}async onMigration(e){let t=$(e.hostPlayerId),r=Lt(e.hostEpoch);if(t===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:t,hostEpoch:r,...$(e.reason)===null?{}:{reason:$(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(o=>typeof o=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(i.kind!=="duplicate"){if(i.kind==="completed"){this.emitter.emit("hostChanged",t,r);return}if(i.kind==="refused"){this.report_(new w("migration_failed",i.why));return}for(let o of [...this.links.values()])this.dropLink(o,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",t,r),i.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration(),await this.offerToHost("full_reconnect");}}watchMigration(){let e=this.hostEpoch;this.options.clock.setTimeout(()=>{this.closed||this.migration===null||this.migration.currentEpoch===e&&this.migration.stalled(this.options.clock.now())&&this.reportedStallEpoch!==e&&(this.reportedStallEpoch=e,this.report_(new w("migration_failed",`host migration to epoch ${e} did not complete. The elected host never acknowledged it, so the platform is still holding the match in migration.`)));},31e3);}onMatchEnded(e){let t=$(e.reason)??"ended";this.ended=t,this.emitter.emit("matchEnded",t),this.ready!==null&&this.fail(new w("match_ended",`the match ended: ${t}`)),this.close();}onSignalingError(e){let t=$(e.code)??"unknown",r=$(e.message)??"the platform refused a signaling message";this.report_(new w("signaling_failed",`${t}: ${r}`));}openLink(e,t){let i=(this.options.peerConnectionFactory??Mt)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let p of Ke){let h=i.createDataChannel(p,Ct[p]);h.binaryType="arraybuffer",o[p]=h;}let a={playerId:e,assignedPeerId:t,connection:i,channels:o,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},s=p=>{let h=p.candidate;h?.candidate&&this.options.signaling.candidate(e,h.candidate,h.sdpMid??void 0,h.sdpMLineIndex??void 0);},l=()=>this.onIceState(a),d=()=>this.onConnectionState(a),m=p=>{this.onHandshakeMessage(a,p.data).catch(h=>this.report_(h));},u=()=>{this.onReliableOpen(a).catch(p=>this.report_(p));};return i.addEventListener("icecandidate",s),i.addEventListener("iceconnectionstatechange",l),i.addEventListener("connectionstatechange",d),o.reliable.addEventListener("open",u),o.reliable.addEventListener("message",m),a.detachHandshake=()=>{o.reliable.removeEventListener("open",u),o.reliable.removeEventListener("message",m);},a.detachAll=()=>{a.detachHandshake(),i.removeEventListener("icecandidate",s),i.removeEventListener("iceconnectionstatechange",l),i.removeEventListener("connectionstatechange",d);},this.links.set(e,a),a}flushCandidates(e){let t=e.pendingCandidates;e.pendingCandidates=[];for(let r of t)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let t=this.credential;if(t===null)throw new w("peer_unauthenticated","the channel opened before the platform issued a join credential, so there is nothing to present");if(this.options.clock.now()>=t.expiresAt)throw new w("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(En({jwt:t.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,t){if(!(t instanceof ArrayBuffer))return;let r=Cn(t);if(r!==null){if(this.isHost&&r.kind==="join"){await this.admit(e,r.jwt,r.protocolVersion);return}if(!this.isHost&&r.kind==="admit"){e.assignedPeerId=r.assignedPeerId,this.finishAdmission(e),this.migration?.complete();return}!this.isHost&&r.kind==="reject"&&(this.fail(new w(Hr(r.reason),Vr(r.reason))),this.dropLink(e,"rejected",false));}}async admit(e,t,r){if(r!==32769){this.refuseLink(e,2,"version_mismatch",`it presented protocol version ${r}, not this SDK's ${32769} \u2014 an engine peer cannot join a browser-hosted match`);return}let i=pe(e.connection.localDescription?.sdp??"");if(i===null||e.remoteFingerprint===null){this.refuseLink(e,1,"fingerprint_unavailable","this connection's DTLS fingerprints could not be read from its SDP, so no credential can be checked against it");return}let o;try{o=await It(t,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:i,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(a){let s=a instanceof w&&a.reason==="keys_unavailable";this.refuseLink(e,s?131:1,s?"keys_unavailable":"credential_invalid",Mn(a)),s&&this.fail(a);return}if(o.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${o.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(o.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(Tn({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,t,r,i){this.warn(`refused to admit ${e.playerId}: ${i}`);try{e.channels.reliable.send(In(t));}catch{}this.dropLink(e,r,false);}finishAdmission(e){this.mark(this.isHost?"peer admitted":"admitted"),e.admitted=true,e.detachHandshake(),e.detachHandshake=()=>{},this.emitter.emit("peerJoined",this.expose(e)),this.settle();}onIceState(e){let t=e.connection.iceConnectionState;if(!(t!=="failed"&&t!=="disconnected"&&t!=="closed")){if(this.isHost){(t==="failed"||t==="closed")&&this.dropLink(e,t,true);return}if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,t);}catch(r){this.report_(r);}}}}onConnectionState(e){let t=e.connection.connectionState;t!=="failed"&&t!=="closed"||this.dropLink(e,t,true);}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(t,r="reliable")=>e.channels[r].send(t)}}dropLink(e,t,r){this.links.delete(e.playerId),e.detachAll();for(let i of Ke)Qr(e.channels[i]);Qr(e.connection),r&&e.admitted&&this.emitter.emit("peerLeft",e.playerId,t);}settle(){this.ready?.resolve(),this.ready=null;}fail(e){if(this.count(e.reason),this.ready!==null){let t=this.ready;this.ready=null,t.reject(e);return}this.emitter.emit("error",e);}report_(e){this.fail(e instanceof w?e:new w("connection_failed",Mn(e),{cause:e}));}count(e){this.counted||!wa.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,t){if(St(e))throw new w("media_refused",`the ${t} carries an active audio or video section. This path carries data channels only; voice belongs to the platform voice service, and gem-api age-gates relayed SDP that proposes media.`)}mark(e){this.options.boot?.mark(e);}sleep(e){return new Promise(t=>this.options.clock.setTimeout(t,e))}warn(e){let t=this.options.log;t!==null&&(t??(r=>console.warn(r)))(`[gem] ${e}`);}get endedReason(){return this.ended}};function $(n){return typeof n=="string"&&n.length>0?n:null}function Lt(n){return typeof n=="number"&&Number.isInteger(n)?n:null}function Mn(n){return n instanceof Error?n.message:String(n)}function Qr(n){try{n.close();}catch{}}var ka=100,Ra=50,Te=class{constructor(e){this.options=e;}options;queue=[];drainHandle=null;dropped=0;closed=false;dropListener=null;onDropped(e){this.dropListener=e;}join(){this.assertUsable(),this.options.bridge.signal("join",this.options.matchId,{});}offer(e,t){this.assertUsable(),this.options.bridge.signal("offer",this.options.matchId,{sdp:e,intent:t});}answer(e,t,r){this.assertUsable(),this.options.bridge.signal("answer",this.options.matchId,{peerId:e,sdp:t,assignedPeerId:r});}candidate(e,t,r,i){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??ka)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:t,...r===void 0?{}:{sdpMid:r},...i===void 0?{}:{sdpMLineIndex:i}}),this.schedule();}migrationAck(e){this.assertUsable(),this.options.bridge.signal("migrationAck",this.options.matchId,{hostEpoch:e});}reportHostUnreachable(e,t){this.assertUsable(),this.options.bridge.signal("hostUnreachable",this.options.matchId,{hostEpoch:e,evidence:{iceState:t,lastSeenAt:Math.floor(this.options.clock.now()/1e3)}});}discardQueued(){this.queue.length=0;}close(){this.closed=true,this.discardQueued(),this.drainHandle!==null&&(this.options.clock.clearTimeout(this.drainHandle),this.drainHandle=null);}assertUsable(){if(this.closed)throw new w("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new w("signaling_unavailable","the page embedding this game did not advertise the `p2p` capability, so there is nothing to carry signaling. P2P needs the notification WebSocket, and only the parent can hold one \u2014 see docs/p2p-and-parties.md \xA72.")}schedule(){this.drainHandle!==null||this.closed||(this.drainHandle=this.options.clock.setTimeout(()=>{this.drainHandle=null;let e=this.queue.shift();if(e!==void 0){let{peerId:t,candidate:r,sdpMid:i,sdpMLineIndex:o}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:t,candidate:r,...i===void 0?{}:{sdpMid:i},...o===void 0?{}:{sdpMLineIndex:o}});}if(this.dropped>0&&this.queue.length===0){let t=this.dropped;this.dropped=0,this.options.onCandidatesDropped?.(t),this.dropListener?.(t);}this.queue.length>0&&this.schedule();},this.options.candidateIntervalMs??Ra));}};var Ln="webrtc_p2p";function Sa(n){let e=new xe({client:n.client,gameId:n.gameId}),t=new Map;return {handleSignalEvent(r,i,o){t.get(r)?.handleSignal(i,o);},session(r){return t.get(r)??null},async connect(r={}){if(n.bridge===null)throw new w("signaling_unavailable","P2P signaling rides the notification WebSocket, which only the page embedding this game can hold. There is no bridge here \u2014 this is `mock` mode, or a game running outside the Arcade frame. See docs/p2p-and-parties.md \xA72.");let i=B(r.clusterTargetId),o=i??B(await n.resolveClusterTarget?.());n.rooms.isHost&&n.rooms.currentMatch===null&&n.rooms.currentRoom?.matchId===void 0&&await n.rooms.startMatch({...i===void 0?{}:{clusterTargetId:i},...r.signal===void 0?{}:{signal:r.signal}});let a=await n.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(a.protocol!==Ln)throw new w("unsupported_protocol",`match ${a.matchId} speaks '${a.protocol}', not '${Ln}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let s=new Te({bridge:n.bridge,matchId:a.matchId,clock:n.clock}),l=new Ee({api:e,clock:n.clock,matchId:a.matchId,gameId:n.gameId(),baseUrl:typeof n.baseUrl=="function"?n.baseUrl():n.baseUrl,signaling:s,...o===void 0?{}:{clusterTargetId:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await Ot(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...n.boot===void 0?{}:{boot:n.boot},...n.log===void 0?{}:{log:n.log}});s.onDropped(d=>l.notifyCandidatesDropped(d)),t.set(a.matchId,l),l.on("matchEnded",()=>t.delete(a.matchId));try{await l.start(r.signal);}catch(d){throw t.delete(a.matchId),l.close(),d}return l}}}function Zr(n){return typeof n=="string"&&n.trim()!==""}function ei(n,e){return Zr(n)?n.trim():Zr(e)?e:null}function Je(n){let e=String(n);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function ti(n,e,t){let r=`/v1/games/${Je(n.gameId())}/matchmaking/tickets/${Je(e)}`;return n.client.delete(r,t?.signal)}async function ni(n,e,t){let r=`/v1/games/${Je(n.gameId())}/matchmaking/tickets`;return n.client.post(r,e,t?.signal)}async function ri(n,e,t){let r=`/v1/games/${Je(n.gameId())}/matchmaking/tickets/${Je(e)}/heartbeat`;return n.client.post(r,void 0,t?.signal)}function ze(n){let e=n??{};if(typeof e.ticket_id!="string"||e.ticket_id.length===0)throw new Error("[gem] a matchmaking-ticket response carried no id");let t=e.heartbeat_interval_seconds;return {id:e.ticket_id,status:typeof e.status=="string"?e.status:"queued",...typeof e.reason=="string"?{reason:e.reason}:{},...typeof e.game_room_id=="string"?{roomId:e.game_room_id}:{},partySize:typeof e.party_size=="number"?e.party_size:1,queuedAt:ii(e.queued_at),expiresAt:ii(e.expires_at),heartbeatIntervalSeconds:typeof t=="number"&&t>0?t:0}}function ii(n){if(typeof n!="string")return 0;let e=Date.parse(n);return Number.isFinite(e)?Math.floor(e/1e3):0}var xa=3,oi=1e3,Gt=class{constructor(e){this.options=e;this.snapshot=e.first;let t=new Promise((o,a)=>{this.resolve=o,this.reject=a;});t.catch(()=>{});let r=()=>this.snapshot,i=()=>this.status;this.ticket={get id(){return r().id},get status(){return i()},get partySize(){return r().partySize},get queuedAt(){return r().queuedAt},get expiresAt(){return r().expiresAt},outcome:t,cancel:()=>(this.requestCancel(),t)};}options;ticket;snapshot;status="queued";timer=null;busy=false;again=false;cancelRequested=false;soon=false;misses=0;settled=false;resolve;reject;start(){this.apply(this.snapshot);}poke(){this.settled||(this.soon=true,!this.busy&&(this.clearTimer(),this.tick()));}abandon(e=false){this.settled||(this.options.cancel(this.snapshot.id,e).catch(()=>{}),this.settle({status:"cancelled",reason:"requested"}));}requestCancel(){this.settled||(this.cancelRequested=true,this.trigger());}trigger(){if(this.busy){this.again=true;return}this.clearTimer(),this.tick();}schedule(e=false){if(this.settled)return;this.clearTimer();let t=e?oi:Math.max(oi,this.snapshot.heartbeatIntervalSeconds*1e3);this.timer=this.options.clock.setTimeout(()=>{this.timer=null,this.tick();},t);}clearTimer(){this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null);}async tick(){if(this.settled||this.busy)return;this.busy=true,this.again=false;let e=null,t=null;try{e=this.cancelRequested?await this.options.cancel(this.snapshot.id):await this.options.heartbeat(this.snapshot.id);}catch(r){t=r;}if(this.busy=false,!this.settled){if(e===null){this.missed(t);return}this.misses=0,await this.apply(e);}}missed(e){if(e instanceof j&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<xa){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let t=e instanceof j&&e.code==="matchmaking_unavailable";this.settle({status:t?"unavailable":"lost"});}async apply(e){if(this.snapshot=e,e.status==="queued"){this.next();return}if(e.status==="matched"){await this.seat(e);return}e.status==="expired"?this.settle({status:"expired",reason:e.reason??"timed_out"}):e.status==="cancelled"?this.settle({status:"cancelled",reason:e.reason??"requested"}):this.settle({status:"failed",reason:e.reason??e.status});}next(){if(this.again){this.again=false,this.tick();return}let e=this.soon;this.soon=false,this.schedule(e);}async seat(e){if(e.roomId===void 0){this.fail(new Error("[gem] a matched matchmaking ticket named no game room"));return}this.busy=true;try{let t=await this.options.seat(e.roomId);this.busy=!1,this.settle({status:"matched",room:t});}catch(t){this.busy=false,this.fail(t);}}settle(e){this.settled||(this.finish(e.status),this.resolve(e));}fail(e){this.settled||(this.finish("matched"),this.reject(e));}finish(e){this.settled=true,this.status=e,this.clearTimer(),this.options.onSettled();}};function he(n){return typeof n=="string"&&n!==""?n:void 0}var Aa=new Set(["localhost","127.0.0.1","[::1]"]);function si(n){let e=he(n);if(e===void 0)return;let t;try{t=new URL(e);}catch{return}if(!(t.username!==""||t.password!=="")&&(t.protocol==="https:"||t.protocol==="http:"&&Aa.has(t.hostname)))return e}function Pa(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=t??{},i=he(r.item_id),o=si(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function ai(n){let e=n??{},t=he(e.player_id),r=he(e.display_name),i=he(e.discriminator),o=he(e.display_tag),a=he(e.avatar_icon_id),s=si(e.avatar_icon_url);return {...t===void 0?{}:{playerId:t},...r===void 0?{}:{displayName:de(r)},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:de(o)},...a===void 0?{}:{avatarIconId:a},...s===void 0?{}:{avatarIconUrl:s},badges:Pa(e.badges)}}function Dt(n){if(typeof n!="object"||n===null)return;let e={};for(let[t,r]of Object.entries(n)){let i=Gn(r);i!==void 0&&(e[t]=i);}return e}function qt(n){if(Array.isArray(n))return n.map(Ea).filter(e=>!!e)}function Gn(n){if(Dn(n)||Array.isArray(n)&&n.every(Dn))return n}function Dn(n){return typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)}function Ea(n){let e=n??{};if(typeof e.name!="string"||e.name.length===0)return null;let t=Gn(e.fixed),r=Gn(e.default);return {name:e.name,type:typeof e.type=="string"?e.type:"string",list:e.list===true,required:e.required===true,mutable:e.mutable!==false,...t===void 0?{}:{fixed:t},...r===void 0?{}:{default:r},...Ie("description",Ta(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(Dn)?{allowed:e.allowed}:{},...Ie("min",Xe(e.min)),...Ie("max",Xe(e.max)),...Ie("minItems",Xe(e.min_items)),...Ie("maxItems",Xe(e.max_items)),...Ie("maxLength",Xe(e.max_length))}}function Ta(n){return typeof n=="string"&&n.length>0?n:void 0}function Xe(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Ie(n,e){return e===void 0?{}:{[n]:e}}function z(n){let e=n??{},t=T(e.id)??T(e.game_room_id);if(t===void 0)throw new Error("[gem] a game-room response carried no id");let r=Array.isArray(e.members)?e.members.map(qn):[];return {id:t,gameId:T(e.game_id)??"",name:T(e.name)??"",status:T(e.status)??"open",hostPlayerId:T(e.host_player_id)??"",maxPlayers:Y(e.max_players)??0,memberCount:Y(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...J("joinCode",T(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...J("roomArgs",Dt(e.room_args)),...J("roomArgsTemplate",qt(e.room_args_template)),gameChannel:T(e.game_channel)??"release",...J("region",T(e.region)),...J("clusterTargetId",T(e.cluster_target_id)),selfHosted:e.self_hosted===true,...J("matchId",T(e.match_id)),version:Y(e.version)??0,...J("templateId",T(e.template_id)),roomType:T(e.game_room_type)??"Standard",...J("transports",Ne(e.transports)??void 0),createdAt:Y(e.created_at)??0,updatedAt:Y(e.updated_at)??0,...J("startedAt",Y(e.started_at))}}function qn(n){let e=n??{};return {...ai(e),playerId:T(e.player_id)??"",isReady:e.is_ready===true,role:T(e.role)??"member",joinedAt:Y(e.joined_at)??0,...J("groupId",T(e.group_id)),...J("platform",T(e.platform))}}function Ye(n){let e=n??{};return {id:T(e.id)??T(e.game_room_id)??"",gameId:T(e.game_id)??"",name:T(e.name)??"",status:T(e.status)??"open",hostPlayerId:T(e.host_player_id)??"",maxPlayers:Y(e.max_players)??0,memberCount:Y(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:T(e.game_channel)??"release",roomType:T(e.game_room_type)??"Standard",createdAt:Y(e.created_at)??0}}function T(n){return typeof n=="string"&&n.length>0?n:void 0}function Y(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function J(n,e){return e===void 0?{}:{[n]:e}}var Ce=class{constructor(e){this.options=e;}options;list(e){let t=new URLSearchParams;e.status&&t.set("status",e.status),e.templateSlug&&t.set("template_slug",e.templateSlug),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor);let r=t.size>0?`?${t.toString()}`:"";return this.options.client.get(`${this.baseV1()}${r}`,e.signal).then(i=>({rooms:(i.game_rooms??[]).map(Ye),...typeof i.next_cursor=="string"?{nextCursor:i.next_cursor}:{}}))}myRooms(e){return this.options.client.get(`/v1/games/${encodeURIComponent(this.options.gameId())}/players/me/game-rooms`,e).then(t=>({rooms:(t.game_rooms??[]).map(Ye)}))}create(e,t,r){return Ia(e.maxPlayers),this.options.client.post(this.baseV2(),{name:e.name,...e.isPublic===void 0?{}:{is_public:e.isPublic},...e.settings===void 0?{}:{settings:e.settings},...e.region===void 0?{}:{region:e.region},...r===void 0?{}:{cluster_target_id:r},...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.partyId===void 0?{}:{party_id:e.partyId},...this.asksSelfHosted(e.partyId)?{self_hosted:true}:{},...e.roomArgs===void 0?{}:{room_args:e.roomArgs},...Qe(t)},e.signal).then(z)}get(e,t){return this.options.client.get(this.roomV2(e),t).then(z)}join(e,t,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...t.partyId===void 0?{}:{party_id:t.partyId},...Qe(r)},t.signal).then(z)}joinByCode(e,t,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...t.partyId===void 0?{}:{party_id:t.partyId},...Qe(r)},t.signal).then(z)}quickJoin(e,t,r=[]){return this.options.client.post(`${this.baseV2()}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...this.asksSelfHosted(e.partyId)?{self_hosted:true}:{},...Qe(t)},e.signal).then(z)}createTicket(e,t,r=[]){return ni(this.generated(),{templates:e.templateSlugs.map(i=>({template_slug:i})),...r.length===0?{}:{cluster_target_ids:[...r]},...e.partyId===void 0?{}:{party_id:e.partyId},...Qe(t)},{...e.signal===void 0?{}:{signal:e.signal}}).then(ze)}heartbeatTicket(e){return ri(this.generated(),e).then(ze)}cancelTicket(e,t=false){return t?this.options.client.delete(`/v1/games/${encodeURIComponent(this.options.gameId())}/matchmaking/tickets/${encodeURIComponent(e)}`,void 0,{keepalive:true}).then(ze):ti(this.generated(),e).then(ze)}leave(e,t,r,i=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:t},r,{keepalive:i}).then(()=>{})}asksSelfHosted(e){return e===void 0&&this.options.selfHosted?.()===true}close(e,t){return this.options.client.delete(this.roomV1(e),t).then(()=>{})}update(e,t){return this.options.client.patch(this.roomV2(e),{...t.name===void 0?{}:{name:t.name},...t.maxPlayers===void 0?{}:{max_players:t.maxPlayers},...t.isPublic===void 0?{}:{is_public:t.isPublic},...t.settings===void 0?{}:{settings:t.settings},...t.roomArgs===void 0?{}:{room_args:t.roomArgs}},t.signal).then(z)}setReady(e,t,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:t},r).then(z)}kick(e,t,r){return this.options.client.post(`${this.roomV1(e)}/kick/${encodeURIComponent(t)}`,{},r).then(()=>this.get(e,r))}transferHost(e,t,r){return this.options.client.post(`${this.roomV2(e)}/transfer/${encodeURIComponent(t)}`,{},r).then(z)}leaveMatch(e,t){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:t}).then(()=>{})}generated(){return {client:this.options.client,gameId:this.options.gameId}}baseV2(){return `/v2/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function Qe(n){return {platform:n.platform,game_version:n.gameVersion,engine_version:n.engineVersion}}function Ia(n){n!==void 0&&console.warn(`[gem] createRoom: maxPlayers (${n}) is deprecated and was not sent. A room's seats come from the room template published in your game config \u2014 name one with templateSlug \u2014 and a room created without a template seats 8. To change a room that already exists, call update({ maxPlayers }) as its host.`);}var Me=class{listeners=new Map;retainedMatch=null;on(e,t){let r=this.listeners.get(e);if(r||(r=new Set,this.listeners.set(e,r)),r.add(t),e==="matchReady"&&this.retainedMatch!==null){let i=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(t)&&this.retainedMatch===i&&t(i);});}return ()=>this.off(e,t)}hasListeners(e){return (this.listeners.get(e)?.size??0)>0}off(e,t){this.listeners.get(e)?.delete(t);}once(e,t){let r=this.on(e,((...i)=>{r(),t(...i);}));return r}emit(e,...t){e==="matchReady"&&(this.retainedMatch=t[0]);let r=this.listeners.get(e);if(r)for(let i of [...r])i(...t);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};function Ca(n,e){return Math.min(e,500*2**Math.max(0,n-1))}var Ma=1e3,Oa=3e3,La=6e4,Ga=2,li=new Set(["game_room_closed","game_room_gone"]),Da=12e4,qa=5e3,$a=new Set(["invalid_cluster_target","capacity_unavailable"]),Fa=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function gi(n){return new $n(n)}var $n=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new Ce({client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new Me;api;room=null;ticketWatch=null;queueing=false;queuedFromRoomId=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create"),this.assertNotQueued("create");let t=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("create",async()=>{let o=await t;return this.api.create(r,this.version("create"),o[0]).catch(async a=>{let s=await this.afterRefusedClusters(a,o);if(s[0]===void 0||s[0]===o[0])throw a;return this.api.create(r,this.version("create"),s[0])})});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,t={}){this.assertNotInRoom("join"),this.assertNotQueued("join");let r=await this.attachParty(t),i=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async joinByCode(e,t={}){this.assertNotInRoom("joinByCode"),this.assertNotQueued("joinByCode");let r=await this.attachParty(t),i=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async quickJoin(e){this.assertNotInRoom("quickJoin"),this.assertNotQueued("quickJoin");let t=this.clusterTargets(),r=await this.attachParty(e),i=a=>this.api.quickJoin(r,this.version("quickJoin"),a).catch(s=>this.retryPastStaleMembership(s,r,a)),o=await this.run("quickJoin",async()=>{let a=await t;return i(a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||pi(l,a))throw s;return i(l)})});return this.enter(o,"joined"),this.askForLocalServer(o),o}async queueForMatch(e){this.assertNotQueued("queueForMatch"),Na(e?.templateSlugs),this.queueing=true;try{let t=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("queueForMatch",async()=>{let a=await t;return this.api.createTicket(r,this.version("queueForMatch"),a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||pi(l,a))throw s;return this.api.createTicket(r,this.version("queueForMatch"),l)})}),o=new Gt({clock:this.options.clock,first:i,heartbeat:a=>this.track(this.api.heartbeatTicket(a)),cancel:(a,s)=>this.track(this.api.cancelTicket(a,s)),seat:a=>this.enterMatchedRoom(a),onSettled:()=>{this.ticketWatch===o&&(this.ticketWatch=null),this.retuneSeatWatch();}});return this.ticketWatch=o,this.retuneSeatWatch(),o.start(),o.ticket}finally{this.queueing=false;}}async enterMatchedRoom(e){let t=await this.run("queueForMatch",()=>this.api.get(e));return this.disposed?t:(this.room!==null&&this.room.id!==t.id&&(this.queuedFromRoomId=this.room.id,this.exit()),this.room===null&&this.enter(t,"joined"),this.room?.id===t.id?this.room:t)}async list(e={}){let t=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",t),t}async myRooms(e){let t=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",t.rooms),t.rooms}async leave(e={}){let t=this.requireRoom("leave"),r=e.keepalive===true,i=()=>this.run("leave",()=>this.api.leave(t.id,e.asGroup!==false,e.signal,r));if(r){let o=i();this.track(this.notifyLeavingMatch({keepalive:true})),await o;}else await this.notifyLeavingMatch(),await i();this.exit(),this.emitter.emit("left");}async leaveAll(e){let t=await this.myRooms(e),r=[];for(let i of t)try{await this.run("leaveAll",()=>this.api.leave(i.id,!0,e)),r.push(i.id),this.room?.id===i.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let t=this.requireRoom("close");await this.run("close",()=>this.api.close(t.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let t=this.room;if(!t)return null;let r;try{r=await this.track(this.api.get(t.id,e));}catch(i){if(i instanceof j&&i.reason==="not_found"){let o=this.heldMatchId;if(o!==null){let a=await this.askWhyEnded(o,e);this.endMatch(o,a??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",i),i}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let t=this.room,r=this.heldMatchId;if(!(t===null||r===null)&&!(t.status==="in_game"&&t.matchId===r)&&!(t.matchId!==void 0&&t.matchId!==r)&&this.settling!==r){this.settling=r;try{let i=await this.askWhyEnded(r,e);i!==null&&this.endMatch(r,i,t.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,t){let r=this.room;if(r===null)return null;let i=this.takeHint(e),o;try{o=await this.track(this.onceGameIdKnown(()=>Zt({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e),...t===void 0?{}:{signal:t}})));}catch(a){return a instanceof j&&a.reason==="not_found"?i??null:(this.reportError("reconcile",a),null)}return o===null?null:o.status==="ready"?(this.seenMatches.add(e),null):o.status==="failed"?(this.settleFailed(o.matchId,o.reason),null):o.reason==="unknown"&&i!==null?i:o.reason}takeHint(e){let t=this.pendingHint;if(t===null||t.matchId!==void 0&&t.matchId!==e||(this.pendingHint=null,t.reason===void 0))return null;let r=Re(t.reason);return r==="unknown"?null:r}async reconcile(e){if(this.disposed)return;if(e!==void 0&&(e.matchId!==void 0||e.reason!==void 0)&&(this.pendingHint=e),this.reconciling!==null)return this.reconcileAgain=true,this.reconciling;let t=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=t,this.track(t)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,t){let r=this.requireRoom("setReady"),i=await this.run("setReady",()=>this.api.setReady(r.id,e,t));return this.apply(i),i}async kick(e,t){let r=this.requireRoom("kick"),i=await this.run("kick",()=>this.api.kick(r.id,e,t));return this.apply(i),i}async transferHost(e,t){let r=this.requireRoom("transferHost"),i=await this.run("transferHost",()=>this.api.transferHost(r.id,e,t));return this.apply(i),i}async update(e){let t=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(t.id,e));return this.apply(r),r}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,t){let r=this.requireRoom("startMatch");if(!this.isHost)throw new c("misconfigured",`only the host of room ${r.id} can start a match, and this player is not it. Every other member waits for \`matchAllocationStarted\` instead \u2014 that is the whole point of the room carrying the match.`);this.startsInFlight++;try{return await this.startIn(r,e,t)}finally{this.startsInFlight--;}}async startIn(e,t,r){let i=B(t.clusterTargetId),o=i??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),a=o??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let s=(m,u)=>pt({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...i===void 0?{nextClusterTarget:()=>this.nextCluster(u)}:{},retry:{...t.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),t.retry?.onWaiting?.(p);}},...t.signal===void 0?{}:{signal:t.signal}}),l=()=>s(o,[a]).catch(async m=>{if(i!==void 0||!ui(m))throw m;let u=await this.nextCluster([a],true);if(u===void 0)throw m;return s(u,[a,u])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new c("misconfigured","this match is suspended \u2014 the transport dropped and nobody has decided to reconnect yet. Call reconnectToMatch(), or dedicatedServer.connect(), which does it for you.");let t=this.emitter.retained;return t!==null&&this.session.phase==="ready"?t:this.pollMatchStatus(e)}async pollMatchStatus(e={}){let t=this.requireRoom("pollMatchStatus"),r=await this.matchIdOrWait(e),i=await this.run("pollMatchStatus",()=>this.chase(t.id,r,e));return this.settleOutcome(i)}chase(e,t,r){return gt({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e,matchId:t,version:this.version("pollMatchStatus"),knownToExist:this.seenMatches.has(t),...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.pollIntervalMs===void 0?{}:{pollIntervalMs:r.pollIntervalMs},...r.signal===void 0?{}:{signal:r.signal}})}settleOutcome(e){if(e.status==="failed")throw this.settleFailed(e.matchId,e.reason),new c("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!li.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new c("match_ended",`match ${e.matchId} ended: ${e.reason}`);return this.seenMatches.add(e.matchId),this.emitter.retained?.matchId===e.matchId?this.emitter.retain(e):this.emitter.emit("matchReady",e),this.heldMatchId===e.matchId&&this.session.phase!=="connected"&&(this.session={phase:"ready",matchId:e.matchId}),e}settleFailed(e,t){this.heldMatchId===e&&(this.abandonReconnect(e,t),this.emitter.emit("matchFailed",e,t),this.abortFollow(),this.refusedMatches.add(e),this.session={phase:"none"},this.emitter.clearRetained());}endMatch(e,t,r){this.heldMatchId===e&&(this.abortFollow(),this.session={phase:"ended",matchId:e,reason:t,roomReopened:r},this.emitter.clearRetained(),this.emitter.emit("matchEnded",{matchId:e,reason:t,roomReopened:r}),this.abandonReconnect(e,t));}armReconnect(e,t){let r=this.options.autoReconnect;if(r===void 0||r.attempts<=0||r.budgetMs<=0)return;if(this.finishReconnect(),t==="kicked"){r.abandon(e,t);return}let i={matchId:e,cause:t,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=i,this.track(this.reconnectStep(i));}park(e,t){e.parkedAt=this.options.clock.now(),e.parked=()=>(e.parkedAt!==null&&(e.deadlineAt+=this.options.clock.now()-e.parkedAt,e.parkedAt=null),t());}reconnecting(e){return !this.disposed&&!e.done&&this.reconnect===e&&this.session.phase==="suspended"&&this.session.matchId===e.matchId}finishReconnect(){let e=this.reconnect;e!==null&&(e.done=true,e.timer!==null&&(this.options.clock.clearTimeout(e.timer),e.timer=null),e.parked=null,this.reconnect=null);}abandonReconnect(e,t){let r=this.reconnect;r===null||r.matchId!==e||(this.finishReconnect(),this.options.autoReconnect?.abandon(e,t));}async reconnectStep(e){if(!this.reconnecting(e))return;if(!$t()){this.park(e,()=>this.reconnectStep(e));return}let t=this.options.autoReconnect;if(t===void 0||e.attempt===0&&(await this.reconcile().catch(()=>{}),!this.reconnecting(e)))return;let r=e.deadlineAt-this.options.clock.now();if(e.attempt>=t.attempts||r<Ma){this.abandonReconnect(e.matchId,e.cause);return}e.attempt+=1,this.emitter.emit("matchReconnecting",{matchId:e.matchId,attempt:e.attempt,attempts:t.attempts,remainingMs:r}),e.timer=this.options.clock.setTimeout(()=>{e.timer=null,this.track(this.reconnectAttempt(e));},Math.min(Ca(e.attempt,t.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!$t()){this.park(e,()=>this.reconnectAttempt(e));return}let t=this.options.autoReconnect,r=this.room;if(t===void 0||r===null)return;let i=null;try{i=await this.track(this.onceGameIdKnown(()=>Zt({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e.matchId,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e.matchId)})));}catch(o){this.reportError("reconcile",o);}if(this.reconnecting(e)){if(i?.status==="ended"){this.endMatch(i.matchId,i.reason,!li.has(i.reason)),this.track(this.reconcile().catch(()=>{}));return}if(i?.status==="failed"){this.abandonReconnect(e.matchId,i.reason),this.settleFailed(i.matchId,i.reason);return}if(i?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(i);let o;try{o=await t.redial(e.matchId,e.deadlineAt);}catch(a){this.reportError("reconcile",a),o="failed";}if(e.done||this.reconnect!==e)return;if(o==="closed"){this.finishReconnect();return}if(o==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let t=this.session.phase==="suspended";this.session={phase:"connected",matchId:e};let r=this.reconnect;r!==null&&r.matchId===e?(this.finishReconnect(),this.emitter.emit("matchReconnected",{matchId:e,attempt:r.attempt})):t&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new c("misconfigured",`no match is connected, so there is nothing to suspend (state '${this.matchConnectionState}').`);let t=this.session.matchId;this.session={phase:"suspended",matchId:t,reason:e},this.emitter.emit("matchSuspended",{matchId:t,cause:e}),this.armReconnect(t,e);}async reconnectToMatch(e={}){if(this.session.phase!=="suspended")throw new c("misconfigured",`reconnectToMatch expects a suspended match; this one is '${this.matchConnectionState}'. Call notifyMatchDisconnected() when the transport drops.`);let t=this.heldMatchId;if(t===null)throw new c("misconfigured","there is no match to reconnect to.");return this.finishReconnect(),this.session={phase:"starting",matchId:t},this.emitter.clearRetained(),this.pollMatchStatus(e)}async notifyLeavingMatch(e={}){let t=this.heldMatchId;if(t!==null)try{await this.api.leaveMatch(t,e.keepalive??!1);}catch{}}get gameId(){let e=typeof this.options.gameId=="function"?this.options.gameId():this.options.gameId;return e===""?null:e}get currentRoom(){return this.room}get currentTicket(){return this.ticketWatch?.ticket??null}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}on(e,t){let r=this.emitter.on(e,t);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,t){this.emitter.off(e,t);}once(e,t){return this.emitter.once(e,t)}handleRoomEvent(e){if(this.ticketWatch!==null&&e.event!=="version_stale"&&e.roomId!==this.room?.id&&this.ticketWatch.poke(),this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let t=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(t).catch(()=>{}));}handleAutoStartFailed(e,t){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(t);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:t,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let i=new AbortController;this.autoStartRetry=i,this.track(this.requestStart({signal:i.signal},false).then(()=>{},o=>{i.signal.aborted||this.reportError("startMatch",o);}).finally(()=>{this.autoStartRetry===i&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!$a.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.watchingSeats&&this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}}async reconcileSeats(){if(this.disposed||!this.watchingSeats||this.ticketWatch!==null)return;let e;try{e=await this.myRooms();}catch{return}let t=new Set;for(let r of e)r.status!=="closed"&&(t.add(r.id),r.id!==this.room?.id&&(this.reported.has(r.id)||await this.reportSeat(r.id).catch(()=>{})));for(let r of [...this.reported])t.has(r)||this.reported.delete(r);}async reportSeat(e){let t=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||t===null||!r.members.some(i=>i.playerId===t)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.ticketWatch===null&&this.seatPollMs>0&&$t())){this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null);return}if(this.seatPollHandle!==null)return;let t=()=>{this.seatPollHandle=null,this.track(this.reconcileSeats().catch(()=>{}).then(()=>this.retuneSeatWatch()));};this.seatPollHandle=this.options.clock.setTimeout(t,this.seatPollMs);}installResumeWatch(){let e=globalThis;if(typeof e.addEventListener!="function")return;this.visibilityListener=()=>{if(!this.disposed&&(this.retuneSeatWatch(),!!$t())){if(this.room!==null){let r=this.reconnect?.parked??null;r!==null&&this.reconnect!==null?(this.reconnect.parked=null,this.track(r())):this.track(this.reconcile().catch(()=>{}));return}if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of di)e.addEventListener(r,this.visibilityListener);let t=globalThis.document;typeof t?.addEventListener=="function"&&t.addEventListener("resume",this.visibilityListener);}startPolling(e){this.stopPolling(),!this.disposed&&(this.pinnedIntervalMs=e??null,this.polling=true,this.schedule());}stopPolling(){this.pollHandle!==null&&(this.options.clock.clearTimeout(this.pollHandle),this.pollHandle=null),this.polling=false,this.pollIntervalMs=null;}async settled(){for(let e=0;e<20&&this.inFlight.length>0;e++){let t=this.inFlight;this.inFlight=[],await Promise.allSettled(t);}}dispose(){if(this.disposed=true,this.ticketWatch?.abandon(),this.abortAutoStartRetry(),this.finishReconnect(),this.stopPolling(),this.emitter.clear(),this.unloadListener&&(globalThis.removeEventListener?.("pagehide",this.unloadListener),this.unloadListener=null),this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null),this.visibilityListener){let e=globalThis;for(let r of di)e.removeEventListener?.(r,this.visibilityListener);globalThis.document?.removeEventListener?.("resume",this.visibilityListener),this.visibilityListener=null;}}get watchingSeats(){return this.options.watchSeats!==false&&this.emitter.hasListeners("seated")}get seatPollMs(){return this.options.seatPollIntervalMs??qa}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new c("misconfigured","the game id is not known yet. It comes from the play token, and this manager was given no way to wait for one \u2014 pass gameId, or awaitGameId so a call made before the first token waits for it the way createGem wires it.")}playerId(){return typeof this.options.playerId=="function"?this.options.playerId():this.options.playerId}version(e){let t=this.options.clientVersion,r=ei(this.options.platformGameVersion?.(),t?.gameVersion);if(r===null)throw new c("misconfigured",`${e} has no game version to report \u2014 gem-api requires platform, game_version and engine_version together on every room route, and refuses a request carrying two of the three. The arcade normally supplies it with the play token; an embedder that does not, or a build running outside the arcade, leaves nobody to ask. Pass \`clientVersion: { gameVersion }\` to createGem (or to createRoomManager) as the fallback. It has to name a build you actually published, and a wrong one pins the room to the wrong build \u2014 which is why the platform answers it wherever it can.`);return Cr({...t,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return be(await this.options.resolveClusterTargets());let e=B(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,t){return !ui(e)||t.length===0?[]:be(await this.options.refreshClusterTargets?.(t)??[])}async nextCluster(e,t=false){let r=a=>a.find(s=>!e.includes(s)),i=await this.clusterTargets(),o=r(i);return o!==void 0||!t?o:r(be(await this.options.refreshClusterTargets?.(i)??[]))}async attachParty(e){if(e.partyId!==void 0)return e;let t=this.options.resolveParty;if(t===void 0)return e;let r=await t();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,t,r){if(!(e instanceof j)||e.reason!=="conflict"||!Fa.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new j(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and \`recoverStaleMembership\` is off, so nothing cleared it. A membership that outlived its page is visible only through myRooms(); leaveAll() is what clears it.`,e.retryAfterSeconds,e.code);let i;try{i=await this.leaveAll(t.signal);}catch{throw new j(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery could not list the rooms it would have cleared, so nothing was tried and the refusal stands. That is the listing failing, not a room refusing to be left: retry once the connection is back. myRooms() shows what is held.`,e.retryAfterSeconds,e.code)}if(i.length===0)throw new j(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery cleared nothing, so the refusal stands. myRooms() shows what is held. A room this player was seated in as a party member cannot be cleared from here at all \u2014 only the leader of a party may take it out of a room \u2014 so a member joins by adopting that room, myRooms() then join(), rather than quick-joining.`,e.retryAfterSeconds,e.code);return this.api.quickJoin(t,this.version("quickJoin"),r)}assertNotInRoom(e){if(this.room!==null)throw new c("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}assertNotQueued(e){if(!(this.ticketWatch===null&&!this.queueing))throw new c("misconfigured",`${e} refused: this player is waiting on a matchmaking ticket, which will seat them in a room of its own. Cancel it first \u2014 currentTicket.cancel() \u2014 or wait for its outcome.`)}requireRoom(e){if(this.room===null)throw new c("misconfigured",`${e} refused: not in a room.`);return this.room}async run(e,t){try{return await this.track(this.onceGameIdKnown(t))}catch(r){throw this.reportError(e,r),r}}onceGameIdKnown(e){return this.gameId!==null||this.options.awaitGameId===void 0?e():this.options.awaitGameId().then(e)}reportError(e,t){let r=t instanceof j?{operation:e,code:t.status,reason:t.reason,message:t.message,retryable:t.retryable}:{operation:e,code:0,reason:t instanceof c?t.reason:"unavailable",message:t instanceof Error?t.message:String(t),retryable:false};this.emitter.emit("error",r);}askForLocalServer(e){let t=this.options.ensureLocalServer;t===void 0||!e.selfHosted||e.status!=="open"||t(e.id).catch(()=>{});}track(e){return this.inFlight.push(e),e}enter(e,t){this.room=e,this.queuedFromRoomId===e.id&&(this.queuedFromRoomId=null),this.abortFollow(),this.autoStartRetried=false,this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(t,e),this.adoptMatch(e),this.options.poll!==false&&this.startPolling(),this.retuneSeatWatch();}exit(){this.room=null,this.abortFollow(),this.abortAutoStartRetry(),this.autoStartRetried=false,this.finishReconnect(),this.session.phase!=="ended"&&(this.session={phase:"none"}),this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.stopPolling(),this.retuneSeatWatch();}apply(e){let t=this.room;if(t===null||t.id!==e.id)return;let r=new Map(t.members.map(s=>[s.playerId,s])),i=new Map(e.members.map(s=>[s.playerId,s])),o=this.playerId();for(let s of i.keys())r.has(s)||this.emitter.emit("memberJoined",s);for(let s of r.keys())if(!i.has(s)){if(s===o){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",s);}for(let[s,l]of i){let d=r.get(s);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",s,l.isReady);}t.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let a=ja(t,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),a&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let t=this.heldMatchId;t!==null&&t!==e&&this.endMatch(t,"replaced",true),this.session={phase:"starting",matchId:e},this.autoStartRetried=false,this.emitter.clearRetained(),this.emitter.emit("matchAllocationStarted",e),this.followMatch();}followMatch(){if(this.autoFollow===false)return;let e=this.room,t=this.heldMatchId;if(e===null||t===null||this.followAbort!==null&&this.followingMatchId===t)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=t,this.track(this.onceGameIdKnown(()=>this.chase(e.id,t,{signal:r.signal})).then(i=>{if(!r.signal.aborted)try{this.settleOutcome(i);}catch{}}).catch(i=>{r.signal.aborted||this.reportError("pollMatchStatus",i);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let t=this.heldMatchId;if(t!==null)return Promise.resolve(t);let r=e.timeoutMs??Da;return new Promise((i,o)=>{let a=u=>{s(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),u();},s=this.emitter.on("matchAllocationStarted",u=>a(()=>i(u))),l=this.emitter.on("matchFailed",(u,p)=>a(()=>o(new c("allocation_failed",`match ${u} did not come up: ${p}`)))),d=()=>a(()=>o(new c("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>a(()=>o(new c("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?d():e.signal?.addEventListener("abort",d);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??Oa}pushedInterval(){return this.options.pushedPollIntervalMs??La}pushed(){return this.options.clock.now()-this.lastPushAt<Ga*this.pushedInterval()}retune(){!this.polling||this.pinnedIntervalMs!==null||this.baseInterval()!==this.pollIntervalMs&&this.startPolling();}schedule(){this.disposed||!this.polling||this.room===null||(this.pollIntervalMs=this.pinnedIntervalMs??this.baseInterval(),this.pollHandle=this.options.clock.setTimeout(()=>{this.pollHandle=null,this.track(this.reconcile().catch(()=>null).then(()=>{this.schedule();}));},this.pollIntervalMs));}installUnloadNotifier(){if(this.options.notifyOnUnload===false)return;let e=globalThis;typeof e.addEventListener=="function"&&(this.unloadListener=t=>{if(this.ticketWatch?.abandon(true),t?.persisted!==true&&(this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{})),this.queuedFromRoomId!==null)){let r=this.queuedFromRoomId;this.queuedFromRoomId=null,this.track(this.api.leave(r,true,void 0,true).catch(()=>{}));}},e.addEventListener("pagehide",this.unloadListener));}};function $t(){let n=globalThis.document;return n?.visibilityState===void 0||n.visibilityState==="visible"}var di=["visibilitychange","focus","pageshow","online"];function ja(n,e){return n.version!==e.version||n.status!==e.status||n.matchId!==e.matchId||n.hostPlayerId!==e.hostPlayerId||n.name!==e.name||n.maxPlayers!==e.maxPlayers||n.isPublic!==e.isPublic||ci(n)!==ci(e)}function ci(n){return n.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function ui(n){return n instanceof j&&n.code==="invalid_cluster_target"}var mi=8;function Na(n){if(!(Array.isArray(n)&&n.length>=1&&n.length<=mi&&n.every(t=>typeof t=="string"&&t.length>0)))throw new c("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${mi} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function pi(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}function hi(n){let e=0,t=new Map;return {resolve(){if(!n.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(i=>{let o={},a=l=>{t.delete(r)&&(n.clock.clearTimeout(o.timer),i(l));};t.set(r,a),o.timer=n.clock.setTimeout(()=>a(void 0),n.timeoutMs??2e3);let s=false;try{s=n.bridge.requestParty(r);}catch{}s||a(void 0);})},settle(r,i){t.get(r)?.(i);}}}
2
- export{yi as CAPABILITY_GATES,bi as CAPABILITY_NAMESPACE_GATES,Ct as CHANNELS,Ke as CHANNEL_KINDS,ce as ClientTelemetry,Wt as DEDICATED_INBOUND_EVENTS,sn as DEFAULT_WELCOME_CEILING_MS,is as DEVICE_SETTINGS_MAX_BYTES,c as DedicatedServerError,yt as DedicatedSignalingHub,Wa as FRAME_TO_PARENT,zt as GemFrame,Jt as GemHost,jt as HANDSHAKE_TIMEOUT_MS,Pe as HostMigration,ye as MALFORMED_INBOUND_KEY,Un as MAX_ARRAY_LENGTH,it as MAX_CLUSTER_TARGETS,fe as MAX_MESSAGE_BYTES,Nn as MAX_MESSAGE_DEPTH,et as MAX_MESSAGE_NODES,ot as MAX_SIGNALS_PER_SECOND,Oe as MAX_SOCKET_FRAME_BYTES,Kr as MIGRATION_TIMEOUT_MS,xe as P2pApi,w as P2pError,Ee as P2pSession,Ba as PARENT_TO_FRAME,f as PROTOCOL,W as PlayerText,tt as RATE_LIMITS,te as RateLimiter,Me as RoomEmitter,Ce as RoomsApi,Z as SUPPORTED_VERSIONS,Te as SignalingClient,mt as TELEMETRY_EVENTS,nr as TRANSPORT_LABELS,ae as VALIDATORS,$e as WEBRTC_DEDICATED,Ln as WEBRTC_P2P,We as WEB_ENGINE_VERSION,ge as WEB_PROTOCOL_VERSION,de as asPlayerText,gt as awaitMatchOutcome,Mt as browserPeerConnection,st as buildDedicatedOfferFrame,lt as buildSocketFrame,nt as capabilityFor,Mo as createClusterTargetSource,Xs as createDedicatedServerApi,Tt as createKeySource,Sa as createP2pApi,hi as createPartyResolver,gi as createRoomManager,os as deviceSettingsByteLength,Be as establishDataChannel,pe as fingerprintOf,Ae as fingerprintsMatch,Ot as generateCertificate,rt as isOrigin,ht as listClusterTargets,qn as memberFromWire,Vt as negotiateVersion,B as normaliseClusterTarget,be as normaliseClusterTargets,Ve as normaliseFingerprint,ke as originsEqual,Fe as presentJoinCredential,at as projectDedicatedEvent,De as projectPartyEvent,dt as projectSignal,Dt as roomArgValuesFromWire,qt as roomArgsTemplateFromWire,z as roomFromWire,pt as startMatch,Ye as summaryFromWire,re as systemClock,Zo as text,bt as unavailableSignaling,xo as validateGemAdResult,lo as validateGemAudioState,Fi as validateGemAutoStartFailedEvent,Bi as validateGemClusterTarget,Ci as validateGemCohorts,Ni as validateGemDedicatedEvent,Xi as validateGemDedicatedOffer,Li as validateGemDeviceSettings,ko as validateGemDeviceSettingsPut,Ro as validateGemDeviceSettingsResult,Wi as validateGemDevtools,Mi as validateGemEarnAllowanceChanged,Zi as validateGemEngaged,_o as validateGemError,oo as validateGemExit,yo as validateGemFrameStats,To as validateGemFriendChallengeResult,Ji as validateGemGameContext,Si as validateGemHandshake,xi as validateGemHandshakeAccept,ro as validateGemLocalServer,io as validateGemLocalServerDenied,mo as validateGemMenu,po as validateGemMenuSelect,so as validateGemOpenExternal,Yi as validateGemPartyRequest,Ui as validateGemPartyResult,Ti as validateGemPause,Ei as validateGemPlayer,bo as validateGemPortraitBorders,Ii as validateGemPrefs,eo as validateGemProgress,wo as validateGemPurchaseResult,Qi as validateGemReady,So as validateGemRequestAd,ho as validateGemRequestAvatarPicker,Ki as validateGemRequestContext,Eo as validateGemRequestFriendChallenge,ao as validateGemRequestFullscreen,no as validateGemRequestLocalServer,vo as validateGemRequestPurchase,go as validateGemRequestShare,Ao as validateGemRequestSignIn,to as validateGemRequestToken,co as validateGemRewardCue,Di as validateGemRoomEvent,Vi as validateGemScreenshot,Hi as validateGemScreenshotDenied,$i as validateGemSeatedEvent,Po as validateGemSignInResult,zi as validateGemSignal,ji as validateGemSignalEvent,qi as validateGemSocketState,Ai as validateGemToken,Pi as validateGemTokenDenied,fo as validateGemVibrate,Oi as validateGemViewport,uo as validateGemWalletDisplay,Gi as validateGemWillTerminate,ki as validateSize,It as verifyCredential};//# sourceMappingURL=gem-web-sdk.esm.js.map
1
+ globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:10.3.1]";var f="gem-web-bridge",Z={min:1,max:1},fe=65536,Nn=8,et=5e3,Un=1024,Nt=1e4;function Bn(n){return Object.freeze(Object.assign(Object.create(null),n))}var tt=Bn({"gem.handshake":30,"gem.handshake.accept":5,"gem.token":30,"gem.token.denied":30,"gem.player":12,"gem.pause":120,"gem.prefs":60,"gem.cohorts":12,"gem.earnAllowanceChanged":30,"gem.viewport":60,"gem.deviceSettings":12,"gem.willTerminate":10,"gem.roomEvent":120,"gem.socketState":12,"gem.seatedEvent":60,"gem.autoStartFailedEvent":30,"gem.signalEvent":1800,"gem.dedicatedEvent":120,"gem.partyResult":30,"gem.clusterTarget":12,"gem.devtools":30,"gem.screenshot":6,"gem.screenshot.denied":12,"gem.requestContext":12,"gem.gameContext":12,"gem.signal":1200,"gem.dedicatedOffer":60,"gem.partyRequest":12,"gem.ready":5,"gem.engaged":5,"gem.progress":600,"gem.requestToken":12,"gem.requestLocalServer":6,"gem.localServer":30,"gem.localServer.denied":30,"gem.exit":5,"gem.openExternal":6,"gem.requestFullscreen":30,"gem.audioState":120,"gem.rewardCue":60,"gem.walletDisplay":60,"gem.controlsDeclare":60,"gem.menu":60,"gem.menuSelect":60,"gem.requestShare":6,"gem.requestAvatarPicker":6,"gem.vibrate":600,"gem.frameStats":120,"gem.portraitBorders":60,"gem.error":60,"gem.requestPurchase":12,"gem.purchaseResult":30,"gem.deviceSettings.put":30,"gem.deviceSettings.result":30,"gem.requestAd":6,"gem.adResult":12,"gem.requestSignIn":6,"gem.signInResult":12,"gem.requestFriendChallenge":12,"gem.friendChallengeResult":30,__malformed:60}),ye="__malformed",Ns=["gem.handshake","gem.token","gem.token.denied","gem.player","gem.pause","gem.prefs","gem.cohorts","gem.earnAllowanceChanged","gem.viewport","gem.deviceSettings","gem.willTerminate","gem.roomEvent","gem.socketState","gem.seatedEvent","gem.autoStartFailedEvent","gem.signalEvent","gem.dedicatedEvent","gem.partyResult","gem.clusterTarget","gem.devtools","gem.screenshot","gem.requestContext","gem.localServer","gem.localServer.denied","gem.menuSelect","gem.error","gem.purchaseResult","gem.deviceSettings.result","gem.adResult","gem.signInResult","gem.friendChallengeResult"],Us=["gem.handshake.accept","gem.screenshot.denied","gem.gameContext","gem.signal","gem.dedicatedOffer","gem.partyRequest","gem.ready","gem.engaged","gem.progress","gem.requestToken","gem.requestLocalServer","gem.exit","gem.openExternal","gem.requestFullscreen","gem.audioState","gem.rewardCue","gem.walletDisplay","gem.controlsDeclare","gem.menu","gem.requestShare","gem.requestAvatarPicker","gem.vibrate","gem.frameStats","gem.portraitBorders","gem.error","gem.requestPurchase","gem.deviceSettings.put","gem.requestAd","gem.requestSignIn","gem.requestFriendChallenge"],_i=Bn({"gem.requestAd":"ads","gem.adResult":"ads","gem.requestSignIn":"signIn","gem.signInResult":"signIn","gem.requestPurchase":"purchases","gem.purchaseResult":"purchases","gem.requestFriendChallenge":"friendChallenges","gem.friendChallengeResult":"friendChallenges","gem.devtools":"devtools","gem.screenshot":"screenshot","gem.screenshot.denied":"screenshot","gem.requestContext":"feedbackContext","gem.gameContext":"feedbackContext","gem.roomEvent":"rooms","gem.signal":"p2p","gem.signalEvent":"p2p","gem.dedicatedOffer":"dedicated","gem.dedicatedEvent":"dedicated","gem.clusterTarget":"clusterTarget","gem.partyRequest":"parties","gem.partyResult":"parties","gem.autoStartFailedEvent":"autoStartFailure","gem.seatedEvent":"partySeating","gem.socketState":"socketState","gem.audioState":"audioState","gem.rewardCue":"rewardCue","gem.frameStats":"frameStats","gem.portraitBorders":"portraitBorders","gem.engaged":"engagement","gem.viewport":"viewport","gem.walletDisplay":"walletDisplay","gem.requestLocalServer":"localHost","gem.localServer":"localHost","gem.localServer.denied":"localHost","gem.cohorts":"cohorts","gem.earnAllowanceChanged":"earnAllowance","gem.deviceSettings":"deviceSettings","gem.deviceSettings.put":"deviceSettings","gem.deviceSettings.result":"deviceSettings","gem.requestShare":"share","gem.requestAvatarPicker":"avatarPicker","gem.vibrate":"vibration","gem.menu":"gameMenu","gem.menuSelect":"gameMenu","gem.controlsDeclare":"controls"}),vi=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"]]);function nt(n){let e=_i[n];if(e!==void 0)return e;for(let[t,r]of vi)if(n.startsWith(t))return r}function rt(n){let e=/^([a-z][a-z0-9+.-]*):\/\/([a-z0-9.-]+|\[[0-9a-f:.]+\])(:([0-9]{1,5}))?$/i.exec(n);return e===null?false:e[4]===void 0||Number(e[4])<=65535}function ki(n){let e;try{e=new URL(n);}catch{return false}return e.username!==""||e.password!==""?false:e.protocol==="https:"?true:e.protocol==="http:"&&(e.hostname==="localhost"||e.hostname==="127.0.0.1")}function wi(n){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(n)}function Ri(n){return /^[a-z_]+$/.test(n)}function jt(n,e,t){if(e>Nn)return `nesting deeper than ${Nn}`;if(++t.nodes>et)return `more than ${et} values`;if(t.bytes>fe)return `over the ${fe} byte limit`;if(n==null)return t.bytes+=4,null;let r=typeof n;if(r==="boolean")return t.bytes+=5,null;if(r==="number")return t.bytes+=8,null;if(r==="string")return t.bytes+=n.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let i=n;if(t.seen.has(i))return "a repeated or cyclic object reference";if(t.seen.add(i),Array.isArray(n)){if(n.length>Un)return `an array of ${n.length} entries, over the ${Un} limit`;t.bytes+=2;for(let s of n){let l=jt(s,e+1,t);if(l)return l}return null}let o=Object.getPrototypeOf(n);if(o!==Object.prototype&&o!==null)return "a value that is not a plain object";t.bytes+=2;let a=n;for(let s in a){if(!Object.prototype.hasOwnProperty.call(a,s))continue;if(++t.nodes>et)return `more than ${et} values`;if(t.bytes+=s.length*3+4,t.bytes>fe)return `over the ${fe} byte limit`;let l=jt(a[s],e+1,t);if(l)return l}return null}function Si(n){let e={nodes:0,bytes:0,seen:new Set},t=jt(n,0,e);return t?`message contains ${t}`:e.bytes>fe?`message is over the ${fe} byte limit`:null}var xi={origin:[rt,"not a well-formed origin"],url:[ki,"not a safe absolute http(s) URL"],bcp47:[wi,"not a well-formed BCP 47 tag"],code:[Ri,"not a code of lower-case letters and underscores"]};function Wn(n,e,t){for(let r of e){let i=t===""?r.n:`${t}.${r.n}`,o=n[r.n];if(o==null){if(r.o)continue;return `${i}: required`}let a=Vn(o,r,i);if(a)return a}return null}function Vn(n,e,t){switch(e.k){case "s":{if(typeof n!="string")return `${t}: expected string`;if(n.length>e.max)return `${t}: exceeds ${e.max} characters`;if(e.f){let[r,i]=xi[e.f];if(!r(n))return `${t}: ${i}`}return null}case "i":return typeof n!="number"||!Number.isInteger(n)?`${t}: expected integer`:n<e.lo||n>e.hi?`${t}: out of range ${e.lo}..${e.hi}`:null;case "b":return typeof n=="boolean"?null:`${t}: expected boolean`;case "e":{let r=e.v;return r.includes(n)?null:`${t}: not one of ${r.join("|")}`}case "o":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected object`:Wn(n,e.fs,t);case "j":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected a plain object`:null;case "a":{if(!Array.isArray(n))return `${t}: expected array`;if(n.length>e.max)return `${t}: exceeds ${e.max} items`;let r=e.it,i=`${t}[]`;for(let o of n){if(o==null){if(r.o)continue;return `${i}: required`}let a=Vn(o,r,i);if(a)return a}return null}default:{let r=e.k;return `${t}: unknown kind ${String(r)}`}}}var Hn=Object.create(null);function y(n,e){return Hn[n]=t=>{let r=Si(t);if(r)return r;if(typeof t!="object"||t===null||Array.isArray(t))return "message: expected object";let i=t;return i.gem!==f?"gem: wrong protocol marker":i.type!==n?`type: expected ${n}`:Wn(i,e,"")}}var Bs=y("gem.handshake",[{n:"versions",k:"o",fs:[{n:"min",k:"i",lo:1,hi:1e3},{n:"max",k:"i",lo:1,hi:1e3}]},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}},{n:"embedder",k:"s",max:2048,f:"origin"},{n:"unbidden",k:"b",o:1}]),Ws=y("gem.handshake.accept",[{n:"v",k:"i",lo:1,hi:1e3},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}}]),Vs=y("gem.token",[{n:"token",k:"s",max:4096},{n:"requestId",k:"s",o:1,max:64},{n:"generation",k:"i",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"s",o:1,max:512,f:"url"},{n:"playerId",k:"s",max:64},{n:"gameId",k:"s",max:64},{n:"channel",k:"e",v:["dev","test","release"]},{n:"gameVersion",k:"s",o:1,max:64},{n:"expiresAt",k:"i",lo:0,hi:4102444800},{n:"chainEndsAt",k:"i",lo:0,hi:4102444800},{n:"allowDevTools",k:"b",o:1}]),Hs=y("gem.token.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:36e5},{n:"reason",k:"e",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"s",max:64}]),Ks=y("gem.player",[{n:"untrusted",k:"o",fs:[{n:"displayName",k:"s",max:64},{n:"displayTag",k:"s",o:1,max:80},{n:"displayHandle",k:"s",max:80}]},{n:"playerId",k:"s",o:1,max:64},{n:"discriminator",k:"s",o:1,max:8},{n:"avatarIconUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatarIconId",k:"s",o:1,max:64},{n:"badges",k:"a",o:1,max:2,it:{n:"",k:"o",fs:[{n:"itemId",k:"s",max:64},{n:"iconUrl",k:"s",max:2048,f:"url"}]}},{n:"displayTag",k:"s",max:8},{n:"avatarUrl",k:"s",o:1,max:2048,f:"url"},{n:"boost",k:"o",o:1,fs:[{n:"multipliers",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"currencyId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"multiplierBp",k:"i",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"i",o:1,lo:1,hi:7}]}]),Js=y("gem.pause",[{n:"paused",k:"b"}]),zs=y("gem.prefs",[{n:"reducedMotion",k:"b"},{n:"muted",k:"b"},{n:"showFrameStats",k:"b",o:1},{n:"locale",k:"s",max:35,f:"bcp47"},{n:"recommended",k:"o",o:1,fs:[{n:"volume",k:"i",lo:0,hi:100},{n:"batterySaver",k:"b"},{n:"keyboardLayout",k:"e",v:["wasd","arrows"]},{n:"gamepadConfirm",k:"e",v:["south","east"]},{n:"vibration",k:"b"},{n:"lookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"gamepadLookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"invertLookY",k:"b",o:1},{n:"touchMovement",k:"s",o:1,max:16,f:"code"}]}]),Ys=y("gem.cohorts",[{n:"cohorts",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"experimentId",k:"s",max:36},{n:"variantKey",k:"s",max:32}]}}]),Xs=y("gem.earnAllowanceChanged",[]),Qs=y("gem.viewport",[{n:"insets",k:"o",fs:[{n:"top",k:"i",lo:0,hi:4096},{n:"right",k:"i",lo:0,hi:4096},{n:"bottom",k:"i",lo:0,hi:4096},{n:"left",k:"i",lo:0,hi:4096}]},{n:"reserved",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384},{n:"width",k:"i",lo:0,hi:16384},{n:"height",k:"i",lo:0,hi:16384}]}}]),Zs=y("gem.deviceSettings",[{n:"settings",k:"j",o:1}]),ea=y("gem.willTerminate",[{n:"reason",k:"e",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"i",lo:0,hi:6e4}]),ta=y("gem.roomEvent",[{n:"event",k:"e",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"s",max:64},{n:"matchId",k:"s",o:1,max:64},{n:"version",k:"i",o:1,lo:0,hi:2147483647},{n:"reason",k:"s",o:1,max:64},{n:"platform",k:"e",o:1,v:["universal","mobile"]}]),na=y("gem.socketState",[{n:"connected",k:"b"},{n:"reason",k:"e",o:1,v:["connecting","dropped","watchdog","terminal"]}]),ra=y("gem.seatedEvent",[{n:"roomId",k:"s",max:64}]),ia=y("gem.autoStartFailedEvent",[{n:"roomId",k:"s",max:64},{n:"code",k:"s",max:64}]),oa=y("gem.signalEvent",[{n:"event",k:"e",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}]),sa=y("gem.dedicatedEvent",[{n:"event",k:"e",v:["answer","error","matchEnded"]},{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",o:1,max:10240},{n:"sessionId",k:"s",o:1,max:64},{n:"code",k:"s",o:1,max:64},{n:"message",k:"s",o:1,max:256},{n:"reason",k:"s",o:1,max:64}]),aa=y("gem.partyResult",[{n:"requestId",k:"s",max:64},{n:"partyId",k:"s",o:1,max:64}]),la=y("gem.clusterTarget",[{n:"clusterTargetId",k:"s",max:64},{n:"clusterTargetIds",k:"a",o:1,max:3,it:{n:"",k:"s",max:64}}]),da=y("gem.devtools",[{n:"action",k:"e",v:["open","close","toggle"]}]),ca=y("gem.screenshot",[{n:"maxWidth",k:"i",lo:1,hi:7680},{n:"maxHeight",k:"i",lo:1,hi:4320}]),ua=y("gem.screenshot.denied",[{n:"reason",k:"e",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"b"}]),ma=y("gem.requestContext",[]),pa=y("gem.gameContext",[{n:"context",k:"j"}]),ga=y("gem.signal",[{n:"signal",k:"e",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}]),ha=y("gem.dedicatedOffer",[{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",max:10240},{n:"intent",k:"e",v:["initial","ice_restart","full_reconnect"]}]),fa=y("gem.partyRequest",[{n:"requestId",k:"s",max:64}]),ya=y("gem.ready",[]),ba=y("gem.engaged",[]),_a=y("gem.progress",[{n:"loaded",k:"i",lo:0,hi:1099511627776},{n:"total",k:"i",lo:0,hi:1099511627776}]),va=y("gem.requestToken",[{n:"requestId",k:"s",max:64},{n:"reason",k:"e",v:["initial","expiring","rejected"]}]),ka=y("gem.requestLocalServer",[{n:"requestId",k:"s",max:64},{n:"gameRoomId",k:"s",max:64}]),wa=y("gem.localServer",[{n:"requestId",k:"s",max:64},{n:"serverId",k:"s",o:1,max:128}]),Ra=y("gem.localServer.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"reason",k:"e",v:["refused","unavailable"]}]),Sa=y("gem.exit",[{n:"reason",k:"s",o:1,max:64}]),xa=y("gem.openExternal",[{n:"url",k:"s",max:2048,f:"url"}]),Aa=y("gem.requestFullscreen",[{n:"enabled",k:"b"}]),Pa=y("gem.audioState",[{n:"muted",k:"b"}]),Ea=y("gem.rewardCue",[{n:"currencySlug",k:"s",max:32},{n:"expected",k:"i",o:1,lo:1,hi:1e9},{n:"origin",k:"o",o:1,fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384}]}]),Ta=y("gem.walletDisplay",[{n:"visible",k:"b"},{n:"currencies",k:"a",o:1,max:8,it:{n:"",k:"s",max:64}},{n:"score",k:"b",o:1}]),Ia=y("gem.controlsDeclare",[{n:"uses",k:"o",fs:[{n:"lookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"gamepadLookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"invertLookY",k:"s",o:1,max:16,f:"code"},{n:"touchMovement",k:"s",o:1,max:16,f:"code"}]}]),Ca=y("gem.menu",[{n:"settings",k:"b"},{n:"items",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"id",k:"s",max:32},{n:"label",k:"s",max:40}]}}]),Ma=y("gem.menuSelect",[{n:"entry",k:"e",v:["settings","item"]},{n:"id",k:"s",o:1,max:32}]),Oa=y("gem.requestShare",[{n:"params",k:"a",max:16,it:{n:"",k:"o",fs:[{n:"key",k:"s",max:64},{n:"value",k:"s",max:512}]}}]),La=y("gem.requestAvatarPicker",[]),Ga=y("gem.vibrate",[{n:"pattern",k:"a",max:99,it:{n:"",k:"i",lo:0,hi:1e4}}]),Da=y("gem.frameStats",[{n:"fps",k:"i",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"i",lo:0,hi:1e5}]),qa=y("gem.portraitBorders",[{n:"name",k:"s",o:1,max:40}]),$a=y("gem.error",[{n:"code",k:"e",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"s",o:1,max:256}]),Fa=y("gem.requestPurchase",[{n:"requestId",k:"s",max:64},{n:"purchaseKind",k:"e",v:["item","recipe"]},{n:"targetId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"quantity",k:"i",o:1,lo:1,hi:10},{n:"catalogId",k:"s",o:1,max:64}]),ja=y("gem.purchaseResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["ok","declined","unavailable"]},{n:"reason",k:"s",o:1,max:64,f:"code"},{n:"purchaseId",k:"s",o:1,max:64}]),Na=y("gem.deviceSettings.put",[{n:"requestId",k:"s",max:64},{n:"settings",k:"j"}]),Ua=y("gem.deviceSettings.result",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["stored","too_large","unavailable"]}]),Ba=y("gem.requestAd",[{n:"requestId",k:"s",max:64},{n:"placement",k:"s",max:32},{n:"format",k:"e",v:["interstitial","rewarded"]}]),Wa=y("gem.adResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["shown","no_ad","unavailable"]}]),Va=y("gem.requestSignIn",[{n:"requestId",k:"s",max:64}]),Ha=y("gem.signInResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["signed_in","declined","unavailable"]}]),Ka=y("gem.requestFriendChallenge",[{n:"requestId",k:"s",max:64},{n:"playerId",k:"s",max:64},{n:"template",k:"s",max:64},{n:"params",k:"j",o:1}]),Ja=y("gem.friendChallengeResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"s",o:1,max:64},{n:"param",k:"s",o:1,max:64},{n:"channel",k:"s",o:1,max:16},{n:"configVersion",k:"i",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:864e5},{n:"detail",k:"s",o:1,max:300}]),ae=Object.freeze(Hn);var it=3;function B(n){if(typeof n!="string")return;let e=n.trim();return e.length===0?void 0:e}function be(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=B(t);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var Ai=2e3,Pi=5e3;function Ei(n){let e=[],t=false,r=null,i=new Map,o=()=>{if(e.length>0)return Promise.resolve(e);if(t)return Promise.resolve([]);if(!n.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let a,s=new Promise(l=>{let d=false,m=null;a=u=>{d||(d=true,r=null,n.clock.clearTimeout(m),l(u));},m=n.clock.setTimeout(()=>{t=true,a([]);},n.timeoutMs??Ai);});return r={promise:s,settle:a},s};return {resolveList:o,resolve(){return e.length>0||t||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):o().then(a=>a[0])},refresh(a){return !Kn(e,a)||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(s=>{let l=null,d=m=>{i.delete(d)&&(n.clock.clearTimeout(l),s(m));};i.set(d,a),l=n.clock.setTimeout(()=>d(e),n.refreshTimeoutMs??Pi);})},accept(a,s){let l=be(s),d=B(a),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[u,p]of [...i])Kn(m,p)||u(m);}}}}function Kn(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var Ti=["lookSensitivity","gamepadLookSensitivity","invertLookY","touchMovement"];function ot(n){let e={};if(typeof n=="object"&&n!==null)for(let t of Ti){let r=n[t];(r==="player"||r==="game")&&(e[t]=r);}return e}var Ii=/^[a-z0-9][a-z0-9_-]{0,39}$/;function Ut(n){return typeof n=="string"&&Ii.test(n)}function Jn(n){if(n===null||Ut(n))return n;let e=typeof n=="string"?JSON.stringify(n.length>48?`${n.slice(0,48)}\u2026`:n):`a value of type ${typeof n}`;console.warn(`[gem] showPortraitBorders: ${e} is not a border name, so nothing was sent. A name is 1 to 40 of a-z, 0-9, _ and -, starting with a letter or digit, exactly as your store page declares it under media.portrait_borders. Pass null for no art.`);}var Oe=16384,st=24;function R(n){return e=>typeof e=="string"&&e.length>0&&e.length<=n?e:void 0}function ee(n,e){return t=>typeof t=="number"&&Number.isInteger(t)&&t>=n&&t<=e?t:void 0}function _e(...n){return e=>typeof e=="string"&&n.includes(e)?e:void 0}function zn(n){return typeof n=="boolean"?n:void 0}var L=R(64),Le=ee(0,2147483647);function Bt(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(e.length>=64)break;let r=L(t);typeof r=="string"&&e.push(r);}return e}function A(n,e,t){return {to:n,from:e,read:t,required:true}}function S(n,e,t){return {to:n,from:e,read:t,required:false}}function ve(n,e){let t={};for(let r of e){let i=r.read(n[r.from]);if(i===void 0){if(r.required)return null;continue}t[r.to]=i;}return t}function Ge(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let e=n;return typeof e.type!="string"||typeof e.data!="object"||e.data===null||Array.isArray(e.data)?null:{type:e.type,data:e.data}}var Yn=[A("sdp","sdp",R(10240)),A("signaling_intent","intent",_e("initial","ice_restart","full_reconnect"))];function at(n,e,t){if(typeof t!="object"||t===null||Array.isArray(t))return {reason:"offer: data must be an object"};let r=t,i=ve(r,Yn);return i===null?{reason:`offer: '${Yn.find(a=>a.read(r[a.from])===void 0)?.from??"?"}' is missing or out of bounds`}:{frame:{type:"webrtc_offer",match_id:n,game_id:e,...i}}}var Wt=Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"})),Ci=new Set(["error"]),Mi=Object.freeze(Object.assign(Object.create(null),{answer:[A("sdp","sdp",R(10240)),S("sessionId","session_id",R(64))],error:[S("code","code",R(64)),S("message","message",R(256))],matchEnded:[S("reason","reason",R(64))]}));function lt(n,e,t){let r=Ge(n);if(r===null)return null;let i=Wt[r.type];if(i===void 0)return null;let o=L(r.data.match_id);if(typeof o!="string"||!(Ci.has(i)?t(o):r.data.game_id===e))return null;let s=ve(r.data,Mi[i]??[]);return s===null?null:{event:i,matchId:o,...s}}var Oi=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=_e("disconnected","failed","closed")(e.iceState),r=ee(0,4102444800)(e.lastSeenAt);if(!(t===void 0&&r===void 0))return {...t===void 0?{}:{ice_state:t},...r===void 0?{}:{last_seen_timestamp:r}}},Li=Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[A("sdp","sdp",R(10240)),A("signaling_intent","intent",_e("initial","ice_restart","full_reconnect")),S("sdp_hash","sdpHash",R(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[A("peer_id","peerId",L),A("sdp","sdp",R(10240)),A("assigned_peer_id","assignedPeerId",ee(0,4294967295)),S("sdp_hash","sdpHash",R(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[A("peer_id","peerId",L),A("candidate","candidate",R(512)),S("sdp_mid","sdpMid",R(64)),S("sdp_mline_index","sdpMLineIndex",ee(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[A("host_epoch","hostEpoch",Le)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[A("host_epoch","hostEpoch",Le),S("evidence","evidence",Oi)]}}));function dt(n,e,t,r){let i=Li[n];if(i===void 0)return {reason:`unknown signal '${n}'`};if(typeof r!="object"||r===null||Array.isArray(r))return {reason:`${n}: data must be an object`};let o=r,a=ve(o,i.args);if(a===null){let s=i.args.find(l=>l.required&&l.read(o[l.from])===void 0);return {reason:`${n}: '${s?.from??"?"}' is missing or out of bounds`}}return {frame:{type:i.type,match_id:e,...i.gameScoped?{game_id:t}:{},...a}}}var Gi=Object.freeze(Object.assign(Object.create(null),{p2p_hello:"hello",p2p_sdp_offer:"offer",p2p_sdp_answer:"answer",p2p_ice_candidate:"ice",p2p_peer_joined:"peerJoined",p2p_peer_left:"peerLeft",p2p_host_migration:"migration",p2p_match_ended:"matchEnded",p2p_error:"error"})),Di=new Set(["error"]),qi=Object.freeze(Object.assign(Object.create(null),{hello:[A("playerId","player_id",L),A("hostPlayerId","host_player_id",L),A("hostEpoch","host_epoch",Le),S("members","members",Bt)],offer:[A("fromPlayerId","from_player_id",L),A("sdp","sdp",R(10240)),S("sessionId","signaling_session_id",R(128)),S("sdpHash","sdp_hash",R(128)),S("iceUfrag","ice_ufrag",R(64)),S("intent","signaling_intent",_e("initial","ice_restart","full_reconnect"))],answer:[A("fromPlayerId","from_player_id",L),A("sdp","sdp",R(10240)),S("sessionId","signaling_session_id",R(128)),S("sdpHash","sdp_hash",R(128)),S("iceUfrag","ice_ufrag",R(64)),S("assignedPeerId","assigned_peer_id",ee(0,4294967295))],ice:[A("fromPlayerId","from_player_id",L),A("candidate","candidate",R(512)),S("sdpMid","sdp_mid",R(64)),S("sdpMLineIndex","sdp_m_line_index",ee(0,255)),S("sdpMLineIndexAlt","sdp_mline_index",ee(0,255))],peerJoined:[A("playerId","player_id",L)],peerLeft:[A("playerId","player_id",L),S("reason","reason",R(64))],migration:[A("hostPlayerId","new_host_player_id",L),A("hostEpoch","host_epoch",Le),S("reason","reason",R(64)),S("kickedPlayerIds","kicked_player_ids",Bt),S("migrationComplete","migration_complete",zn)],matchEnded:[S("reason","reason",R(64))],error:[S("code","code",R(64)),S("message","message",R(256))]}));function ct(n,e,t){let r=Ge(n);if(r===null)return null;let i=Gi[r.type];if(i===void 0)return null;let o=L(r.data.match_id);if(typeof o!="string"||!(Di.has(i)?t(o):r.data.game_id===e))return null;let s=ve(r.data,qi[i]??[]);return s===null?null:{event:i,matchId:o,data:s}}var $i=Object.freeze(Object.assign(Object.create(null),{party_invite_received:"inviteReceived",party_member_joined:"memberJoined",party_member_left:"memberLeft",party_member_kicked:"memberKicked",party_leader_transferred:"leaderTransferred",party_updated:"updated",party_disbanded:"disbanded",party_game_room_joined:"gameRoomJoined",party_game_room_left:"gameRoomLeft"}));function De(n){let e=Ge(n);if(e===null)return null;let t=$i[e.type];if(t===void 0)return null;let r=e.data,i=L(r.party_id);if(typeof i!="string")return null;let o=ee(0,Number.MAX_SAFE_INTEGER)(r.version),a=L(r.game_room_id),s=L(r.game_id),l=L(r.inviter_player_id),d=R(80)(r.inviter_display_tag),m=R(64)(r.party_name);return {event:t,partyId:i,...o===void 0?{}:{version:o},...a===void 0?{}:{gameRoomId:a},...s===void 0?{}:{gameId:s},...l===void 0?{}:{inviterPlayerId:l},...d===void 0?{}:{inviterDisplayTag:d},...m===void 0?{}:{partyName:m}}}var re={now:()=>Date.now(),setTimeout:(n,e)=>setTimeout(n,e),clearTimeout:n=>clearTimeout(n)},te=class{constructor(e=re){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let t=tt[e];if(t===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??t,a=Math.max(0,r-i),s=Math.min(t,o+a*t/6e4);return s<1?(this.tokens.set(e,s),this.lastRefill.set(e,r),false):(this.tokens.set(e,s-1),this.lastRefill.set(e,r),true)}};function we(n,e){return n.toLowerCase()===e.toLowerCase()}function ut(n){let e=n.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function Qn(n,e){if(typeof e!="string"||e==="")return false;let t,r;try{t=new URL(n),r=new URL(e);}catch{return false}return t.protocol!=="http:"&&t.protocol!=="https:"||r.protocol!=="http:"&&r.protocol!=="https:"||t.username!==""||t.password!==""||t.pathname!=="/"||t.search!==""||t.hash!==""||t.port===""?false:ut(t.hostname)&&ut(r.hostname)}function Vt(n,e){if(n.min>n.max||e.min>e.max)return null;let t=Math.min(n.max,e.max),r=Math.max(n.min,e.min);return t>=r?t:null}var Fi=7,ji=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,Ni=["universal","mobile"],Ui={game_room_updated:"updated",game_room_match_started:"match_started",game_room_match_ready:"match_ready",game_room_match_failed:"match_failed",game_room_version_stale:"version_stale",match_ended:"updated",p2p_match_ended:"updated"},Bi=new Set(["match_ended","p2p_match_ended"]),Wi="game_room_auto_start_failed",Vi=/^[a-z][a-z0-9_]{0,63}$/,qe=64,Hi=8,Kt=class{constructor(e,t){this.clock=e;this.limit=t;}clock;limit;windowStart=0;used=0;allow(){let e=this.clock.now();return e-this.windowStart>=1e3&&(this.windowStart=e,this.used=0),this.used>=this.limit?false:(this.used+=1,true)}};function mt(n){if(!(typeof n!="string"||n.length===0||n.length>qe))return n}function Ki(n){return n instanceof Error?n.message:String(n)}function er(n,e){if(!n.has(e)){if(n.size>=Hi){let t=n.values().next().value;t!==void 0&&n.delete(t);}n.add(e);}}function Ht(){return new MessageChannel}var Ji=6e4/(tt["gem.handshake"]??1),zi=6e4,Jt=class{constructor(e){this.options=e;if(!rt(e.frameOrigin))throw new Error(`GemHost: frameOrigin must be a concrete origin, got '${e.frameOrigin}'. '*' and 'null' are refused \u2014 the handshake transfers the MessagePort, so an imprecise targetOrigin gives the session away.`);if(!rt(e.embedderOrigin))throw new Error(`GemHost: embedderOrigin must be a concrete origin, got '${e.embedderOrigin}'.`);this.clock=e.clock??re,this.inbound=new te(this.clock),this.outbound=new te(this.clock),this.socketWindow=new Kt(this.clock,24);}options;state="idle";port=null;version=null;timeoutHandle=null;reofferHandle=null;makeChannel=Ht;offered=[];offersMade=0;localDenials=0;chainEndsAt=null;gameId=null;peerCapabilities=[];knownMatches=new Set;askedMatches=new Set;clock;inbound;outbound;socketWindow;get currentState(){return this.state}get frameCapabilities(){return this.peerCapabilities}frameSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}start(e=Ht){if(this.state!=="idle"){this.fail("handshake_duplicate",`cannot start from state '${this.state}'`);return}if(typeof e=="function")this.makeChannel=e;else if(e&&e.port1&&e.port2){let t=e,r=false;this.makeChannel=()=>r?Ht():(r=true,t);}else throw new Error("GemHost.start: pass a function returning { port1, port2 } \u2014 omit it entirely to get a fresh MessageChannel per offer, which is what an embedder normally wants.");this.transition("handshaking"),this.offer(),this.scheduleReoffer(),this.timeoutHandle=this.clock.setTimeout(()=>{this.timeoutHandle=null,this.state==="handshaking"&&this.fail("handshake_timeout",`no answer from ${this.options.frameOrigin} to ${this.offersMade} handshake ${this.offersMade===1?"offer":"offers"} in the first ${Nt}ms; the offers continue for as long as this page holds the frame. This page presented embedder origin ${this.options.embedderOrigin}. A frame answers none of them if it carries no bridge at all, if it has not started listening yet, or if that origin is missing from the embedders it will accept \u2014 this side cannot tell which, and does not try.`);},Nt);}offer(){if(!this.outbound.allow("gem.handshake"))return false;let e=this.makeChannel(),t=e.port1;return t.onmessage=r=>this.receive(r.data,t),t.start?.(),this.offered.push({port:t,at:this.clock.now()}),this.offersMade+=1,this.options.frame.postMessage({gem:f,type:"gem.handshake",versions:{min:Z.min,max:Z.max},embedder:this.options.embedderOrigin,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]},...this.options.unbidden===true?{unbidden:true}:{}},this.options.frameOrigin,[e.port2]),true}scheduleReoffer(){this.reofferHandle=this.clock.setTimeout(()=>{this.reofferHandle=null,this.state==="handshaking"&&(this.offer(),this.pruneStaleOffers(),this.scheduleReoffer());},Ji);}pruneStaleOffers(){let e=this.clock.now()-zi;for(;this.offered.length>0&&(this.offered[0]?.at??e)<e;){let t=this.offered.shift();if(t===void 0)break;t.port.onmessage=null,t.port.close();}}adopt(e){for(let t of this.offered)t.port!==e&&(t.port.onmessage=null,t.port.close());this.offered.length=0,this.port=e;}static checkHandshakeOrigin(e,t,r){return we(e.origin,t)?e.source!==r?"source is not the mounted frame":null:`origin '${e.origin}' is not the expected frame origin`}sendToken(e){if(!Number.isInteger(e.chainEndsAt)||e.chainEndsAt<0){this.fail("internal","refusing a grant whose chainEndsAt is not a whole number of seconds >= 0");return}let t=this.chainEndsAt??e.chainEndsAt;if(this.chainExpired()){this.fail("token_unavailable","token chain ceiling reached");return}this.send({gem:f,type:"gem.token",token:e.token,expiresAt:e.expiresAt,chainEndsAt:t,generation:e.generation,playerId:e.playerId,gameId:e.gameId,channel:e.channel,...e.gameVersion===void 0?{}:{gameVersion:e.gameVersion},...e.requestId===void 0?{}:{requestId:e.requestId},...e.apiBaseUrl===void 0?{}:{apiBaseUrl:e.apiBaseUrl},...e.allowDevTools===true?{allowDevTools:true}:{},...e.garden===void 0?{}:{garden:e.garden}})&&(this.chainEndsAt=t,this.gameId??=e.gameId);}relayRoomEvent(e){if(this.gameId===null||typeof e!="object"||e===null||Array.isArray(e))return false;let t=e;if(typeof t.type!="string")return false;let r=Ui[t.type];if(r===void 0||typeof t.data!="object"||t.data===null||Array.isArray(t.data))return false;let i=t.data;if(i.game_id!==this.gameId)return false;let o=mt(i.game_room_id);if(o===void 0)return false;let a=Bi.has(t.type)?void 0:mt(i.match_id);a!==void 0&&this.rememberMatch(a);let s=typeof i.version=="number"?i.version:void 0,l=typeof i.reason=="string"?i.reason.slice(0,qe):void 0,d=r==="version_stale"&&Ni.includes(i.platform)?i.platform:void 0;return this.sendRoomEvent({event:r,roomId:o,...a===void 0?{}:{matchId:a},...s===void 0?{}:{version:s},...l===void 0?{}:{reason:l},...d===void 0?{}:{platform:d}})}sendRoomEvent(e){return this.frameSupports("rooms")?this.send({gem:f,type:"gem.roomEvent",event:e.event,roomId:e.roomId,...e.matchId===void 0?{}:{matchId:e.matchId},...e.version===void 0?{}:{version:e.version},...e.reason===void 0?{}:{reason:e.reason},...e.platform===void 0?{}:{platform:e.platform}}):false}sendSocketState(e){return this.frameSupports("socketState")?this.send({gem:f,type:"gem.socketState",connected:e.connected,...e.connected?{}:{reason:e.reason}}):false}sendSeatedEvent(e){return this.frameSupports("partySeating")?this.send({gem:f,type:"gem.seatedEvent",roomId:e}):false}relaySeatedEvent(e){if(this.gameId===null)return false;let t=De(e);if(t===null||t.event!=="gameRoomJoined"||t.gameId!==this.gameId)return false;let r=mt(t.gameRoomId);return r===void 0?false:this.sendSeatedEvent(r)}sendAutoStartFailedEvent(e){return this.frameSupports("autoStartFailure")?this.send({gem:f,type:"gem.autoStartFailedEvent",roomId:e.roomId,code:e.code}):false}relayAutoStartFailedEvent(e){if(this.gameId===null||typeof e!="object"||e===null||Array.isArray(e))return false;let t=e;if(t.type!==Wi||typeof t.data!="object"||t.data===null||Array.isArray(t.data))return false;let r=t.data;if(r.game_id!==this.gameId)return false;let i=mt(r.game_room_id),o=typeof r.code=="string"&&Vi.test(r.code)?r.code:void 0;return i===void 0||o===void 0?false:this.sendAutoStartFailedEvent({roomId:i,code:o})}relaySocketEvent(e){let t=[];(this.relayRoomEvent(e)||this.relayAutoStartFailedEvent(e))&&t.push("room"),this.relaySignalEvent(e)&&t.push("signal"),this.relayDedicatedEvent(e)&&t.push("dedicated");let r=De(e);return r!==null&&(this.options.onPartyEvent?.(r),this.relaySeatedEvent(e),t.push("party")),t}relaySignalEvent(e){if(this.gameId===null)return false;let t=ct(e,this.gameId,r=>this.knowsMatch(r));return t===null?false:(t.event==="hello"&&this.rememberMatch(t.matchId),this.sendSignalEvent(t))}sendSignalEvent(e){return this.frameSupports("p2p")?this.send({gem:f,type:"gem.signalEvent",event:e.event,matchId:e.matchId,data:e.data}):false}relayDedicatedEvent(e){if(this.gameId===null)return false;let t=lt(e,this.gameId,r=>this.knowsMatch(r));return t===null?false:this.sendDedicatedEvent(t)}sendDedicatedEvent(e){return this.frameSupports("dedicated")?this.send({gem:f,type:"gem.dedicatedEvent",event:e.event,matchId:e.matchId,...e.sdp===void 0?{}:{sdp:e.sdp},...e.sessionId===void 0?{}:{sessionId:e.sessionId},...e.code===void 0?{}:{code:e.code},...e.message===void 0?{}:{message:e.message},...e.reason===void 0?{}:{reason:e.reason}}):false}knowsMatch(e){return this.knownMatches.has(e)||this.askedMatches.has(e)}rememberMatch(e){er(this.knownMatches,e);}rememberAsked(e){er(this.askedMatches,e);}answerPartyRequest(e,t){return this.send({gem:f,type:"gem.partyResult",requestId:e,...t===void 0?{}:{partyId:t}})}answerPurchase(e,t,r,i){return this.send({gem:f,type:"gem.purchaseResult",requestId:e,outcome:t,...r===void 0||t!=="ok"?{}:{purchaseId:r},...i===void 0||t==="ok"?{}:{reason:i}})}answerDeviceSettingsPut(e,t){return this.send({gem:f,type:"gem.deviceSettings.result",requestId:e,outcome:t})}sendDeviceSettings(e){return this.frameSupports("deviceSettings")?this.send({gem:f,type:"gem.deviceSettings",...e===void 0?{}:{settings:e}}):false}sendMenuSelect(e){return this.frameSupports("gameMenu")?this.send(e==="settings"?{gem:f,type:"gem.menuSelect",entry:"settings"}:{gem:f,type:"gem.menuSelect",entry:"item",id:e.id}):false}answerAd(e,t){return this.send({gem:f,type:"gem.adResult",requestId:e,outcome:t})}answerSignIn(e,t){return this.send({gem:f,type:"gem.signInResult",requestId:e,outcome:t})}answerFriendChallenge(e,t,r={}){let i={};if(t==="invalid"){let{code:o,param:a,channel:s,configVersion:l,detail:d}=r;typeof o=="string"&&o.length<=64&&(i.code=o),typeof a=="string"&&a.length<=64&&(i.param=a),typeof s=="string"&&s.length<=16&&(i.channel=s),typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&(i.configVersion=l),typeof d=="string"&&(i.detail=d.slice(0,300));}else if(t==="rate_limited"){let o=r.retryAfterMs;typeof o=="number"&&Number.isFinite(o)&&(i.retryAfterMs=Math.min(864e5,Math.max(0,Math.round(o))));}return this.send({gem:f,type:"gem.friendChallengeResult",requestId:e,outcome:t,...i})}denyToken(e){this.send({gem:f,type:"gem.token.denied",requestId:e.requestId,retryable:e.retryable,reason:e.reason,correlationId:e.correlationId,...e.retryAfterMs===void 0?{}:{retryAfterMs:e.retryAfterMs}});}grantLocalServer(e){return this.frameSupports("localHost")?this.send({gem:f,type:"gem.localServer",requestId:e.requestId,...e.serverId===void 0?{}:{serverId:e.serverId}}):false}denyLocalServer(e){return this.frameSupports("localHost")?this.send({gem:f,type:"gem.localServer.denied",requestId:e.requestId,retryable:e.retryable,reason:e.reason}):false}sendClusterTarget(e){let t=typeof e=="string"?[e]:e,r=Array.isArray(t)?t.length===0?"[]":t.find(o=>typeof o!="string"||o.trim().length===0||o.length>qe):String(t);if(r!==void 0)return this.fail("internal",`refusing to send '${String(r)}' as a cluster target \u2014 each id must be a non-blank string of at most ${qe} characters, and a list must name at least one. Omit the message entirely when there is no answer: the frame then names no cluster and gem-api chooses.`),false;if(t.length>3)return this.fail("internal",`refusing to send ${t.length} cluster targets \u2014 at most ${3} acceptable clusters cross, best first.`),false;if(!this.frameSupports("clusterTarget"))return false;let[i]=t;return this.send({gem:f,type:"gem.clusterTarget",clusterTargetId:i,...typeof e=="string"?{}:{clusterTargetIds:[...t]}})}sendPlayer(e){let{displayName:t,displayTag:r}=e.untrusted,i=e.badges?.map(({itemId:l,iconUrl:d})=>({itemId:l,iconUrl:d})),o=e.boost&&{multipliers:e.boost.multipliers.map(({currencyId:l,currencySlug:d,multiplierBp:m})=>({currencyId:l,currencySlug:d,multiplierBp:m})),...e.boost.expiresInDays===void 0?{}:{expiresInDays:Math.min(Fi,e.boost.expiresInDays)}},a=e.discriminator!==void 0&&/^[0-9]{1,8}$/.test(e.discriminator)?e.discriminator:void 0,s=e.avatarIconId!==void 0&&ji.test(e.avatarIconId)?e.avatarIconId:void 0;this.send({gem:f,type:"gem.player",untrusted:{displayName:t,...r===void 0?{}:{displayTag:r},displayHandle:r??t},...e.playerId===void 0?{}:{playerId:e.playerId},...a===void 0?{}:{discriminator:a},...e.avatarIconUrl===void 0?{}:{avatarIconUrl:e.avatarIconUrl},...s===void 0?{}:{avatarIconId:s},...i===void 0?{}:{badges:i},...o===void 0?{}:{boost:o},displayTag:a??"",...e.avatarIconUrl===void 0?{}:{avatarUrl:e.avatarIconUrl}});}chainExpired(){return this.chainEndsAt!==null&&this.clock.now()/1e3>=this.chainEndsAt}localCorrelationId(){return `local-${++this.localDenials}`}sendPause(e){this.send({gem:f,type:"gem.pause",paused:e});}sendDevtools(e){this.send({gem:f,type:"gem.devtools",action:e});}requestScreenshot(e,t){return this.frameSupports("screenshot")?this.send({gem:f,type:"gem.screenshot",maxWidth:t.maxWidth,maxHeight:t.maxHeight},[e]):false}requestContext(){return this.frameSupports("feedbackContext")?this.send({gem:f,type:"gem.requestContext"}):false}sendPrefs(e){this.send({gem:f,type:"gem.prefs",...e});}sendCohorts(e){return this.frameSupports("cohorts")?this.send({gem:f,type:"gem.cohorts",cohorts:e.map(t=>({experimentId:t.experimentId,variantKey:t.variantKey}))}):false}sendEarnAllowanceChanged(){return this.frameSupports("earnAllowance")?this.send({gem:f,type:"gem.earnAllowanceChanged"}):false}sendViewport(e){if(!this.frameSupports("viewport"))return false;let t=(e.reserved??[]).map(({x:o,y:a,width:s,height:l})=>({x:o,y:a,width:s,height:l})),r=this.frameSupports("reservedAreas"),i=e.insets.top;if(!r)for(let o of t)o.y===0&&(i=Math.max(i,o.height));return this.send({gem:f,type:"gem.viewport",insets:{top:i,right:e.insets.right,bottom:e.insets.bottom,left:e.insets.left},...r?{reserved:t}:{}})}sendWillTerminate(e,t){this.send({gem:f,type:"gem.willTerminate",reason:e,graceMs:t});}close(){this.timeoutHandle!==null&&(this.clock.clearTimeout(this.timeoutHandle),this.timeoutHandle=null),this.reofferHandle!==null&&(this.clock.clearTimeout(this.reofferHandle),this.reofferHandle=null);for(let e of this.offered)e.port.onmessage=null,e.port.close();this.offered.length=0,this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="unsupported"&&this.transition("closed");}transition(e){this.state!==e&&(this.state=e,this.options.onStateChange?.(e));}fail(e,t){this.options.onError?.(e,t);}send(e,t){if(this.state!=="connected"||!this.port)return this.options.onDropped?.("internal",`dropped ${String(e.type)} before connect`),false;let r=e.type;if(!this.outbound.allow(r))return this.fail("rate_limited",`parent exceeded its own limit for ${r}`),false;let i=ae[r]?.(e);return i?(this.fail("internal",`refusing to send malformed ${r}: ${i}`),false):(t===void 0?this.port.postMessage({...e,v:this.version}):this.port.postMessage({...e,v:this.version},t),true)}receive(e,t){if(this.state==="closed"||this.state==="unsupported")return;let r=typeof e=="object"&&e!==null?e.type:void 0;if(typeof r!="string"){this.refuseMalformed("invalid_message","message has no type");return}let i=ae[r];if(!i){this.refuseMalformed("unsupported",`unknown message type ${JSON.stringify(r.slice(0,qe))}`);return}if(!this.inbound.allow(r)){this.fail("rate_limited",`frame exceeded the limit for ${r}`);return}let o=nt(r);if(o!==void 0&&!this.options.capabilities?.includes(o)){this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this parent did not advertise`);return}let a=i(e);if(a){this.fail("invalid_message",`${r}: ${a}`);return}let s=e;r!=="gem.handshake.accept"&&!this.versionMatches(s,r)||this.dispatch(r,s,t);}refuseMalformed(e,t){if(!this.inbound.allow(ye)){this.options.onDropped?.(e,t);return}this.fail(e,t);}versionMatches(e,t){return e.v===this.version?true:(this.fail("invalid_message",`${t}: expected v ${String(this.version)}, got ${String(e.v)}`),false)}forwardSignal(e){let t=this.options.onSendSignal;if(t===void 0){this.fail("unsupported","this parent advertised `p2p` but wired no onSendSignal, so signaling has nowhere to go");return}if(this.gameId===null){this.options.onDropped?.("internal","gem.signal before any token was issued");return}if(e.signal!=="join"&&!this.knownMatches.has(e.matchId)){this.fail("unsupported",`gem.signal names match '${e.matchId}', which this player's socket has not mentioned`);return}if(!this.socketWindow.allow()){this.fail("rate_limited","signaling exceeded this parent per-second socket budget");return}let r=dt(e.signal,e.matchId,this.gameId,e.data);if("reason"in r){this.fail("invalid_message",`gem.signal: ${r.reason}`);return}this.withinFrameSize("gem.signal",r.frame,"Trickle ICE candidates rather than gathering them into the offer.")&&(this.rememberAsked(e.matchId),t(r.frame));}forwardDedicatedOffer(e){let t=this.options.onSendSignal;if(t===void 0){this.fail("unsupported","this parent advertised `dedicated` but wired no onSendSignal, so the offer has nowhere to go");return}if(this.gameId===null){this.options.onDropped?.("internal","gem.dedicatedOffer before any token was issued");return}if(!this.socketWindow.allow()){this.fail("rate_limited","signaling exceeded this parent per-second socket budget");return}let r=at(e.matchId,this.gameId,{sdp:e.sdp,intent:e.intent});if("reason"in r){this.fail("invalid_message",`gem.dedicatedOffer: ${r.reason}`);return}if(this.withinFrameSize("gem.dedicatedOffer",r.frame,"A complete gathered offer fits; one that does not is carrying media sections this path does not permit, or candidates from ICE servers this path does not use.")){this.rememberAsked(e.matchId);try{t(r.frame);}catch(i){this.sendDedicatedEvent({event:"error",matchId:e.matchId,code:"embedder_relay_unavailable",message:"the page could not put the offer on the player socket"}),this.fail("internal",`gem.dedicatedOffer: the socket refused the send: ${Ki(i)}`);}}}withinFrameSize(e,t,r){let i=JSON.stringify(t).length;return i<=16384?true:(this.fail("invalid_message",`${e} builds a ${i}-byte socket frame, over the ${16384}-byte limit gem-api enforces, so the socket would drop it and then fail to establish. ${r}`),false)}dispatch(e,t,r){if(e==="gem.handshake.accept"){if(this.state!=="handshaking"){this.fail("handshake_duplicate","handshake already settled");return}let i=t.v;if(i<Z.min||i>Z.max){this.transition("unsupported"),this.fail("version_mismatch",`frame chose v${i}, outside our supported range`),this.close();return}this.adopt(r),this.version=i,this.peerCapabilities=t.capabilities??[],this.timeoutHandle!==null&&(this.clock.clearTimeout(this.timeoutHandle),this.timeoutHandle=null),this.reofferHandle!==null&&(this.clock.clearTimeout(this.reofferHandle),this.reofferHandle=null),this.transition("connected");return}if(this.state!=="connected"){this.fail("invalid_message",`${e} received before the handshake completed`);return}switch(e){case "gem.ready":this.options.onReady?.();break;case "gem.engaged":this.options.onEngaged?.();break;case "gem.progress":this.options.onProgress?.(t);break;case "gem.requestToken":{let i=t;if(this.chainExpired()){this.denyToken({requestId:i.requestId,retryable:false,reason:"chain_exhausted",correlationId:this.localCorrelationId()});break}this.options.onRequestToken?.(i);break}case "gem.requestLocalServer":{this.options.onRequestLocalServer?.(t);break}case "gem.exit":this.options.onExit?.(t),this.close();break;case "gem.openExternal":this.options.onOpenExternal?.(t);break;case "gem.requestFullscreen":this.options.onRequestFullscreen?.(t);break;case "gem.audioState":this.options.onAudioState?.(t);break;case "gem.rewardCue":this.options.onRewardCue?.(t);break;case "gem.walletDisplay":this.options.onWalletDisplay?.(t);break;case "gem.controlsDeclare":this.options.onControlsDeclare?.(ot(t.uses));break;case "gem.menu":this.options.onMenu?.(t);break;case "gem.frameStats":this.options.onFrameStats?.(t);break;case "gem.portraitBorders":{let{name:i}=t;i==null?this.options.onPortraitBorders?.(null):Ut(i)&&this.options.onPortraitBorders?.(i);break}case "gem.screenshot.denied":this.options.onScreenshotDenied?.(t);break;case "gem.gameContext":this.options.onGameContext?.(t);break;case "gem.signal":this.forwardSignal(t);break;case "gem.dedicatedOffer":this.forwardDedicatedOffer(t);break;case "gem.partyRequest":{let i=t;if(this.options.onPartyRequest===void 0){this.answerPartyRequest(i.requestId);break}this.options.onPartyRequest(i);break}case "gem.requestPurchase":{let i=t;if(!this.frameSupports("purchases")){this.fail("unsupported_capability","refusing gem.requestPurchase: the frame did not advertise 'purchases', so it cannot receive gem.purchaseResult. Nothing was prompted and nothing was spent.");break}if(this.options.onRequestPurchase===void 0){this.answerPurchase(i.requestId,"unavailable");break}this.options.onRequestPurchase(i);break}case "gem.deviceSettings.put":{let i=t;if(!this.frameSupports("deviceSettings")){this.fail("unsupported_capability","refusing gem.deviceSettings.put: the frame did not advertise 'deviceSettings', so it cannot receive gem.deviceSettings.result. Nothing was stored.");break}if(this.options.onDeviceSettingsPut===void 0){this.answerDeviceSettingsPut(i.requestId,"unavailable");break}this.options.onDeviceSettingsPut(i);break}case "gem.requestAd":{let i=t;if(!this.frameSupports("ads")){this.fail("unsupported_capability","refusing gem.requestAd: the frame did not advertise 'ads', so it cannot receive gem.adResult. Nothing was rendered.");break}if(this.options.onRequestAd===void 0){this.answerAd(i.requestId,"no_ad");break}this.options.onRequestAd(i);break}case "gem.requestSignIn":{let i=t;if(!this.frameSupports("signIn")){this.fail("unsupported_capability","refusing gem.requestSignIn: the frame did not advertise 'signIn', so it cannot receive gem.signInResult. Nothing was rendered.");break}if(this.options.onRequestSignIn===void 0){this.answerSignIn(i.requestId,"unavailable");break}this.options.onRequestSignIn(i);break}case "gem.requestFriendChallenge":{let i=t;if(!this.frameSupports("friendChallenges")){this.fail("unsupported_capability","refusing gem.requestFriendChallenge: the frame did not advertise 'friendChallenges', so it cannot receive gem.friendChallengeResult. Nothing was previewed, rendered or sent.");break}if(this.options.onRequestFriendChallenge===void 0){this.answerFriendChallenge(i.requestId,"unavailable");break}this.options.onRequestFriendChallenge(i);break}case "gem.requestShare":if(!this.frameSupports("share")){this.fail("unsupported_capability","refusing gem.requestShare: the frame did not advertise 'share'. Nothing was shared.");break}this.options.onRequestShare?.(t);break;case "gem.requestAvatarPicker":if(!this.frameSupports("avatarPicker")){this.fail("unsupported_capability","refusing gem.requestAvatarPicker: the frame did not advertise 'avatarPicker'. Nothing was opened.");break}this.options.onRequestAvatarPicker?.();break;case "gem.vibrate":{if(!this.frameSupports("vibration")){this.fail("unsupported_capability","refusing gem.vibrate: the frame did not advertise 'vibration'. Nothing was played.");break}let i=t,o=i.pattern.reduce((a,s)=>a+s,0);if(o>1e4){this.fail("invalid_message",`refusing gem.vibrate: the pattern totals ${o} ms, over ${1e4}. Nothing was played.`);break}this.options.onVibrate?.(i);break}case "gem.error":this.fail(t.code,t.message);break;default:this.fail("unsupported",`no parent handler for '${e}'`);}}};var W=class{#e;constructor(e){this.#e=e,Object.freeze(this);}toString(){return "[gem: use gem.text.toPlain()]"}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function de(n){return new W(n)}var Yi={toPlain(n){return W.unwrap(n)},compare(n,e,t){let r=n instanceof W?W.unwrap(n):n,i=e instanceof W?W.unwrap(e):e,o;try{o=new Intl.Collator(t);}catch{o=new Intl.Collator;}return o.compare(r,i)},equals(n,e){let t=n instanceof W?W.unwrap(n):n,r=e instanceof W?W.unwrap(e):e;return t.normalize("NFC")===r.normalize("NFC")}};function tr(n){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function Xi(n,e){if(n!==true)return {visible:false};let t=[],r=false;for(let i of Array.isArray(e)?e:[])i==="score"?r=true:typeof i=="string"&&i.length>0&&i.length<=64&&!t.includes(i)&&t.push(i);return !r&&t.length===0?{visible:true}:{visible:true,currencies:t.slice(0,8),score:r}}function Qi(n,e){let t=[];for(let r of Array.isArray(e)?e:[]){if(t.length===4)break;if(typeof r!="object"||r===null)continue;let{id:i,label:o}=r;typeof i!="string"||i.length===0||i.length>32||typeof o!="string"||o.trim().length===0||t.some(a=>a.id===i)||t.push({id:i,label:o.trim().slice(0,40)});}return t.length===0?{settings:n===true}:{settings:n===true,items:t}}function nr(n,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function Zi(n){let e=n.untrusted,t=de(e.displayName),r=e.displayTag||e.displayHandle,i=r?de(r):void 0,o=n.discriminator||n.displayTag,a=o&&/^[0-9]{1,8}$/.test(o)?o:void 0,s=n.avatarIconUrl||n.avatarUrl,l=n.avatarIconId,d={displayName:t,displayHandle:i??t,badges:(n.badges??[]).map(h=>({itemId:h.itemId,iconUrl:h.iconUrl}))};n.playerId&&(d.playerId=n.playerId),a&&(d.discriminator=a),i&&(d.displayTag=i),s&&(d.avatarIconUrl=d.avatarUrl=s),l&&/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i.test(l)&&(d.avatarIconId=l);let m=n.boost,u=(m?.multipliers??[]).map(h=>({currencyId:h.currencyId,currencySlug:h.currencySlug,multiplier:h.multiplierBp/1e4})),p=u.some(h=>h.multiplier>1);return d.boost=p&&m?.expiresInDays?{active:p,multipliers:u,expiresInDays:m.expiresInDays}:{active:p,multipliers:u},d}var eo=1e4,zt=class{constructor(e){this.options=e;if(e.expectedSource===void 0||e.expectedSource===null)throw new Error("GemFrame: expectedSource is required and must not be null \u2014 pass window.parent. The handshake transfers the MessagePort, and origin alone does not say WHICH document on that origin sent it.");this.expectedSource=e.expectedSource,this.clock=e.clock??re,this.inbound=new te(this.clock),this.outbound=new te(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];unbidden=false;engagedSent=false;readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}get unbiddenLaunch(){return this.unbidden}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(s=>we(s,e.origin))||Qn(e.origin,this.options.selfOrigin)))return this.refuse(e,`embedder '${e.origin}' is not in allowedEmbedders`),this.state==="waiting"&&this.transition("refused"),false;if(this.state==="connected")return this.fail("handshake_duplicate","this document already has a port"),false;if(this.state!=="waiting")return false;let r=ae["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!we(i.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${i.embedder}' but arrived from '${e.origin}'`),false;let o=e.ports?.[0];if(!o)return this.refuse(e,"handshake transferred no MessagePort"),false;let a=Vt(Z,i.versions);return a===null?(o.onmessage=null,o.postMessage({gem:f,type:"gem.error",code:"version_mismatch",message:`frame supports v${Z.min}..v${Z.max}`}),o.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=o,this.version=a,o.onmessage=s=>this.receive(s.data,s.ports??[]),o.start?.(),this.peerCapabilities=i.capabilities??[],this.unbidden=i.unbidden===true,o.postMessage({gem:f,type:"gem.handshake.accept",v:a,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:f,type:"gem.ready"});}settled(e=eo){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(t=>{let r=o=>{this.clock.clearTimeout(i),t(o);},i=this.clock.setTimeout(()=>{let o=this.settleWaiters.indexOf(r);o>=0&&this.settleWaiters.splice(o,1),t(this.state);},e);this.settleWaiters.push(r);})}progress(e,t){this.send({gem:f,type:"gem.progress",loaded:e,total:t});}requestToken(e,t){this.send({gem:f,type:"gem.requestToken",requestId:e,reason:t});}requestLocalServer(e,t){return this.parentSupports("localHost")?(this.send({gem:f,type:"gem.requestLocalServer",requestId:e,gameRoomId:t}),true):false}exit(e){this.send(e===void 0?{gem:f,type:"gem.exit"}:{gem:f,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:f,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:f,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:f,type:"gem.audioState",muted:e}),true)}reportEngaged(){return this.engagedSent||this.state!=="connected"||!this.parentSupports("engagement")||!this.send({gem:f,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let t={gem:f,type:"gem.rewardCue",currencySlug:String(e.currencySlug).slice(0,32)};return e.expected!==void 0&&Number.isFinite(e.expected)&&e.expected>=1&&(t.expected=Math.min(1e9,Math.round(e.expected))),e.origin&&(t.origin={x:tr(e.origin.x),y:tr(e.origin.y)}),this.send(t),true}showPortraitBorders(e){let t=Jn(e);return t===void 0||this.state!=="connected"||!this.parentSupports("portraitBorders")?false:this.send(t===null?{gem:f,type:"gem.portraitBorders"}:{gem:f,type:"gem.portraitBorders",name:t})}setWalletVisible(e,t){return this.state!=="connected"||!this.parentSupports("walletDisplay")?false:this.send({gem:f,type:"gem.walletDisplay",...Xi(e,t?.only)})}declareControls(e){return this.state!=="connected"||!this.parentSupports("controls")?false:this.send({gem:f,type:"gem.controlsDeclare",uses:ot(e)})}setMenu(e,t){return this.state!=="connected"||!this.parentSupports("gameMenu")?false:this.send({gem:f,type:"gem.menu",...Qi(e,t)})}requestShare(e){return this.state!=="connected"||!this.parentSupports("share")?false:this.send({gem:f,type:"gem.requestShare",params:e.map(({key:t,value:r})=>({key:t,value:r}))})}requestAvatarPicker(){return this.state!=="connected"||!this.parentSupports("avatarPicker")?false:this.send({gem:f,type:"gem.requestAvatarPicker"})}requestVibrate(e){return this.state!=="connected"||!this.parentSupports("vibration")?false:this.send({gem:f,type:"gem.vibrate",pattern:[...e]})}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:f,type:"gem.frameStats",fps:nr(e.fps,1e3),frameTimeP95Ms:nr(e.frameTimeP95Ms,1e5)}),true)}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:f,type:"gem.gameContext",context:e}),true)}signal(e,t,r){this.send({gem:f,type:"gem.signal",signal:e,matchId:t,data:r});}dedicatedOffer(e,t,r){this.send({gem:f,type:"gem.dedicatedOffer",matchId:e,sdp:t,intent:r});}requestParty(e){return this.send({gem:f,type:"gem.partyRequest",requestId:e})}requestPurchase(e,t,r,i,o,a){return this.send({gem:f,type:"gem.requestPurchase",requestId:e,purchaseKind:t,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...a===void 0?{}:{catalogId:a}})}putDeviceSettings(e,t){return this.send({gem:f,type:"gem.deviceSettings.put",requestId:e,settings:t})}requestAd(e,t,r){return this.send({gem:f,type:"gem.requestAd",requestId:e,placement:t,format:r})}requestSignIn(e){return this.send({gem:f,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,t,r,i){return this.send({gem:f,type:"gem.requestFriendChallenge",requestId:e,playerId:t,template:r,...i===void 0?{}:{params:i}})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let t of this.settleWaiters.splice(0))t(e);this.options.onStateChange?.(e);}}refuseMalformed(e,t){if(!this.inbound.allow(ye)){this.options.onDropped?.(e,t);return}this.fail(e,t);}dropUnknownType(e){this.inbound.allow(ye)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,t){e.ports?.[0]?.close?.(),this.inbound.allow(ye)&&this.options.onRefused?.(t);}fail(e,t){this.options.onError?.(e,t),this.state==="connected"&&this.port&&this.send({gem:f,type:"gem.error",code:e,...t===void 0?{}:{message:t}});}send(e){if(this.state!=="connected"||!this.port)return this.options.onDropped?.("internal",`dropped ${String(e.type)} before connect`),false;let t=e.type;if(!this.outbound.allow(t))return this.options.onError?.("rate_limited",`frame exceeded its own limit for ${t}`),false;let r=ae[t]?.(e);return r?(this.options.onError?.("internal",`refusing to send malformed ${t}: ${r}`),false):(this.port.postMessage(this.version===null?e:{...e,v:this.version}),true)}receive(e,t=[]){let r=false;try{r=this.dispatchInbound(e,t);}finally{r||rr(t);}}dispatchInbound(e,t){if(this.state!=="connected")return false;let r=typeof e=="object"&&e!==null?e.type:void 0;if(typeof r!="string")return this.refuseMalformed("invalid_message","message has no type"),false;let i=ae[r];if(!i)return this.dropUnknownType(r),false;if(!this.inbound.allow(r))return this.fail("rate_limited",`parent exceeded the limit for ${r}`),false;let o=nt(r);if(o!==void 0&&!this.options.capabilities?.includes(o))return this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this frame did not advertise`),false;let a=i(e);if(a)return this.fail("invalid_message",`${r}: ${a}`),false;let s=e;if(s.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(s);break;case "gem.pause":this.options.onPause?.(s);break;case "gem.menuSelect":this.options.onMenuSelect?.(s);break;case "gem.prefs":this.options.onPrefs?.(s);break;case "gem.cohorts":this.options.onCohorts?.(s);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(s);break;case "gem.willTerminate":this.options.onWillTerminate?.(s);break;case "gem.devtools":this.options.onDevtools?.(s.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=t[0];if(!l){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let d={maxWidth:s.maxWidth,maxHeight:s.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return rr(t.slice(1)),this.options.onScreenshot(d,l,(m,u)=>this.screenshotDenied(m,u)),true}case "gem.token.denied":this.options.onTokenDenied?.(s);break;case "gem.localServer":this.options.onLocalServer?.(s);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(s);break;case "gem.player":{this.options.onPlayer?.(Zi(s));break}case "gem.roomEvent":this.options.onRoomEvent?.(s);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(s);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(s);break;case "gem.socketState":this.options.onSocketState?.(s);break;case "gem.signalEvent":this.options.onSignalEvent?.(s);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(s);break;case "gem.clusterTarget":this.options.onClusterTarget?.(s);break;case "gem.partyResult":this.options.onPartyResult?.(s);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(s);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(s);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(s);break;case "gem.adResult":this.options.onAdResult?.(s);break;case "gem.signInResult":this.options.onSignInResult?.(s);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(s);break;case "gem.error":this.options.onError?.(s.code,s.message);break;default:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,t){this.send({gem:f,type:"gem.screenshot.denied",reason:e,retryable:t});}};function rr(n){for(let e of n)try{e?.close?.();}catch{}}var to=16384;function no(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let e;try{e=JSON.stringify(n);}catch{return null}return typeof e!="string"?null:ro(e)}function ro(n){let e=0;for(let t=0;t<n.length;t+=1){let r=n.charCodeAt(t);if(r<128)e+=1;else if(r<2048)e+=2;else if(r>=55296&&r<=56319){let i=n.charCodeAt(t+1);i>=56320&&i<=57343?(e+=4,t+=1):e+=3;}else e+=3;}return e}var ir=["p2p","dedicated","unknown"],pt=["connection_setup_duration_seconds","reconnect_latency_seconds","datachannel_rtt_seconds","p2p_join_to_play_latency_seconds","ice_restart_outcome_total","connection_failures_total","transport_permanent_failures_total","transport_quality_score","host_migration_outcome_total","turn_relay_usage_ratio"];var ce=class{constructor(e){this.options=e;}options;async post(e,t){let r=this.options.gameId();if(r===null||r==="")return;let i=io(e,this.options.transport,(this.options.now??Date.now)());i.length!==0&&await this.options.client.post(`/v1/games/${encodeURIComponent(r)}/telemetry/p2p`,{events:i},t);}report(e){this.post(e).catch(()=>{});}};function io(n,e,t){let r=Math.floor(t/1e3);return n.filter(i=>pt.includes(i.type)).slice(0,100).map(i=>{let o=oo(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:i.value===void 0?{}:{value:i.value}}})}function oo(n){if(n!==void 0)return ir.includes(n)?n:"unknown"}function Yt(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}var j=class extends Error{constructor(t,r,i,o,a){super(`${t} (${r}): ${i}`);this.reason=t;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=a;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}};var ao=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),c=class extends Error{constructor(t,r,i){super(`${t}: ${r}`,i);this.reason=t;this.name="DedicatedServerError",this.retryable=ao.has(t),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var or=["explicit","stale_cleanup","game_room_closed","replaced","migration_failed","host_left","insufficient_players","all_left","expired","migration_rate_exceeded","game_room_gone","failed","idle","reclaimed"],lo=new Set(or);function Re(n){return typeof n=="string"&&lo.has(n)?n:"unknown"}var $e="webrtc_dedicated",Qt=["universal","mobile","web"];var co="p2p_unavailable",uo="capacity_unavailable",mo=2,sr=3e4,ar=1e3,lr=2e4;async function gt(n){let e=B(n.clusterTargetId),t=n.nextClusterTarget,r=0,i=n.clock??re,o=n.retry??{},a=o.budgetMs??sr,s=o.maxDelayMs??lr,l=o.initialDelayMs??ar,d=i.now(),m=d+a,u=0;for(;;){u++;try{let p=await en(n.signal,"while allocating",()=>n.client.post(`${ur(n)}/start_match`,e===void 0?{}:{cluster_target_id:e},n.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!po(p)||a<=0)throw p;if(p.status===503&&p.code===co)throw new c("p2p_unavailable",`room ${n.roomId} starts a peer-to-peer match, which allocates no server \u2014 so this refusal is not capacity and waiting cannot help: ${p.message}`,{cause:p});if(r=p.code===uo?r+1:0,t!==void 0&&r>=mo){let M=t;t=void 0;let I=B(await M());I!==void 0&&(e=I,r=0);}let h=Math.min(s,l*2**(u-1)),b=Math.min(s,(p.retryAfterSeconds??0)*1e3),E=Math.max(h/2,b)+Math.random()*(h/2);if(i.now()+E>m)throw go(n,p,u,i.now()-d,a);if(o.onWaiting?.({attempt:u,elapsedMs:i.now()-d,budgetMs:a,nextAttemptInMs:E,status:p.status,message:p.message}),await yt(i,E,n.signal),n.signal?.aborted)throw Xt("while waiting to allocate")}}}function po(n){return n instanceof j?n.status===503?true:n.status===429&&n.code!=="too_many_concurrent_matches":false}function go(n,e,t,r,i){let o=`${t} attempt${t===1?"":"s"} over ${r}ms of a ${i}ms budget`;return e.status===429?new c("start_rate_limited",`the platform was still limiting match starts for room ${n.roomId} after ${o}: ${e.message}`,{cause:e}):new c("no_server_ready",`the platform had no server ready for room ${n.roomId} after ${o}: ${e.message}`,{cause:e})}var ho=12e4,fo=1e3;async function ht(n){let{clock:e,matchId:t}=n,r=n.pollIntervalMs??fo,i=n.timeoutMs??ho,o=e.now()+i,a=dr(n),s={seen:n.knownToExist===true};for(;;){let l=await cr(n,a,s);if(l.outcome!==null)return l.outcome;if(e.now()+r>o)throw new c("timeout",`match ${t} was still ${l.status} after ${i}ms`);await yt(e,r,n.signal);}}async function Zt(n){return (await cr(n,dr(n),{seen:n.knownToExist===true})).outcome}function dr(n){let e=new URLSearchParams({platform:n.version.platform,game_version:n.version.gameVersion});return `${ur(n)}/matches/${encodeURIComponent(n.matchId)}/status?${e}`}async function cr(n,e,t){let{matchId:r}=n,i=n.clock.now(),o;try{o=await en(n.signal,"while polling match status",()=>n.client.get(e,n.signal));}catch(a){if(a instanceof j&&a.reason==="not_found")return {status:"not_found",outcome:t.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw a}if(t.seen=true,o.status==="ready")return {status:"ready",outcome:yo(r,o,i)};if(o.status==="failed"){let a=o.ended_reason;return typeof a=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:Re(a)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function ft(n){let e=await en(n.signal,"while listing cluster targets",()=>n.client.get("/v1/ping/targets",n.signal)),t=[];for(let r of e.targets??[]){let i=r?.cluster_target_id;typeof i!="string"||i.length===0||t.push({id:i,pressure:typeof r.pressure=="string"?r.pressure:"unknown"});}return t}async function en(n,e,t){if(n?.aborted)throw Xt(e);try{return await t()}catch(r){throw n?.aborted?Xt(e,r):r}}function Xt(n,e){return new c("aborted",`the caller aborted ${n}`,e===void 0?void 0:{cause:e})}function yo(n,e,t){let r=e.join_credential,i=e.expires_in_seconds,o=typeof r=="string"&&typeof i=="number";return {status:"ready",matchId:n,protocol:e.protocol??"unknown",...o?{joinCredential:r,credentialExpiresAt:t+i*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function ur(n){return `/v1/games/${encodeURIComponent(n.gameId)}/game-rooms/${encodeURIComponent(n.roomId)}`}function yt(n,e,t){return t?.aborted?Promise.resolve():new Promise(r=>{let i=()=>{n.clearTimeout(o),t?.removeEventListener("abort",i),r();},o=n.setTimeout(i,e);t?.addEventListener("abort",i);})}var bo=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),nn="embedder_relay_unavailable",_o="embedder_no_relay",vo=new Set([nn]),rn=new Set([_o]),bt=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new tn(this)}handleEvent(e){let t=this.pending.get(e.matchId);if(t!==void 0){if(e.event==="matchEnded"){t.refuse(new c("match_ended",`the match ended while the offer was in flight (${e.reason??"no reason given"}), so no server is left to answer it`));return}if(e.event==="answer"){if(typeof e.sdp!="string"||e.sdp.length===0){t.refuse(new c("signaling_failed","the parent relayed an answer with no SDP in it"));return}t.settle({sdp:e.sdp});return}t.refuse(ko(e.code,e.message));}}register(e,t){this.pending.get(e)?.refuse(new c("signaling_failed","a newer offer for this match superseded the one in flight")),this.pending.set(e,t);}release(e,t){this.pending.get(e)===t&&this.pending.delete(e);}transport(){let e=this.options.bridge;if(e===null)throw new c("signaling_unavailable","this game is not running inside a page that holds the player's notification socket, so there is nothing to carry an offer. Dedicated signaling needs that socket and only the page can hold one \u2014 see docs/dedicated-server-flow.md \xA72.");if(!e.parentSupports("dedicated"))throw new c("signaling_unavailable","the page embedding this game did not advertise the `dedicated` capability, so it will not relay signaling for a dedicated server. See docs/dedicated-server-flow.md \xA72.");return e}};function ko(n,e){let t=e??"the offer was refused",r=n===void 0?t:`${t} (${n})`;return new c(wo(n),r,{platformCode:n})}function wo(n){return n===void 0||vo.has(n)?"signaling_failed":rn.has(n)?"offer_refused":bo.has(n)?n==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var tn=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,t){if(this.closed)return Promise.reject(new c("signaling_unavailable","this signaling channel is closed"));let r;try{r=this.hub.transport();}catch(i){return Promise.reject(i)}return t?.aborted?Promise.reject(new c("aborted","the caller aborted before the offer was sent")):new Promise((i,o)=>{let a=()=>{s(),o(new c("aborted","the caller aborted the signaling exchange"));},s=()=>{t?.removeEventListener("abort",a),this.hub.release(e.matchId,l),this.teardown===s&&(this.teardown=null);},l={settle:d=>{s(),i(d);},refuse:d=>{s(),o(d);}};this.teardown=s,t?.addEventListener("abort",a),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof c?d:new c("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var mr="match_ended:",pr="server_shutdown:",gr="kicked:",Ro=123;function So(n){if(typeof n!="string"||n.length===0||n.length>Ro)return {kind:"other"};if(n.startsWith(mr)){let e=Re(n.slice(mr.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return n.startsWith(pr)?{kind:"server_shutdown",cause:n.slice(pr.length)}:n.startsWith(gr)?{kind:"kicked",detail:n.slice(gr.length)}:{kind:"other"}}function on(n,e,t){let r=So(t),i=r.kind==="kicked"?"kicked":"link_closed";n.notifyMatchDisconnected(i).catch(()=>{}),r.kind==="match_ended"&&n.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}var xo="join",Ao="welcome",Po="rejected",sn=25e3,Eo=1e3,an=1;function ln(n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0}var To={credential_expired:"credential_expired",credential_reused:"credential_reused",credential_timeout:"timeout",join_rate_limited:"join_rate_limited",expected_join:"join_refused",invalid_credential:"join_refused",credential_not_for_this_channel:"join_refused"};function dn(n){let e=typeof n=="string"?n:"unknown";return new c(To[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function Fe(n){let{channel:e,clock:t}=n;return new Promise((r,i)=>{let o=false,a=Math.min(n.credentialExpiresAt-t.now(),n.ceilingMs??sn),s=t.setTimeout(()=>P(new c("timeout","the server runtime sent no welcome before the join credential expired. The channel was open, so this is the runtime not answering rather than a connection that never came up.")),Math.max(a,Eo)),l=E=>{let M=E.data;if(typeof M!="string"){u(M);return}let I;try{I=JSON.parse(M);}catch{u(M);return}if(o){u(M);return}if(I.t===Ao){let g=ln(I.heartbeat_interval);b({...typeof I.player_id=="string"?{playerId:I.player_id}:{},...typeof I.match_id=="string"?{matchId:I.match_id}:{},...g===void 0?{}:{heartbeatIntervalMs:g}});return}if(I.t===Po){P(dn(I.reason));return}u(M);},d=()=>{P(new c("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{P(new c("aborted","the caller aborted during the join exchange"));},u=E=>{o&&n.onMessage?.(E);},p=()=>{t.clearTimeout(s),e.removeEventListener("close",d),n.signal?.removeEventListener("abort",m);},h=()=>{e.removeEventListener("message",l);},b=E=>{o=true,p(),n.onMessage===void 0&&h(),r({welcome:E,detach:h});},P=E=>{o||(o=true,p(),h(),i(E));};if(e.addEventListener("message",l),e.addEventListener("close",d),n.signal?.aborted){m();return}n.signal?.addEventListener("abort",m);try{e.send(JSON.stringify({t:xo,credential:n.credential,...n.wire===void 0?{}:{wire:n.wire},...n.heartbeat===!0?{heartbeat:an}:{}}));}catch(E){P(new c("connection_failed",`the join frame could not be sent on the open channel: ${String(E)}`,{cause:E}));}})}function _t(){return {exchange(){return Promise.reject(new c("signaling_unavailable","no signaling channel is wired. The exchange rides the notification WebSocket, and POST /v1/ws/ticket accepts only account credentials \u2014 a game frame holds a game-scoped token and cannot mint one \u2014 so it has to be relayed by the page embedding this game. Run inside a parent that advertises `dedicated`, or pass your own `signaling` implementation. See docs/dedicated-server-flow.md \xA72."))},close(){}}}var ue=1,je=2,cn=4,pn=8,Io=2,Co=1e3,gn="heartbeat timeout",vt="gem-uu",kt=2,fr="gem_transports";function Ne(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){if(typeof t!="string")continue;let r=t.toLowerCase();!Mo(r)||e.includes(r)||e.push(r);}return e}function Mo(n){return n==="webtransport"||n==="webrtc"||n==="websocket"}function wt(n,e){if(typeof n!="object"||n===null)return null;let t=n[fr];if(typeof t!="object"||t===null)return null;let r=t;return typeof r.v!="number"||r.v<1||typeof r.host!="string"||typeof r.port!="number"||e!==void 0&&r.match_id!==e?null:r}function Rt(n){return n instanceof Error?n.message===""?n.name:`${n.name}: ${n.message}`:String(n)}var yr=new TextEncoder,br=new TextDecoder;function hn(n,e){let t=new Uint8Array(e.byteLength+1);return t[0]=n,t.set(e,1),t}function fn(n){let e=0;return n?.reliable===false&&(e|=ue),n?.ordered===false&&(e|=je),e}function yn(n){return {reliable:(n&ue)===0,ordered:(n&je)===0}}var bn={reliable:true,ordered:true};function _r(n){return JSON.stringify({t:"join",credential:n,wire:kt,heartbeat:an})}function vr(n){let e;try{e=JSON.parse(n);}catch{throw new c("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let t=ln(e.heartbeat_interval);return {...e.player_id===void 0?{}:{playerId:e.player_id},...e.match_id===void 0?{}:{matchId:e.match_id},...t===void 0?{}:{heartbeatIntervalMs:t}}}throw e.t==="rejected"?dn(e.reason):new c("join_refused","the server answered the join out of protocol")}function _n(){return typeof globalThis.WebTransport=="function"&&vn===null}function St(){return vn}var vn=null;var hr="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Oo(n){let e=Yt(n);if(e.byteLength!==32)throw new c("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var un=class{buffered=new Uint8Array(0);push(e){let t=new Uint8Array(this.buffered.byteLength+e.byteLength);t.set(this.buffered,0),t.set(e,this.buffered.byteLength),this.buffered=t;let r=[];for(;!(this.buffered.byteLength<4);){let o=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(o===0||o>1<<20)throw new c("connection_failed",`a control-stream record claims ${o} bytes`);if(this.buffered.byteLength<4+o)break;let a=this.buffered.slice(4,4+o);this.buffered=this.buffered.slice(4+o),r.push({flags:a[0]??0,payload:a.slice(1)});}return r}};function mn(n,e){let t=new Uint8Array(5+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength+1,true),t[4]=n,t.set(e,5),t}async function Ue(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webTransport;if(t===void 0){let s=globalThis.WebTransport;if(s===void 0)throw new c("connection_failed","this environment has no WebTransport");t=n.certHashBase64===void 0?new s(n.url):new s(n.url,{serverCertificateHashes:[{algorithm:"sha-256",value:Oo(n.certHashBase64)}]});}let r=t,i=s=>{try{r.close();}catch{}throw s},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(vn=hr,i(new c("connection_failed",`${hr}; the rung is skipped for the rest of this page (a reload probes again)`)));let a=new Promise((s,l)=>{setTimeout(()=>l(new c("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,a]);let s=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([s.read(),a]);if(s.releaseLock(),l.done||l.value===void 0)return i(new c("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(mn(cn,yr.encode(_r(n.credential))));let u=new un,p=d.readable.getReader(),h;for(;h===void 0;){let b=await Promise.race([p.read(),a]);if(b.done||b.value===void 0)return i(new c("connection_failed","the control stream closed before the join was answered"));for(let P of u.push(b.value)){h=vr(br.decode(P.payload));break}}return {link:Lo(r,m,p,u,n.log??(b=>console.warn(b)),wr(h,n.clock)),welcome:h}}catch(s){return i(s)}}function Lo(n,e,t,r,i,o){let a,s,l=false,d=b=>{if(!l){l=true,m.stop();try{n.close();}catch{}s?.(b);}},m=wn(o,()=>d(gn)),u=(b,P)=>{m.heard(),(b&pn)===0&&a!==void 0&&((b&cn)!==0?a(br.decode(P),bn):a(P,yn(b)));};(async()=>{try{for(;;){let b=await t.read();if(b.done||b.value===void 0)break;for(let P of r.push(b.value))u(P.flags,P.payload);}}catch{}d("stream closed");})();let p,h;try{let b=n.datagrams;if(b?.readable!==void 0&&b.writable!==void 0){let P=b.readable.getReader();h=b.writable.getWriter(),p=b,(async()=>{try{for(;;){let E=await P.read();if(E.done||E.value===void 0)break;let M=E.value;M.byteLength!==0&&u((M[0]??0)|ue|je,M.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(b){p=void 0,h=void 0,i(`[gem] webtransport datagram lane unusable (${Rt(b)}); unreliable sends ride the stream`);}return n.closed.then(b=>d(kr(b?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(b,P){if(l)return;if(typeof b=="string"){e.write(mn(cn,yr.encode(b))).catch(()=>d("write failed"));return}let E=fn(P);if((E&ue)!==0&&h!==void 0){let M=hn(E,b),I=p?.maxDatagramSize;if(I===void 0||M.byteLength<=I){h.write(M).catch(()=>{});return}}e.write(mn(E,b)).catch(()=>d("write failed"));},onMessage(b){a=b;},onClose(b){s=b;},close(){d("closed");}}}function kn(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webSocket;if(t===void 0){let i=globalThis.WebSocket;if(i===void 0)return Promise.reject(new c("connection_failed","this environment has no WebSocket"));t=new i(n.url);}let r=t;return r.binaryType="arraybuffer",new Promise((i,o)=>{let a=false,s=setTimeout(()=>{a||(a=true,r.close(),o(new c("timeout","websocket did not come up in time")));},e),l=h=>{a||(a=true,clearTimeout(s),r.close(),o(h));},d=()=>{r.send(_r(n.credential));},m=h=>{if(a)return;if(typeof h.data!="string"){l(new c("join_refused","the server sent binary before answering the join"));return}let b;try{b=vr(h.data);}catch(P){l(P);return}a=true,clearTimeout(s),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",u),r.removeEventListener("error",p),i({link:Go(r,wr(b,n.clock)),welcome:b});},u=()=>{l(new c("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new c("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",m),r.addEventListener("close",u),r.addEventListener("error",p),r.readyState===1&&d();})}function kr(n){return typeof n=="string"&&n.length>0?n:void 0}function wr(n,e){return n.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:n.heartbeatIntervalMs}}function wn(n,e){if(n===void 0)return {heard:()=>{},stop:()=>{}};let{clock:t}=n,r=Math.max(n.intervalMs,Co)*Io,i=t.now(),o=null,a=()=>{o=null;let s=t.now()-i;if(s>=r){e();return}o=t.setTimeout(a,r-s);};return o=t.setTimeout(a,r),{heard:()=>{i=t.now();},stop:()=>{o!==null&&(t.clearTimeout(o),o=null);}}}function Go(n,e){let t,r,i=false,o=s=>{if(!i){i=true,a.stop();try{n.close();}catch{}r?.(s);}},a=wn(e,()=>o(gn));return n.addEventListener("message",(s=>{if(a.heard(),typeof s.data=="string"){t?.(s.data,bn);return}let l=new Uint8Array(s.data);if(l.byteLength===0)return;let d=l[0]??0;(d&pn)===0&&t?.(l.slice(1),yn(d));})),n.addEventListener("close",(s=>o(kr(s?.reason)??"socket closed"))),{transport:"websocket",send(s,l){if(!i){if(typeof s=="string"){n.send(s);return}n.send(hn(fn(l),s));}},onMessage(s){t=s;},onClose(s){r=s;},close(){o("closed");}}}function Rn(n,e,t,r){let i,o,a=false,s=t,l=u=>{if(!a){a=true,d.stop();try{n.close();}catch{}try{e.close();}catch{}o?.(u);}},d=wn(r,()=>l(gn)),m=(u,p)=>{if(d.heard(),typeof u=="string"){i?.(u,bn);return}let h=new Uint8Array(u);if(h.byteLength===0)return;let b=h[0]??0;(b&pn)===0&&i?.(h.slice(1),yn(b|p));};if(n.addEventListener("message",(u=>m(u.data,0))),n.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let u=e.connectionState;(u==="failed"||u==="closed")&&l(`connection ${u}`);})),s!==void 0){let u=s;u.addEventListener("message",(p=>m(p.data,ue|je))),u.addEventListener("close",(()=>{s=void 0;}));}return {transport:"webrtc",send(u,p){if(a)return;if(typeof u=="string"){n.send(u);return}let h=fn(p),b=hn(h,u);if((h&ue)!==0&&s!==void 0&&s.readyState==="open"){s.send(b);return}n.send(b);},onMessage(u){i=u;},onClose(u){o=u;},close(){l("closed");}}}var Rr=10240,Sr=2048,Do=new TextEncoder;function xr(n){return Do.encode(n).length}function ie(n,e){let t=i=>{throw new c("invalid_sdp",`the ${e} ${i}`)},r=xr(n);r>=Rr&&t(`is ${r} bytes, over the ${Rr} limit`+(e==="offer"?", which for an offer means an unusually wide candidate list":"")),n.startsWith("v=")||t("does not start with 'v=', so it is not SDP"),n.includes("\0")&&t("contains a null byte"),/\r(?!\n)/.test(n)&&t("contains a bare carriage return");for(let i of n.split(/\r\n|\n/)){let o=xr(i);o>Sr&&t(`has a ${o}-byte line, over the ${Sr} limit`);}}function xt(n){for(let e of n.split(/\r\n|\n/)){if(!e.startsWith("m="))continue;let[t,r="0"]=e.slice(2).trim().split(/\s+/);if(!(t!=="audio"&&t!=="video")&&r.split("/")[0]!=="0")return true}return false}var qo=3e3,$o=1e4,Fo=15e3;async function Be(n){let e=n.peerConnection;try{Pr(n,"before the handshake started"),Sn(n);let t=e.createDataChannel(n.channelLabel??"gem",{ordered:!0});for(let a of n.extraChannels??[]){let s=e.createDataChannel(a.label,{...a.ordered===void 0?{}:{ordered:a.ordered},...a.maxRetransmits===void 0?{}:{maxRetransmits:a.maxRetransmits}});n.onExtraChannel?.(a.label,s);}let r=await e.createOffer();await e.setLocalDescription(r),await Uo(e,n),Sn(n);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new c("invalid_sdp","the offer carried no SDP");ie(i,"offer"),Ar(i,"offer");let o=await No(n,i);if(Sn(n),typeof o?.sdp!="string")throw new c("invalid_sdp","the signaling channel answered without an SDP");return ie(o.sdp,"answer"),Ar(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await Bo(t,n),Pr(n,"before the channel opened"),t}catch(t){throw e.close(),jo(t)}}function jo(n){return n instanceof c?n:Ir(n)?me():new c("connection_failed",Cr(n),{cause:n})}function Ar(n,e){if(xt(n))throw new c("media_refused",`the ${e} carries an active audio or video section. This path carries a data channel only; voice belongs to the platform voice service.`)}async function No(n,e){let t=n.exchangeTimeoutMs??$o,r=Tr(n,t),i=n.signaling.exchange({matchId:n.matchId,sdp:e,intent:n.intent??"initial"},n.signal).catch(o=>{throw o instanceof c?o:Ir(o)?me():new c("signaling_failed",Cr(o),{cause:o})});return Wo(i,n,r,()=>r.exhausted?xn("while the offer was in flight"):new c("timeout",`no answer arrived within ${t}ms`))}function Uo(n,e){if(n.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:t}=e;return new Promise(r=>{let i=()=>{t.clearTimeout(a),n.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{n.iceGatheringState==="complete"&&i();},a=t.setTimeout(i,e.gatherTimeoutMs??qo);n.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function Bo(n,e){if(e.signal?.aborted)return Promise.reject(me());if(n.readyState==="open")return Promise.resolve();if(n.readyState!=="connecting")return Promise.reject(new c("connection_failed",`the data channel was already '${n.readyState}' when the answer was applied`));let{clock:t}=e,r=e.openTimeoutMs??Fo,i=Tr(e,r);return new Promise((o,a)=>{let s=()=>{t.clearTimeout(p),n.removeEventListener("open",l),n.removeEventListener("close",d),n.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{s(),o();},d=h=>{s(),a(new c("connection_failed","the data channel failed before it opened",Er(h)===void 0?void 0:{cause:Er(h)}));},m=()=>{s(),a(me());},u=()=>{s(),a(i.exhausted?xn("while the channel was still opening"):new c("timeout",`the data channel did not open within ${r}ms`));},p=t.setTimeout(u,i.ms);n.addEventListener("open",l),n.addEventListener("close",d),n.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function Tr(n,e){if(n.credentialExpiresAt===void 0)return {ms:e,exhausted:false};let t=n.credentialExpiresAt-n.clock.now();return t<=e?{ms:Math.max(0,t),exhausted:true}:{ms:e,exhausted:false}}function Wo(n,e,t,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(me()):new Promise((a,s)=>{let l=u=>{i.clearTimeout(m),o?.removeEventListener("abort",d),u();},d=()=>l(()=>s(me())),m=i.setTimeout(()=>l(()=>s(r())),t.ms);o?.addEventListener("abort",d),n.then(u=>l(()=>a(u)),u=>l(()=>s(u)));})}function Pr(n,e){if(n.credentialExpiresAt!==void 0&&!(n.clock.now()<n.credentialExpiresAt))throw xn(`already ${e}`)}function xn(n){return new c("credential_expired",`the join credential ran out ${n} \u2014 poll match status again for a fresh one`)}function Sn(n){if(n.signal?.aborted)throw me()}function me(){return new c("aborted","the caller aborted the connection attempt")}function Ir(n){return n?.name==="AbortError"}function Er(n){return n?.error}function Cr(n){return n instanceof Error?n.message:String(n)}var We="0.1.0-beta",Mr="0-beta",Se="web",Vo=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/;function Ho(n){let e=Vo.exec(n),t=e?.[1],r=e?.[4];return t===void 0?null:r===void 0?t:`${t}-${r}`}function Or(n,e){let t=Ko(n.platform,e),r=n.engineVersion;if(r===void 0)return {...n,platform:t,engineVersion:We};let i=Ho(r);if(i===null)throw new c("misconfigured",`${e} refused: engineVersion '${r}' is not semver, so no engine line can be derived from it and gem-api answers 400. Omit it \u2014 a browser game has no engine version of its own, and the SDK reports '${We}' for it.`);if(i!==Mr)throw new c("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${Mr}' is the only line a web dedicated-server fleet runs. gem-api uses the line \u2014 the semver major plus any prerelease tag \u2014 verbatim as the fleet's label selector, so a match on '${i}' would match nothing and be reported as a capacity shortfall rather than as this. Omit engineVersion: a browser game has no engine version of its own, and the SDK reports '${We}' for it.`);return {...n,platform:t,engineVersion:r}}function Ko(n,e){if(n===void 0||n===Se)return Se;if(!Qt.includes(n))throw new c("misconfigured",`${e} refused: platform '${String(n)}' is not a client platform gem-api recognises \u2014 it knows ${Qt.map(t=>`'${t}'`).join(", ")}. Remove the field: the SDK reports '${Se}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${n}' was replaced with '${Se}' and is deprecated \u2014 remove the field. A browser game publishes its bundle in the web package dimension, so a client reporting anything else is version-checked against a dimension it has nothing in, and every blacklist, release and expiry check passes without looking at this build.`),Se}function Jo(n){let{client:e,clock:t,rooms:r}=n,i=n.signaling??_t,o=n.log??(g=>console.warn(g)),a=new ce({client:e,gameId:()=>r.gameId,transport:"dedicated"}),s=new Map,l=(g,_)=>{let w=s.get(g)??new Set;w.add(_),s.set(g,w);},d=(g,_)=>{let w=s.get(g);w!==void 0&&(w.delete(_),w.size===0&&s.delete(g));},m=async g=>{if(r.isHost&&!rs(r)&&r.currentRoom?.matchId===void 0){let _=B(g.clusterTargetId);await r.startMatch({..._===void 0?{}:{clusterTargetId:_},...g.retry===void 0?{}:{retry:g.retry},...g.signal===void 0?{}:{signal:g.signal}});}return Fr(r.matchConnectionState==="suspended"?await r.reconnectToMatch(An(g)):await r.awaitMatch(An(g)))},u=async g=>Fr(await r.pollMatchStatus(An(g))),p=async(g,_)=>{let w=false;try{let v=await m(g),G=r.currentRoom?.transports;if(G!==void 0&&!G.includes("webrtc"))throw new c("misconfigured",`the room template offers (${G.join(", ")||"no transports"}), not webrtc, which is all this path dials. Connect through gem.match.connect(), or pass \`transports: []\` here to negotiate across the template's list.`);let C=g.peerConnection??jr();w=!0;let D=await Be({peerConnection:C,signaling:_,clock:t,matchId:v.matchId,credentialExpiresAt:v.credentialExpiresAt,...At(g,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),F=null;if(g.presentCredential!==!1)try{F=await Fe({channel:D,clock:t,credential:v.joinCredential,credentialExpiresAt:v.credentialExpiresAt,...At(g,"onMessage","signal"),...g.welcomeTimeoutMs===void 0?{}:{ceilingMs:g.welcomeTimeoutMs}});}catch(N){throw K(D),K(C),N}return ns(r,v,D,C,_,g.reportDisconnect!==!1,g.reportConnected!==!1,F,{remember:l,forget:d},g.onMatchEnded)}catch(v){throw w&&$r(a,v),K(_),v}},h=async(g,_,w,v,G,C)=>{if(g==="webtransport"){let O=v?.webtransport;if(O===void 0)throw new c("misconfigured","webtransport is not advertised");let Y={credential:w.joinCredential,credentialExpiresAt:w.credentialExpiresAt,clock:t};if(typeof O.named_url=="string"&&O.named_url!==""){let ne=Math.max(Math.floor(C/2),1e3);try{return await Ue({url:O.named_url,timeoutMs:ne,log:o,...Y})}catch(oe){if(St()!==null)throw oe;return o(`[gem] webtransport named dial failed (${Rt(oe)}); retrying the pinned dial`),Ue({url:O.url,certHashBase64:O.cert_sha256_b64,timeoutMs:ne,log:o,...Y})}}return Ue({url:O.url,certHashBase64:O.cert_sha256_b64,timeoutMs:C,...Y})}if(g==="websocket"){let O=v?.websocket;if(O===void 0)throw new c("misconfigured","websocket is not advertised");return kn({url:O.url,credential:w.joinCredential,credentialExpiresAt:w.credentialExpiresAt,clock:t,timeoutMs:C})}let D=_.peerConnection??jr(),F,N=await Be({peerConnection:D,signaling:G,clock:t,matchId:w.matchId,credentialExpiresAt:w.credentialExpiresAt,extraChannels:[{label:vt,ordered:false,maxRetransmits:0}],onExtraChannel:(O,Y)=>{O===vt&&(F=Y);},...At(_,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),..._.exchangeTimeoutMs===void 0&&_.redial===true?{exchangeTimeoutMs:Yo}:{}}),H;try{H=await Fe({channel:N,clock:t,credential:w.joinCredential,credentialExpiresAt:w.credentialExpiresAt,wire:kt,heartbeat:!0,...At(_,"signal"),..._.welcomeTimeoutMs===void 0?{}:{ceilingMs:_.welcomeTimeoutMs}});}catch(O){throw K(N),K(D),O}let x=H.welcome.heartbeatIntervalMs;return {link:Rn(N,D,F,x===void 0?void 0:{clock:t,intervalMs:x}),welcome:H.welcome,channel:N,peerConnection:D}},b=(g,_,w,v,G)=>{let C=false,D;v.link.onClose(x=>{!C&&g.reportDisconnect!==false&&on(r,_.matchId,x),D?.(x);}),g.reportDisconnect!==false&&g.reportConnected!==false&&r.notifyMatchConnected(_.matchId);let F={transport:v.link.transport,send:(x,O)=>v.link.send(x,O),onMessage:x=>v.link.onMessage(x),onClose:x=>{D=x;},close:()=>v.link.close()},N=()=>{C||(C=true,K(v.link),K(G));},H=x=>{if(!C){try{g.onMatchEnded?.(x);}catch{}N();}};return l(_.matchId,H),{matchId:_.matchId,transport:w,link:F,joinCredential:_.joinCredential,credentialExpiresAt:_.credentialExpiresAt,welcome:v.welcome,...v.channel===void 0?{}:{channel:v.channel},...v.peerConnection===void 0?{}:{peerConnection:v.peerConnection},close(){d(_.matchId,H),N();}}},P=async(g,_)=>{let w=r.currentRoom?.id,v=r.gameId,G=()=>({advert:wt(r.currentRoom?.settings,g),template:r.currentRoom?.transports??null});if(w===void 0||v===null)return G();try{let C=await e.get(`/v2/games/${encodeURIComponent(v)}/game-rooms/${encodeURIComponent(w)}`,_);return {advert:wt(C.settings,g),template:Ne(C.transports)??r.currentRoom?.transports??null}}catch{return G()}},E=(g,_)=>{let w=g??Lr;return _.length===0?w:w.filter(v=>_.includes(v))},M=async(g,_,w)=>{try{let v=await m(g),{advert:G,template:C}=await P(v.matchId,g.signal),D=E(C,_),F=D.filter(q=>Zo(q,G)),N=St();if(N!==null&&D.includes("webtransport")&&G?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${N} (learned on an earlier dial in this page)`),F.length===0){let q=C===null?`the default order (${Lr.join(", ")})`:`the room template's transports (${C.join(", ")||"none"})`;throw new c("misconfigured",`none of ${q}`+(_.length>0?`, narrowed to (${_.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let H=g.transportAttemptTimeoutMs??zo,x=()=>g.deadlineAt===void 0?1/0:g.deadlineAt-t.now(),O=q=>n.signalingReady===void 0||q<=0?Promise.resolve(!0):n.signalingReady(q),Y=[],ne=[];for(let q of F){if(x()<Dr){o(`[gem] ${q} rung not tried: the reconnect budget is spent`);break}ne.length>0&&v.credentialExpiresAt-t.now()<qr&&(v=await u(g)),ne.push(q);let Fn=!1,jn=!1,Ze={attempts:0,waitedMs:0};for(;;){if(q==="webrtc"&&g.redial===!0){let Q=Math.min(Gr,x());await O(Q)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(Q)}ms; offering anyway`);}let bi=Math.max(Math.min(H,x()),Dr);try{return b(g,v,q,await h(q,g,v,G,w,bi),w)}catch(Q){let U=Q instanceof c?Q:new c("connection_failed",Q instanceof Error?Q.message:String(Q),{cause:Q});if(q==="webrtc"&&$r(a,U),(U.reason==="credential_expired"||U.reason==="credential_reused")&&!Fn){Fn=!0,v=await u(g);continue}if(q==="webrtc"&&U.reason==="signaling_failed"&&U.platformCode===nn&&!jn){jn=!0;let se=Math.min(Gr,x());if(o(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(se)}ms for the socket before offering again`),await O(se))continue}if(U.reason==="join_rate_limited"){let se=Qo(Ze,Math.random,x());if(se!==null){if(Ze.attempts+=1,Ze.waitedMs+=se,o(`[gem] ${q} rung: the server is rate-limiting this player's joins; waiting ${Math.round(se)}ms before presenting again (retry ${Ze.attempts} of ${Ur.maxAttempts})`),await yt(t,se,g.signal),g.signal?.aborted)throw new c("aborted","the caller aborted while waiting out a join rate limit");v.credentialExpiresAt-t.now()<qr&&(v=await u(g));continue}}if(Xo.has(U.reason)||U.reason==="credential_expired"||q==="webrtc"&&Nr(U)){o(`[gem] ${q} rung failed (${U.reason}): ${Rt(U.cause??U)} \u2014 `+(ne.length<F.length?`falling through to ${F[ne.length]}`:"no rungs left")),Y.push(U);break}throw o(`[gem] ${q} rung refused the session (${U.reason}): ${U.message}`),U}}}let oe=Y[Y.length-1];throw oe===void 0?new c("timeout",`the reconnect budget ran out before any transport (${F.join(", ")}) could be tried`):new c(oe.reason,`every transport tried (${ne.join(", ")}) failed; the last said: ${oe.message}`,{cause:Y,platformCode:oe.platformCode})}catch(v){throw K(w),v}};return {listClusterTargets:async(g={})=>ft({client:e,...g}),handleMatchEnded(g,_){let w=s.get(g);if(w!==void 0){s.delete(g);for(let v of w)v(_);}},connect:(async(g={})=>{let _=g.signaling??i();return g.transports===void 0?p(g,_):M(g,g.transports,_)})}}var Lr=["webtransport","webrtc","websocket"],zo=1e4,Yo=5e3,Gr=3e3,Dr=1e3,qr=1e4,Xo=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function Nr(n){return n.platformCode!==void 0&&rn.has(n.platformCode)}var Ur={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function Qo(n,e=Math.random,t=1/0){let r=Ur;if(n.attempts>=r.maxAttempts)return null;let i=Math.min(r.budgetMs-n.waitedMs,t);if(i<r.initialDelayMs)return null;let o=r.initialDelayMs*r.factor**n.attempts;return Math.min(o+e()*r.jitterMs,i)}function Zo(n,e){return n==="webrtc"?e===null||e.webrtc!==false:e===null?false:n==="webtransport"?e.webtransport!==void 0&&_n():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||es(e.websocket.url)}function es(n){if(typeof n!="string")return false;let e;try{e=new URL(n).hostname.toLowerCase();}catch{return false}return ut(e)}function An(n){return {...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.pollIntervalMs===void 0?{}:{pollIntervalMs:n.pollIntervalMs},...n.signal===void 0?{}:{signal:n.signal}}}var ts=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function $r(n,e){e instanceof c&&(!ts.has(e.reason)&&!Nr(e)||n.report([{type:"connection_failures_total",value:1}]));}function ns(n,e,t,r,i,o,a,s,l,d){let m=false,u=()=>{m||on(n,e.matchId,void 0);};o&&(t.addEventListener("close",u),a&&n.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,t.removeEventListener("close",u),s?.detach(),K(t),K(r),K(i));},h=b=>{if(!m){try{d?.(b);}catch{}p();}};return l.remember(e.matchId,h),{matchId:e.matchId,channel:t,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:s?.welcome??null,close(){l.forget(e.matchId,h),p();}}}function rs(n){let e=n.matchSession.phase;return e!=="none"&&e!=="ended"}function Fr(n){if(n.status==="failed")throw new c("allocation_failed",`match ${n.matchId} did not come up: ${n.reason}`);if(n.status==="ended")throw new c("match_ended",`match ${n.matchId} ended (${n.reason}) before this side connected.`);if(n.protocol!==$e)throw new c("unsupported_protocol",`match ${n.matchId} speaks '${n.protocol}', which a browser cannot connect. Only '${$e}' is reachable from a frame; host and port on this response are advisory and must not be dialled.`);let{joinCredential:e,credentialExpiresAt:t}=n;if(e===void 0||t===void 0)throw new c("connection_failed",`match ${n.matchId} is ready but issued no join credential, so the server would refuse the channel once it opened \u2014 poll match status again.`);return {...n,joinCredential:e,credentialExpiresAt:t}}function jr(){let n=globalThis.RTCPeerConnection;if(!n)throw new c("misconfigured","this environment has no RTCPeerConnection. Pass `peerConnection` to connect against a stand-in, which is how the flow is tested outside a browser.");return new n({iceServers:[]})}function K(n){try{n.close();}catch{}}function At(n,...e){let t={};for(let r of e)n[r]!==void 0&&(t[r]=n[r]);return t}var xe=class{constructor(e){this.options=e;this.reporter=new ce({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,t,r){let i=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:t},r);return {credential:Pt(i.credential)??"",hostFingerprint:Pt(i.host_fingerprint)??"",hostEpoch:Et(i.host_epoch)??0,expiresAt:(Et(i.expires_at)??0)*1e3}}async turnLease(e,t,r){let i=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:t},r),o=[];for(let l of Array.isArray(i.ice_servers)?i.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(u=>typeof u=="string"&&u.length>0);m.length!==0&&o.push({urls:m,username:Pt(d.username)??"",credential:Pt(d.credential)??""});}let a=Et(i.expires_at),s=Et(i.ttl_seconds);return {iceServers:o,expiresAt:a!==void 0?a*1e3:Date.now()+(s??0)*1e3}}async kick(e,t,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:t},r);}async leave(e,t=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:t});}async telemetry(e,t){await this.reporter.post(e,t);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}};function Pt(n){return typeof n=="string"&&n.length>0?n:void 0}function Et(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}var is=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),k=class extends Error{constructor(t,r,i){super(`${t}: ${r}`,i);this.reason=t;this.name="P2pError",this.retryable=is.has(t);}reason;retryable};var Tt=class{listeners=new Map;on(e,t){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>this.off(e,t)}off(e,t){this.listeners.get(e)?.delete(t);}once(e,t){let r=this.on(e,((...i)=>{r(),t(...i);}));return r}emit(e,...t){let r=this.listeners.get(e);if(r)for(let i of [...r])i(...t);}clear(){this.listeners.clear();}};var os=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function pe(n){let e=null;for(let t of n.split(/\r\n|\n/)){if(!t.startsWith("a=fingerprint:"))continue;let r=Ve(t.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function Ve(n){let[e,...t]=n.trim().split(/\s+/);if(e===void 0||t.length===0)return null;let r=`${e.toLowerCase()} ${t.join("").toUpperCase()}`;return os.test(r)?r:null}function Ae(n,e){if(n.length!==e.length)return false;let t=0;for(let r=0;r<n.length;r++)t|=n.charCodeAt(r)^e.charCodeAt(r);return t===0}var Pn=5e3,ss=12e4+Pn,as=1024,ls=6e4,ds=1e4,Br=64*1024,Wr=5;function It(n){let e=new Map,t=-1/0,r=null,i=(()=>{let s;try{s=new URL(`${n.baseUrl.replace(/\/+$/,"")}/oauth2/jwks`);}catch{return {ok:false,reason:"the configured API base is not a valid URL, so the JWKS endpoint cannot be reached. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}}return s.username!==""||s.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:s.href,shown:`${s.protocol}//${s.host}`}})(),o=()=>{let s=n.subtle??globalThis.crypto?.subtle;if(!s)throw new k("keys_unavailable","this environment has no WebCrypto, so a join credential cannot be verified. A page served over plain http on a non-loopback origin is the usual cause \u2014 crypto.subtle is only exposed in a secure context.");return s},a=async()=>{if(!i.ok)throw new k("keys_unavailable",i.reason);let s=n.fetch??((p,h)=>globalThis.fetch(p,h)),l;try{l=await s(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(ds)});}catch{throw new k("keys_unavailable",`the JWKS endpoint at ${i.shown} could not be reached \u2014 it timed out, refused a redirect, or the network failed.`)}if(!l.ok)throw new k("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let d;try{let p=await l.text();if(p.length>Br)throw new k("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${Br} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof k?p:new k("keys_unavailable",`the JWKS endpoint at ${i.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>Wr)throw new k("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${Wr} the platform declares. Refusing rather than verifying against a set of unknown size.`);let u=o();for(let p of m){let h=p;if(h.kty==="RSA"&&!(h.alg!==void 0&&h.alg!=="RS256")&&!(h.use!==void 0&&h.use!=="sig")&&!(typeof h.kid!="string"||h.kid.length===0))try{let b=await u.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(h.kid,b);}catch{}}};return {async key(s){let l=e.get(s);if(l)return l;if(!i.ok)throw new k("keys_unavailable",i.reason);if(r)return await r,e.get(s)??null;let d=n.now();if(!Number.isFinite(d))throw new k("keys_unavailable","the clock supplied to the SDK returned a non-finite time, so the JWKS throttle cannot be evaluated. This is a configuration fault, not a server failure.");return d<t&&(t=-1/0),d-t<ls?null:(t=d,r??=a().finally(()=>{r=null;}),await r,e.get(s)??null)}}}var He=class{seen=new Map;admit(e,t){for(let[r,i]of this.seen)i<=t&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=as){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,t+ss),true}};function Hr(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(t.length);for(let i=0;i<t.length;i++)r[i]=t.charCodeAt(i);return r}function Vr(n){try{let e=new TextDecoder().decode(Hr(n)),t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch{return null}}async function Ct(n,e,t,r,i){let o=x=>{throw new k("peer_unauthenticated",`the peer's join credential is not usable: ${x}`)},a=n.split(".");a.length!==3&&o("it is not a three-part JWT");let[s,l,d]=a,m=Vr(s);m===null&&o("its header does not decode"),m.alg!=="RS256"&&o(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let u=m.kid;(typeof u!="string"||u.length===0)&&o("it names no key");let p=await t.key(u);p===null&&o("it was signed by a key this build cannot resolve");let h=i.subtle??globalThis.crypto?.subtle;h||o("this environment has no WebCrypto");let b=new TextEncoder().encode(`${s}.${l}`),P;try{P=Hr(d);}catch{o("its signature does not decode");}await h.verify({name:"RSASSA-PKCS1-v1_5"},p,P,b)||o("its signature does not verify");let M=Vr(l);M===null&&o("its payload does not decode");let I=M,g=x=>typeof I[x]=="string"?I[x]:"",_=x=>typeof I[x]=="number"&&Number.isFinite(I[x])?I[x]:NaN;g("iss")!==i.issuer&&o("it was issued by someone else"),g("aud")!==`${i.issuer}/p2p-match`&&o("its audience is not this platform"),g("match_id")!==e.matchId&&o("it is for another match"),g("game_id")!==e.gameId&&o("it is for another game");let w=_("exp")*1e3,v=_("nbf")*1e3;(!Number.isFinite(w)||e.now>w+Pn)&&o("it has expired"),Number.isFinite(v)&&e.now<v-Pn&&o("it is not valid yet");let G=g("role");G!=="host"&&G!=="client"&&o("it names no usable role");let C=_("host_epoch");C!==e.hostEpoch&&o("it names a different host epoch");let D=Ve(g("fingerprint"));D===null&&o("its fingerprint claim is malformed"),Ae(D,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let F=Ve(g("host_fingerprint"));F===null&&o("its host fingerprint claim is malformed"),Ae(F,e.hostFingerprint)||o("it was issued against a different host certificate");let N=g("jti");N.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit(N,e.now)||o("it has already been used");let H=g("sub");return H.length===0&&o("it names no player"),{playerId:H.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:C,role:G,fingerprint:D,hostFingerprint:F,jti:N,expiresAt:w}}var ge=32769;function En(n){let e=new TextEncoder().encode(n.jwt);if(e.length>8192)throw new Error(`[gem] a join credential of ${e.length} bytes exceeds the wire format's cap`);let t=new ArrayBuffer(3+e.length+4+4),r=new DataView(t);return r.setUint8(0,1),r.setUint16(1,e.length,true),new Uint8Array(t,3,e.length).set(e),r.setUint32(3+e.length,n.protocolVersion,true),r.setUint32(7+e.length,n.assignedPeerId,true),t}function Tn(n){let e=new ArrayBuffer(9),t=new DataView(e);return t.setUint8(0,2),t.setUint32(1,n.protocolVersion,true),t.setUint32(5,n.assignedPeerId,true),e}function In(n){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,3),t.setUint8(1,n),e}function Cn(n){if(n.byteLength<1)return null;let e=new DataView(n);switch(e.getUint8(0)){case 1:{if(n.byteLength<3)return null;let t=e.getUint16(1,true);return t>8192||n.byteLength<3+t+8?null:{kind:"join",jwt:new TextDecoder().decode(new Uint8Array(n,3,t)),protocolVersion:e.getUint32(3+t,true),assignedPeerId:e.getUint32(7+t,true)}}case 2:return n.byteLength<9?null:{kind:"admit",protocolVersion:e.getUint32(1,true),assignedPeerId:e.getUint32(5,true)};case 3:return n.byteLength<2?null:{kind:"reject",reason:e.getUint8(1)};default:return null}}function Kr(n){switch(n){case 1:return "the host did not accept this credential";case 2:return "the host speaks a different protocol version \u2014 an engine peer refuses a browser peer here, deliberately";case 3:return "the match is full";case 4:return "the host is rate-limiting joins";case 129:return "the host verified this credential but it names a different player than the one who signalled \u2014 the host has its own line saying which";case 130:return "the host has this player on the kicked list for the current host epoch";case 131:return "the host could not fetch the platform's signing keys, so it cannot verify anyone yet \u2014 the host's console says why";default:return `the host refused with an unrecognised code (${n})`}}function Jr(n){switch(n){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var zr=3e4,Pe=class{constructor(e,t,r){this.localPlayerId=e;this.hostPlayerId=t,this.epoch=r;}localPlayerId;state="idle";epoch;hostPlayerId;kicked=new Set;startedAt=0;get currentState(){return this.state}get currentEpoch(){return this.epoch}get currentHostPlayerId(){return this.hostPlayerId}get isLocalHost(){return this.hostPlayerId===this.localPlayerId}isKicked(e){return this.kicked.has(e)}stalled(e){return this.state!=="idle"&&e-this.startedAt>3e4}apply(e,t){return !Number.isInteger(e.hostEpoch)||e.hostEpoch<0?{kind:"refused",why:`host epoch ${String(e.hostEpoch)} is not a whole number`}:e.hostEpoch===this.epoch?e.migrationComplete===true&&this.state!=="idle"?(this.state="idle",{kind:"completed"}):{kind:"duplicate"}:e.hostEpoch<this.epoch?{kind:"refused",why:`host epoch ${e.hostEpoch} is behind the current ${this.epoch}`}:e.hostPlayerId.length===0?{kind:"refused",why:"the migration named no new host"}:(this.kicked=new Set(e.kickedPlayerIds??[]),this.epoch=e.hostEpoch,this.hostPlayerId=e.hostPlayerId,this.startedAt=t,this.state=this.isLocalHost?"preparing":"reconnecting",{kind:"accepted",state:this.state})}complete(){this.state="idle";}};var Mt={reliable:{negotiated:true,id:0,ordered:true},ordered:{negotiated:true,id:1,ordered:true,maxRetransmits:0},unreliable:{negotiated:true,id:2,ordered:false,maxRetransmits:0}},Ke=["reliable","ordered","unreliable"];function Ot(n){let e=globalThis.RTCPeerConnection;if(!e)throw new Error("[gem] this environment has no RTCPeerConnection. Pass `peerConnectionFactory` to connect against a stand-in, which is how this flow is tested outside a browser.");return new e({iceServers:n.iceServers,...n.certificates===void 0?{}:{certificates:n.certificates}})}async function Lt(){let n=globalThis.RTCPeerConnection;return n?.generateCertificate?n.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var Xr=1,gs=3e4,Qr=2e3,hs=5e3,Zr=6e4,fs=8,On=class{constructor(e=fs){this.perMinute=e;}perMinute;sent=[];delayUntilAllowed(e){return this.prune(e),this.sent.length<this.perMinute?0:Math.max(0,(this.sent[0]??e)+6e4-e)}record(e){this.prune(e),this.sent.push(e);}prune(e){let t=0;for(let r of this.sent)r<=e&&e-r<6e4&&(this.sent[t++]=r);this.sent.length=t;}},ys=new On,bs=8,_s=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),Ee=class{constructor(e){this.options=e;this.keys=e.keys??It({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new Tt;links=new Map;replays=new He;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=Xr+1;ended=null;closed=false;ready=null;helloSeen=false;reportedUnreachableEpoch=-1;reportedStallEpoch=-1;counted=false;pendingOffers=new Map;answeredSessions=new Map;credentialGeneration=0;credentialDeadline=0;get matchId(){return this.options.matchId}get playerId(){return this.localPlayerId}get isHost(){return this.migration?.isLocalHost??false}get hostPlayerId(){return this.migration?.currentHostPlayerId??""}get hostEpoch(){return this.migration?.currentEpoch??0}get peers(){let e=[];for(let t of this.links.values())t.admitted&&e.push(this.expose(t));return e}peer(e){let t=this.links.get(e);return t&&t.admitted?this.expose(t):null}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t);}once(e,t){return this.emitter.once(e,t)}async start(e){let t=this.options.connectTimeoutMs??gs;this.credentialDeadline=this.options.clock.now()+t;let r=new Promise((s,l)=>{this.ready={resolve:s,reject:l};}),i=B(this.options.clusterTargetId);if(i!==void 0)try{let s=await this.options.api.turnLease(this.options.matchId,i,e);this.iceServers=s.iceServers,this.mark("turn leased");}catch(s){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${Mn(s)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let o=this.options.clock.setTimeout(()=>{this.fail(new k("timeout",`no usable P2P connection after ${t}ms. The parent relays signaling, so a silent failure here usually means the page is not putting frames on the socket.`));},t),a=()=>this.fail(new k("aborted","the caller aborted while connecting"));e?.aborted?a():e?.addEventListener("abort",a);try{await r;}finally{this.options.clock.clearTimeout(o),e?.removeEventListener("abort",a),this.ready=null;}}async kick(e){if(!this.isHost)throw new k("misconfigured","only the current host of this match can kick a peer");await this.options.api.kick(this.options.matchId,e);}async leave(){try{await this.options.api.leave(this.options.matchId);}catch{}this.close();}close(){if(!this.closed){this.closed=true,this.pendingOffers.clear();for(let e of [...this.links.values()])this.dropLink(e,"closed",false);this.options.signaling.close(),this.emitter.clear();}}report(e){this.options.api.telemetry(e).catch(()=>{});}notifyCandidatesDropped(e){this.emitter.emit("candidatesDropped",e);}handleSignal(e,t){this.closed||this.route(e,t).catch(r=>this.report_(r));}async route(e,t){switch(e){case "hello":return this.onHello(t);case "offer":return this.onOffer(t);case "answer":return this.onAnswer(t);case "ice":return this.onIce(t);case "peerLeft":return this.onPeerLeft(t);case "migration":return this.onMigration(t);case "matchEnded":return this.onMatchEnded(t);case "error":return this.onSignalingError(t);default:return}}async onHello(e){let t=$(e.playerId),r=$(e.hostPlayerId),i=Gt(e.hostEpoch);if(!(t===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=t,this.migration===null&&(this.migration=new Pe(t,r,i)),!this.helloSeen)){if(this.helloSeen=true,this.isHost){this.mark("host listening"),this.settle(),await this.drainPendingOffers();return}this.pendingOffers.clear(),await this.offerToHost("initial");}}async drainPendingOffers(){if(this.pendingOffers.size===0)return;let e=[...this.pendingOffers.values()];this.pendingOffers.clear(),this.mark("queued offer drained");for(let t of e)try{await this.onOffer(t);}catch(r){this.report_(r);}}async offerToHost(e){let t=this.hostPlayerId,r=this.openLink(t,Xr),i=await r.connection.createOffer();await r.connection.setLocalDescription(i);let o=r.connection.localDescription?.sdp??i.sdp;if(!o)throw new k("invalid_sdp","the browser produced an offer with no SDP");ie(o,"offer"),this.refuseMedia(o,"offer"),this.options.signaling.offer(o,e),this.mark("offer sent"),this.fetchCredential().catch(a=>this.report_(a));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,i=r===void 0?null:pe(r);if(i===null)throw new k("invalid_sdp","this browser produced an offer with no usable DTLS fingerprint, so the platform cannot bind a credential to it");let o=this.options.credentialPacing??ys,a=()=>this.closed||e!==this.credentialGeneration,s=hs;for(;;){let l=o.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,a))return;o.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,i);if(a())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(a())return;let m=d.status,u;if(m===409)u=Qr;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?u=p*1e3:(u=s,s=Math.min(s*2,Zr)),u=Math.min(Math.max(u,Qr),Zr);}else throw d;if(!await this.waitForCredential(u,a))return}}}async waitForCredential(e,t){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!t())}async onOffer(e){let t=$(e.fromPlayerId),r=$(e.sdp);if(t===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(t),this.pendingOffers.size>=bs){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(t,e);return}if(!this.isHost||this.migration.isKicked(t)===true)return;let i=$(e.sessionId);if(i!==null&&this.answeredSessions.get(t)===i)return;ie(r,"offer"),this.refuseMedia(r,"offer");let o=pe(r);if(o===null)throw new k("invalid_sdp",`the offer from ${t} carries no usable fingerprint`);this.mark("offer received"),i!==null&&this.answeredSessions.set(t,i);let a=this.links.get(t);a&&this.dropLink(a,"resignalled",false);let s=this.openLink(t,this.nextPeerId++);s.remoteFingerprint=o,await s.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(s);let l=await s.connection.createAnswer();await s.connection.setLocalDescription(l);let d=s.connection.localDescription?.sdp??l.sdp;if(!d)throw new k("invalid_sdp","the browser produced an answer with no SDP");ie(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(t,d,s.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let t=$(e.fromPlayerId),r=$(e.sdp);if(t===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||t!==this.hostPlayerId)return;ie(r,"answer"),this.refuseMedia(r,"answer");let o=pe(r);if(o===null)throw new k("invalid_sdp","the host's answer carries no usable fingerprint");this.mark("answer received"),i.remoteFingerprint=o,i.pendingAnswer=r,this.hostVerified(i)&&await this.applyAnswer(i,r);}hostVerified(e){let t=this.credential;return t===null||e.remoteFingerprint===null?false:Ae(t.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new k("peer_unauthenticated","the host's DTLS certificate is not the one the platform attested for this match. Refusing before the handshake, so no credential is presented.")),this.dropLink(e,"host_fingerprint_mismatch",false),false)}maybeAuthenticate(){if(this.isHost)return;let e=this.links.get(this.hostPlayerId);if(!e||e.remoteFingerprint===null||e.connection.remoteDescription!==null)return;let t=e.pendingAnswer;t!==void 0&&this.hostVerified(e)&&this.applyAnswer(e,t).catch(r=>this.report_(r));}async applyAnswer(e,t){this.mark("host verified"),e.pendingAnswer=void 0,await e.connection.setRemoteDescription({type:"answer",sdp:t}),this.flushCandidates(e);}async onIce(e){let t=$(e.fromPlayerId),r=$(e.candidate);if(t===null||r===null)return;let i=this.links.get(t);if(!i)return;let o=$(e.sdpMid),a=Gt(e.sdpMLineIndex)??Gt(e.sdpMLineIndexAlt),s={candidate:r,...o===null?{}:{sdpMid:o},...a===null?{}:{sdpMLineIndex:a}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(s);return}await i.connection.addIceCandidate(s);}onPeerLeft(e){let t=$(e.playerId);if(t===null)return;let r=$(e.reason)??"left";if(t===this.localPlayerId){this.fail(new k("kicked",`this player was removed from the match (${r})`)),this.close();return}let i=this.links.get(t);i&&this.dropLink(i,r,true);}async onMigration(e){let t=$(e.hostPlayerId),r=Gt(e.hostEpoch);if(t===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:t,hostEpoch:r,...$(e.reason)===null?{}:{reason:$(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(o=>typeof o=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(i.kind!=="duplicate"){if(i.kind==="completed"){this.emitter.emit("hostChanged",t,r);return}if(i.kind==="refused"){this.report_(new k("migration_failed",i.why));return}for(let o of [...this.links.values()])this.dropLink(o,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",t,r),i.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration(),await this.offerToHost("full_reconnect");}}watchMigration(){let e=this.hostEpoch;this.options.clock.setTimeout(()=>{this.closed||this.migration===null||this.migration.currentEpoch===e&&this.migration.stalled(this.options.clock.now())&&this.reportedStallEpoch!==e&&(this.reportedStallEpoch=e,this.report_(new k("migration_failed",`host migration to epoch ${e} did not complete. The elected host never acknowledged it, so the platform is still holding the match in migration.`)));},31e3);}onMatchEnded(e){let t=$(e.reason)??"ended";this.ended=t,this.emitter.emit("matchEnded",t),this.ready!==null&&this.fail(new k("match_ended",`the match ended: ${t}`)),this.close();}onSignalingError(e){let t=$(e.code)??"unknown",r=$(e.message)??"the platform refused a signaling message";this.report_(new k("signaling_failed",`${t}: ${r}`));}openLink(e,t){let i=(this.options.peerConnectionFactory??Ot)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let p of Ke){let h=i.createDataChannel(p,Mt[p]);h.binaryType="arraybuffer",o[p]=h;}let a={playerId:e,assignedPeerId:t,connection:i,channels:o,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},s=p=>{let h=p.candidate;h?.candidate&&this.options.signaling.candidate(e,h.candidate,h.sdpMid??void 0,h.sdpMLineIndex??void 0);},l=()=>this.onIceState(a),d=()=>this.onConnectionState(a),m=p=>{this.onHandshakeMessage(a,p.data).catch(h=>this.report_(h));},u=()=>{this.onReliableOpen(a).catch(p=>this.report_(p));};return i.addEventListener("icecandidate",s),i.addEventListener("iceconnectionstatechange",l),i.addEventListener("connectionstatechange",d),o.reliable.addEventListener("open",u),o.reliable.addEventListener("message",m),a.detachHandshake=()=>{o.reliable.removeEventListener("open",u),o.reliable.removeEventListener("message",m);},a.detachAll=()=>{a.detachHandshake(),i.removeEventListener("icecandidate",s),i.removeEventListener("iceconnectionstatechange",l),i.removeEventListener("connectionstatechange",d);},this.links.set(e,a),a}flushCandidates(e){let t=e.pendingCandidates;e.pendingCandidates=[];for(let r of t)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let t=this.credential;if(t===null)throw new k("peer_unauthenticated","the channel opened before the platform issued a join credential, so there is nothing to present");if(this.options.clock.now()>=t.expiresAt)throw new k("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(En({jwt:t.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,t){if(!(t instanceof ArrayBuffer))return;let r=Cn(t);if(r!==null){if(this.isHost&&r.kind==="join"){await this.admit(e,r.jwt,r.protocolVersion);return}if(!this.isHost&&r.kind==="admit"){e.assignedPeerId=r.assignedPeerId,this.finishAdmission(e),this.migration?.complete();return}!this.isHost&&r.kind==="reject"&&(this.fail(new k(Jr(r.reason),Kr(r.reason))),this.dropLink(e,"rejected",false));}}async admit(e,t,r){if(r!==32769){this.refuseLink(e,2,"version_mismatch",`it presented protocol version ${r}, not this SDK's ${32769} \u2014 an engine peer cannot join a browser-hosted match`);return}let i=pe(e.connection.localDescription?.sdp??"");if(i===null||e.remoteFingerprint===null){this.refuseLink(e,1,"fingerprint_unavailable","this connection's DTLS fingerprints could not be read from its SDP, so no credential can be checked against it");return}let o;try{o=await Ct(t,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:i,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(a){let s=a instanceof k&&a.reason==="keys_unavailable";this.refuseLink(e,s?131:1,s?"keys_unavailable":"credential_invalid",Mn(a)),s&&this.fail(a);return}if(o.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${o.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(o.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(Tn({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,t,r,i){this.warn(`refused to admit ${e.playerId}: ${i}`);try{e.channels.reliable.send(In(t));}catch{}this.dropLink(e,r,false);}finishAdmission(e){this.mark(this.isHost?"peer admitted":"admitted"),e.admitted=true,e.detachHandshake(),e.detachHandshake=()=>{},this.emitter.emit("peerJoined",this.expose(e)),this.settle();}onIceState(e){let t=e.connection.iceConnectionState;if(!(t!=="failed"&&t!=="disconnected"&&t!=="closed")){if(this.isHost){(t==="failed"||t==="closed")&&this.dropLink(e,t,true);return}if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,t);}catch(r){this.report_(r);}}}}onConnectionState(e){let t=e.connection.connectionState;t!=="failed"&&t!=="closed"||this.dropLink(e,t,true);}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(t,r="reliable")=>e.channels[r].send(t)}}dropLink(e,t,r){this.links.delete(e.playerId),e.detachAll();for(let i of Ke)ei(e.channels[i]);ei(e.connection),r&&e.admitted&&this.emitter.emit("peerLeft",e.playerId,t);}settle(){this.ready?.resolve(),this.ready=null;}fail(e){if(this.count(e.reason),this.ready!==null){let t=this.ready;this.ready=null,t.reject(e);return}this.emitter.emit("error",e);}report_(e){this.fail(e instanceof k?e:new k("connection_failed",Mn(e),{cause:e}));}count(e){this.counted||!_s.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,t){if(xt(e))throw new k("media_refused",`the ${t} carries an active audio or video section. This path carries data channels only; voice belongs to the platform voice service, and gem-api age-gates relayed SDP that proposes media.`)}mark(e){this.options.boot?.mark(e);}sleep(e){return new Promise(t=>this.options.clock.setTimeout(t,e))}warn(e){let t=this.options.log;t!==null&&(t??(r=>console.warn(r)))(`[gem] ${e}`);}get endedReason(){return this.ended}};function $(n){return typeof n=="string"&&n.length>0?n:null}function Gt(n){return typeof n=="number"&&Number.isInteger(n)?n:null}function Mn(n){return n instanceof Error?n.message:String(n)}function ei(n){try{n.close();}catch{}}var vs=100,ks=50,Te=class{constructor(e){this.options=e;}options;queue=[];drainHandle=null;dropped=0;closed=false;dropListener=null;onDropped(e){this.dropListener=e;}join(){this.assertUsable(),this.options.bridge.signal("join",this.options.matchId,{});}offer(e,t){this.assertUsable(),this.options.bridge.signal("offer",this.options.matchId,{sdp:e,intent:t});}answer(e,t,r){this.assertUsable(),this.options.bridge.signal("answer",this.options.matchId,{peerId:e,sdp:t,assignedPeerId:r});}candidate(e,t,r,i){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??vs)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:t,...r===void 0?{}:{sdpMid:r},...i===void 0?{}:{sdpMLineIndex:i}}),this.schedule();}migrationAck(e){this.assertUsable(),this.options.bridge.signal("migrationAck",this.options.matchId,{hostEpoch:e});}reportHostUnreachable(e,t){this.assertUsable(),this.options.bridge.signal("hostUnreachable",this.options.matchId,{hostEpoch:e,evidence:{iceState:t,lastSeenAt:Math.floor(this.options.clock.now()/1e3)}});}discardQueued(){this.queue.length=0;}close(){this.closed=true,this.discardQueued(),this.drainHandle!==null&&(this.options.clock.clearTimeout(this.drainHandle),this.drainHandle=null);}assertUsable(){if(this.closed)throw new k("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new k("signaling_unavailable","the page embedding this game did not advertise the `p2p` capability, so there is nothing to carry signaling. P2P needs the notification WebSocket, and only the parent can hold one \u2014 see docs/p2p-and-parties.md \xA72.")}schedule(){this.drainHandle!==null||this.closed||(this.drainHandle=this.options.clock.setTimeout(()=>{this.drainHandle=null;let e=this.queue.shift();if(e!==void 0){let{peerId:t,candidate:r,sdpMid:i,sdpMLineIndex:o}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:t,candidate:r,...i===void 0?{}:{sdpMid:i},...o===void 0?{}:{sdpMLineIndex:o}});}if(this.dropped>0&&this.queue.length===0){let t=this.dropped;this.dropped=0,this.options.onCandidatesDropped?.(t),this.dropListener?.(t);}this.queue.length>0&&this.schedule();},this.options.candidateIntervalMs??ks));}};var Ln="webrtc_p2p";function ws(n){let e=new xe({client:n.client,gameId:n.gameId}),t=new Map;return {handleSignalEvent(r,i,o){t.get(r)?.handleSignal(i,o);},session(r){return t.get(r)??null},async connect(r={}){if(n.bridge===null)throw new k("signaling_unavailable","P2P signaling rides the notification WebSocket, which only the page embedding this game can hold. There is no bridge here \u2014 this is `mock` mode, or a game running outside the Arcade frame. See docs/p2p-and-parties.md \xA72.");let i=B(r.clusterTargetId),o=i??B(await n.resolveClusterTarget?.());n.rooms.isHost&&n.rooms.currentMatch===null&&n.rooms.currentRoom?.matchId===void 0&&await n.rooms.startMatch({...i===void 0?{}:{clusterTargetId:i},...r.signal===void 0?{}:{signal:r.signal}});let a=await n.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(a.protocol!==Ln)throw new k("unsupported_protocol",`match ${a.matchId} speaks '${a.protocol}', not '${Ln}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let s=new Te({bridge:n.bridge,matchId:a.matchId,clock:n.clock}),l=new Ee({api:e,clock:n.clock,matchId:a.matchId,gameId:n.gameId(),baseUrl:typeof n.baseUrl=="function"?n.baseUrl():n.baseUrl,signaling:s,...o===void 0?{}:{clusterTargetId:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await Lt(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...n.boot===void 0?{}:{boot:n.boot},...n.log===void 0?{}:{log:n.log}});s.onDropped(d=>l.notifyCandidatesDropped(d)),t.set(a.matchId,l),l.on("matchEnded",()=>t.delete(a.matchId));try{await l.start(r.signal);}catch(d){throw t.delete(a.matchId),l.close(),d}return l}}}function ti(n){return typeof n=="string"&&n.trim()!==""}function ni(n,e){return ti(n)?n.trim():ti(e)?e:null}function Je(n){let e=String(n);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function ri(n,e,t){let r=`/v1/games/${Je(n.gameId())}/matchmaking/tickets/${Je(e)}`;return n.client.delete(r,t?.signal)}async function ii(n,e,t){let r=`/v1/games/${Je(n.gameId())}/matchmaking/tickets`;return n.client.post(r,e,t?.signal)}async function oi(n,e,t){let r=`/v1/games/${Je(n.gameId())}/matchmaking/tickets/${Je(e)}/heartbeat`;return n.client.post(r,void 0,t?.signal)}function ze(n){let e=n??{};if(typeof e.ticket_id!="string"||e.ticket_id.length===0)throw new Error("[gem] a matchmaking-ticket response carried no id");let t=e.heartbeat_interval_seconds;return {id:e.ticket_id,status:typeof e.status=="string"?e.status:"queued",...typeof e.reason=="string"?{reason:e.reason}:{},...typeof e.game_room_id=="string"?{roomId:e.game_room_id}:{},partySize:typeof e.party_size=="number"?e.party_size:1,queuedAt:si(e.queued_at),expiresAt:si(e.expires_at),heartbeatIntervalSeconds:typeof t=="number"&&t>0?t:0}}function si(n){if(typeof n!="string")return 0;let e=Date.parse(n);return Number.isFinite(e)?Math.floor(e/1e3):0}var Rs=3,ai=1e3,Dt=class{constructor(e){this.options=e;this.snapshot=e.first;let t=new Promise((o,a)=>{this.resolve=o,this.reject=a;});t.catch(()=>{});let r=()=>this.snapshot,i=()=>this.status;this.ticket={get id(){return r().id},get status(){return i()},get partySize(){return r().partySize},get queuedAt(){return r().queuedAt},get expiresAt(){return r().expiresAt},outcome:t,cancel:()=>(this.requestCancel(),t)};}options;ticket;snapshot;status="queued";timer=null;busy=false;again=false;cancelRequested=false;soon=false;misses=0;settled=false;resolve;reject;start(){this.apply(this.snapshot);}poke(){this.settled||(this.soon=true,!this.busy&&(this.clearTimer(),this.tick()));}abandon(e=false){this.settled||(this.options.cancel(this.snapshot.id,e).catch(()=>{}),this.settle({status:"cancelled",reason:"requested"}));}requestCancel(){this.settled||(this.cancelRequested=true,this.trigger());}trigger(){if(this.busy){this.again=true;return}this.clearTimer(),this.tick();}schedule(e=false){if(this.settled)return;this.clearTimer();let t=e?ai:Math.max(ai,this.snapshot.heartbeatIntervalSeconds*1e3);this.timer=this.options.clock.setTimeout(()=>{this.timer=null,this.tick();},t);}clearTimer(){this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null);}async tick(){if(this.settled||this.busy)return;this.busy=true,this.again=false;let e=null,t=null;try{e=this.cancelRequested?await this.options.cancel(this.snapshot.id):await this.options.heartbeat(this.snapshot.id);}catch(r){t=r;}if(this.busy=false,!this.settled){if(e===null){this.missed(t);return}this.misses=0,await this.apply(e);}}missed(e){if(e instanceof j&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<Rs){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let t=e instanceof j&&e.code==="matchmaking_unavailable";this.settle({status:t?"unavailable":"lost"});}async apply(e){if(this.snapshot=e,e.status==="queued"){this.next();return}if(e.status==="matched"){await this.seat(e);return}e.status==="expired"?this.settle({status:"expired",reason:e.reason??"timed_out"}):e.status==="cancelled"?this.settle({status:"cancelled",reason:e.reason??"requested"}):this.settle({status:"failed",reason:e.reason??e.status});}next(){if(this.again){this.again=false,this.tick();return}let e=this.soon;this.soon=false,this.schedule(e);}async seat(e){if(e.roomId===void 0){this.fail(new Error("[gem] a matched matchmaking ticket named no game room"));return}this.busy=true;try{let t=await this.options.seat(e.roomId);this.busy=!1,this.settle({status:"matched",room:t});}catch(t){this.busy=false,this.fail(t);}}settle(e){this.settled||(this.finish(e.status),this.resolve(e));}fail(e){this.settled||(this.finish("matched"),this.reject(e));}finish(e){this.settled=true,this.status=e,this.clearTimer(),this.options.onSettled();}};function he(n){return typeof n=="string"&&n!==""?n:void 0}var Ss=new Set(["localhost","127.0.0.1","[::1]"]);function li(n){let e=he(n);if(e===void 0)return;let t;try{t=new URL(e);}catch{return}if(!(t.username!==""||t.password!=="")&&(t.protocol==="https:"||t.protocol==="http:"&&Ss.has(t.hostname)))return e}function xs(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=t??{},i=he(r.item_id),o=li(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function di(n){let e=n??{},t=he(e.player_id),r=he(e.display_name),i=he(e.discriminator),o=he(e.display_tag),a=he(e.avatar_icon_id),s=li(e.avatar_icon_url);return {...t===void 0?{}:{playerId:t},...r===void 0?{}:{displayName:de(r)},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:de(o)},...a===void 0?{}:{avatarIconId:a},...s===void 0?{}:{avatarIconUrl:s},badges:xs(e.badges)}}function qt(n){if(typeof n!="object"||n===null)return;let e={};for(let[t,r]of Object.entries(n)){let i=Gn(r);i!==void 0&&(e[t]=i);}return e}function $t(n){if(Array.isArray(n))return n.map(As).filter(e=>!!e)}function Gn(n){if(Dn(n)||Array.isArray(n)&&n.every(Dn))return n}function Dn(n){return typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)}function As(n){let e=n??{};if(typeof e.name!="string"||e.name.length===0)return null;let t=Gn(e.fixed),r=Gn(e.default);return {name:e.name,type:typeof e.type=="string"?e.type:"string",list:e.list===true,required:e.required===true,mutable:e.mutable!==false,...t===void 0?{}:{fixed:t},...r===void 0?{}:{default:r},...Ie("description",Ps(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(Dn)?{allowed:e.allowed}:{},...Ie("min",Ye(e.min)),...Ie("max",Ye(e.max)),...Ie("minItems",Ye(e.min_items)),...Ie("maxItems",Ye(e.max_items)),...Ie("maxLength",Ye(e.max_length))}}function Ps(n){return typeof n=="string"&&n.length>0?n:void 0}function Ye(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Ie(n,e){return e===void 0?{}:{[n]:e}}function z(n){let e=n??{},t=T(e.id)??T(e.game_room_id);if(t===void 0)throw new Error("[gem] a game-room response carried no id");let r=Array.isArray(e.members)?e.members.map(qn):[];return {id:t,gameId:T(e.game_id)??"",name:T(e.name)??"",status:T(e.status)??"open",hostPlayerId:T(e.host_player_id)??"",maxPlayers:X(e.max_players)??0,memberCount:X(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...J("joinCode",T(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...J("roomArgs",qt(e.room_args)),...J("roomArgsTemplate",$t(e.room_args_template)),gameChannel:T(e.game_channel)??"release",...J("region",T(e.region)),...J("clusterTargetId",T(e.cluster_target_id)),selfHosted:e.self_hosted===true,...J("matchId",T(e.match_id)),version:X(e.version)??0,...J("templateId",T(e.template_id)),roomType:T(e.game_room_type)??"Standard",...J("transports",Ne(e.transports)??void 0),createdAt:X(e.created_at)??0,updatedAt:X(e.updated_at)??0,...J("startedAt",X(e.started_at))}}function qn(n){let e=n??{};return {...di(e),playerId:T(e.player_id)??"",isReady:e.is_ready===true,role:T(e.role)??"member",joinedAt:X(e.joined_at)??0,...J("groupId",T(e.group_id)),...J("platform",T(e.platform))}}function Xe(n){let e=n??{};return {id:T(e.id)??T(e.game_room_id)??"",gameId:T(e.game_id)??"",name:T(e.name)??"",status:T(e.status)??"open",hostPlayerId:T(e.host_player_id)??"",maxPlayers:X(e.max_players)??0,memberCount:X(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:T(e.game_channel)??"release",roomType:T(e.game_room_type)??"Standard",createdAt:X(e.created_at)??0}}function T(n){return typeof n=="string"&&n.length>0?n:void 0}function X(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function J(n,e){return e===void 0?{}:{[n]:e}}var Ce=class{constructor(e){this.options=e;}options;list(e){let t=new URLSearchParams;e.status&&t.set("status",e.status),e.templateSlug&&t.set("template_slug",e.templateSlug),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor);let r=t.size>0?`?${t.toString()}`:"";return this.options.client.get(`${this.baseV1()}${r}`,e.signal).then(i=>({rooms:(i.game_rooms??[]).map(Xe),...typeof i.next_cursor=="string"?{nextCursor:i.next_cursor}:{}}))}myRooms(e){return this.options.client.get(`/v1/games/${encodeURIComponent(this.options.gameId())}/players/me/game-rooms`,e).then(t=>({rooms:(t.game_rooms??[]).map(Xe)}))}create(e,t,r){return Es(e.maxPlayers),this.options.client.post(this.baseV2(),{name:e.name,...e.isPublic===void 0?{}:{is_public:e.isPublic},...e.settings===void 0?{}:{settings:e.settings},...e.region===void 0?{}:{region:e.region},...r===void 0?{}:{cluster_target_id:r},...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.partyId===void 0?{}:{party_id:e.partyId},...this.asksSelfHosted(e.partyId)?{self_hosted:true}:{},...e.roomArgs===void 0?{}:{room_args:e.roomArgs},...Qe(t)},e.signal).then(z)}get(e,t){return this.options.client.get(this.roomV2(e),t).then(z)}join(e,t,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...t.partyId===void 0?{}:{party_id:t.partyId},...Qe(r)},t.signal).then(z)}joinByCode(e,t,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...t.partyId===void 0?{}:{party_id:t.partyId},...Qe(r)},t.signal).then(z)}quickJoin(e,t,r=[]){return this.options.client.post(`${this.baseV2()}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...this.asksSelfHosted(e.partyId)?{self_hosted:true}:{},...Qe(t)},e.signal).then(z)}createTicket(e,t,r=[]){return ii(this.generated(),{templates:e.templateSlugs.map(i=>({template_slug:i})),...r.length===0?{}:{cluster_target_ids:[...r]},...e.partyId===void 0?{}:{party_id:e.partyId},...Qe(t)},{...e.signal===void 0?{}:{signal:e.signal}}).then(ze)}heartbeatTicket(e){return oi(this.generated(),e).then(ze)}cancelTicket(e,t=false){return t?this.options.client.delete(`/v1/games/${encodeURIComponent(this.options.gameId())}/matchmaking/tickets/${encodeURIComponent(e)}`,void 0,{keepalive:true}).then(ze):ri(this.generated(),e).then(ze)}leave(e,t,r,i=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:t},r,{keepalive:i}).then(()=>{})}asksSelfHosted(e){return e===void 0&&this.options.selfHosted?.()===true}close(e,t){return this.options.client.delete(this.roomV1(e),t).then(()=>{})}update(e,t){return this.options.client.patch(this.roomV2(e),{...t.name===void 0?{}:{name:t.name},...t.maxPlayers===void 0?{}:{max_players:t.maxPlayers},...t.isPublic===void 0?{}:{is_public:t.isPublic},...t.settings===void 0?{}:{settings:t.settings},...t.roomArgs===void 0?{}:{room_args:t.roomArgs}},t.signal).then(z)}setReady(e,t,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:t},r).then(z)}kick(e,t,r){return this.options.client.post(`${this.roomV1(e)}/kick/${encodeURIComponent(t)}`,{},r).then(()=>this.get(e,r))}transferHost(e,t,r){return this.options.client.post(`${this.roomV2(e)}/transfer/${encodeURIComponent(t)}`,{},r).then(z)}leaveMatch(e,t){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:t}).then(()=>{})}generated(){return {client:this.options.client,gameId:this.options.gameId}}baseV2(){return `/v2/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function Qe(n){return {platform:n.platform,game_version:n.gameVersion,engine_version:n.engineVersion}}function Es(n){n!==void 0&&console.warn(`[gem] createRoom: maxPlayers (${n}) is deprecated and was not sent. A room's seats come from the room template published in your game config \u2014 name one with templateSlug \u2014 and a room created without a template seats 8. To change a room that already exists, call update({ maxPlayers }) as its host.`);}var Me=class{listeners=new Map;retainedMatch=null;on(e,t){let r=this.listeners.get(e);if(r||(r=new Set,this.listeners.set(e,r)),r.add(t),e==="matchReady"&&this.retainedMatch!==null){let i=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(t)&&this.retainedMatch===i&&t(i);});}return ()=>this.off(e,t)}hasListeners(e){return (this.listeners.get(e)?.size??0)>0}off(e,t){this.listeners.get(e)?.delete(t);}once(e,t){let r=this.on(e,((...i)=>{r(),t(...i);}));return r}emit(e,...t){e==="matchReady"&&(this.retainedMatch=t[0]);let r=this.listeners.get(e);if(r)for(let i of [...r])i(...t);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};function Ts(n,e){return Math.min(e,500*2**Math.max(0,n-1))}var Is=1e3,Cs=3e3,Ms=6e4,Os=2,ci=new Set(["game_room_closed","game_room_gone"]),Ls=12e4,Gs=5e3,Ds=new Set(["invalid_cluster_target","capacity_unavailable"]),qs=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function fi(n){return new $n(n)}var $n=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new Ce({client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new Me;api;room=null;ticketWatch=null;queueing=false;queuedFromRoomId=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create"),this.assertNotQueued("create");let t=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("create",async()=>{let o=await t;return this.api.create(r,this.version("create"),o[0]).catch(async a=>{let s=await this.afterRefusedClusters(a,o);if(s[0]===void 0||s[0]===o[0])throw a;return this.api.create(r,this.version("create"),s[0])})});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,t={}){this.assertNotInRoom("join"),this.assertNotQueued("join");let r=await this.attachParty(t),i=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async joinByCode(e,t={}){this.assertNotInRoom("joinByCode"),this.assertNotQueued("joinByCode");let r=await this.attachParty(t),i=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async quickJoin(e){this.assertNotInRoom("quickJoin"),this.assertNotQueued("quickJoin");let t=this.clusterTargets(),r=await this.attachParty(e),i=a=>this.api.quickJoin(r,this.version("quickJoin"),a).catch(s=>this.retryPastStaleMembership(s,r,a)),o=await this.run("quickJoin",async()=>{let a=await t;return i(a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||hi(l,a))throw s;return i(l)})});return this.enter(o,"joined"),this.askForLocalServer(o),o}async queueForMatch(e){this.assertNotQueued("queueForMatch"),Fs(e?.templateSlugs),this.queueing=true;try{let t=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("queueForMatch",async()=>{let a=await t;return this.api.createTicket(r,this.version("queueForMatch"),a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||hi(l,a))throw s;return this.api.createTicket(r,this.version("queueForMatch"),l)})}),o=new Dt({clock:this.options.clock,first:i,heartbeat:a=>this.track(this.api.heartbeatTicket(a)),cancel:(a,s)=>this.track(this.api.cancelTicket(a,s)),seat:a=>this.enterMatchedRoom(a),onSettled:()=>{this.ticketWatch===o&&(this.ticketWatch=null),this.retuneSeatWatch();}});return this.ticketWatch=o,this.retuneSeatWatch(),o.start(),o.ticket}finally{this.queueing=false;}}async enterMatchedRoom(e){let t=await this.run("queueForMatch",()=>this.api.get(e));return this.disposed?t:(this.room!==null&&this.room.id!==t.id&&(this.queuedFromRoomId=this.room.id,this.exit()),this.room===null&&this.enter(t,"joined"),this.room?.id===t.id?this.room:t)}async list(e={}){let t=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",t),t}async myRooms(e){let t=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",t.rooms),t.rooms}async leave(e={}){let t=this.requireRoom("leave"),r=e.keepalive===true,i=()=>this.run("leave",()=>this.api.leave(t.id,e.asGroup!==false,e.signal,r));if(r){let o=i();this.track(this.notifyLeavingMatch({keepalive:true})),await o;}else await this.notifyLeavingMatch(),await i();this.exit(),this.emitter.emit("left");}async leaveAll(e){let t=await this.myRooms(e),r=[];for(let i of t)try{await this.run("leaveAll",()=>this.api.leave(i.id,!0,e)),r.push(i.id),this.room?.id===i.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let t=this.requireRoom("close");await this.run("close",()=>this.api.close(t.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let t=this.room;if(!t)return null;let r;try{r=await this.track(this.api.get(t.id,e));}catch(i){if(i instanceof j&&i.reason==="not_found"){let o=this.heldMatchId;if(o!==null){let a=await this.askWhyEnded(o,e);this.endMatch(o,a??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",i),i}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let t=this.room,r=this.heldMatchId;if(!(t===null||r===null)&&!(t.status==="in_game"&&t.matchId===r)&&!(t.matchId!==void 0&&t.matchId!==r)&&this.settling!==r){this.settling=r;try{let i=await this.askWhyEnded(r,e);i!==null&&this.endMatch(r,i,t.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,t){let r=this.room;if(r===null)return null;let i=this.takeHint(e),o;try{o=await this.track(this.onceGameIdKnown(()=>Zt({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e),...t===void 0?{}:{signal:t}})));}catch(a){return a instanceof j&&a.reason==="not_found"?i??null:(this.reportError("reconcile",a),null)}return o===null?null:o.status==="ready"?(this.seenMatches.add(e),null):o.status==="failed"?(this.settleFailed(o.matchId,o.reason),null):o.reason==="unknown"&&i!==null?i:o.reason}takeHint(e){let t=this.pendingHint;if(t===null||t.matchId!==void 0&&t.matchId!==e||(this.pendingHint=null,t.reason===void 0))return null;let r=Re(t.reason);return r==="unknown"?null:r}async reconcile(e){if(this.disposed)return;if(e!==void 0&&(e.matchId!==void 0||e.reason!==void 0)&&(this.pendingHint=e),this.reconciling!==null)return this.reconcileAgain=true,this.reconciling;let t=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=t,this.track(t)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,t){let r=this.requireRoom("setReady"),i=await this.run("setReady",()=>this.api.setReady(r.id,e,t));return this.apply(i),i}async kick(e,t){let r=this.requireRoom("kick"),i=await this.run("kick",()=>this.api.kick(r.id,e,t));return this.apply(i),i}async transferHost(e,t){let r=this.requireRoom("transferHost"),i=await this.run("transferHost",()=>this.api.transferHost(r.id,e,t));return this.apply(i),i}async update(e){let t=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(t.id,e));return this.apply(r),r}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,t){let r=this.requireRoom("startMatch");if(!this.isHost)throw new c("misconfigured",`only the host of room ${r.id} can start a match, and this player is not it. Every other member waits for \`matchAllocationStarted\` instead \u2014 that is the whole point of the room carrying the match.`);this.startsInFlight++;try{return await this.startIn(r,e,t)}finally{this.startsInFlight--;}}async startIn(e,t,r){let i=B(t.clusterTargetId),o=i??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),a=o??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let s=(m,u)=>gt({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...i===void 0?{nextClusterTarget:()=>this.nextCluster(u)}:{},retry:{...t.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),t.retry?.onWaiting?.(p);}},...t.signal===void 0?{}:{signal:t.signal}}),l=()=>s(o,[a]).catch(async m=>{if(i!==void 0||!pi(m))throw m;let u=await this.nextCluster([a],true);if(u===void 0)throw m;return s(u,[a,u])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new c("misconfigured","this match is suspended \u2014 the transport dropped and nobody has decided to reconnect yet. Call reconnectToMatch(), or dedicatedServer.connect(), which does it for you.");let t=this.emitter.retained;return t!==null&&this.session.phase==="ready"?t:this.pollMatchStatus(e)}async pollMatchStatus(e={}){let t=this.requireRoom("pollMatchStatus"),r=await this.matchIdOrWait(e),i=await this.run("pollMatchStatus",()=>this.chase(t.id,r,e));return this.settleOutcome(i)}chase(e,t,r){return ht({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e,matchId:t,version:this.version("pollMatchStatus"),knownToExist:this.seenMatches.has(t),...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.pollIntervalMs===void 0?{}:{pollIntervalMs:r.pollIntervalMs},...r.signal===void 0?{}:{signal:r.signal}})}settleOutcome(e){if(e.status==="failed")throw this.settleFailed(e.matchId,e.reason),new c("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!ci.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new c("match_ended",`match ${e.matchId} ended: ${e.reason}`);return this.seenMatches.add(e.matchId),this.emitter.retained?.matchId===e.matchId?this.emitter.retain(e):this.emitter.emit("matchReady",e),this.heldMatchId===e.matchId&&this.session.phase!=="connected"&&(this.session={phase:"ready",matchId:e.matchId}),e}settleFailed(e,t){this.heldMatchId===e&&(this.abandonReconnect(e,t),this.emitter.emit("matchFailed",e,t),this.abortFollow(),this.refusedMatches.add(e),this.session={phase:"none"},this.emitter.clearRetained());}endMatch(e,t,r){this.heldMatchId===e&&(this.abortFollow(),this.session={phase:"ended",matchId:e,reason:t,roomReopened:r},this.emitter.clearRetained(),this.emitter.emit("matchEnded",{matchId:e,reason:t,roomReopened:r}),this.abandonReconnect(e,t));}armReconnect(e,t){let r=this.options.autoReconnect;if(r===void 0||r.attempts<=0||r.budgetMs<=0)return;if(this.finishReconnect(),t==="kicked"){r.abandon(e,t);return}let i={matchId:e,cause:t,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=i,this.track(this.reconnectStep(i));}park(e,t){e.parkedAt=this.options.clock.now(),e.parked=()=>(e.parkedAt!==null&&(e.deadlineAt+=this.options.clock.now()-e.parkedAt,e.parkedAt=null),t());}reconnecting(e){return !this.disposed&&!e.done&&this.reconnect===e&&this.session.phase==="suspended"&&this.session.matchId===e.matchId}finishReconnect(){let e=this.reconnect;e!==null&&(e.done=true,e.timer!==null&&(this.options.clock.clearTimeout(e.timer),e.timer=null),e.parked=null,this.reconnect=null);}abandonReconnect(e,t){let r=this.reconnect;r===null||r.matchId!==e||(this.finishReconnect(),this.options.autoReconnect?.abandon(e,t));}async reconnectStep(e){if(!this.reconnecting(e))return;if(!Ft()){this.park(e,()=>this.reconnectStep(e));return}let t=this.options.autoReconnect;if(t===void 0||e.attempt===0&&(await this.reconcile().catch(()=>{}),!this.reconnecting(e)))return;let r=e.deadlineAt-this.options.clock.now();if(e.attempt>=t.attempts||r<Is){this.abandonReconnect(e.matchId,e.cause);return}e.attempt+=1,this.emitter.emit("matchReconnecting",{matchId:e.matchId,attempt:e.attempt,attempts:t.attempts,remainingMs:r}),e.timer=this.options.clock.setTimeout(()=>{e.timer=null,this.track(this.reconnectAttempt(e));},Math.min(Ts(e.attempt,t.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!Ft()){this.park(e,()=>this.reconnectAttempt(e));return}let t=this.options.autoReconnect,r=this.room;if(t===void 0||r===null)return;let i=null;try{i=await this.track(this.onceGameIdKnown(()=>Zt({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e.matchId,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e.matchId)})));}catch(o){this.reportError("reconcile",o);}if(this.reconnecting(e)){if(i?.status==="ended"){this.endMatch(i.matchId,i.reason,!ci.has(i.reason)),this.track(this.reconcile().catch(()=>{}));return}if(i?.status==="failed"){this.abandonReconnect(e.matchId,i.reason),this.settleFailed(i.matchId,i.reason);return}if(i?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(i);let o;try{o=await t.redial(e.matchId,e.deadlineAt);}catch(a){this.reportError("reconcile",a),o="failed";}if(e.done||this.reconnect!==e)return;if(o==="closed"){this.finishReconnect();return}if(o==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let t=this.session.phase==="suspended";this.session={phase:"connected",matchId:e};let r=this.reconnect;r!==null&&r.matchId===e?(this.finishReconnect(),this.emitter.emit("matchReconnected",{matchId:e,attempt:r.attempt})):t&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new c("misconfigured",`no match is connected, so there is nothing to suspend (state '${this.matchConnectionState}').`);let t=this.session.matchId;this.session={phase:"suspended",matchId:t,reason:e},this.emitter.emit("matchSuspended",{matchId:t,cause:e}),this.armReconnect(t,e);}async reconnectToMatch(e={}){if(this.session.phase!=="suspended")throw new c("misconfigured",`reconnectToMatch expects a suspended match; this one is '${this.matchConnectionState}'. Call notifyMatchDisconnected() when the transport drops.`);let t=this.heldMatchId;if(t===null)throw new c("misconfigured","there is no match to reconnect to.");return this.finishReconnect(),this.session={phase:"starting",matchId:t},this.emitter.clearRetained(),this.pollMatchStatus(e)}async notifyLeavingMatch(e={}){let t=this.heldMatchId;if(t!==null)try{await this.api.leaveMatch(t,e.keepalive??!1);}catch{}}get gameId(){let e=typeof this.options.gameId=="function"?this.options.gameId():this.options.gameId;return e===""?null:e}get currentRoom(){return this.room}get currentTicket(){return this.ticketWatch?.ticket??null}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}on(e,t){let r=this.emitter.on(e,t);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,t){this.emitter.off(e,t);}once(e,t){return this.emitter.once(e,t)}handleRoomEvent(e){if(this.ticketWatch!==null&&e.event!=="version_stale"&&e.roomId!==this.room?.id&&this.ticketWatch.poke(),this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let t=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(t).catch(()=>{}));}handleAutoStartFailed(e,t){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(t);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:t,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let i=new AbortController;this.autoStartRetry=i,this.track(this.requestStart({signal:i.signal},false).then(()=>{},o=>{i.signal.aborted||this.reportError("startMatch",o);}).finally(()=>{this.autoStartRetry===i&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!Ds.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.watchingSeats&&this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}}async reconcileSeats(){if(this.disposed||!this.watchingSeats||this.ticketWatch!==null)return;let e;try{e=await this.myRooms();}catch{return}let t=new Set;for(let r of e)r.status!=="closed"&&(t.add(r.id),r.id!==this.room?.id&&(this.reported.has(r.id)||await this.reportSeat(r.id).catch(()=>{})));for(let r of [...this.reported])t.has(r)||this.reported.delete(r);}async reportSeat(e){let t=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||t===null||!r.members.some(i=>i.playerId===t)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.ticketWatch===null&&this.seatPollMs>0&&Ft())){this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null);return}if(this.seatPollHandle!==null)return;let t=()=>{this.seatPollHandle=null,this.track(this.reconcileSeats().catch(()=>{}).then(()=>this.retuneSeatWatch()));};this.seatPollHandle=this.options.clock.setTimeout(t,this.seatPollMs);}installResumeWatch(){let e=globalThis;if(typeof e.addEventListener!="function")return;this.visibilityListener=()=>{if(!this.disposed&&(this.retuneSeatWatch(),!!Ft())){if(this.room!==null){let r=this.reconnect?.parked??null;r!==null&&this.reconnect!==null?(this.reconnect.parked=null,this.track(r())):this.track(this.reconcile().catch(()=>{}));return}if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of ui)e.addEventListener(r,this.visibilityListener);let t=globalThis.document;typeof t?.addEventListener=="function"&&t.addEventListener("resume",this.visibilityListener);}startPolling(e){this.stopPolling(),!this.disposed&&(this.pinnedIntervalMs=e??null,this.polling=true,this.schedule());}stopPolling(){this.pollHandle!==null&&(this.options.clock.clearTimeout(this.pollHandle),this.pollHandle=null),this.polling=false,this.pollIntervalMs=null;}async settled(){for(let e=0;e<20&&this.inFlight.length>0;e++){let t=this.inFlight;this.inFlight=[],await Promise.allSettled(t);}}dispose(){if(this.disposed=true,this.ticketWatch?.abandon(),this.abortAutoStartRetry(),this.finishReconnect(),this.stopPolling(),this.emitter.clear(),this.unloadListener&&(globalThis.removeEventListener?.("pagehide",this.unloadListener),this.unloadListener=null),this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null),this.visibilityListener){let e=globalThis;for(let r of ui)e.removeEventListener?.(r,this.visibilityListener);globalThis.document?.removeEventListener?.("resume",this.visibilityListener),this.visibilityListener=null;}}get watchingSeats(){return this.options.watchSeats!==false&&this.emitter.hasListeners("seated")}get seatPollMs(){return this.options.seatPollIntervalMs??Gs}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new c("misconfigured","the game id is not known yet. It comes from the play token, and this manager was given no way to wait for one \u2014 pass gameId, or awaitGameId so a call made before the first token waits for it the way createGem wires it.")}playerId(){return typeof this.options.playerId=="function"?this.options.playerId():this.options.playerId}version(e){let t=this.options.clientVersion,r=ni(this.options.platformGameVersion?.(),t?.gameVersion);if(r===null)throw new c("misconfigured",`${e} has no game version to report \u2014 gem-api requires platform, game_version and engine_version together on every room route, and refuses a request carrying two of the three. The arcade normally supplies it with the play token; an embedder that does not, or a build running outside the arcade, leaves nobody to ask. Pass \`clientVersion: { gameVersion }\` to createGem (or to createRoomManager) as the fallback. It has to name a build you actually published, and a wrong one pins the room to the wrong build \u2014 which is why the platform answers it wherever it can.`);return Or({...t,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return be(await this.options.resolveClusterTargets());let e=B(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,t){return !pi(e)||t.length===0?[]:be(await this.options.refreshClusterTargets?.(t)??[])}async nextCluster(e,t=false){let r=a=>a.find(s=>!e.includes(s)),i=await this.clusterTargets(),o=r(i);return o!==void 0||!t?o:r(be(await this.options.refreshClusterTargets?.(i)??[]))}async attachParty(e){if(e.partyId!==void 0)return e;let t=this.options.resolveParty;if(t===void 0)return e;let r=await t();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,t,r){if(!(e instanceof j)||e.reason!=="conflict"||!qs.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new j(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and \`recoverStaleMembership\` is off, so nothing cleared it. A membership that outlived its page is visible only through myRooms(); leaveAll() is what clears it.`,e.retryAfterSeconds,e.code);let i;try{i=await this.leaveAll(t.signal);}catch{throw new j(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery could not list the rooms it would have cleared, so nothing was tried and the refusal stands. That is the listing failing, not a room refusing to be left: retry once the connection is back. myRooms() shows what is held.`,e.retryAfterSeconds,e.code)}if(i.length===0)throw new j(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery cleared nothing, so the refusal stands. myRooms() shows what is held. A room this player was seated in as a party member cannot be cleared from here at all \u2014 only the leader of a party may take it out of a room \u2014 so a member joins by adopting that room, myRooms() then join(), rather than quick-joining.`,e.retryAfterSeconds,e.code);return this.api.quickJoin(t,this.version("quickJoin"),r)}assertNotInRoom(e){if(this.room!==null)throw new c("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}assertNotQueued(e){if(!(this.ticketWatch===null&&!this.queueing))throw new c("misconfigured",`${e} refused: this player is waiting on a matchmaking ticket, which will seat them in a room of its own. Cancel it first \u2014 currentTicket.cancel() \u2014 or wait for its outcome.`)}requireRoom(e){if(this.room===null)throw new c("misconfigured",`${e} refused: not in a room.`);return this.room}async run(e,t){try{return await this.track(this.onceGameIdKnown(t))}catch(r){throw this.reportError(e,r),r}}onceGameIdKnown(e){return this.gameId!==null||this.options.awaitGameId===void 0?e():this.options.awaitGameId().then(e)}reportError(e,t){let r=t instanceof j?{operation:e,code:t.status,reason:t.reason,message:t.message,retryable:t.retryable}:{operation:e,code:0,reason:t instanceof c?t.reason:"unavailable",message:t instanceof Error?t.message:String(t),retryable:false};this.emitter.emit("error",r);}askForLocalServer(e){let t=this.options.ensureLocalServer;t===void 0||!e.selfHosted||e.status!=="open"||t(e.id).catch(()=>{});}track(e){return this.inFlight.push(e),e}enter(e,t){this.room=e,this.queuedFromRoomId===e.id&&(this.queuedFromRoomId=null),this.abortFollow(),this.autoStartRetried=false,this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(t,e),this.adoptMatch(e),this.options.poll!==false&&this.startPolling(),this.retuneSeatWatch();}exit(){this.room=null,this.abortFollow(),this.abortAutoStartRetry(),this.autoStartRetried=false,this.finishReconnect(),this.session.phase!=="ended"&&(this.session={phase:"none"}),this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.stopPolling(),this.retuneSeatWatch();}apply(e){let t=this.room;if(t===null||t.id!==e.id)return;let r=new Map(t.members.map(s=>[s.playerId,s])),i=new Map(e.members.map(s=>[s.playerId,s])),o=this.playerId();for(let s of i.keys())r.has(s)||this.emitter.emit("memberJoined",s);for(let s of r.keys())if(!i.has(s)){if(s===o){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",s);}for(let[s,l]of i){let d=r.get(s);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",s,l.isReady);}t.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let a=$s(t,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),a&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let t=this.heldMatchId;t!==null&&t!==e&&this.endMatch(t,"replaced",true),this.session={phase:"starting",matchId:e},this.autoStartRetried=false,this.emitter.clearRetained(),this.emitter.emit("matchAllocationStarted",e),this.followMatch();}followMatch(){if(this.autoFollow===false)return;let e=this.room,t=this.heldMatchId;if(e===null||t===null||this.followAbort!==null&&this.followingMatchId===t)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=t,this.track(this.onceGameIdKnown(()=>this.chase(e.id,t,{signal:r.signal})).then(i=>{if(!r.signal.aborted)try{this.settleOutcome(i);}catch{}}).catch(i=>{r.signal.aborted||this.reportError("pollMatchStatus",i);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let t=this.heldMatchId;if(t!==null)return Promise.resolve(t);let r=e.timeoutMs??Ls;return new Promise((i,o)=>{let a=u=>{s(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),u();},s=this.emitter.on("matchAllocationStarted",u=>a(()=>i(u))),l=this.emitter.on("matchFailed",(u,p)=>a(()=>o(new c("allocation_failed",`match ${u} did not come up: ${p}`)))),d=()=>a(()=>o(new c("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>a(()=>o(new c("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?d():e.signal?.addEventListener("abort",d);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??Cs}pushedInterval(){return this.options.pushedPollIntervalMs??Ms}pushed(){return this.options.clock.now()-this.lastPushAt<Os*this.pushedInterval()}retune(){!this.polling||this.pinnedIntervalMs!==null||this.baseInterval()!==this.pollIntervalMs&&this.startPolling();}schedule(){this.disposed||!this.polling||this.room===null||(this.pollIntervalMs=this.pinnedIntervalMs??this.baseInterval(),this.pollHandle=this.options.clock.setTimeout(()=>{this.pollHandle=null,this.track(this.reconcile().catch(()=>null).then(()=>{this.schedule();}));},this.pollIntervalMs));}installUnloadNotifier(){if(this.options.notifyOnUnload===false)return;let e=globalThis;typeof e.addEventListener=="function"&&(this.unloadListener=t=>{if(this.ticketWatch?.abandon(true),t?.persisted!==true&&(this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{})),this.queuedFromRoomId!==null)){let r=this.queuedFromRoomId;this.queuedFromRoomId=null,this.track(this.api.leave(r,true,void 0,true).catch(()=>{}));}},e.addEventListener("pagehide",this.unloadListener));}};function Ft(){let n=globalThis.document;return n?.visibilityState===void 0||n.visibilityState==="visible"}var ui=["visibilitychange","focus","pageshow","online"];function $s(n,e){return n.version!==e.version||n.status!==e.status||n.matchId!==e.matchId||n.hostPlayerId!==e.hostPlayerId||n.name!==e.name||n.maxPlayers!==e.maxPlayers||n.isPublic!==e.isPublic||mi(n)!==mi(e)}function mi(n){return n.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function pi(n){return n instanceof j&&n.code==="invalid_cluster_target"}var gi=8;function Fs(n){if(!(Array.isArray(n)&&n.length>=1&&n.length<=gi&&n.every(t=>typeof t=="string"&&t.length>0)))throw new c("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${gi} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function hi(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}function yi(n){let e=0,t=new Map;return {resolve(){if(!n.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(i=>{let o={},a=l=>{t.delete(r)&&(n.clock.clearTimeout(o.timer),i(l));};t.set(r,a),o.timer=n.clock.setTimeout(()=>a(void 0),n.timeoutMs??2e3);let s=false;try{s=n.bridge.requestParty(r);}catch{}s||a(void 0);})},settle(r,i){t.get(r)?.(i);}}}
2
+ export{_i as CAPABILITY_GATES,vi as CAPABILITY_NAMESPACE_GATES,Mt as CHANNELS,Ke as CHANNEL_KINDS,ce as ClientTelemetry,Wt as DEDICATED_INBOUND_EVENTS,sn as DEFAULT_WELCOME_CEILING_MS,to as DEVICE_SETTINGS_MAX_BYTES,c as DedicatedServerError,bt as DedicatedSignalingHub,Us as FRAME_TO_PARENT,zt as GemFrame,Jt as GemHost,Nt as HANDSHAKE_TIMEOUT_MS,Pe as HostMigration,ye as MALFORMED_INBOUND_KEY,Un as MAX_ARRAY_LENGTH,it as MAX_CLUSTER_TARGETS,fe as MAX_MESSAGE_BYTES,Nn as MAX_MESSAGE_DEPTH,et as MAX_MESSAGE_NODES,st as MAX_SIGNALS_PER_SECOND,Oe as MAX_SOCKET_FRAME_BYTES,zr as MIGRATION_TIMEOUT_MS,xe as P2pApi,k as P2pError,Ee as P2pSession,Ns as PARENT_TO_FRAME,f as PROTOCOL,W as PlayerText,tt as RATE_LIMITS,te as RateLimiter,Me as RoomEmitter,Ce as RoomsApi,Z as SUPPORTED_VERSIONS,Te as SignalingClient,pt as TELEMETRY_EVENTS,ir as TRANSPORT_LABELS,ae as VALIDATORS,$e as WEBRTC_DEDICATED,Ln as WEBRTC_P2P,We as WEB_ENGINE_VERSION,ge as WEB_PROTOCOL_VERSION,de as asPlayerText,ht as awaitMatchOutcome,Ot as browserPeerConnection,at as buildDedicatedOfferFrame,dt as buildSocketFrame,nt as capabilityFor,Ei as createClusterTargetSource,Jo as createDedicatedServerApi,It as createKeySource,ws as createP2pApi,yi as createPartyResolver,fi as createRoomManager,no as deviceSettingsByteLength,Be as establishDataChannel,pe as fingerprintOf,Ae as fingerprintsMatch,Lt as generateCertificate,rt as isOrigin,ft as listClusterTargets,qn as memberFromWire,Vt as negotiateVersion,B as normaliseClusterTarget,be as normaliseClusterTargets,Ve as normaliseFingerprint,we as originsEqual,Fe as presentJoinCredential,lt as projectDedicatedEvent,De as projectPartyEvent,ct as projectSignal,qt as roomArgValuesFromWire,$t as roomArgsTemplateFromWire,z as roomFromWire,gt as startMatch,Xe as summaryFromWire,re as systemClock,Yi as text,_t as unavailableSignaling,Wa as validateGemAdResult,Pa as validateGemAudioState,ia as validateGemAutoStartFailedEvent,la as validateGemClusterTarget,Ys as validateGemCohorts,Ia as validateGemControlsDeclare,sa as validateGemDedicatedEvent,ha as validateGemDedicatedOffer,Zs as validateGemDeviceSettings,Na as validateGemDeviceSettingsPut,Ua as validateGemDeviceSettingsResult,da as validateGemDevtools,Xs as validateGemEarnAllowanceChanged,ba as validateGemEngaged,$a as validateGemError,Sa as validateGemExit,Da as validateGemFrameStats,Ja as validateGemFriendChallengeResult,pa as validateGemGameContext,Bs as validateGemHandshake,Ws as validateGemHandshakeAccept,wa as validateGemLocalServer,Ra as validateGemLocalServerDenied,Ca as validateGemMenu,Ma as validateGemMenuSelect,xa as validateGemOpenExternal,fa as validateGemPartyRequest,aa as validateGemPartyResult,Js as validateGemPause,Ks as validateGemPlayer,qa as validateGemPortraitBorders,zs as validateGemPrefs,_a as validateGemProgress,ja as validateGemPurchaseResult,ya as validateGemReady,Ba as validateGemRequestAd,La as validateGemRequestAvatarPicker,ma as validateGemRequestContext,Ka as validateGemRequestFriendChallenge,Aa as validateGemRequestFullscreen,ka as validateGemRequestLocalServer,Fa as validateGemRequestPurchase,Oa as validateGemRequestShare,Va as validateGemRequestSignIn,va as validateGemRequestToken,Ea as validateGemRewardCue,ta as validateGemRoomEvent,ca as validateGemScreenshot,ua as validateGemScreenshotDenied,ra as validateGemSeatedEvent,Ha as validateGemSignInResult,ga as validateGemSignal,oa as validateGemSignalEvent,na as validateGemSocketState,Vs as validateGemToken,Hs as validateGemTokenDenied,Ga as validateGemVibrate,Qs as validateGemViewport,Ta as validateGemWalletDisplay,ea as validateGemWillTerminate,Si as validateSize,Ct as verifyCredential};//# sourceMappingURL=gem-web-sdk.esm.js.map
3
3
  //# sourceMappingURL=gem-web-sdk.esm.js.map