@indiegems/gem-web-sdk 7.8.1 → 7.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +69 -0
- package/dist/game.d.ts +22 -1
- 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 +32 -4
- package/dist/sdk.d.ts +22 -1
- package/docs/achievements.md +99 -3
- package/docs/api/api-reference-game.md +164 -11
- package/docs/api/api-reference-server.md +1 -1
- package/docs/api/reference.json +177 -4
- package/docs/changelog.md +69 -0
- package/docs/daily-challenges.md +9 -8
- package/docs/game-economy-tutorial.md +3 -2
- package/docs/getting-started.md +8 -4
- package/docs/manifest.json +14 -14
- package/docs/server-bundles.md +2 -2
- package/docs/what-a-game-must-do.md +180 -69
- package/package.json +1 -1
- package/schema/bridge.v1.json +104 -2
- package/schema/capabilities.public.json +7 -0
package/dist/gem-web-sdk.min.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var GemWebSdkGame=(function(exports){'use strict';var Ad=Object.defineProperty;var Pd=(t,e)=>{for(var n in e)Ad(t,n,{get:e[n],enumerable:true});};var wr="GemWebSdkHandshake";function Ed(){return typeof document>"u"?void 0:document.readyState}var vi=()=>Date.now();function _i(t={}){let e=t.win??window,n=e,r=n[wr];if(r!==void 0)return r;let o=t.readyState??Ed,i=t.now??vi,a=[],s=[],l=m=>{let c=m.data;!c||c.type!=="gem.handshake"||(a.length>=4&&(a.shift(),s.shift(),d.dropped+=1),a.push(m),s.push(i()));};e.addEventListener("message",l);let d={events:a,times:s,dropped:0,late:o()==="complete",uninstall(){e.removeEventListener("message",l);}};return n[wr]=d,d}function wi(t,e,n={}){let r=t[wr];if(r===void 0)return null;let o=n.ttlMs??9500,i=n.now??vi,a=r.events.splice(0),s=r.times?.splice(0),l=0,d=0,m=false,c=i()-o;for(let p=a.length-1;p>=0;p--){let g=s?.[p];if(g!==void 0&&g<c){d+=1;continue}if(l+=1,e(a[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:7.8.1]";function Si(){let t=globalThis.__gemWebSdkVersion;if(typeof t!="string")return "";let e=t.lastIndexOf(":"),n=t.lastIndexOf("]");return e<0||n<=e+1?"":t.slice(e+1,n)}function Td(t,e){return e!==void 0?!e:t==="chain_exhausted"}var on=class{constructor(e){this.options=e;}options;grant=null;state="pending";failure=null;generation=0;inFlight=null;rejected=false;get currentState(){return this.state}get lastFailure(){return this.failure}async get(){if(this.state==="lost")throw new ie(this.failure??"unavailable","the session cannot be renewed");let e=this.seconds();if(this.grant&&e<this.grant.expiresAt-this.renewBefore())return this.grant.token;if(this.grant&&e>=this.grant.chainEndsAt)throw this.enter("lost","chain_exhausted"),new ie("chain_exhausted","the token chain reached its ceiling");return this.refresh(this.nextReason())}nextReason(){return this.rejected?"rejected":this.grant?"expiring":"initial"}invalidate(e){e!==void 0&&this.grant!==null&&this.grant.token!==e||this.rejected&&this.grant===null||(this.grant=null,this.generation+=1,this.inFlight=null,this.rejected=true,this.state!=="lost"&&this.enter("pending"));}accept(e){this.state!=="lost"&&(this.grant=e,this.rejected=false,this.enter("ready"));}close(e="unavailable"){this.grant=null,this.generation+=1,this.inFlight=null,this.enter("lost",e);}refresh(e){if(this.inFlight)return this.inFlight;let n=this.generation;this.enter("pending");let r=this.options.request(e).then(o=>{if(n!==this.generation)throw new ie("internal","token arrived for a superseded generation");return this.grant=o,this.rejected=false,this.enter("ready"),o.token}).catch(o=>{let i=Cd(o),a=o?.retryable;throw n===this.generation&&this.enter(Td(i,typeof a=="boolean"?a:void 0)?"lost":"degraded",i),o instanceof ie?o:new ie(i,String(o))}).finally(()=>{this.inFlight===r&&(this.inFlight=null);});return this.inFlight=r,r}enter(e,n){this.failure=n??(e==="ready"?null:this.failure),this.state!==e&&(this.state=e,this.options.onStateChange?.(e,n));}renewBefore(){return this.options.renewBeforeSeconds??60}seconds(){return Math.floor(this.options.clock.now()/1e3)}},ie=class t extends Error{constructor(n,r){super(`auth ${n}: ${r}`);this.reason=n;this.name="AuthError";}reason;static isAuthError(n){if(n instanceof t)return true;let r=n;return r?.name==="AuthError"&&typeof r.reason=="string"}};function Cd(t){if(t instanceof ie)return t.reason;let e=t?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var oe=class t extends Error{retryable=false;constructor(e){super(e),this.name="TransportRefusal";}static isRefusal(e){if(e instanceof t)return true;let n=e;return n?.name==="TransportRefusal"&&n.retryable===false}},pt=["if-match","if-none-match"],Ri=4096;function Id(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let o=n.toLowerCase();if(!pt.includes(o)||r===void 0)continue;let i=typeof r=="string"?Md(r):r;if(typeof i!="string"||i.length>Ri||!Od(i))throw new oe(`the ${o} header value cannot be sent \u2014 it is not a string, is longer than ${Ri} characters, or contains a character outside the range an HTTP header value may carry. This is a malformed request, not a server failure; the value is withheld here rather than written to logs.`);i!==""&&(e[o]=i);}return Object.freeze(e)}function Md(t){let e=o=>o===32||o===9||o===10||o===13,n=0,r=t.length;for(;n<r&&e(t.charCodeAt(n));)n++;for(;r>n&&e(t.charCodeAt(r-1));)r--;return t.slice(n,r)}function Od(t){for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n!==9&&(n<32||n===127||n>255))return false}return true}function Ld(t){let{bytes:e}=t;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new oe("the raw body is not a Uint8Array, so it cannot be sent as bytes. This is a malformed request, not a server failure.");if(t.body!==void 0)throw new oe("the request carries both a JSON body and a raw body, and only one can be sent. This is a malformed request, not a server failure.");return new Uint8Array(e)}}function ki(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let o={...r},i=Id(o.headers),a=Ld(o),s=Object.freeze({...o,headers:i,...a===void 0?{}:{bytes:a}}),l=await e.tokenSource.get(),d=await t(s,l);if(d.status!==401||!n)return d;e.tokenSource.invalidate(l);let m=await e.tokenSource.get(),c=await t(s,m);if(c.status===401)throw e.tokenSource.close("unavailable"),new ie("unavailable","the server refused a freshly minted token");return c}}}function gt(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(Gd(e))}function yt(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}function Sr(t){return new TextDecoder().decode(yt(t))}function Gd(t){let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return n}var G=class extends Error{constructor(n,r,o,i,a){super(`${n} (${r}): ${o}`);this.reason=n;this.status=r;this.detail=o;this.retryAfterSeconds=i;this.code=a;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},Ai=new WeakMap;function Pi(t){return Ai.get(t)??{}}var Dd=new Set([408,429,500,502,503,504]),$d=6e4;function Fd(t){if(t===void 0)return 2;if(!Number.isInteger(t)||t<0||t>10)throw new oe(`maxRetries must be a whole number between 0 and 10; received ${JSON.stringify(t)}. This is a configuration fault, not a server failure.`);return t}var Le=class{constructor(e){this.options=e;}options;async get(e,n){return this.send({method:"GET",path:e,signal:n},true)}async getWithEtag(e,n={}){let r=await this.sendRaw({method:"GET",path:e,...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{headers:{"if-none-match":n.ifNoneMatch}}},true),o=r.etag===void 0?{}:{etag:r.etag};return r.status===304?{modified:false,...o}:{modified:true,body:r.body,...o}}async put(e,n,r,o={}){return this.send({method:"PUT",path:e,body:n,signal:r,...kn(o)},o.replaySafe===true)}async post(e,n,r,o={}){return this.send({method:"POST",path:e,body:n,signal:r,...kn(o)},o.replaySafe===true)}async postBytes(e,n,r,o={}){let i=await this.sendRaw({method:"POST",path:e,bytes:n,responseType:"bytes",signal:r,...kn(o)},o.replaySafe===true);return {bytes:jd(i.body),...i.invocationId===void 0?{}:{invocationId:i.invocationId}}}async patch(e,n,r,o={}){return this.send({method:"PATCH",path:e,body:n,signal:r,...kn(o)},o.replaySafe===true)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...kn(r)},r.replaySafe===true)}async send(e,n){return (await this.sendRaw(e,n)).body}async sendRaw(e,n){let r=n?Fd(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw xi(e.signal);for(let i=0;i<r;i++){if(i>0&&await this.backoff(i,o,e.signal),e.signal?.aborted)throw xi(e.signal);let a;try{a=await this.options.transport.request(e);}catch(l){if(ie.isAuthError(l)||oe.isRefusal(l)||e.signal?.aborted||qd(l))throw l;o=new G("unavailable",0,String(l));continue}if(a.status>=200&&a.status<300||a.status===304)return a;let s=Nd(a);if(!Dd.has(a.status))throw s;o=s;}throw o??new G("unavailable",0,"no attempt was made")}backoff(e,n,r){if(r?.aborted)return Promise.resolve();let o=n?.retryAfterSeconds,i=o!==void 0?o*1e3:2**(e-1)*250,a=2**(e-1)*250,s=Math.min(Math.max(i,a),$d);return new Promise(l=>{let d=this.options.clock,m=false,c=false,p,g=()=>{m||(m=true,c&&d.clearTimeout(p),r?.removeEventListener("abort",g),l());};r?.addEventListener("abort",g,{once:true}),p=d.setTimeout(g,s),c=true,m&&d.clearTimeout(p);})}};function jd(t){if(t instanceof Uint8Array)return t;if(t==null)return new Uint8Array(0);let e=typeof t=="string"?t:JSON.stringify(t);return new TextEncoder().encode(e)}function kn(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function xi(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function qd(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function Nd(t){let e=Bd(t),n=Vd(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&Ai.set(e,r),e}var Ud=new Map([["insufficient_funds","insufficient_funds"]]);function Bd(t){let{status:e,body:n}=t,r=Hd(n),o=t.retryAfterSeconds??Kd(n),i=Wd(n),a=i===void 0?void 0:Ud.get(i);if(a!==void 0)return new G(a,e,r,void 0,i);switch(e){case 304:return new G("not_modified",e,r);case 400:case 422:return new G("invalid",e,r,void 0,i);case 403:return new G("forbidden",e,r,void 0,i);case 404:return new G("not_found",e,r,void 0,i);case 402:return new G("insufficient_funds",e,r,void 0,i);case 409:return new G("conflict",e,r,void 0,i);case 412:return new G("precondition_failed",e,r,void 0,i);case 413:return new G("too_large",e,r,void 0,i);case 429:return new G("rate_limited",e,r,o,i);default:return new G("unavailable",e,r,o,i)}}function Hd(t){if(typeof t=="string")return t;let e=t?.message;if(typeof e=="string")return e;let n=t?.error;if(typeof n=="string")return n;let r=n?.message;return typeof r=="string"?r:"no detail"}function Vd(t){let n=t?.error?.details;return n===null?void 0:n}function Wd(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function Kd(t){let e=t?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function v(t){let e=String(t);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 Ei(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function Ti(t,e,n,r,o,i){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/add`;return t.client.post(a,o,i?.signal)}async function Ci(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Ii(t,e,n,r,o,i){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/claim`;return t.client.post(a,o,i?.signal)}async function Mi(t,e,n){return t.client.post("/v1/characters",e,n?.signal)}async function Oi(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/orders/batch`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Li(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/orders`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Gi(t,e,n,r,o){let i=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(i,o?.signal)}async function Di(t,e,n,r,o){let i=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(i,o?.signal)}async function $i(t,e,n,r){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.delete(o,r?.signal)}async function Fi(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/recipes/execute`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function ji(t,e,n,r,o,i){let a=`/v1/saves/${v(e)}/${v(n)}/${v(r)}/finalize`;return t.client.post(a,o,i?.signal)}async function qi(t,e,n){let r=`/v1/games/${v(t.gameId())}/config/channels/${v(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Ni(t,e,n){let r=`/v1/characters/${v(e)}`;return t.client.get(r,n?.signal)}async function Ui(t,e,n){let r=`/v1/inventory/loot-tables/${v(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Bi(t,e,n,r,o){let i=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Hi(t,e,n,r){let o=new URLSearchParams;r?.include_buckets!==void 0&&o.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&o.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&o.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&o.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&o.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&o.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&o.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&o.set("progression_cursor",String(r?.progression_cursor));let i=o.toString(),a=`/v1/inventory/${v(e)}/${v(n)}`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function Vi(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/items/${v(r)}`;return t.client.get(i,o?.signal)}async function Wi(t,e,n,r,o){let i=new URLSearchParams;o?.bucket_1!==void 0&&i.set("bucket_1",String(o?.bucket_1)),o?.bucket_2!==void 0&&i.set("bucket_2",String(o?.bucket_2)),o?.limit!==void 0&&i.set("limit",String(o?.limit)),o?.periods_back!==void 0&&i.set("periods_back",String(o?.periods_back)),o?.period!==void 0&&i.set("period",String(o?.period)),o?.player_id!==void 0&&i.set("player_id",String(o?.player_id));let a=i.toString(),s=`/v1/leaderboards/${v(e)}/${v(n)}/${v(r)}`+(a?`?${a}`:"");return t.client.get(s,o?.signal)}async function Ki(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/orders/${v(r)}`;return t.client.get(i,o?.signal)}async function Ji(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}`;return t.client.get(i,o?.signal)}async function zi(t,e,n,r,o,i){let a=`/v1/inventory/${v(e)}/${v(n)}/catalogs/${v(r)}/recipes/${v(o)}/availability`;return t.client.get(a,i?.signal)}async function Yi(t,e,n,r){let o=new URLSearchParams;o.set("limit",String(r?.limit));let i=o.toString(),a=`/v1/inventory/${v(e)}/${v(n)}/recipe-usage`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function Rr(t,e,n,r,o){let i=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Xi(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let o=r.toString(),i=`/v1/leaderboards/${v(e)}/friends`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function Qi(t,e,n){let r=`/v1/showcase/friends/${v(e)}`;return t.client.get(r,n?.signal)}async function Zi(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let o=r.toString(),i=`/v1/leaderboards/${v(e)}`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function es(t,e){let n=`/v1/games/${v(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function ft(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function ns(t,e,n){let r=`/v1/profiles/players/${v(e)}`;return t.client.get(r,n?.signal)}async function ts(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),o="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function rs(t,e,n){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${v(e)}`;return t.client.get(r,n?.signal)}async function os(t,e,n,r){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.get(o,r?.signal)}async function is(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function ss(t,e,n){let r=`/v1/inventory/transfers/${v(e)}`;return t.client.get(r,n?.signal)}async function as(t,e,n){let r=`/v1/games/${v(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{...n?.keepalive===void 0?{}:{keepalive:n.keepalive},replaySafe:true})}async function ls(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function ds(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/platform-funded-game-inventory-purchases`;return t.client.post(i,r,o?.signal)}async function cs(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function us(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),o="/v1/challenges"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function ms(t,e){return t.client.get("/v1/characters",e?.signal)}async function ps(t,e,n,r){let o=`/v1/settings/${v(e)}/${v(n)}`;return t.client.get(o,r?.signal)}async function gs(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/inventory/${v(e)}/${v(n)}/orders`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function ys(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/saves/${v(e)}/${v(n)}`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function fs(t,e){let n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),o="/v1/friends"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function hs(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),o="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function bs(t,e,n,r){let o=`/v1/games/${v(t.gameId())}/matches/${v(e)}/end`;return t.client.post(o,n,r?.signal)}async function vs(t,e,n,r,o,i){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/max`;return t.client.post(a,o,i?.signal)}async function _s(t,e,n,r,o,i){let a=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.put(a,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ws(t,e,n,r,o){let i=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.put(i,r,o?.signal)}async function Ss(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function Rs(t,e,n,r){let o=`/v1/characters/${v(e)}`;return t.client.patch(o,n,r?.signal)}async function ks(t,e,n,r,o,i){let a=`/v1/saves/${v(e)}/${v(n)}/${v(r)}/upload-url`;return t.client.post(a,o,i?.signal,{replaySafe:true})}async function xs(t,e,n,r,o,i){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/reset`;return t.client.post(a,o,i?.signal)}async function As(t,e,n){let r=`/v1/characters/${v(e)}`;return t.client.delete(r,n?.signal)}var K="gem-web-bridge",bt={min:1,max:1},sn=65536,Ps=8,ht=5e3,Es=1024;function xr(t){return Object.freeze(Object.assign(Object.create(null),t))}var Ts=xr({"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.requestShare":6,"gem.frameStats":120,"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}),vt="__malformed";var Jd=xr({"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.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"}),zd=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.viewport.","reservedAreas"]]);function Cs(t){let e=Jd[t];if(e!==void 0)return e;for(let[n,r]of zd)if(t.startsWith(n))return r}function Ar(t){let e=/^([a-z][a-z0-9+.-]*):\/\/([a-z0-9.-]+|\[[0-9a-f:.]+\])(:([0-9]{1,5}))?$/i.exec(t);return e===null?false:e[4]===void 0||Number(e[4])<=65535}function Yd(t){let e;try{e=new URL(t);}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 Xd(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function Qd(t){return /^[a-z_]+$/.test(t)}function kr(t,e,n){if(e>Ps)return `nesting deeper than ${Ps}`;if(++n.nodes>ht)return `more than ${ht} values`;if(n.bytes>sn)return `over the ${sn} byte limit`;if(t==null)return n.bytes+=4,null;let r=typeof t;if(r==="boolean")return n.bytes+=5,null;if(r==="number")return n.bytes+=8,null;if(r==="string")return n.bytes+=t.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let o=t;if(n.seen.has(o))return "a repeated or cyclic object reference";if(n.seen.add(o),Array.isArray(t)){if(t.length>Es)return `an array of ${t.length} entries, over the ${Es} limit`;n.bytes+=2;for(let s of t){let l=kr(s,e+1,n);if(l)return l}return null}let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)return "a value that is not a plain object";n.bytes+=2;let a=t;for(let s in a){if(!Object.prototype.hasOwnProperty.call(a,s))continue;if(++n.nodes>ht)return `more than ${ht} values`;if(n.bytes+=s.length*3+4,n.bytes>sn)return `over the ${sn} byte limit`;let l=kr(a[s],e+1,n);if(l)return l}return null}function Zd(t){let e={nodes:0,bytes:0,seen:new Set},n=kr(t,0,e);return n?`message contains ${n}`:e.bytes>sn?`message is over the ${sn} byte limit`:null}var ec={origin:[Ar,"not a well-formed origin"],url:[Yd,"not a safe absolute http(s) URL"],bcp47:[Xd,"not a well-formed BCP 47 tag"],code:[Qd,"not a code of lower-case letters and underscores"]};function Is(t,e,n){for(let r of e){let o=n===""?r.n:`${n}.${r.n}`,i=t[r.n];if(i==null){if(r.o)continue;return `${o}: required`}let a=Ms(i,r,o);if(a)return a}return null}function Ms(t,e,n){switch(e.k){case "string":{if(typeof t!="string")return `${n}: expected string`;if(t.length>e.max)return `${n}: exceeds ${e.max} characters`;if(e.f){let[r,o]=ec[e.f];if(!r(t))return `${n}: ${o}`}return null}case "int":return typeof t!="number"||!Number.isInteger(t)?`${n}: expected integer`:t<e.lo||t>e.hi?`${n}: out of range ${e.lo}..${e.hi}`:null;case "boolean":return typeof t=="boolean"?null:`${n}: expected boolean`;case "enum":{let r=e.v;return r.includes(t)?null:`${n}: not one of ${r.join("|")}`}case "object":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected object`:Is(t,e.fs,n);case "json":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected a plain object`:null;case "array":{if(!Array.isArray(t))return `${n}: expected array`;if(t.length>e.max)return `${n}: exceeds ${e.max} items`;let r=e.it,o=`${n}[]`;for(let i of t){if(i==null){if(r.o)continue;return `${o}: required`}let a=Ms(i,r,o);if(a)return a}return null}default:{let r=e.k;return `${n}: unknown kind ${String(r)}`}}}function C(t,e){return n=>{let r=Zd(n);if(r)return r;if(typeof n!="object"||n===null||Array.isArray(n))return "message: expected object";let o=n;return o.gem!==K?"gem: wrong protocol marker":o.type!==t?`type: expected ${t}`:Is(o,e,"")}}var nc=C("gem.handshake",[{n:"versions",k:"object",fs:[{n:"min",k:"int",lo:1,hi:1e3},{n:"max",k:"int",lo:1,hi:1e3}]},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}},{n:"embedder",k:"string",max:2048,f:"origin"},{n:"unbidden",k:"boolean",o:1}]),tc=C("gem.handshake.accept",[{n:"v",k:"int",lo:1,hi:1e3},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}}]),rc=C("gem.token",[{n:"token",k:"string",max:4096},{n:"requestId",k:"string",o:1,max:64},{n:"generation",k:"int",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"string",o:1,max:512,f:"url"},{n:"playerId",k:"string",max:64},{n:"gameId",k:"string",max:64},{n:"channel",k:"enum",v:["dev","test","release"]},{n:"gameVersion",k:"string",o:1,max:64},{n:"expiresAt",k:"int",lo:0,hi:4102444800},{n:"chainEndsAt",k:"int",lo:0,hi:4102444800},{n:"allowDevTools",k:"boolean",o:1}]),oc=C("gem.token.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"retryAfterMs",k:"int",o:1,lo:0,hi:36e5},{n:"reason",k:"enum",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"string",max:64}]),ic=C("gem.player",[{n:"untrusted",k:"object",fs:[{n:"displayName",k:"string",max:64},{n:"displayTag",k:"string",o:1,max:80},{n:"displayHandle",k:"string",max:80}]},{n:"playerId",k:"string",o:1,max:64},{n:"discriminator",k:"string",o:1,max:8},{n:"avatarIconUrl",k:"string",o:1,max:2048,f:"url"},{n:"badges",k:"array",o:1,max:2,it:{n:"",k:"object",fs:[{n:"itemId",k:"string",max:64},{n:"iconUrl",k:"string",max:2048,f:"url"}]}},{n:"displayTag",k:"string",max:8},{n:"avatarUrl",k:"string",o:1,max:2048,f:"url"},{n:"boost",k:"object",o:1,fs:[{n:"multipliers",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"currencyId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"multiplierBp",k:"int",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"int",o:1,lo:1,hi:7}]}]),sc=C("gem.pause",[{n:"paused",k:"boolean"}]),ac=C("gem.prefs",[{n:"reducedMotion",k:"boolean"},{n:"muted",k:"boolean"},{n:"showFrameStats",k:"boolean",o:1},{n:"locale",k:"string",max:35,f:"bcp47"}]),lc=C("gem.cohorts",[{n:"cohorts",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"experimentId",k:"string",max:36},{n:"variantKey",k:"string",max:32}]}}]),dc=C("gem.earnAllowanceChanged",[]),cc=C("gem.viewport",[{n:"insets",k:"object",fs:[{n:"top",k:"int",lo:0,hi:4096},{n:"right",k:"int",lo:0,hi:4096},{n:"bottom",k:"int",lo:0,hi:4096},{n:"left",k:"int",lo:0,hi:4096}]},{n:"reserved",k:"array",o:1,max:4,it:{n:"",k:"object",fs:[{n:"x",k:"int",lo:0,hi:16384},{n:"y",k:"int",lo:0,hi:16384},{n:"width",k:"int",lo:0,hi:16384},{n:"height",k:"int",lo:0,hi:16384}]}}]),uc=C("gem.deviceSettings",[{n:"settings",k:"json",o:1}]),mc=C("gem.willTerminate",[{n:"reason",k:"enum",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"int",lo:0,hi:6e4}]),pc=C("gem.roomEvent",[{n:"event",k:"enum",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"string",max:64},{n:"matchId",k:"string",o:1,max:64},{n:"version",k:"int",o:1,lo:0,hi:2147483647},{n:"reason",k:"string",o:1,max:64},{n:"platform",k:"enum",o:1,v:["universal","mobile"]}]),gc=C("gem.socketState",[{n:"connected",k:"boolean"},{n:"reason",k:"enum",o:1,v:["connecting","dropped","watchdog","terminal"]}]),yc=C("gem.seatedEvent",[{n:"roomId",k:"string",max:64}]),fc=C("gem.autoStartFailedEvent",[{n:"roomId",k:"string",max:64},{n:"code",k:"string",max:64}]),hc=C("gem.signalEvent",[{n:"event",k:"enum",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),bc=C("gem.dedicatedEvent",[{n:"event",k:"enum",v:["answer","error","matchEnded"]},{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",o:1,max:10240},{n:"sessionId",k:"string",o:1,max:64},{n:"code",k:"string",o:1,max:64},{n:"message",k:"string",o:1,max:256},{n:"reason",k:"string",o:1,max:64}]),vc=C("gem.partyResult",[{n:"requestId",k:"string",max:64},{n:"partyId",k:"string",o:1,max:64}]),_c=C("gem.clusterTarget",[{n:"clusterTargetId",k:"string",max:64},{n:"clusterTargetIds",k:"array",o:1,max:3,it:{n:"",k:"string",max:64}}]),wc=C("gem.devtools",[{n:"action",k:"enum",v:["open","close","toggle"]}]),Sc=C("gem.screenshot",[{n:"maxWidth",k:"int",lo:1,hi:7680},{n:"maxHeight",k:"int",lo:1,hi:4320}]),Rc=C("gem.screenshot.denied",[{n:"reason",k:"enum",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"boolean"}]),kc=C("gem.requestContext",[]),xc=C("gem.gameContext",[{n:"context",k:"json"}]),Ac=C("gem.signal",[{n:"signal",k:"enum",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),Pc=C("gem.dedicatedOffer",[{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",max:10240},{n:"intent",k:"enum",v:["initial","ice_restart","full_reconnect"]}]),Ec=C("gem.partyRequest",[{n:"requestId",k:"string",max:64}]),Tc=C("gem.ready",[]),Cc=C("gem.engaged",[]),Ic=C("gem.progress",[{n:"loaded",k:"int",lo:0,hi:1099511627776},{n:"total",k:"int",lo:0,hi:1099511627776}]),Mc=C("gem.requestToken",[{n:"requestId",k:"string",max:64},{n:"reason",k:"enum",v:["initial","expiring","rejected"]}]),Oc=C("gem.requestLocalServer",[{n:"requestId",k:"string",max:64},{n:"gameRoomId",k:"string",max:64}]),Lc=C("gem.localServer",[{n:"requestId",k:"string",max:64},{n:"serverId",k:"string",o:1,max:128}]),Gc=C("gem.localServer.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"reason",k:"enum",v:["refused","unavailable"]}]),Dc=C("gem.exit",[{n:"reason",k:"string",o:1,max:64}]),$c=C("gem.openExternal",[{n:"url",k:"string",max:2048,f:"url"}]),Fc=C("gem.requestFullscreen",[{n:"enabled",k:"boolean"}]),jc=C("gem.audioState",[{n:"muted",k:"boolean"}]),qc=C("gem.rewardCue",[{n:"currencySlug",k:"string",max:32},{n:"expected",k:"int",o:1,lo:1,hi:1e9},{n:"origin",k:"object",o:1,fs:[{n:"x",k:"int",lo:0,hi:16384},{n:"y",k:"int",lo:0,hi:16384}]}]),Nc=C("gem.walletDisplay",[{n:"visible",k:"boolean"},{n:"currencies",k:"array",o:1,max:8,it:{n:"",k:"string",max:64}},{n:"score",k:"boolean",o:1}]),Uc=C("gem.requestShare",[{n:"params",k:"array",max:16,it:{n:"",k:"object",fs:[{n:"key",k:"string",max:64},{n:"value",k:"string",max:512}]}}]),Bc=C("gem.frameStats",[{n:"fps",k:"int",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"int",lo:0,hi:1e5}]),Hc=C("gem.error",[{n:"code",k:"enum",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"string",o:1,max:256}]),Vc=C("gem.requestPurchase",[{n:"requestId",k:"string",max:64},{n:"purchaseKind",k:"enum",v:["item","recipe"]},{n:"targetId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"quantity",k:"int",o:1,lo:1,hi:10},{n:"catalogId",k:"string",o:1,max:64}]),Wc=C("gem.purchaseResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["ok","declined","unavailable"]},{n:"reason",k:"string",o:1,max:64,f:"code"},{n:"purchaseId",k:"string",o:1,max:64}]),Kc=C("gem.deviceSettings.put",[{n:"requestId",k:"string",max:64},{n:"settings",k:"json"}]),Jc=C("gem.deviceSettings.result",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["stored","too_large","unavailable"]}]),zc=C("gem.requestAd",[{n:"requestId",k:"string",max:64},{n:"placement",k:"string",max:32},{n:"format",k:"enum",v:["interstitial","rewarded"]}]),Yc=C("gem.adResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["shown","no_ad","unavailable"]}]),Xc=C("gem.requestSignIn",[{n:"requestId",k:"string",max:64}]),Qc=C("gem.signInResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["signed_in","declined","unavailable"]}]),Zc=C("gem.requestFriendChallenge",[{n:"requestId",k:"string",max:64},{n:"playerId",k:"string",max:64},{n:"template",k:"string",max:64},{n:"params",k:"json",o:1}]),eu=C("gem.friendChallengeResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"string",o:1,max:64},{n:"param",k:"string",o:1,max:64},{n:"channel",k:"string",o:1,max:16},{n:"configVersion",k:"int",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"int",o:1,lo:0,hi:864e5},{n:"detail",k:"string",o:1,max:300}]),_t=xr({"gem.handshake":nc,"gem.handshake.accept":tc,"gem.token":rc,"gem.token.denied":oc,"gem.player":ic,"gem.pause":sc,"gem.prefs":ac,"gem.cohorts":lc,"gem.earnAllowanceChanged":dc,"gem.viewport":cc,"gem.deviceSettings":uc,"gem.willTerminate":mc,"gem.roomEvent":pc,"gem.socketState":gc,"gem.seatedEvent":yc,"gem.autoStartFailedEvent":fc,"gem.signalEvent":hc,"gem.dedicatedEvent":bc,"gem.partyResult":vc,"gem.clusterTarget":_c,"gem.devtools":wc,"gem.screenshot":Sc,"gem.screenshot.denied":Rc,"gem.requestContext":kc,"gem.gameContext":xc,"gem.signal":Ac,"gem.dedicatedOffer":Pc,"gem.partyRequest":Ec,"gem.ready":Tc,"gem.engaged":Cc,"gem.progress":Ic,"gem.requestToken":Mc,"gem.requestLocalServer":Oc,"gem.localServer":Lc,"gem.localServer.denied":Gc,"gem.exit":Dc,"gem.openExternal":$c,"gem.requestFullscreen":Fc,"gem.audioState":jc,"gem.rewardCue":qc,"gem.walletDisplay":Nc,"gem.requestShare":Uc,"gem.frameStats":Bc,"gem.error":Hc,"gem.requestPurchase":Vc,"gem.purchaseResult":Wc,"gem.deviceSettings.put":Kc,"gem.deviceSettings.result":Jc,"gem.requestAd":zc,"gem.adResult":Yc,"gem.requestSignIn":Xc,"gem.signInResult":Qc,"gem.requestFriendChallenge":Zc,"gem.friendChallengeResult":eu});var le={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},xn=class{constructor(e=le){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=Ts[e];if(n===void 0)return false;let r=this.clock.now(),o=this.lastRefill.get(e)??r,i=this.tokens.get(e)??n,a=Math.max(0,r-o),s=Math.min(n,i+a*n/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 Pr(t,e){return t.toLowerCase()===e.toLowerCase()}function wt(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function Os(t,e){if(typeof e!="string"||e==="")return false;let n,r;try{n=new URL(t),r=new URL(e);}catch{return false}return n.protocol!=="http:"&&n.protocol!=="https:"||r.protocol!=="http:"&&r.protocol!=="https:"||n.username!==""||n.password!==""||n.pathname!=="/"||n.search!==""||n.hash!==""||n.port===""?false:wt(n.hostname)&&wt(r.hostname)}function Ls(t,e){if(e.min>e.max)return null;let n=Math.min(t.max,e.max),r=Math.max(t.min,e.min);return n>=r?n:null}var St=class{constructor(e,n){this.inventory=e;this.resolveCurrencyId=n;}inventory;resolveCurrencyId;async list(e={}){return (await this.inventory.snapshot({buckets:e.buckets})).currencies.data.map(r=>({currencyId:r.currencyId,total:r.total,...r.buckets===void 0?{}:{buckets:r.buckets}}))}async get(e,n={}){let o=(await this.inventory.snapshot({buckets:n.buckets})).currencies.data,i=o.find(s=>s.currencyId===e),a;return !i&&this.resolveCurrencyId&&(a=await this.resolveCurrencyId(e).catch(()=>{}),a!==void 0&&(i=o.find(s=>s.currencyId===a))),{currencyId:i?i.currencyId:a??e,total:i?i.total:null,...i?.buckets===void 0?{}:{buckets:i.buckets}}}};function Tr(t){let e=Array.isArray(t.achievements)?t.achievements:[],n=[];for(let r of e){let o=r??{};typeof o.id!="string"||o.id===""||typeof o.threshold!="number"||!Number.isFinite(o.threshold)||n.push({id:o.id,threshold:o.threshold,points:typeof o.points=="number"?o.points:0,hidden:o.hidden===true,...typeof o.unlocked_at=="number"&&Number.isFinite(o.unlocked_at)?{unlockedAt:o.unlocked_at}:{},...o.revoked===true?{revoked:true}:{}});}return {...n.length>0?{achievements:n}:{},...t.achievements_unavailable===true?{achievementsUnavailable:true}:{}}}var Gs="inventory",an=t=>typeof t=="number"?t:0,An=t=>typeof t=="string"?t:"";function Er(t,e){let n=t??{},r=typeof n.next_cursor=="string"?n.next_cursor:void 0;return {data:Array.isArray(n.data)?n.data.map(e):[],...r===void 0?{}:{nextCursor:r}}}function Ds(t){let e=t??{};return {itemDefinitionId:An(e.item_definition_id),instanceId:An(e.instance_id),quantity:an(e.quantity),acquiredAt:an(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function nu(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:Er(e.currencies,r=>{let o=r??{},i=Array.isArray(o.buckets)?o.buckets.map(a=>{let s=a??{};return {bucket:An(s.bucket),balance:an(s.balance)}}):void 0;return {currencyId:An(o.currency_id),total:an(o.total),...i===void 0?{}:{buckets:i}}}),items:Er(e.items,Ds),progressions:Er(e.progressions,r=>{let o=r??{};return {progressionDefinitionId:An(o.progression_definition_id),currentValue:an(o.current_value),completionCount:an(o.completion_count),isCompleted:o.is_completed===true,...Tr(o)}}),...n===void 0?{}:{etag:n}}}var Rt=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${Gs}#buckets`:Gs;return this.cache.read(n,[],()=>this.fetch({includeBuckets:e.buckets}))}async instances(e,n){let r=await this.snapshot();if(r.items.nextCursor===void 0){let i=r.items.data.filter(a=>a.itemDefinitionId===e);if(i.length>0)return i}let o=await Vi(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(o)?o.map(Ds):[]}page(e){return this.fetch(e)}refresh(){this.invalidate();}onChanged(e){return this.cache.onInvalidate(e)}invalidate(){this.cache.invalidate();}async fetch(e){let n=await Hi(this.api,this.entity.type,this.entity.id,{...e.includeBuckets?{include_buckets:true}:{},...e.currencyCursor===void 0?{}:{currency_cursor:e.currencyCursor},...e.itemCursor===void 0?{}:{item_cursor:e.itemCursor},...e.progressionCursor===void 0?{}:{progression_cursor:e.progressionCursor},...e.currencyLimit===void 0?{}:{currency_limit:e.currencyLimit},...e.itemLimit===void 0?{}:{item_limit:e.itemLimit},...e.progressionLimit===void 0?{}:{progression_limit:e.progressionLimit},...e.signal===void 0?{}:{signal:e.signal}});return nu(n)}};var tu={unknown_currency:1,currency_not_in_game_payable:1,not_purchasable:1,no_price_in_currency:1,busy:1,cancelled:1,insufficient_funds:1,price_mismatch:1,config_version_stale:1,platform_currency_unavailable:1,not_available:1,recipe_locked:1,recipe_on_cooldown:1,recipe_max_uses_exceeded:1,item_max_stack_exceeded:1,recipe_costs_unmet:1,quantity_invalid:1,error:1},ru=new Set(Object.keys(tu));function $s(t){return typeof t=="string"&&ru.has(t)?t:"error"}var Ge=class extends RangeError{constructor(n,r){super(r);this.code=n;this.name="PurchaseRefusal";}code;retryable=false};var Z=t=>typeof t=="string"?t:"",ou=t=>typeof t=="string"?t:Z(t&&typeof t=="object"?t.type:void 0),Re=t=>typeof t=="number"?t:0;function iu(t){let e=t??{};return {prerequisiteType:Z(e.prerequisite_type),referenceId:Z(e.reference_id),required:Re(e.required),current:Re(e.current)}}function Pn(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {orderId:Z(e.order_id),status:Z(e.status),...n===void 0?{}:{etag:n}}}function kt(){return crypto.randomUUID()}var su="recipe-usage",Fs=100;function xt(t){let e=t??{};switch(e.type){case "currency":return {kind:"currency",currencyId:Z(e.currency_id),bucket:Z(e.bucket),delta:Re(e.delta),balanceAfter:Re(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:Z(e.item_definition_id),instanceId:Z(e.instance_id),delta:Re(e.delta),quantityAfter:Re(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:Z(e.progression_definition_id),delta:Re(e.delta),valueAfter:Re(e.value_after),completed:e.completed===true};default:return {kind:"other",type:Z(e.type)}}}function au(t){let e=t??{},n=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:Z(e.entry_id),...n===void 0?{}:{rarityTier:n},rollNumber:Re(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(xt):[]}}function lu(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(au):void 0;return {orderId:Z(e.order_id),status:Z(e.status),...n===void 0?{}:{etag:n},granted:Array.isArray(e.granted)?e.granted.map(xt):[],consumed:Array.isArray(e.consumed)?e.consumed.map(xt):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(xt):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function du(t){let e=t??{},n=e.price??{};return {payment:"platform_currency",orderId:Z(e.target_order_id)||Z(e.source_order_id),status:Z(e.status),purchaseId:Z(e.purchase_id),sourceOrderId:Z(e.source_order_id),price:{currencyId:Z(n.platform_currency_id),amount:Re(n.price)}}}function cu(t){let e=t??{},n=typeof e.last_used_at=="string"?e.last_used_at:void 0,r=typeof e.cooldown_expires_at=="string"?e.cooldown_expires_at:void 0;return {recipeId:Z(e.recipe_id),useCount:typeof e.use_count=="number"?e.use_count:0,isOnCooldown:e.is_on_cooldown===true,...n===void 0?{}:{lastUsedAt:n},...r===void 0?{}:{cooldownExpiresAt:r}}}function js(t){switch(t.type){case "currency_grant":case "currency_consume":return {type:t.type,currency_id:t.currencyId,amount:t.amount};default:return {type:t.type,item_definition_id:t.itemDefinitionId,quantity:t.quantity}}}var At=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;async create(e,n={}){let r=await this.write(()=>Li(this.api,this.entity.type,this.entity.id,{operations:e.map(js),source:n.source??"play",nonce:kt()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return Pn(r)}async createMany(e,n={}){return this.write(()=>Oi(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(js),nonce:kt()})),source:n.source??"play"},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}))}async recipeAvailability(e,n,r){let i=await zi(this.api,this.entity.type,this.entity.id,e,n,r===void 0?{}:{signal:r})??{},a=typeof i.uses_remaining=="number"?i.uses_remaining:void 0,s=typeof i.cooldown_expires_at=="string"?i.cooldown_expires_at:void 0,l=Array.isArray(i.lock_reasons)?i.lock_reasons.map(iu):[];return {canExecute:i.can_execute===true,locked:i.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(i.reasons)?i.reasons.map(d=>ou(d)):[],...a===void 0?{}:{usesRemaining:a},...s===void 0?{}:{cooldownExpiresAt:s}}}async recipeUsageAll(){return this.cache.read(su,[],async()=>{let n=await Yi(this.api,this.entity.type,this.entity.id,{limit:Fs})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(cu),truncated:r.length>=Fs}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,n={}){if(e.payment.kind==="configured"){let c=e,p=await this.write(()=>Fi(this.api,this.entity.type,this.entity.id,{catalog_id:c.catalogId,recipe_id:c.targetId,game_id:this.api.gameId(),nonce:kt()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...lu(p)}}if(this.entity.type!=="players"||this.entity.id!=="me")throw new TypeError("platform-currency purchases are available only on gem.me.mutations");let[r,o]=await Promise.all([ts(this.api,n.signal===void 0?{}:{signal:n.signal}),ft(this.api,n.signal===void 0?{}:{signal:n.signal})]),i=e.payment.currencySlug.toLowerCase(),a=o.currencies.find(c=>c.currency_id.toLowerCase()===i||c.slug.toLowerCase()===i);if(a===void 0){let c=o.currencies.map(p=>p.slug);throw new Ge("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${c.length===0?"none":c.join(", ")}`)}let s=e.kind==="item"?r.items.find(c=>c.item_id===e.targetId):r.recipes.find(c=>c.recipe_id===e.targetId&&c.catalog_id===e.catalogId);if(s===void 0)throw new Ge("not_purchasable",`purchase target ${JSON.stringify(e.targetId)}`+(e.kind==="recipe"?` in catalog ${JSON.stringify(e.catalogId)}`:"")+` is not purchasable in config version ${r.config_version} on this channel. Send the ${e.kind==="item"?"item":"recipe"} id (not its slug), and check that it has platform_prices and that this config version is promoted`);let l=s.platform_prices.find(c=>c.platform_currency_id===a.currency_id);if(l===void 0){let c=g=>o.currencies.find(y=>y.currency_id===g)?.slug??g,p=s.platform_prices.map(g=>`${c(g.platform_currency_id)} ${g.price}`);throw new Ge("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${a.slug} price. It is priced in: ${p.length===0?"nothing":p.join(", ")}`)}let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new Ge("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let m=await this.write(()=>ds(this.api,this.entity.type,this.entity.id,{purchase_kind:e.kind,target_id:e.targetId,...e.kind==="recipe"?{catalog_id:e.catalogId}:{},quantity:d,expected_price:{platform_currency_id:a.currency_id,price:l.price*d},expected_config_version:r.config_version,nonce:kt(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));return du(m)}async executeRecipe(e,n,r={}){return await this.purchase({kind:"recipe",catalogId:e,targetId:n,payment:{kind:"configured"}},r)}async addProgression(e,n,r){let o=await this.write(()=>Ti(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Pn(o)}async maxProgression(e,n,r){let o=await this.write(()=>vs(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Pn(o)}async claimProgression(e,n){let r=await this.write(()=>Ii(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Pn(r)}async resetProgression(e,n){let r=await this.write(()=>xs(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Pn(r)}async write(e){return this.cache.invalidate(),e()}};var Cr=t=>typeof t=="string"?t:"",uu=t=>typeof t=="number"?t:0;function qs(t){let e=t??{};return {orderId:Cr(e.order_id),status:Cr(e.status),source:Cr(e.source),createdAt:uu(e.created_at)}}var Pt=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await gs(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}})??{},o=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {data:Array.isArray(r.orders)?r.orders.map(qs):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await Ki(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return qs(r)}};var Ns=t=>typeof t=="number"?t:0,mu=t=>typeof t=="string"?t:"";function pu(t){let e=t??{};return {progressionDefinitionId:mu(e.progression_definition_id),currentValue:Ns(e.current_value),completionCount:Ns(e.completion_count),isCompleted:e.is_completed===true,...Tr(e)}}var Et=class{constructor(e,n,r){this.api=e;this.entity=n;this.inventory=r;}api;entity;inventory;async list(){return (await this.inventory.snapshot()).progressions.data}async get(e,n){let o=(await this.inventory.snapshot()).progressions.data.find(i=>i.progressionDefinitionId===e);if(o&&o.achievementsUnavailable!==true)return o;try{let i=await Ji(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return pu(i)}catch{return o??null}}};var Tt=class{constructor(e,n){this.clock=e;this.identity=n;}clock;identity;generation=0;slots=new Map;listeners=new Set;boundTo=null;read(e,n,r,o){this.rebind();let i=n.length===0,a=i?e:e+"\0"+n.join("\0"),s=this.slots.get(a);if(s){let c=s.filledAt;if(c!==void 0&&(o===void 0||this.clock.now()-c<=o))return Promise.resolve(s.value);if(s.inFlight)return s.inFlight}let l=s??{};this.slots.set(a,l);let d=this.generation,m=r().then(c=>(i&&this.generation===d&&(l.value=c,l.filledAt=this.clock.now()),c)).finally(()=>{l.inFlight===m&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(a)===l&&this.slots.delete(a));});return l.inFlight=m,m}invalidate(){this.slots.clear(),this.generation+=1;for(let e of [...this.listeners])e();}onInvalidate(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}rebind(){if(!this.identity)return;let e=this.identity();e!==this.boundTo&&(this.boundTo=e,this.invalidate());}};function Ir(t){let e=o=>new RegExp(`<${o}>([^<]{0,300})</${o}>`).exec(t)?.[1]?.trim()||void 0,n=[e("Code"),e("AuthenticationErrorDetail")??e("Message")].filter(Boolean);if(n.length>0)return n.join(" \u2014 ");let r=t.trim();return r?r.slice(0,300):""}async function Mr(t){try{let e=Ir(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var se=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},gu=3e4,Us="the save payload could not reach storage. From a browser this is almost always the storage account's CORS rule, which the platform owns and your game cannot change. If every save fails this way, report it rather than working around it",yu=/^[A-Za-z0-9_]{1,64}$/;function ke(t){let e=t.length===0?"a save key cannot be empty":t.length>64?`it is ${t.length} characters; a save key is at most 64`:t.startsWith("_")||t.startsWith("$")?`it begins with ${JSON.stringify(t[0])}, and \`_\` and \`$\` are reserved prefixes`:"a save key is ASCII letters, digits and underscores only \u2014 no hyphens, spaces or other punctuation, unlike a template slug";if(!yu.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function Bs(t,e){let n=new AbortController,r=AbortSignal.timeout(e),o=()=>n.abort(r.reason),i=()=>n.abort(t?.reason);return t?.aborted?n.abort(t.reason):(r.addEventListener("abort",o,{once:true}),t?.addEventListener("abort",i,{once:true})),{signal:n.signal,release:()=>{r.removeEventListener("abort",o),t?.removeEventListener("abort",i);}}}function Or(t,e){return t.aborted&&e?.aborted!==true}var fu=new Set(["x-ms-blob-type"]),hu=/^[ -~]+$/;function bu(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} described its upload headers as ${Array.isArray(t)?"a list":typeof t}, which is not a set of headers.`);let n={};for(let[r,o]of Object.entries(t)){let i=r.toLowerCase();if(!fu.has(i))throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} asked the upload to send ${JSON.stringify(r)}, which this SDK does not put on a storage request. Report it \u2014 a platform that needs a new upload header needs an SDK release too.`);if(typeof o!="string"||!hu.test(o))throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} gave header ${JSON.stringify(r)} a value that is not usable as one.`);if(i in n)throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(i)} twice.`);n[i]=o;}return n}function Lr(t){let e=typeof t.metadata=="object"&&t.metadata!==null&&!Array.isArray(t.metadata)?t.metadata:void 0;return {key:t.key,sizeBytes:t.size_bytes,etag:t.etag,...e===void 0?{}:{metadata:e},createdAt:t.created_at,updatedAt:t.updated_at}}function Gr(t){return t?.reason==="not_found"}var Ct=class{constructor(e,n,r={}){this.api=e;this.entity=n;this.options=r;}api;entity;options;async put(e,n,r={}){let o;try{o=JSON.stringify(n);}catch(i){throw new se("save_malformed",`save ${JSON.stringify(e)} could not be serialised to JSON: ${String(i)}. Retrying stores the same unserialisable value.`)}if(o===void 0)throw new se("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(o),{...r,contentType:"application/json"})}async putBytes(e,n,r={}){let o=r.contentType??"application/octet-stream",i=this.budget(r.timeoutMs),a=Bs(r.signal,i);try{let s=await ks(this.api,this.entity.type,this.entity.id,ke(e),{size_bytes:n.byteLength,content_type:o,...r.metadata===void 0?{}:{metadata:r.metadata}},{signal:a.signal});if(typeof s.upload_url!="string"||typeof s.session_id!="string")throw new se("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let l=bu(s.upload_headers,e),d,m=this.options.fetch??globalThis.fetch.bind(globalThis);try{d=await m(s.upload_url,{method:"PUT",headers:{"content-type":o,...l},body:n,credentials:"omit",signal:a.signal});}catch(c){throw Or(a.signal,r.signal)?this.timeout("upload",i):new se("upload_failed",`${Us} for PUT. Underlying error: ${c}`)}if(!d.ok){let c=await Mr(d);throw new se("upload_failed",d.status===400?"the save upload answered 400. The platform and the service holding the bytes disagree about what this upload must carry, which is not something your game can fix and not worth retrying \u2014 report it. "+c:`the save upload answered ${d.status}. `+(d.status===403?"An upload URL is short-lived, so this is most likely an expired one \u2014 start the save again rather than retrying the upload. ":"")+c)}return Lr(await ji(this.api,this.entity.type,this.entity.id,ke(e),{session_id:s.session_id},{signal:a.signal}))}catch(s){throw this.rethrow(s,r.signal,a.signal,"save",i)}finally{a.release();}}async get(e,n={}){let r=await this.getBytes(e,n);if(r===null)return null;try{return JSON.parse(new TextDecoder().decode(r))}catch(o){throw new se("save_malformed",`the stored save ${JSON.stringify(e)} is not JSON, so put() did not write it. Read it with getBytes() and decode it yourself. Underlying error: ${o}`)}}async getBytes(e,n={}){let r=this.budget(n.timeoutMs),o=Bs(n.signal,r);try{let i;try{let l=await Rr(this.api,this.entity.type,this.entity.id,ke(e),{signal:o.signal});if(!l.modified)return null;i=l.body;}catch(l){if(Gr(l))return null;throw l}if(typeof i.download_url!="string")throw new se("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let a=this.options.fetch??globalThis.fetch.bind(globalThis),s;try{s=await a(i.download_url,{credentials:"omit",signal:o.signal});}catch(l){throw Or(o.signal,n.signal)?this.timeout("download",r):new se("download_failed",`${Us} for GET. Underlying error: ${l}`)}if(!s.ok){let l=await Mr(s);throw new se("download_failed",`the save download answered ${s.status}. `+(s.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+l)}return new Uint8Array(await s.arrayBuffer())}catch(i){throw this.rethrow(i,n.signal,o.signal,"load",r)}finally{o.release();}}async describe(e,n={}){try{let r=await Rr(this.api,this.entity.type,this.entity.id,ke(e),{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?Lr(r.body):null}catch(r){if(Gr(r))return null;throw r}}async list(e={}){let n=await ys(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}}),r=n.next_cursor;return {saves:(n.data??[]).map(Lr),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await Di(this.api,this.entity.type,this.entity.id,ke(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!Gr(r))throw r}}budget(e){return e??this.options.timeoutMs??gu}timeout(e,n){return new se("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,o,i){return e instanceof se?e:Or(r,n)?this.timeout(o,i):e}};function vu(t){try{return Sr(t)}catch{return t}}function Dr(t,e){let n=t??{},r=typeof n.etag=="string"?n.etag:e;return {key:typeof n.key=="string"?n.key:"",value:typeof n.value=="string"?vu(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var It=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await ps(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(o=>Dr(o)):[]}async get(e,n={}){try{let r=await Bi(this.api,this.entity.type,this.entity.id,e,{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?Dr(r.body,r.etag):null}catch(r){if(Hs(r))return null;throw r}}async put(e,n,r={}){let o=await _s(this.api,this.entity.type,this.entity.id,e,{value:gt(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return Dr(o)}async delete(e,n){try{await Gi(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});}catch(r){if(!Hs(r))throw r}}};function Hs(t){return t?.reason==="not_found"}function Mt(t,e,n={}){let r=new Tt(le,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let o=new Rt(t,e,r);return {settings:new It(t,e),inventory:o,saves:new Ct(t,e,n.saves??{}),currencies:new St(o,n.resolveCurrencyId),mutations:new At(t,e,r),orders:new Pt(t,e),progressions:new Et(t,e,o)}}var $r={type:"players",id:"me"};var qe=t=>typeof t=="string"?t:"",ln=t=>typeof t=="number"?t:0;function Ot(t,e){let n=e??{},r=qe(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:qe(n.player_id),gameId:qe(n.game_id),channel:qe(n.channel)||"release",name:qe(n.name),slotIndex:ln(n.slot_index),isActive:n.is_active!==false,createdAt:qe(n.created_at),updatedAt:qe(n.updated_at)}}var Lt=class{constructor(e,n,r,o){this.api=e;this.saves=n;this.identity=r;this.resolveCurrencyId=o;}api;saves;identity;resolveCurrencyId;scopes=new Map;scope=e=>{let n=this.scopes.get(e);return n||(n=Mt(this.api,{type:"characters",id:e},{saves:this.saves,identity:this.identity,resolveCurrencyId:this.resolveCurrencyId}),this.scopes.set(e,n)),n};async list(e){let r=(await ms(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(o=>Ot(this.scope,o)):[]}async get(e,n){let r=await Ni(this.api,e,n===void 0?{}:{signal:n});return Ot(this.scope,r)}async create(e){let n=await Mi(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return Ot(this.scope,n)}async update(e,n,r){let o=await Rs(this.api,e,{name:n},r===void 0?{}:{signal:r});return Ot(this.scope,o)}async delete(e,n){await As(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await is(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:ln(r?.total_slots),availableSlots:ln(r?.available_slots),activeCharacterCount:ln(r?.active_character_count),defaultMaxSlots:ln(r?.default_max_slots),purchasedExtraSlots:ln(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var pe=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 ye(t){return new pe(t)}var Ne={toPlain(t){return pe.unwrap(t)},compare(t,e,n){let r=t instanceof pe?pe.unwrap(t):t,o=e instanceof pe?pe.unwrap(e):e,i;try{i=new Intl.Collator(n);}catch{i=new Intl.Collator;}return i.compare(r,o)},equals(t,e){let n=t instanceof pe?pe.unwrap(t):t,r=e instanceof pe?pe.unwrap(e):e;return n.normalize("NFC")===r.normalize("NFC")}};var dn=t=>typeof t=="string"?t:"";function Gt(t){let e=t??{},n=typeof e.message=="string"&&e.message.length>0?e.message:void 0,r=typeof e.resolved_at=="string"?e.resolved_at:void 0;return {id:dn(e.transfer_id),status:dn(e.status),sourceEntityId:dn(e.source_entity_id),targetEntityId:dn(e.target_entity_id),...n===void 0?{}:{message:ye(n)},createdAt:dn(e.created_at),expiresAt:dn(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function _u(){return crypto.randomUUID()}var Dt=class{constructor(e,n,r){this.api=e;this.self=n;this.inventory=r;}api;self;inventory;async initiate(e){this.inventory.invalidate();let n=await ls(this.api,{source_entity_type:this.self.type,source_entity_id:this.self.id,target_entity_type:e.to.type,target_entity_id:e.to.id,items:(e.items??[]).map(r=>({item_definition_id:r.itemDefinitionId,quantity:r.quantity})),currencies:(e.currencies??[]).map(r=>({currency_id:r.currencyId,amount:r.amount})),...e.message===void 0?{}:{message:e.message},nonce:_u()},e.signal===void 0?{}:{signal:e.signal});return Gt(n)}async list(e={}){let r=await hs(this.api,{entity_type:this.self.type,entity_id:this.self.id,...e.direction===void 0?{}:{direction:e.direction},...e.status===void 0?{}:{status:e.status},...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit},...e.signal===void 0?{}:{signal:e.signal}})??{},o=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {transfers:Array.isArray(r.transfers)?r.transfers.map(Gt):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await ss(this.api,e,n===void 0?{}:{signal:n});return Gt(r)}async accept(e,n){return this.resolve(()=>Ei(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>Ss(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>Ci(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),Gt(await e())}};var wu=t=>typeof t=="string"?t:"",Su=t=>typeof t=="string"&&t?t:void 0,Ru=t=>typeof t=="number"?t:void 0;function Vs(t){let e=new Map(t.map(r=>[r.id,r])),n=new Map(t.filter(r=>r.slug).map(r=>[r.slug,r]));return r=>e.get(r)??n.get(r)??null}function ku(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new ce("config_malformed",`the config document is ${t===null?"null":typeof t}, expected a JSON object`);let e=t,n=l=>{let d=e[l];if(d==null)return [];if(!Array.isArray(d))throw new ce("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=Ru(e.version);if(r===void 0)throw new ce("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let o=(l,d,m)=>{let c=wu(l.id);if(!c)throw new ce("config_malformed",`${d}[${m}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return c},i=n("items");i.forEach((l,d)=>o(l??{},"items",d));let a=n("currencies");a.forEach((l,d)=>o(l??{},"currencies",d));let s=t;return {...s,version:r,hash:typeof s.hash=="string"?s.hash:"",items:i,currencies:a,catalogs:n("catalogs"),loot_tables:n("loot_tables"),affix_pools:n("affix_pools"),progressions:n("progressions"),game_room_templates:n("game_room_templates"),kv:typeof s.kv=="object"&&s.kv!==null&&!Array.isArray(s.kv)?s.kv:{},item:Vs(i),currency:Vs(a)}}var ce=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},Ws=10*1024*1024,Ks=15e3,Js=new Set(["dev","test","release"]);function xu(t){if(!Js.has(t))throw new ce("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...Js].join(", ")}. gem-api would reject the assignment read.`);return t}var $t=t=>typeof t=="number"?t:0,Fr=t=>typeof t=="string"?t:"";function Au(t){let e=t??{},n=Array.isArray(e.entries)?e.entries.map(r=>{let o=r??{},i=typeof o.rarity_tier=="string"?o.rarity_tier:void 0;return {entryId:Fr(o.entry_id),weight:$t(o.weight),dropRate:$t(o.drop_rate),...i===void 0?{}:{rarityTier:i}}}):[];return {lootTableId:Fr(e.loot_table_id),name:Fr(e.name),rollCount:$t(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:$t(e.total_weight),entries:n}}var Ft=class{constructor(e,n,r={}){this.api=e;this.channel=n;this.options=r;}api;channel;options;loaded=null;inFlight=null;generation=0;dropRatesByConfig=new WeakMap;load(){if(this.loaded)return Promise.resolve(this.loaded);if(this.inFlight)return this.inFlight;let e=this.generation,n=this.fetchConfig().then(r=>(this.generation===e&&(this.loaded=r),r)).finally(()=>{this.inFlight===n&&(this.inFlight=null);});return this.inFlight=n,n}refresh(){this.loaded=null,this.inFlight=null,this.generation+=1;}async dropRates(e,n){let r=await this.load();if(r===null)throw new ce("config_channel_unknown",`dropRates(${e}) needs a loaded config, and this session's channel has none`);let o=this.dropRatesByConfig.get(r);o===void 0&&(o=new Map,this.dropRatesByConfig.set(r,o));let i=o.get(e);if(i!==void 0)return i;let a=(async()=>{let s=await Ui(this.api,e,n===void 0?{}:{signal:n});return Au(s)})().catch(s=>{throw o?.get(e)===a&&o.delete(e),s});return o.set(e,a),a}async fetchConfig(){let e=AbortSignal.timeout(this.options.timeoutMs??Ks),n;try{let l=await qi(this.api,xu(this.channel()),{signal:e});if(!l.modified)throw new ce("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");n=l.body;}catch(l){if(l instanceof ce)throw l;if(l?.reason==="not_found")return null;throw l}let r=Su(n.config_url);if(r===void 0)return null;let o=this.options.fetch??globalThis.fetch.bind(globalThis),i;try{i=await o(r,{credentials:"omit",signal:e});}catch(l){throw e.aborted?new ce("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??Ks}ms`):new ce("config_unreachable",`could not fetch the game config document. From a browser this is almost always the storage CORS rule: the storage account must allow this game origin for GET. It is NOT a CSP problem \u2014 game origins carry no fetch directives by design. Underlying error: ${String(l)}`)}if(!i.ok){let l=await i.text().then(d=>Ir(d)).catch(()=>"");throw new ce("config_unreachable",`the config document answered ${i.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let a=await i.text();if(a.length>Ws)throw new ce("config_too_large",`the config document is ${a.length} bytes, over the ${Ws} cap`);let s;try{s=JSON.parse(a);}catch(l){throw new ce("config_malformed",`config document is not JSON: ${String(l)}`)}return ku(s)}};var zs=400,xe=t=>typeof t=="string"?t:"",Pu=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Ue(t){let e=xe(t);if(!Pu.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var Eu=/^[0-9a-f]{1,64}$/,Tu=/^[0-9a-f]{16}$/,Cu=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,Iu=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function jr(t){let e=xe(t),n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!n)return;let[r,o,i]=[Number(n[1]),Number(n[2]),Number(n[3])],a=new Date(Date.UTC(r,o-1,i));return a.getUTCFullYear()===r&&a.getUTCMonth()===o-1&&a.getUTCDate()===i?e:void 0}var Mu=4096,Ou=new TextEncoder;function Lu(t){let e=xe(t.challenge_data),n=xe(t.challenge_data_hash);return e===""||!Tu.test(n)?{}:Ou.encode(e).length>Mu?{}:{data:e,dataHash:n}}function Gu(t){let e=t??{},n=Ue(e.period_start_at),r=Ue(e.period_ends_at);if(n===0||r===0)return;let o=xe(e.slug),i=xe(e.seed),a=jr(e.period_local_date),s=xe(e.boundary),l=xe(e.reset_time);return {id:xe(e.progression_definition_id),...o===""?{}:{slug:o},window:xe(e.window),periodStartAt:n,periodEndsAt:r,...a===void 0?{}:{periodLocalDate:a},boundary:Cu.test(s)?s:"",resetTime:Iu.test(l)?l:"",seed:Eu.test(i)?i:"",...Lu(e)}}function cn(t){if(t!==void 0&&(!Number.isInteger(t)||t<0||t>400))throw new TypeError(`periodsBack must be an integer between 0 and 400, got ${String(t)}`)}function jt(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(Gu).filter(n=>n!==void 0):[]}var En=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;cn(n);let r=await us(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return jt(r)}};function Be(t){return typeof t=="string"&&t!==""?t:void 0}var Ys=new Set(["localhost","127.0.0.1","[::1]"]);function qr(t){let e=Be(t);if(e===void 0)return;let n;try{n=new URL(e);}catch{return}if(!(n.username!==""||n.password!=="")&&(n.protocol==="https:"||n.protocol==="http:"&&Ys.has(n.hostname)))return e}function Du(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},o=Be(r.item_id),i=qr(r.icon_url);o!==void 0&&i!==void 0&&e.push({itemId:o,iconUrl:i});}return e}function ve(t){let e=t??{},n=Be(e.player_id),r=Be(e.display_name),o=Be(e.discriminator),i=Be(e.display_tag),a=Be(e.avatar_icon_id),s=qr(e.avatar_icon_url);return {...n===void 0?{}:{playerId:n},...r===void 0?{}:{displayName:ye(r)},...o===void 0?{}:{discriminator:o},...i===void 0?{}:{displayTag:ye(i)},...a===void 0?{}:{avatarIconId:a},...s===void 0?{}:{avatarIconUrl:s},badges:Du(e.badges)}}var $u=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function Fu(t){if(t===void 0)return;let e=qr(t);if(e===void 0)return;let n=new URL(e);return Ys.has(n.hostname)||$u.has(n.origin)?e:void 0}var Xs=100,ea=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function Nr(t){let{periodsBack:e,period:n,playerId:r}=t;if(cn(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!ea.test(n)))throw new TypeError(`period must be a period id such as 2026-10-02 (a result's period.id), got ${String(n)}`);if(r!==void 0&&(typeof r!="string"||r===""))throw new TypeError("playerId must be a player id");return {...e===void 0?{}:{periods_back:e},...n===void 0?{}:{period:n},...r===void 0?{}:{player_id:r}}}function na(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!ea.test(e))return;let n=jr(t.period_local_date),r=Ue(t.period_start_at),o=Ue(t.period_ends_at),i=r>0&&o>0;return {id:e,...n===void 0?{}:{localDate:n},...i?{startAt:r,endsAt:o}:{},opensAt:Ue(t.opens_at),closesAt:Ue(t.closes_at),final:t.final===true}}var Tn=t=>typeof t=="string"?t:"",un=t=>typeof t=="number"?t:0,Cn=t=>typeof t=="string"?t:void 0,ju=t=>typeof t=="number"?t:void 0,ta={player:"players",character:"characters"};function qu(t,e){let n=t??{},r=Cn(n.entity_id),o=typeof n.entity_type=="string"&&Object.hasOwn(ta,n.entity_type)?n.entity_type:void 0,i=ra(n.stats),a=n.properties!==null&&typeof n.properties=="object"?n.properties:void 0,s=e?n.is_viewer===true:void 0;return {...ve(n),rank:un(n.rank),occurredAt:un(n.occurred_at),...s===void 0?{}:{isViewer:s},...r===void 0?{}:{entityId:r},...o===void 0?{}:{entityType:o},...i===void 0?{}:{stats:i},...a===void 0?{}:{properties:a}}}function Qs(t,e){let n=t??{},r=Cn(n.bucket_1),o=Cn(n.bucket_2),i=ju(n.update_frequency_seconds),a=na(n);return {leaderboardType:Tn(n.leaderboard_type),runType:Tn(n.run_type),...r===void 0?{}:{bucket1:r},...o===void 0?{}:{bucket2:o},entries:Array.isArray(n.entries)?n.entries.map(s=>qu(s,e)):[],generatedAt:un(n.generated_at),...i===void 0?{}:{updateFrequencySeconds:i},...a===void 0?{}:{period:a}}}function Zs(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=ra(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:un(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function ra(t){if(t===null||typeof t!="object")return;let e={};for(let[n,r]of Object.entries(t))typeof r=="number"&&(e[n]=r);return e}function Nu(t,e,n){let r=t??{},o=Cn(r.bucket_1),i=Cn(r.bucket_2),a=na(r);return {leaderboardType:Tn(r.leaderboard_type),runType:Tn(r.run_type),entityType:e,entityId:n,...o===void 0?{}:{bucket1:o},...i===void 0?{}:{bucket2:i},entries:Array.isArray(r.entries)?r.entries.map(Zs).filter(s=>s!==void 0):[],personalBest:Zs(r.personal_best)??null,totalRuns:un(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:un(r.generated_at),...a===void 0?{}:{period:a}}}var In=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=Nr(n),o=await Zi(this.#e,e,{...r,...n.bucket1===void 0?{}:{bucket_1:n.bucket1},...n.bucket2===void 0?{}:{bucket_2:n.bucket2},...n.signal===void 0?{}:{signal:n.signal}});return Qs(o,false)}async friends(e,n={}){let r=Nr(n),o=await Xi(this.#e,e,{...r,...n.bucket1===void 0?{}:{bucket_1:n.bucket1},...n.bucket2===void 0?{}:{bucket_2:n.bucket2},...n.signal===void 0?{}:{signal:n.signal}});return Qs(o,true)}async mine(e,n={}){return this.#t(e,"player","me",n)}async character(e,n,r={}){return this.#t(e,"character",n,r)}async#t(e,n,r,o){if(o.limit!==void 0){let{limit:l}=o;if(!Number.isInteger(l)||l<1||l>Xs)throw new TypeError(`limit must be an integer between 1 and ${Xs}, got ${String(l)}`)}let i=Nr(o),a=await Wi(this.#e,e,ta[n],r,{...i,...o.bucket1===void 0?{}:{bucket_1:o.bucket1},...o.bucket2===void 0?{}:{bucket_2:o.bucket2},...o.limit===void 0?{}:{limit:o.limit},...o.signal===void 0?{}:{signal:o.signal}}),s=n==="player"&&r==="me"&&Tn((a??{}).entity_id)||r;return Nu(a,n,s)}};var qt=t=>typeof t=="string"?t:"",Ur=t=>typeof t=="number"?t:0;function oa(t){let e=t??{};return {playerId:qt(e.player_id),key:qt(e.key),value:e.value,updatedAt:Ur(e.updated_at)}}function Uu(t){let e=t??{};return {...ve(e),playerId:qt(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:Ur(e.updated_at)}}function Bu(t){return t?.reason==="not_found"}var Mn=class{constructor(e,n){this.api=e;this.selfPlayerId=n;}api;selfPlayerId;async friends(e,n={}){let o=await Qi(this.api,ke(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:qt(o.key),entries:Array.isArray(o.entries)?o.entries.map(Uu):[],generatedAt:Ur(o.generated_at)}}async of(e,n,r={}){try{return oa(await os(this.api,e,ke(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(o){if(Bu(o))return null;throw o}}async set(e,n,r={}){if(ke(e),n===void 0)throw new TypeError(`showcase value for ${JSON.stringify(e)} is undefined, which is not JSON. Use clear() to remove one.`);try{JSON.stringify(n);}catch(i){throw new TypeError(`showcase value for ${JSON.stringify(e)} could not be serialised to JSON: ${String(i)}.`,{cause:i})}let o=await this.selfPlayerId();return oa(await ws(this.api,o,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await $i(this.api,r,ke(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var He=class extends G{constructor(e,n={}){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="FriendChallengeError";for(let[r,o]of Object.entries(n))o!==void 0&&Object.assign(this,{[r]:o});}},ia=t=>typeof t=="string"?t:void 0;function Hu(t){let e=t??{};return {...ve(e),playerId:ia(e.player_id)??""}}function Vu(t){let e=t??{},n=e.has_more===true?ia(e.next_cursor):void 0;return {friends:Array.isArray(e.data)?e.data.map(Hu):[],...n===void 0?{}:{nextCursor:n}}}var On=class{#e;#t;constructor(e,n={}){this.#e=e,this.#t=n.challenge;}async list(e={}){let n=await fs(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Vu(n)}challenge(e){return this.#t===void 0?Promise.resolve({outcome:"unavailable"}):this.#t(e)}};var Wu=0;function Ae(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++Wu)}-${String(Date.now())}-${t}`}}var Ku=12e4,sa=8,Ju=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,zu=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Ln(t,e,n={}){return new He(new G("invalid",400,e,void 0,t),n)}function Yu(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Xu(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!Ju.test(e))return {error:Ln("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!zu.test(n))return {error:Ln("unknown_template","template must be a friend_challenge_templates key from this game's config")};if(r===void 0)return {playerId:e,template:n,params:void 0};if(!Yu(r))return {error:Ln("param_invalid","params must be a plain object of strings and integers")};let o={},i=Object.keys(r);for(let a of i){let s=r[a];if(typeof s=="string"||typeof s=="number"&&Number.isSafeInteger(s)){Object.defineProperty(o,a,{value:s,enumerable:true,writable:true,configurable:true});continue}return {error:Ln("param_invalid",`params.${a} must be a string or a safe integer`,{param:a})}}return i.length>sa?{error:Ln("param_undeclared",`params has ${String(i.length)} keys; a template declares at most ${String(sa)}`)}:{playerId:e,template:n,params:o}}function Qu(t){switch(t.outcome){case "accepted":case "cancelled":case "refused":case "unavailable":return {outcome:{outcome:t.outcome}};case "rate_limited":{let e=t.retryAfterMs,n=typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.ceil(e/1e3):void 0;return {error:new He(new G("rate_limited",429,"this player has sent too many friend challenges; only a fresh press may ask again",n,"rate_limited"))}}case "invalid":{let e=typeof t.code=="string"?t.code:void 0,n=typeof t.detail=="string"&&t.detail!==""?t.detail:e??"the friend challenge request was refused as invalid";return {error:new He(new G("invalid",400,n,void 0,e),{...typeof t.param=="string"?{param:t.param}:{},...typeof t.channel=="string"?{channel:t.channel}:{},...typeof t.configVersion=="number"?{configVersion:t.configVersion}:{}})}}default:return {outcome:{outcome:"unavailable"}}}}function Zu(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function aa(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=Xu(n);if("error"in r)return Promise.reject(r.error);let o=`challenge-${Ae()}`;return new Promise((i,a)=>{let s={},l=m=>{e.delete(o)&&(t.clock.clearTimeout(s.timer),"error"in m?a(m.error):i(m.outcome));};e.set(o,l),s.timer=t.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},t.timeoutMs??Ku);let d=false;try{d=t.bridge.requestFriendChallenge(o,r.playerId,r.template,r.params);}catch{}d||l({outcome:{outcome:"unavailable"}});})},settle(n){let r=e.get(n.requestId);if(r===void 0){t.onDropped?.(`gem.friendChallengeResult (${Zu(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(Qu(n));}}}var Nt=t=>typeof t=="string"?t:void 0;function em(t){let e=t??{},n=Nt(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Nt(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var Ut=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await ft(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let a=em(i);a!==void 0&&o.push(a);}return o}},Br=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function nm(t){let e=t??{},n=Nt(e.currency_id);if(n===void 0||n==="")return;let r=Br(e.limit),o=Math.min(Br(e.earned),r),i=Math.min(Br(e.remaining),r-o),a=e.period_days,s=typeof a=="number"&&Number.isInteger(a)&&a>=1?a:1,l=e.resets_at,d=typeof l=="number"&&Number.isFinite(l)&&l>0?Math.round(l*1e3):void 0;return {currencySlug:Nt(e.currency_slug)??"",currencyId:n,limit:r,earned:o,remaining:i,period:e.period==="day"?"day":"window",periodDays:s,...d===void 0?{}:{resetsAt:d}}}function la(t){let e=new Set,n=r=>{t?.(`[gem] an earnAllowance 'changed' listener threw: ${r instanceof Error?r.message:String(r)}`);};return {on(r){return e.add(r),()=>{e.delete(r);}},emit(){for(let r of [...e])try{let o=r();typeof o?.then=="function"&&o.then(void 0,n);}catch(o){n(o);}}}}var Bt=class{#e;#t;#l;constructor(e,n,r){this.#e=e,this.#t=n,this.#l=r;}async get(e={}){let r=(await es(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let a=nm(i);a!==void 0&&o.push(a);}return o}on(e,n){return e!=="changed"?(this.#l?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#t?.on(n)??(()=>{})}},Gn=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new Ut(e),this.earnAllowance=new Bt(e,n,r);}};var Hr=t=>typeof t=="string"?t:"",da=t=>typeof t=="number"?t:0;function tm(t){let e=t??{};return {key:Hr(e.key),visibility:Hr(e.visibility),value:e.value,updatedAt:da(e.updated_at)}}function rm(t){let e=t??{};return {...ve(e),playerId:Hr(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(tm):[],generatedAt:da(e.generated_at)}}function om(t){return t?.reason==="not_found"}var Dn=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return rm(await ns(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(om(r))return null;throw r}}};var im=new Map([["function_error",false],["function_failed",false],["function_timeout",false],["function_not_published",false],["function_input_too_large",false],["functions_not_configured",false],["forbidden",false],["function_capacity_unavailable",true],["function_host_unreachable",true],["function_host_error",true],["rate_limited",true],["service_unavailable",true]]),$n=class extends G{constructor(e,n){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="GemFunctionError",Object.assign(this,n);}get retryable(){return (this.code===void 0?void 0:im.get(this.code))??super.retryable}},De=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=sm(e),o;try{o=await this.#e(r,n.signal===void 0?{}:{signal:n.signal});}catch(i){throw i instanceof G?lm(i):i}return am(o)}};function sm(t){if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);let e;try{e=JSON.stringify(t);}catch(n){throw new oe(`the function input could not be serialised to JSON: ${String(n)}. Pass bytes, or a value JSON can carry. This is a bug in the call, not a server failure.`)}if(e===void 0)throw new oe(`the function input is ${typeof t}, which JSON cannot carry. Pass bytes \u2014 an empty Uint8Array for no input \u2014 or a JSON value. This is a bug in the call, not a server failure.`);return new TextEncoder().encode(e)}function am(t){let{bytes:e}=t,n=()=>new TextDecoder("utf-8",{fatal:true}).decode(e);return {bytes:e,...t.invocationId===void 0?{}:{invocationId:t.invocationId},text:n,json:()=>JSON.parse(n())}}function lm(t){let{details:e,invocationId:n}=Pi(t),o=e?.untrusted?.message,i=e?.reason;return new $n(t,{...n===void 0?{}:{invocationId:n},...t.code==="function_error"&&typeof o=="string"?{functionMessage:o}:{},...t.code==="function_failed"&&typeof i=="string"?{failure:i}:{}})}var dm=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],Vr="gem_";function ca(t){return t.startsWith(Vr)}var ua=1e4,ma=50,cm=500,um=65536-4*1024,mm=24*1024;function pa(t){let e={},n={};for(let[r,o]of Object.entries(t))typeof o=="string"?e[r]=o:typeof o=="number"&&Number.isFinite(o)&&(n[r]=o);return {dimensions:e,measures:n}}var ga=t=>typeof t=="number"?t:0,pm=t=>typeof t=="string"?t:"";function Wr(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function gm(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:ga(i.index),code:pm(i.code)}}):[];return {accepted:ga(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Kr(){let t=globalThis.crypto;return typeof t?.randomUUID=="function"?t.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.floor(Math.random()*16);return (e==="x"?n:n&3|8).toString(16)})}function ym(t){return t?.retryable===true}var Fn=class{#e;#t;#l;#y;#n=[];#f={};#i=0;#s=null;#h=false;#b=false;#v=false;#r=false;#_=null;#a=null;#d=false;#o=false;#m=false;#w=false;#S=false;constructor(e){this.#e=e,this.#t=e.options?.enabled!==false,this.#l=Math.max(ua,e.options?.flushIntervalMs??ua),this.#y=Math.max(1,Math.floor(e.options?.maxQueue??cm));}track(e,n={}){if(!(!this.#t||this.#r)){if(ca(e)){this.#S||(this.#S=true,this.#g(`[gem] analytics: '${e}' was not recorded \u2014 the gem_ prefix is reserved for the platform's own events, which the SDK emits for you. Name your event something else.`));return}this.#R(e,pa({...this.#f,...n}));}}setContext(e){this.#f={...this.#f,...e};}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#o)return Wr();let n=this.#E();if(n===null||n==="")return this.#n.length>0&&!this.#w&&(this.#w=true,this.#g("[gem] analytics: events are being recorded but no play session has been established, so nothing is being sent. Outside the arcade this is expected.")),Wr();if(this.#k(),this.#n.length===0)return Wr();let r=e.keepalive===true;this.#u();let o=this.#n.splice(0,this.#A(r)),i=this.#i;this.#i=0;let a=Math.round(this.#e.clock.now()),s={batch_id:Kr(),sent_at_ms:a,events:o.map(d=>ya(d,a))},l={client:this.#e.client(),gameId:()=>n};this.#v=true;try{let d=await as(l,s,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=gm(d,i);return this.#P(m),m}catch(d){throw ym(d)?this.#x(o,i):this.#g(`[gem] analytics: ${o.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#v=false,this.#n.length>0&&this.#c();}}trackPlatform(e,n={}){this.#r||this.#o&&(e==="gem_pause"||e==="gem_resume")||this.#R(e,pa(n));}hold(){this.#r||this.#a!==null||(this.#o=true,this.#u());}release(){if(!this.#o||this.#r)return;this.#o=false;let e=this.#e.clock.now(),n=this.#n.map(r=>({...r,atMs:e}));this.#n=n,this.#m&&(this.#m=false,this.#a=e,this.#d=false,this.#n.unshift({uid:Kr(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#n.length>=ma?this.#p():this.#n.length>0&&this.#c();}get held(){return this.#o}startSession(){if(!(this.#r||this.#a!==null)){if(this.#o){this.#m=true;return}this.#a=this.#e.clock.now(),this.#d=false,this.trackPlatform("gem_session_start");}}endSession(e){if(this.#r||this.#d)return;if(this.#d=true,this.#o){this.#m=false,this.#n=[],this.#i=0;return}let n=this.#a;this.trackPlatform("gem_session_end",{reason:e,...n===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-n))}}),this.#p({keepalive:true});}setPaused(e){this.#r||e===this.#h||(this.#h=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#u():this.#n.length>0&&this.#c());}setHidden(e){this.#r||e===this.#b||(this.#b=e,e?this.#u():this.#n.length>0&&this.#c());}dispose(){this.#r=true,this.#u(),this.#n=[],this.#i=0;}get pending(){return this.#n.length}#R(e,n){let{dimensions:r,measures:o}=n;for(this.#k();this.#n.length>=this.#y;)this.#n.shift(),this.#i+=1;this.#n.push({uid:Kr(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:o}),this.#n.length>=ma?this.#p():this.#c();}#p(e={}){this.flush(e).catch(()=>{});}#x(e,n){for(this.#n=[...e,...this.#n],this.#i+=n;this.#n.length>this.#y;)this.#n.shift(),this.#i+=1;}#A(e){let n=e?mm:um,r=Math.min(this.#n.length,100),o=128;for(let i=0;i<r;i+=1){let a=this.#n[i];if(a===void 0)break;if(o+=JSON.stringify(ya(a,0)).length+1,o>n)return Math.max(1,i)}return r}#c(){this.#s!==null||this.#h||this.#b||this.#o||this.#r||this.#v||(this.#s=this.#e.clock.setTimeout(()=>{this.#s=null,this.#p();},this.#l));}#u(){this.#s!==null&&(this.#e.clock.clearTimeout(this.#s),this.#s=null);}#k(){let e=this.#T();e===null||e===""||(this.#_!==null&&this.#_!==e&&(this.#n=[],this.#i=0,this.#a=null,this.#d=false),this.#_=e);}#P(e){for(let n of e.rejected)this.#g(`[gem] analytics: an event was refused (${n.code}). `+fm(n.code));}#g(e){let n=this.#e.log;n!==null&&(n===void 0?console.warn(e):n(e));}#E(){try{return this.#e.gameId()}catch{return null}}#T(){try{return this.#e.playerId()}catch{return null}}};function ya(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:t.dimensions,measures:t.measures}}function fm(t){switch(t){case "analytics_not_declared":return "This channel has no analytics_events section at all \u2014 promote a game config that declares one. The gem_* events in the same batch were still recorded.";case "unknown_event":return "This channel declares a set of events and this name is not in it \u2014 check the spelling, or declare it in analytics_events.";case "unknown_dimension":return "A string property on this event is not declared as one of its dimensions.";case "missing_dimension":return "A dimension this event declares was not supplied.";case "dimension_value_not_declared":return "A dimension value is outside the closed set the config declares for it.";case "unknown_measure":return "A numeric property on this event is not declared as one of its measures.";case "measure_wrong_type":return "A measure was the wrong shape \u2014 an int measure refuses a fractional value.";case "source_not_permitted":return "This event is declared for the server only, so a client may not emit it.";default:return "See the analytics_events section of your game config."}}function me(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e}function jn(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=me(n);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var hm=2e3,bm=5e3;function ha(t){let e=[],n=false,r=null,o=new Map,i=()=>{if(e.length>0)return Promise.resolve(e);if(n)return Promise.resolve([]);if(!t.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,t.clock.clearTimeout(m),l(c));},m=t.clock.setTimeout(()=>{n=true,a([]);},t.timeoutMs??hm);});return r={promise:s,settle:a},s};return {resolveList:i,resolve(){return e.length>0||n||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):i().then(a=>a[0])},refresh(a){return !fa(e,a)||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(s=>{let l=null,d=m=>{o.delete(d)&&(t.clock.clearTimeout(l),s(m));};o.set(d,a),l=t.clock.setTimeout(()=>d(e),t.refreshTimeoutMs??bm);})},accept(a,s){let l=jn(s),d=me(a),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[c,p]of [...o])fa(m,p)||c(m);}}}}function fa(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var vm=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),b=class extends Error{constructor(n,r,o){super(`${n}: ${r}`,o);this.reason=n;this.name="DedicatedServerError",this.retryable=vm.has(n),this.platformCode=o?.platformCode;}reason;retryable;platformCode};var ba=["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"],_m=new Set(ba);function $e(t){return typeof t=="string"&&_m.has(t)?t:"unknown"}var Ht="webrtc_dedicated",Xr=["universal","mobile","web"];var wm="p2p_unavailable",Sm="capacity_unavailable",Rm=2,va=3e4,_a=1e3,wa=2e4;async function Qr(t){let e=me(t.clusterTargetId),n=t.nextClusterTarget,r=0,o=t.clock??le,i=t.retry??{},a=i.budgetMs??va,s=i.maxDelayMs??wa,l=i.initialDelayMs??_a,d=o.now(),m=d+a,c=0;for(;;){c++;try{let p=await to(t.signal,"while allocating",()=>t.client.post(`${ka(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!km(p)||a<=0)throw p;if(p.status===503&&p.code===wm)throw new b("p2p_unavailable",`room ${t.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===Sm?r+1:0,n!==void 0&&r>=Rm){let I=n;n=void 0;let M=me(await I());M!==void 0&&(e=M,r=0);}let g=Math.min(s,l*2**(c-1)),y=Math.min(s,(p.retryAfterSeconds??0)*1e3),R=Math.max(g/2,y)+Math.random()*(g/2);if(o.now()+R>m)throw xm(t,p,c,o.now()-d,a);if(i.onWaiting?.({attempt:c,elapsedMs:o.now()-d,budgetMs:a,nextAttemptInMs:R,status:p.status,message:p.message}),await Vt(o,R,t.signal),t.signal?.aborted)throw Yr("while waiting to allocate")}}}function km(t){return t instanceof G?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function xm(t,e,n,r,o){let i=`${n} attempt${n===1?"":"s"} over ${r}ms of a ${o}ms budget`;return e.status===429?new b("start_rate_limited",`the platform was still limiting match starts for room ${t.roomId} after ${i}: ${e.message}`,{cause:e}):new b("no_server_ready",`the platform had no server ready for room ${t.roomId} after ${i}: ${e.message}`,{cause:e})}var Am=12e4,Pm=1e3;async function Zr(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??Pm,o=t.timeoutMs??Am,i=e.now()+o,a=Sa(t),s={seen:t.knownToExist===true};for(;;){let l=await Ra(t,a,s);if(l.outcome!==null)return l.outcome;if(e.now()+r>i)throw new b("timeout",`match ${n} was still ${l.status} after ${o}ms`);await Vt(e,r,t.signal);}}async function eo(t){return (await Ra(t,Sa(t),{seen:t.knownToExist===true})).outcome}function Sa(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${ka(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function Ra(t,e,n){let{matchId:r}=t,o=t.clock.now(),i;try{i=await to(t.signal,"while polling match status",()=>t.client.get(e,t.signal));}catch(a){if(a instanceof G&&a.reason==="not_found")return {status:"not_found",outcome:n.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw a}if(n.seen=true,i.status==="ready")return {status:"ready",outcome:Em(r,i,o)};if(i.status==="failed"){let a=i.ended_reason;return typeof a=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:$e(a)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:i.failure_reason??"unknown"}}}return {status:i.status,outcome:null}}async function no(t){let e=await to(t.signal,"while listing cluster targets",()=>t.client.get("/v1/ping/targets",t.signal)),n=[];for(let r of e.targets??[]){let o=r?.cluster_target_id;typeof o!="string"||o.length===0||n.push({id:o,pressure:typeof r.pressure=="string"?r.pressure:"unknown"});}return n}async function to(t,e,n){if(t?.aborted)throw Yr(e);try{return await n()}catch(r){throw t?.aborted?Yr(e,r):r}}function Yr(t,e){return new b("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function Em(t,e,n){let r=e.join_credential,o=e.expires_in_seconds,i=typeof r=="string"&&typeof o=="number";return {status:"ready",matchId:t,protocol:e.protocol??"unknown",...i?{joinCredential:r,credentialExpiresAt:n+o*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function ka(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function Vt(t,e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let o=()=>{t.clearTimeout(i),n?.removeEventListener("abort",o),r();},i=t.setTimeout(o,e);n?.addEventListener("abort",o);})}function xa(t){return typeof t=="string"&&t.trim()!==""}function Wt(t,e){return xa(t)?t.trim():xa(e)?e:null}var Kt="0.1.0-beta",Aa="0-beta",mn="web",Tm=/^(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 Cm(t){let e=Tm.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function Pa(t,e){let n=Im(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:Kt};let o=Cm(r);if(o===null)throw new b("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 '${Kt}' for it.`);if(o!==Aa)throw new b("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${o}', and '${Aa}' 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 '${o}' 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 '${Kt}' for it.`);return {...t,platform:n,engineVersion:r}}function Im(t,e){if(t===void 0||t===mn)return mn;if(!Xr.includes(t))throw new b("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${Xr.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${mn}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${mn}' 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.`),mn}var Mm="join",Om="welcome",Lm="rejected",Ea=25e3,Gm=1e3,ro=1;function oo(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var Dm={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 io(t){let e=typeof t=="string"?t:"unknown";return new b(Dm[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function qn(t){let{channel:e,clock:n}=t;return new Promise((r,o)=>{let i=false,a=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??Ea),s=n.setTimeout(()=>w(new b("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,Gm)),l=R=>{let I=R.data;if(typeof I!="string"){c(I);return}let M;try{M=JSON.parse(I);}catch{c(I);return}if(i){c(I);return}if(M.t===Om){let _=oo(M.heartbeat_interval);y({...typeof M.player_id=="string"?{playerId:M.player_id}:{},...typeof M.match_id=="string"?{matchId:M.match_id}:{},..._===void 0?{}:{heartbeatIntervalMs:_}});return}if(M.t===Lm){w(io(M.reason));return}c(I);},d=()=>{w(new b("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{w(new b("aborted","the caller aborted during the join exchange"));},c=R=>{i&&t.onMessage?.(R);},p=()=>{n.clearTimeout(s),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},y=R=>{i=true,p(),t.onMessage===void 0&&g(),r({welcome:R,detach:g});},w=R=>{i||(i=true,p(),g(),o(R));};if(e.addEventListener("message",l),e.addEventListener("close",d),t.signal?.aborted){m();return}t.signal?.addEventListener("abort",m);try{e.send(JSON.stringify({t:Mm,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:ro}:{}}));}catch(R){w(new b("connection_failed",`the join frame could not be sent on the open channel: ${String(R)}`,{cause:R}));}})}var Ve=1,Nn=2,so=4,co=8,$m=2,Fm=1e3,uo="heartbeat timeout",Un="gem-uu",Jt=2,Ca="gem_transports";function pn(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!jm(r)||e.includes(r)||e.push(r);}return e}function jm(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function Bn(t,e){if(typeof t!="object"||t===null)return null;let n=t[Ca];if(typeof n!="object"||n===null)return null;let r=n;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 zt(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var Ia=new TextEncoder,Ma=new TextDecoder;function mo(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function po(t){let e=0;return t?.reliable===false&&(e|=Ve),t?.ordered===false&&(e|=Nn),e}function go(t){return {reliable:(t&Ve)===0,ordered:(t&Nn)===0}}var yo={reliable:true,ordered:true};function Oa(t){return JSON.stringify({t:"join",credential:t,wire:Jt,heartbeat:ro})}function La(t){let e;try{e=JSON.parse(t);}catch{throw new b("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let n=oo(e.heartbeat_interval);return {...e.player_id===void 0?{}:{playerId:e.player_id},...e.match_id===void 0?{}:{matchId:e.match_id},...n===void 0?{}:{heartbeatIntervalMs:n}}}throw e.t==="rejected"?io(e.reason):new b("join_refused","the server answered the join out of protocol")}function Yt(){return typeof globalThis.WebTransport=="function"&&fo===null}function Xt(){return fo}var fo=null;var Ta="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function qm(t){let e=yt(t);if(e.byteLength!==32)throw new b("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var ao=class{buffered=new Uint8Array(0);push(e){let n=new Uint8Array(this.buffered.byteLength+e.byteLength);n.set(this.buffered,0),n.set(e,this.buffered.byteLength),this.buffered=n;let r=[];for(;!(this.buffered.byteLength<4);){let i=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(i===0||i>1<<20)throw new b("connection_failed",`a control-stream record claims ${i} bytes`);if(this.buffered.byteLength<4+i)break;let a=this.buffered.slice(4,4+i);this.buffered=this.buffered.slice(4+i),r.push({flags:a[0]??0,payload:a.slice(1)});}return r}};function lo(t,e){let n=new Uint8Array(5+e.byteLength);return new DataView(n.buffer).setUint32(0,e.byteLength+1,true),n[4]=t,n.set(e,5),n}async function Hn(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webTransport;if(n===void 0){let s=globalThis.WebTransport;if(s===void 0)throw new b("connection_failed","this environment has no WebTransport");n=t.certHashBase64===void 0?new s(t.url):new s(t.url,{serverCertificateHashes:[{algorithm:"sha-256",value:qm(t.certHashBase64)}]});}let r=n,o=s=>{try{r.close();}catch{}throw s},i=r.datagrams;(i?.readable===void 0||i.writable===void 0)&&(fo=Ta,o(new b("connection_failed",`${Ta}; the rung is skipped for the rest of this page (a reload probes again)`)));let a=new Promise((s,l)=>{setTimeout(()=>l(new b("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 o(new b("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(lo(so,Ia.encode(Oa(t.credential))));let c=new ao,p=d.readable.getReader(),g;for(;g===void 0;){let y=await Promise.race([p.read(),a]);if(y.done||y.value===void 0)return o(new b("connection_failed","the control stream closed before the join was answered"));for(let w of c.push(y.value)){g=La(Ma.decode(w.payload));break}}return {link:Nm(r,m,p,c,t.log??(y=>console.warn(y)),Da(g,t.clock)),welcome:g}}catch(s){return o(s)}}function Nm(t,e,n,r,o,i){let a,s,l=false,d=y=>{if(!l){l=true,m.stop();try{t.close();}catch{}s?.(y);}},m=bo(i,()=>d(uo)),c=(y,w)=>{m.heard(),(y&co)===0&&a!==void 0&&((y&so)!==0?a(Ma.decode(w),yo):a(w,go(y)));};(async()=>{try{for(;;){let y=await n.read();if(y.done||y.value===void 0)break;for(let w of r.push(y.value))c(w.flags,w.payload);}}catch{}d("stream closed");})();let p,g;try{let y=t.datagrams;if(y?.readable!==void 0&&y.writable!==void 0){let w=y.readable.getReader();g=y.writable.getWriter(),p=y,(async()=>{try{for(;;){let R=await w.read();if(R.done||R.value===void 0)break;let I=R.value;I.byteLength!==0&&c((I[0]??0)|Ve|Nn,I.slice(1));}}catch{}})();}else o("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(y){p=void 0,g=void 0,o(`[gem] webtransport datagram lane unusable (${zt(y)}); unreliable sends ride the stream`);}return t.closed.then(y=>d(Ga(y?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(y,w){if(l)return;if(typeof y=="string"){e.write(lo(so,Ia.encode(y))).catch(()=>d("write failed"));return}let R=po(w);if((R&Ve)!==0&&g!==void 0){let I=mo(R,y),M=p?.maxDatagramSize;if(M===void 0||I.byteLength<=M){g.write(I).catch(()=>{});return}}e.write(lo(R,y)).catch(()=>d("write failed"));},onMessage(y){a=y;},onClose(y){s=y;},close(){d("closed");}}}function ho(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webSocket;if(n===void 0){let o=globalThis.WebSocket;if(o===void 0)return Promise.reject(new b("connection_failed","this environment has no WebSocket"));n=new o(t.url);}let r=n;return r.binaryType="arraybuffer",new Promise((o,i)=>{let a=false,s=setTimeout(()=>{a||(a=true,r.close(),i(new b("timeout","websocket did not come up in time")));},e),l=g=>{a||(a=true,clearTimeout(s),r.close(),i(g));},d=()=>{r.send(Oa(t.credential));},m=g=>{if(a)return;if(typeof g.data!="string"){l(new b("join_refused","the server sent binary before answering the join"));return}let y;try{y=La(g.data);}catch(w){l(w);return}a=true,clearTimeout(s),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",c),r.removeEventListener("error",p),o({link:Um(r,Da(y,t.clock)),welcome:y});},c=()=>{l(new b("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new b("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 Ga(t){return typeof t=="string"&&t.length>0?t:void 0}function Da(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function bo(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,Fm)*$m,o=n.now(),i=null,a=()=>{i=null;let s=n.now()-o;if(s>=r){e();return}i=n.setTimeout(a,r-s);};return i=n.setTimeout(a,r),{heard:()=>{o=n.now();},stop:()=>{i!==null&&(n.clearTimeout(i),i=null);}}}function Um(t,e){let n,r,o=false,i=s=>{if(!o){o=true,a.stop();try{t.close();}catch{}r?.(s);}},a=bo(e,()=>i(uo));return t.addEventListener("message",(s=>{if(a.heard(),typeof s.data=="string"){n?.(s.data,yo);return}let l=new Uint8Array(s.data);if(l.byteLength===0)return;let d=l[0]??0;(d&co)===0&&n?.(l.slice(1),go(d));})),t.addEventListener("close",(s=>i(Ga(s?.reason)??"socket closed"))),{transport:"websocket",send(s,l){if(!o){if(typeof s=="string"){t.send(s);return}t.send(mo(po(l),s));}},onMessage(s){n=s;},onClose(s){r=s;},close(){i("closed");}}}function vo(t,e,n,r){let o,i,a=false,s=n,l=c=>{if(!a){a=true,d.stop();try{t.close();}catch{}try{e.close();}catch{}i?.(c);}},d=bo(r,()=>l(uo)),m=(c,p)=>{if(d.heard(),typeof c=="string"){o?.(c,yo);return}let g=new Uint8Array(c);if(g.byteLength===0)return;let y=g[0]??0;(y&co)===0&&o?.(g.slice(1),go(y|p));};if(t.addEventListener("message",(c=>m(c.data,0))),t.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,Ve|Nn))),c.addEventListener("close",(()=>{s=void 0;}));}return {transport:"webrtc",send(c,p){if(a)return;if(typeof c=="string"){t.send(c);return}let g=po(p),y=mo(g,c);if((g&Ve)!==0&&s!==void 0&&s.readyState==="open"){s.send(y);return}t.send(y);},onMessage(c){o=c;},onClose(c){i=c;},close(){l("closed");}}}function So(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let o=_o(r);o!==void 0&&(e[n]=o);}return e}function Ro(t){if(Array.isArray(t))return t.map(Bm).filter(e=>!!e)}function _o(t){if(wo(t)||Array.isArray(t)&&t.every(wo))return t}function wo(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function Bm(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=_o(e.fixed),r=_o(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,...n===void 0?{}:{fixed:n},...r===void 0?{}:{default:r},...gn("description",Hm(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(wo)?{allowed:e.allowed}:{},...gn("min",Vn(e.min)),...gn("max",Vn(e.max)),...gn("minItems",Vn(e.min_items)),...gn("maxItems",Vn(e.max_items)),...gn("maxLength",Vn(e.max_length))}}function Hm(t){return typeof t=="string"&&t.length>0?t:void 0}function Vn(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function gn(t,e){return e===void 0?{}:{[t]:e}}function Ee(t){let e=t??{},n=X(e.id)??X(e.game_room_id);if(n===void 0)throw new Error("[gem] a game-room response carried no id");let r=Array.isArray(e.members)?e.members.map($a):[];return {id:n,gameId:X(e.game_id)??"",name:X(e.name)??"",status:X(e.status)??"open",hostPlayerId:X(e.host_player_id)??"",maxPlayers:Pe(e.max_players)??0,memberCount:Pe(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,..._e("joinCode",X(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},..._e("roomArgs",So(e.room_args)),..._e("roomArgsTemplate",Ro(e.room_args_template)),gameChannel:X(e.game_channel)??"release",..._e("region",X(e.region)),..._e("clusterTargetId",X(e.cluster_target_id)),selfHosted:e.self_hosted===true,..._e("matchId",X(e.match_id)),version:Pe(e.version)??0,..._e("templateId",X(e.template_id)),roomType:X(e.game_room_type)??"Standard",..._e("transports",pn(e.transports)??void 0),createdAt:Pe(e.created_at)??0,updatedAt:Pe(e.updated_at)??0,..._e("startedAt",Pe(e.started_at))}}function $a(t){let e=t??{};return {...ve(e),playerId:X(e.player_id)??"",isReady:e.is_ready===true,role:X(e.role)??"member",joinedAt:Pe(e.joined_at)??0,..._e("groupId",X(e.group_id)),..._e("platform",X(e.platform))}}function Qt(t){let e=t??{};return {id:X(e.id)??X(e.game_room_id)??"",gameId:X(e.game_id)??"",name:X(e.name)??"",status:X(e.status)??"open",hostPlayerId:X(e.host_player_id)??"",maxPlayers:Pe(e.max_players)??0,memberCount:Pe(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:X(e.game_channel)??"release",roomType:X(e.game_room_type)??"Standard",createdAt:Pe(e.created_at)??0}}function X(t){return typeof t=="string"&&t.length>0?t:void 0}function Pe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function _e(t,e){return e===void 0?{}:{[t]:e}}var Wn=class{constructor(e){this.options=e;}options;list(e){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.templateSlug&&n.set("template_slug",e.templateSlug),e.limit!==void 0&&n.set("limit",String(e.limit)),e.cursor&&n.set("cursor",e.cursor);let r=n.size>0?`?${n.toString()}`:"";return this.options.client.get(`${this.baseV1()}${r}`,e.signal).then(o=>({rooms:(o.game_rooms??[]).map(Qt),...typeof o.next_cursor=="string"?{nextCursor:o.next_cursor}:{}}))}myRooms(e){return this.options.client.get(`/v1/games/${encodeURIComponent(this.options.gameId())}/players/me/game-rooms`,e).then(n=>({rooms:(n.game_rooms??[]).map(Qt)}))}create(e,n,r){return Vm(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},...Zt(n)},e.signal).then(Ee)}get(e,n){return this.options.client.get(this.roomV2(e),n).then(Ee)}join(e,n,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...n.partyId===void 0?{}:{party_id:n.partyId},...Zt(r)},n.signal).then(Ee)}joinByCode(e,n,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...n.partyId===void 0?{}:{party_id:n.partyId},...Zt(r)},n.signal).then(Ee)}quickJoin(e,n,r=[]){return this.options.client.post(`${this.baseV2()}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...this.asksSelfHosted(e.partyId)?{self_hosted:true}:{},...Zt(n)},e.signal).then(Ee)}leave(e,n,r,o=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:n},r,{keepalive:o}).then(()=>{})}asksSelfHosted(e){return e===void 0&&this.options.selfHosted?.()===true}close(e,n){return this.options.client.delete(this.roomV1(e),n).then(()=>{})}update(e,n){return this.options.client.patch(this.roomV2(e),{...n.name===void 0?{}:{name:n.name},...n.maxPlayers===void 0?{}:{max_players:n.maxPlayers},...n.isPublic===void 0?{}:{is_public:n.isPublic},...n.settings===void 0?{}:{settings:n.settings},...n.roomArgs===void 0?{}:{room_args:n.roomArgs}},n.signal).then(Ee)}setReady(e,n,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:n},r).then(Ee)}kick(e,n,r){return this.options.client.post(`${this.roomV1(e)}/kick/${encodeURIComponent(n)}`,{},r).then(()=>this.get(e,r))}transferHost(e,n,r){return this.options.client.post(`${this.roomV2(e)}/transfer/${encodeURIComponent(n)}`,{},r).then(Ee)}leaveMatch(e,n){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:n}).then(()=>{})}baseV2(){return `/v2/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function Zt(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function Vm(t){t!==void 0&&console.warn(`[gem] createRoom: maxPlayers (${t}) 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 Kn=class{listeners=new Map;retainedMatch=null;on(e,n){let r=this.listeners.get(e);if(r||(r=new Set,this.listeners.set(e,r)),r.add(n),e==="matchReady"&&this.retainedMatch!==null){let o=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(n)&&this.retainedMatch===o&&n(o);});}return ()=>this.off(e,n)}hasListeners(e){return (this.listeners.get(e)?.size??0)>0}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...o)=>{r(),n(...o);}));return r}emit(e,...n){e==="matchReady"&&(this.retainedMatch=n[0]);let r=this.listeners.get(e);if(r)for(let o of [...r])o(...n);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};function Wm(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var Km=1e3,Jm=3e3,zm=6e4,Ym=2,Fa=new Set(["game_room_closed","game_room_gone"]),Xm=12e4,Qm=5e3,Zm=new Set(["invalid_cluster_target","capacity_unavailable"]),ep=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function xo(t){return new ko(t)}var ko=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new Wn({client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new Kn;api;room=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create");let n=this.clusterTargets(),r=await this.attachParty(e),o=await this.run("create",async()=>{let i=await n;return this.api.create(r,this.version("create"),i[0]).catch(async a=>{let s=await this.afterRefusedClusters(a,i);if(s[0]===void 0||s[0]===i[0])throw a;return this.api.create(r,this.version("create"),s[0])})});return this.enter(o,"created"),this.askForLocalServer(o),o}async join(e,n={}){this.assertNotInRoom("join");let r=await this.attachParty(n),o=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(o,"joined"),this.askForLocalServer(o),o}async joinByCode(e,n={}){this.assertNotInRoom("joinByCode");let r=await this.attachParty(n),o=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(o,"joined"),this.askForLocalServer(o),o}async quickJoin(e){this.assertNotInRoom("quickJoin");let n=this.clusterTargets(),r=await this.attachParty(e),o=a=>this.api.quickJoin(r,this.version("quickJoin"),a).catch(s=>this.retryPastStaleMembership(s,r,a)),i=await this.run("quickJoin",async()=>{let a=await n;return o(a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||tp(l,a))throw s;return o(l)})});return this.enter(i,"joined"),this.askForLocalServer(i),i}async list(e={}){let n=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",n),n}async myRooms(e){let n=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",n.rooms),n.rooms}async leave(e={}){let n=this.requireRoom("leave"),r=e.keepalive===true,o=()=>this.run("leave",()=>this.api.leave(n.id,e.asGroup!==false,e.signal,r));if(r){let i=o();this.track(this.notifyLeavingMatch({keepalive:true})),await i;}else await this.notifyLeavingMatch(),await o();this.exit(),this.emitter.emit("left");}async leaveAll(e){let n=await this.myRooms(e),r=[];for(let o of n)try{await this.run("leaveAll",()=>this.api.leave(o.id,!0,e)),r.push(o.id),this.room?.id===o.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let n=this.requireRoom("close");await this.run("close",()=>this.api.close(n.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let n=this.room;if(!n)return null;let r;try{r=await this.track(this.api.get(n.id,e));}catch(o){if(o instanceof G&&o.reason==="not_found"){let i=this.heldMatchId;if(i!==null){let a=await this.askWhyEnded(i,e);this.endMatch(i,a??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",o),o}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let n=this.room,r=this.heldMatchId;if(!(n===null||r===null)&&!(n.status==="in_game"&&n.matchId===r)&&!(n.matchId!==void 0&&n.matchId!==r)&&this.settling!==r){this.settling=r;try{let o=await this.askWhyEnded(r,e);o!==null&&this.endMatch(r,o,n.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,n){let r=this.room;if(r===null)return null;let o=this.takeHint(e),i;try{i=await this.track(this.onceGameIdKnown(()=>eo({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),...n===void 0?{}:{signal:n}})));}catch(a){return a instanceof G&&a.reason==="not_found"?o??null:(this.reportError("reconcile",a),null)}return i===null?null:i.status==="ready"?(this.seenMatches.add(e),null):i.status==="failed"?(this.settleFailed(i.matchId,i.reason),null):i.reason==="unknown"&&o!==null?o:i.reason}takeHint(e){let n=this.pendingHint;if(n===null||n.matchId!==void 0&&n.matchId!==e||(this.pendingHint=null,n.reason===void 0))return null;let r=$e(n.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 n=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=n,this.track(n)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,n){let r=this.requireRoom("setReady"),o=await this.run("setReady",()=>this.api.setReady(r.id,e,n));return this.apply(o),o}async kick(e,n){let r=this.requireRoom("kick"),o=await this.run("kick",()=>this.api.kick(r.id,e,n));return this.apply(o),o}async transferHost(e,n){let r=this.requireRoom("transferHost"),o=await this.run("transferHost",()=>this.api.transferHost(r.id,e,n));return this.apply(o),o}async update(e){let n=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(n.id,e));return this.apply(r),r}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,n){let r=this.requireRoom("startMatch");if(!this.isHost)throw new b("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,n)}finally{this.startsInFlight--;}}async startIn(e,n,r){let o=me(n.clusterTargetId),i=o??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),a=i??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let s=(m,c)=>Qr({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...o===void 0?{nextClusterTarget:()=>this.nextCluster(c)}:{},retry:{...n.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),n.retry?.onWaiting?.(p);}},...n.signal===void 0?{}:{signal:n.signal}}),l=()=>s(i,[a]).catch(async m=>{if(o!==void 0||!qa(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 b("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 n=this.emitter.retained;return n!==null&&this.session.phase==="ready"?n:this.pollMatchStatus(e)}async pollMatchStatus(e={}){let n=this.requireRoom("pollMatchStatus"),r=await this.matchIdOrWait(e),o=await this.run("pollMatchStatus",()=>this.chase(n.id,r,e));return this.settleOutcome(o)}chase(e,n,r){return Zr({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e,matchId:n,version:this.version("pollMatchStatus"),knownToExist:this.seenMatches.has(n),...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 b("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!Fa.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new b("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,n){this.heldMatchId===e&&(this.abandonReconnect(e,n),this.emitter.emit("matchFailed",e,n),this.abortFollow(),this.refusedMatches.add(e),this.session={phase:"none"},this.emitter.clearRetained());}endMatch(e,n,r){this.heldMatchId===e&&(this.abortFollow(),this.session={phase:"ended",matchId:e,reason:n,roomReopened:r},this.emitter.clearRetained(),this.emitter.emit("matchEnded",{matchId:e,reason:n,roomReopened:r}),this.abandonReconnect(e,n));}armReconnect(e,n){let r=this.options.autoReconnect;if(r===void 0||r.attempts<=0||r.budgetMs<=0)return;if(this.finishReconnect(),n==="kicked"){r.abandon(e,n);return}let o={matchId:e,cause:n,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=o,this.track(this.reconnectStep(o));}park(e,n){e.parkedAt=this.options.clock.now(),e.parked=()=>(e.parkedAt!==null&&(e.deadlineAt+=this.options.clock.now()-e.parkedAt,e.parkedAt=null),n());}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,n){let r=this.reconnect;r===null||r.matchId!==e||(this.finishReconnect(),this.options.autoReconnect?.abandon(e,n));}async reconnectStep(e){if(!this.reconnecting(e))return;if(!We()){this.park(e,()=>this.reconnectStep(e));return}let n=this.options.autoReconnect;if(n===void 0||e.attempt===0&&(await this.reconcile().catch(()=>{}),!this.reconnecting(e)))return;let r=e.deadlineAt-this.options.clock.now();if(e.attempt>=n.attempts||r<Km){this.abandonReconnect(e.matchId,e.cause);return}e.attempt+=1,this.emitter.emit("matchReconnecting",{matchId:e.matchId,attempt:e.attempt,attempts:n.attempts,remainingMs:r}),e.timer=this.options.clock.setTimeout(()=>{e.timer=null,this.track(this.reconnectAttempt(e));},Math.min(Wm(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!We()){this.park(e,()=>this.reconnectAttempt(e));return}let n=this.options.autoReconnect,r=this.room;if(n===void 0||r===null)return;let o=null;try{o=await this.track(this.onceGameIdKnown(()=>eo({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(i){this.reportError("reconcile",i);}if(this.reconnecting(e)){if(o?.status==="ended"){this.endMatch(o.matchId,o.reason,!Fa.has(o.reason)),this.track(this.reconcile().catch(()=>{}));return}if(o?.status==="failed"){this.abandonReconnect(e.matchId,o.reason),this.settleFailed(o.matchId,o.reason);return}if(o?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(o);let i;try{i=await n.redial(e.matchId,e.deadlineAt);}catch(a){this.reportError("reconcile",a),i="failed";}if(e.done||this.reconnect!==e)return;if(i==="closed"){this.finishReconnect();return}if(i==="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 n=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})):n&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new b("misconfigured",`no match is connected, so there is nothing to suspend (state '${this.matchConnectionState}').`);let n=this.session.matchId;this.session={phase:"suspended",matchId:n,reason:e},this.emitter.emit("matchSuspended",{matchId:n,cause:e}),this.armReconnect(n,e);}async reconnectToMatch(e={}){if(this.session.phase!=="suspended")throw new b("misconfigured",`reconnectToMatch expects a suspended match; this one is '${this.matchConnectionState}'. Call notifyMatchDisconnected() when the transport drops.`);let n=this.heldMatchId;if(n===null)throw new b("misconfigured","there is no match to reconnect to.");return this.finishReconnect(),this.session={phase:"starting",matchId:n},this.emitter.clearRetained(),this.pollMatchStatus(e)}async notifyLeavingMatch(e={}){let n=this.heldMatchId;if(n!==null)try{await this.api.leaveMatch(n,e.keepalive??!1);}catch{}}get gameId(){let e=typeof this.options.gameId=="function"?this.options.gameId():this.options.gameId;return e===""?null:e}get currentRoom(){return this.room}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}on(e,n){let r=this.emitter.on(e,n);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}handleRoomEvent(e){if(this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let n=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(n).catch(()=>{}));}handleAutoStartFailed(e,n){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(n);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:n,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let o=new AbortController;this.autoStartRetry=o,this.track(this.requestStart({signal:o.signal},false).then(()=>{},i=>{o.signal.aborted||this.reportError("startMatch",i);}).finally(()=>{this.autoStartRetry===o&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!Zm.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){this.disposed||!this.watchingSeats||this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}async reconcileSeats(){if(this.disposed||!this.watchingSeats)return;let e;try{e=await this.myRooms();}catch{return}let n=new Set;for(let r of e)r.status!=="closed"&&(n.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])n.has(r)||this.reported.delete(r);}async reportSeat(e){let n=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||n===null||!r.members.some(o=>o.playerId===n)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.seatPollMs>0&&We())){this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null);return}if(this.seatPollHandle!==null)return;let n=()=>{this.seatPollHandle=null,this.track(this.reconcileSeats().catch(()=>{}).then(()=>this.retuneSeatWatch()));};this.seatPollHandle=this.options.clock.setTimeout(n,this.seatPollMs);}installResumeWatch(){let e=globalThis;if(typeof e.addEventListener!="function")return;this.visibilityListener=()=>{if(!this.disposed&&(this.retuneSeatWatch(),!!We())){if(this.room!==null){let r=this.reconnect?.parked??null;r!==null&&this.reconnect!==null?(this.reconnect.parked=null,this.track(r())):this.track(this.reconcile().catch(()=>{}));return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of er)e.addEventListener(r,this.visibilityListener);let n=globalThis.document;typeof n?.addEventListener=="function"&&n.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 n=this.inFlight;this.inFlight=[],await Promise.allSettled(n);}}dispose(){if(this.disposed=true,this.abortAutoStartRetry(),this.finishReconnect(),this.stopPolling(),this.emitter.clear(),this.unloadListener&&(globalThis.removeEventListener?.("pagehide",this.unloadListener),this.unloadListener=null),this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null),this.visibilityListener){let e=globalThis;for(let r of er)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??Qm}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new b("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 n=this.options.clientVersion,r=Wt(this.options.platformGameVersion?.(),n?.gameVersion);if(r===null)throw new b("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 Pa({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return jn(await this.options.resolveClusterTargets());let e=me(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !qa(e)||n.length===0?[]:jn(await this.options.refreshClusterTargets?.(n)??[])}async nextCluster(e,n=false){let r=a=>a.find(s=>!e.includes(s)),o=await this.clusterTargets(),i=r(o);return i!==void 0||!n?i:r(jn(await this.options.refreshClusterTargets?.(o)??[]))}async attachParty(e){if(e.partyId!==void 0)return e;let n=this.options.resolveParty;if(n===void 0)return e;let r=await n();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,n,r){if(!(e instanceof G)||e.reason!=="conflict"||!ep.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new G(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 o;try{o=await this.leaveAll(n.signal);}catch{throw new G(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(o.length===0)throw new G(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(n,this.version("quickJoin"),r)}assertNotInRoom(e){if(this.room!==null)throw new b("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}requireRoom(e){if(this.room===null)throw new b("misconfigured",`${e} refused: not in a room.`);return this.room}async run(e,n){try{return await this.track(this.onceGameIdKnown(n))}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,n){let r=n instanceof G?{operation:e,code:n.status,reason:n.reason,message:n.message,retryable:n.retryable}:{operation:e,code:0,reason:n instanceof b?n.reason:"unavailable",message:n instanceof Error?n.message:String(n),retryable:false};this.emitter.emit("error",r);}askForLocalServer(e){let n=this.options.ensureLocalServer;n===void 0||!e.selfHosted||e.status!=="open"||n(e.id).catch(()=>{});}track(e){return this.inFlight.push(e),e}enter(e,n){this.room=e,this.abortFollow(),this.autoStartRetried=false,this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(n,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 n=this.room;if(n===null||n.id!==e.id)return;let r=new Map(n.members.map(s=>[s.playerId,s])),o=new Map(e.members.map(s=>[s.playerId,s])),i=this.playerId();for(let s of o.keys())r.has(s)||this.emitter.emit("memberJoined",s);for(let s of r.keys())if(!o.has(s)){if(s===i){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",s);}for(let[s,l]of o){let d=r.get(s);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",s,l.isReady);}n.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let a=np(n,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 n=this.heldMatchId;n!==null&&n!==e&&this.endMatch(n,"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,n=this.heldMatchId;if(e===null||n===null||this.followAbort!==null&&this.followingMatchId===n)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=n,this.track(this.onceGameIdKnown(()=>this.chase(e.id,n,{signal:r.signal})).then(o=>{if(!r.signal.aborted)try{this.settleOutcome(o);}catch{}}).catch(o=>{r.signal.aborted||this.reportError("pollMatchStatus",o);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let n=this.heldMatchId;if(n!==null)return Promise.resolve(n);let r=e.timeoutMs??Xm;return new Promise((o,i)=>{let a=c=>{s(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),c();},s=this.emitter.on("matchAllocationStarted",c=>a(()=>o(c))),l=this.emitter.on("matchFailed",(c,p)=>a(()=>i(new b("allocation_failed",`match ${c} did not come up: ${p}`)))),d=()=>a(()=>i(new b("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>a(()=>i(new b("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??Jm}pushedInterval(){return this.options.pushedPollIntervalMs??zm}pushed(){return this.options.clock.now()-this.lastPushAt<Ym*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=n=>{n?.persisted!==true&&this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{}));},e.addEventListener("pagehide",this.unloadListener));}};function We(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var er=["visibilitychange","focus","pageshow","online"];function np(t,e){return t.version!==e.version||t.status!==e.status||t.matchId!==e.matchId||t.hostPlayerId!==e.hostPlayerId||t.name!==e.name||t.maxPlayers!==e.maxPlayers||t.isPublic!==e.isPublic||ja(t)!==ja(e)}function ja(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function qa(t){return t instanceof G&&t.code==="invalid_cluster_target"}function tp(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var rp=["p2p","dedicated","unknown"],Ao=["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 yn=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let o=op(e,this.options.transport,(this.options.now??Date.now)());o.length!==0&&await this.options.client.post(`/v1/games/${encodeURIComponent(r)}/telemetry/p2p`,{events:o},n);}report(e){this.post(e).catch(()=>{});}};function op(t,e,n){let r=Math.floor(n/1e3);return t.filter(o=>Ao.includes(o.type)).slice(0,100).map(o=>{let i=ip(o.transport??e);return {event_type:o.type,timestamp:r,...i===void 0?{}:{transport:i},data:o.value===void 0?{}:{value:o.value}}})}function ip(t){if(t!==void 0)return rp.includes(t)?t:"unknown"}var Jn=class{constructor(e){this.options=e;this.reporter=new yn({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,n,r){let o=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:n},r);return {credential:nr(o.credential)??"",hostFingerprint:nr(o.host_fingerprint)??"",hostEpoch:tr(o.host_epoch)??0,expiresAt:(tr(o.expires_at)??0)*1e3}}async turnLease(e,n,r){let o=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:n},r),i=[];for(let l of Array.isArray(o.ice_servers)?o.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(c=>typeof c=="string"&&c.length>0);m.length!==0&&i.push({urls:m,username:nr(d.username)??"",credential:nr(d.credential)??""});}let a=tr(o.expires_at),s=tr(o.ttl_seconds);return {iceServers:i,expiresAt:a!==void 0?a*1e3:Date.now()+(s??0)*1e3}}async kick(e,n,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:n},r);}async leave(e,n=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:n});}async telemetry(e,n){await this.reporter.post(e,n);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}};function nr(t){return typeof t=="string"&&t.length>0?t:void 0}function tr(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}var sp=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),O=class extends Error{constructor(n,r,o){super(`${n}: ${r}`,o);this.reason=n;this.name="P2pError",this.retryable=sp.has(n);}reason;retryable};var Na=10240,Ua=2048,ap=new TextEncoder;function Ba(t){return ap.encode(t).length}function Fe(t,e){let n=o=>{throw new b("invalid_sdp",`the ${e} ${o}`)},r=Ba(t);r>=Na&&n(`is ${r} bytes, over the ${Na} limit`+(e==="offer"?", which for an offer means an unusually wide candidate list":"")),t.startsWith("v=")||n("does not start with 'v=', so it is not SDP"),t.includes("\0")&&n("contains a null byte"),/\r(?!\n)/.test(t)&&n("contains a bare carriage return");for(let o of t.split(/\r\n|\n/)){let i=Ba(o);i>Ua&&n(`has a ${i}-byte line, over the ${Ua} limit`);}}function rr(t){for(let e of t.split(/\r\n|\n/)){if(!e.startsWith("m="))continue;let[n,r="0"]=e.slice(2).trim().split(/\s+/);if(!(n!=="audio"&&n!=="video")&&r.split("/")[0]!=="0")return true}return false}var or=class{listeners=new Map;on(e,n){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(n),()=>this.off(e,n)}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...o)=>{r(),n(...o);}));return r}emit(e,...n){let r=this.listeners.get(e);if(r)for(let o of [...r])o(...n);}clear(){this.listeners.clear();}};var lp=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function fn(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=ir(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function ir(t){let[e,...n]=t.trim().split(/\s+/);if(e===void 0||n.length===0)return null;let r=`${e.toLowerCase()} ${n.join("").toUpperCase()}`;return lp.test(r)?r:null}function zn(t,e){if(t.length!==e.length)return false;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}var Po=5e3,dp=12e4+Po,cp=1024,up=6e4,mp=1e4,Ha=64*1024,Va=5;function Eo(t){let e=new Map,n=-1/0,r=null,o=(()=>{let s;try{s=new URL(`${t.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}`}})(),i=()=>{let s=t.subtle??globalThis.crypto?.subtle;if(!s)throw new O("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(!o.ok)throw new O("keys_unavailable",o.reason);let s=t.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await s(o.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(mp)});}catch{throw new O("keys_unavailable",`the JWKS endpoint at ${o.shown} could not be reached \u2014 it timed out, refused a redirect, or the network failed.`)}if(!l.ok)throw new O("keys_unavailable",`the JWKS endpoint answered ${o.shown} with an error`);let d;try{let p=await l.text();if(p.length>Ha)throw new O("keys_unavailable",`the JWKS endpoint at ${o.shown} answered with more than ${Ha} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof O?p:new O("keys_unavailable",`the JWKS endpoint at ${o.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>Va)throw new O("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${Va} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=i();for(let p of m){let g=p;if(g.kty==="RSA"&&!(g.alg!==void 0&&g.alg!=="RS256")&&!(g.use!==void 0&&g.use!=="sig")&&!(typeof g.kid!="string"||g.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(g.kid,y);}catch{}}};return {async key(s){let l=e.get(s);if(l)return l;if(!o.ok)throw new O("keys_unavailable",o.reason);if(r)return await r,e.get(s)??null;let d=t.now();if(!Number.isFinite(d))throw new O("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<n&&(n=-1/0),d-n<up?null:(n=d,r??=a().finally(()=>{r=null;}),await r,e.get(s)??null)}}}var Yn=class{seen=new Map;admit(e,n){for(let[r,o]of this.seen)o<=n&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=cp){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+dp),true}};function Ka(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r}function Wa(t){try{let e=new TextDecoder().decode(Ka(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function To(t,e,n,r,o){let i=D=>{throw new O("peer_unauthenticated",`the peer's join credential is not usable: ${D}`)},a=t.split(".");a.length!==3&&i("it is not a three-part JWT");let[s,l,d]=a,m=Wa(s);m===null&&i("its header does not decode"),m.alg!=="RS256"&&i(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&i(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let c=m.kid;(typeof c!="string"||c.length===0)&&i("it names no key");let p=await n.key(c);p===null&&i("it was signed by a key this build cannot resolve");let g=o.subtle??globalThis.crypto?.subtle;g||i("this environment has no WebCrypto");let y=new TextEncoder().encode(`${s}.${l}`),w;try{w=Ka(d);}catch{i("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,w,y)||i("its signature does not verify");let I=Wa(l);I===null&&i("its payload does not decode");let M=I,_=D=>typeof M[D]=="string"?M[D]:"",S=D=>typeof M[D]=="number"&&Number.isFinite(M[D])?M[D]:NaN;_("iss")!==o.issuer&&i("it was issued by someone else"),_("aud")!==`${o.issuer}/p2p-match`&&i("its audience is not this platform"),_("match_id")!==e.matchId&&i("it is for another match"),_("game_id")!==e.gameId&&i("it is for another game");let P=S("exp")*1e3,x=S("nbf")*1e3;(!Number.isFinite(P)||e.now>P+Po)&&i("it has expired"),Number.isFinite(x)&&e.now<x-Po&&i("it is not valid yet");let V=_("role");V!=="host"&&V!=="client"&&i("it names no usable role");let N=S("host_epoch");N!==e.hostEpoch&&i("it names a different host epoch");let W=ir(_("fingerprint"));W===null&&i("its fingerprint claim is malformed"),zn(W,e.peerFingerprint)||i("it was issued for a different certificate than this connection used");let k=ir(_("host_fingerprint"));k===null&&i("its host fingerprint claim is malformed"),zn(k,e.hostFingerprint)||i("it was issued against a different host certificate");let A=_("jti");A.length===0&&i("it carries no jti, so replay cannot be detected"),r.admit(A,e.now)||i("it has already been used");let L=_("sub");return L.length===0&&i("it names no player"),{playerId:L.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:N,role:V,fingerprint:W,hostFingerprint:k,jti:A,expiresAt:P}}function Co(t){let e=new TextEncoder().encode(t.jwt);if(e.length>8192)throw new Error(`[gem] a join credential of ${e.length} bytes exceeds the wire format's cap`);let n=new ArrayBuffer(3+e.length+4+4),r=new DataView(n);return r.setUint8(0,1),r.setUint16(1,e.length,true),new Uint8Array(n,3,e.length).set(e),r.setUint32(3+e.length,t.protocolVersion,true),r.setUint32(7+e.length,t.assignedPeerId,true),n}function Io(t){let e=new ArrayBuffer(9),n=new DataView(e);return n.setUint8(0,2),n.setUint32(1,t.protocolVersion,true),n.setUint32(5,t.assignedPeerId,true),e}function Mo(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function Oo(t){if(t.byteLength<1)return null;let e=new DataView(t);switch(e.getUint8(0)){case 1:{if(t.byteLength<3)return null;let n=e.getUint16(1,true);return n>8192||t.byteLength<3+n+8?null:{kind:"join",jwt:new TextDecoder().decode(new Uint8Array(t,3,n)),protocolVersion:e.getUint32(3+n,true),assignedPeerId:e.getUint32(7+n,true)}}case 2:return t.byteLength<9?null:{kind:"admit",protocolVersion:e.getUint32(1,true),assignedPeerId:e.getUint32(5,true)};case 3:return t.byteLength<2?null:{kind:"reject",reason:e.getUint8(1)};default:return null}}function Ja(t){switch(t){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 (${t})`}}function za(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var Xn=class{constructor(e,n,r){this.localPlayerId=e;this.hostPlayerId=n,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,n){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=n,this.state=this.isLocalHost?"preparing":"reconnecting",{kind:"accepted",state:this.state})}complete(){this.state="idle";}};var Lo={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}},Me=["reliable","ordered","unreliable"];function Go(t){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:t.iceServers,...t.certificates===void 0?{}:{certificates:t.certificates}})}async function Qn(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var Xa=1,hp=3e4,Qa=2e3,bp=5e3,Za=6e4,vp=8,$o=class{constructor(e=vp){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 n=0;for(let r of this.sent)r<=e&&e-r<6e4&&(this.sent[n++]=r);this.sent.length=n;}},_p=new $o,wp=8,Sp=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),et=class{constructor(e){this.options=e;this.keys=e.keys??Eo({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new or;links=new Map;replays=new Yn;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=Xa+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 n of this.links.values())n.admitted&&e.push(this.expose(n));return e}peer(e){let n=this.links.get(e);return n&&n.admitted?this.expose(n):null}on(e,n){return this.emitter.on(e,n)}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}async start(e){let n=this.options.connectTimeoutMs??hp;this.credentialDeadline=this.options.clock.now()+n;let r=new Promise((s,l)=>{this.ready={resolve:s,reject:l};}),o=me(this.options.clusterTargetId);if(o!==void 0)try{let s=await this.options.api.turnLease(this.options.matchId,o,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: ${Do(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 i=this.options.clock.setTimeout(()=>{this.fail(new O("timeout",`no usable P2P connection after ${n}ms. The parent relays signaling, so a silent failure here usually means the page is not putting frames on the socket.`));},n),a=()=>this.fail(new O("aborted","the caller aborted while connecting"));e?.aborted?a():e?.addEventListener("abort",a);try{await r;}finally{this.options.clock.clearTimeout(i),e?.removeEventListener("abort",a),this.ready=null;}}async kick(e){if(!this.isHost)throw new O("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,n){this.closed||this.route(e,n).catch(r=>this.report_(r));}async route(e,n){switch(e){case "hello":return this.onHello(n);case "offer":return this.onOffer(n);case "answer":return this.onAnswer(n);case "ice":return this.onIce(n);case "peerLeft":return this.onPeerLeft(n);case "migration":return this.onMigration(n);case "matchEnded":return this.onMatchEnded(n);case "error":return this.onSignalingError(n);default:return}}async onHello(e){let n=ae(e.playerId),r=ae(e.hostPlayerId),o=sr(e.hostEpoch);if(!(n===null||r===null||o===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new Xn(n,r,o)),!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 n of e)try{await this.onOffer(n);}catch(r){this.report_(r);}}async offerToHost(e){let n=this.hostPlayerId,r=this.openLink(n,Xa),o=await r.connection.createOffer();await r.connection.setLocalDescription(o);let i=r.connection.localDescription?.sdp??o.sdp;if(!i)throw new O("invalid_sdp","the browser produced an offer with no SDP");Fe(i,"offer"),this.refuseMedia(i,"offer"),this.options.signaling.offer(i,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,o=r===void 0?null:fn(r);if(o===null)throw new O("invalid_sdp","this browser produced an offer with no usable DTLS fingerprint, so the platform cannot bind a credential to it");let i=this.options.credentialPacing??_p,a=()=>this.closed||e!==this.credentialGeneration,s=bp;for(;;){let l=i.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,a))return;i.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,o);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=Qa;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,Za)),c=Math.min(Math.max(c,Qa),Za);}else throw d;if(!await this.waitForCredential(c,a))return}}}async waitForCredential(e,n){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!n())}async onOffer(e){let n=ae(e.fromPlayerId),r=ae(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=wp){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(n,e);return}if(!this.isHost||this.migration.isKicked(n)===true)return;let o=ae(e.sessionId);if(o!==null&&this.answeredSessions.get(n)===o)return;Fe(r,"offer"),this.refuseMedia(r,"offer");let i=fn(r);if(i===null)throw new O("invalid_sdp",`the offer from ${n} carries no usable fingerprint`);this.mark("offer received"),o!==null&&this.answeredSessions.set(n,o);let a=this.links.get(n);a&&this.dropLink(a,"resignalled",false);let s=this.openLink(n,this.nextPeerId++);s.remoteFingerprint=i,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 O("invalid_sdp","the browser produced an answer with no SDP");Fe(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(n,d,s.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let n=ae(e.fromPlayerId),r=ae(e.sdp);if(n===null||r===null)return;let o=this.links.get(this.hostPlayerId);if(!o||n!==this.hostPlayerId)return;Fe(r,"answer"),this.refuseMedia(r,"answer");let i=fn(r);if(i===null)throw new O("invalid_sdp","the host's answer carries no usable fingerprint");this.mark("answer received"),o.remoteFingerprint=i,o.pendingAnswer=r,this.hostVerified(o)&&await this.applyAnswer(o,r);}hostVerified(e){let n=this.credential;return n===null||e.remoteFingerprint===null?false:zn(n.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new O("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 n=e.pendingAnswer;n!==void 0&&this.hostVerified(e)&&this.applyAnswer(e,n).catch(r=>this.report_(r));}async applyAnswer(e,n){this.mark("host verified"),e.pendingAnswer=void 0,await e.connection.setRemoteDescription({type:"answer",sdp:n}),this.flushCandidates(e);}async onIce(e){let n=ae(e.fromPlayerId),r=ae(e.candidate);if(n===null||r===null)return;let o=this.links.get(n);if(!o)return;let i=ae(e.sdpMid),a=sr(e.sdpMLineIndex)??sr(e.sdpMLineIndexAlt),s={candidate:r,...i===null?{}:{sdpMid:i},...a===null?{}:{sdpMLineIndex:a}};if(o.connection.remoteDescription===null){o.pendingCandidates.length<64&&o.pendingCandidates.push(s);return}await o.connection.addIceCandidate(s);}onPeerLeft(e){let n=ae(e.playerId);if(n===null)return;let r=ae(e.reason)??"left";if(n===this.localPlayerId){this.fail(new O("kicked",`this player was removed from the match (${r})`)),this.close();return}let o=this.links.get(n);o&&this.dropLink(o,r,true);}async onMigration(e){let n=ae(e.hostPlayerId),r=sr(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let o=this.migration.apply({hostPlayerId:n,hostEpoch:r,...ae(e.reason)===null?{}:{reason:ae(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(i=>typeof i=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(o.kind!=="duplicate"){if(o.kind==="completed"){this.emitter.emit("hostChanged",n,r);return}if(o.kind==="refused"){this.report_(new O("migration_failed",o.why));return}for(let i of [...this.links.values()])this.dropLink(i,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",n,r),o.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 O("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 n=ae(e.reason)??"ended";this.ended=n,this.emitter.emit("matchEnded",n),this.ready!==null&&this.fail(new O("match_ended",`the match ended: ${n}`)),this.close();}onSignalingError(e){let n=ae(e.code)??"unknown",r=ae(e.message)??"the platform refused a signaling message";this.report_(new O("signaling_failed",`${n}: ${r}`));}openLink(e,n){let o=(this.options.peerConnectionFactory??Go)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),i={};for(let p of Me){let g=o.createDataChannel(p,Lo[p]);g.binaryType="arraybuffer",i[p]=g;}let a={playerId:e,assignedPeerId:n,connection:o,channels:i,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},s=p=>{let g=p.candidate;g?.candidate&&this.options.signaling.candidate(e,g.candidate,g.sdpMid??void 0,g.sdpMLineIndex??void 0);},l=()=>this.onIceState(a),d=()=>this.onConnectionState(a),m=p=>{this.onHandshakeMessage(a,p.data).catch(g=>this.report_(g));},c=()=>{this.onReliableOpen(a).catch(p=>this.report_(p));};return o.addEventListener("icecandidate",s),o.addEventListener("iceconnectionstatechange",l),o.addEventListener("connectionstatechange",d),i.reliable.addEventListener("open",c),i.reliable.addEventListener("message",m),a.detachHandshake=()=>{i.reliable.removeEventListener("open",c),i.reliable.removeEventListener("message",m);},a.detachAll=()=>{a.detachHandshake(),o.removeEventListener("icecandidate",s),o.removeEventListener("iceconnectionstatechange",l),o.removeEventListener("connectionstatechange",d);},this.links.set(e,a),a}flushCandidates(e){let n=e.pendingCandidates;e.pendingCandidates=[];for(let r of n)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let n=this.credential;if(n===null)throw new O("peer_unauthenticated","the channel opened before the platform issued a join credential, so there is nothing to present");if(this.options.clock.now()>=n.expiresAt)throw new O("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(Co({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=Oo(n);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 O(za(r.reason),Ja(r.reason))),this.dropLink(e,"rejected",false));}}async admit(e,n,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 o=fn(e.connection.localDescription?.sdp??"");if(o===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 i;try{i=await To(n,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:o,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(a){let s=a instanceof O&&a.reason==="keys_unavailable";this.refuseLink(e,s?131:1,s?"keys_unavailable":"credential_invalid",Do(a)),s&&this.fail(a);return}if(i.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${i.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(i.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(Io({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,n,r,o){this.warn(`refused to admit ${e.playerId}: ${o}`);try{e.channels.reliable.send(Mo(n));}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 n=e.connection.iceConnectionState;if(!(n!=="failed"&&n!=="disconnected"&&n!=="closed")){if(this.isHost){(n==="failed"||n==="closed")&&this.dropLink(e,n,true);return}if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,n);}catch(r){this.report_(r);}}}}onConnectionState(e){let n=e.connection.connectionState;n!=="failed"&&n!=="closed"||this.dropLink(e,n,true);}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(n,r="reliable")=>e.channels[r].send(n)}}dropLink(e,n,r){this.links.delete(e.playerId),e.detachAll();for(let o of Me)el(e.channels[o]);el(e.connection),r&&e.admitted&&this.emitter.emit("peerLeft",e.playerId,n);}settle(){this.ready?.resolve(),this.ready=null;}fail(e){if(this.count(e.reason),this.ready!==null){let n=this.ready;this.ready=null,n.reject(e);return}this.emitter.emit("error",e);}report_(e){this.fail(e instanceof O?e:new O("connection_failed",Do(e),{cause:e}));}count(e){this.counted||!Sp.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(rr(e))throw new O("media_refused",`the ${n} 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(n=>this.options.clock.setTimeout(n,e))}warn(e){let n=this.options.log;n!==null&&(n??(r=>console.warn(r)))(`[gem] ${e}`);}get endedReason(){return this.ended}};function ae(t){return typeof t=="string"&&t.length>0?t:null}function sr(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function Do(t){return t instanceof Error?t.message:String(t)}function el(t){try{t.close();}catch{}}var Rp=100,kp=50,nt=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,n){this.assertUsable(),this.options.bridge.signal("offer",this.options.matchId,{sdp:e,intent:n});}answer(e,n,r){this.assertUsable(),this.options.bridge.signal("answer",this.options.matchId,{peerId:e,sdp:n,assignedPeerId:r});}candidate(e,n,r,o){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??Rp)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:n,...r===void 0?{}:{sdpMid:r},...o===void 0?{}:{sdpMLineIndex:o}}),this.schedule();}migrationAck(e){this.assertUsable(),this.options.bridge.signal("migrationAck",this.options.matchId,{hostEpoch:e});}reportHostUnreachable(e,n){this.assertUsable(),this.options.bridge.signal("hostUnreachable",this.options.matchId,{hostEpoch:e,evidence:{iceState:n,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 O("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new O("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:n,candidate:r,sdpMid:o,sdpMLineIndex:i}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:n,candidate:r,...o===void 0?{}:{sdpMid:o},...i===void 0?{}:{sdpMLineIndex:i}});}if(this.dropped>0&&this.queue.length===0){let n=this.dropped;this.dropped=0,this.options.onCandidatesDropped?.(n),this.dropListener?.(n);}this.queue.length>0&&this.schedule();},this.options.candidateIntervalMs??kp));}};function B(t){return e=>typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function je(t,e){return n=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e?n:void 0}function hn(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function nl(t){return typeof t=="boolean"?t:void 0}var fe=B(64),tt=je(0,2147483647);function Fo(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=fe(n);typeof r=="string"&&e.push(r);}return e}function z(t,e,n){return {to:t,from:e,read:n,required:true}}function H(t,e,n){return {to:t,from:e,read:n,required:false}}var Pp=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=hn("disconnected","failed","closed")(e.iceState),r=je(0,4102444800)(e.lastSeenAt);if(!(n===void 0&&r===void 0))return {...n===void 0?{}:{ice_state:n},...r===void 0?{}:{last_seen_timestamp:r}}};Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[z("sdp","sdp",B(10240)),z("signaling_intent","intent",hn("initial","ice_restart","full_reconnect")),H("sdp_hash","sdpHash",B(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[z("peer_id","peerId",fe),z("sdp","sdp",B(10240)),z("assigned_peer_id","assignedPeerId",je(0,4294967295)),H("sdp_hash","sdpHash",B(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[z("peer_id","peerId",fe),z("candidate","candidate",B(512)),H("sdp_mid","sdpMid",B(64)),H("sdp_mline_index","sdpMLineIndex",je(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[z("host_epoch","hostEpoch",tt)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[z("host_epoch","hostEpoch",tt),H("evidence","evidence",Pp)]}}));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"}));Object.freeze(Object.assign(Object.create(null),{hello:[z("playerId","player_id",fe),z("hostPlayerId","host_player_id",fe),z("hostEpoch","host_epoch",tt),H("members","members",Fo)],offer:[z("fromPlayerId","from_player_id",fe),z("sdp","sdp",B(10240)),H("sessionId","signaling_session_id",B(128)),H("sdpHash","sdp_hash",B(128)),H("iceUfrag","ice_ufrag",B(64)),H("intent","signaling_intent",hn("initial","ice_restart","full_reconnect"))],answer:[z("fromPlayerId","from_player_id",fe),z("sdp","sdp",B(10240)),H("sessionId","signaling_session_id",B(128)),H("sdpHash","sdp_hash",B(128)),H("iceUfrag","ice_ufrag",B(64)),H("assignedPeerId","assigned_peer_id",je(0,4294967295))],ice:[z("fromPlayerId","from_player_id",fe),z("candidate","candidate",B(512)),H("sdpMid","sdp_mid",B(64)),H("sdpMLineIndex","sdp_m_line_index",je(0,255)),H("sdpMLineIndexAlt","sdp_mline_index",je(0,255))],peerJoined:[z("playerId","player_id",fe)],peerLeft:[z("playerId","player_id",fe),H("reason","reason",B(64))],migration:[z("hostPlayerId","new_host_player_id",fe),z("hostEpoch","host_epoch",tt),H("reason","reason",B(64)),H("kickedPlayerIds","kicked_player_ids",Fo),H("migrationComplete","migration_complete",nl)],matchEnded:[H("reason","reason",B(64))],error:[H("code","code",B(64)),H("message","message",B(256))]}));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"}));var Je="webrtc_p2p";function rl(t){let e=new Jn({client:t.client,gameId:t.gameId}),n=new Map;return {handleSignalEvent(r,o,i){n.get(r)?.handleSignal(o,i);},session(r){return n.get(r)??null},async connect(r={}){if(t.bridge===null)throw new O("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 o=me(r.clusterTargetId),i=o??me(await t.resolveClusterTarget?.());t.rooms.isHost&&t.rooms.currentMatch===null&&t.rooms.currentRoom?.matchId===void 0&&await t.rooms.startMatch({...o===void 0?{}:{clusterTargetId:o},...r.signal===void 0?{}:{signal:r.signal}});let a=await t.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(a.protocol!==Je)throw new O("unsupported_protocol",`match ${a.matchId} speaks '${a.protocol}', not '${Je}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let s=new nt({bridge:t.bridge,matchId:a.matchId,clock:t.clock}),l=new et({api:e,clock:t.clock,matchId:a.matchId,gameId:t.gameId(),baseUrl:typeof t.baseUrl=="function"?t.baseUrl():t.baseUrl,signaling:s,...i===void 0?{}:{clusterTargetId:i},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await Qn(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...t.boot===void 0?{}:{boot:t.boot},...t.log===void 0?{}:{log:t.log}});s.onDropped(d=>l.notifyCandidatesDropped(d)),n.set(a.matchId,l),l.on("matchEnded",()=>n.delete(a.matchId));try{await l.start(r.signal);}catch(d){throw n.delete(a.matchId),l.close(),d}return l}}}function ol(t){let{analytics:e,rooms:n}=t,r=t.target??globalThis,o=t.document??globalThis.document,i=[];if(typeof r.addEventListener=="function"){let s=d=>{d?.persisted!==true&&e.endSession("pagehide");};r.addEventListener("pagehide",s),i.push(()=>r.removeEventListener?.("pagehide",s));let l=()=>e.setHidden(!We());for(let d of er)r.addEventListener(d,l),i.push(()=>r.removeEventListener?.(d,l));typeof o?.addEventListener=="function"&&(o.addEventListener("resume",l),i.push(()=>o.removeEventListener?.("resume",l))),e.setHidden(!We());}let a=new Map;return i.push(n.on("matchReady",s=>{let l=s.protocol===Je?"p2p":"dedicated";a.set(s.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),i.push(n.on("matchEnded",s=>{let l=a.get(s.matchId);l!==void 0&&(a.delete(s.matchId),e.trackPlatform("gem_match_ended",{transport:l}));})),()=>{for(let s of i.splice(0))try{s();}catch{}a.clear();}}var il=["pointerdown","keydown"];function sl(t,e=globalThis){let n=false,r=false,o=null,i=()=>{if(o!==null){try{e.cancelAnimationFrame?.(o);}catch{}o=null;}},a=()=>{if(!r){r=true,i();for(let g of il)e.removeEventListener?.(g,l,{capture:true});e.removeEventListener?.("gamepadconnected",p,{capture:true});}},s=()=>{if(!(n||r)){n=true,a();try{t();}catch{}}};function l(g){g?.isTrusted===true&&s();}let d=()=>{let g;try{g=e.navigator?.getGamepads?.()??[];}catch{return false}return g.some(y=>y?.buttons.some(w=>w.pressed)===true)},m=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},c=()=>{if(o=null,!(n||r)){if(d()){s();return}m()&&(o=e.requestAnimationFrame?.(c)??null);}};function p(){o===null&&!n&&!r&&c();}if(typeof e.addEventListener=="function"){for(let g of il)e.addEventListener(g,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",p,{capture:true,passive:true}),m()&&(o=e.requestAnimationFrame?.(c)??null);}return {get engaged(){return n},stop:a}}async function ar(t,e,n,r){let o=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),o}function jo(t,e){let n=false;return async r=>{let o=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),o}}function qo(t={}){let e=t.now??(typeof performance>"u"?()=>Date.now():()=>performance.now()),n=[],r=new Set;return {marks:n,mark(o,i){return r.has(o)?false:(r.add(o),n.push({name:o,at:i??e()}),true)},timeline(){let o=[...n].sort((i,a)=>i.at-a.at);return o.map((i,a)=>{let s=o[a-1],l=s===void 0?"":` (+${Math.round(i.at-s.at)}ms)`;return `${i.name}@${Math.round(i.at)}ms${l}`}).join(" \u2192 ")}}}var No=false;async function cl(t,e,n,r){if(No){e.close(),n("busy",true);return}No=true;let o=null;try{let i=await Tp(t,r);if(typeof i=="string"){e.close(),n(i,Ep(i));return}o=i;let s=await(r.encodeRef??(l=>Op(l,r)))(o);if(o.close(),o=null,s===null){e.close(),n("failed",!0);return}if(s.size>Mp){e.close(),n("too_large",!1);return}e.postMessage(s);}catch(i){e.close(),n("failed",true),console.error("[gem] screenshot capture failed",i);}finally{No=false,o?.close();}}function Ep(t){switch(t){case "no_source":case "busy":case "failed":return true;case "not_wired":case "unsupported":case "unreadable":case "tainted":case "too_large":case "declined":return false}}async function Tp(t,e){if(e.handler){let i=await e.handler(t);return i===null?"declined":al(i,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=Ip(n);if(!r)return "no_source";let o=Cp(r);if(o!==null)return o;try{return al(await createImageBitmap(r),t)}catch(i){if(i instanceof DOMException&&i.name==="SecurityError")return "tainted";throw i}}function Cp(t){let e;try{e=t.getContext("webgl2")??t.getContext("webgl");}catch{return "unreadable"}if(e){let n=e.getContextAttributes();return !n||n.preserveDrawingBuffer!==true?"unsupported":null}try{if(t.getContext("2d"))return null}catch{return "unreadable"}return "unreadable"}function Ip(t){let e=null,n=0;for(let r of Array.from(t.querySelectorAll("canvas"))){let o=r.width*r.height;o<=0||r.clientWidth<=0||r.clientHeight<=0||o>n&&(e=r,n=o);}return e}async function al(t,e){let{maxWidth:n,maxHeight:r}=e;if(t.width<=n&&t.height<=r)return t;let o=Math.min(n/t.width,r/t.height),i=Math.max(1,Math.floor(t.width*o)),a=Math.max(1,Math.floor(t.height*o));try{let s=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:"high"});return t.close(),s}catch{return t.close(),"too_large"}}var Mp=8*1024*1024,ll="image/webp",dl=.92;async function Op(t,e){try{if(typeof OffscreenCanvas=="function"){let i=new OffscreenCanvas(t.width,t.height),a=i.getContext("2d");if(a){a.drawImage(t,0,0);let s=await i.convertToBlob({type:ll,quality:dl});if(s&&s.size>0)return s}}}catch{}let n=e.documentRef??globalThis.document;if(!n)return null;let r=n.createElement("canvas");r.width=t.width,r.height=t.height;let o=r.getContext("2d");return !o||(o.drawImage(t,0,0),typeof r.toBlob!="function")?null:await new Promise(i=>{r.toBlob(a=>i(a),ll,dl);})}async function ul(t,e){if(!e)return;let n;try{n=await Lp(e);}catch(r){console.error("[gem] onFeedbackContext threw; sending the report without context",r);return}if(n!=null){if(typeof n!="object"||Array.isArray(n)){console.error("[gem] onFeedbackContext must return a plain object or null; got",n);return}t.sendGameContext(n);}}function Lp(t){return new Promise((e,n)=>{let r=false,o=setTimeout(()=>{r||(r=true,console.warn("[gem] onFeedbackContext did not answer within 1000ms; sending the report without context. Gather cheaply, or keep a snapshot."),e(null));},1e3);(async()=>t())().then(i=>{r||(r=true,clearTimeout(o),e(i??null));},i=>{r||(r=true,clearTimeout(o),n(i instanceof Error?i:new Error(String(i))));});})}var ml=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function pl(t=globalThis){let n=t[ml];if(n!==void 0)return n;let r=false,o=()=>r,i=[],a=Gp(t,o);a!==null&&i.push(a);let s=Dp(t,o);s!==null&&i.push(s);let l={get muted(){return r},setMuted(d){let m=!!d;if(m!==r){r=m;for(let c of i)c();}}};return Object.defineProperty(t,ml,{value:l,configurable:true}),l}function Gp(t,e){let n=t.AudioNode?.prototype,r=t.AudioDestinationNode;if(n===void 0||r===void 0)return null;let o=t.OfflineAudioContext,i=n.connect,a=n.disconnect,s=new Map,l=m=>{let c=m.gain,p=m.context.currentTime;c.cancelScheduledValues(p),e()?c.setValueAtTime(0,p):c.setTargetAtTime(1,p,.01);},d=m=>{let c=m.context;if(o!==void 0&&c instanceof o)return null;let p=s.get(c);return p===void 0&&(p=c.createGain(),p.gain.value=e()?0:1,i.call(p,m),s.set(c,p)),p};return n.connect=function(...c){let[p,...g]=c;if(p instanceof r){let y;try{y=d(p);}catch{y=null;}if(y!==null)return i.call(this,y,...g),p}return i.apply(this,c)},n.disconnect=function(...c){let[p,...g]=c;if(p instanceof r){let y=s.get(p.context);if(y!==void 0&&y!==this)try{return a.call(this,y,...g)}catch{}}return a.apply(this,c)},()=>{for(let[m,c]of s){if(m.state==="closed"){s.delete(m);continue}try{l(c);}catch{}}}}function Dp(t,e){let n=t.HTMLMediaElement;if(n===void 0)return null;let r=n.prototype,o=Object.getOwnPropertyDescriptor(r,"muted"),i=o?.get,a=o?.set;if(i===void 0||a===void 0)return null;let s=r.play,l=new WeakMap,d=new WeakSet,m=new Set,c=p=>{l.has(p)||l.set(p,!!i.call(p)),d.has(p)||(d.add(p),m.add(new WeakRef(p))),a.call(p,(l.get(p)??false)||e());};return Object.defineProperty(r,"muted",{configurable:true,enumerable:o?.enumerable??true,get(){let p=l.get(this);return p===void 0?!!i.call(this):p},set(p){l.set(this,!!p),c(this);}}),r.play=function(){try{c(this);}catch{}return s.call(this)},t.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof n)try{c(g);}catch{}},true),()=>{for(let p of m){let g=p.deref();if(g===void 0){m.delete(p);continue}try{a.call(g,(l.get(g)??!1)||e());}catch{}}}}var $p=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",Fp=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',jp=`${$p}${Fp}`,Uo=new WeakSet;function gl(t=globalThis.document){if(t==null||Uo.has(t))return null;try{let e=t.defaultView?.CSSStyleSheet??globalThis.CSSStyleSheet;if(Array.isArray(t.adoptedStyleSheets)&&typeof e=="function"){let r=new e;if(typeof r.replaceSync=="function")return r.replaceSync(jp),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],Uo.add(t),"sheet"}let n=t.documentElement?.style;return n===void 0||typeof n.setProperty!="function"?null:(n.setProperty("-webkit-user-select","none"),n.setProperty("user-select","none"),n.setProperty("-webkit-tap-highlight-color","transparent"),Uo.add(t),"inline")}catch{return null}}function yl(t){let e=t.windowMs??1e3,n=t.realm??globalThis,r=false,o=false,i=false,a=null,s=null,l=null,d=[],m=()=>r&&!o&&!i,c=()=>{s=null,l=null,d=[];},p=w=>{if(a=null,!m()){c();return}if(l!==null&&d.push(w-l),l=w,s===null)s=w;else {let R=w-s;R>=e&&d.length>0&&(t.report(qp(d,R)),s=w,d=[]);}g();},g=()=>{let w=n.requestAnimationFrame;typeof w=="function"&&(a=w.call(n,p));},y=()=>{if(m()){a===null&&(c(),g());return}a!==null&&(n.cancelAnimationFrame?.call(n,a),a=null),c();};return {setRequested(w){r=w,y();},setPaused(w){o=w,y();},get running(){return a!==null},dispose(){i=true,y();}}}function qp(t,e){let n=[...t].sort((o,i)=>o-i),r=Math.max(1,Math.ceil(n.length*.95));return {fps:t.length*1e3/e,frameTimeP95Ms:n[r-1]}}var lr=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function hl(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function bl(t,e){t!==null&&(t.style.setProperty(lr.top,`${e.top}px`),t.style.setProperty(lr.right,`${e.right}px`),t.style.setProperty(lr.bottom,`${e.bottom}px`),t.style.setProperty(lr.left,`${e.left}px`));}var fl=Object.freeze({tl:{width:"--gem-reserved-tl-width",height:"--gem-reserved-tl-height"},tr:{width:"--gem-reserved-tr-width",height:"--gem-reserved-tr-height"},bl:{width:"--gem-reserved-bl-width",height:"--gem-reserved-bl-height"},br:{width:"--gem-reserved-br-width",height:"--gem-reserved-br-height"}});function vl(){let t=globalThis,e=t.innerWidth,n=t.innerHeight;return typeof e=="number"&&e>0&&typeof n=="number"&&n>0?{width:e,height:n}:null}function Np(t,e){let n={tl:{width:0,height:0},tr:{width:0,height:0},bl:{width:0,height:0},br:{width:0,height:0}};for(let r of t){let o=e?r.x+r.width/2<=e.width/2:r.x===0,i=e?r.y+r.height/2<=e.height/2:r.y===0,a=o?r.x+r.width:e?e.width-r.x:r.width,s=i?r.y+r.height:e?e.height-r.y:r.height,l=n[`${i?"t":"b"}${o?"l":"r"}`];l.width=Math.max(l.width,Math.ceil(a)),l.height=Math.max(l.height,Math.ceil(s));}return n}function _l(t,e,n){if(t===null)return;let r=Np(e,n);for(let o of ["tl","tr","bl","br"])t.style.setProperty(fl[o].width,`${r[o].width}px`),t.style.setProperty(fl[o].height,`${r[o].height}px`);}var Up=3e4,dr=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function wl(t){let e=t.clock??le,n=t.timeoutMs??Up,r=new Map,o=new Map,i=0,a=s=>{let l=r.get(s);return l?(r.delete(s),o.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return t.bridge.parentSupports("localHost")},ensure(s){if(!t.bridge.parentSupports("localHost"))return Promise.resolve();let l=o.get(s);if(l)return l;let d=new Promise((m,c)=>{let p=`ls${++i}`,g=e.setTimeout(()=>{r.delete(p),o.delete(s),c(new dr("timeout",true,`the embedder did not answer a local-server request for room ${s} within ${String(n)}ms`));},n);r.set(p,{room:s,resolve:m,reject:c,timer:g}),t.bridge.requestLocalServer(p,s)||(a(p),m());});return o.set(s,d),d.catch(()=>{}),d},accept(s){a(s.requestId)?.resolve();},refuse(s){let l=a(s.requestId);l&&l.reject(new dr(s.reason,s.retryable,s.reason==="refused"?`the platform refused to let this machine serve room ${l.room}. Check that you are signed in as a developer on this game, that the room is on the dev or test channel, and that you host it.`:`this machine could not start a server for room ${l.room}. Your development tool has the reason.`));}}}var rt={url:"https://downloads.indiegems.games/sdk/v7.8.1/gem-web-sdk.devtools.min.js",integrity:"sha384-2IdwSrfdvvOZAn4Xm3GL19qlqsobqsu8C4FEltETQm+m0Slj3syH5hvH62dH76zf"};var vn=null;function Bp(){return vn!==null||(vn=new Promise((t,e)=>{let n=document.createElement("script");n.src=rt.url,n.integrity=rt.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){vn=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${rt.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{vn=null,e(new Error(`gem devtools: could not load ${rt.url}. Either the network refused it or its Subresource Integrity check failed, or the CDN did not answer the CORS preflight this request needs \u2014 SRI is only checkable on bytes the page may read. A locally rebuilt SDK is the commonest cause: it produces panel bytes that do not match the hash compiled into this build.`));},document.head.append(n);})),vn}function Sl(t,e){let n=null,r=0;async function o(i){if(n!==null)return true;let a=++r;if(!e())return false;let s=await Bp();return !e()||a!==r?false:(n!==null||(n=s.mount(t(),{openedBy:i,text:Ne,onDismiss:()=>{n?.unmount(),n=null;}})),true)}return {get isOpen(){return n!==null},close(){r+=1,n?.unmount(),n=null;},open:()=>o("game"),openFrom:o}}var Hp=1e4,Rl={reason:"unavailable",retryable:false};function kl(t){let e=new Map,n=null,r=null,o=0,i=(d,m)=>{m.timer=t.clock.setTimeout(()=>{e.delete(d),m.reject({reason:"timeout",retryable:true});},t.timeoutMs??Hp);},a=(d,m)=>{let c=s(d);c&&m(c);},s=d=>{let m=e.get(d);return m?(e.delete(d),t.clock.clearTimeout(m.timer),m):null},l=new on({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((m,c)=>{let p=t.bridge.currentState;if(p==="refused"||p==="closed"){c(Rl);return}let g=`t${++o}`,y={resolve:m,reject:c,reason:d,timer:null,held:p!=="connected"};e.set(g,y),i(g,y),y.held||t.bridge.requestToken(g,d);})});return {source:l,onToken(d){let m={token:d.token,expiresAt:d.expiresAt,chainEndsAt:d.chainEndsAt};if(n={playerId:d.playerId,gameId:d.gameId,channel:d.channel},r=d.gameVersion??null,d.requestId!==void 0&&e.has(d.requestId)){a(d.requestId,c=>c.resolve(m));return}l.accept(m);},onDenied(d){a(d.requestId,m=>m.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[m,c]of e)c.held&&(c.held=false,t.clock.clearTimeout(c.timer),i(m,c),t.bridge.requestToken(m,c.reason));else if(d==="refused"||d==="closed")for(let m of [...e.keys()])a(m,c=>c.reject(Rl));},get identity(){return n},get gameVersion(){return r}}}function Vp(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var Wp=new Set(pt);function Kp(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))Wp.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function cr(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return ki(async(n,r)=>{let o;try{o=new URL(t.baseUrl.replace(/\/+$/,""));}catch{throw new oe("the configured baseUrl is not a valid URL. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure.")}let i;try{i=new URL(o.href.replace(/\/+$/,"")+n.path);}catch{throw new oe(`${JSON.stringify(typeof n.path=="string"?Vp(n.path):"(a non-string path)")} does not form a valid URL against ${o.protocol}//${o.host}. This is a malformed request, not a server failure.`)}if(i.protocol!==o.protocol||i.host!==o.host)throw new oe(`${JSON.stringify(i.pathname)} resolves to ${i.protocol}//${i.host}, not ${o.protocol}//${o.host}. A request path may not change the request's origin \u2014 it carries the play token.`);if(i.username!==""||i.password!==""){let g=o.username!==""||o.password!=="",y=i.username!==o.username||i.password!==o.password,w=g?y?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new oe(`the ${w} puts credentials in the URL, which cannot be fetched (${n.method} ${i.pathname}). The value is withheld here rather than written to logs. This is a malformed request, not a server failure.`)}for(let[g,y]of Object.entries(t.defaultQuery??{}))i.searchParams.has(g)||i.searchParams.set(g,y);let a=n.bytes,s=n.bytes===void 0?void 0:"application/octet-stream";try{n.body!==void 0&&(a=JSON.stringify(n.body),s="application/json");}catch(g){throw new oe(`the body of ${n.method} ${JSON.stringify(i.pathname)} could not be serialised to JSON: ${String(g)}. This is a bug in the request, not a server failure \u2014 retrying sends the same unserialisable value.`)}let l=await e(i.toString(),{method:n.method,headers:{authorization:`Bearer ${r}`,...s===void 0?{}:{"content-type":s},...Kp(n.headers)},body:a,signal:n.signal,...n.keepalive===void 0?{}:{keepalive:n.keepalive},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer"}),d=null;if(n.responseType==="bytes"&&l.status>=200&&l.status<300)d=new Uint8Array(await l.arrayBuffer());else {let g=await l.text();if(g.length>0)try{d=JSON.parse(g);}catch{d=g;}}let m=l.headers.get("etag"),c=Jp(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...m===null?{}:{etag:m},...c===void 0?{}:{retryAfterSeconds:c},...p===null||p===""?{}:{invocationId:p}}},t)}function Jp(t){if(t===null)return;let e=t.trim();if(!/^\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)?n:void 0}var zp=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),Ho="embedder_relay_unavailable",Yp="embedder_no_relay",Xp=new Set([Ho]),Vo=new Set([Yp]),ot=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new Bo(this)}handleEvent(e){let n=this.pending.get(e.matchId);if(n!==void 0){if(e.event==="matchEnded"){n.refuse(new b("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){n.refuse(new b("signaling_failed","the parent relayed an answer with no SDP in it"));return}n.settle({sdp:e.sdp});return}n.refuse(Qp(e.code,e.message));}}register(e,n){this.pending.get(e)?.refuse(new b("signaling_failed","a newer offer for this match superseded the one in flight")),this.pending.set(e,n);}release(e,n){this.pending.get(e)===n&&this.pending.delete(e);}transport(){let e=this.options.bridge;if(e===null)throw new b("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 b("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 Qp(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new b(Zp(t),r,{platformCode:t})}function Zp(t){return t===void 0||Xp.has(t)?"signaling_failed":Vo.has(t)?"offer_refused":zp.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var Bo=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,n){if(this.closed)return Promise.reject(new b("signaling_unavailable","this signaling channel is closed"));let r;try{r=this.hub.transport();}catch(o){return Promise.reject(o)}return n?.aborted?Promise.reject(new b("aborted","the caller aborted before the offer was sent")):new Promise((o,i)=>{let a=()=>{s(),i(new b("aborted","the caller aborted the signaling exchange"));},s=()=>{n?.removeEventListener("abort",a),this.hub.release(e.matchId,l),this.teardown===s&&(this.teardown=null);},l={settle:d=>{s(),o(d);},refuse:d=>{s(),i(d);}};this.teardown=s,n?.addEventListener("abort",a),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof b?d:new b("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var xl="match_ended:",Al="server_shutdown:",Pl="kicked:",eg=123;function ng(t){if(typeof t!="string"||t.length===0||t.length>eg)return {kind:"other"};if(t.startsWith(xl)){let e=$e(t.slice(xl.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(Al)?{kind:"server_shutdown",cause:t.slice(Al.length)}:t.startsWith(Pl)?{kind:"kicked",detail:t.slice(Pl.length)}:{kind:"other"}}function Wo(t,e,n){let r=ng(n),o=r.kind==="kicked"?"kicked":"link_closed";t.notifyMatchDisconnected(o).catch(()=>{}),r.kind==="match_ended"&&t.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}function Ko(){return {exchange(){return Promise.reject(new b("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 tg=3e3,rg=1e4,og=15e3;async function ur(t){let e=t.peerConnection;try{Tl(t,"before the handshake started"),Jo(t);let n=e.createDataChannel(t.channelLabel??"gem",{ordered:!0});for(let a of t.extraChannels??[]){let s=e.createDataChannel(a.label,{...a.ordered===void 0?{}:{ordered:a.ordered},...a.maxRetransmits===void 0?{}:{maxRetransmits:a.maxRetransmits}});t.onExtraChannel?.(a.label,s);}let r=await e.createOffer();await e.setLocalDescription(r),await ag(e,t),Jo(t);let o=e.localDescription?.sdp??r.sdp;if(!o)throw new b("invalid_sdp","the offer carried no SDP");Fe(o,"offer"),El(o,"offer");let i=await sg(t,o);if(Jo(t),typeof i?.sdp!="string")throw new b("invalid_sdp","the signaling channel answered without an SDP");return Fe(i.sdp,"answer"),El(i.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:i.sdp}),await lg(n,t),Tl(t,"before the channel opened"),n}catch(n){throw e.close(),ig(n)}}function ig(t){return t instanceof b?t:Ml(t)?ze():new b("connection_failed",Ol(t),{cause:t})}function El(t,e){if(rr(t))throw new b("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 sg(t,e){let n=t.exchangeTimeoutMs??rg,r=Il(t,n),o=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(i=>{throw i instanceof b?i:Ml(i)?ze():new b("signaling_failed",Ol(i),{cause:i})});return dg(o,t,r,()=>r.exhausted?zo("while the offer was in flight"):new b("timeout",`no answer arrived within ${n}ms`))}function ag(t,e){if(t.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:n}=e;return new Promise(r=>{let o=()=>{n.clearTimeout(a),t.removeEventListener("icegatheringstatechange",i),e.signal?.removeEventListener("abort",o),r();},i=()=>{t.iceGatheringState==="complete"&&o();},a=n.setTimeout(o,e.gatherTimeoutMs??tg);t.addEventListener("icegatheringstatechange",i),e.signal?.addEventListener("abort",o);})}function lg(t,e){if(e.signal?.aborted)return Promise.reject(ze());if(t.readyState==="open")return Promise.resolve();if(t.readyState!=="connecting")return Promise.reject(new b("connection_failed",`the data channel was already '${t.readyState}' when the answer was applied`));let{clock:n}=e,r=e.openTimeoutMs??og,o=Il(e,r);return new Promise((i,a)=>{let s=()=>{n.clearTimeout(p),t.removeEventListener("open",l),t.removeEventListener("close",d),t.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{s(),i();},d=g=>{s(),a(new b("connection_failed","the data channel failed before it opened",Cl(g)===void 0?void 0:{cause:Cl(g)}));},m=()=>{s(),a(ze());},c=()=>{s(),a(o.exhausted?zo("while the channel was still opening"):new b("timeout",`the data channel did not open within ${r}ms`));},p=n.setTimeout(c,o.ms);t.addEventListener("open",l),t.addEventListener("close",d),t.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function Il(t,e){if(t.credentialExpiresAt===void 0)return {ms:e,exhausted:false};let n=t.credentialExpiresAt-t.clock.now();return n<=e?{ms:Math.max(0,n),exhausted:true}:{ms:e,exhausted:false}}function dg(t,e,n,r){let{clock:o,signal:i}=e;return i?.aborted?Promise.reject(ze()):new Promise((a,s)=>{let l=c=>{o.clearTimeout(m),i?.removeEventListener("abort",d),c();},d=()=>l(()=>s(ze())),m=o.setTimeout(()=>l(()=>s(r())),n.ms);i?.addEventListener("abort",d),t.then(c=>l(()=>a(c)),c=>l(()=>s(c)));})}function Tl(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw zo(`already ${e}`)}function zo(t){return new b("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function Jo(t){if(t.signal?.aborted)throw ze()}function ze(){return new b("aborted","the caller aborted the connection attempt")}function Ml(t){return t?.name==="AbortError"}function Cl(t){return t?.error}function Ol(t){return t instanceof Error?t.message:String(t)}Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"}));Object.freeze(Object.assign(Object.create(null),{answer:[z("sdp","sdp",B(10240)),H("sessionId","session_id",B(64))],error:[H("code","code",B(64)),H("message","message",B(256))],matchEnded:[H("reason","reason",B(64))]}));function Nl(t){let{client:e,clock:n,rooms:r}=t,o=t.signaling??Ko,i=t.log??(_=>console.warn(_)),a=new yn({client:e,gameId:()=>r.gameId,transport:"dedicated"}),s=new Map,l=(_,S)=>{let P=s.get(_)??new Set;P.add(S),s.set(_,P);},d=(_,S)=>{let P=s.get(_);P!==void 0&&(P.delete(S),P.size===0&&s.delete(_));},m=async _=>{if(r.isHost&&!Xo(r)&&r.currentRoom?.matchId===void 0){let S=me(_.clusterTargetId);await r.startMatch({...S===void 0?{}:{clusterTargetId:S},..._.retry===void 0?{}:{retry:_.retry},..._.signal===void 0?{}:{signal:_.signal}});}return jl(r.matchConnectionState==="suspended"?await r.reconnectToMatch(Yo(_)):await r.awaitMatch(Yo(_)))},c=async _=>jl(await r.pollMatchStatus(Yo(_))),p=async(_,S)=>{let P=false;try{let x=await m(_),V=r.currentRoom?.transports;if(V!==void 0&&!V.includes("webrtc"))throw new b("misconfigured",`the room template offers (${V.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 N=_.peerConnection??ql();P=!0;let W=await ur({peerConnection:N,signaling:S,clock:n,matchId:x.matchId,credentialExpiresAt:x.credentialExpiresAt,...mr(_,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),k=null;if(_.presentCredential!==!1)try{k=await qn({channel:W,clock:n,credential:x.joinCredential,credentialExpiresAt:x.credentialExpiresAt,...mr(_,"onMessage","signal"),..._.welcomeTimeoutMs===void 0?{}:{ceilingMs:_.welcomeTimeoutMs}});}catch(A){throw we(W),we(N),A}return bg(r,x,W,N,S,_.reportDisconnect!==!1,_.reportConnected!==!1,k,{remember:l,forget:d},_.onMatchEnded)}catch(x){throw P&&Fl(a,x),we(S),x}},g=async(_,S,P,x,V,N)=>{if(_==="webtransport"){let j=x?.webtransport;if(j===void 0)throw new b("misconfigured","webtransport is not advertised");let U={credential:P.joinCredential,credentialExpiresAt:P.credentialExpiresAt,clock:n};if(typeof j.named_url=="string"&&j.named_url!==""){let ee=Math.max(Math.floor(N/2),1e3);try{return await Hn({url:j.named_url,timeoutMs:ee,log:i,...U})}catch(ge){if(Xt()!==null)throw ge;return i(`[gem] webtransport named dial failed (${zt(ge)}); retrying the pinned dial`),Hn({url:j.url,certHashBase64:j.cert_sha256_b64,timeoutMs:ee,log:i,...U})}}return Hn({url:j.url,certHashBase64:j.cert_sha256_b64,timeoutMs:N,...U})}if(_==="websocket"){let j=x?.websocket;if(j===void 0)throw new b("misconfigured","websocket is not advertised");return ho({url:j.url,credential:P.joinCredential,credentialExpiresAt:P.credentialExpiresAt,clock:n,timeoutMs:N})}let W=S.peerConnection??ql(),k,A=await ur({peerConnection:W,signaling:V,clock:n,matchId:P.matchId,credentialExpiresAt:P.credentialExpiresAt,extraChannels:[{label:Un,ordered:false,maxRetransmits:0}],onExtraChannel:(j,U)=>{j===Un&&(k=U);},...mr(S,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...S.exchangeTimeoutMs===void 0&&S.redial===true?{exchangeTimeoutMs:mg}:{}}),L;try{L=await qn({channel:A,clock:n,credential:P.joinCredential,credentialExpiresAt:P.credentialExpiresAt,wire:Jt,heartbeat:!0,...mr(S,"signal"),...S.welcomeTimeoutMs===void 0?{}:{ceilingMs:S.welcomeTimeoutMs}});}catch(j){throw we(A),we(W),j}let D=L.welcome.heartbeatIntervalMs;return {link:vo(A,W,k,D===void 0?void 0:{clock:n,intervalMs:D}),welcome:L.welcome,channel:A,peerConnection:W}},y=(_,S,P,x,V)=>{let N=false,W;x.link.onClose(D=>{!N&&_.reportDisconnect!==false&&Wo(r,S.matchId,D),W?.(D);}),_.reportDisconnect!==false&&_.reportConnected!==false&&r.notifyMatchConnected(S.matchId);let k={transport:x.link.transport,send:(D,j)=>x.link.send(D,j),onMessage:D=>x.link.onMessage(D),onClose:D=>{W=D;},close:()=>x.link.close()},A=()=>{N||(N=true,we(x.link),we(V));},L=D=>{if(!N){try{_.onMatchEnded?.(D);}catch{}A();}};return l(S.matchId,L),{matchId:S.matchId,transport:P,link:k,joinCredential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,welcome:x.welcome,...x.channel===void 0?{}:{channel:x.channel},...x.peerConnection===void 0?{}:{peerConnection:x.peerConnection},close(){d(S.matchId,L),A();}}},w=async(_,S)=>{let P=r.currentRoom?.id,x=r.gameId,V=()=>({advert:Bn(r.currentRoom?.settings,_),template:r.currentRoom?.transports??null});if(P===void 0||x===null)return V();try{let N=await e.get(`/v2/games/${encodeURIComponent(x)}/game-rooms/${encodeURIComponent(P)}`,S);return {advert:Bn(N.settings,_),template:pn(N.transports)??r.currentRoom?.transports??null}}catch{return V()}},R=(_,S)=>{let P=_??Ll;return S.length===0?P:P.filter(x=>S.includes(x))},I=async(_,S,P)=>{try{let x=await m(_),{advert:V,template:N}=await w(x.matchId,_.signal),W=R(N,S),k=W.filter(Q=>yg(Q,V)),A=Xt();if(A!==null&&W.includes("webtransport")&&V?.webtransport!==void 0&&i(`[gem] webtransport skipped: ${A} (learned on an earlier dial in this page)`),k.length===0){let Q=N===null?`the default order (${Ll.join(", ")})`:`the room template's transports (${N.join(", ")||"none"})`;throw new b("misconfigured",`none of ${Q}`+(S.length>0?`, narrowed to (${S.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let L=_.transportAttemptTimeoutMs??ug,D=()=>_.deadlineAt===void 0?1/0:_.deadlineAt-n.now(),j=Q=>t.signalingReady===void 0||Q<=0?Promise.resolve(!0):t.signalingReady(Q),U=[],ee=[];for(let Q of k){if(D()<Dl){i(`[gem] ${Q} rung not tried: the reconnect budget is spent`);break}ee.length>0&&x.credentialExpiresAt-n.now()<$l&&(x=await c(_)),ee.push(Q);let Oe=!1,Se=!1,Ce={attempts:0,waitedMs:0};for(;;){if(Q==="webrtc"&&_.redial===!0){let re=Math.min(Gl,D());await j(re)||i(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(re)}ms; offering anyway`);}let Ie=Math.max(Math.min(L,D()),Dl);try{return y(_,x,Q,await g(Q,_,x,V,P,Ie),P)}catch(re){let Y=re instanceof b?re:new b("connection_failed",re instanceof Error?re.message:String(re),{cause:re});if(Q==="webrtc"&&Fl(a,Y),(Y.reason==="credential_expired"||Y.reason==="credential_reused")&&!Oe){Oe=!0,x=await c(_);continue}if(Q==="webrtc"&&Y.reason==="signaling_failed"&&Y.platformCode===Ho&&!Se){Se=!0;let de=Math.min(Gl,D());if(i(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(de)}ms for the socket before offering again`),await j(de))continue}if(Y.reason==="join_rate_limited"){let de=gg(Ce,Math.random,D());if(de!==null){if(Ce.attempts+=1,Ce.waitedMs+=de,i(`[gem] ${Q} rung: the server is rate-limiting this player's joins; waiting ${Math.round(de)}ms before presenting again (retry ${Ce.attempts} of ${Bl.maxAttempts})`),await Vt(n,de,_.signal),_.signal?.aborted)throw new b("aborted","the caller aborted while waiting out a join rate limit");x.credentialExpiresAt-n.now()<$l&&(x=await c(_));continue}}if(pg.has(Y.reason)||Y.reason==="credential_expired"||Q==="webrtc"&&Ul(Y)){i(`[gem] ${Q} rung failed (${Y.reason}): ${zt(Y.cause??Y)} \u2014 `+(ee.length<k.length?`falling through to ${k[ee.length]}`:"no rungs left")),U.push(Y);break}throw i(`[gem] ${Q} rung refused the session (${Y.reason}): ${Y.message}`),Y}}}let ge=U[U.length-1];throw ge===void 0?new b("timeout",`the reconnect budget ran out before any transport (${k.join(", ")}) could be tried`):new b(ge.reason,`every transport tried (${ee.join(", ")}) failed; the last said: ${ge.message}`,{cause:U,platformCode:ge.platformCode})}catch(x){throw we(P),x}};return {listClusterTargets:async(_={})=>no({client:e,..._}),handleMatchEnded(_,S){let P=s.get(_);if(P!==void 0){s.delete(_);for(let x of P)x(S);}},connect:(async(_={})=>{let S=_.signaling??o();return _.transports===void 0?p(_,S):I(_,_.transports,S)})}}var Ll=["webtransport","webrtc","websocket"],ug=1e4,mg=5e3,Gl=3e3,Dl=1e3,$l=1e4,pg=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function Ul(t){return t.platformCode!==void 0&&Vo.has(t.platformCode)}var Bl={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function gg(t,e=Math.random,n=1/0){let r=Bl;if(t.attempts>=r.maxAttempts)return null;let o=Math.min(r.budgetMs-t.waitedMs,n);if(o<r.initialDelayMs)return null;let i=r.initialDelayMs*r.factor**t.attempts;return Math.min(i+e()*r.jitterMs,o)}function yg(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&Yt():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||fg(e.websocket.url)}function fg(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return wt(e)}function Yo(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var hg=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Fl(t,e){e instanceof b&&(!hg.has(e.reason)&&!Ul(e)||t.report([{type:"connection_failures_total",value:1}]));}function bg(t,e,n,r,o,i,a,s,l,d){let m=false,c=()=>{m||Wo(t,e.matchId,void 0);};i&&(n.addEventListener("close",c),a&&t.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,n.removeEventListener("close",c),s?.detach(),we(n),we(r),we(o));},g=y=>{if(!m){try{d?.(y);}catch{}p();}};return l.remember(e.matchId,g),{matchId:e.matchId,channel:n,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:s?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function Xo(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function jl(t){if(t.status==="failed")throw new b("allocation_failed",`match ${t.matchId} did not come up: ${t.reason}`);if(t.status==="ended")throw new b("match_ended",`match ${t.matchId} ended (${t.reason}) before this side connected.`);if(t.protocol!==Ht)throw new b("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${Ht}' is reachable from a frame; host and port on this response are advisory and must not be dialled.`);let{joinCredential:e,credentialExpiresAt:n}=t;if(e===void 0||n===void 0)throw new b("connection_failed",`match ${t.matchId} is ready but issued no join credential, so the server would refuse the channel once it opened \u2014 poll match status again.`);return {...t,joinCredential:e,credentialExpiresAt:n}}function ql(){let t=globalThis.RTCPeerConnection;if(!t)throw new b("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 t({iceServers:[]})}function we(t){try{t.close();}catch{}}function mr(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var vg=1e4;function Hl(t,e){return Qo(t,e)}function Qo(t,e){if(typeof t.serverToken!="function"||typeof t.onServerToken!="function")throw new Error("this runtime delivers no game-server token: host.serverToken/onServerToken are missing. The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let n=a=>({token:a.token,expiresAt:a.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,o=new on({clock:e.clock,...e.onStateChange===void 0?{}:{onStateChange:e.onStateChange},request:()=>new Promise((a,s)=>{let l=e.clock.setTimeout(()=>{r=null,s({reason:"unavailable",retryable:true});},e.timeoutMs??vg);r={resolve:d=>{e.clock.clearTimeout(l),a(d);},reject:s,timer:l};})}),i=t.onServerToken(a=>{let s=n(a),l=r;if(l){r=null,l.resolve(s);return}o.accept(s);});return {source:o,dispose(){i(),r&&(e.clock.clearTimeout(r.timer),r.reject({reason:"unavailable",retryable:false}),r=null);}}}var ei={};Pd(ei,{acceptTransfer:()=>_g,addEntityProgression:()=>wg,adminAction:()=>Sg,cancelInventoryTransfer:()=>Rg,claimEntityProgressionRewards:()=>kg,closeGameRoom:()=>xg,createEntityBatchOrder:()=>Ag,createEntityOrder:()=>Pg,createSession:()=>Eg,deleteEntityGameSetting:()=>Tg,deleteEntitySave:()=>Cg,deleteSession:()=>Ig,deleteShowcaseValue:()=>Mg,executeEntityRecipe:()=>Og,finalizeSaveUpload:()=>Lg,getChannelAssignment:()=>Gg,getDropRates:()=>Dg,getEntityCurrency:()=>$g,getEntityGameSetting:()=>Fg,getEntityInventory:()=>jg,getEntityInventoryItem:()=>qg,getEntityLeaderboard:()=>Ng,getEntityOrder:()=>Ug,getEntityProgression:()=>Bg,getEntityRecipeAvailability:()=>Hg,getEntityRecipeUsage:()=>Vg,getEntitySave:()=>Wg,getEvent:()=>Kg,getGameRoomV2:()=>Jg,getLeaderboard:()=>zg,getPlayerGameProfile:()=>Yg,getPurchaseCatalog:()=>Xg,getResolvedTemplate:()=>Qg,getRoomArgs:()=>Zg,getShowcaseValue:()=>ey,getTransferDetails:()=>ny,ingestAnalyticsEvents:()=>Zo,initiateInventoryTransfer:()=>ty,invokeFunction:()=>ry,kickPlayer:()=>oy,listChallenges:()=>iy,listEntityGameSettings:()=>sy,listEntityOrders:()=>ay,listEntityProgressions:()=>ly,listEntitySaves:()=>dy,listEvents:()=>cy,listGameRooms:()=>uy,listResolvedTemplates:()=>my,listTransfers:()=>py,maxEntityProgression:()=>gy,putEntityGameSetting:()=>yy,putRoomArgs:()=>fy,putShowcaseValue:()=>hy,rejectTransfer:()=>by,requestSaveUploadUrl:()=>vy,resetEntityProgression:()=>_y,simulateEntityOrder:()=>wy,transferHostV2:()=>Sy,updateGameRoomV2:()=>Ry});function h(t){let e=String(t);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 _g(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function wg(t,e,n,r,o,i){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/add`;return t.client.post(a,o,i?.signal)}async function Sg(t,e,n,r){let o=`/v1/voice/sessions/${h(e)}/admin`;return t.client.post(o,n,r?.signal)}async function Rg(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function kg(t,e,n,r,o,i){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/claim`;return t.client.post(a,o,i?.signal)}async function xg(t,e,n){let r=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}`;return t.client.delete(r,n?.signal)}async function Ag(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/orders/batch`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Pg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/orders`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Eg(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function Tg(t,e,n,r,o){let i=`/v1/settings/${h(e)}/${h(n)}/${h(r)}`;return t.client.delete(i,o?.signal)}async function Cg(t,e,n,r,o){let i=`/v1/saves/${h(e)}/${h(n)}/${h(r)}`;return t.client.delete(i,o?.signal)}async function Ig(t,e,n){let r=`/v1/voice/sessions/${h(e)}`;return t.client.delete(r,n?.signal)}async function Mg(t,e,n,r){let o=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.delete(o,r?.signal)}async function Og(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/recipes/execute`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Lg(t,e,n,r,o,i){let a=`/v1/saves/${h(e)}/${h(n)}/${h(r)}/finalize`;return t.client.post(a,o,i?.signal)}async function Gg(t,e,n){let r=`/v1/games/${h(t.gameId())}/config/channels/${h(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Dg(t,e,n){let r=`/v1/inventory/loot-tables/${h(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function $g(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/currencies/${h(r)}`;return t.client.get(i,o?.signal)}async function Fg(t,e,n,r,o){let i=`/v1/settings/${h(e)}/${h(n)}/${h(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function jg(t,e,n,r){let o=new URLSearchParams;r?.include_buckets!==void 0&&o.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&o.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&o.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&o.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&o.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&o.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&o.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&o.set("progression_cursor",String(r?.progression_cursor));let i=o.toString(),a=`/v1/inventory/${h(e)}/${h(n)}`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function qg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/items/${h(r)}`;return t.client.get(i,o?.signal)}async function Ng(t,e,n,r,o){let i=new URLSearchParams;o?.bucket_1!==void 0&&i.set("bucket_1",String(o?.bucket_1)),o?.bucket_2!==void 0&&i.set("bucket_2",String(o?.bucket_2)),o?.limit!==void 0&&i.set("limit",String(o?.limit)),o?.periods_back!==void 0&&i.set("periods_back",String(o?.periods_back)),o?.period!==void 0&&i.set("period",String(o?.period)),o?.player_id!==void 0&&i.set("player_id",String(o?.player_id));let a=i.toString(),s=`/v1/leaderboards/${h(e)}/${h(n)}/${h(r)}`+(a?`?${a}`:"");return t.client.get(s,o?.signal)}async function Ug(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/orders/${h(r)}`;return t.client.get(i,o?.signal)}async function Bg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}`;return t.client.get(i,o?.signal)}async function Hg(t,e,n,r,o,i){let a=`/v1/inventory/${h(e)}/${h(n)}/catalogs/${h(r)}/recipes/${h(o)}/availability`;return t.client.get(a,i?.signal)}async function Vg(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit));let i=o.toString(),a=`/v1/inventory/${h(e)}/${h(n)}/recipe-usage`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function Wg(t,e,n,r,o){let i=`/v1/saves/${h(e)}/${h(n)}/${h(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Kg(t,e,n){let r=`/v1/events/${h(e)}`;return t.client.get(r,n?.signal)}async function Jg(t,e,n){let r=`/v2/games/${h(t.gameId())}/game-rooms/${h(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function zg(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let o=r.toString(),i=`/v1/leaderboards/${h(e)}`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function Yg(t,e,n){let r=`/v1/profiles/players/${h(e)}`;return t.client.get(r,n?.signal)}async function Xg(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),o="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function Qg(t,e,n){let r=`/v1/game-room-templates/${h(e)}`;return t.client.get(r,n?.signal)}async function Zg(t,e,n){let r=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}/room-args`;return t.client.get(r,n?.signal)}async function ey(t,e,n,r){let o=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.get(o,r?.signal)}async function ny(t,e,n){let r=`/v1/inventory/transfers/${h(e)}`;return t.client.get(r,n?.signal)}async function Zo(t,e,n){let r=`/v1/games/${h(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true})}async function ty(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function ry(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function oy(t,e,n,r){let o=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}/kick/${h(n)}`;return t.client.post(o,void 0,r?.signal)}async function iy(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),o="/v1/challenges"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function sy(t,e,n,r){let o=`/v1/settings/${h(e)}/${h(n)}`;return t.client.get(o,r?.signal)}async function ay(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/inventory/${h(e)}/${h(n)}/orders`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function ly(t,e,n,r){let o=`/v1/inventory/${h(e)}/${h(n)}/progressions`;return t.client.get(o,r?.signal)}async function dy(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/saves/${h(e)}/${h(n)}`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function cy(t,e){let n=new URLSearchParams;e?.include_inactive!==void 0&&n.set("include_inactive",String(e?.include_inactive)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.offset!==void 0&&n.set("offset",String(e?.offset));let r=n.toString(),o="/v1/events"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function uy(t,e){let n=new URLSearchParams;e?.status!==void 0&&n.set("status",String(e?.status)),e?.game_channel!==void 0&&n.set("game_channel",String(e?.game_channel)),e?.game_room_type!==void 0&&n.set("game_room_type",String(e?.game_room_type)),e?.template_id!==void 0&&n.set("template_id",String(e?.template_id)),e?.template_slug!==void 0&&n.set("template_slug",String(e?.template_slug)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),o=`/v1/games/${h(t.gameId())}/game-rooms`+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function my(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function py(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),o="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function gy(t,e,n,r,o,i){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/max`;return t.client.post(a,o,i?.signal)}async function yy(t,e,n,r,o,i){let a=`/v1/settings/${h(e)}/${h(n)}/${h(r)}`;return t.client.put(a,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function fy(t,e,n,r){let o=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}/room-args`;return t.client.put(o,n,r?.signal)}async function hy(t,e,n,r,o){let i=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.put(i,r,o?.signal)}async function by(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function vy(t,e,n,r,o,i){let a=`/v1/saves/${h(e)}/${h(n)}/${h(r)}/upload-url`;return t.client.post(a,o,i?.signal,{replaySafe:true})}async function _y(t,e,n,r,o,i){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/reset`;return t.client.post(a,o,i?.signal)}async function wy(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/orders/simulate`;return t.client.post(i,r,o?.signal)}async function Sy(t,e,n,r){let o=`/v2/games/${h(t.gameId())}/game-rooms/${h(e)}/transfer/${h(n)}`;return t.client.post(o,void 0,r?.signal)}async function Ry(t,e,n,r){let o=`/v2/games/${h(t.gameId())}/game-rooms/${h(e)}`;return t.client.patch(o,n,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var ky=1e4,xy=50,Ay=1e3,Py=65536-4*1024,Vl=t=>typeof t=="number"?t:0,Ey=t=>typeof t=="string"?t:"";function Wl(){let t=globalThis.crypto;return typeof t?.randomUUID=="function"?t.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.floor(Math.random()*16);return (e==="x"?n:n&3|8).toString(16)})}function Ty(t){return t?.retryable===true}function Cy(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:Vl(i.index),code:Ey(i.code)}}):[];return {accepted:Vl(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Kl(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,player_id:t.playerId,dimensions:t.dimensions,measures:t.measures}}function Jl(t){let e=Math.max(1,Math.floor(t.maxQueue??Ay)),n={client:t.client,gameId:()=>t.gameId},r=[],o=0,i=null,a=false,s=false,l=false,d=false,m=w=>{t.log?.(w);},c=()=>{i!==null&&(t.clock.clearTimeout(i),i=null);},p=()=>{i!==null||a||s||(i=t.clock.setTimeout(()=>{i=null,y().catch(()=>{});},ky));},g=()=>{let w=Math.min(r.length,100),R=128;for(let I=0;I<w;I+=1){let M=r[I];if(M===void 0)break;if(R+=JSON.stringify(Kl(M,0)).length+1,R>Py)return Math.max(1,I)}return w};async function y(w){if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};c();let R=r.splice(0,g()),I=o;o=0;let M=Math.round(t.clock.now()),_={batch_id:Wl(),sent_at_ms:M,events:R.map(S=>Kl(S,M))};s=true;try{let S=await Zo(n,_,w===void 0?void 0:{signal:w}),P=Cy(S,I);for(let x of P.rejected)m(`[gem] analytics: an event was refused (${x.code}). See the analytics_events section of your game config.`);return P}catch(S){if(Ty(S))for(r=[...R,...r],o+=I;r.length>e;)r.shift(),o+=1;else m(`[gem] analytics: ${R.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(S)}`);throw S}finally{s=false,r.length>0&&p();}}return {track(w,R,I={}){if(a)return;if(typeof w!="string"||w===""){d||(d=true,m(`[gem] analytics: '${R}' was not recorded \u2014 an event from a server has to name the player it is about. A game-server token names no player, so the platform cannot infer one; pass the id from join() or host.players().`));return}if(R.startsWith(Vr)){l||(l=true,m(`[gem] analytics: '${R}' was not recorded \u2014 the gem_ prefix is reserved, and the platform's own events are client-sourced, so a server may not emit one at all. Name your event something else.`));return}let M={},_={};for(let[S,P]of Object.entries(I))typeof P=="string"?M[S]=P:typeof P=="number"&&Number.isFinite(P)&&(_[S]=P);for(;r.length>=e;)r.shift(),o+=1;r.push({uid:Wl(),playerId:w,name:R,atMs:t.clock.now(),dimensions:M,measures:_}),r.length>=xy?y().catch(()=>{}):p();},flush:w=>y(w),get pending(){return r.length},dispose(){a=true,c(),r=[],o=0;}}}function zl(t){return {async list(e){let{playerId:n,periodsBack:r,signal:o}=e??{};if(typeof n!="string"||n==="")throw new TypeError("gem.challenges.list needs { playerId }: a game-server token names no player, so the platform cannot tell whose period you mean. Pass the id from join() or gem.players().");cn(r);let i=await t({player_id:n,...r===void 0?{}:{periods_back:r},...o===void 0?{}:{signal:o}});return jt(i)}}}function Iy(t){let e={};for(let[n,r]of Object.entries(ei))if(typeof r=="function"){let o=r;e[n]=(...i)=>o(t,...i);}return e}function _n(t,e={}){let n=e.clock??le,r=e.baseUrl??t.apiBaseUrl;if(!r)throw new Error("this runtime names no gem-api host (host.apiBaseUrl is missing). The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let o=Qo(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),i=cr({baseUrl:r,tokenSource:o.source,defaultQuery:{game_id:t.gameId,channel:t.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),a=new Le({transport:i,clock:n}),s={gameId:t.gameId,channel:t.channel,matchId:t.matchId,...t.gameRoomId===void 0?{}:{gameRoomId:t.gameRoomId}},l=Iy({client:a,gameId:()=>s.gameId}),d=s.gameRoomId,m=t.endMatch,c=t.log,p=Jl({client:a,clock:n,gameId:s.gameId,...typeof c=="function"?{log:y=>c.call(t,y)}:{}});return {identity:s,client:a,api:l,match:{end:async()=>{if(m===void 0)throw new Error("this runtime cannot end the match: the server image running this bundle predates host.endMatch, and only the platform half holds the allocation proof an end needs.");await m.call(t);}},analytics:p,functions:new De(l.invokeFunction),challenges:zl(l.listChallenges),...d===void 0?{}:{room:{get:y=>l.getGameRoomV2(d,y),args:async y=>{let w=await l.getGameRoomV2(d,y?.signal===void 0?{}:{signal:y.signal}),R=w.modified?w.body:void 0;if(R?.room_args==null||R.room_args_template==null)throw new G("not_found",404,"this room's template declares no room args",void 0,"room_args_not_defined");return {room_args:R.room_args,room_args_template:R.room_args_template}}}},dispose:()=>{p.dispose(),o.dispose();}}}function Ye(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function wn(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function it(t){return typeof t=="string"?t:t.slice().buffer}function pr(t){if(typeof t=="string")return {data:t,isText:true};if(t instanceof ArrayBuffer)return {data:new Uint8Array(t),isText:false};if(ArrayBuffer.isView(t)){let e=t;return {data:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),isText:false}}return null}var My=5e3,Yl=3e4,Xl=2e3,Oy=1e4,Ql=1;async function Zl(t,e){let{session:n,localPlayerId:r}=e;if(!n.isHost)throw new Error("[gem] runListenHost was handed a session this player does not host. The room decides who hosts; gate on `gem.rooms.isHost` \u2014 or call `gem.match.serve()`, which does.");let o=e.log===void 0?f=>console.info(f):e.log,i=f=>o?.(`[gem host] ${f}`),a=typeof t=="function"?t():t,s=Promise.resolve(),l=true,d=false,m=(f,E)=>{l&&(s=s.then(async()=>{if(!d)try{await E();}catch($){i(`the bundle's ${f} handler threw: ${Xe($)}. Serving continues.`);}}));},c=true,p,g,y,w=f=>{if(!c)return;c=false,m("leave",()=>a.leave?.(r,{cause:f??"left"}));let E=g;E&&queueMicrotask(()=>E(f));},R={send(f,E){if(!c)return;let $=wn(Ye(E));m("message",()=>a.message?.(r,f,typeof f=="string",{reliable:$.reliable,ordered:$.ordered}));},onMessage(f){p=f;},onClose(f){g=f;},close(){w("closed");}},I=(f,E)=>{if(!c)return;let $=wn(Ye(E));queueMicrotask(()=>{c&&p?.(f,$);});},M=new Map,_=f=>{let E=[];for(let $ of Me){let ne=f.channels[$];try{ne.binaryType="arraybuffer";}catch{}let J=wn($),Sn=gr=>{let en=pr(gr?.data);en!==null&&m("message",()=>a.message?.(f.playerId,en.data,en.isText,{reliable:J.reliable,ordered:J.ordered}));};ne.addEventListener("message",Sn),E.push(()=>ne.removeEventListener("message",Sn));}M.get(f.playerId)?.forEach($=>$()),M.set(f.playerId,E);},S=f=>{M.get(f)?.forEach(E=>E()),M.delete(f);},P=new Set,x=new Map,V=(f,E,$)=>({playerNumber:f.assignedPeerId,transport:"webrtc_p2p",...E?{rejoin:true}:{},...$?{superseded:true}:{}}),N=f=>{let E=M.has(f.playerId),$=P.has(f.playerId);P.add(f.playerId),_(f),E&&m("leave",()=>a.leave?.(f.playerId,{cause:"superseded"})),m("join",()=>a.join?.(f.playerId,V(f,$,E)));},W=new Set,k=(f,E,$)=>{if(f===r){I(E,$);return}let ne=n.peer(f);if(ne===null){let J=x.get(f);if(J!==void 0&&e.clock.now()-J<Xl)return;W.has(f)||(W.add(f),i(`send to '${f}' dropped: no such connected player`));return}ne.send(it(E),Ye($));},A={matchId:n.matchId,gameId:e.gameId,channel:e.channel,...e.gameRoomId===void 0?{}:{gameRoomId:e.gameRoomId},apiBaseUrl:e.apiBaseUrl,serverToken:()=>e.tokens.current(),onServerToken:f=>e.tokens.subscribe(f),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(f=>f.playerId)??[],players(){let f=c?[r]:[];for(let E of n.peers)f.push(E.playerId);return f},profile(f){let E=e.room()?.members.find($=>$.playerId===f);if(!(!E||E.displayName===void 0))return {displayName:Ne.toPlain(E.displayName),...E.displayTag===void 0?{}:{displayTag:Ne.toPlain(E.displayTag)},...E.discriminator===void 0?{}:{discriminator:E.discriminator}}},playerNumber(f){return f===r?Ql:n.peer(f)?.assignedPeerId},send(f,E,$){k(f,E,$);},broadcast(f,E){let $=E?.except;c&&r!==$&&I(f,E);for(let ne of n.peers)ne.playerId!==$&&ne.send(it(f),Ye(E));},async endMatch(){let f=await Ie();return f.answer!=="ok"&&i(f.cause),f.answer},kick(f,E){if(f===r){w(E??"kicked");return}n.kick(f).catch($=>{i(`kick of '${f}' failed: ${Xe($)}`);});},log(f){i(f);},warn(f){i(`\u26A0 ${f}`);}},L=()=>{},D=new Promise(f=>{L=f;}),j=[],U=null,ee=async(f,E)=>{l=false;let $=s.then(async()=>{try{await a.shutdown(f);}catch(ne){i(`the bundle's shutdown threw: ${Xe(ne)}`);}});s=$,await $,de();for(let ne of j.splice(0))ne();for(let ne of [...M.keys()])S(ne);w(E);},ge=(f,E)=>U||(U=(async()=>{await ee(E,f),n.close(),L();})(),U),Q=()=>U||(U=(async()=>{await ee({reason:"signal"},"left"),await n.leave().catch(f=>i(`leaving the match failed: ${Xe(f)}`)),L();})(),U),Oe=()=>U||(U=(async()=>{l=false;let f=await Ie();f.answer==="ok"?(await ee({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(i(`${f.cause}; leaving instead`),await ee({reason:"signal"},"left"),await n.leave().catch(E=>i(`leaving the match failed: ${Xe(E)}`))),L();})(),U),Se=null,Ce=()=>(Se??=_n(A,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),Se),Ie=async()=>{try{return await bs({client:Ce().client,gameId:()=>A.gameId},A.matchId,{},{signal:AbortSignal.timeout(My)}),{answer:"ok"}}catch(f){return f instanceof G&&(f.reason==="forbidden"||f.reason==="not_found")?{answer:f.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${f.reason})`}:{answer:"failed",cause:`ending the match failed: ${Xe(f)}`}}},re=null,Y=false,de=()=>{Y=true,re!==null&&(e.clock.clearTimeout(re),re=null);},q=async()=>{if(re=null,!Y){try{await Ce().client.post(`/v1/games/${encodeURIComponent(A.gameId)}/matches/${encodeURIComponent(A.matchId)}/heartbeat`,void 0,AbortSignal.timeout(Oy));}catch(f){if(f instanceof G&&(f.reason==="forbidden"||f.reason==="not_found")){i(`the platform no longer holds this match under this host (${f.reason}); heartbeats stop`),de();return}i(`heartbeat failed: ${Xe(f)}`);}Y||(re=e.clock.setTimeout(()=>{q();},Yl));}},dt=()=>{Y||re!==null||(re=e.clock.setTimeout(()=>{q();},Yl));};{let f=L;L=()=>{de(),Se?.dispose(),Se=null,f();};}let Ze=Promise.resolve().then(()=>a.init(A));s=Ze.then(()=>{},()=>{}),m("join",()=>a.join?.(r,{playerNumber:Ql,transport:"loopback"})),j.push(n.on("peerJoined",N)),j.push(n.on("peerLeft",(f,E)=>{S(f);let $=e.clock.now();for(let[ne,J]of x)$-J>=Xl&&x.delete(ne);x.set(f,$),W.delete(f),m("leave",()=>a.leave?.(f,{cause:E}));})),j.push(n.on("error",f=>{i(`\u26A0 session error: ${f.message}`);})),j.push(n.on("matchEnded",f=>{U||ni(y,f),ge("match ended",{reason:"match_ended",platform_reason:f});})),j.push(n.on("hostChanged",f=>{f!==r&&ge("host migrated",{reason:"host_migrated"});}));for(let f of n.peers)N(f);try{await Ze,dt();}catch(f){l=false,de(),d=true;for(let E of j.splice(0))E();for(let E of [...M.keys()])S(E);throw n.leave().catch(()=>{}),L(),f}return {matchId:n.matchId,localLink:R,onMatchEnded(f){y=f;},end:Oe,leave:Q,stop:f=>ge(f,{reason:"stopped"}),done:D}}function ni(t,e){try{t?.(e);}catch{}}function Xe(t){return t instanceof Error?t.message:String(t)}function ti(t,e){let n=async()=>{throw new b("misconfigured",`this seat is \`${t}\`, not the match's authority: `+(t==="dedicated"?"the platform runs the server, and its bundle ends the match with gem.match.end().":"another player hosts this match."))};return {mode:t,matchId:e,end:n,leave:n,stop:async()=>{}}}function ed(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,o=new Map,i=async s=>{r.isHost&&!Xo(r)&&r.currentRoom?.matchId===void 0&&await r.startMatch({...s.clusterTargetId===void 0||s.clusterTargetId===null?{}:{clusterTargetId:s.clusterTargetId},...s.signal===void 0?{}:{signal:s.signal}});let l={...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal}};return r.matchConnectionState==="suspended"?r.reconnectToMatch(l):r.awaitMatch(l)},a=s=>({...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal},...s.clusterTargetId===void 0?{}:{clusterTargetId:s.clusterTargetId}});return {async serve(s,l={}){let d=await i(l);if(d.protocol!==Je)return ti("dedicated",d.matchId);let m=t.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return ti("peer",d.matchId);let c=t.identity();if(c===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let p=m??await t.p2p.connect(a(l)),g=await Zl(s,{session:p,clock:t.clock,gameId:c.gameId,channel:c.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:t.apiBaseUrl(),tokens:t.tokens,room:t.room,localPlayerId:p.playerId!==""?p.playerId:c.playerId,...t.log===void 0?{}:{log:t.log},...t.fetch===void 0?{}:{fetch:t.fetch}});return o.set(d.matchId,g),g.done.then(()=>{o.get(d.matchId)===g&&o.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>g.end(),leave:()=>g.leave(),stop:()=>g.stop()}},async connect(s={}){let l=await i(s),d=s.onMatchEnded;if(l.protocol===Je){let g=o.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),$y(l.matchId,g,d);if(r.isHost)throw new Error("[gem] this player hosts the P2P match, so there is no one to connect TO yet. Call gem.match.serve(yourServer) first; connect() then resolves the loopback to your own bundle.");let y=await Qn(),w=async()=>t.p2p.connect({...a(s),certificate:y}),R=await w(),I=jy(R,w,d,M=>{r.notifyMatchDisconnected(M).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(R.matchId,{redial:I.redial,abandon:I.abandon}),I.onClosed(()=>{e.get(R.matchId)?.abandon===I.abandon&&e.delete(R.matchId);})),I}let m=async(g=null)=>await t.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal},...s.clusterTargetId===void 0||s.clusterTargetId===null?{}:{clusterTargetId:s.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:s.transports??[]}),c=await m(),p=Fy(c,m,r,n);return n&&(e.set(c.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(c.matchId)?.abandon===p.abandon&&e.delete(c.matchId);})),p},async redialMatch(s,l){let d=e.get(s);return d===void 0?"closed":d.redial(l)},abandonMatch(s,l){e.get(s)?.abandon(l);}}}var nd="link_closed",Ly="host_unreachable",Gy=new Set(["failed","closed"]);function Dy(t){return Gy.has(t)?nd:Ly}function $y(t,e,n){let r=e.localLink;e.onMatchEnded(n);let o="connected";r.onClose(()=>{o="closed";});let i;return {matchId:t,protocol:"loopback",get state(){return o},send:(a,s)=>r.send(a,s),onMessage:a=>r.onMessage(a),onClose:a=>{i=a,r.onClose(s=>{o="closed",i?.(s);});},close:()=>r.close()}}function Fy(t,e,n,r){let o=t.matchId,i=t,a="connected",s,l,d=[],m=false,c=false,p=y=>{if(a!=="closed"){a="closed";for(let w of d.splice(0))w();l?.(y);}},g=y=>{y.link.onMessage((w,R)=>s?.(w,R)),y.link.onClose(w=>{if(y!==i||a==="closed")return;if(m||!r){p(w);return}let R=n.matchSession;if(R.phase==="suspended"&&R.matchId===o){a="suspended";return}p(w);});};return g(t),{matchId:o,protocol:"dedicated",get transport(){return i.transport},get state(){return a},send(y,w){a==="connected"&&i.link.send(y,w);},onMessage(y){s=y;},onClose(y){l=y;},close(){if(a!=="closed"){if(m=true,a==="suspended"){p("closed");return}i.close(),p("closed");}},async redial(y){if(a==="closed"||m)return "closed";if(c)return "connected";c=true;let w;try{w=await e(y===void 0?{}:{deadlineAt:y});}finally{c=false;}return m||a==="closed"?(w.close(),"closed"):(i=w,g(w),a="connected",n.notifyMatchConnected(o),"connected")},abandon(y){a!=="closed"&&(a==="connected"&&i.close(),p(y));},onClosed(y){a==="closed"?y():d.push(y);}}}function jy(t,e,n,r,o,i=false){let a=t.matchId,s=t,l,d,m=[],c=[],p=[],g=false,y=false,w=false,R=false,I="connected",M=k=>{if(g)return;g=true,I="closed";for(let L of m.splice(0))L();for(let L of c.splice(0))L();for(let L of p.splice(0))L();let A=d;A&&queueMicrotask(()=>A(k));},_=k=>{for(let A of m.splice(0))A();for(let A of Me){let L=k.channels[A];try{L.binaryType="arraybuffer";}catch{}let D=wn(A),j=U=>{let ee=pr(U?.data);ee!==null&&l?.(ee.data,D);};L.addEventListener("message",j),m.push(()=>L.removeEventListener("message",j));}},S=()=>s.peer(s.hostPlayerId),P=k=>{if(!(g||s.isHost)&&I!=="suspended"){if(r?.(k),i){I="suspended";return}M(k);}},x=k=>{for(let A of Me){let L=k.channels[A];if(typeof L.addEventListener!="function")continue;let D=()=>{S()===k&&P(nd);};L.addEventListener("close",D),m.push(()=>L.removeEventListener?.("close",D));}},V=k=>{_(k),x(k),!g&&(I="connected",o?.());},N=k=>{for(let A of c.splice(0))A();c.push(k.on("migrating",()=>{R=true;})),c.push(k.on("hostChanged",A=>{if(R=false,A===k.playerId){M("host_migrated_here");return}let L=S();L!==null&&V(L);})),c.push(k.on("peerJoined",A=>{A.playerId===k.hostPlayerId&&V(A);})),c.push(k.on("matchEnded",A=>{g||ni(n,A),M(A);})),c.push(k.on("peerLeft",(A,L)=>{A===k.hostPlayerId&&P(Dy(L));}));};N(s);let W=S();return W!==null&&V(W),{matchId:a,protocol:"p2p",get state(){return I},send(k,A){I==="connected"&&S()?.send(it(k),Ye(A));},onMessage(k){l=k;},onClose(k){d=k;},close(){y=true,M("closed"),s.leave().catch(()=>{});},async redial(){if(I==="closed")return "closed";if(I==="connected"||w)return "connected";if(R)throw new O("connection_failed","a host migration is in flight, and it is the way back \u2014 this attempt waits it out rather than tearing down the session the platform is moving");w=true;let k;try{for(let L of m.splice(0))L();for(let L of c.splice(0))L();s.close(),k=await e();}finally{w=false;}if(g)return y?k.leave().catch(()=>{}):k.close(),"closed";s=k,N(s);let A=S();if(A===null)throw s.close(),new O("connection_failed","this peer rejoined the match but the host never answered with a link");return V(A),"connected"},abandon(k){M(k);},onClosed(k){g?k():p.push(k);}}}function ri(t){let e=0,n=new Map;return {resolve(){if(!t.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(o=>{let i={},a=l=>{n.delete(r)&&(t.clock.clearTimeout(i.timer),o(l));};n.set(r,a),i.timer=t.clock.setTimeout(()=>a(void 0),t.timeoutMs??2e3);let s=false;try{s=t.bridge.requestParty(r);}catch{}s||a(void 0);})},settle(r,o){n.get(r)?.(o);}}}var qy=12e4;function Qe(t,e){return {outcome:t,reason:e}}function td(t){let e=false,n=new Map;return {api:{request(r){if(!t.bridge.parentSupports("purchases"))return Promise.resolve(Qe("unavailable","error"));if(e)return Promise.resolve(Qe("declined","busy"));let o=`purchase-${Ae()}`;return new Promise(i=>{let a={},s=d=>{n.delete(o)&&(e=false,t.clock.clearTimeout(a.timer),i(d));};e=true,n.set(o,s),a.timer=t.clock.setTimeout(()=>s(Qe("unavailable","error")),t.timeoutMs??qy);let l=false;try{l=t.bridge.requestPurchase(o,r.kind,r.targetId,r.currencySlug,r.quantity,r.catalogId);}catch{}l||s(Qe("unavailable","error"));})}},settle(r){let o=r.outcome==="ok"||r.outcome==="declined"?r.outcome:"unavailable",i=n.get(r.requestId);if(i===void 0){t.onDropped?.(`gem.purchaseResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}if(o!=="ok"){i(Qe(o,$s(r.reason)));return}let a=r.purchaseId;if(a===void 0){t.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),i(Qe("unavailable","error"));return}(async()=>{let s;try{s=await t.confirm(a);}catch{s="unknown";}if(s==="granted"){i({outcome:"ok",purchaseId:a});return}s==="absent"&&t.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for purchase "+JSON.stringify(a)),i(Qe("unavailable","error"));})();}}}async function rd(t,e){try{return (await rs(t,e)).granted?"granted":"absent"}catch(n){return n instanceof G&&n.reason==="not_found"?"absent":"unknown"}}var Ny=6e5;function od(t){let e=null,n=new Map;return {api:{requestSignIn(){if(!t.bridge.parentSupports("signIn"))return Promise.resolve({outcome:"unavailable"});if(e!==null)return e;let r=`signin-${Ae()}`;return e=new Promise(o=>{let i={},a=l=>{n.delete(r)&&(e=null,t.clock.clearTimeout(i.timer),o(l));};n.set(r,a),i.timer=t.clock.setTimeout(()=>{a({outcome:"unavailable"});},t.timeoutMs??Ny);let s=false;try{s=t.bridge.requestSignIn(r);}catch{}s||a({outcome:"unavailable"});}),e}},settle(r){let o=r.outcome==="signed_in"||r.outcome==="declined"?r.outcome:"unavailable",i=n.get(r.requestId);if(i===void 0){t.onDropped?.(`gem.signInResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}i({outcome:o});}}}var Uy=new Set(["play","channel","purchase","devtools","devLocale","playOverlay","social","embedder","_s","fbclid","ttclid","gclid","msclkid"]),By=["utm_"];function id(t){return Uy.has(t)||By.some(e=>t.startsWith(e))}var sd=16,ad=512,Hy=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Vy=/[\p{Cc}\p{Cf}]/u,Wy=/\p{Cs}/u,Te="[gem] gem.share.request:";function ld(t){let{frame:e,log:n}=t,r=false,o=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,i=a=>{n!==null&&(n===void 0?console.warn(a):n(a));};return {get available(){return o()!==null},request(a){let s=o();if(s===null)throw new Error(`${Te} the arcade does not handle share here \u2014 check gem.share.available first`);if(a!==void 0&&(typeof a!="object"||a===null))throw new TypeError(`${Te} pass { params }, or nothing`);let l=a?.params===void 0?{}:a.params;if(!Ky(l))throw new TypeError(`${Te} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>sd)throw new TypeError(`${Te} at most ${sd} params; got ${d.length}`);let m=[];for(let[c,p]of d){let g=JSON.stringify(c);if(!Hy.test(c))throw new TypeError(`${Te} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(id(c))throw new TypeError(`${Te} param ${g} is reserved: the arcade reads it itself and never forwards it`);if(typeof p!="string")throw new TypeError(`${Te} param ${g}: values must be strings`);if(p.length>ad)throw new TypeError(`${Te} param ${g}: a value is at most ${ad} characters`);if(Vy.test(p))throw new TypeError(`${Te} param ${g}: control and format characters are not allowed`);if(Wy.test(p))throw new TypeError(`${Te} param ${g}: a value must be well-formed text`);m.push({key:c,value:p});}!s.requestShare(m)&&!r&&(r=true,i("[gem] gem.share.request was not sent: more than 6 share requests in a minute. Call it from your Share button's click, not a loop."));}}}function Ky(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var Jy=18e4,dd=32,zy=/^[a-z0-9_-]+$/;function Yy(t){return t==="interstitial"||t==="rewarded"}function cd(t){let e=false,n=new Map;return {api:{requestAd(r){if(!t.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});if(typeof r.placement!="string"||r.placement===""||r.placement.length>dd||!zy.test(r.placement)||!Yy(r.format))return t.onDropped?.(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${JSON.stringify(r.placement)}, format ${JSON.stringify(r.format)}. A placement is 1..${String(dd)} characters of a-z, 0-9, '-' and '_' \u2014 the grammar the platform's own ad endpoint accepts \u2014 and a format is 'interstitial' or 'rewarded'. Answering no_ad.`),Promise.resolve({outcome:"no_ad"});let o=`ad-${Ae()}`,i=r.format,a=r.placement;return new Promise(s=>{let l={},d=c=>{n.delete(o)&&(e=false,t.clock.clearTimeout(l.timer),s(c));};e=true,n.set(o,d),l.timer=t.clock.setTimeout(()=>{d({outcome:"unavailable"});},t.timeoutMs??Jy);let m=false;try{m=t.bridge.requestAd(o,a,i);}catch{}m||d({outcome:"no_ad"});})}},settle(r){let o=r.outcome==="shown"||r.outcome==="no_ad"?r.outcome:"unavailable",i=n.get(r.requestId);if(i===void 0){t.onDropped?.(`gem.adResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}i({outcome:o});}}}var oi=16384;function ud(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e;try{e=JSON.stringify(t);}catch{return null}return typeof e!="string"?null:Xy(e)}function Xy(t){let e=0;for(let n=0;n<t.length;n+=1){let r=t.charCodeAt(n);if(r<128)e+=1;else if(r<2048)e+=2;else if(r>=55296&&r<=56319){let o=t.charCodeAt(n+1);o>=56320&&o<=57343?(e+=4,n+=1):e+=3;}else e+=3;}return e}var Qy=1e4,Zy=5e3;function md(t){let e=null,n=false,r=[],o=new Map,i=()=>{for(let a of r.splice(0))a();};return {api:{get current(){return e},wait(a=Zy){return n?Promise.resolve(e):new Promise(s=>{let l=()=>{let c=r.indexOf(d);c>=0&&r.splice(c,1);},d=()=>{t.clock.clearTimeout(m),l(),s(e);},m=t.clock.setTimeout(()=>{l(),s(e);},a);r.push(d);})},put(a){if(!t.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let s=ud(a);if(s===null)return t.onDropped?.("gem.deviceSettings.put refused locally: settings must be a plain JSON object (not a primitive, an array, null, or something JSON.stringify cannot take)"),Promise.resolve("unavailable");if(s>16384)return Promise.resolve("too_large");let l=JSON.parse(JSON.stringify(a)),d=`device-settings-${Ae()}`;return new Promise(m=>{let c={},p=y=>{o.delete(d)&&(t.clock.clearTimeout(c.timer),y==="stored"&&(e=l,n=true,i()),m(y));};o.set(d,p),c.timer=t.clock.setTimeout(()=>p("unavailable"),t.timeoutMs??Qy);let g=false;try{g=t.bridge.putDeviceSettings(d,l);}catch{}g||p("unavailable");})}},receive(a){let s=a.settings;e=typeof s=="object"&&s!==null&&!Array.isArray(s)?s:null,n=true,i();},settle(a){let s=a.outcome==="stored"||a.outcome==="too_large"?a.outcome:"unavailable",l=o.get(a.requestId);if(l===void 0){t.onDropped?.(`gem.deviceSettings.result (${s}) for an unknown requestId: `+JSON.stringify(a.requestId));return}l(s);}}}var st=class extends Error{constructor(){super("createGem: this game is not framed (window.parent === window), so nothing can hand it a player, saves, config or rooms. Play it in the Gem Arcade or the Gem Editor, or through the Gem dev host on this machine: `npm run dev` (`gemctl serve start . --dev`) while editing, `gemctl serve start .` for a build, signed in to gemctl. Do not open the dev server's own address."),this.name="GemUnframedError";}};function pd(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function ii(t,e){if(t!==true)return {visible:false};let n=[],r=false;for(let o of Array.isArray(e)?e:[])o==="score"?r=true:typeof o=="string"&&o.length>0&&o.length<=64&&!n.includes(o)&&n.push(o);return !r&&n.length===0?{visible:true}:{visible:true,currencies:n.slice(0,8),score:r}}function gd(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function ef(t){let e=t.untrusted,n=ye(e.displayName),r=e.displayTag||e.displayHandle,o=r?ye(r):void 0,i=t.discriminator||t.displayTag,a=i&&/^[0-9]{1,8}$/.test(i)?i:void 0,s=t.avatarIconUrl||t.avatarUrl,l={displayName:n,displayHandle:o??n,badges:(t.badges??[]).map(p=>({itemId:p.itemId,iconUrl:p.iconUrl}))};t.playerId&&(l.playerId=t.playerId),a&&(l.discriminator=a),o&&(l.displayTag=o),s&&(l.avatarIconUrl=l.avatarUrl=s);let d=t.boost,m=(d?.multipliers??[]).map(p=>({currencyId:p.currencyId,currencySlug:p.currencySlug,multiplier:p.multiplierBp/1e4})),c=m.some(p=>p.multiplier>1);return l.boost=c&&d?.expiresInDays?{active:c,multipliers:m,expiresInDays:d.expiresInDays}:{active:c,multipliers:m},l}var nf=1e4,at=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??le,this.inbound=new xn(this.clock),this.outbound=new xn(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=>Pr(s,e.origin))||Os(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=_t["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let o=e.data;if(!Pr(o.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${o.embedder}' but arrived from '${e.origin}'`),false;let i=e.ports?.[0];if(!i)return this.refuse(e,"handshake transferred no MessagePort"),false;let a=Ls(bt,o.versions);return a===null?(i.onmessage=null,i.postMessage({gem:K,type:"gem.error",code:"version_mismatch",message:`frame supports v${bt.min}..v${bt.max}`}),i.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=i,this.version=a,i.onmessage=s=>this.receive(s.data,s.ports??[]),i.start?.(),this.peerCapabilities=o.capabilities??[],this.unbidden=o.unbidden===true,i.postMessage({gem:K,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:K,type:"gem.ready"});}settled(e=nf){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(n=>{let r=i=>{this.clock.clearTimeout(o),n(i);},o=this.clock.setTimeout(()=>{let i=this.settleWaiters.indexOf(r);i>=0&&this.settleWaiters.splice(i,1),n(this.state);},e);this.settleWaiters.push(r);})}progress(e,n){this.send({gem:K,type:"gem.progress",loaded:e,total:n});}requestToken(e,n){this.send({gem:K,type:"gem.requestToken",requestId:e,reason:n});}requestLocalServer(e,n){return this.parentSupports("localHost")?(this.send({gem:K,type:"gem.requestLocalServer",requestId:e,gameRoomId:n}),true):false}exit(e){this.send(e===void 0?{gem:K,type:"gem.exit"}:{gem:K,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:K,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:K,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:K,type:"gem.audioState",muted:e}),true)}reportEngaged(){return this.engagedSent||this.state!=="connected"||!this.parentSupports("engagement")||!this.send({gem:K,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let n={gem:K,type:"gem.rewardCue",currencySlug:String(e.currencySlug).slice(0,32)};return e.expected!==void 0&&Number.isFinite(e.expected)&&e.expected>=1&&(n.expected=Math.min(1e9,Math.round(e.expected))),e.origin&&(n.origin={x:pd(e.origin.x),y:pd(e.origin.y)}),this.send(n),true}setWalletVisible(e,n){return this.state!=="connected"||!this.parentSupports("walletDisplay")?false:this.send({gem:K,type:"gem.walletDisplay",...ii(e,n?.only)})}requestShare(e){return this.state!=="connected"||!this.parentSupports("share")?false:this.send({gem:K,type:"gem.requestShare",params:e.map(({key:n,value:r})=>({key:n,value:r}))})}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:K,type:"gem.frameStats",fps:gd(e.fps,1e3),frameTimeP95Ms:gd(e.frameTimeP95Ms,1e5)}),true)}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:K,type:"gem.gameContext",context:e}),true)}signal(e,n,r){this.send({gem:K,type:"gem.signal",signal:e,matchId:n,data:r});}dedicatedOffer(e,n,r){this.send({gem:K,type:"gem.dedicatedOffer",matchId:e,sdp:n,intent:r});}requestParty(e){return this.send({gem:K,type:"gem.partyRequest",requestId:e})}requestPurchase(e,n,r,o,i,a){return this.send({gem:K,type:"gem.requestPurchase",requestId:e,purchaseKind:n,targetId:r,currencySlug:o,...i===void 0?{}:{quantity:i},...a===void 0?{}:{catalogId:a}})}putDeviceSettings(e,n){return this.send({gem:K,type:"gem.deviceSettings.put",requestId:e,settings:n})}requestAd(e,n,r){return this.send({gem:K,type:"gem.requestAd",requestId:e,placement:n,format:r})}requestSignIn(e){return this.send({gem:K,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,n,r,o){return this.send({gem:K,type:"gem.requestFriendChallenge",requestId:e,playerId:n,template:r,...o===void 0?{}:{params:o}})}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 n of this.settleWaiters.splice(0))n(e);this.options.onStateChange?.(e);}}refuseMalformed(e,n){if(!this.inbound.allow(vt)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(vt)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(vt)&&this.options.onRefused?.(n);}fail(e,n){this.options.onError?.(e,n),this.state==="connected"&&this.port&&this.send({gem:K,type:"gem.error",code:e,...n===void 0?{}:{message:n}});}send(e){if(this.state!=="connected"||!this.port)return this.options.onDropped?.("internal",`dropped ${String(e.type)} before connect`),false;let n=e.type;if(!this.outbound.allow(n))return this.options.onError?.("rate_limited",`frame exceeded its own limit for ${n}`),false;let r=_t[n]?.(e);return r?(this.options.onError?.("internal",`refusing to send malformed ${n}: ${r}`),false):(this.port.postMessage(this.version===null?e:{...e,v:this.version}),true)}receive(e,n=[]){let r=false;try{r=this.dispatchInbound(e,n);}finally{r||yd(n);}}dispatchInbound(e,n){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 o=_t[r];if(!o)return this.dropUnknownType(r),false;if(!this.inbound.allow(r))return this.fail("rate_limited",`parent exceeded the limit for ${r}`),false;let i=Cs(r);if(i!==void 0&&!this.options.capabilities?.includes(i))return this.fail("unsupported_capability",`${r} requires the '${i}' capability, which this frame did not advertise`),false;let a=o(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.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=n[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 yd(n.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?.(ef(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,n){this.send({gem:K,type:"gem.screenshot.denied",reason:e,retryable:n});}};function yd(t){for(let e of t)try{e?.close?.();}catch{}}var fd="https://api.gemarcade.com";function si(t){let e;try{e=new URL(t);}catch{return "it is not a valid URL"}return e.protocol!=="https:"&&e.protocol!=="http:"?`its scheme is ${e.protocol.replace(":","")}, and only http and https can be used`:e.username!==""||e.password!==""?"it carries credentials in the URL, which `fetch` will not send":e.href.includes("#")?"it carries a fragment. The transport joins the base and the path by concatenation, so the fragment would swallow the path and every request would go to the API root":e.href.includes("?")?"it carries a query string. The transport joins the base and the path by concatenation, so the query would swallow the path and every request would go to the API root":null}var tf=new Set(["localhost","127.0.0.1","[::1]"]);function hd(t){let e=si(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!tf.has(n.hostname)?"it is a plaintext http address that is not loopback. An embedder may name an https root, or http on localhost for a rig running the whole stack on one machine \u2014 the play token travels on every request to it":null}var rf=Object.freeze(["https://gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),of=fd,bd=8e3,ai=15e3,sf=9e4,af=1/0,lf=8e3,df=5e3,cf=5e3;async function uf(t,e,n,r){if(t.isInRoom)try{await t.leave();}catch{}r?.endSession("session_ended"),e!==null&&e.currentState==="connected"&&e.exit(n);}function lt(t){let e=null,n=false,r=[];return {get current(){return e},set(o){e=o;for(let i of r.splice(0))i(o);},release(){n=true;for(let o of r.splice(0))o(e);},wait(o){return e!==null||n?Promise.resolve(e):new Promise(i=>{let a=()=>{let d=r.indexOf(s);d>=0&&r.splice(d,1);},s=d=>{t.clearTimeout(l),a(),i(d);},l=t.setTimeout(()=>{a(),i(e);},o);r.push(s);})}}}function US(t={}){let e=t.clock??le,n=t.log===void 0?u=>console.info(u):t.log,r=t.baseUrl??void 0;if(r!=null){let u=si(r);if(u!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${u}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let o=qo();o.mark("sdk created");let i=()=>Wt(J.gameVersion,t.clientVersion?.gameVersion),a=new Fn({client:()=>tn,clock:e,gameId:()=>J.identity?.gameId??null,playerId:()=>J.identity?.playerId??null,environment:()=>{let u=i();return {sdk_version:Si(),...u===null?{}:{game_version:u}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),s=sl(()=>{o.mark("engaged"),a.release(),q.reportEngaged();},typeof window>"u"?{}:window),l=u=>{if(u===false)return null;let T=u?.attempts??af,F=u?.budgetMs??sf;return !(T>0)||!(F>0)?null:{attempts:T,budgetMs:F,maxDelayMs:u?.maxDelayMs??lf}},d=u=>{u.on("created",()=>{o.mark("room created");}),u.on("joined",()=>{o.mark("room joined");}),u.on("matchAllocationStarted",()=>{o.mark("allocation started");}),u.on("matchReady",()=>{o.mark("match ready");}),u.on("matchFailed",()=>{o.mark("match failed");});};if(typeof window>"u")throw new Error("createGem: there is no `window` in this environment, so the SDK has no document to listen on and no embedder to hand it a port. A game runs in a browser; if this is a server-side render or a node process, do not construct the SDK there.");if(window.parent===window)throw new st;let m=t.allowedEmbedders;if(m!=null&&!Array.isArray(m))throw new Error("createGem: `allowedEmbedders` must be an array of origins, e.g. `['https://my-own-site.example']`. The Gem Arcade is allowed without any entry.");let c=Array.from(m??[]),p=c.filter(u=>typeof u!="string"||!Ar(u));if(p.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${p.length===1?"an entry":"entries"} that ${p.length===1?"is":"are"} not an origin: ${p.map(u=>typeof u=="string"?JSON.stringify(u):String(u)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let g=Object.freeze([...new Set([...rf,...c])]),y=lt(e),w=lt(e),R=lt(e),I=la(n),M=lt(e),_=t.manageAudio===false?null:pl();t.selectableText!==true&&gl();let S=null,P=()=>{S!==null&&(w.current!==null&&w.current.muted===S||q.reportMuted(S));},x=null,V=null,N=()=>{if(x===null)return false;let u=JSON.stringify(ii(x.visible,x.only));return u===V?q.parentSupports("walletDisplay"):q.setWalletVisible(x.visible,x)?(V=u,true):false},W=yl({report:u=>q.reportFrameStats(u)}),k=false,A=Sl(()=>bi,()=>k),L=u=>{let T=k&&!u,F=k!==u;if(k=u,T&&A.close(),!!F)try{t.onDevToolsPermissionChange?.(u);}catch(te){n?.(`[gem] onDevToolsPermissionChange threw: ${te instanceof Error?te.message:String(te)}`),queueMicrotask(()=>{throw te});}},D=r??of,j=r!==void 0,U,ee=u=>(n?.(`[gem] token refused: ${u}`),t.onError?.("internal",u),false),ge=(u,T)=>{if(u===void 0)return T!==void 0?ee("the embedder named a backend by tag, which this build no longer resolves \u2014 it needs `apiBaseUrl` on `gem.token`. The token was refused rather than sent to the default: silently resolving production is how a development session writes to the live backend."):true;let F=hd(u);return F!==null?ee(`the embedder named an API root that cannot be used: ${F}. Its value is withheld here rather than written to logs.`):U!==void 0&&U!==u?ee("the embedder named a different API root than it named on this session\u2019s first token. The address is fixed by the first grant, so a later message cannot repoint a running game; both values are withheld here."):(U=u,j||(D=u),true)},Q=window.location?.origin,Oe=null,Se=-1/0,Ce=2e3,Ie=new Set,re=u=>Oe!==false?Promise.resolve(true):new Promise(T=>{let F=e.setTimeout(()=>{Ie.delete(te),T(false);},u),te=()=>{e.clearTimeout(F),Ie.delete(te),T(true);};Ie.add(te);}),Y=()=>{},de=null,q=new at({allowedEmbedders:g,...typeof Q=="string"&&Q!==""?{selfOrigin:Q}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","clusterTarget","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","earnAllowance","share","frameStats","walletDisplay","engagement","reservedAreas","viewport","purchases","deviceSettings","ads","signIn","friendChallenges",...t.onFeedbackContext!==void 0?["feedbackContext"]:[]],onRefused:u=>{de=u,t.onRefused?.(u);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:u=>{J.onBridgeState(u),u!=="connected"&&W.setRequested(false),V=null,u==="refused"&&(console.error("[gem] this game refused the page that framed it"+(de===null?"":` (${de})`)+", so it has no player, saves, config or rooms. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders."),Y()),u==="connected"&&(o.mark("bridge connected"),gr(),P(),N(),q.unbiddenLaunch&&!s.engaged&&a.hold(),a.startSession(),s.engaged&&q.reportEngaged()),t.onStateChange?.(u);},onPlayer:u=>{y.set(u),t.onPlayer?.(u);},onPrefs:u=>{let T={reducedMotion:u.reducedMotion,muted:u.muted,locale:u.locale,showFrameStats:u.showFrameStats===true};w.set(T),_?.setMuted(T.muted),W.setRequested(T.showFrameStats&&q.parentSupports("frameStats")),t.onPrefs?.(T);},onCohorts:u=>{let T=Object.freeze(u.cohorts.map(F=>Object.freeze({experimentId:F.experimentId,variantKey:F.variantKey})));R.set(T),t.onCohorts?.(T);},onEarnAllowanceChanged:()=>I.emit(),onViewport:u=>{let T=Object.freeze({insets:Object.freeze({top:u.insets.top,right:u.insets.right,bottom:u.insets.bottom,left:u.insets.left}),reserved:Object.freeze((u.reserved??[]).map(te=>Object.freeze({x:te.x,y:te.y,width:te.width,height:te.height})))});M.set(T);let F=hl();bl(F,T.insets),_l(F,T.reserved,vl()),t.onViewport?.(T);},onPause:u=>{a.setPaused(u.paused),W.setPaused(u.paused),t.onPause?.(u.paused);},onWillTerminate:u=>{a.endSession(u.reason),t.onWillTerminate?.({reason:u.reason,graceMs:u.graceMs});},onToken:u=>{let T=u.garden;if(L(u.allowDevTools===true),!ge(u.apiBaseUrl,T))return;let F=u;J.onToken(F);let te=J.identity;te&&(Ze.set(te),f||(f=true,ue.reconcileSeats().catch(()=>{}))),ne.push({token:F.token,expiresAt:F.expiresAt});},onTokenDenied:u=>{L(false),J.onDenied(u);},onScreenshot:(u,T,F)=>{cl(u,T,F,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{ul(q,t.onFeedbackContext);},onDevtools:u=>{u==="close"?A.close():u==="open"?A.openFrom("platform").catch(()=>{}):A.isOpen?A.close():A.openFrom("platform").catch(()=>{});},onRoomEvent:u=>ue.handleRoomEvent({event:u.event,roomId:u.roomId,...u.matchId===void 0?{}:{matchId:u.matchId},...u.version===void 0?{}:{version:u.version},...u.reason===void 0?{}:{reason:u.reason},...u.platform===void 0?{}:{platform:u.platform}}),onSeatedEvent:u=>ue.handleSeated(u.roomId),onAutoStartFailedEvent:u=>ue.handleAutoStartFailed(u.roomId,u.code),onSocketState:u=>{let T=Oe;if(Oe=u.connected,u.connected)for(let te of [...Ie])te();if(!u.connected||T===true)return;let F=e.now();F-Se<Ce||(Se=F,ue.reconcile().catch(()=>{}));},onSignalEvent:u=>{let T=typeof u.data=="object"&&u.data!==null&&!Array.isArray(u.data)?u.data:{};rn.handleSignalEvent(u.matchId,u.event,T),u.event==="matchEnded"&&ue.reconcile({matchId:u.matchId,...typeof T.reason=="string"?{reason:T.reason}:{}}).catch(()=>{});},onDedicatedEvent:u=>{u.event==="matchEnded"&&(Rn.handleMatchEnded(u.matchId,u.reason),ue.reconcile({matchId:u.matchId,...u.reason===void 0?{}:{reason:u.reason}}).catch(()=>{})),dt.handleEvent(u);},onClusterTarget:u=>ut.accept(u.clusterTargetId,u.clusterTargetIds),onLocalServer:u=>mt.accept(u),onLocalServerDenied:u=>mt.refuse(u),onPartyResult:u=>en.settle(u.requestId,u.partyId),onPurchaseResult:u=>ci.settle(u),onDeviceSettings:u=>{ct.receive(u),t.onDeviceSettings?.(ct.api.current);},onDeviceSettingsResult:u=>ct.settle(u),onAdResult:u=>ui.settle(u),onSignInResult:u=>mi.settle(u),onFriendChallengeResult:u=>pi.settle(u)}),dt=new ot({bridge:q}),Ze=lt(e);Y=()=>{Ze.release(),y.release(),R.release();},q.currentState==="refused"&&Y();let f=false,E=new Set,$,ne={current:()=>$,subscribe:u=>(E.add(u),$!==void 0&&u($),()=>E.delete(u)),push:u=>{$=u;for(let T of [...E])try{T(u);}catch(F){n?.(`[gem] a server-token listener threw: ${F instanceof Error?F.message:String(F)}`);}}},J=kl({bridge:q,clock:e,onStateChange:(u,T)=>{if(u==="ready"){if(o.mark("token ready")){let F=o.marks.find(te=>te.name==="token ready")?.at;a.trackPlatform("gem_boot_ready",F===void 0?{}:{boot_ms:Math.max(0,Math.round(F))});}}else u==="lost"&&(o.mark("token lost"),a.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(u,T);}}),Sn=()=>{let u=J.identity;return !u||J.source.currentState==="lost"?null:`${u.playerId}\0${u.gameId}\0${u.channel}`},gr=()=>{o.mark("token requested"),J.source.get().catch(()=>{});},en=ri({bridge:q,clock:e}),di={},ci=td({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u),confirm:async u=>di.confirm?.(u)??"unknown"}),ct=md({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u)}),ui=cd({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u)}),mi=od({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u)}),pi=aa({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u)}),ut=ha({bridge:q,clock:e}),mt=wl({bridge:q,clock:e}),yr=u=>{let T=q.handleWindowMessage({data:u.data,origin:u.origin,source:u.source,ports:u.ports});return T&&window.removeEventListener("message",yr),T};window.addEventListener("message",yr);let nn=wi(window,yr),Sd=nn?.capture,fr=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];fr?.domInteractive!==void 0&&fr.domInteractive>0&&o.mark("document parsed",fr.domInteractive),Sd?.late&&n?.("[gem] the early-handshake capture installed after this document finished loading, so a handshake posted at iframe load may already have been missed. Load the capture script ahead of everything else in the document.");let hr=t.handshakeWarningMs;hr!==null&&n&&e.setTimeout(()=>{let u=nn===null?"no capture script ran":`capture: ${nn.delivered} offer(s) delivered, ${nn.stale} stale, ${nn.capture.dropped} evicted${nn.capture.late?", installed late":""}`;if(q.currentState==="connected"){n(`[gem] handshake connected. boot: ${o.timeline()} \xB7 ${u}`);return}n(`[gem] no completed handshake after ${hr??bd}ms (bridge state: ${q.currentState}). Either the embedder does not run the gem-web-sdk parent half, its origin is not in this build\u2019s allowedEmbedders, or its handshake fired before this frame\u2019s listener registered. boot: ${o.timeline()} \xB7 `+u);},hr??bd);let Rd=cr({get baseUrl(){return D},tokenSource:J.source,get defaultQuery(){let u=J.identity;return u?{game_id:u.gameId,channel:u.channel}:{}}}),tn=new Le({transport:Rd,clock:e}),he={client:tn,gameId:()=>J.identity?.gameId??""};di.confirm=u=>rd(he,u);let kd=()=>J.identity?.channel??"release",gi=new Ft(he,kd),yi=async u=>(await gi.load())?.currency(u)?.id??void 0,fi=Mt(he,$r,{identity:Sn,resolveCurrencyId:yi}),br=async u=>{let T=await Ze.wait(u);if(T)return T;throw q.currentState==="refused"?new ie("unavailable","the page that framed this game is not one it accepts, so no play token will ever arrive. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders (see onRefused for the reason)."):new ie("timeout","no play token arrived over the bridge. Every route a game reaches is scoped by the token, so nothing can proceed without one \u2014 the bridge may not be connected, or the parent may have refused to mint (see onAuthStateChange).")},vr=l(t.autoReconnect),ue=xo({client:tn,clock:e,gameId:()=>J.identity?.gameId??null,playerId:()=>J.identity?.playerId??null,awaitGameId:async()=>(await br(ai)).gameId,resolveParty:en.resolve,resolveClusterTargets:ut.resolveList,refreshClusterTargets:ut.refresh,ensureLocalServer:mt.ensure,localHostAvailable:mt.available,...t.clientVersion===void 0?{}:{clientVersion:t.clientVersion},platformGameVersion:()=>J.gameVersion,...t.pollRooms===void 0?{}:{poll:t.pollRooms},...t.recoverStaleMembership===void 0?{}:{recoverStaleMembership:t.recoverStaleMembership},...t.retryAutoStart===void 0?{}:{retryAutoStart:t.retryAutoStart},...t.watchSeats===void 0?{}:{watchSeats:t.watchSeats},...t.seatPollIntervalMs===void 0?{}:{seatPollIntervalMs:t.seatPollIntervalMs},...vr===null?{}:{autoReconnect:{...vr,redial:(u,T)=>_r.redialMatch(u,T),abandon:(u,T)=>_r.abandonMatch(u,T)}}});d(ue),ol({analytics:a,rooms:ue});let rn=rl({client:tn,clock:e,rooms:ue,bridge:q,gameId:()=>J.identity?.gameId??"",baseUrl:()=>D,resolveClusterTarget:ut.resolve,boot:o,...t.log===void 0?{}:{log:t.log}}),hi=jo(o,n),Rn=Nl({client:tn,clock:e,rooms:ue,signaling:()=>dt.channel(),signalingReady:re,log:n??(()=>{})}),_r=ed({rooms:ue,p2p:{connect:u=>hi(rn.connect(u)),session:u=>rn.session(u)},dedicated:{connect:(u=>ar(o,"welcome",Rn.connect(u),n))},clock:e,identity:()=>J.identity,apiBaseUrl:()=>D,tokens:ne,room:()=>ue.currentRoom,autoReconnect:vr!==null,...t.log===void 0?{}:{log:t.log}}),xd=async()=>(await br(ai)).playerId,bi={client:tn,boot:o,get identity(){return J.identity},awaitIdentity:(u=ai)=>br(u),awaitBridge:u=>q.settled(u),get player(){return y.current},awaitPlayer:(u=df)=>y.wait(u),me:fi,characters:new Lt(he,void 0,Sn,yi),transfers:new Dt(he,$r,fi.inventory),gameConfig:gi,purchases:ci.api,deviceSettings:ct.api,ads:ui.api,account:mi.api,share:ld({frame:q,log:t.log}),analytics:a,leaderboards:new In(he),challenges:new En(he),showcase:new Mn(he,xd),friends:new On(he,{challenge:pi.challenge}),platform:new Gn(he,I,n),profiles:new Dn(he),functions:new De((u,T)=>cs(he,u,T)),get prefs(){return w.current},get cohorts(){return R.current},get viewport(){return M.current},awaitCohorts:(u=cf)=>R.wait(u),reportMuted:u=>{S=!!u,P();},cueReward:u=>q.cueReward(u),setWalletVisible:(u,T)=>{let F=Array.isArray(T?.only)?[...T.only]:void 0;return x=F===void 0?{visible:u===true}:{visible:u===true,only:F},N()},exit:u=>uf(ue,q,u,a),frame:q,devtools:A,rooms:ue,dedicatedServer:{listClusterTargets:u=>Rn.listClusterTargets(u),connect:(u=>ar(o,"welcome",Rn.connect(u),n)),handleMatchEnded:(u,T)=>Rn.handleMatchEnded(u,T)},p2p:{handleSignalEvent:(u,T,F)=>rn.handleSignalEvent(u,T,F),session:u=>rn.session(u),connect:u=>hi(rn.connect(u))},match:_r};return bi}var vd="the match has not started yet: the runtime hands over the host at `init`, and this was read before that. Read it from `init` or later \u2014 a bundle that needs a value at module scope is reading it one call too early.";function li(t,e={}){let n=e.clock??le,r=()=>{let s=t();if(s===null)throw new Error(vd);return s},o=null,i=()=>{if(o===null)throw new Error(vd);return o};return {server:{get identity(){return i().identity},get client(){return i().client},get api(){return i().api},get match(){return i().match},get analytics(){return i().analytics},get functions(){return i().functions},get challenges(){return i().challenges},get room(){return i().room},dispose(){o?.dispose();},get sizeClass(){return r().sizeClass},get roomArgs(){return r().roomArgs},get roster(){return r().roster},players(){return r().players()},profile(s){let d=r().profile?.(s);if(!d)return null;let m=d.displayName;return typeof m!="string"||m===""?null:{displayName:ye(m),...typeof d.displayTag=="string"&&d.displayTag!==""?{displayTag:ye(d.displayTag)}:{},...typeof d.discriminator=="string"?{discriminator:d.discriminator}:{}}},playerNumber(s){return r().playerNumber?.(s)},send(s,l,d){d===void 0?r().send(s,l):r().send(s,l,d);},broadcast(s,l){l===void 0?r().broadcast(s):r().broadcast(s,l);},kick(s,l){l===void 0?r().kick(s):r().kick(s,l);},log(s){r().log(s);},warn(s){r().warn(s);}},attach:()=>{o=_n(r(),{...e,clock:n});}}}function _d(t,e={}){let{server:n,attach:r}=li(()=>t,e);return r(),n}function mf(t){if(t===void 0||typeof t.reason!="string"||t.reason==="")return;let e=t.platform_reason??t.endedReason;return {reason:t.reason,...e===void 0?{}:{endedReason:$e(e)}}}function wd(t,e={}){return ()=>{let n=null,{server:r,attach:o}=li(()=>n,e),i=t(r),a={async init(s){n=s,o(),await i.init?.();},async shutdown(s){let l=mf(s);try{await i.shutdown?.(l);}finally{r.dispose();}}};return i.join&&(a.join=(s,l)=>i.join?.(s,l)),i.leave&&(a.leave=(s,l)=>i.leave?.(s,l)),i.message&&(a.message=(s,l,d,m)=>i.message?.(s,l,d,m)),a}}_i();
|
|
2
|
-
exports.ARCADE_EMBEDDERS=
|
|
1
|
+
var GemWebSdkGame=(function(exports){'use strict';var Cd=Object.defineProperty;var Id=(t,e)=>{for(var n in e)Cd(t,n,{get:e[n],enumerable:true});};var Sr="GemWebSdkHandshake";function Md(){return typeof document>"u"?void 0:document.readyState}var Si=()=>Date.now();function Ri(t={}){let e=t.win??window,n=e,r=n[Sr];if(r!==void 0)return r;let o=t.readyState??Md,i=t.now??Si,a=[],s=[],l=m=>{let u=m.data;!u||u.type!=="gem.handshake"||(a.length>=4&&(a.shift(),s.shift(),d.dropped+=1),a.push(m),s.push(i()));};e.addEventListener("message",l);let d={events:a,times:s,dropped:0,late:o()==="complete",uninstall(){e.removeEventListener("message",l);}};return n[Sr]=d,d}function ki(t,e,n={}){let r=t[Sr];if(r===void 0)return null;let o=n.ttlMs??9500,i=n.now??Si,a=r.events.splice(0),s=r.times?.splice(0),l=0,d=0,m=false,u=i()-o;for(let p=a.length-1;p>=0;p--){let g=s?.[p];if(g!==void 0&&g<u){d+=1;continue}if(l+=1,e(a[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:7.9.1]";function xi(){let t=globalThis.__gemWebSdkVersion;if(typeof t!="string")return "";let e=t.lastIndexOf(":"),n=t.lastIndexOf("]");return e<0||n<=e+1?"":t.slice(e+1,n)}function Od(t,e){return e!==void 0?!e:t==="chain_exhausted"}var on=class{constructor(e){this.options=e;}options;grant=null;state="pending";failure=null;generation=0;inFlight=null;rejected=false;get currentState(){return this.state}get lastFailure(){return this.failure}async get(){if(this.state==="lost")throw new oe(this.failure??"unavailable","the session cannot be renewed");let e=this.seconds();if(this.grant&&e<this.grant.expiresAt-this.renewBefore())return this.grant.token;if(this.grant&&e>=this.grant.chainEndsAt)throw this.enter("lost","chain_exhausted"),new oe("chain_exhausted","the token chain reached its ceiling");return this.refresh(this.nextReason())}nextReason(){return this.rejected?"rejected":this.grant?"expiring":"initial"}invalidate(e){e!==void 0&&this.grant!==null&&this.grant.token!==e||this.rejected&&this.grant===null||(this.grant=null,this.generation+=1,this.inFlight=null,this.rejected=true,this.state!=="lost"&&this.enter("pending"));}accept(e){this.state!=="lost"&&(this.grant=e,this.rejected=false,this.enter("ready"));}close(e="unavailable"){this.grant=null,this.generation+=1,this.inFlight=null,this.enter("lost",e);}refresh(e){if(this.inFlight)return this.inFlight;let n=this.generation;this.enter("pending");let r=this.options.request(e).then(o=>{if(n!==this.generation)throw new oe("internal","token arrived for a superseded generation");return this.grant=o,this.rejected=false,this.enter("ready"),o.token}).catch(o=>{let i=Ld(o),a=o?.retryable;throw n===this.generation&&this.enter(Od(i,typeof a=="boolean"?a:void 0)?"lost":"degraded",i),o instanceof oe?o:new oe(i,String(o))}).finally(()=>{this.inFlight===r&&(this.inFlight=null);});return this.inFlight=r,r}enter(e,n){this.failure=n??(e==="ready"?null:this.failure),this.state!==e&&(this.state=e,this.options.onStateChange?.(e,n));}renewBefore(){return this.options.renewBeforeSeconds??60}seconds(){return Math.floor(this.options.clock.now()/1e3)}},oe=class t extends Error{constructor(n,r){super(`auth ${n}: ${r}`);this.reason=n;this.name="AuthError";}reason;static isAuthError(n){if(n instanceof t)return true;let r=n;return r?.name==="AuthError"&&typeof r.reason=="string"}};function Ld(t){if(t instanceof oe)return t.reason;let e=t?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var re=class t extends Error{retryable=false;constructor(e){super(e),this.name="TransportRefusal";}static isRefusal(e){if(e instanceof t)return true;let n=e;return n?.name==="TransportRefusal"&&n.retryable===false}},gt=["if-match","if-none-match"],Ai=4096;function Gd(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let o=n.toLowerCase();if(!gt.includes(o)||r===void 0)continue;let i=typeof r=="string"?Dd(r):r;if(typeof i!="string"||i.length>Ai||!$d(i))throw new re(`the ${o} header value cannot be sent \u2014 it is not a string, is longer than ${Ai} characters, or contains a character outside the range an HTTP header value may carry. This is a malformed request, not a server failure; the value is withheld here rather than written to logs.`);i!==""&&(e[o]=i);}return Object.freeze(e)}function Dd(t){let e=o=>o===32||o===9||o===10||o===13,n=0,r=t.length;for(;n<r&&e(t.charCodeAt(n));)n++;for(;r>n&&e(t.charCodeAt(r-1));)r--;return t.slice(n,r)}function $d(t){for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n!==9&&(n<32||n===127||n>255))return false}return true}function Fd(t){let{bytes:e}=t;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new re("the raw body is not a Uint8Array, so it cannot be sent as bytes. This is a malformed request, not a server failure.");if(t.body!==void 0)throw new re("the request carries both a JSON body and a raw body, and only one can be sent. This is a malformed request, not a server failure.");return new Uint8Array(e)}}function Pi(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let o={...r},i=Gd(o.headers),a=Fd(o),s=Object.freeze({...o,headers:i,...a===void 0?{}:{bytes:a}}),l=await e.tokenSource.get(),d=await t(s,l);if(d.status!==401||!n)return d;e.tokenSource.invalidate(l);let m=await e.tokenSource.get(),u=await t(s,m);if(u.status===401)throw e.tokenSource.close("unavailable"),new oe("unavailable","the server refused a freshly minted token");return u}}}function yt(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(jd(e))}function ft(t){let e=atob(t),n=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)n[r]=e.charCodeAt(r);return n}function Rr(t){return new TextDecoder().decode(ft(t))}function jd(t){let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return n}var G=class extends Error{constructor(n,r,o,i,a){super(`${n} (${r}): ${o}`);this.reason=n;this.status=r;this.detail=o;this.retryAfterSeconds=i;this.code=a;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},Ti=new WeakMap;function Ci(t){return Ti.get(t)??{}}var qd=new Set([408,429,500,502,503,504]),Nd=6e4;function Ud(t){if(t===void 0)return 2;if(!Number.isInteger(t)||t<0||t>10)throw new re(`maxRetries must be a whole number between 0 and 10; received ${JSON.stringify(t)}. This is a configuration fault, not a server failure.`);return t}var Le=class{constructor(e){this.options=e;}options;async get(e,n){return this.send({method:"GET",path:e,signal:n},true)}async getWithEtag(e,n={}){let r=await this.sendRaw({method:"GET",path:e,...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{headers:{"if-none-match":n.ifNoneMatch}}},true),o=r.etag===void 0?{}:{etag:r.etag};return r.status===304?{modified:false,...o}:{modified:true,body:r.body,...o}}async put(e,n,r,o={}){return this.send({method:"PUT",path:e,body:n,signal:r,...kn(o)},o.replaySafe===true)}async post(e,n,r,o={}){return this.send({method:"POST",path:e,body:n,signal:r,...kn(o)},o.replaySafe===true)}async postBytes(e,n,r,o={}){let i=await this.sendRaw({method:"POST",path:e,bytes:n,responseType:"bytes",signal:r,...kn(o)},o.replaySafe===true);return {bytes:Bd(i.body),...i.invocationId===void 0?{}:{invocationId:i.invocationId}}}async patch(e,n,r,o={}){return this.send({method:"PATCH",path:e,body:n,signal:r,...kn(o)},o.replaySafe===true)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...kn(r)},r.replaySafe===true)}async send(e,n){return (await this.sendRaw(e,n)).body}async sendRaw(e,n){let r=n?Ud(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw Ei(e.signal);for(let i=0;i<r;i++){if(i>0&&await this.backoff(i,o,e.signal),e.signal?.aborted)throw Ei(e.signal);let a;try{a=await this.options.transport.request(e);}catch(l){if(oe.isAuthError(l)||re.isRefusal(l)||e.signal?.aborted||Hd(l))throw l;o=new G("unavailable",0,String(l));continue}if(a.status>=200&&a.status<300||a.status===304)return a;let s=Vd(a);if(!qd.has(a.status))throw s;o=s;}throw o??new G("unavailable",0,"no attempt was made")}backoff(e,n,r){if(r?.aborted)return Promise.resolve();let o=n?.retryAfterSeconds,i=o!==void 0?o*1e3:2**(e-1)*250,a=2**(e-1)*250,s=Math.min(Math.max(i,a),Nd);return new Promise(l=>{let d=this.options.clock,m=false,u=false,p,g=()=>{m||(m=true,u&&d.clearTimeout(p),r?.removeEventListener("abort",g),l());};r?.addEventListener("abort",g,{once:true}),p=d.setTimeout(g,s),u=true,m&&d.clearTimeout(p);})}};function Bd(t){if(t instanceof Uint8Array)return t;if(t==null)return new Uint8Array(0);let e=typeof t=="string"?t:JSON.stringify(t);return new TextEncoder().encode(e)}function kn(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function Ei(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function Hd(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function Vd(t){let e=Kd(t),n=zd(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&Ti.set(e,r),e}var Wd=new Map([["insufficient_funds","insufficient_funds"]]);function Kd(t){let{status:e,body:n}=t,r=Jd(n),o=t.retryAfterSeconds??Xd(n),i=Yd(n),a=i===void 0?void 0:Wd.get(i);if(a!==void 0)return new G(a,e,r,void 0,i);switch(e){case 304:return new G("not_modified",e,r);case 400:case 422:return new G("invalid",e,r,void 0,i);case 403:return new G("forbidden",e,r,void 0,i);case 404:return new G("not_found",e,r,void 0,i);case 402:return new G("insufficient_funds",e,r,void 0,i);case 409:return new G("conflict",e,r,void 0,i);case 412:return new G("precondition_failed",e,r,void 0,i);case 413:return new G("too_large",e,r,void 0,i);case 429:return new G("rate_limited",e,r,o,i);default:return new G("unavailable",e,r,o,i)}}function Jd(t){if(typeof t=="string")return t;let e=t?.message;if(typeof e=="string")return e;let n=t?.error;if(typeof n=="string")return n;let r=n?.message;return typeof r=="string"?r:"no detail"}function zd(t){let n=t?.error?.details;return n===null?void 0:n}function Yd(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function Xd(t){let e=t?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function v(t){let e=String(t);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 Ii(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function Mi(t,e,n,r,o,i){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/add`;return t.client.post(a,o,i?.signal)}async function Oi(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Li(t,e,n,r,o,i){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/claim`;return t.client.post(a,o,i?.signal)}async function Gi(t,e,n){return t.client.post("/v1/characters",e,n?.signal)}async function Di(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/orders/batch`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function $i(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/orders`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Fi(t,e,n,r,o){let i=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(i,o?.signal)}async function ji(t,e,n,r,o){let i=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.delete(i,o?.signal)}async function qi(t,e,n,r){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.delete(o,r?.signal)}async function Ni(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/recipes/execute`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Ui(t,e,n,r,o,i){let a=`/v1/saves/${v(e)}/${v(n)}/${v(r)}/finalize`;return t.client.post(a,o,i?.signal)}async function Bi(t,e,n){let r=`/v1/games/${v(t.gameId())}/config/channels/${v(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Hi(t,e,n){let r=`/v1/characters/${v(e)}`;return t.client.get(r,n?.signal)}async function Vi(t,e,n){let r=`/v1/inventory/loot-tables/${v(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Wi(t,e,n,r,o){let i=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Ki(t,e,n,r){let o=new URLSearchParams;r?.include_buckets!==void 0&&o.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&o.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&o.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&o.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&o.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&o.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&o.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&o.set("progression_cursor",String(r?.progression_cursor));let i=o.toString(),a=`/v1/inventory/${v(e)}/${v(n)}`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function Ji(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/items/${v(r)}`;return t.client.get(i,o?.signal)}async function zi(t,e,n,r,o){let i=new URLSearchParams;o?.bucket_1!==void 0&&i.set("bucket_1",String(o?.bucket_1)),o?.bucket_2!==void 0&&i.set("bucket_2",String(o?.bucket_2)),o?.limit!==void 0&&i.set("limit",String(o?.limit)),o?.periods_back!==void 0&&i.set("periods_back",String(o?.periods_back)),o?.period!==void 0&&i.set("period",String(o?.period)),o?.player_id!==void 0&&i.set("player_id",String(o?.player_id));let a=i.toString(),s=`/v1/leaderboards/${v(e)}/${v(n)}/${v(r)}`+(a?`?${a}`:"");return t.client.get(s,o?.signal)}async function Yi(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/orders/${v(r)}`;return t.client.get(i,o?.signal)}async function Xi(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}`;return t.client.get(i,o?.signal)}async function Qi(t,e,n,r,o,i){let a=`/v1/inventory/${v(e)}/${v(n)}/catalogs/${v(r)}/recipes/${v(o)}/availability`;return t.client.get(a,i?.signal)}async function Zi(t,e,n,r){let o=new URLSearchParams;o.set("limit",String(r?.limit));let i=o.toString(),a=`/v1/inventory/${v(e)}/${v(n)}/recipe-usage`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function kr(t,e,n,r,o){let i=`/v1/saves/${v(e)}/${v(n)}/${v(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function es(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let o=r.toString(),i=`/v1/leaderboards/${v(e)}/friends`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function ns(t,e,n){let r=`/v1/showcase/friends/${v(e)}`;return t.client.get(r,n?.signal)}async function ts(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let o=r.toString(),i=`/v1/leaderboards/${v(e)}`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function rs(t,e){let n=`/v1/games/${v(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function ht(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function os(t,e,n){let r=`/v1/profiles/players/${v(e)}`;return t.client.get(r,n?.signal)}async function is(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),o="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function ss(t,e,n){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${v(e)}`;return t.client.get(r,n?.signal)}async function as(t,e,n,r){let o=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.get(o,r?.signal)}async function ls(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function ds(t,e,n){let r=`/v1/inventory/transfers/${v(e)}`;return t.client.get(r,n?.signal)}async function cs(t,e,n){let r=`/v1/games/${v(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{...n?.keepalive===void 0?{}:{keepalive:n.keepalive},replaySafe:true})}async function us(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function ms(t,e,n,r,o){let i=`/v1/inventory/${v(e)}/${v(n)}/platform-funded-game-inventory-purchases`;return t.client.post(i,r,o?.signal)}async function ps(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function gs(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),o="/v1/challenges"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function ys(t,e){return t.client.get("/v1/characters",e?.signal)}async function fs(t,e,n,r){let o=`/v1/settings/${v(e)}/${v(n)}`;return t.client.get(o,r?.signal)}async function hs(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/inventory/${v(e)}/${v(n)}/orders`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function bs(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/saves/${v(e)}/${v(n)}`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function vs(t,e){let n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),o="/v1/friends"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function _s(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),o="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function ws(t,e,n,r){let o=`/v1/games/${v(t.gameId())}/matches/${v(e)}/end`;return t.client.post(o,n,r?.signal)}async function Ss(t,e,n,r,o,i){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/max`;return t.client.post(a,o,i?.signal)}async function Rs(t,e,n,r,o,i){let a=`/v1/settings/${v(e)}/${v(n)}/${v(r)}`;return t.client.put(a,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ks(t,e,n,r,o){let i=`/v1/showcase/players/${v(e)}/${v(n)}`;return t.client.put(i,r,o?.signal)}async function xs(t,e,n){let r=`/v1/inventory/transfers/${v(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function As(t,e,n,r){let o=`/v1/characters/${v(e)}`;return t.client.patch(o,n,r?.signal)}async function Ps(t,e,n,r,o,i){let a=`/v1/saves/${v(e)}/${v(n)}/${v(r)}/upload-url`;return t.client.post(a,o,i?.signal,{replaySafe:true})}async function Es(t,e,n,r,o,i){let a=`/v1/inventory/${v(e)}/${v(n)}/progressions/${v(r)}/reset`;return t.client.post(a,o,i?.signal)}async function Ts(t,e,n){let r=`/v1/characters/${v(e)}`;return t.client.delete(r,n?.signal)}var U="gem-web-bridge",vt={min:1,max:1},sn=65536,Cs=8,bt=5e3,Is=1024;function Ar(t){return Object.freeze(Object.assign(Object.create(null),t))}var Ms=Ar({"gem.handshake":30,"gem.handshake.accept":5,"gem.token":30,"gem.token.denied":30,"gem.player":12,"gem.pause":120,"gem.prefs":60,"gem.cohorts":12,"gem.earnAllowanceChanged":30,"gem.viewport":60,"gem.deviceSettings":12,"gem.willTerminate":10,"gem.roomEvent":120,"gem.socketState":12,"gem.seatedEvent":60,"gem.autoStartFailedEvent":30,"gem.signalEvent":1800,"gem.dedicatedEvent":120,"gem.partyResult":30,"gem.clusterTarget":12,"gem.devtools":30,"gem.screenshot":6,"gem.screenshot.denied":12,"gem.requestContext":12,"gem.gameContext":12,"gem.signal":1200,"gem.dedicatedOffer":60,"gem.partyRequest":12,"gem.ready":5,"gem.engaged":5,"gem.progress":600,"gem.requestToken":12,"gem.requestLocalServer":6,"gem.localServer":30,"gem.localServer.denied":30,"gem.exit":5,"gem.openExternal":6,"gem.requestFullscreen":30,"gem.audioState":120,"gem.rewardCue":60,"gem.walletDisplay":60,"gem.menu":60,"gem.menuSelect":60,"gem.requestShare":6,"gem.frameStats":120,"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}),_t="__malformed";var Qd=Ar({"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.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.menu":"gameMenu","gem.menuSelect":"gameMenu"}),Zd=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.viewport.","reservedAreas"]]);function Os(t){let e=Qd[t];if(e!==void 0)return e;for(let[n,r]of Zd)if(t.startsWith(n))return r}function Pr(t){let e=/^([a-z][a-z0-9+.-]*):\/\/([a-z0-9.-]+|\[[0-9a-f:.]+\])(:([0-9]{1,5}))?$/i.exec(t);return e===null?false:e[4]===void 0||Number(e[4])<=65535}function ec(t){let e;try{e=new URL(t);}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 nc(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function tc(t){return /^[a-z_]+$/.test(t)}function xr(t,e,n){if(e>Cs)return `nesting deeper than ${Cs}`;if(++n.nodes>bt)return `more than ${bt} values`;if(n.bytes>sn)return `over the ${sn} byte limit`;if(t==null)return n.bytes+=4,null;let r=typeof t;if(r==="boolean")return n.bytes+=5,null;if(r==="number")return n.bytes+=8,null;if(r==="string")return n.bytes+=t.length*3+2,null;if(r!=="object")return `${r} is not plain data`;let o=t;if(n.seen.has(o))return "a repeated or cyclic object reference";if(n.seen.add(o),Array.isArray(t)){if(t.length>Is)return `an array of ${t.length} entries, over the ${Is} limit`;n.bytes+=2;for(let s of t){let l=xr(s,e+1,n);if(l)return l}return null}let i=Object.getPrototypeOf(t);if(i!==Object.prototype&&i!==null)return "a value that is not a plain object";n.bytes+=2;let a=t;for(let s in a){if(!Object.prototype.hasOwnProperty.call(a,s))continue;if(++n.nodes>bt)return `more than ${bt} values`;if(n.bytes+=s.length*3+4,n.bytes>sn)return `over the ${sn} byte limit`;let l=xr(a[s],e+1,n);if(l)return l}return null}function rc(t){let e={nodes:0,bytes:0,seen:new Set},n=xr(t,0,e);return n?`message contains ${n}`:e.bytes>sn?`message is over the ${sn} byte limit`:null}var oc={origin:[Pr,"not a well-formed origin"],url:[ec,"not a safe absolute http(s) URL"],bcp47:[nc,"not a well-formed BCP 47 tag"],code:[tc,"not a code of lower-case letters and underscores"]};function Ls(t,e,n){for(let r of e){let o=n===""?r.n:`${n}.${r.n}`,i=t[r.n];if(i==null){if(r.o)continue;return `${o}: required`}let a=Gs(i,r,o);if(a)return a}return null}function Gs(t,e,n){switch(e.k){case "string":{if(typeof t!="string")return `${n}: expected string`;if(t.length>e.max)return `${n}: exceeds ${e.max} characters`;if(e.f){let[r,o]=oc[e.f];if(!r(t))return `${n}: ${o}`}return null}case "int":return typeof t!="number"||!Number.isInteger(t)?`${n}: expected integer`:t<e.lo||t>e.hi?`${n}: out of range ${e.lo}..${e.hi}`:null;case "boolean":return typeof t=="boolean"?null:`${n}: expected boolean`;case "enum":{let r=e.v;return r.includes(t)?null:`${n}: not one of ${r.join("|")}`}case "object":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected object`:Ls(t,e.fs,n);case "json":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected a plain object`:null;case "array":{if(!Array.isArray(t))return `${n}: expected array`;if(t.length>e.max)return `${n}: exceeds ${e.max} items`;let r=e.it,o=`${n}[]`;for(let i of t){if(i==null){if(r.o)continue;return `${o}: required`}let a=Gs(i,r,o);if(a)return a}return null}default:{let r=e.k;return `${n}: unknown kind ${String(r)}`}}}function P(t,e){return n=>{let r=rc(n);if(r)return r;if(typeof n!="object"||n===null||Array.isArray(n))return "message: expected object";let o=n;return o.gem!==U?"gem: wrong protocol marker":o.type!==t?`type: expected ${t}`:Ls(o,e,"")}}var ic=P("gem.handshake",[{n:"versions",k:"object",fs:[{n:"min",k:"int",lo:1,hi:1e3},{n:"max",k:"int",lo:1,hi:1e3}]},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}},{n:"embedder",k:"string",max:2048,f:"origin"},{n:"unbidden",k:"boolean",o:1}]),sc=P("gem.handshake.accept",[{n:"v",k:"int",lo:1,hi:1e3},{n:"capabilities",k:"array",o:1,max:64,it:{n:"",k:"string",max:64}}]),ac=P("gem.token",[{n:"token",k:"string",max:4096},{n:"requestId",k:"string",o:1,max:64},{n:"generation",k:"int",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"string",o:1,max:512,f:"url"},{n:"playerId",k:"string",max:64},{n:"gameId",k:"string",max:64},{n:"channel",k:"enum",v:["dev","test","release"]},{n:"gameVersion",k:"string",o:1,max:64},{n:"expiresAt",k:"int",lo:0,hi:4102444800},{n:"chainEndsAt",k:"int",lo:0,hi:4102444800},{n:"allowDevTools",k:"boolean",o:1}]),lc=P("gem.token.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"retryAfterMs",k:"int",o:1,lo:0,hi:36e5},{n:"reason",k:"enum",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"string",max:64}]),dc=P("gem.player",[{n:"untrusted",k:"object",fs:[{n:"displayName",k:"string",max:64},{n:"displayTag",k:"string",o:1,max:80},{n:"displayHandle",k:"string",max:80}]},{n:"playerId",k:"string",o:1,max:64},{n:"discriminator",k:"string",o:1,max:8},{n:"avatarIconUrl",k:"string",o:1,max:2048,f:"url"},{n:"badges",k:"array",o:1,max:2,it:{n:"",k:"object",fs:[{n:"itemId",k:"string",max:64},{n:"iconUrl",k:"string",max:2048,f:"url"}]}},{n:"displayTag",k:"string",max:8},{n:"avatarUrl",k:"string",o:1,max:2048,f:"url"},{n:"boost",k:"object",o:1,fs:[{n:"multipliers",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"currencyId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"multiplierBp",k:"int",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"int",o:1,lo:1,hi:7}]}]),cc=P("gem.pause",[{n:"paused",k:"boolean"}]),uc=P("gem.prefs",[{n:"reducedMotion",k:"boolean"},{n:"muted",k:"boolean"},{n:"showFrameStats",k:"boolean",o:1},{n:"locale",k:"string",max:35,f:"bcp47"}]),mc=P("gem.cohorts",[{n:"cohorts",k:"array",max:8,it:{n:"",k:"object",fs:[{n:"experimentId",k:"string",max:36},{n:"variantKey",k:"string",max:32}]}}]),pc=P("gem.earnAllowanceChanged",[]),gc=P("gem.viewport",[{n:"insets",k:"object",fs:[{n:"top",k:"int",lo:0,hi:4096},{n:"right",k:"int",lo:0,hi:4096},{n:"bottom",k:"int",lo:0,hi:4096},{n:"left",k:"int",lo:0,hi:4096}]},{n:"reserved",k:"array",o:1,max:4,it:{n:"",k:"object",fs:[{n:"x",k:"int",lo:0,hi:16384},{n:"y",k:"int",lo:0,hi:16384},{n:"width",k:"int",lo:0,hi:16384},{n:"height",k:"int",lo:0,hi:16384}]}}]),yc=P("gem.deviceSettings",[{n:"settings",k:"json",o:1}]),fc=P("gem.willTerminate",[{n:"reason",k:"enum",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"int",lo:0,hi:6e4}]),hc=P("gem.roomEvent",[{n:"event",k:"enum",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"string",max:64},{n:"matchId",k:"string",o:1,max:64},{n:"version",k:"int",o:1,lo:0,hi:2147483647},{n:"reason",k:"string",o:1,max:64},{n:"platform",k:"enum",o:1,v:["universal","mobile"]}]),bc=P("gem.socketState",[{n:"connected",k:"boolean"},{n:"reason",k:"enum",o:1,v:["connecting","dropped","watchdog","terminal"]}]),vc=P("gem.seatedEvent",[{n:"roomId",k:"string",max:64}]),_c=P("gem.autoStartFailedEvent",[{n:"roomId",k:"string",max:64},{n:"code",k:"string",max:64}]),wc=P("gem.signalEvent",[{n:"event",k:"enum",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),Sc=P("gem.dedicatedEvent",[{n:"event",k:"enum",v:["answer","error","matchEnded"]},{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",o:1,max:10240},{n:"sessionId",k:"string",o:1,max:64},{n:"code",k:"string",o:1,max:64},{n:"message",k:"string",o:1,max:256},{n:"reason",k:"string",o:1,max:64}]),Rc=P("gem.partyResult",[{n:"requestId",k:"string",max:64},{n:"partyId",k:"string",o:1,max:64}]),kc=P("gem.clusterTarget",[{n:"clusterTargetId",k:"string",max:64},{n:"clusterTargetIds",k:"array",o:1,max:3,it:{n:"",k:"string",max:64}}]),xc=P("gem.devtools",[{n:"action",k:"enum",v:["open","close","toggle"]}]),Ac=P("gem.screenshot",[{n:"maxWidth",k:"int",lo:1,hi:7680},{n:"maxHeight",k:"int",lo:1,hi:4320}]),Pc=P("gem.screenshot.denied",[{n:"reason",k:"enum",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"boolean"}]),Ec=P("gem.requestContext",[]),Tc=P("gem.gameContext",[{n:"context",k:"json"}]),Cc=P("gem.signal",[{n:"signal",k:"enum",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"string",max:64},{n:"data",k:"json"}]),Ic=P("gem.dedicatedOffer",[{n:"matchId",k:"string",max:64},{n:"sdp",k:"string",max:10240},{n:"intent",k:"enum",v:["initial","ice_restart","full_reconnect"]}]),Mc=P("gem.partyRequest",[{n:"requestId",k:"string",max:64}]),Oc=P("gem.ready",[]),Lc=P("gem.engaged",[]),Gc=P("gem.progress",[{n:"loaded",k:"int",lo:0,hi:1099511627776},{n:"total",k:"int",lo:0,hi:1099511627776}]),Dc=P("gem.requestToken",[{n:"requestId",k:"string",max:64},{n:"reason",k:"enum",v:["initial","expiring","rejected"]}]),$c=P("gem.requestLocalServer",[{n:"requestId",k:"string",max:64},{n:"gameRoomId",k:"string",max:64}]),Fc=P("gem.localServer",[{n:"requestId",k:"string",max:64},{n:"serverId",k:"string",o:1,max:128}]),jc=P("gem.localServer.denied",[{n:"requestId",k:"string",max:64},{n:"retryable",k:"boolean"},{n:"reason",k:"enum",v:["refused","unavailable"]}]),qc=P("gem.exit",[{n:"reason",k:"string",o:1,max:64}]),Nc=P("gem.openExternal",[{n:"url",k:"string",max:2048,f:"url"}]),Uc=P("gem.requestFullscreen",[{n:"enabled",k:"boolean"}]),Bc=P("gem.audioState",[{n:"muted",k:"boolean"}]),Hc=P("gem.rewardCue",[{n:"currencySlug",k:"string",max:32},{n:"expected",k:"int",o:1,lo:1,hi:1e9},{n:"origin",k:"object",o:1,fs:[{n:"x",k:"int",lo:0,hi:16384},{n:"y",k:"int",lo:0,hi:16384}]}]),Vc=P("gem.walletDisplay",[{n:"visible",k:"boolean"},{n:"currencies",k:"array",o:1,max:8,it:{n:"",k:"string",max:64}},{n:"score",k:"boolean",o:1}]),Wc=P("gem.menu",[{n:"settings",k:"boolean"},{n:"items",k:"array",o:1,max:4,it:{n:"",k:"object",fs:[{n:"id",k:"string",max:32},{n:"label",k:"string",max:40}]}}]),Kc=P("gem.menuSelect",[{n:"entry",k:"enum",v:["settings","item"]},{n:"id",k:"string",o:1,max:32}]),Jc=P("gem.requestShare",[{n:"params",k:"array",max:16,it:{n:"",k:"object",fs:[{n:"key",k:"string",max:64},{n:"value",k:"string",max:512}]}}]),zc=P("gem.frameStats",[{n:"fps",k:"int",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"int",lo:0,hi:1e5}]),Yc=P("gem.error",[{n:"code",k:"enum",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"string",o:1,max:256}]),Xc=P("gem.requestPurchase",[{n:"requestId",k:"string",max:64},{n:"purchaseKind",k:"enum",v:["item","recipe"]},{n:"targetId",k:"string",max:64},{n:"currencySlug",k:"string",max:32},{n:"quantity",k:"int",o:1,lo:1,hi:10},{n:"catalogId",k:"string",o:1,max:64}]),Qc=P("gem.purchaseResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["ok","declined","unavailable"]},{n:"reason",k:"string",o:1,max:64,f:"code"},{n:"purchaseId",k:"string",o:1,max:64}]),Zc=P("gem.deviceSettings.put",[{n:"requestId",k:"string",max:64},{n:"settings",k:"json"}]),eu=P("gem.deviceSettings.result",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["stored","too_large","unavailable"]}]),nu=P("gem.requestAd",[{n:"requestId",k:"string",max:64},{n:"placement",k:"string",max:32},{n:"format",k:"enum",v:["interstitial","rewarded"]}]),tu=P("gem.adResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["shown","no_ad","unavailable"]}]),ru=P("gem.requestSignIn",[{n:"requestId",k:"string",max:64}]),ou=P("gem.signInResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["signed_in","declined","unavailable"]}]),iu=P("gem.requestFriendChallenge",[{n:"requestId",k:"string",max:64},{n:"playerId",k:"string",max:64},{n:"template",k:"string",max:64},{n:"params",k:"json",o:1}]),su=P("gem.friendChallengeResult",[{n:"requestId",k:"string",max:64},{n:"outcome",k:"enum",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"string",o:1,max:64},{n:"param",k:"string",o:1,max:64},{n:"channel",k:"string",o:1,max:16},{n:"configVersion",k:"int",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"int",o:1,lo:0,hi:864e5},{n:"detail",k:"string",o:1,max:300}]),wt=Ar({"gem.handshake":ic,"gem.handshake.accept":sc,"gem.token":ac,"gem.token.denied":lc,"gem.player":dc,"gem.pause":cc,"gem.prefs":uc,"gem.cohorts":mc,"gem.earnAllowanceChanged":pc,"gem.viewport":gc,"gem.deviceSettings":yc,"gem.willTerminate":fc,"gem.roomEvent":hc,"gem.socketState":bc,"gem.seatedEvent":vc,"gem.autoStartFailedEvent":_c,"gem.signalEvent":wc,"gem.dedicatedEvent":Sc,"gem.partyResult":Rc,"gem.clusterTarget":kc,"gem.devtools":xc,"gem.screenshot":Ac,"gem.screenshot.denied":Pc,"gem.requestContext":Ec,"gem.gameContext":Tc,"gem.signal":Cc,"gem.dedicatedOffer":Ic,"gem.partyRequest":Mc,"gem.ready":Oc,"gem.engaged":Lc,"gem.progress":Gc,"gem.requestToken":Dc,"gem.requestLocalServer":$c,"gem.localServer":Fc,"gem.localServer.denied":jc,"gem.exit":qc,"gem.openExternal":Nc,"gem.requestFullscreen":Uc,"gem.audioState":Bc,"gem.rewardCue":Hc,"gem.walletDisplay":Vc,"gem.menu":Wc,"gem.menuSelect":Kc,"gem.requestShare":Jc,"gem.frameStats":zc,"gem.error":Yc,"gem.requestPurchase":Xc,"gem.purchaseResult":Qc,"gem.deviceSettings.put":Zc,"gem.deviceSettings.result":eu,"gem.requestAd":nu,"gem.adResult":tu,"gem.requestSignIn":ru,"gem.signInResult":ou,"gem.requestFriendChallenge":iu,"gem.friendChallengeResult":su});var le={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},xn=class{constructor(e=le){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=Ms[e];if(n===void 0)return false;let r=this.clock.now(),o=this.lastRefill.get(e)??r,i=this.tokens.get(e)??n,a=Math.max(0,r-o),s=Math.min(n,i+a*n/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 Er(t,e){return t.toLowerCase()===e.toLowerCase()}function St(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function Ds(t,e){if(typeof e!="string"||e==="")return false;let n,r;try{n=new URL(t),r=new URL(e);}catch{return false}return n.protocol!=="http:"&&n.protocol!=="https:"||r.protocol!=="http:"&&r.protocol!=="https:"||n.username!==""||n.password!==""||n.pathname!=="/"||n.search!==""||n.hash!==""||n.port===""?false:St(n.hostname)&&St(r.hostname)}function $s(t,e){if(e.min>e.max)return null;let n=Math.min(t.max,e.max),r=Math.max(t.min,e.min);return n>=r?n:null}var Rt=class{constructor(e,n){this.inventory=e;this.resolveCurrencyId=n;}inventory;resolveCurrencyId;async list(e={}){return (await this.inventory.snapshot({buckets:e.buckets})).currencies.data.map(r=>({currencyId:r.currencyId,total:r.total,...r.buckets===void 0?{}:{buckets:r.buckets}}))}async get(e,n={}){let o=(await this.inventory.snapshot({buckets:n.buckets})).currencies.data,i=o.find(s=>s.currencyId===e),a;return !i&&this.resolveCurrencyId&&(a=await this.resolveCurrencyId(e).catch(()=>{}),a!==void 0&&(i=o.find(s=>s.currencyId===a))),{currencyId:i?i.currencyId:a??e,total:i?i.total:null,...i?.buckets===void 0?{}:{buckets:i.buckets}}}};function Cr(t){let e=Array.isArray(t.achievements)?t.achievements:[],n=[];for(let r of e){let o=r??{};typeof o.id!="string"||o.id===""||typeof o.threshold!="number"||!Number.isFinite(o.threshold)||n.push({id:o.id,threshold:o.threshold,points:typeof o.points=="number"?o.points:0,hidden:o.hidden===true,...typeof o.unlocked_at=="number"&&Number.isFinite(o.unlocked_at)?{unlockedAt:o.unlocked_at}:{},...o.revoked===true?{revoked:true}:{}});}return {...n.length>0?{achievements:n}:{},...t.achievements_unavailable===true?{achievementsUnavailable:true}:{}}}var Fs="inventory",an=t=>typeof t=="number"?t:0,An=t=>typeof t=="string"?t:"";function Tr(t,e){let n=t??{},r=typeof n.next_cursor=="string"?n.next_cursor:void 0;return {data:Array.isArray(n.data)?n.data.map(e):[],...r===void 0?{}:{nextCursor:r}}}function js(t){let e=t??{};return {itemDefinitionId:An(e.item_definition_id),instanceId:An(e.instance_id),quantity:an(e.quantity),acquiredAt:an(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function au(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:Tr(e.currencies,r=>{let o=r??{},i=Array.isArray(o.buckets)?o.buckets.map(a=>{let s=a??{};return {bucket:An(s.bucket),balance:an(s.balance)}}):void 0;return {currencyId:An(o.currency_id),total:an(o.total),...i===void 0?{}:{buckets:i}}}),items:Tr(e.items,js),progressions:Tr(e.progressions,r=>{let o=r??{};return {progressionDefinitionId:An(o.progression_definition_id),currentValue:an(o.current_value),completionCount:an(o.completion_count),isCompleted:o.is_completed===true,...Cr(o)}}),...n===void 0?{}:{etag:n}}}var kt=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${Fs}#buckets`:Fs;return this.cache.read(n,[],()=>this.fetch({includeBuckets:e.buckets}))}async instances(e,n){let r=await this.snapshot();if(r.items.nextCursor===void 0){let i=r.items.data.filter(a=>a.itemDefinitionId===e);if(i.length>0)return i}let o=await Ji(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(o)?o.map(js):[]}page(e){return this.fetch(e)}refresh(){this.invalidate();}onChanged(e){return this.cache.onInvalidate(e)}invalidate(){this.cache.invalidate();}async fetch(e){let n=await Ki(this.api,this.entity.type,this.entity.id,{...e.includeBuckets?{include_buckets:true}:{},...e.currencyCursor===void 0?{}:{currency_cursor:e.currencyCursor},...e.itemCursor===void 0?{}:{item_cursor:e.itemCursor},...e.progressionCursor===void 0?{}:{progression_cursor:e.progressionCursor},...e.currencyLimit===void 0?{}:{currency_limit:e.currencyLimit},...e.itemLimit===void 0?{}:{item_limit:e.itemLimit},...e.progressionLimit===void 0?{}:{progression_limit:e.progressionLimit},...e.signal===void 0?{}:{signal:e.signal}});return au(n)}};var lu={unknown_currency:1,currency_not_in_game_payable:1,not_purchasable:1,no_price_in_currency:1,busy:1,cancelled:1,insufficient_funds:1,price_mismatch:1,config_version_stale:1,platform_currency_unavailable:1,not_available:1,recipe_locked:1,recipe_on_cooldown:1,recipe_max_uses_exceeded:1,item_max_stack_exceeded:1,recipe_costs_unmet:1,quantity_invalid:1,error:1},du=new Set(Object.keys(lu));function qs(t){return typeof t=="string"&&du.has(t)?t:"error"}var Ge=class extends RangeError{constructor(n,r){super(r);this.code=n;this.name="PurchaseRefusal";}code;retryable=false};var Z=t=>typeof t=="string"?t:"",cu=t=>typeof t=="string"?t:Z(t&&typeof t=="object"?t.type:void 0),Re=t=>typeof t=="number"?t:0;function uu(t){let e=t??{};return {prerequisiteType:Z(e.prerequisite_type),referenceId:Z(e.reference_id),required:Re(e.required),current:Re(e.current)}}function Pn(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {orderId:Z(e.order_id),status:Z(e.status),...n===void 0?{}:{etag:n}}}function xt(){return crypto.randomUUID()}var mu="recipe-usage",Ns=100;function At(t){let e=t??{};switch(e.type){case "currency":return {kind:"currency",currencyId:Z(e.currency_id),bucket:Z(e.bucket),delta:Re(e.delta),balanceAfter:Re(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:Z(e.item_definition_id),instanceId:Z(e.instance_id),delta:Re(e.delta),quantityAfter:Re(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:Z(e.progression_definition_id),delta:Re(e.delta),valueAfter:Re(e.value_after),completed:e.completed===true};default:return {kind:"other",type:Z(e.type)}}}function pu(t){let e=t??{},n=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:Z(e.entry_id),...n===void 0?{}:{rarityTier:n},rollNumber:Re(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(At):[]}}function gu(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(pu):void 0;return {orderId:Z(e.order_id),status:Z(e.status),...n===void 0?{}:{etag:n},granted:Array.isArray(e.granted)?e.granted.map(At):[],consumed:Array.isArray(e.consumed)?e.consumed.map(At):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(At):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function yu(t){let e=t??{},n=e.price??{};return {payment:"platform_currency",orderId:Z(e.target_order_id)||Z(e.source_order_id),status:Z(e.status),purchaseId:Z(e.purchase_id),sourceOrderId:Z(e.source_order_id),price:{currencyId:Z(n.platform_currency_id),amount:Re(n.price)}}}function fu(t){let e=t??{},n=typeof e.last_used_at=="string"?e.last_used_at:void 0,r=typeof e.cooldown_expires_at=="string"?e.cooldown_expires_at:void 0;return {recipeId:Z(e.recipe_id),useCount:typeof e.use_count=="number"?e.use_count:0,isOnCooldown:e.is_on_cooldown===true,...n===void 0?{}:{lastUsedAt:n},...r===void 0?{}:{cooldownExpiresAt:r}}}function Us(t){switch(t.type){case "currency_grant":case "currency_consume":return {type:t.type,currency_id:t.currencyId,amount:t.amount};default:return {type:t.type,item_definition_id:t.itemDefinitionId,quantity:t.quantity}}}var Pt=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;async create(e,n={}){let r=await this.write(()=>$i(this.api,this.entity.type,this.entity.id,{operations:e.map(Us),source:n.source??"play",nonce:xt()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return Pn(r)}async createMany(e,n={}){return this.write(()=>Di(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(Us),nonce:xt()})),source:n.source??"play"},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}))}async recipeAvailability(e,n,r){let i=await Qi(this.api,this.entity.type,this.entity.id,e,n,r===void 0?{}:{signal:r})??{},a=typeof i.uses_remaining=="number"?i.uses_remaining:void 0,s=typeof i.cooldown_expires_at=="string"?i.cooldown_expires_at:void 0,l=Array.isArray(i.lock_reasons)?i.lock_reasons.map(uu):[];return {canExecute:i.can_execute===true,locked:i.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(i.reasons)?i.reasons.map(d=>cu(d)):[],...a===void 0?{}:{usesRemaining:a},...s===void 0?{}:{cooldownExpiresAt:s}}}async recipeUsageAll(){return this.cache.read(mu,[],async()=>{let n=await Zi(this.api,this.entity.type,this.entity.id,{limit:Ns})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(fu),truncated:r.length>=Ns}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,n={}){if(e.payment.kind==="configured"){let u=e,p=await this.write(()=>Ni(this.api,this.entity.type,this.entity.id,{catalog_id:u.catalogId,recipe_id:u.targetId,game_id:this.api.gameId(),nonce:xt()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...gu(p)}}if(this.entity.type!=="players"||this.entity.id!=="me")throw new TypeError("platform-currency purchases are available only on gem.me.mutations");let[r,o]=await Promise.all([is(this.api,n.signal===void 0?{}:{signal:n.signal}),ht(this.api,n.signal===void 0?{}:{signal:n.signal})]),i=e.payment.currencySlug.toLowerCase(),a=o.currencies.find(u=>u.currency_id.toLowerCase()===i||u.slug.toLowerCase()===i);if(a===void 0){let u=o.currencies.map(p=>p.slug);throw new Ge("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${u.length===0?"none":u.join(", ")}`)}let s=e.kind==="item"?r.items.find(u=>u.item_id===e.targetId):r.recipes.find(u=>u.recipe_id===e.targetId&&u.catalog_id===e.catalogId);if(s===void 0)throw new Ge("not_purchasable",`purchase target ${JSON.stringify(e.targetId)}`+(e.kind==="recipe"?` in catalog ${JSON.stringify(e.catalogId)}`:"")+` is not purchasable in config version ${r.config_version} on this channel. Send the ${e.kind==="item"?"item":"recipe"} id (not its slug), and check that it has platform_prices and that this config version is promoted`);let l=s.platform_prices.find(u=>u.platform_currency_id===a.currency_id);if(l===void 0){let u=g=>o.currencies.find(f=>f.currency_id===g)?.slug??g,p=s.platform_prices.map(g=>`${u(g.platform_currency_id)} ${g.price}`);throw new Ge("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${a.slug} price. It is priced in: ${p.length===0?"nothing":p.join(", ")}`)}let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new Ge("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let m=await this.write(()=>ms(this.api,this.entity.type,this.entity.id,{purchase_kind:e.kind,target_id:e.targetId,...e.kind==="recipe"?{catalog_id:e.catalogId}:{},quantity:d,expected_price:{platform_currency_id:a.currency_id,price:l.price*d},expected_config_version:r.config_version,nonce:xt(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));return yu(m)}async executeRecipe(e,n,r={}){return await this.purchase({kind:"recipe",catalogId:e,targetId:n,payment:{kind:"configured"}},r)}async addProgression(e,n,r){let o=await this.write(()=>Mi(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Pn(o)}async maxProgression(e,n,r){let o=await this.write(()=>Ss(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return Pn(o)}async claimProgression(e,n){let r=await this.write(()=>Li(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Pn(r)}async resetProgression(e,n){let r=await this.write(()=>Es(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return Pn(r)}async write(e){return this.cache.invalidate(),e()}};var Ir=t=>typeof t=="string"?t:"",hu=t=>typeof t=="number"?t:0;function Bs(t){let e=t??{};return {orderId:Ir(e.order_id),status:Ir(e.status),source:Ir(e.source),createdAt:hu(e.created_at)}}var Et=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await hs(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}})??{},o=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {data:Array.isArray(r.orders)?r.orders.map(Bs):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await Yi(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Bs(r)}};var Hs=t=>typeof t=="number"?t:0,bu=t=>typeof t=="string"?t:"";function vu(t){let e=t??{};return {progressionDefinitionId:bu(e.progression_definition_id),currentValue:Hs(e.current_value),completionCount:Hs(e.completion_count),isCompleted:e.is_completed===true,...Cr(e)}}var Tt=class{constructor(e,n,r){this.api=e;this.entity=n;this.inventory=r;}api;entity;inventory;async list(){return (await this.inventory.snapshot()).progressions.data}async get(e,n){let o=(await this.inventory.snapshot()).progressions.data.find(i=>i.progressionDefinitionId===e);if(o&&o.achievementsUnavailable!==true)return o;try{let i=await Xi(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return vu(i)}catch{return o??null}}};var Ct=class{constructor(e,n){this.clock=e;this.identity=n;}clock;identity;generation=0;slots=new Map;listeners=new Set;boundTo=null;read(e,n,r,o){this.rebind();let i=n.length===0,a=i?e:e+"\0"+n.join("\0"),s=this.slots.get(a);if(s){let u=s.filledAt;if(u!==void 0&&(o===void 0||this.clock.now()-u<=o))return Promise.resolve(s.value);if(s.inFlight)return s.inFlight}let l=s??{};this.slots.set(a,l);let d=this.generation,m=r().then(u=>(i&&this.generation===d&&(l.value=u,l.filledAt=this.clock.now()),u)).finally(()=>{l.inFlight===m&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(a)===l&&this.slots.delete(a));});return l.inFlight=m,m}invalidate(){this.slots.clear(),this.generation+=1;for(let e of [...this.listeners])e();}onInvalidate(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}rebind(){if(!this.identity)return;let e=this.identity();e!==this.boundTo&&(this.boundTo=e,this.invalidate());}};function Mr(t){let e=o=>new RegExp(`<${o}>([^<]{0,300})</${o}>`).exec(t)?.[1]?.trim()||void 0,n=[e("Code"),e("AuthenticationErrorDetail")??e("Message")].filter(Boolean);if(n.length>0)return n.join(" \u2014 ");let r=t.trim();return r?r.slice(0,300):""}async function Or(t){try{let e=Mr(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var ie=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},_u=3e4,Vs="the save payload could not reach storage. From a browser this is almost always the storage account's CORS rule, which the platform owns and your game cannot change. If every save fails this way, report it rather than working around it",wu=/^[A-Za-z0-9_]{1,64}$/;function ke(t){let e=t.length===0?"a save key cannot be empty":t.length>64?`it is ${t.length} characters; a save key is at most 64`:t.startsWith("_")||t.startsWith("$")?`it begins with ${JSON.stringify(t[0])}, and \`_\` and \`$\` are reserved prefixes`:"a save key is ASCII letters, digits and underscores only \u2014 no hyphens, spaces or other punctuation, unlike a template slug";if(!wu.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function Ws(t,e){let n=new AbortController,r=AbortSignal.timeout(e),o=()=>n.abort(r.reason),i=()=>n.abort(t?.reason);return t?.aborted?n.abort(t.reason):(r.addEventListener("abort",o,{once:true}),t?.addEventListener("abort",i,{once:true})),{signal:n.signal,release:()=>{r.removeEventListener("abort",o),t?.removeEventListener("abort",i);}}}function Lr(t,e){return t.aborted&&e?.aborted!==true}var Su=new Set(["x-ms-blob-type"]),Ru=/^[ -~]+$/;function ku(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new ie("save_malformed",`the grant for save ${JSON.stringify(e)} described its upload headers as ${Array.isArray(t)?"a list":typeof t}, which is not a set of headers.`);let n={};for(let[r,o]of Object.entries(t)){let i=r.toLowerCase();if(!Su.has(i))throw new ie("save_malformed",`the grant for save ${JSON.stringify(e)} asked the upload to send ${JSON.stringify(r)}, which this SDK does not put on a storage request. Report it \u2014 a platform that needs a new upload header needs an SDK release too.`);if(typeof o!="string"||!Ru.test(o))throw new ie("save_malformed",`the grant for save ${JSON.stringify(e)} gave header ${JSON.stringify(r)} a value that is not usable as one.`);if(i in n)throw new ie("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(i)} twice.`);n[i]=o;}return n}function Gr(t){let e=typeof t.metadata=="object"&&t.metadata!==null&&!Array.isArray(t.metadata)?t.metadata:void 0;return {key:t.key,sizeBytes:t.size_bytes,etag:t.etag,...e===void 0?{}:{metadata:e},createdAt:t.created_at,updatedAt:t.updated_at}}function Dr(t){return t?.reason==="not_found"}var It=class{constructor(e,n,r={}){this.api=e;this.entity=n;this.options=r;}api;entity;options;async put(e,n,r={}){let o;try{o=JSON.stringify(n);}catch(i){throw new ie("save_malformed",`save ${JSON.stringify(e)} could not be serialised to JSON: ${String(i)}. Retrying stores the same unserialisable value.`)}if(o===void 0)throw new ie("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(o),{...r,contentType:"application/json"})}async putBytes(e,n,r={}){let o=r.contentType??"application/octet-stream",i=this.budget(r.timeoutMs),a=Ws(r.signal,i);try{let s=await Ps(this.api,this.entity.type,this.entity.id,ke(e),{size_bytes:n.byteLength,content_type:o,...r.metadata===void 0?{}:{metadata:r.metadata}},{signal:a.signal});if(typeof s.upload_url!="string"||typeof s.session_id!="string")throw new ie("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let l=ku(s.upload_headers,e),d,m=this.options.fetch??globalThis.fetch.bind(globalThis);try{d=await m(s.upload_url,{method:"PUT",headers:{"content-type":o,...l},body:n,credentials:"omit",signal:a.signal});}catch(u){throw Lr(a.signal,r.signal)?this.timeout("upload",i):new ie("upload_failed",`${Vs} for PUT. Underlying error: ${u}`)}if(!d.ok){let u=await Or(d);throw new ie("upload_failed",d.status===400?"the save upload answered 400. The platform and the service holding the bytes disagree about what this upload must carry, which is not something your game can fix and not worth retrying \u2014 report it. "+u:`the save upload answered ${d.status}. `+(d.status===403?"An upload URL is short-lived, so this is most likely an expired one \u2014 start the save again rather than retrying the upload. ":"")+u)}return Gr(await Ui(this.api,this.entity.type,this.entity.id,ke(e),{session_id:s.session_id},{signal:a.signal}))}catch(s){throw this.rethrow(s,r.signal,a.signal,"save",i)}finally{a.release();}}async get(e,n={}){let r=await this.getBytes(e,n);if(r===null)return null;try{return JSON.parse(new TextDecoder().decode(r))}catch(o){throw new ie("save_malformed",`the stored save ${JSON.stringify(e)} is not JSON, so put() did not write it. Read it with getBytes() and decode it yourself. Underlying error: ${o}`)}}async getBytes(e,n={}){let r=this.budget(n.timeoutMs),o=Ws(n.signal,r);try{let i;try{let l=await kr(this.api,this.entity.type,this.entity.id,ke(e),{signal:o.signal});if(!l.modified)return null;i=l.body;}catch(l){if(Dr(l))return null;throw l}if(typeof i.download_url!="string")throw new ie("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let a=this.options.fetch??globalThis.fetch.bind(globalThis),s;try{s=await a(i.download_url,{credentials:"omit",signal:o.signal});}catch(l){throw Lr(o.signal,n.signal)?this.timeout("download",r):new ie("download_failed",`${Vs} for GET. Underlying error: ${l}`)}if(!s.ok){let l=await Or(s);throw new ie("download_failed",`the save download answered ${s.status}. `+(s.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+l)}return new Uint8Array(await s.arrayBuffer())}catch(i){throw this.rethrow(i,n.signal,o.signal,"load",r)}finally{o.release();}}async describe(e,n={}){try{let r=await kr(this.api,this.entity.type,this.entity.id,ke(e),{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?Gr(r.body):null}catch(r){if(Dr(r))return null;throw r}}async list(e={}){let n=await bs(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}}),r=n.next_cursor;return {saves:(n.data??[]).map(Gr),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await ji(this.api,this.entity.type,this.entity.id,ke(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!Dr(r))throw r}}budget(e){return e??this.options.timeoutMs??_u}timeout(e,n){return new ie("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,o,i){return e instanceof ie?e:Lr(r,n)?this.timeout(o,i):e}};function xu(t){try{return Rr(t)}catch{return t}}function $r(t,e){let n=t??{},r=typeof n.etag=="string"?n.etag:e;return {key:typeof n.key=="string"?n.key:"",value:typeof n.value=="string"?xu(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var Mt=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await fs(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(o=>$r(o)):[]}async get(e,n={}){try{let r=await Wi(this.api,this.entity.type,this.entity.id,e,{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?$r(r.body,r.etag):null}catch(r){if(Ks(r))return null;throw r}}async put(e,n,r={}){let o=await Rs(this.api,this.entity.type,this.entity.id,e,{value:yt(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return $r(o)}async delete(e,n){try{await Fi(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});}catch(r){if(!Ks(r))throw r}}};function Ks(t){return t?.reason==="not_found"}function Ot(t,e,n={}){let r=new Ct(le,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let o=new kt(t,e,r);return {settings:new Mt(t,e),inventory:o,saves:new It(t,e,n.saves??{}),currencies:new Rt(o,n.resolveCurrencyId),mutations:new Pt(t,e,r),orders:new Et(t,e),progressions:new Tt(t,e,o)}}var Fr={type:"players",id:"me"};var Ne=t=>typeof t=="string"?t:"",ln=t=>typeof t=="number"?t:0;function Lt(t,e){let n=e??{},r=Ne(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:Ne(n.player_id),gameId:Ne(n.game_id),channel:Ne(n.channel)||"release",name:Ne(n.name),slotIndex:ln(n.slot_index),isActive:n.is_active!==false,createdAt:Ne(n.created_at),updatedAt:Ne(n.updated_at)}}var Gt=class{constructor(e,n,r,o){this.api=e;this.saves=n;this.identity=r;this.resolveCurrencyId=o;}api;saves;identity;resolveCurrencyId;scopes=new Map;scope=e=>{let n=this.scopes.get(e);return n||(n=Ot(this.api,{type:"characters",id:e},{saves:this.saves,identity:this.identity,resolveCurrencyId:this.resolveCurrencyId}),this.scopes.set(e,n)),n};async list(e){let r=(await ys(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(o=>Lt(this.scope,o)):[]}async get(e,n){let r=await Hi(this.api,e,n===void 0?{}:{signal:n});return Lt(this.scope,r)}async create(e){let n=await Gi(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return Lt(this.scope,n)}async update(e,n,r){let o=await As(this.api,e,{name:n},r===void 0?{}:{signal:r});return Lt(this.scope,o)}async delete(e,n){await Ts(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await ls(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:ln(r?.total_slots),availableSlots:ln(r?.available_slots),activeCharacterCount:ln(r?.active_character_count),defaultMaxSlots:ln(r?.default_max_slots),purchasedExtraSlots:ln(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var me=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 ge(t){return new me(t)}var Ue={toPlain(t){return me.unwrap(t)},compare(t,e,n){let r=t instanceof me?me.unwrap(t):t,o=e instanceof me?me.unwrap(e):e,i;try{i=new Intl.Collator(n);}catch{i=new Intl.Collator;}return i.compare(r,o)},equals(t,e){let n=t instanceof me?me.unwrap(t):t,r=e instanceof me?me.unwrap(e):e;return n.normalize("NFC")===r.normalize("NFC")}};var dn=t=>typeof t=="string"?t:"";function Dt(t){let e=t??{},n=typeof e.message=="string"&&e.message.length>0?e.message:void 0,r=typeof e.resolved_at=="string"?e.resolved_at:void 0;return {id:dn(e.transfer_id),status:dn(e.status),sourceEntityId:dn(e.source_entity_id),targetEntityId:dn(e.target_entity_id),...n===void 0?{}:{message:ge(n)},createdAt:dn(e.created_at),expiresAt:dn(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function Au(){return crypto.randomUUID()}var $t=class{constructor(e,n,r){this.api=e;this.self=n;this.inventory=r;}api;self;inventory;async initiate(e){this.inventory.invalidate();let n=await us(this.api,{source_entity_type:this.self.type,source_entity_id:this.self.id,target_entity_type:e.to.type,target_entity_id:e.to.id,items:(e.items??[]).map(r=>({item_definition_id:r.itemDefinitionId,quantity:r.quantity})),currencies:(e.currencies??[]).map(r=>({currency_id:r.currencyId,amount:r.amount})),...e.message===void 0?{}:{message:e.message},nonce:Au()},e.signal===void 0?{}:{signal:e.signal});return Dt(n)}async list(e={}){let r=await _s(this.api,{entity_type:this.self.type,entity_id:this.self.id,...e.direction===void 0?{}:{direction:e.direction},...e.status===void 0?{}:{status:e.status},...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit},...e.signal===void 0?{}:{signal:e.signal}})??{},o=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {transfers:Array.isArray(r.transfers)?r.transfers.map(Dt):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await ds(this.api,e,n===void 0?{}:{signal:n});return Dt(r)}async accept(e,n){return this.resolve(()=>Ii(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>xs(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>Oi(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),Dt(await e())}};var Pu=t=>typeof t=="string"?t:"",Eu=t=>typeof t=="string"&&t?t:void 0,Tu=t=>typeof t=="number"?t:void 0;function Js(t){let e=new Map(t.map(r=>[r.id,r])),n=new Map(t.filter(r=>r.slug).map(r=>[r.slug,r]));return r=>e.get(r)??n.get(r)??null}function Cu(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new de("config_malformed",`the config document is ${t===null?"null":typeof t}, expected a JSON object`);let e=t,n=l=>{let d=e[l];if(d==null)return [];if(!Array.isArray(d))throw new de("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=Tu(e.version);if(r===void 0)throw new de("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let o=(l,d,m)=>{let u=Pu(l.id);if(!u)throw new de("config_malformed",`${d}[${m}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return u},i=n("items");i.forEach((l,d)=>o(l??{},"items",d));let a=n("currencies");a.forEach((l,d)=>o(l??{},"currencies",d));let s=t;return {...s,version:r,hash:typeof s.hash=="string"?s.hash:"",items:i,currencies:a,catalogs:n("catalogs"),loot_tables:n("loot_tables"),affix_pools:n("affix_pools"),progressions:n("progressions"),game_room_templates:n("game_room_templates"),kv:typeof s.kv=="object"&&s.kv!==null&&!Array.isArray(s.kv)?s.kv:{},item:Js(i),currency:Js(a)}}var de=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},zs=10*1024*1024,Ys=15e3,Xs=new Set(["dev","test","release"]);function Iu(t){if(!Xs.has(t))throw new de("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...Xs].join(", ")}. gem-api would reject the assignment read.`);return t}var Ft=t=>typeof t=="number"?t:0,jr=t=>typeof t=="string"?t:"";function Mu(t){let e=t??{},n=Array.isArray(e.entries)?e.entries.map(r=>{let o=r??{},i=typeof o.rarity_tier=="string"?o.rarity_tier:void 0;return {entryId:jr(o.entry_id),weight:Ft(o.weight),dropRate:Ft(o.drop_rate),...i===void 0?{}:{rarityTier:i}}}):[];return {lootTableId:jr(e.loot_table_id),name:jr(e.name),rollCount:Ft(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:Ft(e.total_weight),entries:n}}var jt=class{constructor(e,n,r={}){this.api=e;this.channel=n;this.options=r;}api;channel;options;loaded=null;inFlight=null;generation=0;dropRatesByConfig=new WeakMap;load(){if(this.loaded)return Promise.resolve(this.loaded);if(this.inFlight)return this.inFlight;let e=this.generation,n=this.fetchConfig().then(r=>(this.generation===e&&(this.loaded=r),r)).finally(()=>{this.inFlight===n&&(this.inFlight=null);});return this.inFlight=n,n}refresh(){this.loaded=null,this.inFlight=null,this.generation+=1;}async dropRates(e,n){let r=await this.load();if(r===null)throw new de("config_channel_unknown",`dropRates(${e}) needs a loaded config, and this session's channel has none`);let o=this.dropRatesByConfig.get(r);o===void 0&&(o=new Map,this.dropRatesByConfig.set(r,o));let i=o.get(e);if(i!==void 0)return i;let a=(async()=>{let s=await Vi(this.api,e,n===void 0?{}:{signal:n});return Mu(s)})().catch(s=>{throw o?.get(e)===a&&o.delete(e),s});return o.set(e,a),a}async fetchConfig(){let e=AbortSignal.timeout(this.options.timeoutMs??Ys),n;try{let l=await Bi(this.api,Iu(this.channel()),{signal:e});if(!l.modified)throw new de("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");n=l.body;}catch(l){if(l instanceof de)throw l;if(l?.reason==="not_found")return null;throw l}let r=Eu(n.config_url);if(r===void 0)return null;let o=this.options.fetch??globalThis.fetch.bind(globalThis),i;try{i=await o(r,{credentials:"omit",signal:e});}catch(l){throw e.aborted?new de("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??Ys}ms`):new de("config_unreachable",`could not fetch the game config document. From a browser this is almost always the storage CORS rule: the storage account must allow this game origin for GET. It is NOT a CSP problem \u2014 game origins carry no fetch directives by design. Underlying error: ${String(l)}`)}if(!i.ok){let l=await i.text().then(d=>Mr(d)).catch(()=>"");throw new de("config_unreachable",`the config document answered ${i.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let a=await i.text();if(a.length>zs)throw new de("config_too_large",`the config document is ${a.length} bytes, over the ${zs} cap`);let s;try{s=JSON.parse(a);}catch(l){throw new de("config_malformed",`config document is not JSON: ${String(l)}`)}return Cu(s)}};var Qs=400,xe=t=>typeof t=="string"?t:"",Ou=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Be(t){let e=xe(t);if(!Ou.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var Lu=/^[0-9a-f]{1,64}$/,Gu=/^[0-9a-f]{16}$/,Du=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,$u=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function qr(t){let e=xe(t),n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!n)return;let[r,o,i]=[Number(n[1]),Number(n[2]),Number(n[3])],a=new Date(Date.UTC(r,o-1,i));return a.getUTCFullYear()===r&&a.getUTCMonth()===o-1&&a.getUTCDate()===i?e:void 0}var Fu=4096,ju=new TextEncoder;function qu(t){let e=xe(t.challenge_data),n=xe(t.challenge_data_hash);return e===""||!Gu.test(n)?{}:ju.encode(e).length>Fu?{}:{data:e,dataHash:n}}function Nu(t){let e=t??{},n=Be(e.period_start_at),r=Be(e.period_ends_at);if(n===0||r===0)return;let o=xe(e.slug),i=xe(e.seed),a=qr(e.period_local_date),s=xe(e.boundary),l=xe(e.reset_time);return {id:xe(e.progression_definition_id),...o===""?{}:{slug:o},window:xe(e.window),periodStartAt:n,periodEndsAt:r,...a===void 0?{}:{periodLocalDate:a},boundary:Du.test(s)?s:"",resetTime:$u.test(l)?l:"",seed:Lu.test(i)?i:"",...qu(e)}}function cn(t){if(t!==void 0&&(!Number.isInteger(t)||t<0||t>400))throw new TypeError(`periodsBack must be an integer between 0 and 400, got ${String(t)}`)}function qt(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(Nu).filter(n=>n!==void 0):[]}var En=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;cn(n);let r=await gs(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return qt(r)}};function He(t){return typeof t=="string"&&t!==""?t:void 0}var Zs=new Set(["localhost","127.0.0.1","[::1]"]);function Nr(t){let e=He(t);if(e===void 0)return;let n;try{n=new URL(e);}catch{return}if(!(n.username!==""||n.password!=="")&&(n.protocol==="https:"||n.protocol==="http:"&&Zs.has(n.hostname)))return e}function Uu(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},o=He(r.item_id),i=Nr(r.icon_url);o!==void 0&&i!==void 0&&e.push({itemId:o,iconUrl:i});}return e}function _e(t){let e=t??{},n=He(e.player_id),r=He(e.display_name),o=He(e.discriminator),i=He(e.display_tag),a=He(e.avatar_icon_id),s=Nr(e.avatar_icon_url);return {...n===void 0?{}:{playerId:n},...r===void 0?{}:{displayName:ge(r)},...o===void 0?{}:{discriminator:o},...i===void 0?{}:{displayTag:ge(i)},...a===void 0?{}:{avatarIconId:a},...s===void 0?{}:{avatarIconUrl:s},badges:Uu(e.badges)}}var Bu=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function Hu(t){if(t===void 0)return;let e=Nr(t);if(e===void 0)return;let n=new URL(e);return Zs.has(n.hostname)||Bu.has(n.origin)?e:void 0}var ea=100,ra=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function Ur(t){let{periodsBack:e,period:n,playerId:r}=t;if(cn(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!ra.test(n)))throw new TypeError(`period must be a period id such as 2026-10-02 (a result's period.id), got ${String(n)}`);if(r!==void 0&&(typeof r!="string"||r===""))throw new TypeError("playerId must be a player id");return {...e===void 0?{}:{periods_back:e},...n===void 0?{}:{period:n},...r===void 0?{}:{player_id:r}}}function oa(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!ra.test(e))return;let n=qr(t.period_local_date),r=Be(t.period_start_at),o=Be(t.period_ends_at),i=r>0&&o>0;return {id:e,...n===void 0?{}:{localDate:n},...i?{startAt:r,endsAt:o}:{},opensAt:Be(t.opens_at),closesAt:Be(t.closes_at),final:t.final===true}}var Tn=t=>typeof t=="string"?t:"",un=t=>typeof t=="number"?t:0,Cn=t=>typeof t=="string"?t:void 0,Vu=t=>typeof t=="number"?t:void 0,ia={player:"players",character:"characters"};function Wu(t,e){let n=t??{},r=Cn(n.entity_id),o=typeof n.entity_type=="string"&&Object.hasOwn(ia,n.entity_type)?n.entity_type:void 0,i=sa(n.stats),a=n.properties!==null&&typeof n.properties=="object"?n.properties:void 0,s=e?n.is_viewer===true:void 0;return {..._e(n),rank:un(n.rank),occurredAt:un(n.occurred_at),...s===void 0?{}:{isViewer:s},...r===void 0?{}:{entityId:r},...o===void 0?{}:{entityType:o},...i===void 0?{}:{stats:i},...a===void 0?{}:{properties:a}}}function na(t,e){let n=t??{},r=Cn(n.bucket_1),o=Cn(n.bucket_2),i=Vu(n.update_frequency_seconds),a=oa(n);return {leaderboardType:Tn(n.leaderboard_type),runType:Tn(n.run_type),...r===void 0?{}:{bucket1:r},...o===void 0?{}:{bucket2:o},entries:Array.isArray(n.entries)?n.entries.map(s=>Wu(s,e)):[],generatedAt:un(n.generated_at),...i===void 0?{}:{updateFrequencySeconds:i},...a===void 0?{}:{period:a}}}function ta(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=sa(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:un(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function sa(t){if(t===null||typeof t!="object")return;let e={};for(let[n,r]of Object.entries(t))typeof r=="number"&&(e[n]=r);return e}function Ku(t,e,n){let r=t??{},o=Cn(r.bucket_1),i=Cn(r.bucket_2),a=oa(r);return {leaderboardType:Tn(r.leaderboard_type),runType:Tn(r.run_type),entityType:e,entityId:n,...o===void 0?{}:{bucket1:o},...i===void 0?{}:{bucket2:i},entries:Array.isArray(r.entries)?r.entries.map(ta).filter(s=>s!==void 0):[],personalBest:ta(r.personal_best)??null,totalRuns:un(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:un(r.generated_at),...a===void 0?{}:{period:a}}}var In=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=Ur(n),o=await ts(this.#e,e,{...r,...n.bucket1===void 0?{}:{bucket_1:n.bucket1},...n.bucket2===void 0?{}:{bucket_2:n.bucket2},...n.signal===void 0?{}:{signal:n.signal}});return na(o,false)}async friends(e,n={}){let r=Ur(n),o=await es(this.#e,e,{...r,...n.bucket1===void 0?{}:{bucket_1:n.bucket1},...n.bucket2===void 0?{}:{bucket_2:n.bucket2},...n.signal===void 0?{}:{signal:n.signal}});return na(o,true)}async mine(e,n={}){return this.#t(e,"player","me",n)}async character(e,n,r={}){return this.#t(e,"character",n,r)}async#t(e,n,r,o){if(o.limit!==void 0){let{limit:l}=o;if(!Number.isInteger(l)||l<1||l>ea)throw new TypeError(`limit must be an integer between 1 and ${ea}, got ${String(l)}`)}let i=Ur(o),a=await zi(this.#e,e,ia[n],r,{...i,...o.bucket1===void 0?{}:{bucket_1:o.bucket1},...o.bucket2===void 0?{}:{bucket_2:o.bucket2},...o.limit===void 0?{}:{limit:o.limit},...o.signal===void 0?{}:{signal:o.signal}}),s=n==="player"&&r==="me"&&Tn((a??{}).entity_id)||r;return Ku(a,n,s)}};var Nt=t=>typeof t=="string"?t:"",Br=t=>typeof t=="number"?t:0;function aa(t){let e=t??{};return {playerId:Nt(e.player_id),key:Nt(e.key),value:e.value,updatedAt:Br(e.updated_at)}}function Ju(t){let e=t??{};return {..._e(e),playerId:Nt(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:Br(e.updated_at)}}function zu(t){return t?.reason==="not_found"}var Mn=class{constructor(e,n){this.api=e;this.selfPlayerId=n;}api;selfPlayerId;async friends(e,n={}){let o=await ns(this.api,ke(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:Nt(o.key),entries:Array.isArray(o.entries)?o.entries.map(Ju):[],generatedAt:Br(o.generated_at)}}async of(e,n,r={}){try{return aa(await as(this.api,e,ke(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(o){if(zu(o))return null;throw o}}async set(e,n,r={}){if(ke(e),n===void 0)throw new TypeError(`showcase value for ${JSON.stringify(e)} is undefined, which is not JSON. Use clear() to remove one.`);try{JSON.stringify(n);}catch(i){throw new TypeError(`showcase value for ${JSON.stringify(e)} could not be serialised to JSON: ${String(i)}.`,{cause:i})}let o=await this.selfPlayerId();return aa(await ks(this.api,o,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await qi(this.api,r,ke(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var Ve=class extends G{constructor(e,n={}){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="FriendChallengeError";for(let[r,o]of Object.entries(n))o!==void 0&&Object.assign(this,{[r]:o});}},la=t=>typeof t=="string"?t:void 0;function Yu(t){let e=t??{};return {..._e(e),playerId:la(e.player_id)??""}}function Xu(t){let e=t??{},n=e.has_more===true?la(e.next_cursor):void 0;return {friends:Array.isArray(e.data)?e.data.map(Yu):[],...n===void 0?{}:{nextCursor:n}}}var On=class{#e;#t;constructor(e,n={}){this.#e=e,this.#t=n.challenge;}async list(e={}){let n=await vs(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Xu(n)}challenge(e){return this.#t===void 0?Promise.resolve({outcome:"unavailable"}):this.#t(e)}};var Qu=0;function Ae(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++Qu)}-${String(Date.now())}-${t}`}}var Zu=12e4,da=8,em=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,nm=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Ln(t,e,n={}){return new Ve(new G("invalid",400,e,void 0,t),n)}function tm(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function rm(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!em.test(e))return {error:Ln("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!nm.test(n))return {error:Ln("unknown_template","template must be a friend_challenge_templates key from this game's config")};if(r===void 0)return {playerId:e,template:n,params:void 0};if(!tm(r))return {error:Ln("param_invalid","params must be a plain object of strings and integers")};let o={},i=Object.keys(r);for(let a of i){let s=r[a];if(typeof s=="string"||typeof s=="number"&&Number.isSafeInteger(s)){Object.defineProperty(o,a,{value:s,enumerable:true,writable:true,configurable:true});continue}return {error:Ln("param_invalid",`params.${a} must be a string or a safe integer`,{param:a})}}return i.length>da?{error:Ln("param_undeclared",`params has ${String(i.length)} keys; a template declares at most ${String(da)}`)}:{playerId:e,template:n,params:o}}function om(t){switch(t.outcome){case "accepted":case "cancelled":case "refused":case "unavailable":return {outcome:{outcome:t.outcome}};case "rate_limited":{let e=t.retryAfterMs,n=typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.ceil(e/1e3):void 0;return {error:new Ve(new G("rate_limited",429,"this player has sent too many friend challenges; only a fresh press may ask again",n,"rate_limited"))}}case "invalid":{let e=typeof t.code=="string"?t.code:void 0,n=typeof t.detail=="string"&&t.detail!==""?t.detail:e??"the friend challenge request was refused as invalid";return {error:new Ve(new G("invalid",400,n,void 0,e),{...typeof t.param=="string"?{param:t.param}:{},...typeof t.channel=="string"?{channel:t.channel}:{},...typeof t.configVersion=="number"?{configVersion:t.configVersion}:{}})}}default:return {outcome:{outcome:"unavailable"}}}}function im(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function ca(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=rm(n);if("error"in r)return Promise.reject(r.error);let o=`challenge-${Ae()}`;return new Promise((i,a)=>{let s={},l=m=>{e.delete(o)&&(t.clock.clearTimeout(s.timer),"error"in m?a(m.error):i(m.outcome));};e.set(o,l),s.timer=t.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},t.timeoutMs??Zu);let d=false;try{d=t.bridge.requestFriendChallenge(o,r.playerId,r.template,r.params);}catch{}d||l({outcome:{outcome:"unavailable"}});})},settle(n){let r=e.get(n.requestId);if(r===void 0){t.onDropped?.(`gem.friendChallengeResult (${im(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(om(n));}}}var Ut=t=>typeof t=="string"?t:void 0;function sm(t){let e=t??{},n=Ut(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Ut(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var Bt=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await ht(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let a=sm(i);a!==void 0&&o.push(a);}return o}},Hr=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function am(t){let e=t??{},n=Ut(e.currency_id);if(n===void 0||n==="")return;let r=Hr(e.limit),o=Math.min(Hr(e.earned),r),i=Math.min(Hr(e.remaining),r-o),a=e.period_days,s=typeof a=="number"&&Number.isInteger(a)&&a>=1?a:1,l=e.resets_at,d=typeof l=="number"&&Number.isFinite(l)&&l>0?Math.round(l*1e3):void 0;return {currencySlug:Ut(e.currency_slug)??"",currencyId:n,limit:r,earned:o,remaining:i,period:e.period==="day"?"day":"window",periodDays:s,...d===void 0?{}:{resetsAt:d}}}function ua(t){let e=new Set,n=r=>{t?.(`[gem] an earnAllowance 'changed' listener threw: ${r instanceof Error?r.message:String(r)}`);};return {on(r){return e.add(r),()=>{e.delete(r);}},emit(){for(let r of [...e])try{let o=r();typeof o?.then=="function"&&o.then(void 0,n);}catch(o){n(o);}}}}var Ht=class{#e;#t;#l;constructor(e,n,r){this.#e=e,this.#t=n,this.#l=r;}async get(e={}){let r=(await rs(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let a=am(i);a!==void 0&&o.push(a);}return o}on(e,n){return e!=="changed"?(this.#l?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#t?.on(n)??(()=>{})}},Gn=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new Bt(e),this.earnAllowance=new Ht(e,n,r);}};var Vr=t=>typeof t=="string"?t:"",ma=t=>typeof t=="number"?t:0;function lm(t){let e=t??{};return {key:Vr(e.key),visibility:Vr(e.visibility),value:e.value,updatedAt:ma(e.updated_at)}}function dm(t){let e=t??{};return {..._e(e),playerId:Vr(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(lm):[],generatedAt:ma(e.generated_at)}}function cm(t){return t?.reason==="not_found"}var Dn=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return dm(await os(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(cm(r))return null;throw r}}};var um=new Map([["function_error",false],["function_failed",false],["function_timeout",false],["function_not_published",false],["function_input_too_large",false],["functions_not_configured",false],["forbidden",false],["function_capacity_unavailable",true],["function_host_unreachable",true],["function_host_error",true],["rate_limited",true],["service_unavailable",true]]),$n=class extends G{constructor(e,n){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="GemFunctionError",Object.assign(this,n);}get retryable(){return (this.code===void 0?void 0:um.get(this.code))??super.retryable}},De=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=mm(e),o;try{o=await this.#e(r,n.signal===void 0?{}:{signal:n.signal});}catch(i){throw i instanceof G?gm(i):i}return pm(o)}};function mm(t){if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);let e;try{e=JSON.stringify(t);}catch(n){throw new re(`the function input could not be serialised to JSON: ${String(n)}. Pass bytes, or a value JSON can carry. This is a bug in the call, not a server failure.`)}if(e===void 0)throw new re(`the function input is ${typeof t}, which JSON cannot carry. Pass bytes \u2014 an empty Uint8Array for no input \u2014 or a JSON value. This is a bug in the call, not a server failure.`);return new TextEncoder().encode(e)}function pm(t){let{bytes:e}=t,n=()=>new TextDecoder("utf-8",{fatal:true}).decode(e);return {bytes:e,...t.invocationId===void 0?{}:{invocationId:t.invocationId},text:n,json:()=>JSON.parse(n())}}function gm(t){let{details:e,invocationId:n}=Ci(t),o=e?.untrusted?.message,i=e?.reason;return new $n(t,{...n===void 0?{}:{invocationId:n},...t.code==="function_error"&&typeof o=="string"?{functionMessage:o}:{},...t.code==="function_failed"&&typeof i=="string"?{failure:i}:{}})}var ym=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],Wr="gem_";function pa(t){return t.startsWith(Wr)}var ga=1e4,ya=50,fm=500,hm=65536-4*1024,bm=24*1024;function fa(t){let e={},n={};for(let[r,o]of Object.entries(t))typeof o=="string"?e[r]=o:typeof o=="number"&&Number.isFinite(o)&&(n[r]=o);return {dimensions:e,measures:n}}var ha=t=>typeof t=="number"?t:0,vm=t=>typeof t=="string"?t:"";function Kr(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function _m(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:ha(i.index),code:vm(i.code)}}):[];return {accepted:ha(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Jr(){let t=globalThis.crypto;return typeof t?.randomUUID=="function"?t.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.floor(Math.random()*16);return (e==="x"?n:n&3|8).toString(16)})}function wm(t){return t?.retryable===true}var Fn=class{#e;#t;#l;#y;#n=[];#f={};#i=0;#s=null;#h=false;#b=false;#v=false;#r=false;#_=null;#a=null;#d=false;#o=false;#m=false;#w=false;#S=false;constructor(e){this.#e=e,this.#t=e.options?.enabled!==false,this.#l=Math.max(ga,e.options?.flushIntervalMs??ga),this.#y=Math.max(1,Math.floor(e.options?.maxQueue??fm));}track(e,n={}){if(!(!this.#t||this.#r)){if(pa(e)){this.#S||(this.#S=true,this.#g(`[gem] analytics: '${e}' was not recorded \u2014 the gem_ prefix is reserved for the platform's own events, which the SDK emits for you. Name your event something else.`));return}this.#R(e,fa({...this.#f,...n}));}}setContext(e){this.#f={...this.#f,...e};}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#o)return Kr();let n=this.#E();if(n===null||n==="")return this.#n.length>0&&!this.#w&&(this.#w=true,this.#g("[gem] analytics: events are being recorded but no play session has been established, so nothing is being sent. Outside the arcade this is expected.")),Kr();if(this.#k(),this.#n.length===0)return Kr();let r=e.keepalive===true;this.#u();let o=this.#n.splice(0,this.#A(r)),i=this.#i;this.#i=0;let a=Math.round(this.#e.clock.now()),s={batch_id:Jr(),sent_at_ms:a,events:o.map(d=>ba(d,a))},l={client:this.#e.client(),gameId:()=>n};this.#v=true;try{let d=await cs(l,s,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=_m(d,i);return this.#P(m),m}catch(d){throw wm(d)?this.#x(o,i):this.#g(`[gem] analytics: ${o.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#v=false,this.#n.length>0&&this.#c();}}trackPlatform(e,n={}){this.#r||this.#o&&(e==="gem_pause"||e==="gem_resume")||this.#R(e,fa(n));}hold(){this.#r||this.#a!==null||(this.#o=true,this.#u());}release(){if(!this.#o||this.#r)return;this.#o=false;let e=this.#e.clock.now(),n=this.#n.map(r=>({...r,atMs:e}));this.#n=n,this.#m&&(this.#m=false,this.#a=e,this.#d=false,this.#n.unshift({uid:Jr(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#n.length>=ya?this.#p():this.#n.length>0&&this.#c();}get held(){return this.#o}startSession(){if(!(this.#r||this.#a!==null)){if(this.#o){this.#m=true;return}this.#a=this.#e.clock.now(),this.#d=false,this.trackPlatform("gem_session_start");}}endSession(e){if(this.#r||this.#d)return;if(this.#d=true,this.#o){this.#m=false,this.#n=[],this.#i=0;return}let n=this.#a;this.trackPlatform("gem_session_end",{reason:e,...n===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-n))}}),this.#p({keepalive:true});}setPaused(e){this.#r||e===this.#h||(this.#h=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#u():this.#n.length>0&&this.#c());}setHidden(e){this.#r||e===this.#b||(this.#b=e,e?this.#u():this.#n.length>0&&this.#c());}dispose(){this.#r=true,this.#u(),this.#n=[],this.#i=0;}get pending(){return this.#n.length}#R(e,n){let{dimensions:r,measures:o}=n;for(this.#k();this.#n.length>=this.#y;)this.#n.shift(),this.#i+=1;this.#n.push({uid:Jr(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:o}),this.#n.length>=ya?this.#p():this.#c();}#p(e={}){this.flush(e).catch(()=>{});}#x(e,n){for(this.#n=[...e,...this.#n],this.#i+=n;this.#n.length>this.#y;)this.#n.shift(),this.#i+=1;}#A(e){let n=e?bm:hm,r=Math.min(this.#n.length,100),o=128;for(let i=0;i<r;i+=1){let a=this.#n[i];if(a===void 0)break;if(o+=JSON.stringify(ba(a,0)).length+1,o>n)return Math.max(1,i)}return r}#c(){this.#s!==null||this.#h||this.#b||this.#o||this.#r||this.#v||(this.#s=this.#e.clock.setTimeout(()=>{this.#s=null,this.#p();},this.#l));}#u(){this.#s!==null&&(this.#e.clock.clearTimeout(this.#s),this.#s=null);}#k(){let e=this.#T();e===null||e===""||(this.#_!==null&&this.#_!==e&&(this.#n=[],this.#i=0,this.#a=null,this.#d=false),this.#_=e);}#P(e){for(let n of e.rejected)this.#g(`[gem] analytics: an event was refused (${n.code}). `+Sm(n.code));}#g(e){let n=this.#e.log;n!==null&&(n===void 0?console.warn(e):n(e));}#E(){try{return this.#e.gameId()}catch{return null}}#T(){try{return this.#e.playerId()}catch{return null}}};function ba(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:t.dimensions,measures:t.measures}}function Sm(t){switch(t){case "analytics_not_declared":return "This channel has no analytics_events section at all \u2014 promote a game config that declares one. The gem_* events in the same batch were still recorded.";case "unknown_event":return "This channel declares a set of events and this name is not in it \u2014 check the spelling, or declare it in analytics_events.";case "unknown_dimension":return "A string property on this event is not declared as one of its dimensions.";case "missing_dimension":return "A dimension this event declares was not supplied.";case "dimension_value_not_declared":return "A dimension value is outside the closed set the config declares for it.";case "unknown_measure":return "A numeric property on this event is not declared as one of its measures.";case "measure_wrong_type":return "A measure was the wrong shape \u2014 an int measure refuses a fractional value.";case "source_not_permitted":return "This event is declared for the server only, so a client may not emit it.";default:return "See the analytics_events section of your game config."}}function ue(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e}function jn(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=ue(n);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var Rm=2e3,km=5e3;function _a(t){let e=[],n=false,r=null,o=new Map,i=()=>{if(e.length>0)return Promise.resolve(e);if(n)return Promise.resolve([]);if(!t.bridge.parentSupports("clusterTarget"))return Promise.resolve([]);if(r!==null)return r.promise;let a,s=new Promise(l=>{let d=false,m=null;a=u=>{d||(d=true,r=null,t.clock.clearTimeout(m),l(u));},m=t.clock.setTimeout(()=>{n=true,a([]);},t.timeoutMs??Rm);});return r={promise:s,settle:a},s};return {resolveList:i,resolve(){return e.length>0||n||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):i().then(a=>a[0])},refresh(a){return !va(e,a)||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(s=>{let l=null,d=m=>{o.delete(d)&&(t.clock.clearTimeout(l),s(m));};o.set(d,a),l=t.clock.setTimeout(()=>d(e),t.refreshTimeoutMs??km);})},accept(a,s){let l=jn(s),d=ue(a),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[u,p]of [...o])va(m,p)||u(m);}}}}function va(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var xm=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),b=class extends Error{constructor(n,r,o){super(`${n}: ${r}`,o);this.reason=n;this.name="DedicatedServerError",this.retryable=xm.has(n),this.platformCode=o?.platformCode;}reason;retryable;platformCode};var wa=["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"],Am=new Set(wa);function $e(t){return typeof t=="string"&&Am.has(t)?t:"unknown"}var Vt="webrtc_dedicated",Qr=["universal","mobile","web"];var Pm="p2p_unavailable",Em="capacity_unavailable",Tm=2,Sa=3e4,Ra=1e3,ka=2e4;async function Zr(t){let e=ue(t.clusterTargetId),n=t.nextClusterTarget,r=0,o=t.clock??le,i=t.retry??{},a=i.budgetMs??Sa,s=i.maxDelayMs??ka,l=i.initialDelayMs??Ra,d=o.now(),m=d+a,u=0;for(;;){u++;try{let p=await ro(t.signal,"while allocating",()=>t.client.post(`${Pa(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!Cm(p)||a<=0)throw p;if(p.status===503&&p.code===Pm)throw new b("p2p_unavailable",`room ${t.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===Em?r+1:0,n!==void 0&&r>=Tm){let I=n;n=void 0;let M=ue(await I());M!==void 0&&(e=M,r=0);}let g=Math.min(s,l*2**(u-1)),f=Math.min(s,(p.retryAfterSeconds??0)*1e3),R=Math.max(g/2,f)+Math.random()*(g/2);if(o.now()+R>m)throw Im(t,p,u,o.now()-d,a);if(i.onWaiting?.({attempt:u,elapsedMs:o.now()-d,budgetMs:a,nextAttemptInMs:R,status:p.status,message:p.message}),await Wt(o,R,t.signal),t.signal?.aborted)throw Xr("while waiting to allocate")}}}function Cm(t){return t instanceof G?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function Im(t,e,n,r,o){let i=`${n} attempt${n===1?"":"s"} over ${r}ms of a ${o}ms budget`;return e.status===429?new b("start_rate_limited",`the platform was still limiting match starts for room ${t.roomId} after ${i}: ${e.message}`,{cause:e}):new b("no_server_ready",`the platform had no server ready for room ${t.roomId} after ${i}: ${e.message}`,{cause:e})}var Mm=12e4,Om=1e3;async function eo(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??Om,o=t.timeoutMs??Mm,i=e.now()+o,a=xa(t),s={seen:t.knownToExist===true};for(;;){let l=await Aa(t,a,s);if(l.outcome!==null)return l.outcome;if(e.now()+r>i)throw new b("timeout",`match ${n} was still ${l.status} after ${o}ms`);await Wt(e,r,t.signal);}}async function no(t){return (await Aa(t,xa(t),{seen:t.knownToExist===true})).outcome}function xa(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${Pa(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function Aa(t,e,n){let{matchId:r}=t,o=t.clock.now(),i;try{i=await ro(t.signal,"while polling match status",()=>t.client.get(e,t.signal));}catch(a){if(a instanceof G&&a.reason==="not_found")return {status:"not_found",outcome:n.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw a}if(n.seen=true,i.status==="ready")return {status:"ready",outcome:Lm(r,i,o)};if(i.status==="failed"){let a=i.ended_reason;return typeof a=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:$e(a)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:i.failure_reason??"unknown"}}}return {status:i.status,outcome:null}}async function to(t){let e=await ro(t.signal,"while listing cluster targets",()=>t.client.get("/v1/ping/targets",t.signal)),n=[];for(let r of e.targets??[]){let o=r?.cluster_target_id;typeof o!="string"||o.length===0||n.push({id:o,pressure:typeof r.pressure=="string"?r.pressure:"unknown"});}return n}async function ro(t,e,n){if(t?.aborted)throw Xr(e);try{return await n()}catch(r){throw t?.aborted?Xr(e,r):r}}function Xr(t,e){return new b("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function Lm(t,e,n){let r=e.join_credential,o=e.expires_in_seconds,i=typeof r=="string"&&typeof o=="number";return {status:"ready",matchId:t,protocol:e.protocol??"unknown",...i?{joinCredential:r,credentialExpiresAt:n+o*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function Pa(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function Wt(t,e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let o=()=>{t.clearTimeout(i),n?.removeEventListener("abort",o),r();},i=t.setTimeout(o,e);n?.addEventListener("abort",o);})}function Ea(t){return typeof t=="string"&&t.trim()!==""}function Kt(t,e){return Ea(t)?t.trim():Ea(e)?e:null}var Jt="0.1.0-beta",Ta="0-beta",mn="web",Gm=/^(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 Dm(t){let e=Gm.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function Ca(t,e){let n=$m(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:Jt};let o=Dm(r);if(o===null)throw new b("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 '${Jt}' for it.`);if(o!==Ta)throw new b("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${o}', and '${Ta}' 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 '${o}' 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 '${Jt}' for it.`);return {...t,platform:n,engineVersion:r}}function $m(t,e){if(t===void 0||t===mn)return mn;if(!Qr.includes(t))throw new b("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${Qr.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${mn}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${mn}' 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.`),mn}var Fm="join",jm="welcome",qm="rejected",Ia=25e3,Nm=1e3,oo=1;function io(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var Um={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 so(t){let e=typeof t=="string"?t:"unknown";return new b(Um[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function qn(t){let{channel:e,clock:n}=t;return new Promise((r,o)=>{let i=false,a=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??Ia),s=n.setTimeout(()=>w(new b("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,Nm)),l=R=>{let I=R.data;if(typeof I!="string"){u(I);return}let M;try{M=JSON.parse(I);}catch{u(I);return}if(i){u(I);return}if(M.t===jm){let _=io(M.heartbeat_interval);f({...typeof M.player_id=="string"?{playerId:M.player_id}:{},...typeof M.match_id=="string"?{matchId:M.match_id}:{},..._===void 0?{}:{heartbeatIntervalMs:_}});return}if(M.t===qm){w(so(M.reason));return}u(I);},d=()=>{w(new b("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{w(new b("aborted","the caller aborted during the join exchange"));},u=R=>{i&&t.onMessage?.(R);},p=()=>{n.clearTimeout(s),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},f=R=>{i=true,p(),t.onMessage===void 0&&g(),r({welcome:R,detach:g});},w=R=>{i||(i=true,p(),g(),o(R));};if(e.addEventListener("message",l),e.addEventListener("close",d),t.signal?.aborted){m();return}t.signal?.addEventListener("abort",m);try{e.send(JSON.stringify({t:Fm,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:oo}:{}}));}catch(R){w(new b("connection_failed",`the join frame could not be sent on the open channel: ${String(R)}`,{cause:R}));}})}var We=1,Nn=2,ao=4,uo=8,Bm=2,Hm=1e3,mo="heartbeat timeout",Un="gem-uu",zt=2,Oa="gem_transports";function pn(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!Vm(r)||e.includes(r)||e.push(r);}return e}function Vm(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function Bn(t,e){if(typeof t!="object"||t===null)return null;let n=t[Oa];if(typeof n!="object"||n===null)return null;let r=n;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 Yt(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var La=new TextEncoder,Ga=new TextDecoder;function po(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function go(t){let e=0;return t?.reliable===false&&(e|=We),t?.ordered===false&&(e|=Nn),e}function yo(t){return {reliable:(t&We)===0,ordered:(t&Nn)===0}}var fo={reliable:true,ordered:true};function Da(t){return JSON.stringify({t:"join",credential:t,wire:zt,heartbeat:oo})}function $a(t){let e;try{e=JSON.parse(t);}catch{throw new b("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let n=io(e.heartbeat_interval);return {...e.player_id===void 0?{}:{playerId:e.player_id},...e.match_id===void 0?{}:{matchId:e.match_id},...n===void 0?{}:{heartbeatIntervalMs:n}}}throw e.t==="rejected"?so(e.reason):new b("join_refused","the server answered the join out of protocol")}function Xt(){return typeof globalThis.WebTransport=="function"&&ho===null}function Qt(){return ho}var ho=null;var Ma="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Wm(t){let e=ft(t);if(e.byteLength!==32)throw new b("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var lo=class{buffered=new Uint8Array(0);push(e){let n=new Uint8Array(this.buffered.byteLength+e.byteLength);n.set(this.buffered,0),n.set(e,this.buffered.byteLength),this.buffered=n;let r=[];for(;!(this.buffered.byteLength<4);){let i=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(i===0||i>1<<20)throw new b("connection_failed",`a control-stream record claims ${i} bytes`);if(this.buffered.byteLength<4+i)break;let a=this.buffered.slice(4,4+i);this.buffered=this.buffered.slice(4+i),r.push({flags:a[0]??0,payload:a.slice(1)});}return r}};function co(t,e){let n=new Uint8Array(5+e.byteLength);return new DataView(n.buffer).setUint32(0,e.byteLength+1,true),n[4]=t,n.set(e,5),n}async function Hn(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webTransport;if(n===void 0){let s=globalThis.WebTransport;if(s===void 0)throw new b("connection_failed","this environment has no WebTransport");n=t.certHashBase64===void 0?new s(t.url):new s(t.url,{serverCertificateHashes:[{algorithm:"sha-256",value:Wm(t.certHashBase64)}]});}let r=n,o=s=>{try{r.close();}catch{}throw s},i=r.datagrams;(i?.readable===void 0||i.writable===void 0)&&(ho=Ma,o(new b("connection_failed",`${Ma}; the rung is skipped for the rest of this page (a reload probes again)`)));let a=new Promise((s,l)=>{setTimeout(()=>l(new b("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 o(new b("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(co(ao,La.encode(Da(t.credential))));let u=new lo,p=d.readable.getReader(),g;for(;g===void 0;){let f=await Promise.race([p.read(),a]);if(f.done||f.value===void 0)return o(new b("connection_failed","the control stream closed before the join was answered"));for(let w of u.push(f.value)){g=$a(Ga.decode(w.payload));break}}return {link:Km(r,m,p,u,t.log??(f=>console.warn(f)),ja(g,t.clock)),welcome:g}}catch(s){return o(s)}}function Km(t,e,n,r,o,i){let a,s,l=false,d=f=>{if(!l){l=true,m.stop();try{t.close();}catch{}s?.(f);}},m=vo(i,()=>d(mo)),u=(f,w)=>{m.heard(),(f&uo)===0&&a!==void 0&&((f&ao)!==0?a(Ga.decode(w),fo):a(w,yo(f)));};(async()=>{try{for(;;){let f=await n.read();if(f.done||f.value===void 0)break;for(let w of r.push(f.value))u(w.flags,w.payload);}}catch{}d("stream closed");})();let p,g;try{let f=t.datagrams;if(f?.readable!==void 0&&f.writable!==void 0){let w=f.readable.getReader();g=f.writable.getWriter(),p=f,(async()=>{try{for(;;){let R=await w.read();if(R.done||R.value===void 0)break;let I=R.value;I.byteLength!==0&&u((I[0]??0)|We|Nn,I.slice(1));}}catch{}})();}else o("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(f){p=void 0,g=void 0,o(`[gem] webtransport datagram lane unusable (${Yt(f)}); unreliable sends ride the stream`);}return t.closed.then(f=>d(Fa(f?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(f,w){if(l)return;if(typeof f=="string"){e.write(co(ao,La.encode(f))).catch(()=>d("write failed"));return}let R=go(w);if((R&We)!==0&&g!==void 0){let I=po(R,f),M=p?.maxDatagramSize;if(M===void 0||I.byteLength<=M){g.write(I).catch(()=>{});return}}e.write(co(R,f)).catch(()=>d("write failed"));},onMessage(f){a=f;},onClose(f){s=f;},close(){d("closed");}}}function bo(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webSocket;if(n===void 0){let o=globalThis.WebSocket;if(o===void 0)return Promise.reject(new b("connection_failed","this environment has no WebSocket"));n=new o(t.url);}let r=n;return r.binaryType="arraybuffer",new Promise((o,i)=>{let a=false,s=setTimeout(()=>{a||(a=true,r.close(),i(new b("timeout","websocket did not come up in time")));},e),l=g=>{a||(a=true,clearTimeout(s),r.close(),i(g));},d=()=>{r.send(Da(t.credential));},m=g=>{if(a)return;if(typeof g.data!="string"){l(new b("join_refused","the server sent binary before answering the join"));return}let f;try{f=$a(g.data);}catch(w){l(w);return}a=true,clearTimeout(s),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",u),r.removeEventListener("error",p),o({link:Jm(r,ja(f,t.clock)),welcome:f});},u=()=>{l(new b("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new b("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",m),r.addEventListener("close",u),r.addEventListener("error",p),r.readyState===1&&d();})}function Fa(t){return typeof t=="string"&&t.length>0?t:void 0}function ja(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function vo(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,Hm)*Bm,o=n.now(),i=null,a=()=>{i=null;let s=n.now()-o;if(s>=r){e();return}i=n.setTimeout(a,r-s);};return i=n.setTimeout(a,r),{heard:()=>{o=n.now();},stop:()=>{i!==null&&(n.clearTimeout(i),i=null);}}}function Jm(t,e){let n,r,o=false,i=s=>{if(!o){o=true,a.stop();try{t.close();}catch{}r?.(s);}},a=vo(e,()=>i(mo));return t.addEventListener("message",(s=>{if(a.heard(),typeof s.data=="string"){n?.(s.data,fo);return}let l=new Uint8Array(s.data);if(l.byteLength===0)return;let d=l[0]??0;(d&uo)===0&&n?.(l.slice(1),yo(d));})),t.addEventListener("close",(s=>i(Fa(s?.reason)??"socket closed"))),{transport:"websocket",send(s,l){if(!o){if(typeof s=="string"){t.send(s);return}t.send(po(go(l),s));}},onMessage(s){n=s;},onClose(s){r=s;},close(){i("closed");}}}function _o(t,e,n,r){let o,i,a=false,s=n,l=u=>{if(!a){a=true,d.stop();try{t.close();}catch{}try{e.close();}catch{}i?.(u);}},d=vo(r,()=>l(mo)),m=(u,p)=>{if(d.heard(),typeof u=="string"){o?.(u,fo);return}let g=new Uint8Array(u);if(g.byteLength===0)return;let f=g[0]??0;(f&uo)===0&&o?.(g.slice(1),yo(f|p));};if(t.addEventListener("message",(u=>m(u.data,0))),t.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let u=e.connectionState;(u==="failed"||u==="closed")&&l(`connection ${u}`);})),s!==void 0){let u=s;u.addEventListener("message",(p=>m(p.data,We|Nn))),u.addEventListener("close",(()=>{s=void 0;}));}return {transport:"webrtc",send(u,p){if(a)return;if(typeof u=="string"){t.send(u);return}let g=go(p),f=po(g,u);if((g&We)!==0&&s!==void 0&&s.readyState==="open"){s.send(f);return}t.send(f);},onMessage(u){o=u;},onClose(u){i=u;},close(){l("closed");}}}function Ro(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let o=wo(r);o!==void 0&&(e[n]=o);}return e}function ko(t){if(Array.isArray(t))return t.map(zm).filter(e=>!!e)}function wo(t){if(So(t)||Array.isArray(t)&&t.every(So))return t}function So(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function zm(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=wo(e.fixed),r=wo(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,...n===void 0?{}:{fixed:n},...r===void 0?{}:{default:r},...gn("description",Ym(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(So)?{allowed:e.allowed}:{},...gn("min",Vn(e.min)),...gn("max",Vn(e.max)),...gn("minItems",Vn(e.min_items)),...gn("maxItems",Vn(e.max_items)),...gn("maxLength",Vn(e.max_length))}}function Ym(t){return typeof t=="string"&&t.length>0?t:void 0}function Vn(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function gn(t,e){return e===void 0?{}:{[t]:e}}function Ee(t){let e=t??{},n=J(e.id)??J(e.game_room_id);if(n===void 0)throw new Error("[gem] a game-room response carried no id");let r=Array.isArray(e.members)?e.members.map(qa):[];return {id:n,gameId:J(e.game_id)??"",name:J(e.name)??"",status:J(e.status)??"open",hostPlayerId:J(e.host_player_id)??"",maxPlayers:Pe(e.max_players)??0,memberCount:Pe(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...we("joinCode",J(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...we("roomArgs",Ro(e.room_args)),...we("roomArgsTemplate",ko(e.room_args_template)),gameChannel:J(e.game_channel)??"release",...we("region",J(e.region)),...we("clusterTargetId",J(e.cluster_target_id)),selfHosted:e.self_hosted===true,...we("matchId",J(e.match_id)),version:Pe(e.version)??0,...we("templateId",J(e.template_id)),roomType:J(e.game_room_type)??"Standard",...we("transports",pn(e.transports)??void 0),createdAt:Pe(e.created_at)??0,updatedAt:Pe(e.updated_at)??0,...we("startedAt",Pe(e.started_at))}}function qa(t){let e=t??{};return {..._e(e),playerId:J(e.player_id)??"",isReady:e.is_ready===true,role:J(e.role)??"member",joinedAt:Pe(e.joined_at)??0,...we("groupId",J(e.group_id)),...we("platform",J(e.platform))}}function Zt(t){let e=t??{};return {id:J(e.id)??J(e.game_room_id)??"",gameId:J(e.game_id)??"",name:J(e.name)??"",status:J(e.status)??"open",hostPlayerId:J(e.host_player_id)??"",maxPlayers:Pe(e.max_players)??0,memberCount:Pe(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:J(e.game_channel)??"release",roomType:J(e.game_room_type)??"Standard",createdAt:Pe(e.created_at)??0}}function J(t){return typeof t=="string"&&t.length>0?t:void 0}function Pe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function we(t,e){return e===void 0?{}:{[t]:e}}var Wn=class{constructor(e){this.options=e;}options;list(e){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.templateSlug&&n.set("template_slug",e.templateSlug),e.limit!==void 0&&n.set("limit",String(e.limit)),e.cursor&&n.set("cursor",e.cursor);let r=n.size>0?`?${n.toString()}`:"";return this.options.client.get(`${this.baseV1()}${r}`,e.signal).then(o=>({rooms:(o.game_rooms??[]).map(Zt),...typeof o.next_cursor=="string"?{nextCursor:o.next_cursor}:{}}))}myRooms(e){return this.options.client.get(`/v1/games/${encodeURIComponent(this.options.gameId())}/players/me/game-rooms`,e).then(n=>({rooms:(n.game_rooms??[]).map(Zt)}))}create(e,n,r){return Xm(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},...er(n)},e.signal).then(Ee)}get(e,n){return this.options.client.get(this.roomV2(e),n).then(Ee)}join(e,n,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...n.partyId===void 0?{}:{party_id:n.partyId},...er(r)},n.signal).then(Ee)}joinByCode(e,n,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...n.partyId===void 0?{}:{party_id:n.partyId},...er(r)},n.signal).then(Ee)}quickJoin(e,n,r=[]){return this.options.client.post(`${this.baseV2()}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...this.asksSelfHosted(e.partyId)?{self_hosted:true}:{},...er(n)},e.signal).then(Ee)}leave(e,n,r,o=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:n},r,{keepalive:o}).then(()=>{})}asksSelfHosted(e){return e===void 0&&this.options.selfHosted?.()===true}close(e,n){return this.options.client.delete(this.roomV1(e),n).then(()=>{})}update(e,n){return this.options.client.patch(this.roomV2(e),{...n.name===void 0?{}:{name:n.name},...n.maxPlayers===void 0?{}:{max_players:n.maxPlayers},...n.isPublic===void 0?{}:{is_public:n.isPublic},...n.settings===void 0?{}:{settings:n.settings},...n.roomArgs===void 0?{}:{room_args:n.roomArgs}},n.signal).then(Ee)}setReady(e,n,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:n},r).then(Ee)}kick(e,n,r){return this.options.client.post(`${this.roomV1(e)}/kick/${encodeURIComponent(n)}`,{},r).then(()=>this.get(e,r))}transferHost(e,n,r){return this.options.client.post(`${this.roomV2(e)}/transfer/${encodeURIComponent(n)}`,{},r).then(Ee)}leaveMatch(e,n){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:n}).then(()=>{})}baseV2(){return `/v2/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}baseV1(){return `/v1/games/${encodeURIComponent(this.options.gameId())}/game-rooms`}roomV2(e){return `${this.baseV2()}/${encodeURIComponent(e)}`}roomV1(e){return `${this.baseV1()}/${encodeURIComponent(e)}`}};function er(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function Xm(t){t!==void 0&&console.warn(`[gem] createRoom: maxPlayers (${t}) 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 Kn=class{listeners=new Map;retainedMatch=null;on(e,n){let r=this.listeners.get(e);if(r||(r=new Set,this.listeners.set(e,r)),r.add(n),e==="matchReady"&&this.retainedMatch!==null){let o=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(n)&&this.retainedMatch===o&&n(o);});}return ()=>this.off(e,n)}hasListeners(e){return (this.listeners.get(e)?.size??0)>0}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...o)=>{r(),n(...o);}));return r}emit(e,...n){e==="matchReady"&&(this.retainedMatch=n[0]);let r=this.listeners.get(e);if(r)for(let o of [...r])o(...n);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};function Qm(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var Zm=1e3,ep=3e3,np=6e4,tp=2,Na=new Set(["game_room_closed","game_room_gone"]),rp=12e4,op=5e3,ip=new Set(["invalid_cluster_target","capacity_unavailable"]),sp=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function Ao(t){return new xo(t)}var xo=class{constructor(e){this.options=e;this.autoFollow=e.followMatch!==false,this.api=new Wn({client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true}),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;emitter=new Kn;api;room=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create");let n=this.clusterTargets(),r=await this.attachParty(e),o=await this.run("create",async()=>{let i=await n;return this.api.create(r,this.version("create"),i[0]).catch(async a=>{let s=await this.afterRefusedClusters(a,i);if(s[0]===void 0||s[0]===i[0])throw a;return this.api.create(r,this.version("create"),s[0])})});return this.enter(o,"created"),this.askForLocalServer(o),o}async join(e,n={}){this.assertNotInRoom("join");let r=await this.attachParty(n),o=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(o,"joined"),this.askForLocalServer(o),o}async joinByCode(e,n={}){this.assertNotInRoom("joinByCode");let r=await this.attachParty(n),o=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(o,"joined"),this.askForLocalServer(o),o}async quickJoin(e){this.assertNotInRoom("quickJoin");let n=this.clusterTargets(),r=await this.attachParty(e),o=a=>this.api.quickJoin(r,this.version("quickJoin"),a).catch(s=>this.retryPastStaleMembership(s,r,a)),i=await this.run("quickJoin",async()=>{let a=await n;return o(a).catch(async s=>{let l=await this.afterRefusedClusters(s,a);if(l.length===0||lp(l,a))throw s;return o(l)})});return this.enter(i,"joined"),this.askForLocalServer(i),i}async list(e={}){let n=await this.run("list",()=>this.api.list(e));return this.emitter.emit("listed",n),n}async myRooms(e){let n=await this.run("myRooms",()=>this.api.myRooms(e));return this.emitter.emit("mineListed",n.rooms),n.rooms}async leave(e={}){let n=this.requireRoom("leave"),r=e.keepalive===true,o=()=>this.run("leave",()=>this.api.leave(n.id,e.asGroup!==false,e.signal,r));if(r){let i=o();this.track(this.notifyLeavingMatch({keepalive:true})),await i;}else await this.notifyLeavingMatch(),await o();this.exit(),this.emitter.emit("left");}async leaveAll(e){let n=await this.myRooms(e),r=[];for(let o of n)try{await this.run("leaveAll",()=>this.api.leave(o.id,!0,e)),r.push(o.id),this.room?.id===o.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let n=this.requireRoom("close");await this.run("close",()=>this.api.close(n.id,e)),this.exit(),this.emitter.emit("closed");}async refresh(e){let n=this.room;if(!n)return null;let r;try{r=await this.track(this.api.get(n.id,e));}catch(o){if(o instanceof G&&o.reason==="not_found"){let i=this.heldMatchId;if(i!==null){let a=await this.askWhyEnded(i,e);this.endMatch(i,a??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",o),o}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let n=this.room,r=this.heldMatchId;if(!(n===null||r===null)&&!(n.status==="in_game"&&n.matchId===r)&&!(n.matchId!==void 0&&n.matchId!==r)&&this.settling!==r){this.settling=r;try{let o=await this.askWhyEnded(r,e);o!==null&&this.endMatch(r,o,n.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,n){let r=this.room;if(r===null)return null;let o=this.takeHint(e),i;try{i=await this.track(this.onceGameIdKnown(()=>no({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),...n===void 0?{}:{signal:n}})));}catch(a){return a instanceof G&&a.reason==="not_found"?o??null:(this.reportError("reconcile",a),null)}return i===null?null:i.status==="ready"?(this.seenMatches.add(e),null):i.status==="failed"?(this.settleFailed(i.matchId,i.reason),null):i.reason==="unknown"&&o!==null?o:i.reason}takeHint(e){let n=this.pendingHint;if(n===null||n.matchId!==void 0&&n.matchId!==e||(this.pendingHint=null,n.reason===void 0))return null;let r=$e(n.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 n=this.reconcileOnce().finally(()=>{this.reconciling=null,this.reconcileAgain&&(this.reconcileAgain=false,this.track(this.reconcile().catch(()=>{})));});return this.reconciling=n,this.track(n)}async reconcileOnce(){if(this.room===null){await this.reconcileSeats();return}await this.refresh().catch(()=>null);}async setReady(e,n){let r=this.requireRoom("setReady"),o=await this.run("setReady",()=>this.api.setReady(r.id,e,n));return this.apply(o),o}async kick(e,n){let r=this.requireRoom("kick"),o=await this.run("kick",()=>this.api.kick(r.id,e,n));return this.apply(o),o}async transferHost(e,n){let r=this.requireRoom("transferHost"),o=await this.run("transferHost",()=>this.api.transferHost(r.id,e,n));return this.apply(o),o}async update(e){let n=this.requireRoom("update"),r=await this.run("update",()=>this.api.update(n.id,e));return this.apply(r),r}startMatch(e={}){return this.requestStart(e,true)}async requestStart(e,n){let r=this.requireRoom("startMatch");if(!this.isHost)throw new b("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,n)}finally{this.startsInFlight--;}}async startIn(e,n,r){let o=ue(n.clusterTargetId),i=o??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),a=i??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let s=(m,u)=>Zr({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...o===void 0?{nextClusterTarget:()=>this.nextCluster(u)}:{},retry:{...n.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),n.retry?.onWaiting?.(p);}},...n.signal===void 0?{}:{signal:n.signal}}),l=()=>s(i,[a]).catch(async m=>{if(o!==void 0||!Ba(m))throw m;let u=await this.nextCluster([a],true);if(u===void 0)throw m;return s(u,[a,u])}),d=await(r?this.run("startMatch",l):this.track(this.onceGameIdKnown(l)));return this.beginMatch(d.matchId),d}async awaitMatch(e={}){if(this.session.phase==="suspended")throw new b("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 n=this.emitter.retained;return n!==null&&this.session.phase==="ready"?n:this.pollMatchStatus(e)}async pollMatchStatus(e={}){let n=this.requireRoom("pollMatchStatus"),r=await this.matchIdOrWait(e),o=await this.run("pollMatchStatus",()=>this.chase(n.id,r,e));return this.settleOutcome(o)}chase(e,n,r){return eo({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e,matchId:n,version:this.version("pollMatchStatus"),knownToExist:this.seenMatches.has(n),...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 b("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!Na.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new b("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,n){this.heldMatchId===e&&(this.abandonReconnect(e,n),this.emitter.emit("matchFailed",e,n),this.abortFollow(),this.refusedMatches.add(e),this.session={phase:"none"},this.emitter.clearRetained());}endMatch(e,n,r){this.heldMatchId===e&&(this.abortFollow(),this.session={phase:"ended",matchId:e,reason:n,roomReopened:r},this.emitter.clearRetained(),this.emitter.emit("matchEnded",{matchId:e,reason:n,roomReopened:r}),this.abandonReconnect(e,n));}armReconnect(e,n){let r=this.options.autoReconnect;if(r===void 0||r.attempts<=0||r.budgetMs<=0)return;if(this.finishReconnect(),n==="kicked"){r.abandon(e,n);return}let o={matchId:e,cause:n,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=o,this.track(this.reconnectStep(o));}park(e,n){e.parkedAt=this.options.clock.now(),e.parked=()=>(e.parkedAt!==null&&(e.deadlineAt+=this.options.clock.now()-e.parkedAt,e.parkedAt=null),n());}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,n){let r=this.reconnect;r===null||r.matchId!==e||(this.finishReconnect(),this.options.autoReconnect?.abandon(e,n));}async reconnectStep(e){if(!this.reconnecting(e))return;if(!Ke()){this.park(e,()=>this.reconnectStep(e));return}let n=this.options.autoReconnect;if(n===void 0||e.attempt===0&&(await this.reconcile().catch(()=>{}),!this.reconnecting(e)))return;let r=e.deadlineAt-this.options.clock.now();if(e.attempt>=n.attempts||r<Zm){this.abandonReconnect(e.matchId,e.cause);return}e.attempt+=1,this.emitter.emit("matchReconnecting",{matchId:e.matchId,attempt:e.attempt,attempts:n.attempts,remainingMs:r}),e.timer=this.options.clock.setTimeout(()=>{e.timer=null,this.track(this.reconnectAttempt(e));},Math.min(Qm(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!Ke()){this.park(e,()=>this.reconnectAttempt(e));return}let n=this.options.autoReconnect,r=this.room;if(n===void 0||r===null)return;let o=null;try{o=await this.track(this.onceGameIdKnown(()=>no({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(i){this.reportError("reconcile",i);}if(this.reconnecting(e)){if(o?.status==="ended"){this.endMatch(o.matchId,o.reason,!Na.has(o.reason)),this.track(this.reconcile().catch(()=>{}));return}if(o?.status==="failed"){this.abandonReconnect(e.matchId,o.reason),this.settleFailed(o.matchId,o.reason);return}if(o?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(o);let i;try{i=await n.redial(e.matchId,e.deadlineAt);}catch(a){this.reportError("reconcile",a),i="failed";}if(e.done||this.reconnect!==e)return;if(i==="closed"){this.finishReconnect();return}if(i==="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 n=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})):n&&this.emitter.emit("matchReconnected",{matchId:e,attempt:0});}async notifyMatchDisconnected(e="link_closed"){if(this.session.phase!=="ready"&&this.session.phase!=="connected")throw new b("misconfigured",`no match is connected, so there is nothing to suspend (state '${this.matchConnectionState}').`);let n=this.session.matchId;this.session={phase:"suspended",matchId:n,reason:e},this.emitter.emit("matchSuspended",{matchId:n,cause:e}),this.armReconnect(n,e);}async reconnectToMatch(e={}){if(this.session.phase!=="suspended")throw new b("misconfigured",`reconnectToMatch expects a suspended match; this one is '${this.matchConnectionState}'. Call notifyMatchDisconnected() when the transport drops.`);let n=this.heldMatchId;if(n===null)throw new b("misconfigured","there is no match to reconnect to.");return this.finishReconnect(),this.session={phase:"starting",matchId:n},this.emitter.clearRetained(),this.pollMatchStatus(e)}async notifyLeavingMatch(e={}){let n=this.heldMatchId;if(n!==null)try{await this.api.leaveMatch(n,e.keepalive??!1);}catch{}}get gameId(){let e=typeof this.options.gameId=="function"?this.options.gameId():this.options.gameId;return e===""?null:e}get currentRoom(){return this.room}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}on(e,n){let r=this.emitter.on(e,n);return e==="seated"&&(this.retuneSeatWatch(),this.room===null&&this.track(this.reconcileSeats().catch(()=>{}))),r}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}handleRoomEvent(e){if(this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let n=e.event==="updated"&&e.reason!==void 0?{...e.matchId===void 0?{}:{matchId:e.matchId},reason:e.reason}:void 0;this.track(this.reconcile(n).catch(()=>{}));}handleAutoStartFailed(e,n){if(this.disposed||this.room?.id!==e)return;let r=this.answerAutoStart(n);if(this.emitter.emit("matchAutoStartFailed",{roomId:e,code:n,handled:r!=="leave"}),r!=="start"||this.startsInFlight>0||this.room?.id!==e)return;this.autoStartRetried=true;let o=new AbortController;this.autoStartRetry=o,this.track(this.requestStart({signal:o.signal},false).then(()=>{},i=>{o.signal.aborted||this.reportError("startMatch",i);}).finally(()=>{this.autoStartRetry===o&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!ip.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){this.disposed||!this.watchingSeats||this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}async reconcileSeats(){if(this.disposed||!this.watchingSeats)return;let e;try{e=await this.myRooms();}catch{return}let n=new Set;for(let r of e)r.status!=="closed"&&(n.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])n.has(r)||this.reported.delete(r);}async reportSeat(e){let n=this.playerId(),r=await this.run("handleSeated",()=>this.api.get(e));this.disposed||n===null||!r.members.some(o=>o.playerId===n)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.seatPollMs>0&&Ke())){this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null);return}if(this.seatPollHandle!==null)return;let n=()=>{this.seatPollHandle=null,this.track(this.reconcileSeats().catch(()=>{}).then(()=>this.retuneSeatWatch()));};this.seatPollHandle=this.options.clock.setTimeout(n,this.seatPollMs);}installResumeWatch(){let e=globalThis;if(typeof e.addEventListener!="function")return;this.visibilityListener=()=>{if(!this.disposed&&(this.retuneSeatWatch(),!!Ke())){if(this.room!==null){let r=this.reconnect?.parked??null;r!==null&&this.reconnect!==null?(this.reconnect.parked=null,this.track(r())):this.track(this.reconcile().catch(()=>{}));return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of nr)e.addEventListener(r,this.visibilityListener);let n=globalThis.document;typeof n?.addEventListener=="function"&&n.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 n=this.inFlight;this.inFlight=[],await Promise.allSettled(n);}}dispose(){if(this.disposed=true,this.abortAutoStartRetry(),this.finishReconnect(),this.stopPolling(),this.emitter.clear(),this.unloadListener&&(globalThis.removeEventListener?.("pagehide",this.unloadListener),this.unloadListener=null),this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null),this.visibilityListener){let e=globalThis;for(let r of nr)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??op}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new b("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 n=this.options.clientVersion,r=Kt(this.options.platformGameVersion?.(),n?.gameVersion);if(r===null)throw new b("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 Ca({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return jn(await this.options.resolveClusterTargets());let e=ue(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !Ba(e)||n.length===0?[]:jn(await this.options.refreshClusterTargets?.(n)??[])}async nextCluster(e,n=false){let r=a=>a.find(s=>!e.includes(s)),o=await this.clusterTargets(),i=r(o);return i!==void 0||!n?i:r(jn(await this.options.refreshClusterTargets?.(o)??[]))}async attachParty(e){if(e.partyId!==void 0)return e;let n=this.options.resolveParty;if(n===void 0)return e;let r=await n();return r===void 0?e:{...e,partyId:r}}async retryPastStaleMembership(e,n,r){if(!(e instanceof G)||e.reason!=="conflict"||!sp.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new G(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 o;try{o=await this.leaveAll(n.signal);}catch{throw new G(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(o.length===0)throw new G(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(n,this.version("quickJoin"),r)}assertNotInRoom(e){if(this.room!==null)throw new b("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}requireRoom(e){if(this.room===null)throw new b("misconfigured",`${e} refused: not in a room.`);return this.room}async run(e,n){try{return await this.track(this.onceGameIdKnown(n))}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,n){let r=n instanceof G?{operation:e,code:n.status,reason:n.reason,message:n.message,retryable:n.retryable}:{operation:e,code:0,reason:n instanceof b?n.reason:"unavailable",message:n instanceof Error?n.message:String(n),retryable:false};this.emitter.emit("error",r);}askForLocalServer(e){let n=this.options.ensureLocalServer;n===void 0||!e.selfHosted||e.status!=="open"||n(e.id).catch(()=>{});}track(e){return this.inFlight.push(e),e}enter(e,n){this.room=e,this.abortFollow(),this.autoStartRetried=false,this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(n,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 n=this.room;if(n===null||n.id!==e.id)return;let r=new Map(n.members.map(s=>[s.playerId,s])),o=new Map(e.members.map(s=>[s.playerId,s])),i=this.playerId();for(let s of o.keys())r.has(s)||this.emitter.emit("memberJoined",s);for(let s of r.keys())if(!o.has(s)){if(s===i){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",s);}for(let[s,l]of o){let d=r.get(s);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",s,l.isReady);}n.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let a=ap(n,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 n=this.heldMatchId;n!==null&&n!==e&&this.endMatch(n,"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,n=this.heldMatchId;if(e===null||n===null||this.followAbort!==null&&this.followingMatchId===n)return;this.abortFollow();let r=new AbortController;this.followAbort=r,this.followingMatchId=n,this.track(this.onceGameIdKnown(()=>this.chase(e.id,n,{signal:r.signal})).then(o=>{if(!r.signal.aborted)try{this.settleOutcome(o);}catch{}}).catch(o=>{r.signal.aborted||this.reportError("pollMatchStatus",o);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let n=this.heldMatchId;if(n!==null)return Promise.resolve(n);let r=e.timeoutMs??rp;return new Promise((o,i)=>{let a=u=>{s(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),u();},s=this.emitter.on("matchAllocationStarted",u=>a(()=>o(u))),l=this.emitter.on("matchFailed",(u,p)=>a(()=>i(new b("allocation_failed",`match ${u} did not come up: ${p}`)))),d=()=>a(()=>i(new b("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>a(()=>i(new b("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??ep}pushedInterval(){return this.options.pushedPollIntervalMs??np}pushed(){return this.options.clock.now()-this.lastPushAt<tp*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=n=>{n?.persisted!==true&&this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{}));},e.addEventListener("pagehide",this.unloadListener));}};function Ke(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var nr=["visibilitychange","focus","pageshow","online"];function ap(t,e){return t.version!==e.version||t.status!==e.status||t.matchId!==e.matchId||t.hostPlayerId!==e.hostPlayerId||t.name!==e.name||t.maxPlayers!==e.maxPlayers||t.isPublic!==e.isPublic||Ua(t)!==Ua(e)}function Ua(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function Ba(t){return t instanceof G&&t.code==="invalid_cluster_target"}function lp(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var dp=["p2p","dedicated","unknown"],Po=["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 yn=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let o=cp(e,this.options.transport,(this.options.now??Date.now)());o.length!==0&&await this.options.client.post(`/v1/games/${encodeURIComponent(r)}/telemetry/p2p`,{events:o},n);}report(e){this.post(e).catch(()=>{});}};function cp(t,e,n){let r=Math.floor(n/1e3);return t.filter(o=>Po.includes(o.type)).slice(0,100).map(o=>{let i=up(o.transport??e);return {event_type:o.type,timestamp:r,...i===void 0?{}:{transport:i},data:o.value===void 0?{}:{value:o.value}}})}function up(t){if(t!==void 0)return dp.includes(t)?t:"unknown"}var Jn=class{constructor(e){this.options=e;this.reporter=new yn({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,n,r){let o=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:n},r);return {credential:tr(o.credential)??"",hostFingerprint:tr(o.host_fingerprint)??"",hostEpoch:rr(o.host_epoch)??0,expiresAt:(rr(o.expires_at)??0)*1e3}}async turnLease(e,n,r){let o=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:n},r),i=[];for(let l of Array.isArray(o.ice_servers)?o.ice_servers:[]){let d=l,m=(Array.isArray(d.urls)?d.urls:[]).filter(u=>typeof u=="string"&&u.length>0);m.length!==0&&i.push({urls:m,username:tr(d.username)??"",credential:tr(d.credential)??""});}let a=rr(o.expires_at),s=rr(o.ttl_seconds);return {iceServers:i,expiresAt:a!==void 0?a*1e3:Date.now()+(s??0)*1e3}}async kick(e,n,r){await this.options.client.post(`${this.match(e)}/kick`,{player_id:n},r);}async leave(e,n=false){await this.options.client.post(`${this.match(e)}/leave`,{},void 0,{keepalive:n});}async telemetry(e,n){await this.reporter.post(e,n);}match(e){return `/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}`}};function tr(t){return typeof t=="string"&&t.length>0?t:void 0}function rr(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}var mp=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),L=class extends Error{constructor(n,r,o){super(`${n}: ${r}`,o);this.reason=n;this.name="P2pError",this.retryable=mp.has(n);}reason;retryable};var Ha=10240,Va=2048,pp=new TextEncoder;function Wa(t){return pp.encode(t).length}function Fe(t,e){let n=o=>{throw new b("invalid_sdp",`the ${e} ${o}`)},r=Wa(t);r>=Ha&&n(`is ${r} bytes, over the ${Ha} limit`+(e==="offer"?", which for an offer means an unusually wide candidate list":"")),t.startsWith("v=")||n("does not start with 'v=', so it is not SDP"),t.includes("\0")&&n("contains a null byte"),/\r(?!\n)/.test(t)&&n("contains a bare carriage return");for(let o of t.split(/\r\n|\n/)){let i=Wa(o);i>Va&&n(`has a ${i}-byte line, over the ${Va} limit`);}}function or(t){for(let e of t.split(/\r\n|\n/)){if(!e.startsWith("m="))continue;let[n,r="0"]=e.slice(2).trim().split(/\s+/);if(!(n!=="audio"&&n!=="video")&&r.split("/")[0]!=="0")return true}return false}var ir=class{listeners=new Map;on(e,n){let r=this.listeners.get(e);return r||(r=new Set,this.listeners.set(e,r)),r.add(n),()=>this.off(e,n)}off(e,n){this.listeners.get(e)?.delete(n);}once(e,n){let r=this.on(e,((...o)=>{r(),n(...o);}));return r}emit(e,...n){let r=this.listeners.get(e);if(r)for(let o of [...r])o(...n);}clear(){this.listeners.clear();}};var gp=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function fn(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=sr(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function sr(t){let[e,...n]=t.trim().split(/\s+/);if(e===void 0||n.length===0)return null;let r=`${e.toLowerCase()} ${n.join("").toUpperCase()}`;return gp.test(r)?r:null}function zn(t,e){if(t.length!==e.length)return false;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}var Eo=5e3,yp=12e4+Eo,fp=1024,hp=6e4,bp=1e4,Ka=64*1024,Ja=5;function To(t){let e=new Map,n=-1/0,r=null,o=(()=>{let s;try{s=new URL(`${t.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}`}})(),i=()=>{let s=t.subtle??globalThis.crypto?.subtle;if(!s)throw new L("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(!o.ok)throw new L("keys_unavailable",o.reason);let s=t.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await s(o.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(bp)});}catch{throw new L("keys_unavailable",`the JWKS endpoint at ${o.shown} could not be reached \u2014 it timed out, refused a redirect, or the network failed.`)}if(!l.ok)throw new L("keys_unavailable",`the JWKS endpoint answered ${o.shown} with an error`);let d;try{let p=await l.text();if(p.length>Ka)throw new L("keys_unavailable",`the JWKS endpoint at ${o.shown} answered with more than ${Ka} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof L?p:new L("keys_unavailable",`the JWKS endpoint at ${o.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>Ja)throw new L("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${Ja} the platform declares. Refusing rather than verifying against a set of unknown size.`);let u=i();for(let p of m){let g=p;if(g.kty==="RSA"&&!(g.alg!==void 0&&g.alg!=="RS256")&&!(g.use!==void 0&&g.use!=="sig")&&!(typeof g.kid!="string"||g.kid.length===0))try{let f=await u.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(g.kid,f);}catch{}}};return {async key(s){let l=e.get(s);if(l)return l;if(!o.ok)throw new L("keys_unavailable",o.reason);if(r)return await r,e.get(s)??null;let d=t.now();if(!Number.isFinite(d))throw new L("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<n&&(n=-1/0),d-n<hp?null:(n=d,r??=a().finally(()=>{r=null;}),await r,e.get(s)??null)}}}var Yn=class{seen=new Map;admit(e,n){for(let[r,o]of this.seen)o<=n&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=fp){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+yp),true}};function Ya(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(n.length);for(let o=0;o<n.length;o++)r[o]=n.charCodeAt(o);return r}function za(t){try{let e=new TextDecoder().decode(Ya(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function Co(t,e,n,r,o){let i=D=>{throw new L("peer_unauthenticated",`the peer's join credential is not usable: ${D}`)},a=t.split(".");a.length!==3&&i("it is not a three-part JWT");let[s,l,d]=a,m=za(s);m===null&&i("its header does not decode"),m.alg!=="RS256"&&i(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&i(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let u=m.kid;(typeof u!="string"||u.length===0)&&i("it names no key");let p=await n.key(u);p===null&&i("it was signed by a key this build cannot resolve");let g=o.subtle??globalThis.crypto?.subtle;g||i("this environment has no WebCrypto");let f=new TextEncoder().encode(`${s}.${l}`),w;try{w=Ya(d);}catch{i("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,w,f)||i("its signature does not verify");let I=za(l);I===null&&i("its payload does not decode");let M=I,_=D=>typeof M[D]=="string"?M[D]:"",S=D=>typeof M[D]=="number"&&Number.isFinite(M[D])?M[D]:NaN;_("iss")!==o.issuer&&i("it was issued by someone else"),_("aud")!==`${o.issuer}/p2p-match`&&i("its audience is not this platform"),_("match_id")!==e.matchId&&i("it is for another match"),_("game_id")!==e.gameId&&i("it is for another game");let E=S("exp")*1e3,A=S("nbf")*1e3;(!Number.isFinite(E)||e.now>E+Eo)&&i("it has expired"),Number.isFinite(A)&&e.now<A-Eo&&i("it is not valid yet");let V=_("role");V!=="host"&&V!=="client"&&i("it names no usable role");let N=S("host_epoch");N!==e.hostEpoch&&i("it names a different host epoch");let q=sr(_("fingerprint"));q===null&&i("its fingerprint claim is malformed"),zn(q,e.peerFingerprint)||i("it was issued for a different certificate than this connection used");let k=sr(_("host_fingerprint"));k===null&&i("its host fingerprint claim is malformed"),zn(k,e.hostFingerprint)||i("it was issued against a different host certificate");let C=_("jti");C.length===0&&i("it carries no jti, so replay cannot be detected"),r.admit(C,e.now)||i("it has already been used");let O=_("sub");return O.length===0&&i("it names no player"),{playerId:O.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:N,role:V,fingerprint:q,hostFingerprint:k,jti:C,expiresAt:E}}function Io(t){let e=new TextEncoder().encode(t.jwt);if(e.length>8192)throw new Error(`[gem] a join credential of ${e.length} bytes exceeds the wire format's cap`);let n=new ArrayBuffer(3+e.length+4+4),r=new DataView(n);return r.setUint8(0,1),r.setUint16(1,e.length,true),new Uint8Array(n,3,e.length).set(e),r.setUint32(3+e.length,t.protocolVersion,true),r.setUint32(7+e.length,t.assignedPeerId,true),n}function Mo(t){let e=new ArrayBuffer(9),n=new DataView(e);return n.setUint8(0,2),n.setUint32(1,t.protocolVersion,true),n.setUint32(5,t.assignedPeerId,true),e}function Oo(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function Lo(t){if(t.byteLength<1)return null;let e=new DataView(t);switch(e.getUint8(0)){case 1:{if(t.byteLength<3)return null;let n=e.getUint16(1,true);return n>8192||t.byteLength<3+n+8?null:{kind:"join",jwt:new TextDecoder().decode(new Uint8Array(t,3,n)),protocolVersion:e.getUint32(3+n,true),assignedPeerId:e.getUint32(7+n,true)}}case 2:return t.byteLength<9?null:{kind:"admit",protocolVersion:e.getUint32(1,true),assignedPeerId:e.getUint32(5,true)};case 3:return t.byteLength<2?null:{kind:"reject",reason:e.getUint8(1)};default:return null}}function Xa(t){switch(t){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 (${t})`}}function Qa(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var Xn=class{constructor(e,n,r){this.localPlayerId=e;this.hostPlayerId=n,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,n){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=n,this.state=this.isLocalHost?"preparing":"reconnecting",{kind:"accepted",state:this.state})}complete(){this.state="idle";}};var Go={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}},Ie=["reliable","ordered","unreliable"];function Do(t){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:t.iceServers,...t.certificates===void 0?{}:{certificates:t.certificates}})}async function Qn(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var el=1,Rp=3e4,nl=2e3,kp=5e3,tl=6e4,xp=8,Fo=class{constructor(e=xp){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 n=0;for(let r of this.sent)r<=e&&e-r<6e4&&(this.sent[n++]=r);this.sent.length=n;}},Ap=new Fo,Pp=8,Ep=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),et=class{constructor(e){this.options=e;this.keys=e.keys??To({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new ir;links=new Map;replays=new Yn;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=el+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 n of this.links.values())n.admitted&&e.push(this.expose(n));return e}peer(e){let n=this.links.get(e);return n&&n.admitted?this.expose(n):null}on(e,n){return this.emitter.on(e,n)}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}async start(e){let n=this.options.connectTimeoutMs??Rp;this.credentialDeadline=this.options.clock.now()+n;let r=new Promise((s,l)=>{this.ready={resolve:s,reject:l};}),o=ue(this.options.clusterTargetId);if(o!==void 0)try{let s=await this.options.api.turnLease(this.options.matchId,o,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: ${$o(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 i=this.options.clock.setTimeout(()=>{this.fail(new L("timeout",`no usable P2P connection after ${n}ms. The parent relays signaling, so a silent failure here usually means the page is not putting frames on the socket.`));},n),a=()=>this.fail(new L("aborted","the caller aborted while connecting"));e?.aborted?a():e?.addEventListener("abort",a);try{await r;}finally{this.options.clock.clearTimeout(i),e?.removeEventListener("abort",a),this.ready=null;}}async kick(e){if(!this.isHost)throw new L("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,n){this.closed||this.route(e,n).catch(r=>this.report_(r));}async route(e,n){switch(e){case "hello":return this.onHello(n);case "offer":return this.onOffer(n);case "answer":return this.onAnswer(n);case "ice":return this.onIce(n);case "peerLeft":return this.onPeerLeft(n);case "migration":return this.onMigration(n);case "matchEnded":return this.onMatchEnded(n);case "error":return this.onSignalingError(n);default:return}}async onHello(e){let n=se(e.playerId),r=se(e.hostPlayerId),o=ar(e.hostEpoch);if(!(n===null||r===null||o===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new Xn(n,r,o)),!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 n of e)try{await this.onOffer(n);}catch(r){this.report_(r);}}async offerToHost(e){let n=this.hostPlayerId,r=this.openLink(n,el),o=await r.connection.createOffer();await r.connection.setLocalDescription(o);let i=r.connection.localDescription?.sdp??o.sdp;if(!i)throw new L("invalid_sdp","the browser produced an offer with no SDP");Fe(i,"offer"),this.refuseMedia(i,"offer"),this.options.signaling.offer(i,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,o=r===void 0?null:fn(r);if(o===null)throw new L("invalid_sdp","this browser produced an offer with no usable DTLS fingerprint, so the platform cannot bind a credential to it");let i=this.options.credentialPacing??Ap,a=()=>this.closed||e!==this.credentialGeneration,s=kp;for(;;){let l=i.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,a))return;i.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,o);if(a())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(a())return;let m=d.status,u;if(m===409)u=nl;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?u=p*1e3:(u=s,s=Math.min(s*2,tl)),u=Math.min(Math.max(u,nl),tl);}else throw d;if(!await this.waitForCredential(u,a))return}}}async waitForCredential(e,n){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!n())}async onOffer(e){let n=se(e.fromPlayerId),r=se(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=Pp){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(n,e);return}if(!this.isHost||this.migration.isKicked(n)===true)return;let o=se(e.sessionId);if(o!==null&&this.answeredSessions.get(n)===o)return;Fe(r,"offer"),this.refuseMedia(r,"offer");let i=fn(r);if(i===null)throw new L("invalid_sdp",`the offer from ${n} carries no usable fingerprint`);this.mark("offer received"),o!==null&&this.answeredSessions.set(n,o);let a=this.links.get(n);a&&this.dropLink(a,"resignalled",false);let s=this.openLink(n,this.nextPeerId++);s.remoteFingerprint=i,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 L("invalid_sdp","the browser produced an answer with no SDP");Fe(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(n,d,s.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let n=se(e.fromPlayerId),r=se(e.sdp);if(n===null||r===null)return;let o=this.links.get(this.hostPlayerId);if(!o||n!==this.hostPlayerId)return;Fe(r,"answer"),this.refuseMedia(r,"answer");let i=fn(r);if(i===null)throw new L("invalid_sdp","the host's answer carries no usable fingerprint");this.mark("answer received"),o.remoteFingerprint=i,o.pendingAnswer=r,this.hostVerified(o)&&await this.applyAnswer(o,r);}hostVerified(e){let n=this.credential;return n===null||e.remoteFingerprint===null?false:zn(n.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new L("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 n=e.pendingAnswer;n!==void 0&&this.hostVerified(e)&&this.applyAnswer(e,n).catch(r=>this.report_(r));}async applyAnswer(e,n){this.mark("host verified"),e.pendingAnswer=void 0,await e.connection.setRemoteDescription({type:"answer",sdp:n}),this.flushCandidates(e);}async onIce(e){let n=se(e.fromPlayerId),r=se(e.candidate);if(n===null||r===null)return;let o=this.links.get(n);if(!o)return;let i=se(e.sdpMid),a=ar(e.sdpMLineIndex)??ar(e.sdpMLineIndexAlt),s={candidate:r,...i===null?{}:{sdpMid:i},...a===null?{}:{sdpMLineIndex:a}};if(o.connection.remoteDescription===null){o.pendingCandidates.length<64&&o.pendingCandidates.push(s);return}await o.connection.addIceCandidate(s);}onPeerLeft(e){let n=se(e.playerId);if(n===null)return;let r=se(e.reason)??"left";if(n===this.localPlayerId){this.fail(new L("kicked",`this player was removed from the match (${r})`)),this.close();return}let o=this.links.get(n);o&&this.dropLink(o,r,true);}async onMigration(e){let n=se(e.hostPlayerId),r=ar(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let o=this.migration.apply({hostPlayerId:n,hostEpoch:r,...se(e.reason)===null?{}:{reason:se(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(i=>typeof i=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(o.kind!=="duplicate"){if(o.kind==="completed"){this.emitter.emit("hostChanged",n,r);return}if(o.kind==="refused"){this.report_(new L("migration_failed",o.why));return}for(let i of [...this.links.values()])this.dropLink(i,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",n,r),o.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 L("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 n=se(e.reason)??"ended";this.ended=n,this.emitter.emit("matchEnded",n),this.ready!==null&&this.fail(new L("match_ended",`the match ended: ${n}`)),this.close();}onSignalingError(e){let n=se(e.code)??"unknown",r=se(e.message)??"the platform refused a signaling message";this.report_(new L("signaling_failed",`${n}: ${r}`));}openLink(e,n){let o=(this.options.peerConnectionFactory??Do)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),i={};for(let p of Ie){let g=o.createDataChannel(p,Go[p]);g.binaryType="arraybuffer",i[p]=g;}let a={playerId:e,assignedPeerId:n,connection:o,channels:i,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},s=p=>{let g=p.candidate;g?.candidate&&this.options.signaling.candidate(e,g.candidate,g.sdpMid??void 0,g.sdpMLineIndex??void 0);},l=()=>this.onIceState(a),d=()=>this.onConnectionState(a),m=p=>{this.onHandshakeMessage(a,p.data).catch(g=>this.report_(g));},u=()=>{this.onReliableOpen(a).catch(p=>this.report_(p));};return o.addEventListener("icecandidate",s),o.addEventListener("iceconnectionstatechange",l),o.addEventListener("connectionstatechange",d),i.reliable.addEventListener("open",u),i.reliable.addEventListener("message",m),a.detachHandshake=()=>{i.reliable.removeEventListener("open",u),i.reliable.removeEventListener("message",m);},a.detachAll=()=>{a.detachHandshake(),o.removeEventListener("icecandidate",s),o.removeEventListener("iceconnectionstatechange",l),o.removeEventListener("connectionstatechange",d);},this.links.set(e,a),a}flushCandidates(e){let n=e.pendingCandidates;e.pendingCandidates=[];for(let r of n)e.connection.addIceCandidate(r).catch(()=>{});}async onReliableOpen(e){if(this.mark("channel open"),this.isHost)return;let n=this.credential;if(n===null)throw new L("peer_unauthenticated","the channel opened before the platform issued a join credential, so there is nothing to present");if(this.options.clock.now()>=n.expiresAt)throw new L("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(Io({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=Lo(n);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 L(Qa(r.reason),Xa(r.reason))),this.dropLink(e,"rejected",false));}}async admit(e,n,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 o=fn(e.connection.localDescription?.sdp??"");if(o===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 i;try{i=await Co(n,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:o,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(a){let s=a instanceof L&&a.reason==="keys_unavailable";this.refuseLink(e,s?131:1,s?"keys_unavailable":"credential_invalid",$o(a)),s&&this.fail(a);return}if(i.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${i.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(i.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(Mo({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,n,r,o){this.warn(`refused to admit ${e.playerId}: ${o}`);try{e.channels.reliable.send(Oo(n));}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 n=e.connection.iceConnectionState;if(!(n!=="failed"&&n!=="disconnected"&&n!=="closed")){if(this.isHost){(n==="failed"||n==="closed")&&this.dropLink(e,n,true);return}if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,n);}catch(r){this.report_(r);}}}}onConnectionState(e){let n=e.connection.connectionState;n!=="failed"&&n!=="closed"||this.dropLink(e,n,true);}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(n,r="reliable")=>e.channels[r].send(n)}}dropLink(e,n,r){this.links.delete(e.playerId),e.detachAll();for(let o of Ie)rl(e.channels[o]);rl(e.connection),r&&e.admitted&&this.emitter.emit("peerLeft",e.playerId,n);}settle(){this.ready?.resolve(),this.ready=null;}fail(e){if(this.count(e.reason),this.ready!==null){let n=this.ready;this.ready=null,n.reject(e);return}this.emitter.emit("error",e);}report_(e){this.fail(e instanceof L?e:new L("connection_failed",$o(e),{cause:e}));}count(e){this.counted||!Ep.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(or(e))throw new L("media_refused",`the ${n} 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(n=>this.options.clock.setTimeout(n,e))}warn(e){let n=this.options.log;n!==null&&(n??(r=>console.warn(r)))(`[gem] ${e}`);}get endedReason(){return this.ended}};function se(t){return typeof t=="string"&&t.length>0?t:null}function ar(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function $o(t){return t instanceof Error?t.message:String(t)}function rl(t){try{t.close();}catch{}}var Tp=100,Cp=50,nt=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,n){this.assertUsable(),this.options.bridge.signal("offer",this.options.matchId,{sdp:e,intent:n});}answer(e,n,r){this.assertUsable(),this.options.bridge.signal("answer",this.options.matchId,{peerId:e,sdp:n,assignedPeerId:r});}candidate(e,n,r,o){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??Tp)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:n,...r===void 0?{}:{sdpMid:r},...o===void 0?{}:{sdpMLineIndex:o}}),this.schedule();}migrationAck(e){this.assertUsable(),this.options.bridge.signal("migrationAck",this.options.matchId,{hostEpoch:e});}reportHostUnreachable(e,n){this.assertUsable(),this.options.bridge.signal("hostUnreachable",this.options.matchId,{hostEpoch:e,evidence:{iceState:n,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 L("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new L("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:n,candidate:r,sdpMid:o,sdpMLineIndex:i}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:n,candidate:r,...o===void 0?{}:{sdpMid:o},...i===void 0?{}:{sdpMLineIndex:i}});}if(this.dropped>0&&this.queue.length===0){let n=this.dropped;this.dropped=0,this.options.onCandidatesDropped?.(n),this.dropListener?.(n);}this.queue.length>0&&this.schedule();},this.options.candidateIntervalMs??Cp));}};function B(t){return e=>typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function je(t,e){return n=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e?n:void 0}function hn(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function ol(t){return typeof t=="boolean"?t:void 0}var ye=B(64),tt=je(0,2147483647);function jo(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=ye(n);typeof r=="string"&&e.push(r);}return e}function K(t,e,n){return {to:t,from:e,read:n,required:true}}function H(t,e,n){return {to:t,from:e,read:n,required:false}}var Op=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=hn("disconnected","failed","closed")(e.iceState),r=je(0,4102444800)(e.lastSeenAt);if(!(n===void 0&&r===void 0))return {...n===void 0?{}:{ice_state:n},...r===void 0?{}:{last_seen_timestamp:r}}};Object.freeze(Object.assign(Object.create(null),{join:{type:"p2p_join",gameScoped:true,args:[]},offer:{type:"p2p_offer",gameScoped:false,args:[K("sdp","sdp",B(10240)),K("signaling_intent","intent",hn("initial","ice_restart","full_reconnect")),H("sdp_hash","sdpHash",B(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[K("peer_id","peerId",ye),K("sdp","sdp",B(10240)),K("assigned_peer_id","assignedPeerId",je(0,4294967295)),H("sdp_hash","sdpHash",B(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[K("peer_id","peerId",ye),K("candidate","candidate",B(512)),H("sdp_mid","sdpMid",B(64)),H("sdp_mline_index","sdpMLineIndex",je(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[K("host_epoch","hostEpoch",tt)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[K("host_epoch","hostEpoch",tt),H("evidence","evidence",Op)]}}));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"}));Object.freeze(Object.assign(Object.create(null),{hello:[K("playerId","player_id",ye),K("hostPlayerId","host_player_id",ye),K("hostEpoch","host_epoch",tt),H("members","members",jo)],offer:[K("fromPlayerId","from_player_id",ye),K("sdp","sdp",B(10240)),H("sessionId","signaling_session_id",B(128)),H("sdpHash","sdp_hash",B(128)),H("iceUfrag","ice_ufrag",B(64)),H("intent","signaling_intent",hn("initial","ice_restart","full_reconnect"))],answer:[K("fromPlayerId","from_player_id",ye),K("sdp","sdp",B(10240)),H("sessionId","signaling_session_id",B(128)),H("sdpHash","sdp_hash",B(128)),H("iceUfrag","ice_ufrag",B(64)),H("assignedPeerId","assigned_peer_id",je(0,4294967295))],ice:[K("fromPlayerId","from_player_id",ye),K("candidate","candidate",B(512)),H("sdpMid","sdp_mid",B(64)),H("sdpMLineIndex","sdp_m_line_index",je(0,255)),H("sdpMLineIndexAlt","sdp_mline_index",je(0,255))],peerJoined:[K("playerId","player_id",ye)],peerLeft:[K("playerId","player_id",ye),H("reason","reason",B(64))],migration:[K("hostPlayerId","new_host_player_id",ye),K("hostEpoch","host_epoch",tt),H("reason","reason",B(64)),H("kickedPlayerIds","kicked_player_ids",jo),H("migrationComplete","migration_complete",ol)],matchEnded:[H("reason","reason",B(64))],error:[H("code","code",B(64)),H("message","message",B(256))]}));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"}));var ze="webrtc_p2p";function sl(t){let e=new Jn({client:t.client,gameId:t.gameId}),n=new Map;return {handleSignalEvent(r,o,i){n.get(r)?.handleSignal(o,i);},session(r){return n.get(r)??null},async connect(r={}){if(t.bridge===null)throw new L("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 o=ue(r.clusterTargetId),i=o??ue(await t.resolveClusterTarget?.());t.rooms.isHost&&t.rooms.currentMatch===null&&t.rooms.currentRoom?.matchId===void 0&&await t.rooms.startMatch({...o===void 0?{}:{clusterTargetId:o},...r.signal===void 0?{}:{signal:r.signal}});let a=await t.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(a.protocol!==ze)throw new L("unsupported_protocol",`match ${a.matchId} speaks '${a.protocol}', not '${ze}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let s=new nt({bridge:t.bridge,matchId:a.matchId,clock:t.clock}),l=new et({api:e,clock:t.clock,matchId:a.matchId,gameId:t.gameId(),baseUrl:typeof t.baseUrl=="function"?t.baseUrl():t.baseUrl,signaling:s,...i===void 0?{}:{clusterTargetId:i},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await Qn(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...t.boot===void 0?{}:{boot:t.boot},...t.log===void 0?{}:{log:t.log}});s.onDropped(d=>l.notifyCandidatesDropped(d)),n.set(a.matchId,l),l.on("matchEnded",()=>n.delete(a.matchId));try{await l.start(r.signal);}catch(d){throw n.delete(a.matchId),l.close(),d}return l}}}function al(t){let{analytics:e,rooms:n}=t,r=t.target??globalThis,o=t.document??globalThis.document,i=[];if(typeof r.addEventListener=="function"){let s=d=>{d?.persisted!==true&&e.endSession("pagehide");};r.addEventListener("pagehide",s),i.push(()=>r.removeEventListener?.("pagehide",s));let l=()=>e.setHidden(!Ke());for(let d of nr)r.addEventListener(d,l),i.push(()=>r.removeEventListener?.(d,l));typeof o?.addEventListener=="function"&&(o.addEventListener("resume",l),i.push(()=>o.removeEventListener?.("resume",l))),e.setHidden(!Ke());}let a=new Map;return i.push(n.on("matchReady",s=>{let l=s.protocol===ze?"p2p":"dedicated";a.set(s.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),i.push(n.on("matchEnded",s=>{let l=a.get(s.matchId);l!==void 0&&(a.delete(s.matchId),e.trackPlatform("gem_match_ended",{transport:l}));})),()=>{for(let s of i.splice(0))try{s();}catch{}a.clear();}}var ll=["pointerdown","keydown"];function dl(t,e=globalThis){let n=false,r=false,o=null,i=()=>{if(o!==null){try{e.cancelAnimationFrame?.(o);}catch{}o=null;}},a=()=>{if(!r){r=true,i();for(let g of ll)e.removeEventListener?.(g,l,{capture:true});e.removeEventListener?.("gamepadconnected",p,{capture:true});}},s=()=>{if(!(n||r)){n=true,a();try{t();}catch{}}};function l(g){g?.isTrusted===true&&s();}let d=()=>{let g;try{g=e.navigator?.getGamepads?.()??[];}catch{return false}return g.some(f=>f?.buttons.some(w=>w.pressed)===true)},m=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},u=()=>{if(o=null,!(n||r)){if(d()){s();return}m()&&(o=e.requestAnimationFrame?.(u)??null);}};function p(){o===null&&!n&&!r&&u();}if(typeof e.addEventListener=="function"){for(let g of ll)e.addEventListener(g,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",p,{capture:true,passive:true}),m()&&(o=e.requestAnimationFrame?.(u)??null);}return {get engaged(){return n},stop:a}}async function lr(t,e,n,r){let o=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),o}function qo(t,e){let n=false;return async r=>{let o=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),o}}function No(t={}){let e=t.now??(typeof performance>"u"?()=>Date.now():()=>performance.now()),n=[],r=new Set;return {marks:n,mark(o,i){return r.has(o)?false:(r.add(o),n.push({name:o,at:i??e()}),true)},timeline(){let o=[...n].sort((i,a)=>i.at-a.at);return o.map((i,a)=>{let s=o[a-1],l=s===void 0?"":` (+${Math.round(i.at-s.at)}ms)`;return `${i.name}@${Math.round(i.at)}ms${l}`}).join(" \u2192 ")}}}var Uo=false;async function pl(t,e,n,r){if(Uo){e.close(),n("busy",true);return}Uo=true;let o=null;try{let i=await Gp(t,r);if(typeof i=="string"){e.close(),n(i,Lp(i));return}o=i;let s=await(r.encodeRef??(l=>jp(l,r)))(o);if(o.close(),o=null,s===null){e.close(),n("failed",!0);return}if(s.size>Fp){e.close(),n("too_large",!1);return}e.postMessage(s);}catch(i){e.close(),n("failed",true),console.error("[gem] screenshot capture failed",i);}finally{Uo=false,o?.close();}}function Lp(t){switch(t){case "no_source":case "busy":case "failed":return true;case "not_wired":case "unsupported":case "unreadable":case "tainted":case "too_large":case "declined":return false}}async function Gp(t,e){if(e.handler){let i=await e.handler(t);return i===null?"declined":cl(i,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=$p(n);if(!r)return "no_source";let o=Dp(r);if(o!==null)return o;try{return cl(await createImageBitmap(r),t)}catch(i){if(i instanceof DOMException&&i.name==="SecurityError")return "tainted";throw i}}function Dp(t){let e;try{e=t.getContext("webgl2")??t.getContext("webgl");}catch{return "unreadable"}if(e){let n=e.getContextAttributes();return !n||n.preserveDrawingBuffer!==true?"unsupported":null}try{if(t.getContext("2d"))return null}catch{return "unreadable"}return "unreadable"}function $p(t){let e=null,n=0;for(let r of Array.from(t.querySelectorAll("canvas"))){let o=r.width*r.height;o<=0||r.clientWidth<=0||r.clientHeight<=0||o>n&&(e=r,n=o);}return e}async function cl(t,e){let{maxWidth:n,maxHeight:r}=e;if(t.width<=n&&t.height<=r)return t;let o=Math.min(n/t.width,r/t.height),i=Math.max(1,Math.floor(t.width*o)),a=Math.max(1,Math.floor(t.height*o));try{let s=await createImageBitmap(t,{resizeWidth:i,resizeHeight:a,resizeQuality:"high"});return t.close(),s}catch{return t.close(),"too_large"}}var Fp=8*1024*1024,ul="image/webp",ml=.92;async function jp(t,e){try{if(typeof OffscreenCanvas=="function"){let i=new OffscreenCanvas(t.width,t.height),a=i.getContext("2d");if(a){a.drawImage(t,0,0);let s=await i.convertToBlob({type:ul,quality:ml});if(s&&s.size>0)return s}}}catch{}let n=e.documentRef??globalThis.document;if(!n)return null;let r=n.createElement("canvas");r.width=t.width,r.height=t.height;let o=r.getContext("2d");return !o||(o.drawImage(t,0,0),typeof r.toBlob!="function")?null:await new Promise(i=>{r.toBlob(a=>i(a),ul,ml);})}async function gl(t,e){if(!e)return;let n;try{n=await qp(e);}catch(r){console.error("[gem] onFeedbackContext threw; sending the report without context",r);return}if(n!=null){if(typeof n!="object"||Array.isArray(n)){console.error("[gem] onFeedbackContext must return a plain object or null; got",n);return}t.sendGameContext(n);}}function qp(t){return new Promise((e,n)=>{let r=false,o=setTimeout(()=>{r||(r=true,console.warn("[gem] onFeedbackContext did not answer within 1000ms; sending the report without context. Gather cheaply, or keep a snapshot."),e(null));},1e3);(async()=>t())().then(i=>{r||(r=true,clearTimeout(o),e(i??null));},i=>{r||(r=true,clearTimeout(o),n(i instanceof Error?i:new Error(String(i))));});})}var yl=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function fl(t=globalThis){let n=t[yl];if(n!==void 0)return n;let r=false,o=()=>r,i=[],a=Np(t,o);a!==null&&i.push(a);let s=Up(t,o);s!==null&&i.push(s);let l={get muted(){return r},setMuted(d){let m=!!d;if(m!==r){r=m;for(let u of i)u();}}};return Object.defineProperty(t,yl,{value:l,configurable:true}),l}function Np(t,e){let n=t.AudioNode?.prototype,r=t.AudioDestinationNode;if(n===void 0||r===void 0)return null;let o=t.OfflineAudioContext,i=n.connect,a=n.disconnect,s=new Map,l=m=>{let u=m.gain,p=m.context.currentTime;u.cancelScheduledValues(p),e()?u.setValueAtTime(0,p):u.setTargetAtTime(1,p,.01);},d=m=>{let u=m.context;if(o!==void 0&&u instanceof o)return null;let p=s.get(u);return p===void 0&&(p=u.createGain(),p.gain.value=e()?0:1,i.call(p,m),s.set(u,p)),p};return n.connect=function(...u){let[p,...g]=u;if(p instanceof r){let f;try{f=d(p);}catch{f=null;}if(f!==null)return i.call(this,f,...g),p}return i.apply(this,u)},n.disconnect=function(...u){let[p,...g]=u;if(p instanceof r){let f=s.get(p.context);if(f!==void 0&&f!==this)try{return a.call(this,f,...g)}catch{}}return a.apply(this,u)},()=>{for(let[m,u]of s){if(m.state==="closed"){s.delete(m);continue}try{l(u);}catch{}}}}function Up(t,e){let n=t.HTMLMediaElement;if(n===void 0)return null;let r=n.prototype,o=Object.getOwnPropertyDescriptor(r,"muted"),i=o?.get,a=o?.set;if(i===void 0||a===void 0)return null;let s=r.play,l=new WeakMap,d=new WeakSet,m=new Set,u=p=>{l.has(p)||l.set(p,!!i.call(p)),d.has(p)||(d.add(p),m.add(new WeakRef(p))),a.call(p,(l.get(p)??false)||e());};return Object.defineProperty(r,"muted",{configurable:true,enumerable:o?.enumerable??true,get(){let p=l.get(this);return p===void 0?!!i.call(this):p},set(p){l.set(this,!!p),u(this);}}),r.play=function(){try{u(this);}catch{}return s.call(this)},t.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof n)try{u(g);}catch{}},true),()=>{for(let p of m){let g=p.deref();if(g===void 0){m.delete(p);continue}try{a.call(g,(l.get(g)??!1)||e());}catch{}}}}var Bp=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",Hp=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',Vp=`${Bp}${Hp}`,Bo=new WeakSet;function hl(t=globalThis.document){if(t==null||Bo.has(t))return null;try{let e=t.defaultView?.CSSStyleSheet??globalThis.CSSStyleSheet;if(Array.isArray(t.adoptedStyleSheets)&&typeof e=="function"){let r=new e;if(typeof r.replaceSync=="function")return r.replaceSync(Vp),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],Bo.add(t),"sheet"}let n=t.documentElement?.style;return n===void 0||typeof n.setProperty!="function"?null:(n.setProperty("-webkit-user-select","none"),n.setProperty("user-select","none"),n.setProperty("-webkit-tap-highlight-color","transparent"),Bo.add(t),"inline")}catch{return null}}function bl(t){let e=t.windowMs??1e3,n=t.realm??globalThis,r=false,o=false,i=false,a=null,s=null,l=null,d=[],m=()=>r&&!o&&!i,u=()=>{s=null,l=null,d=[];},p=w=>{if(a=null,!m()){u();return}if(l!==null&&d.push(w-l),l=w,s===null)s=w;else {let R=w-s;R>=e&&d.length>0&&(t.report(Wp(d,R)),s=w,d=[]);}g();},g=()=>{let w=n.requestAnimationFrame;typeof w=="function"&&(a=w.call(n,p));},f=()=>{if(m()){a===null&&(u(),g());return}a!==null&&(n.cancelAnimationFrame?.call(n,a),a=null),u();};return {setRequested(w){r=w,f();},setPaused(w){o=w,f();},get running(){return a!==null},dispose(){i=true,f();}}}function Wp(t,e){let n=[...t].sort((o,i)=>o-i),r=Math.max(1,Math.ceil(n.length*.95));return {fps:t.length*1e3/e,frameTimeP95Ms:n[r-1]}}var dr=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function _l(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function wl(t,e){t!==null&&(t.style.setProperty(dr.top,`${e.top}px`),t.style.setProperty(dr.right,`${e.right}px`),t.style.setProperty(dr.bottom,`${e.bottom}px`),t.style.setProperty(dr.left,`${e.left}px`));}var vl=Object.freeze({tl:{width:"--gem-reserved-tl-width",height:"--gem-reserved-tl-height"},tr:{width:"--gem-reserved-tr-width",height:"--gem-reserved-tr-height"},bl:{width:"--gem-reserved-bl-width",height:"--gem-reserved-bl-height"},br:{width:"--gem-reserved-br-width",height:"--gem-reserved-br-height"}});function Sl(){let t=globalThis,e=t.innerWidth,n=t.innerHeight;return typeof e=="number"&&e>0&&typeof n=="number"&&n>0?{width:e,height:n}:null}function Kp(t,e){let n={tl:{width:0,height:0},tr:{width:0,height:0},bl:{width:0,height:0},br:{width:0,height:0}};for(let r of t){let o=e?r.x+r.width/2<=e.width/2:r.x===0,i=e?r.y+r.height/2<=e.height/2:r.y===0,a=o?r.x+r.width:e?e.width-r.x:r.width,s=i?r.y+r.height:e?e.height-r.y:r.height,l=n[`${i?"t":"b"}${o?"l":"r"}`];l.width=Math.max(l.width,Math.ceil(a)),l.height=Math.max(l.height,Math.ceil(s));}return n}function Rl(t,e,n){if(t===null)return;let r=Kp(e,n);for(let o of ["tl","tr","bl","br"])t.style.setProperty(vl[o].width,`${r[o].width}px`),t.style.setProperty(vl[o].height,`${r[o].height}px`);}var Jp=3e4,cr=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function kl(t){let e=t.clock??le,n=t.timeoutMs??Jp,r=new Map,o=new Map,i=0,a=s=>{let l=r.get(s);return l?(r.delete(s),o.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return t.bridge.parentSupports("localHost")},ensure(s){if(!t.bridge.parentSupports("localHost"))return Promise.resolve();let l=o.get(s);if(l)return l;let d=new Promise((m,u)=>{let p=`ls${++i}`,g=e.setTimeout(()=>{r.delete(p),o.delete(s),u(new cr("timeout",true,`the embedder did not answer a local-server request for room ${s} within ${String(n)}ms`));},n);r.set(p,{room:s,resolve:m,reject:u,timer:g}),t.bridge.requestLocalServer(p,s)||(a(p),m());});return o.set(s,d),d.catch(()=>{}),d},accept(s){a(s.requestId)?.resolve();},refuse(s){let l=a(s.requestId);l&&l.reject(new cr(s.reason,s.retryable,s.reason==="refused"?`the platform refused to let this machine serve room ${l.room}. Check that you are signed in as a developer on this game, that the room is on the dev or test channel, and that you host it.`:`this machine could not start a server for room ${l.room}. Your development tool has the reason.`));}}}var rt={url:"https://downloads.indiegems.games/sdk/v7.9.1/gem-web-sdk.devtools.min.js",integrity:"sha384-jZUCZvoobGUVHiuFD3kx35yN9IR+luuU0L0xAaPl4iY5t2LocNUhDV0vfGvZ0TMZ"};var vn=null;function zp(){return vn!==null||(vn=new Promise((t,e)=>{let n=document.createElement("script");n.src=rt.url,n.integrity=rt.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){vn=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${rt.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{vn=null,e(new Error(`gem devtools: could not load ${rt.url}. Either the network refused it or its Subresource Integrity check failed, or the CDN did not answer the CORS preflight this request needs \u2014 SRI is only checkable on bytes the page may read. A locally rebuilt SDK is the commonest cause: it produces panel bytes that do not match the hash compiled into this build.`));},document.head.append(n);})),vn}function xl(t,e){let n=null,r=0;async function o(i){if(n!==null)return true;let a=++r;if(!e())return false;let s=await zp();return !e()||a!==r?false:(n!==null||(n=s.mount(t(),{openedBy:i,text:Ue,onDismiss:()=>{n?.unmount(),n=null;}})),true)}return {get isOpen(){return n!==null},close(){r+=1,n?.unmount(),n=null;},open:()=>o("game"),openFrom:o}}var Yp=1e4,Al={reason:"unavailable",retryable:false};function Pl(t){let e=new Map,n=null,r=null,o=0,i=(d,m)=>{m.timer=t.clock.setTimeout(()=>{e.delete(d),m.reject({reason:"timeout",retryable:true});},t.timeoutMs??Yp);},a=(d,m)=>{let u=s(d);u&&m(u);},s=d=>{let m=e.get(d);return m?(e.delete(d),t.clock.clearTimeout(m.timer),m):null},l=new on({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((m,u)=>{let p=t.bridge.currentState;if(p==="refused"||p==="closed"){u(Al);return}let g=`t${++o}`,f={resolve:m,reject:u,reason:d,timer:null,held:p!=="connected"};e.set(g,f),i(g,f),f.held||t.bridge.requestToken(g,d);})});return {source:l,onToken(d){let m={token:d.token,expiresAt:d.expiresAt,chainEndsAt:d.chainEndsAt};if(n={playerId:d.playerId,gameId:d.gameId,channel:d.channel},r=d.gameVersion??null,d.requestId!==void 0&&e.has(d.requestId)){a(d.requestId,u=>u.resolve(m));return}l.accept(m);},onDenied(d){a(d.requestId,m=>m.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[m,u]of e)u.held&&(u.held=false,t.clock.clearTimeout(u.timer),i(m,u),t.bridge.requestToken(m,u.reason));else if(d==="refused"||d==="closed")for(let m of [...e.keys()])a(m,u=>u.reject(Al));},get identity(){return n},get gameVersion(){return r}}}function Xp(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var Qp=new Set(gt);function Zp(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))Qp.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function ur(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return Pi(async(n,r)=>{let o;try{o=new URL(t.baseUrl.replace(/\/+$/,""));}catch{throw new re("the configured baseUrl is not a valid URL. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure.")}let i;try{i=new URL(o.href.replace(/\/+$/,"")+n.path);}catch{throw new re(`${JSON.stringify(typeof n.path=="string"?Xp(n.path):"(a non-string path)")} does not form a valid URL against ${o.protocol}//${o.host}. This is a malformed request, not a server failure.`)}if(i.protocol!==o.protocol||i.host!==o.host)throw new re(`${JSON.stringify(i.pathname)} resolves to ${i.protocol}//${i.host}, not ${o.protocol}//${o.host}. A request path may not change the request's origin \u2014 it carries the play token.`);if(i.username!==""||i.password!==""){let g=o.username!==""||o.password!=="",f=i.username!==o.username||i.password!==o.password,w=g?f?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new re(`the ${w} puts credentials in the URL, which cannot be fetched (${n.method} ${i.pathname}). The value is withheld here rather than written to logs. This is a malformed request, not a server failure.`)}for(let[g,f]of Object.entries(t.defaultQuery??{}))i.searchParams.has(g)||i.searchParams.set(g,f);let a=n.bytes,s=n.bytes===void 0?void 0:"application/octet-stream";try{n.body!==void 0&&(a=JSON.stringify(n.body),s="application/json");}catch(g){throw new re(`the body of ${n.method} ${JSON.stringify(i.pathname)} could not be serialised to JSON: ${String(g)}. This is a bug in the request, not a server failure \u2014 retrying sends the same unserialisable value.`)}let l=await e(i.toString(),{method:n.method,headers:{authorization:`Bearer ${r}`,...s===void 0?{}:{"content-type":s},...Zp(n.headers)},body:a,signal:n.signal,...n.keepalive===void 0?{}:{keepalive:n.keepalive},credentials:"omit",mode:"cors",redirect:"error",cache:"no-store",referrerPolicy:"no-referrer"}),d=null;if(n.responseType==="bytes"&&l.status>=200&&l.status<300)d=new Uint8Array(await l.arrayBuffer());else {let g=await l.text();if(g.length>0)try{d=JSON.parse(g);}catch{d=g;}}let m=l.headers.get("etag"),u=eg(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...m===null?{}:{etag:m},...u===void 0?{}:{retryAfterSeconds:u},...p===null||p===""?{}:{invocationId:p}}},t)}function eg(t){if(t===null)return;let e=t.trim();if(!/^\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)?n:void 0}var ng=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),Vo="embedder_relay_unavailable",tg="embedder_no_relay",rg=new Set([Vo]),Wo=new Set([tg]),ot=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new Ho(this)}handleEvent(e){let n=this.pending.get(e.matchId);if(n!==void 0){if(e.event==="matchEnded"){n.refuse(new b("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){n.refuse(new b("signaling_failed","the parent relayed an answer with no SDP in it"));return}n.settle({sdp:e.sdp});return}n.refuse(og(e.code,e.message));}}register(e,n){this.pending.get(e)?.refuse(new b("signaling_failed","a newer offer for this match superseded the one in flight")),this.pending.set(e,n);}release(e,n){this.pending.get(e)===n&&this.pending.delete(e);}transport(){let e=this.options.bridge;if(e===null)throw new b("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 b("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 og(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new b(ig(t),r,{platformCode:t})}function ig(t){return t===void 0||rg.has(t)?"signaling_failed":Wo.has(t)?"offer_refused":ng.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var Ho=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,n){if(this.closed)return Promise.reject(new b("signaling_unavailable","this signaling channel is closed"));let r;try{r=this.hub.transport();}catch(o){return Promise.reject(o)}return n?.aborted?Promise.reject(new b("aborted","the caller aborted before the offer was sent")):new Promise((o,i)=>{let a=()=>{s(),i(new b("aborted","the caller aborted the signaling exchange"));},s=()=>{n?.removeEventListener("abort",a),this.hub.release(e.matchId,l),this.teardown===s&&(this.teardown=null);},l={settle:d=>{s(),o(d);},refuse:d=>{s(),i(d);}};this.teardown=s,n?.addEventListener("abort",a),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof b?d:new b("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var El="match_ended:",Tl="server_shutdown:",Cl="kicked:",sg=123;function ag(t){if(typeof t!="string"||t.length===0||t.length>sg)return {kind:"other"};if(t.startsWith(El)){let e=$e(t.slice(El.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(Tl)?{kind:"server_shutdown",cause:t.slice(Tl.length)}:t.startsWith(Cl)?{kind:"kicked",detail:t.slice(Cl.length)}:{kind:"other"}}function Ko(t,e,n){let r=ag(n),o=r.kind==="kicked"?"kicked":"link_closed";t.notifyMatchDisconnected(o).catch(()=>{}),r.kind==="match_ended"&&t.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}function Jo(){return {exchange(){return Promise.reject(new b("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 lg=3e3,dg=1e4,cg=15e3;async function mr(t){let e=t.peerConnection;try{Ml(t,"before the handshake started"),zo(t);let n=e.createDataChannel(t.channelLabel??"gem",{ordered:!0});for(let a of t.extraChannels??[]){let s=e.createDataChannel(a.label,{...a.ordered===void 0?{}:{ordered:a.ordered},...a.maxRetransmits===void 0?{}:{maxRetransmits:a.maxRetransmits}});t.onExtraChannel?.(a.label,s);}let r=await e.createOffer();await e.setLocalDescription(r),await pg(e,t),zo(t);let o=e.localDescription?.sdp??r.sdp;if(!o)throw new b("invalid_sdp","the offer carried no SDP");Fe(o,"offer"),Il(o,"offer");let i=await mg(t,o);if(zo(t),typeof i?.sdp!="string")throw new b("invalid_sdp","the signaling channel answered without an SDP");return Fe(i.sdp,"answer"),Il(i.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:i.sdp}),await gg(n,t),Ml(t,"before the channel opened"),n}catch(n){throw e.close(),ug(n)}}function ug(t){return t instanceof b?t:Gl(t)?Ye():new b("connection_failed",Dl(t),{cause:t})}function Il(t,e){if(or(t))throw new b("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 mg(t,e){let n=t.exchangeTimeoutMs??dg,r=Ll(t,n),o=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(i=>{throw i instanceof b?i:Gl(i)?Ye():new b("signaling_failed",Dl(i),{cause:i})});return yg(o,t,r,()=>r.exhausted?Yo("while the offer was in flight"):new b("timeout",`no answer arrived within ${n}ms`))}function pg(t,e){if(t.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:n}=e;return new Promise(r=>{let o=()=>{n.clearTimeout(a),t.removeEventListener("icegatheringstatechange",i),e.signal?.removeEventListener("abort",o),r();},i=()=>{t.iceGatheringState==="complete"&&o();},a=n.setTimeout(o,e.gatherTimeoutMs??lg);t.addEventListener("icegatheringstatechange",i),e.signal?.addEventListener("abort",o);})}function gg(t,e){if(e.signal?.aborted)return Promise.reject(Ye());if(t.readyState==="open")return Promise.resolve();if(t.readyState!=="connecting")return Promise.reject(new b("connection_failed",`the data channel was already '${t.readyState}' when the answer was applied`));let{clock:n}=e,r=e.openTimeoutMs??cg,o=Ll(e,r);return new Promise((i,a)=>{let s=()=>{n.clearTimeout(p),t.removeEventListener("open",l),t.removeEventListener("close",d),t.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{s(),i();},d=g=>{s(),a(new b("connection_failed","the data channel failed before it opened",Ol(g)===void 0?void 0:{cause:Ol(g)}));},m=()=>{s(),a(Ye());},u=()=>{s(),a(o.exhausted?Yo("while the channel was still opening"):new b("timeout",`the data channel did not open within ${r}ms`));},p=n.setTimeout(u,o.ms);t.addEventListener("open",l),t.addEventListener("close",d),t.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function Ll(t,e){if(t.credentialExpiresAt===void 0)return {ms:e,exhausted:false};let n=t.credentialExpiresAt-t.clock.now();return n<=e?{ms:Math.max(0,n),exhausted:true}:{ms:e,exhausted:false}}function yg(t,e,n,r){let{clock:o,signal:i}=e;return i?.aborted?Promise.reject(Ye()):new Promise((a,s)=>{let l=u=>{o.clearTimeout(m),i?.removeEventListener("abort",d),u();},d=()=>l(()=>s(Ye())),m=o.setTimeout(()=>l(()=>s(r())),n.ms);i?.addEventListener("abort",d),t.then(u=>l(()=>a(u)),u=>l(()=>s(u)));})}function Ml(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw Yo(`already ${e}`)}function Yo(t){return new b("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function zo(t){if(t.signal?.aborted)throw Ye()}function Ye(){return new b("aborted","the caller aborted the connection attempt")}function Gl(t){return t?.name==="AbortError"}function Ol(t){return t?.error}function Dl(t){return t instanceof Error?t.message:String(t)}Object.freeze(Object.assign(Object.create(null),{webrtc_sdp_answer:"answer",webrtc_error:"error",match_ended:"matchEnded"}));Object.freeze(Object.assign(Object.create(null),{answer:[K("sdp","sdp",B(10240)),H("sessionId","session_id",B(64))],error:[H("code","code",B(64)),H("message","message",B(256))],matchEnded:[H("reason","reason",B(64))]}));function Hl(t){let{client:e,clock:n,rooms:r}=t,o=t.signaling??Jo,i=t.log??(_=>console.warn(_)),a=new yn({client:e,gameId:()=>r.gameId,transport:"dedicated"}),s=new Map,l=(_,S)=>{let E=s.get(_)??new Set;E.add(S),s.set(_,E);},d=(_,S)=>{let E=s.get(_);E!==void 0&&(E.delete(S),E.size===0&&s.delete(_));},m=async _=>{if(r.isHost&&!Qo(r)&&r.currentRoom?.matchId===void 0){let S=ue(_.clusterTargetId);await r.startMatch({...S===void 0?{}:{clusterTargetId:S},..._.retry===void 0?{}:{retry:_.retry},..._.signal===void 0?{}:{signal:_.signal}});}return Ul(r.matchConnectionState==="suspended"?await r.reconnectToMatch(Xo(_)):await r.awaitMatch(Xo(_)))},u=async _=>Ul(await r.pollMatchStatus(Xo(_))),p=async(_,S)=>{let E=false;try{let A=await m(_),V=r.currentRoom?.transports;if(V!==void 0&&!V.includes("webrtc"))throw new b("misconfigured",`the room template offers (${V.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 N=_.peerConnection??Bl();E=!0;let q=await mr({peerConnection:N,signaling:S,clock:n,matchId:A.matchId,credentialExpiresAt:A.credentialExpiresAt,...pr(_,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),k=null;if(_.presentCredential!==!1)try{k=await qn({channel:q,clock:n,credential:A.joinCredential,credentialExpiresAt:A.credentialExpiresAt,...pr(_,"onMessage","signal"),..._.welcomeTimeoutMs===void 0?{}:{ceilingMs:_.welcomeTimeoutMs}});}catch(C){throw Se(q),Se(N),C}return kg(r,A,q,N,S,_.reportDisconnect!==!1,_.reportConnected!==!1,k,{remember:l,forget:d},_.onMatchEnded)}catch(A){throw E&&Nl(a,A),Se(S),A}},g=async(_,S,E,A,V,N)=>{if(_==="webtransport"){let F=A?.webtransport;if(F===void 0)throw new b("misconfigured","webtransport is not advertised");let W={credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,clock:n};if(typeof F.named_url=="string"&&F.named_url!==""){let Q=Math.max(Math.floor(N/2),1e3);try{return await Hn({url:F.named_url,timeoutMs:Q,log:i,...W})}catch(pe){if(Qt()!==null)throw pe;return i(`[gem] webtransport named dial failed (${Yt(pe)}); retrying the pinned dial`),Hn({url:F.url,certHashBase64:F.cert_sha256_b64,timeoutMs:Q,log:i,...W})}}return Hn({url:F.url,certHashBase64:F.cert_sha256_b64,timeoutMs:N,...W})}if(_==="websocket"){let F=A?.websocket;if(F===void 0)throw new b("misconfigured","websocket is not advertised");return bo({url:F.url,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,clock:n,timeoutMs:N})}let q=S.peerConnection??Bl(),k,C=await mr({peerConnection:q,signaling:V,clock:n,matchId:E.matchId,credentialExpiresAt:E.credentialExpiresAt,extraChannels:[{label:Un,ordered:false,maxRetransmits:0}],onExtraChannel:(F,W)=>{F===Un&&(k=W);},...pr(S,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...S.exchangeTimeoutMs===void 0&&S.redial===true?{exchangeTimeoutMs:bg}:{}}),O;try{O=await qn({channel:C,clock:n,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,wire:zt,heartbeat:!0,...pr(S,"signal"),...S.welcomeTimeoutMs===void 0?{}:{ceilingMs:S.welcomeTimeoutMs}});}catch(F){throw Se(C),Se(q),F}let D=O.welcome.heartbeatIntervalMs;return {link:_o(C,q,k,D===void 0?void 0:{clock:n,intervalMs:D}),welcome:O.welcome,channel:C,peerConnection:q}},f=(_,S,E,A,V)=>{let N=false,q;A.link.onClose(D=>{!N&&_.reportDisconnect!==false&&Ko(r,S.matchId,D),q?.(D);}),_.reportDisconnect!==false&&_.reportConnected!==false&&r.notifyMatchConnected(S.matchId);let k={transport:A.link.transport,send:(D,F)=>A.link.send(D,F),onMessage:D=>A.link.onMessage(D),onClose:D=>{q=D;},close:()=>A.link.close()},C=()=>{N||(N=true,Se(A.link),Se(V));},O=D=>{if(!N){try{_.onMatchEnded?.(D);}catch{}C();}};return l(S.matchId,O),{matchId:S.matchId,transport:E,link:k,joinCredential:S.joinCredential,credentialExpiresAt:S.credentialExpiresAt,welcome:A.welcome,...A.channel===void 0?{}:{channel:A.channel},...A.peerConnection===void 0?{}:{peerConnection:A.peerConnection},close(){d(S.matchId,O),C();}}},w=async(_,S)=>{let E=r.currentRoom?.id,A=r.gameId,V=()=>({advert:Bn(r.currentRoom?.settings,_),template:r.currentRoom?.transports??null});if(E===void 0||A===null)return V();try{let N=await e.get(`/v2/games/${encodeURIComponent(A)}/game-rooms/${encodeURIComponent(E)}`,S);return {advert:Bn(N.settings,_),template:pn(N.transports)??r.currentRoom?.transports??null}}catch{return V()}},R=(_,S)=>{let E=_??$l;return S.length===0?E:E.filter(A=>S.includes(A))},I=async(_,S,E)=>{try{let A=await m(_),{advert:V,template:N}=await w(A.matchId,_.signal),q=R(N,S),k=q.filter(z=>wg(z,V)),C=Qt();if(C!==null&&q.includes("webtransport")&&V?.webtransport!==void 0&&i(`[gem] webtransport skipped: ${C} (learned on an earlier dial in this page)`),k.length===0){let z=N===null?`the default order (${$l.join(", ")})`:`the room template's transports (${N.join(", ")||"none"})`;throw new b("misconfigured",`none of ${z}`+(S.length>0?`, narrowed to (${S.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let O=_.transportAttemptTimeoutMs??hg,D=()=>_.deadlineAt===void 0?1/0:_.deadlineAt-n.now(),F=z=>t.signalingReady===void 0||z<=0?Promise.resolve(!0):t.signalingReady(z),W=[],Q=[];for(let z of k){if(D()<jl){i(`[gem] ${z} rung not tried: the reconnect budget is spent`);break}Q.length>0&&A.credentialExpiresAt-n.now()<ql&&(A=await u(_)),Q.push(z);let Me=!1,Ce=!1,be={attempts:0,waitedMs:0};for(;;){if(z==="webrtc"&&_.redial===!0){let ee=Math.min(Fl,D());await F(ee)||i(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(ee)}ms; offering anyway`);}let Oe=Math.max(Math.min(O,D()),jl);try{return f(_,A,z,await g(z,_,A,V,E,Oe),E)}catch(ee){let X=ee instanceof b?ee:new b("connection_failed",ee instanceof Error?ee.message:String(ee),{cause:ee});if(z==="webrtc"&&Nl(a,X),(X.reason==="credential_expired"||X.reason==="credential_reused")&&!Me){Me=!0,A=await u(_);continue}if(z==="webrtc"&&X.reason==="signaling_failed"&&X.platformCode===Vo&&!Ce){Ce=!0;let ae=Math.min(Fl,D());if(i(`[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 F(ae))continue}if(X.reason==="join_rate_limited"){let ae=_g(be,Math.random,D());if(ae!==null){if(be.attempts+=1,be.waitedMs+=ae,i(`[gem] ${z} rung: the server is rate-limiting this player's joins; waiting ${Math.round(ae)}ms before presenting again (retry ${be.attempts} of ${Wl.maxAttempts})`),await Wt(n,ae,_.signal),_.signal?.aborted)throw new b("aborted","the caller aborted while waiting out a join rate limit");A.credentialExpiresAt-n.now()<ql&&(A=await u(_));continue}}if(vg.has(X.reason)||X.reason==="credential_expired"||z==="webrtc"&&Vl(X)){i(`[gem] ${z} rung failed (${X.reason}): ${Yt(X.cause??X)} \u2014 `+(Q.length<k.length?`falling through to ${k[Q.length]}`:"no rungs left")),W.push(X);break}throw i(`[gem] ${z} rung refused the session (${X.reason}): ${X.message}`),X}}}let pe=W[W.length-1];throw pe===void 0?new b("timeout",`the reconnect budget ran out before any transport (${k.join(", ")}) could be tried`):new b(pe.reason,`every transport tried (${Q.join(", ")}) failed; the last said: ${pe.message}`,{cause:W,platformCode:pe.platformCode})}catch(A){throw Se(E),A}};return {listClusterTargets:async(_={})=>to({client:e,..._}),handleMatchEnded(_,S){let E=s.get(_);if(E!==void 0){s.delete(_);for(let A of E)A(S);}},connect:(async(_={})=>{let S=_.signaling??o();return _.transports===void 0?p(_,S):I(_,_.transports,S)})}}var $l=["webtransport","webrtc","websocket"],hg=1e4,bg=5e3,Fl=3e3,jl=1e3,ql=1e4,vg=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function Vl(t){return t.platformCode!==void 0&&Wo.has(t.platformCode)}var Wl={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function _g(t,e=Math.random,n=1/0){let r=Wl;if(t.attempts>=r.maxAttempts)return null;let o=Math.min(r.budgetMs-t.waitedMs,n);if(o<r.initialDelayMs)return null;let i=r.initialDelayMs*r.factor**t.attempts;return Math.min(i+e()*r.jitterMs,o)}function wg(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&Xt():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||Sg(e.websocket.url)}function Sg(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return St(e)}function Xo(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var Rg=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Nl(t,e){e instanceof b&&(!Rg.has(e.reason)&&!Vl(e)||t.report([{type:"connection_failures_total",value:1}]));}function kg(t,e,n,r,o,i,a,s,l,d){let m=false,u=()=>{m||Ko(t,e.matchId,void 0);};i&&(n.addEventListener("close",u),a&&t.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,n.removeEventListener("close",u),s?.detach(),Se(n),Se(r),Se(o));},g=f=>{if(!m){try{d?.(f);}catch{}p();}};return l.remember(e.matchId,g),{matchId:e.matchId,channel:n,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:s?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function Qo(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function Ul(t){if(t.status==="failed")throw new b("allocation_failed",`match ${t.matchId} did not come up: ${t.reason}`);if(t.status==="ended")throw new b("match_ended",`match ${t.matchId} ended (${t.reason}) before this side connected.`);if(t.protocol!==Vt)throw new b("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${Vt}' is reachable from a frame; host and port on this response are advisory and must not be dialled.`);let{joinCredential:e,credentialExpiresAt:n}=t;if(e===void 0||n===void 0)throw new b("connection_failed",`match ${t.matchId} is ready but issued no join credential, so the server would refuse the channel once it opened \u2014 poll match status again.`);return {...t,joinCredential:e,credentialExpiresAt:n}}function Bl(){let t=globalThis.RTCPeerConnection;if(!t)throw new b("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 t({iceServers:[]})}function Se(t){try{t.close();}catch{}}function pr(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var xg=1e4;function Kl(t,e){return Zo(t,e)}function Zo(t,e){if(typeof t.serverToken!="function"||typeof t.onServerToken!="function")throw new Error("this runtime delivers no game-server token: host.serverToken/onServerToken are missing. The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let n=a=>({token:a.token,expiresAt:a.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,o=new on({clock:e.clock,...e.onStateChange===void 0?{}:{onStateChange:e.onStateChange},request:()=>new Promise((a,s)=>{let l=e.clock.setTimeout(()=>{r=null,s({reason:"unavailable",retryable:true});},e.timeoutMs??xg);r={resolve:d=>{e.clock.clearTimeout(l),a(d);},reject:s,timer:l};})}),i=t.onServerToken(a=>{let s=n(a),l=r;if(l){r=null,l.resolve(s);return}o.accept(s);});return {source:o,dispose(){i(),r&&(e.clock.clearTimeout(r.timer),r.reject({reason:"unavailable",retryable:false}),r=null);}}}var ni={};Id(ni,{acceptTransfer:()=>Ag,addEntityProgression:()=>Pg,adminAction:()=>Eg,cancelInventoryTransfer:()=>Tg,claimEntityProgressionRewards:()=>Cg,closeGameRoom:()=>Ig,createEntityBatchOrder:()=>Mg,createEntityOrder:()=>Og,createSession:()=>Lg,deleteEntityGameSetting:()=>Gg,deleteEntitySave:()=>Dg,deleteSession:()=>$g,deleteShowcaseValue:()=>Fg,executeEntityRecipe:()=>jg,finalizeSaveUpload:()=>qg,getChannelAssignment:()=>Ng,getDropRates:()=>Ug,getEntityCurrency:()=>Bg,getEntityGameSetting:()=>Hg,getEntityInventory:()=>Vg,getEntityInventoryItem:()=>Wg,getEntityLeaderboard:()=>Kg,getEntityOrder:()=>Jg,getEntityProgression:()=>zg,getEntityRecipeAvailability:()=>Yg,getEntityRecipeUsage:()=>Xg,getEntitySave:()=>Qg,getEvent:()=>Zg,getGameRoomV2:()=>ey,getLeaderboard:()=>ny,getPlayerGameProfile:()=>ty,getPurchaseCatalog:()=>ry,getResolvedTemplate:()=>oy,getRoomArgs:()=>iy,getShowcaseValue:()=>sy,getTransferDetails:()=>ay,ingestAnalyticsEvents:()=>ei,initiateInventoryTransfer:()=>ly,invokeFunction:()=>dy,kickPlayer:()=>cy,listChallenges:()=>uy,listEntityGameSettings:()=>my,listEntityOrders:()=>py,listEntityProgressions:()=>gy,listEntitySaves:()=>yy,listEvents:()=>fy,listGameRooms:()=>hy,listResolvedTemplates:()=>by,listTransfers:()=>vy,maxEntityProgression:()=>_y,putEntityGameSetting:()=>wy,putRoomArgs:()=>Sy,putShowcaseValue:()=>Ry,rejectTransfer:()=>ky,requestSaveUploadUrl:()=>xy,resetEntityProgression:()=>Ay,simulateEntityOrder:()=>Py,transferHostV2:()=>Ey,updateGameRoomV2:()=>Ty});function h(t){let e=String(t);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 Ag(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function Pg(t,e,n,r,o,i){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/add`;return t.client.post(a,o,i?.signal)}async function Eg(t,e,n,r){let o=`/v1/voice/sessions/${h(e)}/admin`;return t.client.post(o,n,r?.signal)}async function Tg(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Cg(t,e,n,r,o,i){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/claim`;return t.client.post(a,o,i?.signal)}async function Ig(t,e,n){let r=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}`;return t.client.delete(r,n?.signal)}async function Mg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/orders/batch`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Og(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/orders`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Lg(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function Gg(t,e,n,r,o){let i=`/v1/settings/${h(e)}/${h(n)}/${h(r)}`;return t.client.delete(i,o?.signal)}async function Dg(t,e,n,r,o){let i=`/v1/saves/${h(e)}/${h(n)}/${h(r)}`;return t.client.delete(i,o?.signal)}async function $g(t,e,n){let r=`/v1/voice/sessions/${h(e)}`;return t.client.delete(r,n?.signal)}async function Fg(t,e,n,r){let o=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.delete(o,r?.signal)}async function jg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/recipes/execute`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function qg(t,e,n,r,o,i){let a=`/v1/saves/${h(e)}/${h(n)}/${h(r)}/finalize`;return t.client.post(a,o,i?.signal)}async function Ng(t,e,n){let r=`/v1/games/${h(t.gameId())}/config/channels/${h(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Ug(t,e,n){let r=`/v1/inventory/loot-tables/${h(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Bg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/currencies/${h(r)}`;return t.client.get(i,o?.signal)}async function Hg(t,e,n,r,o){let i=`/v1/settings/${h(e)}/${h(n)}/${h(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Vg(t,e,n,r){let o=new URLSearchParams;r?.include_buckets!==void 0&&o.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&o.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&o.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&o.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&o.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&o.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&o.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&o.set("progression_cursor",String(r?.progression_cursor));let i=o.toString(),a=`/v1/inventory/${h(e)}/${h(n)}`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function Wg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/items/${h(r)}`;return t.client.get(i,o?.signal)}async function Kg(t,e,n,r,o){let i=new URLSearchParams;o?.bucket_1!==void 0&&i.set("bucket_1",String(o?.bucket_1)),o?.bucket_2!==void 0&&i.set("bucket_2",String(o?.bucket_2)),o?.limit!==void 0&&i.set("limit",String(o?.limit)),o?.periods_back!==void 0&&i.set("periods_back",String(o?.periods_back)),o?.period!==void 0&&i.set("period",String(o?.period)),o?.player_id!==void 0&&i.set("player_id",String(o?.player_id));let a=i.toString(),s=`/v1/leaderboards/${h(e)}/${h(n)}/${h(r)}`+(a?`?${a}`:"");return t.client.get(s,o?.signal)}async function Jg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/orders/${h(r)}`;return t.client.get(i,o?.signal)}async function zg(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}`;return t.client.get(i,o?.signal)}async function Yg(t,e,n,r,o,i){let a=`/v1/inventory/${h(e)}/${h(n)}/catalogs/${h(r)}/recipes/${h(o)}/availability`;return t.client.get(a,i?.signal)}async function Xg(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit));let i=o.toString(),a=`/v1/inventory/${h(e)}/${h(n)}/recipe-usage`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function Qg(t,e,n,r,o){let i=`/v1/saves/${h(e)}/${h(n)}/${h(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Zg(t,e,n){let r=`/v1/events/${h(e)}`;return t.client.get(r,n?.signal)}async function ey(t,e,n){let r=`/v2/games/${h(t.gameId())}/game-rooms/${h(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function ny(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let o=r.toString(),i=`/v1/leaderboards/${h(e)}`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function ty(t,e,n){let r=`/v1/profiles/players/${h(e)}`;return t.client.get(r,n?.signal)}async function ry(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),o="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function oy(t,e,n){let r=`/v1/game-room-templates/${h(e)}`;return t.client.get(r,n?.signal)}async function iy(t,e,n){let r=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}/room-args`;return t.client.get(r,n?.signal)}async function sy(t,e,n,r){let o=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.get(o,r?.signal)}async function ay(t,e,n){let r=`/v1/inventory/transfers/${h(e)}`;return t.client.get(r,n?.signal)}async function ei(t,e,n){let r=`/v1/games/${h(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true})}async function ly(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function dy(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function cy(t,e,n,r){let o=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}/kick/${h(n)}`;return t.client.post(o,void 0,r?.signal)}async function uy(t,e){let n=new URLSearchParams;e?.periods_back!==void 0&&n.set("periods_back",String(e?.periods_back)),e?.player_id!==void 0&&n.set("player_id",String(e?.player_id));let r=n.toString(),o="/v1/challenges"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function my(t,e,n,r){let o=`/v1/settings/${h(e)}/${h(n)}`;return t.client.get(o,r?.signal)}async function py(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/inventory/${h(e)}/${h(n)}/orders`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function gy(t,e,n,r){let o=`/v1/inventory/${h(e)}/${h(n)}/progressions`;return t.client.get(o,r?.signal)}async function yy(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit)),r?.cursor!==void 0&&o.set("cursor",String(r?.cursor));let i=o.toString(),a=`/v1/saves/${h(e)}/${h(n)}`+(i?`?${i}`:"");return t.client.get(a,r?.signal)}async function fy(t,e){let n=new URLSearchParams;e?.include_inactive!==void 0&&n.set("include_inactive",String(e?.include_inactive)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.offset!==void 0&&n.set("offset",String(e?.offset));let r=n.toString(),o="/v1/events"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function hy(t,e){let n=new URLSearchParams;e?.status!==void 0&&n.set("status",String(e?.status)),e?.game_channel!==void 0&&n.set("game_channel",String(e?.game_channel)),e?.game_room_type!==void 0&&n.set("game_room_type",String(e?.game_room_type)),e?.template_id!==void 0&&n.set("template_id",String(e?.template_id)),e?.template_slug!==void 0&&n.set("template_slug",String(e?.template_slug)),e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),o=`/v1/games/${h(t.gameId())}/game-rooms`+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function by(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function vy(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),o="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function _y(t,e,n,r,o,i){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/max`;return t.client.post(a,o,i?.signal)}async function wy(t,e,n,r,o,i){let a=`/v1/settings/${h(e)}/${h(n)}/${h(r)}`;return t.client.put(a,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Sy(t,e,n,r){let o=`/v1/games/${h(t.gameId())}/game-rooms/${h(e)}/room-args`;return t.client.put(o,n,r?.signal)}async function Ry(t,e,n,r,o){let i=`/v1/showcase/players/${h(e)}/${h(n)}`;return t.client.put(i,r,o?.signal)}async function ky(t,e,n){let r=`/v1/inventory/transfers/${h(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function xy(t,e,n,r,o,i){let a=`/v1/saves/${h(e)}/${h(n)}/${h(r)}/upload-url`;return t.client.post(a,o,i?.signal,{replaySafe:true})}async function Ay(t,e,n,r,o,i){let a=`/v1/inventory/${h(e)}/${h(n)}/progressions/${h(r)}/reset`;return t.client.post(a,o,i?.signal)}async function Py(t,e,n,r,o){let i=`/v1/inventory/${h(e)}/${h(n)}/orders/simulate`;return t.client.post(i,r,o?.signal)}async function Ey(t,e,n,r){let o=`/v2/games/${h(t.gameId())}/game-rooms/${h(e)}/transfer/${h(n)}`;return t.client.post(o,void 0,r?.signal)}async function Ty(t,e,n,r){let o=`/v2/games/${h(t.gameId())}/game-rooms/${h(e)}`;return t.client.patch(o,n,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var Cy=1e4,Iy=50,My=1e3,Oy=65536-4*1024,Jl=t=>typeof t=="number"?t:0,Ly=t=>typeof t=="string"?t:"";function zl(){let t=globalThis.crypto;return typeof t?.randomUUID=="function"?t.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let n=Math.floor(Math.random()*16);return (e==="x"?n:n&3|8).toString(16)})}function Gy(t){return t?.retryable===true}function Dy(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:Jl(i.index),code:Ly(i.code)}}):[];return {accepted:Jl(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Yl(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,player_id:t.playerId,dimensions:t.dimensions,measures:t.measures}}function Xl(t){let e=Math.max(1,Math.floor(t.maxQueue??My)),n={client:t.client,gameId:()=>t.gameId},r=[],o=0,i=null,a=false,s=false,l=false,d=false,m=w=>{t.log?.(w);},u=()=>{i!==null&&(t.clock.clearTimeout(i),i=null);},p=()=>{i!==null||a||s||(i=t.clock.setTimeout(()=>{i=null,f().catch(()=>{});},Cy));},g=()=>{let w=Math.min(r.length,100),R=128;for(let I=0;I<w;I+=1){let M=r[I];if(M===void 0)break;if(R+=JSON.stringify(Yl(M,0)).length+1,R>Oy)return Math.max(1,I)}return w};async function f(w){if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};u();let R=r.splice(0,g()),I=o;o=0;let M=Math.round(t.clock.now()),_={batch_id:zl(),sent_at_ms:M,events:R.map(S=>Yl(S,M))};s=true;try{let S=await ei(n,_,w===void 0?void 0:{signal:w}),E=Dy(S,I);for(let A of E.rejected)m(`[gem] analytics: an event was refused (${A.code}). See the analytics_events section of your game config.`);return E}catch(S){if(Gy(S))for(r=[...R,...r],o+=I;r.length>e;)r.shift(),o+=1;else m(`[gem] analytics: ${R.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(S)}`);throw S}finally{s=false,r.length>0&&p();}}return {track(w,R,I={}){if(a)return;if(typeof w!="string"||w===""){d||(d=true,m(`[gem] analytics: '${R}' was not recorded \u2014 an event from a server has to name the player it is about. A game-server token names no player, so the platform cannot infer one; pass the id from join() or host.players().`));return}if(R.startsWith(Wr)){l||(l=true,m(`[gem] analytics: '${R}' was not recorded \u2014 the gem_ prefix is reserved, and the platform's own events are client-sourced, so a server may not emit one at all. Name your event something else.`));return}let M={},_={};for(let[S,E]of Object.entries(I))typeof E=="string"?M[S]=E:typeof E=="number"&&Number.isFinite(E)&&(_[S]=E);for(;r.length>=e;)r.shift(),o+=1;r.push({uid:zl(),playerId:w,name:R,atMs:t.clock.now(),dimensions:M,measures:_}),r.length>=Iy?f().catch(()=>{}):p();},flush:w=>f(w),get pending(){return r.length},dispose(){a=true,u(),r=[],o=0;}}}function Ql(t){return {async list(e){let{playerId:n,periodsBack:r,signal:o}=e??{};if(typeof n!="string"||n==="")throw new TypeError("gem.challenges.list needs { playerId }: a game-server token names no player, so the platform cannot tell whose period you mean. Pass the id from join() or gem.players().");cn(r);let i=await t({player_id:n,...r===void 0?{}:{periods_back:r},...o===void 0?{}:{signal:o}});return qt(i)}}}function $y(t){let e={};for(let[n,r]of Object.entries(ni))if(typeof r=="function"){let o=r;e[n]=(...i)=>o(t,...i);}return e}function _n(t,e={}){let n=e.clock??le,r=e.baseUrl??t.apiBaseUrl;if(!r)throw new Error("this runtime names no gem-api host (host.apiBaseUrl is missing). The server image running this bundle predates token delivery \u2014 the bundle cannot call gem-api on it.");let o=Zo(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),i=ur({baseUrl:r,tokenSource:o.source,defaultQuery:{game_id:t.gameId,channel:t.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),a=new Le({transport:i,clock:n}),s={gameId:t.gameId,channel:t.channel,matchId:t.matchId,...t.gameRoomId===void 0?{}:{gameRoomId:t.gameRoomId}},l=$y({client:a,gameId:()=>s.gameId}),d=s.gameRoomId,m=t.endMatch,u=t.log,p=Xl({client:a,clock:n,gameId:s.gameId,...typeof u=="function"?{log:f=>u.call(t,f)}:{}});return {identity:s,client:a,api:l,match:{end:async()=>{if(m===void 0)throw new Error("this runtime cannot end the match: the server image running this bundle predates host.endMatch, and only the platform half holds the allocation proof an end needs.");await m.call(t);}},analytics:p,functions:new De(l.invokeFunction),challenges:Ql(l.listChallenges),...d===void 0?{}:{room:{get:f=>l.getGameRoomV2(d,f),args:async f=>{let w=await l.getGameRoomV2(d,f?.signal===void 0?{}:{signal:f.signal}),R=w.modified?w.body:void 0;if(R?.room_args==null||R.room_args_template==null)throw new G("not_found",404,"this room's template declares no room args",void 0,"room_args_not_defined");return {room_args:R.room_args,room_args_template:R.room_args_template}}}},dispose:()=>{p.dispose(),o.dispose();}}}function Xe(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function wn(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function it(t){return typeof t=="string"?t:t.slice().buffer}function gr(t){if(typeof t=="string")return {data:t,isText:true};if(t instanceof ArrayBuffer)return {data:new Uint8Array(t),isText:false};if(ArrayBuffer.isView(t)){let e=t;return {data:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),isText:false}}return null}var Fy=5e3,Zl=3e4,ed=2e3,jy=1e4,nd=1;async function td(t,e){let{session:n,localPlayerId:r}=e;if(!n.isHost)throw new Error("[gem] runListenHost was handed a session this player does not host. The room decides who hosts; gate on `gem.rooms.isHost` \u2014 or call `gem.match.serve()`, which does.");let o=e.log===void 0?y=>console.info(y):e.log,i=y=>o?.(`[gem host] ${y}`),a=typeof t=="function"?t():t,s=Promise.resolve(),l=true,d=false,m=(y,T)=>{l&&(s=s.then(async()=>{if(!d)try{await T();}catch(j){i(`the bundle's ${y} handler threw: ${Qe(j)}. Serving continues.`);}}));},u=true,p,g,f,w=y=>{if(!u)return;u=false,m("leave",()=>a.leave?.(r,{cause:y??"left"}));let T=g;T&&queueMicrotask(()=>T(y));},R={send(y,T){if(!u)return;let j=wn(Xe(T));m("message",()=>a.message?.(r,y,typeof y=="string",{reliable:j.reliable,ordered:j.ordered}));},onMessage(y){p=y;},onClose(y){g=y;},close(){w("closed");}},I=(y,T)=>{if(!u)return;let j=wn(Xe(T));queueMicrotask(()=>{u&&p?.(y,j);});},M=new Map,_=y=>{let T=[];for(let j of Ie){let ne=y.channels[j];try{ne.binaryType="arraybuffer";}catch{}let ve=wn(j),qe=ct=>{let Y=gr(ct?.data);Y!==null&&m("message",()=>a.message?.(y.playerId,Y.data,Y.isText,{reliable:ve.reliable,ordered:ve.ordered}));};ne.addEventListener("message",qe),T.push(()=>ne.removeEventListener("message",qe));}M.get(y.playerId)?.forEach(j=>j()),M.set(y.playerId,T);},S=y=>{M.get(y)?.forEach(T=>T()),M.delete(y);},E=new Set,A=new Map,V=(y,T,j)=>({playerNumber:y.assignedPeerId,transport:"webrtc_p2p",...T?{rejoin:true}:{},...j?{superseded:true}:{}}),N=y=>{let T=M.has(y.playerId),j=E.has(y.playerId);E.add(y.playerId),_(y),T&&m("leave",()=>a.leave?.(y.playerId,{cause:"superseded"})),m("join",()=>a.join?.(y.playerId,V(y,j,T)));},q=new Set,k=(y,T,j)=>{if(y===r){I(T,j);return}let ne=n.peer(y);if(ne===null){let ve=A.get(y);if(ve!==void 0&&e.clock.now()-ve<ed)return;q.has(y)||(q.add(y),i(`send to '${y}' dropped: no such connected player`));return}ne.send(it(T),Xe(j));},C={matchId:n.matchId,gameId:e.gameId,channel:e.channel,...e.gameRoomId===void 0?{}:{gameRoomId:e.gameRoomId},apiBaseUrl:e.apiBaseUrl,serverToken:()=>e.tokens.current(),onServerToken:y=>e.tokens.subscribe(y),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(y=>y.playerId)??[],players(){let y=u?[r]:[];for(let T of n.peers)y.push(T.playerId);return y},profile(y){let T=e.room()?.members.find(j=>j.playerId===y);if(!(!T||T.displayName===void 0))return {displayName:Ue.toPlain(T.displayName),...T.displayTag===void 0?{}:{displayTag:Ue.toPlain(T.displayTag)},...T.discriminator===void 0?{}:{discriminator:T.discriminator}}},playerNumber(y){return y===r?nd:n.peer(y)?.assignedPeerId},send(y,T,j){k(y,T,j);},broadcast(y,T){let j=T?.except;u&&r!==j&&I(y,T);for(let ne of n.peers)ne.playerId!==j&&ne.send(it(y),Xe(T));},async endMatch(){let y=await Oe();return y.answer!=="ok"&&i(y.cause),y.answer},kick(y,T){if(y===r){w(T??"kicked");return}n.kick(y).catch(j=>{i(`kick of '${y}' failed: ${Qe(j)}`);});},log(y){i(y);},warn(y){i(`\u26A0 ${y}`);}},O=()=>{},D=new Promise(y=>{O=y;}),F=[],W=null,Q=async(y,T)=>{l=false;let j=s.then(async()=>{try{await a.shutdown(y);}catch(ne){i(`the bundle's shutdown threw: ${Qe(ne)}`);}});s=j,await j,ae();for(let ne of F.splice(0))ne();for(let ne of [...M.keys()])S(ne);w(T);},pe=(y,T)=>W||(W=(async()=>{await Q(T,y),n.close(),O();})(),W),z=()=>W||(W=(async()=>{await Q({reason:"signal"},"left"),await n.leave().catch(y=>i(`leaving the match failed: ${Qe(y)}`)),O();})(),W),Me=()=>W||(W=(async()=>{l=false;let y=await Oe();y.answer==="ok"?(await Q({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(i(`${y.cause}; leaving instead`),await Q({reason:"signal"},"left"),await n.leave().catch(T=>i(`leaving the match failed: ${Qe(T)}`))),O();})(),W),Ce=null,be=()=>(Ce??=_n(C,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),Ce),Oe=async()=>{try{return await ws({client:be().client,gameId:()=>C.gameId},C.matchId,{},{signal:AbortSignal.timeout(Fy)}),{answer:"ok"}}catch(y){return y instanceof G&&(y.reason==="forbidden"||y.reason==="not_found")?{answer:y.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${y.reason})`}:{answer:"failed",cause:`ending the match failed: ${Qe(y)}`}}},ee=null,X=false,ae=()=>{X=true,ee!==null&&(e.clock.clearTimeout(ee),ee=null);},dt=async()=>{if(ee=null,!X){try{await be().client.post(`/v1/games/${encodeURIComponent(C.gameId)}/matches/${encodeURIComponent(C.matchId)}/heartbeat`,void 0,AbortSignal.timeout(jy));}catch(y){if(y instanceof G&&(y.reason==="forbidden"||y.reason==="not_found")){i(`the platform no longer holds this match under this host (${y.reason}); heartbeats stop`),ae();return}i(`heartbeat failed: ${Qe(y)}`);}X||(ee=e.clock.setTimeout(()=>{dt();},Zl));}},Sn=()=>{X||ee!==null||(ee=e.clock.setTimeout(()=>{dt();},Zl));};{let y=O;O=()=>{ae(),Ce?.dispose(),Ce=null,y();};}let en=Promise.resolve().then(()=>a.init(C));s=en.then(()=>{},()=>{}),m("join",()=>a.join?.(r,{playerNumber:nd,transport:"loopback"})),F.push(n.on("peerJoined",N)),F.push(n.on("peerLeft",(y,T)=>{S(y);let j=e.clock.now();for(let[ne,ve]of A)j-ve>=ed&&A.delete(ne);A.set(y,j),q.delete(y),m("leave",()=>a.leave?.(y,{cause:T}));})),F.push(n.on("error",y=>{i(`\u26A0 session error: ${y.message}`);})),F.push(n.on("matchEnded",y=>{W||ti(f,y),pe("match ended",{reason:"match_ended",platform_reason:y});})),F.push(n.on("hostChanged",y=>{y!==r&&pe("host migrated",{reason:"host_migrated"});}));for(let y of n.peers)N(y);try{await en,Sn();}catch(y){l=false,ae(),d=true;for(let T of F.splice(0))T();for(let T of [...M.keys()])S(T);throw n.leave().catch(()=>{}),O(),y}return {matchId:n.matchId,localLink:R,onMatchEnded(y){f=y;},end:Me,leave:z,stop:y=>pe(y,{reason:"stopped"}),done:D}}function ti(t,e){try{t?.(e);}catch{}}function Qe(t){return t instanceof Error?t.message:String(t)}function ri(t,e){let n=async()=>{throw new b("misconfigured",`this seat is \`${t}\`, not the match's authority: `+(t==="dedicated"?"the platform runs the server, and its bundle ends the match with gem.match.end().":"another player hosts this match."))};return {mode:t,matchId:e,end:n,leave:n,stop:async()=>{}}}function rd(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,o=new Map,i=async s=>{r.isHost&&!Qo(r)&&r.currentRoom?.matchId===void 0&&await r.startMatch({...s.clusterTargetId===void 0||s.clusterTargetId===null?{}:{clusterTargetId:s.clusterTargetId},...s.signal===void 0?{}:{signal:s.signal}});let l={...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal}};return r.matchConnectionState==="suspended"?r.reconnectToMatch(l):r.awaitMatch(l)},a=s=>({...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal},...s.clusterTargetId===void 0?{}:{clusterTargetId:s.clusterTargetId}});return {async serve(s,l={}){let d=await i(l);if(d.protocol!==ze)return ri("dedicated",d.matchId);let m=t.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return ri("peer",d.matchId);let u=t.identity();if(u===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let p=m??await t.p2p.connect(a(l)),g=await td(s,{session:p,clock:t.clock,gameId:u.gameId,channel:u.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:t.apiBaseUrl(),tokens:t.tokens,room:t.room,localPlayerId:p.playerId!==""?p.playerId:u.playerId,...t.log===void 0?{}:{log:t.log},...t.fetch===void 0?{}:{fetch:t.fetch}});return o.set(d.matchId,g),g.done.then(()=>{o.get(d.matchId)===g&&o.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>g.end(),leave:()=>g.leave(),stop:()=>g.stop()}},async connect(s={}){let l=await i(s),d=s.onMatchEnded;if(l.protocol===ze){let g=o.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),By(l.matchId,g,d);if(r.isHost)throw new Error("[gem] this player hosts the P2P match, so there is no one to connect TO yet. Call gem.match.serve(yourServer) first; connect() then resolves the loopback to your own bundle.");let f=await Qn(),w=async()=>t.p2p.connect({...a(s),certificate:f}),R=await w(),I=Vy(R,w,d,M=>{r.notifyMatchDisconnected(M).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(R.matchId,{redial:I.redial,abandon:I.abandon}),I.onClosed(()=>{e.get(R.matchId)?.abandon===I.abandon&&e.delete(R.matchId);})),I}let m=async(g=null)=>await t.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...s.timeoutMs===void 0?{}:{timeoutMs:s.timeoutMs},...s.signal===void 0?{}:{signal:s.signal},...s.clusterTargetId===void 0||s.clusterTargetId===null?{}:{clusterTargetId:s.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:s.transports??[]}),u=await m(),p=Hy(u,m,r,n);return n&&(e.set(u.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(u.matchId)?.abandon===p.abandon&&e.delete(u.matchId);})),p},async redialMatch(s,l){let d=e.get(s);return d===void 0?"closed":d.redial(l)},abandonMatch(s,l){e.get(s)?.abandon(l);}}}var od="link_closed",qy="host_unreachable",Ny=new Set(["failed","closed"]);function Uy(t){return Ny.has(t)?od:qy}function By(t,e,n){let r=e.localLink;e.onMatchEnded(n);let o="connected";r.onClose(()=>{o="closed";});let i;return {matchId:t,protocol:"loopback",get state(){return o},send:(a,s)=>r.send(a,s),onMessage:a=>r.onMessage(a),onClose:a=>{i=a,r.onClose(s=>{o="closed",i?.(s);});},close:()=>r.close()}}function Hy(t,e,n,r){let o=t.matchId,i=t,a="connected",s,l,d=[],m=false,u=false,p=f=>{if(a!=="closed"){a="closed";for(let w of d.splice(0))w();l?.(f);}},g=f=>{f.link.onMessage((w,R)=>s?.(w,R)),f.link.onClose(w=>{if(f!==i||a==="closed")return;if(m||!r){p(w);return}let R=n.matchSession;if(R.phase==="suspended"&&R.matchId===o){a="suspended";return}p(w);});};return g(t),{matchId:o,protocol:"dedicated",get transport(){return i.transport},get state(){return a},send(f,w){a==="connected"&&i.link.send(f,w);},onMessage(f){s=f;},onClose(f){l=f;},close(){if(a!=="closed"){if(m=true,a==="suspended"){p("closed");return}i.close(),p("closed");}},async redial(f){if(a==="closed"||m)return "closed";if(u)return "connected";u=true;let w;try{w=await e(f===void 0?{}:{deadlineAt:f});}finally{u=false;}return m||a==="closed"?(w.close(),"closed"):(i=w,g(w),a="connected",n.notifyMatchConnected(o),"connected")},abandon(f){a!=="closed"&&(a==="connected"&&i.close(),p(f));},onClosed(f){a==="closed"?f():d.push(f);}}}function Vy(t,e,n,r,o,i=false){let a=t.matchId,s=t,l,d,m=[],u=[],p=[],g=false,f=false,w=false,R=false,I="connected",M=k=>{if(g)return;g=true,I="closed";for(let O of m.splice(0))O();for(let O of u.splice(0))O();for(let O of p.splice(0))O();let C=d;C&&queueMicrotask(()=>C(k));},_=k=>{for(let C of m.splice(0))C();for(let C of Ie){let O=k.channels[C];try{O.binaryType="arraybuffer";}catch{}let D=wn(C),F=W=>{let Q=gr(W?.data);Q!==null&&l?.(Q.data,D);};O.addEventListener("message",F),m.push(()=>O.removeEventListener("message",F));}},S=()=>s.peer(s.hostPlayerId),E=k=>{if(!(g||s.isHost)&&I!=="suspended"){if(r?.(k),i){I="suspended";return}M(k);}},A=k=>{for(let C of Ie){let O=k.channels[C];if(typeof O.addEventListener!="function")continue;let D=()=>{S()===k&&E(od);};O.addEventListener("close",D),m.push(()=>O.removeEventListener?.("close",D));}},V=k=>{_(k),A(k),!g&&(I="connected",o?.());},N=k=>{for(let C of u.splice(0))C();u.push(k.on("migrating",()=>{R=true;})),u.push(k.on("hostChanged",C=>{if(R=false,C===k.playerId){M("host_migrated_here");return}let O=S();O!==null&&V(O);})),u.push(k.on("peerJoined",C=>{C.playerId===k.hostPlayerId&&V(C);})),u.push(k.on("matchEnded",C=>{g||ti(n,C),M(C);})),u.push(k.on("peerLeft",(C,O)=>{C===k.hostPlayerId&&E(Uy(O));}));};N(s);let q=S();return q!==null&&V(q),{matchId:a,protocol:"p2p",get state(){return I},send(k,C){I==="connected"&&S()?.send(it(k),Xe(C));},onMessage(k){l=k;},onClose(k){d=k;},close(){f=true,M("closed"),s.leave().catch(()=>{});},async redial(){if(I==="closed")return "closed";if(I==="connected"||w)return "connected";if(R)throw new L("connection_failed","a host migration is in flight, and it is the way back \u2014 this attempt waits it out rather than tearing down the session the platform is moving");w=true;let k;try{for(let O of m.splice(0))O();for(let O of u.splice(0))O();s.close(),k=await e();}finally{w=false;}if(g)return f?k.leave().catch(()=>{}):k.close(),"closed";s=k,N(s);let C=S();if(C===null)throw s.close(),new L("connection_failed","this peer rejoined the match but the host never answered with a link");return V(C),"connected"},abandon(k){M(k);},onClosed(k){g?k():p.push(k);}}}function oi(t){let e=0,n=new Map;return {resolve(){if(!t.bridge.parentSupports("parties"))return Promise.resolve(void 0);let r=`party-${String(++e)}`;return new Promise(o=>{let i={},a=l=>{n.delete(r)&&(t.clock.clearTimeout(i.timer),o(l));};n.set(r,a),i.timer=t.clock.setTimeout(()=>a(void 0),t.timeoutMs??2e3);let s=false;try{s=t.bridge.requestParty(r);}catch{}s||a(void 0);})},settle(r,o){n.get(r)?.(o);}}}var Wy=12e4;function Ze(t,e){return {outcome:t,reason:e}}function id(t){let e=false,n=new Map;return {api:{request(r){if(!t.bridge.parentSupports("purchases"))return Promise.resolve(Ze("unavailable","error"));if(e)return Promise.resolve(Ze("declined","busy"));let o=`purchase-${Ae()}`;return new Promise(i=>{let a={},s=d=>{n.delete(o)&&(e=false,t.clock.clearTimeout(a.timer),i(d));};e=true,n.set(o,s),a.timer=t.clock.setTimeout(()=>s(Ze("unavailable","error")),t.timeoutMs??Wy);let l=false;try{l=t.bridge.requestPurchase(o,r.kind,r.targetId,r.currencySlug,r.quantity,r.catalogId);}catch{}l||s(Ze("unavailable","error"));})}},settle(r){let o=r.outcome==="ok"||r.outcome==="declined"?r.outcome:"unavailable",i=n.get(r.requestId);if(i===void 0){t.onDropped?.(`gem.purchaseResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}if(o!=="ok"){i(Ze(o,qs(r.reason)));return}let a=r.purchaseId;if(a===void 0){t.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),i(Ze("unavailable","error"));return}(async()=>{let s;try{s=await t.confirm(a);}catch{s="unknown";}if(s==="granted"){i({outcome:"ok",purchaseId:a});return}s==="absent"&&t.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for purchase "+JSON.stringify(a)),i(Ze("unavailable","error"));})();}}}async function sd(t,e){try{return (await ss(t,e)).granted?"granted":"absent"}catch(n){return n instanceof G&&n.reason==="not_found"?"absent":"unknown"}}var Ky=6e5;function ad(t){let e=null,n=new Map;return {api:{requestSignIn(){if(!t.bridge.parentSupports("signIn"))return Promise.resolve({outcome:"unavailable"});if(e!==null)return e;let r=`signin-${Ae()}`;return e=new Promise(o=>{let i={},a=l=>{n.delete(r)&&(e=null,t.clock.clearTimeout(i.timer),o(l));};n.set(r,a),i.timer=t.clock.setTimeout(()=>{a({outcome:"unavailable"});},t.timeoutMs??Ky);let s=false;try{s=t.bridge.requestSignIn(r);}catch{}s||a({outcome:"unavailable"});}),e}},settle(r){let o=r.outcome==="signed_in"||r.outcome==="declined"?r.outcome:"unavailable",i=n.get(r.requestId);if(i===void 0){t.onDropped?.(`gem.signInResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}i({outcome:o});}}}var Jy=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid"]),zy=["utm_"];function ld(t){return Jy.has(t)||zy.some(e=>t.startsWith(e))}var dd=16,cd=512,Yy=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,Xy=/[\p{Cc}\p{Cf}]/u,Qy=/\p{Cs}/u,Te="[gem] gem.share.request:";function ud(t){let{frame:e,log:n}=t,r=false,o=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,i=a=>{n!==null&&(n===void 0?console.warn(a):n(a));};return {get available(){return o()!==null},request(a){let s=o();if(s===null)throw new Error(`${Te} the arcade does not handle share here \u2014 check gem.share.available first`);if(a!==void 0&&(typeof a!="object"||a===null))throw new TypeError(`${Te} pass { params }, or nothing`);let l=a?.params===void 0?{}:a.params;if(!Zy(l))throw new TypeError(`${Te} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>dd)throw new TypeError(`${Te} at most ${dd} params; got ${d.length}`);let m=[];for(let[u,p]of d){let g=JSON.stringify(u);if(!Yy.test(u))throw new TypeError(`${Te} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(ld(u))throw new TypeError(`${Te} param ${g} is reserved: the arcade reads it itself and never forwards it`);if(typeof p!="string")throw new TypeError(`${Te} param ${g}: values must be strings`);if(p.length>cd)throw new TypeError(`${Te} param ${g}: a value is at most ${cd} characters`);if(Xy.test(p))throw new TypeError(`${Te} param ${g}: control and format characters are not allowed`);if(Qy.test(p))throw new TypeError(`${Te} param ${g}: a value must be well-formed text`);m.push({key:u,value:p});}!s.requestShare(m)&&!r&&(r=true,i("[gem] gem.share.request was not sent: more than 6 share requests in a minute. Call it from your Share button's click, not a loop."));}}}function Zy(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var ef=18e4,md=32,nf=/^[a-z0-9_-]+$/;function tf(t){return t==="interstitial"||t==="rewarded"}function pd(t){let e=false,n=new Map;return {api:{requestAd(r){if(!t.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});if(typeof r.placement!="string"||r.placement===""||r.placement.length>md||!nf.test(r.placement)||!tf(r.format))return t.onDropped?.(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${JSON.stringify(r.placement)}, format ${JSON.stringify(r.format)}. A placement is 1..${String(md)} characters of a-z, 0-9, '-' and '_' \u2014 the grammar the platform's own ad endpoint accepts \u2014 and a format is 'interstitial' or 'rewarded'. Answering no_ad.`),Promise.resolve({outcome:"no_ad"});let o=`ad-${Ae()}`,i=r.format,a=r.placement;return new Promise(s=>{let l={},d=u=>{n.delete(o)&&(e=false,t.clock.clearTimeout(l.timer),s(u));};e=true,n.set(o,d),l.timer=t.clock.setTimeout(()=>{d({outcome:"unavailable"});},t.timeoutMs??ef);let m=false;try{m=t.bridge.requestAd(o,a,i);}catch{}m||d({outcome:"no_ad"});})}},settle(r){let o=r.outcome==="shown"||r.outcome==="no_ad"?r.outcome:"unavailable",i=n.get(r.requestId);if(i===void 0){t.onDropped?.(`gem.adResult (${o}) for an unknown requestId: `+JSON.stringify(r.requestId));return}i({outcome:o});}}}var ii=16384;function gd(t){if(typeof t!="object"||t===null||Array.isArray(t))return null;let e;try{e=JSON.stringify(t);}catch{return null}return typeof e!="string"?null:rf(e)}function rf(t){let e=0;for(let n=0;n<t.length;n+=1){let r=t.charCodeAt(n);if(r<128)e+=1;else if(r<2048)e+=2;else if(r>=55296&&r<=56319){let o=t.charCodeAt(n+1);o>=56320&&o<=57343?(e+=4,n+=1):e+=3;}else e+=3;}return e}var of=1e4,sf=5e3;function yd(t){let e=null,n=false,r=[],o=new Map,i=()=>{for(let a of r.splice(0))a();};return {api:{get current(){return e},wait(a=sf){return n?Promise.resolve(e):new Promise(s=>{let l=()=>{let u=r.indexOf(d);u>=0&&r.splice(u,1);},d=()=>{t.clock.clearTimeout(m),l(),s(e);},m=t.clock.setTimeout(()=>{l(),s(e);},a);r.push(d);})},put(a){if(!t.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let s=gd(a);if(s===null)return t.onDropped?.("gem.deviceSettings.put refused locally: settings must be a plain JSON object (not a primitive, an array, null, or something JSON.stringify cannot take)"),Promise.resolve("unavailable");if(s>16384)return Promise.resolve("too_large");let l=JSON.parse(JSON.stringify(a)),d=`device-settings-${Ae()}`;return new Promise(m=>{let u={},p=f=>{o.delete(d)&&(t.clock.clearTimeout(u.timer),f==="stored"&&(e=l,n=true,i()),m(f));};o.set(d,p),u.timer=t.clock.setTimeout(()=>p("unavailable"),t.timeoutMs??of);let g=false;try{g=t.bridge.putDeviceSettings(d,l);}catch{}g||p("unavailable");})}},receive(a){let s=a.settings;e=typeof s=="object"&&s!==null&&!Array.isArray(s)?s:null,n=true,i();},settle(a){let s=a.outcome==="stored"||a.outcome==="too_large"?a.outcome:"unavailable",l=o.get(a.requestId);if(l===void 0){t.onDropped?.(`gem.deviceSettings.result (${s}) for an unknown requestId: `+JSON.stringify(a.requestId));return}l(s);}}}var st=class extends Error{constructor(){super("createGem: this game is not framed (window.parent === window), so nothing can hand it a player, saves, config or rooms. Play it in the Gem Arcade or the Gem Editor, or through the Gem dev host on this machine: `npm run dev` (`gemctl serve start . --dev`) while editing, `gemctl serve start .` for a build, signed in to gemctl. Do not open the dev server's own address."),this.name="GemUnframedError";}};function fd(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function si(t,e){if(t!==true)return {visible:false};let n=[],r=false;for(let o of Array.isArray(e)?e:[])o==="score"?r=true:typeof o=="string"&&o.length>0&&o.length<=64&&!n.includes(o)&&n.push(o);return !r&&n.length===0?{visible:true}:{visible:true,currencies:n.slice(0,8),score:r}}function yr(t,e){let n=[];for(let r of Array.isArray(e)?e:[]){if(n.length===4)break;if(typeof r!="object"||r===null)continue;let{id:o,label:i}=r;typeof o!="string"||o.length===0||o.length>32||typeof i!="string"||i.trim().length===0||n.some(a=>a.id===o)||n.push({id:o,label:i.trim().slice(0,40)});}return n.length===0?{settings:t===true}:{settings:t===true,items:n}}function hd(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function af(t){let e=t.untrusted,n=ge(e.displayName),r=e.displayTag||e.displayHandle,o=r?ge(r):void 0,i=t.discriminator||t.displayTag,a=i&&/^[0-9]{1,8}$/.test(i)?i:void 0,s=t.avatarIconUrl||t.avatarUrl,l={displayName:n,displayHandle:o??n,badges:(t.badges??[]).map(p=>({itemId:p.itemId,iconUrl:p.iconUrl}))};t.playerId&&(l.playerId=t.playerId),a&&(l.discriminator=a),o&&(l.displayTag=o),s&&(l.avatarIconUrl=l.avatarUrl=s);let d=t.boost,m=(d?.multipliers??[]).map(p=>({currencyId:p.currencyId,currencySlug:p.currencySlug,multiplier:p.multiplierBp/1e4})),u=m.some(p=>p.multiplier>1);return l.boost=u&&d?.expiresInDays?{active:u,multipliers:m,expiresInDays:d.expiresInDays}:{active:u,multipliers:m},l}var lf=1e4,at=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??le,this.inbound=new xn(this.clock),this.outbound=new xn(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=>Er(s,e.origin))||Ds(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=wt["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let o=e.data;if(!Er(o.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${o.embedder}' but arrived from '${e.origin}'`),false;let i=e.ports?.[0];if(!i)return this.refuse(e,"handshake transferred no MessagePort"),false;let a=$s(vt,o.versions);return a===null?(i.onmessage=null,i.postMessage({gem:U,type:"gem.error",code:"version_mismatch",message:`frame supports v${vt.min}..v${vt.max}`}),i.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=i,this.version=a,i.onmessage=s=>this.receive(s.data,s.ports??[]),i.start?.(),this.peerCapabilities=o.capabilities??[],this.unbidden=o.unbidden===true,i.postMessage({gem:U,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:U,type:"gem.ready"});}settled(e=lf){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(n=>{let r=i=>{this.clock.clearTimeout(o),n(i);},o=this.clock.setTimeout(()=>{let i=this.settleWaiters.indexOf(r);i>=0&&this.settleWaiters.splice(i,1),n(this.state);},e);this.settleWaiters.push(r);})}progress(e,n){this.send({gem:U,type:"gem.progress",loaded:e,total:n});}requestToken(e,n){this.send({gem:U,type:"gem.requestToken",requestId:e,reason:n});}requestLocalServer(e,n){return this.parentSupports("localHost")?(this.send({gem:U,type:"gem.requestLocalServer",requestId:e,gameRoomId:n}),true):false}exit(e){this.send(e===void 0?{gem:U,type:"gem.exit"}:{gem:U,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:U,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:U,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.state!=="connected"||!this.parentSupports("audioState")?false:(this.send({gem:U,type:"gem.audioState",muted:e}),true)}reportEngaged(){return this.engagedSent||this.state!=="connected"||!this.parentSupports("engagement")||!this.send({gem:U,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(this.state!=="connected"||!this.parentSupports("rewardCue"))return false;let n={gem:U,type:"gem.rewardCue",currencySlug:String(e.currencySlug).slice(0,32)};return e.expected!==void 0&&Number.isFinite(e.expected)&&e.expected>=1&&(n.expected=Math.min(1e9,Math.round(e.expected))),e.origin&&(n.origin={x:fd(e.origin.x),y:fd(e.origin.y)}),this.send(n),true}setWalletVisible(e,n){return this.state!=="connected"||!this.parentSupports("walletDisplay")?false:this.send({gem:U,type:"gem.walletDisplay",...si(e,n?.only)})}setMenu(e,n){return this.state!=="connected"||!this.parentSupports("gameMenu")?false:this.send({gem:U,type:"gem.menu",...yr(e,n)})}requestShare(e){return this.state!=="connected"||!this.parentSupports("share")?false:this.send({gem:U,type:"gem.requestShare",params:e.map(({key:n,value:r})=>({key:n,value:r}))})}reportFrameStats(e){return this.state!=="connected"||!this.parentSupports("frameStats")?false:(this.send({gem:U,type:"gem.frameStats",fps:hd(e.fps,1e3),frameTimeP95Ms:hd(e.frameTimeP95Ms,1e5)}),true)}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:U,type:"gem.gameContext",context:e}),true)}signal(e,n,r){this.send({gem:U,type:"gem.signal",signal:e,matchId:n,data:r});}dedicatedOffer(e,n,r){this.send({gem:U,type:"gem.dedicatedOffer",matchId:e,sdp:n,intent:r});}requestParty(e){return this.send({gem:U,type:"gem.partyRequest",requestId:e})}requestPurchase(e,n,r,o,i,a){return this.send({gem:U,type:"gem.requestPurchase",requestId:e,purchaseKind:n,targetId:r,currencySlug:o,...i===void 0?{}:{quantity:i},...a===void 0?{}:{catalogId:a}})}putDeviceSettings(e,n){return this.send({gem:U,type:"gem.deviceSettings.put",requestId:e,settings:n})}requestAd(e,n,r){return this.send({gem:U,type:"gem.requestAd",requestId:e,placement:n,format:r})}requestSignIn(e){return this.send({gem:U,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,n,r,o){return this.send({gem:U,type:"gem.requestFriendChallenge",requestId:e,playerId:n,template:r,...o===void 0?{}:{params:o}})}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 n of this.settleWaiters.splice(0))n(e);this.options.onStateChange?.(e);}}refuseMalformed(e,n){if(!this.inbound.allow(_t)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(_t)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(_t)&&this.options.onRefused?.(n);}fail(e,n){this.options.onError?.(e,n),this.state==="connected"&&this.port&&this.send({gem:U,type:"gem.error",code:e,...n===void 0?{}:{message:n}});}send(e){if(this.state!=="connected"||!this.port)return this.options.onDropped?.("internal",`dropped ${String(e.type)} before connect`),false;let n=e.type;if(!this.outbound.allow(n))return this.options.onError?.("rate_limited",`frame exceeded its own limit for ${n}`),false;let r=wt[n]?.(e);return r?(this.options.onError?.("internal",`refusing to send malformed ${n}: ${r}`),false):(this.port.postMessage(this.version===null?e:{...e,v:this.version}),true)}receive(e,n=[]){let r=false;try{r=this.dispatchInbound(e,n);}finally{r||bd(n);}}dispatchInbound(e,n){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 o=wt[r];if(!o)return this.dropUnknownType(r),false;if(!this.inbound.allow(r))return this.fail("rate_limited",`parent exceeded the limit for ${r}`),false;let i=Os(r);if(i!==void 0&&!this.options.capabilities?.includes(i))return this.fail("unsupported_capability",`${r} requires the '${i}' capability, which this frame did not advertise`),false;let a=o(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=n[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 bd(n.slice(1)),this.options.onScreenshot(d,l,(m,u)=>this.screenshotDenied(m,u)),true}case "gem.token.denied":this.options.onTokenDenied?.(s);break;case "gem.localServer":this.options.onLocalServer?.(s);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(s);break;case "gem.player":{this.options.onPlayer?.(af(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,n){this.send({gem:U,type:"gem.screenshot.denied",reason:e,retryable:n});}};function bd(t){for(let e of t)try{e?.close?.();}catch{}}var vd="https://api.gemarcade.com";function ai(t){let e;try{e=new URL(t);}catch{return "it is not a valid URL"}return e.protocol!=="https:"&&e.protocol!=="http:"?`its scheme is ${e.protocol.replace(":","")}, and only http and https can be used`:e.username!==""||e.password!==""?"it carries credentials in the URL, which `fetch` will not send":e.href.includes("#")?"it carries a fragment. The transport joins the base and the path by concatenation, so the fragment would swallow the path and every request would go to the API root":e.href.includes("?")?"it carries a query string. The transport joins the base and the path by concatenation, so the query would swallow the path and every request would go to the API root":null}var df=new Set(["localhost","127.0.0.1","[::1]"]);function _d(t){let e=ai(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!df.has(n.hostname)?"it is a plaintext http address that is not loopback. An embedder may name an https root, or http on localhost for a rig running the whole stack on one machine \u2014 the play token travels on every request to it":null}var cf=Object.freeze(["https://gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),uf=vd,wd=8e3,li=15e3,mf=9e4,pf=1/0,gf=8e3,yf=5e3,ff=5e3;async function hf(t,e,n,r){if(t.isInRoom)try{await t.leave();}catch{}r?.endSession("session_ended"),e!==null&&e.currentState==="connected"&&e.exit(n);}function lt(t){let e=null,n=false,r=[];return {get current(){return e},set(o){e=o;for(let i of r.splice(0))i(o);},release(){n=true;for(let o of r.splice(0))o(e);},wait(o){return e!==null||n?Promise.resolve(e):new Promise(i=>{let a=()=>{let d=r.indexOf(s);d>=0&&r.splice(d,1);},s=d=>{t.clearTimeout(l),a(),i(d);},l=t.setTimeout(()=>{a(),i(e);},o);r.push(s);})}}}function JS(t={}){let e=t.clock??le,n=t.log===void 0?c=>console.info(c):t.log,r=t.baseUrl??void 0;if(r!=null){let c=ai(r);if(c!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${c}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let o=No();o.mark("sdk created");let i=()=>Kt(Y.gameVersion,t.clientVersion?.gameVersion),a=new Fn({client:()=>tn,clock:e,gameId:()=>Y.identity?.gameId??null,playerId:()=>Y.identity?.playerId??null,environment:()=>{let c=i();return {sdk_version:xi(),...c===null?{}:{game_version:c}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),s=dl(()=>{o.mark("engaged"),a.release(),y.reportEngaged();},typeof window>"u"?{}:window),l=c=>{if(c===false)return null;let x=c?.attempts??pf,$=c?.budgetMs??mf;return !(x>0)||!($>0)?null:{attempts:x,budgetMs:$,maxDelayMs:c?.maxDelayMs??gf}},d=c=>{c.on("created",()=>{o.mark("room created");}),c.on("joined",()=>{o.mark("room joined");}),c.on("matchAllocationStarted",()=>{o.mark("allocation started");}),c.on("matchReady",()=>{o.mark("match ready");}),c.on("matchFailed",()=>{o.mark("match failed");});};if(typeof window>"u")throw new Error("createGem: there is no `window` in this environment, so the SDK has no document to listen on and no embedder to hand it a port. A game runs in a browser; if this is a server-side render or a node process, do not construct the SDK there.");if(window.parent===window)throw new st;let m=t.allowedEmbedders;if(m!=null&&!Array.isArray(m))throw new Error("createGem: `allowedEmbedders` must be an array of origins, e.g. `['https://my-own-site.example']`. The Gem Arcade is allowed without any entry.");let u=Array.from(m??[]),p=u.filter(c=>typeof c!="string"||!Pr(c));if(p.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${p.length===1?"an entry":"entries"} that ${p.length===1?"is":"are"} not an origin: ${p.map(c=>typeof c=="string"?JSON.stringify(c):String(c)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let g=Object.freeze([...new Set([...cf,...u])]),f=lt(e),w=lt(e),R=lt(e),I=ua(n),M=lt(e),_=t.manageAudio===false?null:fl();t.selectableText!==true&&hl();let S=null,E=()=>{S!==null&&(w.current!==null&&w.current.muted===S||y.reportMuted(S));},A=null,V=null,N=()=>{if(A===null)return false;let c=JSON.stringify(si(A.visible,A.only));return c===V?y.parentSupports("walletDisplay"):y.setWalletVisible(A.visible,A)?(V=c,true):false},q=null,k=null,C=()=>{if(q===null)return false;let c=typeof q.onSettings=="function",x=JSON.stringify(yr(c,q.items));return x===k?y.parentSupports("gameMenu"):y.setMenu(c,q.items)?(k=x,true):false},O=bl({report:c=>y.reportFrameStats(c)}),D=false,F=xl(()=>wi,()=>D),W=c=>{let x=D&&!c,$=D!==c;if(D=c,x&&F.close(),!!$)try{t.onDevToolsPermissionChange?.(c);}catch(te){n?.(`[gem] onDevToolsPermissionChange threw: ${te instanceof Error?te.message:String(te)}`),queueMicrotask(()=>{throw te});}},Q=r??uf,pe=r!==void 0,z,Me=c=>(n?.(`[gem] token refused: ${c}`),t.onError?.("internal",c),false),Ce=(c,x)=>{if(c===void 0)return x!==void 0?Me("the embedder named a backend by tag, which this build no longer resolves \u2014 it needs `apiBaseUrl` on `gem.token`. The token was refused rather than sent to the default: silently resolving production is how a development session writes to the live backend."):true;let $=_d(c);return $!==null?Me(`the embedder named an API root that cannot be used: ${$}. Its value is withheld here rather than written to logs.`):z!==void 0&&z!==c?Me("the embedder named a different API root than it named on this session\u2019s first token. The address is fixed by the first grant, so a later message cannot repoint a running game; both values are withheld here."):(z=c,pe||(Q=c),true)},be=window.location?.origin,Oe=null,ee=-1/0,X=2e3,ae=new Set,dt=c=>Oe!==false?Promise.resolve(true):new Promise(x=>{let $=e.setTimeout(()=>{ae.delete(te),x(false);},c),te=()=>{e.clearTimeout($),ae.delete(te),x(true);};ae.add(te);}),Sn=()=>{},en=null,y=new at({allowedEmbedders:g,...typeof be=="string"&&be!==""?{selfOrigin:be}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","clusterTarget","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","earnAllowance","share","frameStats","walletDisplay","gameMenu","engagement","reservedAreas","viewport","purchases","deviceSettings","ads","signIn","friendChallenges",...t.onFeedbackContext!==void 0?["feedbackContext"]:[]],onRefused:c=>{en=c,t.onRefused?.(c);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:c=>{Y.onBridgeState(c),c!=="connected"&&O.setRequested(false),V=null,k=null,c==="refused"&&(console.error("[gem] this game refused the page that framed it"+(en===null?"":` (${en})`)+", so it has no player, saves, config or rooms. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders."),Sn()),c==="connected"&&(o.mark("bridge connected"),xd(),E(),N(),C(),y.unbiddenLaunch&&!s.engaged&&a.hold(),a.startSession(),s.engaged&&y.reportEngaged()),t.onStateChange?.(c);},onPlayer:c=>{f.set(c),t.onPlayer?.(c);},onPrefs:c=>{let x={reducedMotion:c.reducedMotion,muted:c.muted,locale:c.locale,showFrameStats:c.showFrameStats===true};w.set(x),_?.setMuted(x.muted),O.setRequested(x.showFrameStats&&y.parentSupports("frameStats")),t.onPrefs?.(x);},onCohorts:c=>{let x=Object.freeze(c.cohorts.map($=>Object.freeze({experimentId:$.experimentId,variantKey:$.variantKey})));R.set(x),t.onCohorts?.(x);},onEarnAllowanceChanged:()=>I.emit(),onViewport:c=>{let x=Object.freeze({insets:Object.freeze({top:c.insets.top,right:c.insets.right,bottom:c.insets.bottom,left:c.insets.left}),reserved:Object.freeze((c.reserved??[]).map(te=>Object.freeze({x:te.x,y:te.y,width:te.width,height:te.height})))});M.set(x);let $=_l();wl($,x.insets),Rl($,x.reserved,Sl()),t.onViewport?.(x);},onPause:c=>{a.setPaused(c.paused),O.setPaused(c.paused),t.onPause?.(c.paused);},onMenuSelect:c=>{if(q===null)return;if(c.entry==="settings"){q.onSettings?.();return}(yr(false,q.items).items??[]).some($=>$.id===c.id)&&q.items?.find($=>$.id===c.id)?.onSelect?.();},onWillTerminate:c=>{a.endSession(c.reason),t.onWillTerminate?.({reason:c.reason,graceMs:c.graceMs});},onToken:c=>{let x=c.garden;if(W(c.allowDevTools===true),!Ce(c.apiBaseUrl,x))return;let $=c;Y.onToken($);let te=Y.identity;te&&(j.set(te),ne||(ne=true,ce.reconcileSeats().catch(()=>{}))),ct.push({token:$.token,expiresAt:$.expiresAt});},onTokenDenied:c=>{W(false),Y.onDenied(c);},onScreenshot:(c,x,$)=>{pl(c,x,$,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{gl(y,t.onFeedbackContext);},onDevtools:c=>{c==="close"?F.close():c==="open"?F.openFrom("platform").catch(()=>{}):F.isOpen?F.close():F.openFrom("platform").catch(()=>{});},onRoomEvent:c=>ce.handleRoomEvent({event:c.event,roomId:c.roomId,...c.matchId===void 0?{}:{matchId:c.matchId},...c.version===void 0?{}:{version:c.version},...c.reason===void 0?{}:{reason:c.reason},...c.platform===void 0?{}:{platform:c.platform}}),onSeatedEvent:c=>ce.handleSeated(c.roomId),onAutoStartFailedEvent:c=>ce.handleAutoStartFailed(c.roomId,c.code),onSocketState:c=>{let x=Oe;if(Oe=c.connected,c.connected)for(let te of [...ae])te();if(!c.connected||x===true)return;let $=e.now();$-ee<X||(ee=$,ce.reconcile().catch(()=>{}));},onSignalEvent:c=>{let x=typeof c.data=="object"&&c.data!==null&&!Array.isArray(c.data)?c.data:{};rn.handleSignalEvent(c.matchId,c.event,x),c.event==="matchEnded"&&ce.reconcile({matchId:c.matchId,...typeof x.reason=="string"?{reason:x.reason}:{}}).catch(()=>{});},onDedicatedEvent:c=>{c.event==="matchEnded"&&(Rn.handleMatchEnded(c.matchId,c.reason),ce.reconcile({matchId:c.matchId,...c.reason===void 0?{}:{reason:c.reason}}).catch(()=>{})),T.handleEvent(c);},onClusterTarget:c=>mt.accept(c.clusterTargetId,c.clusterTargetIds),onLocalServer:c=>pt.accept(c),onLocalServerDenied:c=>pt.refuse(c),onPartyResult:c=>ui.settle(c.requestId,c.partyId),onPurchaseResult:c=>pi.settle(c),onDeviceSettings:c=>{ut.receive(c),t.onDeviceSettings?.(ut.api.current);},onDeviceSettingsResult:c=>ut.settle(c),onAdResult:c=>gi.settle(c),onSignInResult:c=>yi.settle(c),onFriendChallengeResult:c=>fi.settle(c)}),T=new ot({bridge:y}),j=lt(e);Sn=()=>{j.release(),f.release(),R.release();},y.currentState==="refused"&&Sn();let ne=false,ve=new Set,qe,ct={current:()=>qe,subscribe:c=>(ve.add(c),qe!==void 0&&c(qe),()=>ve.delete(c)),push:c=>{qe=c;for(let x of [...ve])try{x(c);}catch($){n?.(`[gem] a server-token listener threw: ${$ instanceof Error?$.message:String($)}`);}}},Y=Pl({bridge:y,clock:e,onStateChange:(c,x)=>{if(c==="ready"){if(o.mark("token ready")){let $=o.marks.find(te=>te.name==="token ready")?.at;a.trackPlatform("gem_boot_ready",$===void 0?{}:{boot_ms:Math.max(0,Math.round($))});}}else c==="lost"&&(o.mark("token lost"),a.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(c,x);}}),ci=()=>{let c=Y.identity;return !c||Y.source.currentState==="lost"?null:`${c.playerId}\0${c.gameId}\0${c.channel}`},xd=()=>{o.mark("token requested"),Y.source.get().catch(()=>{});},ui=oi({bridge:y,clock:e}),mi={},pi=id({bridge:y,clock:e,onDropped:c=>t.onError?.("internal",c),confirm:async c=>mi.confirm?.(c)??"unknown"}),ut=yd({bridge:y,clock:e,onDropped:c=>t.onError?.("internal",c)}),gi=pd({bridge:y,clock:e,onDropped:c=>t.onError?.("internal",c)}),yi=ad({bridge:y,clock:e,onDropped:c=>t.onError?.("internal",c)}),fi=ca({bridge:y,clock:e,onDropped:c=>t.onError?.("internal",c)}),mt=_a({bridge:y,clock:e}),pt=kl({bridge:y,clock:e}),fr=c=>{let x=y.handleWindowMessage({data:c.data,origin:c.origin,source:c.source,ports:c.ports});return x&&window.removeEventListener("message",fr),x};window.addEventListener("message",fr);let nn=ki(window,fr),Ad=nn?.capture,hr=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];hr?.domInteractive!==void 0&&hr.domInteractive>0&&o.mark("document parsed",hr.domInteractive),Ad?.late&&n?.("[gem] the early-handshake capture installed after this document finished loading, so a handshake posted at iframe load may already have been missed. Load the capture script ahead of everything else in the document.");let br=t.handshakeWarningMs;br!==null&&n&&e.setTimeout(()=>{let c=nn===null?"no capture script ran":`capture: ${nn.delivered} offer(s) delivered, ${nn.stale} stale, ${nn.capture.dropped} evicted${nn.capture.late?", installed late":""}`;if(y.currentState==="connected"){n(`[gem] handshake connected. boot: ${o.timeline()} \xB7 ${c}`);return}n(`[gem] no completed handshake after ${br??wd}ms (bridge state: ${y.currentState}). Either the embedder does not run the gem-web-sdk parent half, its origin is not in this build\u2019s allowedEmbedders, or its handshake fired before this frame\u2019s listener registered. boot: ${o.timeline()} \xB7 `+c);},br??wd);let Pd=ur({get baseUrl(){return Q},tokenSource:Y.source,get defaultQuery(){let c=Y.identity;return c?{game_id:c.gameId,channel:c.channel}:{}}}),tn=new Le({transport:Pd,clock:e}),fe={client:tn,gameId:()=>Y.identity?.gameId??""};mi.confirm=c=>sd(fe,c);let Ed=()=>Y.identity?.channel??"release",hi=new jt(fe,Ed),bi=async c=>(await hi.load())?.currency(c)?.id??void 0,vi=Ot(fe,Fr,{identity:ci,resolveCurrencyId:bi}),vr=async c=>{let x=await j.wait(c);if(x)return x;throw y.currentState==="refused"?new oe("unavailable","the page that framed this game is not one it accepts, so no play token will ever arrive. It plays in the Gem Arcade, the Gem Editor and the Gem dev host; a site of your own must be in allowedEmbedders (see onRefused for the reason)."):new oe("timeout","no play token arrived over the bridge. Every route a game reaches is scoped by the token, so nothing can proceed without one \u2014 the bridge may not be connected, or the parent may have refused to mint (see onAuthStateChange).")},_r=l(t.autoReconnect),ce=Ao({client:tn,clock:e,gameId:()=>Y.identity?.gameId??null,playerId:()=>Y.identity?.playerId??null,awaitGameId:async()=>(await vr(li)).gameId,resolveParty:ui.resolve,resolveClusterTargets:mt.resolveList,refreshClusterTargets:mt.refresh,ensureLocalServer:pt.ensure,localHostAvailable:pt.available,...t.clientVersion===void 0?{}:{clientVersion:t.clientVersion},platformGameVersion:()=>Y.gameVersion,...t.pollRooms===void 0?{}:{poll:t.pollRooms},...t.recoverStaleMembership===void 0?{}:{recoverStaleMembership:t.recoverStaleMembership},...t.retryAutoStart===void 0?{}:{retryAutoStart:t.retryAutoStart},...t.watchSeats===void 0?{}:{watchSeats:t.watchSeats},...t.seatPollIntervalMs===void 0?{}:{seatPollIntervalMs:t.seatPollIntervalMs},..._r===null?{}:{autoReconnect:{..._r,redial:(c,x)=>wr.redialMatch(c,x),abandon:(c,x)=>wr.abandonMatch(c,x)}}});d(ce),al({analytics:a,rooms:ce});let rn=sl({client:tn,clock:e,rooms:ce,bridge:y,gameId:()=>Y.identity?.gameId??"",baseUrl:()=>Q,resolveClusterTarget:mt.resolve,boot:o,...t.log===void 0?{}:{log:t.log}}),_i=qo(o,n),Rn=Hl({client:tn,clock:e,rooms:ce,signaling:()=>T.channel(),signalingReady:dt,log:n??(()=>{})}),wr=rd({rooms:ce,p2p:{connect:c=>_i(rn.connect(c)),session:c=>rn.session(c)},dedicated:{connect:(c=>lr(o,"welcome",Rn.connect(c),n))},clock:e,identity:()=>Y.identity,apiBaseUrl:()=>Q,tokens:ct,room:()=>ce.currentRoom,autoReconnect:_r!==null,...t.log===void 0?{}:{log:t.log}}),Td=async()=>(await vr(li)).playerId,wi={client:tn,boot:o,get identity(){return Y.identity},awaitIdentity:(c=li)=>vr(c),awaitBridge:c=>y.settled(c),get player(){return f.current},awaitPlayer:(c=yf)=>f.wait(c),me:vi,characters:new Gt(fe,void 0,ci,bi),transfers:new $t(fe,Fr,vi.inventory),gameConfig:hi,purchases:pi.api,deviceSettings:ut.api,ads:gi.api,account:yi.api,share:ud({frame:y,log:t.log}),analytics:a,leaderboards:new In(fe),challenges:new En(fe),showcase:new Mn(fe,Td),friends:new On(fe,{challenge:fi.challenge}),platform:new Gn(fe,I,n),profiles:new Dn(fe),functions:new De((c,x)=>ps(fe,c,x)),get prefs(){return w.current},get cohorts(){return R.current},get viewport(){return M.current},awaitCohorts:(c=ff)=>R.wait(c),reportMuted:c=>{S=!!c,E();},cueReward:c=>y.cueReward(c),setWalletVisible:(c,x)=>{let $=Array.isArray(x?.only)?[...x.only]:void 0;return A=$===void 0?{visible:c===true}:{visible:c===true,only:$},N()},setMenu:c=>(q={...typeof c?.onSettings=="function"?{onSettings:c.onSettings}:{},...Array.isArray(c?.items)?{items:c.items.map(x=>({...x}))}:{}},C()),exit:c=>hf(ce,y,c,a),frame:y,devtools:F,rooms:ce,dedicatedServer:{listClusterTargets:c=>Rn.listClusterTargets(c),connect:(c=>lr(o,"welcome",Rn.connect(c),n)),handleMatchEnded:(c,x)=>Rn.handleMatchEnded(c,x)},p2p:{handleSignalEvent:(c,x,$)=>rn.handleSignalEvent(c,x,$),session:c=>rn.session(c),connect:c=>_i(rn.connect(c))},match:wr};return wi}var Sd="the match has not started yet: the runtime hands over the host at `init`, and this was read before that. Read it from `init` or later \u2014 a bundle that needs a value at module scope is reading it one call too early.";function di(t,e={}){let n=e.clock??le,r=()=>{let s=t();if(s===null)throw new Error(Sd);return s},o=null,i=()=>{if(o===null)throw new Error(Sd);return o};return {server:{get identity(){return i().identity},get client(){return i().client},get api(){return i().api},get match(){return i().match},get analytics(){return i().analytics},get functions(){return i().functions},get challenges(){return i().challenges},get room(){return i().room},dispose(){o?.dispose();},get sizeClass(){return r().sizeClass},get roomArgs(){return r().roomArgs},get roster(){return r().roster},players(){return r().players()},profile(s){let d=r().profile?.(s);if(!d)return null;let m=d.displayName;return typeof m!="string"||m===""?null:{displayName:ge(m),...typeof d.displayTag=="string"&&d.displayTag!==""?{displayTag:ge(d.displayTag)}:{},...typeof d.discriminator=="string"?{discriminator:d.discriminator}:{}}},playerNumber(s){return r().playerNumber?.(s)},send(s,l,d){d===void 0?r().send(s,l):r().send(s,l,d);},broadcast(s,l){l===void 0?r().broadcast(s):r().broadcast(s,l);},kick(s,l){l===void 0?r().kick(s):r().kick(s,l);},log(s){r().log(s);},warn(s){r().warn(s);}},attach:()=>{o=_n(r(),{...e,clock:n});}}}function Rd(t,e={}){let{server:n,attach:r}=di(()=>t,e);return r(),n}function bf(t){if(t===void 0||typeof t.reason!="string"||t.reason==="")return;let e=t.platform_reason??t.endedReason;return {reason:t.reason,...e===void 0?{}:{endedReason:$e(e)}}}function kd(t,e={}){return ()=>{let n=null,{server:r,attach:o}=di(()=>n,e),i=t(r),a={async init(s){n=s,o(),await i.init?.();},async shutdown(s){let l=bf(s);try{await i.shutdown?.(l);}finally{r.dispose();}}};return i.join&&(a.join=(s,l)=>i.join?.(s,l)),i.leave&&(a.leave=(s,l)=>i.leave?.(s,l)),i.message&&(a.message=(s,l,d,m)=>i.message?.(s,l,d,m)),a}}Ri();
|
|
2
|
+
exports.ARCADE_EMBEDDERS=cf;exports.AnalyticsApi=Fn;exports.AuthError=oe;exports.CONDITIONAL_HEADERS=gt;exports.ChallengesApi=En;exports.DEVICE_SETTINGS_MAX_BYTES=ii;exports.DedicatedServerError=b;exports.FriendChallengeError=Ve;exports.FriendsApi=On;exports.FunctionsApi=De;exports.GemApiError=G;exports.GemClient=Le;exports.GemConfigError=de;exports.GemFrame=at;exports.GemFunctionError=$n;exports.GemSaveError=ie;exports.GemUnframedError=st;exports.LeaderboardsApi=In;exports.MAX_PERIODS_BACK=Qs;exports.PLATFORM_EVENTS=ym;exports.PlatformApi=Gn;exports.PlatformCurrenciesApi=Bt;exports.PlatformEarnAllowanceApi=Ht;exports.PlayerText=me;exports.ProfilesApi=Dn;exports.PurchaseRefusal=Ge;exports.ShowcaseApi=Mn;exports.TransportRefusal=re;exports.UNRELIABLE_CHANNEL_LABEL=Un;exports.asPlayerText=ge;exports.createBootTimeline=No;exports.createGem=JS;exports.createGemServer=_n;exports.createHostTokenSource=Kl;exports.createMatchServer=Rd;exports.defineServer=kd;exports.leaveAndExit=hf;exports.mapIdentity=_e;exports.markOnResolve=lr;exports.platformIconUrl=Hu;exports.presentJoinCredential=qn;exports.readTemplateTransports=pn;exports.readTransportAdvert=Bn;exports.reportOnResolve=qo;exports.systemClock=le;exports.text=Ue;exports.toBase64=yt;exports.webTransportAvailable=Xt;return exports;})({});
|