@indiegems/gem-web-sdk 11.1.1 → 12.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/README.md +3 -1
- package/dist/game.d.ts +49 -0
- package/dist/gem-web-sdk.bridge.js +1 -1
- package/dist/gem-web-sdk.esm.js +2 -2
- package/dist/gem-web-sdk.function.js +2 -2
- package/dist/gem-web-sdk.game.js +2 -2
- package/dist/gem-web-sdk.min.js +2 -2
- package/dist/gem-web-sdk.sdk.js +2 -2
- package/dist/gem-web-sdk.server.js +2 -2
- package/dist/index.d.ts +66 -4
- package/dist/sdk.d.ts +49 -0
- package/docs/api/api-reference-function.md +7916 -0
- package/docs/api/api-reference-game.md +196 -3
- package/docs/api/api-reference-server.md +5 -3
- package/docs/api/reference.json +9492 -4
- package/docs/changelog.md +20 -0
- package/docs/friends.md +14 -0
- package/docs/getting-started.md +5 -2
- package/docs/manifest.json +16 -16
- package/docs/rooms-and-matches.md +64 -1
- package/docs/server-bundles.md +2 -2
- package/docs/serverless-functions-js.md +118 -44
- package/docs/serverless-functions.md +26 -11
- package/docs/what-a-game-must-do.md +3 -0
- package/package.json +1 -1
- package/schema/bridge.v1.json +84 -0
- package/schema/capabilities.public.json +6 -0
package/dist/gem-web-sdk.esm.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:11.1.1]";var h="gem-web-bridge",Z={min:1,max:1},fe=65536,Bn=8,et=5e3,Wn=1024,Bt=1e4;function Vn(n){return Object.freeze(Object.assign(Object.create(null),n))}var tt=Vn({"gem.handshake":30,"gem.handshake.accept":5,"gem.token":30,"gem.token.denied":30,"gem.player":12,"gem.pause":120,"gem.prefs":60,"gem.cohorts":12,"gem.earnAllowanceChanged":30,"gem.viewport":60,"gem.deviceSettings":12,"gem.willTerminate":10,"gem.roomEvent":120,"gem.socketState":12,"gem.seatedEvent":60,"gem.autoStartFailedEvent":30,"gem.signalEvent":1800,"gem.dedicatedEvent":120,"gem.partyResult":30,"gem.clusterTarget":12,"gem.devtools":30,"gem.screenshot":6,"gem.screenshot.denied":12,"gem.requestContext":12,"gem.gameContext":12,"gem.signal":1200,"gem.dedicatedOffer":60,"gem.partyRequest":12,"gem.ready":5,"gem.engaged":5,"gem.progress":600,"gem.requestToken":12,"gem.requestLocalServer":6,"gem.localServer":30,"gem.localServer.denied":30,"gem.exit":5,"gem.openExternal":6,"gem.requestFullscreen":30,"gem.audioState":120,"gem.rewardCue":60,"gem.walletDisplay":60,"gem.controlsDeclare":60,"gem.menu":60,"gem.menuSelect":60,"gem.requestShare":6,"gem.requestAvatarPicker":6,"gem.vibrate":600,"gem.frameStats":120,"gem.portraitBorders":60,"gem.error":60,"gem.requestPurchase":12,"gem.purchaseResult":30,"gem.deviceSettings.put":30,"gem.deviceSettings.result":30,"gem.requestAd":6,"gem.adResult":12,"gem.requestSignIn":6,"gem.signInResult":12,"gem.requestFriendChallenge":12,"gem.friendChallengeResult":30,__malformed:60}),ye="__malformed",Bs=["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"],Ws=["gem.handshake.accept","gem.screenshot.denied","gem.gameContext","gem.signal","gem.dedicatedOffer","gem.partyRequest","gem.ready","gem.engaged","gem.progress","gem.requestToken","gem.requestLocalServer","gem.exit","gem.openExternal","gem.requestFullscreen","gem.audioState","gem.rewardCue","gem.walletDisplay","gem.controlsDeclare","gem.menu","gem.requestShare","gem.requestAvatarPicker","gem.vibrate","gem.frameStats","gem.portraitBorders","gem.error","gem.requestPurchase","gem.deviceSettings.put","gem.requestAd","gem.requestSignIn","gem.requestFriendChallenge"],_i=Vn({"gem.requestAd":"ads","gem.adResult":"ads","gem.requestSignIn":"signIn","gem.signInResult":"signIn","gem.requestPurchase":"purchases","gem.purchaseResult":"purchases","gem.requestFriendChallenge":"friendChallenges","gem.friendChallengeResult":"friendChallenges","gem.devtools":"devtools","gem.screenshot":"screenshot","gem.screenshot.denied":"screenshot","gem.requestContext":"feedbackContext","gem.gameContext":"feedbackContext","gem.roomEvent":"rooms","gem.signal":"p2p","gem.signalEvent":"p2p","gem.dedicatedOffer":"dedicated","gem.dedicatedEvent":"dedicated","gem.clusterTarget":"clusterTarget","gem.partyRequest":"parties","gem.partyResult":"parties","gem.autoStartFailedEvent":"autoStartFailure","gem.seatedEvent":"partySeating","gem.socketState":"socketState","gem.audioState":"audioState","gem.rewardCue":"rewardCue","gem.frameStats":"frameStats","gem.portraitBorders":"portraitBorders","gem.engaged":"engagement","gem.viewport":"viewport","gem.walletDisplay":"walletDisplay","gem.requestLocalServer":"localHost","gem.localServer":"localHost","gem.localServer.denied":"localHost","gem.cohorts":"cohorts","gem.earnAllowanceChanged":"earnAllowance","gem.deviceSettings":"deviceSettings","gem.deviceSettings.put":"deviceSettings","gem.deviceSettings.result":"deviceSettings","gem.requestShare":"share","gem.requestAvatarPicker":"avatarPicker","gem.vibrate":"vibration","gem.menu":"gameMenu","gem.menuSelect":"gameMenu","gem.controlsDeclare":"controls"}),ki=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"]]);function nt(n){let e=_i[n];if(e!==void 0)return e;for(let[t,r]of ki)if(n.startsWith(t))return r}function rt(n){let e=/^([a-z][a-z0-9+.-]*):\/\/([a-z0-9.-]+|\[[0-9a-f:.]+\])(:([0-9]{1,5}))?$/i.exec(n);return e===null?false:e[4]===void 0||Number(e[4])<=65535}function wi(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 Ri(n){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(n)}function Si(n){return /^[a-z_]+$/.test(n)}function Ut(n,e,t){if(e>Bn)return `nesting deeper than ${Bn}`;if(++t.nodes>et)return `more than ${et} values`;if(t.bytes>fe)return `over the ${fe} byte limit`;if(n==null)return t.bytes+=4,null;let r=typeof n;if(r==="boolean")return t.bytes+=5,null;if(r==="number")return t.bytes+=8,null;if(r==="string")return t.bytes+=n.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let i=n;if(t.seen.has(i))return "a repeated or cyclic object reference";if(t.seen.add(i),Array.isArray(n)){if(n.length>Wn)return `an array of ${n.length} entries, over the ${Wn} limit`;t.bytes+=2;for(let s of n){let l=Ut(s,e+1,t);if(l)return l}return null}let o=Object.getPrototypeOf(n);if(o!==Object.prototype&&o!==null)return "a value that is not a plain object";t.bytes+=2;let a=n;for(let s in a){if(!Object.prototype.hasOwnProperty.call(a,s))continue;if(++t.nodes>et)return `more than ${et} values`;if(t.bytes+=s.length*3+4,t.bytes>fe)return `over the ${fe} byte limit`;let l=Ut(a[s],e+1,t);if(l)return l}return null}function xi(n){let e={nodes:0,bytes:0,seen:new Set},t=Ut(n,0,e);return t?`message contains ${t}`:e.bytes>fe?`message is over the ${fe} byte limit`:null}var Ai={origin:[rt,"not a well-formed origin"],url:[wi,"not a safe absolute http(s) URL"],bcp47:[Ri,"not a well-formed BCP 47 tag"],code:[Si,"not a code of lower-case letters and underscores"]};function Hn(n,e,t){for(let r of e){let i=t===""?r.n:`${t}.${r.n}`,o=n[r.n];if(o==null){if(r.o)continue;return `${i}: required`}let a=Kn(o,r,i);if(a)return a}return null}function Kn(n,e,t){switch(e.k){case "s":{if(typeof n!="string")return `${t}: expected string`;if(n.length>e.max)return `${t}: exceeds ${e.max} characters`;if(e.f){let[r,i]=Ai[e.f];if(!r(n))return `${t}: ${i}`}return null}case "i":return typeof n!="number"||!Number.isInteger(n)?`${t}: expected integer`:n<e.lo||n>e.hi?`${t}: out of range ${e.lo}..${e.hi}`:null;case "b":return typeof n=="boolean"?null:`${t}: expected boolean`;case "e":{let r=e.v;return r.includes(n)?null:`${t}: not one of ${r.join("|")}`}case "o":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected object`:Hn(n,e.fs,t);case "j":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected a plain object`:null;case "a":{if(!Array.isArray(n))return `${t}: expected array`;if(n.length>e.max)return `${t}: exceeds ${e.max} items`;let r=e.it,i=`${t}[]`;for(let o of n){if(o==null){if(r.o)continue;return `${i}: required`}let a=Kn(o,r,i);if(a)return a}return null}default:{let r=e.k;return `${t}: unknown kind ${String(r)}`}}}var Jn=Object.create(null);function b(n,e){return Jn[n]=t=>{let r=xi(t);if(r)return r;if(typeof t!="object"||t===null||Array.isArray(t))return "message: expected object";let i=t;return i.gem!==h?"gem: wrong protocol marker":i.type!==n?`type: expected ${n}`:Hn(i,e,"")}}var Vs=b("gem.handshake",[{n:"versions",k:"o",fs:[{n:"min",k:"i",lo:1,hi:1e3},{n:"max",k:"i",lo:1,hi:1e3}]},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}},{n:"embedder",k:"s",max:2048,f:"origin"},{n:"unbidden",k:"b",o:1}]),Hs=b("gem.handshake.accept",[{n:"v",k:"i",lo:1,hi:1e3},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}}]),Ks=b("gem.token",[{n:"token",k:"s",max:4096},{n:"requestId",k:"s",o:1,max:64},{n:"generation",k:"i",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"s",o:1,max:512,f:"url"},{n:"playerId",k:"s",max:64},{n:"gameId",k:"s",max:64},{n:"channel",k:"e",v:["dev","test","release"]},{n:"gameVersion",k:"s",o:1,max:64},{n:"expiresAt",k:"i",lo:0,hi:4102444800},{n:"chainEndsAt",k:"i",lo:0,hi:4102444800},{n:"allowDevTools",k:"b",o:1}]),Js=b("gem.token.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:36e5},{n:"reason",k:"e",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"s",max:64}]),zs=b("gem.player",[{n:"untrusted",k:"o",fs:[{n:"displayName",k:"s",max:64},{n:"displayTag",k:"s",o:1,max:80},{n:"displayHandle",k:"s",max:80}]},{n:"playerId",k:"s",o:1,max:64},{n:"discriminator",k:"s",o:1,max:8},{n:"avatarIconUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatarIconId",k:"s",o:1,max:64},{n:"avatar3dId",k:"s",o:1,max:64},{n:"avatar3dModelUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatar3dIconUrl",k:"s",o:1,max:2048,f:"url"},{n:"badges",k:"a",o:1,max:2,it:{n:"",k:"o",fs:[{n:"itemId",k:"s",max:64},{n:"iconUrl",k:"s",max:2048,f:"url"}]}},{n:"displayTag",k:"s",max:8},{n:"avatarUrl",k:"s",o:1,max:2048,f:"url"},{n:"boost",k:"o",o:1,fs:[{n:"multipliers",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"currencyId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"multiplierBp",k:"i",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"i",o:1,lo:1,hi:7}]}]),Ys=b("gem.pause",[{n:"paused",k:"b"}]),Xs=b("gem.prefs",[{n:"reducedMotion",k:"b"},{n:"muted",k:"b"},{n:"showFrameStats",k:"b",o:1},{n:"locale",k:"s",max:35,f:"bcp47"},{n:"recommended",k:"o",o:1,fs:[{n:"volume",k:"i",lo:0,hi:100},{n:"batterySaver",k:"b"},{n:"keyboardLayout",k:"e",v:["wasd","arrows"]},{n:"gamepadConfirm",k:"e",v:["south","east"]},{n:"vibration",k:"b"},{n:"lookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"gamepadLookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"invertLookY",k:"b",o:1},{n:"touchMovement",k:"s",o:1,max:16,f:"code"},{n:"graphicsQuality",k:"s",o:1,max:16,f:"code"},{n:"graphicsQualityAuto",k:"b",o:1}]}]),Qs=b("gem.cohorts",[{n:"cohorts",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"experimentId",k:"s",max:36},{n:"variantKey",k:"s",max:32}]}}]),Zs=b("gem.earnAllowanceChanged",[]),ea=b("gem.viewport",[{n:"insets",k:"o",fs:[{n:"top",k:"i",lo:0,hi:4096},{n:"right",k:"i",lo:0,hi:4096},{n:"bottom",k:"i",lo:0,hi:4096},{n:"left",k:"i",lo:0,hi:4096}]},{n:"reserved",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384},{n:"width",k:"i",lo:0,hi:16384},{n:"height",k:"i",lo:0,hi:16384}]}}]),ta=b("gem.deviceSettings",[{n:"settings",k:"j",o:1}]),na=b("gem.willTerminate",[{n:"reason",k:"e",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"i",lo:0,hi:6e4}]),ra=b("gem.roomEvent",[{n:"event",k:"e",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"s",max:64},{n:"matchId",k:"s",o:1,max:64},{n:"version",k:"i",o:1,lo:0,hi:2147483647},{n:"reason",k:"s",o:1,max:64},{n:"platform",k:"e",o:1,v:["universal","mobile"]}]),ia=b("gem.socketState",[{n:"connected",k:"b"},{n:"reason",k:"e",o:1,v:["connecting","dropped","watchdog","terminal"]}]),oa=b("gem.seatedEvent",[{n:"roomId",k:"s",max:64}]),sa=b("gem.autoStartFailedEvent",[{n:"roomId",k:"s",max:64},{n:"code",k:"s",max:64}]),aa=b("gem.signalEvent",[{n:"event",k:"e",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}]),la=b("gem.dedicatedEvent",[{n:"event",k:"e",v:["answer","error","matchEnded"]},{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",o:1,max:10240},{n:"sessionId",k:"s",o:1,max:64},{n:"code",k:"s",o:1,max:64},{n:"message",k:"s",o:1,max:256},{n:"reason",k:"s",o:1,max:64}]),da=b("gem.partyResult",[{n:"requestId",k:"s",max:64},{n:"partyId",k:"s",o:1,max:64}]),ca=b("gem.clusterTarget",[{n:"clusterTargetId",k:"s",max:64},{n:"clusterTargetIds",k:"a",o:1,max:3,it:{n:"",k:"s",max:64}}]),ua=b("gem.devtools",[{n:"action",k:"e",v:["open","close","toggle"]}]),ma=b("gem.screenshot",[{n:"maxWidth",k:"i",lo:1,hi:7680},{n:"maxHeight",k:"i",lo:1,hi:4320}]),pa=b("gem.screenshot.denied",[{n:"reason",k:"e",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"b"}]),ga=b("gem.requestContext",[]),ha=b("gem.gameContext",[{n:"context",k:"j"}]),fa=b("gem.signal",[{n:"signal",k:"e",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}]),ya=b("gem.dedicatedOffer",[{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",max:10240},{n:"intent",k:"e",v:["initial","ice_restart","full_reconnect"]}]),ba=b("gem.partyRequest",[{n:"requestId",k:"s",max:64}]),va=b("gem.ready",[]),_a=b("gem.engaged",[]),ka=b("gem.progress",[{n:"loaded",k:"i",lo:0,hi:1099511627776},{n:"total",k:"i",lo:0,hi:1099511627776}]),wa=b("gem.requestToken",[{n:"requestId",k:"s",max:64},{n:"reason",k:"e",v:["initial","expiring","rejected"]}]),Ra=b("gem.requestLocalServer",[{n:"requestId",k:"s",max:64},{n:"gameRoomId",k:"s",max:64}]),Sa=b("gem.localServer",[{n:"requestId",k:"s",max:64},{n:"serverId",k:"s",o:1,max:128}]),xa=b("gem.localServer.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"reason",k:"e",v:["refused","unavailable"]}]),Aa=b("gem.exit",[{n:"reason",k:"s",o:1,max:64}]),Pa=b("gem.openExternal",[{n:"url",k:"s",max:2048,f:"url"}]),Ea=b("gem.requestFullscreen",[{n:"enabled",k:"b"}]),Ta=b("gem.audioState",[{n:"muted",k:"b"}]),Ia=b("gem.rewardCue",[{n:"currencySlug",k:"s",max:32},{n:"expected",k:"i",o:1,lo:1,hi:1e9},{n:"origin",k:"o",o:1,fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384}]}]),Ca=b("gem.walletDisplay",[{n:"visible",k:"b"},{n:"currencies",k:"a",o:1,max:8,it:{n:"",k:"s",max:64}},{n:"score",k:"b",o:1}]),Ma=b("gem.controlsDeclare",[{n:"uses",k:"o",fs:[{n:"lookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"gamepadLookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"invertLookY",k:"s",o:1,max:16,f:"code"},{n:"touchMovement",k:"s",o:1,max:16,f:"code"}]}]),Oa=b("gem.menu",[{n:"settings",k:"b"},{n:"items",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"id",k:"s",max:32},{n:"label",k:"s",max:40}]}}]),La=b("gem.menuSelect",[{n:"entry",k:"e",v:["settings","item"]},{n:"id",k:"s",o:1,max:32}]),Ga=b("gem.requestShare",[{n:"params",k:"a",max:16,it:{n:"",k:"o",fs:[{n:"key",k:"s",max:64},{n:"value",k:"s",max:512}]}}]),Da=b("gem.requestAvatarPicker",[{n:"tab",k:"e",o:1,v:["2d","3d"]}]),qa=b("gem.vibrate",[{n:"pattern",k:"a",max:99,it:{n:"",k:"i",lo:0,hi:1e4}}]),$a=b("gem.frameStats",[{n:"fps",k:"i",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"i",lo:0,hi:1e5}]),Fa=b("gem.portraitBorders",[{n:"name",k:"s",o:1,max:40}]),ja=b("gem.error",[{n:"code",k:"e",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"s",o:1,max:256}]),Na=b("gem.requestPurchase",[{n:"requestId",k:"s",max:64},{n:"purchaseKind",k:"e",v:["item","recipe"]},{n:"targetId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"quantity",k:"i",o:1,lo:1,hi:10},{n:"catalogId",k:"s",o:1,max:64}]),Ua=b("gem.purchaseResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["ok","declined","unavailable"]},{n:"reason",k:"s",o:1,max:64,f:"code"},{n:"purchaseId",k:"s",o:1,max:64}]),Ba=b("gem.deviceSettings.put",[{n:"requestId",k:"s",max:64},{n:"settings",k:"j"}]),Wa=b("gem.deviceSettings.result",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["stored","too_large","unavailable"]}]),Va=b("gem.requestAd",[{n:"requestId",k:"s",max:64},{n:"placement",k:"s",max:32},{n:"format",k:"e",v:["interstitial","rewarded"]}]),Ha=b("gem.adResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["shown","no_ad","unavailable"]}]),Ka=b("gem.requestSignIn",[{n:"requestId",k:"s",max:64}]),Ja=b("gem.signInResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["signed_in","declined","unavailable"]}]),za=b("gem.requestFriendChallenge",[{n:"requestId",k:"s",max:64},{n:"playerId",k:"s",max:64},{n:"template",k:"s",max:64},{n:"params",k:"j",o:1}]),Ya=b("gem.friendChallengeResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"s",o:1,max:64},{n:"param",k:"s",o:1,max:64},{n:"channel",k:"s",o:1,max:16},{n:"configVersion",k:"i",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:864e5},{n:"detail",k:"s",o:1,max:300}]),le=Object.freeze(Jn);var it=3;function B(n){if(typeof n!="string")return;let e=n.trim();return e.length===0?void 0:e}function be(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=B(t);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var Pi=2e3,Ei=5e3;function Ti(n){let e=[],t=false,r=null,i=new Map,o=()=>{if(e.length>0)return Promise.resolve(e);if(t)return Promise.resolve([]);if(!n.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let a,s=new Promise(l=>{let d=false,m=null;a=c=>{d||(d=true,r=null,n.clock.clearTimeout(m),l(c));},m=n.clock.setTimeout(()=>{t=true,a([]);},n.timeoutMs??Pi);});return r={promise:s,settle:a},s};return {resolveList:o,resolve(){return e.length>0||t||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):o().then(a=>a[0])},refresh(a){return !zn(e,a)||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(s=>{let l=null,d=m=>{i.delete(d)&&(n.clock.clearTimeout(l),s(m));};i.set(d,a),l=n.clock.setTimeout(()=>d(e),n.refreshTimeoutMs??Ei);})},accept(a,s){let l=be(s),d=B(a),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[c,p]of [...i])zn(m,p)||c(m);}}}}function zn(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var Ii=["lookSensitivity","gamepadLookSensitivity","invertLookY","touchMovement"];function ot(n){let e={};if(typeof n=="object"&&n!==null)for(let t of Ii){let r=n[t];(r==="player"||r==="game")&&(e[t]=r);}return e}var Ci=/^[a-z0-9][a-z0-9_-]{0,39}$/;function Wt(n){return typeof n=="string"&&Ci.test(n)}function Yn(n){if(n===null||Wt(n))return n;let e=typeof n=="string"?JSON.stringify(n.length>48?`${n.slice(0,48)}\u2026`:n):`a value of type ${typeof n}`;console.warn(`[gem] showPortraitBorders: ${e} is not a border name, so nothing was sent. A name is 1 to 40 of a-z, 0-9, _ and -, starting with a letter or digit, exactly as your store page declares it under media.portrait_borders. Pass null for no art.`);}var Oe=16384,st=24;function S(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 ve(...n){return e=>typeof e=="string"&&n.includes(e)?e:void 0}function Xn(n){return typeof n=="boolean"?n:void 0}var L=S(64),Le=ee(0,2147483647);function Vt(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(e.length>=64)break;let r=L(t);typeof r=="string"&&e.push(r);}return e}function P(n,e,t){return {to:n,from:e,read:t,required:true}}function x(n,e,t){return {to:n,from:e,read:t,required:false}}function _e(n,e){let t={};for(let r of e){let i=r.read(n[r.from]);if(i===void 0){if(r.required)return null;continue}t[r.to]=i;}return t}function Ge(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let e=n;return typeof e.type!="string"||typeof e.data!="object"||e.data===null||Array.isArray(e.data)?null:{type:e.type,data:e.data}}var Qn=[P("sdp","sdp",S(10240)),P("signaling_intent","intent",ve("initial","ice_restart","full_reconnect"))];function at(n,e,t){if(typeof t!="object"||t===null||Array.isArray(t))return {reason:"offer: data must be an object"};let r=t,i=_e(r,Qn);return i===null?{reason:`offer: '${Qn.find(a=>a.read(r[a.from])===void 0)?.from??"?"}' is missing or out of bounds`}:{frame:{type:"webrtc_offer",match_id:n,game_id:e,...i}}}var Ht=Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"})),Mi=new Set(["error"]),Oi=Object.freeze(Object.assign(Object.create(null),{answer:[P("sdp","sdp",S(10240)),x("sessionId","session_id",S(64))],error:[x("code","code",S(64)),x("message","message",S(256))],matchEnded:[x("reason","reason",S(64))]}));function lt(n,e,t){let r=Ge(n);if(r===null)return null;let i=Ht[r.type];if(i===void 0)return null;let o=L(r.data.match_id);if(typeof o!="string"||!(Mi.has(i)?t(o):r.data.game_id===e))return null;let s=_e(r.data,Oi[i]??[]);return s===null?null:{event:i,matchId:o,...s}}var Li=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=ve("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}}},Gi=Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[P("sdp","sdp",S(10240)),P("signaling_intent","intent",ve("initial","ice_restart","full_reconnect")),x("sdp_hash","sdpHash",S(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[P("peer_id","peerId",L),P("sdp","sdp",S(10240)),P("assigned_peer_id","assignedPeerId",ee(0,4294967295)),x("sdp_hash","sdpHash",S(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[P("peer_id","peerId",L),P("candidate","candidate",S(512)),x("sdp_mid","sdpMid",S(64)),x("sdp_mline_index","sdpMLineIndex",ee(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[P("host_epoch","hostEpoch",Le)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[P("host_epoch","hostEpoch",Le),x("evidence","evidence",Li)]}}));function dt(n,e,t,r){let i=Gi[n];if(i===void 0)return {reason:`unknown signal '${n}'`};if(typeof r!="object"||r===null||Array.isArray(r))return {reason:`${n}: data must be an object`};let o=r,a=_e(o,i.args);if(a===null){let s=i.args.find(l=>l.required&&l.read(o[l.from])===void 0);return {reason:`${n}: '${s?.from??"?"}' is missing or out of bounds`}}return {frame:{type:i.type,match_id:e,...i.gameScoped?{game_id:t}:{},...a}}}var Di=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"})),qi=new Set(["error"]),$i=Object.freeze(Object.assign(Object.create(null),{hello:[P("playerId","player_id",L),P("hostPlayerId","host_player_id",L),P("hostEpoch","host_epoch",Le),x("members","members",Vt)],offer:[P("fromPlayerId","from_player_id",L),P("sdp","sdp",S(10240)),x("sessionId","signaling_session_id",S(128)),x("sdpHash","sdp_hash",S(128)),x("iceUfrag","ice_ufrag",S(64)),x("intent","signaling_intent",ve("initial","ice_restart","full_reconnect"))],answer:[P("fromPlayerId","from_player_id",L),P("sdp","sdp",S(10240)),x("sessionId","signaling_session_id",S(128)),x("sdpHash","sdp_hash",S(128)),x("iceUfrag","ice_ufrag",S(64)),x("assignedPeerId","assigned_peer_id",ee(0,4294967295))],ice:[P("fromPlayerId","from_player_id",L),P("candidate","candidate",S(512)),x("sdpMid","sdp_mid",S(64)),x("sdpMLineIndex","sdp_m_line_index",ee(0,255)),x("sdpMLineIndexAlt","sdp_mline_index",ee(0,255))],peerJoined:[P("playerId","player_id",L)],peerLeft:[P("playerId","player_id",L),x("reason","reason",S(64))],migration:[P("hostPlayerId","new_host_player_id",L),P("hostEpoch","host_epoch",Le),x("reason","reason",S(64)),x("kickedPlayerIds","kicked_player_ids",Vt),x("migrationComplete","migration_complete",Xn)],matchEnded:[x("reason","reason",S(64))],error:[x("code","code",S(64)),x("message","message",S(256))]}));function ct(n,e,t){let r=Ge(n);if(r===null)return null;let i=Di[r.type];if(i===void 0)return null;let o=L(r.data.match_id);if(typeof o!="string"||!(qi.has(i)?t(o):r.data.game_id===e))return null;let s=_e(r.data,$i[i]??[]);return s===null?null:{event:i,matchId:o,data:s}}var Fi=Object.freeze(Object.assign(Object.create(null),{party_invite_received:"inviteReceived",party_member_joined:"memberJoined",party_member_left:"memberLeft",party_member_kicked:"memberKicked",party_leader_transferred:"leaderTransferred",party_updated:"updated",party_disbanded:"disbanded",party_game_room_joined:"gameRoomJoined",party_game_room_left:"gameRoomLeft"}));function De(n){let e=Ge(n);if(e===null)return null;let t=Fi[e.type];if(t===void 0)return null;let r=e.data,i=L(r.party_id);if(typeof i!="string")return null;let o=ee(0,Number.MAX_SAFE_INTEGER)(r.version),a=L(r.game_room_id),s=L(r.game_id),l=L(r.inviter_player_id),d=S(80)(r.inviter_display_tag),m=S(64)(r.party_name);return {event:t,partyId:i,...o===void 0?{}:{version:o},...a===void 0?{}:{gameRoomId:a},...s===void 0?{}:{gameId:s},...l===void 0?{}:{inviterPlayerId:l},...d===void 0?{}:{inviterDisplayTag:d},...m===void 0?{}:{partyName:m}}}var re={now:()=>Date.now(),setTimeout:(n,e)=>setTimeout(n,e),clearTimeout:n=>clearTimeout(n)},te=class{constructor(e=re){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let t=tt[e];if(t===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??t,a=Math.max(0,r-i),s=Math.min(t,o+a*t/6e4);return s<1?(this.tokens.set(e,s),this.lastRefill.set(e,r),false):(this.tokens.set(e,s-1),this.lastRefill.set(e,r),true)}};function we(n,e){return n.toLowerCase()===e.toLowerCase()}function ut(n){let e=n.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function er(n,e){if(typeof e!="string"||e==="")return false;let t,r;try{t=new URL(n),r=new URL(e);}catch{return false}return t.protocol!=="http:"&&t.protocol!=="https:"||r.protocol!=="http:"&&r.protocol!=="https:"||t.username!==""||t.password!==""||t.pathname!=="/"||t.search!==""||t.hash!==""||t.port===""?false:ut(t.hostname)&&ut(r.hostname)}function Kt(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 ji=7,nr=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,Ni=["universal","mobile"],Ui={game_room_updated:"updated",game_room_match_started:"match_started",game_room_match_ready:"match_ready",game_room_match_failed:"match_failed",game_room_version_stale:"version_stale",match_ended:"updated",p2p_match_ended:"updated"},Bi=new Set(["match_ended","p2p_match_ended"]),Wi="game_room_auto_start_failed",Vi=/^[a-z][a-z0-9_]{0,63}$/,qe=64,Hi=8,zt=class{constructor(e,t){this.clock=e;this.limit=t;}clock;limit;windowStart=0;used=0;allow(){let e=this.clock.now();return e-this.windowStart>=1e3&&(this.windowStart=e,this.used=0),this.used>=this.limit?false:(this.used+=1,true)}};function mt(n){if(!(typeof n!="string"||n.length===0||n.length>qe))return n}function Ki(n){return n instanceof Error?n.message:String(n)}function rr(n,e){if(!n.has(e)){if(n.size>=Hi){let t=n.values().next().value;t!==void 0&&n.delete(t);}n.add(e);}}function Jt(){return new MessageChannel}var Ji=6e4/(tt["gem.handshake"]??1),zi=6e4,Yt=class{constructor(e){this.options=e;if(!rt(e.frameOrigin))throw new Error(`GemHost: frameOrigin must be a concrete origin, got '${e.frameOrigin}'. '*' and 'null' are refused \u2014 the handshake transfers the MessagePort, so an imprecise targetOrigin gives the session away.`);if(!rt(e.embedderOrigin))throw new Error(`GemHost: embedderOrigin must be a concrete origin, got '${e.embedderOrigin}'.`);this.clock=e.clock??re,this.inbound=new te(this.clock),this.outbound=new te(this.clock),this.socketWindow=new zt(this.clock,24);}options;state="idle";port=null;version=null;timeoutHandle=null;reofferHandle=null;makeChannel=Jt;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=Jt){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?Jt():(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 ${Bt}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.`);},Bt);}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:h,type:"gem.handshake",versions:{min:Z.min,max:Z.max},embedder:this.options.embedderOrigin,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]},...this.options.unbidden===true?{unbidden:true}:{}},this.options.frameOrigin,[e.port2]),true}scheduleReoffer(){this.reofferHandle=this.clock.setTimeout(()=>{this.reofferHandle=null,this.state==="handshaking"&&(this.offer(),this.pruneStaleOffers(),this.scheduleReoffer());},Ji);}pruneStaleOffers(){let e=this.clock.now()-zi;for(;this.offered.length>0&&(this.offered[0]?.at??e)<e;){let t=this.offered.shift();if(t===void 0)break;t.port.onmessage=null,t.port.close();}}adopt(e){for(let t of this.offered)t.port!==e&&(t.port.onmessage=null,t.port.close());this.offered.length=0,this.port=e;}static checkHandshakeOrigin(e,t,r){return we(e.origin,t)?e.source!==r?"source is not the mounted frame":null:`origin '${e.origin}' is not the expected frame origin`}sendToken(e){if(!Number.isInteger(e.chainEndsAt)||e.chainEndsAt<0){this.fail("internal","refusing a grant whose chainEndsAt is not a whole number of seconds >= 0");return}let t=this.chainEndsAt??e.chainEndsAt;if(this.chainExpired()){this.fail("token_unavailable","token chain ceiling reached");return}this.send({gem:h,type:"gem.token",token:e.token,expiresAt:e.expiresAt,chainEndsAt:t,generation:e.generation,playerId:e.playerId,gameId:e.gameId,channel:e.channel,...e.gameVersion===void 0?{}:{gameVersion:e.gameVersion},...e.requestId===void 0?{}:{requestId:e.requestId},...e.apiBaseUrl===void 0?{}:{apiBaseUrl:e.apiBaseUrl},...e.allowDevTools===true?{allowDevTools:true}:{},...e.garden===void 0?{}:{garden:e.garden}})&&(this.chainEndsAt=t,this.gameId??=e.gameId);}relayRoomEvent(e){if(this.gameId===null||typeof e!="object"||e===null||Array.isArray(e))return false;let t=e;if(typeof t.type!="string")return false;let r=Ui[t.type];if(r===void 0||typeof t.data!="object"||t.data===null||Array.isArray(t.data))return false;let i=t.data;if(i.game_id!==this.gameId)return false;let o=mt(i.game_room_id);if(o===void 0)return false;let a=Bi.has(t.type)?void 0:mt(i.match_id);a!==void 0&&this.rememberMatch(a);let s=typeof i.version=="number"?i.version:void 0,l=typeof i.reason=="string"?i.reason.slice(0,qe):void 0,d=r==="version_stale"&&Ni.includes(i.platform)?i.platform:void 0;return this.sendRoomEvent({event:r,roomId:o,...a===void 0?{}:{matchId:a},...s===void 0?{}:{version:s},...l===void 0?{}:{reason:l},...d===void 0?{}:{platform:d}})}sendRoomEvent(e){return this.frameSupports("rooms")?this.send({gem:h,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:h,type:"gem.socketState",connected:e.connected,...e.connected?{}:{reason:e.reason}}):false}sendSeatedEvent(e){return this.frameSupports("partySeating")?this.send({gem:h,type:"gem.seatedEvent",roomId:e}):false}relaySeatedEvent(e){if(this.gameId===null)return false;let t=De(e);if(t===null||t.event!=="gameRoomJoined"||t.gameId!==this.gameId)return false;let r=mt(t.gameRoomId);return r===void 0?false:this.sendSeatedEvent(r)}sendAutoStartFailedEvent(e){return this.frameSupports("autoStartFailure")?this.send({gem:h,type:"gem.autoStartFailedEvent",roomId:e.roomId,code:e.code}):false}relayAutoStartFailedEvent(e){if(this.gameId===null||typeof e!="object"||e===null||Array.isArray(e))return false;let t=e;if(t.type!==Wi||typeof t.data!="object"||t.data===null||Array.isArray(t.data))return false;let r=t.data;if(r.game_id!==this.gameId)return false;let i=mt(r.game_room_id),o=typeof r.code=="string"&&Vi.test(r.code)?r.code:void 0;return i===void 0||o===void 0?false:this.sendAutoStartFailedEvent({roomId:i,code:o})}relaySocketEvent(e){let t=[];(this.relayRoomEvent(e)||this.relayAutoStartFailedEvent(e))&&t.push("room"),this.relaySignalEvent(e)&&t.push("signal"),this.relayDedicatedEvent(e)&&t.push("dedicated");let r=De(e);return r!==null&&(this.options.onPartyEvent?.(r),this.relaySeatedEvent(e),t.push("party")),t}relaySignalEvent(e){if(this.gameId===null)return false;let t=ct(e,this.gameId,r=>this.knowsMatch(r));return t===null?false:(t.event==="hello"&&this.rememberMatch(t.matchId),this.sendSignalEvent(t))}sendSignalEvent(e){return this.frameSupports("p2p")?this.send({gem:h,type:"gem.signalEvent",event:e.event,matchId:e.matchId,data:e.data}):false}relayDedicatedEvent(e){if(this.gameId===null)return false;let t=lt(e,this.gameId,r=>this.knowsMatch(r));return t===null?false:this.sendDedicatedEvent(t)}sendDedicatedEvent(e){return this.frameSupports("dedicated")?this.send({gem:h,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){rr(this.knownMatches,e);}rememberAsked(e){rr(this.askedMatches,e);}answerPartyRequest(e,t){return this.send({gem:h,type:"gem.partyResult",requestId:e,...t===void 0?{}:{partyId:t}})}answerPurchase(e,t,r,i){return this.send({gem:h,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:h,type:"gem.deviceSettings.result",requestId:e,outcome:t})}sendDeviceSettings(e){return this.frameSupports("deviceSettings")?this.send({gem:h,type:"gem.deviceSettings",...e===void 0?{}:{settings:e}}):false}sendMenuSelect(e){return this.frameSupports("gameMenu")?this.send(e==="settings"?{gem:h,type:"gem.menuSelect",entry:"settings"}:{gem:h,type:"gem.menuSelect",entry:"item",id:e.id}):false}answerAd(e,t){return this.send({gem:h,type:"gem.adResult",requestId:e,outcome:t})}answerSignIn(e,t){return this.send({gem:h,type:"gem.signInResult",requestId:e,outcome:t})}answerFriendChallenge(e,t,r={}){let i={};if(t==="invalid"){let{code:o,param:a,channel:s,configVersion:l,detail:d}=r;typeof o=="string"&&o.length<=64&&(i.code=o),typeof a=="string"&&a.length<=64&&(i.param=a),typeof s=="string"&&s.length<=16&&(i.channel=s),typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&(i.configVersion=l),typeof d=="string"&&(i.detail=d.slice(0,300));}else if(t==="rate_limited"){let o=r.retryAfterMs;typeof o=="number"&&Number.isFinite(o)&&(i.retryAfterMs=Math.min(864e5,Math.max(0,Math.round(o))));}return this.send({gem:h,type:"gem.friendChallengeResult",requestId:e,outcome:t,...i})}denyToken(e){this.send({gem:h,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:h,type:"gem.localServer",requestId:e.requestId,...e.serverId===void 0?{}:{serverId:e.serverId}}):false}denyLocalServer(e){return this.frameSupports("localHost")?this.send({gem:h,type:"gem.localServer.denied",requestId:e.requestId,retryable:e.retryable,reason:e.reason}):false}sendClusterTarget(e){let t=typeof e=="string"?[e]:e,r=Array.isArray(t)?t.length===0?"[]":t.find(o=>typeof o!="string"||o.trim().length===0||o.length>qe):String(t);if(r!==void 0)return this.fail("internal",`refusing to send '${String(r)}' as a cluster target \u2014 each id must be a non-blank string of at most ${qe} characters, and a list must name at least one. Omit the message entirely when there is no answer: the frame then names no cluster and gem-api chooses.`),false;if(t.length>3)return this.fail("internal",`refusing to send ${t.length} cluster targets \u2014 at most ${3} acceptable clusters cross, best first.`),false;if(!this.frameSupports("clusterTarget"))return false;let[i]=t;return this.send({gem:h,type:"gem.clusterTarget",clusterTargetId:i,...typeof e=="string"?{}:{clusterTargetIds:[...t]}})}sendPlayer(e){let{displayName:t,displayTag:r}=e.untrusted,i=e.badges?.map(({itemId:d,iconUrl:m})=>({itemId:d,iconUrl:m})),o=e.boost&&{multipliers:e.boost.multipliers.map(({currencyId:d,currencySlug:m,multiplierBp:c})=>({currencyId:d,currencySlug:m,multiplierBp:c})),...e.boost.expiresInDays===void 0?{}:{expiresInDays:Math.min(ji,e.boost.expiresInDays)}},a=e.discriminator!==void 0&&/^[0-9]{1,8}$/.test(e.discriminator)?e.discriminator:void 0,s=e.avatarIconId!==void 0&&nr.test(e.avatarIconId)?e.avatarIconId:void 0,l=e.avatar3dId!==void 0&&nr.test(e.avatar3dId)?e.avatar3dId:void 0;this.send({gem:h,type:"gem.player",untrusted:{displayName:t,...r===void 0?{}:{displayTag:r},displayHandle:r??t},...e.playerId===void 0?{}:{playerId:e.playerId},...a===void 0?{}:{discriminator:a},...e.avatarIconUrl===void 0?{}:{avatarIconUrl:e.avatarIconUrl},...s===void 0?{}:{avatarIconId:s},...l===void 0?{}:{avatar3dId:l},...e.avatar3dModelUrl===void 0?{}:{avatar3dModelUrl:e.avatar3dModelUrl},...e.avatar3dIconUrl===void 0?{}:{avatar3dIconUrl:e.avatar3dIconUrl},...i===void 0?{}:{badges:i},...o===void 0?{}:{boost:o},displayTag:a??"",...e.avatarIconUrl===void 0?{}:{avatarUrl:e.avatarIconUrl}});}chainExpired(){return this.chainEndsAt!==null&&this.clock.now()/1e3>=this.chainEndsAt}localCorrelationId(){return `local-${++this.localDenials}`}sendPause(e){this.send({gem:h,type:"gem.pause",paused:e});}sendDevtools(e){this.send({gem:h,type:"gem.devtools",action:e});}requestScreenshot(e,t){return this.frameSupports("screenshot")?this.send({gem:h,type:"gem.screenshot",maxWidth:t.maxWidth,maxHeight:t.maxHeight},[e]):false}requestContext(){return this.frameSupports("feedbackContext")?this.send({gem:h,type:"gem.requestContext"}):false}sendPrefs(e){this.send({gem:h,type:"gem.prefs",...e});}sendCohorts(e){return this.frameSupports("cohorts")?this.send({gem:h,type:"gem.cohorts",cohorts:e.map(t=>({experimentId:t.experimentId,variantKey:t.variantKey}))}):false}sendEarnAllowanceChanged(){return this.frameSupports("earnAllowance")?this.send({gem:h,type:"gem.earnAllowanceChanged"}):false}sendViewport(e){if(!this.frameSupports("viewport"))return false;let t=(e.reserved??[]).map(({x:o,y:a,width:s,height:l})=>({x:o,y:a,width:s,height:l})),r=this.frameSupports("reservedAreas"),i=e.insets.top;if(!r)for(let o of t)o.y===0&&(i=Math.max(i,o.height));return this.send({gem:h,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:h,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=le[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=le[r];if(!i){this.refuseMalformed("unsupported",`unknown message type ${JSON.stringify(r.slice(0,qe))}`);return}if(!this.inbound.allow(r)){this.fail("rate_limited",`frame exceeded the limit for ${r}`);return}let o=nt(r);if(o!==void 0&&!this.options.capabilities?.includes(o)){this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this parent did not advertise`);return}let a=i(e);if(a){this.fail("invalid_message",`${r}: ${a}`);return}let s=e;r!=="gem.handshake.accept"&&!this.versionMatches(s,r)||this.dispatch(r,s,t);}refuseMalformed(e,t){if(!this.inbound.allow(ye)){this.options.onDropped?.(e,t);return}this.fail(e,t);}versionMatches(e,t){return e.v===this.version?true:(this.fail("invalid_message",`${t}: expected v ${String(this.version)}, got ${String(e.v)}`),false)}forwardSignal(e){let t=this.options.onSendSignal;if(t===void 0){this.fail("unsupported","this parent advertised `p2p` but wired no onSendSignal, so signaling has nowhere to go");return}if(this.gameId===null){this.options.onDropped?.("internal","gem.signal before any token was issued");return}if(e.signal!=="join"&&!this.knownMatches.has(e.matchId)){this.fail("unsupported",`gem.signal names match '${e.matchId}', which this player's socket has not mentioned`);return}if(!this.socketWindow.allow()){this.fail("rate_limited","signaling exceeded this parent per-second socket budget");return}let r=dt(e.signal,e.matchId,this.gameId,e.data);if("reason"in r){this.fail("invalid_message",`gem.signal: ${r.reason}`);return}this.withinFrameSize("gem.signal",r.frame,"Trickle ICE candidates rather than gathering them into the offer.")&&(this.rememberAsked(e.matchId),t(r.frame));}forwardDedicatedOffer(e){let t=this.options.onSendSignal;if(t===void 0){this.fail("unsupported","this parent advertised `dedicated` but wired no onSendSignal, so the offer has nowhere to go");return}if(this.gameId===null){this.options.onDropped?.("internal","gem.dedicatedOffer before any token was issued");return}if(!this.socketWindow.allow()){this.fail("rate_limited","signaling exceeded this parent per-second socket budget");return}let r=at(e.matchId,this.gameId,{sdp:e.sdp,intent:e.intent});if("reason"in r){this.fail("invalid_message",`gem.dedicatedOffer: ${r.reason}`);return}if(this.withinFrameSize("gem.dedicatedOffer",r.frame,"A complete gathered offer fits; one that does not is carrying media sections this path does not permit, or candidates from ICE servers this path does not use.")){this.rememberAsked(e.matchId);try{t(r.frame);}catch(i){this.sendDedicatedEvent({event:"error",matchId:e.matchId,code:"embedder_relay_unavailable",message:"the page could not put the offer on the player socket"}),this.fail("internal",`gem.dedicatedOffer: the socket refused the send: ${Ki(i)}`);}}}withinFrameSize(e,t,r){let i=JSON.stringify(t).length;return i<=16384?true:(this.fail("invalid_message",`${e} builds a ${i}-byte socket frame, over the ${16384}-byte limit gem-api enforces, so the socket would drop it and then fail to establish. ${r}`),false)}dispatch(e,t,r){if(e==="gem.handshake.accept"){if(this.state!=="handshaking"){this.fail("handshake_duplicate","handshake already settled");return}let i=t.v;if(i<Z.min||i>Z.max){this.transition("unsupported"),this.fail("version_mismatch",`frame chose v${i}, outside our supported range`),this.close();return}this.adopt(r),this.version=i,this.peerCapabilities=t.capabilities??[],this.timeoutHandle!==null&&(this.clock.clearTimeout(this.timeoutHandle),this.timeoutHandle=null),this.reofferHandle!==null&&(this.clock.clearTimeout(this.reofferHandle),this.reofferHandle=null),this.transition("connected");return}if(this.state!=="connected"){this.fail("invalid_message",`${e} received before the handshake completed`);return}switch(e){case "gem.ready":this.options.onReady?.();break;case "gem.engaged":this.options.onEngaged?.();break;case "gem.progress":this.options.onProgress?.(t);break;case "gem.requestToken":{let i=t;if(this.chainExpired()){this.denyToken({requestId:i.requestId,retryable:false,reason:"chain_exhausted",correlationId:this.localCorrelationId()});break}this.options.onRequestToken?.(i);break}case "gem.requestLocalServer":{this.options.onRequestLocalServer?.(t);break}case "gem.exit":this.options.onExit?.(t),this.close();break;case "gem.openExternal":this.options.onOpenExternal?.(t);break;case "gem.requestFullscreen":this.options.onRequestFullscreen?.(t);break;case "gem.audioState":this.options.onAudioState?.(t);break;case "gem.rewardCue":this.options.onRewardCue?.(t);break;case "gem.walletDisplay":this.options.onWalletDisplay?.(t);break;case "gem.controlsDeclare":this.options.onControlsDeclare?.(ot(t.uses));break;case "gem.menu":this.options.onMenu?.(t);break;case "gem.frameStats":this.options.onFrameStats?.(t);break;case "gem.portraitBorders":{let{name:i}=t;i==null?this.options.onPortraitBorders?.(null):Wt(i)&&this.options.onPortraitBorders?.(i);break}case "gem.screenshot.denied":this.options.onScreenshotDenied?.(t);break;case "gem.gameContext":this.options.onGameContext?.(t);break;case "gem.signal":this.forwardSignal(t);break;case "gem.dedicatedOffer":this.forwardDedicatedOffer(t);break;case "gem.partyRequest":{let i=t;if(this.options.onPartyRequest===void 0){this.answerPartyRequest(i.requestId);break}this.options.onPartyRequest(i);break}case "gem.requestPurchase":{let i=t;if(!this.frameSupports("purchases")){this.fail("unsupported_capability","refusing gem.requestPurchase: the frame did not advertise 'purchases', so it cannot receive gem.purchaseResult. Nothing was prompted and nothing was spent.");break}if(this.options.onRequestPurchase===void 0){this.answerPurchase(i.requestId,"unavailable");break}this.options.onRequestPurchase(i);break}case "gem.deviceSettings.put":{let i=t;if(!this.frameSupports("deviceSettings")){this.fail("unsupported_capability","refusing gem.deviceSettings.put: the frame did not advertise 'deviceSettings', so it cannot receive gem.deviceSettings.result. Nothing was stored.");break}if(this.options.onDeviceSettingsPut===void 0){this.answerDeviceSettingsPut(i.requestId,"unavailable");break}this.options.onDeviceSettingsPut(i);break}case "gem.requestAd":{let i=t;if(!this.frameSupports("ads")){this.fail("unsupported_capability","refusing gem.requestAd: the frame did not advertise 'ads', so it cannot receive gem.adResult. Nothing was rendered.");break}if(this.options.onRequestAd===void 0){this.answerAd(i.requestId,"no_ad");break}this.options.onRequestAd(i);break}case "gem.requestSignIn":{let i=t;if(!this.frameSupports("signIn")){this.fail("unsupported_capability","refusing gem.requestSignIn: the frame did not advertise 'signIn', so it cannot receive gem.signInResult. Nothing was rendered.");break}if(this.options.onRequestSignIn===void 0){this.answerSignIn(i.requestId,"unavailable");break}this.options.onRequestSignIn(i);break}case "gem.requestFriendChallenge":{let i=t;if(!this.frameSupports("friendChallenges")){this.fail("unsupported_capability","refusing gem.requestFriendChallenge: the frame did not advertise 'friendChallenges', so it cannot receive gem.friendChallengeResult. Nothing was previewed, rendered or sent.");break}if(this.options.onRequestFriendChallenge===void 0){this.answerFriendChallenge(i.requestId,"unavailable");break}this.options.onRequestFriendChallenge(i);break}case "gem.requestShare":if(!this.frameSupports("share")){this.fail("unsupported_capability","refusing gem.requestShare: the frame did not advertise 'share'. Nothing was shared.");break}this.options.onRequestShare?.(t);break;case "gem.requestAvatarPicker":if(!this.frameSupports("avatarPicker")){this.fail("unsupported_capability","refusing gem.requestAvatarPicker: the frame did not advertise 'avatarPicker'. Nothing was opened.");break}{let i=t.tab;this.options.onRequestAvatarPicker?.(i==="2d"||i==="3d"?{tab:i}:{});}break;case "gem.vibrate":{if(!this.frameSupports("vibration")){this.fail("unsupported_capability","refusing gem.vibrate: the frame did not advertise 'vibration'. Nothing was played.");break}let i=t,o=i.pattern.reduce((a,s)=>a+s,0);if(o>1e4){this.fail("invalid_message",`refusing gem.vibrate: the pattern totals ${o} ms, over ${1e4}. Nothing was played.`);break}this.options.onVibrate?.(i);break}case "gem.error":this.fail(t.code,t.message);break;default:this.fail("unsupported",`no parent handler for '${e}'`);}}};var W=class{#e;constructor(e){this.#e=e,Object.freeze(this);}toString(){return "[gem: use gem.text.toPlain()]"}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function ce(n){return new W(n)}var Yi={toPlain(n){return W.unwrap(n)},compare(n,e,t){let r=n instanceof W?W.unwrap(n):n,i=e instanceof W?W.unwrap(e):e,o;try{o=new Intl.Collator(t);}catch{o=new Intl.Collator;}return o.compare(r,i)},equals(n,e){let t=n instanceof W?W.unwrap(n):n,r=e instanceof W?W.unwrap(e):e;return t.normalize("NFC")===r.normalize("NFC")}};function ir(n){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function Xi(n,e){if(n!==true)return {visible:false};let t=[],r=false;for(let i of Array.isArray(e)?e:[])i==="score"?r=true:typeof i=="string"&&i.length>0&&i.length<=64&&!t.includes(i)&&t.push(i);return !r&&t.length===0?{visible:true}:{visible:true,currencies:t.slice(0,8),score:r}}function Qi(n,e){let t=[];for(let r of Array.isArray(e)?e:[]){if(t.length===4)break;if(typeof r!="object"||r===null)continue;let{id:i,label:o}=r;typeof i!="string"||i.length===0||i.length>32||typeof o!="string"||o.trim().length===0||t.some(a=>a.id===i)||t.push({id:i,label:o.trim().slice(0,40)});}return t.length===0?{settings:n===true}:{settings:n===true,items:t}}function or(n,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function Zi(n){let e=n.untrusted,t=ce(e.displayName),r=e.displayTag||e.displayHandle,i=r?ce(r):void 0,o=n.discriminator||n.displayTag,a=o&&/^[0-9]{1,8}$/.test(o)?o:void 0,s=n.avatarIconUrl||n.avatarUrl,l=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,d=n.avatarIconId,m=n.avatar3dId,c={displayName:t,displayHandle:i??t,badges:(n.badges??[]).map(R=>({itemId:R.itemId,iconUrl:R.iconUrl}))};n.playerId&&(c.playerId=n.playerId),a&&(c.discriminator=a),i&&(c.displayTag=i),s&&(c.avatarIconUrl=c.avatarUrl=s),d&&l.test(d)&&(c.avatarIconId=d),m&&l.test(m)&&(c.avatar3dId=m),n.avatar3dModelUrl&&(c.avatar3dModelUrl=n.avatar3dModelUrl),n.avatar3dIconUrl&&(c.avatar3dIconUrl=n.avatar3dIconUrl);let p=n.boost,f=(p?.multipliers??[]).map(R=>({currencyId:R.currencyId,currencySlug:R.currencySlug,multiplier:R.multiplierBp/1e4})),y=f.some(R=>R.multiplier>1);return c.boost=y&&p?.expiresInDays?{active:y,multipliers:f,expiresInDays:p.expiresInDays}:{active:y,multipliers:f},c}var eo=1e4,Xt=class{constructor(e){this.options=e;if(e.expectedSource===void 0||e.expectedSource===null)throw new Error("GemFrame: expectedSource is required and must not be null \u2014 pass window.parent. The handshake transfers the MessagePort, and origin alone does not say WHICH document on that origin sent it.");this.expectedSource=e.expectedSource,this.clock=e.clock??re,this.inbound=new te(this.clock),this.outbound=new te(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];unbidden=false;engagedSent=false;readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}get unbiddenLaunch(){return this.unbidden}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(s=>we(s,e.origin))||er(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=le["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!we(i.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${i.embedder}' but arrived from '${e.origin}'`),false;let o=e.ports?.[0];if(!o)return this.refuse(e,"handshake transferred no MessagePort"),false;let a=Kt(Z,i.versions);return a===null?(o.onmessage=null,o.postMessage({gem:h,type:"gem.error",code:"version_mismatch",message:`frame supports v${Z.min}..v${Z.max}`}),o.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=o,this.version=a,o.onmessage=s=>this.receive(s.data,s.ports??[]),o.start?.(),this.peerCapabilities=i.capabilities??[],this.unbidden=i.unbidden===true,o.postMessage({gem:h,type:"gem.handshake.accept",v:a,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:h,type:"gem.ready"});}settled(e=eo){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(t=>{let r=o=>{this.clock.clearTimeout(i),t(o);},i=this.clock.setTimeout(()=>{let o=this.settleWaiters.indexOf(r);o>=0&&this.settleWaiters.splice(o,1),t(this.state);},e);this.settleWaiters.push(r);})}progress(e,t){this.send({gem:h,type:"gem.progress",loaded:e,total:t});}requestToken(e,t){this.send({gem:h,type:"gem.requestToken",requestId:e,reason:t});}requestLocalServer(e,t){return this.parentSupports("localHost")?(this.send({gem:h,type:"gem.requestLocalServer",requestId:e,gameRoomId:t}),true):false}exit(e){this.send(e===void 0?{gem:h,type:"gem.exit"}:{gem:h,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:h,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:h,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:h,type:"gem.audioState",muted:e}),true)}reportEngaged(){return this.engagedSent||this.state!=="connected"||!this.parentSupports("engagement")||!this.send({gem:h,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let t={gem:h,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:ir(e.origin.x),y:ir(e.origin.y)}),this.send(t),true}showPortraitBorders(e){let t=Yn(e);return t===void 0||this.state!=="connected"||!this.parentSupports("portraitBorders")?false:this.send(t===null?{gem:h,type:"gem.portraitBorders"}:{gem:h,type:"gem.portraitBorders",name:t})}setWalletVisible(e,t){return this.state!=="connected"||!this.parentSupports("walletDisplay")?false:this.send({gem:h,type:"gem.walletDisplay",...Xi(e,t?.only)})}declareControls(e){return this.state!=="connected"||!this.parentSupports("controls")?false:this.send({gem:h,type:"gem.controlsDeclare",uses:ot(e)})}setMenu(e,t){return this.state!=="connected"||!this.parentSupports("gameMenu")?false:this.send({gem:h,type:"gem.menu",...Qi(e,t)})}requestShare(e){return this.state!=="connected"||!this.parentSupports("share")?false:this.send({gem:h,type:"gem.requestShare",params:e.map(({key:t,value:r})=>({key:t,value:r}))})}requestAvatarPicker(e){return this.state!=="connected"||!this.parentSupports("avatarPicker")?false:this.send({gem:h,type:"gem.requestAvatarPicker",...e==="2d"||e==="3d"?{tab:e}:{}})}requestVibrate(e){return this.state!=="connected"||!this.parentSupports("vibration")?false:this.send({gem:h,type:"gem.vibrate",pattern:[...e]})}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:h,type:"gem.frameStats",fps:or(e.fps,1e3),frameTimeP95Ms:or(e.frameTimeP95Ms,1e5)}),true)}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:h,type:"gem.gameContext",context:e}),true)}signal(e,t,r){this.send({gem:h,type:"gem.signal",signal:e,matchId:t,data:r});}dedicatedOffer(e,t,r){this.send({gem:h,type:"gem.dedicatedOffer",matchId:e,sdp:t,intent:r});}requestParty(e){return this.send({gem:h,type:"gem.partyRequest",requestId:e})}requestPurchase(e,t,r,i,o,a){return this.send({gem:h,type:"gem.requestPurchase",requestId:e,purchaseKind:t,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...a===void 0?{}:{catalogId:a}})}putDeviceSettings(e,t){return this.send({gem:h,type:"gem.deviceSettings.put",requestId:e,settings:t})}requestAd(e,t,r){return this.send({gem:h,type:"gem.requestAd",requestId:e,placement:t,format:r})}requestSignIn(e){return this.send({gem:h,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,t,r,i){return this.send({gem:h,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:h,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=le[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||sr(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=le[r];if(!i)return this.dropUnknownType(r),false;if(!this.inbound.allow(r))return this.fail("rate_limited",`parent exceeded the limit for ${r}`),false;let o=nt(r);if(o!==void 0&&!this.options.capabilities?.includes(o))return this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this frame did not advertise`),false;let a=i(e);if(a)return this.fail("invalid_message",`${r}: ${a}`),false;let s=e;if(s.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(s);break;case "gem.pause":this.options.onPause?.(s);break;case "gem.menuSelect":this.options.onMenuSelect?.(s);break;case "gem.prefs":this.options.onPrefs?.(s);break;case "gem.cohorts":this.options.onCohorts?.(s);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(s);break;case "gem.willTerminate":this.options.onWillTerminate?.(s);break;case "gem.devtools":this.options.onDevtools?.(s.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=t[0];if(!l){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let d={maxWidth:s.maxWidth,maxHeight:s.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return sr(t.slice(1)),this.options.onScreenshot(d,l,(m,c)=>this.screenshotDenied(m,c)),true}case "gem.token.denied":this.options.onTokenDenied?.(s);break;case "gem.localServer":this.options.onLocalServer?.(s);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(s);break;case "gem.player":{this.options.onPlayer?.(Zi(s));break}case "gem.roomEvent":this.options.onRoomEvent?.(s);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(s);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(s);break;case "gem.socketState":this.options.onSocketState?.(s);break;case "gem.signalEvent":this.options.onSignalEvent?.(s);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(s);break;case "gem.clusterTarget":this.options.onClusterTarget?.(s);break;case "gem.partyResult":this.options.onPartyResult?.(s);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(s);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(s);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(s);break;case "gem.adResult":this.options.onAdResult?.(s);break;case "gem.signInResult":this.options.onSignInResult?.(s);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(s);break;case "gem.error":this.options.onError?.(s.code,s.message);break;default:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,t){this.send({gem:h,type:"gem.screenshot.denied",reason:e,retryable:t});}};function sr(n){for(let e of n)try{e?.close?.();}catch{}}var to=16384;function no(n){if(typeof n!="object"||n===null||Array.isArray(n))return null;let e;try{e=JSON.stringify(n);}catch{return null}return typeof e!="string"?null:ro(e)}function ro(n){let e=0;for(let t=0;t<n.length;t+=1){let r=n.charCodeAt(t);if(r<128)e+=1;else if(r<2048)e+=2;else if(r>=55296&&r<=56319){let i=n.charCodeAt(t+1);i>=56320&&i<=57343?(e+=4,t+=1):e+=3;}else e+=3;}return e}var ar=["p2p","dedicated","unknown"],pt=["connection_setup_duration_seconds","reconnect_latency_seconds","datachannel_rtt_seconds","p2p_join_to_play_latency_seconds","ice_restart_outcome_total","connection_failures_total","transport_permanent_failures_total","transport_quality_score","host_migration_outcome_total","turn_relay_usage_ratio"];var ue=class{constructor(e){this.options=e;}options;async post(e,t){let r=this.options.gameId();if(r===null||r==="")return;let i=io(e,this.options.transport,(this.options.now??Date.now)());i.length!==0&&await this.options.client.post(`/v1/games/${encodeURIComponent(r)}/telemetry/p2p`,{events:i},t);}report(e){this.post(e).catch(()=>{});}};function io(n,e,t){let r=Math.floor(t/1e3);return n.filter(i=>pt.includes(i.type)).slice(0,100).map(i=>{let o=oo(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:i.value===void 0?{}:{value:i.value}}})}function oo(n){if(n!==void 0)return ar.includes(n)?n:"unknown"}function Qt(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}var j=class extends Error{constructor(t,r,i,o,a){super(`${t} (${r}): ${i}`);this.reason=t;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=a;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}};var ao=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),u=class extends Error{constructor(t,r,i){super(`${t}: ${r}`,i);this.reason=t;this.name="DedicatedServerError",this.retryable=ao.has(t),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var lr=["explicit","stale_cleanup","game_room_closed","replaced","migration_failed","host_left","insufficient_players","all_left","expired","migration_rate_exceeded","game_room_gone","failed","idle","reclaimed"],lo=new Set(lr);function Re(n){return typeof n=="string"&&lo.has(n)?n:"unknown"}var $e="webrtc_dedicated",en=["universal","mobile","web"];var co="p2p_unavailable",uo="capacity_unavailable",mo=2,dr=3e4,cr=1e3,ur=2e4;async function gt(n){let e=B(n.clusterTargetId),t=n.nextClusterTarget,r=0,i=n.clock??re,o=n.retry??{},a=o.budgetMs??dr,s=o.maxDelayMs??ur,l=o.initialDelayMs??cr,d=i.now(),m=d+a,c=0;for(;;){c++;try{let p=await nn(n.signal,"while allocating",()=>n.client.post(`${gr(n)}/start_match`,e===void 0?{}:{cluster_target_id:e},n.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!po(p)||a<=0)throw p;if(p.status===503&&p.code===co)throw new 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: ${p.message}`,{cause:p});if(r=p.code===uo?r+1:0,t!==void 0&&r>=mo){let M=t;t=void 0;let I=B(await M());I!==void 0&&(e=I,r=0);}let f=Math.min(s,l*2**(c-1)),y=Math.min(s,(p.retryAfterSeconds??0)*1e3),T=Math.max(f/2,y)+Math.random()*(f/2);if(i.now()+T>m)throw go(n,p,c,i.now()-d,a);if(o.onWaiting?.({attempt:c,elapsedMs:i.now()-d,budgetMs:a,nextAttemptInMs:T,status:p.status,message:p.message}),await yt(i,T,n.signal),n.signal?.aborted)throw Zt("while waiting to allocate")}}}function po(n){return n instanceof j?n.status===503?true:n.status===429&&n.code!=="too_many_concurrent_matches":false}function go(n,e,t,r,i){let o=`${t} attempt${t===1?"":"s"} over ${r}ms of a ${i}ms budget`;return e.status===429?new 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 ho=12e4,fo=1e3;async function ht(n){let{clock:e,matchId:t}=n,r=n.pollIntervalMs??fo,i=n.timeoutMs??ho,o=e.now()+i,a=mr(n),s={seen:n.knownToExist===true};for(;;){let l=await pr(n,a,s);if(l.outcome!==null)return l.outcome;if(e.now()+r>o)throw new u("timeout",`match ${t} was still ${l.status} after ${i}ms`);await yt(e,r,n.signal);}}async function tn(n){return (await pr(n,mr(n),{seen:n.knownToExist===true})).outcome}function mr(n){let e=new URLSearchParams({platform:n.version.platform,game_version:n.version.gameVersion});return `${gr(n)}/matches/${encodeURIComponent(n.matchId)}/status?${e}`}async function pr(n,e,t){let{matchId:r}=n,i=n.clock.now(),o;try{o=await nn(n.signal,"while polling match status",()=>n.client.get(e,n.signal));}catch(a){if(a instanceof j&&a.reason==="not_found")return {status:"not_found",outcome:t.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw a}if(t.seen=true,o.status==="ready")return {status:"ready",outcome:yo(r,o,i)};if(o.status==="failed"){let a=o.ended_reason;return typeof a=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:Re(a)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function ft(n){let e=await nn(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 nn(n,e,t){if(n?.aborted)throw Zt(e);try{return await t()}catch(r){throw n?.aborted?Zt(e,r):r}}function Zt(n,e){return new u("aborted",`the caller aborted ${n}`,e===void 0?void 0:{cause:e})}function yo(n,e,t){let r=e.join_credential,i=e.expires_in_seconds,o=typeof r=="string"&&typeof i=="number";return {status:"ready",matchId:n,protocol:e.protocol??"unknown",...o?{joinCredential:r,credentialExpiresAt:t+i*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function gr(n){return `/v1/games/${encodeURIComponent(n.gameId)}/game-rooms/${encodeURIComponent(n.roomId)}`}function yt(n,e,t){return t?.aborted?Promise.resolve():new Promise(r=>{let i=()=>{n.clearTimeout(o),t?.removeEventListener("abort",i),r();},o=n.setTimeout(i,e);t?.addEventListener("abort",i);})}var bo=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),on="embedder_relay_unavailable",vo="embedder_no_relay",_o=new Set([on]),sn=new Set([vo]),bt=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new rn(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(ko(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 ko(n,e){let t=e??"the offer was refused",r=n===void 0?t:`${t} (${n})`;return new u(wo(n),r,{platformCode:n})}function wo(n){return n===void 0||_o.has(n)?"signaling_failed":sn.has(n)?"offer_refused":bo.has(n)?n==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var rn=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 a=()=>{s(),o(new u("aborted","the caller aborted the signaling exchange"));},s=()=>{t?.removeEventListener("abort",a),this.hub.release(e.matchId,l),this.teardown===s&&(this.teardown=null);},l={settle:d=>{s(),i(d);},refuse:d=>{s(),o(d);}};this.teardown=s,t?.addEventListener("abort",a),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof u?d:new u("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var hr="match_ended:",fr="server_shutdown:",yr="kicked:",Ro=123;function So(n){if(typeof n!="string"||n.length===0||n.length>Ro)return {kind:"other"};if(n.startsWith(hr)){let e=Re(n.slice(hr.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return n.startsWith(fr)?{kind:"server_shutdown",cause:n.slice(fr.length)}:n.startsWith(yr)?{kind:"kicked",detail:n.slice(yr.length)}:{kind:"other"}}function an(n,e,t){let r=So(t),i=r.kind==="kicked"?"kicked":"link_closed";n.notifyMatchDisconnected(i).catch(()=>{}),r.kind==="match_ended"&&n.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}var xo="join",Ao="welcome",Po="rejected",ln=25e3,Eo=1e3,dn=1;function cn(n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0}var To={credential_expired:"credential_expired",credential_reused:"credential_reused",credential_timeout:"timeout",join_rate_limited:"join_rate_limited",expected_join:"join_refused",invalid_credential:"join_refused",credential_not_for_this_channel:"join_refused"};function un(n){let e=typeof n=="string"?n:"unknown";return new u(To[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function Fe(n){let{channel:e,clock:t}=n;return new Promise((r,i)=>{let o=false,a=Math.min(n.credentialExpiresAt-t.now(),n.ceilingMs??ln),s=t.setTimeout(()=>R(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(a,Eo)),l=T=>{let M=T.data;if(typeof M!="string"){c(M);return}let I;try{I=JSON.parse(M);}catch{c(M);return}if(o){c(M);return}if(I.t===Ao){let g=cn(I.heartbeat_interval);y({...typeof I.player_id=="string"?{playerId:I.player_id}:{},...typeof I.match_id=="string"?{matchId:I.match_id}:{},...g===void 0?{}:{heartbeatIntervalMs:g}});return}if(I.t===Po){R(un(I.reason));return}c(M);},d=()=>{R(new u("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{R(new u("aborted","the caller aborted during the join exchange"));},c=T=>{o&&n.onMessage?.(T);},p=()=>{t.clearTimeout(s),e.removeEventListener("close",d),n.signal?.removeEventListener("abort",m);},f=()=>{e.removeEventListener("message",l);},y=T=>{o=true,p(),n.onMessage===void 0&&f(),r({welcome:T,detach:f});},R=T=>{o||(o=true,p(),f(),i(T));};if(e.addEventListener("message",l),e.addEventListener("close",d),n.signal?.aborted){m();return}n.signal?.addEventListener("abort",m);try{e.send(JSON.stringify({t:xo,credential:n.credential,...n.wire===void 0?{}:{wire:n.wire},...n.heartbeat===!0?{heartbeat:dn}:{}}));}catch(T){R(new u("connection_failed",`the join frame could not be sent on the open channel: ${String(T)}`,{cause:T}));}})}function vt(){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 me=1,je=2,mn=4,hn=8,Io=2,Co=1e3,fn="heartbeat timeout",_t="gem-uu",kt=2,vr="gem_transports";function Ne(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){if(typeof t!="string")continue;let r=t.toLowerCase();!Mo(r)||e.includes(r)||e.push(r);}return e}function Mo(n){return n==="webtransport"||n==="webrtc"||n==="websocket"}function wt(n,e){if(typeof n!="object"||n===null)return null;let t=n[vr];if(typeof t!="object"||t===null)return null;let r=t;return typeof r.v!="number"||r.v<1||typeof r.host!="string"||typeof r.port!="number"||e!==void 0&&r.match_id!==e?null:r}function Rt(n){return n instanceof Error?n.message===""?n.name:`${n.name}: ${n.message}`:String(n)}var _r=new TextEncoder,kr=new TextDecoder;function yn(n,e){let t=new Uint8Array(e.byteLength+1);return t[0]=n,t.set(e,1),t}function bn(n){let e=0;return n?.reliable===false&&(e|=me),n?.ordered===false&&(e|=je),e}function vn(n){return {reliable:(n&me)===0,ordered:(n&je)===0}}var _n={reliable:true,ordered:true};function wr(n){return JSON.stringify({t:"join",credential:n,wire:kt,heartbeat:dn})}function Rr(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=cn(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"?un(e.reason):new u("join_refused","the server answered the join out of protocol")}function kn(){return typeof globalThis.WebTransport=="function"&&wn===null}function St(){return wn}var wn=null;var br="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Oo(n){let e=Qt(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 pn=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 a=this.buffered.slice(4,4+o);this.buffered=this.buffered.slice(4+o),r.push({flags:a[0]??0,payload:a.slice(1)});}return r}};function gn(n,e){let t=new Uint8Array(5+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength+1,true),t[4]=n,t.set(e,5),t}async function Ue(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webTransport;if(t===void 0){let s=globalThis.WebTransport;if(s===void 0)throw new u("connection_failed","this environment has no WebTransport");t=n.certHashBase64===void 0?new s(n.url):new s(n.url,{serverCertificateHashes:[{algorithm:"sha-256",value:Oo(n.certHashBase64)}]});}let r=t,i=s=>{try{r.close();}catch{}throw s},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(wn=br,i(new u("connection_failed",`${br}; the rung is skipped for the rest of this page (a reload probes again)`)));let a=new Promise((s,l)=>{setTimeout(()=>l(new u("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,a]);let s=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([s.read(),a]);if(s.releaseLock(),l.done||l.value===void 0)return i(new u("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(gn(mn,_r.encode(wr(n.credential))));let c=new pn,p=d.readable.getReader(),f;for(;f===void 0;){let y=await Promise.race([p.read(),a]);if(y.done||y.value===void 0)return i(new u("connection_failed","the control stream closed before the join was answered"));for(let R of c.push(y.value)){f=Rr(kr.decode(R.payload));break}}return {link:Lo(r,m,p,c,n.log??(y=>console.warn(y)),xr(f,n.clock)),welcome:f}}catch(s){return i(s)}}function Lo(n,e,t,r,i,o){let a,s,l=false,d=y=>{if(!l){l=true,m.stop();try{n.close();}catch{}s?.(y);}},m=Sn(o,()=>d(fn)),c=(y,R)=>{m.heard(),(y&hn)===0&&a!==void 0&&((y&mn)!==0?a(kr.decode(R),_n):a(R,vn(y)));};(async()=>{try{for(;;){let y=await t.read();if(y.done||y.value===void 0)break;for(let R of r.push(y.value))c(R.flags,R.payload);}}catch{}d("stream closed");})();let p,f;try{let y=n.datagrams;if(y?.readable!==void 0&&y.writable!==void 0){let R=y.readable.getReader();f=y.writable.getWriter(),p=y,(async()=>{try{for(;;){let T=await R.read();if(T.done||T.value===void 0)break;let M=T.value;M.byteLength!==0&&c((M[0]??0)|me|je,M.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(y){p=void 0,f=void 0,i(`[gem] webtransport datagram lane unusable (${Rt(y)}); unreliable sends ride the stream`);}return n.closed.then(y=>d(Sr(y?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(y,R){if(l)return;if(typeof y=="string"){e.write(gn(mn,_r.encode(y))).catch(()=>d("write failed"));return}let T=bn(R);if((T&me)!==0&&f!==void 0){let M=yn(T,y),I=p?.maxDatagramSize;if(I===void 0||M.byteLength<=I){f.write(M).catch(()=>{});return}}e.write(gn(T,y)).catch(()=>d("write failed"));},onMessage(y){a=y;},onClose(y){s=y;},close(){d("closed");}}}function Rn(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 a=false,s=setTimeout(()=>{a||(a=true,r.close(),o(new u("timeout","websocket did not come up in time")));},e),l=f=>{a||(a=true,clearTimeout(s),r.close(),o(f));},d=()=>{r.send(wr(n.credential));},m=f=>{if(a)return;if(typeof f.data!="string"){l(new u("join_refused","the server sent binary before answering the join"));return}let y;try{y=Rr(f.data);}catch(R){l(R);return}a=true,clearTimeout(s),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",c),r.removeEventListener("error",p),i({link:Go(r,xr(y,n.clock)),welcome:y});},c=()=>{l(new u("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new u("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",m),r.addEventListener("close",c),r.addEventListener("error",p),r.readyState===1&&d();})}function Sr(n){return typeof n=="string"&&n.length>0?n:void 0}function xr(n,e){return n.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:n.heartbeatIntervalMs}}function Sn(n,e){if(n===void 0)return {heard:()=>{},stop:()=>{}};let{clock:t}=n,r=Math.max(n.intervalMs,Co)*Io,i=t.now(),o=null,a=()=>{o=null;let s=t.now()-i;if(s>=r){e();return}o=t.setTimeout(a,r-s);};return o=t.setTimeout(a,r),{heard:()=>{i=t.now();},stop:()=>{o!==null&&(t.clearTimeout(o),o=null);}}}function Go(n,e){let t,r,i=false,o=s=>{if(!i){i=true,a.stop();try{n.close();}catch{}r?.(s);}},a=Sn(e,()=>o(fn));return n.addEventListener("message",(s=>{if(a.heard(),typeof s.data=="string"){t?.(s.data,_n);return}let l=new Uint8Array(s.data);if(l.byteLength===0)return;let d=l[0]??0;(d&hn)===0&&t?.(l.slice(1),vn(d));})),n.addEventListener("close",(s=>o(Sr(s?.reason)??"socket closed"))),{transport:"websocket",send(s,l){if(!i){if(typeof s=="string"){n.send(s);return}n.send(yn(bn(l),s));}},onMessage(s){t=s;},onClose(s){r=s;},close(){o("closed");}}}function xn(n,e,t,r){let i,o,a=false,s=t,l=c=>{if(!a){a=true,d.stop();try{n.close();}catch{}try{e.close();}catch{}o?.(c);}},d=Sn(r,()=>l(fn)),m=(c,p)=>{if(d.heard(),typeof c=="string"){i?.(c,_n);return}let f=new Uint8Array(c);if(f.byteLength===0)return;let y=f[0]??0;(y&hn)===0&&i?.(f.slice(1),vn(y|p));};if(n.addEventListener("message",(c=>m(c.data,0))),n.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let c=e.connectionState;(c==="failed"||c==="closed")&&l(`connection ${c}`);})),s!==void 0){let c=s;c.addEventListener("message",(p=>m(p.data,me|je))),c.addEventListener("close",(()=>{s=void 0;}));}return {transport:"webrtc",send(c,p){if(a)return;if(typeof c=="string"){n.send(c);return}let f=bn(p),y=yn(f,c);if((f&me)!==0&&s!==void 0&&s.readyState==="open"){s.send(y);return}n.send(y);},onMessage(c){i=c;},onClose(c){o=c;},close(){l("closed");}}}var Ar=10240,Pr=2048,Do=new TextEncoder;function Er(n){return Do.encode(n).length}function ie(n,e){let t=i=>{throw new u("invalid_sdp",`the ${e} ${i}`)},r=Er(n);r>=Ar&&t(`is ${r} bytes, over the ${Ar} 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=Er(i);o>Pr&&t(`has a ${o}-byte line, over the ${Pr} limit`);}}function xt(n){for(let e of n.split(/\r\n|\n/)){if(!e.startsWith("m="))continue;let[t,r="0"]=e.slice(2).trim().split(/\s+/);if(!(t!=="audio"&&t!=="video")&&r.split("/")[0]!=="0")return true}return false}var qo=3e3,$o=1e4,Fo=15e3;async function Be(n){let e=n.peerConnection;try{Ir(n,"before the handshake started"),An(n);let t=e.createDataChannel(n.channelLabel??"gem",{ordered:!0});for(let a of n.extraChannels??[]){let s=e.createDataChannel(a.label,{...a.ordered===void 0?{}:{ordered:a.ordered},...a.maxRetransmits===void 0?{}:{maxRetransmits:a.maxRetransmits}});n.onExtraChannel?.(a.label,s);}let r=await e.createOffer();await e.setLocalDescription(r),await Uo(e,n),An(n);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new u("invalid_sdp","the offer carried no SDP");ie(i,"offer"),Tr(i,"offer");let o=await No(n,i);if(An(n),typeof o?.sdp!="string")throw new u("invalid_sdp","the signaling channel answered without an SDP");return ie(o.sdp,"answer"),Tr(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await Bo(t,n),Ir(n,"before the channel opened"),t}catch(t){throw e.close(),jo(t)}}function jo(n){return n instanceof u?n:Or(n)?pe():new u("connection_failed",Lr(n),{cause:n})}function Tr(n,e){if(xt(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 No(n,e){let t=n.exchangeTimeoutMs??$o,r=Mr(n,t),i=n.signaling.exchange({matchId:n.matchId,sdp:e,intent:n.intent??"initial"},n.signal).catch(o=>{throw o instanceof u?o:Or(o)?pe():new u("signaling_failed",Lr(o),{cause:o})});return Wo(i,n,r,()=>r.exhausted?Pn("while the offer was in flight"):new u("timeout",`no answer arrived within ${t}ms`))}function Uo(n,e){if(n.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:t}=e;return new Promise(r=>{let i=()=>{t.clearTimeout(a),n.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{n.iceGatheringState==="complete"&&i();},a=t.setTimeout(i,e.gatherTimeoutMs??qo);n.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function Bo(n,e){if(e.signal?.aborted)return Promise.reject(pe());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??Fo,i=Mr(e,r);return new Promise((o,a)=>{let s=()=>{t.clearTimeout(p),n.removeEventListener("open",l),n.removeEventListener("close",d),n.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{s(),o();},d=f=>{s(),a(new u("connection_failed","the data channel failed before it opened",Cr(f)===void 0?void 0:{cause:Cr(f)}));},m=()=>{s(),a(pe());},c=()=>{s(),a(i.exhausted?Pn("while the channel was still opening"):new u("timeout",`the data channel did not open within ${r}ms`));},p=t.setTimeout(c,i.ms);n.addEventListener("open",l),n.addEventListener("close",d),n.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function Mr(n,e){if(n.credentialExpiresAt===void 0)return {ms:e,exhausted:false};let t=n.credentialExpiresAt-n.clock.now();return t<=e?{ms:Math.max(0,t),exhausted:true}:{ms:e,exhausted:false}}function Wo(n,e,t,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(pe()):new Promise((a,s)=>{let l=c=>{i.clearTimeout(m),o?.removeEventListener("abort",d),c();},d=()=>l(()=>s(pe())),m=i.setTimeout(()=>l(()=>s(r())),t.ms);o?.addEventListener("abort",d),n.then(c=>l(()=>a(c)),c=>l(()=>s(c)));})}function Ir(n,e){if(n.credentialExpiresAt!==void 0&&!(n.clock.now()<n.credentialExpiresAt))throw Pn(`already ${e}`)}function Pn(n){return new u("credential_expired",`the join credential ran out ${n} \u2014 poll match status again for a fresh one`)}function An(n){if(n.signal?.aborted)throw pe()}function pe(){return new u("aborted","the caller aborted the connection attempt")}function Or(n){return n?.name==="AbortError"}function Cr(n){return n?.error}function Lr(n){return n instanceof Error?n.message:String(n)}var We="0.1.0-beta",Gr="0-beta",Se="web",Vo=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/;function Ho(n){let e=Vo.exec(n),t=e?.[1],r=e?.[4];return t===void 0?null:r===void 0?t:`${t}-${r}`}function Dr(n,e){let t=Ko(n.platform,e),r=n.engineVersion;if(r===void 0)return {...n,platform:t,engineVersion:We};let i=Ho(r);if(i===null)throw new 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!==Gr)throw new u("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${Gr}' is the only line a web dedicated-server fleet runs. gem-api uses the line \u2014 the semver major plus any prerelease tag \u2014 verbatim as the fleet's label selector, so a match on '${i}' would match nothing and be reported as a capacity shortfall rather than as this. Omit engineVersion: a browser game has no engine version of its own, and the SDK reports '${We}' for it.`);return {...n,platform:t,engineVersion:r}}function Ko(n,e){if(n===void 0||n===Se)return Se;if(!en.includes(n))throw new u("misconfigured",`${e} refused: platform '${String(n)}' is not a client platform gem-api recognises \u2014 it knows ${en.map(t=>`'${t}'`).join(", ")}. Remove the field: the SDK reports '${Se}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${n}' was replaced with '${Se}' and is deprecated \u2014 remove the field. A browser game publishes its bundle in the web package dimension, so a client reporting anything else is version-checked against a dimension it has nothing in, and every blacklist, release and expiry check passes without looking at this build.`),Se}function Jo(n){let{client:e,clock:t,rooms:r}=n,i=n.signaling??vt,o=n.log??(g=>console.warn(g)),a=new ue({client:e,gameId:()=>r.gameId,transport:"dedicated"}),s=new Map,l=(g,v)=>{let w=s.get(g)??new Set;w.add(v),s.set(g,w);},d=(g,v)=>{let w=s.get(g);w!==void 0&&(w.delete(v),w.size===0&&s.delete(g));},m=async g=>{if(r.isHost&&!rs(r)&&r.currentRoom?.matchId===void 0){let v=B(g.clusterTargetId);await r.startMatch({...v===void 0?{}:{clusterTargetId:v},...g.retry===void 0?{}:{retry:g.retry},...g.signal===void 0?{}:{signal:g.signal}});}return Ur(r.matchConnectionState==="suspended"?await r.reconnectToMatch(En(g)):await r.awaitMatch(En(g)))},c=async g=>Ur(await r.pollMatchStatus(En(g))),p=async(g,v)=>{let w=false;try{let _=await m(g),G=r.currentRoom?.transports;if(G!==void 0&&!G.includes("webrtc"))throw new u("misconfigured",`the room template offers (${G.join(", ")||"no transports"}), not webrtc, which is all this path dials. Connect through gem.match.connect(), or pass \`transports: []\` here to negotiate across the template's list.`);let C=g.peerConnection??Br();w=!0;let D=await Be({peerConnection:C,signaling:v,clock:t,matchId:_.matchId,credentialExpiresAt:_.credentialExpiresAt,...At(g,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),F=null;if(g.presentCredential!==!1)try{F=await Fe({channel:D,clock:t,credential:_.joinCredential,credentialExpiresAt:_.credentialExpiresAt,...At(g,"onMessage","signal"),...g.welcomeTimeoutMs===void 0?{}:{ceilingMs:g.welcomeTimeoutMs}});}catch(N){throw J(D),J(C),N}return ns(r,_,D,C,v,g.reportDisconnect!==!1,g.reportConnected!==!1,F,{remember:l,forget:d},g.onMatchEnded)}catch(_){throw w&&Nr(a,_),J(v),_}},f=async(g,v,w,_,G,C)=>{if(g==="webtransport"){let O=_?.webtransport;if(O===void 0)throw new u("misconfigured","webtransport is not advertised");let Y={credential:w.joinCredential,credentialExpiresAt:w.credentialExpiresAt,clock:t};if(typeof O.named_url=="string"&&O.named_url!==""){let ne=Math.max(Math.floor(C/2),1e3);try{return await Ue({url:O.named_url,timeoutMs:ne,log:o,...Y})}catch(se){if(St()!==null)throw se;return o(`[gem] webtransport named dial failed (${Rt(se)}); retrying the pinned dial`),Ue({url:O.url,certHashBase64:O.cert_sha256_b64,timeoutMs:ne,log:o,...Y})}}return Ue({url:O.url,certHashBase64:O.cert_sha256_b64,timeoutMs:C,...Y})}if(g==="websocket"){let O=_?.websocket;if(O===void 0)throw new u("misconfigured","websocket is not advertised");return Rn({url:O.url,credential:w.joinCredential,credentialExpiresAt:w.credentialExpiresAt,clock:t,timeoutMs:C})}let D=v.peerConnection??Br(),F,N=await Be({peerConnection:D,signaling:G,clock:t,matchId:w.matchId,credentialExpiresAt:w.credentialExpiresAt,extraChannels:[{label:_t,ordered:false,maxRetransmits:0}],onExtraChannel:(O,Y)=>{O===_t&&(F=Y);},...At(v,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...v.exchangeTimeoutMs===void 0&&v.redial===true?{exchangeTimeoutMs:Yo}:{}}),K;try{K=await Fe({channel:N,clock:t,credential:w.joinCredential,credentialExpiresAt:w.credentialExpiresAt,wire:kt,heartbeat:!0,...At(v,"signal"),...v.welcomeTimeoutMs===void 0?{}:{ceilingMs:v.welcomeTimeoutMs}});}catch(O){throw J(N),J(D),O}let A=K.welcome.heartbeatIntervalMs;return {link:xn(N,D,F,A===void 0?void 0:{clock:t,intervalMs:A}),welcome:K.welcome,channel:N,peerConnection:D}},y=(g,v,w,_,G)=>{let C=false,D;_.link.onClose(A=>{!C&&g.reportDisconnect!==false&&an(r,v.matchId,A),D?.(A);}),g.reportDisconnect!==false&&g.reportConnected!==false&&r.notifyMatchConnected(v.matchId);let F={transport:_.link.transport,send:(A,O)=>_.link.send(A,O),onMessage:A=>_.link.onMessage(A),onClose:A=>{D=A;},close:()=>_.link.close()},N=()=>{C||(C=true,J(_.link),J(G));},K=A=>{if(!C){try{g.onMatchEnded?.(A);}catch{}N();}};return l(v.matchId,K),{matchId:v.matchId,transport:w,link:F,joinCredential:v.joinCredential,credentialExpiresAt:v.credentialExpiresAt,welcome:_.welcome,..._.channel===void 0?{}:{channel:_.channel},..._.peerConnection===void 0?{}:{peerConnection:_.peerConnection},close(){d(v.matchId,K),N();}}},R=async(g,v)=>{let w=r.currentRoom?.id,_=r.gameId,G=()=>({advert:wt(r.currentRoom?.settings,g),template:r.currentRoom?.transports??null});if(w===void 0||_===null)return G();try{let C=await e.get(`/v2/games/${encodeURIComponent(_)}/game-rooms/${encodeURIComponent(w)}`,v);return {advert:wt(C.settings,g),template:Ne(C.transports)??r.currentRoom?.transports??null}}catch{return G()}},T=(g,v)=>{let w=g??qr;return v.length===0?w:w.filter(_=>v.includes(_))},M=async(g,v,w)=>{try{let _=await m(g),{advert:G,template:C}=await R(_.matchId,g.signal),D=T(C,v),F=D.filter(q=>Zo(q,G)),N=St();if(N!==null&&D.includes("webtransport")&&G?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${N} (learned on an earlier dial in this page)`),F.length===0){let q=C===null?`the default order (${qr.join(", ")})`:`the room template's transports (${C.join(", ")||"none"})`;throw new u("misconfigured",`none of ${q}`+(v.length>0?`, narrowed to (${v.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let K=g.transportAttemptTimeoutMs??zo,A=()=>g.deadlineAt===void 0?1/0:g.deadlineAt-t.now(),O=q=>n.signalingReady===void 0||q<=0?Promise.resolve(!0):n.signalingReady(q),Y=[],ne=[];for(let q of F){if(A()<Fr){o(`[gem] ${q} rung not tried: the reconnect budget is spent`);break}ne.length>0&&_.credentialExpiresAt-t.now()<jr&&(_=await c(g)),ne.push(q);let Nn=!1,Un=!1,Ze={attempts:0,waitedMs:0};for(;;){if(q==="webrtc"&&g.redial===!0){let Q=Math.min($r,A());await O(Q)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(Q)}ms; offering anyway`);}let vi=Math.max(Math.min(K,A()),Fr);try{return y(g,_,q,await f(q,g,_,G,w,vi),w)}catch(Q){let U=Q instanceof u?Q:new u("connection_failed",Q instanceof Error?Q.message:String(Q),{cause:Q});if(q==="webrtc"&&Nr(a,U),(U.reason==="credential_expired"||U.reason==="credential_reused")&&!Nn){Nn=!0,_=await c(g);continue}if(q==="webrtc"&&U.reason==="signaling_failed"&&U.platformCode===on&&!Un){Un=!0;let ae=Math.min($r,A());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 O(ae))continue}if(U.reason==="join_rate_limited"){let ae=Qo(Ze,Math.random,A());if(ae!==null){if(Ze.attempts+=1,Ze.waitedMs+=ae,o(`[gem] ${q} rung: the server is rate-limiting this player's joins; waiting ${Math.round(ae)}ms before presenting again (retry ${Ze.attempts} of ${Vr.maxAttempts})`),await yt(t,ae,g.signal),g.signal?.aborted)throw new u("aborted","the caller aborted while waiting out a join rate limit");_.credentialExpiresAt-t.now()<jr&&(_=await c(g));continue}}if(Xo.has(U.reason)||U.reason==="credential_expired"||q==="webrtc"&&Wr(U)){o(`[gem] ${q} rung failed (${U.reason}): ${Rt(U.cause??U)} \u2014 `+(ne.length<F.length?`falling through to ${F[ne.length]}`:"no rungs left")),Y.push(U);break}throw o(`[gem] ${q} rung refused the session (${U.reason}): ${U.message}`),U}}}let se=Y[Y.length-1];throw se===void 0?new u("timeout",`the reconnect budget ran out before any transport (${F.join(", ")}) could be tried`):new u(se.reason,`every transport tried (${ne.join(", ")}) failed; the last said: ${se.message}`,{cause:Y,platformCode:se.platformCode})}catch(_){throw J(w),_}};return {listClusterTargets:async(g={})=>ft({client:e,...g}),handleMatchEnded(g,v){let w=s.get(g);if(w!==void 0){s.delete(g);for(let _ of w)_(v);}},connect:(async(g={})=>{let v=g.signaling??i();return g.transports===void 0?p(g,v):M(g,g.transports,v)})}}var qr=["webtransport","webrtc","websocket"],zo=1e4,Yo=5e3,$r=3e3,Fr=1e3,jr=1e4,Xo=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function Wr(n){return n.platformCode!==void 0&&sn.has(n.platformCode)}var Vr={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function Qo(n,e=Math.random,t=1/0){let r=Vr;if(n.attempts>=r.maxAttempts)return null;let i=Math.min(r.budgetMs-n.waitedMs,t);if(i<r.initialDelayMs)return null;let o=r.initialDelayMs*r.factor**n.attempts;return Math.min(o+e()*r.jitterMs,i)}function Zo(n,e){return n==="webrtc"?e===null||e.webrtc!==false:e===null?false:n==="webtransport"?e.webtransport!==void 0&&kn():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||es(e.websocket.url)}function es(n){if(typeof n!="string")return false;let e;try{e=new URL(n).hostname.toLowerCase();}catch{return false}return ut(e)}function En(n){return {...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.pollIntervalMs===void 0?{}:{pollIntervalMs:n.pollIntervalMs},...n.signal===void 0?{}:{signal:n.signal}}}var ts=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Nr(n,e){e instanceof u&&(!ts.has(e.reason)&&!Wr(e)||n.report([{type:"connection_failures_total",value:1}]));}function ns(n,e,t,r,i,o,a,s,l,d){let m=false,c=()=>{m||an(n,e.matchId,void 0);};o&&(t.addEventListener("close",c),a&&n.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,t.removeEventListener("close",c),s?.detach(),J(t),J(r),J(i));},f=y=>{if(!m){try{d?.(y);}catch{}p();}};return l.remember(e.matchId,f),{matchId:e.matchId,channel:t,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:s?.welcome??null,close(){l.forget(e.matchId,f),p();}}}function rs(n){let e=n.matchSession.phase;return e!=="none"&&e!=="ended"}function Ur(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!==$e)throw new u("unsupported_protocol",`match ${n.matchId} speaks '${n.protocol}', which a browser cannot connect. Only '${$e}' is reachable from a frame; host and port on this response are advisory and must not be dialled.`);let{joinCredential:e,credentialExpiresAt:t}=n;if(e===void 0||t===void 0)throw new 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 Br(){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 J(n){try{n.close();}catch{}}function At(n,...e){let t={};for(let r of e)n[r]!==void 0&&(t[r]=n[r]);return t}var xe=class{constructor(e){this.options=e;this.reporter=new ue({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,t,r){let i=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:t},r);return {credential:Pt(i.credential)??"",hostFingerprint:Pt(i.host_fingerprint)??"",hostEpoch:Et(i.host_epoch)??0,expiresAt:(Et(i.expires_at)??0)*1e3}}async turnLease(e,t,r){let i=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:t},r),o=[];for(let l of Array.isArray(i.ice_servers)?i.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(c=>typeof c=="string"&&c.length>0);m.length!==0&&o.push({urls:m,username:Pt(d.username)??"",credential:Pt(d.credential)??""});}let a=Et(i.expires_at),s=Et(i.ttl_seconds);return {iceServers:o,expiresAt:a!==void 0?a*1e3:Date.now()+(s??0)*1e3}}async kick(e,t,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:t},r);}async leave(e,t=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:t});}async telemetry(e,t){await this.reporter.post(e,t);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}};function Pt(n){return typeof n=="string"&&n.length>0?n:void 0}function Et(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}var is=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),k=class extends Error{constructor(t,r,i){super(`${t}: ${r}`,i);this.reason=t;this.name="P2pError",this.retryable=is.has(t);}reason;retryable};var Tt=class{listeners=new Map;on(e,t){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>this.off(e,t)}off(e,t){this.listeners.get(e)?.delete(t);}once(e,t){let r=this.on(e,((...i)=>{r(),t(...i);}));return r}emit(e,...t){let r=this.listeners.get(e);if(r)for(let i of [...r])i(...t);}clear(){this.listeners.clear();}};var os=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function ge(n){let e=null;for(let t of n.split(/\r\n|\n/)){if(!t.startsWith("a=fingerprint:"))continue;let r=Ve(t.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function Ve(n){let[e,...t]=n.trim().split(/\s+/);if(e===void 0||t.length===0)return null;let r=`${e.toLowerCase()} ${t.join("").toUpperCase()}`;return os.test(r)?r:null}function Ae(n,e){if(n.length!==e.length)return false;let t=0;for(let r=0;r<n.length;r++)t|=n.charCodeAt(r)^e.charCodeAt(r);return t===0}var Tn=5e3,ss=12e4+Tn,as=1024,ls=6e4,ds=1e4,Hr=64*1024,Kr=5;function It(n){let e=new Map,t=-1/0,r=null,i=(()=>{let s;try{s=new URL(`${n.baseUrl.replace(/\/+$/,"")}/oauth2/jwks`);}catch{return {ok:false,reason:"the configured API base is not a valid URL, so the JWKS endpoint cannot be reached. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}}return s.username!==""||s.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:s.href,shown:`${s.protocol}//${s.host}`}})(),o=()=>{let s=n.subtle??globalThis.crypto?.subtle;if(!s)throw new k("keys_unavailable","this environment has no WebCrypto, so a join credential cannot be verified. A page served over plain http on a non-loopback origin is the usual cause \u2014 crypto.subtle is only exposed in a secure context.");return s},a=async()=>{if(!i.ok)throw new k("keys_unavailable",i.reason);let s=n.fetch??((p,f)=>globalThis.fetch(p,f)),l;try{l=await s(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(ds)});}catch{throw new k("keys_unavailable",`the JWKS endpoint at ${i.shown} could not be reached \u2014 it timed out, refused a redirect, or the network failed.`)}if(!l.ok)throw new k("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let d;try{let p=await l.text();if(p.length>Hr)throw new k("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${Hr} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof k?p:new k("keys_unavailable",`the JWKS endpoint at ${i.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>Kr)throw new k("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${Kr} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=o();for(let p of m){let f=p;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 y=await c.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(f.kid,y);}catch{}}};return {async key(s){let l=e.get(s);if(l)return l;if(!i.ok)throw new k("keys_unavailable",i.reason);if(r)return await r,e.get(s)??null;let d=n.now();if(!Number.isFinite(d))throw new k("keys_unavailable","the clock supplied to the SDK returned a non-finite time, so the JWKS throttle cannot be evaluated. This is a configuration fault, not a server failure.");return d<t&&(t=-1/0),d-t<ls?null:(t=d,r??=a().finally(()=>{r=null;}),await r,e.get(s)??null)}}}var He=class{seen=new Map;admit(e,t){for(let[r,i]of this.seen)i<=t&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=as){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,t+ss),true}};function zr(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 Jr(n){try{let e=new TextDecoder().decode(zr(n)),t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch{return null}}async function Ct(n,e,t,r,i){let o=A=>{throw new k("peer_unauthenticated",`the peer's join credential is not usable: ${A}`)},a=n.split(".");a.length!==3&&o("it is not a three-part JWT");let[s,l,d]=a,m=Jr(s);m===null&&o("its header does not decode"),m.alg!=="RS256"&&o(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let c=m.kid;(typeof c!="string"||c.length===0)&&o("it names no key");let p=await t.key(c);p===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 y=new TextEncoder().encode(`${s}.${l}`),R;try{R=zr(d);}catch{o("its signature does not decode");}await f.verify({name:"RSASSA-PKCS1-v1_5"},p,R,y)||o("its signature does not verify");let M=Jr(l);M===null&&o("its payload does not decode");let I=M,g=A=>typeof I[A]=="string"?I[A]:"",v=A=>typeof I[A]=="number"&&Number.isFinite(I[A])?I[A]:NaN;g("iss")!==i.issuer&&o("it was issued by someone else"),g("aud")!==`${i.issuer}/p2p-match`&&o("its audience is not this platform"),g("match_id")!==e.matchId&&o("it is for another match"),g("game_id")!==e.gameId&&o("it is for another game");let w=v("exp")*1e3,_=v("nbf")*1e3;(!Number.isFinite(w)||e.now>w+Tn)&&o("it has expired"),Number.isFinite(_)&&e.now<_-Tn&&o("it is not valid yet");let G=g("role");G!=="host"&&G!=="client"&&o("it names no usable role");let C=v("host_epoch");C!==e.hostEpoch&&o("it names a different host epoch");let D=Ve(g("fingerprint"));D===null&&o("its fingerprint claim is malformed"),Ae(D,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let F=Ve(g("host_fingerprint"));F===null&&o("its host fingerprint claim is malformed"),Ae(F,e.hostFingerprint)||o("it was issued against a different host certificate");let N=g("jti");N.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit(N,e.now)||o("it has already been used");let K=g("sub");return K.length===0&&o("it names no player"),{playerId:K.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:C,role:G,fingerprint:D,hostFingerprint:F,jti:N,expiresAt:w}}var he=32769;function In(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 Cn(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 Mn(n){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,3),t.setUint8(1,n),e}function On(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 Yr(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 Xr(n){switch(n){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var Qr=3e4,Pe=class{constructor(e,t,r){this.localPlayerId=e;this.hostPlayerId=t,this.epoch=r;}localPlayerId;state="idle";epoch;hostPlayerId;kicked=new Set;startedAt=0;get currentState(){return this.state}get currentEpoch(){return this.epoch}get currentHostPlayerId(){return this.hostPlayerId}get isLocalHost(){return this.hostPlayerId===this.localPlayerId}isKicked(e){return this.kicked.has(e)}stalled(e){return this.state!=="idle"&&e-this.startedAt>3e4}apply(e,t){return !Number.isInteger(e.hostEpoch)||e.hostEpoch<0?{kind:"refused",why:`host epoch ${String(e.hostEpoch)} is not a whole number`}:e.hostEpoch===this.epoch?e.migrationComplete===true&&this.state!=="idle"?(this.state="idle",{kind:"completed"}):{kind:"duplicate"}:e.hostEpoch<this.epoch?{kind:"refused",why:`host epoch ${e.hostEpoch} is behind the current ${this.epoch}`}:e.hostPlayerId.length===0?{kind:"refused",why:"the migration named no new host"}:(this.kicked=new Set(e.kickedPlayerIds??[]),this.epoch=e.hostEpoch,this.hostPlayerId=e.hostPlayerId,this.startedAt=t,this.state=this.isLocalHost?"preparing":"reconnecting",{kind:"accepted",state:this.state})}complete(){this.state="idle";}};var Mt={reliable:{negotiated:true,id:0,ordered:true},ordered:{negotiated:true,id:1,ordered:true,maxRetransmits:0},unreliable:{negotiated:true,id:2,ordered:false,maxRetransmits:0}},Ke=["reliable","ordered","unreliable"];function Ot(n){let e=globalThis.RTCPeerConnection;if(!e)throw new Error("[gem] this environment has no RTCPeerConnection. Pass `peerConnectionFactory` to connect against a stand-in, which is how this flow is tested outside a browser.");return new e({iceServers:n.iceServers,...n.certificates===void 0?{}:{certificates:n.certificates}})}async function Lt(){let n=globalThis.RTCPeerConnection;return n?.generateCertificate?n.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var ei=1,gs=3e4,ti=2e3,hs=5e3,ni=6e4,fs=8,Gn=class{constructor(e=fs){this.perMinute=e;}perMinute;sent=[];delayUntilAllowed(e){return this.prune(e),this.sent.length<this.perMinute?0:Math.max(0,(this.sent[0]??e)+6e4-e)}record(e){this.prune(e),this.sent.push(e);}prune(e){let t=0;for(let r of this.sent)r<=e&&e-r<6e4&&(this.sent[t++]=r);this.sent.length=t;}},ys=new Gn,bs=8,vs=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),Ee=class{constructor(e){this.options=e;this.keys=e.keys??It({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new Tt;links=new Map;replays=new He;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=ei+1;ended=null;closed=false;ready=null;helloSeen=false;reportedUnreachableEpoch=-1;reportedStallEpoch=-1;counted=false;pendingOffers=new Map;answeredSessions=new Map;credentialGeneration=0;credentialDeadline=0;get matchId(){return this.options.matchId}get playerId(){return this.localPlayerId}get isHost(){return this.migration?.isLocalHost??false}get hostPlayerId(){return this.migration?.currentHostPlayerId??""}get hostEpoch(){return this.migration?.currentEpoch??0}get peers(){let e=[];for(let t of this.links.values())t.admitted&&e.push(this.expose(t));return e}peer(e){let t=this.links.get(e);return t&&t.admitted?this.expose(t):null}on(e,t){return this.emitter.on(e,t)}off(e,t){this.emitter.off(e,t);}once(e,t){return this.emitter.once(e,t)}async start(e){let t=this.options.connectTimeoutMs??gs;this.credentialDeadline=this.options.clock.now()+t;let r=new Promise((s,l)=>{this.ready={resolve:s,reject:l};}),i=B(this.options.clusterTargetId);if(i!==void 0)try{let s=await this.options.api.turnLease(this.options.matchId,i,e);this.iceServers=s.iceServers,this.mark("turn leased");}catch(s){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${Ln(s)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let o=this.options.clock.setTimeout(()=>{this.fail(new k("timeout",`no usable P2P connection after ${t}ms. The parent relays signaling, so a silent failure here usually means the page is not putting frames on the socket.`));},t),a=()=>this.fail(new k("aborted","the caller aborted while connecting"));e?.aborted?a():e?.addEventListener("abort",a);try{await r;}finally{this.options.clock.clearTimeout(o),e?.removeEventListener("abort",a),this.ready=null;}}async kick(e){if(!this.isHost)throw new k("misconfigured","only the current host of this match can kick a peer");await this.options.api.kick(this.options.matchId,e);}async leave(){try{await this.options.api.leave(this.options.matchId);}catch{}this.close();}close(){if(!this.closed){this.closed=true,this.pendingOffers.clear();for(let e of [...this.links.values()])this.dropLink(e,"closed",false);this.options.signaling.close(),this.emitter.clear();}}report(e){this.options.api.telemetry(e).catch(()=>{});}notifyCandidatesDropped(e){this.emitter.emit("candidatesDropped",e);}handleSignal(e,t){this.closed||this.route(e,t).catch(r=>this.report_(r));}async route(e,t){switch(e){case "hello":return this.onHello(t);case "offer":return this.onOffer(t);case "answer":return this.onAnswer(t);case "ice":return this.onIce(t);case "peerLeft":return this.onPeerLeft(t);case "migration":return this.onMigration(t);case "matchEnded":return this.onMatchEnded(t);case "error":return this.onSignalingError(t);default:return}}async onHello(e){let t=$(e.playerId),r=$(e.hostPlayerId),i=Gt(e.hostEpoch);if(!(t===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=t,this.migration===null&&(this.migration=new Pe(t,r,i)),!this.helloSeen)){if(this.helloSeen=true,this.isHost){this.mark("host listening"),this.settle(),await this.drainPendingOffers();return}this.pendingOffers.clear(),await this.offerToHost("initial");}}async drainPendingOffers(){if(this.pendingOffers.size===0)return;let e=[...this.pendingOffers.values()];this.pendingOffers.clear(),this.mark("queued offer drained");for(let t of e)try{await this.onOffer(t);}catch(r){this.report_(r);}}async offerToHost(e){let t=this.hostPlayerId,r=this.openLink(t,ei),i=await r.connection.createOffer();await r.connection.setLocalDescription(i);let o=r.connection.localDescription?.sdp??i.sdp;if(!o)throw new k("invalid_sdp","the browser produced an offer with no SDP");ie(o,"offer"),this.refuseMedia(o,"offer"),this.options.signaling.offer(o,e),this.mark("offer sent"),this.fetchCredential().catch(a=>this.report_(a));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,i=r===void 0?null:ge(r);if(i===null)throw new k("invalid_sdp","this browser produced an offer with no usable DTLS fingerprint, so the platform cannot bind a credential to it");let o=this.options.credentialPacing??ys,a=()=>this.closed||e!==this.credentialGeneration,s=hs;for(;;){let l=o.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,a))return;o.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,i);if(a())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(a())return;let m=d.status,c;if(m===409)c=ti;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?c=p*1e3:(c=s,s=Math.min(s*2,ni)),c=Math.min(Math.max(c,ti),ni);}else throw d;if(!await this.waitForCredential(c,a))return}}}async waitForCredential(e,t){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!t())}async onOffer(e){let t=$(e.fromPlayerId),r=$(e.sdp);if(t===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(t),this.pendingOffers.size>=bs){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(t,e);return}if(!this.isHost||this.migration.isKicked(t)===true)return;let i=$(e.sessionId);if(i!==null&&this.answeredSessions.get(t)===i)return;ie(r,"offer"),this.refuseMedia(r,"offer");let o=ge(r);if(o===null)throw new k("invalid_sdp",`the offer from ${t} carries no usable fingerprint`);this.mark("offer received"),i!==null&&this.answeredSessions.set(t,i);let a=this.links.get(t);a&&this.dropLink(a,"resignalled",false);let s=this.openLink(t,this.nextPeerId++);s.remoteFingerprint=o,await s.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(s);let l=await s.connection.createAnswer();await s.connection.setLocalDescription(l);let d=s.connection.localDescription?.sdp??l.sdp;if(!d)throw new k("invalid_sdp","the browser produced an answer with no SDP");ie(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(t,d,s.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let t=$(e.fromPlayerId),r=$(e.sdp);if(t===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||t!==this.hostPlayerId)return;ie(r,"answer"),this.refuseMedia(r,"answer");let o=ge(r);if(o===null)throw new k("invalid_sdp","the host's answer carries no usable fingerprint");this.mark("answer received"),i.remoteFingerprint=o,i.pendingAnswer=r,this.hostVerified(i)&&await this.applyAnswer(i,r);}hostVerified(e){let t=this.credential;return t===null||e.remoteFingerprint===null?false:Ae(t.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new k("peer_unauthenticated","the host's DTLS certificate is not the one the platform attested for this match. Refusing before the handshake, so no credential is presented.")),this.dropLink(e,"host_fingerprint_mismatch",false),false)}maybeAuthenticate(){if(this.isHost)return;let e=this.links.get(this.hostPlayerId);if(!e||e.remoteFingerprint===null||e.connection.remoteDescription!==null)return;let t=e.pendingAnswer;t!==void 0&&this.hostVerified(e)&&this.applyAnswer(e,t).catch(r=>this.report_(r));}async applyAnswer(e,t){this.mark("host verified"),e.pendingAnswer=void 0,await e.connection.setRemoteDescription({type:"answer",sdp:t}),this.flushCandidates(e);}async onIce(e){let t=$(e.fromPlayerId),r=$(e.candidate);if(t===null||r===null)return;let i=this.links.get(t);if(!i)return;let o=$(e.sdpMid),a=Gt(e.sdpMLineIndex)??Gt(e.sdpMLineIndexAlt),s={candidate:r,...o===null?{}:{sdpMid:o},...a===null?{}:{sdpMLineIndex:a}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(s);return}await i.connection.addIceCandidate(s);}onPeerLeft(e){let t=$(e.playerId);if(t===null)return;let r=$(e.reason)??"left";if(t===this.localPlayerId){this.fail(new k("kicked",`this player was removed from the match (${r})`)),this.close();return}let i=this.links.get(t);i&&this.dropLink(i,r,true);}async onMigration(e){let t=$(e.hostPlayerId),r=Gt(e.hostEpoch);if(t===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:t,hostEpoch:r,...$(e.reason)===null?{}:{reason:$(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(o=>typeof o=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(i.kind!=="duplicate"){if(i.kind==="completed"){this.emitter.emit("hostChanged",t,r);return}if(i.kind==="refused"){this.report_(new k("migration_failed",i.why));return}for(let o of [...this.links.values()])this.dropLink(o,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",t,r),i.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration(),await this.offerToHost("full_reconnect");}}watchMigration(){let e=this.hostEpoch;this.options.clock.setTimeout(()=>{this.closed||this.migration===null||this.migration.currentEpoch===e&&this.migration.stalled(this.options.clock.now())&&this.reportedStallEpoch!==e&&(this.reportedStallEpoch=e,this.report_(new k("migration_failed",`host migration to epoch ${e} did not complete. The elected host never acknowledged it, so the platform is still holding the match in migration.`)));},31e3);}onMatchEnded(e){let t=$(e.reason)??"ended";this.ended=t,this.emitter.emit("matchEnded",t),this.ready!==null&&this.fail(new k("match_ended",`the match ended: ${t}`)),this.close();}onSignalingError(e){let t=$(e.code)??"unknown",r=$(e.message)??"the platform refused a signaling message";this.report_(new k("signaling_failed",`${t}: ${r}`));}openLink(e,t){let i=(this.options.peerConnectionFactory??Ot)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let p of Ke){let f=i.createDataChannel(p,Mt[p]);f.binaryType="arraybuffer",o[p]=f;}let a={playerId:e,assignedPeerId:t,connection:i,channels:o,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},s=p=>{let f=p.candidate;f?.candidate&&this.options.signaling.candidate(e,f.candidate,f.sdpMid??void 0,f.sdpMLineIndex??void 0);},l=()=>this.onIceState(a),d=()=>this.onConnectionState(a),m=p=>{this.onHandshakeMessage(a,p.data).catch(f=>this.report_(f));},c=()=>{this.onReliableOpen(a).catch(p=>this.report_(p));};return i.addEventListener("icecandidate",s),i.addEventListener("iceconnectionstatechange",l),i.addEventListener("connectionstatechange",d),o.reliable.addEventListener("open",c),o.reliable.addEventListener("message",m),a.detachHandshake=()=>{o.reliable.removeEventListener("open",c),o.reliable.removeEventListener("message",m);},a.detachAll=()=>{a.detachHandshake(),i.removeEventListener("icecandidate",s),i.removeEventListener("iceconnectionstatechange",l),i.removeEventListener("connectionstatechange",d);},this.links.set(e,a),a}flushCandidates(e){let t=e.pendingCandidates;e.pendingCandidates=[];for(let r of t)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let t=this.credential;if(t===null)throw new k("peer_unauthenticated","the channel opened before the platform issued a join credential, so there is nothing to present");if(this.options.clock.now()>=t.expiresAt)throw new k("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(In({jwt:t.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,t){if(!(t instanceof ArrayBuffer))return;let r=On(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(Xr(r.reason),Yr(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=ge(e.connection.localDescription?.sdp??"");if(i===null||e.remoteFingerprint===null){this.refuseLink(e,1,"fingerprint_unavailable","this connection's DTLS fingerprints could not be read from its SDP, so no credential can be checked against it");return}let o;try{o=await Ct(t,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:i,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(a){let s=a instanceof k&&a.reason==="keys_unavailable";this.refuseLink(e,s?131:1,s?"keys_unavailable":"credential_invalid",Ln(a)),s&&this.fail(a);return}if(o.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${o.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(o.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(Cn({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(Mn(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)ri(e.channels[i]);ri(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",Ln(e),{cause:e}));}count(e){this.counted||!vs.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,t){if(xt(e))throw new k("media_refused",`the ${t} carries an active audio or video section. This path carries data channels only; voice belongs to the platform voice service, and gem-api age-gates relayed SDP that proposes media.`)}mark(e){this.options.boot?.mark(e);}sleep(e){return new Promise(t=>this.options.clock.setTimeout(t,e))}warn(e){let t=this.options.log;t!==null&&(t??(r=>console.warn(r)))(`[gem] ${e}`);}get endedReason(){return this.ended}};function $(n){return typeof n=="string"&&n.length>0?n:null}function Gt(n){return typeof n=="number"&&Number.isInteger(n)?n:null}function Ln(n){return n instanceof Error?n.message:String(n)}function ri(n){try{n.close();}catch{}}var _s=100,ks=50,Te=class{constructor(e){this.options=e;}options;queue=[];drainHandle=null;dropped=0;closed=false;dropListener=null;onDropped(e){this.dropListener=e;}join(){this.assertUsable(),this.options.bridge.signal("join",this.options.matchId,{});}offer(e,t){this.assertUsable(),this.options.bridge.signal("offer",this.options.matchId,{sdp:e,intent:t});}answer(e,t,r){this.assertUsable(),this.options.bridge.signal("answer",this.options.matchId,{peerId:e,sdp:t,assignedPeerId:r});}candidate(e,t,r,i){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??_s)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:t,...r===void 0?{}:{sdpMid:r},...i===void 0?{}:{sdpMLineIndex:i}}),this.schedule();}migrationAck(e){this.assertUsable(),this.options.bridge.signal("migrationAck",this.options.matchId,{hostEpoch:e});}reportHostUnreachable(e,t){this.assertUsable(),this.options.bridge.signal("hostUnreachable",this.options.matchId,{hostEpoch:e,evidence:{iceState:t,lastSeenAt:Math.floor(this.options.clock.now()/1e3)}});}discardQueued(){this.queue.length=0;}close(){this.closed=true,this.discardQueued(),this.drainHandle!==null&&(this.options.clock.clearTimeout(this.drainHandle),this.drainHandle=null);}assertUsable(){if(this.closed)throw new k("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new k("signaling_unavailable","the page embedding this game did not advertise the `p2p` capability, so there is nothing to carry signaling. P2P needs the notification WebSocket, and only the parent can hold one \u2014 see docs/p2p-and-parties.md \xA72.")}schedule(){this.drainHandle!==null||this.closed||(this.drainHandle=this.options.clock.setTimeout(()=>{this.drainHandle=null;let e=this.queue.shift();if(e!==void 0){let{peerId:t,candidate:r,sdpMid:i,sdpMLineIndex:o}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:t,candidate:r,...i===void 0?{}:{sdpMid:i},...o===void 0?{}:{sdpMLineIndex:o}});}if(this.dropped>0&&this.queue.length===0){let t=this.dropped;this.dropped=0,this.options.onCandidatesDropped?.(t),this.dropListener?.(t);}this.queue.length>0&&this.schedule();},this.options.candidateIntervalMs??ks));}};var Dn="webrtc_p2p";function ws(n){let e=new xe({client:n.client,gameId:n.gameId}),t=new Map;return {handleSignalEvent(r,i,o){t.get(r)?.handleSignal(i,o);},session(r){return t.get(r)??null},async connect(r={}){if(n.bridge===null)throw new k("signaling_unavailable","P2P signaling rides the notification WebSocket, which only the page embedding this game can hold. There is no bridge here \u2014 this is `mock` mode, or a game running outside the Arcade frame. See docs/p2p-and-parties.md \xA72.");let i=B(r.clusterTargetId),o=i??B(await n.resolveClusterTarget?.());n.rooms.isHost&&n.rooms.currentMatch===null&&n.rooms.currentRoom?.matchId===void 0&&await n.rooms.startMatch({...i===void 0?{}:{clusterTargetId:i},...r.signal===void 0?{}:{signal:r.signal}});let a=await n.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(a.protocol!==Dn)throw new k("unsupported_protocol",`match ${a.matchId} speaks '${a.protocol}', not '${Dn}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let s=new Te({bridge:n.bridge,matchId:a.matchId,clock:n.clock}),l=new Ee({api:e,clock:n.clock,matchId:a.matchId,gameId:n.gameId(),baseUrl:typeof n.baseUrl=="function"?n.baseUrl():n.baseUrl,signaling:s,...o===void 0?{}:{clusterTargetId:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await Lt(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...n.boot===void 0?{}:{boot:n.boot},...n.log===void 0?{}:{log:n.log}});s.onDropped(d=>l.notifyCandidatesDropped(d)),t.set(a.matchId,l),l.on("matchEnded",()=>t.delete(a.matchId));try{await l.start(r.signal);}catch(d){throw t.delete(a.matchId),l.close(),d}return l}}}function ii(n){return typeof n=="string"&&n.trim()!==""}function oi(n,e){return ii(n)?n.trim():ii(e)?e:null}function Je(n){let e=String(n);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function si(n,e,t){let r=`/v1/games/${Je(n.gameId())}/matchmaking/tickets/${Je(e)}`;return n.client.delete(r,t?.signal)}async function ai(n,e,t){let r=`/v1/games/${Je(n.gameId())}/matchmaking/tickets`;return n.client.post(r,e,t?.signal)}async function li(n,e,t){let r=`/v1/games/${Je(n.gameId())}/matchmaking/tickets/${Je(e)}/heartbeat`;return n.client.post(r,void 0,t?.signal)}function ze(n){let e=n??{};if(typeof e.ticket_id!="string"||e.ticket_id.length===0)throw new Error("[gem] a matchmaking-ticket response carried no id");let t=e.heartbeat_interval_seconds;return {id:e.ticket_id,status:typeof e.status=="string"?e.status:"queued",...typeof e.reason=="string"?{reason:e.reason}:{},...typeof e.game_room_id=="string"?{roomId:e.game_room_id}:{},partySize:typeof e.party_size=="number"?e.party_size:1,queuedAt:di(e.queued_at),expiresAt:di(e.expires_at),heartbeatIntervalSeconds:typeof t=="number"&&t>0?t:0}}function di(n){if(typeof n!="string")return 0;let e=Date.parse(n);return Number.isFinite(e)?Math.floor(e/1e3):0}var Rs=3,ci=1e3,Dt=class{constructor(e){this.options=e;this.snapshot=e.first;let t=new Promise((o,a)=>{this.resolve=o,this.reject=a;});t.catch(()=>{});let r=()=>this.snapshot,i=()=>this.status;this.ticket={get id(){return r().id},get status(){return i()},get partySize(){return r().partySize},get queuedAt(){return r().queuedAt},get expiresAt(){return r().expiresAt},outcome:t,cancel:()=>(this.requestCancel(),t)};}options;ticket;snapshot;status="queued";timer=null;busy=false;again=false;cancelRequested=false;soon=false;misses=0;settled=false;resolve;reject;start(){this.apply(this.snapshot);}poke(){this.settled||(this.soon=true,!this.busy&&(this.clearTimer(),this.tick()));}abandon(e=false){this.settled||(this.options.cancel(this.snapshot.id,e).catch(()=>{}),this.settle({status:"cancelled",reason:"requested"}));}requestCancel(){this.settled||(this.cancelRequested=true,this.trigger());}trigger(){if(this.busy){this.again=true;return}this.clearTimer(),this.tick();}schedule(e=false){if(this.settled)return;this.clearTimer();let t=e?ci:Math.max(ci,this.snapshot.heartbeatIntervalSeconds*1e3);this.timer=this.options.clock.setTimeout(()=>{this.timer=null,this.tick();},t);}clearTimer(){this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null);}async tick(){if(this.settled||this.busy)return;this.busy=true,this.again=false;let e=null,t=null;try{e=this.cancelRequested?await this.options.cancel(this.snapshot.id):await this.options.heartbeat(this.snapshot.id);}catch(r){t=r;}if(this.busy=false,!this.settled){if(e===null){this.missed(t);return}this.misses=0,await this.apply(e);}}missed(e){if(e instanceof j&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<Rs){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let t=e instanceof j&&e.code==="matchmaking_unavailable";this.settle({status:t?"unavailable":"lost"});}async apply(e){if(this.snapshot=e,e.status==="queued"){this.next();return}if(e.status==="matched"){await this.seat(e);return}e.status==="expired"?this.settle({status:"expired",reason:e.reason??"timed_out"}):e.status==="cancelled"?this.settle({status:"cancelled",reason:e.reason??"requested"}):this.settle({status:"failed",reason:e.reason??e.status});}next(){if(this.again){this.again=false,this.tick();return}let e=this.soon;this.soon=false,this.schedule(e);}async seat(e){if(e.roomId===void 0){this.fail(new Error("[gem] a matched matchmaking ticket named no game room"));return}this.busy=true;try{let t=await this.options.seat(e.roomId);this.busy=!1,this.settle({status:"matched",room:t});}catch(t){this.busy=false,this.fail(t);}}settle(e){this.settled||(this.finish(e.status),this.resolve(e));}fail(e){this.settled||(this.finish("matched"),this.reject(e));}finish(e){this.settled=true,this.status=e,this.clearTimer(),this.options.onSettled();}};function oe(n){return typeof n=="string"&&n!==""?n:void 0}var Ss=new Set(["localhost","127.0.0.1","[::1]"]);function qt(n){let e=oe(n);if(e===void 0)return;let t;try{t=new URL(e);}catch{return}if(!(t.username!==""||t.password!=="")&&(t.protocol==="https:"||t.protocol==="http:"&&Ss.has(t.hostname)))return e}function xs(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=t??{},i=oe(r.item_id),o=qt(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function ui(n){let e=n??{},t=oe(e.player_id),r=oe(e.display_name),i=oe(e.discriminator),o=oe(e.display_tag),a=oe(e.avatar_icon_id),s=qt(e.avatar_icon_url),l=oe(e.avatar_3d_id),d=qt(e.avatar_3d_model_url),m=qt(e.avatar_3d_icon_url);return {...t===void 0?{}:{playerId:t},...r===void 0?{}:{displayName:ce(r)},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:ce(o)},...a===void 0?{}:{avatarIconId:a},...s===void 0?{}:{avatarIconUrl:s},...l===void 0?{}:{avatar3dId:l},...d===void 0?{}:{avatar3dModelUrl:d},...m===void 0?{}:{avatar3dIconUrl:m},badges:xs(e.badges)}}function $t(n){if(typeof n!="object"||n===null)return;let e={};for(let[t,r]of Object.entries(n)){let i=qn(r);i!==void 0&&(e[t]=i);}return e}function Ft(n){if(Array.isArray(n))return n.map(As).filter(e=>!!e)}function qn(n){if($n(n)||Array.isArray(n)&&n.every($n))return n}function $n(n){return typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)}function As(n){let e=n??{};if(typeof e.name!="string"||e.name.length===0)return null;let t=qn(e.fixed),r=qn(e.default);return {name:e.name,type:typeof e.type=="string"?e.type:"string",list:e.list===true,required:e.required===true,mutable:e.mutable!==false,...t===void 0?{}:{fixed:t},...r===void 0?{}:{default:r},...Ie("description",Ps(e.description)),...Array.isArray(e.allowed)&&e.allowed.every($n)?{allowed:e.allowed}:{},...Ie("min",Ye(e.min)),...Ie("max",Ye(e.max)),...Ie("minItems",Ye(e.min_items)),...Ie("maxItems",Ye(e.max_items)),...Ie("maxLength",Ye(e.max_length))}}function Ps(n){return typeof n=="string"&&n.length>0?n:void 0}function Ye(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Ie(n,e){return e===void 0?{}:{[n]:e}}function z(n){let e=n??{},t=E(e.id)??E(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(Fn):[];return {id:t,gameId:E(e.game_id)??"",name:E(e.name)??"",status:E(e.status)??"open",hostPlayerId:E(e.host_player_id)??"",maxPlayers:X(e.max_players)??0,memberCount:X(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...H("joinCode",E(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...H("roomArgs",$t(e.room_args)),...H("roomArgsTemplate",Ft(e.room_args_template)),gameChannel:E(e.game_channel)??"release",...H("region",E(e.region)),...H("clusterTargetId",E(e.cluster_target_id)),selfHosted:e.self_hosted===true,...H("matchId",E(e.match_id)),version:X(e.version)??0,...H("templateId",E(e.template_id)),...H("templateSlug",E(e.template_slug)),roomType:E(e.game_room_type)??"Standard",...H("transports",Ne(e.transports)??void 0),createdAt:X(e.created_at)??0,updatedAt:X(e.updated_at)??0,...H("startedAt",X(e.started_at))}}function Fn(n){let e=n??{};return {...ui(e),playerId:E(e.player_id)??"",isReady:e.is_ready===true,role:E(e.role)??"member",joinedAt:X(e.joined_at)??0,...H("groupId",E(e.group_id)),...H("platform",E(e.platform))}}function Xe(n){let e=n??{};return {id:E(e.id)??E(e.game_room_id)??"",gameId:E(e.game_id)??"",name:E(e.name)??"",status:E(e.status)??"open",hostPlayerId:E(e.host_player_id)??"",maxPlayers:X(e.max_players)??0,memberCount:X(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:E(e.game_channel)??"release",roomType:E(e.game_room_type)??"Standard",createdAt:X(e.created_at)??0}}function E(n){return typeof n=="string"&&n.length>0?n:void 0}function X(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function H(n,e){return e===void 0?{}:{[n]:e}}var Ce=class{constructor(e){this.options=e;}options;list(e){let t=new URLSearchParams;e.status&&t.set("status",e.status),e.templateSlug&&t.set("template_slug",e.templateSlug),e.limit!==void 0&&t.set("limit",String(e.limit)),e.cursor&&t.set("cursor",e.cursor);let r=t.size>0?`?${t.toString()}`:"";return this.options.client.get(`${this.baseV1()}${r}`,e.signal).then(i=>({rooms:(i.game_rooms??[]).map(Xe),...typeof i.next_cursor=="string"?{nextCursor:i.next_cursor}:{}}))}myRooms(e){return this.options.client.get(`/v1/games/${encodeURIComponent(this.options.gameId())}/players/me/game-rooms`,e).then(t=>({rooms:(t.game_rooms??[]).map(Xe)}))}create(e,t,r){return Ts(e.maxPlayers),this.options.client.post(this.baseV2(),{name:e.name,...e.isPublic===void 0?{}:{is_public:e.isPublic},...e.settings===void 0?{}:{settings:e.settings},...e.region===void 0?{}:{region:e.region},...r===void 0?{}:{cluster_target_id:r},...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.partyId===void 0?{}:{party_id:e.partyId},...this.asksSelfHosted(e.partyId)?{self_hosted:true}:{},...e.roomArgs===void 0?{}:{room_args:e.roomArgs},...Qe(t)},e.signal).then(z)}get(e,t){return this.options.client.get(this.roomV2(e),t).then(z)}join(e,t,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...t.partyId===void 0?{}:{party_id:t.partyId},...Qe(r)},t.signal).then(z)}joinByCode(e,t,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...t.partyId===void 0?{}:{party_id:t.partyId},...Qe(r)},t.signal).then(z)}quickJoin(e,t,r=[]){let i=this.asksSelfHosted(e.partyId);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},...Es(e.templateSlugs,i),...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},...i?{self_hosted:true}:{},...Qe(t)},e.signal).then(z)}createTicket(e,t,r=[]){return ai(this.generated(),{templates:e.templateSlugs.map(i=>({template_slug:i})),...r.length===0?{}:{cluster_target_ids:[...r]},...e.partyId===void 0?{}:{party_id:e.partyId},...Qe(t)},{...e.signal===void 0?{}:{signal:e.signal}}).then(ze)}heartbeatTicket(e){return li(this.generated(),e).then(ze)}cancelTicket(e,t=false){return t?this.options.client.delete(`/v1/games/${encodeURIComponent(this.options.gameId())}/matchmaking/tickets/${encodeURIComponent(e)}`,void 0,{keepalive:true}).then(ze):si(this.generated(),e).then(ze)}leave(e,t,r,i=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:t},r,{keepalive:i}).then(()=>{})}asksSelfHosted(e){return e===void 0&&this.options.selfHosted?.()===true}close(e,t){return this.options.client.delete(this.roomV1(e),t).then(()=>{})}update(e,t){return this.options.client.patch(this.roomV2(e),{...t.name===void 0?{}:{name:t.name},...t.maxPlayers===void 0?{}:{max_players:t.maxPlayers},...t.isPublic===void 0?{}:{is_public:t.isPublic},...t.settings===void 0?{}:{settings:t.settings},...t.roomArgs===void 0?{}:{room_args:t.roomArgs}},t.signal).then(z)}setReady(e,t,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:t},r).then(z)}kick(e,t,r){return this.options.client.post(`${this.roomV1(e)}/kick/${encodeURIComponent(t)}`,{},r).then(()=>this.get(e,r))}transferHost(e,t,r){return this.options.client.post(`${this.roomV2(e)}/transfer/${encodeURIComponent(t)}`,{},r).then(z)}leaveMatch(e,t){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:t}).then(()=>{})}generated(){return {client:this.options.client,gameId:this.options.gameId}}baseV2(){return `/v2/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function Es(n,e){return n===void 0?{}:{templates:(e?n.slice(0,1):n).map(r=>({template_slug:r}))}}function Qe(n){return {platform:n.platform,game_version:n.gameVersion,engine_version:n.engineVersion}}function Ts(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 Is(n,e){return Math.min(e,500*2**Math.max(0,n-1))}var Cs=1e3,Ms=3e3,Os=6e4,Ls=2,mi=new Set(["game_room_closed","game_room_gone"]),Gs=12e4,Ds=5e3,qs=new Set(["invalid_cluster_target","capacity_unavailable"]),$s=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function yi(n){return new jn(n)}var jn=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new Ce({client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new Me;api;room=null;ticketWatch=null;queueing=false;queuedFromRoomId=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create"),this.assertNotQueued("create");let t=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("create",async()=>{let o=await t;return this.api.create(r,this.version("create"),o[0]).catch(async a=>{let s=await this.afterRefusedClusters(a,o);if(s[0]===void 0||s[0]===o[0])throw a;return this.api.create(r,this.version("create"),s[0])})});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,t={}){this.assertNotInRoom("join"),this.assertNotQueued("join");let r=await this.attachParty(t),i=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async joinByCode(e,t={}){this.assertNotInRoom("joinByCode"),this.assertNotQueued("joinByCode");let r=await this.attachParty(t),i=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async quickJoin(e){this.assertNotInRoom("quickJoin"),this.assertNotQueued("quickJoin"),Ns(e);let t=this.clusterTargets(),r=await this.attachParty(e),i=a=>this.api.quickJoin(r,this.version("quickJoin"),a).catch(s=>this.retryPastStaleMembership(s,r,a)),o=await this.run("quickJoin",async()=>{let a=await t;return i(a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||fi(l,a))throw s;return i(l)})});return this.enter(o,"joined"),this.askForLocalServer(o),o}async queueForMatch(e){this.assertNotQueued("queueForMatch"),js(e?.templateSlugs),this.queueing=true;try{let t=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("queueForMatch",async()=>{let a=await t;return this.api.createTicket(r,this.version("queueForMatch"),a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||fi(l,a))throw s;return this.api.createTicket(r,this.version("queueForMatch"),l)})}),o=new Dt({clock:this.options.clock,first:i,heartbeat:a=>this.track(this.api.heartbeatTicket(a)),cancel:(a,s)=>this.track(this.api.cancelTicket(a,s)),seat:a=>this.enterMatchedRoom(a),onSettled:()=>{this.ticketWatch===o&&(this.ticketWatch=null),this.retuneSeatWatch();}});return this.ticketWatch=o,this.retuneSeatWatch(),o.start(),o.ticket}finally{this.queueing=false;}}async enterMatchedRoom(e){let t=await this.run("queueForMatch",()=>this.api.get(e));return this.disposed?t:(this.room!==null&&this.room.id!==t.id&&(this.queuedFromRoomId=this.room.id,this.exit()),this.room===null&&this.enter(t,"joined"),this.room?.id===t.id?this.room:t)}async list(e={}){let t=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",t),t}async myRooms(e){let t=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",t.rooms),t.rooms}async leave(e={}){let t=this.requireRoom("leave"),r=e.keepalive===true,i=()=>this.run("leave",()=>this.api.leave(t.id,e.asGroup!==false,e.signal,r));if(r){let o=i();this.track(this.notifyLeavingMatch({keepalive:true})),await o;}else await this.notifyLeavingMatch(),await i();this.exit(),this.emitter.emit("left");}async leaveAll(e){let t=await this.myRooms(e),r=[];for(let i of t)try{await this.run("leaveAll",()=>this.api.leave(i.id,!0,e)),r.push(i.id),this.room?.id===i.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let t=this.requireRoom("close");await this.run("close",()=>this.api.close(t.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let t=this.room;if(!t)return null;let r;try{r=await this.track(this.api.get(t.id,e));}catch(i){if(i instanceof j&&i.reason==="not_found"){let o=this.heldMatchId;if(o!==null){let a=await this.askWhyEnded(o,e);this.endMatch(o,a??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",i),i}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let t=this.room,r=this.heldMatchId;if(!(t===null||r===null)&&!(t.status==="in_game"&&t.matchId===r)&&!(t.matchId!==void 0&&t.matchId!==r)&&this.settling!==r){this.settling=r;try{let i=await this.askWhyEnded(r,e);i!==null&&this.endMatch(r,i,t.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,t){let r=this.room;if(r===null)return null;let i=this.takeHint(e),o;try{o=await this.track(this.onceGameIdKnown(()=>tn({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e),...t===void 0?{}:{signal:t}})));}catch(a){return a instanceof j&&a.reason==="not_found"?i??null:(this.reportError("reconcile",a),null)}return o===null?null:o.status==="ready"?(this.seenMatches.add(e),null):o.status==="failed"?(this.settleFailed(o.matchId,o.reason),null):o.reason==="unknown"&&i!==null?i:o.reason}takeHint(e){let t=this.pendingHint;if(t===null||t.matchId!==void 0&&t.matchId!==e||(this.pendingHint=null,t.reason===void 0))return null;let r=Re(t.reason);return r==="unknown"?null:r}async reconcile(e){if(this.disposed)return;if(e!==void 0&&(e.matchId!==void 0||e.reason!==void 0)&&(this.pendingHint=e),this.reconciling!==null)return this.reconcileAgain=true,this.reconciling;let t=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=t,this.track(t)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,t){let r=this.requireRoom("setReady"),i=await this.run("setReady",()=>this.api.setReady(r.id,e,t));return this.apply(i),i}async kick(e,t){let r=this.requireRoom("kick"),i=await this.run("kick",()=>this.api.kick(r.id,e,t));return this.apply(i),i}async transferHost(e,t){let r=this.requireRoom("transferHost"),i=await this.run("transferHost",()=>this.api.transferHost(r.id,e,t));return this.apply(i),i}async update(e){let t=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(t.id,e));return this.apply(r),r}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,t){let r=this.requireRoom("startMatch");if(!this.isHost)throw new 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=B(t.clusterTargetId),o=i??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),a=o??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let s=(m,c)=>gt({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...i===void 0?{nextClusterTarget:()=>this.nextCluster(c)}:{},retry:{...t.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),t.retry?.onWaiting?.(p);}},...t.signal===void 0?{}:{signal:t.signal}}),l=()=>s(o,[a]).catch(async m=>{if(i!==void 0||!hi(m))throw m;let c=await this.nextCluster([a],true);if(c===void 0)throw m;return s(c,[a,c])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new 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 ht({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e,matchId:t,version:this.version("pollMatchStatus"),knownToExist:this.seenMatches.has(t),...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.pollIntervalMs===void 0?{}:{pollIntervalMs:r.pollIntervalMs},...r.signal===void 0?{}:{signal:r.signal}})}settleOutcome(e){if(e.status==="failed")throw this.settleFailed(e.matchId,e.reason),new u("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!mi.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(!jt()){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<Cs){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(Is(e.attempt,t.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!jt()){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(()=>tn({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,!mi.has(i.reason)),this.track(this.reconcile().catch(()=>{}));return}if(i?.status==="failed"){this.abandonReconnect(e.matchId,i.reason),this.settleFailed(i.matchId,i.reason);return}if(i?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(i);let o;try{o=await t.redial(e.matchId,e.deadlineAt);}catch(a){this.reportError("reconcile",a),o="failed";}if(e.done||this.reconnect!==e)return;if(o==="closed"){this.finishReconnect();return}if(o==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let t=this.session.phase==="suspended";this.session={phase:"connected",matchId:e};let r=this.reconnect;r!==null&&r.matchId===e?(this.finishReconnect(),this.emitter.emit("matchReconnected",{matchId:e,attempt:r.attempt})):t&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new 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 currentTicket(){return this.ticketWatch?.ticket??null}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}on(e,t){let r=this.emitter.on(e,t);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,t){this.emitter.off(e,t);}once(e,t){return this.emitter.once(e,t)}handleRoomEvent(e){if(this.ticketWatch!==null&&e.event!=="version_stale"&&e.roomId!==this.room?.id&&this.ticketWatch.poke(),this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let t=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(t).catch(()=>{}));}handleAutoStartFailed(e,t){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(t);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:t,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let i=new AbortController;this.autoStartRetry=i,this.track(this.requestStart({signal:i.signal},false).then(()=>{},o=>{i.signal.aborted||this.reportError("startMatch",o);}).finally(()=>{this.autoStartRetry===i&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!qs.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.watchingSeats&&this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}}async reconcileSeats(){if(this.disposed||!this.watchingSeats||this.ticketWatch!==null)return;let e;try{e=await this.myRooms();}catch{return}let t=new Set;for(let r of e)r.status!=="closed"&&(t.add(r.id),r.id!==this.room?.id&&(this.reported.has(r.id)||await this.reportSeat(r.id).catch(()=>{})));for(let r of [...this.reported])t.has(r)||this.reported.delete(r);}async reportSeat(e){let t=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||t===null||!r.members.some(i=>i.playerId===t)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.ticketWatch===null&&this.seatPollMs>0&&jt())){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(),!!jt())){if(this.room!==null){let r=this.reconnect?.parked??null;r!==null&&this.reconnect!==null?(this.reconnect.parked=null,this.track(r())):this.track(this.reconcile().catch(()=>{}));return}if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of pi)e.addEventListener(r,this.visibilityListener);let t=globalThis.document;typeof t?.addEventListener=="function"&&t.addEventListener("resume",this.visibilityListener);}startPolling(e){this.stopPolling(),!this.disposed&&(this.pinnedIntervalMs=e??null,this.polling=true,this.schedule());}stopPolling(){this.pollHandle!==null&&(this.options.clock.clearTimeout(this.pollHandle),this.pollHandle=null),this.polling=false,this.pollIntervalMs=null;}async settled(){for(let e=0;e<20&&this.inFlight.length>0;e++){let t=this.inFlight;this.inFlight=[],await Promise.allSettled(t);}}dispose(){if(this.disposed=true,this.ticketWatch?.abandon(),this.abortAutoStartRetry(),this.finishReconnect(),this.stopPolling(),this.emitter.clear(),this.unloadListener&&(globalThis.removeEventListener?.("pagehide",this.unloadListener),this.unloadListener=null),this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null),this.visibilityListener){let e=globalThis;for(let r of pi)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??Ds}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=oi(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 Dr({...t,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return be(await this.options.resolveClusterTargets());let e=B(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,t){return !hi(e)||t.length===0?[]:be(await this.options.refreshClusterTargets?.(t)??[])}async nextCluster(e,t=false){let r=a=>a.find(s=>!e.includes(s)),i=await this.clusterTargets(),o=r(i);return o!==void 0||!t?o:r(be(await this.options.refreshClusterTargets?.(i)??[]))}async attachParty(e){if(e.partyId!==void 0)return e;let t=this.options.resolveParty;if(t===void 0)return e;let r=await t();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,t,r){if(!(e instanceof j)||e.reason!=="conflict"||!$s.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new j(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and \`recoverStaleMembership\` is off, so nothing cleared it. A membership that outlived its page is visible only through myRooms(); leaveAll() is what clears it.`,e.retryAfterSeconds,e.code);let i;try{i=await this.leaveAll(t.signal);}catch{throw new j(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery could not list the rooms it would have cleared, so nothing was tried and the refusal stands. That is the listing failing, not a room refusing to be left: retry once the connection is back. myRooms() shows what is held.`,e.retryAfterSeconds,e.code)}if(i.length===0)throw new j(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery cleared nothing, so the refusal stands. myRooms() shows what is held. A room this player was seated in as a party member cannot be cleared from here at all \u2014 only the leader of a party may take it out of a room \u2014 so a member joins by adopting that room, myRooms() then join(), rather than quick-joining.`,e.retryAfterSeconds,e.code);return this.api.quickJoin(t,this.version("quickJoin"),r)}assertNotInRoom(e){if(this.room!==null)throw new 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.`)}assertNotQueued(e){if(!(this.ticketWatch===null&&!this.queueing))throw new u("misconfigured",`${e} refused: this player is waiting on a matchmaking ticket, which will seat them in a room of its own. Cancel it first \u2014 currentTicket.cancel() \u2014 or wait for its outcome.`)}requireRoom(e){if(this.room===null)throw new 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 j?{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.queuedFromRoomId===e.id&&(this.queuedFromRoomId=null),this.abortFollow(),this.autoStartRetried=false,this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(t,e),this.adoptMatch(e),this.options.poll!==false&&this.startPolling(),this.retuneSeatWatch();}exit(){this.room=null,this.abortFollow(),this.abortAutoStartRetry(),this.autoStartRetried=false,this.finishReconnect(),this.session.phase!=="ended"&&(this.session={phase:"none"}),this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.stopPolling(),this.retuneSeatWatch();}apply(e){let t=this.room;if(t===null||t.id!==e.id)return;let r=new Map(t.members.map(s=>[s.playerId,s])),i=new Map(e.members.map(s=>[s.playerId,s])),o=this.playerId();for(let s of i.keys())r.has(s)||this.emitter.emit("memberJoined",s);for(let s of r.keys())if(!i.has(s)){if(s===o){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",s);}for(let[s,l]of i){let d=r.get(s);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",s,l.isReady);}t.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let a=Fs(t,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),a&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let t=this.heldMatchId;t!==null&&t!==e&&this.endMatch(t,"replaced",true),this.session={phase:"starting",matchId:e},this.autoStartRetried=false,this.emitter.clearRetained(),this.emitter.emit("matchAllocationStarted",e),this.followMatch();}followMatch(){if(this.autoFollow===false)return;let e=this.room,t=this.heldMatchId;if(e===null||t===null||this.followAbort!==null&&this.followingMatchId===t)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=t,this.track(this.onceGameIdKnown(()=>this.chase(e.id,t,{signal:r.signal})).then(i=>{if(!r.signal.aborted)try{this.settleOutcome(i);}catch{}}).catch(i=>{r.signal.aborted||this.reportError("pollMatchStatus",i);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let t=this.heldMatchId;if(t!==null)return Promise.resolve(t);let r=e.timeoutMs??Gs;return new Promise((i,o)=>{let a=c=>{s(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),c();},s=this.emitter.on("matchAllocationStarted",c=>a(()=>i(c))),l=this.emitter.on("matchFailed",(c,p)=>a(()=>o(new u("allocation_failed",`match ${c} did not come up: ${p}`)))),d=()=>a(()=>o(new u("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>a(()=>o(new u("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?d():e.signal?.addEventListener("abort",d);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??Ms}pushedInterval(){return this.options.pushedPollIntervalMs??Os}pushed(){return this.options.clock.now()-this.lastPushAt<Ls*this.pushedInterval()}retune(){!this.polling||this.pinnedIntervalMs!==null||this.baseInterval()!==this.pollIntervalMs&&this.startPolling();}schedule(){this.disposed||!this.polling||this.room===null||(this.pollIntervalMs=this.pinnedIntervalMs??this.baseInterval(),this.pollHandle=this.options.clock.setTimeout(()=>{this.pollHandle=null,this.track(this.reconcile().catch(()=>null).then(()=>{this.schedule();}));},this.pollIntervalMs));}installUnloadNotifier(){if(this.options.notifyOnUnload===false)return;let e=globalThis;typeof e.addEventListener=="function"&&(this.unloadListener=t=>{if(this.ticketWatch?.abandon(true),t?.persisted!==true&&(this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{})),this.queuedFromRoomId!==null)){let r=this.queuedFromRoomId;this.queuedFromRoomId=null,this.track(this.api.leave(r,true,void 0,true).catch(()=>{}));}},e.addEventListener("pagehide",this.unloadListener));}};function jt(){let n=globalThis.document;return n?.visibilityState===void 0||n.visibilityState==="visible"}var pi=["visibilitychange","focus","pageshow","online"];function Fs(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||gi(n)!==gi(e)}function gi(n){return n.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function hi(n){return n instanceof j&&n.code==="invalid_cluster_target"}var Nt=8;function js(n){if(!(Array.isArray(n)&&n.length>=1&&n.length<=Nt&&n.every(t=>typeof t=="string"&&t.length>0)))throw new u("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${Nt} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function Ns(n){let e=n?.templateSlugs;if(e===void 0)return;if(!(Array.isArray(e)&&e.length>=1&&e.length<=Nt&&e.every(r=>typeof r=="string"&&r.length>0)))throw new u("misconfigured",`quickJoin's templateSlugs is an array naming one to ${Nt} room templates by slug \u2014 quickJoin({ templateSlugs: ['duel', 'brawl'] }). A room that has to be created is made from the first.`);if(n?.templateSlug!==void 0||n?.templateId!==void 0)throw new u("misconfigured","quickJoin takes templateSlugs or a single templateSlug / templateId, not both. Put every template this player accepts in templateSlugs, with the one to create from first.")}function fi(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}function bi(n){let e=0,t=new Map;return {resolve(){if(!n.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(i=>{let o={},a=l=>{t.delete(r)&&(n.clock.clearTimeout(o.timer),i(l));};t.set(r,a),o.timer=n.clock.setTimeout(()=>a(void 0),n.timeoutMs??2e3);let s=false;try{s=n.bridge.requestParty(r);}catch{}s||a(void 0);})},settle(r,i){t.get(r)?.(i);}}}
|
|
2
|
-
export{
|
|
1
|
+
globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:12.0.0]";var h="gem-web-bridge",Z={min:1,max:1},fe=65536,Bn=8,tt=5e3,Vn=1024,Bt=1e4;function Hn(n){return Object.freeze(Object.assign(Object.create(null),n))}var nt=Hn({"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.ticketEvent":60,"gem.signalEvent":1800,"gem.dedicatedEvent":120,"gem.partyResult":30,"gem.clusterTarget":12,"gem.devtools":30,"gem.screenshot":6,"gem.screenshot.denied":12,"gem.requestContext":12,"gem.gameContext":12,"gem.signal":1200,"gem.dedicatedOffer":60,"gem.partyRequest":12,"gem.ready":5,"gem.engaged":5,"gem.progress":600,"gem.requestToken":12,"gem.requestLocalServer":6,"gem.localServer":30,"gem.localServer.denied":30,"gem.exit":5,"gem.openExternal":6,"gem.requestFullscreen":30,"gem.audioState":120,"gem.rewardCue":60,"gem.walletDisplay":60,"gem.controlsDeclare":60,"gem.menu":60,"gem.menuSelect":60,"gem.requestShare":6,"gem.requestAvatarPicker":6,"gem.vibrate":600,"gem.frameStats":120,"gem.portraitBorders":60,"gem.error":60,"gem.requestPurchase":12,"gem.purchaseResult":30,"gem.deviceSettings.put":30,"gem.deviceSettings.result":30,"gem.requestAd":6,"gem.adResult":12,"gem.requestSignIn":6,"gem.signInResult":12,"gem.requestFriendChallenge":12,"gem.friendChallengeResult":30,__malformed:60}),ye="__malformed",Ks=["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.ticketEvent","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"],Js=["gem.handshake.accept","gem.screenshot.denied","gem.gameContext","gem.signal","gem.dedicatedOffer","gem.partyRequest","gem.ready","gem.engaged","gem.progress","gem.requestToken","gem.requestLocalServer","gem.exit","gem.openExternal","gem.requestFullscreen","gem.audioState","gem.rewardCue","gem.walletDisplay","gem.controlsDeclare","gem.menu","gem.requestShare","gem.requestAvatarPicker","gem.vibrate","gem.frameStats","gem.portraitBorders","gem.error","gem.requestPurchase","gem.deviceSettings.put","gem.requestAd","gem.requestSignIn","gem.requestFriendChallenge"],Si=Hn({"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.ticketEvent":"ticketEvents","gem.seatedEvent":"partySeating","gem.socketState":"socketState","gem.audioState":"audioState","gem.rewardCue":"rewardCue","gem.frameStats":"frameStats","gem.portraitBorders":"portraitBorders","gem.engaged":"engagement","gem.viewport":"viewport","gem.walletDisplay":"walletDisplay","gem.requestLocalServer":"localHost","gem.localServer":"localHost","gem.localServer.denied":"localHost","gem.cohorts":"cohorts","gem.earnAllowanceChanged":"earnAllowance","gem.deviceSettings":"deviceSettings","gem.deviceSettings.put":"deviceSettings","gem.deviceSettings.result":"deviceSettings","gem.requestShare":"share","gem.requestAvatarPicker":"avatarPicker","gem.vibrate":"vibration","gem.menu":"gameMenu","gem.menuSelect":"gameMenu","gem.controlsDeclare":"controls"}),xi=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"]]);function rt(n){let e=Si[n];if(e!==void 0)return e;for(let[t,r]of xi)if(n.startsWith(t))return r}function it(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 Ai(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 Pi(n){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(n)}function Ei(n){return /^[a-z_]+$/.test(n)}function Wt(n,e,t){if(e>Bn)return `nesting deeper than ${Bn}`;if(++t.nodes>tt)return `more than ${tt} 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>Vn)return `an array of ${n.length} entries, over the ${Vn} limit`;t.bytes+=2;for(let s of n){let l=Wt(s,e+1,t);if(l)return l}return null}let o=Object.getPrototypeOf(n);if(o!==Object.prototype&&o!==null)return "a value that is not a plain object";t.bytes+=2;let a=n;for(let s in a){if(!Object.prototype.hasOwnProperty.call(a,s))continue;if(++t.nodes>tt)return `more than ${tt} values`;if(t.bytes+=s.length*3+4,t.bytes>fe)return `over the ${fe} byte limit`;let l=Wt(a[s],e+1,t);if(l)return l}return null}function Ti(n){let e={nodes:0,bytes:0,seen:new Set},t=Wt(n,0,e);return t?`message contains ${t}`:e.bytes>fe?`message is over the ${fe} byte limit`:null}var Ii={origin:[it,"not a well-formed origin"],url:[Ai,"not a safe absolute http(s) URL"],bcp47:[Pi,"not a well-formed BCP 47 tag"],code:[Ei,"not a code of lower-case letters and underscores"]};function Kn(n,e,t){for(let r of e){let i=t===""?r.n:`${t}.${r.n}`,o=n[r.n];if(o==null){if(r.o)continue;return `${i}: required`}let a=Jn(o,r,i);if(a)return a}return null}function Jn(n,e,t){switch(e.k){case "s":{if(typeof n!="string")return `${t}: expected string`;if(n.length>e.max)return `${t}: exceeds ${e.max} characters`;if(e.f){let[r,i]=Ii[e.f];if(!r(n))return `${t}: ${i}`}return null}case "i":return typeof n!="number"||!Number.isInteger(n)?`${t}: expected integer`:n<e.lo||n>e.hi?`${t}: out of range ${e.lo}..${e.hi}`:null;case "b":return typeof n=="boolean"?null:`${t}: expected boolean`;case "e":{let r=e.v;return r.includes(n)?null:`${t}: not one of ${r.join("|")}`}case "o":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected object`:Kn(n,e.fs,t);case "j":return typeof n!="object"||n===null||Array.isArray(n)?`${t}: expected a plain object`:null;case "a":{if(!Array.isArray(n))return `${t}: expected array`;if(n.length>e.max)return `${t}: exceeds ${e.max} items`;let r=e.it,i=`${t}[]`;for(let o of n){if(o==null){if(r.o)continue;return `${i}: required`}let a=Jn(o,r,i);if(a)return a}return null}default:{let r=e.k;return `${t}: unknown kind ${String(r)}`}}}var zn=Object.create(null);function y(n,e){return zn[n]=t=>{let r=Ti(t);if(r)return r;if(typeof t!="object"||t===null||Array.isArray(t))return "message: expected object";let i=t;return i.gem!==h?"gem: wrong protocol marker":i.type!==n?`type: expected ${n}`:Kn(i,e,"")}}var zs=y("gem.handshake",[{n:"versions",k:"o",fs:[{n:"min",k:"i",lo:1,hi:1e3},{n:"max",k:"i",lo:1,hi:1e3}]},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}},{n:"embedder",k:"s",max:2048,f:"origin"},{n:"unbidden",k:"b",o:1}]),Ys=y("gem.handshake.accept",[{n:"v",k:"i",lo:1,hi:1e3},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}}]),Xs=y("gem.token",[{n:"token",k:"s",max:4096},{n:"requestId",k:"s",o:1,max:64},{n:"generation",k:"i",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"s",o:1,max:512,f:"url"},{n:"playerId",k:"s",max:64},{n:"gameId",k:"s",max:64},{n:"channel",k:"e",v:["dev","test","release"]},{n:"gameVersion",k:"s",o:1,max:64},{n:"expiresAt",k:"i",lo:0,hi:4102444800},{n:"chainEndsAt",k:"i",lo:0,hi:4102444800},{n:"allowDevTools",k:"b",o:1}]),Qs=y("gem.token.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:36e5},{n:"reason",k:"e",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"s",max:64}]),Zs=y("gem.player",[{n:"untrusted",k:"o",fs:[{n:"displayName",k:"s",max:64},{n:"displayTag",k:"s",o:1,max:80},{n:"displayHandle",k:"s",max:80}]},{n:"playerId",k:"s",o:1,max:64},{n:"discriminator",k:"s",o:1,max:8},{n:"avatarIconUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatarIconId",k:"s",o:1,max:64},{n:"avatar3dId",k:"s",o:1,max:64},{n:"avatar3dModelUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatar3dIconUrl",k:"s",o:1,max:2048,f:"url"},{n:"badges",k:"a",o:1,max:2,it:{n:"",k:"o",fs:[{n:"itemId",k:"s",max:64},{n:"iconUrl",k:"s",max:2048,f:"url"}]}},{n:"displayTag",k:"s",max:8},{n:"avatarUrl",k:"s",o:1,max:2048,f:"url"},{n:"boost",k:"o",o:1,fs:[{n:"multipliers",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"currencyId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"multiplierBp",k:"i",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"i",o:1,lo:1,hi:7}]}]),ea=y("gem.pause",[{n:"paused",k:"b"}]),ta=y("gem.prefs",[{n:"reducedMotion",k:"b"},{n:"muted",k:"b"},{n:"showFrameStats",k:"b",o:1},{n:"locale",k:"s",max:35,f:"bcp47"},{n:"recommended",k:"o",o:1,fs:[{n:"volume",k:"i",lo:0,hi:100},{n:"batterySaver",k:"b"},{n:"keyboardLayout",k:"e",v:["wasd","arrows"]},{n:"gamepadConfirm",k:"e",v:["south","east"]},{n:"vibration",k:"b"},{n:"lookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"gamepadLookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"invertLookY",k:"b",o:1},{n:"touchMovement",k:"s",o:1,max:16,f:"code"},{n:"graphicsQuality",k:"s",o:1,max:16,f:"code"},{n:"graphicsQualityAuto",k:"b",o:1}]}]),na=y("gem.cohorts",[{n:"cohorts",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"experimentId",k:"s",max:36},{n:"variantKey",k:"s",max:32}]}}]),ra=y("gem.earnAllowanceChanged",[]),ia=y("gem.viewport",[{n:"insets",k:"o",fs:[{n:"top",k:"i",lo:0,hi:4096},{n:"right",k:"i",lo:0,hi:4096},{n:"bottom",k:"i",lo:0,hi:4096},{n:"left",k:"i",lo:0,hi:4096}]},{n:"reserved",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384},{n:"width",k:"i",lo:0,hi:16384},{n:"height",k:"i",lo:0,hi:16384}]}}]),oa=y("gem.deviceSettings",[{n:"settings",k:"j",o:1}]),sa=y("gem.willTerminate",[{n:"reason",k:"e",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"i",lo:0,hi:6e4}]),aa=y("gem.roomEvent",[{n:"event",k:"e",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"s",max:64},{n:"matchId",k:"s",o:1,max:64},{n:"version",k:"i",o:1,lo:0,hi:2147483647},{n:"reason",k:"s",o:1,max:64},{n:"platform",k:"e",o:1,v:["universal","mobile"]}]),la=y("gem.socketState",[{n:"connected",k:"b"},{n:"reason",k:"e",o:1,v:["connecting","dropped","watchdog","terminal"]}]),da=y("gem.seatedEvent",[{n:"roomId",k:"s",max:64}]),ca=y("gem.autoStartFailedEvent",[{n:"roomId",k:"s",max:64},{n:"code",k:"s",max:64}]),ua=y("gem.ticketEvent",[{n:"event",k:"e",v:["queued","matched","expired","cancelled","failed"]},{n:"ticketId",k:"s",max:64},{n:"partySize",k:"i",o:1,lo:1,hi:64},{n:"queuedAt",k:"i",o:1,lo:0,hi:4102444800},{n:"expiresAt",k:"i",o:1,lo:0,hi:4102444800},{n:"reason",k:"s",o:1,max:64},{n:"roomId",k:"s",o:1,max:64}]),ma=y("gem.signalEvent",[{n:"event",k:"e",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}]),pa=y("gem.dedicatedEvent",[{n:"event",k:"e",v:["answer","error","matchEnded"]},{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",o:1,max:10240},{n:"sessionId",k:"s",o:1,max:64},{n:"code",k:"s",o:1,max:64},{n:"message",k:"s",o:1,max:256},{n:"reason",k:"s",o:1,max:64}]),ga=y("gem.partyResult",[{n:"requestId",k:"s",max:64},{n:"partyId",k:"s",o:1,max:64}]),ha=y("gem.clusterTarget",[{n:"clusterTargetId",k:"s",max:64},{n:"clusterTargetIds",k:"a",o:1,max:3,it:{n:"",k:"s",max:64}}]),fa=y("gem.devtools",[{n:"action",k:"e",v:["open","close","toggle"]}]),ya=y("gem.screenshot",[{n:"maxWidth",k:"i",lo:1,hi:7680},{n:"maxHeight",k:"i",lo:1,hi:4320}]),ba=y("gem.screenshot.denied",[{n:"reason",k:"e",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"b"}]),va=y("gem.requestContext",[]),_a=y("gem.gameContext",[{n:"context",k:"j"}]),ka=y("gem.signal",[{n:"signal",k:"e",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}]),wa=y("gem.dedicatedOffer",[{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",max:10240},{n:"intent",k:"e",v:["initial","ice_restart","full_reconnect"]}]),Ra=y("gem.partyRequest",[{n:"requestId",k:"s",max:64}]),Sa=y("gem.ready",[]),xa=y("gem.engaged",[]),Aa=y("gem.progress",[{n:"loaded",k:"i",lo:0,hi:1099511627776},{n:"total",k:"i",lo:0,hi:1099511627776}]),Pa=y("gem.requestToken",[{n:"requestId",k:"s",max:64},{n:"reason",k:"e",v:["initial","expiring","rejected"]}]),Ea=y("gem.requestLocalServer",[{n:"requestId",k:"s",max:64},{n:"gameRoomId",k:"s",max:64}]),Ta=y("gem.localServer",[{n:"requestId",k:"s",max:64},{n:"serverId",k:"s",o:1,max:128}]),Ia=y("gem.localServer.denied",[{n:"requestId",k:"s",max:64},{n:"retryable",k:"b"},{n:"reason",k:"e",v:["refused","unavailable"]}]),Ca=y("gem.exit",[{n:"reason",k:"s",o:1,max:64}]),Ma=y("gem.openExternal",[{n:"url",k:"s",max:2048,f:"url"}]),Oa=y("gem.requestFullscreen",[{n:"enabled",k:"b"}]),La=y("gem.audioState",[{n:"muted",k:"b"}]),Ga=y("gem.rewardCue",[{n:"currencySlug",k:"s",max:32},{n:"expected",k:"i",o:1,lo:1,hi:1e9},{n:"origin",k:"o",o:1,fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384}]}]),Da=y("gem.walletDisplay",[{n:"visible",k:"b"},{n:"currencies",k:"a",o:1,max:8,it:{n:"",k:"s",max:64}},{n:"score",k:"b",o:1}]),qa=y("gem.controlsDeclare",[{n:"uses",k:"o",fs:[{n:"lookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"gamepadLookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"invertLookY",k:"s",o:1,max:16,f:"code"},{n:"touchMovement",k:"s",o:1,max:16,f:"code"}]}]),$a=y("gem.menu",[{n:"settings",k:"b"},{n:"items",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"id",k:"s",max:32},{n:"label",k:"s",max:40}]}}]),Fa=y("gem.menuSelect",[{n:"entry",k:"e",v:["settings","item"]},{n:"id",k:"s",o:1,max:32}]),ja=y("gem.requestShare",[{n:"params",k:"a",max:16,it:{n:"",k:"o",fs:[{n:"key",k:"s",max:64},{n:"value",k:"s",max:512}]}}]),Na=y("gem.requestAvatarPicker",[{n:"tab",k:"e",o:1,v:["2d","3d"]}]),Ua=y("gem.vibrate",[{n:"pattern",k:"a",max:99,it:{n:"",k:"i",lo:0,hi:1e4}}]),Wa=y("gem.frameStats",[{n:"fps",k:"i",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"i",lo:0,hi:1e5}]),Ba=y("gem.portraitBorders",[{n:"name",k:"s",o:1,max:40}]),Va=y("gem.error",[{n:"code",k:"e",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"s",o:1,max:256}]),Ha=y("gem.requestPurchase",[{n:"requestId",k:"s",max:64},{n:"purchaseKind",k:"e",v:["item","recipe"]},{n:"targetId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"quantity",k:"i",o:1,lo:1,hi:10},{n:"catalogId",k:"s",o:1,max:64}]),Ka=y("gem.purchaseResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["ok","declined","unavailable"]},{n:"reason",k:"s",o:1,max:64,f:"code"},{n:"purchaseId",k:"s",o:1,max:64}]),Ja=y("gem.deviceSettings.put",[{n:"requestId",k:"s",max:64},{n:"settings",k:"j"}]),za=y("gem.deviceSettings.result",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["stored","too_large","unavailable"]}]),Ya=y("gem.requestAd",[{n:"requestId",k:"s",max:64},{n:"placement",k:"s",max:32},{n:"format",k:"e",v:["interstitial","rewarded"]}]),Xa=y("gem.adResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["shown","no_ad","unavailable"]}]),Qa=y("gem.requestSignIn",[{n:"requestId",k:"s",max:64}]),Za=y("gem.signInResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["signed_in","declined","unavailable"]}]),el=y("gem.requestFriendChallenge",[{n:"requestId",k:"s",max:64},{n:"playerId",k:"s",max:64},{n:"template",k:"s",max:64},{n:"params",k:"j",o:1}]),tl=y("gem.friendChallengeResult",[{n:"requestId",k:"s",max:64},{n:"outcome",k:"e",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"s",o:1,max:64},{n:"param",k:"s",o:1,max:64},{n:"channel",k:"s",o:1,max:16},{n:"configVersion",k:"i",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:864e5},{n:"detail",k:"s",o:1,max:300}]),le=Object.freeze(zn);var ot=3;function W(n){if(typeof n!="string")return;let e=n.trim();return e.length===0?void 0:e}function be(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=W(t);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var Ci=2e3,Mi=5e3;function Oi(n){let e=[],t=false,r=null,i=new Map,o=()=>{if(e.length>0)return Promise.resolve(e);if(t)return Promise.resolve([]);if(!n.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let a,s=new Promise(l=>{let d=false,m=null;a=c=>{d||(d=true,r=null,n.clock.clearTimeout(m),l(c));},m=n.clock.setTimeout(()=>{t=true,a([]);},n.timeoutMs??Ci);});return r={promise:s,settle:a},s};return {resolveList:o,resolve(){return e.length>0||t||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):o().then(a=>a[0])},refresh(a){return !Yn(e,a)||!n.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(s=>{let l=null,d=m=>{i.delete(d)&&(n.clock.clearTimeout(l),s(m));};i.set(d,a),l=n.clock.setTimeout(()=>d(e),n.refreshTimeoutMs??Mi);})},accept(a,s){let l=be(s),d=W(a),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[c,p]of [...i])Yn(m,p)||c(m);}}}}function Yn(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}var Li=["lookSensitivity","gamepadLookSensitivity","invertLookY","touchMovement"];function st(n){let e={};if(typeof n=="object"&&n!==null)for(let t of Li){let r=n[t];(r==="player"||r==="game")&&(e[t]=r);}return e}var Gi=/^[a-z0-9][a-z0-9_-]{0,39}$/;function Vt(n){return typeof n=="string"&&Gi.test(n)}function Xn(n){if(n===null||Vt(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,at=24;function S(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 ve(...n){return e=>typeof e=="string"&&n.includes(e)?e:void 0}function Qn(n){return typeof n=="boolean"?n:void 0}var L=S(64),Ge=ee(0,2147483647);function Ht(n){if(!Array.isArray(n))return;let e=[];for(let t of n){if(e.length>=64)break;let r=L(t);typeof r=="string"&&e.push(r);}return e}function P(n,e,t){return {to:n,from:e,read:t,required:true}}function x(n,e,t){return {to:n,from:e,read:t,required:false}}function _e(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 Zn=[P("sdp","sdp",S(10240)),P("signaling_intent","intent",ve("initial","ice_restart","full_reconnect"))];function lt(n,e,t){if(typeof t!="object"||t===null||Array.isArray(t))return {reason:"offer: data must be an object"};let r=t,i=_e(r,Zn);return i===null?{reason:`offer: '${Zn.find(a=>a.read(r[a.from])===void 0)?.from??"?"}' is missing or out of bounds`}:{frame:{type:"webrtc_offer",match_id:n,game_id:e,...i}}}var Kt=Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"})),Di=new Set(["error"]),qi=Object.freeze(Object.assign(Object.create(null),{answer:[P("sdp","sdp",S(10240)),x("sessionId","session_id",S(64))],error:[x("code","code",S(64)),x("message","message",S(256))],matchEnded:[x("reason","reason",S(64))]}));function dt(n,e,t){let r=De(n);if(r===null)return null;let i=Kt[r.type];if(i===void 0)return null;let o=L(r.data.match_id);if(typeof o!="string"||!(Di.has(i)?t(o):r.data.game_id===e))return null;let s=_e(r.data,qi[i]??[]);return s===null?null:{event:i,matchId:o,...s}}var $i=n=>{if(typeof n!="object"||n===null||Array.isArray(n))return;let e=n,t=ve("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}}},Fi=Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[P("sdp","sdp",S(10240)),P("signaling_intent","intent",ve("initial","ice_restart","full_reconnect")),x("sdp_hash","sdpHash",S(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[P("peer_id","peerId",L),P("sdp","sdp",S(10240)),P("assigned_peer_id","assignedPeerId",ee(0,4294967295)),x("sdp_hash","sdpHash",S(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[P("peer_id","peerId",L),P("candidate","candidate",S(512)),x("sdp_mid","sdpMid",S(64)),x("sdp_mline_index","sdpMLineIndex",ee(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[P("host_epoch","hostEpoch",Ge)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[P("host_epoch","hostEpoch",Ge),x("evidence","evidence",$i)]}}));function ct(n,e,t,r){let i=Fi[n];if(i===void 0)return {reason:`unknown signal '${n}'`};if(typeof r!="object"||r===null||Array.isArray(r))return {reason:`${n}: data must be an object`};let o=r,a=_e(o,i.args);if(a===null){let s=i.args.find(l=>l.required&&l.read(o[l.from])===void 0);return {reason:`${n}: '${s?.from??"?"}' is missing or out of bounds`}}return {frame:{type:i.type,match_id:e,...i.gameScoped?{game_id:t}:{},...a}}}var ji=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"})),Ni=new Set(["error"]),Ui=Object.freeze(Object.assign(Object.create(null),{hello:[P("playerId","player_id",L),P("hostPlayerId","host_player_id",L),P("hostEpoch","host_epoch",Ge),x("members","members",Ht)],offer:[P("fromPlayerId","from_player_id",L),P("sdp","sdp",S(10240)),x("sessionId","signaling_session_id",S(128)),x("sdpHash","sdp_hash",S(128)),x("iceUfrag","ice_ufrag",S(64)),x("intent","signaling_intent",ve("initial","ice_restart","full_reconnect"))],answer:[P("fromPlayerId","from_player_id",L),P("sdp","sdp",S(10240)),x("sessionId","signaling_session_id",S(128)),x("sdpHash","sdp_hash",S(128)),x("iceUfrag","ice_ufrag",S(64)),x("assignedPeerId","assigned_peer_id",ee(0,4294967295))],ice:[P("fromPlayerId","from_player_id",L),P("candidate","candidate",S(512)),x("sdpMid","sdp_mid",S(64)),x("sdpMLineIndex","sdp_m_line_index",ee(0,255)),x("sdpMLineIndexAlt","sdp_mline_index",ee(0,255))],peerJoined:[P("playerId","player_id",L)],peerLeft:[P("playerId","player_id",L),x("reason","reason",S(64))],migration:[P("hostPlayerId","new_host_player_id",L),P("hostEpoch","host_epoch",Ge),x("reason","reason",S(64)),x("kickedPlayerIds","kicked_player_ids",Ht),x("migrationComplete","migration_complete",Qn)],matchEnded:[x("reason","reason",S(64))],error:[x("code","code",S(64)),x("message","message",S(256))]}));function ut(n,e,t){let r=De(n);if(r===null)return null;let i=ji[r.type];if(i===void 0)return null;let o=L(r.data.match_id);if(typeof o!="string"||!(Ni.has(i)?t(o):r.data.game_id===e))return null;let s=_e(r.data,Ui[i]??[]);return s===null?null:{event:i,matchId:o,data:s}}var Wi=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 qe(n){let e=De(n);if(e===null)return null;let t=Wi[e.type];if(t===void 0)return null;let r=e.data,i=L(r.party_id);if(typeof i!="string")return null;let o=ee(0,Number.MAX_SAFE_INTEGER)(r.version),a=L(r.game_room_id),s=L(r.game_id),l=L(r.inviter_player_id),d=S(80)(r.inviter_display_tag),m=S(64)(r.party_name);return {event:t,partyId:i,...o===void 0?{}:{version:o},...a===void 0?{}:{gameRoomId:a},...s===void 0?{}:{gameId:s},...l===void 0?{}:{inviterPlayerId:l},...d===void 0?{}:{inviterDisplayTag:d},...m===void 0?{}:{partyName:m}}}var re={now:()=>Date.now(),setTimeout:(n,e)=>setTimeout(n,e),clearTimeout:n=>clearTimeout(n)},te=class{constructor(e=re){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let t=nt[e];if(t===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??t,a=Math.max(0,r-i),s=Math.min(t,o+a*t/6e4);return s<1?(this.tokens.set(e,s),this.lastRefill.set(e,r),false):(this.tokens.set(e,s-1),this.lastRefill.set(e,r),true)}};function we(n,e){return n.toLowerCase()===e.toLowerCase()}function mt(n){let e=n.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function tr(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:mt(t.hostname)&&mt(r.hostname)}function Jt(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 Bi=7,rr=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,Vi=["universal","mobile"],Hi={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"},Ki=new Set(["match_ended","p2p_match_ended"]),Ji="game_room_auto_start_failed",ir={matchmaking_ticket_queued:"queued",matchmaking_ticket_matched:"matched",matchmaking_ticket_expired:"expired",matchmaking_ticket_cancelled:"cancelled",matchmaking_ticket_failed:"failed"},zi=64,or=/^[a-z][a-z0-9_]{0,63}$/,$e=64,Yi=8,Yt=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 Re(n){if(!(typeof n!="string"||n.length===0||n.length>$e))return n}function sr(n){return typeof n=="number"&&Number.isSafeInteger(n)&&n>=0?n:void 0}function Xi(n){return n instanceof Error?n.message:String(n)}function ar(n,e){if(!n.has(e)){if(n.size>=Yi){let t=n.values().next().value;t!==void 0&&n.delete(t);}n.add(e);}}function zt(){return new MessageChannel}var Qi=6e4/(nt["gem.handshake"]??1),Zi=6e4,Xt=class{constructor(e){this.options=e;if(!it(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(!it(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 Yt(this.clock,24);}options;state="idle";port=null;version=null;timeoutHandle=null;reofferHandle=null;makeChannel=zt;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=zt){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?zt():(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 ${Bt}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.`);},Bt);}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:h,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());},Qi);}pruneStaleOffers(){let e=this.clock.now()-Zi;for(;this.offered.length>0&&(this.offered[0]?.at??e)<e;){let t=this.offered.shift();if(t===void 0)break;t.port.onmessage=null,t.port.close();}}adopt(e){for(let t of this.offered)t.port!==e&&(t.port.onmessage=null,t.port.close());this.offered.length=0,this.port=e;}static checkHandshakeOrigin(e,t,r){return we(e.origin,t)?e.source!==r?"source is not the mounted frame":null:`origin '${e.origin}' is not the expected frame origin`}sendToken(e){if(!Number.isInteger(e.chainEndsAt)||e.chainEndsAt<0){this.fail("internal","refusing a grant whose chainEndsAt is not a whole number of seconds >= 0");return}let t=this.chainEndsAt??e.chainEndsAt;if(this.chainExpired()){this.fail("token_unavailable","token chain ceiling reached");return}this.send({gem:h,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=Hi[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=Re(i.game_room_id);if(o===void 0)return false;let a=Ki.has(t.type)?void 0:Re(i.match_id);a!==void 0&&this.rememberMatch(a);let s=typeof i.version=="number"?i.version:void 0,l=typeof i.reason=="string"?i.reason.slice(0,$e):void 0,d=r==="version_stale"&&Vi.includes(i.platform)?i.platform:void 0;return this.sendRoomEvent({event:r,roomId:o,...a===void 0?{}:{matchId:a},...s===void 0?{}:{version:s},...l===void 0?{}:{reason:l},...d===void 0?{}:{platform:d}})}sendRoomEvent(e){return this.frameSupports("rooms")?this.send({gem:h,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:h,type:"gem.socketState",connected:e.connected,...e.connected?{}:{reason:e.reason}}):false}sendSeatedEvent(e){return this.frameSupports("partySeating")?this.send({gem:h,type:"gem.seatedEvent",roomId:e}):false}relaySeatedEvent(e){if(this.gameId===null)return false;let t=qe(e);if(t===null||t.event!=="gameRoomJoined"||t.gameId!==this.gameId)return false;let r=Re(t.gameRoomId);return r===void 0?false:this.sendSeatedEvent(r)}sendAutoStartFailedEvent(e){return this.frameSupports("autoStartFailure")?this.send({gem:h,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!==Ji||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=Re(r.game_room_id),o=typeof r.code=="string"&&or.test(r.code)?r.code:void 0;return i===void 0||o===void 0?false:this.sendAutoStartFailedEvent({roomId:i,code:o})}sendTicketEvent(e){return this.frameSupports("ticketEvents")?this.send({gem:h,type:"gem.ticketEvent",event:e.event,ticketId:e.ticketId,...e.partySize===void 0?{}:{partySize:e.partySize},...e.queuedAt===void 0?{}:{queuedAt:e.queuedAt},...e.expiresAt===void 0?{}:{expiresAt:e.expiresAt},...e.reason===void 0?{}:{reason:e.reason},...e.roomId===void 0?{}:{roomId:e.roomId}}):false}relayTicketEvent(e){if(this.gameId===null||typeof e!="object"||e===null||Array.isArray(e))return false;let t=e;if(typeof t.type!="string"||!Object.hasOwn(ir,t.type))return false;let r=ir[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=Re(i.ticket_id);if(o===void 0)return false;if(r==="queued"){let s=typeof i.party_size=="number"&&Number.isInteger(i.party_size)&&i.party_size>=1&&i.party_size<=zi?i.party_size:void 0,l=sr(i.queued_at),d=sr(i.expires_at);return this.sendTicketEvent({event:r,ticketId:o,...s===void 0?{}:{partySize:s},...l===void 0?{}:{queuedAt:l},...d===void 0?{}:{expiresAt:d}})}if(r==="matched"){let s=Re(i.game_room_id);return this.sendTicketEvent({event:r,ticketId:o,...s===void 0?{}:{roomId:s}})}let a=typeof i.reason=="string"&&or.test(i.reason)?i.reason:void 0;return this.sendTicketEvent({event:r,ticketId:o,...a===void 0?{}:{reason:a}})}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"),this.relayTicketEvent(e)&&t.push("ticket");let r=qe(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=ut(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:h,type:"gem.signalEvent",event:e.event,matchId:e.matchId,data:e.data}):false}relayDedicatedEvent(e){if(this.gameId===null)return false;let t=dt(e,this.gameId,r=>this.knowsMatch(r));return t===null?false:this.sendDedicatedEvent(t)}sendDedicatedEvent(e){return this.frameSupports("dedicated")?this.send({gem:h,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){ar(this.knownMatches,e);}rememberAsked(e){ar(this.askedMatches,e);}answerPartyRequest(e,t){return this.send({gem:h,type:"gem.partyResult",requestId:e,...t===void 0?{}:{partyId:t}})}answerPurchase(e,t,r,i){return this.send({gem:h,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:h,type:"gem.deviceSettings.result",requestId:e,outcome:t})}sendDeviceSettings(e){return this.frameSupports("deviceSettings")?this.send({gem:h,type:"gem.deviceSettings",...e===void 0?{}:{settings:e}}):false}sendMenuSelect(e){return this.frameSupports("gameMenu")?this.send(e==="settings"?{gem:h,type:"gem.menuSelect",entry:"settings"}:{gem:h,type:"gem.menuSelect",entry:"item",id:e.id}):false}answerAd(e,t){return this.send({gem:h,type:"gem.adResult",requestId:e,outcome:t})}answerSignIn(e,t){return this.send({gem:h,type:"gem.signInResult",requestId:e,outcome:t})}answerFriendChallenge(e,t,r={}){let i={};if(t==="invalid"){let{code:o,param:a,channel:s,configVersion:l,detail:d}=r;typeof o=="string"&&o.length<=64&&(i.code=o),typeof a=="string"&&a.length<=64&&(i.param=a),typeof s=="string"&&s.length<=16&&(i.channel=s),typeof l=="number"&&Number.isSafeInteger(l)&&l>=0&&(i.configVersion=l),typeof d=="string"&&(i.detail=d.slice(0,300));}else if(t==="rate_limited"){let o=r.retryAfterMs;typeof o=="number"&&Number.isFinite(o)&&(i.retryAfterMs=Math.min(864e5,Math.max(0,Math.round(o))));}return this.send({gem:h,type:"gem.friendChallengeResult",requestId:e,outcome:t,...i})}denyToken(e){this.send({gem:h,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:h,type:"gem.localServer",requestId:e.requestId,...e.serverId===void 0?{}:{serverId:e.serverId}}):false}denyLocalServer(e){return this.frameSupports("localHost")?this.send({gem:h,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>$e):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 ${$e} 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:h,type:"gem.clusterTarget",clusterTargetId:i,...typeof e=="string"?{}:{clusterTargetIds:[...t]}})}sendPlayer(e){let{displayName:t,displayTag:r}=e.untrusted,i=e.badges?.map(({itemId:d,iconUrl:m})=>({itemId:d,iconUrl:m})),o=e.boost&&{multipliers:e.boost.multipliers.map(({currencyId:d,currencySlug:m,multiplierBp:c})=>({currencyId:d,currencySlug:m,multiplierBp:c})),...e.boost.expiresInDays===void 0?{}:{expiresInDays:Math.min(Bi,e.boost.expiresInDays)}},a=e.discriminator!==void 0&&/^[0-9]{1,8}$/.test(e.discriminator)?e.discriminator:void 0,s=e.avatarIconId!==void 0&&rr.test(e.avatarIconId)?e.avatarIconId:void 0,l=e.avatar3dId!==void 0&&rr.test(e.avatar3dId)?e.avatar3dId:void 0;this.send({gem:h,type:"gem.player",untrusted:{displayName:t,...r===void 0?{}:{displayTag:r},displayHandle:r??t},...e.playerId===void 0?{}:{playerId:e.playerId},...a===void 0?{}:{discriminator:a},...e.avatarIconUrl===void 0?{}:{avatarIconUrl:e.avatarIconUrl},...s===void 0?{}:{avatarIconId:s},...l===void 0?{}:{avatar3dId:l},...e.avatar3dModelUrl===void 0?{}:{avatar3dModelUrl:e.avatar3dModelUrl},...e.avatar3dIconUrl===void 0?{}:{avatar3dIconUrl:e.avatar3dIconUrl},...i===void 0?{}:{badges:i},...o===void 0?{}:{boost:o},displayTag:a??"",...e.avatarIconUrl===void 0?{}:{avatarUrl:e.avatarIconUrl}});}chainExpired(){return this.chainEndsAt!==null&&this.clock.now()/1e3>=this.chainEndsAt}localCorrelationId(){return `local-${++this.localDenials}`}sendPause(e){this.send({gem:h,type:"gem.pause",paused:e});}sendDevtools(e){this.send({gem:h,type:"gem.devtools",action:e});}requestScreenshot(e,t){return this.frameSupports("screenshot")?this.send({gem:h,type:"gem.screenshot",maxWidth:t.maxWidth,maxHeight:t.maxHeight},[e]):false}requestContext(){return this.frameSupports("feedbackContext")?this.send({gem:h,type:"gem.requestContext"}):false}sendPrefs(e){this.send({gem:h,type:"gem.prefs",...e});}sendCohorts(e){return this.frameSupports("cohorts")?this.send({gem:h,type:"gem.cohorts",cohorts:e.map(t=>({experimentId:t.experimentId,variantKey:t.variantKey}))}):false}sendEarnAllowanceChanged(){return this.frameSupports("earnAllowance")?this.send({gem:h,type:"gem.earnAllowanceChanged"}):false}sendViewport(e){if(!this.frameSupports("viewport"))return false;let t=(e.reserved??[]).map(({x:o,y:a,width:s,height:l})=>({x:o,y:a,width:s,height:l})),r=this.frameSupports("reservedAreas"),i=e.insets.top;if(!r)for(let o of t)o.y===0&&(i=Math.max(i,o.height));return this.send({gem:h,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:h,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=le[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=le[r];if(!i){this.refuseMalformed("unsupported",`unknown message type ${JSON.stringify(r.slice(0,$e))}`);return}if(!this.inbound.allow(r)){this.fail("rate_limited",`frame exceeded the limit for ${r}`);return}let o=rt(r);if(o!==void 0&&!this.options.capabilities?.includes(o)){this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this parent did not advertise`);return}let a=i(e);if(a){this.fail("invalid_message",`${r}: ${a}`);return}let s=e;r!=="gem.handshake.accept"&&!this.versionMatches(s,r)||this.dispatch(r,s,t);}refuseMalformed(e,t){if(!this.inbound.allow(ye)){this.options.onDropped?.(e,t);return}this.fail(e,t);}versionMatches(e,t){return e.v===this.version?true:(this.fail("invalid_message",`${t}: expected v ${String(this.version)}, got ${String(e.v)}`),false)}forwardSignal(e){let t=this.options.onSendSignal;if(t===void 0){this.fail("unsupported","this parent advertised `p2p` but wired no onSendSignal, so signaling has nowhere to go");return}if(this.gameId===null){this.options.onDropped?.("internal","gem.signal before any token was issued");return}if(e.signal!=="join"&&!this.knownMatches.has(e.matchId)){this.fail("unsupported",`gem.signal names match '${e.matchId}', which this player's socket has not mentioned`);return}if(!this.socketWindow.allow()){this.fail("rate_limited","signaling exceeded this parent per-second socket budget");return}let r=ct(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=lt(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: ${Xi(i)}`);}}}withinFrameSize(e,t,r){let i=JSON.stringify(t).length;return i<=16384?true:(this.fail("invalid_message",`${e} builds a ${i}-byte socket frame, over the ${16384}-byte limit gem-api enforces, so the socket would drop it and then fail to establish. ${r}`),false)}dispatch(e,t,r){if(e==="gem.handshake.accept"){if(this.state!=="handshaking"){this.fail("handshake_duplicate","handshake already settled");return}let i=t.v;if(i<Z.min||i>Z.max){this.transition("unsupported"),this.fail("version_mismatch",`frame chose v${i}, outside our supported range`),this.close();return}this.adopt(r),this.version=i,this.peerCapabilities=t.capabilities??[],this.timeoutHandle!==null&&(this.clock.clearTimeout(this.timeoutHandle),this.timeoutHandle=null),this.reofferHandle!==null&&(this.clock.clearTimeout(this.reofferHandle),this.reofferHandle=null),this.transition("connected");return}if(this.state!=="connected"){this.fail("invalid_message",`${e} received before the handshake completed`);return}switch(e){case "gem.ready":this.options.onReady?.();break;case "gem.engaged":this.options.onEngaged?.();break;case "gem.progress":this.options.onProgress?.(t);break;case "gem.requestToken":{let i=t;if(this.chainExpired()){this.denyToken({requestId:i.requestId,retryable:false,reason:"chain_exhausted",correlationId:this.localCorrelationId()});break}this.options.onRequestToken?.(i);break}case "gem.requestLocalServer":{this.options.onRequestLocalServer?.(t);break}case "gem.exit":this.options.onExit?.(t),this.close();break;case "gem.openExternal":this.options.onOpenExternal?.(t);break;case "gem.requestFullscreen":this.options.onRequestFullscreen?.(t);break;case "gem.audioState":this.options.onAudioState?.(t);break;case "gem.rewardCue":this.options.onRewardCue?.(t);break;case "gem.walletDisplay":this.options.onWalletDisplay?.(t);break;case "gem.controlsDeclare":this.options.onControlsDeclare?.(st(t.uses));break;case "gem.menu":this.options.onMenu?.(t);break;case "gem.frameStats":this.options.onFrameStats?.(t);break;case "gem.portraitBorders":{let{name:i}=t;i==null?this.options.onPortraitBorders?.(null):Vt(i)&&this.options.onPortraitBorders?.(i);break}case "gem.screenshot.denied":this.options.onScreenshotDenied?.(t);break;case "gem.gameContext":this.options.onGameContext?.(t);break;case "gem.signal":this.forwardSignal(t);break;case "gem.dedicatedOffer":this.forwardDedicatedOffer(t);break;case "gem.partyRequest":{let i=t;if(this.options.onPartyRequest===void 0){this.answerPartyRequest(i.requestId);break}this.options.onPartyRequest(i);break}case "gem.requestPurchase":{let i=t;if(!this.frameSupports("purchases")){this.fail("unsupported_capability","refusing gem.requestPurchase: the frame did not advertise 'purchases', so it cannot receive gem.purchaseResult. Nothing was prompted and nothing was spent.");break}if(this.options.onRequestPurchase===void 0){this.answerPurchase(i.requestId,"unavailable");break}this.options.onRequestPurchase(i);break}case "gem.deviceSettings.put":{let i=t;if(!this.frameSupports("deviceSettings")){this.fail("unsupported_capability","refusing gem.deviceSettings.put: the frame did not advertise 'deviceSettings', so it cannot receive gem.deviceSettings.result. Nothing was stored.");break}if(this.options.onDeviceSettingsPut===void 0){this.answerDeviceSettingsPut(i.requestId,"unavailable");break}this.options.onDeviceSettingsPut(i);break}case "gem.requestAd":{let i=t;if(!this.frameSupports("ads")){this.fail("unsupported_capability","refusing gem.requestAd: the frame did not advertise 'ads', so it cannot receive gem.adResult. Nothing was rendered.");break}if(this.options.onRequestAd===void 0){this.answerAd(i.requestId,"no_ad");break}this.options.onRequestAd(i);break}case "gem.requestSignIn":{let i=t;if(!this.frameSupports("signIn")){this.fail("unsupported_capability","refusing gem.requestSignIn: the frame did not advertise 'signIn', so it cannot receive gem.signInResult. Nothing was rendered.");break}if(this.options.onRequestSignIn===void 0){this.answerSignIn(i.requestId,"unavailable");break}this.options.onRequestSignIn(i);break}case "gem.requestFriendChallenge":{let i=t;if(!this.frameSupports("friendChallenges")){this.fail("unsupported_capability","refusing gem.requestFriendChallenge: the frame did not advertise 'friendChallenges', so it cannot receive gem.friendChallengeResult. Nothing was previewed, rendered or sent.");break}if(this.options.onRequestFriendChallenge===void 0){this.answerFriendChallenge(i.requestId,"unavailable");break}this.options.onRequestFriendChallenge(i);break}case "gem.requestShare":if(!this.frameSupports("share")){this.fail("unsupported_capability","refusing gem.requestShare: the frame did not advertise 'share'. Nothing was shared.");break}this.options.onRequestShare?.(t);break;case "gem.requestAvatarPicker":if(!this.frameSupports("avatarPicker")){this.fail("unsupported_capability","refusing gem.requestAvatarPicker: the frame did not advertise 'avatarPicker'. Nothing was opened.");break}{let i=t.tab;this.options.onRequestAvatarPicker?.(i==="2d"||i==="3d"?{tab:i}:{});}break;case "gem.vibrate":{if(!this.frameSupports("vibration")){this.fail("unsupported_capability","refusing gem.vibrate: the frame did not advertise 'vibration'. Nothing was played.");break}let i=t,o=i.pattern.reduce((a,s)=>a+s,0);if(o>1e4){this.fail("invalid_message",`refusing gem.vibrate: the pattern totals ${o} ms, over ${1e4}. Nothing was played.`);break}this.options.onVibrate?.(i);break}case "gem.error":this.fail(t.code,t.message);break;default:this.fail("unsupported",`no parent handler for '${e}'`);}}};var B=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 ce(n){return new B(n)}var eo={toPlain(n){return B.unwrap(n)},compare(n,e,t){let r=n instanceof B?B.unwrap(n):n,i=e instanceof B?B.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 B?B.unwrap(n):n,r=e instanceof B?B.unwrap(e):e;return t.normalize("NFC")===r.normalize("NFC")}};function lr(n){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function to(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 no(n,e){let t=[];for(let r of Array.isArray(e)?e:[]){if(t.length===4)break;if(typeof r!="object"||r===null)continue;let{id:i,label:o}=r;typeof i!="string"||i.length===0||i.length>32||typeof o!="string"||o.trim().length===0||t.some(a=>a.id===i)||t.push({id:i,label:o.trim().slice(0,40)});}return t.length===0?{settings:n===true}:{settings:n===true,items:t}}function dr(n,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(n)?n:0)))}function ro(n){let e=n.untrusted,t=ce(e.displayName),r=e.displayTag||e.displayHandle,i=r?ce(r):void 0,o=n.discriminator||n.displayTag,a=o&&/^[0-9]{1,8}$/.test(o)?o:void 0,s=n.avatarIconUrl||n.avatarUrl,l=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,d=n.avatarIconId,m=n.avatar3dId,c={displayName:t,displayHandle:i??t,badges:(n.badges??[]).map(R=>({itemId:R.itemId,iconUrl:R.iconUrl}))};n.playerId&&(c.playerId=n.playerId),a&&(c.discriminator=a),i&&(c.displayTag=i),s&&(c.avatarIconUrl=c.avatarUrl=s),d&&l.test(d)&&(c.avatarIconId=d),m&&l.test(m)&&(c.avatar3dId=m),n.avatar3dModelUrl&&(c.avatar3dModelUrl=n.avatar3dModelUrl),n.avatar3dIconUrl&&(c.avatar3dIconUrl=n.avatar3dIconUrl);let p=n.boost,f=(p?.multipliers??[]).map(R=>({currencyId:R.currencyId,currencySlug:R.currencySlug,multiplier:R.multiplierBp/1e4})),b=f.some(R=>R.multiplier>1);return c.boost=b&&p?.expiresInDays?{active:b,multipliers:f,expiresInDays:p.expiresInDays}:{active:b,multipliers:f},c}var io=1e4,Qt=class{constructor(e){this.options=e;if(e.expectedSource===void 0||e.expectedSource===null)throw new Error("GemFrame: expectedSource is required and must not be null \u2014 pass window.parent. The handshake transfers the MessagePort, and origin alone does not say WHICH document on that origin sent it.");this.expectedSource=e.expectedSource,this.clock=e.clock??re,this.inbound=new te(this.clock),this.outbound=new te(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];unbidden=false;engagedSent=false;readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}get unbiddenLaunch(){return this.unbidden}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(s=>we(s,e.origin))||tr(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=le["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!we(i.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${i.embedder}' but arrived from '${e.origin}'`),false;let o=e.ports?.[0];if(!o)return this.refuse(e,"handshake transferred no MessagePort"),false;let a=Jt(Z,i.versions);return a===null?(o.onmessage=null,o.postMessage({gem:h,type:"gem.error",code:"version_mismatch",message:`frame supports v${Z.min}..v${Z.max}`}),o.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=o,this.version=a,o.onmessage=s=>this.receive(s.data,s.ports??[]),o.start?.(),this.peerCapabilities=i.capabilities??[],this.unbidden=i.unbidden===true,o.postMessage({gem:h,type:"gem.handshake.accept",v:a,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:h,type:"gem.ready"});}settled(e=io){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:h,type:"gem.progress",loaded:e,total:t});}requestToken(e,t){this.send({gem:h,type:"gem.requestToken",requestId:e,reason:t});}requestLocalServer(e,t){return this.parentSupports("localHost")?(this.send({gem:h,type:"gem.requestLocalServer",requestId:e,gameRoomId:t}),true):false}exit(e){this.send(e===void 0?{gem:h,type:"gem.exit"}:{gem:h,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:h,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:h,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:h,type:"gem.audioState",muted:e}),true)}reportEngaged(){return this.engagedSent||this.state!=="connected"||!this.parentSupports("engagement")||!this.send({gem:h,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let t={gem:h,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:lr(e.origin.x),y:lr(e.origin.y)}),this.send(t),true}showPortraitBorders(e){let t=Xn(e);return t===void 0||this.state!=="connected"||!this.parentSupports("portraitBorders")?false:this.send(t===null?{gem:h,type:"gem.portraitBorders"}:{gem:h,type:"gem.portraitBorders",name:t})}setWalletVisible(e,t){return this.state!=="connected"||!this.parentSupports("walletDisplay")?false:this.send({gem:h,type:"gem.walletDisplay",...to(e,t?.only)})}declareControls(e){return this.state!=="connected"||!this.parentSupports("controls")?false:this.send({gem:h,type:"gem.controlsDeclare",uses:st(e)})}setMenu(e,t){return this.state!=="connected"||!this.parentSupports("gameMenu")?false:this.send({gem:h,type:"gem.menu",...no(e,t)})}requestShare(e){return this.state!=="connected"||!this.parentSupports("share")?false:this.send({gem:h,type:"gem.requestShare",params:e.map(({key:t,value:r})=>({key:t,value:r}))})}requestAvatarPicker(e){return this.state!=="connected"||!this.parentSupports("avatarPicker")?false:this.send({gem:h,type:"gem.requestAvatarPicker",...e==="2d"||e==="3d"?{tab:e}:{}})}requestVibrate(e){return this.state!=="connected"||!this.parentSupports("vibration")?false:this.send({gem:h,type:"gem.vibrate",pattern:[...e]})}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:h,type:"gem.frameStats",fps:dr(e.fps,1e3),frameTimeP95Ms:dr(e.frameTimeP95Ms,1e5)}),true)}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:h,type:"gem.gameContext",context:e}),true)}signal(e,t,r){this.send({gem:h,type:"gem.signal",signal:e,matchId:t,data:r});}dedicatedOffer(e,t,r){this.send({gem:h,type:"gem.dedicatedOffer",matchId:e,sdp:t,intent:r});}requestParty(e){return this.send({gem:h,type:"gem.partyRequest",requestId:e})}requestPurchase(e,t,r,i,o,a){return this.send({gem:h,type:"gem.requestPurchase",requestId:e,purchaseKind:t,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...a===void 0?{}:{catalogId:a}})}putDeviceSettings(e,t){return this.send({gem:h,type:"gem.deviceSettings.put",requestId:e,settings:t})}requestAd(e,t,r){return this.send({gem:h,type:"gem.requestAd",requestId:e,placement:t,format:r})}requestSignIn(e){return this.send({gem:h,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,t,r,i){return this.send({gem:h,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:h,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=le[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||cr(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=le[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=rt(r);if(o!==void 0&&!this.options.capabilities?.includes(o))return this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this frame did not advertise`),false;let a=i(e);if(a)return this.fail("invalid_message",`${r}: ${a}`),false;let s=e;if(s.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(s);break;case "gem.pause":this.options.onPause?.(s);break;case "gem.menuSelect":this.options.onMenuSelect?.(s);break;case "gem.prefs":this.options.onPrefs?.(s);break;case "gem.cohorts":this.options.onCohorts?.(s);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(s);break;case "gem.willTerminate":this.options.onWillTerminate?.(s);break;case "gem.devtools":this.options.onDevtools?.(s.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let l=t[0];if(!l){this.options.onError?.("invalid_message","gem.screenshot transferred no MessagePort");break}let d={maxWidth:s.maxWidth,maxHeight:s.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return cr(t.slice(1)),this.options.onScreenshot(d,l,(m,c)=>this.screenshotDenied(m,c)),true}case "gem.token.denied":this.options.onTokenDenied?.(s);break;case "gem.localServer":this.options.onLocalServer?.(s);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(s);break;case "gem.player":{this.options.onPlayer?.(ro(s));break}case "gem.roomEvent":this.options.onRoomEvent?.(s);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(s);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(s);break;case "gem.ticketEvent":this.options.onTicketEvent?.(s);break;case "gem.socketState":this.options.onSocketState?.(s);break;case "gem.signalEvent":this.options.onSignalEvent?.(s);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(s);break;case "gem.clusterTarget":this.options.onClusterTarget?.(s);break;case "gem.partyResult":this.options.onPartyResult?.(s);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(s);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(s);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(s);break;case "gem.adResult":this.options.onAdResult?.(s);break;case "gem.signInResult":this.options.onSignInResult?.(s);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(s);break;case "gem.error":this.options.onError?.(s.code,s.message);break;default:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,t){this.send({gem:h,type:"gem.screenshot.denied",reason:e,retryable:t});}};function cr(n){for(let e of n)try{e?.close?.();}catch{}}var oo=16384;function so(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:ao(e)}function ao(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 ur=["p2p","dedicated","unknown"],pt=["connection_setup_duration_seconds","reconnect_latency_seconds","datachannel_rtt_seconds","p2p_join_to_play_latency_seconds","ice_restart_outcome_total","connection_failures_total","transport_permanent_failures_total","transport_quality_score","host_migration_outcome_total","turn_relay_usage_ratio"];var ue=class{constructor(e){this.options=e;}options;async post(e,t){let r=this.options.gameId();if(r===null||r==="")return;let i=lo(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 lo(n,e,t){let r=Math.floor(t/1e3);return n.filter(i=>pt.includes(i.type)).slice(0,100).map(i=>{let o=co(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:i.value===void 0?{}:{value:i.value}}})}function co(n){if(n!==void 0)return ur.includes(n)?n:"unknown"}function Zt(n){let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)t[r]=e.charCodeAt(r);return t}var j=class extends Error{constructor(t,r,i,o,a){super(`${t} (${r}): ${i}`);this.reason=t;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=a;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}};var mo=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=mo.has(t),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var mr=["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"],po=new Set(mr);function Se(n){return typeof n=="string"&&po.has(n)?n:"unknown"}var Fe="webrtc_dedicated",tn=["universal","mobile","web"];var go="p2p_unavailable",ho="capacity_unavailable",fo=2,pr=3e4,gr=1e3,hr=2e4;async function gt(n){let e=W(n.clusterTargetId),t=n.nextClusterTarget,r=0,i=n.clock??re,o=n.retry??{},a=o.budgetMs??pr,s=o.maxDelayMs??hr,l=o.initialDelayMs??gr,d=i.now(),m=d+a,c=0;for(;;){c++;try{let p=await rn(n.signal,"while allocating",()=>n.client.post(`${br(n)}/start_match`,e===void 0?{}:{cluster_target_id:e},n.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!yo(p)||a<=0)throw p;if(p.status===503&&p.code===go)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: ${p.message}`,{cause:p});if(r=p.code===ho?r+1:0,t!==void 0&&r>=fo){let M=t;t=void 0;let I=W(await M());I!==void 0&&(e=I,r=0);}let f=Math.min(s,l*2**(c-1)),b=Math.min(s,(p.retryAfterSeconds??0)*1e3),T=Math.max(f/2,b)+Math.random()*(f/2);if(i.now()+T>m)throw bo(n,p,c,i.now()-d,a);if(o.onWaiting?.({attempt:c,elapsedMs:i.now()-d,budgetMs:a,nextAttemptInMs:T,status:p.status,message:p.message}),await yt(i,T,n.signal),n.signal?.aborted)throw en("while waiting to allocate")}}}function yo(n){return n instanceof j?n.status===503?true:n.status===429&&n.code!=="too_many_concurrent_matches":false}function bo(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 vo=12e4,_o=1e3;async function ht(n){let{clock:e,matchId:t}=n,r=n.pollIntervalMs??_o,i=n.timeoutMs??vo,o=e.now()+i,a=fr(n),s={seen:n.knownToExist===true};for(;;){let l=await yr(n,a,s);if(l.outcome!==null)return l.outcome;if(e.now()+r>o)throw new u("timeout",`match ${t} was still ${l.status} after ${i}ms`);await yt(e,r,n.signal);}}async function nn(n){return (await yr(n,fr(n),{seen:n.knownToExist===true})).outcome}function fr(n){let e=new URLSearchParams({platform:n.version.platform,game_version:n.version.gameVersion});return `${br(n)}/matches/${encodeURIComponent(n.matchId)}/status?${e}`}async function yr(n,e,t){let{matchId:r}=n,i=n.clock.now(),o;try{o=await rn(n.signal,"while polling match status",()=>n.client.get(e,n.signal));}catch(a){if(a instanceof j&&a.reason==="not_found")return {status:"not_found",outcome:t.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw a}if(t.seen=true,o.status==="ready")return {status:"ready",outcome:ko(r,o,i)};if(o.status==="failed"){let a=o.ended_reason;return typeof a=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:Se(a)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function ft(n){let e=await rn(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 rn(n,e,t){if(n?.aborted)throw en(e);try{return await t()}catch(r){throw n?.aborted?en(e,r):r}}function en(n,e){return new u("aborted",`the caller aborted ${n}`,e===void 0?void 0:{cause:e})}function ko(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 br(n){return `/v1/games/${encodeURIComponent(n.gameId)}/game-rooms/${encodeURIComponent(n.roomId)}`}function yt(n,e,t){return t?.aborted?Promise.resolve():new Promise(r=>{let i=()=>{n.clearTimeout(o),t?.removeEventListener("abort",i),r();},o=n.setTimeout(i,e);t?.addEventListener("abort",i);})}var wo=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),sn="embedder_relay_unavailable",Ro="embedder_no_relay",So=new Set([sn]),an=new Set([Ro]),bt=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new on(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(xo(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 xo(n,e){let t=e??"the offer was refused",r=n===void 0?t:`${t} (${n})`;return new u(Ao(n),r,{platformCode:n})}function Ao(n){return n===void 0||So.has(n)?"signaling_failed":an.has(n)?"offer_refused":wo.has(n)?n==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var on=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 a=()=>{s(),o(new u("aborted","the caller aborted the signaling exchange"));},s=()=>{t?.removeEventListener("abort",a),this.hub.release(e.matchId,l),this.teardown===s&&(this.teardown=null);},l={settle:d=>{s(),i(d);},refuse:d=>{s(),o(d);}};this.teardown=s,t?.addEventListener("abort",a),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof u?d:new u("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var vr="match_ended:",_r="server_shutdown:",kr="kicked:",Po=123;function Eo(n){if(typeof n!="string"||n.length===0||n.length>Po)return {kind:"other"};if(n.startsWith(vr)){let e=Se(n.slice(vr.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return n.startsWith(_r)?{kind:"server_shutdown",cause:n.slice(_r.length)}:n.startsWith(kr)?{kind:"kicked",detail:n.slice(kr.length)}:{kind:"other"}}function ln(n,e,t){let r=Eo(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 To="join",Io="welcome",Co="rejected",dn=25e3,Mo=1e3,cn=1;function un(n){return typeof n=="number"&&Number.isFinite(n)&&n>0?n:void 0}var Oo={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 mn(n){let e=typeof n=="string"?n:"unknown";return new u(Oo[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function je(n){let{channel:e,clock:t}=n;return new Promise((r,i)=>{let o=false,a=Math.min(n.credentialExpiresAt-t.now(),n.ceilingMs??dn),s=t.setTimeout(()=>R(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(a,Mo)),l=T=>{let M=T.data;if(typeof M!="string"){c(M);return}let I;try{I=JSON.parse(M);}catch{c(M);return}if(o){c(M);return}if(I.t===Io){let g=un(I.heartbeat_interval);b({...typeof I.player_id=="string"?{playerId:I.player_id}:{},...typeof I.match_id=="string"?{matchId:I.match_id}:{},...g===void 0?{}:{heartbeatIntervalMs:g}});return}if(I.t===Co){R(mn(I.reason));return}c(M);},d=()=>{R(new u("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{R(new u("aborted","the caller aborted during the join exchange"));},c=T=>{o&&n.onMessage?.(T);},p=()=>{t.clearTimeout(s),e.removeEventListener("close",d),n.signal?.removeEventListener("abort",m);},f=()=>{e.removeEventListener("message",l);},b=T=>{o=true,p(),n.onMessage===void 0&&f(),r({welcome:T,detach:f});},R=T=>{o||(o=true,p(),f(),i(T));};if(e.addEventListener("message",l),e.addEventListener("close",d),n.signal?.aborted){m();return}n.signal?.addEventListener("abort",m);try{e.send(JSON.stringify({t:To,credential:n.credential,...n.wire===void 0?{}:{wire:n.wire},...n.heartbeat===!0?{heartbeat:cn}:{}}));}catch(T){R(new u("connection_failed",`the join frame could not be sent on the open channel: ${String(T)}`,{cause:T}));}})}function vt(){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 me=1,Ne=2,pn=4,fn=8,Lo=2,Go=1e3,yn="heartbeat timeout",_t="gem-uu",kt=2,Rr="gem_transports";function Ue(n){if(!Array.isArray(n))return null;let e=[];for(let t of n){if(typeof t!="string")continue;let r=t.toLowerCase();!Do(r)||e.includes(r)||e.push(r);}return e}function Do(n){return n==="webtransport"||n==="webrtc"||n==="websocket"}function wt(n,e){if(typeof n!="object"||n===null)return null;let t=n[Rr];if(typeof t!="object"||t===null)return null;let r=t;return typeof r.v!="number"||r.v<1||typeof r.host!="string"||typeof r.port!="number"||e!==void 0&&r.match_id!==e?null:r}function Rt(n){return n instanceof Error?n.message===""?n.name:`${n.name}: ${n.message}`:String(n)}var Sr=new TextEncoder,xr=new TextDecoder;function bn(n,e){let t=new Uint8Array(e.byteLength+1);return t[0]=n,t.set(e,1),t}function vn(n){let e=0;return n?.reliable===false&&(e|=me),n?.ordered===false&&(e|=Ne),e}function _n(n){return {reliable:(n&me)===0,ordered:(n&Ne)===0}}var kn={reliable:true,ordered:true};function Ar(n){return JSON.stringify({t:"join",credential:n,wire:kt,heartbeat:cn})}function Pr(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=un(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"?mn(e.reason):new u("join_refused","the server answered the join out of protocol")}function wn(){return typeof globalThis.WebTransport=="function"&&Rn===null}function St(){return Rn}var Rn=null;var wr="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function qo(n){let e=Zt(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 gn=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 a=this.buffered.slice(4,4+o);this.buffered=this.buffered.slice(4+o),r.push({flags:a[0]??0,payload:a.slice(1)});}return r}};function hn(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 We(n){let e=Math.min(n.timeoutMs??1e4,Math.max(n.credentialExpiresAt-n.clock.now(),1e3)),t=n.webTransport;if(t===void 0){let s=globalThis.WebTransport;if(s===void 0)throw new u("connection_failed","this environment has no WebTransport");t=n.certHashBase64===void 0?new s(n.url):new s(n.url,{serverCertificateHashes:[{algorithm:"sha-256",value:qo(n.certHashBase64)}]});}let r=t,i=s=>{try{r.close();}catch{}throw s},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(Rn=wr,i(new u("connection_failed",`${wr}; the rung is skipped for the rest of this page (a reload probes again)`)));let a=new Promise((s,l)=>{setTimeout(()=>l(new u("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,a]);let s=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([s.read(),a]);if(s.releaseLock(),l.done||l.value===void 0)return i(new u("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(hn(pn,Sr.encode(Ar(n.credential))));let c=new gn,p=d.readable.getReader(),f;for(;f===void 0;){let b=await Promise.race([p.read(),a]);if(b.done||b.value===void 0)return i(new u("connection_failed","the control stream closed before the join was answered"));for(let R of c.push(b.value)){f=Pr(xr.decode(R.payload));break}}return {link:$o(r,m,p,c,n.log??(b=>console.warn(b)),Tr(f,n.clock)),welcome:f}}catch(s){return i(s)}}function $o(n,e,t,r,i,o){let a,s,l=false,d=b=>{if(!l){l=true,m.stop();try{n.close();}catch{}s?.(b);}},m=xn(o,()=>d(yn)),c=(b,R)=>{m.heard(),(b&fn)===0&&a!==void 0&&((b&pn)!==0?a(xr.decode(R),kn):a(R,_n(b)));};(async()=>{try{for(;;){let b=await t.read();if(b.done||b.value===void 0)break;for(let R of r.push(b.value))c(R.flags,R.payload);}}catch{}d("stream closed");})();let p,f;try{let b=n.datagrams;if(b?.readable!==void 0&&b.writable!==void 0){let R=b.readable.getReader();f=b.writable.getWriter(),p=b,(async()=>{try{for(;;){let T=await R.read();if(T.done||T.value===void 0)break;let M=T.value;M.byteLength!==0&&c((M[0]??0)|me|Ne,M.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(b){p=void 0,f=void 0,i(`[gem] webtransport datagram lane unusable (${Rt(b)}); unreliable sends ride the stream`);}return n.closed.then(b=>d(Er(b?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(b,R){if(l)return;if(typeof b=="string"){e.write(hn(pn,Sr.encode(b))).catch(()=>d("write failed"));return}let T=vn(R);if((T&me)!==0&&f!==void 0){let M=bn(T,b),I=p?.maxDatagramSize;if(I===void 0||M.byteLength<=I){f.write(M).catch(()=>{});return}}e.write(hn(T,b)).catch(()=>d("write failed"));},onMessage(b){a=b;},onClose(b){s=b;},close(){d("closed");}}}function Sn(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 a=false,s=setTimeout(()=>{a||(a=true,r.close(),o(new u("timeout","websocket did not come up in time")));},e),l=f=>{a||(a=true,clearTimeout(s),r.close(),o(f));},d=()=>{r.send(Ar(n.credential));},m=f=>{if(a)return;if(typeof f.data!="string"){l(new u("join_refused","the server sent binary before answering the join"));return}let b;try{b=Pr(f.data);}catch(R){l(R);return}a=true,clearTimeout(s),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",c),r.removeEventListener("error",p),i({link:Fo(r,Tr(b,n.clock)),welcome:b});},c=()=>{l(new u("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new u("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",m),r.addEventListener("close",c),r.addEventListener("error",p),r.readyState===1&&d();})}function Er(n){return typeof n=="string"&&n.length>0?n:void 0}function Tr(n,e){return n.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:n.heartbeatIntervalMs}}function xn(n,e){if(n===void 0)return {heard:()=>{},stop:()=>{}};let{clock:t}=n,r=Math.max(n.intervalMs,Go)*Lo,i=t.now(),o=null,a=()=>{o=null;let s=t.now()-i;if(s>=r){e();return}o=t.setTimeout(a,r-s);};return o=t.setTimeout(a,r),{heard:()=>{i=t.now();},stop:()=>{o!==null&&(t.clearTimeout(o),o=null);}}}function Fo(n,e){let t,r,i=false,o=s=>{if(!i){i=true,a.stop();try{n.close();}catch{}r?.(s);}},a=xn(e,()=>o(yn));return n.addEventListener("message",(s=>{if(a.heard(),typeof s.data=="string"){t?.(s.data,kn);return}let l=new Uint8Array(s.data);if(l.byteLength===0)return;let d=l[0]??0;(d&fn)===0&&t?.(l.slice(1),_n(d));})),n.addEventListener("close",(s=>o(Er(s?.reason)??"socket closed"))),{transport:"websocket",send(s,l){if(!i){if(typeof s=="string"){n.send(s);return}n.send(bn(vn(l),s));}},onMessage(s){t=s;},onClose(s){r=s;},close(){o("closed");}}}function An(n,e,t,r){let i,o,a=false,s=t,l=c=>{if(!a){a=true,d.stop();try{n.close();}catch{}try{e.close();}catch{}o?.(c);}},d=xn(r,()=>l(yn)),m=(c,p)=>{if(d.heard(),typeof c=="string"){i?.(c,kn);return}let f=new Uint8Array(c);if(f.byteLength===0)return;let b=f[0]??0;(b&fn)===0&&i?.(f.slice(1),_n(b|p));};if(n.addEventListener("message",(c=>m(c.data,0))),n.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let c=e.connectionState;(c==="failed"||c==="closed")&&l(`connection ${c}`);})),s!==void 0){let c=s;c.addEventListener("message",(p=>m(p.data,me|Ne))),c.addEventListener("close",(()=>{s=void 0;}));}return {transport:"webrtc",send(c,p){if(a)return;if(typeof c=="string"){n.send(c);return}let f=vn(p),b=bn(f,c);if((f&me)!==0&&s!==void 0&&s.readyState==="open"){s.send(b);return}n.send(b);},onMessage(c){i=c;},onClose(c){o=c;},close(){l("closed");}}}var Ir=10240,Cr=2048,jo=new TextEncoder;function Mr(n){return jo.encode(n).length}function ie(n,e){let t=i=>{throw new u("invalid_sdp",`the ${e} ${i}`)},r=Mr(n);r>=Ir&&t(`is ${r} bytes, over the ${Ir} 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=Mr(i);o>Cr&&t(`has a ${o}-byte line, over the ${Cr} limit`);}}function xt(n){for(let e of n.split(/\r\n|\n/)){if(!e.startsWith("m="))continue;let[t,r="0"]=e.slice(2).trim().split(/\s+/);if(!(t!=="audio"&&t!=="video")&&r.split("/")[0]!=="0")return true}return false}var No=3e3,Uo=1e4,Wo=15e3;async function Be(n){let e=n.peerConnection;try{Lr(n,"before the handshake started"),Pn(n);let t=e.createDataChannel(n.channelLabel??"gem",{ordered:!0});for(let a of n.extraChannels??[]){let s=e.createDataChannel(a.label,{...a.ordered===void 0?{}:{ordered:a.ordered},...a.maxRetransmits===void 0?{}:{maxRetransmits:a.maxRetransmits}});n.onExtraChannel?.(a.label,s);}let r=await e.createOffer();await e.setLocalDescription(r),await Ho(e,n),Pn(n);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new u("invalid_sdp","the offer carried no SDP");ie(i,"offer"),Or(i,"offer");let o=await Vo(n,i);if(Pn(n),typeof o?.sdp!="string")throw new u("invalid_sdp","the signaling channel answered without an SDP");return ie(o.sdp,"answer"),Or(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await Ko(t,n),Lr(n,"before the channel opened"),t}catch(t){throw e.close(),Bo(t)}}function Bo(n){return n instanceof u?n:qr(n)?pe():new u("connection_failed",$r(n),{cause:n})}function Or(n,e){if(xt(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 Vo(n,e){let t=n.exchangeTimeoutMs??Uo,r=Dr(n,t),i=n.signaling.exchange({matchId:n.matchId,sdp:e,intent:n.intent??"initial"},n.signal).catch(o=>{throw o instanceof u?o:qr(o)?pe():new u("signaling_failed",$r(o),{cause:o})});return Jo(i,n,r,()=>r.exhausted?En("while the offer was in flight"):new u("timeout",`no answer arrived within ${t}ms`))}function Ho(n,e){if(n.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:t}=e;return new Promise(r=>{let i=()=>{t.clearTimeout(a),n.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{n.iceGatheringState==="complete"&&i();},a=t.setTimeout(i,e.gatherTimeoutMs??No);n.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function Ko(n,e){if(e.signal?.aborted)return Promise.reject(pe());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??Wo,i=Dr(e,r);return new Promise((o,a)=>{let s=()=>{t.clearTimeout(p),n.removeEventListener("open",l),n.removeEventListener("close",d),n.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{s(),o();},d=f=>{s(),a(new u("connection_failed","the data channel failed before it opened",Gr(f)===void 0?void 0:{cause:Gr(f)}));},m=()=>{s(),a(pe());},c=()=>{s(),a(i.exhausted?En("while the channel was still opening"):new u("timeout",`the data channel did not open within ${r}ms`));},p=t.setTimeout(c,i.ms);n.addEventListener("open",l),n.addEventListener("close",d),n.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function Dr(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 Jo(n,e,t,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(pe()):new Promise((a,s)=>{let l=c=>{i.clearTimeout(m),o?.removeEventListener("abort",d),c();},d=()=>l(()=>s(pe())),m=i.setTimeout(()=>l(()=>s(r())),t.ms);o?.addEventListener("abort",d),n.then(c=>l(()=>a(c)),c=>l(()=>s(c)));})}function Lr(n,e){if(n.credentialExpiresAt!==void 0&&!(n.clock.now()<n.credentialExpiresAt))throw En(`already ${e}`)}function En(n){return new u("credential_expired",`the join credential ran out ${n} \u2014 poll match status again for a fresh one`)}function Pn(n){if(n.signal?.aborted)throw pe()}function pe(){return new u("aborted","the caller aborted the connection attempt")}function qr(n){return n?.name==="AbortError"}function Gr(n){return n?.error}function $r(n){return n instanceof Error?n.message:String(n)}var Ve="0.1.0-beta",Fr="0-beta",xe="web",zo=/^(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 Yo(n){let e=zo.exec(n),t=e?.[1],r=e?.[4];return t===void 0?null:r===void 0?t:`${t}-${r}`}function jr(n,e){let t=Xo(n.platform,e),r=n.engineVersion;if(r===void 0)return {...n,platform:t,engineVersion:Ve};let i=Yo(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 '${Ve}' for it.`);if(i!==Fr)throw new u("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${Fr}' 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 '${Ve}' for it.`);return {...n,platform:t,engineVersion:r}}function Xo(n,e){if(n===void 0||n===xe)return xe;if(!tn.includes(n))throw new u("misconfigured",`${e} refused: platform '${String(n)}' is not a client platform gem-api recognises \u2014 it knows ${tn.map(t=>`'${t}'`).join(", ")}. Remove the field: the SDK reports '${xe}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${n}' was replaced with '${xe}' 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.`),xe}function Qo(n){let{client:e,clock:t,rooms:r}=n,i=n.signaling??vt,o=n.log??(g=>console.warn(g)),a=new ue({client:e,gameId:()=>r.gameId,transport:"dedicated"}),s=new Map,l=(g,v)=>{let w=s.get(g)??new Set;w.add(v),s.set(g,w);},d=(g,v)=>{let w=s.get(g);w!==void 0&&(w.delete(v),w.size===0&&s.delete(g));},m=async g=>{if(r.isHost&&!as(r)&&r.currentRoom?.matchId===void 0){let v=W(g.clusterTargetId);await r.startMatch({...v===void 0?{}:{clusterTargetId:v},...g.retry===void 0?{}:{retry:g.retry},...g.signal===void 0?{}:{signal:g.signal}});}return Hr(r.matchConnectionState==="suspended"?await r.reconnectToMatch(Tn(g)):await r.awaitMatch(Tn(g)))},c=async g=>Hr(await r.pollMatchStatus(Tn(g))),p=async(g,v)=>{let w=false;try{let _=await m(g),G=r.currentRoom?.transports;if(G!==void 0&&!G.includes("webrtc"))throw new u("misconfigured",`the room template offers (${G.join(", ")||"no transports"}), not webrtc, which is all this path dials. Connect through gem.match.connect(), or pass \`transports: []\` here to negotiate across the template's list.`);let C=g.peerConnection??Kr();w=!0;let D=await Be({peerConnection:C,signaling:v,clock:t,matchId:_.matchId,credentialExpiresAt:_.credentialExpiresAt,...At(g,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),F=null;if(g.presentCredential!==!1)try{F=await je({channel:D,clock:t,credential:_.joinCredential,credentialExpiresAt:_.credentialExpiresAt,...At(g,"onMessage","signal"),...g.welcomeTimeoutMs===void 0?{}:{ceilingMs:g.welcomeTimeoutMs}});}catch(N){throw J(D),J(C),N}return ss(r,_,D,C,v,g.reportDisconnect!==!1,g.reportConnected!==!1,F,{remember:l,forget:d},g.onMatchEnded)}catch(_){throw w&&Vr(a,_),J(v),_}},f=async(g,v,w,_,G,C)=>{if(g==="webtransport"){let O=_?.webtransport;if(O===void 0)throw new u("misconfigured","webtransport is not advertised");let Y={credential:w.joinCredential,credentialExpiresAt:w.credentialExpiresAt,clock:t};if(typeof O.named_url=="string"&&O.named_url!==""){let ne=Math.max(Math.floor(C/2),1e3);try{return await We({url:O.named_url,timeoutMs:ne,log:o,...Y})}catch(se){if(St()!==null)throw se;return o(`[gem] webtransport named dial failed (${Rt(se)}); retrying the pinned dial`),We({url:O.url,certHashBase64:O.cert_sha256_b64,timeoutMs:ne,log:o,...Y})}}return We({url:O.url,certHashBase64:O.cert_sha256_b64,timeoutMs:C,...Y})}if(g==="websocket"){let O=_?.websocket;if(O===void 0)throw new u("misconfigured","websocket is not advertised");return Sn({url:O.url,credential:w.joinCredential,credentialExpiresAt:w.credentialExpiresAt,clock:t,timeoutMs:C})}let D=v.peerConnection??Kr(),F,N=await Be({peerConnection:D,signaling:G,clock:t,matchId:w.matchId,credentialExpiresAt:w.credentialExpiresAt,extraChannels:[{label:_t,ordered:false,maxRetransmits:0}],onExtraChannel:(O,Y)=>{O===_t&&(F=Y);},...At(v,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...v.exchangeTimeoutMs===void 0&&v.redial===true?{exchangeTimeoutMs:es}:{}}),K;try{K=await je({channel:N,clock:t,credential:w.joinCredential,credentialExpiresAt:w.credentialExpiresAt,wire:kt,heartbeat:!0,...At(v,"signal"),...v.welcomeTimeoutMs===void 0?{}:{ceilingMs:v.welcomeTimeoutMs}});}catch(O){throw J(N),J(D),O}let A=K.welcome.heartbeatIntervalMs;return {link:An(N,D,F,A===void 0?void 0:{clock:t,intervalMs:A}),welcome:K.welcome,channel:N,peerConnection:D}},b=(g,v,w,_,G)=>{let C=false,D;_.link.onClose(A=>{!C&&g.reportDisconnect!==false&&ln(r,v.matchId,A),D?.(A);}),g.reportDisconnect!==false&&g.reportConnected!==false&&r.notifyMatchConnected(v.matchId);let F={transport:_.link.transport,send:(A,O)=>_.link.send(A,O),onMessage:A=>_.link.onMessage(A),onClose:A=>{D=A;},close:()=>_.link.close()},N=()=>{C||(C=true,J(_.link),J(G));},K=A=>{if(!C){try{g.onMatchEnded?.(A);}catch{}N();}};return l(v.matchId,K),{matchId:v.matchId,transport:w,link:F,joinCredential:v.joinCredential,credentialExpiresAt:v.credentialExpiresAt,welcome:_.welcome,..._.channel===void 0?{}:{channel:_.channel},..._.peerConnection===void 0?{}:{peerConnection:_.peerConnection},close(){d(v.matchId,K),N();}}},R=async(g,v)=>{let w=r.currentRoom?.id,_=r.gameId,G=()=>({advert:wt(r.currentRoom?.settings,g),template:r.currentRoom?.transports??null});if(w===void 0||_===null)return G();try{let C=await e.get(`/v2/games/${encodeURIComponent(_)}/game-rooms/${encodeURIComponent(w)}`,v);return {advert:wt(C.settings,g),template:Ue(C.transports)??r.currentRoom?.transports??null}}catch{return G()}},T=(g,v)=>{let w=g??Nr;return v.length===0?w:w.filter(_=>v.includes(_))},M=async(g,v,w)=>{try{let _=await m(g),{advert:G,template:C}=await R(_.matchId,g.signal),D=T(C,v),F=D.filter(q=>rs(q,G)),N=St();if(N!==null&&D.includes("webtransport")&&G?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${N} (learned on an earlier dial in this page)`),F.length===0){let q=C===null?`the default order (${Nr.join(", ")})`:`the room template's transports (${C.join(", ")||"none"})`;throw new u("misconfigured",`none of ${q}`+(v.length>0?`, narrowed to (${v.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let K=g.transportAttemptTimeoutMs??Zo,A=()=>g.deadlineAt===void 0?1/0:g.deadlineAt-t.now(),O=q=>n.signalingReady===void 0||q<=0?Promise.resolve(!0):n.signalingReady(q),Y=[],ne=[];for(let q of F){if(A()<Wr){o(`[gem] ${q} rung not tried: the reconnect budget is spent`);break}ne.length>0&&_.credentialExpiresAt-t.now()<Br&&(_=await c(g)),ne.push(q);let Un=!1,Wn=!1,et={attempts:0,waitedMs:0};for(;;){if(q==="webrtc"&&g.redial===!0){let Q=Math.min(Ur,A());await O(Q)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(Q)}ms; offering anyway`);}let Ri=Math.max(Math.min(K,A()),Wr);try{return b(g,_,q,await f(q,g,_,G,w,Ri),w)}catch(Q){let U=Q instanceof u?Q:new u("connection_failed",Q instanceof Error?Q.message:String(Q),{cause:Q});if(q==="webrtc"&&Vr(a,U),(U.reason==="credential_expired"||U.reason==="credential_reused")&&!Un){Un=!0,_=await c(g);continue}if(q==="webrtc"&&U.reason==="signaling_failed"&&U.platformCode===sn&&!Wn){Wn=!0;let ae=Math.min(Ur,A());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 O(ae))continue}if(U.reason==="join_rate_limited"){let ae=ns(et,Math.random,A());if(ae!==null){if(et.attempts+=1,et.waitedMs+=ae,o(`[gem] ${q} rung: the server is rate-limiting this player's joins; waiting ${Math.round(ae)}ms before presenting again (retry ${et.attempts} of ${zr.maxAttempts})`),await yt(t,ae,g.signal),g.signal?.aborted)throw new u("aborted","the caller aborted while waiting out a join rate limit");_.credentialExpiresAt-t.now()<Br&&(_=await c(g));continue}}if(ts.has(U.reason)||U.reason==="credential_expired"||q==="webrtc"&&Jr(U)){o(`[gem] ${q} rung failed (${U.reason}): ${Rt(U.cause??U)} \u2014 `+(ne.length<F.length?`falling through to ${F[ne.length]}`:"no rungs left")),Y.push(U);break}throw o(`[gem] ${q} rung refused the session (${U.reason}): ${U.message}`),U}}}let se=Y[Y.length-1];throw se===void 0?new u("timeout",`the reconnect budget ran out before any transport (${F.join(", ")}) could be tried`):new u(se.reason,`every transport tried (${ne.join(", ")}) failed; the last said: ${se.message}`,{cause:Y,platformCode:se.platformCode})}catch(_){throw J(w),_}};return {listClusterTargets:async(g={})=>ft({client:e,...g}),handleMatchEnded(g,v){let w=s.get(g);if(w!==void 0){s.delete(g);for(let _ of w)_(v);}},connect:(async(g={})=>{let v=g.signaling??i();return g.transports===void 0?p(g,v):M(g,g.transports,v)})}}var Nr=["webtransport","webrtc","websocket"],Zo=1e4,es=5e3,Ur=3e3,Wr=1e3,Br=1e4,ts=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function Jr(n){return n.platformCode!==void 0&&an.has(n.platformCode)}var zr={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function ns(n,e=Math.random,t=1/0){let r=zr;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 rs(n,e){return n==="webrtc"?e===null||e.webrtc!==false:e===null?false:n==="webtransport"?e.webtransport!==void 0&&wn():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||is(e.websocket.url)}function is(n){if(typeof n!="string")return false;let e;try{e=new URL(n).hostname.toLowerCase();}catch{return false}return mt(e)}function Tn(n){return {...n.timeoutMs===void 0?{}:{timeoutMs:n.timeoutMs},...n.pollIntervalMs===void 0?{}:{pollIntervalMs:n.pollIntervalMs},...n.signal===void 0?{}:{signal:n.signal}}}var os=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Vr(n,e){e instanceof u&&(!os.has(e.reason)&&!Jr(e)||n.report([{type:"connection_failures_total",value:1}]));}function ss(n,e,t,r,i,o,a,s,l,d){let m=false,c=()=>{m||ln(n,e.matchId,void 0);};o&&(t.addEventListener("close",c),a&&n.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,t.removeEventListener("close",c),s?.detach(),J(t),J(r),J(i));},f=b=>{if(!m){try{d?.(b);}catch{}p();}};return l.remember(e.matchId,f),{matchId:e.matchId,channel:t,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:s?.welcome??null,close(){l.forget(e.matchId,f),p();}}}function as(n){let e=n.matchSession.phase;return e!=="none"&&e!=="ended"}function Hr(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!==Fe)throw new u("unsupported_protocol",`match ${n.matchId} speaks '${n.protocol}', which a browser cannot connect. Only '${Fe}' 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 Kr(){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 J(n){try{n.close();}catch{}}function At(n,...e){let t={};for(let r of e)n[r]!==void 0&&(t[r]=n[r]);return t}var Ae=class{constructor(e){this.options=e;this.reporter=new ue({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,t,r){let i=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:t},r);return {credential:Pt(i.credential)??"",hostFingerprint:Pt(i.host_fingerprint)??"",hostEpoch:Et(i.host_epoch)??0,expiresAt:(Et(i.expires_at)??0)*1e3}}async turnLease(e,t,r){let i=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:t},r),o=[];for(let l of Array.isArray(i.ice_servers)?i.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(c=>typeof c=="string"&&c.length>0);m.length!==0&&o.push({urls:m,username:Pt(d.username)??"",credential:Pt(d.credential)??""});}let a=Et(i.expires_at),s=Et(i.ttl_seconds);return {iceServers:o,expiresAt:a!==void 0?a*1e3:Date.now()+(s??0)*1e3}}async kick(e,t,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:t},r);}async leave(e,t=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:t});}async telemetry(e,t){await this.reporter.post(e,t);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}};function Pt(n){return typeof n=="string"&&n.length>0?n:void 0}function Et(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}var ls=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=ls.has(t);}reason;retryable};var Tt=class{listeners=new Map;on(e,t){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(t),()=>this.off(e,t)}off(e,t){this.listeners.get(e)?.delete(t);}once(e,t){let r=this.on(e,((...i)=>{r(),t(...i);}));return r}emit(e,...t){let r=this.listeners.get(e);if(r)for(let i of [...r])i(...t);}clear(){this.listeners.clear();}};var ds=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function ge(n){let e=null;for(let t of n.split(/\r\n|\n/)){if(!t.startsWith("a=fingerprint:"))continue;let r=He(t.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function He(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 ds.test(r)?r:null}function Pe(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 In=5e3,cs=12e4+In,us=1024,ms=6e4,ps=1e4,Yr=64*1024,Xr=5;function It(n){let e=new Map,t=-1/0,r=null,i=(()=>{let s;try{s=new URL(`${n.baseUrl.replace(/\/+$/,"")}/oauth2/jwks`);}catch{return {ok:false,reason:"the configured API base is not a valid URL, so the JWKS endpoint cannot be reached. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}}return s.username!==""||s.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:s.href,shown:`${s.protocol}//${s.host}`}})(),o=()=>{let s=n.subtle??globalThis.crypto?.subtle;if(!s)throw new k("keys_unavailable","this environment has no WebCrypto, so a join credential cannot be verified. A page served over plain http on a non-loopback origin is the usual cause \u2014 crypto.subtle is only exposed in a secure context.");return s},a=async()=>{if(!i.ok)throw new k("keys_unavailable",i.reason);let s=n.fetch??((p,f)=>globalThis.fetch(p,f)),l;try{l=await s(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(ps)});}catch{throw new k("keys_unavailable",`the JWKS endpoint at ${i.shown} could not be reached \u2014 it timed out, refused a redirect, or the network failed.`)}if(!l.ok)throw new k("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let d;try{let p=await l.text();if(p.length>Yr)throw new k("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${Yr} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof k?p:new k("keys_unavailable",`the JWKS endpoint at ${i.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>Xr)throw new k("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${Xr} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=o();for(let p of m){let f=p;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 b=await c.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(f.kid,b);}catch{}}};return {async key(s){let l=e.get(s);if(l)return l;if(!i.ok)throw new k("keys_unavailable",i.reason);if(r)return await r,e.get(s)??null;let d=n.now();if(!Number.isFinite(d))throw new k("keys_unavailable","the clock supplied to the SDK returned a non-finite time, so the JWKS throttle cannot be evaluated. This is a configuration fault, not a server failure.");return d<t&&(t=-1/0),d-t<ms?null:(t=d,r??=a().finally(()=>{r=null;}),await r,e.get(s)??null)}}}var Ke=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>=us){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,t+cs),true}};function Zr(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(Zr(n)),t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?null:t}catch{return null}}async function Ct(n,e,t,r,i){let o=A=>{throw new k("peer_unauthenticated",`the peer's join credential is not usable: ${A}`)},a=n.split(".");a.length!==3&&o("it is not a three-part JWT");let[s,l,d]=a,m=Qr(s);m===null&&o("its header does not decode"),m.alg!=="RS256"&&o(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let c=m.kid;(typeof c!="string"||c.length===0)&&o("it names no key");let p=await t.key(c);p===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 b=new TextEncoder().encode(`${s}.${l}`),R;try{R=Zr(d);}catch{o("its signature does not decode");}await f.verify({name:"RSASSA-PKCS1-v1_5"},p,R,b)||o("its signature does not verify");let M=Qr(l);M===null&&o("its payload does not decode");let I=M,g=A=>typeof I[A]=="string"?I[A]:"",v=A=>typeof I[A]=="number"&&Number.isFinite(I[A])?I[A]:NaN;g("iss")!==i.issuer&&o("it was issued by someone else"),g("aud")!==`${i.issuer}/p2p-match`&&o("its audience is not this platform"),g("match_id")!==e.matchId&&o("it is for another match"),g("game_id")!==e.gameId&&o("it is for another game");let w=v("exp")*1e3,_=v("nbf")*1e3;(!Number.isFinite(w)||e.now>w+In)&&o("it has expired"),Number.isFinite(_)&&e.now<_-In&&o("it is not valid yet");let G=g("role");G!=="host"&&G!=="client"&&o("it names no usable role");let C=v("host_epoch");C!==e.hostEpoch&&o("it names a different host epoch");let D=He(g("fingerprint"));D===null&&o("its fingerprint claim is malformed"),Pe(D,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let F=He(g("host_fingerprint"));F===null&&o("its host fingerprint claim is malformed"),Pe(F,e.hostFingerprint)||o("it was issued against a different host certificate");let N=g("jti");N.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit(N,e.now)||o("it has already been used");let K=g("sub");return K.length===0&&o("it names no player"),{playerId:K.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:C,role:G,fingerprint:D,hostFingerprint:F,jti:N,expiresAt:w}}var he=32769;function Cn(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 Mn(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 On(n){let e=new ArrayBuffer(2),t=new DataView(e);return t.setUint8(0,3),t.setUint8(1,n),e}function Ln(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 ei(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 ti(n){switch(n){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var ni=3e4,Ee=class{constructor(e,t,r){this.localPlayerId=e;this.hostPlayerId=t,this.epoch=r;}localPlayerId;state="idle";epoch;hostPlayerId;kicked=new Set;startedAt=0;get currentState(){return this.state}get currentEpoch(){return this.epoch}get currentHostPlayerId(){return this.hostPlayerId}get isLocalHost(){return this.hostPlayerId===this.localPlayerId}isKicked(e){return this.kicked.has(e)}stalled(e){return this.state!=="idle"&&e-this.startedAt>3e4}apply(e,t){return !Number.isInteger(e.hostEpoch)||e.hostEpoch<0?{kind:"refused",why:`host epoch ${String(e.hostEpoch)} is not a whole number`}:e.hostEpoch===this.epoch?e.migrationComplete===true&&this.state!=="idle"?(this.state="idle",{kind:"completed"}):{kind:"duplicate"}:e.hostEpoch<this.epoch?{kind:"refused",why:`host epoch ${e.hostEpoch} is behind the current ${this.epoch}`}:e.hostPlayerId.length===0?{kind:"refused",why:"the migration named no new host"}:(this.kicked=new Set(e.kickedPlayerIds??[]),this.epoch=e.hostEpoch,this.hostPlayerId=e.hostPlayerId,this.startedAt=t,this.state=this.isLocalHost?"preparing":"reconnecting",{kind:"accepted",state:this.state})}complete(){this.state="idle";}};var Mt={reliable:{negotiated:true,id:0,ordered:true},ordered:{negotiated:true,id:1,ordered:true,maxRetransmits:0},unreliable:{negotiated:true,id:2,ordered:false,maxRetransmits:0}},Je=["reliable","ordered","unreliable"];function Ot(n){let e=globalThis.RTCPeerConnection;if(!e)throw new Error("[gem] this environment has no RTCPeerConnection. Pass `peerConnectionFactory` to connect against a stand-in, which is how this flow is tested outside a browser.");return new e({iceServers:n.iceServers,...n.certificates===void 0?{}:{certificates:n.certificates}})}async function Lt(){let n=globalThis.RTCPeerConnection;return n?.generateCertificate?n.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var ii=1,bs=3e4,oi=2e3,vs=5e3,si=6e4,_s=8,Dn=class{constructor(e=_s){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;}},ks=new Dn,ws=8,Rs=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),Te=class{constructor(e){this.options=e;this.keys=e.keys??It({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new Tt;links=new Map;replays=new Ke;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=ii+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??bs;this.credentialDeadline=this.options.clock.now()+t;let r=new Promise((s,l)=>{this.ready={resolve:s,reject:l};}),i=W(this.options.clusterTargetId);if(i!==void 0)try{let s=await this.options.api.turnLease(this.options.matchId,i,e);this.iceServers=s.iceServers,this.mark("turn leased");}catch(s){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${Gn(s)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let o=this.options.clock.setTimeout(()=>{this.fail(new k("timeout",`no usable P2P connection after ${t}ms. The parent relays signaling, so a silent failure here usually means the page is not putting frames on the socket.`));},t),a=()=>this.fail(new k("aborted","the caller aborted while connecting"));e?.aborted?a():e?.addEventListener("abort",a);try{await r;}finally{this.options.clock.clearTimeout(o),e?.removeEventListener("abort",a),this.ready=null;}}async kick(e){if(!this.isHost)throw new k("misconfigured","only the current host of this match can kick a peer");await this.options.api.kick(this.options.matchId,e);}async leave(){try{await this.options.api.leave(this.options.matchId);}catch{}this.close();}close(){if(!this.closed){this.closed=true,this.pendingOffers.clear();for(let e of [...this.links.values()])this.dropLink(e,"closed",false);this.options.signaling.close(),this.emitter.clear();}}report(e){this.options.api.telemetry(e).catch(()=>{});}notifyCandidatesDropped(e){this.emitter.emit("candidatesDropped",e);}handleSignal(e,t){this.closed||this.route(e,t).catch(r=>this.report_(r));}async route(e,t){switch(e){case "hello":return this.onHello(t);case "offer":return this.onOffer(t);case "answer":return this.onAnswer(t);case "ice":return this.onIce(t);case "peerLeft":return this.onPeerLeft(t);case "migration":return this.onMigration(t);case "matchEnded":return this.onMatchEnded(t);case "error":return this.onSignalingError(t);default:return}}async onHello(e){let t=$(e.playerId),r=$(e.hostPlayerId),i=Gt(e.hostEpoch);if(!(t===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=t,this.migration===null&&(this.migration=new Ee(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,ii),i=await r.connection.createOffer();await r.connection.setLocalDescription(i);let o=r.connection.localDescription?.sdp??i.sdp;if(!o)throw new k("invalid_sdp","the browser produced an offer with no SDP");ie(o,"offer"),this.refuseMedia(o,"offer"),this.options.signaling.offer(o,e),this.mark("offer sent"),this.fetchCredential().catch(a=>this.report_(a));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,i=r===void 0?null:ge(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??ks,a=()=>this.closed||e!==this.credentialGeneration,s=vs;for(;;){let l=o.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,a))return;o.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,i);if(a())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(a())return;let m=d.status,c;if(m===409)c=oi;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?c=p*1e3:(c=s,s=Math.min(s*2,si)),c=Math.min(Math.max(c,oi),si);}else throw d;if(!await this.waitForCredential(c,a))return}}}async waitForCredential(e,t){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!t())}async onOffer(e){let t=$(e.fromPlayerId),r=$(e.sdp);if(t===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(t),this.pendingOffers.size>=ws){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(t,e);return}if(!this.isHost||this.migration.isKicked(t)===true)return;let i=$(e.sessionId);if(i!==null&&this.answeredSessions.get(t)===i)return;ie(r,"offer"),this.refuseMedia(r,"offer");let o=ge(r);if(o===null)throw new k("invalid_sdp",`the offer from ${t} carries no usable fingerprint`);this.mark("offer received"),i!==null&&this.answeredSessions.set(t,i);let a=this.links.get(t);a&&this.dropLink(a,"resignalled",false);let s=this.openLink(t,this.nextPeerId++);s.remoteFingerprint=o,await s.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(s);let l=await s.connection.createAnswer();await s.connection.setLocalDescription(l);let d=s.connection.localDescription?.sdp??l.sdp;if(!d)throw new k("invalid_sdp","the browser produced an answer with no SDP");ie(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(t,d,s.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let t=$(e.fromPlayerId),r=$(e.sdp);if(t===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||t!==this.hostPlayerId)return;ie(r,"answer"),this.refuseMedia(r,"answer");let o=ge(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:Pe(t.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new k("peer_unauthenticated","the host's DTLS certificate is not the one the platform attested for this match. Refusing before the handshake, so no credential is presented.")),this.dropLink(e,"host_fingerprint_mismatch",false),false)}maybeAuthenticate(){if(this.isHost)return;let e=this.links.get(this.hostPlayerId);if(!e||e.remoteFingerprint===null||e.connection.remoteDescription!==null)return;let t=e.pendingAnswer;t!==void 0&&this.hostVerified(e)&&this.applyAnswer(e,t).catch(r=>this.report_(r));}async applyAnswer(e,t){this.mark("host verified"),e.pendingAnswer=void 0,await e.connection.setRemoteDescription({type:"answer",sdp:t}),this.flushCandidates(e);}async onIce(e){let t=$(e.fromPlayerId),r=$(e.candidate);if(t===null||r===null)return;let i=this.links.get(t);if(!i)return;let o=$(e.sdpMid),a=Gt(e.sdpMLineIndex)??Gt(e.sdpMLineIndexAlt),s={candidate:r,...o===null?{}:{sdpMid:o},...a===null?{}:{sdpMLineIndex:a}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(s);return}await i.connection.addIceCandidate(s);}onPeerLeft(e){let t=$(e.playerId);if(t===null)return;let r=$(e.reason)??"left";if(t===this.localPlayerId){this.fail(new k("kicked",`this player was removed from the match (${r})`)),this.close();return}let i=this.links.get(t);i&&this.dropLink(i,r,true);}async onMigration(e){let t=$(e.hostPlayerId),r=Gt(e.hostEpoch);if(t===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:t,hostEpoch:r,...$(e.reason)===null?{}:{reason:$(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(o=>typeof o=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(i.kind!=="duplicate"){if(i.kind==="completed"){this.emitter.emit("hostChanged",t,r);return}if(i.kind==="refused"){this.report_(new k("migration_failed",i.why));return}for(let o of [...this.links.values()])this.dropLink(o,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",t,r),i.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration(),await this.offerToHost("full_reconnect");}}watchMigration(){let e=this.hostEpoch;this.options.clock.setTimeout(()=>{this.closed||this.migration===null||this.migration.currentEpoch===e&&this.migration.stalled(this.options.clock.now())&&this.reportedStallEpoch!==e&&(this.reportedStallEpoch=e,this.report_(new k("migration_failed",`host migration to epoch ${e} did not complete. The elected host never acknowledged it, so the platform is still holding the match in migration.`)));},31e3);}onMatchEnded(e){let t=$(e.reason)??"ended";this.ended=t,this.emitter.emit("matchEnded",t),this.ready!==null&&this.fail(new k("match_ended",`the match ended: ${t}`)),this.close();}onSignalingError(e){let t=$(e.code)??"unknown",r=$(e.message)??"the platform refused a signaling message";this.report_(new k("signaling_failed",`${t}: ${r}`));}openLink(e,t){let i=(this.options.peerConnectionFactory??Ot)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let p of Je){let f=i.createDataChannel(p,Mt[p]);f.binaryType="arraybuffer",o[p]=f;}let a={playerId:e,assignedPeerId:t,connection:i,channels:o,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},s=p=>{let f=p.candidate;f?.candidate&&this.options.signaling.candidate(e,f.candidate,f.sdpMid??void 0,f.sdpMLineIndex??void 0);},l=()=>this.onIceState(a),d=()=>this.onConnectionState(a),m=p=>{this.onHandshakeMessage(a,p.data).catch(f=>this.report_(f));},c=()=>{this.onReliableOpen(a).catch(p=>this.report_(p));};return i.addEventListener("icecandidate",s),i.addEventListener("iceconnectionstatechange",l),i.addEventListener("connectionstatechange",d),o.reliable.addEventListener("open",c),o.reliable.addEventListener("message",m),a.detachHandshake=()=>{o.reliable.removeEventListener("open",c),o.reliable.removeEventListener("message",m);},a.detachAll=()=>{a.detachHandshake(),i.removeEventListener("icecandidate",s),i.removeEventListener("iceconnectionstatechange",l),i.removeEventListener("connectionstatechange",d);},this.links.set(e,a),a}flushCandidates(e){let t=e.pendingCandidates;e.pendingCandidates=[];for(let r of t)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let t=this.credential;if(t===null)throw new k("peer_unauthenticated","the channel opened before the platform issued a join credential, so there is nothing to present");if(this.options.clock.now()>=t.expiresAt)throw new k("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(Cn({jwt:t.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,t){if(!(t instanceof ArrayBuffer))return;let r=Ln(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(ti(r.reason),ei(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=ge(e.connection.localDescription?.sdp??"");if(i===null||e.remoteFingerprint===null){this.refuseLink(e,1,"fingerprint_unavailable","this connection's DTLS fingerprints could not be read from its SDP, so no credential can be checked against it");return}let o;try{o=await Ct(t,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:i,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(a){let s=a instanceof k&&a.reason==="keys_unavailable";this.refuseLink(e,s?131:1,s?"keys_unavailable":"credential_invalid",Gn(a)),s&&this.fail(a);return}if(o.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${o.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(o.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(Mn({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(On(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 Je)ai(e.channels[i]);ai(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",Gn(e),{cause:e}));}count(e){this.counted||!Rs.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,t){if(xt(e))throw new k("media_refused",`the ${t} carries an active audio or video section. This path carries data channels only; voice belongs to the platform voice service, and gem-api age-gates relayed SDP that proposes media.`)}mark(e){this.options.boot?.mark(e);}sleep(e){return new Promise(t=>this.options.clock.setTimeout(t,e))}warn(e){let t=this.options.log;t!==null&&(t??(r=>console.warn(r)))(`[gem] ${e}`);}get endedReason(){return this.ended}};function $(n){return typeof n=="string"&&n.length>0?n:null}function Gt(n){return typeof n=="number"&&Number.isInteger(n)?n:null}function Gn(n){return n instanceof Error?n.message:String(n)}function ai(n){try{n.close();}catch{}}var Ss=100,xs=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??Ss)){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??xs));}};var qn="webrtc_p2p";function As(n){let e=new Ae({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=W(r.clusterTargetId),o=i??W(await n.resolveClusterTarget?.());n.rooms.isHost&&n.rooms.currentMatch===null&&n.rooms.currentRoom?.matchId===void 0&&await n.rooms.startMatch({...i===void 0?{}:{clusterTargetId:i},...r.signal===void 0?{}:{signal:r.signal}});let a=await n.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(a.protocol!==qn)throw new k("unsupported_protocol",`match ${a.matchId} speaks '${a.protocol}', not '${qn}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let s=new Ie({bridge:n.bridge,matchId:a.matchId,clock:n.clock}),l=new Te({api:e,clock:n.clock,matchId:a.matchId,gameId:n.gameId(),baseUrl:typeof n.baseUrl=="function"?n.baseUrl():n.baseUrl,signaling:s,...o===void 0?{}:{clusterTargetId:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await Lt(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...n.boot===void 0?{}:{boot:n.boot},...n.log===void 0?{}:{log:n.log}});s.onDropped(d=>l.notifyCandidatesDropped(d)),t.set(a.matchId,l),l.on("matchEnded",()=>t.delete(a.matchId));try{await l.start(r.signal);}catch(d){throw t.delete(a.matchId),l.close(),d}return l}}}function li(n){return typeof n=="string"&&n.trim()!==""}function di(n,e){return li(n)?n.trim():li(e)?e:null}function ze(n){let e=String(n);if(!/^[A-Za-z0-9_.-]{1,128}$/.test(e)||e==="."||e==="..")throw new TypeError(`${JSON.stringify(e)} is not a usable path segment \u2014 it is interpolated into a URL`);return encodeURIComponent(e)}async function ci(n,e,t){let r=`/v1/games/${ze(n.gameId())}/matchmaking/tickets/${ze(e)}`;return n.client.delete(r,t?.signal)}async function ui(n,e,t){let r=`/v1/games/${ze(n.gameId())}/matchmaking/tickets`;return n.client.post(r,e,t?.signal)}async function mi(n,e,t){let r=`/v1/games/${ze(n.gameId())}/matchmaking/tickets/${ze(e)}/heartbeat`;return n.client.post(r,void 0,t?.signal)}function Ye(n){let e=n??{};if(typeof e.ticket_id!="string"||e.ticket_id.length===0)throw new Error("[gem] a matchmaking-ticket response carried no id");let t=e.heartbeat_interval_seconds;return {id:e.ticket_id,status:typeof e.status=="string"?e.status:"queued",...typeof e.reason=="string"?{reason:e.reason}:{},...typeof e.game_room_id=="string"?{roomId:e.game_room_id}:{},partySize:typeof e.party_size=="number"?e.party_size:1,queuedAt:pi(e.queued_at),expiresAt:pi(e.expires_at),heartbeatIntervalSeconds:typeof t=="number"&&t>0?t:0}}function pi(n){if(typeof n!="string")return 0;let e=Date.parse(n);return Number.isFinite(e)?Math.floor(e/1e3):0}var Ps=3,gi=1e3,Dt=class{constructor(e){this.options=e;this.snapshot=e.first;let t=new Promise((o,a)=>{this.resolve=o,this.reject=a;});t.catch(()=>{});let r=()=>this.snapshot,i=()=>this.status;this.ticket={get id(){return r().id},get status(){return i()},get partySize(){return r().partySize},get queuedAt(){return r().queuedAt},get expiresAt(){return r().expiresAt},outcome:t,cancel:()=>(this.requestCancel(),t)};}options;ticket;snapshot;status="queued";timer=null;busy=false;again=false;cancelRequested=false;soon=false;misses=0;settled=false;resolve;reject;start(){this.apply(this.snapshot);}poke(){this.settled||(this.soon=true,!this.busy&&(this.clearTimer(),this.tick()));}abandon(e=false){this.settled||(this.options.cancel(this.snapshot.id,e).catch(()=>{}),this.settle({status:"cancelled",reason:"requested"}));}requestCancel(){this.settled||(this.cancelRequested=true,this.trigger());}trigger(){if(this.busy){this.again=true;return}this.clearTimer(),this.tick();}schedule(e=false){if(this.settled)return;this.clearTimer();let t=e?gi:Math.max(gi,this.snapshot.heartbeatIntervalSeconds*1e3);this.timer=this.options.clock.setTimeout(()=>{this.timer=null,this.tick();},t);}clearTimer(){this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null);}async tick(){if(this.settled||this.busy)return;this.busy=true,this.again=false;let e=null,t=null;try{e=this.cancelRequested?await this.options.cancel(this.snapshot.id):await this.options.heartbeat(this.snapshot.id);}catch(r){t=r;}if(this.busy=false,!this.settled){if(e===null){this.missed(t);return}this.misses=0,await this.apply(e);}}missed(e){if(e instanceof j&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<Ps){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let t=e instanceof j&&e.code==="matchmaking_unavailable";this.settle({status:t?"unavailable":"lost"});}async apply(e){if(this.snapshot=e,e.status==="queued"){this.next();return}if(e.status==="matched"){await this.seat(e);return}e.status==="expired"?this.settle({status:"expired",reason:e.reason??"timed_out"}):e.status==="cancelled"?this.settle({status:"cancelled",reason:e.reason??"requested"}):this.settle({status:"failed",reason:e.reason??e.status});}next(){if(this.again){this.again=false,this.tick();return}let e=this.soon;this.soon=false,this.schedule(e);}async seat(e){if(e.roomId===void 0){this.fail(new Error("[gem] a matched matchmaking ticket named no game room"));return}this.busy=true;try{let t=await this.options.seat(e.roomId);this.busy=!1,this.settle({status:"matched",room:t});}catch(t){this.busy=false,this.fail(t);}}settle(e){this.settled||(this.finish(e.status),this.resolve(e));}fail(e){this.settled||(this.finish("matched"),this.reject(e));}finish(e){this.settled=true,this.status=e,this.clearTimer(),this.options.onSettled();}};function oe(n){return typeof n=="string"&&n!==""?n:void 0}var Es=new Set(["localhost","127.0.0.1","[::1]"]);function qt(n){let e=oe(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:"&&Es.has(t.hostname)))return e}function Ts(n){if(!Array.isArray(n))return [];let e=[];for(let t of n){let r=t??{},i=oe(r.item_id),o=qt(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function hi(n){let e=n??{},t=oe(e.player_id),r=oe(e.display_name),i=oe(e.discriminator),o=oe(e.display_tag),a=oe(e.avatar_icon_id),s=qt(e.avatar_icon_url),l=oe(e.avatar_3d_id),d=qt(e.avatar_3d_model_url),m=qt(e.avatar_3d_icon_url);return {...t===void 0?{}:{playerId:t},...r===void 0?{}:{displayName:ce(r)},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:ce(o)},...a===void 0?{}:{avatarIconId:a},...s===void 0?{}:{avatarIconUrl:s},...l===void 0?{}:{avatar3dId:l},...d===void 0?{}:{avatar3dModelUrl:d},...m===void 0?{}:{avatar3dIconUrl:m},badges:Ts(e.badges)}}function $t(n){if(typeof n!="object"||n===null)return;let e={};for(let[t,r]of Object.entries(n)){let i=$n(r);i!==void 0&&(e[t]=i);}return e}function Ft(n){if(Array.isArray(n))return n.map(Is).filter(e=>!!e)}function $n(n){if(Fn(n)||Array.isArray(n)&&n.every(Fn))return n}function Fn(n){return typeof n=="string"||typeof n=="boolean"||typeof n=="number"&&Number.isFinite(n)}function Is(n){let e=n??{};if(typeof e.name!="string"||e.name.length===0)return null;let t=$n(e.fixed),r=$n(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",Cs(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(Fn)?{allowed:e.allowed}:{},...Ce("min",Xe(e.min)),...Ce("max",Xe(e.max)),...Ce("minItems",Xe(e.min_items)),...Ce("maxItems",Xe(e.max_items)),...Ce("maxLength",Xe(e.max_length))}}function Cs(n){return typeof n=="string"&&n.length>0?n:void 0}function Xe(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function Ce(n,e){return e===void 0?{}:{[n]:e}}function z(n){let e=n??{},t=E(e.id)??E(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(jn):[];return {id:t,gameId:E(e.game_id)??"",name:E(e.name)??"",status:E(e.status)??"open",hostPlayerId:E(e.host_player_id)??"",maxPlayers:X(e.max_players)??0,memberCount:X(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...H("joinCode",E(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...H("roomArgs",$t(e.room_args)),...H("roomArgsTemplate",Ft(e.room_args_template)),gameChannel:E(e.game_channel)??"release",...H("region",E(e.region)),...H("clusterTargetId",E(e.cluster_target_id)),selfHosted:e.self_hosted===true,...H("matchId",E(e.match_id)),version:X(e.version)??0,...H("templateId",E(e.template_id)),...H("templateSlug",E(e.template_slug)),roomType:E(e.game_room_type)??"Standard",...H("transports",Ue(e.transports)??void 0),createdAt:X(e.created_at)??0,updatedAt:X(e.updated_at)??0,...H("startedAt",X(e.started_at))}}function jn(n){let e=n??{};return {...hi(e),playerId:E(e.player_id)??"",isReady:e.is_ready===true,role:E(e.role)??"member",joinedAt:X(e.joined_at)??0,...H("groupId",E(e.group_id)),...H("platform",E(e.platform))}}function Qe(n){let e=n??{};return {id:E(e.id)??E(e.game_room_id)??"",gameId:E(e.game_id)??"",name:E(e.name)??"",status:E(e.status)??"open",hostPlayerId:E(e.host_player_id)??"",maxPlayers:X(e.max_players)??0,memberCount:X(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:E(e.game_channel)??"release",roomType:E(e.game_room_type)??"Standard",createdAt:X(e.created_at)??0}}function E(n){return typeof n=="string"&&n.length>0?n:void 0}function X(n){return typeof n=="number"&&Number.isFinite(n)?n:void 0}function H(n,e){return e===void 0?{}:{[n]:e}}var Me=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(Qe),...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(Qe)}))}create(e,t,r){return Os(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},...Ze(t)},e.signal).then(z)}get(e,t){return this.options.client.get(this.roomV2(e),t).then(z)}join(e,t,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...t.partyId===void 0?{}:{party_id:t.partyId},...Ze(r)},t.signal).then(z)}joinByCode(e,t,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...t.partyId===void 0?{}:{party_id:t.partyId},...Ze(r)},t.signal).then(z)}quickJoin(e,t,r=[]){let i=this.asksSelfHosted(e.partyId);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},...Ms(e.templateSlugs,i),...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},...i?{self_hosted:true}:{},...Ze(t)},e.signal).then(z)}createTicket(e,t,r=[]){return ui(this.generated(),{templates:e.templateSlugs.map(i=>({template_slug:i})),...r.length===0?{}:{cluster_target_ids:[...r]},...e.partyId===void 0?{}:{party_id:e.partyId},...Ze(t)},{...e.signal===void 0?{}:{signal:e.signal}}).then(Ye)}heartbeatTicket(e){return mi(this.generated(),e).then(Ye)}cancelTicket(e,t=false){return t?this.options.client.delete(`/v1/games/${encodeURIComponent(this.options.gameId())}/matchmaking/tickets/${encodeURIComponent(e)}`,void 0,{keepalive:true}).then(Ye):ci(this.generated(),e).then(Ye)}leave(e,t,r,i=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:t},r,{keepalive:i}).then(()=>{})}asksSelfHosted(e){return e===void 0&&this.options.selfHosted?.()===true}close(e,t){return this.options.client.delete(this.roomV1(e),t).then(()=>{})}update(e,t){return this.options.client.patch(this.roomV2(e),{...t.name===void 0?{}:{name:t.name},...t.maxPlayers===void 0?{}:{max_players:t.maxPlayers},...t.isPublic===void 0?{}:{is_public:t.isPublic},...t.settings===void 0?{}:{settings:t.settings},...t.roomArgs===void 0?{}:{room_args:t.roomArgs}},t.signal).then(z)}setReady(e,t,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:t},r).then(z)}kick(e,t,r){return this.options.client.post(`${this.roomV1(e)}/kick/${encodeURIComponent(t)}`,{},r).then(()=>this.get(e,r))}transferHost(e,t,r){return this.options.client.post(`${this.roomV2(e)}/transfer/${encodeURIComponent(t)}`,{},r).then(z)}leaveMatch(e,t){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:t}).then(()=>{})}generated(){return {client:this.options.client,gameId:this.options.gameId}}baseV2(){return `/v2/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function Ms(n,e){return n===void 0?{}:{templates:(e?n.slice(0,1):n).map(r=>({template_slug:r}))}}function Ze(n){return {platform:n.platform,game_version:n.gameVersion,engine_version:n.engineVersion}}function Os(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 Oe=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;}};var jt=class{constructor(e){this.options=e;let t=e.first,r=new Promise(s=>{this.resolve=s;}),i=()=>this.status;this.ticket={id:t.ticketId,get status(){return i()},partySize:t.partySize??0,queuedAt:t.queuedAt??0,expiresAt:t.expiresAt??0,outcome:r};let o=t.queuedAt!==void 0&&t.expiresAt!==void 0?(t.expiresAt-t.queuedAt)*1e3:9e5,a=Math.min(Math.max(o,0),9e5)+5e3;this.timer=e.clock.setTimeout(()=>{this.timer=null,this.end({status:"lost"});},a);}options;ticket;status="queued";timer=null;resolve;get id(){return this.ticket.id}end(e){this.status==="queued"&&(this.status=e.status,this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null),this.options.onSettled(),this.resolve(e));}};function Ls(n,e){return Math.min(e,500*2**Math.max(0,n-1))}var Gs=1e3,Ds=3e3,qs=6e4,$s=2,fi=new Set(["game_room_closed","game_room_gone"]),Fs=12e4,js=5e3,Ns=new Set(["invalid_cluster_target","capacity_unavailable"]),Us=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function ki(n){return new Nn(n)}var Nn=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new Me({client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new Oe;api;room=null;ticketWatch=null;queueing=false;partyWatch=null;heldQueued=null;queuedFromRoomId=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create"),this.assertNotQueued("create");let t=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("create",async()=>{let o=await t;return this.api.create(r,this.version("create"),o[0]).catch(async a=>{let s=await this.afterRefusedClusters(a,o);if(s[0]===void 0||s[0]===o[0])throw a;return this.api.create(r,this.version("create"),s[0])})});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,t={}){this.assertNotInRoom("join"),this.assertNotQueued("join");let r=await this.attachParty(t),i=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async joinByCode(e,t={}){this.assertNotInRoom("joinByCode"),this.assertNotQueued("joinByCode");let r=await this.attachParty(t),i=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async quickJoin(e){this.assertNotInRoom("quickJoin"),this.assertNotQueued("quickJoin"),Vs(e);let t=this.clusterTargets(),r=await this.attachParty(e),i=a=>this.api.quickJoin(r,this.version("quickJoin"),a).catch(s=>this.retryPastStaleMembership(s,r,a)),o=await this.run("quickJoin",async()=>{let a=await t;return i(a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||_i(l,a))throw s;return i(l)})});return this.enter(o,"joined"),this.askForLocalServer(o),o}async queueForMatch(e){this.assertNotQueued("queueForMatch"),Bs(e?.templateSlugs),this.queueing=true;try{let t=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("queueForMatch",async()=>{let a=await t;return this.api.createTicket(r,this.version("queueForMatch"),a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||_i(l,a))throw s;return this.api.createTicket(r,this.version("queueForMatch"),l)})});this.heldQueued?.ticketId===i.id&&(this.heldQueued=null),this.partyWatch?.end({status:"lost"});let o=new Dt({clock:this.options.clock,first:i,heartbeat:a=>this.track(this.api.heartbeatTicket(a)),cancel:(a,s)=>this.track(this.api.cancelTicket(a,s)),seat:a=>this.enterMatchedRoom(a),onSettled:()=>{this.ticketWatch===o&&(this.ticketWatch=null),this.retuneSeatWatch();}});return this.ticketWatch=o,this.retuneSeatWatch(),o.start(),o.ticket}finally{this.queueing=false;let t=this.heldQueued;this.heldQueued=null,t!==null&&this.showPartyTicket(t);}}async enterMatchedRoom(e){let t=await this.run("queueForMatch",()=>this.api.get(e));return this.disposed?t:(this.room!==null&&this.room.id!==t.id&&(this.queuedFromRoomId=this.room.id,this.exit()),this.room===null&&this.enter(t,"joined"),this.room?.id===t.id?this.room:t)}async list(e={}){let t=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",t),t}async myRooms(e){let t=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",t.rooms),t.rooms}async leave(e={}){let t=this.requireRoom("leave"),r=e.keepalive===true,i=()=>this.run("leave",()=>this.api.leave(t.id,e.asGroup!==false,e.signal,r));if(r){let o=i();this.track(this.notifyLeavingMatch({keepalive:true})),await o;}else await this.notifyLeavingMatch(),await i();this.exit(),this.emitter.emit("left");}async leaveAll(e){let t=await this.myRooms(e),r=[];for(let i of t)try{await this.run("leaveAll",()=>this.api.leave(i.id,!0,e)),r.push(i.id),this.room?.id===i.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let t=this.requireRoom("close");await this.run("close",()=>this.api.close(t.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let t=this.room;if(!t)return null;let r;try{r=await this.track(this.api.get(t.id,e));}catch(i){if(i instanceof j&&i.reason==="not_found"){let o=this.heldMatchId;if(o!==null){let a=await this.askWhyEnded(o,e);this.endMatch(o,a??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",i),i}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let t=this.room,r=this.heldMatchId;if(!(t===null||r===null)&&!(t.status==="in_game"&&t.matchId===r)&&!(t.matchId!==void 0&&t.matchId!==r)&&this.settling!==r){this.settling=r;try{let i=await this.askWhyEnded(r,e);i!==null&&this.endMatch(r,i,t.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,t){let r=this.room;if(r===null)return null;let i=this.takeHint(e),o;try{o=await this.track(this.onceGameIdKnown(()=>nn({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e),...t===void 0?{}:{signal:t}})));}catch(a){return a instanceof j&&a.reason==="not_found"?i??null:(this.reportError("reconcile",a),null)}return o===null?null:o.status==="ready"?(this.seenMatches.add(e),null):o.status==="failed"?(this.settleFailed(o.matchId,o.reason),null):o.reason==="unknown"&&i!==null?i:o.reason}takeHint(e){let t=this.pendingHint;if(t===null||t.matchId!==void 0&&t.matchId!==e||(this.pendingHint=null,t.reason===void 0))return null;let r=Se(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=W(t.clusterTargetId),o=i??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),a=o??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let s=(m,c)=>gt({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...i===void 0?{nextClusterTarget:()=>this.nextCluster(c)}:{},retry:{...t.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),t.retry?.onWaiting?.(p);}},...t.signal===void 0?{}:{signal:t.signal}}),l=()=>s(o,[a]).catch(async m=>{if(i!==void 0||!vi(m))throw m;let c=await this.nextCluster([a],true);if(c===void 0)throw m;return s(c,[a,c])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new 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 ht({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e,matchId:t,version:this.version("pollMatchStatus"),knownToExist:this.seenMatches.has(t),...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.pollIntervalMs===void 0?{}:{pollIntervalMs:r.pollIntervalMs},...r.signal===void 0?{}:{signal:r.signal}})}settleOutcome(e){if(e.status==="failed")throw this.settleFailed(e.matchId,e.reason),new u("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!fi.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(!Nt()){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<Gs){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(Ls(e.attempt,t.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!Nt()){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(()=>nn({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,!fi.has(i.reason)),this.track(this.reconcile().catch(()=>{}));return}if(i?.status==="failed"){this.abandonReconnect(e.matchId,i.reason),this.settleFailed(i.matchId,i.reason);return}if(i?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(i);let o;try{o=await t.redial(e.matchId,e.deadlineAt);}catch(a){this.reportError("reconcile",a),o="failed";}if(e.done||this.reconnect!==e)return;if(o==="closed"){this.finishReconnect();return}if(o==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let t=this.session.phase==="suspended";this.session={phase:"connected",matchId:e};let r=this.reconnect;r!==null&&r.matchId===e?(this.finishReconnect(),this.emitter.emit("matchReconnected",{matchId:e,attempt:r.attempt})):t&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new 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 currentTicket(){return this.ticketWatch?.ticket??null}get partyTicket(){return this.partyWatch?.ticket??null}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}on(e,t){let r=this.emitter.on(e,t);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,t){this.emitter.off(e,t);}once(e,t){return this.emitter.once(e,t)}handleRoomEvent(e){if(this.ticketWatch!==null&&e.event!=="version_stale"&&e.roomId!==this.room?.id&&this.ticketWatch.poke(),this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let t=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(t).catch(()=>{}));}handleAutoStartFailed(e,t){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(t);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:t,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let i=new AbortController;this.autoStartRetry=i,this.track(this.requestStart({signal:i.signal},false).then(()=>{},o=>{i.signal.aborted||this.reportError("startMatch",o);}).finally(()=>{this.autoStartRetry===i&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!Ns.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.watchingSeats&&this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}}handleTicketEvent(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}if(this.queueing){e.event==="queued"?this.heldQueued=e:this.heldQueued?.ticketId===e.ticketId&&(this.heldQueued=null);return}if(e.event==="queued"){this.showPartyTicket(e);return}if(e.event==="matched"){e.roomId!==void 0&&this.handleSeated(e.roomId),this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:"matched"});return}this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:e.event,reason:e.reason??e.event});}}showPartyTicket(e){if(this.disposed||this.partyWatch?.id===e.ticketId)return;this.partyWatch?.end({status:"lost"});let t=new jt({clock:this.options.clock,first:e,onSettled:()=>{this.partyWatch===t&&(this.partyWatch=null);}});this.partyWatch=t,this.emitter.emit("partyQueued",t.ticket);}async reconcileSeats(){if(this.disposed||!this.watchingSeats||this.ticketWatch!==null)return;let e;try{e=await this.myRooms();}catch{return}let t=new Set;for(let r of e)r.status!=="closed"&&(t.add(r.id),r.id!==this.room?.id&&(this.reported.has(r.id)||await this.reportSeat(r.id).catch(()=>{})));for(let r of [...this.reported])t.has(r)||this.reported.delete(r);}async reportSeat(e){let t=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||t===null||!r.members.some(i=>i.playerId===t)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.partyWatch?.end({status:"matched"}),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.ticketWatch===null&&this.seatPollMs>0&&Nt())){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(),!!Nt())){if(this.room!==null){let r=this.reconnect?.parked??null;r!==null&&this.reconnect!==null?(this.reconnect.parked=null,this.track(r())):this.track(this.reconcile().catch(()=>{}));return}if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of yi)e.addEventListener(r,this.visibilityListener);let t=globalThis.document;typeof t?.addEventListener=="function"&&t.addEventListener("resume",this.visibilityListener);}startPolling(e){this.stopPolling(),!this.disposed&&(this.pinnedIntervalMs=e??null,this.polling=true,this.schedule());}stopPolling(){this.pollHandle!==null&&(this.options.clock.clearTimeout(this.pollHandle),this.pollHandle=null),this.polling=false,this.pollIntervalMs=null;}async settled(){for(let e=0;e<20&&this.inFlight.length>0;e++){let t=this.inFlight;this.inFlight=[],await Promise.allSettled(t);}}dispose(){if(this.disposed=true,this.ticketWatch?.abandon(),this.heldQueued=null,this.partyWatch?.end({status:"lost"}),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 yi)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??js}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=di(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 jr({...t,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return be(await this.options.resolveClusterTargets());let e=W(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,t){return !vi(e)||t.length===0?[]:be(await this.options.refreshClusterTargets?.(t)??[])}async nextCluster(e,t=false){let r=a=>a.find(s=>!e.includes(s)),i=await this.clusterTargets(),o=r(i);return o!==void 0||!t?o:r(be(await this.options.refreshClusterTargets?.(i)??[]))}async attachParty(e){if(e.partyId!==void 0)return e;let t=this.options.resolveParty;if(t===void 0)return e;let r=await t();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,t,r){if(!(e instanceof j)||e.reason!=="conflict"||!Us.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new j(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and \`recoverStaleMembership\` is off, so nothing cleared it. A membership that outlived its page is visible only through myRooms(); leaveAll() is what clears it.`,e.retryAfterSeconds,e.code);let i;try{i=await this.leaveAll(t.signal);}catch{throw new j(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery could not list the rooms it would have cleared, so nothing was tried and the refusal stands. That is the listing failing, not a room refusing to be left: retry once the connection is back. myRooms() shows what is held.`,e.retryAfterSeconds,e.code)}if(i.length===0)throw new j(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery cleared nothing, so the refusal stands. myRooms() shows what is held. A room this player was seated in as a party member cannot be cleared from here at all \u2014 only the leader of a party may take it out of a room \u2014 so a member joins by adopting that room, myRooms() then join(), rather than quick-joining.`,e.retryAfterSeconds,e.code);return this.api.quickJoin(t,this.version("quickJoin"),r)}assertNotInRoom(e){if(this.room!==null)throw new 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.`)}assertNotQueued(e){if(!(this.ticketWatch===null&&!this.queueing))throw new u("misconfigured",`${e} refused: this player is waiting on a matchmaking ticket, which will seat them in a room of its own. Cancel it first \u2014 currentTicket.cancel() \u2014 or wait for its outcome.`)}requireRoom(e){if(this.room===null)throw new 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 j?{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.queuedFromRoomId===e.id&&(this.queuedFromRoomId=null),this.abortFollow(),this.autoStartRetried=false,this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(t,e),this.adoptMatch(e),this.options.poll!==false&&this.startPolling(),this.retuneSeatWatch();}exit(){this.room=null,this.abortFollow(),this.abortAutoStartRetry(),this.autoStartRetried=false,this.finishReconnect(),this.session.phase!=="ended"&&(this.session={phase:"none"}),this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.stopPolling(),this.retuneSeatWatch();}apply(e){let t=this.room;if(t===null||t.id!==e.id)return;let r=new Map(t.members.map(s=>[s.playerId,s])),i=new Map(e.members.map(s=>[s.playerId,s])),o=this.playerId();for(let s of i.keys())r.has(s)||this.emitter.emit("memberJoined",s);for(let s of r.keys())if(!i.has(s)){if(s===o){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",s);}for(let[s,l]of i){let d=r.get(s);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",s,l.isReady);}t.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let a=Ws(t,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),a&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let t=this.heldMatchId;t!==null&&t!==e&&this.endMatch(t,"replaced",true),this.session={phase:"starting",matchId:e},this.autoStartRetried=false,this.emitter.clearRetained(),this.emitter.emit("matchAllocationStarted",e),this.followMatch();}followMatch(){if(this.autoFollow===false)return;let e=this.room,t=this.heldMatchId;if(e===null||t===null||this.followAbort!==null&&this.followingMatchId===t)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=t,this.track(this.onceGameIdKnown(()=>this.chase(e.id,t,{signal:r.signal})).then(i=>{if(!r.signal.aborted)try{this.settleOutcome(i);}catch{}}).catch(i=>{r.signal.aborted||this.reportError("pollMatchStatus",i);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let t=this.heldMatchId;if(t!==null)return Promise.resolve(t);let r=e.timeoutMs??Fs;return new Promise((i,o)=>{let a=c=>{s(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),c();},s=this.emitter.on("matchAllocationStarted",c=>a(()=>i(c))),l=this.emitter.on("matchFailed",(c,p)=>a(()=>o(new u("allocation_failed",`match ${c} did not come up: ${p}`)))),d=()=>a(()=>o(new u("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>a(()=>o(new u("timeout",`no match was allocated for room ${this.room?.id??"(none)"} within ${r}ms`))),r);e.signal?.aborted?d():e.signal?.addEventListener("abort",d);})}baseInterval(){return this.pushed()?this.pushedInterval():this.options.pollIntervalMs??Ds}pushedInterval(){return this.options.pushedPollIntervalMs??qs}pushed(){return this.options.clock.now()-this.lastPushAt<$s*this.pushedInterval()}retune(){!this.polling||this.pinnedIntervalMs!==null||this.baseInterval()!==this.pollIntervalMs&&this.startPolling();}schedule(){this.disposed||!this.polling||this.room===null||(this.pollIntervalMs=this.pinnedIntervalMs??this.baseInterval(),this.pollHandle=this.options.clock.setTimeout(()=>{this.pollHandle=null,this.track(this.reconcile().catch(()=>null).then(()=>{this.schedule();}));},this.pollIntervalMs));}installUnloadNotifier(){if(this.options.notifyOnUnload===false)return;let e=globalThis;typeof e.addEventListener=="function"&&(this.unloadListener=t=>{if(this.ticketWatch?.abandon(true),t?.persisted!==true&&(this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{})),this.queuedFromRoomId!==null)){let r=this.queuedFromRoomId;this.queuedFromRoomId=null,this.track(this.api.leave(r,true,void 0,true).catch(()=>{}));}},e.addEventListener("pagehide",this.unloadListener));}};function Nt(){let n=globalThis.document;return n?.visibilityState===void 0||n.visibilityState==="visible"}var yi=["visibilitychange","focus","pageshow","online"];function Ws(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||bi(n)!==bi(e)}function bi(n){return n.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function vi(n){return n instanceof j&&n.code==="invalid_cluster_target"}var Ut=8;function Bs(n){if(!(Array.isArray(n)&&n.length>=1&&n.length<=Ut&&n.every(t=>typeof t=="string"&&t.length>0)))throw new u("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${Ut} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function Vs(n){let e=n?.templateSlugs;if(e===void 0)return;if(!(Array.isArray(e)&&e.length>=1&&e.length<=Ut&&e.every(r=>typeof r=="string"&&r.length>0)))throw new u("misconfigured",`quickJoin's templateSlugs is an array naming one to ${Ut} room templates by slug \u2014 quickJoin({ templateSlugs: ['duel', 'brawl'] }). A room that has to be created is made from the first.`);if(n?.templateSlug!==void 0||n?.templateId!==void 0)throw new u("misconfigured","quickJoin takes templateSlugs or a single templateSlug / templateId, not both. Put every template this player accepts in templateSlugs, with the one to create from first.")}function _i(n,e){return n.length===e.length&&n.every((t,r)=>t===e[r])}function wi(n){let e=0,t=new Map;return {resolve(){if(!n.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(i=>{let o={},a=l=>{t.delete(r)&&(n.clock.clearTimeout(o.timer),i(l));};t.set(r,a),o.timer=n.clock.setTimeout(()=>a(void 0),n.timeoutMs??2e3);let s=false;try{s=n.bridge.requestParty(r);}catch{}s||a(void 0);})},settle(r,i){t.get(r)?.(i);}}}
|
|
2
|
+
export{Si as CAPABILITY_GATES,xi as CAPABILITY_NAMESPACE_GATES,Mt as CHANNELS,Je as CHANNEL_KINDS,ue as ClientTelemetry,Kt as DEDICATED_INBOUND_EVENTS,dn as DEFAULT_WELCOME_CEILING_MS,oo as DEVICE_SETTINGS_MAX_BYTES,u as DedicatedServerError,bt as DedicatedSignalingHub,Js as FRAME_TO_PARENT,Qt as GemFrame,Xt as GemHost,Bt as HANDSHAKE_TIMEOUT_MS,Ee as HostMigration,ye as MALFORMED_INBOUND_KEY,Vn as MAX_ARRAY_LENGTH,ot as MAX_CLUSTER_TARGETS,fe as MAX_MESSAGE_BYTES,Bn as MAX_MESSAGE_DEPTH,tt as MAX_MESSAGE_NODES,at as MAX_SIGNALS_PER_SECOND,Le as MAX_SOCKET_FRAME_BYTES,ni as MIGRATION_TIMEOUT_MS,Ae as P2pApi,k as P2pError,Te as P2pSession,Ks as PARENT_TO_FRAME,h as PROTOCOL,B as PlayerText,nt as RATE_LIMITS,te as RateLimiter,Oe as RoomEmitter,Me as RoomsApi,Z as SUPPORTED_VERSIONS,Ie as SignalingClient,pt as TELEMETRY_EVENTS,ur as TRANSPORT_LABELS,le as VALIDATORS,Fe as WEBRTC_DEDICATED,qn as WEBRTC_P2P,Ve as WEB_ENGINE_VERSION,he as WEB_PROTOCOL_VERSION,ce as asPlayerText,ht as awaitMatchOutcome,Ot as browserPeerConnection,lt as buildDedicatedOfferFrame,ct as buildSocketFrame,rt as capabilityFor,Oi as createClusterTargetSource,Qo as createDedicatedServerApi,It as createKeySource,As as createP2pApi,wi as createPartyResolver,ki as createRoomManager,so as deviceSettingsByteLength,Be as establishDataChannel,ge as fingerprintOf,Pe as fingerprintsMatch,Lt as generateCertificate,it as isOrigin,ft as listClusterTargets,jn as memberFromWire,Jt as negotiateVersion,W as normaliseClusterTarget,be as normaliseClusterTargets,He as normaliseFingerprint,we as originsEqual,je as presentJoinCredential,dt as projectDedicatedEvent,qe as projectPartyEvent,ut as projectSignal,$t as roomArgValuesFromWire,Ft as roomArgsTemplateFromWire,z as roomFromWire,gt as startMatch,Qe as summaryFromWire,re as systemClock,eo as text,vt as unavailableSignaling,Xa as validateGemAdResult,La as validateGemAudioState,ca as validateGemAutoStartFailedEvent,ha as validateGemClusterTarget,na as validateGemCohorts,qa as validateGemControlsDeclare,pa as validateGemDedicatedEvent,wa as validateGemDedicatedOffer,oa as validateGemDeviceSettings,Ja as validateGemDeviceSettingsPut,za as validateGemDeviceSettingsResult,fa as validateGemDevtools,ra as validateGemEarnAllowanceChanged,xa as validateGemEngaged,Va as validateGemError,Ca as validateGemExit,Wa as validateGemFrameStats,tl as validateGemFriendChallengeResult,_a as validateGemGameContext,zs as validateGemHandshake,Ys as validateGemHandshakeAccept,Ta as validateGemLocalServer,Ia as validateGemLocalServerDenied,$a as validateGemMenu,Fa as validateGemMenuSelect,Ma as validateGemOpenExternal,Ra as validateGemPartyRequest,ga as validateGemPartyResult,ea as validateGemPause,Zs as validateGemPlayer,Ba as validateGemPortraitBorders,ta as validateGemPrefs,Aa as validateGemProgress,Ka as validateGemPurchaseResult,Sa as validateGemReady,Ya as validateGemRequestAd,Na as validateGemRequestAvatarPicker,va as validateGemRequestContext,el as validateGemRequestFriendChallenge,Oa as validateGemRequestFullscreen,Ea as validateGemRequestLocalServer,Ha as validateGemRequestPurchase,ja as validateGemRequestShare,Qa as validateGemRequestSignIn,Pa as validateGemRequestToken,Ga as validateGemRewardCue,aa as validateGemRoomEvent,ya as validateGemScreenshot,ba as validateGemScreenshotDenied,da as validateGemSeatedEvent,Za as validateGemSignInResult,ka as validateGemSignal,ma as validateGemSignalEvent,la as validateGemSocketState,ua as validateGemTicketEvent,Xs as validateGemToken,Qs as validateGemTokenDenied,Ua as validateGemVibrate,ia as validateGemViewport,Da as validateGemWalletDisplay,sa as validateGemWillTerminate,Ti as validateSize,Ct as verifyCredential};//# sourceMappingURL=gem-web-sdk.esm.js.map
|
|
3
3
|
//# sourceMappingURL=gem-web-sdk.esm.js.map
|