@indiegems/gem-web-sdk 9.1.2 → 9.1.3

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:9.1.2]";var g="gem-web-bridge",Z={min:1,max:1},fe=65536,jn=8,ze=5e3,Nn=1024,Ft=1e4;function jt(n){return Object.freeze(Object.assign(Object.create(null),n))}var Qe=jt({"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.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",Cs=["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"],Ps=["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.vibrate","gem.frameStats","gem.portraitBorders","gem.error","gem.requestPurchase","gem.deviceSettings.put","gem.requestAd","gem.requestSignIn","gem.requestFriendChallenge"],si=jt({"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.vibrate":"vibration","gem.menu":"gameMenu","gem.menuSelect":"gameMenu"}),di=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"]]);function Ze(n){let e=si[n];if(e!==void 0)return e;for(let[t,r]of di)if(n.startsWith(t))return r}function et(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 li(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 ci(n){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(n)}function ui(n){return /^[a-z_]+$/.test(n)}function Gt(n,e,t){if(e>jn)return `nesting deeper than ${jn}`;if(++t.nodes>ze)return `more than ${ze} 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>Nn)return `an array of ${n.length} entries, over the ${Nn} limit`;t.bytes+=2;for(let a of n){let d=Gt(a,e+1,t);if(d)return d}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 s=n;for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;if(++t.nodes>ze)return `more than ${ze} values`;if(t.bytes+=a.length*3+4,t.bytes>fe)return `over the ${fe} byte limit`;let d=Gt(s[a],e+1,t);if(d)return d}return null}function mi(n){let e={nodes:0,bytes:0,seen:new Set},t=Gt(n,0,e);return t?`message contains ${t}`:e.bytes>fe?`message is over the ${fe} byte limit`:null}var pi={origin:[et,"not a well-formed origin"],url:[li,"not a safe absolute http(s) URL"],bcp47:[ci,"not a well-formed BCP 47 tag"],code:[ui,"not a code of lower-case letters and underscores"]};function qn(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 s=$n(o,r,i);if(s)return s}return null}function $n(n,e,t){switch(e.k){case "string":{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]=pi[e.f];if(!r(n))return `${t}: ${i}`}return null}case "int":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 "boolean":return typeof n=="boolean"?null:`${t}: expected boolean`;case "enum":{let r=e.v;return r.includes(n)?null:`${t}: not one of ${r.join("|")}`}case "object":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected object`:qn(n,e.fs,t);case "json":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected a plain object`:null;case "array":{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 s=$n(o,r,i);if(s)return s}return null}default:{let r=e.k;return `${t}: unknown kind ${String(r)}`}}}function y(n,e){return t=>{let r=mi(t);if(r)return r;if(typeof t!="object"||t===null||Array.isArray(t))return "message: expected object";let i=t;return i.gem!==g?"gem: wrong protocol marker":i.type!==n?`type: expected ${n}`:qn(i,e,"")}}var hi=y("gem.handshake",[{n:"versions",k:"object",fs:[{n:"min",k:"int",lo:1,hi:1e3},{n:"max",k:"int",lo:1,hi:1e3}]},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}},{n:"embedder",k:"string",max:2048,f:"origin"},{n:"unbidden",k:"boolean",o:1}]),gi=y("gem.handshake.accept",[{n:"v",k:"int",lo:1,hi:1e3},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}}]),fi=y("gem.token",[{n:"token",k:"string",max:4096},{n:"requestId",k:"string",o:1,max:64},{n:"generation",k:"int",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"string",o:1,max:512,f:"url"},{n:"playerId",k:"string",max:64},{n:"gameId",k:"string",max:64},{n:"channel",k:"enum",v:["dev","test","release"]},{n:"gameVersion",k:"string",o:1,max:64},{n:"expiresAt",k:"int",lo:0,hi:4102444800},{n:"chainEndsAt",k:"int",lo:0,hi:4102444800},{n:"allowDevTools",k:"boolean",o:1}]),yi=y("gem.token.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"retryAfterMs",k:"int",o:1,lo:0,hi:36e5},{n:"reason",k:"enum",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"string",max:64}]),vi=y("gem.player",[{n:"untrusted",k:"object",fs:[{n:"displayName",k:"string",max:64},{n:"displayTag",k:"string",o:1,max:80},{n:"displayHandle",k:"string",max:80}]},{n:"playerId",k:"string",o:1,max:64},{n:"discriminator",k:"string",o:1,max:8},{n:"avatarIconUrl",k:"string",o:1,max:2048,f:"url"},{n:"badges",k:"array",o:1,max:2,it:{n:"",k:"object",fs:[{n:"itemId",k:"string",max:64},{n:"iconUrl",k:"string",max:2048,f:"url"}]}},{n:"displayTag",k:"string",max:8},{n:"avatarUrl",k:"string",o:1,max:2048,f:"url"},{n:"boost",k:"object",o:1,fs:[{n:"multipliers",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"currencyId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"multiplierBp",k:"int",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"int",o:1,lo:1,hi:7}]}]),bi=y("gem.pause",[{n:"paused",k:"boolean"}]),wi=y("gem.prefs",[{n:"reducedMotion",k:"boolean"},{n:"muted",k:"boolean"},{n:"showFrameStats",k:"boolean",o:1},{n:"locale",k:"string",max:35,f:"bcp47"}]),ki=y("gem.cohorts",[{n:"cohorts",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"experimentId",k:"string",max:36},{n:"variantKey",k:"string",max:32}]}}]),Si=y("gem.earnAllowanceChanged",[]),Ri=y("gem.viewport",[{n:"insets",k:"object",fs:[{n:"top",k:"int",lo:0,hi:4096},{n:"right",k:"int",lo:0,hi:4096},{n:"bottom",k:"int",lo:0,hi:4096},{n:"left",k:"int",lo:0,hi:4096}]},{n:"reserved",k:"array",o:1,max:4,it:{n:"",k:"object",fs:[{n:"x",k:"int",lo:0,hi:16384},{n:"y",k:"int",lo:0,hi:16384},{n:"width",k:"int",lo:0,hi:16384},{n:"height",k:"int",lo:0,hi:16384}]}}]),_i=y("gem.deviceSettings",[{n:"settings",k:"json",o:1}]),Ei=y("gem.willTerminate",[{n:"reason",k:"enum",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"int",lo:0,hi:6e4}]),xi=y("gem.roomEvent",[{n:"event",k:"enum",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"string",max:64},{n:"matchId",k:"string",o:1,max:64},{n:"version",k:"int",o:1,lo:0,hi:2147483647},{n:"reason",k:"string",o:1,max:64},{n:"platform",k:"enum",o:1,v:["universal","mobile"]}]),Ti=y("gem.socketState",[{n:"connected",k:"boolean"},{n:"reason",k:"enum",o:1,v:["connecting","dropped","watchdog","terminal"]}]),Ai=y("gem.seatedEvent",[{n:"roomId",k:"string",max:64}]),Ii=y("gem.autoStartFailedEvent",[{n:"roomId",k:"string",max:64},{n:"code",k:"string",max:64}]),Ci=y("gem.signalEvent",[{n:"event",k:"enum",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),Pi=y("gem.dedicatedEvent",[{n:"event",k:"enum",v:["answer","error","matchEnded"]},{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",o:1,max:10240},{n:"sessionId",k:"string",o:1,max:64},{n:"code",k:"string",o:1,max:64},{n:"message",k:"string",o:1,max:256},{n:"reason",k:"string",o:1,max:64}]),Mi=y("gem.partyResult",[{n:"requestId",k:"string",max:64},{n:"partyId",k:"string",o:1,max:64}]),Li=y("gem.clusterTarget",[{n:"clusterTargetId",k:"string",max:64},{n:"clusterTargetIds",k:"array",o:1,max:3,it:{n:"",k:"string",max:64}}]),Oi=y("gem.devtools",[{n:"action",k:"enum",v:["open","close","toggle"]}]),Di=y("gem.screenshot",[{n:"maxWidth",k:"int",lo:1,hi:7680},{n:"maxHeight",k:"int",lo:1,hi:4320}]),Gi=y("gem.screenshot.denied",[{n:"reason",k:"enum",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"boolean"}]),Fi=y("gem.requestContext",[]),ji=y("gem.gameContext",[{n:"context",k:"json"}]),Ni=y("gem.signal",[{n:"signal",k:"enum",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),qi=y("gem.dedicatedOffer",[{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",max:10240},{n:"intent",k:"enum",v:["initial","ice_restart","full_reconnect"]}]),$i=y("gem.partyRequest",[{n:"requestId",k:"string",max:64}]),Ui=y("gem.ready",[]),Hi=y("gem.engaged",[]),Wi=y("gem.progress",[{n:"loaded",k:"int",lo:0,hi:1099511627776},{n:"total",k:"int",lo:0,hi:1099511627776}]),Vi=y("gem.requestToken",[{n:"requestId",k:"string",max:64},{n:"reason",k:"enum",v:["initial","expiring","rejected"]}]),Bi=y("gem.requestLocalServer",[{n:"requestId",k:"string",max:64},{n:"gameRoomId",k:"string",max:64}]),Ki=y("gem.localServer",[{n:"requestId",k:"string",max:64},{n:"serverId",k:"string",o:1,max:128}]),Ji=y("gem.localServer.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"reason",k:"enum",v:["refused","unavailable"]}]),Xi=y("gem.exit",[{n:"reason",k:"string",o:1,max:64}]),Yi=y("gem.openExternal",[{n:"url",k:"string",max:2048,f:"url"}]),zi=y("gem.requestFullscreen",[{n:"enabled",k:"boolean"}]),Qi=y("gem.audioState",[{n:"muted",k:"boolean"}]),Zi=y("gem.rewardCue",[{n:"currencySlug",k:"string",max:32},{n:"expected",k:"int",o:1,lo:1,hi:1e9},{n:"origin",k:"object",o:1,fs:[{n:"x",k:"int",lo:0,hi:16384},{n:"y",k:"int",lo:0,hi:16384}]}]),eo=y("gem.walletDisplay",[{n:"visible",k:"boolean"},{n:"currencies",k:"array",o:1,max:8,it:{n:"",k:"string",max:64}},{n:"score",k:"boolean",o:1}]),to=y("gem.menu",[{n:"settings",k:"boolean"},{n:"items",k:"array",o:1,max:4,it:{n:"",k:"object",fs:[{n:"id",k:"string",max:32},{n:"label",k:"string",max:40}]}}]),no=y("gem.menuSelect",[{n:"entry",k:"enum",v:["settings","item"]},{n:"id",k:"string",o:1,max:32}]),ro=y("gem.requestShare",[{n:"params",k:"array",max:16,it:{n:"",k:"object",fs:[{n:"key",k:"string",max:64},{n:"value",k:"string",max:512}]}}]),io=y("gem.vibrate",[{n:"pattern",k:"array",max:99,it:{n:"",k:"int",lo:0,hi:1e4}}]),oo=y("gem.frameStats",[{n:"fps",k:"int",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"int",lo:0,hi:1e5}]),ao=y("gem.portraitBorders",[{n:"name",k:"string",o:1,max:40}]),so=y("gem.error",[{n:"code",k:"enum",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"string",o:1,max:256}]),lo=y("gem.requestPurchase",[{n:"requestId",k:"string",max:64},{n:"purchaseKind",k:"enum",v:["item","recipe"]},{n:"targetId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"quantity",k:"int",o:1,lo:1,hi:10},{n:"catalogId",k:"string",o:1,max:64}]),co=y("gem.purchaseResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["ok","declined","unavailable"]},{n:"reason",k:"string",o:1,max:64,f:"code"},{n:"purchaseId",k:"string",o:1,max:64}]),uo=y("gem.deviceSettings.put",[{n:"requestId",k:"string",max:64},{n:"settings",k:"json"}]),mo=y("gem.deviceSettings.result",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["stored","too_large","unavailable"]}]),po=y("gem.requestAd",[{n:"requestId",k:"string",max:64},{n:"placement",k:"string",max:32},{n:"format",k:"enum",v:["interstitial","rewarded"]}]),ho=y("gem.adResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["shown","no_ad","unavailable"]}]),go=y("gem.requestSignIn",[{n:"requestId",k:"string",max:64}]),fo=y("gem.signInResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["signed_in","declined","unavailable"]}]),yo=y("gem.requestFriendChallenge",[{n:"requestId",k:"string",max:64},{n:"playerId",k:"string",max:64},{n:"template",k:"string",max:64},{n:"params",k:"json",o:1}]),vo=y("gem.friendChallengeResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"string",o:1,max:64},{n:"param",k:"string",o:1,max:64},{n:"channel",k:"string",o:1,max:16},{n:"configVersion",k:"int",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"int",o:1,lo:0,hi:864e5},{n:"detail",k:"string",o:1,max:300}]),se=jt({"gem.handshake":hi,"gem.handshake.accept":gi,"gem.token":fi,"gem.token.denied":yi,"gem.player":vi,"gem.pause":bi,"gem.prefs":wi,"gem.cohorts":ki,"gem.earnAllowanceChanged":Si,"gem.viewport":Ri,"gem.deviceSettings":_i,"gem.willTerminate":Ei,"gem.roomEvent":xi,"gem.socketState":Ti,"gem.seatedEvent":Ai,"gem.autoStartFailedEvent":Ii,"gem.signalEvent":Ci,"gem.dedicatedEvent":Pi,"gem.partyResult":Mi,"gem.clusterTarget":Li,"gem.devtools":Oi,"gem.screenshot":Di,"gem.screenshot.denied":Gi,"gem.requestContext":Fi,"gem.gameContext":ji,"gem.signal":Ni,"gem.dedicatedOffer":qi,"gem.partyRequest":$i,"gem.ready":Ui,"gem.engaged":Hi,"gem.progress":Wi,"gem.requestToken":Vi,"gem.requestLocalServer":Bi,"gem.localServer":Ki,"gem.localServer.denied":Ji,"gem.exit":Xi,"gem.openExternal":Yi,"gem.requestFullscreen":zi,"gem.audioState":Qi,"gem.rewardCue":Zi,"gem.walletDisplay":eo,"gem.menu":to,"gem.menuSelect":no,"gem.requestShare":ro,"gem.vibrate":io,"gem.frameStats":oo,"gem.portraitBorders":ao,"gem.error":so,"gem.requestPurchase":lo,"gem.purchaseResult":co,"gem.deviceSettings.put":uo,"gem.deviceSettings.result":mo,"gem.requestAd":po,"gem.adResult":ho,"gem.requestSignIn":go,"gem.signInResult":fo,"gem.requestFriendChallenge":yo,"gem.friendChallengeResult":vo});var tt=3;function U(n){if(typeof n!="string")return;let e=n.trim();return e.length===0?void 0:e}function ve(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=U(t);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var bo=2e3,wo=5e3;function ko(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 s,a=new Promise(d=>{let l=false,p=null;s=c=>{l||(l=true,r=null,n.clock.clearTimeout(p),d(c));},p=n.clock.setTimeout(()=>{t=true,s([]);},n.timeoutMs??bo);});return r={promise:a,settle:s},a};return {resolveList:o,resolve(){return e.length>0||t||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):o().then(s=>s[0])},refresh(s){return !Un(e,s)||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let d=null,l=p=>{i.delete(l)&&(n.clock.clearTimeout(d),a(p));};i.set(l,s),d=n.clock.setTimeout(()=>l(e),n.refreshTimeoutMs??wo);})},accept(s,a){let d=ve(a),l=U(s),p=d.length>0?d:l===void 0?[]:[l];if(p.length!==0){e=p,r?.settle(p);for(let[c,m]of [...i])Un(p,m)||c(p);}}}}function Un(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var So=/^[a-z0-9][a-z0-9_-]{0,39}$/;function Nt(n){return typeof n=="string"&&So.test(n)}function Hn(n){if(n===null||Nt(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 Le=16384,nt=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 be(...n){return e=>typeof e=="string"&&n.includes(e)?e:void 0}function Wn(n){return typeof n=="boolean"?n:void 0}var O=R(64),Oe=ee(0,2147483647);function qt(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(e.length>=64)break;let r=O(t);typeof r=="string"&&e.push(r);}return e}function x(n,e,t){return {to:n,from:e,read:t,required:true}}function _(n,e,t){return {to:n,from:e,read:t,required:false}}function we(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 De(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 Vn=[x("sdp","sdp",R(10240)),x("signaling_intent","intent",be("initial","ice_restart","full_reconnect"))];function rt(n,e,t){if(typeof t!="object"||t===null||Array.isArray(t))return {reason:"offer: data must be an object"};let r=t,i=we(r,Vn);return i===null?{reason:`offer: '${Vn.find(s=>s.read(r[s.from])===void 0)?.from??"?"}' is missing or out of bounds`}:{frame:{type:"webrtc_offer",match_id:n,game_id:e,...i}}}var $t=Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"})),Ro=new Set(["error"]),_o=Object.freeze(Object.assign(Object.create(null),{answer:[x("sdp","sdp",R(10240)),_("sessionId","session_id",R(64))],error:[_("code","code",R(64)),_("message","message",R(256))],matchEnded:[_("reason","reason",R(64))]}));function it(n,e,t){let r=De(n);if(r===null)return null;let i=$t[r.type];if(i===void 0)return null;let o=O(r.data.match_id);if(typeof o!="string"||!(Ro.has(i)?t(o):r.data.game_id===e))return null;let a=we(r.data,_o[i]??[]);return a===null?null:{event:i,matchId:o,...a}}var Eo=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=be("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}}},xo=Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[x("sdp","sdp",R(10240)),x("signaling_intent","intent",be("initial","ice_restart","full_reconnect")),_("sdp_hash","sdpHash",R(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[x("peer_id","peerId",O),x("sdp","sdp",R(10240)),x("assigned_peer_id","assignedPeerId",ee(0,4294967295)),_("sdp_hash","sdpHash",R(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[x("peer_id","peerId",O),x("candidate","candidate",R(512)),_("sdp_mid","sdpMid",R(64)),_("sdp_mline_index","sdpMLineIndex",ee(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[x("host_epoch","hostEpoch",Oe)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[x("host_epoch","hostEpoch",Oe),_("evidence","evidence",Eo)]}}));function ot(n,e,t,r){let i=xo[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,s=we(o,i.args);if(s===null){let a=i.args.find(d=>d.required&&d.read(o[d.from])===void 0);return {reason:`${n}: '${a?.from??"?"}' is missing or out of bounds`}}return {frame:{type:i.type,match_id:e,...i.gameScoped?{game_id:t}:{},...s}}}var To=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"})),Ao=new Set(["error"]),Io=Object.freeze(Object.assign(Object.create(null),{hello:[x("playerId","player_id",O),x("hostPlayerId","host_player_id",O),x("hostEpoch","host_epoch",Oe),_("members","members",qt)],offer:[x("fromPlayerId","from_player_id",O),x("sdp","sdp",R(10240)),_("sessionId","signaling_session_id",R(128)),_("sdpHash","sdp_hash",R(128)),_("iceUfrag","ice_ufrag",R(64)),_("intent","signaling_intent",be("initial","ice_restart","full_reconnect"))],answer:[x("fromPlayerId","from_player_id",O),x("sdp","sdp",R(10240)),_("sessionId","signaling_session_id",R(128)),_("sdpHash","sdp_hash",R(128)),_("iceUfrag","ice_ufrag",R(64)),_("assignedPeerId","assigned_peer_id",ee(0,4294967295))],ice:[x("fromPlayerId","from_player_id",O),x("candidate","candidate",R(512)),_("sdpMid","sdp_mid",R(64)),_("sdpMLineIndex","sdp_m_line_index",ee(0,255)),_("sdpMLineIndexAlt","sdp_mline_index",ee(0,255))],peerJoined:[x("playerId","player_id",O)],peerLeft:[x("playerId","player_id",O),_("reason","reason",R(64))],migration:[x("hostPlayerId","new_host_player_id",O),x("hostEpoch","host_epoch",Oe),_("reason","reason",R(64)),_("kickedPlayerIds","kicked_player_ids",qt),_("migrationComplete","migration_complete",Wn)],matchEnded:[_("reason","reason",R(64))],error:[_("code","code",R(64)),_("message","message",R(256))]}));function at(n,e,t){let r=De(n);if(r===null)return null;let i=To[r.type];if(i===void 0)return null;let o=O(r.data.match_id);if(typeof o!="string"||!(Ao.has(i)?t(o):r.data.game_id===e))return null;let a=we(r.data,Io[i]??[]);return a===null?null:{event:i,matchId:o,data:a}}var Co=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 Ge(n){let e=De(n);if(e===null)return null;let t=Co[e.type];if(t===void 0)return null;let r=e.data,i=O(r.party_id);if(typeof i!="string")return null;let o=ee(0,Number.MAX_SAFE_INTEGER)(r.version),s=O(r.game_room_id),a=O(r.game_id),d=O(r.inviter_player_id),l=R(80)(r.inviter_display_tag),p=R(64)(r.party_name);return {event:t,partyId:i,...o===void 0?{}:{version:o},...s===void 0?{}:{gameRoomId:s},...a===void 0?{}:{gameId:a},...d===void 0?{}:{inviterPlayerId:d},...l===void 0?{}:{inviterDisplayTag:l},...p===void 0?{}:{partyName:p}}}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=Qe[e];if(t===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??t,s=Math.max(0,r-i),a=Math.min(t,o+s*t/6e4);return a<1?(this.tokens.set(e,a),this.lastRefill.set(e,r),false):(this.tokens.set(e,a-1),this.lastRefill.set(e,r),true)}};function Se(n,e){return n.toLowerCase()===e.toLowerCase()}function st(n){let e=n.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function Kn(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:st(t.hostname)&&st(r.hostname)}function Ut(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 Po=7,Mo=["universal","mobile"],Lo={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"},Oo=new Set(["match_ended","p2p_match_ended"]),Do="game_room_auto_start_failed",Go=/^[a-z][a-z0-9_]{0,63}$/,Fe=64,Fo=8,Wt=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 dt(n){if(!(typeof n!="string"||n.length===0||n.length>Fe))return n}function jo(n){return n instanceof Error?n.message:String(n)}function Xn(n,e){if(!n.has(e)){if(n.size>=Fo){let t=n.values().next().value;t!==void 0&&n.delete(t);}n.add(e);}}function Ht(){return new MessageChannel}var No=6e4/(Qe["gem.handshake"]??1),qo=6e4,Vt=class{constructor(e){this.options=e;if(!et(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(!et(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 Wt(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 ${Ft}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.`);},Ft);}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:g,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());},No);}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 Se(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:g,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=Lo[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=dt(i.game_room_id);if(o===void 0)return false;let s=Oo.has(t.type)?void 0:dt(i.match_id);s!==void 0&&this.rememberMatch(s);let a=typeof i.version=="number"?i.version:void 0,d=typeof i.reason=="string"?i.reason.slice(0,Fe):void 0,l=r==="version_stale"&&Mo.includes(i.platform)?i.platform:void 0;return this.sendRoomEvent({event:r,roomId:o,...s===void 0?{}:{matchId:s},...a===void 0?{}:{version:a},...d===void 0?{}:{reason:d},...l===void 0?{}:{platform:l}})}sendRoomEvent(e){return this.frameSupports("rooms")?this.send({gem:g,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:g,type:"gem.socketState",connected:e.connected,...e.connected?{}:{reason:e.reason}}):false}sendSeatedEvent(e){return this.frameSupports("partySeating")?this.send({gem:g,type:"gem.seatedEvent",roomId:e}):false}relaySeatedEvent(e){if(this.gameId===null)return false;let t=Ge(e);if(t===null||t.event!=="gameRoomJoined"||t.gameId!==this.gameId)return false;let r=dt(t.gameRoomId);return r===void 0?false:this.sendSeatedEvent(r)}sendAutoStartFailedEvent(e){return this.frameSupports("autoStartFailure")?this.send({gem:g,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!==Do||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=dt(r.game_room_id),o=typeof r.code=="string"&&Go.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=Ge(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=at(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:g,type:"gem.signalEvent",event:e.event,matchId:e.matchId,data:e.data}):false}relayDedicatedEvent(e){if(this.gameId===null)return false;let t=it(e,this.gameId,r=>this.knowsMatch(r));return t===null?false:this.sendDedicatedEvent(t)}sendDedicatedEvent(e){return this.frameSupports("dedicated")?this.send({gem:g,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){Xn(this.knownMatches,e);}rememberAsked(e){Xn(this.askedMatches,e);}answerPartyRequest(e,t){return this.send({gem:g,type:"gem.partyResult",requestId:e,...t===void 0?{}:{partyId:t}})}answerPurchase(e,t,r,i){return this.send({gem:g,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:g,type:"gem.deviceSettings.result",requestId:e,outcome:t})}sendDeviceSettings(e){return this.frameSupports("deviceSettings")?this.send({gem:g,type:"gem.deviceSettings",...e===void 0?{}:{settings:e}}):false}sendMenuSelect(e){return this.frameSupports("gameMenu")?this.send(e==="settings"?{gem:g,type:"gem.menuSelect",entry:"settings"}:{gem:g,type:"gem.menuSelect",entry:"item",id:e.id}):false}answerAd(e,t){return this.send({gem:g,type:"gem.adResult",requestId:e,outcome:t})}answerSignIn(e,t){return this.send({gem:g,type:"gem.signInResult",requestId:e,outcome:t})}answerFriendChallenge(e,t,r={}){let i={};if(t==="invalid"){let{code:o,param:s,channel:a,configVersion:d,detail:l}=r;typeof o=="string"&&o.length<=64&&(i.code=o),typeof s=="string"&&s.length<=64&&(i.param=s),typeof a=="string"&&a.length<=16&&(i.channel=a),typeof d=="number"&&Number.isSafeInteger(d)&&d>=0&&(i.configVersion=d),typeof l=="string"&&(i.detail=l.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:g,type:"gem.friendChallengeResult",requestId:e,outcome:t,...i})}denyToken(e){this.send({gem:g,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:g,type:"gem.localServer",requestId:e.requestId,...e.serverId===void 0?{}:{serverId:e.serverId}}):false}denyLocalServer(e){return this.frameSupports("localHost")?this.send({gem:g,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>Fe):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 ${Fe} 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:g,type:"gem.clusterTarget",clusterTargetId:i,...typeof e=="string"?{}:{clusterTargetIds:[...t]}})}sendPlayer(e){let{displayName:t,displayTag:r}=e.untrusted,i=e.badges?.map(({itemId:a,iconUrl:d})=>({itemId:a,iconUrl:d})),o=e.boost&&{multipliers:e.boost.multipliers.map(({currencyId:a,currencySlug:d,multiplierBp:l})=>({currencyId:a,currencySlug:d,multiplierBp:l})),...e.boost.expiresInDays===void 0?{}:{expiresInDays:Math.min(Po,e.boost.expiresInDays)}},s=e.discriminator!==void 0&&/^[0-9]{1,8}$/.test(e.discriminator)?e.discriminator:void 0;this.send({gem:g,type:"gem.player",untrusted:{displayName:t,...r===void 0?{}:{displayTag:r},displayHandle:r??t},...e.playerId===void 0?{}:{playerId:e.playerId},...s===void 0?{}:{discriminator:s},...e.avatarIconUrl===void 0?{}:{avatarIconUrl:e.avatarIconUrl},...i===void 0?{}:{badges:i},...o===void 0?{}:{boost:o},displayTag:s??"",...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:g,type:"gem.pause",paused:e});}sendDevtools(e){this.send({gem:g,type:"gem.devtools",action:e});}requestScreenshot(e,t){return this.frameSupports("screenshot")?this.send({gem:g,type:"gem.screenshot",maxWidth:t.maxWidth,maxHeight:t.maxHeight},[e]):false}requestContext(){return this.frameSupports("feedbackContext")?this.send({gem:g,type:"gem.requestContext"}):false}sendPrefs(e){this.send({gem:g,type:"gem.prefs",...e});}sendCohorts(e){return this.frameSupports("cohorts")?this.send({gem:g,type:"gem.cohorts",cohorts:e.map(t=>({experimentId:t.experimentId,variantKey:t.variantKey}))}):false}sendEarnAllowanceChanged(){return this.frameSupports("earnAllowance")?this.send({gem:g,type:"gem.earnAllowanceChanged"}):false}sendViewport(e){if(!this.frameSupports("viewport"))return false;let t=(e.reserved??[]).map(({x:o,y:s,width:a,height:d})=>({x:o,y:s,width:a,height:d})),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:g,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:g,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=se[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=se[r];if(!i){this.refuseMalformed("unsupported",`unknown message type ${JSON.stringify(r.slice(0,Fe))}`);return}if(!this.inbound.allow(r)){this.fail("rate_limited",`frame exceeded the limit for ${r}`);return}let o=Ze(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 s=i(e);if(s){this.fail("invalid_message",`${r}: ${s}`);return}let a=e;r!=="gem.handshake.accept"&&!this.versionMatches(a,r)||this.dispatch(r,a,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=ot(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=rt(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: ${jo(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):Nt(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.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((s,a)=>s+a,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 le(n){return new W(n)}var $o={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 Yn(n){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function Uo(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 Ho(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(s=>s.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 zn(n,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function Wo(n){let e=n.untrusted,t=le(e.displayName),r=e.displayTag||e.displayHandle,i=r?le(r):void 0,o=n.discriminator||n.displayTag,s=o&&/^[0-9]{1,8}$/.test(o)?o:void 0,a=n.avatarIconUrl||n.avatarUrl,d={displayName:t,displayHandle:i??t,badges:(n.badges??[]).map(m=>({itemId:m.itemId,iconUrl:m.iconUrl}))};n.playerId&&(d.playerId=n.playerId),s&&(d.discriminator=s),i&&(d.displayTag=i),a&&(d.avatarIconUrl=d.avatarUrl=a);let l=n.boost,p=(l?.multipliers??[]).map(m=>({currencyId:m.currencyId,currencySlug:m.currencySlug,multiplier:m.multiplierBp/1e4})),c=p.some(m=>m.multiplier>1);return d.boost=c&&l?.expiresInDays?{active:c,multipliers:p,expiresInDays:l.expiresInDays}:{active:c,multipliers:p},d}var Vo=1e4,Bt=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(a=>Se(a,e.origin))||Kn(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=se["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!Se(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 s=Ut(Z,i.versions);return s===null?(o.onmessage=null,o.postMessage({gem:g,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=s,o.onmessage=a=>this.receive(a.data,a.ports??[]),o.start?.(),this.peerCapabilities=i.capabilities??[],this.unbidden=i.unbidden===true,o.postMessage({gem:g,type:"gem.handshake.accept",v:s,...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:g,type:"gem.ready"});}settled(e=Vo){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:g,type:"gem.progress",loaded:e,total:t});}requestToken(e,t){this.send({gem:g,type:"gem.requestToken",requestId:e,reason:t});}requestLocalServer(e,t){return this.parentSupports("localHost")?(this.send({gem:g,type:"gem.requestLocalServer",requestId:e,gameRoomId:t}),true):false}exit(e){this.send(e===void 0?{gem:g,type:"gem.exit"}:{gem:g,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:g,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:g,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:g,type:"gem.audioState",muted:e}),true)}reportEngaged(){return this.engagedSent||this.state!=="connected"||!this.parentSupports("engagement")||!this.send({gem:g,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let t={gem:g,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:Yn(e.origin.x),y:Yn(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:g,type:"gem.portraitBorders"}:{gem:g,type:"gem.portraitBorders",name:t})}setWalletVisible(e,t){return this.state!=="connected"||!this.parentSupports("walletDisplay")?false:this.send({gem:g,type:"gem.walletDisplay",...Uo(e,t?.only)})}setMenu(e,t){return this.state!=="connected"||!this.parentSupports("gameMenu")?false:this.send({gem:g,type:"gem.menu",...Ho(e,t)})}requestShare(e){return this.state!=="connected"||!this.parentSupports("share")?false:this.send({gem:g,type:"gem.requestShare",params:e.map(({key:t,value:r})=>({key:t,value:r}))})}requestVibrate(e){return this.state!=="connected"||!this.parentSupports("vibration")?false:this.send({gem:g,type:"gem.vibrate",pattern:[...e]})}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:g,type:"gem.frameStats",fps:zn(e.fps,1e3),frameTimeP95Ms:zn(e.frameTimeP95Ms,1e5)}),true)}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:g,type:"gem.gameContext",context:e}),true)}signal(e,t,r){this.send({gem:g,type:"gem.signal",signal:e,matchId:t,data:r});}dedicatedOffer(e,t,r){this.send({gem:g,type:"gem.dedicatedOffer",matchId:e,sdp:t,intent:r});}requestParty(e){return this.send({gem:g,type:"gem.partyRequest",requestId:e})}requestPurchase(e,t,r,i,o,s){return this.send({gem:g,type:"gem.requestPurchase",requestId:e,purchaseKind:t,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...s===void 0?{}:{catalogId:s}})}putDeviceSettings(e,t){return this.send({gem:g,type:"gem.deviceSettings.put",requestId:e,settings:t})}requestAd(e,t,r){return this.send({gem:g,type:"gem.requestAd",requestId:e,placement:t,format:r})}requestSignIn(e){return this.send({gem:g,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,t,r,i){return this.send({gem:g,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:g,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=se[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||Qn(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=se[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=Ze(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 s=i(e);if(s)return this.fail("invalid_message",`${r}: ${s}`),false;let a=e;if(a.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(a);break;case "gem.pause":this.options.onPause?.(a);break;case "gem.menuSelect":this.options.onMenuSelect?.(a);break;case "gem.prefs":this.options.onPrefs?.(a);break;case "gem.cohorts":this.options.onCohorts?.(a);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(a);break;case "gem.willTerminate":this.options.onWillTerminate?.(a);break;case "gem.devtools":this.options.onDevtools?.(a.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let d=t[0];if(!d){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let l={maxWidth:a.maxWidth,maxHeight:a.maxHeight};if(!this.options.onScreenshot){d.close(),this.screenshotDenied("not_wired",false);break}return Qn(t.slice(1)),this.options.onScreenshot(l,d,(p,c)=>this.screenshotDenied(p,c)),true}case "gem.token.denied":this.options.onTokenDenied?.(a);break;case "gem.localServer":this.options.onLocalServer?.(a);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(a);break;case "gem.player":{this.options.onPlayer?.(Wo(a));break}case "gem.roomEvent":this.options.onRoomEvent?.(a);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(a);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(a);break;case "gem.socketState":this.options.onSocketState?.(a);break;case "gem.signalEvent":this.options.onSignalEvent?.(a);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(a);break;case "gem.clusterTarget":this.options.onClusterTarget?.(a);break;case "gem.partyResult":this.options.onPartyResult?.(a);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(a);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(a);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(a);break;case "gem.adResult":this.options.onAdResult?.(a);break;case "gem.signInResult":this.options.onSignInResult?.(a);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(a);break;case "gem.error":this.options.onError?.(a.code,a.message);break;default:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,t){this.send({gem:g,type:"gem.screenshot.denied",reason:e,retryable:t});}};function Qn(n){for(let e of n)try{e?.close?.();}catch{}}var Bo=16384;function Ko(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:Jo(e)}function Jo(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 Zn=["p2p","dedicated","unknown"],lt=["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=Xo(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 Xo(n,e,t){let r=Math.floor(t/1e3);return n.filter(i=>lt.includes(i.type)).slice(0,100).map(i=>{let o=Yo(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:i.value===void 0?{}:{value:i.value}}})}function Yo(n){if(n!==void 0)return Zn.includes(n)?n:"unknown"}function Kt(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 H=class extends Error{constructor(t,r,i,o,s){super(`${t} (${r}): ${i}`);this.reason=t;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=s;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}};var Qo=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),u=class extends Error{constructor(t,r,i){super(`${t}: ${r}`,i);this.reason=t;this.name="DedicatedServerError",this.retryable=Qo.has(t),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var er=["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"],Zo=new Set(er);function Re(n){return typeof n=="string"&&Zo.has(n)?n:"unknown"}var je="webrtc_dedicated",Xt=["universal","mobile","web"];var ea="p2p_unavailable",ta="capacity_unavailable",na=2,tr=3e4,nr=1e3,rr=2e4;async function ct(n){let e=U(n.clusterTargetId),t=n.nextClusterTarget,r=0,i=n.clock??re,o=n.retry??{},s=o.budgetMs??tr,a=o.maxDelayMs??rr,d=o.initialDelayMs??nr,l=i.now(),p=l+s,c=0;for(;;){c++;try{let m=await zt(n.signal,"while allocating",()=>n.client.post(`${ar(n)}/start_match`,e===void 0?{}:{cluster_target_id:e},n.signal));return {matchId:m.match_id,status:m.status}}catch(m){if(!ra(m)||s<=0)throw m;if(m.status===503&&m.code===ea)throw new u("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: ${m.message}`,{cause:m});if(r=m.code===ta?r+1:0,t!==void 0&&r>=na){let M=t;t=void 0;let C=U(await M());C!==void 0&&(e=C,r=0);}let f=Math.min(a,d*2**(c-1)),v=Math.min(a,(m.retryAfterSeconds??0)*1e3),A=Math.max(f/2,v)+Math.random()*(f/2);if(i.now()+A>p)throw ia(n,m,c,i.now()-l,s);if(o.onWaiting?.({attempt:c,elapsedMs:i.now()-l,budgetMs:s,nextAttemptInMs:A,status:m.status,message:m.message}),await pt(i,A,n.signal),n.signal?.aborted)throw Jt("while waiting to allocate")}}}function ra(n){return n instanceof H?n.status===503?true:n.status===429&&n.code!=="too_many_concurrent_matches":false}function ia(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 u("start_rate_limited",`the platform was still limiting match starts for room ${n.roomId} after ${o}: ${e.message}`,{cause:e}):new u("no_server_ready",`the platform had no server ready for room ${n.roomId} after ${o}: ${e.message}`,{cause:e})}var oa=12e4,aa=1e3;async function ut(n){let{clock:e,matchId:t}=n,r=n.pollIntervalMs??aa,i=n.timeoutMs??oa,o=e.now()+i,s=ir(n),a={seen:n.knownToExist===true};for(;;){let d=await or(n,s,a);if(d.outcome!==null)return d.outcome;if(e.now()+r>o)throw new u("timeout",`match ${t} was still ${d.status} after ${i}ms`);await pt(e,r,n.signal);}}async function Yt(n){return (await or(n,ir(n),{seen:n.knownToExist===true})).outcome}function ir(n){let e=new URLSearchParams({platform:n.version.platform,game_version:n.version.gameVersion});return `${ar(n)}/matches/${encodeURIComponent(n.matchId)}/status?${e}`}async function or(n,e,t){let{matchId:r}=n,i=n.clock.now(),o;try{o=await zt(n.signal,"while polling match status",()=>n.client.get(e,n.signal));}catch(s){if(s instanceof H&&s.reason==="not_found")return {status:"not_found",outcome:t.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw s}if(t.seen=true,o.status==="ready")return {status:"ready",outcome:sa(r,o,i)};if(o.status==="failed"){let s=o.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:Re(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function mt(n){let e=await zt(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 zt(n,e,t){if(n?.aborted)throw Jt(e);try{return await t()}catch(r){throw n?.aborted?Jt(e,r):r}}function Jt(n,e){return new u("aborted",`the caller aborted ${n}`,e===void 0?void 0:{cause:e})}function sa(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 ar(n){return `/v1/games/${encodeURIComponent(n.gameId)}/game-rooms/${encodeURIComponent(n.roomId)}`}function pt(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 da=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),Zt="embedder_relay_unavailable",la="embedder_no_relay",ca=new Set([Zt]),en=new Set([la]),ht=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new Qt(this)}handleEvent(e){let t=this.pending.get(e.matchId);if(t!==void 0){if(e.event==="matchEnded"){t.refuse(new u("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 u("signaling_failed","the parent relayed an answer with no SDP in it"));return}t.settle({sdp:e.sdp});return}t.refuse(ua(e.code,e.message));}}register(e,t){this.pending.get(e)?.refuse(new u("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 u("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 u("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 ua(n,e){let t=e??"the offer was refused",r=n===void 0?t:`${t} (${n})`;return new u(ma(n),r,{platformCode:n})}function ma(n){return n===void 0||ca.has(n)?"signaling_failed":en.has(n)?"offer_refused":da.has(n)?n==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var Qt=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,t){if(this.closed)return Promise.reject(new u("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 u("aborted","the caller aborted before the offer was sent")):new Promise((i,o)=>{let s=()=>{a(),o(new u("aborted","the caller aborted the signaling exchange"));},a=()=>{t?.removeEventListener("abort",s),this.hub.release(e.matchId,d),this.teardown===a&&(this.teardown=null);},d={settle:l=>{a(),i(l);},refuse:l=>{a(),o(l);}};this.teardown=a,t?.addEventListener("abort",s),this.hub.register(e.matchId,d);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(l){d.refuse(l instanceof u?l:new u("signaling_failed",l instanceof Error?l.message:String(l),{cause:l}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var sr="match_ended:",dr="server_shutdown:",lr="kicked:",pa=123;function ha(n){if(typeof n!="string"||n.length===0||n.length>pa)return {kind:"other"};if(n.startsWith(sr)){let e=Re(n.slice(sr.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return n.startsWith(dr)?{kind:"server_shutdown",cause:n.slice(dr.length)}:n.startsWith(lr)?{kind:"kicked",detail:n.slice(lr.length)}:{kind:"other"}}function tn(n,e,t){let r=ha(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 ga="join",fa="welcome",ya="rejected",nn=25e3,va=1e3,rn=1;function on(n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0}var ba={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 an(n){let e=typeof n=="string"?n:"unknown";return new u(ba[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function Ne(n){let{channel:e,clock:t}=n;return new Promise((r,i)=>{let o=false,s=Math.min(n.credentialExpiresAt-t.now(),n.ceilingMs??nn),a=t.setTimeout(()=>T(new u("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(s,va)),d=A=>{let M=A.data;if(typeof M!="string"){c(M);return}let C;try{C=JSON.parse(M);}catch{c(M);return}if(o){c(M);return}if(C.t===fa){let h=on(C.heartbeat_interval);v({...typeof C.player_id=="string"?{playerId:C.player_id}:{},...typeof C.match_id=="string"?{matchId:C.match_id}:{},...h===void 0?{}:{heartbeatIntervalMs:h}});return}if(C.t===ya){T(an(C.reason));return}c(M);},l=()=>{T(new u("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},p=()=>{T(new u("aborted","the caller aborted during the join exchange"));},c=A=>{o&&n.onMessage?.(A);},m=()=>{t.clearTimeout(a),e.removeEventListener("close",l),n.signal?.removeEventListener("abort",p);},f=()=>{e.removeEventListener("message",d);},v=A=>{o=true,m(),n.onMessage===void 0&&f(),r({welcome:A,detach:f});},T=A=>{o||(o=true,m(),f(),i(A));};if(e.addEventListener("message",d),e.addEventListener("close",l),n.signal?.aborted){p();return}n.signal?.addEventListener("abort",p);try{e.send(JSON.stringify({t:ga,credential:n.credential,...n.wire===void 0?{}:{wire:n.wire},...n.heartbeat===!0?{heartbeat:rn}:{}}));}catch(A){T(new u("connection_failed",`the join frame could not be sent on the open channel: ${String(A)}`,{cause:A}));}})}function gt(){return {exchange(){return Promise.reject(new u("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,qe=2,sn=4,cn=8,wa=2,ka=1e3,un="heartbeat timeout",ft="gem-uu",yt=2,ur="gem_transports";function $e(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){if(typeof t!="string")continue;let r=t.toLowerCase();!Sa(r)||e.includes(r)||e.push(r);}return e}function Sa(n){return n==="webtransport"||n==="webrtc"||n==="websocket"}function vt(n,e){if(typeof n!="object"||n===null)return null;let t=n[ur];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 bt(n){return n instanceof Error?n.message===""?n.name:`${n.name}: ${n.message}`:String(n)}var mr=new TextEncoder,pr=new TextDecoder;function mn(n,e){let t=new Uint8Array(e.byteLength+1);return t[0]=n,t.set(e,1),t}function pn(n){let e=0;return n?.reliable===false&&(e|=ue),n?.ordered===false&&(e|=qe),e}function hn(n){return {reliable:(n&ue)===0,ordered:(n&qe)===0}}var gn={reliable:true,ordered:true};function hr(n){return JSON.stringify({t:"join",credential:n,wire:yt,heartbeat:rn})}function gr(n){let e;try{e=JSON.parse(n);}catch{throw new u("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let t=on(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"?an(e.reason):new u("join_refused","the server answered the join out of protocol")}function fn(){return typeof globalThis.WebTransport=="function"&&yn===null}function wt(){return yn}var yn=null;var cr="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Ra(n){let e=Kt(n);if(e.byteLength!==32)throw new u("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var dn=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 u("connection_failed",`a control-stream record claims ${o} bytes`);if(this.buffered.byteLength<4+o)break;let s=this.buffered.slice(4,4+o);this.buffered=this.buffered.slice(4+o),r.push({flags:s[0]??0,payload:s.slice(1)});}return r}};function ln(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 a=globalThis.WebTransport;if(a===void 0)throw new u("connection_failed","this environment has no WebTransport");t=n.certHashBase64===void 0?new a(n.url):new a(n.url,{serverCertificateHashes:[{algorithm:"sha-256",value:Ra(n.certHashBase64)}]});}let r=t,i=a=>{try{r.close();}catch{}throw a},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(yn=cr,i(new u("connection_failed",`${cr}; the rung is skipped for the rest of this page (a reload probes again)`)));let s=new Promise((a,d)=>{setTimeout(()=>d(new u("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,s]);let a=r.incomingBidirectionalStreams.getReader(),d=await Promise.race([a.read(),s]);if(a.releaseLock(),d.done||d.value===void 0)return i(new u("connection_failed","the session ended before the control stream arrived"));let l=d.value,p=l.writable.getWriter();await p.write(ln(sn,mr.encode(hr(n.credential))));let c=new dn,m=l.readable.getReader(),f;for(;f===void 0;){let v=await Promise.race([m.read(),s]);if(v.done||v.value===void 0)return i(new u("connection_failed","the control stream closed before the join was answered"));for(let T of c.push(v.value)){f=gr(pr.decode(T.payload));break}}return {link:_a(r,p,m,c,n.log??(v=>console.warn(v)),yr(f,n.clock)),welcome:f}}catch(a){return i(a)}}function _a(n,e,t,r,i,o){let s,a,d=false,l=v=>{if(!d){d=true,p.stop();try{n.close();}catch{}a?.(v);}},p=bn(o,()=>l(un)),c=(v,T)=>{p.heard(),(v&cn)===0&&s!==void 0&&((v&sn)!==0?s(pr.decode(T),gn):s(T,hn(v)));};(async()=>{try{for(;;){let v=await t.read();if(v.done||v.value===void 0)break;for(let T of r.push(v.value))c(T.flags,T.payload);}}catch{}l("stream closed");})();let m,f;try{let v=n.datagrams;if(v?.readable!==void 0&&v.writable!==void 0){let T=v.readable.getReader();f=v.writable.getWriter(),m=v,(async()=>{try{for(;;){let A=await T.read();if(A.done||A.value===void 0)break;let M=A.value;M.byteLength!==0&&c((M[0]??0)|ue|qe,M.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(v){m=void 0,f=void 0,i(`[gem] webtransport datagram lane unusable (${bt(v)}); unreliable sends ride the stream`);}return n.closed.then(v=>l(fr(v?.reason)??"session closed"),()=>l("session failed")),{transport:"webtransport",send(v,T){if(d)return;if(typeof v=="string"){e.write(ln(sn,mr.encode(v))).catch(()=>l("write failed"));return}let A=pn(T);if((A&ue)!==0&&f!==void 0){let M=mn(A,v),C=m?.maxDatagramSize;if(C===void 0||M.byteLength<=C){f.write(M).catch(()=>{});return}}e.write(ln(A,v)).catch(()=>l("write failed"));},onMessage(v){s=v;},onClose(v){a=v;},close(){l("closed");}}}function vn(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 u("connection_failed","this environment has no WebSocket"));t=new i(n.url);}let r=t;return r.binaryType="arraybuffer",new Promise((i,o)=>{let s=false,a=setTimeout(()=>{s||(s=true,r.close(),o(new u("timeout","websocket did not come up in time")));},e),d=f=>{s||(s=true,clearTimeout(a),r.close(),o(f));},l=()=>{r.send(hr(n.credential));},p=f=>{if(s)return;if(typeof f.data!="string"){d(new u("join_refused","the server sent binary before answering the join"));return}let v;try{v=gr(f.data);}catch(T){d(T);return}s=true,clearTimeout(a),r.removeEventListener("open",l),r.removeEventListener("message",p),r.removeEventListener("close",c),r.removeEventListener("error",m),i({link:Ea(r,yr(v,n.clock)),welcome:v});},c=()=>{d(new u("connection_failed","the websocket closed before the join was answered"));},m=()=>{d(new u("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",l),r.addEventListener("message",p),r.addEventListener("close",c),r.addEventListener("error",m),r.readyState===1&&l();})}function fr(n){return typeof n=="string"&&n.length>0?n:void 0}function yr(n,e){return n.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:n.heartbeatIntervalMs}}function bn(n,e){if(n===void 0)return {heard:()=>{},stop:()=>{}};let{clock:t}=n,r=Math.max(n.intervalMs,ka)*wa,i=t.now(),o=null,s=()=>{o=null;let a=t.now()-i;if(a>=r){e();return}o=t.setTimeout(s,r-a);};return o=t.setTimeout(s,r),{heard:()=>{i=t.now();},stop:()=>{o!==null&&(t.clearTimeout(o),o=null);}}}function Ea(n,e){let t,r,i=false,o=a=>{if(!i){i=true,s.stop();try{n.close();}catch{}r?.(a);}},s=bn(e,()=>o(un));return n.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){t?.(a.data,gn);return}let d=new Uint8Array(a.data);if(d.byteLength===0)return;let l=d[0]??0;(l&cn)===0&&t?.(d.slice(1),hn(l));})),n.addEventListener("close",(a=>o(fr(a?.reason)??"socket closed"))),{transport:"websocket",send(a,d){if(!i){if(typeof a=="string"){n.send(a);return}n.send(mn(pn(d),a));}},onMessage(a){t=a;},onClose(a){r=a;},close(){o("closed");}}}function wn(n,e,t,r){let i,o,s=false,a=t,d=c=>{if(!s){s=true,l.stop();try{n.close();}catch{}try{e.close();}catch{}o?.(c);}},l=bn(r,()=>d(un)),p=(c,m)=>{if(l.heard(),typeof c=="string"){i?.(c,gn);return}let f=new Uint8Array(c);if(f.byteLength===0)return;let v=f[0]??0;(v&cn)===0&&i?.(f.slice(1),hn(v|m));};if(n.addEventListener("message",(c=>p(c.data,0))),n.addEventListener("close",(()=>d("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let c=e.connectionState;(c==="failed"||c==="closed")&&d(`connection ${c}`);})),a!==void 0){let c=a;c.addEventListener("message",(m=>p(m.data,ue|qe))),c.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(c,m){if(s)return;if(typeof c=="string"){n.send(c);return}let f=pn(m),v=mn(f,c);if((f&ue)!==0&&a!==void 0&&a.readyState==="open"){a.send(v);return}n.send(v);},onMessage(c){i=c;},onClose(c){o=c;},close(){d("closed");}}}var vr=10240,br=2048,xa=new TextEncoder;function wr(n){return xa.encode(n).length}function ie(n,e){let t=i=>{throw new u("invalid_sdp",`the ${e} ${i}`)},r=wr(n);r>=vr&&t(`is ${r} bytes, over the ${vr} 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=wr(i);o>br&&t(`has a ${o}-byte line, over the ${br} limit`);}}function kt(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 Ta=3e3,Aa=1e4,Ia=15e3;async function He(n){let e=n.peerConnection;try{Sr(n,"before the handshake started"),kn(n);let t=e.createDataChannel(n.channelLabel??"gem",{ordered:!0});for(let s of n.extraChannels??[]){let a=e.createDataChannel(s.label,{...s.ordered===void 0?{}:{ordered:s.ordered},...s.maxRetransmits===void 0?{}:{maxRetransmits:s.maxRetransmits}});n.onExtraChannel?.(s.label,a);}let r=await e.createOffer();await e.setLocalDescription(r),await Ma(e,n),kn(n);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new u("invalid_sdp","the offer carried no SDP");ie(i,"offer"),kr(i,"offer");let o=await Pa(n,i);if(kn(n),typeof o?.sdp!="string")throw new u("invalid_sdp","the signaling channel answered without an SDP");return ie(o.sdp,"answer"),kr(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await La(t,n),Sr(n,"before the channel opened"),t}catch(t){throw e.close(),Ca(t)}}function Ca(n){return n instanceof u?n:Er(n)?me():new u("connection_failed",xr(n),{cause:n})}function kr(n,e){if(kt(n))throw new u("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 Pa(n,e){let t=n.exchangeTimeoutMs??Aa,r=_r(n,t),i=n.signaling.exchange({matchId:n.matchId,sdp:e,intent:n.intent??"initial"},n.signal).catch(o=>{throw o instanceof u?o:Er(o)?me():new u("signaling_failed",xr(o),{cause:o})});return Oa(i,n,r,()=>r.exhausted?Sn("while the offer was in flight"):new u("timeout",`no answer arrived within ${t}ms`))}function Ma(n,e){if(n.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:t}=e;return new Promise(r=>{let i=()=>{t.clearTimeout(s),n.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{n.iceGatheringState==="complete"&&i();},s=t.setTimeout(i,e.gatherTimeoutMs??Ta);n.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function La(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 u("connection_failed",`the data channel was already '${n.readyState}' when the answer was applied`));let{clock:t}=e,r=e.openTimeoutMs??Ia,i=_r(e,r);return new Promise((o,s)=>{let a=()=>{t.clearTimeout(m),n.removeEventListener("open",d),n.removeEventListener("close",l),n.removeEventListener("error",l),e.signal?.removeEventListener("abort",p);},d=()=>{a(),o();},l=f=>{a(),s(new u("connection_failed","the data channel failed before it opened",Rr(f)===void 0?void 0:{cause:Rr(f)}));},p=()=>{a(),s(me());},c=()=>{a(),s(i.exhausted?Sn("while the channel was still opening"):new u("timeout",`the data channel did not open within ${r}ms`));},m=t.setTimeout(c,i.ms);n.addEventListener("open",d),n.addEventListener("close",l),n.addEventListener("error",l),e.signal?.addEventListener("abort",p);})}function _r(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 Oa(n,e,t,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(me()):new Promise((s,a)=>{let d=c=>{i.clearTimeout(p),o?.removeEventListener("abort",l),c();},l=()=>d(()=>a(me())),p=i.setTimeout(()=>d(()=>a(r())),t.ms);o?.addEventListener("abort",l),n.then(c=>d(()=>s(c)),c=>d(()=>a(c)));})}function Sr(n,e){if(n.credentialExpiresAt!==void 0&&!(n.clock.now()<n.credentialExpiresAt))throw Sn(`already ${e}`)}function Sn(n){return new u("credential_expired",`the join credential ran out ${n} \u2014 poll match status again for a fresh one`)}function kn(n){if(n.signal?.aborted)throw me()}function me(){return new u("aborted","the caller aborted the connection attempt")}function Er(n){return n?.name==="AbortError"}function Rr(n){return n?.error}function xr(n){return n instanceof Error?n.message:String(n)}var We="0.1.0-beta",Tr="0-beta",_e="web",Da=/^(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 Ga(n){let e=Da.exec(n),t=e?.[1],r=e?.[4];return t===void 0?null:r===void 0?t:`${t}-${r}`}function Ar(n,e){let t=Fa(n.platform,e),r=n.engineVersion;if(r===void 0)return {...n,platform:t,engineVersion:We};let i=Ga(r);if(i===null)throw new u("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!==Tr)throw new u("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${Tr}' 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 Fa(n,e){if(n===void 0||n===_e)return _e;if(!Xt.includes(n))throw new u("misconfigured",`${e} refused: platform '${String(n)}' is not a client platform gem-api recognises \u2014 it knows ${Xt.map(t=>`'${t}'`).join(", ")}. Remove the field: the SDK reports '${_e}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${n}' was replaced with '${_e}' 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.`),_e}function ja(n){let{client:e,clock:t,rooms:r}=n,i=n.signaling??gt,o=n.log??(h=>console.warn(h)),s=new ce({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,d=(h,b)=>{let S=a.get(h)??new Set;S.add(b),a.set(h,S);},l=(h,b)=>{let S=a.get(h);S!==void 0&&(S.delete(b),S.size===0&&a.delete(h));},p=async h=>{if(r.isHost&&!Ka(r)&&r.currentRoom?.matchId===void 0){let b=U(h.clusterTargetId);await r.startMatch({...b===void 0?{}:{clusterTargetId:b},...h.retry===void 0?{}:{retry:h.retry},...h.signal===void 0?{}:{signal:h.signal}});}return Or(r.matchConnectionState==="suspended"?await r.reconnectToMatch(Rn(h)):await r.awaitMatch(Rn(h)))},c=async h=>Or(await r.pollMatchStatus(Rn(h))),m=async(h,b)=>{let S=false;try{let w=await p(h),D=r.currentRoom?.transports;if(D!==void 0&&!D.includes("webrtc"))throw new u("misconfigured",`the room template offers (${D.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 P=h.peerConnection??Dr();S=!0;let G=await He({peerConnection:P,signaling:b,clock:t,matchId:w.matchId,credentialExpiresAt:w.credentialExpiresAt,...St(h,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),N=null;if(h.presentCredential!==!1)try{N=await Ne({channel:G,clock:t,credential:w.joinCredential,credentialExpiresAt:w.credentialExpiresAt,...St(h,"onMessage","signal"),...h.welcomeTimeoutMs===void 0?{}:{ceilingMs:h.welcomeTimeoutMs}});}catch(q){throw K(G),K(P),q}return Ba(r,w,G,P,b,h.reportDisconnect!==!1,h.reportConnected!==!1,N,{remember:d,forget:l},h.onMatchEnded)}catch(w){throw S&&Lr(s,w),K(b),w}},f=async(h,b,S,w,D,P)=>{if(h==="webtransport"){let L=w?.webtransport;if(L===void 0)throw new u("misconfigured","webtransport is not advertised");let Y={credential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,clock:t};if(typeof L.named_url=="string"&&L.named_url!==""){let ne=Math.max(Math.floor(P/2),1e3);try{return await Ue({url:L.named_url,timeoutMs:ne,log:o,...Y})}catch(oe){if(wt()!==null)throw oe;return o(`[gem] webtransport named dial failed (${bt(oe)}); retrying the pinned dial`),Ue({url:L.url,certHashBase64:L.cert_sha256_b64,timeoutMs:ne,log:o,...Y})}}return Ue({url:L.url,certHashBase64:L.cert_sha256_b64,timeoutMs:P,...Y})}if(h==="websocket"){let L=w?.websocket;if(L===void 0)throw new u("misconfigured","websocket is not advertised");return vn({url:L.url,credential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,clock:t,timeoutMs:P})}let G=b.peerConnection??Dr(),N,q=await He({peerConnection:G,signaling:D,clock:t,matchId:S.matchId,credentialExpiresAt:S.credentialExpiresAt,extraChannels:[{label:ft,ordered:false,maxRetransmits:0}],onExtraChannel:(L,Y)=>{L===ft&&(N=Y);},...St(b,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...b.exchangeTimeoutMs===void 0&&b.redial===true?{exchangeTimeoutMs:qa}:{}}),B;try{B=await Ne({channel:q,clock:t,credential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,wire:yt,heartbeat:!0,...St(b,"signal"),...b.welcomeTimeoutMs===void 0?{}:{ceilingMs:b.welcomeTimeoutMs}});}catch(L){throw K(q),K(G),L}let E=B.welcome.heartbeatIntervalMs;return {link:wn(q,G,N,E===void 0?void 0:{clock:t,intervalMs:E}),welcome:B.welcome,channel:q,peerConnection:G}},v=(h,b,S,w,D)=>{let P=false,G;w.link.onClose(E=>{!P&&h.reportDisconnect!==false&&tn(r,b.matchId,E),G?.(E);}),h.reportDisconnect!==false&&h.reportConnected!==false&&r.notifyMatchConnected(b.matchId);let N={transport:w.link.transport,send:(E,L)=>w.link.send(E,L),onMessage:E=>w.link.onMessage(E),onClose:E=>{G=E;},close:()=>w.link.close()},q=()=>{P||(P=true,K(w.link),K(D));},B=E=>{if(!P){try{h.onMatchEnded?.(E);}catch{}q();}};return d(b.matchId,B),{matchId:b.matchId,transport:S,link:N,joinCredential:b.joinCredential,credentialExpiresAt:b.credentialExpiresAt,welcome:w.welcome,...w.channel===void 0?{}:{channel:w.channel},...w.peerConnection===void 0?{}:{peerConnection:w.peerConnection},close(){l(b.matchId,B),q();}}},T=async(h,b)=>{let S=r.currentRoom?.id,w=r.gameId,D=()=>({advert:vt(r.currentRoom?.settings,h),template:r.currentRoom?.transports??null});if(S===void 0||w===null)return D();try{let P=await e.get(`/v2/games/${encodeURIComponent(w)}/game-rooms/${encodeURIComponent(S)}`,b);return {advert:vt(P.settings,h),template:$e(P.transports)??r.currentRoom?.transports??null}}catch{return D()}},A=(h,b)=>{let S=h??Ir;return b.length===0?S:S.filter(w=>b.includes(w))},M=async(h,b,S)=>{try{let w=await p(h),{advert:D,template:P}=await T(w.matchId,h.signal),G=A(P,b),N=G.filter(F=>Ha(F,D)),q=wt();if(q!==null&&G.includes("webtransport")&&D?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${q} (learned on an earlier dial in this page)`),N.length===0){let F=P===null?`the default order (${Ir.join(", ")})`:`the room template's transports (${P.join(", ")||"none"})`;throw new u("misconfigured",`none of ${F}`+(b.length>0?`, narrowed to (${b.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let B=h.transportAttemptTimeoutMs??Na,E=()=>h.deadlineAt===void 0?1/0:h.deadlineAt-t.now(),L=F=>n.signalingReady===void 0||F<=0?Promise.resolve(!0):n.signalingReady(F),Y=[],ne=[];for(let F of N){if(E()<Pr){o(`[gem] ${F} rung not tried: the reconnect budget is spent`);break}ne.length>0&&w.credentialExpiresAt-t.now()<Mr&&(w=await c(h)),ne.push(F);let Gn=!1,Fn=!1,Ye={attempts:0,waitedMs:0};for(;;){if(F==="webrtc"&&h.redial===!0){let Q=Math.min(Cr,E());await L(Q)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(Q)}ms; offering anyway`);}let ai=Math.max(Math.min(B,E()),Pr);try{return v(h,w,F,await f(F,h,w,D,S,ai),S)}catch(Q){let $=Q instanceof u?Q:new u("connection_failed",Q instanceof Error?Q.message:String(Q),{cause:Q});if(F==="webrtc"&&Lr(s,$),($.reason==="credential_expired"||$.reason==="credential_reused")&&!Gn){Gn=!0,w=await c(h);continue}if(F==="webrtc"&&$.reason==="signaling_failed"&&$.platformCode===Zt&&!Fn){Fn=!0;let ae=Math.min(Cr,E());if(o(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(ae)}ms for the socket before offering again`),await L(ae))continue}if($.reason==="join_rate_limited"){let ae=Ua(Ye,Math.random,E());if(ae!==null){if(Ye.attempts+=1,Ye.waitedMs+=ae,o(`[gem] ${F} rung: the server is rate-limiting this player's joins; waiting ${Math.round(ae)}ms before presenting again (retry ${Ye.attempts} of ${Fr.maxAttempts})`),await pt(t,ae,h.signal),h.signal?.aborted)throw new u("aborted","the caller aborted while waiting out a join rate limit");w.credentialExpiresAt-t.now()<Mr&&(w=await c(h));continue}}if($a.has($.reason)||$.reason==="credential_expired"||F==="webrtc"&&Gr($)){o(`[gem] ${F} rung failed (${$.reason}): ${bt($.cause??$)} \u2014 `+(ne.length<N.length?`falling through to ${N[ne.length]}`:"no rungs left")),Y.push($);break}throw o(`[gem] ${F} rung refused the session (${$.reason}): ${$.message}`),$}}}let oe=Y[Y.length-1];throw oe===void 0?new u("timeout",`the reconnect budget ran out before any transport (${N.join(", ")}) could be tried`):new u(oe.reason,`every transport tried (${ne.join(", ")}) failed; the last said: ${oe.message}`,{cause:Y,platformCode:oe.platformCode})}catch(w){throw K(S),w}};return {listClusterTargets:async(h={})=>mt({client:e,...h}),handleMatchEnded(h,b){let S=a.get(h);if(S!==void 0){a.delete(h);for(let w of S)w(b);}},connect:(async(h={})=>{let b=h.signaling??i();return h.transports===void 0?m(h,b):M(h,h.transports,b)})}}var Ir=["webtransport","webrtc","websocket"],Na=1e4,qa=5e3,Cr=3e3,Pr=1e3,Mr=1e4,$a=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function Gr(n){return n.platformCode!==void 0&&en.has(n.platformCode)}var Fr={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function Ua(n,e=Math.random,t=1/0){let r=Fr;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 Ha(n,e){return n==="webrtc"?e===null||e.webrtc!==false:e===null?false:n==="webtransport"?e.webtransport!==void 0&&fn():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||Wa(e.websocket.url)}function Wa(n){if(typeof n!="string")return false;let e;try{e=new URL(n).hostname.toLowerCase();}catch{return false}return st(e)}function Rn(n){return {...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.pollIntervalMs===void 0?{}:{pollIntervalMs:n.pollIntervalMs},...n.signal===void 0?{}:{signal:n.signal}}}var Va=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Lr(n,e){e instanceof u&&(!Va.has(e.reason)&&!Gr(e)||n.report([{type:"connection_failures_total",value:1}]));}function Ba(n,e,t,r,i,o,s,a,d,l){let p=false,c=()=>{p||tn(n,e.matchId,void 0);};o&&(t.addEventListener("close",c),s&&n.notifyMatchConnected(e.matchId));let m=()=>{p||(p=true,t.removeEventListener("close",c),a?.detach(),K(t),K(r),K(i));},f=v=>{if(!p){try{l?.(v);}catch{}m();}};return d.remember(e.matchId,f),{matchId:e.matchId,channel:t,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:a?.welcome??null,close(){d.forget(e.matchId,f),m();}}}function Ka(n){let e=n.matchSession.phase;return e!=="none"&&e!=="ended"}function Or(n){if(n.status==="failed")throw new u("allocation_failed",`match ${n.matchId} did not come up: ${n.reason}`);if(n.status==="ended")throw new u("match_ended",`match ${n.matchId} ended (${n.reason}) before this side connected.`);if(n.protocol!==je)throw new u("unsupported_protocol",`match ${n.matchId} speaks '${n.protocol}', which a browser cannot connect. Only '${je}' 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 u("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 Dr(){let n=globalThis.RTCPeerConnection;if(!n)throw new u("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 St(n,...e){let t={};for(let r of e)n[r]!==void 0&&(t[r]=n[r]);return t}var Ee=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:Rt(i.credential)??"",hostFingerprint:Rt(i.host_fingerprint)??"",hostEpoch:_t(i.host_epoch)??0,expiresAt:(_t(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 d of Array.isArray(i.ice_servers)?i.ice_servers:[]){let l=d,p=(Array.isArray(l.urls)?l.urls:[]).filter(c=>typeof c=="string"&&c.length>0);p.length!==0&&o.push({urls:p,username:Rt(l.username)??"",credential:Rt(l.credential)??""});}let s=_t(i.expires_at),a=_t(i.ttl_seconds);return {iceServers:o,expiresAt:s!==void 0?s*1e3:Date.now()+(a??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 Rt(n){return typeof n=="string"&&n.length>0?n:void 0}function _t(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}var Ja=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=Ja.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 Xa=/^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 Xa.test(r)?r:null}function xe(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 _n=5e3,Ya=12e4+_n,za=1024,Qa=6e4,Za=1e4,jr=64*1024,Nr=5;function xt(n){let e=new Map,t=-1/0,r=null,i=(()=>{let a;try{a=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 a.username!==""||a.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:a.href,shown:`${a.protocol}//${a.host}`}})(),o=()=>{let a=n.subtle??globalThis.crypto?.subtle;if(!a)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 a},s=async()=>{if(!i.ok)throw new k("keys_unavailable",i.reason);let a=n.fetch??((m,f)=>globalThis.fetch(m,f)),d;try{d=await a(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(Za)});}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(!d.ok)throw new k("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let l;try{let m=await d.text();if(m.length>jr)throw new k("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${jr} characters, which is not a key set this platform publishes.`);l=JSON.parse(m);}catch(m){throw m instanceof k?m:new k("keys_unavailable",`the JWKS endpoint at ${i.shown} did not answer with a readable key set.`)}let p=Array.isArray(l.keys)?l.keys:[];if(p.length>Nr)throw new k("keys_unavailable",`the JWKS endpoint published ${p.length} keys, over the ${Nr} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=o();for(let m of p){let f=m;if(f.kty==="RSA"&&!(f.alg!==void 0&&f.alg!=="RS256")&&!(f.use!==void 0&&f.use!=="sig")&&!(typeof f.kid!="string"||f.kid.length===0))try{let v=await c.importKey("jwk",{...m,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(f.kid,v);}catch{}}};return {async key(a){let d=e.get(a);if(d)return d;if(!i.ok)throw new k("keys_unavailable",i.reason);if(r)return await r,e.get(a)??null;let l=n.now();if(!Number.isFinite(l))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 l<t&&(t=-1/0),l-t<Qa?null:(t=l,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var Be=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>=za){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,t+Ya),true}};function $r(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 qr(n){try{let e=new TextDecoder().decode($r(n)),t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch{return null}}async function Tt(n,e,t,r,i){let o=E=>{throw new k("peer_unauthenticated",`the peer's join credential is not usable: ${E}`)},s=n.split(".");s.length!==3&&o("it is not a three-part JWT");let[a,d,l]=s,p=qr(a);p===null&&o("its header does not decode"),p.alg!=="RS256"&&o(`its alg is ${JSON.stringify(p.alg)}, not RS256`),p.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(p.typ)}, not p2p+jwt`);let c=p.kid;(typeof c!="string"||c.length===0)&&o("it names no key");let m=await t.key(c);m===null&&o("it was signed by a key this build cannot resolve");let f=i.subtle??globalThis.crypto?.subtle;f||o("this environment has no WebCrypto");let v=new TextEncoder().encode(`${a}.${d}`),T;try{T=$r(l);}catch{o("its signature does not decode");}await f.verify({name:"RSASSA-PKCS1-v1_5"},m,T,v)||o("its signature does not verify");let M=qr(d);M===null&&o("its payload does not decode");let C=M,h=E=>typeof C[E]=="string"?C[E]:"",b=E=>typeof C[E]=="number"&&Number.isFinite(C[E])?C[E]:NaN;h("iss")!==i.issuer&&o("it was issued by someone else"),h("aud")!==`${i.issuer}/p2p-match`&&o("its audience is not this platform"),h("match_id")!==e.matchId&&o("it is for another match"),h("game_id")!==e.gameId&&o("it is for another game");let S=b("exp")*1e3,w=b("nbf")*1e3;(!Number.isFinite(S)||e.now>S+_n)&&o("it has expired"),Number.isFinite(w)&&e.now<w-_n&&o("it is not valid yet");let D=h("role");D!=="host"&&D!=="client"&&o("it names no usable role");let P=b("host_epoch");P!==e.hostEpoch&&o("it names a different host epoch");let G=Ve(h("fingerprint"));G===null&&o("its fingerprint claim is malformed"),xe(G,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let N=Ve(h("host_fingerprint"));N===null&&o("its host fingerprint claim is malformed"),xe(N,e.hostFingerprint)||o("it was issued against a different host certificate");let q=h("jti");q.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit(q,e.now)||o("it has already been used");let B=h("sub");return B.length===0&&o("it names no player"),{playerId:B.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:P,role:D,fingerprint:G,hostFingerprint:N,jti:q,expiresAt:S}}var he=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 xn(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 Tn(n){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,3),t.setUint8(1,n),e}function An(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 Ur(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 Wr=3e4,Te=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 At={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 It(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 Ct(){let n=globalThis.RTCPeerConnection;return n?.generateCertificate?n.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var Br=1,is=3e4,Kr=2e3,os=5e3,Jr=6e4,as=8,Cn=class{constructor(e=as){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;}},ss=new Cn,ds=8,ls=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),Ae=class{constructor(e){this.options=e;this.keys=e.keys??xt({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new Et;links=new Map;replays=new Be;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=Br+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??is;this.credentialDeadline=this.options.clock.now()+t;let r=new Promise((a,d)=>{this.ready={resolve:a,reject:d};}),i=U(this.options.clusterTargetId);if(i!==void 0)try{let a=await this.options.api.turnLease(this.options.matchId,i,e);this.iceServers=a.iceServers,this.mark("turn leased");}catch(a){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: ${In(a)}`);}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),s=()=>this.fail(new k("aborted","the caller aborted while connecting"));e?.aborted?s():e?.addEventListener("abort",s);try{await r;}finally{this.options.clock.clearTimeout(o),e?.removeEventListener("abort",s),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=j(e.playerId),r=j(e.hostPlayerId),i=Pt(e.hostEpoch);if(!(t===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=t,this.migration===null&&(this.migration=new Te(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,Br),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(s=>this.report_(s));}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??ss,s=()=>this.closed||e!==this.credentialGeneration,a=os;for(;;){let d=o.delayUntilAllowed(this.options.clock.now());if(d>0&&!await this.waitForCredential(d,s))return;o.record(this.options.clock.now());try{let l=await this.options.api.joinCredential(this.options.matchId,i);if(s())return;this.credential=l,this.mark("credential ready"),this.maybeAuthenticate();return}catch(l){if(s())return;let p=l.status,c;if(p===409)c=Kr;else if(p===429){let m=l.retryAfterSeconds;typeof m=="number"&&Number.isFinite(m)&&m>=0?c=m*1e3:(c=a,a=Math.min(a*2,Jr)),c=Math.min(Math.max(c,Kr),Jr);}else throw l;if(!await this.waitForCredential(c,s))return}}}async waitForCredential(e,t){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!t())}async onOffer(e){let t=j(e.fromPlayerId),r=j(e.sdp);if(t===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(t),this.pendingOffers.size>=ds){let p=this.pendingOffers.keys().next().value;p!==void 0&&this.pendingOffers.delete(p);}this.pendingOffers.set(t,e);return}if(!this.isHost||this.migration.isKicked(t)===true)return;let i=j(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 s=this.links.get(t);s&&this.dropLink(s,"resignalled",false);let a=this.openLink(t,this.nextPeerId++);a.remoteFingerprint=o,await a.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(a);let d=await a.connection.createAnswer();await a.connection.setLocalDescription(d);let l=a.connection.localDescription?.sdp??d.sdp;if(!l)throw new k("invalid_sdp","the browser produced an answer with no SDP");ie(l,"answer"),this.refuseMedia(l,"answer"),this.options.signaling.answer(t,l,a.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let t=j(e.fromPlayerId),r=j(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:xe(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=j(e.fromPlayerId),r=j(e.candidate);if(t===null||r===null)return;let i=this.links.get(t);if(!i)return;let o=j(e.sdpMid),s=Pt(e.sdpMLineIndex)??Pt(e.sdpMLineIndexAlt),a={candidate:r,...o===null?{}:{sdpMid:o},...s===null?{}:{sdpMLineIndex:s}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(a);return}await i.connection.addIceCandidate(a);}onPeerLeft(e){let t=j(e.playerId);if(t===null)return;let r=j(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=j(e.hostPlayerId),r=Pt(e.hostEpoch);if(t===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:t,hostEpoch:r,...j(e.reason)===null?{}:{reason:j(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=j(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=j(e.code)??"unknown",r=j(e.message)??"the platform refused a signaling message";this.report_(new k("signaling_failed",`${t}: ${r}`));}openLink(e,t){let i=(this.options.peerConnectionFactory??It)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let m of Ke){let f=i.createDataChannel(m,At[m]);f.binaryType="arraybuffer",o[m]=f;}let s={playerId:e,assignedPeerId:t,connection:i,channels:o,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},a=m=>{let f=m.candidate;f?.candidate&&this.options.signaling.candidate(e,f.candidate,f.sdpMid??void 0,f.sdpMLineIndex??void 0);},d=()=>this.onIceState(s),l=()=>this.onConnectionState(s),p=m=>{this.onHandshakeMessage(s,m.data).catch(f=>this.report_(f));},c=()=>{this.onReliableOpen(s).catch(m=>this.report_(m));};return i.addEventListener("icecandidate",a),i.addEventListener("iceconnectionstatechange",d),i.addEventListener("connectionstatechange",l),o.reliable.addEventListener("open",c),o.reliable.addEventListener("message",p),s.detachHandshake=()=>{o.reliable.removeEventListener("open",c),o.reliable.removeEventListener("message",p);},s.detachAll=()=>{s.detachHandshake(),i.removeEventListener("icecandidate",a),i.removeEventListener("iceconnectionstatechange",d),i.removeEventListener("connectionstatechange",l);},this.links.set(e,s),s}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=An(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(Hr(r.reason),Ur(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 Tt(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(s){let a=s instanceof k&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",In(s)),a&&this.fail(s);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(xn({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(Tn(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)Xr(e.channels[i]);Xr(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",In(e),{cause:e}));}count(e){this.counted||!ls.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,t){if(kt(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 j(n){return typeof n=="string"&&n.length>0?n:null}function Pt(n){return typeof n=="number"&&Number.isInteger(n)?n:null}function In(n){return n instanceof Error?n.message:String(n)}function Xr(n){try{n.close();}catch{}}var cs=100,us=50,Ie=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??cs)){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??us));}};var Pn="webrtc_p2p";function ms(n){let e=new Ee({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=U(r.clusterTargetId),o=i??U(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 s=await n.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(s.protocol!==Pn)throw new k("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${Pn}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let a=new Ie({bridge:n.bridge,matchId:s.matchId,clock:n.clock}),d=new Ae({api:e,clock:n.clock,matchId:s.matchId,gameId:n.gameId(),baseUrl:typeof n.baseUrl=="function"?n.baseUrl():n.baseUrl,signaling:a,...o===void 0?{}:{clusterTargetId:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await Ct(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...n.boot===void 0?{}:{boot:n.boot},...n.log===void 0?{}:{log:n.log}});a.onDropped(l=>d.notifyCandidatesDropped(l)),t.set(s.matchId,d),d.on("matchEnded",()=>t.delete(s.matchId));try{await d.start(r.signal);}catch(l){throw t.delete(s.matchId),d.close(),l}return d}}}function Yr(n){return typeof n=="string"&&n.trim()!==""}function zr(n,e){return Yr(n)?n.trim():Yr(e)?e:null}function ge(n){return typeof n=="string"&&n!==""?n:void 0}var ps=new Set(["localhost","127.0.0.1","[::1]"]);function Qr(n){let e=ge(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:"&&ps.has(t.hostname)))return e}function hs(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=t??{},i=ge(r.item_id),o=Qr(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function Zr(n){let e=n??{},t=ge(e.player_id),r=ge(e.display_name),i=ge(e.discriminator),o=ge(e.display_tag),s=ge(e.avatar_icon_id),a=Qr(e.avatar_icon_url);return {...t===void 0?{}:{playerId:t},...r===void 0?{}:{displayName:le(r)},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:le(o)},...s===void 0?{}:{avatarIconId:s},...a===void 0?{}:{avatarIconUrl:a},badges:hs(e.badges)}}function Mt(n){if(typeof n!="object"||n===null)return;let e={};for(let[t,r]of Object.entries(n)){let i=Mn(r);i!==void 0&&(e[t]=i);}return e}function Lt(n){if(Array.isArray(n))return n.map(gs).filter(e=>!!e)}function Mn(n){if(Ln(n)||Array.isArray(n)&&n.every(Ln))return n}function Ln(n){return typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)}function gs(n){let e=n??{};if(typeof e.name!="string"||e.name.length===0)return null;let t=Mn(e.fixed),r=Mn(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},...Ce("description",fs(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(Ln)?{allowed:e.allowed}:{},...Ce("min",Je(e.min)),...Ce("max",Je(e.max)),...Ce("minItems",Je(e.min_items)),...Ce("maxItems",Je(e.max_items)),...Ce("maxLength",Je(e.max_length))}}function fs(n){return typeof n=="string"&&n.length>0?n:void 0}function Je(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Ce(n,e){return e===void 0?{}:{[n]:e}}function X(n){let e=n??{},t=I(e.id)??I(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(On):[];return {id:t,gameId:I(e.game_id)??"",name:I(e.name)??"",status:I(e.status)??"open",hostPlayerId:I(e.host_player_id)??"",maxPlayers:z(e.max_players)??0,memberCount:z(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...J("joinCode",I(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...J("roomArgs",Mt(e.room_args)),...J("roomArgsTemplate",Lt(e.room_args_template)),gameChannel:I(e.game_channel)??"release",...J("region",I(e.region)),...J("clusterTargetId",I(e.cluster_target_id)),selfHosted:e.self_hosted===true,...J("matchId",I(e.match_id)),version:z(e.version)??0,...J("templateId",I(e.template_id)),roomType:I(e.game_room_type)??"Standard",...J("transports",$e(e.transports)??void 0),createdAt:z(e.created_at)??0,updatedAt:z(e.updated_at)??0,...J("startedAt",z(e.started_at))}}function On(n){let e=n??{};return {...Zr(e),playerId:I(e.player_id)??"",isReady:e.is_ready===true,role:I(e.role)??"member",joinedAt:z(e.joined_at)??0,...J("groupId",I(e.group_id)),...J("platform",I(e.platform))}}function Xe(n){let e=n??{};return {id:I(e.id)??I(e.game_room_id)??"",gameId:I(e.game_id)??"",name:I(e.name)??"",status:I(e.status)??"open",hostPlayerId:I(e.host_player_id)??"",maxPlayers:z(e.max_players)??0,memberCount:z(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:I(e.game_channel)??"release",roomType:I(e.game_room_type)??"Standard",createdAt:z(e.created_at)??0}}function I(n){return typeof n=="string"&&n.length>0?n:void 0}function z(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function J(n,e){return e===void 0?{}:{[n]:e}}var Pe=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 ys(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},...Ot(t)},e.signal).then(X)}get(e,t){return this.options.client.get(this.roomV2(e),t).then(X)}join(e,t,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...t.partyId===void 0?{}:{party_id:t.partyId},...Ot(r)},t.signal).then(X)}joinByCode(e,t,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...t.partyId===void 0?{}:{party_id:t.partyId},...Ot(r)},t.signal).then(X)}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}:{},...Ot(t)},e.signal).then(X)}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(X)}setReady(e,t,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:t},r).then(X)}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(X)}leaveMatch(e,t){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:t}).then(()=>{})}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 Ot(n){return {platform:n.platform,game_version:n.gameVersion,engine_version:n.engineVersion}}function ys(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 vs(n,e){return Math.min(e,500*2**Math.max(0,n-1))}var bs=1e3,ws=3e3,ks=6e4,Ss=2,ei=new Set(["game_room_closed","game_room_gone"]),Rs=12e4,_s=5e3,Es=new Set(["invalid_cluster_target","capacity_unavailable"]),xs=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function ii(n){return new Dn(n)}var Dn=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new Pe({client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new Me;api;room=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");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 s=>{let a=await this.afterRefusedClusters(s,o);if(a[0]===void 0||a[0]===o[0])throw s;return this.api.create(r,this.version("create"),a[0])})});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,t={}){this.assertNotInRoom("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");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");let t=this.clusterTargets(),r=await this.attachParty(e),i=s=>this.api.quickJoin(r,this.version("quickJoin"),s).catch(a=>this.retryPastStaleMembership(a,r,s)),o=await this.run("quickJoin",async()=>{let s=await t;return i(s).catch(async a=>{let d=await this.afterRefusedClusters(a,s);if(d.length===0||As(d,s))throw a;return i(d)})});return this.enter(o,"joined"),this.askForLocalServer(o),o}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 H&&i.reason==="not_found"){let o=this.heldMatchId;if(o!==null){let s=await this.askWhyEnded(o,e);this.endMatch(o,s??"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(()=>Yt({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(s){return s instanceof H&&s.reason==="not_found"?i??null:(this.reportError("reconcile",s),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 u("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=U(t.clusterTargetId),o=i??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),s=o??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let a=(p,c)=>ct({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...p===void 0?{}:{clusterTargetId:p},...i===void 0?{nextClusterTarget:()=>this.nextCluster(c)}:{},retry:{...t.retry,onWaiting:m=>{this.emitter.emit("matchStartWaiting",m),t.retry?.onWaiting?.(m);}},...t.signal===void 0?{}:{signal:t.signal}}),d=()=>a(o,[s]).catch(async p=>{if(i!==void 0||!ri(p))throw p;let c=await this.nextCluster([s],true);if(c===void 0)throw p;return a(c,[s,c])}),l=await(r?this.run("startMatch",d):this.track(this.onceGameIdKnown(d)));return this.beginMatch(l.matchId),l}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new u("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 ut({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 u("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!ei.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new u("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(!Dt()){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<bs){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(vs(e.attempt,t.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!Dt()){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(()=>Yt({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,!ei.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(s){this.reportError("reconcile",s),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 u("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 u("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 u("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 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.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||!Es.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){this.disposed||!this.watchingSeats||this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}async reconcileSeats(){if(this.disposed||!this.watchingSeats)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.seatPollMs>0&&Dt())){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(),!!Dt())){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}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of ti)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.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 ti)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??_s}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new u("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=zr(this.options.platformGameVersion?.(),t?.gameVersion);if(r===null)throw new u("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 Ar({...t,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return ve(await this.options.resolveClusterTargets());let e=U(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,t){return !ri(e)||t.length===0?[]:ve(await this.options.refreshClusterTargets?.(t)??[])}async nextCluster(e,t=false){let r=s=>s.find(a=>!e.includes(a)),i=await this.clusterTargets(),o=r(i);return o!==void 0||!t?o:r(ve(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 H)||e.reason!=="conflict"||!xs.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new H(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 H(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 H(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 u("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.`)}requireRoom(e){if(this.room===null)throw new u("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 H?{operation:e,code:t.status,reason:t.reason,message:t.message,retryable:t.retryable}:{operation:e,code:0,reason:t instanceof u?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.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(a=>[a.playerId,a])),i=new Map(e.members.map(a=>[a.playerId,a])),o=this.playerId();for(let a of i.keys())r.has(a)||this.emitter.emit("memberJoined",a);for(let a of r.keys())if(!i.has(a)){if(a===o){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",a);}for(let[a,d]of i){let l=r.get(a);l&&l.isReady!==d.isReady&&this.emitter.emit("readyChanged",a,d.isReady);}t.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let s=Ts(t,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),s&&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??Rs;return new Promise((i,o)=>{let s=c=>{a(),d(),this.options.clock.clearTimeout(p),e.signal?.removeEventListener("abort",l),c();},a=this.emitter.on("matchAllocationStarted",c=>s(()=>i(c))),d=this.emitter.on("matchFailed",(c,m)=>s(()=>o(new u("allocation_failed",`match ${c} did not come up: ${m}`)))),l=()=>s(()=>o(new u("aborted","the caller aborted while awaiting a match"))),p=this.options.clock.setTimeout(()=>s(()=>o(new u("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?l():e.signal?.addEventListener("abort",l);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??ws}pushedInterval(){return this.options.pushedPollIntervalMs??ks}pushed(){return this.options.clock.now()-this.lastPushAt<Ss*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=>{t?.persisted!==true&&this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{}));},e.addEventListener("pagehide",this.unloadListener));}};function Dt(){let n=globalThis.document;return n?.visibilityState===void 0||n.visibilityState==="visible"}var ti=["visibilitychange","focus","pageshow","online"];function Ts(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||ni(n)!==ni(e)}function ni(n){return n.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function ri(n){return n instanceof H&&n.code==="invalid_cluster_target"}function As(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}function oi(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={},s=d=>{t.delete(r)&&(n.clock.clearTimeout(o.timer),i(d));};t.set(r,s),o.timer=n.clock.setTimeout(()=>s(void 0),n.timeoutMs??2e3);let a=false;try{a=n.bridge.requestParty(r);}catch{}a||s(void 0);})},settle(r,i){t.get(r)?.(i);}}}
1
+ globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:9.1.3]";var g="gem-web-bridge",Z={min:1,max:1},fe=65536,jn=8,ze=5e3,Nn=1024,Ft=1e4;function jt(n){return Object.freeze(Object.assign(Object.create(null),n))}var Qe=jt({"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.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",Cs=["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"],Ps=["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.vibrate","gem.frameStats","gem.portraitBorders","gem.error","gem.requestPurchase","gem.deviceSettings.put","gem.requestAd","gem.requestSignIn","gem.requestFriendChallenge"],si=jt({"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.vibrate":"vibration","gem.menu":"gameMenu","gem.menuSelect":"gameMenu"}),di=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"]]);function Ze(n){let e=si[n];if(e!==void 0)return e;for(let[t,r]of di)if(n.startsWith(t))return r}function et(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 li(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 ci(n){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(n)}function ui(n){return /^[a-z_]+$/.test(n)}function Gt(n,e,t){if(e>jn)return `nesting deeper than ${jn}`;if(++t.nodes>ze)return `more than ${ze} 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>Nn)return `an array of ${n.length} entries, over the ${Nn} limit`;t.bytes+=2;for(let a of n){let d=Gt(a,e+1,t);if(d)return d}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 s=n;for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;if(++t.nodes>ze)return `more than ${ze} values`;if(t.bytes+=a.length*3+4,t.bytes>fe)return `over the ${fe} byte limit`;let d=Gt(s[a],e+1,t);if(d)return d}return null}function mi(n){let e={nodes:0,bytes:0,seen:new Set},t=Gt(n,0,e);return t?`message contains ${t}`:e.bytes>fe?`message is over the ${fe} byte limit`:null}var pi={origin:[et,"not a well-formed origin"],url:[li,"not a safe absolute http(s) URL"],bcp47:[ci,"not a well-formed BCP 47 tag"],code:[ui,"not a code of lower-case letters and underscores"]};function qn(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 s=$n(o,r,i);if(s)return s}return null}function $n(n,e,t){switch(e.k){case "string":{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]=pi[e.f];if(!r(n))return `${t}: ${i}`}return null}case "int":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 "boolean":return typeof n=="boolean"?null:`${t}: expected boolean`;case "enum":{let r=e.v;return r.includes(n)?null:`${t}: not one of ${r.join("|")}`}case "object":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected object`:qn(n,e.fs,t);case "json":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected a plain object`:null;case "array":{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 s=$n(o,r,i);if(s)return s}return null}default:{let r=e.k;return `${t}: unknown kind ${String(r)}`}}}function y(n,e){return t=>{let r=mi(t);if(r)return r;if(typeof t!="object"||t===null||Array.isArray(t))return "message: expected object";let i=t;return i.gem!==g?"gem: wrong protocol marker":i.type!==n?`type: expected ${n}`:qn(i,e,"")}}var hi=y("gem.handshake",[{n:"versions",k:"object",fs:[{n:"min",k:"int",lo:1,hi:1e3},{n:"max",k:"int",lo:1,hi:1e3}]},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}},{n:"embedder",k:"string",max:2048,f:"origin"},{n:"unbidden",k:"boolean",o:1}]),gi=y("gem.handshake.accept",[{n:"v",k:"int",lo:1,hi:1e3},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}}]),fi=y("gem.token",[{n:"token",k:"string",max:4096},{n:"requestId",k:"string",o:1,max:64},{n:"generation",k:"int",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"string",o:1,max:512,f:"url"},{n:"playerId",k:"string",max:64},{n:"gameId",k:"string",max:64},{n:"channel",k:"enum",v:["dev","test","release"]},{n:"gameVersion",k:"string",o:1,max:64},{n:"expiresAt",k:"int",lo:0,hi:4102444800},{n:"chainEndsAt",k:"int",lo:0,hi:4102444800},{n:"allowDevTools",k:"boolean",o:1}]),yi=y("gem.token.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"retryAfterMs",k:"int",o:1,lo:0,hi:36e5},{n:"reason",k:"enum",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"string",max:64}]),vi=y("gem.player",[{n:"untrusted",k:"object",fs:[{n:"displayName",k:"string",max:64},{n:"displayTag",k:"string",o:1,max:80},{n:"displayHandle",k:"string",max:80}]},{n:"playerId",k:"string",o:1,max:64},{n:"discriminator",k:"string",o:1,max:8},{n:"avatarIconUrl",k:"string",o:1,max:2048,f:"url"},{n:"badges",k:"array",o:1,max:2,it:{n:"",k:"object",fs:[{n:"itemId",k:"string",max:64},{n:"iconUrl",k:"string",max:2048,f:"url"}]}},{n:"displayTag",k:"string",max:8},{n:"avatarUrl",k:"string",o:1,max:2048,f:"url"},{n:"boost",k:"object",o:1,fs:[{n:"multipliers",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"currencyId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"multiplierBp",k:"int",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"int",o:1,lo:1,hi:7}]}]),bi=y("gem.pause",[{n:"paused",k:"boolean"}]),wi=y("gem.prefs",[{n:"reducedMotion",k:"boolean"},{n:"muted",k:"boolean"},{n:"showFrameStats",k:"boolean",o:1},{n:"locale",k:"string",max:35,f:"bcp47"}]),ki=y("gem.cohorts",[{n:"cohorts",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"experimentId",k:"string",max:36},{n:"variantKey",k:"string",max:32}]}}]),Si=y("gem.earnAllowanceChanged",[]),Ri=y("gem.viewport",[{n:"insets",k:"object",fs:[{n:"top",k:"int",lo:0,hi:4096},{n:"right",k:"int",lo:0,hi:4096},{n:"bottom",k:"int",lo:0,hi:4096},{n:"left",k:"int",lo:0,hi:4096}]},{n:"reserved",k:"array",o:1,max:4,it:{n:"",k:"object",fs:[{n:"x",k:"int",lo:0,hi:16384},{n:"y",k:"int",lo:0,hi:16384},{n:"width",k:"int",lo:0,hi:16384},{n:"height",k:"int",lo:0,hi:16384}]}}]),_i=y("gem.deviceSettings",[{n:"settings",k:"json",o:1}]),Ei=y("gem.willTerminate",[{n:"reason",k:"enum",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"int",lo:0,hi:6e4}]),xi=y("gem.roomEvent",[{n:"event",k:"enum",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"string",max:64},{n:"matchId",k:"string",o:1,max:64},{n:"version",k:"int",o:1,lo:0,hi:2147483647},{n:"reason",k:"string",o:1,max:64},{n:"platform",k:"enum",o:1,v:["universal","mobile"]}]),Ti=y("gem.socketState",[{n:"connected",k:"boolean"},{n:"reason",k:"enum",o:1,v:["connecting","dropped","watchdog","terminal"]}]),Ai=y("gem.seatedEvent",[{n:"roomId",k:"string",max:64}]),Ii=y("gem.autoStartFailedEvent",[{n:"roomId",k:"string",max:64},{n:"code",k:"string",max:64}]),Ci=y("gem.signalEvent",[{n:"event",k:"enum",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),Pi=y("gem.dedicatedEvent",[{n:"event",k:"enum",v:["answer","error","matchEnded"]},{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",o:1,max:10240},{n:"sessionId",k:"string",o:1,max:64},{n:"code",k:"string",o:1,max:64},{n:"message",k:"string",o:1,max:256},{n:"reason",k:"string",o:1,max:64}]),Mi=y("gem.partyResult",[{n:"requestId",k:"string",max:64},{n:"partyId",k:"string",o:1,max:64}]),Li=y("gem.clusterTarget",[{n:"clusterTargetId",k:"string",max:64},{n:"clusterTargetIds",k:"array",o:1,max:3,it:{n:"",k:"string",max:64}}]),Oi=y("gem.devtools",[{n:"action",k:"enum",v:["open","close","toggle"]}]),Di=y("gem.screenshot",[{n:"maxWidth",k:"int",lo:1,hi:7680},{n:"maxHeight",k:"int",lo:1,hi:4320}]),Gi=y("gem.screenshot.denied",[{n:"reason",k:"enum",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"boolean"}]),Fi=y("gem.requestContext",[]),ji=y("gem.gameContext",[{n:"context",k:"json"}]),Ni=y("gem.signal",[{n:"signal",k:"enum",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),qi=y("gem.dedicatedOffer",[{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",max:10240},{n:"intent",k:"enum",v:["initial","ice_restart","full_reconnect"]}]),$i=y("gem.partyRequest",[{n:"requestId",k:"string",max:64}]),Ui=y("gem.ready",[]),Hi=y("gem.engaged",[]),Wi=y("gem.progress",[{n:"loaded",k:"int",lo:0,hi:1099511627776},{n:"total",k:"int",lo:0,hi:1099511627776}]),Vi=y("gem.requestToken",[{n:"requestId",k:"string",max:64},{n:"reason",k:"enum",v:["initial","expiring","rejected"]}]),Bi=y("gem.requestLocalServer",[{n:"requestId",k:"string",max:64},{n:"gameRoomId",k:"string",max:64}]),Ki=y("gem.localServer",[{n:"requestId",k:"string",max:64},{n:"serverId",k:"string",o:1,max:128}]),Ji=y("gem.localServer.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"reason",k:"enum",v:["refused","unavailable"]}]),Xi=y("gem.exit",[{n:"reason",k:"string",o:1,max:64}]),Yi=y("gem.openExternal",[{n:"url",k:"string",max:2048,f:"url"}]),zi=y("gem.requestFullscreen",[{n:"enabled",k:"boolean"}]),Qi=y("gem.audioState",[{n:"muted",k:"boolean"}]),Zi=y("gem.rewardCue",[{n:"currencySlug",k:"string",max:32},{n:"expected",k:"int",o:1,lo:1,hi:1e9},{n:"origin",k:"object",o:1,fs:[{n:"x",k:"int",lo:0,hi:16384},{n:"y",k:"int",lo:0,hi:16384}]}]),eo=y("gem.walletDisplay",[{n:"visible",k:"boolean"},{n:"currencies",k:"array",o:1,max:8,it:{n:"",k:"string",max:64}},{n:"score",k:"boolean",o:1}]),to=y("gem.menu",[{n:"settings",k:"boolean"},{n:"items",k:"array",o:1,max:4,it:{n:"",k:"object",fs:[{n:"id",k:"string",max:32},{n:"label",k:"string",max:40}]}}]),no=y("gem.menuSelect",[{n:"entry",k:"enum",v:["settings","item"]},{n:"id",k:"string",o:1,max:32}]),ro=y("gem.requestShare",[{n:"params",k:"array",max:16,it:{n:"",k:"object",fs:[{n:"key",k:"string",max:64},{n:"value",k:"string",max:512}]}}]),io=y("gem.vibrate",[{n:"pattern",k:"array",max:99,it:{n:"",k:"int",lo:0,hi:1e4}}]),oo=y("gem.frameStats",[{n:"fps",k:"int",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"int",lo:0,hi:1e5}]),ao=y("gem.portraitBorders",[{n:"name",k:"string",o:1,max:40}]),so=y("gem.error",[{n:"code",k:"enum",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"string",o:1,max:256}]),lo=y("gem.requestPurchase",[{n:"requestId",k:"string",max:64},{n:"purchaseKind",k:"enum",v:["item","recipe"]},{n:"targetId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"quantity",k:"int",o:1,lo:1,hi:10},{n:"catalogId",k:"string",o:1,max:64}]),co=y("gem.purchaseResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["ok","declined","unavailable"]},{n:"reason",k:"string",o:1,max:64,f:"code"},{n:"purchaseId",k:"string",o:1,max:64}]),uo=y("gem.deviceSettings.put",[{n:"requestId",k:"string",max:64},{n:"settings",k:"json"}]),mo=y("gem.deviceSettings.result",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["stored","too_large","unavailable"]}]),po=y("gem.requestAd",[{n:"requestId",k:"string",max:64},{n:"placement",k:"string",max:32},{n:"format",k:"enum",v:["interstitial","rewarded"]}]),ho=y("gem.adResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["shown","no_ad","unavailable"]}]),go=y("gem.requestSignIn",[{n:"requestId",k:"string",max:64}]),fo=y("gem.signInResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["signed_in","declined","unavailable"]}]),yo=y("gem.requestFriendChallenge",[{n:"requestId",k:"string",max:64},{n:"playerId",k:"string",max:64},{n:"template",k:"string",max:64},{n:"params",k:"json",o:1}]),vo=y("gem.friendChallengeResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"string",o:1,max:64},{n:"param",k:"string",o:1,max:64},{n:"channel",k:"string",o:1,max:16},{n:"configVersion",k:"int",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"int",o:1,lo:0,hi:864e5},{n:"detail",k:"string",o:1,max:300}]),se=jt({"gem.handshake":hi,"gem.handshake.accept":gi,"gem.token":fi,"gem.token.denied":yi,"gem.player":vi,"gem.pause":bi,"gem.prefs":wi,"gem.cohorts":ki,"gem.earnAllowanceChanged":Si,"gem.viewport":Ri,"gem.deviceSettings":_i,"gem.willTerminate":Ei,"gem.roomEvent":xi,"gem.socketState":Ti,"gem.seatedEvent":Ai,"gem.autoStartFailedEvent":Ii,"gem.signalEvent":Ci,"gem.dedicatedEvent":Pi,"gem.partyResult":Mi,"gem.clusterTarget":Li,"gem.devtools":Oi,"gem.screenshot":Di,"gem.screenshot.denied":Gi,"gem.requestContext":Fi,"gem.gameContext":ji,"gem.signal":Ni,"gem.dedicatedOffer":qi,"gem.partyRequest":$i,"gem.ready":Ui,"gem.engaged":Hi,"gem.progress":Wi,"gem.requestToken":Vi,"gem.requestLocalServer":Bi,"gem.localServer":Ki,"gem.localServer.denied":Ji,"gem.exit":Xi,"gem.openExternal":Yi,"gem.requestFullscreen":zi,"gem.audioState":Qi,"gem.rewardCue":Zi,"gem.walletDisplay":eo,"gem.menu":to,"gem.menuSelect":no,"gem.requestShare":ro,"gem.vibrate":io,"gem.frameStats":oo,"gem.portraitBorders":ao,"gem.error":so,"gem.requestPurchase":lo,"gem.purchaseResult":co,"gem.deviceSettings.put":uo,"gem.deviceSettings.result":mo,"gem.requestAd":po,"gem.adResult":ho,"gem.requestSignIn":go,"gem.signInResult":fo,"gem.requestFriendChallenge":yo,"gem.friendChallengeResult":vo});var tt=3;function U(n){if(typeof n!="string")return;let e=n.trim();return e.length===0?void 0:e}function ve(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=U(t);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var bo=2e3,wo=5e3;function ko(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 s,a=new Promise(d=>{let l=false,p=null;s=c=>{l||(l=true,r=null,n.clock.clearTimeout(p),d(c));},p=n.clock.setTimeout(()=>{t=true,s([]);},n.timeoutMs??bo);});return r={promise:a,settle:s},a};return {resolveList:o,resolve(){return e.length>0||t||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):o().then(s=>s[0])},refresh(s){return !Un(e,s)||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let d=null,l=p=>{i.delete(l)&&(n.clock.clearTimeout(d),a(p));};i.set(l,s),d=n.clock.setTimeout(()=>l(e),n.refreshTimeoutMs??wo);})},accept(s,a){let d=ve(a),l=U(s),p=d.length>0?d:l===void 0?[]:[l];if(p.length!==0){e=p,r?.settle(p);for(let[c,m]of [...i])Un(p,m)||c(p);}}}}function Un(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var So=/^[a-z0-9][a-z0-9_-]{0,39}$/;function Nt(n){return typeof n=="string"&&So.test(n)}function Hn(n){if(n===null||Nt(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 Le=16384,nt=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 be(...n){return e=>typeof e=="string"&&n.includes(e)?e:void 0}function Wn(n){return typeof n=="boolean"?n:void 0}var O=R(64),Oe=ee(0,2147483647);function qt(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(e.length>=64)break;let r=O(t);typeof r=="string"&&e.push(r);}return e}function x(n,e,t){return {to:n,from:e,read:t,required:true}}function _(n,e,t){return {to:n,from:e,read:t,required:false}}function we(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 De(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 Vn=[x("sdp","sdp",R(10240)),x("signaling_intent","intent",be("initial","ice_restart","full_reconnect"))];function rt(n,e,t){if(typeof t!="object"||t===null||Array.isArray(t))return {reason:"offer: data must be an object"};let r=t,i=we(r,Vn);return i===null?{reason:`offer: '${Vn.find(s=>s.read(r[s.from])===void 0)?.from??"?"}' is missing or out of bounds`}:{frame:{type:"webrtc_offer",match_id:n,game_id:e,...i}}}var $t=Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"})),Ro=new Set(["error"]),_o=Object.freeze(Object.assign(Object.create(null),{answer:[x("sdp","sdp",R(10240)),_("sessionId","session_id",R(64))],error:[_("code","code",R(64)),_("message","message",R(256))],matchEnded:[_("reason","reason",R(64))]}));function it(n,e,t){let r=De(n);if(r===null)return null;let i=$t[r.type];if(i===void 0)return null;let o=O(r.data.match_id);if(typeof o!="string"||!(Ro.has(i)?t(o):r.data.game_id===e))return null;let a=we(r.data,_o[i]??[]);return a===null?null:{event:i,matchId:o,...a}}var Eo=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=be("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}}},xo=Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[x("sdp","sdp",R(10240)),x("signaling_intent","intent",be("initial","ice_restart","full_reconnect")),_("sdp_hash","sdpHash",R(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[x("peer_id","peerId",O),x("sdp","sdp",R(10240)),x("assigned_peer_id","assignedPeerId",ee(0,4294967295)),_("sdp_hash","sdpHash",R(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[x("peer_id","peerId",O),x("candidate","candidate",R(512)),_("sdp_mid","sdpMid",R(64)),_("sdp_mline_index","sdpMLineIndex",ee(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[x("host_epoch","hostEpoch",Oe)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[x("host_epoch","hostEpoch",Oe),_("evidence","evidence",Eo)]}}));function ot(n,e,t,r){let i=xo[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,s=we(o,i.args);if(s===null){let a=i.args.find(d=>d.required&&d.read(o[d.from])===void 0);return {reason:`${n}: '${a?.from??"?"}' is missing or out of bounds`}}return {frame:{type:i.type,match_id:e,...i.gameScoped?{game_id:t}:{},...s}}}var To=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"})),Ao=new Set(["error"]),Io=Object.freeze(Object.assign(Object.create(null),{hello:[x("playerId","player_id",O),x("hostPlayerId","host_player_id",O),x("hostEpoch","host_epoch",Oe),_("members","members",qt)],offer:[x("fromPlayerId","from_player_id",O),x("sdp","sdp",R(10240)),_("sessionId","signaling_session_id",R(128)),_("sdpHash","sdp_hash",R(128)),_("iceUfrag","ice_ufrag",R(64)),_("intent","signaling_intent",be("initial","ice_restart","full_reconnect"))],answer:[x("fromPlayerId","from_player_id",O),x("sdp","sdp",R(10240)),_("sessionId","signaling_session_id",R(128)),_("sdpHash","sdp_hash",R(128)),_("iceUfrag","ice_ufrag",R(64)),_("assignedPeerId","assigned_peer_id",ee(0,4294967295))],ice:[x("fromPlayerId","from_player_id",O),x("candidate","candidate",R(512)),_("sdpMid","sdp_mid",R(64)),_("sdpMLineIndex","sdp_m_line_index",ee(0,255)),_("sdpMLineIndexAlt","sdp_mline_index",ee(0,255))],peerJoined:[x("playerId","player_id",O)],peerLeft:[x("playerId","player_id",O),_("reason","reason",R(64))],migration:[x("hostPlayerId","new_host_player_id",O),x("hostEpoch","host_epoch",Oe),_("reason","reason",R(64)),_("kickedPlayerIds","kicked_player_ids",qt),_("migrationComplete","migration_complete",Wn)],matchEnded:[_("reason","reason",R(64))],error:[_("code","code",R(64)),_("message","message",R(256))]}));function at(n,e,t){let r=De(n);if(r===null)return null;let i=To[r.type];if(i===void 0)return null;let o=O(r.data.match_id);if(typeof o!="string"||!(Ao.has(i)?t(o):r.data.game_id===e))return null;let a=we(r.data,Io[i]??[]);return a===null?null:{event:i,matchId:o,data:a}}var Co=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 Ge(n){let e=De(n);if(e===null)return null;let t=Co[e.type];if(t===void 0)return null;let r=e.data,i=O(r.party_id);if(typeof i!="string")return null;let o=ee(0,Number.MAX_SAFE_INTEGER)(r.version),s=O(r.game_room_id),a=O(r.game_id),d=O(r.inviter_player_id),l=R(80)(r.inviter_display_tag),p=R(64)(r.party_name);return {event:t,partyId:i,...o===void 0?{}:{version:o},...s===void 0?{}:{gameRoomId:s},...a===void 0?{}:{gameId:a},...d===void 0?{}:{inviterPlayerId:d},...l===void 0?{}:{inviterDisplayTag:l},...p===void 0?{}:{partyName:p}}}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=Qe[e];if(t===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??t,s=Math.max(0,r-i),a=Math.min(t,o+s*t/6e4);return a<1?(this.tokens.set(e,a),this.lastRefill.set(e,r),false):(this.tokens.set(e,a-1),this.lastRefill.set(e,r),true)}};function Se(n,e){return n.toLowerCase()===e.toLowerCase()}function st(n){let e=n.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function Kn(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:st(t.hostname)&&st(r.hostname)}function Ut(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 Po=7,Mo=["universal","mobile"],Lo={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"},Oo=new Set(["match_ended","p2p_match_ended"]),Do="game_room_auto_start_failed",Go=/^[a-z][a-z0-9_]{0,63}$/,Fe=64,Fo=8,Wt=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 dt(n){if(!(typeof n!="string"||n.length===0||n.length>Fe))return n}function jo(n){return n instanceof Error?n.message:String(n)}function Xn(n,e){if(!n.has(e)){if(n.size>=Fo){let t=n.values().next().value;t!==void 0&&n.delete(t);}n.add(e);}}function Ht(){return new MessageChannel}var No=6e4/(Qe["gem.handshake"]??1),qo=6e4,Vt=class{constructor(e){this.options=e;if(!et(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(!et(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 Wt(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 ${Ft}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.`);},Ft);}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:g,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());},No);}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 Se(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:g,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=Lo[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=dt(i.game_room_id);if(o===void 0)return false;let s=Oo.has(t.type)?void 0:dt(i.match_id);s!==void 0&&this.rememberMatch(s);let a=typeof i.version=="number"?i.version:void 0,d=typeof i.reason=="string"?i.reason.slice(0,Fe):void 0,l=r==="version_stale"&&Mo.includes(i.platform)?i.platform:void 0;return this.sendRoomEvent({event:r,roomId:o,...s===void 0?{}:{matchId:s},...a===void 0?{}:{version:a},...d===void 0?{}:{reason:d},...l===void 0?{}:{platform:l}})}sendRoomEvent(e){return this.frameSupports("rooms")?this.send({gem:g,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:g,type:"gem.socketState",connected:e.connected,...e.connected?{}:{reason:e.reason}}):false}sendSeatedEvent(e){return this.frameSupports("partySeating")?this.send({gem:g,type:"gem.seatedEvent",roomId:e}):false}relaySeatedEvent(e){if(this.gameId===null)return false;let t=Ge(e);if(t===null||t.event!=="gameRoomJoined"||t.gameId!==this.gameId)return false;let r=dt(t.gameRoomId);return r===void 0?false:this.sendSeatedEvent(r)}sendAutoStartFailedEvent(e){return this.frameSupports("autoStartFailure")?this.send({gem:g,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!==Do||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=dt(r.game_room_id),o=typeof r.code=="string"&&Go.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=Ge(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=at(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:g,type:"gem.signalEvent",event:e.event,matchId:e.matchId,data:e.data}):false}relayDedicatedEvent(e){if(this.gameId===null)return false;let t=it(e,this.gameId,r=>this.knowsMatch(r));return t===null?false:this.sendDedicatedEvent(t)}sendDedicatedEvent(e){return this.frameSupports("dedicated")?this.send({gem:g,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){Xn(this.knownMatches,e);}rememberAsked(e){Xn(this.askedMatches,e);}answerPartyRequest(e,t){return this.send({gem:g,type:"gem.partyResult",requestId:e,...t===void 0?{}:{partyId:t}})}answerPurchase(e,t,r,i){return this.send({gem:g,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:g,type:"gem.deviceSettings.result",requestId:e,outcome:t})}sendDeviceSettings(e){return this.frameSupports("deviceSettings")?this.send({gem:g,type:"gem.deviceSettings",...e===void 0?{}:{settings:e}}):false}sendMenuSelect(e){return this.frameSupports("gameMenu")?this.send(e==="settings"?{gem:g,type:"gem.menuSelect",entry:"settings"}:{gem:g,type:"gem.menuSelect",entry:"item",id:e.id}):false}answerAd(e,t){return this.send({gem:g,type:"gem.adResult",requestId:e,outcome:t})}answerSignIn(e,t){return this.send({gem:g,type:"gem.signInResult",requestId:e,outcome:t})}answerFriendChallenge(e,t,r={}){let i={};if(t==="invalid"){let{code:o,param:s,channel:a,configVersion:d,detail:l}=r;typeof o=="string"&&o.length<=64&&(i.code=o),typeof s=="string"&&s.length<=64&&(i.param=s),typeof a=="string"&&a.length<=16&&(i.channel=a),typeof d=="number"&&Number.isSafeInteger(d)&&d>=0&&(i.configVersion=d),typeof l=="string"&&(i.detail=l.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:g,type:"gem.friendChallengeResult",requestId:e,outcome:t,...i})}denyToken(e){this.send({gem:g,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:g,type:"gem.localServer",requestId:e.requestId,...e.serverId===void 0?{}:{serverId:e.serverId}}):false}denyLocalServer(e){return this.frameSupports("localHost")?this.send({gem:g,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>Fe):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 ${Fe} 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:g,type:"gem.clusterTarget",clusterTargetId:i,...typeof e=="string"?{}:{clusterTargetIds:[...t]}})}sendPlayer(e){let{displayName:t,displayTag:r}=e.untrusted,i=e.badges?.map(({itemId:a,iconUrl:d})=>({itemId:a,iconUrl:d})),o=e.boost&&{multipliers:e.boost.multipliers.map(({currencyId:a,currencySlug:d,multiplierBp:l})=>({currencyId:a,currencySlug:d,multiplierBp:l})),...e.boost.expiresInDays===void 0?{}:{expiresInDays:Math.min(Po,e.boost.expiresInDays)}},s=e.discriminator!==void 0&&/^[0-9]{1,8}$/.test(e.discriminator)?e.discriminator:void 0;this.send({gem:g,type:"gem.player",untrusted:{displayName:t,...r===void 0?{}:{displayTag:r},displayHandle:r??t},...e.playerId===void 0?{}:{playerId:e.playerId},...s===void 0?{}:{discriminator:s},...e.avatarIconUrl===void 0?{}:{avatarIconUrl:e.avatarIconUrl},...i===void 0?{}:{badges:i},...o===void 0?{}:{boost:o},displayTag:s??"",...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:g,type:"gem.pause",paused:e});}sendDevtools(e){this.send({gem:g,type:"gem.devtools",action:e});}requestScreenshot(e,t){return this.frameSupports("screenshot")?this.send({gem:g,type:"gem.screenshot",maxWidth:t.maxWidth,maxHeight:t.maxHeight},[e]):false}requestContext(){return this.frameSupports("feedbackContext")?this.send({gem:g,type:"gem.requestContext"}):false}sendPrefs(e){this.send({gem:g,type:"gem.prefs",...e});}sendCohorts(e){return this.frameSupports("cohorts")?this.send({gem:g,type:"gem.cohorts",cohorts:e.map(t=>({experimentId:t.experimentId,variantKey:t.variantKey}))}):false}sendEarnAllowanceChanged(){return this.frameSupports("earnAllowance")?this.send({gem:g,type:"gem.earnAllowanceChanged"}):false}sendViewport(e){if(!this.frameSupports("viewport"))return false;let t=(e.reserved??[]).map(({x:o,y:s,width:a,height:d})=>({x:o,y:s,width:a,height:d})),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:g,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:g,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=se[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=se[r];if(!i){this.refuseMalformed("unsupported",`unknown message type ${JSON.stringify(r.slice(0,Fe))}`);return}if(!this.inbound.allow(r)){this.fail("rate_limited",`frame exceeded the limit for ${r}`);return}let o=Ze(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 s=i(e);if(s){this.fail("invalid_message",`${r}: ${s}`);return}let a=e;r!=="gem.handshake.accept"&&!this.versionMatches(a,r)||this.dispatch(r,a,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=ot(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=rt(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: ${jo(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):Nt(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.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((s,a)=>s+a,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 le(n){return new W(n)}var $o={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 Yn(n){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function Uo(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 Ho(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(s=>s.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 zn(n,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function Wo(n){let e=n.untrusted,t=le(e.displayName),r=e.displayTag||e.displayHandle,i=r?le(r):void 0,o=n.discriminator||n.displayTag,s=o&&/^[0-9]{1,8}$/.test(o)?o:void 0,a=n.avatarIconUrl||n.avatarUrl,d={displayName:t,displayHandle:i??t,badges:(n.badges??[]).map(m=>({itemId:m.itemId,iconUrl:m.iconUrl}))};n.playerId&&(d.playerId=n.playerId),s&&(d.discriminator=s),i&&(d.displayTag=i),a&&(d.avatarIconUrl=d.avatarUrl=a);let l=n.boost,p=(l?.multipliers??[]).map(m=>({currencyId:m.currencyId,currencySlug:m.currencySlug,multiplier:m.multiplierBp/1e4})),c=p.some(m=>m.multiplier>1);return d.boost=c&&l?.expiresInDays?{active:c,multipliers:p,expiresInDays:l.expiresInDays}:{active:c,multipliers:p},d}var Vo=1e4,Bt=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(a=>Se(a,e.origin))||Kn(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=se["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!Se(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 s=Ut(Z,i.versions);return s===null?(o.onmessage=null,o.postMessage({gem:g,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=s,o.onmessage=a=>this.receive(a.data,a.ports??[]),o.start?.(),this.peerCapabilities=i.capabilities??[],this.unbidden=i.unbidden===true,o.postMessage({gem:g,type:"gem.handshake.accept",v:s,...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:g,type:"gem.ready"});}settled(e=Vo){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:g,type:"gem.progress",loaded:e,total:t});}requestToken(e,t){this.send({gem:g,type:"gem.requestToken",requestId:e,reason:t});}requestLocalServer(e,t){return this.parentSupports("localHost")?(this.send({gem:g,type:"gem.requestLocalServer",requestId:e,gameRoomId:t}),true):false}exit(e){this.send(e===void 0?{gem:g,type:"gem.exit"}:{gem:g,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:g,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:g,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:g,type:"gem.audioState",muted:e}),true)}reportEngaged(){return this.engagedSent||this.state!=="connected"||!this.parentSupports("engagement")||!this.send({gem:g,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let t={gem:g,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:Yn(e.origin.x),y:Yn(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:g,type:"gem.portraitBorders"}:{gem:g,type:"gem.portraitBorders",name:t})}setWalletVisible(e,t){return this.state!=="connected"||!this.parentSupports("walletDisplay")?false:this.send({gem:g,type:"gem.walletDisplay",...Uo(e,t?.only)})}setMenu(e,t){return this.state!=="connected"||!this.parentSupports("gameMenu")?false:this.send({gem:g,type:"gem.menu",...Ho(e,t)})}requestShare(e){return this.state!=="connected"||!this.parentSupports("share")?false:this.send({gem:g,type:"gem.requestShare",params:e.map(({key:t,value:r})=>({key:t,value:r}))})}requestVibrate(e){return this.state!=="connected"||!this.parentSupports("vibration")?false:this.send({gem:g,type:"gem.vibrate",pattern:[...e]})}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:g,type:"gem.frameStats",fps:zn(e.fps,1e3),frameTimeP95Ms:zn(e.frameTimeP95Ms,1e5)}),true)}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:g,type:"gem.gameContext",context:e}),true)}signal(e,t,r){this.send({gem:g,type:"gem.signal",signal:e,matchId:t,data:r});}dedicatedOffer(e,t,r){this.send({gem:g,type:"gem.dedicatedOffer",matchId:e,sdp:t,intent:r});}requestParty(e){return this.send({gem:g,type:"gem.partyRequest",requestId:e})}requestPurchase(e,t,r,i,o,s){return this.send({gem:g,type:"gem.requestPurchase",requestId:e,purchaseKind:t,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...s===void 0?{}:{catalogId:s}})}putDeviceSettings(e,t){return this.send({gem:g,type:"gem.deviceSettings.put",requestId:e,settings:t})}requestAd(e,t,r){return this.send({gem:g,type:"gem.requestAd",requestId:e,placement:t,format:r})}requestSignIn(e){return this.send({gem:g,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,t,r,i){return this.send({gem:g,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:g,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=se[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||Qn(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=se[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=Ze(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 s=i(e);if(s)return this.fail("invalid_message",`${r}: ${s}`),false;let a=e;if(a.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(a);break;case "gem.pause":this.options.onPause?.(a);break;case "gem.menuSelect":this.options.onMenuSelect?.(a);break;case "gem.prefs":this.options.onPrefs?.(a);break;case "gem.cohorts":this.options.onCohorts?.(a);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(a);break;case "gem.willTerminate":this.options.onWillTerminate?.(a);break;case "gem.devtools":this.options.onDevtools?.(a.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let d=t[0];if(!d){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let l={maxWidth:a.maxWidth,maxHeight:a.maxHeight};if(!this.options.onScreenshot){d.close(),this.screenshotDenied("not_wired",false);break}return Qn(t.slice(1)),this.options.onScreenshot(l,d,(p,c)=>this.screenshotDenied(p,c)),true}case "gem.token.denied":this.options.onTokenDenied?.(a);break;case "gem.localServer":this.options.onLocalServer?.(a);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(a);break;case "gem.player":{this.options.onPlayer?.(Wo(a));break}case "gem.roomEvent":this.options.onRoomEvent?.(a);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(a);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(a);break;case "gem.socketState":this.options.onSocketState?.(a);break;case "gem.signalEvent":this.options.onSignalEvent?.(a);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(a);break;case "gem.clusterTarget":this.options.onClusterTarget?.(a);break;case "gem.partyResult":this.options.onPartyResult?.(a);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(a);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(a);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(a);break;case "gem.adResult":this.options.onAdResult?.(a);break;case "gem.signInResult":this.options.onSignInResult?.(a);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(a);break;case "gem.error":this.options.onError?.(a.code,a.message);break;default:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,t){this.send({gem:g,type:"gem.screenshot.denied",reason:e,retryable:t});}};function Qn(n){for(let e of n)try{e?.close?.();}catch{}}var Bo=16384;function Ko(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:Jo(e)}function Jo(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 Zn=["p2p","dedicated","unknown"],lt=["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=Xo(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 Xo(n,e,t){let r=Math.floor(t/1e3);return n.filter(i=>lt.includes(i.type)).slice(0,100).map(i=>{let o=Yo(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:i.value===void 0?{}:{value:i.value}}})}function Yo(n){if(n!==void 0)return Zn.includes(n)?n:"unknown"}function Kt(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 H=class extends Error{constructor(t,r,i,o,s){super(`${t} (${r}): ${i}`);this.reason=t;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=s;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}};var Qo=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),u=class extends Error{constructor(t,r,i){super(`${t}: ${r}`,i);this.reason=t;this.name="DedicatedServerError",this.retryable=Qo.has(t),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var er=["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"],Zo=new Set(er);function Re(n){return typeof n=="string"&&Zo.has(n)?n:"unknown"}var je="webrtc_dedicated",Xt=["universal","mobile","web"];var ea="p2p_unavailable",ta="capacity_unavailable",na=2,tr=3e4,nr=1e3,rr=2e4;async function ct(n){let e=U(n.clusterTargetId),t=n.nextClusterTarget,r=0,i=n.clock??re,o=n.retry??{},s=o.budgetMs??tr,a=o.maxDelayMs??rr,d=o.initialDelayMs??nr,l=i.now(),p=l+s,c=0;for(;;){c++;try{let m=await zt(n.signal,"while allocating",()=>n.client.post(`${ar(n)}/start_match`,e===void 0?{}:{cluster_target_id:e},n.signal));return {matchId:m.match_id,status:m.status}}catch(m){if(!ra(m)||s<=0)throw m;if(m.status===503&&m.code===ea)throw new u("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: ${m.message}`,{cause:m});if(r=m.code===ta?r+1:0,t!==void 0&&r>=na){let M=t;t=void 0;let C=U(await M());C!==void 0&&(e=C,r=0);}let f=Math.min(a,d*2**(c-1)),v=Math.min(a,(m.retryAfterSeconds??0)*1e3),A=Math.max(f/2,v)+Math.random()*(f/2);if(i.now()+A>p)throw ia(n,m,c,i.now()-l,s);if(o.onWaiting?.({attempt:c,elapsedMs:i.now()-l,budgetMs:s,nextAttemptInMs:A,status:m.status,message:m.message}),await pt(i,A,n.signal),n.signal?.aborted)throw Jt("while waiting to allocate")}}}function ra(n){return n instanceof H?n.status===503?true:n.status===429&&n.code!=="too_many_concurrent_matches":false}function ia(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 u("start_rate_limited",`the platform was still limiting match starts for room ${n.roomId} after ${o}: ${e.message}`,{cause:e}):new u("no_server_ready",`the platform had no server ready for room ${n.roomId} after ${o}: ${e.message}`,{cause:e})}var oa=12e4,aa=1e3;async function ut(n){let{clock:e,matchId:t}=n,r=n.pollIntervalMs??aa,i=n.timeoutMs??oa,o=e.now()+i,s=ir(n),a={seen:n.knownToExist===true};for(;;){let d=await or(n,s,a);if(d.outcome!==null)return d.outcome;if(e.now()+r>o)throw new u("timeout",`match ${t} was still ${d.status} after ${i}ms`);await pt(e,r,n.signal);}}async function Yt(n){return (await or(n,ir(n),{seen:n.knownToExist===true})).outcome}function ir(n){let e=new URLSearchParams({platform:n.version.platform,game_version:n.version.gameVersion});return `${ar(n)}/matches/${encodeURIComponent(n.matchId)}/status?${e}`}async function or(n,e,t){let{matchId:r}=n,i=n.clock.now(),o;try{o=await zt(n.signal,"while polling match status",()=>n.client.get(e,n.signal));}catch(s){if(s instanceof H&&s.reason==="not_found")return {status:"not_found",outcome:t.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw s}if(t.seen=true,o.status==="ready")return {status:"ready",outcome:sa(r,o,i)};if(o.status==="failed"){let s=o.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:Re(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function mt(n){let e=await zt(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 zt(n,e,t){if(n?.aborted)throw Jt(e);try{return await t()}catch(r){throw n?.aborted?Jt(e,r):r}}function Jt(n,e){return new u("aborted",`the caller aborted ${n}`,e===void 0?void 0:{cause:e})}function sa(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 ar(n){return `/v1/games/${encodeURIComponent(n.gameId)}/game-rooms/${encodeURIComponent(n.roomId)}`}function pt(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 da=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),Zt="embedder_relay_unavailable",la="embedder_no_relay",ca=new Set([Zt]),en=new Set([la]),ht=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new Qt(this)}handleEvent(e){let t=this.pending.get(e.matchId);if(t!==void 0){if(e.event==="matchEnded"){t.refuse(new u("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 u("signaling_failed","the parent relayed an answer with no SDP in it"));return}t.settle({sdp:e.sdp});return}t.refuse(ua(e.code,e.message));}}register(e,t){this.pending.get(e)?.refuse(new u("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 u("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 u("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 ua(n,e){let t=e??"the offer was refused",r=n===void 0?t:`${t} (${n})`;return new u(ma(n),r,{platformCode:n})}function ma(n){return n===void 0||ca.has(n)?"signaling_failed":en.has(n)?"offer_refused":da.has(n)?n==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var Qt=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,t){if(this.closed)return Promise.reject(new u("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 u("aborted","the caller aborted before the offer was sent")):new Promise((i,o)=>{let s=()=>{a(),o(new u("aborted","the caller aborted the signaling exchange"));},a=()=>{t?.removeEventListener("abort",s),this.hub.release(e.matchId,d),this.teardown===a&&(this.teardown=null);},d={settle:l=>{a(),i(l);},refuse:l=>{a(),o(l);}};this.teardown=a,t?.addEventListener("abort",s),this.hub.register(e.matchId,d);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(l){d.refuse(l instanceof u?l:new u("signaling_failed",l instanceof Error?l.message:String(l),{cause:l}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var sr="match_ended:",dr="server_shutdown:",lr="kicked:",pa=123;function ha(n){if(typeof n!="string"||n.length===0||n.length>pa)return {kind:"other"};if(n.startsWith(sr)){let e=Re(n.slice(sr.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return n.startsWith(dr)?{kind:"server_shutdown",cause:n.slice(dr.length)}:n.startsWith(lr)?{kind:"kicked",detail:n.slice(lr.length)}:{kind:"other"}}function tn(n,e,t){let r=ha(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 ga="join",fa="welcome",ya="rejected",nn=25e3,va=1e3,rn=1;function on(n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0}var ba={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 an(n){let e=typeof n=="string"?n:"unknown";return new u(ba[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function Ne(n){let{channel:e,clock:t}=n;return new Promise((r,i)=>{let o=false,s=Math.min(n.credentialExpiresAt-t.now(),n.ceilingMs??nn),a=t.setTimeout(()=>T(new u("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(s,va)),d=A=>{let M=A.data;if(typeof M!="string"){c(M);return}let C;try{C=JSON.parse(M);}catch{c(M);return}if(o){c(M);return}if(C.t===fa){let h=on(C.heartbeat_interval);v({...typeof C.player_id=="string"?{playerId:C.player_id}:{},...typeof C.match_id=="string"?{matchId:C.match_id}:{},...h===void 0?{}:{heartbeatIntervalMs:h}});return}if(C.t===ya){T(an(C.reason));return}c(M);},l=()=>{T(new u("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},p=()=>{T(new u("aborted","the caller aborted during the join exchange"));},c=A=>{o&&n.onMessage?.(A);},m=()=>{t.clearTimeout(a),e.removeEventListener("close",l),n.signal?.removeEventListener("abort",p);},f=()=>{e.removeEventListener("message",d);},v=A=>{o=true,m(),n.onMessage===void 0&&f(),r({welcome:A,detach:f});},T=A=>{o||(o=true,m(),f(),i(A));};if(e.addEventListener("message",d),e.addEventListener("close",l),n.signal?.aborted){p();return}n.signal?.addEventListener("abort",p);try{e.send(JSON.stringify({t:ga,credential:n.credential,...n.wire===void 0?{}:{wire:n.wire},...n.heartbeat===!0?{heartbeat:rn}:{}}));}catch(A){T(new u("connection_failed",`the join frame could not be sent on the open channel: ${String(A)}`,{cause:A}));}})}function gt(){return {exchange(){return Promise.reject(new u("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,qe=2,sn=4,cn=8,wa=2,ka=1e3,un="heartbeat timeout",ft="gem-uu",yt=2,ur="gem_transports";function $e(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){if(typeof t!="string")continue;let r=t.toLowerCase();!Sa(r)||e.includes(r)||e.push(r);}return e}function Sa(n){return n==="webtransport"||n==="webrtc"||n==="websocket"}function vt(n,e){if(typeof n!="object"||n===null)return null;let t=n[ur];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 bt(n){return n instanceof Error?n.message===""?n.name:`${n.name}: ${n.message}`:String(n)}var mr=new TextEncoder,pr=new TextDecoder;function mn(n,e){let t=new Uint8Array(e.byteLength+1);return t[0]=n,t.set(e,1),t}function pn(n){let e=0;return n?.reliable===false&&(e|=ue),n?.ordered===false&&(e|=qe),e}function hn(n){return {reliable:(n&ue)===0,ordered:(n&qe)===0}}var gn={reliable:true,ordered:true};function hr(n){return JSON.stringify({t:"join",credential:n,wire:yt,heartbeat:rn})}function gr(n){let e;try{e=JSON.parse(n);}catch{throw new u("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let t=on(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"?an(e.reason):new u("join_refused","the server answered the join out of protocol")}function fn(){return typeof globalThis.WebTransport=="function"&&yn===null}function wt(){return yn}var yn=null;var cr="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Ra(n){let e=Kt(n);if(e.byteLength!==32)throw new u("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var dn=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 u("connection_failed",`a control-stream record claims ${o} bytes`);if(this.buffered.byteLength<4+o)break;let s=this.buffered.slice(4,4+o);this.buffered=this.buffered.slice(4+o),r.push({flags:s[0]??0,payload:s.slice(1)});}return r}};function ln(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 a=globalThis.WebTransport;if(a===void 0)throw new u("connection_failed","this environment has no WebTransport");t=n.certHashBase64===void 0?new a(n.url):new a(n.url,{serverCertificateHashes:[{algorithm:"sha-256",value:Ra(n.certHashBase64)}]});}let r=t,i=a=>{try{r.close();}catch{}throw a},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(yn=cr,i(new u("connection_failed",`${cr}; the rung is skipped for the rest of this page (a reload probes again)`)));let s=new Promise((a,d)=>{setTimeout(()=>d(new u("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,s]);let a=r.incomingBidirectionalStreams.getReader(),d=await Promise.race([a.read(),s]);if(a.releaseLock(),d.done||d.value===void 0)return i(new u("connection_failed","the session ended before the control stream arrived"));let l=d.value,p=l.writable.getWriter();await p.write(ln(sn,mr.encode(hr(n.credential))));let c=new dn,m=l.readable.getReader(),f;for(;f===void 0;){let v=await Promise.race([m.read(),s]);if(v.done||v.value===void 0)return i(new u("connection_failed","the control stream closed before the join was answered"));for(let T of c.push(v.value)){f=gr(pr.decode(T.payload));break}}return {link:_a(r,p,m,c,n.log??(v=>console.warn(v)),yr(f,n.clock)),welcome:f}}catch(a){return i(a)}}function _a(n,e,t,r,i,o){let s,a,d=false,l=v=>{if(!d){d=true,p.stop();try{n.close();}catch{}a?.(v);}},p=bn(o,()=>l(un)),c=(v,T)=>{p.heard(),(v&cn)===0&&s!==void 0&&((v&sn)!==0?s(pr.decode(T),gn):s(T,hn(v)));};(async()=>{try{for(;;){let v=await t.read();if(v.done||v.value===void 0)break;for(let T of r.push(v.value))c(T.flags,T.payload);}}catch{}l("stream closed");})();let m,f;try{let v=n.datagrams;if(v?.readable!==void 0&&v.writable!==void 0){let T=v.readable.getReader();f=v.writable.getWriter(),m=v,(async()=>{try{for(;;){let A=await T.read();if(A.done||A.value===void 0)break;let M=A.value;M.byteLength!==0&&c((M[0]??0)|ue|qe,M.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(v){m=void 0,f=void 0,i(`[gem] webtransport datagram lane unusable (${bt(v)}); unreliable sends ride the stream`);}return n.closed.then(v=>l(fr(v?.reason)??"session closed"),()=>l("session failed")),{transport:"webtransport",send(v,T){if(d)return;if(typeof v=="string"){e.write(ln(sn,mr.encode(v))).catch(()=>l("write failed"));return}let A=pn(T);if((A&ue)!==0&&f!==void 0){let M=mn(A,v),C=m?.maxDatagramSize;if(C===void 0||M.byteLength<=C){f.write(M).catch(()=>{});return}}e.write(ln(A,v)).catch(()=>l("write failed"));},onMessage(v){s=v;},onClose(v){a=v;},close(){l("closed");}}}function vn(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 u("connection_failed","this environment has no WebSocket"));t=new i(n.url);}let r=t;return r.binaryType="arraybuffer",new Promise((i,o)=>{let s=false,a=setTimeout(()=>{s||(s=true,r.close(),o(new u("timeout","websocket did not come up in time")));},e),d=f=>{s||(s=true,clearTimeout(a),r.close(),o(f));},l=()=>{r.send(hr(n.credential));},p=f=>{if(s)return;if(typeof f.data!="string"){d(new u("join_refused","the server sent binary before answering the join"));return}let v;try{v=gr(f.data);}catch(T){d(T);return}s=true,clearTimeout(a),r.removeEventListener("open",l),r.removeEventListener("message",p),r.removeEventListener("close",c),r.removeEventListener("error",m),i({link:Ea(r,yr(v,n.clock)),welcome:v});},c=()=>{d(new u("connection_failed","the websocket closed before the join was answered"));},m=()=>{d(new u("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",l),r.addEventListener("message",p),r.addEventListener("close",c),r.addEventListener("error",m),r.readyState===1&&l();})}function fr(n){return typeof n=="string"&&n.length>0?n:void 0}function yr(n,e){return n.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:n.heartbeatIntervalMs}}function bn(n,e){if(n===void 0)return {heard:()=>{},stop:()=>{}};let{clock:t}=n,r=Math.max(n.intervalMs,ka)*wa,i=t.now(),o=null,s=()=>{o=null;let a=t.now()-i;if(a>=r){e();return}o=t.setTimeout(s,r-a);};return o=t.setTimeout(s,r),{heard:()=>{i=t.now();},stop:()=>{o!==null&&(t.clearTimeout(o),o=null);}}}function Ea(n,e){let t,r,i=false,o=a=>{if(!i){i=true,s.stop();try{n.close();}catch{}r?.(a);}},s=bn(e,()=>o(un));return n.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){t?.(a.data,gn);return}let d=new Uint8Array(a.data);if(d.byteLength===0)return;let l=d[0]??0;(l&cn)===0&&t?.(d.slice(1),hn(l));})),n.addEventListener("close",(a=>o(fr(a?.reason)??"socket closed"))),{transport:"websocket",send(a,d){if(!i){if(typeof a=="string"){n.send(a);return}n.send(mn(pn(d),a));}},onMessage(a){t=a;},onClose(a){r=a;},close(){o("closed");}}}function wn(n,e,t,r){let i,o,s=false,a=t,d=c=>{if(!s){s=true,l.stop();try{n.close();}catch{}try{e.close();}catch{}o?.(c);}},l=bn(r,()=>d(un)),p=(c,m)=>{if(l.heard(),typeof c=="string"){i?.(c,gn);return}let f=new Uint8Array(c);if(f.byteLength===0)return;let v=f[0]??0;(v&cn)===0&&i?.(f.slice(1),hn(v|m));};if(n.addEventListener("message",(c=>p(c.data,0))),n.addEventListener("close",(()=>d("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let c=e.connectionState;(c==="failed"||c==="closed")&&d(`connection ${c}`);})),a!==void 0){let c=a;c.addEventListener("message",(m=>p(m.data,ue|qe))),c.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(c,m){if(s)return;if(typeof c=="string"){n.send(c);return}let f=pn(m),v=mn(f,c);if((f&ue)!==0&&a!==void 0&&a.readyState==="open"){a.send(v);return}n.send(v);},onMessage(c){i=c;},onClose(c){o=c;},close(){d("closed");}}}var vr=10240,br=2048,xa=new TextEncoder;function wr(n){return xa.encode(n).length}function ie(n,e){let t=i=>{throw new u("invalid_sdp",`the ${e} ${i}`)},r=wr(n);r>=vr&&t(`is ${r} bytes, over the ${vr} 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=wr(i);o>br&&t(`has a ${o}-byte line, over the ${br} limit`);}}function kt(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 Ta=3e3,Aa=1e4,Ia=15e3;async function He(n){let e=n.peerConnection;try{Sr(n,"before the handshake started"),kn(n);let t=e.createDataChannel(n.channelLabel??"gem",{ordered:!0});for(let s of n.extraChannels??[]){let a=e.createDataChannel(s.label,{...s.ordered===void 0?{}:{ordered:s.ordered},...s.maxRetransmits===void 0?{}:{maxRetransmits:s.maxRetransmits}});n.onExtraChannel?.(s.label,a);}let r=await e.createOffer();await e.setLocalDescription(r),await Ma(e,n),kn(n);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new u("invalid_sdp","the offer carried no SDP");ie(i,"offer"),kr(i,"offer");let o=await Pa(n,i);if(kn(n),typeof o?.sdp!="string")throw new u("invalid_sdp","the signaling channel answered without an SDP");return ie(o.sdp,"answer"),kr(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await La(t,n),Sr(n,"before the channel opened"),t}catch(t){throw e.close(),Ca(t)}}function Ca(n){return n instanceof u?n:Er(n)?me():new u("connection_failed",xr(n),{cause:n})}function kr(n,e){if(kt(n))throw new u("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 Pa(n,e){let t=n.exchangeTimeoutMs??Aa,r=_r(n,t),i=n.signaling.exchange({matchId:n.matchId,sdp:e,intent:n.intent??"initial"},n.signal).catch(o=>{throw o instanceof u?o:Er(o)?me():new u("signaling_failed",xr(o),{cause:o})});return Oa(i,n,r,()=>r.exhausted?Sn("while the offer was in flight"):new u("timeout",`no answer arrived within ${t}ms`))}function Ma(n,e){if(n.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:t}=e;return new Promise(r=>{let i=()=>{t.clearTimeout(s),n.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{n.iceGatheringState==="complete"&&i();},s=t.setTimeout(i,e.gatherTimeoutMs??Ta);n.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function La(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 u("connection_failed",`the data channel was already '${n.readyState}' when the answer was applied`));let{clock:t}=e,r=e.openTimeoutMs??Ia,i=_r(e,r);return new Promise((o,s)=>{let a=()=>{t.clearTimeout(m),n.removeEventListener("open",d),n.removeEventListener("close",l),n.removeEventListener("error",l),e.signal?.removeEventListener("abort",p);},d=()=>{a(),o();},l=f=>{a(),s(new u("connection_failed","the data channel failed before it opened",Rr(f)===void 0?void 0:{cause:Rr(f)}));},p=()=>{a(),s(me());},c=()=>{a(),s(i.exhausted?Sn("while the channel was still opening"):new u("timeout",`the data channel did not open within ${r}ms`));},m=t.setTimeout(c,i.ms);n.addEventListener("open",d),n.addEventListener("close",l),n.addEventListener("error",l),e.signal?.addEventListener("abort",p);})}function _r(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 Oa(n,e,t,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(me()):new Promise((s,a)=>{let d=c=>{i.clearTimeout(p),o?.removeEventListener("abort",l),c();},l=()=>d(()=>a(me())),p=i.setTimeout(()=>d(()=>a(r())),t.ms);o?.addEventListener("abort",l),n.then(c=>d(()=>s(c)),c=>d(()=>a(c)));})}function Sr(n,e){if(n.credentialExpiresAt!==void 0&&!(n.clock.now()<n.credentialExpiresAt))throw Sn(`already ${e}`)}function Sn(n){return new u("credential_expired",`the join credential ran out ${n} \u2014 poll match status again for a fresh one`)}function kn(n){if(n.signal?.aborted)throw me()}function me(){return new u("aborted","the caller aborted the connection attempt")}function Er(n){return n?.name==="AbortError"}function Rr(n){return n?.error}function xr(n){return n instanceof Error?n.message:String(n)}var We="0.1.0-beta",Tr="0-beta",_e="web",Da=/^(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 Ga(n){let e=Da.exec(n),t=e?.[1],r=e?.[4];return t===void 0?null:r===void 0?t:`${t}-${r}`}function Ar(n,e){let t=Fa(n.platform,e),r=n.engineVersion;if(r===void 0)return {...n,platform:t,engineVersion:We};let i=Ga(r);if(i===null)throw new u("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!==Tr)throw new u("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${Tr}' 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 Fa(n,e){if(n===void 0||n===_e)return _e;if(!Xt.includes(n))throw new u("misconfigured",`${e} refused: platform '${String(n)}' is not a client platform gem-api recognises \u2014 it knows ${Xt.map(t=>`'${t}'`).join(", ")}. Remove the field: the SDK reports '${_e}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${n}' was replaced with '${_e}' 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.`),_e}function ja(n){let{client:e,clock:t,rooms:r}=n,i=n.signaling??gt,o=n.log??(h=>console.warn(h)),s=new ce({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,d=(h,b)=>{let S=a.get(h)??new Set;S.add(b),a.set(h,S);},l=(h,b)=>{let S=a.get(h);S!==void 0&&(S.delete(b),S.size===0&&a.delete(h));},p=async h=>{if(r.isHost&&!Ka(r)&&r.currentRoom?.matchId===void 0){let b=U(h.clusterTargetId);await r.startMatch({...b===void 0?{}:{clusterTargetId:b},...h.retry===void 0?{}:{retry:h.retry},...h.signal===void 0?{}:{signal:h.signal}});}return Or(r.matchConnectionState==="suspended"?await r.reconnectToMatch(Rn(h)):await r.awaitMatch(Rn(h)))},c=async h=>Or(await r.pollMatchStatus(Rn(h))),m=async(h,b)=>{let S=false;try{let w=await p(h),D=r.currentRoom?.transports;if(D!==void 0&&!D.includes("webrtc"))throw new u("misconfigured",`the room template offers (${D.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 P=h.peerConnection??Dr();S=!0;let G=await He({peerConnection:P,signaling:b,clock:t,matchId:w.matchId,credentialExpiresAt:w.credentialExpiresAt,...St(h,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),N=null;if(h.presentCredential!==!1)try{N=await Ne({channel:G,clock:t,credential:w.joinCredential,credentialExpiresAt:w.credentialExpiresAt,...St(h,"onMessage","signal"),...h.welcomeTimeoutMs===void 0?{}:{ceilingMs:h.welcomeTimeoutMs}});}catch(q){throw K(G),K(P),q}return Ba(r,w,G,P,b,h.reportDisconnect!==!1,h.reportConnected!==!1,N,{remember:d,forget:l},h.onMatchEnded)}catch(w){throw S&&Lr(s,w),K(b),w}},f=async(h,b,S,w,D,P)=>{if(h==="webtransport"){let L=w?.webtransport;if(L===void 0)throw new u("misconfigured","webtransport is not advertised");let Y={credential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,clock:t};if(typeof L.named_url=="string"&&L.named_url!==""){let ne=Math.max(Math.floor(P/2),1e3);try{return await Ue({url:L.named_url,timeoutMs:ne,log:o,...Y})}catch(oe){if(wt()!==null)throw oe;return o(`[gem] webtransport named dial failed (${bt(oe)}); retrying the pinned dial`),Ue({url:L.url,certHashBase64:L.cert_sha256_b64,timeoutMs:ne,log:o,...Y})}}return Ue({url:L.url,certHashBase64:L.cert_sha256_b64,timeoutMs:P,...Y})}if(h==="websocket"){let L=w?.websocket;if(L===void 0)throw new u("misconfigured","websocket is not advertised");return vn({url:L.url,credential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,clock:t,timeoutMs:P})}let G=b.peerConnection??Dr(),N,q=await He({peerConnection:G,signaling:D,clock:t,matchId:S.matchId,credentialExpiresAt:S.credentialExpiresAt,extraChannels:[{label:ft,ordered:false,maxRetransmits:0}],onExtraChannel:(L,Y)=>{L===ft&&(N=Y);},...St(b,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...b.exchangeTimeoutMs===void 0&&b.redial===true?{exchangeTimeoutMs:qa}:{}}),B;try{B=await Ne({channel:q,clock:t,credential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,wire:yt,heartbeat:!0,...St(b,"signal"),...b.welcomeTimeoutMs===void 0?{}:{ceilingMs:b.welcomeTimeoutMs}});}catch(L){throw K(q),K(G),L}let E=B.welcome.heartbeatIntervalMs;return {link:wn(q,G,N,E===void 0?void 0:{clock:t,intervalMs:E}),welcome:B.welcome,channel:q,peerConnection:G}},v=(h,b,S,w,D)=>{let P=false,G;w.link.onClose(E=>{!P&&h.reportDisconnect!==false&&tn(r,b.matchId,E),G?.(E);}),h.reportDisconnect!==false&&h.reportConnected!==false&&r.notifyMatchConnected(b.matchId);let N={transport:w.link.transport,send:(E,L)=>w.link.send(E,L),onMessage:E=>w.link.onMessage(E),onClose:E=>{G=E;},close:()=>w.link.close()},q=()=>{P||(P=true,K(w.link),K(D));},B=E=>{if(!P){try{h.onMatchEnded?.(E);}catch{}q();}};return d(b.matchId,B),{matchId:b.matchId,transport:S,link:N,joinCredential:b.joinCredential,credentialExpiresAt:b.credentialExpiresAt,welcome:w.welcome,...w.channel===void 0?{}:{channel:w.channel},...w.peerConnection===void 0?{}:{peerConnection:w.peerConnection},close(){l(b.matchId,B),q();}}},T=async(h,b)=>{let S=r.currentRoom?.id,w=r.gameId,D=()=>({advert:vt(r.currentRoom?.settings,h),template:r.currentRoom?.transports??null});if(S===void 0||w===null)return D();try{let P=await e.get(`/v2/games/${encodeURIComponent(w)}/game-rooms/${encodeURIComponent(S)}`,b);return {advert:vt(P.settings,h),template:$e(P.transports)??r.currentRoom?.transports??null}}catch{return D()}},A=(h,b)=>{let S=h??Ir;return b.length===0?S:S.filter(w=>b.includes(w))},M=async(h,b,S)=>{try{let w=await p(h),{advert:D,template:P}=await T(w.matchId,h.signal),G=A(P,b),N=G.filter(F=>Ha(F,D)),q=wt();if(q!==null&&G.includes("webtransport")&&D?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${q} (learned on an earlier dial in this page)`),N.length===0){let F=P===null?`the default order (${Ir.join(", ")})`:`the room template's transports (${P.join(", ")||"none"})`;throw new u("misconfigured",`none of ${F}`+(b.length>0?`, narrowed to (${b.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let B=h.transportAttemptTimeoutMs??Na,E=()=>h.deadlineAt===void 0?1/0:h.deadlineAt-t.now(),L=F=>n.signalingReady===void 0||F<=0?Promise.resolve(!0):n.signalingReady(F),Y=[],ne=[];for(let F of N){if(E()<Pr){o(`[gem] ${F} rung not tried: the reconnect budget is spent`);break}ne.length>0&&w.credentialExpiresAt-t.now()<Mr&&(w=await c(h)),ne.push(F);let Gn=!1,Fn=!1,Ye={attempts:0,waitedMs:0};for(;;){if(F==="webrtc"&&h.redial===!0){let Q=Math.min(Cr,E());await L(Q)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(Q)}ms; offering anyway`);}let ai=Math.max(Math.min(B,E()),Pr);try{return v(h,w,F,await f(F,h,w,D,S,ai),S)}catch(Q){let $=Q instanceof u?Q:new u("connection_failed",Q instanceof Error?Q.message:String(Q),{cause:Q});if(F==="webrtc"&&Lr(s,$),($.reason==="credential_expired"||$.reason==="credential_reused")&&!Gn){Gn=!0,w=await c(h);continue}if(F==="webrtc"&&$.reason==="signaling_failed"&&$.platformCode===Zt&&!Fn){Fn=!0;let ae=Math.min(Cr,E());if(o(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(ae)}ms for the socket before offering again`),await L(ae))continue}if($.reason==="join_rate_limited"){let ae=Ua(Ye,Math.random,E());if(ae!==null){if(Ye.attempts+=1,Ye.waitedMs+=ae,o(`[gem] ${F} rung: the server is rate-limiting this player's joins; waiting ${Math.round(ae)}ms before presenting again (retry ${Ye.attempts} of ${Fr.maxAttempts})`),await pt(t,ae,h.signal),h.signal?.aborted)throw new u("aborted","the caller aborted while waiting out a join rate limit");w.credentialExpiresAt-t.now()<Mr&&(w=await c(h));continue}}if($a.has($.reason)||$.reason==="credential_expired"||F==="webrtc"&&Gr($)){o(`[gem] ${F} rung failed (${$.reason}): ${bt($.cause??$)} \u2014 `+(ne.length<N.length?`falling through to ${N[ne.length]}`:"no rungs left")),Y.push($);break}throw o(`[gem] ${F} rung refused the session (${$.reason}): ${$.message}`),$}}}let oe=Y[Y.length-1];throw oe===void 0?new u("timeout",`the reconnect budget ran out before any transport (${N.join(", ")}) could be tried`):new u(oe.reason,`every transport tried (${ne.join(", ")}) failed; the last said: ${oe.message}`,{cause:Y,platformCode:oe.platformCode})}catch(w){throw K(S),w}};return {listClusterTargets:async(h={})=>mt({client:e,...h}),handleMatchEnded(h,b){let S=a.get(h);if(S!==void 0){a.delete(h);for(let w of S)w(b);}},connect:(async(h={})=>{let b=h.signaling??i();return h.transports===void 0?m(h,b):M(h,h.transports,b)})}}var Ir=["webtransport","webrtc","websocket"],Na=1e4,qa=5e3,Cr=3e3,Pr=1e3,Mr=1e4,$a=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function Gr(n){return n.platformCode!==void 0&&en.has(n.platformCode)}var Fr={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function Ua(n,e=Math.random,t=1/0){let r=Fr;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 Ha(n,e){return n==="webrtc"?e===null||e.webrtc!==false:e===null?false:n==="webtransport"?e.webtransport!==void 0&&fn():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||Wa(e.websocket.url)}function Wa(n){if(typeof n!="string")return false;let e;try{e=new URL(n).hostname.toLowerCase();}catch{return false}return st(e)}function Rn(n){return {...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.pollIntervalMs===void 0?{}:{pollIntervalMs:n.pollIntervalMs},...n.signal===void 0?{}:{signal:n.signal}}}var Va=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Lr(n,e){e instanceof u&&(!Va.has(e.reason)&&!Gr(e)||n.report([{type:"connection_failures_total",value:1}]));}function Ba(n,e,t,r,i,o,s,a,d,l){let p=false,c=()=>{p||tn(n,e.matchId,void 0);};o&&(t.addEventListener("close",c),s&&n.notifyMatchConnected(e.matchId));let m=()=>{p||(p=true,t.removeEventListener("close",c),a?.detach(),K(t),K(r),K(i));},f=v=>{if(!p){try{l?.(v);}catch{}m();}};return d.remember(e.matchId,f),{matchId:e.matchId,channel:t,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:a?.welcome??null,close(){d.forget(e.matchId,f),m();}}}function Ka(n){let e=n.matchSession.phase;return e!=="none"&&e!=="ended"}function Or(n){if(n.status==="failed")throw new u("allocation_failed",`match ${n.matchId} did not come up: ${n.reason}`);if(n.status==="ended")throw new u("match_ended",`match ${n.matchId} ended (${n.reason}) before this side connected.`);if(n.protocol!==je)throw new u("unsupported_protocol",`match ${n.matchId} speaks '${n.protocol}', which a browser cannot connect. Only '${je}' 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 u("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 Dr(){let n=globalThis.RTCPeerConnection;if(!n)throw new u("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 St(n,...e){let t={};for(let r of e)n[r]!==void 0&&(t[r]=n[r]);return t}var Ee=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:Rt(i.credential)??"",hostFingerprint:Rt(i.host_fingerprint)??"",hostEpoch:_t(i.host_epoch)??0,expiresAt:(_t(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 d of Array.isArray(i.ice_servers)?i.ice_servers:[]){let l=d,p=(Array.isArray(l.urls)?l.urls:[]).filter(c=>typeof c=="string"&&c.length>0);p.length!==0&&o.push({urls:p,username:Rt(l.username)??"",credential:Rt(l.credential)??""});}let s=_t(i.expires_at),a=_t(i.ttl_seconds);return {iceServers:o,expiresAt:s!==void 0?s*1e3:Date.now()+(a??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 Rt(n){return typeof n=="string"&&n.length>0?n:void 0}function _t(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}var Ja=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=Ja.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 Xa=/^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 Xa.test(r)?r:null}function xe(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 _n=5e3,Ya=12e4+_n,za=1024,Qa=6e4,Za=1e4,jr=64*1024,Nr=5;function xt(n){let e=new Map,t=-1/0,r=null,i=(()=>{let a;try{a=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 a.username!==""||a.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:a.href,shown:`${a.protocol}//${a.host}`}})(),o=()=>{let a=n.subtle??globalThis.crypto?.subtle;if(!a)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 a},s=async()=>{if(!i.ok)throw new k("keys_unavailable",i.reason);let a=n.fetch??((m,f)=>globalThis.fetch(m,f)),d;try{d=await a(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(Za)});}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(!d.ok)throw new k("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let l;try{let m=await d.text();if(m.length>jr)throw new k("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${jr} characters, which is not a key set this platform publishes.`);l=JSON.parse(m);}catch(m){throw m instanceof k?m:new k("keys_unavailable",`the JWKS endpoint at ${i.shown} did not answer with a readable key set.`)}let p=Array.isArray(l.keys)?l.keys:[];if(p.length>Nr)throw new k("keys_unavailable",`the JWKS endpoint published ${p.length} keys, over the ${Nr} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=o();for(let m of p){let f=m;if(f.kty==="RSA"&&!(f.alg!==void 0&&f.alg!=="RS256")&&!(f.use!==void 0&&f.use!=="sig")&&!(typeof f.kid!="string"||f.kid.length===0))try{let v=await c.importKey("jwk",{...m,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(f.kid,v);}catch{}}};return {async key(a){let d=e.get(a);if(d)return d;if(!i.ok)throw new k("keys_unavailable",i.reason);if(r)return await r,e.get(a)??null;let l=n.now();if(!Number.isFinite(l))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 l<t&&(t=-1/0),l-t<Qa?null:(t=l,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var Be=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>=za){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,t+Ya),true}};function $r(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 qr(n){try{let e=new TextDecoder().decode($r(n)),t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch{return null}}async function Tt(n,e,t,r,i){let o=E=>{throw new k("peer_unauthenticated",`the peer's join credential is not usable: ${E}`)},s=n.split(".");s.length!==3&&o("it is not a three-part JWT");let[a,d,l]=s,p=qr(a);p===null&&o("its header does not decode"),p.alg!=="RS256"&&o(`its alg is ${JSON.stringify(p.alg)}, not RS256`),p.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(p.typ)}, not p2p+jwt`);let c=p.kid;(typeof c!="string"||c.length===0)&&o("it names no key");let m=await t.key(c);m===null&&o("it was signed by a key this build cannot resolve");let f=i.subtle??globalThis.crypto?.subtle;f||o("this environment has no WebCrypto");let v=new TextEncoder().encode(`${a}.${d}`),T;try{T=$r(l);}catch{o("its signature does not decode");}await f.verify({name:"RSASSA-PKCS1-v1_5"},m,T,v)||o("its signature does not verify");let M=qr(d);M===null&&o("its payload does not decode");let C=M,h=E=>typeof C[E]=="string"?C[E]:"",b=E=>typeof C[E]=="number"&&Number.isFinite(C[E])?C[E]:NaN;h("iss")!==i.issuer&&o("it was issued by someone else"),h("aud")!==`${i.issuer}/p2p-match`&&o("its audience is not this platform"),h("match_id")!==e.matchId&&o("it is for another match"),h("game_id")!==e.gameId&&o("it is for another game");let S=b("exp")*1e3,w=b("nbf")*1e3;(!Number.isFinite(S)||e.now>S+_n)&&o("it has expired"),Number.isFinite(w)&&e.now<w-_n&&o("it is not valid yet");let D=h("role");D!=="host"&&D!=="client"&&o("it names no usable role");let P=b("host_epoch");P!==e.hostEpoch&&o("it names a different host epoch");let G=Ve(h("fingerprint"));G===null&&o("its fingerprint claim is malformed"),xe(G,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let N=Ve(h("host_fingerprint"));N===null&&o("its host fingerprint claim is malformed"),xe(N,e.hostFingerprint)||o("it was issued against a different host certificate");let q=h("jti");q.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit(q,e.now)||o("it has already been used");let B=h("sub");return B.length===0&&o("it names no player"),{playerId:B.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:P,role:D,fingerprint:G,hostFingerprint:N,jti:q,expiresAt:S}}var he=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 xn(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 Tn(n){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,3),t.setUint8(1,n),e}function An(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 Ur(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 Wr=3e4,Te=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 At={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 It(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 Ct(){let n=globalThis.RTCPeerConnection;return n?.generateCertificate?n.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var Br=1,is=3e4,Kr=2e3,os=5e3,Jr=6e4,as=8,Cn=class{constructor(e=as){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;}},ss=new Cn,ds=8,ls=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),Ae=class{constructor(e){this.options=e;this.keys=e.keys??xt({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new Et;links=new Map;replays=new Be;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=Br+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??is;this.credentialDeadline=this.options.clock.now()+t;let r=new Promise((a,d)=>{this.ready={resolve:a,reject:d};}),i=U(this.options.clusterTargetId);if(i!==void 0)try{let a=await this.options.api.turnLease(this.options.matchId,i,e);this.iceServers=a.iceServers,this.mark("turn leased");}catch(a){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: ${In(a)}`);}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),s=()=>this.fail(new k("aborted","the caller aborted while connecting"));e?.aborted?s():e?.addEventListener("abort",s);try{await r;}finally{this.options.clock.clearTimeout(o),e?.removeEventListener("abort",s),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=j(e.playerId),r=j(e.hostPlayerId),i=Pt(e.hostEpoch);if(!(t===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=t,this.migration===null&&(this.migration=new Te(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,Br),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(s=>this.report_(s));}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??ss,s=()=>this.closed||e!==this.credentialGeneration,a=os;for(;;){let d=o.delayUntilAllowed(this.options.clock.now());if(d>0&&!await this.waitForCredential(d,s))return;o.record(this.options.clock.now());try{let l=await this.options.api.joinCredential(this.options.matchId,i);if(s())return;this.credential=l,this.mark("credential ready"),this.maybeAuthenticate();return}catch(l){if(s())return;let p=l.status,c;if(p===409)c=Kr;else if(p===429){let m=l.retryAfterSeconds;typeof m=="number"&&Number.isFinite(m)&&m>=0?c=m*1e3:(c=a,a=Math.min(a*2,Jr)),c=Math.min(Math.max(c,Kr),Jr);}else throw l;if(!await this.waitForCredential(c,s))return}}}async waitForCredential(e,t){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!t())}async onOffer(e){let t=j(e.fromPlayerId),r=j(e.sdp);if(t===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(t),this.pendingOffers.size>=ds){let p=this.pendingOffers.keys().next().value;p!==void 0&&this.pendingOffers.delete(p);}this.pendingOffers.set(t,e);return}if(!this.isHost||this.migration.isKicked(t)===true)return;let i=j(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 s=this.links.get(t);s&&this.dropLink(s,"resignalled",false);let a=this.openLink(t,this.nextPeerId++);a.remoteFingerprint=o,await a.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(a);let d=await a.connection.createAnswer();await a.connection.setLocalDescription(d);let l=a.connection.localDescription?.sdp??d.sdp;if(!l)throw new k("invalid_sdp","the browser produced an answer with no SDP");ie(l,"answer"),this.refuseMedia(l,"answer"),this.options.signaling.answer(t,l,a.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let t=j(e.fromPlayerId),r=j(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:xe(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=j(e.fromPlayerId),r=j(e.candidate);if(t===null||r===null)return;let i=this.links.get(t);if(!i)return;let o=j(e.sdpMid),s=Pt(e.sdpMLineIndex)??Pt(e.sdpMLineIndexAlt),a={candidate:r,...o===null?{}:{sdpMid:o},...s===null?{}:{sdpMLineIndex:s}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(a);return}await i.connection.addIceCandidate(a);}onPeerLeft(e){let t=j(e.playerId);if(t===null)return;let r=j(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=j(e.hostPlayerId),r=Pt(e.hostEpoch);if(t===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:t,hostEpoch:r,...j(e.reason)===null?{}:{reason:j(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=j(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=j(e.code)??"unknown",r=j(e.message)??"the platform refused a signaling message";this.report_(new k("signaling_failed",`${t}: ${r}`));}openLink(e,t){let i=(this.options.peerConnectionFactory??It)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let m of Ke){let f=i.createDataChannel(m,At[m]);f.binaryType="arraybuffer",o[m]=f;}let s={playerId:e,assignedPeerId:t,connection:i,channels:o,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},a=m=>{let f=m.candidate;f?.candidate&&this.options.signaling.candidate(e,f.candidate,f.sdpMid??void 0,f.sdpMLineIndex??void 0);},d=()=>this.onIceState(s),l=()=>this.onConnectionState(s),p=m=>{this.onHandshakeMessage(s,m.data).catch(f=>this.report_(f));},c=()=>{this.onReliableOpen(s).catch(m=>this.report_(m));};return i.addEventListener("icecandidate",a),i.addEventListener("iceconnectionstatechange",d),i.addEventListener("connectionstatechange",l),o.reliable.addEventListener("open",c),o.reliable.addEventListener("message",p),s.detachHandshake=()=>{o.reliable.removeEventListener("open",c),o.reliable.removeEventListener("message",p);},s.detachAll=()=>{s.detachHandshake(),i.removeEventListener("icecandidate",a),i.removeEventListener("iceconnectionstatechange",d),i.removeEventListener("connectionstatechange",l);},this.links.set(e,s),s}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=An(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(Hr(r.reason),Ur(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 Tt(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(s){let a=s instanceof k&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",In(s)),a&&this.fail(s);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(xn({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(Tn(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)Xr(e.channels[i]);Xr(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",In(e),{cause:e}));}count(e){this.counted||!ls.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,t){if(kt(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 j(n){return typeof n=="string"&&n.length>0?n:null}function Pt(n){return typeof n=="number"&&Number.isInteger(n)?n:null}function In(n){return n instanceof Error?n.message:String(n)}function Xr(n){try{n.close();}catch{}}var cs=100,us=50,Ie=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??cs)){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??us));}};var Pn="webrtc_p2p";function ms(n){let e=new Ee({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=U(r.clusterTargetId),o=i??U(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 s=await n.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(s.protocol!==Pn)throw new k("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${Pn}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let a=new Ie({bridge:n.bridge,matchId:s.matchId,clock:n.clock}),d=new Ae({api:e,clock:n.clock,matchId:s.matchId,gameId:n.gameId(),baseUrl:typeof n.baseUrl=="function"?n.baseUrl():n.baseUrl,signaling:a,...o===void 0?{}:{clusterTargetId:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await Ct(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...n.boot===void 0?{}:{boot:n.boot},...n.log===void 0?{}:{log:n.log}});a.onDropped(l=>d.notifyCandidatesDropped(l)),t.set(s.matchId,d),d.on("matchEnded",()=>t.delete(s.matchId));try{await d.start(r.signal);}catch(l){throw t.delete(s.matchId),d.close(),l}return d}}}function Yr(n){return typeof n=="string"&&n.trim()!==""}function zr(n,e){return Yr(n)?n.trim():Yr(e)?e:null}function ge(n){return typeof n=="string"&&n!==""?n:void 0}var ps=new Set(["localhost","127.0.0.1","[::1]"]);function Qr(n){let e=ge(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:"&&ps.has(t.hostname)))return e}function hs(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=t??{},i=ge(r.item_id),o=Qr(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function Zr(n){let e=n??{},t=ge(e.player_id),r=ge(e.display_name),i=ge(e.discriminator),o=ge(e.display_tag),s=ge(e.avatar_icon_id),a=Qr(e.avatar_icon_url);return {...t===void 0?{}:{playerId:t},...r===void 0?{}:{displayName:le(r)},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:le(o)},...s===void 0?{}:{avatarIconId:s},...a===void 0?{}:{avatarIconUrl:a},badges:hs(e.badges)}}function Mt(n){if(typeof n!="object"||n===null)return;let e={};for(let[t,r]of Object.entries(n)){let i=Mn(r);i!==void 0&&(e[t]=i);}return e}function Lt(n){if(Array.isArray(n))return n.map(gs).filter(e=>!!e)}function Mn(n){if(Ln(n)||Array.isArray(n)&&n.every(Ln))return n}function Ln(n){return typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)}function gs(n){let e=n??{};if(typeof e.name!="string"||e.name.length===0)return null;let t=Mn(e.fixed),r=Mn(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},...Ce("description",fs(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(Ln)?{allowed:e.allowed}:{},...Ce("min",Je(e.min)),...Ce("max",Je(e.max)),...Ce("minItems",Je(e.min_items)),...Ce("maxItems",Je(e.max_items)),...Ce("maxLength",Je(e.max_length))}}function fs(n){return typeof n=="string"&&n.length>0?n:void 0}function Je(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Ce(n,e){return e===void 0?{}:{[n]:e}}function X(n){let e=n??{},t=I(e.id)??I(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(On):[];return {id:t,gameId:I(e.game_id)??"",name:I(e.name)??"",status:I(e.status)??"open",hostPlayerId:I(e.host_player_id)??"",maxPlayers:z(e.max_players)??0,memberCount:z(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...J("joinCode",I(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...J("roomArgs",Mt(e.room_args)),...J("roomArgsTemplate",Lt(e.room_args_template)),gameChannel:I(e.game_channel)??"release",...J("region",I(e.region)),...J("clusterTargetId",I(e.cluster_target_id)),selfHosted:e.self_hosted===true,...J("matchId",I(e.match_id)),version:z(e.version)??0,...J("templateId",I(e.template_id)),roomType:I(e.game_room_type)??"Standard",...J("transports",$e(e.transports)??void 0),createdAt:z(e.created_at)??0,updatedAt:z(e.updated_at)??0,...J("startedAt",z(e.started_at))}}function On(n){let e=n??{};return {...Zr(e),playerId:I(e.player_id)??"",isReady:e.is_ready===true,role:I(e.role)??"member",joinedAt:z(e.joined_at)??0,...J("groupId",I(e.group_id)),...J("platform",I(e.platform))}}function Xe(n){let e=n??{};return {id:I(e.id)??I(e.game_room_id)??"",gameId:I(e.game_id)??"",name:I(e.name)??"",status:I(e.status)??"open",hostPlayerId:I(e.host_player_id)??"",maxPlayers:z(e.max_players)??0,memberCount:z(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:I(e.game_channel)??"release",roomType:I(e.game_room_type)??"Standard",createdAt:z(e.created_at)??0}}function I(n){return typeof n=="string"&&n.length>0?n:void 0}function z(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function J(n,e){return e===void 0?{}:{[n]:e}}var Pe=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 ys(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},...Ot(t)},e.signal).then(X)}get(e,t){return this.options.client.get(this.roomV2(e),t).then(X)}join(e,t,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...t.partyId===void 0?{}:{party_id:t.partyId},...Ot(r)},t.signal).then(X)}joinByCode(e,t,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...t.partyId===void 0?{}:{party_id:t.partyId},...Ot(r)},t.signal).then(X)}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}:{},...Ot(t)},e.signal).then(X)}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(X)}setReady(e,t,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:t},r).then(X)}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(X)}leaveMatch(e,t){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:t}).then(()=>{})}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 Ot(n){return {platform:n.platform,game_version:n.gameVersion,engine_version:n.engineVersion}}function ys(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 vs(n,e){return Math.min(e,500*2**Math.max(0,n-1))}var bs=1e3,ws=3e3,ks=6e4,Ss=2,ei=new Set(["game_room_closed","game_room_gone"]),Rs=12e4,_s=5e3,Es=new Set(["invalid_cluster_target","capacity_unavailable"]),xs=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function ii(n){return new Dn(n)}var Dn=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new Pe({client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new Me;api;room=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");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 s=>{let a=await this.afterRefusedClusters(s,o);if(a[0]===void 0||a[0]===o[0])throw s;return this.api.create(r,this.version("create"),a[0])})});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,t={}){this.assertNotInRoom("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");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");let t=this.clusterTargets(),r=await this.attachParty(e),i=s=>this.api.quickJoin(r,this.version("quickJoin"),s).catch(a=>this.retryPastStaleMembership(a,r,s)),o=await this.run("quickJoin",async()=>{let s=await t;return i(s).catch(async a=>{let d=await this.afterRefusedClusters(a,s);if(d.length===0||As(d,s))throw a;return i(d)})});return this.enter(o,"joined"),this.askForLocalServer(o),o}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 H&&i.reason==="not_found"){let o=this.heldMatchId;if(o!==null){let s=await this.askWhyEnded(o,e);this.endMatch(o,s??"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(()=>Yt({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(s){return s instanceof H&&s.reason==="not_found"?i??null:(this.reportError("reconcile",s),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 u("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=U(t.clusterTargetId),o=i??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),s=o??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let a=(p,c)=>ct({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...p===void 0?{}:{clusterTargetId:p},...i===void 0?{nextClusterTarget:()=>this.nextCluster(c)}:{},retry:{...t.retry,onWaiting:m=>{this.emitter.emit("matchStartWaiting",m),t.retry?.onWaiting?.(m);}},...t.signal===void 0?{}:{signal:t.signal}}),d=()=>a(o,[s]).catch(async p=>{if(i!==void 0||!ri(p))throw p;let c=await this.nextCluster([s],true);if(c===void 0)throw p;return a(c,[s,c])}),l=await(r?this.run("startMatch",d):this.track(this.onceGameIdKnown(d)));return this.beginMatch(l.matchId),l}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new u("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 ut({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 u("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!ei.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new u("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(!Dt()){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<bs){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(vs(e.attempt,t.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!Dt()){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(()=>Yt({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,!ei.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(s){this.reportError("reconcile",s),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 u("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 u("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 u("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 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.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||!Es.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){this.disposed||!this.watchingSeats||this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}async reconcileSeats(){if(this.disposed||!this.watchingSeats)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.seatPollMs>0&&Dt())){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(),!!Dt())){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}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of ti)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.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 ti)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??_s}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new u("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=zr(this.options.platformGameVersion?.(),t?.gameVersion);if(r===null)throw new u("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 Ar({...t,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return ve(await this.options.resolveClusterTargets());let e=U(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,t){return !ri(e)||t.length===0?[]:ve(await this.options.refreshClusterTargets?.(t)??[])}async nextCluster(e,t=false){let r=s=>s.find(a=>!e.includes(a)),i=await this.clusterTargets(),o=r(i);return o!==void 0||!t?o:r(ve(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 H)||e.reason!=="conflict"||!xs.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new H(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 H(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 H(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 u("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.`)}requireRoom(e){if(this.room===null)throw new u("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 H?{operation:e,code:t.status,reason:t.reason,message:t.message,retryable:t.retryable}:{operation:e,code:0,reason:t instanceof u?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.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(a=>[a.playerId,a])),i=new Map(e.members.map(a=>[a.playerId,a])),o=this.playerId();for(let a of i.keys())r.has(a)||this.emitter.emit("memberJoined",a);for(let a of r.keys())if(!i.has(a)){if(a===o){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",a);}for(let[a,d]of i){let l=r.get(a);l&&l.isReady!==d.isReady&&this.emitter.emit("readyChanged",a,d.isReady);}t.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let s=Ts(t,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),s&&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??Rs;return new Promise((i,o)=>{let s=c=>{a(),d(),this.options.clock.clearTimeout(p),e.signal?.removeEventListener("abort",l),c();},a=this.emitter.on("matchAllocationStarted",c=>s(()=>i(c))),d=this.emitter.on("matchFailed",(c,m)=>s(()=>o(new u("allocation_failed",`match ${c} did not come up: ${m}`)))),l=()=>s(()=>o(new u("aborted","the caller aborted while awaiting a match"))),p=this.options.clock.setTimeout(()=>s(()=>o(new u("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?l():e.signal?.addEventListener("abort",l);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??ws}pushedInterval(){return this.options.pushedPollIntervalMs??ks}pushed(){return this.options.clock.now()-this.lastPushAt<Ss*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=>{t?.persisted!==true&&this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{}));},e.addEventListener("pagehide",this.unloadListener));}};function Dt(){let n=globalThis.document;return n?.visibilityState===void 0||n.visibilityState==="visible"}var ti=["visibilitychange","focus","pageshow","online"];function Ts(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||ni(n)!==ni(e)}function ni(n){return n.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function ri(n){return n instanceof H&&n.code==="invalid_cluster_target"}function As(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}function oi(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={},s=d=>{t.delete(r)&&(n.clock.clearTimeout(o.timer),i(d));};t.set(r,s),o.timer=n.clock.setTimeout(()=>s(void 0),n.timeoutMs??2e3);let a=false;try{a=n.bridge.requestParty(r);}catch{}a||s(void 0);})},settle(r,i){t.get(r)?.(i);}}}
2
2
  export{si as CAPABILITY_GATES,di as CAPABILITY_NAMESPACE_GATES,At as CHANNELS,Ke as CHANNEL_KINDS,ce as ClientTelemetry,$t as DEDICATED_INBOUND_EVENTS,nn as DEFAULT_WELCOME_CEILING_MS,Bo as DEVICE_SETTINGS_MAX_BYTES,u as DedicatedServerError,ht as DedicatedSignalingHub,Ps as FRAME_TO_PARENT,Bt as GemFrame,Vt as GemHost,Ft as HANDSHAKE_TIMEOUT_MS,Te as HostMigration,ye as MALFORMED_INBOUND_KEY,Nn as MAX_ARRAY_LENGTH,tt as MAX_CLUSTER_TARGETS,fe as MAX_MESSAGE_BYTES,jn as MAX_MESSAGE_DEPTH,ze as MAX_MESSAGE_NODES,nt as MAX_SIGNALS_PER_SECOND,Le as MAX_SOCKET_FRAME_BYTES,Wr as MIGRATION_TIMEOUT_MS,Ee as P2pApi,k as P2pError,Ae as P2pSession,Cs as PARENT_TO_FRAME,g as PROTOCOL,W as PlayerText,Qe as RATE_LIMITS,te as RateLimiter,Me as RoomEmitter,Pe as RoomsApi,Z as SUPPORTED_VERSIONS,Ie as SignalingClient,lt as TELEMETRY_EVENTS,Zn as TRANSPORT_LABELS,se as VALIDATORS,je as WEBRTC_DEDICATED,Pn as WEBRTC_P2P,We as WEB_ENGINE_VERSION,he as WEB_PROTOCOL_VERSION,le as asPlayerText,ut as awaitMatchOutcome,It as browserPeerConnection,rt as buildDedicatedOfferFrame,ot as buildSocketFrame,Ze as capabilityFor,ko as createClusterTargetSource,ja as createDedicatedServerApi,xt as createKeySource,ms as createP2pApi,oi as createPartyResolver,ii as createRoomManager,Ko as deviceSettingsByteLength,He as establishDataChannel,pe as fingerprintOf,xe as fingerprintsMatch,Ct as generateCertificate,et as isOrigin,mt as listClusterTargets,On as memberFromWire,Ut as negotiateVersion,U as normaliseClusterTarget,ve as normaliseClusterTargets,Ve as normaliseFingerprint,Se as originsEqual,Ne as presentJoinCredential,it as projectDedicatedEvent,Ge as projectPartyEvent,at as projectSignal,Mt as roomArgValuesFromWire,Lt as roomArgsTemplateFromWire,X as roomFromWire,ct as startMatch,Xe as summaryFromWire,re as systemClock,$o as text,gt as unavailableSignaling,ho as validateGemAdResult,Qi as validateGemAudioState,Ii as validateGemAutoStartFailedEvent,Li as validateGemClusterTarget,ki as validateGemCohorts,Pi as validateGemDedicatedEvent,qi as validateGemDedicatedOffer,_i as validateGemDeviceSettings,uo as validateGemDeviceSettingsPut,mo as validateGemDeviceSettingsResult,Oi as validateGemDevtools,Si as validateGemEarnAllowanceChanged,Hi as validateGemEngaged,so as validateGemError,Xi as validateGemExit,oo as validateGemFrameStats,vo as validateGemFriendChallengeResult,ji as validateGemGameContext,hi as validateGemHandshake,gi as validateGemHandshakeAccept,Ki as validateGemLocalServer,Ji as validateGemLocalServerDenied,to as validateGemMenu,no as validateGemMenuSelect,Yi as validateGemOpenExternal,$i as validateGemPartyRequest,Mi as validateGemPartyResult,bi as validateGemPause,vi as validateGemPlayer,ao as validateGemPortraitBorders,wi as validateGemPrefs,Wi as validateGemProgress,co as validateGemPurchaseResult,Ui as validateGemReady,po as validateGemRequestAd,Fi as validateGemRequestContext,yo as validateGemRequestFriendChallenge,zi as validateGemRequestFullscreen,Bi as validateGemRequestLocalServer,lo as validateGemRequestPurchase,ro as validateGemRequestShare,go as validateGemRequestSignIn,Vi as validateGemRequestToken,Zi as validateGemRewardCue,xi as validateGemRoomEvent,Di as validateGemScreenshot,Gi as validateGemScreenshotDenied,Ai as validateGemSeatedEvent,fo as validateGemSignInResult,Ni as validateGemSignal,Ci as validateGemSignalEvent,Ti as validateGemSocketState,fi as validateGemToken,yi as validateGemTokenDenied,io as validateGemVibrate,Ri as validateGemViewport,eo as validateGemWalletDisplay,Ei as validateGemWillTerminate,mi as validateSize,Tt as verifyCredential};//# sourceMappingURL=gem-web-sdk.esm.js.map
3
3
  //# sourceMappingURL=gem-web-sdk.esm.js.map