@indiegems/gem-web-sdk 23.2.0 → 24.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- var Dp=Object.defineProperty;var Fp=(t,e)=>{for(var n in e)Dp(t,n,{get:e[n],enumerable:true});};globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:23.2.0]";function Gs(){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)}var $p={initialDelayMs:2e3,maxDelayMs:6e4};function qp(t,e){return e!==void 0?!e:t==="chain_exhausted"}var At=class{constructor(e){this.options=e;}options;grant=null;state="pending";failure=null;generation=0;inFlight=null;rejected=false;retry=null;failures=0;notBefore=0;disposed=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.pastChainCeiling())throw new ie("chain_exhausted","the token chain reached its ceiling");if(this.inFlight===null&&this.options.clock.now()<this.notBefore)throw new ie(this.failure??"unavailable","the embedder asked for no new token yet; one is asked for when that wait is over");return this.refresh(this.nextReason())}pastChainCeiling(){return this.grant===null||this.seconds()<this.grant.chainEndsAt?false:(this.enter("lost","chain_exhausted"),true)}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);}dispose(){this.disposed=true,this.cancelRetry();}scheduleRetry(e){if(this.cancelRetry(),this.failures+=1,this.notBefore=e===void 0?0:this.options.clock.now()+e,this.disposed)return;let{initialDelayMs:n,maxDelayMs:r}=$p,i=Math.min(r,n*2**(this.failures-1)),o=Math.max(i/2,e??0)+Math.random()*(i/2);this.retry={handle:this.options.clock.setTimeout(()=>this.retryNow(),o)};}retryNow(){this.retry=null,this.notBefore=0,!(this.state==="lost"||this.pastChainCeiling())&&this.refresh(this.nextReason()).catch(()=>{});}cancelRetry(){this.retry!==null&&(this.options.clock.clearTimeout(this.retry.handle),this.retry=null);}refresh(e){if(this.inFlight)return this.inFlight;this.cancelRetry();let n=this.generation;this.enter("pending");let r=this.options.request(e).then(i=>{if(n!==this.generation)throw new ie("internal","token arrived for a superseded generation");return this.grant=i,this.rejected=false,this.enter("ready"),i.token}).catch(i=>{let o=Np(i),{retryable:s,retryAfterMs:a}=i??{};throw n===this.generation&&(qp(o,typeof s=="boolean"?s:void 0)?this.enter("lost",o):(this.scheduleRetry(typeof a=="number"&&Number.isFinite(a)&&a>0?a:void 0),this.enter("degraded",o))),i instanceof ie?i:new ie(o,String(i))}).finally(()=>{this.inFlight===r&&(this.inFlight=null);});return this.inFlight=r,r}enter(e,n){(e==="ready"||e==="lost")&&this.cancelRetry(),e==="ready"&&(this.failures=0,this.notBefore=0),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 Np(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 de=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}},cr=["if-match","if-none-match"],Ls=4096;function jp(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let i=n.toLowerCase();if(!cr.includes(i)||r===void 0)continue;let o=typeof r=="string"?Bp(r):r;if(typeof o!="string"||o.length>Ls||!Up(o))throw new de(`the ${i} header value cannot be sent \u2014 it is not a string, is longer than ${Ls} 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.`);o!==""&&(e[i]=o);}return Object.freeze(e)}function Bp(t){let e=i=>i===32||i===9||i===10||i===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 Up(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 Wp(t){let{bytes:e}=t;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new de("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 de("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 Ds(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let i={...r},o=jp(i.headers),s=Wp(i),a=Object.freeze({...i,headers:o,...s===void 0?{}:{bytes:s}}),l=await e.tokenSource.get(),d=await t(a,l);if(d.status!==401||!n)return d;e.tokenSource.invalidate(l);let u=await e.tokenSource.get(),c=await t(a,u);if(c.status===401)throw e.tokenSource.close("unavailable"),new ie("unavailable","the server refused a freshly minted token");return c}}}function ur(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(Hp(e))}function mr(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 Xi(t){return new TextDecoder().decode(mr(t))}function Hp(t){let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return n}var O=class extends Error{constructor(n,r,i,o,s){super(`${n} (${r}): ${i}`);this.reason=n;this.status=r;this.detail=i;this.retryAfterSeconds=o;this.code=s;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},qs=new WeakMap;function Ns(t){return qs.get(t)??{}}var Vp=new Set([408,429,500,502,503,504]),Kp=6e4,js=new WeakMap;function Bs(t,e){js.set(t,e);}function Fs(t){return t!==null&&(t.reason==="rate_limited"||t.retryAfterSeconds!==void 0)}function Jp(t){if(t===void 0)return 2;if(!Number.isInteger(t)||t<0||t>10)throw new de(`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 Ve=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),i=r.etag===void 0?{}:{etag:r.etag};return r.status===304?{modified:false,...i}:{modified:true,body:r.body,...i}}async put(e,n,r,i={}){return this.send({method:"PUT",path:e,body:n,signal:r,...Zt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async post(e,n,r,i={}){return this.send({method:"POST",path:e,body:n,signal:r,...Zt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async postBytes(e,n,r,i={}){let o=await this.sendRaw({method:"POST",path:e,bytes:n,responseType:"bytes",signal:r,...Zt(i)},i.replaySafe===true,i.retryRateLimited!==false);return {bytes:zp(o.body),...o.invocationId===void 0?{}:{invocationId:o.invocationId}}}async patch(e,n,r,i={}){return this.send({method:"PATCH",path:e,body:n,signal:r,...Zt(i)},i.replaySafe===true,i.retryRateLimited!==false)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...Zt(r)},r.replaySafe===true,r.retryRateLimited!==false)}async send(e,n,r=true){return (await this.sendRaw(e,n,r)).body}async sendRaw(e,n,r=true){let i=n?Jp(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw $s(e.signal);let s=e.signal===void 0?void 0:js.get(e.signal);for(let a=0;a<i;a++){if(a>0){let u=this.backoffMs(a,o);if(Fs(o)&&s!==void 0&&u>=s())throw o;await this.backoff(u,e.signal);}if(e.signal?.aborted)throw Fs(o)&&s!==void 0&&s()<=0?o:$s(e.signal);let l;try{l=await this.options.transport.request(e);}catch(u){if(ie.isAuthError(u)||de.isRefusal(u)||e.signal?.aborted||Xp(u))throw u;o=new O("unavailable",0,String(u));continue}if(l.status>=200&&l.status<300||l.status===304)return l;let d=Yp(l);if(!Vp.has(l.status)||l.status===429&&!r)throw d;o=d;}throw o??new O("unavailable",0,"no attempt was made")}backoffMs(e,n){let r=n?.retryAfterSeconds,i=r!==void 0?r*1e3:2**(e-1)*250,o=2**(e-1)*250;return Math.min(Math.max(i,o),Kp)}backoff(e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let i=this.options.clock,o=false,s=false,a,l=()=>{o||(o=true,s&&i.clearTimeout(a),n?.removeEventListener("abort",l),r());};n?.addEventListener("abort",l,{once:true}),a=i.setTimeout(l,e),s=true,o&&i.clearTimeout(a);})}};function zp(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 Zt(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function $s(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function Xp(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function Yp(t){let e=Zp(t),n=tg(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&qs.set(e,r),e}var Qp=new Map([["insufficient_funds","insufficient_funds"]]);function Zp(t){let{status:e,body:n}=t,r=eg(n),i=t.retryAfterSeconds??rg(n),o=ng(n),s=o===void 0?void 0:Qp.get(o);if(s!==void 0)return new O(s,e,r,void 0,o);switch(e){case 304:return new O("not_modified",e,r);case 400:case 422:return new O("invalid",e,r,void 0,o);case 403:return new O("forbidden",e,r,void 0,o);case 404:return new O("not_found",e,r,void 0,o);case 402:return new O("insufficient_funds",e,r,void 0,o);case 409:return new O("conflict",e,r,void 0,o);case 412:return new O("precondition_failed",e,r,void 0,o);case 413:return new O("too_large",e,r,void 0,o);case 429:return new O("rate_limited",e,r,i,o);default:return new O("unavailable",e,r,i,o)}}function eg(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 tg(t){let n=t?.error?.details;return n===null?void 0:n}function ng(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function rg(t){let e=t?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function S(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 Us(t,e,n){let r=`/v1/inventory/transfers/${S(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function Ws(t,e,n,r,i,o){let s=`/v1/inventory/${S(e)}/${S(n)}/progressions/${S(r)}/add`;return t.client.post(s,i,o?.signal)}async function Hs(t,e,n){let r=`/v1/inventory/transfers/${S(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Vs(t,e,n){let r=`/v1/games/${S(t.gameId())}/matchmaking/tickets/${S(e)}`;return t.client.delete(r,n?.signal)}async function Ks(t,e,n,r,i,o){let s=`/v1/inventory/${S(e)}/${S(n)}/progressions/${S(r)}/claim`;return t.client.post(s,i,o?.signal)}async function Js(t,e,n){return t.client.post("/v1/characters",e,n?.signal)}async function zs(t,e,n,r,i){let o=`/v1/inventory/${S(e)}/${S(n)}/orders/batch`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Xs(t,e,n,r,i){let o=`/v1/inventory/${S(e)}/${S(n)}/orders`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Ys(t,e,n){let r=`/v1/games/${S(t.gameId())}/matchmaking/tickets`;return t.client.post(r,e,n?.signal)}async function Qs(t,e,n,r,i){let o=`/v1/settings/${S(e)}/${S(n)}/${S(r)}`;return t.client.delete(o,i?.signal)}async function Zs(t,e,n,r,i){let o=`/v1/saves/${S(e)}/${S(n)}/${S(r)}`;return t.client.delete(o,i?.signal)}async function el(t,e,n,r){let i=`/v1/showcase/players/${S(e)}/${S(n)}`;return t.client.delete(i,r?.signal)}async function tl(t,e,n,r,i){let o=`/v1/inventory/${S(e)}/${S(n)}/recipes/execute`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function nl(t,e,n,r,i,o){let s=`/v1/saves/${S(e)}/${S(n)}/${S(r)}/finalize`;return t.client.post(s,i,o?.signal)}async function rl(t,e,n){let r=`/v1/games/${S(t.gameId())}/avatars-3d/${S(e)}/owned`;return t.client.get(r,n?.signal)}async function il(t,e,n){let r=`/v1/games/${S(t.gameId())}/config/channels/${S(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function ol(t,e,n){let r=`/v1/characters/${S(e)}`;return t.client.get(r,n?.signal)}async function al(t,e,n){let r=`/v1/inventory/loot-tables/${S(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function sl(t,e,n,r,i){let o=`/v1/settings/${S(e)}/${S(n)}/${S(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function ll(t,e,n,r){let i=new URLSearchParams;r?.include_buckets!==void 0&&i.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&i.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&i.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&i.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&i.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&i.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&i.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&i.set("progression_cursor",String(r?.progression_cursor));let o=i.toString(),s=`/v1/inventory/${S(e)}/${S(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function dl(t,e,n,r,i){let o=`/v1/inventory/${S(e)}/${S(n)}/items/${S(r)}`;return t.client.get(o,i?.signal)}async function cl(t,e,n,r,i){let o=new URLSearchParams;i?.bucket_1!==void 0&&o.set("bucket_1",String(i?.bucket_1)),i?.bucket_2!==void 0&&o.set("bucket_2",String(i?.bucket_2)),i?.limit!==void 0&&o.set("limit",String(i?.limit)),i?.periods_back!==void 0&&o.set("periods_back",String(i?.periods_back)),i?.period!==void 0&&o.set("period",String(i?.period)),i?.player_id!==void 0&&o.set("player_id",String(i?.player_id));let s=o.toString(),a=`/v1/leaderboards/${S(e)}/${S(n)}/${S(r)}`+(s?`?${s}`:"");return t.client.get(a,i?.signal)}async function ul(t,e,n,r,i){let o=`/v1/inventory/${S(e)}/${S(n)}/orders/${S(r)}`;return t.client.get(o,i?.signal)}async function ml(t,e,n,r,i){let o=`/v1/inventory/${S(e)}/${S(n)}/progressions/${S(r)}`;return t.client.get(o,i?.signal)}async function pl(t,e,n,r,i,o){let s=`/v1/inventory/${S(e)}/${S(n)}/catalogs/${S(r)}/recipes/${S(i)}/availability`;return t.client.get(s,o?.signal)}async function gl(t,e,n,r){let i=new URLSearchParams;i.set("limit",String(r?.limit));let o=i.toString(),s=`/v1/inventory/${S(e)}/${S(n)}/recipe-usage`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Yi(t,e,n,r,i){let o=`/v1/saves/${S(e)}/${S(n)}/${S(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function fl(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 i=r.toString(),o=`/v1/leaderboards/${S(e)}/friends`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function yl(t,e,n){let r=`/v1/showcase/friends/${S(e)}`;return t.client.get(r,n?.signal)}async function hl(t,e){let n=`/v1/games/${S(t.gameId())}/avatars-3d`;return t.client.get(n,e?.signal)}async function bl(t,e,n){let r=`/v1/inbox/friend-challenges/${S(e)}`;return t.client.get(r,n?.signal)}async function vl(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 i=r.toString(),o=`/v1/leaderboards/${S(e)}`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function _l(t,e){let n=`/v1/games/${S(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function wl(t,e){let n=`/v1/games/${S(t.gameId())}/players/me/passes`;return t.client.get(n,e?.signal)}async function pr(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function Sl(t,e,n){let r=`/v1/profiles/players/${S(e)}`;return t.client.get(r,n?.signal)}async function Rl(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),i="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function kl(t,e,n){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${S(e)}`;return t.client.get(r,n?.signal)}async function Al(t,e,n,r){let i=`/v1/showcase/players/${S(e)}/${S(n)}`;return t.client.get(i,r?.signal)}async function xl(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function Pl(t,e,n){let r=`/v1/inventory/transfers/${S(e)}`;return t.client.get(r,n?.signal)}async function El(t,e,n){let r=`/v1/games/${S(t.gameId())}/matchmaking/tickets/${S(e)}/heartbeat`;return t.client.post(r,void 0,n?.signal)}async function Tl(t,e,n){let r=`/v1/games/${S(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{...n?.keepalive===void 0?{}:{keepalive:n.keepalive},replaySafe:true,retryRateLimited:false})}async function Il(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function Cl(t,e,n,r,i){let o=`/v1/inventory/${S(e)}/${S(n)}/platform-funded-game-inventory-purchases`;return t.client.post(o,r,i?.signal)}async function Ol(t,e,n){let r=new URLSearchParams;n?.cue_id!==void 0&&r.set("cue_id",String(n?.cue_id));let i=r.toString(),o="/v1/functions/invoke"+(i?`?${i}`:"");return t.client.postBytes(o,e,n?.signal)}async function Ml(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(),i="/v1/challenges"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Gl(t,e){return t.client.get("/v1/characters",e?.signal)}async function Ll(t,e,n,r){let i=`/v1/settings/${S(e)}/${S(n)}`;return t.client.get(i,r?.signal)}async function Dl(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/inventory/${S(e)}/${S(n)}/orders`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Fl(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/saves/${S(e)}/${S(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function $l(t,e){let n=new URLSearchParams;e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),i="/v1/inbox/friend-challenges"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function ql(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(),i="/v1/friends"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Nl(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(),i="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function jl(t,e,n){let r=`/v1/inbox/friend-challenges/${S(e)}/answered`;return t.client.post(r,void 0,n?.signal)}async function Bl(t,e,n,r){let i=`/v1/games/${S(t.gameId())}/matches/${S(e)}/end`;return t.client.post(i,n,r?.signal)}async function Ul(t,e,n,r,i,o){let s=`/v1/inventory/${S(e)}/${S(n)}/progressions/${S(r)}/max`;return t.client.post(s,i,o?.signal)}async function Wl(t,e,n,r,i,o){let s=`/v1/settings/${S(e)}/${S(n)}/${S(r)}`;return t.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Hl(t,e,n,r,i){let o=`/v1/showcase/players/${S(e)}/${S(n)}`;return t.client.put(o,r,i?.signal)}async function Vl(t,e,n,r,i){let o=`/v1/inventory/${S(e)}/${S(n)}/rewarded-placements/${S(r)}/availability`;return t.client.get(o,i?.signal)}async function Kl(t,e,n){let r=`/v1/inventory/transfers/${S(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function Jl(t,e,n,r){let i=`/v1/characters/${S(e)}`;return t.client.patch(i,n,r?.signal)}async function zl(t,e,n,r,i,o){let s=`/v1/saves/${S(e)}/${S(n)}/${S(r)}/upload-url`;return t.client.post(s,i,o?.signal,{replaySafe:true})}async function Xl(t,e,n,r,i,o){let s=`/v1/inventory/${S(e)}/${S(n)}/progressions/${S(r)}/reset`;return t.client.post(s,i,o?.signal)}async function Yl(t,e,n){let r=`/v1/characters/${S(e)}`;return t.client.delete(r,n?.signal)}var j="gem-web-bridge",fr={min:1,max:1},ig=65536,Ql=8,gr=5e3,Zl=1024;var en=Object.create(null),yr="__malformed";var eo=Object.create(null),og=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.textScale.","textScale"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"],["gem.moments.","moments"],["gem.prefs.","audioChannels"],["gem.share.","shareRemap"]]);function hr(t){let e=eo[t];if(e!==void 0)return e;for(let[n,r]of og)if(t.startsWith(n))return r}function xt(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 ag(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 sg(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function lg(t){return /^[a-z_]+$/.test(t)}function dg(t){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)||/^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/.test(t)&&!t.includes("--")}function Qi(t,e,n){if(e>Ql)return `nesting deeper than ${Ql}`;if(++n.nodes>gr)return `more than ${gr} values`;if(n.bytes>n.cap)return `over the ${n.cap} 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 i=t;if(n.seen.has(i))return "a repeated or cyclic object reference";if(n.seen.add(i),Array.isArray(t)){if(t.length>Zl)return `an array of ${t.length} entries, over the ${Zl} limit`;n.bytes+=2;for(let a of t){let l=Qi(a,e+1,n);if(l)return l}return null}let o=Object.getPrototypeOf(t);if(o!==Object.prototype&&o!==null)return "a value that is not a plain object";n.bytes+=2;let s=t;for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;if(++n.nodes>gr)return `more than ${gr} values`;if(n.bytes+=a.length*3+4,n.bytes>n.cap)return `over the ${n.cap} byte limit`;let l=Qi(s[a],e+1,n);if(l)return l}return null}function cg(t,e=ig){let n={nodes:0,bytes:0,seen:new Set,cap:e},r=Qi(t,0,n);return r?`message contains ${r}`:n.bytes>e?`message is over the ${e} byte limit`:null}var ug={origin:[xt,"not a well-formed origin"],url:[ag,"not a safe absolute http(s) URL"],bcp47:[sg,"not a well-formed BCP 47 tag"],code:[lg,"not a code of lower-case letters and underscores"],gameRef:[dg,"not a game id or web address"]};function ed(t,e,n){for(let r of e){let i=n===""?r[0]:`${n}.${r[0]}`,o=t[r[0]];if(o==null){if(r[1]<"a")continue;return `${i}: required`}let s=Zi(o,r,i);if(s)return s}return null}function Zi(t,e,n){let r=e[1].toLowerCase();switch(r){case "u":return typeof t=="boolean"?null:Zi(t,typeof t=="string"?[e[0],"s",e[2]]:[e[0],"n",e[3],e[4]],n);case "s":{if(typeof t!="string")return `${n}: expected string`;if(t.length>e[2])return `${n}: exceeds ${e[2]} characters`;if(e[3]){let[i,o]=ug[e[3]];if(!i(t))return `${n}: ${o}`}return null}case "n":case "i":return typeof t!="number"||!(r=="i"?Number.isInteger:Number.isFinite)(t)?`${n}: expected ${r=="i"?"integer":"number"}`:t<e[2]||t>e[3]?`${n}: out of range ${e[2]}..${e[3]}`:null;case "b":return typeof t=="boolean"?null:`${n}: expected boolean`;case "e":{let i=e[2];return i.includes(t)?null:`${n}: not one of ${i.join("|")}`}case "o":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected object`:ed(t,e[2],n);case "j":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected a plain object`:null;case "a":{if(!Array.isArray(t))return `${n}: expected array`;if(t.length>e[2])return `${n}: exceeds ${e[2]} items`;let i=e[3],o=`${n}[]`;for(let s of t){if(s==null){if(i[1]<"a")continue;return `${o}: required`}let a=Zi(s,i,o);if(a)return a}return null}default:return `${n}: unknown kind ${String(r)}`}}var td=Object.create(null);function P(t,e,n,r,i){return en[t]=n,r&&(eo[t]=r),td[t]=o=>{let s=cg(o,i);if(s)return s;if(typeof o!="object"||o===null||Array.isArray(o))return "message: expected object";let a=o;return a.gem!==j?"gem: wrong protocol marker":a.type!==t?`type: expected ${t}`:ed(a,e,"")}}var tn=["","s",64],V=["requestId","s",64],nn=["matchId","s",64],$e=["reason","S",64,"code"],Ke=["outcome","e",["ok","declined","unavailable"]];P("gem.handshake",[["versions","o",[["min","i",1,1e3],["max","i",1,1e3]]],["capabilities","A",64,tn],["embedder","s",2048,"origin"],["unbidden","B"]],30);P("gem.handshake.accept",[["v","i",1,1e3],["capabilities","A",64,tn]],5);P("gem.token",[["token","s",4096],["requestId","S",64],["generation","i",0,2147483647],["apiBaseUrl","S",512,"url"],["playerId","s",64],["gameId","s",64],["channel","e",["dev","test","release"]],["gameVersion","S",64],["expiresAt","i",0,4102444800],["chainEndsAt","i",0,4102444800],["allowDevTools","B"]],30);P("gem.token.denied",[V,["retryable","b"],["retryAfterMs","I",0,36e5],["reason","e",["chain_exhausted","unavailable"]],["correlationId","s",64]],30);P("gem.player",[["untrusted","o",[["displayName","s",64],["displayTag","S",80],["displayHandle","s",80]]],["playerId","S",64],["discriminator","S",8],["avatarIconUrl","S",2048,"url"],["avatarIconId","S",64],["avatar3dId","S",64],["avatar3dModelUrl","S",2048,"url"],["avatar3dIconUrl","S",2048,"url"],["avatars3d","A",8,["","o",[["family","s",32],["id","s",64],["modelUrl","s",256,"url"],["iconUrl","s",256,"url"]]]],["badges","A",2,["","o",[["itemId","s",64],["iconUrl","s",2048,"url"]]]],["displayTag","s",8],["avatarUrl","S",2048,"url"],["boost","O",[["multipliers","a",8,["","o",[["currencyId","s",64],["currencySlug","s",32],["multiplierBp","i",1e4,1e6]]]],["expiresInDays","I",1,7]]]],12);P("gem.pause",[["paused","b"]],120);P("gem.prefs",[["reducedMotion","b"],["muted","b"],["showFrameStats","B"],["music","B"],["sounds","B"],["locale","s",35,"bcp47"],["recommended","O",[["volume","i",0,100],["batterySaver","b"],["keyboardLayout","e",["wasd","arrows"]],["gamepadConfirm","e",["south","east"]],["vibration","b"],["lookSensitivity","I",20,400],["gamepadLookSensitivity","I",20,400],["invertLookY","B"],["touchMovement","S",16,"code"],["graphicsQuality","S",16,"code"],["graphicsQualityAuto","B"],["colorHelp","B"],["textScale","I",100,200]]]],60);P("gem.cohorts",[["cohorts","a",8,["","o",[["experimentId","s",36],["variantKey","s",32]]]]],12,"cohorts");P("gem.earnAllowanceChanged",[],30,"earnAllowance");P("gem.inventoryChanged",[],30,"inventoryChanged");P("gem.viewport",[["insets","o",[["top","i",0,4096],["right","i",0,4096],["bottom","i",0,4096],["left","i",0,4096]]],["reserved","A",4,["","o",[["x","i",0,16384],["y","i",0,16384],["width","i",0,16384],["height","i",0,16384],["control","O",[["x","i",0,16384],["y","i",0,16384],["width","i",0,16384],["height","i",0,16384]]]]]]],60,"viewport");P("gem.deviceSettings",[["settings","J"]],12,"deviceSettings");P("gem.willTerminate",[["reason","e",["grant_expiring","session_ended","navigating","kill_switch"]],["graceMs","i",0,6e4]],10);P("gem.roomEvent",[["event","e",["updated","match_started","match_ready","match_failed","version_stale"]],["roomId","s",64],["matchId","S",64],["version","I",0,2147483647],["reason","S",64],["platform","E",["universal","mobile"]]],120,"rooms");P("gem.socketState",[["connected","b"],["reason","E",["connecting","dropped","watchdog","terminal"]]],12,"socketState");P("gem.seatedEvent",[["roomId","s",64]],60,"partySeating");P("gem.autoStartFailedEvent",[["roomId","s",64],["code","s",64]],30,"autoStartFailure");P("gem.ticketEvent",[["event","e",["queued","matched","expired","cancelled","failed"]],["ticketId","s",64],["partySize","I",1,64],["queuedAt","I",0,4102444800],["expiresAt","I",0,4102444800],["reason","S",64],["roomId","S",64]],60,"ticketEvents");P("gem.signalEvent",[["event","e",["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]],nn,["data","j"]],1800,"p2p");P("gem.relayDraining",[nn,["clusterTargetId","s",64],["relayIps","a",16,tn],["drainingSince","s",40],["deadline","s",40]],60,"p2pRelayDrain");P("gem.dedicatedEvent",[["event","e",["answer","error","matchEnded"]],nn,["sdp","S",10240],["sessionId","S",64],["code","S",64],["message","S",256],["reason","S",64]],120,"dedicated");P("gem.partyResult",[V,["partyId","S",64]],30,"parties");P("gem.clusterTarget",[["clusterTargetId","s",64],["clusterTargetIds","A",3,tn]],12,"clusterTarget");P("gem.graphicsRoutes",[["entries","a",32,["","o",[["gpu","s",32],["route","S",32],["host","S",32]]]]],12,"graphicsRoutes");P("gem.devtools",[["action","e",["open","close","toggle"]]],30,"devtools");P("gem.screenshot",[["maxWidth","i",1,7680],["maxHeight","i",1,4320]],6,"screenshot");P("gem.screenshot.denied",[["reason","e",["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]],["retryable","b"]],12,"screenshot");P("gem.requestContext",[],12,"feedbackContext");P("gem.gameContext",[["context","j"]],12,"feedbackContext");P("gem.signal",[["signal","e",["join","offer","answer","ice","migrationAck","hostUnreachable"]],nn,["data","j"]],1200,"p2p");P("gem.dedicatedOffer",[nn,["sdp","s",10240],["intent","e",["initial","ice_restart","full_reconnect"]]],60,"dedicated");P("gem.partyRequest",[V],12,"parties");P("gem.ready",[],5);P("gem.engaged",[],5,"engagement");P("gem.progress",[["loaded","i",0,1099511627776],["total","i",0,1099511627776]],600);P("gem.requestToken",[V,["reason","e",["initial","expiring","rejected"]]],12);P("gem.requestLocalServer",[V,["gameRoomId","s",64]],6,"localHost");P("gem.localServer",[V,["serverId","S",128]],30,"localHost");P("gem.localServer.denied",[V,["retryable","b"],["reason","e",["refused","unavailable"]]],30,"localHost");P("gem.exit",[["reason","S",64]],5);P("gem.openExternal",[["url","s",2048,"url"]],6);P("gem.requestFullscreen",[["enabled","b"]],30);P("gem.audioState",[["muted","b"]],120,"audioState");P("gem.rewardCue",[["currencySlug","s",32],["cueId","S",64],["expected","I",1,1e9],["origin","O",[["x","i",0,16384],["y","i",0,16384]]]],60,"rewardCue");P("gem.rewardPresentation",[["mode","e",["arcade","game"]]],12,"rewardPresentation");P("gem.walletDisplay",[["visible","b"],["currencies","A",8,tn],["score","B"]],60,"walletDisplay");P("gem.controlsDeclare",[["uses","o",[["lookSensitivity","S",16,"code"],["gamepadLookSensitivity","S",16,"code"],["invertLookY","S",16,"code"],["touchMovement","S",16,"code"]]]],60,"controls");P("gem.menu",[["settings","b"],["items","A",4,["","o",[["id","s",32],["label","s",40]]]]],60,"gameMenu");P("gem.menuSelect",[["entry","e",["settings","item"]],["id","S",32]],60,"gameMenu");P("gem.gemCorner",[["corner","e",["top-left","top-right","bottom-left","bottom-right"]]],12,"gemCorner");P("gem.menuStyle",[["ground","S",7],["accent","S",7]],12,"menuStyle");P("gem.settingsDeclare",[["settings","a",8,["","o",[["id","s",40],["label","s",40],["kind","e",["toggle","slider","choice"]],["value","u",40,-1e6,1e6],["quick","B"],["icon","S",16,"code"],["min","N",-1e6,1e6],["max","N",-1e6,1e6],["step","N",0,1e6],["options","A",4,["","o",[["id","s",40],["label","s",40]]]]]]]],120,"gameSettings");P("gem.settingChange",[["id","s",40],["value","u",40,-1e6,1e6]],120,"gameSettings");P("gem.requestShare",[["requestId","S",64],["params","a",16,["","o",[["key","s",64],["value","s",512]]]]],6,"share");P("gem.shareResult",[V,["outcome","e",["accepted","refused"]],$e,["key","S",64]],30,"shareResult");P("gem.requestAvatarPicker",[["tab","E",["2d","3d"]]],6,"avatarPicker");P("gem.vibrate",[["pattern","a",99,["","i",0,1e4]]],600,"vibration");P("gem.frameStats",[["fps","i",0,1e3],["frameTimeP95Ms","i",0,1e5],["counts","E",["pageFrames","gameDraws"]]],120,"frameStats");P("gem.portraitBorders",[["name","S",40]],60,"portraitBorders");P("gem.error",[["code","e",["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]],["message","S",256]],60);P("gem.requestPurchase",[V,["purchaseKind","e",["item","recipe"]],["targetId","s",64],["currencySlug","s",32],["quantity","I",1,10],["catalogId","S",64],["origin","E",["sheet","direct_refused"]]],12,"purchases");P("gem.requestAvatar3dPurchase",[V,["itemId","s",64],["currencySlug","s",32]],12,"avatar3dPurchases");P("gem.purchaseResult",[V,Ke,$e,["purchaseId","S",64]],30,"purchases");P("gem.purchaseSettled",[["purchaseKind","e",["item","recipe"]],["targetId","s",64],["catalogId","S",64],["quantity","i",1,10],["purchaseId","S",64]],30,"purchaseSettled");P("gem.deviceSettings.put",[V,["settings","j"]],30,"deviceSettings");P("gem.deviceSettings.result",[V,["outcome","e",["stored","too_large","unavailable"]]],30,"deviceSettings");P("gem.requestAd",[V,["placement","s",32],["format","e",["interstitial","rewarded"]]],6,"ads");P("gem.adResult",[V,["outcome","e",["shown","no_ad","unavailable"]]],12,"ads");P("gem.signalMoment",[V,["kind","e",["level_end","run_end","match_end","menu_return","other_break"]],["placement","S",32],["wall","B"]],6,"moments");P("gem.momentResult",[V,["shown","b"]],12,"moments");P("gem.requestSignIn",[V],6,"signIn");P("gem.signInResult",[V,["outcome","e",["signed_in","declined","unavailable"]]],12,"signIn");P("gem.requestFriendChallenge",[V,["playerId","s",64],["template","s",64],["params","J"]],12,"friendChallenges");P("gem.friendChallengeResult",[V,["outcome","e",["accepted","cancelled","refused","unavailable","rate_limited","invalid"]],["code","S",64],["param","S",64],["channel","S",16],["configVersion","I",0,9007199254740991],["retryAfterMs","I",0,864e5],["detail","S",300]],30,"friendChallenges");P("gem.requestPlayInvite",[V,["params","A",16,["","o",[["key","s",64],["value","s",512]]]]],6,"playInvites");P("gem.playInviteResult",[V,["shown","b"]],12,"playInvites");P("gem.inviteParams",[["params","A",16,["","o",[["key","s",64],["value","s",512]]]]],30,"playInvites");P("gem.requestAppLinks",[V],12,"appLinks");P("gem.appLinksResult",[V,Ke,$e,["arcade","O",[["store","e",["app_store","google_play"]]]],["game","O",[["store","e",["app_store","google_play"]]]]],30,"appLinks");P("gem.requestOpenApp",[V,["target","e",["arcade","game"]]],6,"appLinks");P("gem.openAppResult",[V,Ke,$e],30,"appLinks");var nd=P("gem.requestOpenGame",[V,["ref","s",40,"gameRef"]],6,"openGame");P("gem.openGameResult",[V,Ke,$e],30,"openGame");P("gem.requestSimilarGames",[V,["limit","I",1,24]],12,"openGame");P("gem.similarGamesResult",[V,Ke,$e,["games","a",24,["","o",[["gameId","s",36,"gameRef"],["slug","S",40,"gameRef"],["iconUrl","s",1024,"url"],["capsuleLandscapeUrl","s",1024,"url"],["capsulePortraitUrl","s",1024,"url"],["previewVideoUrl","S",1024,"url"],["previewPosterUrl","S",1024,"url"],["untrusted","o",[["name","s",64],["tagline","s",64],["shortDescription","s",320],["tags","a",10,["","s",32]]]]]]]],30,"openGame",524288);P("gem.requestStoreOffers",[V],12,"store");P("gem.storeOffersResult",[V,Ke,$e,["offers","a",32,["","o",[["skuId","s",64],["kind","e",["gem_pack","boost","pass","bundle"]],["name","s",80],["description","s",400],["imageUrl","S",1024,"url"],["priceDisplay","s",32],["grant","O",[["currency","s",32],["amount","i",1,1e9]]]]]]],30,"store",262144);P("gem.requestStorePurchase",[V,["skuId","s",64]],12,"store");P("gem.storePurchaseResult",[V,Ke,$e],30,"store");P("gem.storePurchaseSettled",[["skuId","s",64]],30,"store");P("gem.requestStoreOfferSheet",[V,["skuId","s",64]],12,"storeOfferSheet");P("gem.storeOfferSheetResult",[V,Ke,$e],30,"storeOfferSheet");var br=Object.freeze(td);en.__malformed=60;Object.freeze(en);Object.freeze(eo);var ce={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},rn=class{constructor(e=ce){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=en[e];if(n===void 0)return false;let r=this.clock.now(),i=this.lastRefill.get(e)??r,o=this.tokens.get(e)??n,s=Math.max(0,r-i),a=Math.min(n,o+s*n/6e4);return a<1?(this.tokens.set(e,a),this.lastRefill.set(e,r),false):(this.tokens.set(e,a-1),this.lastRefill.set(e,r),true)}};function Pt(t,e){return t.toLowerCase()===e.toLowerCase()}function Je(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function vr(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:Je(n.hostname)&&Je(r.hostname)}function rd(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 _r=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 i=(await this.inventory.snapshot({buckets:n.buckets})).currencies.data,o=i.find(a=>a.currencyId===e),s;return !o&&this.resolveCurrencyId&&(s=await this.resolveCurrencyId(e).catch(()=>{}),s!==void 0&&(o=i.find(a=>a.currencyId===s))),{currencyId:o?o.currencyId:s??e,total:o?o.total:null,...o?.buckets===void 0?{}:{buckets:o.buckets}}}};function no(t){let e=Array.isArray(t.achievements)?t.achievements:[],n=[];for(let r of e){let i=r??{};typeof i.id!="string"||i.id===""||typeof i.threshold!="number"||!Number.isFinite(i.threshold)||n.push({id:i.id,threshold:i.threshold,points:typeof i.points=="number"?i.points:0,hidden:i.hidden===true,...typeof i.unlocked_at=="number"&&Number.isFinite(i.unlocked_at)?{unlockedAt:i.unlocked_at}:{},...i.revoked===true?{revoked:true}:{}});}return {...n.length>0?{achievements:n}:{},...t.achievements_unavailable===true?{achievementsUnavailable:true}:{}}}var id="inventory",Et=t=>typeof t=="number"?t:0,on=t=>typeof t=="string"?t:"";function to(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 od(t){let e=t??{};return {itemDefinitionId:on(e.item_definition_id),instanceId:on(e.instance_id),quantity:Et(e.quantity),acquiredAt:Et(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function mg(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:to(e.currencies,r=>{let i=r??{},o=Array.isArray(i.buckets)?i.buckets.map(s=>{let a=s??{};return {bucket:on(a.bucket),balance:Et(a.balance)}}):void 0;return {currencyId:on(i.currency_id),total:Et(i.total),...o===void 0?{}:{buckets:o}}}),items:to(e.items,od),progressions:to(e.progressions,r=>{let i=r??{};return {progressionDefinitionId:on(i.progression_definition_id),currentValue:Et(i.current_value),completionCount:Et(i.completion_count),isCompleted:i.is_completed===true,...no(i)}}),...n===void 0?{}:{etag:n}}}var wr=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${id}#buckets`:id;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 o=r.items.data.filter(s=>s.itemDefinitionId===e);if(o.length>0)return o}let i=await dl(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(i)?i.map(od):[]}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 ll(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 mg(n)}};var pg={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,already_owned:1,guest_upgrade_required:1,recipe_on_cooldown:1,recipe_max_uses_exceeded:1,item_max_stack_exceeded:1,recipe_costs_unmet:1,quantity_invalid:1,error:1},gg=new Set(Object.keys(pg));function ad(t){return typeof t=="string"&&gg.has(t)?t:"error"}var ze=class extends RangeError{constructor(n,r){super(r);this.code=n;this.name="PurchaseRefusal";}code;retryable=false};var oe=t=>typeof t=="string"?t:"",fg=t=>typeof t=="string"?t:oe(t&&typeof t=="object"?t.type:void 0),Oe=t=>typeof t=="number"?t:0;function yg(t){let e=t??{};return {prerequisiteType:oe(e.prerequisite_type),referenceId:oe(e.reference_id),required:Oe(e.required),current:Oe(e.current)}}function an(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {orderId:oe(e.order_id),status:oe(e.status),...n===void 0?{}:{etag:n}}}function Sr(){return crypto.randomUUID()}var hg="recipe-usage",sd=100;function Rr(t){let e=t??{};switch(e.type){case "currency":return {kind:"currency",currencyId:oe(e.currency_id),bucket:oe(e.bucket),delta:Oe(e.delta),balanceAfter:Oe(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:oe(e.item_definition_id),instanceId:oe(e.instance_id),delta:Oe(e.delta),quantityAfter:Oe(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:oe(e.progression_definition_id),delta:Oe(e.delta),valueAfter:Oe(e.value_after),completed:e.completed===true};default:return {kind:"other",type:oe(e.type)}}}function bg(t){let e=t??{},n=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:oe(e.entry_id),...n===void 0?{}:{rarityTier:n},rollNumber:Oe(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(Rr):[]}}function vg(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(bg):void 0;return {orderId:oe(e.order_id),status:oe(e.status),...n===void 0?{}:{etag:n},granted:Array.isArray(e.granted)?e.granted.map(Rr):[],consumed:Array.isArray(e.consumed)?e.consumed.map(Rr):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(Rr):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function _g(t){let e=t??{},n=e.price??{};return {payment:"platform_currency",orderId:oe(e.target_order_id)||oe(e.source_order_id),status:oe(e.status),purchaseId:oe(e.purchase_id),sourceOrderId:oe(e.source_order_id),price:{currencyId:oe(n.platform_currency_id),amount:Oe(n.price)}}}function wg(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:oe(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 ld(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 kr=class{constructor(e,n,r,i){this.api=e;this.entity=n;this.cache=r;this.handOffRefused=i;}api;entity;cache;handOffRefused;async create(e,n={}){let r=await this.write(()=>Xs(this.api,this.entity.type,this.entity.id,{operations:e.map(ld),source:n.source??"play",nonce:Sr()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return an(r)}async createMany(e,n={}){return this.write(()=>zs(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(ld),nonce:Sr()})),source:n.source??"play"},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}))}async recipeAvailability(e,n,r){let o=await pl(this.api,this.entity.type,this.entity.id,e,n,r===void 0?{}:{signal:r})??{},s=typeof o.uses_remaining=="number"?o.uses_remaining:void 0,a=typeof o.cooldown_expires_at=="string"?o.cooldown_expires_at:void 0,l=Array.isArray(o.lock_reasons)?o.lock_reasons.map(yg):[];return {canExecute:o.can_execute===true,locked:o.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(o.reasons)?o.reasons.map(d=>fg(d)):[],...s===void 0?{}:{usesRemaining:s},...a===void 0?{}:{cooldownExpiresAt:a}}}async recipeUsageAll(){return this.cache.read(hg,[],async()=>{let n=await gl(this.api,this.entity.type,this.entity.id,{limit:sd})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(wg),truncated:r.length>=sd}})}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,g=await this.write(()=>tl(this.api,this.entity.type,this.entity.id,{catalog_id:c.catalogId,recipe_id:c.targetId,game_id:this.api.gameId(),nonce:Sr()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...vg(g)}}if(this.entity.type!=="players"||this.entity.id!=="me")throw new TypeError("platform-currency purchases are available only on gem.me.mutations");let[r,i]=await Promise.all([Rl(this.api,n.signal===void 0?{}:{signal:n.signal}),pr(this.api,n.signal===void 0?{}:{signal:n.signal})]),o=e.payment.currencySlug.toLowerCase(),s=i.currencies.find(c=>c.currency_id.toLowerCase()===o||c.slug.toLowerCase()===o);if(s===void 0){let c=i.currencies.map(g=>g.slug);throw new ze("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${c.length===0?"none":c.join(", ")}`)}let a=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(a===void 0)throw new ze("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=a.platform_prices.find(c=>c.platform_currency_id===s.currency_id);if(l===void 0){let c=p=>i.currencies.find(f=>f.currency_id===p)?.slug??p,g=a.platform_prices.map(p=>`${c(p.platform_currency_id)} ${p.price}`);throw new ze("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${s.slug} price. It is priced in: ${g.length===0?"nothing":g.join(", ")}`)}let d=e.kind==="item"?e.quantity??1:1;if(!Number.isInteger(d)||d<1||d>10)throw new ze("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let u;try{u=await this.write(()=>Cl(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:s.currency_id,price:l.price*d},expected_config_version:r.config_version,nonce:Sr(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));}catch(c){if(this.handOffRefused!==void 0&&c instanceof O&&c.status===403&&c.code==="guest_upgrade_required")try{this.handOffRefused({kind:e.kind,targetId:e.targetId,...e.kind==="recipe"?{catalogId:e.catalogId}:{},currencySlug:s.slug,quantity:d});}catch{}throw c}return _g(u)}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 i=await this.write(()=>Ws(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return an(i)}async maxProgression(e,n,r){let i=await this.write(()=>Ul(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return an(i)}async claimProgression(e,n){let r=await this.write(()=>Ks(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return an(r)}async resetProgression(e,n){let r=await this.write(()=>Xl(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return an(r)}async write(e){return this.cache.invalidate(),e()}};var ro=t=>typeof t=="string"?t:"",Sg=t=>typeof t=="number"?t:0;function dd(t){let e=t??{};return {orderId:ro(e.order_id),status:ro(e.status),source:ro(e.source),createdAt:Sg(e.created_at)}}var Ar=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await Dl(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}})??{},i=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {data:Array.isArray(r.orders)?r.orders.map(dd):[],...i===void 0?{}:{nextCursor:i}}}async get(e,n){let r=await ul(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return dd(r)}};var Rg=["live"],io=6e4,cd=864e5;function kg(t){let e=t?.passes;if(!Array.isArray(e))return Object.freeze([]);let n=e.flatMap(r=>{let i=r??{};if(typeof i.pass!="string"||i.pass==="")return [];let o=i.held===true,s=o&&typeof i.ends_at=="string"?i.ends_at:null;return [Object.freeze({pass:i.pass,held:o,endsAt:s})]});return Object.freeze(n)}function Ag(t){let n=t.flatMap(r=>r.endsAt===null?[]:[Date.parse(r.endsAt)]).filter(r=>Number.isFinite(r));return n.length===0?null:Math.min(...n)}function ud(t,e,n={}){let{watch:r}=n,i=new Set,o=null,s=0,a=null,l=io,d=()=>{a!==null&&r?.clock.clearTimeout(a.handle),a=null;},u=v=>{d(),!(r===void 0||i.size===0)&&(a={handle:r.clock.setTimeout(R,v)});},c=v=>{let k=Ag(v);if(k===null||r===void 0){d();return}let y=k-r.clock.now();u(y>0?Math.min(y,cd):io);},g=v=>{r?.log?.(`[gem] a passes 'changed' listener threw: ${v instanceof Error?v.message:String(v)}`);},p=v=>{let k=o!==null&&JSON.stringify(o)!==JSON.stringify(v);if(o=v,l=io,c(v),!!k)for(let y of [...i])try{let _=y(v);typeof _?.then=="function"&&_.then(void 0,g);}catch(_){g(_);}},f=()=>{let v=s;return e.read("passes",Rg,()=>wl(t)).then(k=>{if(v!==s)return f();let y=kg(k);return p(y),y})},h=()=>{f().catch(()=>{u(l),l=Math.min(l*2,cd);});};function R(){s+=1,e.invalidate(),d(),r!==void 0&&i.size>0&&h();}return {api:{list:f,async get(v){return (await f()).find(y=>y.pass===v)??Object.freeze({pass:v,held:false,endsAt:null})},on(v,k){let y=i.size===0;return i.add(k),y&&r!==void 0&&(o===null?h():c(o)),()=>{i.delete(k),i.size===0&&d();}}},recheck:R}}var md=t=>typeof t=="number"?t:0,xg=t=>typeof t=="string"?t:"";function Pg(t){let e=t??{};return {progressionDefinitionId:xg(e.progression_definition_id),currentValue:md(e.current_value),completionCount:md(e.completion_count),isCompleted:e.is_completed===true,...no(e)}}var xr=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 i=(await this.inventory.snapshot()).progressions.data.find(o=>o.progressionDefinitionId===e);if(i&&i.achievementsUnavailable!==true)return i;try{let o=await ml(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Pg(o)}catch{return i??null}}};var sn=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,i){this.rebind();let o=n.length===0,s=o?e:e+"\0"+n.join("\0"),a=this.slots.get(s);if(a){let c=a.filledAt;if(c!==void 0&&(i===void 0||this.clock.now()-c<=i))return Promise.resolve(a.value);if(a.inFlight)return a.inFlight}let l=a??{};this.slots.set(s,l);let d=this.generation,u=r().then(c=>(o&&this.generation===d&&(l.value=c,l.filledAt=this.clock.now()),c)).finally(()=>{l.inFlight===u&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(s)===l&&this.slots.delete(s));});return l.inFlight=u,u}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 Eg(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var Tg=new Set(cr);function Ig(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))Tg.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function Pr(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return Ds(async(n,r)=>{let i;try{i=new URL(t.baseUrl.replace(/\/+$/,""));}catch{throw new de("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 o;try{o=new URL(i.href.replace(/\/+$/,"")+n.path);}catch{throw new de(`${JSON.stringify(typeof n.path=="string"?Eg(n.path):"(a non-string path)")} does not form a valid URL against ${i.protocol}//${i.host}. This is a malformed request, not a server failure.`)}if(o.protocol!==i.protocol||o.host!==i.host)throw new de(`${JSON.stringify(o.pathname)} resolves to ${o.protocol}//${o.host}, not ${i.protocol}//${i.host}. A request path may not change the request's origin \u2014 it carries the play token.`);if(o.username!==""||o.password!==""){let p=i.username!==""||i.password!=="",f=o.username!==i.username||o.password!==i.password,h=p?f?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new de(`the ${h} puts credentials in the URL, which cannot be fetched (${n.method} ${o.pathname}). The value is withheld here rather than written to logs. This is a malformed request, not a server failure.`)}for(let[p,f]of Object.entries(t.defaultQuery??{}))o.searchParams.has(p)||o.searchParams.set(p,f);let s=n.bytes,a=n.bytes===void 0?void 0:"application/octet-stream";try{n.body!==void 0&&(s=JSON.stringify(n.body),a="application/json");}catch(p){throw new de(`the body of ${n.method} ${JSON.stringify(o.pathname)} could not be serialised to JSON: ${String(p)}. This is a bug in the request, not a server failure \u2014 retrying sends the same unserialisable value.`)}let l=await e(o.toString(),{method:n.method,headers:{authorization:`Bearer ${r}`,...a===void 0?{}:{"content-type":a},...Ig(n.headers)},body:s,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 p=await l.text();if(p.length>0)try{d=JSON.parse(p);}catch{d=p;}}let u=l.headers.get("etag"),c=oo(l.headers.get("retry-after")),g=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...u===null?{}:{etag:u},...c===void 0?{}:{retryAfterSeconds:c},...g===null||g===""?{}:{invocationId:g}}},t)}function oo(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}function ao(t){let e=i=>new RegExp(`<${i}>([^<]{0,300})</${i}>`).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 Er(t){try{let e=ao(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var ae=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},Cg=3e4,Og=5e3,pd=6e4,Mg=2**31-1,gd="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",Gg=/^[A-Za-z0-9_]{1,64}$/;function qe(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(!Gg.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function fd(t,e){let n=new AbortController,r=Date.now()+e;Bs(n.signal,()=>r-Date.now());let i=AbortSignal.timeout(e),o=()=>n.abort(i.reason),s=()=>n.abort(t?.reason);return t?.aborted?n.abort(t.reason):(i.addEventListener("abort",o,{once:true}),t?.addEventListener("abort",s,{once:true})),{signal:n.signal,release:()=>{i.removeEventListener("abort",o),t?.removeEventListener("abort",s);}}}function so(t,e){return t.aborted&&e?.aborted!==true}var Lg=new Set(["x-ms-blob-type"]),Dg=/^[ -~]+$/;function Fg(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new ae("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,i]of Object.entries(t)){let o=r.toLowerCase();if(!Lg.has(o))throw new ae("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 i!="string"||!Dg.test(i))throw new ae("save_malformed",`the grant for save ${JSON.stringify(e)} gave header ${JSON.stringify(r)} a value that is not usable as one.`);if(o in n)throw new ae("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(o)} twice.`);n[o]=i;}return n}function lo(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 co(t){return t?.reason==="not_found"}function $g(t){return t?.code==="save_conflict"}function yd(t){return t instanceof O&&t.reason==="rate_limited"}async function hd(t,e){let n=await Er(e);return new O("rate_limited",429,`the save ${t} answered 429: too many save calls. ${n}`.trim(),oo(e.headers.get("retry-after")))}function Tr(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function qg(t,e,n,r,i){let o=false,s=()=>o?false:(o=true,a.detach?.(),true),a={signal:n.signal,budget:r,deadlineAt:Date.now()+r,teardown:n.teardown===true,overwrite:n.overwrite===true,identity:i,resolve:l=>{s()&&t(l);},reject:l=>{s()&&e(l);},detach:void 0};return a}function bd(t,e){return t!==null&&e!==null&&e!==t}function vd(t){return new ae("save_conflict",`save ${JSON.stringify(t)} was not written: the signed-in player changed while it waited for the write before it, and it holds the last player's progress.`)}var Ir=class{constructor(e,n,r={},i){this.api=e;this.entity=n;this.options=r;this.identity=i;}api;entity;options;identity;versions=new Map;seq=0;versionsOf=null;writes=new Map;holdUntil=0;async put(e,n,r={}){let i;try{i=JSON.stringify(n);}catch(o){throw new ae("save_malformed",`save ${JSON.stringify(e)} could not be serialised to JSON: ${String(o)}. Retrying stores the same unserialisable value.`)}if(i===void 0)throw new ae("save_malformed",`save ${JSON.stringify(e)} is undefined, which is not JSON. Use delete() to remove one.`);return this.putBytes(e,new TextEncoder().encode(i),{...r,contentType:"application/json"})}async putBytes(e,n,r={}){if(qe(e),r.signal?.aborted)throw Tr(r.signal);let i=this.budget(r.timeoutMs),o=this.slotWrites(e);return new Promise((s,a)=>{let l=o.queued;l?.release();let d=l?.waiters[l.waiters.length-1];d!==void 0&&this.holdOwn(o,d);let u=this.identity?.()??null;for(let c of l?.waiters.slice()??[])bd(c.identity,u)&&this.drop(o,c,vd(e));o.queued=this.queue(o,n,r,qg(s,a,r,i,u),l?.waiters??[]),o.wake?.(),this.pump(e,o);})}holdOwn(e,n){let{signal:r}=n,i=n.deadlineAt-Date.now();if(r?.aborted)return this.drop(e,n,Tr(r));if(i<=0)return this.drop(e,n,this.timeout("save",n.budget));let o=AbortSignal.timeout(i),s=()=>this.drop(e,n,this.timeout("save",n.budget)),a=()=>{r&&this.drop(e,n,Tr(r));};o.addEventListener("abort",s,{once:true}),r?.addEventListener("abort",a,{once:true}),n.detach=()=>{o.removeEventListener("abort",s),r?.removeEventListener("abort",a);};}drop(e,n,r){let i=e.queued?.waiters,o=i?.indexOf(n)??-1;o>=0&&i?.splice(o,1),n.reject(r),e.wake?.();}queue(e,n,r,i,o){let{budget:s}=i,a=[...o,i],l=AbortSignal.timeout(s),d=p=>{if(e.queued===g){this.take(e,g);for(let f of a)f.reject(p);e.wake?.();}},u=()=>d(this.timeout("save",s)),c=()=>{r.signal&&d(Tr(r.signal));};l.addEventListener("abort",u,{once:true}),r.signal?.addEventListener("abort",c,{once:true});let g={bytes:n,options:r,budget:s,deadlineAt:i.deadlineAt,identity:i.identity,waiters:a,release:()=>{l.removeEventListener("abort",u),r.signal?.removeEventListener("abort",c);}};return g}async pump(e,n){if(!n.running){n.running=true;try{for(let r=n.queued;r!==void 0;r=n.queued){let i=Date.now(),o=this.holdUntil-i;if(o>0){if(o>=r.deadlineAt-i){this.take(n,r);for(let l of r.waiters)l.reject(this.held(e,o));continue}for(let l of r.waiters.slice(0,-1))o>=l.deadlineAt-i&&this.drop(n,l,this.held(e,o));}let s=Math.max(o,this.spacing(n,r,i));if(s>0){await this.pause(n,s);continue}this.take(n,r);let a;try{a=this.precondition(e,r);}catch(l){for(let d of r.waiters)d.reject(l);continue}n.lastSentAt=i;try{let l=await this.send(e,r,a);for(let d of r.waiters)d.resolve(l);}catch(l){for(let d of r.waiters)d.reject(l);}}}finally{n.running=false;}}}spacing(e,n,r){if(e.lastSentAt===void 0||n.waiters.some(s=>s.teardown))return 0;let i=this.options.minWriteIntervalMs??Og,o=Math.min(...n.waiters.map(s=>s.deadlineAt-s.budget/2));return Math.min(e.lastSentAt+i,o)-r}pause(e,n){return new Promise(r=>{let i=()=>{clearTimeout(o),e.wake===i&&(e.wake=void 0),r();},o=setTimeout(i,Math.min(n,Mg));e.wake=i;})}take(e,n){e.queued===n&&(e.queued=void 0),n.release();}slotWrites(e){let n=this.writes.get(e);return n===void 0&&(n={running:false,queued:void 0,lastSentAt:void 0,wake:void 0},this.writes.set(e,n)),n}noteRateLimit(e){if(!yd(e))return;let n=e.retryAfterSeconds,r=n===void 0?pd:Math.min(n*1e3,pd);this.holdUntil=Math.max(this.holdUntil,Date.now()+r);}held(e,n){let r=Math.ceil(n/1e3);return new O("rate_limited",429,`save ${JSON.stringify(e)} was not sent: the platform refused a save call for the rate, and the wait it asked for ends in ${r}s, after this call's timeoutMs. Keep the state and write once the wait is over.`,r)}async send(e,n,r){let{bytes:i,options:o,budget:s}=n,a=o.contentType??"application/octet-stream",l=fd(o.signal,Math.max(0,n.deadlineAt-Date.now()));try{let d=await zl(this.api,this.entity.type,this.entity.id,e,{size_bytes:i.byteLength,content_type:a,...r,...o.metadata===void 0?{}:{metadata:o.metadata}},{signal:l.signal});if(typeof d.upload_url!="string"||typeof d.session_id!="string")throw new ae("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let u=Fg(d.upload_headers,e),c,g=this.options.fetch??globalThis.fetch.bind(globalThis);try{c=await g(d.upload_url,{method:"PUT",headers:{"content-type":a,...u},body:i,credentials:"omit",signal:l.signal});}catch(f){throw so(l.signal,o.signal)?this.timeout("upload",s):new ae("upload_failed",`${gd} for PUT. Underlying error: ${f}`)}if(c.status===429)throw await hd("upload",c);if(!c.ok){let f=await Er(c);throw new ae("upload_failed",c.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. "+f:`the save upload answered ${c.status}. `+(c.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. ":"")+f)}let p=lo(await nl(this.api,this.entity.type,this.entity.id,e,{session_id:d.session_id},{signal:l.signal}));return this.remember(e,p.etag?{kind:"etag",etag:p.etag}:void 0),p}catch(d){throw $g(d)?new ae("save_conflict",`save ${JSON.stringify(e)} was not written: the stored save changed since this game last loaded or wrote it, so another device or tab saved in between. Load it again and decide what to write from what is stored, rather than resending this write.`):(this.noteRateLimit(d),this.rethrow(d,o.signal,l.signal,"save",s))}finally{l.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(i){throw new ae("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: ${i}`)}}async getBytes(e,n={}){qe(e);let r=this.budget(n.timeoutMs),i=fd(n.signal,r),o=this.seq;try{let s;try{let u=await Yi(this.api,this.entity.type,this.entity.id,e,{signal:i.signal});if(!u.modified)return this.remember(e,{kind:"empty"},o),null;s=u.body;}catch(u){if(co(u))return this.remember(e,{kind:"empty"},o),null;throw u}if(typeof s.download_url!="string")throw new ae("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),l;try{l=await a(s.download_url,{credentials:"omit",signal:i.signal});}catch(u){throw so(i.signal,n.signal)?this.timeout("download",r):new ae("download_failed",`${gd} for GET. Underlying error: ${u}`)}if(l.status===429)throw await hd("download",l);if(!l.ok){let u=await Er(l);throw new ae("download_failed",`the save download answered ${l.status}. `+(l.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+u)}let d=new Uint8Array(await l.arrayBuffer());return this.remember(e,s.etag?{kind:"etag",etag:s.etag}:void 0,o),d}catch(s){throw this.slots().get(e)===void 0&&this.remember(e,{kind:"failed"}),this.noteRateLimit(s),this.rethrow(s,n.signal,i.signal,"load",r)}finally{i.release();}}async describe(e,n={}){try{let r=await Yi(this.api,this.entity.type,this.entity.id,qe(e),{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?lo(r.body):null}catch(r){if(co(r))return null;throw r}}async list(e={}){let n=await Fl(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(lo),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await Zs(this.api,this.entity.type,this.entity.id,qe(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!co(r))throw r}this.remember(e,{kind:"empty"});}precondition(e,n){if(bd(n.identity,this.identity?.()??null))throw vd(e);if(n.waiters.some(i=>i.overwrite))return {};let r=this.slots().get(e);if(r===void 0)return {};if(r.kind==="etag")return {if_match:r.etag};if(r.kind==="empty")return {if_none_match:"*"};throw new ae("load_failed",`save ${JSON.stringify(e)} was not written: the last load of this slot failed, so what this write would replace is unknown, and it could be the player's real progress. Load it again before saving, or pass overwrite: true if replacing whatever is stored is what you mean.`)}remember(e,n,r){let i=this.slots(),o=i.get(e);r!==void 0&&o!==void 0&&o.kind!=="failed"&&o.seq>r||(this.seq+=1,n===void 0?i.delete(e):i.set(e,{...n,seq:this.seq}));}slots(){let e=this.identity?.()??null;return e!==null&&e!==this.versionsOf&&(this.versionsOf!==null&&this.versions.clear(),this.versionsOf=e),this.versions}budget(e){return e??this.options.timeoutMs??Cg}timeout(e,n){return new ae("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,i,o){return e instanceof ae||yd(e)?e:so(r,n)?this.timeout(i,o):e}};function Ng(t){try{return Xi(t)}catch{return t}}function uo(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"?Ng(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var Cr=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await Ll(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(i=>uo(i)):[]}async get(e,n={}){try{let r=await sl(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?uo(r.body,r.etag):null}catch(r){if(_d(r))return null;throw r}}async put(e,n,r={}){let i=await Wl(this.api,this.entity.type,this.entity.id,e,{value:ur(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return uo(i)}async delete(e,n){try{await Qs(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});}catch(r){if(!_d(r))throw r}}};function _d(t){return t?.reason==="not_found"}function mo(t,e,n={}){let r=new sn(ce,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let i=new wr(t,e,r);return {settings:new Cr(t,e),inventory:i,saves:new Ir(t,e,n.saves??{},n.identity),currencies:new _r(i,n.resolveCurrencyId),mutations:new kr(t,e,r,n.handOffRefusedPurchase),orders:new Ar(t,e),progressions:new xr(t,e,i)}}function wd(t,e,n={}){let r=new sn(ce,n.identity),i=ud(t,r,n);return {scope:{...mo(t,e,n),passes:i.api},recheckPasses:i.recheck}}var po={type:"players",id:"me"};var at=t=>typeof t=="string"?t:"",Tt=t=>typeof t=="number"?t:0;function Or(t,e){let n=e??{},r=at(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:at(n.player_id),gameId:at(n.game_id),channel:at(n.channel)||"release",name:at(n.name),slotIndex:Tt(n.slot_index),isActive:n.is_active!==false,createdAt:at(n.created_at),updatedAt:at(n.updated_at)}}var Mr=class{constructor(e,n,r,i){this.api=e;this.saves=n;this.identity=r;this.resolveCurrencyId=i;}api;saves;identity;resolveCurrencyId;scopes=new Map;scope=e=>{let n=this.scopes.get(e);return n||(n=mo(this.api,{type:"characters",id:e},{saves:this.saves,identity:this.identity,resolveCurrencyId:this.resolveCurrencyId}),this.scopes.set(e,n)),n};refreshHeld(){for(let e of this.scopes.values())e.inventory.refresh();}async list(e){let r=(await Gl(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(i=>Or(this.scope,i)):[]}async get(e,n){let r=await ol(this.api,e,n===void 0?{}:{signal:n});return Or(this.scope,r)}async create(e){let n=await Js(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return Or(this.scope,n)}async update(e,n,r){let i=await Jl(this.api,e,{name:n},r===void 0?{}:{signal:r});return Or(this.scope,i)}async delete(e,n){await Yl(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await xl(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:Tt(r?.total_slots),availableSlots:Tt(r?.available_slots),activeCharacterCount:Tt(r?.active_character_count),defaultMaxSlots:Tt(r?.default_max_slots),purchasedExtraSlots:Tt(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var kd="[gem: use gem.text.toPlain()]",Sd=new Set,Rd;function jg(t){try{if(Sd.has(t))return;let e=globalThis.location;if(Rd??=!!e?.port&&Je(e.hostname??""),!Rd)return;Sd.add(t),console.warn(`[gem] ${t} is PlayerText, turned into a string: players see ${kd}. Render text.toPlain(value) (text is in @indiegems/gem-web-sdk/sdk).
2
- ${new Error().stack}`);}catch{}}var ve=class{#e;#n;constructor(e,n="player text"){this.#e=e,this.#n=n,Object.freeze(this);}toString(){return jg(this.#n),kd}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function be(t,e){return new ve(t,e)}var st={toPlain(t){return ve.unwrap(t)},compare(t,e,n){let r=t instanceof ve?ve.unwrap(t):t,i=e instanceof ve?ve.unwrap(e):e;if(typeof Intl>"u"||typeof Intl.Collator!="function")return r<i?-1:r>i?1:0;let o;try{o=new Intl.Collator(n);}catch{o=new Intl.Collator;}return o.compare(r,i)},equals(t,e){let n=t instanceof ve?ve.unwrap(t):t,r=e instanceof ve?ve.unwrap(e):e;return n.normalize("NFC")===r.normalize("NFC")}};var It=t=>typeof t=="string"?t:"";function Gr(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:It(e.transfer_id),status:It(e.status),sourceEntityId:It(e.source_entity_id),targetEntityId:It(e.target_entity_id),...n===void 0?{}:{message:be(n,"transfer.message")},createdAt:It(e.created_at),expiresAt:It(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function Bg(){return crypto.randomUUID()}var Lr=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 Il(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:Bg()},e.signal===void 0?{}:{signal:e.signal});return Gr(n)}async list(e={}){let r=await Nl(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}})??{},i=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {transfers:Array.isArray(r.transfers)?r.transfers.map(Gr):[],...i===void 0?{}:{nextCursor:i}}}async get(e,n){let r=await Pl(this.api,e,n===void 0?{}:{signal:n});return Gr(r)}async accept(e,n){return this.resolve(()=>Us(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>Kl(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>Hs(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),Gr(await e())}};var Ug=t=>typeof t=="string"?t:"",Wg=t=>typeof t=="string"&&t?t:void 0,Hg=t=>typeof t=="number"?t:void 0;function Ad(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 Vg(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new fe("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 fe("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=Hg(e.version);if(r===void 0)throw new fe("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let i=(l,d,u)=>{let c=Ug(l.id);if(!c)throw new fe("config_malformed",`${d}[${u}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return c},o=n("items");o.forEach((l,d)=>i(l??{},"items",d));let s=n("currencies");s.forEach((l,d)=>i(l??{},"currencies",d));let a=t;return {...a,version:r,hash:typeof a.hash=="string"?a.hash:"",items:o,currencies:s,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 a.kv=="object"&&a.kv!==null&&!Array.isArray(a.kv)?a.kv:{},item:Ad(o),currency:Ad(s)}}var fe=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},xd=10*1024*1024,Pd=15e3,Ed=new Set(["dev","test","release"]);function Kg(t){if(!Ed.has(t))throw new fe("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...Ed].join(", ")}. gem-api would reject the assignment read.`);return t}var Dr=t=>typeof t=="number"?t:0,go=t=>typeof t=="string"?t:"";function Jg(t){let e=t??{},n=Array.isArray(e.entries)?e.entries.map(r=>{let i=r??{},o=typeof i.rarity_tier=="string"?i.rarity_tier:void 0;return {entryId:go(i.entry_id),weight:Dr(i.weight),dropRate:Dr(i.drop_rate),...o===void 0?{}:{rarityTier:o}}}):[];return {lootTableId:go(e.loot_table_id),name:go(e.name),rollCount:Dr(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:Dr(e.total_weight),entries:n}}var Fr=class{constructor(e,n,r={}){this.api=e;this.channel=n;this.options=r;}api;channel;options;loaded=void 0;inFlight=null;generation=0;dropRatesByConfig=new WeakMap;load(){if(this.loaded!==void 0)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=void 0,this.inFlight=null,this.generation+=1;}async dropRates(e,n){let r=await this.load();if(r===null)throw new fe("config_channel_unknown",`dropRates(${e}) needs a loaded config, and this session's channel has none`);let i=this.dropRatesByConfig.get(r);i===void 0&&(i=new Map,this.dropRatesByConfig.set(r,i));let o=i.get(e);if(o!==void 0)return o;let s=(async()=>{let a=await al(this.api,e,n===void 0?{}:{signal:n});return Jg(a)})().catch(a=>{throw i?.get(e)===s&&i.delete(e),a});return i.set(e,s),s}async fetchConfig(){let e=AbortSignal.timeout(this.options.timeoutMs??Pd),n;try{let l=await il(this.api,Kg(this.channel()),{signal:e});if(!l.modified)throw new fe("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");n=l.body;}catch(l){if(l instanceof fe)throw l;if(l?.reason==="not_found")return null;throw l}let r=Wg(n.config_url);if(r===void 0)return null;let i=this.options.fetch??globalThis.fetch.bind(globalThis),o;try{o=await i(r,{credentials:"omit",signal:e});}catch(l){throw e.aborted?new fe("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??Pd}ms`):new fe("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(!o.ok){let l=await o.text().then(d=>ao(d)).catch(()=>"");throw new fe("config_unreachable",`the config document answered ${o.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let s=await o.text();if(s.length>xd)throw new fe("config_too_large",`the config document is ${s.length} bytes, over the ${xd} cap`);let a;try{a=JSON.parse(s);}catch(l){throw new fe("config_malformed",`config document is not JSON: ${String(l)}`)}return Vg(a)}};var Td=400,Me=t=>typeof t=="string"?t:"",zg=/(?:Z|[+-]\d{2}:?\d{2})$/i;function lt(t){let e=Me(t);if(!zg.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var Xg=/^[0-9a-f]{1,64}$/,Yg=/^[0-9a-f]{16}$/,Qg=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,Zg=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function fo(t){let e=Me(t),n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!n)return;let[r,i,o]=[Number(n[1]),Number(n[2]),Number(n[3])],s=new Date(Date.UTC(r,i-1,o));return s.getUTCFullYear()===r&&s.getUTCMonth()===i-1&&s.getUTCDate()===o?e:void 0}var ef=4096,tf=new TextEncoder;function nf(t){let e=Me(t.challenge_data),n=Me(t.challenge_data_hash);return e===""||!Yg.test(n)?{}:tf.encode(e).length>ef?{}:{data:e,dataHash:n}}function rf(t){let e=t??{},n=lt(e.period_start_at),r=lt(e.period_ends_at);if(n===0||r===0)return;let i=Me(e.slug),o=Me(e.seed),s=fo(e.period_local_date),a=Me(e.boundary),l=Me(e.reset_time);return {id:Me(e.progression_definition_id),...i===""?{}:{slug:i},window:Me(e.window),periodStartAt:n,periodEndsAt:r,...s===void 0?{}:{periodLocalDate:s},boundary:Qg.test(a)?a:"",resetTime:Zg.test(l)?l:"",seed:Xg.test(o)?o:"",...nf(e)}}function Ct(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 $r(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(rf).filter(n=>n!==void 0):[]}var ln=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;Ct(n);let r=await Ml(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return $r(r)}};function Ge(t){return typeof t=="string"&&t!==""?t:void 0}var Id=new Set(["localhost","127.0.0.1","[::1]"]);function dt(t){return Ot(t)}function Ot(t){let e=Ge(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:"&&Id.has(n.hostname)))return e}var of=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,af=/^[a-z][a-z0-9_]{0,31}$/;function sf(t){if(!Array.isArray(t))return;let e=[],n=new Set;for(let r of t.slice(0,8)){let i=r??{},o=Ge(i.family),s=Ge(i.avatar_3d_id),a=dt(i.model_url),l=dt(i.icon_url);o===void 0||!af.test(o)||n.has(o)||s===void 0||!of.test(s)||a===void 0||l===void 0||(n.add(o),e.push({family:o,id:s,modelUrl:a,iconUrl:l}));}return e}function lf(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},i=Ge(r.item_id),o=dt(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function Pe(t){let e=t??{},n=Ge(e.player_id),r=Ge(e.display_name),i=Ge(e.discriminator),o=Ge(e.display_tag),s=Ge(e.avatar_icon_id),a=dt(e.avatar_icon_url),l=Ge(e.avatar_3d_id),d=dt(e.avatar_3d_model_url),u=dt(e.avatar_3d_icon_url),c=sf(e.avatars_3d);return {...n===void 0?{}:{playerId:n},...r===void 0?{}:{displayName:be(r,"displayName")},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:be(o,"displayTag")},...s===void 0?{}:{avatarIconId:s},...a===void 0?{}:{avatarIconUrl:a},...l===void 0?{}:{avatar3dId:l},...d===void 0?{}:{avatar3dModelUrl:d},...u===void 0?{}:{avatar3dIconUrl:u},...c===void 0?{}:{avatars3d:c},badges:lf(e.badges)}}var df=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function yo(t){if(t===void 0)return;let e=dt(t);if(e===void 0)return;let n=new URL(e);return Id.has(n.hostname)||df.has(n.origin)?e:void 0}var Cd=100,Gd=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function ho(t){let{periodsBack:e,period:n,playerId:r}=t;if(Ct(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!Gd.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 Ld(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!Gd.test(e))return;let n=fo(t.period_local_date),r=lt(t.period_start_at),i=lt(t.period_ends_at),o=r>0&&i>0;return {id:e,...n===void 0?{}:{localDate:n},...o?{startAt:r,endsAt:i}:{},opensAt:lt(t.opens_at),closesAt:lt(t.closes_at),final:t.final===true}}var dn=t=>typeof t=="string"?t:"",Mt=t=>typeof t=="number"?t:0,cn=t=>typeof t=="string"?t:void 0,cf=t=>typeof t=="number"?t:void 0,Dd={player:"players",character:"characters"};function uf(t,e){let n=t??{},r=cn(n.entity_id),i=typeof n.entity_type=="string"&&Object.hasOwn(Dd,n.entity_type)?n.entity_type:void 0,o=Fd(n.stats),s=n.properties!==null&&typeof n.properties=="object"?n.properties:void 0,a=e?n.is_viewer===true:void 0;return {...Pe(n),rank:Mt(n.rank),occurredAt:Mt(n.occurred_at),...a===void 0?{}:{isViewer:a},...r===void 0?{}:{entityId:r},...i===void 0?{}:{entityType:i},...o===void 0?{}:{stats:o},...s===void 0?{}:{properties:s}}}function Od(t,e){let n=t??{},r=cn(n.bucket_1),i=cn(n.bucket_2),o=cf(n.update_frequency_seconds),s=Ld(n);return {leaderboardType:dn(n.leaderboard_type),runType:dn(n.run_type),...r===void 0?{}:{bucket1:r},...i===void 0?{}:{bucket2:i},entries:Array.isArray(n.entries)?n.entries.map(a=>uf(a,e)):[],generatedAt:Mt(n.generated_at),...o===void 0?{}:{updateFrequencySeconds:o},...s===void 0?{}:{period:s}}}function Md(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=Fd(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:Mt(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function Fd(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 mf(t,e,n){let r=t??{},i=cn(r.bucket_1),o=cn(r.bucket_2),s=Ld(r);return {leaderboardType:dn(r.leaderboard_type),runType:dn(r.run_type),entityType:e,entityId:n,...i===void 0?{}:{bucket1:i},...o===void 0?{}:{bucket2:o},entries:Array.isArray(r.entries)?r.entries.map(Md).filter(a=>a!==void 0):[],personalBest:Md(r.personal_best)??null,totalRuns:Mt(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:Mt(r.generated_at),...s===void 0?{}:{period:s}}}var un=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=ho(n),i=await vl(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 Od(i,false)}async friends(e,n={}){let r=ho(n),i=await fl(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 Od(i,true)}async mine(e,n={}){return this.#n(e,"player","me",n)}async character(e,n,r={}){return this.#n(e,"character",n,r)}async#n(e,n,r,i){if(i.limit!==void 0){let{limit:l}=i;if(!Number.isInteger(l)||l<1||l>Cd)throw new TypeError(`limit must be an integer between 1 and ${Cd}, got ${String(l)}`)}let o=ho(i),s=await cl(this.#e,e,Dd[n],r,{...o,...i.bucket1===void 0?{}:{bucket_1:i.bucket1},...i.bucket2===void 0?{}:{bucket_2:i.bucket2},...i.limit===void 0?{}:{limit:i.limit},...i.signal===void 0?{}:{signal:i.signal}}),a=n==="player"&&r==="me"&&dn((s??{}).entity_id)||r;return mf(s,n,a)}};var qr=t=>typeof t=="string"?t:"",bo=t=>typeof t=="number"?t:0;function $d(t){let e=t??{};return {playerId:qr(e.player_id),key:qr(e.key),value:e.value,updatedAt:bo(e.updated_at)}}function pf(t){let e=t??{};return {...Pe(e),playerId:qr(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:bo(e.updated_at)}}function gf(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 i=await yl(this.api,qe(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:qr(i.key),entries:Array.isArray(i.entries)?i.entries.map(pf):[],generatedAt:bo(i.generated_at)}}async of(e,n,r={}){try{return $d(await Al(this.api,e,qe(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(i){if(gf(i))return null;throw i}}async set(e,n,r={}){if(qe(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(o){throw new TypeError(`showcase value for ${JSON.stringify(e)} could not be serialised to JSON: ${String(o)}.`,{cause:o})}let i=await this.selfPlayerId();return $d(await Hl(this.api,i,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await el(this.api,r,qe(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var ff="gemChallenge",qd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Nd(t){if(!(typeof t!="string"||t===""))try{return new URLSearchParams(t).get(ff)??void 0}catch{return}}var ct=class extends O{constructor(e,n={}){super(e.reason,e.status,e.detail,e.retryAfterSeconds,e.code),this.name="FriendChallengeError";for(let[r,i]of Object.entries(n))i!==void 0&&Object.assign(this,{[r]:i});}},Nr=t=>typeof t=="string"?t:void 0;function jd(t){let e=t??{};return {...Pe(e),playerId:Nr(e.player_id)??""}}function Bd(t){let e=t.has_more===true?Nr(t.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function yf(t){let e=t??{};return {friends:Array.isArray(e.data)?e.data.map(jd):[],...Bd(e)}}var vo=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function hf(t){return typeof t!="object"||t===null||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]=="string"||typeof e[1]=="number"&&Number.isFinite(e[1])))}function Ud(t){let e=t??{},n=vo(e.opened_at),r=vo(e.answered_at);return {id:Nr(e.item_id)??"",from:jd(e.sender),template:Nr(e.template)??"",params:hf(e.params),createdAt:vo(e.created_at)??0,...n===void 0?{}:{openedAt:n},...r===void 0?{}:{answeredAt:r}}}function bf(t){let e=t??{};return {challenges:Array.isArray(e.data)?e.data.map(Ud):[],...Bd(e)}}function vf(t){let e=t;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var pn=class{#e;#n;#i;#s;#t;constructor(e,n={}){this.#e=e,this.#n=n.challenge,this.#i=n.inviteToPlay,this.#s=n.setInviteParams,this.#t=n.launchedChallengeId;}async list(e={}){let n=await ql(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return yf(n)}challenge(e){return this.#n===void 0?Promise.resolve({outcome:"unavailable"}):this.#n(e)}inviteToPlay(e){return this.#i===void 0?Promise.resolve(false):this.#i(e)}setInviteParams(e){return this.#s===void 0?false:this.#s(e)}async inbox(e={}){let n=await $l(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return bf(n)}async launchedChallenge(e={}){let n=this.#t;if(n===void 0||!qd.test(n))return null;try{return Ud(await bl(this.#e,n,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(vf(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!qd.test(e))throw new O("invalid",400,"id must be a FriendChallenge.id, as gem.friends.launchedChallenge() or inbox() returned it",void 0,"bad_request");await jl(this.#e,e);}};var _f=0;function ue(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++_f)}-${String(Date.now())}-${t}`}}var wf=12e4,Wd=8,Sf=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Rf=/^[a-z0-9][a-z0-9_-]{0,63}$/;function gn(t,e,n={}){return new ct(new O("invalid",400,e,void 0,t),n)}function kf(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Af(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!Sf.test(e))return {error:gn("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!Rf.test(n))return {error:gn("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(!kf(r))return {error:gn("param_invalid","params must be a plain object of strings and integers")};let i={},o=Object.keys(r);for(let s of o){let a=r[s];if(typeof a=="string"||typeof a=="number"&&Number.isSafeInteger(a)){Object.defineProperty(i,s,{value:a,enumerable:true,writable:true,configurable:true});continue}return {error:gn("param_invalid",`params.${s} must be a string or a safe integer`,{param:s})}}return o.length>Wd?{error:gn("param_undeclared",`params has ${String(o.length)} keys; a template declares at most ${String(Wd)}`)}:{playerId:e,template:n,params:i}}function xf(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 ct(new O("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 ct(new O("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 Pf(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function Hd(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=Af(n);if("error"in r)return Promise.reject(r.error);let i=`challenge-${ue()}`;return new Promise((o,s)=>{let a={},l=u=>{e.delete(i)&&(t.clock.clearTimeout(a.timer),"error"in u?s(u.error):o(u.outcome));};e.set(i,l),a.timer=t.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},t.timeoutMs??wf);let d=false;try{d=t.bridge.requestFriendChallenge(i,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 (${Pf(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(xf(n));}}}var Ef=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","invite","_s","fbclid","ttclid","gclid","gbraid","wbraid","msclkid","gem_link","gem_test_ads","gem_cluster","moments","ads"]),Tf=["utm_"];function _o(t){return Ef.has(t)||Tf.some(e=>t.startsWith(e))}var If=new Set(["_s","embedder"]),Vd="gemEsc_",Kd=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,wo=64,So=16,Ro=512,ko=wo-Vd.length;function Jd(t){return If.has(t)?"reserved_key":(_o(t)||t.startsWith(Vd))&&t.length>ko?"round_trip":null}var Cf=/[\p{Cc}\p{Cf}]/u,Of=/\p{Cs}/u;function Gt(t,e){if(!Mf(t))return {error:"params must be a plain object of string values"};let n=Object.entries(t);if(n.length>So)return {error:`at most ${So} params; got ${n.length}`};let r=[];for(let[i,o]of n){let s=JSON.stringify(i);if(!Kd.test(i))return {error:`param ${s}: a key is a letter followed by up to ${wo-1} letters, digits, _ or -`};let a=e?Jd(i):_o(i)?"reserved_key":null;if(a==="reserved_key")return {error:e?`param ${s} is reserved: the arcade never carries it in a share link`:`param ${s} is reserved: this arcade reads it itself and never forwards it`};if(a==="round_trip")return {error:`param ${s}: a reserved key is carried escaped, and this one is too long to stay a valid key \u2014 keep it to ${ko} characters`};if(typeof o!="string")return {error:`param ${s}: values must be strings`};if(o.length>Ro)return {error:`param ${s}: a value is at most ${Ro} characters`};if(Cf.test(o))return {error:`param ${s}: control and format characters are not allowed`};if(Of.test(o))return {error:`param ${s}: a value must be well-formed text`};r.push({key:i,value:o});}return {pairs:r}}function Mf(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var jr="[gem] gem.friends",Gf=3e4;function zd(t){let e=null,n=new Map;return {inviteToPlay(r){if(!t.bridge.parentSupports("playInvites"))return Promise.resolve(false);let i;if(r!==void 0){if(typeof r!="object"||r===null)return console.warn(`${jr}.inviteToPlay: pass { params }, or nothing. Nothing was asked.`),Promise.resolve(false);if(r.params!==void 0){let s=Gt(r.params,t.bridge.parentSupports("shareRemap"));if("error"in s)return console.warn(`${jr}.inviteToPlay: ${s.error}. Nothing was asked.`),Promise.resolve(false);i=s.pairs;}}if(e!==null)return e;let o=`invite-${ue()}`;return e=new Promise(s=>{let a={},l=u=>{n.delete(o)&&(e=null,t.clock.clearTimeout(a.timer),s(u));};n.set(o,l),a.timer=t.clock.setTimeout(()=>{l(false);},t.timeoutMs??Gf);let d=false;try{d=t.bridge.requestArcade({type:"gem.requestPlayInvite",requestId:o,...i===void 0?{}:{params:i}});}catch{}d||l(false);}),e},settle(r){let i=r.shown===true,o=n.get(r.requestId);if(o===void 0){t.onDropped?.(`gem.playInviteResult (shown: ${String(i)}) for an unknown requestId: `+JSON.stringify(r.requestId));return}o(i);}}}function Xd(t){let e,n,r=()=>{if(e===void 0)return false;if(e===null&&n===void 0)return true;let i=t();if(i.currentState!=="connected"||!i.parentSupports("playInvites"))return false;let o;if(e!==null){let a=Gt(e,i.parentSupports("shareRemap"));if("error"in a)return console.warn(`${jr}.setInviteParams: ${a.error}. Nothing was sent.`),false;o=a.pairs;}let s=o===void 0?"":JSON.stringify(o);return s===n?true:i.requestArcade({type:"gem.inviteParams",...o===void 0?{}:{params:o}})?(n=s,true):false};return {set(i){if(i!==null){let o=Gt(i,true);if("error"in o)return console.warn(`${jr}.setInviteParams: ${o.error}. Nothing was sent; the last declaration stands.`),false;e=Object.fromEntries(o.pairs.map(({key:s,value:a})=>[s,a]));}else e=null;return r()},flush:r,forgetSent(){n=void 0;}}}var Br=t=>typeof t=="string"?t:void 0;function Lf(t){let e=t??{},n=Br(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:Br(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var Ur=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await pr(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=Lf(o);s!==void 0&&i.push(s);}return i}},Ao=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function Df(t){let e=t??{},n=Br(e.currency_id);if(n===void 0||n==="")return;let r=Ao(e.limit),i=Math.min(Ao(e.earned),r),o=Math.min(Ao(e.remaining),r-i),s=e.period_days,a=typeof s=="number"&&Number.isInteger(s)&&s>=1?s:1,l=e.resets_at,d=typeof l=="number"&&Number.isFinite(l)&&l>0?Math.round(l*1e3):void 0;return {currencySlug:Br(e.currency_slug)??"",currencyId:n,limit:r,earned:i,remaining:o,period:e.period==="day"?"day":"window",periodDays:a,...d===void 0?{}:{resetsAt:d}}}function Yd(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 i=r();typeof i?.then=="function"&&i.then(void 0,n);}catch(i){n(i);}}}}var Wr=class{#e;#n;#i;constructor(e,n,r){this.#e=e,this.#n=n,this.#i=r;}async get(e={}){let r=(await _l(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=Df(o);s!==void 0&&i.push(s);}return i}on(e,n){return e!=="changed"?(this.#i?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#n?.on(n)??(()=>{})}},fn=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new Ur(e),this.earnAllowance=new Wr(e,n,r);}};var xo=t=>typeof t=="string"?t:"",Qd=t=>typeof t=="number"?t:0;function Ff(t){let e=t??{};return {key:xo(e.key),visibility:xo(e.visibility),value:e.value,updatedAt:Qd(e.updated_at)}}function $f(t){let e=t??{};return {...Pe(e),playerId:xo(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(Ff):[],generatedAt:Qd(e.generated_at)}}function qf(t){return t?.reason==="not_found"}var yn=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return $f(await Sl(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(qf(r))return null;throw r}}};function Po(t){return typeof t=="string"&&/^[\w-]{1,64}$/.test(t)}function Hr(t,e){if(t===void 0||Po(t))return t;let n=typeof t=="string"?JSON.stringify(t.slice(0,72)):`a value of type ${typeof t}`;console.warn(`[gem] ${e}: cueId ${n} is not 1 to 64 letters, digits, _ or -, so it was left out. Use one crypto.randomUUID() per award.`);}var Nf=new Map([["function_error",false],["function_failed",false],["function_timeout",false],["function_not_published",false],["function_input_too_large",false],["invalid_cue_id",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]]),hn=class extends O{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:Nf.get(this.code))??super.retryable}},Xe=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=jf(e),i=Hr(n.cueId,"functions.invoke"),o;try{o=await this.#e(r,{...n.signal===void 0?{}:{signal:n.signal},...i===void 0?{}:{cue_id:i}});}catch(s){throw s instanceof O?Uf(s):s}return Bf(o)}};function jf(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 de(`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 de(`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 Bf(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 Uf(t){let{details:e,invocationId:n}=Ns(t),i=e?.untrusted?.message,o=e?.reason;return new hn(t,{...n===void 0?{}:{invocationId:n},...t.code==="function_error"&&typeof i=="string"?{functionMessage:i}:{},...t.code==="function_failed"&&typeof o=="string"?{failure:o}:{}})}function Vr(t,e){let n=e?.retryAfterSeconds,r=typeof n=="number"&&Number.isFinite(n)&&n>0?n*1e3:0,i=1e4*2**Math.min(Math.max(0,t-1),16);return Math.min(Math.max(r,i),3e5)}var Wf=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost","gem_graphics_context_lost"],Eo="gem_";function To(t){return t.startsWith(Eo)}function Hf(t){let e=2166136261;for(let n of new TextEncoder().encode(t))e^=n,e=Math.imul(e,16777619);return e>>>0}function Vf(t){let e=t;return e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^=e>>>16,e>>>0}function Kr(t,e,n){if(Io(t,n),typeof e!="string"||e==="")throw new TypeError("[gem] experiment: playerId must be a non-empty string");let r=typeof n=="number"?n:n.length,i=Vf(Hf(`${t}:${e}`))%r;return typeof n=="number"?i:n[i]}function Io(t,e){if(typeof t!="string"||t==="")throw new TypeError("[gem] experiment: key must be a non-empty string");if(typeof e=="number"){if(!Number.isInteger(e)||e<1||e>2048)throw new RangeError(`[gem] experiment '${t}': the count must be an integer from 1 to 2048; got ${String(e)}`);return}if(!Array.isArray(e))throw new TypeError(`[gem] experiment '${t}': pass a count or a list of strings; got ${typeof e}`);let n=e;if(n.length<1||n.length>2048)throw new RangeError(`[gem] experiment '${t}': the list must hold 1 to 2048 strings; got ${n.length}`);if(!n.every(r=>typeof r=="string"))throw new TypeError(`[gem] experiment '${t}': every option must be a string`)}var Zd=1e4,ec=50,Kf=500,Jf=65536-4*1024,zf=24*1024;function tc(t){let e={},n={};for(let[r,i]of Object.entries(t))typeof i=="string"?e[r]=i:typeof i=="number"&&Number.isFinite(i)&&(n[r]=i);return {dimensions:e,measures:n}}var Xf=6e4;function Yf(t){let e=new Map;for(let n of t??[]){let r=new Set;for(let[i,o]of Object.entries(n.dimensions??{})){let s=o?.range;typeof s=="object"&&s!==null&&r.add(i);}r.size>0&&e.set(n.id,r);}return e}function Qf(t,e){if(e===void 0)return t;let n=null,r={};for(let[i,o]of Object.entries(t.measures))e.has(i)?(n??={...t.dimensions})[i]=String(o):r[i]=o;return n===null?t:{dimensions:n,measures:r}}var nc=t=>typeof t=="number"?t:0,Zf=t=>typeof t=="string"?t:"";function Jr(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function ey(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(i=>{let o=i??{};return {index:nc(o.index),code:Zf(o.code)}}):[];return {accepted:nc(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Co(){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}var bn=class{#e;#n;#i;#s;#t=[];#b={};#a=0;#l=null;#v=false;#_=false;#p=0;#w=0;#S=0;#r=false;#R=null;#d=null;#u=false;#o=false;#g=false;#k=false;#A=false;#f=void 0;#x=false;#P=0;constructor(e){this.#e=e,this.#n=e.options?.enabled!==false,this.#i=Math.max(Zd,e.options?.flushIntervalMs??Zd),this.#s=Math.max(1,Math.floor(e.options?.maxQueue??Kf));}track(e,n={}){if(!this.#n||this.#r)return;if(To(e)){this.#A||(this.#A=true,this.#h(`[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.#E(e,tc({...this.#b,...n}));let r=this.#C();this.#f===void 0&&!this.#x&&r!==null&&r!==""&&(this.#x=true,this.#O());}setContext(e){this.#b={...this.#b,...e};}async experiment(e,n){Io(e,n);let r=this.#e.awaitPlayerId===void 0?this.#e.playerId():await this.#e.awaitPlayerId();if(r===null)throw new Error(`[gem] experiment '${e}': no player to select for \u2014 this call was not made by a player.`);return typeof n=="number"?Kr(e,r,n):Kr(e,r,n)}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#o)return Jr();let n=this.#C();if(n===null||n==="")return this.#t.length>0&&!this.#k&&(this.#k=true,this.#h("[gem] analytics: events are being recorded but no play session has been established, so nothing is being sent. Outside the arcade this is expected.")),Jr();let r=e.keepalive===true;if(!r&&this.#e.declarations!==void 0&&this.#t.some(d=>!To(d.name))&&await this.#O(),this.#I(),this.#t.length===0||this.#p>0&&!r)return Jr();this.#m();let i=this.#t.splice(0,this.#G(r)),o=this.#a;this.#a=0;let s=Math.round(this.#e.clock.now()),a={batch_id:Co(),sent_at_ms:s,events:i.map(d=>rc(d,s,this.#f?.get(d.name)))},l={client:this.#e.client(),gameId:()=>n};this.#p+=1;try{let d=await Tl(l,a,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),u=ey(d,o);return this.#w=0,this.#S=0,this.#L(u),u}catch(d){throw ty(d)?(this.#M(i,o),this.#w+=1,this.#S=this.#e.clock.now()+Vr(this.#w,d)):this.#h(`[gem] analytics: ${i.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#p-=1,this.#t.length>0&&this.#c();}}trackPlatform(e,n={}){this.#r||this.#o&&(e==="gem_pause"||e==="gem_resume")||this.#E(e,tc(n));}hold(){this.#r||this.#d!==null||(this.#o=true,this.#m());}release(){if(!this.#o||this.#r)return;this.#o=false;let e=this.#e.clock.now(),n=this.#t.map(r=>({...r,atMs:e}));this.#t=n,this.#g&&(this.#g=false,this.#d=e,this.#u=false,this.#t.unshift({uid:Co(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#t.length>=ec?this.#y():this.#t.length>0&&this.#c();}get held(){return this.#o}startSession(){if(!(this.#r||this.#d!==null)){if(this.#o){this.#g=true;return}this.#d=this.#e.clock.now(),this.#u=false,this.trackPlatform("gem_session_start");}}endSession(e){if(this.#r||this.#u)return;if(this.#u=true,this.#o){this.#g=false,this.#t=[],this.#a=0;return}let n=this.#d;this.trackPlatform("gem_session_end",{reason:e,...n===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-n))}}),this.#y({keepalive:true});}setPaused(e){this.#r||e===this.#v||(this.#v=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#m():this.#t.length>0&&this.#c());}setHidden(e){this.#r||e===this.#_||(this.#_=e,e?this.#m():this.#t.length>0&&this.#c());}dispose(){this.#r=true,this.#m(),this.#t=[],this.#a=0;}get pending(){return this.#t.length}#E(e,n){let{dimensions:r,measures:i}=n;for(this.#I();this.#t.length>=this.#s;)this.#t.shift(),this.#a+=1;this.#t.push({uid:Co(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:i}),this.#t.length>=ec?this.#y():this.#c();}#y(e={}){if(e.keepalive!==true&&this.#T()>0){this.#c();return}this.flush(e).catch(()=>{});}#T(){return Math.max(0,this.#S-this.#e.clock.now())}#M(e,n){for(this.#t=[...e,...this.#t],this.#a+=n;this.#t.length>this.#s;)this.#t.shift(),this.#a+=1;}#G(e){let n=e?zf:Jf,r=Math.min(this.#t.length,100),i=128;for(let o=0;o<r;o+=1){let s=this.#t[o];if(s===void 0)break;if(i+=JSON.stringify(rc(s,0,this.#f?.get(s.name))).length+1,i>n)return Math.max(1,o)}return r}#c(){this.#l!==null||this.#v||this.#_||this.#o||this.#r||this.#p>0||(this.#l=this.#e.clock.setTimeout(()=>{this.#l=null,this.#y();},Math.max(this.#i,this.#T())));}#m(){this.#l!==null&&(this.#e.clock.clearTimeout(this.#l),this.#l=null);}#I(){let e=this.#D();e===null||e===""||(this.#R!==null&&this.#R!==e&&(this.#t=[],this.#a=0,this.#d=null,this.#u=false),this.#R=e);}#L(e){for(let n of e.rejected)this.#h(`[gem] analytics: an event was refused (${n.code}). `+ny(n.code));}#h(e){let n=this.#e.log;n!==null&&(n===void 0?console.warn(e):n(e));}#C(){try{return this.#e.gameId()}catch{return null}}#D(){try{return this.#e.playerId()}catch{return null}}async#O(){let e=this.#e.declarations;if(e!==void 0&&!(this.#e.clock.now()<this.#P))try{this.#f=Yf(await e());}catch{this.#P=this.#e.clock.now()+Xf;}}};function rc(t,e,n){let{dimensions:r,measures:i}=Qf(t,n);return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:r,measures:i}}function ny(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 Se(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e}function Ee(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=Se(n);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var ry=2e3,iy=5e3;function oc(t){let e=[],n=false,r=null,i=new Map,o=()=>{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 s,a=new Promise(l=>{let d=false,u=null;s=c=>{d||(d=true,r=null,t.clock.clearTimeout(u),l(c));},u=t.clock.setTimeout(()=>{n=true,s([]);},t.timeoutMs??ry);});return r={promise:a,settle:s},a};return {resolveList:o,resolve(){return e.length>0||n||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):o().then(s=>s[0])},refresh(s){return !ic(e,s)||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let l=null,d=u=>{i.delete(d)&&(t.clock.clearTimeout(l),a(u));};i.set(d,s),l=t.clock.setTimeout(()=>d(e),t.refreshTimeoutMs??iy);})},accept(s,a){let l=Ee(a),d=Se(s),u=l.length>0?l:d===void 0?[]:[d];if(u.length!==0){e=u,r?.settle(u);for(let[c,g]of [...i])ic(u,g)||c(u);}}}}function ic(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var oy=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),A=class extends Error{constructor(n,r,i){super(`${n}: ${r}`,i);this.reason=n;this.name="DedicatedServerError",this.retryable=oy.has(n),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var ac=["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"],ay=new Set(ac);function Ye(t){return typeof t=="string"&&ay.has(t)?t:"unknown"}var zr="webrtc_dedicated",Lo=["universal","mobile","web"];var sy="p2p_unavailable",ly="capacity_unavailable",dy=2,sc=3e4,lc=1e3,dc=2e4;async function Do(t){let e=Se(t.clusterTargetId),n=t.nextClusterTarget,r=0,i=t.clock??ce,o=t.retry??{},s=o.budgetMs??sc,a=o.maxDelayMs??dc,l=o.initialDelayMs??lc,d=i.now(),u=d+s,c=0;for(;;){c++;try{let g=await No(t.signal,"while allocating",()=>t.client.post(`${mc(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:g.match_id,status:g.status}}catch(g){if(!cy(g)||s<=0)throw g;if(g.status===503&&g.code===sy)throw new A("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: ${g.message}`,{cause:g});if(r=g.code===ly?r+1:0,n!==void 0&&r>=dy){let v=n;n=void 0;let k=Se(await v());k!==void 0&&(e=k,r=0);}let p=Math.min(a,l*2**(c-1)),f=Math.min(a,(g.retryAfterSeconds??0)*1e3),R=Math.max(p/2,f)+Math.random()*(p/2);if(i.now()+R>u)throw uy(t,g,c,i.now()-d,s);if(o.onWaiting?.({attempt:c,elapsedMs:i.now()-d,budgetMs:s,nextAttemptInMs:R,status:g.status,message:g.message}),await Xr(i,R,t.signal),t.signal?.aborted)throw Go("while waiting to allocate")}}}function cy(t){return t instanceof O?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function uy(t,e,n,r,i){let o=`${n} attempt${n===1?"":"s"} over ${r}ms of a ${i}ms budget`;return e.status===429?new A("start_rate_limited",`the platform was still limiting match starts for room ${t.roomId} after ${o}: ${e.message}`,{cause:e}):new A("no_server_ready",`the platform had no server ready for room ${t.roomId} after ${o}: ${e.message}`,{cause:e})}var my=12e4,py=1e3;async function Fo(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??py,i=t.timeoutMs??my,o=e.now()+i,s=cc(t),a={seen:t.knownToExist===true};for(;;){let l=await uc(t,s,a);if(l.outcome!==null)return l.outcome;if(e.now()+r>o)throw new A("timeout",`match ${n} was still ${l.status} after ${i}ms`);await Xr(e,r,t.signal);}}async function $o(t){return (await uc(t,cc(t),{seen:t.knownToExist===true})).outcome}function cc(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${mc(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function uc(t,e,n){let{matchId:r}=t,i=t.clock.now(),o;try{o=await No(t.signal,"while polling match status",()=>t.client.get(e,t.signal));}catch(s){if(s instanceof O&&s.reason==="not_found")return {status:"not_found",outcome:n.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw s}if(n.seen=true,o.status==="ready")return {status:"ready",outcome:gy(r,o,i)};if(o.status==="failed"){let s=o.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:Ye(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function qo(t){let e=await No(t.signal,"while listing cluster targets",()=>t.client.get("/v1/ping/targets",t.signal)),n=[];for(let r of e.targets??[]){let i=r?.cluster_target_id;typeof i!="string"||i.length===0||n.push({id:i,pressure:typeof r.pressure=="string"?r.pressure:"unknown"});}return n}async function No(t,e,n){if(t?.aborted)throw Go(e);try{return await n()}catch(r){throw t?.aborted?Go(e,r):r}}function Go(t,e){return new A("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function gy(t,e,n){let r=e.join_credential,i=e.expires_in_seconds,o=typeof r=="string"&&typeof i=="number";return {status:"ready",matchId:t,protocol:e.protocol??"unknown",...o?{joinCredential:r,credentialExpiresAt:n+i*1e3}:{},...e.host===void 0?{}:{host:e.host},...e.port===void 0?{}:{port:e.port}}}function mc(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function Xr(t,e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let i=()=>{t.clearTimeout(o),n?.removeEventListener("abort",i),r();},o=t.setTimeout(i,e);n?.addEventListener("abort",i);})}function pc(t){return typeof t=="string"&&t.trim()!==""}function Yr(t,e){return pc(t)?t.trim():pc(e)?e:null}var Qr="0.1.0-beta",gc="0-beta",Lt="web",fy=/^(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 yy(t){let e=fy.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function fc(t,e){let n=hy(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:Qr};let i=yy(r);if(i===null)throw new A("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 '${Qr}' for it.`);if(i!==gc)throw new A("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${gc}' is the only line a web dedicated-server fleet runs. gem-api uses the line \u2014 the semver major plus any prerelease tag \u2014 verbatim as the fleet's label selector, so a match on '${i}' would match nothing and be reported as a capacity shortfall rather than as this. Omit engineVersion: a browser game has no engine version of its own, and the SDK reports '${Qr}' for it.`);return {...t,platform:n,engineVersion:r}}function hy(t,e){if(t===void 0||t===Lt)return Lt;if(!Lo.includes(t))throw new A("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${Lo.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${Lt}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${Lt}' 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.`),Lt}function vn(t){let e=t??{};if(typeof e.ticket_id!="string"||e.ticket_id.length===0)throw new Error("[gem] a matchmaking-ticket response carried no id");let n=e.heartbeat_interval_seconds;return {id:e.ticket_id,status:typeof e.status=="string"?e.status:"queued",...typeof e.reason=="string"?{reason:e.reason}:{},...typeof e.game_room_id=="string"?{roomId:e.game_room_id}:{},partySize:typeof e.party_size=="number"?e.party_size:1,queuedAt:yc(e.queued_at),expiresAt:yc(e.expires_at),heartbeatIntervalSeconds:typeof n=="number"&&n>0?n:0}}function yc(t){if(typeof t!="string")return 0;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1e3):0}var by=3,hc=1e3,Zr=class{constructor(e){this.options=e;this.snapshot=e.first;let n=new Promise((o,s)=>{this.resolve=o,this.reject=s;});n.catch(()=>{});let r=()=>this.snapshot,i=()=>this.status;this.ticket={get id(){return r().id},get status(){return i()},get partySize(){return r().partySize},get queuedAt(){return r().queuedAt},get expiresAt(){return r().expiresAt},outcome:n,cancel:()=>(this.requestCancel(),n)};}options;ticket;snapshot;status="queued";timer=null;busy=false;again=false;cancelRequested=false;soon=false;misses=0;settled=false;resolve;reject;start(){this.apply(this.snapshot);}poke(){this.settled||(this.soon=true,!this.busy&&(this.clearTimer(),this.tick()));}abandon(e=false){this.settled||(this.options.cancel(this.snapshot.id,e).catch(()=>{}),this.settle({status:"cancelled",reason:"requested"}));}requestCancel(){this.settled||(this.cancelRequested=true,this.trigger());}trigger(){if(this.busy){this.again=true;return}this.clearTimer(),this.tick();}schedule(e=false){if(this.settled)return;this.clearTimer();let n=e?hc:Math.max(hc,this.snapshot.heartbeatIntervalSeconds*1e3);this.timer=this.options.clock.setTimeout(()=>{this.timer=null,this.tick();},n);}clearTimer(){this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null);}async tick(){if(this.settled||this.busy)return;this.busy=true,this.again=false;let e=null,n=null;try{e=this.cancelRequested?await this.options.cancel(this.snapshot.id):await this.options.heartbeat(this.snapshot.id);}catch(r){n=r;}if(this.busy=false,!this.settled){if(e===null){this.missed(n);return}this.misses=0,await this.apply(e);}}missed(e){if(e instanceof O&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<by){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let n=e instanceof O&&e.code==="matchmaking_unavailable";this.settle({status:n?"unavailable":"lost"});}async apply(e){if(this.snapshot=e,e.status==="queued"){this.next();return}if(e.status==="matched"){await this.seat(e);return}e.status==="expired"?this.settle({status:"expired",reason:e.reason??"timed_out"}):e.status==="cancelled"?this.settle({status:"cancelled",reason:e.reason??"requested"}):this.settle({status:"failed",reason:e.reason??e.status});}next(){if(this.again){this.again=false,this.tick();return}let e=this.soon;this.soon=false,this.schedule(e);}async seat(e){if(e.roomId===void 0){this.fail(new Error("[gem] a matched matchmaking ticket named no game room"));return}this.busy=true;try{let n=await this.options.seat(e.roomId);this.busy=!1,this.settle({status:"matched",room:n});}catch(n){this.busy=false,this.fail(n);}}settle(e){this.settled||(this.finish(e.status),this.resolve(e));}fail(e){this.settled||(this.finish("matched"),this.reject(e));}finish(e){this.settled=true,this.status=e,this.clearTimer(),this.options.onSettled();}};var vy="gemPlayWith",_y=/^[A-Za-z0-9_-]{16,128}$/;function bc(t){if(typeof t!="string"||t==="")return;let e;try{e=new URLSearchParams(t).get(vy);}catch{return}return e!==null&&_y.test(e)?e:void 0}function vc(t){let e=typeof t=="object"&&t!==null?t.play_with:void 0;return e==null?null:e==="joined"?"joined":"unavailable"}var wy="join",Sy="welcome",Ry="rejected",_c=25e3,ky=1e3,jo=1;function Bo(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var Ay={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 Uo(t){let e=typeof t=="string"?t:"unknown";return new A(Ay[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function _n(t){let{channel:e,clock:n}=t;return new Promise((r,i)=>{let o=false,s=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??_c),a=n.setTimeout(()=>h(new A("timeout","the server runtime sent no welcome before the join credential expired. The channel was open, so this is the runtime not answering rather than a connection that never came up.")),Math.max(s,ky)),l=R=>{let v=R.data;if(typeof v!="string"){c(v);return}let k;try{k=JSON.parse(v);}catch{c(v);return}if(o){c(v);return}if(k.t===Sy){let y=Bo(k.heartbeat_interval);f({...typeof k.player_id=="string"?{playerId:k.player_id}:{},...typeof k.match_id=="string"?{matchId:k.match_id}:{},...y===void 0?{}:{heartbeatIntervalMs:y}});return}if(k.t===Ry){h(Uo(k.reason));return}c(v);},d=()=>{h(new A("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},u=()=>{h(new A("aborted","the caller aborted during the join exchange"));},c=R=>{o&&t.onMessage?.(R);},g=()=>{n.clearTimeout(a),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",u);},p=()=>{e.removeEventListener("message",l);},f=R=>{o=true,g(),t.onMessage===void 0&&p(),r({welcome:R,detach:p});},h=R=>{o||(o=true,g(),p(),i(R));};if(e.addEventListener("message",l),e.addEventListener("close",d),t.signal?.aborted){u();return}t.signal?.addEventListener("abort",u);try{e.send(JSON.stringify({t:wy,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:jo}:{}}));}catch(R){h(new A("connection_failed",`the join frame could not be sent on the open channel: ${String(R)}`,{cause:R}));}})}var ut=1,wn=2,Wo=4,Ko=8,xy=2,Py=1e3,Jo="heartbeat timeout",Sn="gem-uu",ei=2,Sc="gem_transports";function Dt(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!Ey(r)||e.includes(r)||e.push(r);}return e}function Ey(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function Rn(t,e){if(typeof t!="object"||t===null)return null;let n=t[Sc];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 ti(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var Rc=new TextEncoder,kc=new TextDecoder;function zo(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function Xo(t){let e=0;return t?.reliable===false&&(e|=ut),t?.ordered===false&&(e|=wn),e}function Yo(t){return {reliable:(t&ut)===0,ordered:(t&wn)===0}}var Qo={reliable:true,ordered:true};function Ac(t){return JSON.stringify({t:"join",credential:t,wire:ei,heartbeat:jo})}function xc(t){let e;try{e=JSON.parse(t);}catch{throw new A("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let n=Bo(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"?Uo(e.reason):new A("join_refused","the server answered the join out of protocol")}function ni(){return typeof globalThis.WebTransport=="function"&&Zo===null}function ri(){return Zo}var Zo=null;var wc="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Ty(t){let e=mr(t);if(e.byteLength!==32)throw new A("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var Ho=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 o=new DataView(this.buffered.buffer,this.buffered.byteOffset,4).getUint32(0,true);if(o===0||o>1<<20)throw new A("connection_failed",`a control-stream record claims ${o} bytes`);if(this.buffered.byteLength<4+o)break;let s=this.buffered.slice(4,4+o);this.buffered=this.buffered.slice(4+o),r.push({flags:s[0]??0,payload:s.slice(1)});}return r}};function Vo(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 kn(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webTransport;if(n===void 0){let a=globalThis.WebTransport;if(a===void 0)throw new A("connection_failed","this environment has no WebTransport");n=t.certHashBase64===void 0?new a(t.url):new a(t.url,{serverCertificateHashes:[{algorithm:"sha-256",value:Ty(t.certHashBase64)}]});}let r=n,i=a=>{try{r.close();}catch{}throw a},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(Zo=wc,i(new A("connection_failed",`${wc}; the rung is skipped for the rest of this page (a reload probes again)`)));let s=new Promise((a,l)=>{setTimeout(()=>l(new A("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,s]);let a=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([a.read(),s]);if(a.releaseLock(),l.done||l.value===void 0)return i(new A("connection_failed","the session ended before the control stream arrived"));let d=l.value,u=d.writable.getWriter();await u.write(Vo(Wo,Rc.encode(Ac(t.credential))));let c=new Ho,g=d.readable.getReader(),p;for(;p===void 0;){let f=await Promise.race([g.read(),s]);if(f.done||f.value===void 0)return i(new A("connection_failed","the control stream closed before the join was answered"));for(let h of c.push(f.value)){p=xc(kc.decode(h.payload));break}}return {link:Iy(r,u,g,c,t.log??(f=>console.warn(f)),Ec(p,t.clock)),welcome:p}}catch(a){return i(a)}}function Iy(t,e,n,r,i,o){let s,a,l=false,d=f=>{if(!l){l=true,u.stop();try{t.close();}catch{}a?.(f);}},u=ta(o,()=>d(Jo)),c=(f,h)=>{u.heard(),(f&Ko)===0&&s!==void 0&&((f&Wo)!==0?s(kc.decode(h),Qo):s(h,Yo(f)));};(async()=>{try{for(;;){let f=await n.read();if(f.done||f.value===void 0)break;for(let h of r.push(f.value))c(h.flags,h.payload);}}catch{}d("stream closed");})();let g,p;try{let f=t.datagrams;if(f?.readable!==void 0&&f.writable!==void 0){let h=f.readable.getReader();p=f.writable.getWriter(),g=f,(async()=>{try{for(;;){let R=await h.read();if(R.done||R.value===void 0)break;let v=R.value;v.byteLength!==0&&c((v[0]??0)|ut|wn,v.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(f){g=void 0,p=void 0,i(`[gem] webtransport datagram lane unusable (${ti(f)}); unreliable sends ride the stream`);}return t.closed.then(f=>d(Pc(f?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(f,h){if(l)return;if(typeof f=="string"){e.write(Vo(Wo,Rc.encode(f))).catch(()=>d("write failed"));return}let R=Xo(h);if((R&ut)!==0&&p!==void 0){let v=zo(R,f),k=g?.maxDatagramSize;if(k===void 0||v.byteLength<=k){p.write(v).catch(()=>{});return}}e.write(Vo(R,f)).catch(()=>d("write failed"));},onMessage(f){s=f;},onClose(f){a=f;},close(){d("closed");}}}function ea(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webSocket;if(n===void 0){let i=globalThis.WebSocket;if(i===void 0)return Promise.reject(new A("connection_failed","this environment has no WebSocket"));n=new i(t.url);}let r=n;return r.binaryType="arraybuffer",new Promise((i,o)=>{let s=false,a=setTimeout(()=>{s||(s=true,r.close(),o(new A("timeout","websocket did not come up in time")));},e),l=p=>{s||(s=true,clearTimeout(a),r.close(),o(p));},d=()=>{r.send(Ac(t.credential));},u=p=>{if(s)return;if(typeof p.data!="string"){l(new A("join_refused","the server sent binary before answering the join"));return}let f;try{f=xc(p.data);}catch(h){l(h);return}s=true,clearTimeout(a),r.removeEventListener("open",d),r.removeEventListener("message",u),r.removeEventListener("close",c),r.removeEventListener("error",g),i({link:Cy(r,Ec(f,t.clock)),welcome:f});},c=()=>{l(new A("connection_failed","the websocket closed before the join was answered"));},g=()=>{l(new A("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",u),r.addEventListener("close",c),r.addEventListener("error",g),r.readyState===1&&d();})}function Pc(t){return typeof t=="string"&&t.length>0?t:void 0}function Ec(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function ta(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,Py)*xy,i=n.now(),o=null,s=()=>{o=null;let a=n.now()-i;if(a>=r){e();return}o=n.setTimeout(s,r-a);};return o=n.setTimeout(s,r),{heard:()=>{i=n.now();},stop:()=>{o!==null&&(n.clearTimeout(o),o=null);}}}function Cy(t,e){let n,r,i=false,o=a=>{if(!i){i=true,s.stop();try{t.close();}catch{}r?.(a);}},s=ta(e,()=>o(Jo));return t.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){n?.(a.data,Qo);return}let l=new Uint8Array(a.data);if(l.byteLength===0)return;let d=l[0]??0;(d&Ko)===0&&n?.(l.slice(1),Yo(d));})),t.addEventListener("close",(a=>o(Pc(a?.reason)??"socket closed"))),{transport:"websocket",send(a,l){if(!i){if(typeof a=="string"){t.send(a);return}t.send(zo(Xo(l),a));}},onMessage(a){n=a;},onClose(a){r=a;},close(){o("closed");}}}function na(t,e,n,r){let i,o,s=false,a=n,l=c=>{if(!s){s=true,d.stop();try{t.close();}catch{}try{e.close();}catch{}o?.(c);}},d=ta(r,()=>l(Jo)),u=(c,g)=>{if(d.heard(),typeof c=="string"){i?.(c,Qo);return}let p=new Uint8Array(c);if(p.byteLength===0)return;let f=p[0]??0;(f&Ko)===0&&i?.(p.slice(1),Yo(f|g));};if(t.addEventListener("message",(c=>u(c.data,0))),t.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let c=e.connectionState;(c==="failed"||c==="closed")&&l(`connection ${c}`);})),a!==void 0){let c=a;c.addEventListener("message",(g=>u(g.data,ut|wn))),c.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(c,g){if(s)return;if(typeof c=="string"){t.send(c);return}let p=Xo(g),f=zo(p,c);if((p&ut)!==0&&a!==void 0&&a.readyState==="open"){a.send(f);return}t.send(f);},onMessage(c){i=c;},onClose(c){o=c;},close(){l("closed");}}}function Tc(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let i=ra(r);i!==void 0&&(e[n]=i);}return e}function Ic(t){if(Array.isArray(t))return t.map(Oy).filter(e=>!!e)}function ra(t){if(ia(t)||Array.isArray(t)&&t.every(ia))return t}function ia(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function Oy(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=ra(e.fixed),r=ra(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},...Ft("description",My(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(ia)?{allowed:e.allowed}:{},...Ft("min",An(e.min)),...Ft("max",An(e.max)),...Ft("minItems",An(e.min_items)),...Ft("maxItems",An(e.max_items)),...Ft("maxLength",An(e.max_length))}}function My(t){return typeof t=="string"&&t.length>0?t:void 0}function An(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Ft(t,e){return e===void 0?{}:{[t]:e}}function Ne(t){let e=t??{},n=Y(e.id)??Y(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(Gy):[];return {id:n,gameId:Y(e.game_id)??"",name:Y(e.name)??"",status:Y(e.status)??"open",hostPlayerId:Y(e.host_player_id)??"",maxPlayers:Le(e.max_players)??0,memberCount:Le(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...Re("joinCode",Y(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...Re("roomArgs",Tc(e.room_args)),...Re("roomArgsTemplate",Ic(e.room_args_template)),gameChannel:Y(e.game_channel)??"release",...Re("region",Y(e.region)),...Re("clusterTargetId",Y(e.cluster_target_id)),selfHosted:e.self_hosted===true,...Re("matchId",Y(e.match_id)),version:Le(e.version)??0,...Re("templateId",Y(e.template_id)),...Re("templateSlug",Y(e.template_slug)),roomType:Y(e.game_room_type)??"Standard",...Re("transports",Dt(e.transports)??void 0),createdAt:Le(e.created_at)??0,updatedAt:Le(e.updated_at)??0,...Re("startedAt",Le(e.started_at))}}function Gy(t){let e=t??{};return {...Pe(e),playerId:Y(e.player_id)??"",isReady:e.is_ready===true,role:Y(e.role)??"member",joinedAt:Le(e.joined_at)??0,...Re("groupId",Y(e.group_id)),...Re("platform",Y(e.platform))}}function oa(t){let e=t??{};return {id:Y(e.id)??Y(e.game_room_id)??"",gameId:Y(e.game_id)??"",name:Y(e.name)??"",status:Y(e.status)??"open",hostPlayerId:Y(e.host_player_id)??"",maxPlayers:Le(e.max_players)??0,memberCount:Le(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:Y(e.game_channel)??"release",roomType:Y(e.game_room_type)??"Standard",createdAt:Le(e.created_at)??0}}function Y(t){return typeof t=="string"&&t.length>0?t:void 0}function Le(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Re(t,e){return e===void 0?{}:{[t]:e}}var ii=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(i=>({rooms:(i.game_rooms??[]).map(oa),...typeof i.next_cursor=="string"?{nextCursor:i.next_cursor}:{}}))}myRooms(e){return this.options.client.get(`/v1/games/${encodeURIComponent(this.options.gameId())}/players/me/game-rooms`,e).then(n=>({rooms:(n.game_rooms??[]).map(oa)}))}create(e,n,r){return Dy(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},...xn(n)},e.signal).then(Ne)}get(e,n){return this.options.client.get(this.roomV2(e),n).then(Ne)}join(e,n,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...n.partyId===void 0?{}:{party_id:n.partyId},...xn(r)},n.signal).then(Ne)}joinByCode(e,n,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...n.partyId===void 0?{}:{party_id:n.partyId},...xn(r)},n.signal).then(Ne)}quickJoin(e,n,r=[]){return aa(this.options,e,n,r).then(i=>i.room)}createTicket(e,n,r=[]){return Ys(this.generated(),{templates:e.templateSlugs.map(i=>({template_slug:i})),...r.length===0?{}:{cluster_target_ids:[...r]},...e.partyId===void 0?{}:{party_id:e.partyId},...xn(n)},{...e.signal===void 0?{}:{signal:e.signal}}).then(vn)}heartbeatTicket(e){return El(this.generated(),e).then(vn)}cancelTicket(e,n=false){return n?this.options.client.delete(`/v1/games/${encodeURIComponent(this.options.gameId())}/matchmaking/tickets/${encodeURIComponent(e)}`,void 0,{keepalive:true}).then(vn):Vs(this.generated(),e).then(vn)}leave(e,n,r,i=false){return this.options.client.post(`${this.roomV2(e)}/leave`,{leave_as_group:n},r,{keepalive:i}).then(()=>{})}asksSelfHosted(e){return Oc(this.options,e)}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(Ne)}setReady(e,n,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:n},r).then(Ne)}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(Ne)}leaveMatch(e,n){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:n}).then(()=>{})}generated(){return {client:this.options.client,gameId:this.options.gameId}}baseV2(){return Cc(this.options)}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 Cc(t){return `/v2/games/${encodeURIComponent(t.gameId())}/game-rooms`}function Oc(t,e){return e===void 0&&t.selfHosted?.()===true}function aa(t,e,n,r=[],i){let o=Oc(t,e.partyId);return t.client.post(`${Cc(t)}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...Ly(e.templateSlugs,o),...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},...o?{self_hosted:true}:{},...i===void 0?{}:{play_with_ticket:i},...xn(n)},e.signal).then(s=>({room:Ne(s),playWith:i===void 0?null:vc(s)}))}function Ly(t,e){return t===void 0?{}:{templates:(e?t.slice(0,1):t).map(r=>({template_slug:r}))}}function xn(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function Dy(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 oi=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 i=this.retainedMatch;queueMicrotask(()=>{this.listeners.get(e)?.has(n)&&this.retainedMatch===i&&n(i);});}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,((...i)=>{r(),n(...i);}));return r}emit(e,...n){e==="matchReady"&&(this.retainedMatch=n[0]);let r=this.listeners.get(e);if(r)for(let i of [...r])i(...n);}get retained(){return this.retainedMatch}retain(e){this.retainedMatch=e;}clearRetained(){this.retainedMatch=null;}clear(){this.listeners.clear(),this.retainedMatch=null;}};var ai=class{constructor(e){this.options=e;let n=e.first,r=new Promise(a=>{this.resolve=a;}),i=()=>this.status;this.ticket={id:n.ticketId,get status(){return i()},partySize:n.partySize??0,queuedAt:n.queuedAt??0,expiresAt:n.expiresAt??0,outcome:r};let o=n.queuedAt!==void 0&&n.expiresAt!==void 0?(n.expiresAt-n.queuedAt)*1e3:9e5,s=Math.min(Math.max(o,0),9e5)+5e3;this.timer=e.clock.setTimeout(()=>{this.timer=null,this.end({status:"lost"});},s);}options;ticket;status="queued";timer=null;resolve;get id(){return this.ticket.id}end(e){this.status==="queued"&&(this.status=e.status,this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null),this.options.onSettled(),this.resolve(e));}};function Fy(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var $y=1e3,qy=3e3,Ny=6e4,jy=2,Mc=new Set(["game_room_closed","game_room_gone"]),By=12e4,Uy=5e3,Wy=new Set(["invalid_cluster_target","capacity_unavailable"]),Hy=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function Dc(t,e){return new la(e,t)}var la=class{constructor(e,n={}){this.options=e;this.internals=n;this.autoFollow=e.followMatch!==false,this.apiOptions={client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true},this.api=new ii(this.apiOptions),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;internals;emitter=new oi;api;apiOptions;playWithAnswer=null;room=null;ticketWatch=null;queueing=false;partyWatch=null;heldQueued=null;queuedFromRoomId=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create"),this.assertNotQueued("create");let n=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("create",async()=>{let o=await n,s=a=>this.api.create(r,this.version("create"),a);for(let a=0;;a++)try{return await s(o[a])}catch(l){if(!sa(l))throw l;if(a+1<o.length)continue;let d=(await this.afterRefusedClusters(l,o)).find(u=>!o.includes(u));if(d===void 0)throw l;return s(d)}});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,n={}){this.assertNotInRoom("join"),this.assertNotQueued("join");let r=await this.attachParty(n),i=await this.run("join",()=>this.api.join(e,r,this.version("join")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async joinByCode(e,n={}){this.assertNotInRoom("joinByCode"),this.assertNotQueued("joinByCode");let r=await this.attachParty(n),i=await this.run("joinByCode",()=>this.api.joinByCode(e,r,this.version("joinByCode")));return this.enter(i,"joined"),this.askForLocalServer(i),i}async quickJoin(e){this.assertNotInRoom("quickJoin"),this.assertNotQueued("quickJoin"),Jy(e);let n=this.clusterTargets(),r=await this.attachParty(e),i=a=>this.postQuickJoin(r,a).catch(l=>this.retryPastStaleMembership(l,r,a)),o=await this.run("quickJoin",async()=>{let a=await n;return i(a).catch(async l=>{let d=await this.afterRefusedClusters(l,a);if(d.length===0||Lc(d,a))throw l;return i(d)})}),{room:s}=o;return this.playWithAnswer=o.playWith,this.enter(s,"joined"),this.askForLocalServer(s),s}async queueForMatch(e){this.assertNotQueued("queueForMatch"),Ky(e?.templateSlugs),this.queueing=true;try{let n=this.clusterTargets(),r=await this.attachParty(e),i=await this.run("queueForMatch",async()=>{let s=await n;return this.api.createTicket(r,this.version("queueForMatch"),s).catch(async a=>{let l=await this.afterRefusedClusters(a,s);if(l.length===0||Lc(l,s))throw a;return this.api.createTicket(r,this.version("queueForMatch"),l)})});this.heldQueued?.ticketId===i.id&&(this.heldQueued=null),this.partyWatch?.end({status:"lost"});let o=new Zr({clock:this.options.clock,first:i,heartbeat:s=>this.track(this.api.heartbeatTicket(s)),cancel:(s,a)=>this.track(this.api.cancelTicket(s,a)),seat:s=>this.enterMatchedRoom(s),onSettled:()=>{this.ticketWatch===o&&(this.ticketWatch=null),this.retuneSeatWatch();}});return this.ticketWatch=o,this.retuneSeatWatch(),o.start(),o.ticket}finally{this.queueing=false;let n=this.heldQueued;this.heldQueued=null,n!==null&&this.showPartyTicket(n);}}async enterMatchedRoom(e){let n=await this.run("queueForMatch",()=>this.api.get(e));return this.disposed?n:(this.room!==null&&this.room.id!==n.id&&(this.queuedFromRoomId=this.room.id,this.exit()),this.room===null&&this.enter(n,"joined"),this.room?.id===n.id?this.room:n)}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,i=()=>this.run("leave",()=>this.api.leave(n.id,e.asGroup!==false,e.signal,r));if(r){let o=i();this.track(this.notifyLeavingMatch({keepalive:true})),await o;}else await this.notifyLeavingMatch(),await i();this.exit(),this.emitter.emit("left");}async leaveAll(e){let n=await this.myRooms(e),r=[];for(let i of n)try{await this.run("leaveAll",()=>this.api.leave(i.id,!0,e)),r.push(i.id),this.room?.id===i.id&&(this.exit(),this.emitter.emit("left"));}catch{}return r}async close(e){let 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(i){if(i instanceof O&&i.reason==="not_found"){let o=this.heldMatchId;if(o!==null){let s=await this.askWhyEnded(o,e);this.endMatch(o,s??"game_room_gone",false);}return this.exit(),this.emitter.emit("closed"),null}throw this.reportError("refresh",i),i}return this.apply(r),await this.settleHeldMatch(e),this.room}async settleHeldMatch(e){let 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 i=await this.askWhyEnded(r,e);i!==null&&this.endMatch(r,i,n.status!=="closed");}finally{this.settling===r&&(this.settling=null);}}}async askWhyEnded(e,n){let r=this.room;if(r===null)return null;let i=this.takeHint(e),o;try{o=await this.track(this.onceGameIdKnown(()=>$o({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(s){return s instanceof O&&s.reason==="not_found"?i??null:(this.reportError("reconcile",s),null)}return o===null?null:o.status==="ready"?(this.seenMatches.add(e),null):o.status==="failed"?(this.settleFailed(o.matchId,o.reason),null):o.reason==="unknown"&&i!==null?i:o.reason}takeHint(e){let n=this.pendingHint;if(n===null||n.matchId!==void 0&&n.matchId!==e||(this.pendingHint=null,n.reason===void 0))return null;let r=Ye(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"),i=await this.run("setReady",()=>this.api.setReady(r.id,e,n));return this.apply(i),i}async kick(e,n){let r=this.requireRoom("kick"),i=await this.run("kick",()=>this.api.kick(r.id,e,n));return this.apply(i),i}async transferHost(e,n){let r=this.requireRoom("transferHost"),i=await this.run("transferHost",()=>this.api.transferHost(r.id,e,n));return this.apply(i),i}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 A("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 i=Se(n.clusterTargetId),o=i??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),s=o??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let a=(u,c)=>Do({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...u===void 0?{}:{clusterTargetId:u},...i===void 0?{nextClusterTarget:()=>this.nextCluster(c)}:{},retry:{...n.retry,onWaiting:g=>{this.emitter.emit("matchStartWaiting",g),n.retry?.onWaiting?.(g);}},...n.signal===void 0?{}:{signal:n.signal}}),l=()=>a(o,[s]).catch(async u=>{if(i!==void 0||!sa(u))throw u;let c=await this.nextCluster([s],true);if(c===void 0)throw u;return a(c,[s,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 A("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),i=await this.run("pollMatchStatus",()=>this.chase(n.id,r,e));return this.settleOutcome(i)}chase(e,n,r){return Fo({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 A("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!Mc.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new A("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 i={matchId:e,cause:n,attempt:0,deadlineAt:this.options.clock.now()+r.budgetMs,parkedAt:null,timer:null,parked:null,done:false};this.reconnect=i,this.track(this.reconnectStep(i));}park(e,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(!mt()){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<$y){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(Fy(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!mt()){this.park(e,()=>this.reconnectAttempt(e));return}let n=this.options.autoReconnect,r=this.room;if(n===void 0||r===null)return;let i=null;try{i=await this.track(this.onceGameIdKnown(()=>$o({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:r.id,matchId:e.matchId,version:this.version("reconcile"),knownToExist:this.seenMatches.has(e.matchId)})));}catch(o){this.reportError("reconcile",o);}if(this.reconnecting(e)){if(i?.status==="ended"){this.endMatch(i.matchId,i.reason,!Mc.has(i.reason)),this.track(this.reconcile().catch(()=>{}));return}if(i?.status==="failed"){this.abandonReconnect(e.matchId,i.reason),this.settleFailed(i.matchId,i.reason);return}if(i?.status==="ready"){this.seenMatches.add(e.matchId),this.session={phase:"ready",matchId:e.matchId},this.emitter.retain(i);let o;try{o=await n.redial(e.matchId,e.deadlineAt);}catch(s){this.reportError("reconcile",s),o="failed";}if(e.done||this.reconnect!==e)return;if(o==="closed"){this.finishReconnect();return}if(o==="connected")return;this.session.phase==="ready"&&this.session.matchId===e.matchId&&(this.session={phase:"suspended",matchId:e.matchId,reason:e.cause});}await this.reconnectStep(e);}}notifyMatchConnected(e){if(this.heldMatchId!==e||this.session.phase!=="ready"&&this.session.phase!=="suspended")return;let 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 A("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 A("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 A("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 currentTicket(){return this.ticketWatch?.ticket??null}get partyTicket(){return this.partyWatch?.ticket??null}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}get playWith(){return this.playWithAnswer}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.ticketWatch!==null&&e.event!=="version_stale"&&e.roomId!==this.room?.id&&this.ticketWatch.poke(),this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let 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 i=new AbortController;this.autoStartRetry=i,this.track(this.requestStart({signal:i.signal},false).then(()=>{},o=>{i.signal.aborted||this.reportError("startMatch",o);}).finally(()=>{this.autoStartRetry===i&&(this.autoStartRetry=null);}));}answerAutoStart(e){return this.options.retryAutoStart===false||!this.isHost||!Wy.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.watchingSeats&&this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}}handleTicketEvent(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}if(this.queueing){e.event==="queued"?this.heldQueued=e:this.heldQueued?.ticketId===e.ticketId&&(this.heldQueued=null);return}if(e.event==="queued"){this.showPartyTicket(e);return}if(e.event==="matched"){e.roomId!==void 0&&this.handleSeated(e.roomId),this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:"matched"});return}this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:e.event,reason:e.reason??e.event});}}showPartyTicket(e){if(this.disposed||this.partyWatch?.id===e.ticketId)return;this.partyWatch?.end({status:"lost"});let n=new ai({clock:this.options.clock,first:e,onSettled:()=>{this.partyWatch===n&&(this.partyWatch=null);}});this.partyWatch=n,this.emitter.emit("partyQueued",n.ticket);}async reconcileSeats(){if(this.disposed||!this.watchingSeats||this.ticketWatch!==null)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(i=>i.playerId===n)||this.room?.id!==r.id&&(this.reported.has(r.id)||(this.reported.add(r.id),this.partyWatch?.end({status:"matched"}),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.ticketWatch===null&&this.seatPollMs>0&&mt())){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(),!!mt())){if(this.room!==null){let r=this.reconnect?.parked??null;r!==null&&this.reconnect!==null?(this.reconnect.parked=null,this.track(r())):this.track(this.reconcile().catch(()=>{}));return}if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of si)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.ticketWatch?.abandon(),this.heldQueued=null,this.partyWatch?.end({status:"lost"}),this.abortAutoStartRetry(),this.finishReconnect(),this.stopPolling(),this.emitter.clear(),this.unloadListener&&(globalThis.removeEventListener?.("pagehide",this.unloadListener),this.unloadListener=null),this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null),this.visibilityListener){let e=globalThis;for(let r of si)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??Uy}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new A("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=Yr(this.options.platformGameVersion?.(),n?.gameVersion);if(r===null)throw new A("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 fc({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return Ee(await this.options.resolveClusterTargets());let e=Se(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !sa(e)||n.length===0?[]:Ee(await this.options.refreshClusterTargets?.(n)??[])}async nextCluster(e,n=false){let r=s=>s.find(a=>!e.includes(a)),i=await this.clusterTargets(),o=r(i);return o!==void 0||!n?o:r(Ee(await this.options.refreshClusterTargets?.(i)??[]))}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 O)||e.reason!=="conflict"||!Hy.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new O(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and \`recoverStaleMembership\` is off, so nothing cleared it. A membership that outlived its page is visible only through myRooms(); leaveAll() is what clears it.`,e.retryAfterSeconds,e.code);let i;try{i=await this.leaveAll(n.signal);}catch{throw new O(e.reason,e.status,`${e.detail} \u2014 quick-join is refused while this player already holds a game room, and the recovery could not list the rooms it would have cleared, so nothing was tried and the refusal stands. That is the listing failing, not a room refusing to be left: retry once the connection is back. myRooms() shows what is held.`,e.retryAfterSeconds,e.code)}if(i.length===0)throw new O(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.postQuickJoin(n,r)}postQuickJoin(e,n){return aa(this.apiOptions,e,this.version("quickJoin"),n,this.internals.playWithTicket)}assertNotInRoom(e){if(this.room!==null)throw new A("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}assertNotQueued(e){if(!(this.ticketWatch===null&&!this.queueing))throw new A("misconfigured",`${e} refused: this player is waiting on a matchmaking ticket, which will seat them in a room of its own. Cancel it first \u2014 currentTicket.cancel() \u2014 or wait for its outcome.`)}requireRoom(e){if(this.room===null)throw new A("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 O?{operation:e,code:n.status,reason:n.reason,message:n.message,retryable:n.retryable}:{operation:e,code:0,reason:n instanceof A?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.queuedFromRoomId===e.id&&(this.queuedFromRoomId=null),this.abortFollow(),this.autoStartRetried=false,this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(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(a=>[a.playerId,a])),i=new Map(e.members.map(a=>[a.playerId,a])),o=this.playerId();for(let a of i.keys())r.has(a)||this.emitter.emit("memberJoined",a);for(let a of r.keys())if(!i.has(a)){if(a===o){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",a);}for(let[a,l]of i){let d=r.get(a);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",a,l.isReady);}n.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let s=Vy(n,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),s&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let 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(i=>{if(!r.signal.aborted)try{this.settleOutcome(i);}catch{}}).catch(i=>{r.signal.aborted||this.reportError("pollMatchStatus",i);}).finally(()=>{this.followAbort===r&&(this.followAbort=null,this.followingMatchId=null);}));}abortFollow(){this.followAbort?.abort(),this.followAbort=null,this.followingMatchId=null;}matchIdOrWait(e){let n=this.heldMatchId;if(n!==null)return Promise.resolve(n);let r=e.timeoutMs??By;return new Promise((i,o)=>{let s=c=>{a(),l(),this.options.clock.clearTimeout(u),e.signal?.removeEventListener("abort",d),c();},a=this.emitter.on("matchAllocationStarted",c=>s(()=>i(c))),l=this.emitter.on("matchFailed",(c,g)=>s(()=>o(new A("allocation_failed",`match ${c} did not come up: ${g}`)))),d=()=>s(()=>o(new A("aborted","the caller aborted while awaiting a match"))),u=this.options.clock.setTimeout(()=>s(()=>o(new A("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??qy}pushedInterval(){return this.options.pushedPollIntervalMs??Ny}pushed(){return this.options.clock.now()-this.lastPushAt<jy*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=>{if(this.ticketWatch?.abandon(true),n?.persisted!==true&&(this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{})),this.queuedFromRoomId!==null)){let r=this.queuedFromRoomId;this.queuedFromRoomId=null,this.track(this.api.leave(r,true,void 0,true).catch(()=>{}));}},e.addEventListener("pagehide",this.unloadListener));}};function mt(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var si=["visibilitychange","focus","pageshow","online"];function Vy(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||Gc(t)!==Gc(e)}function Gc(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function sa(t){return t instanceof O&&t.code==="invalid_cluster_target"}var li=8;function Ky(t){if(!(Array.isArray(t)&&t.length>=1&&t.length<=li&&t.every(n=>typeof n=="string"&&n.length>0)))throw new A("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${li} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function Jy(t){let e=t?.templateSlugs;if(e===void 0)return;if(!(Array.isArray(e)&&e.length>=1&&e.length<=li&&e.every(r=>typeof r=="string"&&r.length>0)))throw new A("misconfigured",`quickJoin's templateSlugs is an array naming one to ${li} room templates by slug \u2014 quickJoin({ templateSlugs: ['duel', 'brawl'] }). A room that has to be created is made from the first.`);if(t?.templateSlug!==void 0||t?.templateId!==void 0)throw new A("misconfigured","quickJoin takes templateSlugs or a single templateSlug / templateId, not both. Put every template this player accepts in templateSlugs, with the one to create from first.")}function Lc(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var zy=["p2p","dedicated","unknown"],da=["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 $t=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let i=Xy(e,this.options.transport,(this.options.now??Date.now)());i.length!==0&&await this.options.client.post(`/v1/games/${encodeURIComponent(r)}/telemetry/p2p`,{events:i},n);}report(e){this.post(e).catch(()=>{});}};function Xy(t,e,n){let r=Math.floor(n/1e3);return t.filter(i=>da.includes(i.type)).slice(0,100).map(i=>{let o=Qy(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:{...Yy(i.labels),...i.value===void 0?{}:{value:i.value}}}})}function Yy(t){let e={};if(typeof t!="object"||t===null)return e;let n=0;for(let[r,i]of Object.entries(t)){if(n>=4)break;r==="value"||!Fc(r)||!Fc(i)||(e[r]=i,n+=1);}return e}function Fc(t){return typeof t=="string"&&t.length>0&&t.length<=32}function Qy(t){if(t!==void 0)return zy.includes(t)?t:"unknown"}var Pn=class{constructor(e){this.options=e;this.reporter=new $t({client:e.client,gameId:e.gameId,transport:"p2p"});}options;reporter;async joinCredential(e,n,r){let i=await this.options.client.post(`${this.match(e)}/join-credential`,{fingerprint:n},r);return {credential:di(i.credential)??"",hostFingerprint:di(i.host_fingerprint)??"",hostEpoch:ci(i.host_epoch)??0,expiresAt:(ci(i.expires_at)??0)*1e3}}async turnLease(e,n,r){let i=await this.options.client.post(`${this.match(e)}/turn-lease`,{cluster_target_id:n},r),o=[];for(let l of Array.isArray(i.ice_servers)?i.ice_servers:[]){let d=l,u=(Array.isArray(d.urls)?d.urls:[]).filter(c=>typeof c=="string"&&c.length>0);u.length!==0&&o.push({urls:u,username:di(d.username)??"",credential:di(d.credential)??""});}let s=ci(i.expires_at),a=ci(i.ttl_seconds);return {iceServers:o,expiresAt:s!==void 0?s*1e3:Date.now()+(a??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)}`}},Zy=new Set(["cluster_hidden","invalid_cluster_target"]);async function $c(t,e,n,r){let i=Ee(n);if(i.length===0)throw new Error("no cluster to lease TURN from");let o;for(let s of i)try{return {...await t.turnLease(e,s,r),clusterTargetId:s}}catch(a){if(!eh(a))throw a;o=a;}throw o}function eh(t){return t instanceof O&&Zy.has(t.code??"")}function di(t){return typeof t=="string"&&t.length>0?t:void 0}function ci(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}var th=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),N=class extends Error{constructor(n,r,i){super(`${n}: ${r}`,i);this.reason=n;this.name="P2pError",this.retryable=th.has(n);}reason;retryable};var qc=10240,Nc=2048,nh=new TextEncoder;function jc(t){return nh.encode(t).length}function je(t,e){let n=i=>{throw new A("invalid_sdp",`the ${e} ${i}`)},r=jc(t);r>=qc&&n(`is ${r} bytes, over the ${qc} 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 i of t.split(/\r\n|\n/)){let o=jc(i);o>Nc&&n(`has a ${o}-byte line, over the ${Nc} limit`);}}function ui(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 mi=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,((...i)=>{r(),n(...i);}));return r}emit(e,...n){let r=this.listeners.get(e);if(r)for(let i of [...r])i(...n);}clear(){this.listeners.clear();}};var rh=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function Nt(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=pi(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function pi(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 rh.test(r)?r:null}function qt(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 ca=5e3,ih=12e4+ca,oh=1024,ah=6e4,sh=1e4,Bc=64*1024;function ua(t){let e=new Map,n=-1/0,r=null,i=(()=>{let a;try{a=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 a.username!==""||a.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:a.href,shown:`${a.protocol}//${a.host}`}})(),o=()=>{let a=t.subtle??globalThis.crypto?.subtle;if(!a)throw new N("keys_unavailable","this environment has no WebCrypto, so a join credential cannot be verified. A page served over plain http on a non-loopback origin is the usual cause \u2014 crypto.subtle is only exposed in a secure context.");return a},s=async()=>{if(!i.ok)throw new N("keys_unavailable",i.reason);let a=t.fetch??((g,p)=>globalThis.fetch(g,p)),l;try{l=await a(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(sh)});}catch{throw new N("keys_unavailable",`the JWKS endpoint at ${i.shown} could not be reached \u2014 it timed out, refused a redirect, or the network failed.`)}if(!l.ok)throw new N("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let d;try{let g=await l.text();if(g.length>Bc)throw new N("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${Bc} characters, which is not a key set this platform publishes.`);d=JSON.parse(g);}catch(g){throw g instanceof N?g:new N("keys_unavailable",`the JWKS endpoint at ${i.shown} did not answer with a readable key set.`)}let u=Array.isArray(d.keys)?d.keys:[],c=o();for(let g of u){let p=g;if(p.kty==="RSA"&&!(p.alg!==void 0&&p.alg!=="RS256")&&!(p.use!==void 0&&p.use!=="sig")&&!(typeof p.kid!="string"||p.kid.length===0))try{let f=await c.importKey("jwk",{...g,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(p.kid,f);}catch{}}};return {async key(a){let l=e.get(a);if(l)return l;if(!i.ok)throw new N("keys_unavailable",i.reason);if(r)return await r,e.get(a)??null;let d=t.now();if(!Number.isFinite(d))throw new N("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<ah?null:(n=d,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var En=class{seen=new Map;admit(e,n){for(let[r,i]of this.seen)i<=n&&this.seen.delete(r);if(this.seen.has(e))return false;if(this.seen.size>=oh){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+ih),true}};function Wc(t){let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=atob(e+"=".repeat((4-e.length%4)%4)),r=new Uint8Array(n.length);for(let i=0;i<n.length;i++)r[i]=n.charCodeAt(i);return r}function Uc(t){try{let e=new TextDecoder().decode(Wc(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function ma(t,e,n,r,i){let o=U=>{throw new N("peer_unauthenticated",`the peer's join credential is not usable: ${U}`)},s=t.split(".");s.length!==3&&o("it is not a three-part JWT");let[a,l,d]=s,u=Uc(a);u===null&&o("its header does not decode"),u.alg!=="RS256"&&o(`its alg is ${JSON.stringify(u.alg)}, not RS256`),u.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(u.typ)}, not p2p+jwt`);let c=u.kid;(typeof c!="string"||c.length===0)&&o("it names no key");let g=await n.key(c);g===null&&o("it was signed by a key this build cannot resolve");let p=i.subtle??globalThis.crypto?.subtle;p||o("this environment has no WebCrypto");let f=new TextEncoder().encode(`${a}.${l}`),h;try{h=Wc(d);}catch{o("its signature does not decode");}await p.verify({name:"RSASSA-PKCS1-v1_5"},g,h,f)||o("its signature does not verify");let v=Uc(l);v===null&&o("its payload does not decode");let k=v,y=U=>typeof k[U]=="string"?k[U]:"",_=U=>typeof k[U]=="number"&&Number.isFinite(k[U])?k[U]:NaN;y("iss")!==i.issuer&&o("it was issued by someone else"),y("aud")!==`${i.issuer}/p2p-match`&&o("its audience is not this platform"),y("match_id")!==e.matchId&&o("it is for another match"),y("game_id")!==e.gameId&&o("it is for another game");let I=_("exp")*1e3,T=_("nbf")*1e3;(!Number.isFinite(I)||e.now>I+ca)&&o("it has expired"),Number.isFinite(T)&&e.now<T-ca&&o("it is not valid yet");let H=y("role");H!=="host"&&H!=="client"&&o("it names no usable role");let q=_("host_epoch");q!==e.hostEpoch&&o("it names a different host epoch");let W=pi(y("fingerprint"));W===null&&o("its fingerprint claim is malformed"),qt(W,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let C=pi(y("host_fingerprint"));C===null&&o("its host fingerprint claim is malformed"),qt(C,e.hostFingerprint)||o("it was issued against a different host certificate");let L=y("jti");L.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit(L,e.now)||o("it has already been used");let $=y("sub");return $.length===0&&o("it names no player"),{playerId:$.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:q,role:H,fingerprint:W,hostFingerprint:C,jti:L,expiresAt:I}}function pa(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 ga(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 fa(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function ya(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 Hc(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 Vc(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var Tn=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 ha={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}},Be=["reliable","ordered","unreliable"];function ba(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 In(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var Jc=1,mh=3e4,zc=2e3,ph=5e3,Xc=6e4,gh=8,fh=12e4,yh=5e3,hh=8e3,eu=18e5,bh=eu+6e4,_a=class{constructor(e=gh){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;}},vh=new _a,_h=8,wh=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),Gn=class{constructor(e){this.options=e;this.keys=e.keys??ua({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new mi;links=new Map;replays=new En;keys;localPlayerId="";migration=null;lease=null;clusterTargetIds=[];leaseRenewal=null;leaseAskedAt=null;leaseRenewalWarned=false;credential=null;nextPeerId=Jc+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;drainTimers=new Set;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??mh;this.credentialDeadline=this.options.clock.now()+n;let r=new Promise((s,a)=>{this.ready={resolve:s,reject:a};});if(this.clusterTargetIds=Ee([this.options.clusterTargetId,...this.options.clusterTargetIds??[]]),this.clusterTargetIds.length>0)try{await this.takeLease(e),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: ${On(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 N("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),o=()=>this.fail(new N("aborted","the caller aborted while connecting"));e?.aborted?o():e?.addEventListener("abort",o);try{await r;}finally{this.options.clock.clearTimeout(i),e?.removeEventListener("abort",o),this.ready=null;}}async kick(e){if(!this.isHost)throw new N("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.drainTimers)this.options.clock.clearTimeout(e);this.drainTimers.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);case "relayDraining":return this.onRelayDraining(n);default:return}}async onHello(e){let n=le(e.playerId),r=le(e.hostPlayerId),i=Cn(e.hostEpoch);if(!(n===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new Tn(n,r,i)),!this.helloSeen)){if(this.helloSeen=true,this.isHost){this.mark("host listening"),this.settle(),await this.drainPendingOffers();return}this.pendingOffers.clear(),await this.offerToHost("initial");}}async drainPendingOffers(){if(this.pendingOffers.size===0)return;let e=[...this.pendingOffers.values()];this.pendingOffers.clear(),this.mark("queued offer drained");for(let n of e)try{await this.onOffer(n);}catch(r){this.report_(r);}}async offerToHost(e){let n=this.hostPlayerId,r=this.openLink(n,Jc),i=await r.connection.createOffer();await r.connection.setLocalDescription(i);let o=r.connection.localDescription?.sdp??i.sdp;if(!o)throw new N("invalid_sdp","the browser produced an offer with no SDP");je(o,"offer"),this.refuseMedia(o,"offer"),this.options.signaling.offer(o,e),this.mark("offer sent"),this.fetchCredential().catch(s=>this.report_(s));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,i=r===void 0?null:Nt(r);if(i===null)throw new N("invalid_sdp","this browser produced an offer with no usable DTLS fingerprint, so the platform cannot bind a credential to it");let o=this.options.credentialPacing??vh,s=()=>this.closed||e!==this.credentialGeneration,a=ph;for(;;){let l=o.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,s))return;o.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,i);if(s())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(s())return;let u=d.status,c;if(u===409)c=zc;else if(u===429){let g=d.retryAfterSeconds;typeof g=="number"&&Number.isFinite(g)&&g>=0?c=g*1e3:(c=a,a=Math.min(a*2,Xc)),c=Math.min(Math.max(c,zc),Xc);}else throw d;if(!await this.waitForCredential(c,s))return}}}async waitForCredential(e,n){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!n())}async onOffer(e){let n=le(e.fromPlayerId),r=le(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=_h){let l=this.pendingOffers.keys().next().value;l!==void 0&&this.pendingOffers.delete(l);}this.pendingOffers.set(n,e);return}if(!this.isHost||this.migration.isKicked(n)===true)return;let i=le(e.sessionId);if(i!==null&&this.answeredSessions.get(n)===i)return;je(r,"offer"),this.refuseMedia(r,"offer");let o=Nt(r);if(o===null)throw new N("invalid_sdp",`the offer from ${n} carries no usable fingerprint`);if(this.mark("offer received"),i!==null&&this.answeredSessions.set(n,i),await this.refreshLease(false),this.closed||!this.isHost)return;let s=this.links.get(n);if(le(e.intent)==="ice_restart"&&s?.admitted===true&&s.remoteFingerprint!==null&&qt(s.remoteFingerprint,o)){await this.answer(s,r),this.mark("ice restart answered");return}s&&this.dropLink(s,"resignalled",false);let a=this.openLink(n,this.nextPeerId++);a.remoteFingerprint=o,await this.answer(a,r),this.mark("answer sent");}async answer(e,n){await e.connection.setRemoteDescription({type:"offer",sdp:n}),this.flushCandidates(e);let r=await e.connection.createAnswer();await e.connection.setLocalDescription(r);let i=e.connection.localDescription?.sdp??r.sdp;if(!i)throw new N("invalid_sdp","the browser produced an answer with no SDP");je(i,"answer"),this.refuseMedia(i,"answer"),this.options.signaling.answer(e.playerId,i,e.assignedPeerId);}async onAnswer(e){if(this.isHost)return;let n=le(e.fromPlayerId),r=le(e.sdp);if(n===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||n!==this.hostPlayerId)return;je(r,"answer"),this.refuseMedia(r,"answer");let o=Nt(r);if(o===null)throw new N("invalid_sdp","the host's answer carries no usable fingerprint");let s=Cn(e.assignedPeerId);if(i.restart!==void 0&&s!==null&&s!==i.assignedPeerId){this.warn(`the host answered the ICE restart from a new connection (peer id ${s}, this link is ${i.assignedPeerId}); dropping the link to re-dial`),this.dropLink(i,"restart_mismatch",true);return}this.mark("answer received"),i.remoteFingerprint=o,i.pendingAnswer=r,this.hostVerified(i)&&await this.applyAnswer(i,r);}hostVerified(e){let n=this.credential;return n===null||e.remoteFingerprint===null?false:qt(n.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new N("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),e.restart!==void 0&&(e.restart.answered=true,this.progressRestart(e));}async onIce(e){let n=le(e.fromPlayerId),r=le(e.candidate);if(n===null||r===null)return;let i=this.links.get(n);if(!i)return;let o=le(e.sdpMid),s=Cn(e.sdpMLineIndex)??Cn(e.sdpMLineIndexAlt),a={candidate:r,...o===null?{}:{sdpMid:o},...s===null?{}:{sdpMLineIndex:s}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(a);return}await i.connection.addIceCandidate(a).catch(()=>{});}onPeerLeft(e){let n=le(e.playerId);if(n===null)return;let r=le(e.reason)??"left";if(n===this.localPlayerId){this.fail(new N("kicked",`this player was removed from the match (${r})`)),this.close();return}let i=this.links.get(n);i&&this.dropLink(i,r,true);}async onMigration(e){let n=le(e.hostPlayerId),r=Cn(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:n,hostEpoch:r,...le(e.reason)===null?{}:{reason:le(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(s=>typeof s=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(i.kind==="duplicate")return;if(i.kind==="completed"){this.emitter.emit("hostChanged",n,r);return}if(i.kind==="refused"){this.report_(new N("migration_failed",i.why));return}for(let s of [...this.links.values()])this.dropLink(s,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",n,r),i.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration();let o=this.hostEpoch;await this.refreshLease(false),!(this.closed||this.hostEpoch!==o)&&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 N("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=le(e.reason)??"ended";this.ended=n,this.emitter.emit("matchEnded",n),this.ready!==null&&this.fail(new N("match_ended",`the match ended: ${n}`)),this.close();}onSignalingError(e){let n=le(e.code)??"unknown",r=le(e.message)??"the platform refused a signaling message",i=this.isHost?void 0:this.links.get(this.hostPlayerId)?.restart;if(i!==void 0){this.warn(`the platform refused an ICE restart (${n}: ${r})`),i.settle(false);return}this.report_(new N("signaling_failed",`${n}: ${r}`));}async onRelayDraining(e){if(this.migration===null)return;let n=new Set((Array.isArray(e.relayIps)?e.relayIps:[]).filter(c=>typeof c=="string").map(c=>c.toLowerCase())),r=this.isHost?void 0:this.links.get(this.hostPlayerId),i,o=this.options.clock.now(),s=Date.parse(le(e.deadline)??""),a=(Number.isFinite(s)?s:o+eu)-o,l=this.options.clock.setTimeout(()=>{this.drainTimers.delete(l),this.onDrainDeadline(n,r,i).catch(c=>this.report_(c));},Math.max(0,Math.min(a,bh)));if(this.drainTimers.add(l),await this.refreshLease(true),this.closed||(this.withoutDrainingRelays(n),this.isHost))return;let d=this.links.get(this.hostPlayerId);if(d===void 0||!d.admitted)return this.reportRestart("skipped","announced");let u=await Yc(d.connection,n);if(!(this.closed||this.links.get(d.playerId)!==d)){if(u===false)return this.reportRestart("skipped","announced");await this.restartIceToHost(d,"announced")&&(i=d);}}async onDrainDeadline(e,n,r){if(this.closed||this.isHost)return;let i=this.links.get(this.hostPlayerId);if(i===void 0)return;let o=await Yc(i.connection,e);if(this.closed||this.links.get(i.playerId)!==i)return;(o===true||o===null&&i===n&&i!==r)&&this.dropLink(i,"relay_deadline",true);}withoutDrainingRelays(e){let n=this.lease;if(n===null||e.size===0)return;let r=false,i=[];for(let o of n.iceServers){let s=o.urls.filter(a=>{let l=Sh(a),d=l===null||!e.has(l);return r||=!d,d});s.length>0&&i.push({...o,urls:s});}r&&(this.lease={iceServers:i,expiresAt:n.expiresAt},this.reconfigureLinks());}restartIceToHost(e,n){if(e.restart!==void 0)return e.restart.done;if(e.connection.restartIce===void 0)return this.reportRestart("skipped",n),Promise.resolve(false);let r=()=>{},i=new Promise(a=>{r=a;}),o=this.options.clock.setTimeout(()=>s.settle(false),hh),s={done:i,answered:false,settle:a=>{e.restart===s&&(e.restart=void 0,this.options.clock.clearTimeout(o),this.closed||this.reportRestart(a?"success":"failed",n),r(a));}};return e.restart=s,this.offerIceRestart(e).catch(a=>{this.warn(`could not restart ICE on the connection to the host: ${On(a)}`),s.settle(false);}),i}async offerIceRestart(e){let n=e.connection;n.restartIce?.();let r=await n.createOffer();await n.setLocalDescription(r);let i=n.localDescription?.sdp??r.sdp;if(!i)throw new N("invalid_sdp","the browser produced an offer with no SDP");je(i,"offer"),this.refuseMedia(i,"offer"),!(e.restart===void 0||this.links.get(e.playerId)!==e)&&(this.options.signaling.offer(i,"ice_restart"),this.mark("ice restart offered"));}progressRestart(e){let n=e.restart;if(n===void 0)return;let r=e.connection.iceConnectionState;r==="failed"||r==="closed"?n.settle(false):n.answered&&va(r)&&n.settle(true);}reportRestart(e,n){this.report([{type:"ice_restart_outcome_total",value:1,labels:{outcome:e,reason:n}}]);}async takeLease(e){this.leaseAskedAt=this.options.clock.now();let n=this.clusterTargetIds,r=await $c(this.options.api,this.options.matchId,n,e);this.lease={iceServers:r.iceServers,expiresAt:r.expiresAt},this.clusterTargetIds=n.slice(Math.max(0,n.indexOf(r.clusterTargetId)));}refreshLease(e){if(this.clusterTargetIds.length===0||this.closed)return Promise.resolve();if(this.leaseRenewal!==null)return this.leaseRenewal;let n=this.options.clock.now();if(this.leaseAskedAt!==null&&n-this.leaseAskedAt<yh)return Promise.resolve();let r=this.lease;if(!e&&r!==null&&r.expiresAt-n>=fh)return Promise.resolve();let i=this.takeLease().then(()=>{this.closed||(this.mark("turn re-leased"),this.reconfigureLinks());},o=>{this.leaseRenewalWarned||(this.leaseRenewalWarned=true,this.warn(`could not renew the TURN lease for this match, so connections keep the relays they were given: ${On(o)}`));}).finally(()=>{this.leaseRenewal=null;});return this.leaseRenewal=i,i}reconfigureLinks(){for(let e of this.links.values()){let n=e.connection;if(n.setConfiguration!==void 0)try{n.setConfiguration({...n.getConfiguration?.(),iceServers:this.iceServers()});}catch{}}}iceServers(){return (this.lease?.iceServers??[]).map(e=>({urls:[...e.urls],username:e.username,credential:e.credential}))}openLink(e,n){let i=(this.options.peerConnectionFactory??ba)({iceServers:this.iceServers(),...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let g of Be){let p=i.createDataChannel(g,ha[g]);p.binaryType="arraybuffer",o[g]=p;}let s={playerId:e,assignedPeerId:n,connection:i,channels:o,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},a=g=>{let p=g.candidate;p?.candidate&&this.options.signaling.candidate(e,p.candidate,p.sdpMid??void 0,p.sdpMLineIndex??void 0);},l=()=>this.onIceState(s),d=()=>this.onConnectionState(s),u=g=>{this.onHandshakeMessage(s,g.data).catch(p=>this.report_(p));},c=()=>{this.onReliableOpen(s).catch(g=>this.report_(g));};return i.addEventListener("icecandidate",a),i.addEventListener("iceconnectionstatechange",l),i.addEventListener("connectionstatechange",d),o.reliable.addEventListener("open",c),o.reliable.addEventListener("message",u),s.detachHandshake=()=>{o.reliable.removeEventListener("open",c),o.reliable.removeEventListener("message",u);},s.detachAll=()=>{s.detachHandshake(),i.removeEventListener("icecandidate",a),i.removeEventListener("iceconnectionstatechange",l),i.removeEventListener("connectionstatechange",d);},this.links.set(e,s),s}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 N("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 N("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(pa({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=ya(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 N(Vc(r.reason),Hc(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 i=Nt(e.connection.localDescription?.sdp??"");if(i===null||e.remoteFingerprint===null){this.refuseLink(e,1,"fingerprint_unavailable","this connection's DTLS fingerprints could not be read from its SDP, so no credential can be checked against it");return}let o;try{o=await ma(n,{matchId:this.options.matchId,gameId:this.options.gameId,hostEpoch:this.hostEpoch,peerFingerprint:e.remoteFingerprint,hostFingerprint:i,now:this.options.clock.now()},this.keys,this.replays,{issuer:this.options.baseUrl.replace(/\/+$/,"")});}catch(s){let a=s instanceof N&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",On(s)),a&&this.fail(s);return}if(o.playerId!==e.playerId.toLowerCase()){this.refuseLink(e,129,"credential_player_mismatch",`its credential was issued to ${o.playerId}, not to the player who signalled this connection`);return}if(this.migration?.isKicked(o.playerId)===true){this.refuseLink(e,130,"kicked",`it was kicked from this match at host epoch ${this.hostEpoch}`);return}e.channels.reliable.send(ga({protocolVersion:32769,assignedPeerId:e.assignedPeerId})),this.finishAdmission(e);}refuseLink(e,n,r,i){this.warn(`refused to admit ${e.playerId}: ${i}`);try{e.channels.reliable.send(fa(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){this.progressRestart(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(n==="disconnected"){if(e.recovering===true)return;if(e.admitted&&e.connection.restartIce!==void 0&&this.reportedUnreachableEpoch!==this.hostEpoch){this.recoverHostLink(e).catch(r=>this.report_(r));return}}this.voteHostUnreachable(n);}}async recoverHostLink(e){let n=this.hostEpoch,r=()=>!this.closed&&this.hostEpoch===n&&this.links.get(e.playerId)===e;e.recovering=true;try{if(await this.refreshLease(!0),!r())return;if(va(e.connection.iceConnectionState))return this.reportRestart("skipped","disconnected");if(await this.restartIceToHost(e,"disconnected")||!r()||va(e.connection.iceConnectionState))return;this.voteHostUnreachable(Qc(e.connection.iceConnectionState));}finally{e.recovering=false;}}voteHostUnreachable(e){if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,e);}catch(n){this.report_(n);}}}onConnectionState(e){let n=e.connection.connectionState;n!=="failed"&&n!=="closed"||(e.recovering===true&&this.voteHostUnreachable(Qc(e.connection.iceConnectionState)),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.restart?.settle(false),e.detachAll();for(let i of Be)Zc(e.channels[i]);Zc(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 N?e:new N("connection_failed",On(e),{cause:e}));}count(e){this.counted||!wh.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(ui(e))throw new N("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 le(t){return typeof t=="string"&&t.length>0?t:null}function Cn(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function On(t){return t instanceof Error?t.message:String(t)}async function Yc(t,e){if(t.getStats===void 0)return null;let n=new Map;try{(await t.getStats()).forEach((a,l)=>{typeof a=="object"&&a!==null&&n.set(l,a);});}catch{return null}let r=[...n.values()],i=r.find(a=>a.type==="transport")?.selectedCandidatePairId,o=(typeof i=="string"?n.get(i):void 0)??r.find(a=>a.type==="candidate-pair"&&a.selected===true)??r.find(a=>a.type==="candidate-pair"&&a.nominated===true&&a.state==="succeeded");if(o===void 0)return null;let s=[o.localCandidateId,o.remoteCandidateId].map(a=>typeof a=="string"?n.get(a):void 0);return s.every(a=>a===void 0)?null:s.some(a=>{let l=a?.address??a?.ip;return typeof l=="string"&&e.has(l.toLowerCase())})}function Sh(t){let e=/^(?:turns?|stuns?):(?:\[([^\]]+)\]|([^:?/]+))/i.exec(t),n=e?.[1]??e?.[2];return n===void 0?null:n.toLowerCase()}function va(t){return t==="connected"||t==="completed"}function Qc(t){return t==="failed"||t==="closed"?t:"disconnected"}function Zc(t){try{t.close();}catch{}}var Rh=100,kh=50,Ln=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,i){if(this.assertUsable(),this.queue.length>=(this.options.maxQueuedCandidates??Rh)){this.dropped+=1;return}this.queue.push({peerId:e,candidate:n,...r===void 0?{}:{sdpMid:r},...i===void 0?{}:{sdpMLineIndex:i}}),this.schedule();}migrationAck(e){this.assertUsable(),this.options.bridge.signal("migrationAck",this.options.matchId,{hostEpoch:e});}reportHostUnreachable(e,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 N("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new N("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:i,sdpMLineIndex:o}=e;this.options.bridge.signal("ice",this.options.matchId,{peerId:n,candidate:r,...i===void 0?{}:{sdpMid:i},...o===void 0?{}:{sdpMLineIndex:o}});}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??kh));}};function K(t){return e=>typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function Qe(t,e){return n=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e?n:void 0}function jt(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function tu(t){return typeof t=="boolean"?t:void 0}var _e=K(64),Dn=Qe(0,2147483647);function gi(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=_e(n);typeof r=="string"&&e.push(r);}return e}function J(t,e,n){return {to:t,from:e,read:n,required:true}}function z(t,e,n){return {to:t,from:e,read:n,required:false}}var Ph=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=jt("disconnected","failed","closed")(e.iceState),r=Qe(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:[J("sdp","sdp",K(10240)),J("signaling_intent","intent",jt("initial","ice_restart","full_reconnect")),z("sdp_hash","sdpHash",K(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[J("peer_id","peerId",_e),J("sdp","sdp",K(10240)),J("assigned_peer_id","assignedPeerId",Qe(0,4294967295)),z("sdp_hash","sdpHash",K(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[J("peer_id","peerId",_e),J("candidate","candidate",K(512)),z("sdp_mid","sdpMid",K(64)),z("sdp_mline_index","sdpMLineIndex",Qe(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[J("host_epoch","hostEpoch",Dn)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[J("host_epoch","hostEpoch",Dn),z("evidence","evidence",Ph)]}}));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",p2p_relay_draining:"relayDraining"}));var Eh=16,Th=t=>gi(t)?.slice(0,Eh);Object.freeze(Object.assign(Object.create(null),{hello:[J("playerId","player_id",_e),J("hostPlayerId","host_player_id",_e),J("hostEpoch","host_epoch",Dn),z("members","members",gi)],offer:[J("fromPlayerId","from_player_id",_e),J("sdp","sdp",K(10240)),z("sessionId","signaling_session_id",K(128)),z("sdpHash","sdp_hash",K(128)),z("iceUfrag","ice_ufrag",K(64)),z("intent","signaling_intent",jt("initial","ice_restart","full_reconnect"))],answer:[J("fromPlayerId","from_player_id",_e),J("sdp","sdp",K(10240)),z("sessionId","signaling_session_id",K(128)),z("sdpHash","sdp_hash",K(128)),z("iceUfrag","ice_ufrag",K(64)),z("assignedPeerId","assigned_peer_id",Qe(0,4294967295))],ice:[J("fromPlayerId","from_player_id",_e),J("candidate","candidate",K(512)),z("sdpMid","sdp_mid",K(64)),z("sdpMLineIndex","sdp_m_line_index",Qe(0,255)),z("sdpMLineIndexAlt","sdp_mline_index",Qe(0,255))],peerJoined:[J("playerId","player_id",_e)],peerLeft:[J("playerId","player_id",_e),z("reason","reason",K(64))],migration:[J("hostPlayerId","new_host_player_id",_e),J("hostEpoch","host_epoch",Dn),z("reason","reason",K(64)),z("kickedPlayerIds","kicked_player_ids",gi),z("migrationComplete","migration_complete",tu)],matchEnded:[z("reason","reason",K(64))],error:[z("code","code",K(64)),z("message","message",K(256))],relayDraining:[J("clusterTargetId","cluster_target_id",_e),J("relayIps","relay_ips",Th),J("drainingSince","draining_since",K(40)),J("deadline","deadline",K(40))]}));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 gt="webrtc_p2p";function ru(t){let e=new Pn({client:t.client,gameId:t.gameId}),n=new Map;return {handleSignalEvent(r,i,o){n.get(r)?.handleSignal(i,o);},session(r){return n.get(r)??null},async connect(r={}){if(t.bridge===null)throw new N("signaling_unavailable","P2P signaling rides the notification WebSocket, which only the page embedding this game can hold. There is no bridge here \u2014 this is `mock` mode, or a game running outside the Arcade frame. See docs/p2p-and-parties.md \xA72.");let i=Se(r.clusterTargetId),o=i===void 0?await Ih(t):[i];t.rooms.isHost&&t.rooms.currentMatch===null&&t.rooms.currentRoom?.matchId===void 0&&await t.rooms.startMatch({...i===void 0?{}:{clusterTargetId:i},...r.signal===void 0?{}:{signal:r.signal}});let s=await t.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(s.protocol!==gt)throw new N("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${gt}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let a=new Ln({bridge:t.bridge,matchId:s.matchId,clock:t.clock}),l=new Gn({api:e,clock:t.clock,matchId:s.matchId,gameId:t.gameId(),baseUrl:typeof t.baseUrl=="function"?t.baseUrl():t.baseUrl,signaling:a,...o.length===0?{}:{clusterTargetIds:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await In(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...t.boot===void 0?{}:{boot:t.boot},...t.log===void 0?{}:{log:t.log}});a.onDropped(d=>l.notifyCandidatesDropped(d)),n.set(s.matchId,l),l.on("matchEnded",()=>n.delete(s.matchId));try{await l.start(r.signal);}catch(d){throw n.delete(s.matchId),l.close(),d}return l}}}async function Ih(t){if(t.resolveClusterTargets!==void 0)return Ee(await t.resolveClusterTargets());let e=Se(await t.resolveClusterTarget?.());return e===void 0?[]:[e]}function iu(t){let{analytics:e,rooms:n}=t,r=t.target??globalThis,i=t.document??globalThis.document,o=[];if(typeof r.addEventListener=="function"){let a=d=>{d?.persisted!==true&&e.endSession("pagehide");};r.addEventListener("pagehide",a),o.push(()=>r.removeEventListener?.("pagehide",a));let l=()=>e.setHidden(!mt());for(let d of si)r.addEventListener(d,l),o.push(()=>r.removeEventListener?.(d,l));typeof i?.addEventListener=="function"&&(i.addEventListener("resume",l),o.push(()=>i.removeEventListener?.("resume",l))),e.setHidden(!mt());}let s=new Map;return o.push(n.on("matchReady",a=>{let l=a.protocol===gt?"p2p":"dedicated";s.set(a.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),o.push(n.on("matchEnded",a=>{let l=s.get(a.matchId);l!==void 0&&(s.delete(a.matchId),e.trackPlatform("gem_match_ended",{transport:l}));})),()=>{for(let a of o.splice(0))try{a();}catch{}s.clear();}}var Ch=[[/swiftshader|llvmpipe|softpipe|software|basic render driver/i,"software"],[/powervr d-series/i,"powervr_d_series"],[/powervr|imagination/i,"powervr_other"],[/adreno/i,"adreno"],[/mali|immortalis/i,"mali"],[/xclipse/i,"xclipse"],[/apple/i,"apple"],[/nvidia|geforce|quadro|tegra/i,"nvidia"],[/\bamd\b|radeon|\bati\b/i,"amd"],[/intel/i,"intel"]];function Fn(t){if(t===null||t==="")return "unknown";for(let[e,n]of Ch)if(e.test(t))return n;return "other"}function wa(t){return t===null||t===""?"unknown":/^ANGLE \(/.test(t)?/vulkan/i.test(t)?"angle_vulkan":/opengl es/i.test(t)?"angle_gles":/direct3d11|d3d11/i.test(t)?"angle_d3d11":/direct3d9|d3d9/i.test(t)?"angle_d3d9":/metal/i.test(t)?"angle_metal":/opengl/i.test(t)?"angle_opengl":"angle_other":"native_gl"}function Sa(t){return /Android/.test(t)&&/; wv\)/.test(t)?"android_webview":"other"}function Ra(t){try{let e=t.getParameter(t.RENDERER);if(typeof e=="string"&&e!==""&&!/^WebKit WebGL$/i.test(e))return e;let n=t.getExtension("WEBGL_debug_renderer_info");if(n){let r=t.getParameter(n.UNMASKED_RENDERER_WEBGL);if(typeof r=="string"&&r!=="")return r}return typeof e=="string"&&e!==""?e:null}catch{return null}}function Oh(t){try{let{vendor:e,architecture:n,description:r}=t??{},i=[e,n,r].filter(o=>typeof o=="string"&&o!=="").join(" ").replace(/img-tec/gi,"PowerVR").replace(/qualcomm/gi,"Adreno").replace(/\barm\b/gi,"Mali").replace(/samsung/gi,"Xclipse");return Fn(i)}catch{return "unknown"}}var Mh=new Set(["webgl","webgl2","experimental-webgl"]),ou=false;function au(t){let e=t.win??globalThis.window,n=e?.HTMLCanvasElement?.prototype;if(ou||!e||!n)return;ou=true;let r=t.now??(()=>performance.now()),i=Sa(e.navigator?.userAgent??""),o=new WeakMap,s=null,a=0,l=(g,p,f)=>{try{if(a+=1,a>5)return;t.analytics.trackPlatform("gem_graphics_context_lost",{gpu:g,host:i,route:p,...f===void 0?{}:{context_ms:Math.max(0,Math.round(r()-f))},hidden:e.document?.visibilityState==="hidden"?1:0,nth_loss:a});}catch{}},d=g=>{let p=o.get(g),f=p?.renderer??s;l(Fn(f),wa(f),p?.createdAt);},u=n.getContext;n.getContext=function(g,...p){let f=u.call(this,g,...p);try{if(f&&typeof g=="string"&&Mh.has(g)&&!o.has(this)){let h=Ra(f);h!==null&&(s=h),o.set(this,{createdAt:r(),renderer:h}),this.addEventListener?.("webglcontextlost",()=>d(this));}}catch{}return f};let c=e.GPUAdapter?.prototype;if(c&&typeof c.requestDevice=="function"){let g=c.requestDevice;c.requestDevice=function(...p){let f=g.apply(this,p);try{let h=r(),R=Oh(this.info),v=R==="unknown"?Fn(s):R;Promise.resolve(f).then(k=>k?.lost).then(k=>{k&&k.reason!=="destroyed"&&l(v,"webgpu",h);},()=>{});}catch{}return f};}e.addEventListener?.("webglcontextlost",g=>{let p=g.target;p&&!o.has(p)&&d(p);},true);}var su=["pointerdown","keydown"];function lu(t,e=globalThis){let n=false,r=false,i=null,o=()=>{if(i!==null){try{e.cancelAnimationFrame?.(i);}catch{}i=null;}},s=()=>{if(!r){r=true,o();for(let p of su)e.removeEventListener?.(p,l,{capture:true});e.removeEventListener?.("gamepadconnected",g,{capture:true});}},a=()=>{if(!(n||r)){n=true,s();try{t();}catch{}}};function l(p){p?.isTrusted===true&&a();}let d=()=>{let p;try{p=e.navigator?.getGamepads?.()??[];}catch{return false}return p.some(f=>f?.buttons.some(h=>h.pressed)===true)},u=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(p=>p!==null)}catch{return false}},c=()=>{if(i=null,!(n||r)){if(d()){a();return}u()&&(i=e.requestAnimationFrame?.(c)??null);}};function g(){i===null&&!n&&!r&&c();}if(typeof e.addEventListener=="function"){for(let p of su)e.addEventListener(p,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",g,{capture:true,passive:true}),u()&&(i=e.requestAnimationFrame?.(c)??null);}return {get engaged(){return n},stop:s}}async function fi(t,e,n,r){let i=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),i}function ka(t,e){let n=false;return async r=>{let i=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),i}}function Aa(t={}){let e=t.now??(typeof performance>"u"?()=>Date.now():()=>performance.now()),n=[],r=new Set;return {marks:n,mark(i,o){return r.has(i)?false:(r.add(i),n.push({name:i,at:o??e()}),true)},timeline(){let i=[...n].sort((o,s)=>o.at-s.at);return i.map((o,s)=>{let a=i[s-1],l=a===void 0?"":` (+${Math.round(o.at-a.at)}ms)`;return `${o.name}@${Math.round(o.at)}ms${l}`}).join(" \u2192 ")}}}var Gh="GemWebSdkHandshake";var Lh=()=>Date.now();function du(t,e,n={}){let r=t[Gh];if(r===void 0)return null;let i=n.ttlMs??9500,o=n.now??Lh,s=r.events.splice(0),a=r.times?.splice(0),l=0,d=0,u=false,c=o()-i;for(let g=s.length-1;g>=0;g--){let p=a?.[g];if(p!==void 0&&p<c){d+=1;continue}if(l+=1,e(s[g])===true){u=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:u}}var Dh=["angle_gles","native_gl","angle_opengl","angle_other","angle_d3d11","angle_d3d9","angle_metal"],Fh=Object.freeze(Dh.map(t=>Object.freeze({gpu:"powervr_d_series",route:t}))),uu="gemGraphics",cu=1e3,$h=5e3,qh=32,Nh=32,jh=300;function mu(t){if(typeof t!="string"||t==="")return null;try{let n=new URLSearchParams(t).get(uu)?.trim().toLowerCase();return n==="webgpu"||n==="webgl"||n==="safe"?n:null}catch{return null}}function Bh(t){if(!Array.isArray(t)||t.length>qh)return null;let e=[];for(let n of t){if(n===null||typeof n!="object"||Array.isArray(n))return null;let{gpu:r,route:i,host:o}=n;if(!xa(r)||i!==void 0&&!xa(i)||o!==void 0&&!xa(o))return null;e.push(Object.freeze({gpu:r,...i===void 0?{}:{route:i},...o===void 0?{}:{host:o}}));}return Object.freeze(e)}function xa(t){return typeof t=="string"&&t!==""&&t.length<=Nh}function Uh(t,e){return e.some(n=>n.gpu===t.gpu&&(n.route===void 0||n.route===t.route)&&(n.host===void 0||n.host===t.host))}function Wh(t){let e=t?.navigator?.gpu;return e&&typeof e.requestAdapter=="function"?e:null}function Hh(t){try{let e=t?.OffscreenCanvas;if(typeof e!="function")return null;let n=new e(1,1).getContext("webgl");if(!n)return null;let r=Ra(n);try{n.getExtension("WEBGL_lose_context")?.loseContext();}catch{}return r===null?null:{gpu:Fn(r),route:wa(r),host:Sa(t?.navigator?.userAgent??"")}}catch{return null}}function Pa(t,e){return Object.freeze({route:t,listed:e})}var yi=Pa("webgl",false);function pu(t){let{bridge:e,clock:n,forced:r}=t,i=()=>t.win??globalThis.window,o=t.log??null,s=null,a=false,l=new Set,d,u=null,c=false,g=(v,k,y)=>new Promise(_=>{let I=n.setTimeout(()=>_(y),Math.max(0,k));v.then(T=>{n.clearTimeout(I),_(T);},()=>{n.clearTimeout(I),_(y);});}),p=(v,k)=>(u??=Promise.resolve().then(()=>v.requestAdapter()).then(y=>y!=null,()=>false),g(u,k,false)),f=async v=>{if(a||v<=0)return;let k=n.now(),y=await e.settled(v);if(a||y!=="connected"||!e.parentSupports("graphicsRoutes"))return;let _=v-(n.now()-k);_<=0||await new Promise(I=>{let T=()=>{l.delete(T),n.clearTimeout(H),I();},H=n.setTimeout(T,_);l.add(T);});},h=async(v,k)=>Pa(v!==null&&await p(v,k)?"webgpu":"webgl",true),R=async v=>{let k=n.now()+v,y=()=>Math.max(0,k-n.now()),_=Wh(i());if(r!==null&&!c&&(c=true,o?.(`[gem] graphics route forced to ${r} by the ${uu} launch key`+(r==="webgpu"&&_===null?", but this browser has no WebGPU: webgl, listed":""))),r==="webgl")return yi;if(r==="safe")return Pa("webgl",true);if(r==="webgpu")return h(_,y());await f(y()-(_===null?0:Math.min(jh,v/2)));let I=s??Fh;return I.length===0||(d===void 0&&(d=Hh(i())),d===null||!Uh(d,I))?yi:h(_,y())};return {api:{preferredRoute(v){let k=Number(v?.timeoutMs??cu),y=Number.isFinite(k)?Math.min(Math.max(0,k),$h):cu;return R(y).catch(()=>yi)}},accept(v){let k=Bh(v);a=true,k!==null&&(s=k);for(let y of [...l])y();}}}var Ea=new WeakMap,gu=new WeakSet,Ta=new Set,hi=new Set,bi=[],Ut=null,Ia=false,Vh=1920;function Ca(t){return Ea.get(t)}function Oa(t){return !Ia||gu.has(t)}function Ma(t){return t.kind==="webgpu"?true:t.kind!=="webgl"&&t.kind!=="webgl2"&&t.kind!=="experimental-webgl"?false:t.context.getContextAttributes()?.preserveDrawingBuffer!==true}function fu(t=globalThis.window){if(Ia||!t?.HTMLCanvasElement||typeof t.requestAnimationFrame!="function")return;Ia=true;for(let o of Array.from(t.document?.querySelectorAll("canvas")??[]))gu.add(o);let e=t.HTMLCanvasElement.prototype,n=e.getContext;e.getContext=function(o,...s){let a=n.call(this,o,...s);if(a&&!Ea.has(this)){let l={kind:o,context:a};Ea.set(this,l),Ma(l)&&Ta.add(this);}return a};let r=t.requestAnimationFrame,i=t.cancelAnimationFrame;t.requestAnimationFrame=o=>{let s=r.call(t,a=>{hi.delete(s);try{o(a);}finally{Kh();}});return hi.add(s),bu(),s},t.cancelAnimationFrame=o=>{hi.delete(o),i.call(t,o);};}function yu(t,e){return new Promise(n=>{let r={canvas:t,done:o=>{clearTimeout(i),bi=bi.filter(s=>s!==r),n(o);}},i=setTimeout(()=>r.done(null),e);bi.push(r);})}function hu(t){return Ut?.canvas===t?Ut.bitmap:null}function Kh(){for(let t of bi){let e;try{e=Ga(t.canvas);}catch(n){t.done(Promise.reject(n));continue}e&&t.done(createImageBitmap(t.canvas));}hi.size===0&&Jh();}function Jh(){let t=null;for(let r of Ta)r.isConnected?(!t||r.width*r.height>t.width*t.height)&&(t=r):Ta.delete(r);if(!t||t.width===0||t.height===0)return;let e=Math.min(1,Vh/Math.max(t.width,t.height)),n=e<1?{resizeWidth:Math.max(1,Math.floor(t.width*e)),resizeHeight:Math.max(1,Math.floor(t.height*e)),resizeQuality:"medium"}:{};bu(),Ut={canvas:t,bitmap:createImageBitmap(t,n).catch(()=>null)};}function bu(){Ut&&(Ut.bitmap.then(t=>t?.close()),Ut=null);}function Ga(t){let e=zh();if(!e)return true;e.clearRect(0,0,8,8),e.drawImage(t,0,0,8,8);let n=e.getImageData(0,0,8,8).data;for(let r=0;r<n.length;r+=4){if(n[r]|n[r+1]|n[r+2])return true;let i=n[r+3];if(i!==0&&i!==255)return true}return false}var $n;function zh(){if($n!==void 0)return $n;if(typeof OffscreenCanvas=="function")$n=new OffscreenCanvas(8,8).getContext("2d",{willReadFrequently:true});else {let t=globalThis.document?.createElement("canvas");t&&(t.width=t.height=8),$n=t?.getContext("2d",{willReadFrequently:true})??null;}return $n??null}var La=false;async function Su(t,e,n,r){if(La){e.close(),n("busy",true);return}La=true;let i=null;try{let o=await Qh(t,r);if(typeof o=="string"){e.close(),n(o,Xh(o));return}i=o;let a=await(r.encodeRef??(l=>rb(l,r)))(i);if(i.close(),i=null,a===null){e.close(),n("failed",!0);return}if(a.size>nb){e.close(),n("too_large",!1);return}e.postMessage(a);}catch(o){e.close(),n("failed",true),console.error("[gem] screenshot capture failed",o);}finally{La=false,i?.close();}}function Xh(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}}var Yh=600;async function Qh(t,e){if(e.handler){let i=await e.handler(t);return i===null?"declined":vu(i,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=tb(n);if(!r)return "no_source";try{let i=await Zh(r);return typeof i=="string"?i:vu(i,t)}catch(i){if(i instanceof DOMException&&i.name==="SecurityError")return "tainted";throw i}}async function Zh(t){let e=eb(t);if(typeof e=="string")return e;if(e.kind.includes("webgl")&&!e.context.getContextAttributes())return "unsupported";if(!Ma(e))return createImageBitmap(t);let n=await yu(t,Yh);if(n)return n;let r=await hu(t);return r&&Ga(r)?createImageBitmap(r):e.kind==="webgpu"?"unreadable":"unsupported"}function eb(t){let e=Ca(t);if(e)return e;if(!Oa(t))return "no_source";try{for(let n of ["webgl2","webgl","2d","webgpu"]){let r=t.getContext(n);if(r)return {kind:n,context:r}}}catch{return "unreadable"}return "unreadable"}function tb(t){let e=null,n=0;for(let r of Array.from(t.querySelectorAll("canvas"))){let i=r.width*r.height;i<=0||r.clientWidth<=0||r.clientHeight<=0||!Ca(r)&&!Oa(r)||i>n&&(e=r,n=i);}return e}async function vu(t,e){let{maxWidth:n,maxHeight:r}=e;if(t.width<=n&&t.height<=r)return t;let i=Math.min(n/t.width,r/t.height),o=Math.max(1,Math.floor(t.width*i)),s=Math.max(1,Math.floor(t.height*i));try{let a=await createImageBitmap(t,{resizeWidth:o,resizeHeight:s,resizeQuality:"high"});return t.close(),a}catch{return t.close(),"too_large"}}var nb=8*1024*1024,_u="image/webp",wu=.92;async function rb(t,e){try{if(typeof OffscreenCanvas=="function"){let o=new OffscreenCanvas(t.width,t.height),s=o.getContext("2d");if(s){s.drawImage(t,0,0);let a=await o.convertToBlob({type:_u,quality:wu});if(a&&a.size>0)return a}}}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 i=r.getContext("2d");return !i||(i.drawImage(t,0,0),typeof r.toBlob!="function")?null:await new Promise(o=>{r.toBlob(s=>o(s),_u,wu);})}async function Ru(t,e){if(!e)return;let n;try{n=await ib(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 ib(t){return new Promise((e,n)=>{let r=false,i=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(o=>{r||(r=true,clearTimeout(i),e(o??null));},o=>{r||(r=true,clearTimeout(i),n(o instanceof Error?o:new Error(String(o))));});})}var ku=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function xu(t=globalThis){let n=t[ku];if(n!==void 0)return n;let r=false,i=()=>r,o=sb(t),s=[],a=ob(t,i,o.watch);a!==null&&s.push(a);let l=ab(t,i,o.watch);l!==null&&s.push(l);let d={get muted(){return r},setMuted(u){let c=!!u;if(c!==r){r=c;for(let g of s)g();}},setPaused(u){o.setPaused(!!u);}};return Object.defineProperty(t,ku,{value:d,configurable:true}),d}function ob(t,e,n){let r=t.AudioNode?.prototype,i=t.AudioDestinationNode;if(r===void 0||i===void 0)return null;let o=t.OfflineAudioContext,s=r.connect,a=r.disconnect,l=new Map,d=c=>{let g=c.gain,p=c.context.currentTime;g.cancelScheduledValues(p),e()?g.setValueAtTime(0,p):g.setTargetAtTime(1,p,.01);},u=c=>{let g=c.context;if(o!==void 0&&g instanceof o)return null;let p=l.get(g);return p===void 0&&(p=g.createGain(),p.gain.value=e()?0:1,s.call(p,c),l.set(g,p),n.context(g)),p};return r.connect=function(...g){let[p,...f]=g;if(p instanceof i){let h;try{h=u(p);}catch{h=null;}if(h!==null)return s.call(this,h,...f),p}return s.apply(this,g)},r.disconnect=function(...g){let[p,...f]=g;if(p instanceof i){let h=l.get(p.context);if(h!==void 0&&h!==this)try{return a.call(this,h,...f)}catch{}}return a.apply(this,g)},()=>{for(let[c,g]of l){if(c.state==="closed"){l.delete(c);continue}try{d(g);}catch{}}}}function ab(t,e,n){let r=t.HTMLMediaElement;if(r===void 0)return null;let i=r.prototype,o=Object.getOwnPropertyDescriptor(i,"muted"),s=o?.get,a=o?.set;if(s===void 0||a===void 0)return null;let l=i.play,d=new WeakMap,u=new WeakSet,c=new Set,g=p=>{d.has(p)||d.set(p,!!s.call(p)),u.has(p)||(u.add(p),c.add(new WeakRef(p)),n.element(p)),a.call(p,(d.get(p)??false)||e());};return Object.defineProperty(i,"muted",{configurable:true,enumerable:o?.enumerable??true,get(){let p=d.get(this);return p===void 0?!!s.call(this):p},set(p){d.set(this,!!p),g(this);}}),i.play=function(){try{g(this);}catch{}return l.call(this)},t.document?.addEventListener("play",p=>{let f=p.target;if(f instanceof r)try{g(f);}catch{}},true),()=>{for(let p of c){let f=p.deref();if(f===void 0){c.delete(p);continue}try{a.call(f,(d.get(f)??!1)||e());}catch{}}}}var Au=["pointerup","touchend","click","keydown"];function sb(t){let e=t.document,n=new Set,r=new WeakSet,i=new WeakSet,o=new Set,s=new WeakSet,a=new Set,l=new Set,d=false,u=false,c=t.AudioContext?.prototype,g=c?.suspend,p=c?.resume,f=c!==void 0&&typeof g=="function"&&typeof p=="function";f&&(c.suspend=function(...G){try{i.add(this);}catch{}return g.apply(this,G)},c.resume=function(...G){try{i.delete(this);}catch{}return p.apply(this,G)});let h=t.HTMLMediaElement?.prototype,R=h?.pause;h!==void 0&&typeof R=="function"&&(h.pause=function(){l.delete(this),R.call(this);});let v=x=>x.state!=="running"&&x.state!=="closed"&&r.has(x)&&!i.has(x),k=x=>x.state==="running"&&o.has(x)&&!i.has(x),y=x=>x.paused&&!x.ended,_=()=>{for(let x of n)if(x.state==="closed")n.delete(x),o.delete(x);else if(v(x)||k(x))return true;for(let x of l){if(y(x))return true;l.delete(x);}return false},I=()=>{for(let x of a){let G=x.deref();if(G===void 0){a.delete(x);continue}try{!G.paused&&!G.ended&&l.add(G);}catch{}}},T=()=>{if(u){u=false,l.clear();for(let x of Au)e?.removeEventListener?.(x,q,true);}},H=()=>{try{u&&!_()&&T();}catch{}};function q(){if(!u||d)return;let x=[];try{for(let G of n){if(G.state==="closed"){n.delete(G),o.delete(G);continue}if(v(G)){o.delete(G);try{x.push(Promise.resolve(p?.call(G)));}catch{}}else if(k(G)){o.delete(G);try{x.push(Promise.resolve(g?.call(G))),s.add(G),x.push(Promise.resolve(p?.call(G)));}catch{}}}for(let G of l){if(!y(G)){l.delete(G);continue}try{x.push(Promise.resolve(G.play()).then(()=>l.delete(G),re=>{re?.name!=="NotAllowedError"&&l.delete(G);}));}catch{l.delete(G);}}}catch{}if(x.length===0){H();return}Promise.allSettled(x).then(H);}let W=()=>{if(!(u||e===void 0)){u=true;for(let x of Au)e.addEventListener(x,q,true);}},C=()=>{I(),e?.visibilityState!=="hidden"&&W();},L=()=>{for(let x of n)x.state!=="closed"&&r.has(x)&&o.add(x);W();},$=()=>{o.clear(),I();};try{e?.addEventListener("visibilitychange",()=>{try{e.visibilityState==="hidden"?$():L();}catch{}},!0),t.addEventListener?.("pagehide",()=>{try{$();}catch{}}),t.addEventListener?.("pageshow",x=>{try{x.persisted&&L();}catch{}});}catch{}return {watch:{context(x){if(f)try{n.add(x),(x.state==="running"||x.currentTime>0)&&r.add(x),x.addEventListener("statechange",()=>{try{let G=x.state;G==="running"?(r.add(x),s.delete(x),o.has(x)&&W(),H()):G!=="closed"&&r.has(x)&&!i.has(x)&&!s.has(x)&&C();}catch{}});}catch{}},element(x){try{a.add(new WeakRef(x));}catch{}}},setPaused(x){d=x;}}}var lb=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",db=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',cb=`${lb}${db}`,Da=new WeakSet;function Pu(t=globalThis.document){if(t==null||Da.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(cb),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],Da.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"),Da.add(t),"inline")}catch{return null}}function Eu(t){let e=t.windowMs??1e3,n=t.realm??globalThis,r=t.now??(()=>globalThis.performance?.now()??Date.now()),i=false,o=false,s=false,a=null,l=null,d=null,u=[],c=false,g=0,p=null,f=[],h=()=>i&&!o&&!s,R=()=>{l=null,d=null,u=[],g=0,p=null,f=[];},v=_=>{if(a=null,!h()){R();return}if(d!==null&&u.push(_-d),d=_,l===null)l=_;else {let I=_-l;if(I>=e&&u.length>0){if(c){let T=p===null?I:r()-p;t.report(mb(g,f,I,T));}else t.report(ub(u,I));l=_,u=[],g=0,f=[];}}k();},k=()=>{let _=n.requestAnimationFrame;typeof _=="function"&&(a=_.call(n,v));},y=()=>{if(h()){a===null&&(R(),k());return}a!==null&&(n.cancelAnimationFrame?.call(n,a),a=null),R();};return {setRequested(_){i=_,y();},setPaused(_){o=_,y();},draw(){if(!c){c=true,a!==null&&R();return}if(a===null||l===null)return;let _=r();p!==null&&f.length<1e3&&f.push(_-p),p=_,g+=1;},get running(){return a!==null},dispose(){s=true,y();}}}function ub(t,e){return {fps:t.length*1e3/e,frameTimeP95Ms:Tu(t),counts:"pageFrames"}}function mb(t,e,n,r){let i=r;return e.length>0&&(i=Tu(r>Math.max(...e)?[...e,r]:e)),{fps:t*1e3/n,frameTimeP95Ms:i,counts:"gameDraws"}}function Tu(t){let e=[...t].sort((r,i)=>r-i),n=Math.max(1,Math.ceil(e.length*.95));return e[n-1]}var vi=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function Iu(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function Cu(t,e){t!==null&&(t.style.setProperty(vi.top,`${e.top}px`),t.style.setProperty(vi.right,`${e.right}px`),t.style.setProperty(vi.bottom,`${e.bottom}px`),t.style.setProperty(vi.left,`${e.left}px`));}var _i=Object.freeze({tl:{width:"--gem-reserved-tl-width",height:"--gem-reserved-tl-height",centerY:"--gem-reserved-tl-center-y",controlHeight:"--gem-reserved-tl-control-height"},tr:{width:"--gem-reserved-tr-width",height:"--gem-reserved-tr-height",centerY:"--gem-reserved-tr-center-y",controlHeight:"--gem-reserved-tr-control-height"},bl:{width:"--gem-reserved-bl-width",height:"--gem-reserved-bl-height",centerY:"--gem-reserved-bl-center-y",controlHeight:"--gem-reserved-bl-control-height"},br:{width:"--gem-reserved-br-width",height:"--gem-reserved-br-height",centerY:"--gem-reserved-br-center-y",controlHeight:"--gem-reserved-br-control-height"}});function Ou(){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 pb(t,e){let n={tl:{width:0,height:0,control:null},tr:{width:0,height:0,control:null},bl:{width:0,height:0,control:null},br:{width:0,height:0,control:null}};for(let r of t){let i=e?r.x+r.width/2<=e.width/2:r.x===0,o=e?r.y+r.height/2<=e.height/2:r.y===0,s=i?r.x+r.width:e?e.width-r.x:r.width,a=o?r.y+r.height:e?e.height-r.y:r.height,l=n[`${o?"t":"b"}${i?"l":"r"}`];l.width=Math.max(l.width,Math.ceil(s)),l.height=Math.max(l.height,Math.ceil(a));let d=r.control;if(d){let u=l.control;l.control=u?{top:Math.min(u.top,d.y),bottom:Math.max(u.bottom,d.y+d.height)}:{top:d.y,bottom:d.y+d.height};}}return n}function Mu(t,e,n){if(t===null)return;let r=pb(e,n);for(let i of ["tl","tr","bl","br"]){t.style.setProperty(_i[i].width,`${r[i].width}px`),t.style.setProperty(_i[i].height,`${r[i].height}px`);let o=r[i].control;t.style.setProperty(_i[i].centerY,o?`${(o.top+o.bottom)/2}px`:""),t.style.setProperty(_i[i].controlHeight,o?`${o.bottom-o.top}px`:"");}}var gb=3e4,wi=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function Gu(t){let e=t.clock??ce,n=t.timeoutMs??gb,r=new Map,i=new Map,o=0,s=a=>{let l=r.get(a);return l?(r.delete(a),i.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return t.bridge.parentSupports("localHost")},ensure(a){if(!t.bridge.parentSupports("localHost"))return Promise.resolve();let l=i.get(a);if(l)return l;let d=new Promise((u,c)=>{let g=`ls${++o}`,p=e.setTimeout(()=>{r.delete(g),i.delete(a),c(new wi("timeout",true,`the embedder did not answer a local-server request for room ${a} within ${String(n)}ms`));},n);r.set(g,{room:a,resolve:u,reject:c,timer:p}),t.bridge.requestLocalServer(g,a)||(s(g),u());});return i.set(a,d),d.catch(()=>{}),d},accept(a){s(a.requestId)?.resolve();},refuse(a){let l=s(a.requestId);l&&l.reject(new wi(a.reason,a.retryable,a.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 qn={url:"https://downloads.indiegems.games/sdk/v23.2.0/gem-web-sdk.devtools.min.js",integrity:"sha384-Dh+0LTxFu29MKUWYKl5MteRBW1ESH1loukkF4h0Lv0hia8hJOHzUfTC1U0N5y/st"};var Wt=null;function fb(){return Wt!==null||(Wt=new Promise((t,e)=>{let n=document.createElement("script");n.src=qn.url,n.integrity=qn.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){Wt=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${qn.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{Wt=null,e(new Error(`gem devtools: could not load ${qn.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);})),Wt}function Lu(t,e){let n=null,r=0;async function i(o){if(n!==null)return true;let s=++r;if(!e())return false;let a=await fb();return !e()||s!==r?false:(n!==null||(n=a.mount(t(),{openedBy:o,text:st,onDismiss:()=>{n?.unmount(),n=null;}})),true)}return {get isOpen(){return n!==null},close(){r+=1,n?.unmount(),n=null;},open:()=>i("game"),openFrom:i}}var yb=1e4,Du={reason:"unavailable",retryable:false};function Fu(t){let e=new Map,n=null,r=null,i=0,o=(d,u)=>{u.timer=t.clock.setTimeout(()=>{e.delete(d),u.reject({reason:"timeout",retryable:true});},t.timeoutMs??yb);},s=(d,u)=>{let c=a(d);c&&u(c);},a=d=>{let u=e.get(d);return u?(e.delete(d),t.clock.clearTimeout(u.timer),u):null},l=new At({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((u,c)=>{let g=t.bridge.currentState;if(g==="refused"||g==="closed"){c(Du);return}let p=`t${++i}`,f={resolve:u,reject:c,reason:d,timer:null,held:g!=="connected"};e.set(p,f),o(p,f),f.held||t.bridge.requestToken(p,d);})});return {source:l,onToken(d){let u={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)){s(d.requestId,c=>c.resolve(u));return}l.accept(u);},onDenied(d){s(d.requestId,u=>u.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[u,c]of e)c.held&&(c.held=false,t.clock.clearTimeout(c.timer),o(u,c),t.bridge.requestToken(u,c.reason));else if(d==="refused"||d==="closed")for(let u of [...e.keys()])s(u,c=>c.reject(Du));},get identity(){return n},get gameVersion(){return r}}}var hb=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),$a="embedder_relay_unavailable",bb="embedder_no_relay",vb=new Set([$a]),qa=new Set([bb]),Nn=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new Fa(this)}handleEvent(e){let n=this.pending.get(e.matchId);if(n!==void 0){if(e.event==="matchEnded"){n.refuse(new A("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 A("signaling_failed","the parent relayed an answer with no SDP in it"));return}n.settle({sdp:e.sdp});return}n.refuse(_b(e.code,e.message));}}register(e,n){this.pending.get(e)?.refuse(new A("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 A("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 A("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 _b(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new A(wb(t),r,{platformCode:t})}function wb(t){return t===void 0||vb.has(t)?"signaling_failed":qa.has(t)?"offer_refused":hb.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var Fa=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,n){if(this.closed)return Promise.reject(new A("signaling_unavailable","this signaling channel is closed"));let r;try{r=this.hub.transport();}catch(i){return Promise.reject(i)}return n?.aborted?Promise.reject(new A("aborted","the caller aborted before the offer was sent")):new Promise((i,o)=>{let s=()=>{a(),o(new A("aborted","the caller aborted the signaling exchange"));},a=()=>{n?.removeEventListener("abort",s),this.hub.release(e.matchId,l),this.teardown===a&&(this.teardown=null);},l={settle:d=>{a(),i(d);},refuse:d=>{a(),o(d);}};this.teardown=a,n?.addEventListener("abort",s),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof A?d:new A("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var $u="match_ended:",qu="server_shutdown:",Nu="kicked:",Sb=123;function Rb(t){if(typeof t!="string"||t.length===0||t.length>Sb)return {kind:"other"};if(t.startsWith($u)){let e=Ye(t.slice($u.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(qu)?{kind:"server_shutdown",cause:t.slice(qu.length)}:t.startsWith(Nu)?{kind:"kicked",detail:t.slice(Nu.length)}:{kind:"other"}}function Na(t,e,n){let r=Rb(n),i=r.kind==="kicked"?"kicked":"link_closed";t.notifyMatchDisconnected(i).catch(()=>{}),r.kind==="match_ended"&&t.reconcile({matchId:e,reason:r.reason}).catch(()=>{});}function ja(){return {exchange(){return Promise.reject(new A("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 kb=3e3,Ab=1e4,xb=15e3;async function Si(t){let e=t.peerConnection;try{Bu(t,"before the handshake started"),Ba(t);let n=e.createDataChannel(t.channelLabel??"gem",{ordered:!0});for(let s of t.extraChannels??[]){let a=e.createDataChannel(s.label,{...s.ordered===void 0?{}:{ordered:s.ordered},...s.maxRetransmits===void 0?{}:{maxRetransmits:s.maxRetransmits}});t.onExtraChannel?.(s.label,a);}let r=await e.createOffer();await e.setLocalDescription(r),await Tb(e,t),Ba(t);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new A("invalid_sdp","the offer carried no SDP");je(i,"offer"),ju(i,"offer");let o=await Eb(t,i);if(Ba(t),typeof o?.sdp!="string")throw new A("invalid_sdp","the signaling channel answered without an SDP");return je(o.sdp,"answer"),ju(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await Ib(n,t),Bu(t,"before the channel opened"),n}catch(n){throw e.close(),Pb(n)}}function Pb(t){return t instanceof A?t:Hu(t)?ft():new A("connection_failed",Vu(t),{cause:t})}function ju(t,e){if(ui(t))throw new A("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 Eb(t,e){let n=t.exchangeTimeoutMs??Ab,r=Wu(t,n),i=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(o=>{throw o instanceof A?o:Hu(o)?ft():new A("signaling_failed",Vu(o),{cause:o})});return Cb(i,t,r,()=>r.exhausted?Ua("while the offer was in flight"):new A("timeout",`no answer arrived within ${n}ms`))}function Tb(t,e){if(t.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:n}=e;return new Promise(r=>{let i=()=>{n.clearTimeout(s),t.removeEventListener("icegatheringstatechange",o),e.signal?.removeEventListener("abort",i),r();},o=()=>{t.iceGatheringState==="complete"&&i();},s=n.setTimeout(i,e.gatherTimeoutMs??kb);t.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function Ib(t,e){if(e.signal?.aborted)return Promise.reject(ft());if(t.readyState==="open")return Promise.resolve();if(t.readyState!=="connecting")return Promise.reject(new A("connection_failed",`the data channel was already '${t.readyState}' when the answer was applied`));let{clock:n}=e,r=e.openTimeoutMs??xb,i=Wu(e,r);return new Promise((o,s)=>{let a=()=>{n.clearTimeout(g),t.removeEventListener("open",l),t.removeEventListener("close",d),t.removeEventListener("error",d),e.signal?.removeEventListener("abort",u);},l=()=>{a(),o();},d=p=>{a(),s(new A("connection_failed","the data channel failed before it opened",Uu(p)===void 0?void 0:{cause:Uu(p)}));},u=()=>{a(),s(ft());},c=()=>{a(),s(i.exhausted?Ua("while the channel was still opening"):new A("timeout",`the data channel did not open within ${r}ms`));},g=n.setTimeout(c,i.ms);t.addEventListener("open",l),t.addEventListener("close",d),t.addEventListener("error",d),e.signal?.addEventListener("abort",u);})}function Wu(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 Cb(t,e,n,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(ft()):new Promise((s,a)=>{let l=c=>{i.clearTimeout(u),o?.removeEventListener("abort",d),c();},d=()=>l(()=>a(ft())),u=i.setTimeout(()=>l(()=>a(r())),n.ms);o?.addEventListener("abort",d),t.then(c=>l(()=>s(c)),c=>l(()=>a(c)));})}function Bu(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw Ua(`already ${e}`)}function Ua(t){return new A("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function Ba(t){if(t.signal?.aborted)throw ft()}function ft(){return new A("aborted","the caller aborted the connection attempt")}function Hu(t){return t?.name==="AbortError"}function Uu(t){return t?.error}function Vu(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:[J("sdp","sdp",K(10240)),z("sessionId","session_id",K(64))],error:[z("code","code",K(64)),z("message","message",K(256))],matchEnded:[z("reason","reason",K(64))]}));function em(t){let{client:e,clock:n,rooms:r}=t,i=t.signaling??ja,o=t.log??(y=>console.warn(y)),s=new $t({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,l=(y,_)=>{let I=a.get(y)??new Set;I.add(_),a.set(y,I);},d=(y,_)=>{let I=a.get(y);I!==void 0&&(I.delete(_),I.size===0&&a.delete(y));},u=async y=>{if(r.isHost&&!Ha(r)&&r.currentRoom?.matchId===void 0){let _=Se(y.clusterTargetId);await r.startMatch({..._===void 0?{}:{clusterTargetId:_},...y.retry===void 0?{}:{retry:y.retry},...y.signal===void 0?{}:{signal:y.signal}});}return Qu(r.matchConnectionState==="suspended"?await r.reconnectToMatch(Wa(y)):await r.awaitMatch(Wa(y)))},c=async y=>Qu(await r.pollMatchStatus(Wa(y))),g=async(y,_)=>{let I=false;try{let T=await u(y),H=r.currentRoom?.transports;if(H!==void 0&&!H.includes("webrtc"))throw new A("misconfigured",`the room template offers (${H.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 q=y.peerConnection??Zu();I=!0;let W=await Si({peerConnection:q,signaling:_,clock:n,matchId:T.matchId,credentialExpiresAt:T.credentialExpiresAt,...Ri(y,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),C=null;if(y.presentCredential!==!1)try{C=await _n({channel:W,clock:n,credential:T.joinCredential,credentialExpiresAt:T.credentialExpiresAt,...Ri(y,"onMessage","signal"),...y.welcomeTimeoutMs===void 0?{}:{ceilingMs:y.welcomeTimeoutMs}});}catch(L){throw Te(W),Te(q),L}return Nb(r,T,W,q,_,y.reportDisconnect!==!1,y.reportConnected!==!1,C,{remember:l,forget:d},y.onMatchEnded)}catch(T){throw I&&Yu(s,T),Te(_),T}},p=async(y,_,I,T,H,q)=>{if(y==="webtransport"){let x=T?.webtransport;if(x===void 0)throw new A("misconfigured","webtransport is not advertised");let G={credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,clock:n};if(typeof x.named_url=="string"&&x.named_url!==""){let re=Math.max(Math.floor(q/2),1e3);try{return await kn({url:x.named_url,timeoutMs:re,log:o,...G})}catch(pe){if(ri()!==null)throw pe;return o(`[gem] webtransport named dial failed (${ti(pe)}); retrying the pinned dial`),kn({url:x.url,certHashBase64:x.cert_sha256_b64,timeoutMs:re,log:o,...G})}}return kn({url:x.url,certHashBase64:x.cert_sha256_b64,timeoutMs:q,...G})}if(y==="websocket"){let x=T?.websocket;if(x===void 0)throw new A("misconfigured","websocket is not advertised");return ea({url:x.url,credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,clock:n,timeoutMs:q})}let W=_.peerConnection??Zu(),C,L=await Si({peerConnection:W,signaling:H,clock:n,matchId:I.matchId,credentialExpiresAt:I.credentialExpiresAt,extraChannels:[{label:Sn,ordered:false,maxRetransmits:0}],onExtraChannel:(x,G)=>{x===Sn&&(C=G);},...Ri(_,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),..._.exchangeTimeoutMs===void 0&&_.redial===true?{exchangeTimeoutMs:Gb}:{}}),$;try{$=await _n({channel:L,clock:n,credential:I.joinCredential,credentialExpiresAt:I.credentialExpiresAt,wire:ei,heartbeat:!0,...Ri(_,"signal"),..._.welcomeTimeoutMs===void 0?{}:{ceilingMs:_.welcomeTimeoutMs}});}catch(x){throw Te(L),Te(W),x}let U=$.welcome.heartbeatIntervalMs;return {link:na(L,W,C,U===void 0?void 0:{clock:n,intervalMs:U}),welcome:$.welcome,channel:L,peerConnection:W}},f=(y,_,I,T,H)=>{let q=false,W;T.link.onClose(U=>{!q&&y.reportDisconnect!==false&&Na(r,_.matchId,U),W?.(U);}),y.reportDisconnect!==false&&y.reportConnected!==false&&r.notifyMatchConnected(_.matchId);let C={transport:T.link.transport,send:(U,x)=>T.link.send(U,x),onMessage:U=>T.link.onMessage(U),onClose:U=>{W=U;},close:()=>T.link.close()},L=()=>{q||(q=true,Te(T.link),Te(H));},$=U=>{if(!q){try{y.onMatchEnded?.(U);}catch{}L();}};return l(_.matchId,$),{matchId:_.matchId,transport:I,link:C,joinCredential:_.joinCredential,credentialExpiresAt:_.credentialExpiresAt,welcome:T.welcome,...T.channel===void 0?{}:{channel:T.channel},...T.peerConnection===void 0?{}:{peerConnection:T.peerConnection},close(){d(_.matchId,$),L();}}},h=async(y,_)=>{let I=r.currentRoom?.id,T=r.gameId,H=()=>({advert:Rn(r.currentRoom?.settings,y),template:r.currentRoom?.transports??null});if(I===void 0||T===null)return H();try{let q=await e.get(`/v2/games/${encodeURIComponent(T)}/game-rooms/${encodeURIComponent(I)}`,_);return {advert:Rn(q.settings,y),template:Dt(q.transports)??r.currentRoom?.transports??null}}catch{return H()}},R=(y,_)=>{let I=y??Ku;return _.length===0?I:I.filter(T=>_.includes(T))},v=async(y,_,I)=>{try{let T=await u(y),{advert:H,template:q}=await h(T.matchId,y.signal),W=R(q,_),C=W.filter(Q=>Fb(Q,H)),L=ri();if(L!==null&&W.includes("webtransport")&&H?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${L} (learned on an earlier dial in this page)`),C.length===0){let Q=q===null?`the default order (${Ku.join(", ")})`:`the room template's transports (${q.join(", ")||"none"})`;throw new A("misconfigured",`none of ${Q}`+(_.length>0?`, narrowed to (${_.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let $=y.transportAttemptTimeoutMs??Mb,U=()=>y.deadlineAt===void 0?1/0:y.deadlineAt-n.now(),x=Q=>t.signalingReady===void 0||Q<=0?Promise.resolve(!0):t.signalingReady(Q),G=[],re=[];for(let Q of C){if(U()<zu){o(`[gem] ${Q} rung not tried: the reconnect budget is spent`);break}re.length>0&&T.credentialExpiresAt-n.now()<Xu&&(T=await c(y)),re.push(Q);let tt=!1,we=!1,Ae={attempts:0,waitedMs:0};for(;;){if(Q==="webrtc"&&y.redial===!0){let te=Math.min(Ju,U());await x(te)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(te)}ms; offering anyway`);}let xe=Math.max(Math.min($,U()),zu);try{return f(y,T,Q,await p(Q,y,T,H,I,xe),I)}catch(te){let X=te instanceof A?te:new A("connection_failed",te instanceof Error?te.message:String(te),{cause:te});if(Q==="webrtc"&&Yu(s,X),(X.reason==="credential_expired"||X.reason==="credential_reused")&&!tt){tt=!0,T=await c(y);continue}if(Q==="webrtc"&&X.reason==="signaling_failed"&&X.platformCode===$a&&!we){we=!0;let ne=Math.min(Ju,U());if(o(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(ne)}ms for the socket before offering again`),await x(ne))continue}if(X.reason==="join_rate_limited"){let ne=Db(Ae,Math.random,U());if(ne!==null){if(Ae.attempts+=1,Ae.waitedMs+=ne,o(`[gem] ${Q} rung: the server is rate-limiting this player's joins; waiting ${Math.round(ne)}ms before presenting again (retry ${Ae.attempts} of ${nm.maxAttempts})`),await Xr(n,ne,y.signal),y.signal?.aborted)throw new A("aborted","the caller aborted while waiting out a join rate limit");T.credentialExpiresAt-n.now()<Xu&&(T=await c(y));continue}}if(Lb.has(X.reason)||X.reason==="credential_expired"||Q==="webrtc"&&tm(X)){o(`[gem] ${Q} rung failed (${X.reason}): ${ti(X.cause??X)} \u2014 `+(re.length<C.length?`falling through to ${C[re.length]}`:"no rungs left")),G.push(X);break}throw o(`[gem] ${Q} rung refused the session (${X.reason}): ${X.message}`),X}}}let pe=G[G.length-1];throw pe===void 0?new A("timeout",`the reconnect budget ran out before any transport (${C.join(", ")}) could be tried`):new A(pe.reason,`every transport tried (${re.join(", ")}) failed; the last said: ${pe.message}`,{cause:G,platformCode:pe.platformCode})}catch(T){throw Te(I),T}};return {listClusterTargets:async(y={})=>qo({client:e,...y}),handleMatchEnded(y,_){let I=a.get(y);if(I!==void 0){a.delete(y);for(let T of I)T(_);}},connect:(async(y={})=>{let _=y.signaling??i();return y.transports===void 0?g(y,_):v(y,y.transports,_)})}}var Ku=["webtransport","webrtc","websocket"],Mb=1e4,Gb=5e3,Ju=3e3,zu=1e3,Xu=1e4,Lb=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function tm(t){return t.platformCode!==void 0&&qa.has(t.platformCode)}var nm={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function Db(t,e=Math.random,n=1/0){let r=nm;if(t.attempts>=r.maxAttempts)return null;let i=Math.min(r.budgetMs-t.waitedMs,n);if(i<r.initialDelayMs)return null;let o=r.initialDelayMs*r.factor**t.attempts;return Math.min(o+e()*r.jitterMs,i)}function Fb(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&ni():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||$b(e.websocket.url)}function $b(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return Je(e)}function Wa(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var qb=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Yu(t,e){e instanceof A&&(!qb.has(e.reason)&&!tm(e)||t.report([{type:"connection_failures_total",value:1}]));}function Nb(t,e,n,r,i,o,s,a,l,d){let u=false,c=()=>{u||Na(t,e.matchId,void 0);};o&&(n.addEventListener("close",c),s&&t.notifyMatchConnected(e.matchId));let g=()=>{u||(u=true,n.removeEventListener("close",c),a?.detach(),Te(n),Te(r),Te(i));},p=f=>{if(!u){try{d?.(f);}catch{}g();}};return l.remember(e.matchId,p),{matchId:e.matchId,channel:n,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:a?.welcome??null,close(){l.forget(e.matchId,p),g();}}}function Ha(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function Qu(t){if(t.status==="failed")throw new A("allocation_failed",`match ${t.matchId} did not come up: ${t.reason}`);if(t.status==="ended")throw new A("match_ended",`match ${t.matchId} ended (${t.reason}) before this side connected.`);if(t.protocol!==zr)throw new A("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${zr}' 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 A("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 Zu(){let t=globalThis.RTCPeerConnection;if(!t)throw new A("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 Te(t){try{t.close();}catch{}}function Ri(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var jb=1e4;function rm(t,e){return Va(t,e)}function Va(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=s=>({token:s.token,expiresAt:s.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,i=new At({clock:e.clock,...e.onStateChange===void 0?{}:{onStateChange:e.onStateChange},request:()=>new Promise((s,a)=>{let l=e.clock.setTimeout(()=>{r=null,a({reason:"unavailable",retryable:true});},e.timeoutMs??jb);r={resolve:d=>{e.clock.clearTimeout(l),s(d);},reject:a,timer:l};})}),o=t.onServerToken(s=>{let a=n(s),l=r;if(l){r=null,l.resolve(a);return}i.accept(a);});return {source:i,dispose(){o(),i.dispose(),r&&(e.clock.clearTimeout(r.timer),r.reject({reason:"unavailable",retryable:false}),r=null);}}}var Ja={};Fp(Ja,{acceptTransfer:()=>Bb,addEntityProgression:()=>Ub,adminAction:()=>Wb,cancelInventoryTransfer:()=>Hb,claimEntityProgressionRewards:()=>Vb,closeGameRoom:()=>Kb,createEntityBatchOrder:()=>Jb,createEntityOrder:()=>zb,createSession:()=>Xb,deleteEntityGameSetting:()=>Yb,deleteEntitySave:()=>Qb,deleteSession:()=>Zb,deleteShowcaseValue:()=>ev,executeEntityRecipe:()=>tv,finalizeSaveUpload:()=>nv,getChannelAssignment:()=>rv,getDropRates:()=>iv,getEntityCurrency:()=>ov,getEntityGameSetting:()=>av,getEntityInventory:()=>sv,getEntityInventoryItem:()=>lv,getEntityLeaderboard:()=>dv,getEntityOrder:()=>cv,getEntityProgression:()=>uv,getEntityRecipeAvailability:()=>mv,getEntityRecipeUsage:()=>pv,getEntitySave:()=>gv,getEvent:()=>fv,getGameRoomV2:()=>yv,getLeaderboard:()=>hv,getPlayerGameProfile:()=>bv,getPurchaseCatalog:()=>vv,getResolvedTemplate:()=>_v,getRoomArgs:()=>wv,getShowcaseValue:()=>Sv,getTransferDetails:()=>Rv,ingestAnalyticsEvents:()=>Ka,initiateInventoryTransfer:()=>kv,invokeFunction:()=>Av,kickPlayer:()=>xv,listChallenges:()=>Pv,listEntityGameSettings:()=>Ev,listEntityOrders:()=>Tv,listEntityProgressions:()=>Iv,listEntitySaves:()=>Cv,listEvents:()=>Ov,listGameRooms:()=>Mv,listResolvedTemplates:()=>Gv,listTransfers:()=>Lv,maxEntityProgression:()=>Dv,putEntityGameSetting:()=>Fv,putRoomArgs:()=>$v,putShowcaseValue:()=>qv,rejectTransfer:()=>Nv,reportMatchPlayers:()=>jv,requestSaveUploadUrl:()=>Bv,resetEntityProgression:()=>Uv,setMatchBackfill:()=>Wv,simulateEntityOrder:()=>Hv,transferHostV2:()=>Vv,updateGameRoomV2:()=>Kv});function w(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 Bb(t,e,n){let r=`/v1/inventory/transfers/${w(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function Ub(t,e,n,r,i,o){let s=`/v1/inventory/${w(e)}/${w(n)}/progressions/${w(r)}/add`;return t.client.post(s,i,o?.signal)}async function Wb(t,e,n,r){let i=`/v1/voice/sessions/${w(e)}/admin`;return t.client.post(i,n,r?.signal)}async function Hb(t,e,n){let r=`/v1/inventory/transfers/${w(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Vb(t,e,n,r,i,o){let s=`/v1/inventory/${w(e)}/${w(n)}/progressions/${w(r)}/claim`;return t.client.post(s,i,o?.signal)}async function Kb(t,e,n){let r=`/v1/games/${w(t.gameId())}/game-rooms/${w(e)}`;return t.client.delete(r,n?.signal)}async function Jb(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/orders/batch`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function zb(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/orders`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Xb(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function Yb(t,e,n,r,i){let o=`/v1/settings/${w(e)}/${w(n)}/${w(r)}`;return t.client.delete(o,i?.signal)}async function Qb(t,e,n,r,i){let o=`/v1/saves/${w(e)}/${w(n)}/${w(r)}`;return t.client.delete(o,i?.signal)}async function Zb(t,e,n){let r=`/v1/voice/sessions/${w(e)}`;return t.client.delete(r,n?.signal)}async function ev(t,e,n,r){let i=`/v1/showcase/players/${w(e)}/${w(n)}`;return t.client.delete(i,r?.signal)}async function tv(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/recipes/execute`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function nv(t,e,n,r,i,o){let s=`/v1/saves/${w(e)}/${w(n)}/${w(r)}/finalize`;return t.client.post(s,i,o?.signal)}async function rv(t,e,n){let r=`/v1/games/${w(t.gameId())}/config/channels/${w(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function iv(t,e,n){let r=`/v1/inventory/loot-tables/${w(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function ov(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/currencies/${w(r)}`;return t.client.get(o,i?.signal)}async function av(t,e,n,r,i){let o=`/v1/settings/${w(e)}/${w(n)}/${w(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function sv(t,e,n,r){let i=new URLSearchParams;r?.include_buckets!==void 0&&i.set("include_buckets",String(r?.include_buckets)),r?.include_custom_data!==void 0&&i.set("include_custom_data",String(r?.include_custom_data)),r?.currency_limit!==void 0&&i.set("currency_limit",String(r?.currency_limit)),r?.currency_cursor!==void 0&&i.set("currency_cursor",String(r?.currency_cursor)),r?.item_limit!==void 0&&i.set("item_limit",String(r?.item_limit)),r?.item_cursor!==void 0&&i.set("item_cursor",String(r?.item_cursor)),r?.progression_limit!==void 0&&i.set("progression_limit",String(r?.progression_limit)),r?.progression_cursor!==void 0&&i.set("progression_cursor",String(r?.progression_cursor));let o=i.toString(),s=`/v1/inventory/${w(e)}/${w(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function lv(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/items/${w(r)}`;return t.client.get(o,i?.signal)}async function dv(t,e,n,r,i){let o=new URLSearchParams;i?.bucket_1!==void 0&&o.set("bucket_1",String(i?.bucket_1)),i?.bucket_2!==void 0&&o.set("bucket_2",String(i?.bucket_2)),i?.limit!==void 0&&o.set("limit",String(i?.limit)),i?.periods_back!==void 0&&o.set("periods_back",String(i?.periods_back)),i?.period!==void 0&&o.set("period",String(i?.period)),i?.player_id!==void 0&&o.set("player_id",String(i?.player_id));let s=o.toString(),a=`/v1/leaderboards/${w(e)}/${w(n)}/${w(r)}`+(s?`?${s}`:"");return t.client.get(a,i?.signal)}async function cv(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/orders/${w(r)}`;return t.client.get(o,i?.signal)}async function uv(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/progressions/${w(r)}`;return t.client.get(o,i?.signal)}async function mv(t,e,n,r,i,o){let s=`/v1/inventory/${w(e)}/${w(n)}/catalogs/${w(r)}/recipes/${w(i)}/availability`;return t.client.get(s,o?.signal)}async function pv(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit));let o=i.toString(),s=`/v1/inventory/${w(e)}/${w(n)}/recipe-usage`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function gv(t,e,n,r,i){let o=`/v1/saves/${w(e)}/${w(n)}/${w(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function fv(t,e,n){let r=`/v1/events/${w(e)}`;return t.client.get(r,n?.signal)}async function yv(t,e,n){let r=`/v2/games/${w(t.gameId())}/game-rooms/${w(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function hv(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 i=r.toString(),o=`/v1/leaderboards/${w(e)}`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function bv(t,e,n){let r=`/v1/profiles/players/${w(e)}`;return t.client.get(r,n?.signal)}async function vv(t,e){let n=new URLSearchParams;e?.config_version!==void 0&&n.set("config_version",String(e?.config_version));let r=n.toString(),i="/v1/inventory/platform-funded-game-inventory-purchase-catalog"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function _v(t,e,n){let r=`/v1/game-room-templates/${w(e)}`;return t.client.get(r,n?.signal)}async function wv(t,e,n){let r=`/v1/games/${w(t.gameId())}/game-rooms/${w(e)}/room-args`;return t.client.get(r,n?.signal)}async function Sv(t,e,n,r){let i=`/v1/showcase/players/${w(e)}/${w(n)}`;return t.client.get(i,r?.signal)}async function Rv(t,e,n){let r=`/v1/inventory/transfers/${w(e)}`;return t.client.get(r,n?.signal)}async function Ka(t,e,n){let r=`/v1/games/${w(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true,retryRateLimited:false})}async function kv(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function Av(t,e,n){let r=new URLSearchParams;n?.cue_id!==void 0&&r.set("cue_id",String(n?.cue_id));let i=r.toString(),o="/v1/functions/invoke"+(i?`?${i}`:"");return t.client.postBytes(o,e,n?.signal)}async function xv(t,e,n,r){let i=`/v1/games/${w(t.gameId())}/game-rooms/${w(e)}/kick/${w(n)}`;return t.client.post(i,void 0,r?.signal)}async function Pv(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(),i="/v1/challenges"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Ev(t,e,n,r){let i=`/v1/settings/${w(e)}/${w(n)}`;return t.client.get(i,r?.signal)}async function Tv(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/inventory/${w(e)}/${w(n)}/orders`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Iv(t,e,n,r){let i=`/v1/inventory/${w(e)}/${w(n)}/progressions`;return t.client.get(i,r?.signal)}async function Cv(t,e,n,r){let i=new URLSearchParams;r?.limit!==void 0&&i.set("limit",String(r?.limit)),r?.cursor!==void 0&&i.set("cursor",String(r?.cursor));let o=i.toString(),s=`/v1/saves/${w(e)}/${w(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Ov(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(),i="/v1/events"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Mv(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(),i=`/v1/games/${w(t.gameId())}/game-rooms`+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Gv(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function Lv(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(),i="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Dv(t,e,n,r,i,o){let s=`/v1/inventory/${w(e)}/${w(n)}/progressions/${w(r)}/max`;return t.client.post(s,i,o?.signal)}async function Fv(t,e,n,r,i,o){let s=`/v1/settings/${w(e)}/${w(n)}/${w(r)}`;return t.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function $v(t,e,n,r){let i=`/v1/games/${w(t.gameId())}/game-rooms/${w(e)}/room-args`;return t.client.put(i,n,r?.signal)}async function qv(t,e,n,r,i){let o=`/v1/showcase/players/${w(e)}/${w(n)}`;return t.client.put(o,r,i?.signal)}async function Nv(t,e,n){let r=`/v1/inventory/transfers/${w(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function jv(t,e,n,r){let i=`/v1/games/${w(t.gameId())}/matches/${w(e)}/players/report`;return t.client.post(i,n,r?.signal)}async function Bv(t,e,n,r,i,o){let s=`/v1/saves/${w(e)}/${w(n)}/${w(r)}/upload-url`;return t.client.post(s,i,o?.signal,{replaySafe:true})}async function Uv(t,e,n,r,i,o){let s=`/v1/inventory/${w(e)}/${w(n)}/progressions/${w(r)}/reset`;return t.client.post(s,i,o?.signal)}async function Wv(t,e,n,r){let i=`/v1/games/${w(t.gameId())}/matches/${w(e)}/backfill`;return t.client.put(i,n,r?.signal)}async function Hv(t,e,n,r,i){let o=`/v1/inventory/${w(e)}/${w(n)}/orders/simulate`;return t.client.post(o,r,i?.signal)}async function Vv(t,e,n,r){let i=`/v2/games/${w(t.gameId())}/game-rooms/${w(e)}/transfer/${w(n)}`;return t.client.post(i,void 0,r?.signal)}async function Kv(t,e,n,r){let i=`/v2/games/${w(t.gameId())}/game-rooms/${w(e)}`;return t.client.patch(i,n,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var Jv=1e4,zv=50,Xv=1e3,Yv=65536-4*1024,im=t=>typeof t=="number"?t:0,Qv=t=>typeof t=="string"?t:"";function om(){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 Zv(t){return t?.retryable===true}function e_(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(i=>{let o=i??{};return {index:im(o.index),code:Qv(o.code)}}):[];return {accepted:im(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function am(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 sm(t){let e=Math.max(1,Math.floor(t.maxQueue??Xv)),n={client:t.client,gameId:()=>t.gameId},r=[],i=0,o=null,s=false,a=null,l=0,d=0,u=false,c=false,g=y=>{t.log?.(y);},p=()=>{o!==null&&(t.clock.clearTimeout(o),o=null);},f=()=>Math.max(0,d-t.clock.now()),h=()=>{o!==null||s||a!==null||(o=t.clock.setTimeout(()=>{o=null,v().catch(()=>{});},Math.max(Jv,f())));},R=()=>{let y=Math.min(r.length,100),_=128;for(let I=0;I<y;I+=1){let T=r[I];if(T===void 0)break;if(_+=JSON.stringify(am(T,0)).length+1,_>Yv)return Math.max(1,I)}return y};async function v(y){for(;a!==null;)await a.catch(()=>{});if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};let _=k(y);a=_;try{return await _}finally{a===_&&(a=null),r.length>0&&h();}}async function k(y){p();let _=r.splice(0,R()),I=i;i=0;let T=Math.round(t.clock.now()),H={batch_id:om(),sent_at_ms:T,events:_.map(q=>am(q,T))};try{let q=await Ka(n,H,y===void 0?void 0:{signal:y}),W=e_(q,I);l=0,d=0;for(let C of W.rejected)g(`[gem] analytics: an event was refused (${C.code}). See the analytics_events section of your game config.`);return W}catch(q){if(Zv(q)){for(r=[..._,...r],i+=I;r.length>e;)r.shift(),i+=1;l+=1,d=t.clock.now()+Vr(l,q);}else g(`[gem] analytics: ${_.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(q)}`);throw q}}return {track(y,_,I={}){if(s)return;if(typeof y!="string"||y===""){c||(c=true,g(`[gem] analytics: '${_}' 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(_.startsWith(Eo)){u||(u=true,g(`[gem] analytics: '${_}' 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 T={},H={};for(let[q,W]of Object.entries(I))typeof W=="string"?T[q]=W:typeof W=="number"&&Number.isFinite(W)&&(H[q]=W);for(;r.length>=e;)r.shift(),i+=1;r.push({uid:om(),playerId:y,name:_,atMs:t.clock.now(),dimensions:T,measures:H}),r.length>=zv&&a===null&&f()===0?v().catch(()=>{}):h();},flush:y=>v(y),get pending(){return r.length},dispose(){s=true,p(),r=[],i=0;}}}function lm(t){return {async list(e){let{playerId:n,periodsBack:r,signal:i}=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().");Ct(r);let o=await t({player_id:n,...r===void 0?{}:{periods_back:r},...i===void 0?{}:{signal:i}});return $r(o)}}}function t_(t){let e={};for(let[n,r]of Object.entries(Ja))if(typeof r=="function"){let i=r;e[n]=(...o)=>i(t,...o);}return e}function Ht(t,e={}){let n=e.clock??ce,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 i=Va(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),o=Pr({baseUrl:r,tokenSource:i.source,defaultQuery:{game_id:t.gameId,channel:t.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),s=new Ve({transport:o,clock:n}),a={gameId:t.gameId,channel:t.channel,matchId:t.matchId,...t.gameRoomId===void 0?{}:{gameRoomId:t.gameRoomId}},l=t_({client:s,gameId:()=>a.gameId}),d=a.gameRoomId,u=t.endMatch,c=t.log,g=sm({client:s,clock:n,gameId:a.gameId,...typeof c=="function"?{log:f=>c.call(t,f)}:{}});return {identity:a,client:s,api:l,match:{end:async()=>{if(u===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 u.call(t);},setBackfill:async(f,h)=>{let R=await l.setMatchBackfill(a.matchId,{open:f.open,...f.seats===void 0?{}:{seats:f.seats}},h===void 0?{}:{signal:h});return {open:R.open,seats:R.seats??null}},reportPlayers:async(f,h)=>(await l.reportMatchPlayers(a.matchId,{players:f.map(v=>({player_id:v.playerId,state:v.state}))},h===void 0?{}:{signal:h})).players.map(v=>({playerId:v.player_id,outcome:v.outcome}))},analytics:g,functions:new Xe(l.invokeFunction),challenges:lm(l.listChallenges),...d===void 0?{}:{room:{get:f=>l.getGameRoomV2(d,f),args:async f=>{let h=await l.getGameRoomV2(d,f?.signal===void 0?{}:{signal:f.signal}),R=h.modified?h.body:void 0;if(R?.room_args==null||R.room_args_template==null)throw new O("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:()=>{g.dispose(),i.dispose();}}}function yt(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function Vt(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function jn(t){return typeof t=="string"?t:t.slice().buffer}function ki(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 n_=5e3,dm=3e4,cm=2e3,r_=1e4,i_=3,um=1;async function mm(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 i=e.log===void 0?b=>console.info(b):e.log,o=b=>i?.(`[gem host] ${b}`),s=typeof t=="function"?t():t,a=Promise.resolve(),l=true,d=false,u=(b,M)=>{l&&(a=a.then(async()=>{if(!d)try{await M();}catch(B){o(`the bundle's ${b} handler threw: ${ht(B)}. Serving continues.`);}}));},c=true,g,p,f,h=b=>{if(!c)return;c=false,u("leave",()=>s.leave?.(r,{cause:b??"left"}));let M=p;M&&queueMicrotask(()=>M(b));},R={send(b,M){if(!c)return;let B=Vt(yt(M));u("message",()=>s.message?.(r,b,typeof b=="string",{reliable:B.reliable,ordered:B.ordered}));},onMessage(b){g=b;},onClose(b){p=b;},close(){h("closed");}},v=(b,M)=>{if(!c)return;let B=Vt(yt(M));queueMicrotask(()=>{c&&g?.(b,B);});},k=new Map,y=b=>{let M=[];for(let B of Be){let Z=b.channels[B];try{Z.binaryType="arraybuffer";}catch{}let ye=Vt(B),rt=Fe=>{let wt=ki(Fe?.data);wt!==null&&u("message",()=>s.message?.(b.playerId,wt.data,wt.isText,{reliable:ye.reliable,ordered:ye.ordered}));};Z.addEventListener("message",rt),M.push(()=>Z.removeEventListener("message",rt));}k.get(b.playerId)?.forEach(B=>B()),k.set(b.playerId,M);},_=b=>{k.get(b)?.forEach(M=>M()),k.delete(b);},I=new Set,T=new Map,H=(b,M,B)=>({playerNumber:b.assignedPeerId,transport:"webrtc_p2p",...M?{rejoin:true}:{},...B?{superseded:true}:{}}),q=b=>{let M=k.has(b.playerId),B=I.has(b.playerId);I.add(b.playerId),y(b),M&&u("leave",()=>s.leave?.(b.playerId,{cause:"superseded"})),u("join",()=>s.join?.(b.playerId,H(b,B,M)));},W=new Set,C=(b,M,B)=>{if(b===r){v(M,B);return}let Z=n.peer(b);if(Z===null){let ye=T.get(b);if(ye!==void 0&&e.clock.now()-ye<cm)return;W.has(b)||(W.add(b),o(`send to '${b}' dropped: no such connected player`));return}Z.send(jn(M),yt(B));},L={matchId:n.matchId,gameId:e.gameId,channel:e.channel,...e.gameRoomId===void 0?{}:{gameRoomId:e.gameRoomId},apiBaseUrl:e.apiBaseUrl,serverToken:()=>e.tokens.current(),onServerToken:b=>e.tokens.subscribe(b),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(b=>b.playerId)??[],players(){let b=c?[r]:[];for(let M of n.peers)b.push(M.playerId);return b},profile(b){let M=e.room()?.members.find(B=>B.playerId===b);if(!(!M||M.displayName===void 0))return {displayName:st.toPlain(M.displayName),...M.displayTag===void 0?{}:{displayTag:st.toPlain(M.displayTag)},...M.discriminator===void 0?{}:{discriminator:M.discriminator}}},playerNumber(b){return b===r?um:n.peer(b)?.assignedPeerId},send(b,M,B){C(b,M,B);},broadcast(b,M){let B=M?.except;c&&r!==B&&v(b,M);for(let Z of n.peers)Z.playerId!==B&&Z.send(jn(b),yt(M));},async endMatch(){let b=await xe();return b.answer!=="ok"&&o(b.cause),b.answer},kick(b,M){if(b===r){h(M??"kicked");return}n.kick(b).catch(B=>{o(`kick of '${b}' failed: ${ht(B)}`);});},log(b){o(b);},warn(b){o(`\u26A0 ${b}`);}},$=()=>{},U=new Promise(b=>{$=b;}),x=[],G=null,re=async(b,M)=>{l=false;let B=a.then(async()=>{try{await s.shutdown(b);}catch(Z){o(`the bundle's shutdown threw: ${ht(Z)}`);}});a=B,await B,Ce();for(let Z of x.splice(0))Z();for(let Z of [...k.keys()])_(Z);h(M);},pe=(b,M)=>G||(G=(async()=>{await re(M,b),n.close(),$();})(),G),Q=()=>G||(G=(async()=>{await re({reason:"signal"},"left"),await n.leave().catch(b=>o(`leaving the match failed: ${ht(b)}`)),$();})(),G),tt=()=>G||(G=(async()=>{l=false;let b=await xe();b.answer==="ok"?(await re({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(o(`${b.cause}; leaving instead`),await re({reason:"signal"},"left"),await n.leave().catch(M=>o(`leaving the match failed: ${ht(M)}`))),$();})(),G),we=null,Ae=()=>(we??=Ht(L,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),we),xe=async()=>{try{return await Bl({client:Ae().client,gameId:()=>L.gameId},L.matchId,{},{signal:AbortSignal.timeout(n_)}),{answer:"ok"}}catch(b){return b instanceof O&&(b.reason==="forbidden"||b.reason==="not_found")?{answer:b.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${b.reason})`}:{answer:"failed",cause:`ending the match failed: ${ht(b)}`}}},te=null,X=false,ne=0,Ie,Ue=null,Ce=()=>{X=true,te!==null&&(e.clock.clearTimeout(te),te=null),Ue?.(),Ue=null;},Jt=b=>{o(`heartbeats paused: ${b}; they resume when a fresh play token arrives`),We();let M=Ie,B=false,Z=e.tokens.subscribe(ye=>{B||X||ye.token===M||_t(ye)||(B=true,Ue?.(),Ue=null,ne=0,Ie=void 0,We(),o("a fresh play token arrived; heartbeats resume"),te=e.clock.setTimeout(()=>{He();},0));});B?Z():Ue=Z;},We=()=>{let b=we;we=null,b?.dispose();},_t=b=>b.expiresAt*1e3<=e.clock.now(),He=async()=>{if(te=null,!X){try{await Ae().client.post(`/v1/games/${encodeURIComponent(L.gameId)}/matches/${encodeURIComponent(L.matchId)}/heartbeat`,void 0,AbortSignal.timeout(r_)),ne=0,Ie=void 0;}catch(b){if(b instanceof O&&(b.reason==="forbidden"||b.reason==="not_found")){o(`the platform no longer holds this match under this host (${b.reason}); heartbeats stop`),Ce();return}if(o_(b)){if(X)return;ne+=1;let M=e.tokens.current(),B=M===void 0?"this host holds no play token":_t(M)?"this host's play token has expired":M.token===Ie?"the platform refused this host's play token again":ne>=i_?`the platform refused this host's play token ${ne} times in a row`:null;if(Ie=M?.token,B!==null){Jt(B);return}}else ne=0,Ie=void 0;o(`heartbeat failed: ${ht(b)}`);}X||(te=e.clock.setTimeout(()=>{He();},dm));}},zt=()=>{X||te!==null||(te=e.clock.setTimeout(()=>{He();},dm));};{let b=$;$=()=>{Ce(),we?.dispose(),we=null,b();};}let nt=Promise.resolve().then(()=>s.init(L));a=nt.then(()=>{},()=>{}),u("join",()=>s.join?.(r,{playerNumber:um,transport:"loopback"})),x.push(n.on("peerJoined",q)),x.push(n.on("peerLeft",(b,M)=>{_(b);let B=e.clock.now();for(let[Z,ye]of T)B-ye>=cm&&T.delete(Z);T.set(b,B),W.delete(b),u("leave",()=>s.leave?.(b,{cause:M}));})),x.push(n.on("error",b=>{o(`\u26A0 session error: ${b.message}`);})),x.push(n.on("matchEnded",b=>{G||za(f,b),pe("match ended",{reason:"match_ended",platform_reason:b});})),x.push(n.on("hostChanged",b=>{b!==r&&pe("host migrated",{reason:"host_migrated"});}));for(let b of n.peers)q(b);try{await nt,zt();}catch(b){l=false,Ce(),d=true;for(let M of x.splice(0))M();for(let M of [...k.keys()])_(M);throw n.leave().catch(()=>{}),$(),b}return {matchId:n.matchId,localLink:R,onMatchEnded(b){f=b;},end:tt,leave:Q,stop:b=>pe(b,{reason:"stopped"}),done:U}}function za(t,e){try{t?.(e);}catch{}}function o_(t){return t instanceof O&&t.status===401||ie.isAuthError(t)}function ht(t){return t instanceof Error?t.message:String(t)}function Xa(t,e){let n=async()=>{throw new A("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 pm(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,i=new Map,o=async a=>{r.isHost&&!Ha(r)&&r.currentRoom?.matchId===void 0&&await r.startMatch({...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...a.signal===void 0?{}:{signal:a.signal}});let l={...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal}};return r.matchConnectionState==="suspended"?r.reconnectToMatch(l):r.awaitMatch(l)},s=a=>({...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0?{}:{clusterTargetId:a.clusterTargetId}});return {async serve(a,l={}){let d=await o(l);if(d.protocol!==gt)return Xa("dedicated",d.matchId);let u=t.p2p.session?.(d.matchId)??null;if(u===null&&!r.isHost||u!==null&&!u.isHost)return Xa("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 g=u??await t.p2p.connect(s(l)),p=await mm(a,{session:g,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:g.playerId!==""?g.playerId:c.playerId,...t.log===void 0?{}:{log:t.log},...t.fetch===void 0?{}:{fetch:t.fetch}});return i.set(d.matchId,p),p.done.then(()=>{i.get(d.matchId)===p&&i.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>p.end(),leave:()=>p.leave(),stop:()=>p.stop()}},async connect(a={}){let l=await o(a),d=a.onMatchEnded;if(l.protocol===gt){let p=i.get(l.matchId);if(p!==void 0)return r.notifyMatchConnected(l.matchId),d_(l.matchId,p,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 In(),h=async()=>t.p2p.connect({...s(a),certificate:f}),R=await h(),v=u_(R,h,d,k=>{r.notifyMatchDisconnected(k).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(R.matchId,{redial:v.redial,abandon:v.abandon}),v.onClosed(()=>{e.get(R.matchId)?.abandon===v.abandon&&e.delete(R.matchId);})),v}let u=async(p=null)=>await t.dedicated.connect({...p===null?{}:{reportConnected:false,redial:true,...p.deadlineAt===void 0?{}:{deadlineAt:p.deadlineAt}},...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:a.transports??[]}),c=await u(),g=c_(c,u,r,n);return n&&(e.set(c.matchId,{redial:g.redial,abandon:g.abandon}),g.onClosed(()=>{e.get(c.matchId)?.abandon===g.abandon&&e.delete(c.matchId);})),g},async redialMatch(a,l){let d=e.get(a);return d===void 0?"closed":d.redial(l)},abandonMatch(a,l){e.get(a)?.abandon(l);}}}var gm="link_closed",a_="host_unreachable",s_=new Set(["failed","closed","relay_deadline","restart_mismatch"]);function l_(t){return s_.has(t)?gm:a_}function d_(t,e,n){let r=e.localLink;e.onMatchEnded(n);let i="connected";r.onClose(()=>{i="closed";});let o;return {matchId:t,protocol:"loopback",get state(){return i},send:(s,a)=>r.send(s,a),onMessage:s=>r.onMessage(s),onClose:s=>{o=s,r.onClose(a=>{i="closed",o?.(a);});},close:()=>r.close()}}function c_(t,e,n,r){let i=t.matchId,o=t,s="connected",a,l,d=[],u=false,c=false,g=f=>{if(s!=="closed"){s="closed";for(let h of d.splice(0))h();l?.(f);}},p=f=>{f.link.onMessage((h,R)=>a?.(h,R)),f.link.onClose(h=>{if(f!==o||s==="closed")return;if(u||!r){g(h);return}let R=n.matchSession;if(R.phase==="suspended"&&R.matchId===i){s="suspended";return}g(h);});};return p(t),{matchId:i,protocol:"dedicated",get transport(){return o.transport},get state(){return s},send(f,h){s==="connected"&&o.link.send(f,h);},onMessage(f){a=f;},onClose(f){l=f;},close(){if(s!=="closed"){if(u=true,s==="suspended"){g("closed");return}o.close(),g("closed");}},async redial(f){if(s==="closed"||u)return "closed";if(c)return "connected";c=true;let h;try{h=await e(f===void 0?{}:{deadlineAt:f});}finally{c=false;}return u||s==="closed"?(h.close(),"closed"):(o=h,p(h),s="connected",n.notifyMatchConnected(i),"connected")},abandon(f){s!=="closed"&&(s==="connected"&&o.close(),g(f));},onClosed(f){s==="closed"?f():d.push(f);}}}function u_(t,e,n,r,i,o=false){let s=t.matchId,a=t,l,d,u=[],c=[],g=[],p=false,f=false,h=false,R=false,v="connected",k=C=>{if(p)return;p=true,v="closed";for(let $ of u.splice(0))$();for(let $ of c.splice(0))$();for(let $ of g.splice(0))$();let L=d;L&&queueMicrotask(()=>L(C));},y=C=>{for(let L of u.splice(0))L();for(let L of Be){let $=C.channels[L];try{$.binaryType="arraybuffer";}catch{}let U=Vt(L),x=G=>{let re=ki(G?.data);re!==null&&l?.(re.data,U);};$.addEventListener("message",x),u.push(()=>$.removeEventListener("message",x));}},_=()=>a.peer(a.hostPlayerId),I=C=>{if(!(p||a.isHost)&&v!=="suspended"){if(r?.(C),o){v="suspended";return}k(C);}},T=C=>{for(let L of Be){let $=C.channels[L];if(typeof $.addEventListener!="function")continue;let U=()=>{_()===C&&I(gm);};$.addEventListener("close",U),u.push(()=>$.removeEventListener?.("close",U));}},H=C=>{y(C),T(C),!p&&(v="connected",i?.());},q=C=>{for(let L of c.splice(0))L();c.push(C.on("migrating",()=>{R=true;})),c.push(C.on("hostChanged",L=>{if(R=false,L===C.playerId){k("host_migrated_here");return}let $=_();$!==null&&H($);})),c.push(C.on("peerJoined",L=>{L.playerId===C.hostPlayerId&&H(L);})),c.push(C.on("matchEnded",L=>{p||za(n,L),k(L);})),c.push(C.on("peerLeft",(L,$)=>{L===C.hostPlayerId&&I(l_($));}));};q(a);let W=_();return W!==null&&H(W),{matchId:s,protocol:"p2p",get state(){return v},send(C,L){v==="connected"&&_()?.send(jn(C),yt(L));},onMessage(C){l=C;},onClose(C){d=C;},close(){f=true,k("closed"),a.leave().catch(()=>{});},async redial(){if(v==="closed")return "closed";if(v==="connected"||h)return "connected";if(R)throw new N("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");h=true;let C;try{for(let $ of u.splice(0))$();for(let $ of c.splice(0))$();a.close(),C=await e();}finally{h=false;}if(p)return f?C.leave().catch(()=>{}):C.close(),"closed";a=C,q(a);let L=_();if(L===null)throw a.close(),new N("connection_failed","this peer rejoined the match but the host never answered with a link");return H(L),"connected"},abandon(C){k(C);},onClosed(C){p?C():g.push(C);}}}function fm(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(i=>{let o={},s=l=>{n.delete(r)&&(t.clock.clearTimeout(o.timer),i(l));};n.set(r,s),o.timer=t.clock.setTimeout(()=>s(void 0),t.timeoutMs??2e3);let a=false;try{a=t.bridge.requestParty(r);}catch{}a||s(void 0);})},settle(r,i){n.get(r)?.(i);}}}var m_=12e4;function bt(t,e){return {outcome:t,reason:e}}function ym(t){let e=false,n=new Map,r=new Set,i=l=>{for(let d of [...r])try{d(l);}catch(u){t.onListenerError?.(u);}},o=async l=>{try{return await t.confirm(l)}catch{return "unknown"}},s=(l,d,u,c)=>{if(!t.bridge.parentSupports(l))return Promise.resolve(bt("unavailable","error"));if(e)return Promise.resolve(bt("declined","busy"));let g=`purchase-${ue()}`;return new Promise(p=>{let f={},h=v=>{n.delete(g)&&(e=false,t.clock.clearTimeout(f.timer),p(v));};e=true,n.set(g,{finish:h,check:u,label:c}),f.timer=t.clock.setTimeout(()=>h(bt("unavailable","error")),t.timeoutMs??m_);let R=false;try{R=d(g);}catch{}R||h(bt("unavailable","error"));})},a=l=>l===void 0?null:t.confirm(l);return {api:{request(l){return s("purchases",d=>t.bridge.requestPurchase(d,l.kind,l.targetId,l.currencySlug,l.quantity,l.catalogId),a,d=>`purchase ${JSON.stringify(d)}`)},onSettled(l){return r.add(l),()=>{r.delete(l);}}},handOffRefused(l){s("purchases",d=>t.bridge.requestPurchase(d,l.kind,l.targetId,l.currencySlug,l.quantity,l.catalogId,"direct_refused"),a,d=>`purchase ${JSON.stringify(d)}`).then(d=>{d.outcome!=="ok"||d.purchaseId===void 0||(t.onInventoryStale?.(),i(Object.freeze({kind:l.kind,targetId:l.targetId,...l.catalogId===void 0?{}:{catalogId:l.catalogId},quantity:l.quantity,purchaseId:d.purchaseId})));});},settled(l){if(!t.bridge.parentSupports("purchaseSettled")){t.onDropped?.("gem.purchaseSettled from a parent that did not advertise purchaseSettled; ignored");return}let{purchaseId:d}=l;(async()=>{let u=d===void 0?"unknown":await o(d);if(u==="absent"){t.onDropped?.(`gem.purchaseSettled for purchase ${JSON.stringify(d)}, which the platform has no grant for; ignored`);return}t.onInventoryStale?.(),!(u!=="granted"||d===void 0)&&i(Object.freeze({kind:l.purchaseKind,targetId:l.targetId,...l.catalogId===void 0?{}:{catalogId:l.catalogId},quantity:l.quantity,purchaseId:d}));})();},requestAvatar3d(l){return s("avatar3dPurchases",d=>t.bridge.requestAvatar3dPurchase(d,l.itemId,l.currencySlug),()=>t.confirmAvatar3d(l.itemId),()=>`3D avatar ${JSON.stringify(l.itemId)}`)},settle(l){let d=l.outcome==="ok"||l.outcome==="declined"?l.outcome:"unavailable",u=n.get(l.requestId);if(u===void 0){t.onDropped?.(`gem.purchaseResult (${d}) for an unknown requestId: `+JSON.stringify(l.requestId));return}let{finish:c}=u;if(d!=="ok"){c(bt(d,ad(l.reason)));return}let g=l.purchaseId,p;try{p=u.check(g);}catch{p=Promise.resolve("unknown");}if(p===null){t.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),c(bt("unavailable","error"));return}(async()=>{let f;try{f=await p;}catch{f="unknown";}if(f==="granted"){c(g===void 0?{outcome:"ok"}:{outcome:"ok",purchaseId:g});return}f==="absent"&&t.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for "+u.label(g)),c(bt("unavailable","error"));})();}}}async function hm(t,e){try{return (await kl(t,e)).granted?"granted":"absent"}catch(n){return n instanceof O&&n.reason==="not_found"?"absent":"unknown"}}var p_="small_human",bm=/^[a-z][a-z0-9_]{0,31}$/,vm=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,g_=8;function Ya(t){if(t===null)return [];if(t.avatars3d!==void 0)return t.avatars3d;let{avatar3dId:e,avatar3dModelUrl:n,avatar3dIconUrl:r}=t;return e===void 0||n===void 0||r===void 0?[]:[{family:p_,id:e,modelUrl:n,iconUrl:r}]}function f_(t,e){return t.length===e.length&&t.every((n,r)=>{let i=e[r];return n.family===i.family&&n.id===i.id&&n.modelUrl===i.modelUrl})}function y_(t){let e=t??{},n=typeof e.item_id=="string"&&vm.test(e.item_id)?e.item_id:void 0,r=typeof e.family=="string"&&bm.test(e.family)?e.family:void 0,i=typeof e.slug=="string"&&e.slug!==""?e.slug:void 0,o=typeof e.display_name=="string"&&e.display_name!==""?e.display_name:void 0,s=typeof e.description=="string"&&e.description!==""?e.description:void 0,a=Ot(e.icon_url),l=Ot(e.model_url),d=[];for(let u of Array.isArray(e.prices)?e.prices:[]){let c=u??{};typeof c.currency_slug=="string"&&c.currency_slug!==""&&typeof c.price=="number"&&Number.isSafeInteger(c.price)&&c.price>0&&d.push({currencySlug:c.currency_slug,price:c.price});}if(!(n===void 0||r===void 0||i===void 0||o===void 0||a===void 0||l===void 0||d.length===0))return {itemId:n,slug:i,family:r,displayName:o,...s===void 0?{}:{description:s},iconUrl:a,modelUrl:l,prices:d}}function h_(t){if(!Array.isArray(t))return [];let e=[];for(let n of t)if(typeof n=="string"&&bm.test(n)&&!e.includes(n)&&e.push(n),e.length===g_)break;return e}function _m(t){let e=new Set,n=Ya(t.player()),r=i=>{t.log?.(`[gem] an avatars3d onChange listener threw: ${i instanceof Error?i.message:String(i)}`);};return t.subscribe(i=>{let o=Ya(i);if(!f_(n,o)){n=o;for(let s of [...e])try{s(o);}catch(a){r(a);}}}),{async families(){return h_(await t.configFamilies())},worn(i){let o=Ya(t.player());if(i!==void 0)return o.find(l=>l.family===i);let a=t.player()?.avatar3dId;return (a===void 0?void 0:o.find(l=>l.id===a))??o[0]},async offers(){let i=await t.readOffers(),o=[];for(let s of Array.isArray(i?.offers)?i.offers:[]){let a=y_(s);a!==void 0&&o.push(a);}return o},purchase(i){let o=i?.itemId,s=i?.currencySlug;return typeof o!="string"||!vm.test(o)?Promise.resolve({outcome:"declined",reason:"not_purchasable"}):typeof s!="string"||s===""?Promise.resolve({outcome:"declined",reason:"unknown_currency"}):t.purchase({itemId:o,currencySlug:s})},onChange(i){return e.add(i),()=>{e.delete(i);}}}}async function wm(t,e){try{return (await rl(t,e))?.owned===!0?"granted":"absent"}catch(n){return n instanceof O&&n.reason==="not_found"?"absent":"unknown"}}function Sm(t){return hl(t)}var b_=6e5;function Rm(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-${ue()}`;return e=new Promise(i=>{let o={},s=l=>{n.delete(r)&&(e=null,t.clock.clearTimeout(o.timer),i(l));};n.set(r,s),o.timer=t.clock.setTimeout(()=>{s({outcome:"unavailable"});},t.timeoutMs??b_);let a=false;try{a=t.bridge.requestSignIn(r);}catch{}a||s({outcome:"unavailable"});}),e}},settle(r){let i=r.outcome==="signed_in"||r.outcome==="declined"?r.outcome:"unavailable",o=n.get(r.requestId);if(o===void 0){t.onDropped?.(`gem.signInResult (${i}) for an unknown requestId: `+JSON.stringify(r.requestId));return}o({outcome:i});}}}var v_=1e4,Ai="[gem] gem.share.request:",xi=class extends Error{reason;constructor(e,n){super(`${Ai} the arcade refused the share: ${e}`+(n===void 0?"":` (param ${JSON.stringify(n)})`)),this.name="ShareRefusal",this.reason=e,n!==void 0&&(this.key=n);}};function km(t){let e=new Map;return {wait(n){let r=()=>{};return {answer:new Promise(o=>{let s={};r=a=>{e.delete(n)&&("timer"in s&&t.clearTimeout(s.timer),o(a));},e.set(n,r),s.timer=t.setTimeout(()=>r(null),v_);}),cancel:()=>r(null)}},settle(n){let r=e.get(n.requestId);return r===void 0?false:(r(n),true)},abandon(){for(let n of [...e.values()])n(null);}}}function Am(t){let{frame:e,log:n,answers:r}=t,i=false,o=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,s=a=>{n!==null&&(n===void 0?console.warn(a):n(a));};return {get available(){return o()!==null},request(a){let l=o();if(l===null)throw new Error(`${Ai} 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(`${Ai} pass { params }, or nothing`);let d=Gt(a?.params===void 0?{}:a.params,l.parentSupports("shareRemap"));if("error"in d)throw new TypeError(`${Ai} ${d.error}`);let{pairs:u}=d,c=l.parentSupports("shareResult")?`share-${ue()}`:void 0,g=c===void 0?null:r.wait(c);return l.requestShare(u,c)?g===null?Promise.resolve():g.answer.then(p=>{if(p?.outcome==="refused")throw new xi(p.reason??"error",p.key)}):(g?.cancel(),i||(i=true,s("[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.")),Promise.resolve())}}}var Bn=3e4,Qa=12e4;function Un(t,e,n){return t.held?Promise.resolve(n):(t.held=true,e().then(r=>(t.held=false,r)))}function me(t,e,n){return {outcome:t,reason:e,...n}}function Ze(t){let e=t.outcome==="ok"||t.outcome==="declined"?t.outcome:"unavailable";return typeof t.reason=="string"?{outcome:e,reason:t.reason}:{outcome:e}}function xm(t){let e=new Map;return {ask(n,r,i,o){let s=`arcade-${ue()}`;return new Promise(a=>{let l={},d=c=>{e.delete(s)&&("timer"in l&&t.clearTimeout(l.timer),a(i(c)));};e.set(s,{expect:n,finish:d}),o!==void 0&&(l.timer=t.setTimeout(()=>d(null),o));let u=false;try{u=r(s);}catch{}u||d(null);})},settle(n){let r=e.get(n.requestId);return r===void 0||r.expect!==n.type?false:(r.finish(n),true)},abandon(){for(let n of [...e.values()])n.finish(null);}}}var __=12,w_=24,Za=Object.freeze({games:Object.freeze([])});function S_(t){let e=(n,r)=>be(n,`GameCard.${r}`);return Object.freeze({gameId:t.gameId,...t.slug===void 0?{}:{slug:t.slug},name:e(t.untrusted.name,"name"),tagline:e(t.untrusted.tagline,"tagline"),shortDescription:e(t.untrusted.shortDescription,"shortDescription"),tags:Object.freeze(t.untrusted.tags.map(n=>e(n,"tags"))),iconUrl:t.iconUrl,capsuleLandscapeUrl:t.capsuleLandscapeUrl,capsulePortraitUrl:t.capsulePortraitUrl,...t.previewVideoUrl===void 0?{}:{previewVideoUrl:t.previewVideoUrl},...t.previewPosterUrl===void 0?{}:{previewPosterUrl:t.previewPosterUrl}})}function Pi(t){return me("unavailable","error",t)}function Pm(t){let{bridge:e,asker:n,acting:r}=t,i=a=>e.currentState==="connected"&&e.parentSupports(a),o=new Map,s=(a,l)=>{let d=o.get(a);if(d!==void 0)return d;let u=l().then(c=>(o.delete(a),c));return o.set(a,u),u};return {get available(){return {appLinks:i("appLinks"),openGame:i("openGame")}},appLinks(){return e.parentSupports("appLinks")?s("appLinks",()=>n.ask("gem.appLinksResult",a=>e.requestArcade({type:"gem.requestAppLinks",requestId:a}),a=>{if(a===null)return Pi({});let l=a;return {...Ze(a),...l.arcade===void 0?{}:{arcade:{store:l.arcade.store}},...l.game===void 0?{}:{game:{store:l.game.store}}}},Bn)):Promise.resolve(me("unavailable","unsupported",{}))},openApp(a){return e.parentSupports("appLinks")?a!=="arcade"&&a!=="game"?Promise.resolve(me("unavailable","invalid_argument",{})):Un(r,()=>n.ask("gem.openAppResult",l=>e.requestArcade({type:"gem.requestOpenApp",requestId:l,target:a}),l=>l===null?Pi({}):Ze(l),Qa),me("declined","busy",{})):Promise.resolve(me("unavailable","unsupported",{}))},openGame(a){if(!e.parentSupports("openGame"))return Promise.resolve(me("unavailable","unsupported",{}));let l=typeof a=="string"?a.toLowerCase():"";return nd({gem:j,type:"gem.requestOpenGame",requestId:"-",ref:l})!==null?Promise.resolve(me("unavailable","invalid_argument",{})):Un(r,()=>n.ask("gem.openGameResult",u=>e.requestArcade({type:"gem.requestOpenGame",requestId:u,ref:l}),u=>u===null?Pi({}):Ze(u),Qa),me("declined","busy",{}))},similarGames(a){if(!e.parentSupports("openGame"))return Promise.resolve(me("unavailable","unsupported",Za));let l=a?.limit;return l!==void 0&&(typeof l!="number"||!Number.isInteger(l)||l<1||l>w_)?Promise.resolve(me("unavailable","invalid_argument",Za)):s(`similar:${l??__}`,()=>n.ask("gem.similarGamesResult",d=>e.requestArcade({type:"gem.requestSimilarGames",requestId:d,...l===void 0?{}:{limit:l}}),d=>{if(d===null)return Pi(Za);let u=Ze(d),c=d,g=u.outcome==="ok"?Object.freeze(c.games.map(S_)):[];return {...u,games:g}},Bn))}}}var R_=64,Em=Object.freeze({offers:Object.freeze([])});function k_(t){return Object.freeze({skuId:t.skuId,kind:t.kind,name:t.name,description:t.description,...t.imageUrl===void 0?{}:{imageUrl:t.imageUrl},priceDisplay:t.priceDisplay,...t.grant===void 0?{}:{grant:Object.freeze({currency:t.grant.currency,amount:t.grant.amount})}})}function Tm(t){let{bridge:e,asker:n,acting:r}=t,i=new Set,o=null;function s(a,l,d,u){return e.parentSupports(a)?typeof u!="string"||u.length===0||u.length>R_?Promise.resolve(me("unavailable","invalid_argument",{})):Un(r,()=>n.ask(d,c=>e.requestArcade({type:l,requestId:c,skuId:u}),c=>c===null?me("unavailable","error",{}):Ze(c)).then(c=>((c.outcome==="ok"||c.reason==="error")&&t.onPurchaseEnded?.(),c)),me("declined","busy",{})):Promise.resolve(me("unavailable","unsupported",{}))}return {api:{get available(){return e.currentState==="connected"&&e.parentSupports("store")},get showOfferAvailable(){return e.currentState==="connected"&&e.parentSupports("storeOfferSheet")},offers(){return e.parentSupports("store")?(o!==null||(o=n.ask("gem.storeOffersResult",a=>e.requestArcade({type:"gem.requestStoreOffers",requestId:a}),a=>{if(a===null)return me("unavailable","error",Em);let l=Ze(a),d=a,u=l.outcome==="ok"?Object.freeze(d.offers.map(k_)):[];return {...l,offers:u}},Bn).then(a=>(o=null,a))),o):Promise.resolve(me("unavailable","unsupported",Em))},purchase(a){return s("store","gem.requestStorePurchase","gem.storePurchaseResult",a)},showOffer(a){return s("storeOfferSheet","gem.requestStoreOfferSheet","gem.storeOfferSheetResult",a)},onSettled(a){return i.add(a),()=>{i.delete(a);}}},settled(a){t.onPurchaseEnded?.();let l=Object.freeze({skuId:a.skuId});for(let d of [...i])try{d(l);}catch(u){t.onListenerError?.(u);}}}}var Lm="https://gemarcade.com/branding/manifest.json",A_=1,Im=256*1024,x_=256,P_=64,E_=256,Cm=8e3,T_=6e4,I_=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Om={GEMS:"gems-mark",ARCADE_TICKETS:"ticket-mark"},Mm=Object.freeze({outcome:"unavailable"}),Gm=Object.freeze({outcome:"not_found"});function vt(t){return typeof t=="number"&&Number.isFinite(t)&&t>0}function Ti(t){return typeof t=="string"&&t!==""&&t.length<=E_}function C_(t,e){if(!Ti(t))return;let n;try{n=new URL(t,e);}catch{return}let r=Ot(n.href);if(r!==void 0)return n.origin===new URL(e).origin?r:yo(r)}function O_(t,e){let n=t??{},r=C_(n.url,e);if(!(r===void 0||!Ti(n.type))&&!(typeof n.bytes!="number"||!(n.bytes>=0))&&!(n.theme!==void 0&&n.theme!=="light"&&n.theme!=="dark"))return Object.freeze({url:r,type:n.type,bytes:n.bytes,...vt(n.width)?{width:n.width}:{},...vt(n.height)?{height:n.height}:{},...vt(n.size)?{size:n.size}:{},...vt(n.density)?{density:n.density}:{},...n.vector===true?{vector:true}:{},...n.theme===void 0?{}:{theme:n.theme}})}function M_(t,e=Lm){let n;try{n=JSON.parse(t);}catch{return null}let r=n??{};if(r.format!==A_||!Array.isArray(r.assets))return null;let i=[],o=new Set;for(let s of r.assets.slice(0,x_)){let a=s??{};if(!Ti(a.id)||!I_.test(a.id)||o.has(a.id)||!Ti(a.kind)||!Array.isArray(a.variants))continue;let l=[];for(let d of a.variants.slice(0,P_)){let u=O_(d,e);u!==void 0&&l.push(u);}l.length!==0&&(o.add(a.id),i.push(Object.freeze({id:a.id,kind:a.kind,variants:Object.freeze(l)})));}return Object.freeze(i)}function Ei(t){let e;for(let n of t)(e===void 0||(n.width??0)>(e.width??0))&&(e=n);return e}function G_(t,e,n){let r=t.find(l=>l.vector===true),i=t.filter(l=>l.size===void 0);if(e===void 0)return r??Ei(i)??Ei(t);let o=t.filter(l=>l.size===e);if(o.length>0){let l=u=>u.density??1,d=o.filter(u=>l(u)>=n);return d.length>0?d.reduce((u,c)=>l(c)<l(u)?c:u):o.reduce((u,c)=>l(c)>l(u)?c:u)}if(r!==void 0)return r;let s=i.filter(l=>(l.width??0)>=e*n);return (s.length>0?s.reduce((l,d)=>(d.width??0)<(l.width??0)?d:l):void 0)??Ei(i)??Ei(t)}function L_(t,e){let n=e.theme===void 0?[]:t.variants.filter(a=>a.theme===e.theme),r=t.variants.filter(a=>a.theme===void 0),i=[n,r].filter(a=>a.length>0);if(t.kind!=="image")return i[0]?.[0];let s=(e.size===void 0?void 0:i.find(a=>a.some(l=>l.size===e.size)))??i[0];return s&&G_(s,e.size,e.density)}function D_(t,e){if(e!==void 0){if(e===null||typeof e!="object")throw new TypeError(`[gem] branding.${t}: options must be an object`);if(e.size!==void 0&&!vt(e.size))throw new RangeError(`[gem] branding.${t}: size must be a positive number of CSS px`);if(e.density!==void 0&&!vt(e.density))throw new RangeError(`[gem] branding.${t}: density must be a positive number`);if(e.theme!==void 0&&e.theme!=="light"&&e.theme!=="dark")throw new TypeError(`[gem] branding.${t}: theme must be 'light' or 'dark'`)}}function Dm(t){let e=t.manifestUrl??Lm,n=null,r=null,i=-1/0,o=false,s=u=>(i=t.clock.now(),o||(o=true,t.log?.(`[gem] gem.branding could not read the platform's branding (${u}), so every lookup answers 'unavailable' and your bundled fallback shows. If your page sets a Content-Security-Policy, allow ${new URL(e).origin} in connect-src and img-src.`)),null),a=async()=>{if(t.fetch===null)return s("this page has no fetch");let u=t.fetch,c=typeof AbortController=="function"?new AbortController:null,g,p=new Promise(h=>{g=t.clock.setTimeout(()=>{c?.abort(),h(s(`no answer in ${Cm} ms`));},Cm);}),f=(async()=>{let h=await u(e,{credentials:"omit",redirect:"error",...c?{signal:c.signal}:{}});if(!h.ok)return s("the manifest answered an error");if(Number(h.headers.get("content-length"))>Im)return s("the manifest is too large");let R=await h.text();return R.length>Im?s("the manifest is too large"):M_(R,e)??s("the manifest is not format 1 JSON")})().catch(()=>s("the request failed"));try{return await Promise.race([f,p])}finally{t.clock.clearTimeout(g);}},l=()=>n!==null?Promise.resolve(n):r!==null?r:t.clock.now()-i<T_?Promise.resolve(null):(r=a().then(u=>(r=null,u!==null&&(n=u),u)),r),d=async(u,c,g,p)=>{D_(u,p);let f=await l();if(f===null)return Mm;let h=f.find(k=>k.id===c&&k.kind===g);if(h===void 0)return Gm;let R=t.devicePixelRatio(),v=L_(h,{...p?.size===void 0?{}:{size:p.size},density:p?.density??(vt(R)?R:1),...p?.theme===void 0?{}:{theme:p.theme}});return v===void 0?Gm:Object.freeze({outcome:"ok",url:v.url,variant:v,asset:h})};return Object.freeze({get:async(u,c)=>{if(typeof u!="string"||u==="")throw new TypeError("[gem] branding.get: id must be a non-empty string");if(c===null||typeof c!="object"||typeof c.kind!="string")throw new TypeError("[gem] branding.get: options.kind must be a string, such as 'image'");return d("get",u,c.kind,c)},logo:u=>d("logo","gem-logo","image",u),wordmark:u=>d("wordmark","gem-wordmark","image",u),currencyMark:async(u,c)=>{let g=Object.prototype.hasOwnProperty.call(Om,u)?Om[u]:void 0;if(g===void 0)throw new TypeError("[gem] branding.currencyMark: currency must be 'GEMS' or 'ARCADE_TICKETS', not "+JSON.stringify(String(u).slice(0,40)));return d("currencyMark",g,"image",c)},trophy:u=>d("trophy","trophy-mark","image",u),list:async()=>{let u=await l();return u===null?Mm:Object.freeze({outcome:"ok",assets:u})}})}var N_="(any-pointer: coarse)";function j_(t){let e=Array.isArray(t)?t:[t],n=[],r=1e4;for(let i of e){if(typeof i!="number"||!Number.isFinite(i)||i<0)return null;if(n.length===99||r===0)continue;let o=Math.min(Math.trunc(i),1e4,r);n.push(o),r-=o;}return n.length%2===0&&n.pop(),n.every(i=>i===0)?[]:n}function Fm(t){let{frame:e,log:n}=t,r=t.environment??{navigator:typeof navigator>"u"?void 0:navigator,matchMedia:typeof matchMedia=="function"?u=>matchMedia(u):void 0},i=r.navigator,o,s=new Set,a=()=>typeof i?.vibrate!="function"||r.matchMedia===void 0?false:(o??=r.matchMedia(N_),o.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(u,c)=>{s.has(u)||(s.add(u),n!==null&&(n===void 0?console.warn(c):n(c)));};return {get available(){return a()||l()},vibrate(u){let c=a();if(!c&&!l())return false;let g=j_(u);if(g===null)return d("pattern","[gem] gem.vibration.vibrate did nothing: a pattern is a number of milliseconds, or an array of them, each finite and not negative."),false;if(i?.userActivation?.hasBeenActive!==true)return d("activation","[gem] gem.vibration.vibrate did nothing: the player has not tapped or pressed a key in your game yet, and browsers allow vibration only after that."),false;if(c)try{return i.vibrate(g)===!0}catch{return false}let p=e.requestVibrate(g);return p||d("rate","[gem] gem.vibration.vibrate was not sent: more than 600 vibrations in a minute. Vibrate on events, not every frame."),p}}}var Kt=Math.PI/180,De=Object.freeze({touch:Object.freeze({yaw:1*Kt,pitch:.66*Kt}),mouse:Object.freeze({yaw:.5*Kt,pitch:.5*.77*Kt}),stick:Object.freeze({yaw:240*Kt,pitch:240*.77*Kt}),stickDeadzone:.1,stickCurve:2,touchPitchMin:.25}),es="[gem.controls]",ts=Object.freeze({yaw:0,pitch:0}),Ii=t=>Number.isFinite(t)?t:0,$m=(t,e)=>({yaw:t+0,pitch:e+0});function qm(t){let e=Ii(t),n=(Math.abs(e)-De.stickDeadzone)/(1-De.stickDeadzone),r=De.stickCurve,i=(Math.exp(r*n)-1)/(Math.exp(r)-1);return Math.sign(e)*Math.min(1,Math.max(0,i))+0}function B_(t){let e=Math.min(1,2*Math.abs(t)/Math.PI);return (1-Math.pow(e,.75))*(1-De.touchPitchMin)+De.touchPitchMin}function Nm(t,e){if(t===void 0)return {};if(typeof t!="object"||t===null)throw new TypeError(`${es} ${e} takes an options object`);let n=t;for(let r of ["sensitivity","gamepadSensitivity"]){let i=n[r];if(i!==void 0&&!(typeof i=="number"&&Number.isFinite(i)&&i>0))throw new TypeError(`${es} ${e}: ${r} must be a finite number above 0 (1 = the base speed); got ${String(i)}`)}if(n.invertY!==void 0&&typeof n.invertY!="boolean")throw new TypeError(`${es} ${e}: invertY must be a boolean; got ${String(n.invertY)}`);return n}function U_(t,e){let n=Nm(e,"look()"),r=n.sensitivity,i=n.gamepadSensitivity,o=n.invertY,s=a=>o??a?.invertLookY??false;return {fromPointer(a,l,d,u){let c=Ii(a),g=Ii(l);if(c===0&&g===0)return ts;let p=t(),f=r??(p===null?void 0:p.lookSensitivity/100)??1,h=d==="touch"||d==="pen",R=h?De.touch:De.mouse,v=c*R.yaw*f,k=-g*R.pitch*f;return s(p)&&(k=-k),h&&u!==void 0&&Number.isFinite(u)&&k*u>0&&(k*=B_(u)),$m(v,k)},fromStick(a,l,d){let u=Ii(d);if(u<=0)return ts;let c=qm(a),g=qm(l);if(c===0&&g===0)return ts;let p=t(),f=i??(p===null?void 0:p.gamepadLookSensitivity/100)??1,h=c*De.stick.yaw*u*f,R=-g*De.stick.pitch*u*f;return s(p)&&(R=-R),$m(h,R)},set(a){let l=Nm(a,"set()");"sensitivity"in l&&(r=l.sensitivity),"gamepadSensitivity"in l&&(i=l.gamepadSensitivity),"invertY"in l&&(o=l.invertY);}}}function jm(t){return {look:e=>U_(t.recommended,e),LOOK_BASE:De}}var Bm=Object.freeze(["music","sfx","voice","eye","text","hint","speed","bright","controls","star"]),Um=/^[A-Za-z0-9_-]{1,40}$/;function ns(t){return typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=1e6}function Wm(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e.slice(0,40)}function Hm(t,e,n,r){let i=a=>Number.parseFloat(a.toPrecision(12)),o=Math.min(n,Math.max(e,t)),s=i(e+Math.round((o-e)/r)*r);return s>n&&(s=i(s-r)),Math.min(n,Math.max(e,s))}function Vm(t,e){switch(t.kind){case "toggle":return typeof e=="boolean"?e:void 0;case "slider":{if(typeof e!="number"||!Number.isFinite(e))return;let n=t.min??0,r=t.max??100;return Hm(e,n,r,t.step??1)}case "choice":return typeof e=="string"&&(t.options??[]).some(n=>n.id===e)?e:void 0;default:return}}function Km(t,e=()=>{}){if(!Array.isArray(t))return null;let n=[],r=0;for(let i=0;i<t.length;i+=1){let o=t[i],s=`settings[${i}]`;if(n.length===8){e(`${s} and later were left out: at most 8 settings are shown.`);break}if(typeof o!="object"||o===null){e(`${s} was dropped: a setting is an object.`);continue}let a=o,l=a.id;if(typeof l!="string"||!Um.test(l)){e(`${s} was dropped: its id must be 1 to 40 of A-Z a-z 0-9 _ -.`);continue}let d=`${s} (${JSON.stringify(l)})`;if(n.some(g=>g.id===l)){e(`${d} was dropped: an earlier setting has the same id.`);continue}let u=Wm(a.label);if(u===void 0){e(`${d} was dropped: its label is empty.`);continue}let c;switch(a.kind){case "toggle":{if(typeof a.value!="boolean"){e(`${d} was dropped: a toggle's value is true or false.`);continue}c={id:l,label:u,kind:"toggle",value:a.value},a.quick===true&&(r<2?(c.quick=true,r+=1):e(`${d} is not in the quick row: at most 2 toggles are, the first that ask.`));break}case "slider":{let g=a.min??0,p=a.max??100,f=a.step??1;if(!ns(g)||!ns(p)||!ns(f)||g>=p||f<=0){e(`${d} was dropped: a slider needs finite numbers within \xB11000000 with min below max and a step above 0.`);continue}if(typeof a.value!="number"||!Number.isFinite(a.value)){e(`${d} was dropped: a slider's value is a number.`);continue}c={id:l,label:u,kind:"slider",value:Hm(a.value,g,p,f),min:g,max:p,step:f};break}case "choice":{let g=[];for(let p of Array.isArray(a.options)?a.options:[]){if(g.length===4)break;if(typeof p!="object"||p===null)continue;let f=p,h=Wm(f.label);typeof f.id!="string"||!Um.test(f.id)||h===void 0||g.some(R=>R.id===f.id)||g.push({id:f.id,label:h});}if(g.length<2){e(`${d} was dropped: a choice needs 2 to 4 options, each with an id of 1 to 40 of A-Z a-z 0-9 _ - and a label.`);continue}if(typeof a.value!="string"||!g.some(p=>p.id===a.value)){e(`${d} was dropped: a choice's value is the id of one of its options.`);continue}c={id:l,label:u,kind:"choice",value:a.value,options:g};break}default:e(`${d} was dropped: its kind must be 'toggle', 'slider' or 'choice'.`);continue}a.icon!==void 0&&(Bm.includes(a.icon)?c.icon=a.icon:e(`${d} keeps the Arcade's generic icon: ${JSON.stringify(a.icon)} is not one of ${Bm.join(", ")}.`)),n.push(c);}return n}var W_=500;function Jm(t){let{clock:e}=t,n=null,r=null,i=-1/0,o=null,s=new Set,a=new Set,l=c=>{a.has(c)||(a.add(c),t.log!==null&&(t.log===void 0?console.warn(c):t.log(c)));},d=()=>{let c=t.frame();return c.currentState==="connected"&&c.parentSupports("gameSettings")},u=()=>{if(n===null||o!==null)return;let c=JSON.stringify(n);if(c===r)return;let g=i+W_-e.now();if(g>0){o=e.setTimeout(()=>{o=null,u();},g);return}t.frame().declareSettings(n)&&(r=c,i=e.now());};return {api:{declare(c){let g=Km(c,p=>l(`[gem] gem.settings.declare: ${p}`));return g===null?(l("[gem] gem.settings.declare did nothing: pass an array of settings, or [] for none."),false):(n=g,u(),d())},onChange(c){if(typeof c!="function")return ()=>{};let g=p=>c(p);return s.add(g),()=>{s.delete(g);}}},forgetSent(){r=null,i=-1/0;},flush:u,onSettingChange(c){let g=n?.findIndex(v=>v.id===c.id)??-1,p=n?.[g];if(n===null||p===void 0)return;let f=Vm(p,c.value);if(f===void 0)return;let h=JSON.stringify(n);n=n.map((v,k)=>k===g?{...v,value:f}:v),r===h&&(r=JSON.stringify(n));let R={id:p.id,value:f};for(let v of [...s])try{v(R);}catch(k){console.error("[gem] a gem.settings.onChange handler threw:",k);}}}}function zm(t,e){return t==null?e?"low":"medium":t==="low"||t==="high"?t:"medium"}var H_=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Xm(t){if(typeof t!="string"||!H_.test(t))return;let e=Date.parse(t);return Number.isFinite(e)&&e>0?e:void 0}function Wn(){return {declared:false,grantable:false,adGrantable:false,heldLimitReached:false}}var V_=new Set(["coins","gems"]);function K_(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(typeof n!="object"||n===null)continue;let r=n,{kind:i,currency_id:o,price:s}=r;!V_.has(i)||e.some(a=>a.kind===i)||typeof o!="string"||o.trim()===""||typeof s!="number"||!Number.isSafeInteger(s)||s<=0||e.push({kind:i,currencyId:o,price:s});}return e.length>0?e:void 0}function Ym(t,e){let n=typeof t=="object"&&t!==null?t:{},r=Xm(n.resets_at),i=r===void 0?{}:{resetsAt:r};if(n.declared!==true)return {...Wn(),...i};let o=n.remaining_today,s=typeof o=="number"&&Number.isFinite(o)&&o>=0?Math.floor(o):void 0,a=n.next_eligible_at,l=Xm(a),d=n.held_limit_reached===true,u=a!=null,c=o!=null&&s===void 0,g=K_(n.options),f=(n.ad_grantable!==void 0&&n.ad_grantable!==null?n.ad_grantable===true:n.grantable===true&&(n.options===void 0||n.options===null))&&n.grantable===true&&e&&s!==0&&!c&&!u&&!d,h=g!==void 0&&n.grantable===true&&e;return {declared:true,grantable:f||h,adGrantable:f,...g===void 0?{}:{options:g},...s===void 0?{}:{remainingToday:s},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...i}}var J_=18e4,rs=32,z_=/^[a-z0-9_-]+$/,X_="rewarded_requires_user_gesture";function Y_(){let t=globalThis.navigator?.userActivation?.isActive;return typeof t=="boolean"?t:void 0}var Q_=1e3;function Z_(){let t=globalThis,e=t.navigator?.getGamepads,n=t.performance?.now;if(typeof e!="function"||typeof n!="function")return;let r=n.call(t.performance),i=e.call(t.navigator);for(let o=0;o<i.length;o+=1){let s=i[o]?.timestamp;if(typeof s=="number"&&r-s>=0&&r-s<=Q_)return true}return false}var Qm=1e4;function ew(t){return t==="interstitial"||t==="rewarded"}function Zm(t){return typeof t=="string"&&t!==""&&t.length<=rs&&z_.test(t)}function tw(t){let e=typeof t=="object"&&t!==null?t:{};return [e.name,e.reason,e.status].join()}function Ci(t){return typeof t=="string"?JSON.stringify(t):typeof t}function ep(t){let e=false,n=new Map,r=new Map,i=new Set,o=d=>{try{t.onDropped?.(d);}catch{}},s=false,a=d=>{if(s)return;s=true;let u=t.log;if(u!==null)try{u===void 0?console.warn(`[gem] ${d}`):u(`[gem] ${d}`);}catch{}},l=d=>{let u=t.readAvailability;if(u===void 0)return Promise.resolve(Wn());let c=r.get(d);if(c!==void 0)return c;let g=new Promise(p=>{let f={},h=y=>f.done===true?false:(f.done=true,t.clock.clearTimeout(f.timer),p(y),true),R=(y,_)=>{!h(Wn())||i.has(y)||(i.add(y),o(`gem.ads.rewardedStatus("${d}") answered not grantable: ${_}. Said once.`));},v=y=>{R(tw(y),`the read failed (${y instanceof Error?y.message:Ci(y)})`);},k;try{k=Promise.resolve(u(d,AbortSignal.timeout(Qm)));}catch(y){k=Promise.reject(y);}f.timer=t.clock.setTimeout(()=>{R("timeout","no answer within 10 s");},Qm),k.then(y=>{try{h(Ym(y,t.bridge.parentSupports("ads")));}catch(_){v(_);}},v);});return r.set(d,g),g.then(()=>{r.get(d)===g&&r.delete(d);}),g};return {api:{rewardedStatus(d){return Zm(d)?l(d):(o(`gem.ads.rewardedStatus(${Ci(d)}) answered not grantable: a placement is 1..${String(rs)} characters of a-z, 0-9, '-' and '_'.`),Promise.resolve(Wn()))},requestAd(d){if(!t.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});let u=d?.placement,c=d?.format;if(!Zm(u)||!ew(c))return o(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${Ci(u)}, format ${Ci(c)}. A placement is 1..${String(rs)} 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"});if(c==="rewarded"){let p;try{p=(t.userActivation??Y_)();}catch{p=void 0;}if(p===false)try{(t.recentGamepadInput??Z_)()===!0&&(p=!0);}catch{}if(p===false){let f=`${X_}: gem.ads.requestAd("${u}", 'rewarded') answered no_ad without asking: the frame has no user activation and no controller input in the last second. Ask from the button's click, pointerup, touchend or keydown handler, or straight from a controller press, before any await or timer that can outlast the press. On a touchscreen, pointerdown and touchstart run before the tap counts.`;return o(f),a(f),Promise.resolve({outcome:"no_ad"})}}let g=`ad-${ue()}`;return new Promise(p=>{let f={},h=v=>{n.delete(g)&&(e=false,t.clock.clearTimeout(f.timer),p(v));};e=true,n.set(g,h),f.timer=t.clock.setTimeout(()=>{h({outcome:"unavailable"});},t.timeoutMs??J_);let R=false;try{R=t.bridge.requestAd(g,u,c);}catch{}R||h({outcome:"no_ad"});})}},settle(d){let u=d.outcome==="shown"||d.outcome==="no_ad"?d.outcome:"unavailable",c=n.get(d.requestId);if(c===void 0){t.onDropped?.(`gem.adResult (${u}) for an unknown requestId: `+JSON.stringify(d.requestId));return}c({outcome:u});}}}var tp=Object.freeze(["level_end","run_end","match_end","menu_return","other_break"]),np=18e4,nw=1e4,rw=/^[a-z0-9_-]{1,32}$/;function is(t){return typeof t=="string"?JSON.stringify(t):typeof t}var Hn=Object.freeze({shown:false});function rp(t){let e=new Map,n,r=false,i=o=>{try{t.onDropped?.(o);}catch{}return Hn};return {api:{signal(o){try{if(!t.bridge.parentSupports("moments"))return r?Promise.resolve(Hn):(r=!0,Promise.resolve(i("moments_unsupported: gem.moments.signal answered shown: false without asking: this arcade does not do platform moments. Keep the call; it costs nothing. Said once.")));let s=o?.kind,a=o?.placement,l=o?.wall;if(!tp.includes(s)||a!==void 0&&(typeof a!="string"||!rw.test(a))||l!==void 0&&typeof l!="boolean")return Promise.resolve(i(`moments_invalid_argument: gem.moments.signal was called with arguments the SDK will not send: kind ${is(s)}, placement ${is(a)}, wall ${is(l)}. A kind is one of ${tp.join(", ")}; a placement, when given, is 1..32 characters of a-z, 0-9, '-' and '_'; a wall, when given, is true or false. Answering shown: false.`));if(!t.bridge.readyCalled())return Promise.resolve(i(`moments_before_ready: gem.moments.signal({ kind: '${s}' }) before gem.frame.ready(): a moment is a break in play, and play has not started. Signal from the press that leaves a break, never on boot. Answering shown: false.`));if(e.size>0)return Promise.resolve(i(`moments_in_flight: gem.moments.signal({ kind: '${s}' }) while another moment is still waiting for its answer. Signal once per break, and await the answer before play resumes. Answering shown: false.`));let d=t.clock.now();if(n!==void 0&&d-n<nw)return Promise.resolve(i(`moments_called_repeatedly: gem.moments.signal({ kind: '${s}' }) within 10 s of the last moment's answer (${String(d-n)} ms). One break, one signal, from the press that leaves it; never on a timer. Answering shown: false.`));let u=`moment-${ue()}`;return new Promise(c=>{let g={},p=(h,R)=>{e.delete(u)&&(t.clock.clearTimeout(g.timer),R&&(n=t.clock.now()),c(h));};e.set(u,h=>p(h,!0)),g.timer=t.clock.setTimeout(()=>{e.has(u)&&(p(Hn,!0),i(`moments_timeout: gem.moments.signal({ kind: '${s}' }) had no answer within ${String((t.timeoutMs??np)/1e3)} s. Answering shown: false.`));},t.timeoutMs??np);let f=!1;try{f=t.bridge.signalMoment(u,s,a,l===!0?!0:void 0);}catch{}f||p(Hn,!1);})}catch{return Promise.resolve(Hn)}}},settle(o){let s=e.get(o.requestId);if(s===void 0){i(`gem.momentResult (shown: ${String(o.shown)}) for an unknown requestId: `+JSON.stringify(o.requestId));return}s({shown:o.shown===true});}}}var os=16384;function ip(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:iw(e)}function iw(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 i=t.charCodeAt(n+1);i>=56320&&i<=57343?(e+=4,n+=1):e+=3;}else e+=3;}return e}var ow=1e4,aw=5e3;function op(t){let e=null,n=false,r=[],i=new Map,o=()=>{for(let s of r.splice(0))s();};return {api:{get current(){return e},wait(s=aw){return n?Promise.resolve(e):new Promise(a=>{let l=()=>{let c=r.indexOf(d);c>=0&&r.splice(c,1);},d=()=>{t.clock.clearTimeout(u),l(),a(e);},u=t.clock.setTimeout(()=>{l(),a(e);},s);r.push(d);})},put(s){if(!t.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let a=ip(s);if(a===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(a>16384)return Promise.resolve("too_large");let l=JSON.parse(JSON.stringify(s)),d=`device-settings-${ue()}`;return new Promise(u=>{let c={},g=f=>{i.delete(d)&&(t.clock.clearTimeout(c.timer),f==="stored"&&(e=l,n=true,o()),u(f));};i.set(d,g),c.timer=t.clock.setTimeout(()=>g("unavailable"),t.timeoutMs??ow);let p=false;try{p=t.bridge.putDeviceSettings(d,l);}catch{}p||g("unavailable");})}},receive(s){let a=s.settings;e=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:null,n=true,o();},settle(s){let a=s.outcome==="stored"||s.outcome==="too_large"?s.outcome:"unavailable",l=i.get(s.requestId);if(l===void 0){t.onDropped?.(`gem.deviceSettings.result (${a}) for an unknown requestId: `+JSON.stringify(s.requestId));return}l(a);}}}var Vn=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";}};var sw=/^[a-z0-9][a-z0-9_-]{0,39}$/;function lw(t){return typeof t=="string"&&sw.test(t)}function Oi(t){if(t===null||lw(t))return t;let e=typeof t=="string"?JSON.stringify(t.length>48?`${t.slice(0,48)}\u2026`:t):`a value of type ${typeof t}`;console.warn(`[gem] showPortraitBorders: ${e} is not a border name, so nothing was sent. A name is 1 to 40 of a-z, 0-9, _ and -, starting with a letter or digit, exactly as your store page declares it under media.portrait_borders. Pass null for no art.`);}function ap(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function ss(t,e){if(t!==true)return {visible:false};let n=[],r=false;for(let i of Array.isArray(e)?e:[])i==="score"?r=true:typeof i=="string"&&i.length>0&&i.length<=64&&!n.includes(i)&&n.push(i);return !r&&n.length===0?{visible:true}:{visible:true,currencies:n.slice(0,8),score:r}}function Mi(t){let e=[];for(let n of Array.isArray(t)?t:[]){if(e.length===4)break;if(typeof n!="object"||n===null)continue;let{id:r,label:i}=n;typeof r!="string"||r.length===0||r.length>32||typeof i!="string"||i.trim().length===0||e.some(o=>o.id===r)||e.push({id:r,label:i.trim().slice(0,40)});}return e.length===0?{settings:false}:{settings:false,items:e}}function sp(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function dw(t){let e=t.untrusted,n=be(e.displayName,"gem.player.displayName"),r=e.displayTag||e.displayHandle,i=r?be(r,"gem.player.displayTag"):void 0,o=t.discriminator||t.displayTag,s=o&&/^[0-9]{1,8}$/.test(o)?o:void 0,a=t.avatarIconUrl||t.avatarUrl,l=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,d=t.avatarIconId,u=t.avatar3dId,c={displayName:n,displayHandle:i??n,badges:(t.badges??[]).map(h=>({itemId:h.itemId,iconUrl:h.iconUrl}))};t.playerId&&(c.playerId=t.playerId),s&&(c.discriminator=s),i&&(c.displayTag=i),a&&(c.avatarIconUrl=c.avatarUrl=a),d&&l.test(d)&&(c.avatarIconId=d),u&&l.test(u)&&(c.avatar3dId=u),t.avatar3dModelUrl&&(c.avatar3dModelUrl=t.avatar3dModelUrl),t.avatar3dIconUrl&&(c.avatar3dIconUrl=t.avatar3dIconUrl),t.avatars3d&&(c.avatars3d=t.avatars3d.filter(h=>l.test(h.id)&&/^[a-z][a-z0-9_]*$/.test(h.family)).filter((h,R,v)=>v.findIndex(k=>k.family==h.family)==R).map(({family:h,id:R,modelUrl:v,iconUrl:k})=>({family:h,id:R,modelUrl:v,iconUrl:k})));let g=t.boost,p=(g?.multipliers??[]).map(h=>({currencyId:h.currencyId,currencySlug:h.currencySlug,multiplier:h.multiplierBp/1e4})),f=p.some(h=>h.multiplier>1);return c.boost=f&&g?.expiresInDays?{active:f,multipliers:p,expiresInDays:g.expiresInDays}:{active:f,multipliers:p},c}var cw=1e4,uw=["appLinks","openGame","store","storeOfferSheet"],mw=["token","pause","menuSelect","settingChange","prefs","cohorts","viewport","willTerminate","localServer","roomEvent","seatedEvent","autoStartFailedEvent","ticketEvent","socketState","signalEvent","relayDraining","dedicatedEvent","clusterTarget","graphicsRoutes","partyResult","purchaseResult","purchaseSettled","inventoryChanged","shareResult","deviceSettings","adResult","momentResult","signInResult","friendChallengeResult","playInviteResult"],as=new WeakMap;function dp(t,e){if(as.has(t))throw new Error("admitBuildEmbedders: already admitted");as.set(t,Object.freeze([...e]));}var Kn=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??ce,this.inbound=new rn(this.clock),this.outbound=new rn(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];unbidden=false;engagedSent=false;readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}get unbiddenLaunch(){return this.unbidden}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(a=>Pt(a,e.origin))||vr(e.origin,this.options.selfOrigin)||(as.get(this)??[]).some(a=>Pt(a,e.origin))))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=br["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!Pt(i.embedder,e.origin))return this.refuse(e,`handshake claims embedder '${i.embedder}' but arrived from '${e.origin}'`),false;let o=e.ports?.[0];if(!o)return this.refuse(e,"handshake transferred no MessagePort"),false;let s=rd(fr,i.versions);return s===null?(o.onmessage=null,o.postMessage({gem:j,type:"gem.error",code:"version_mismatch",message:`frame supports v${fr.min}..v${fr.max}`}),o.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=o,this.version=s,o.onmessage=a=>this.receive(a.data,a.ports??[]),o.start?.(),this.peerCapabilities=i.capabilities??[],this.unbidden=i.unbidden===true,o.postMessage({gem:j,type:"gem.handshake.accept",v:s,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:j,type:"gem.ready"});}settled(e=cw){return this.state!=="waiting"?Promise.resolve(this.state):new Promise(n=>{let r=o=>{this.clock.clearTimeout(i),n(o);},i=this.clock.setTimeout(()=>{let o=this.settleWaiters.indexOf(r);o>=0&&this.settleWaiters.splice(o,1),n(this.state);},e);this.settleWaiters.push(r);})}progress(e,n){this.send({gem:j,type:"gem.progress",loaded:e,total:n});}requestToken(e,n){this.send({gem:j,type:"gem.requestToken",requestId:e,reason:n});}requestLocalServer(e,n){return this.parentSupports("localHost")?(this.send({gem:j,type:"gem.requestLocalServer",requestId:e,gameRoomId:n}),true):false}exit(e){this.send(e===void 0?{gem:j,type:"gem.exit"}:{gem:j,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:j,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:j,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.gated("audioState")?(this.send({gem:j,type:"gem.audioState",muted:e}),true):false}reportEngaged(){return this.engagedSent||!this.gated("engagement")||!this.send({gem:j,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(!this.gated("rewardCue"))return false;let n={gem:j,type:"gem.rewardCue",currencySlug:String(e.currencySlug).slice(0,32)};return Po(e.cueId)&&(n.cueId=e.cueId),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:ap(e.origin.x),y:ap(e.origin.y)}),this.send(n),true}showPortraitBorders(e){let n=Oi(e);return n===void 0||!this.gated("portraitBorders")?false:this.send(n===null?{gem:j,type:"gem.portraitBorders"}:{gem:j,type:"gem.portraitBorders",name:n})}setWalletVisible(e,n){return this.gated("walletDisplay")?this.send({gem:j,type:"gem.walletDisplay",...ss(e,n?.only)}):false}setMenu(e){return this.gated("gameMenu")?this.send({gem:j,type:"gem.menu",...Mi(e)}):false}declareSettings(e){return this.gated("gameSettings")?this.send({gem:j,type:"gem.settingsDeclare",settings:e}):false}setGemCorner(e){return this.gated("gemCorner")?this.send({gem:j,type:"gem.gemCorner",corner:e}):false}setRewardPresentation(e){return this.gated("rewardPresentation")?this.send({gem:j,type:"gem.rewardPresentation",mode:e}):false}setMenuStyle(e){return this.gated("menuStyle")?this.send(e===null?{gem:j,type:"gem.menuStyle"}:{gem:j,type:"gem.menuStyle",ground:e.ground,accent:e.accent}):false}requestShare(e,n){return this.gated("share")?this.send({gem:j,type:"gem.requestShare",...n===void 0?{}:{requestId:n},params:e.map(({key:r,value:i})=>({key:r,value:i}))}):false}requestAvatarPicker(e){return this.gated("avatarPicker")?this.send({gem:j,type:"gem.requestAvatarPicker",...e==="2d"||e==="3d"?{tab:e}:{}}):false}requestVibrate(e){return this.gated("vibration")?this.send({gem:j,type:"gem.vibrate",pattern:[...e]}):false}reportFrameStats(e){return this.gated("frameStats")?(this.send({gem:j,type:"gem.frameStats",fps:sp(e.fps,1e3),frameTimeP95Ms:sp(e.frameTimeP95Ms,1e5),counts:e.counts==="gameDraws"?"gameDraws":"pageFrames"}),true):false}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:j,type:"gem.gameContext",context:e}),true)}signal(e,n,r){this.send({gem:j,type:"gem.signal",signal:e,matchId:n,data:r});}dedicatedOffer(e,n,r){this.send({gem:j,type:"gem.dedicatedOffer",matchId:e,sdp:n,intent:r});}requestParty(e){return this.send({gem:j,type:"gem.partyRequest",requestId:e})}requestPurchase(e,n,r,i,o,s,a){return this.send({gem:j,type:"gem.requestPurchase",requestId:e,purchaseKind:n,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...s===void 0?{}:{catalogId:s},...a===void 0?{}:{origin:a}})}requestAvatar3dPurchase(e,n,r){return this.parentSupports("avatar3dPurchases")?this.send({gem:j,type:"gem.requestAvatar3dPurchase",requestId:e,itemId:n,currencySlug:r}):false}putDeviceSettings(e,n){return this.send({gem:j,type:"gem.deviceSettings.put",requestId:e,settings:n})}requestAd(e,n,r){return this.send({gem:j,type:"gem.requestAd",requestId:e,placement:n,format:r})}signalMoment(e,n,r,i){return this.send({gem:j,type:"gem.signalMoment",requestId:e,kind:n,...r===void 0?{}:{placement:r},...i===true?{wall:true}:{}})}readyCalled(){return this.readySent||this.readyPending}requestSignIn(e){return this.send({gem:j,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,n,r,i){return this.send({gem:j,type:"gem.requestFriendChallenge",requestId:e,playerId:n,template:r,...i===void 0?{}:{params:i}})}requestArcade(e){return this.gated(hr(e.type))&&this.send({gem:j,...e})}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(yr)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(yr)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(yr)&&this.options.onRefused?.(n);}fail(e,n){this.options.onError?.(e,n),this.state==="connected"&&this.port&&this.send({gem:j,type:"gem.error",code:e,...n===void 0?{}:{message:n}});}gated(e){return this.state==="connected"&&this.parentSupports(e)}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=br[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||lp(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 i=br[r];if(!i)return this.dropUnknownType(r),false;if(!this.inbound.allow(r))return this.fail("rate_limited",`parent exceeded the limit for ${r}`),false;let o=hr(r);if(o!==void 0&&!this.options.capabilities?.includes(o))return this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this frame did not advertise`),false;let s=i(e);if(s)return this.fail("invalid_message",`${r}: ${s}`),false;let a=e;if(a.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.devtools":this.options.onDevtools?.(a.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:a.maxWidth,maxHeight:a.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return lp(n.slice(1)),this.options.onScreenshot(d,l,(u,c)=>this.screenshotDenied(u,c)),true}case "gem.token.denied":this.options.onTokenDenied?.(a);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(a);break;case "gem.player":{this.options.onPlayer?.(dw(a));break}case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(a);break;case "gem.error":this.options.onError?.(a.code,a.message);break;default:if(mw.includes(r.slice(4))){this.options[`on${r[4].toUpperCase()}${r.slice(5)}`]?.(a);break}if(uw.includes(hr(r))){this.options.onArcadeAnswer?.(a);break}this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,n){this.send({gem:j,type:"gem.screenshot.denied",reason:e,retryable:n});}};function lp(t){for(let e of t)try{e?.close?.();}catch{}}var cp="https://api.gemarcade.com";function ls(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 pw=new Set(["localhost","127.0.0.1","[::1]"]);function up(t){let e=ls(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!pw.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 gp="/gem-embedders.json",Gi=4096,mp=16,pp=5e3,Jn=Object.freeze({origins:Object.freeze([])});function et(t){return {origins:[],refused:`[gem] ${gp} was ignored: ${t}`}}function gw(t){if(t.trim()==="")return Jn;let e;try{e=JSON.parse(t);}catch{return et("it is not JSON.")}if(e===null||typeof e!="object"||Array.isArray(e))return et('it must be an object, { "embedders": [...] }.');let n=e.embedders;if(n===void 0)return Jn;if(!Array.isArray(n))return et('"embedders" must be an array of origins.');if(n.length>mp)return et(`"embedders" has more than ${mp} entries.`);let r=n.filter(i=>typeof i!="string"||!xt(i)||!i.toLowerCase().startsWith("https://")||Je(new URL(i).hostname));if(r.length>0){let i=r.slice(0,3).map(o=>typeof o=="string"?JSON.stringify(o.slice(0,100)):String(o)).join(", ");return et(`${r.length===1?"an entry is":"entries are"} not an https origin off this machine (${i}${r.length>3?", \u2026":""}).`)}return {origins:Object.freeze([...new Set(n)])}}async function fp(t){let e=typeof AbortController=="function"?new AbortController:null,n,r=new Promise(o=>{n=t.clock.setTimeout(()=>{e?.abort(),o(et(`it took more than ${pp} ms to read.`));},pp);}),i=(async()=>{let o=await t.fetch(t.selfOrigin+gp,{credentials:"omit",redirect:"error",...e?{signal:e.signal}:{}});if(!o.ok||(o.headers.get("content-type")??"").toLowerCase().includes("text/html"))return Jn;if(Number(o.headers.get("content-length"))>Gi)return et(`it is larger than ${Gi} bytes.`);let a=await o.text();return a.length>Gi?et(`it is larger than ${Gi} bytes.`):gw(a)})().catch(()=>Jn);try{return await Promise.race([i,r])}finally{t.clock.clearTimeout(n);}}function yp(t){if(typeof t!="string"||!xt(t))return null;let e=t.slice(0,t.indexOf(":")).toLowerCase();return e==="https"||e==="http"?t:null}function hp(t){return Object.freeze(t.map(([e,n])=>Object.freeze({node:e,parent:n})))}function fw(){let t=[["root",null],["hips","root"],["spine","hips"],["chest","spine"],["upper_chest","chest"],["neck","upper_chest"],["head","neck"],["head_socket","head"]];for(let e of ["l","r"]){let n=r=>`${r}_${e}`;t.push([n("shoulder"),"upper_chest"],[n("upper_arm"),n("shoulder")],[n("lower_arm"),n("upper_arm")],[n("hand"),n("lower_arm")],[n("hand_socket"),n("hand")]);for(let r of ["thumb","index","middle","ring","little"])for(let i=1;i<=3;i++)t.push([n(`${r}_${i}`),n(i===1?"hand":`${r}_${i-1}`)]);}for(let e of ["l","r"]){let n=r=>`${r}_${e}`;t.push([n("upper_leg"),"hips"],[n("lower_leg"),n("upper_leg")],[n("foot"),n("lower_leg")],[n("toes"),n("foot")]);}return t}var yw=Object.freeze({small_human:hp([["root",null],["body","root"],["head","body"],["arm_l","body"],["arm_r","body"],["hand_socket","arm_r"],["leg_l","body"],["leg_r","body"]]),adult_human:hp(fw())});var bw=Object.freeze(["https://gemarcade.com","https://developer.gemarcade.com","http://gemarcade.localhost","gemarcade://localhost","https://app.gemarcade.com"]),vw=cp,_w=["top-left","top-right","bottom-left","bottom-right"],ww=["arcade","game"];function bp(t){let e=[1,3,5].map(n=>{let r=parseInt(t.slice(n,n+2),16)/255;return r<=.03928?r/12.92:((r+.055)/1.055)**2.4});return .2126*e[0]+.7152*e[1]+.0722*e[2]}function Sw(t){if(t===null)return null;let{ground:e,accent:n}=Object(t);for(let[s,a]of [["ground",e],["accent",n]]){if(typeof a=="string"&&/^#[0-9a-fA-F]{6}$/.test(a))continue;let l=typeof a=="string"?JSON.stringify(a.slice(0,48)):`a value of type ${typeof a}`;console.warn(`[gem] setMenuStyle: ${s} is ${l}, which is not #rrggbb, so nothing was sent.`);return}let r={ground:e.toLowerCase(),accent:n.toLowerCase()},i=[bp(r.ground),bp(r.accent)],o=(Math.max(...i)+.05)/(Math.min(...i)+.05);if(o>=3)return r;console.warn(`[gem] setMenuStyle: accent ${r.accent} reaches ${Math.floor(o*100)/100}:1 against ground ${r.ground}, under the 3:1 it needs, so nothing was sent.`);}var vp=8e3,Li=15e3,Rw=9e4,kw=1/0,Aw=8e3,xw=5e3,Pw=5e3;async function Ew(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 zn(t){let e=null,n=false,r=[];return {get current(){return e},set(i){e=i;for(let o of r.splice(0))o(i);},release(){n=true;for(let i of r.splice(0))i(e);},wait(i){return e!==null||n?Promise.resolve(e):new Promise(o=>{let s=()=>{let d=r.indexOf(a);d>=0&&r.splice(d,1);},a=d=>{t.clearTimeout(l),s(),o(d);},l=t.setTimeout(()=>{s(),o(e);},i);r.push(a);})}}}function Tw(t){return typeof t=="number"&&Number.isInteger(t)&&t>=100&&t<=200?t:null}function vC(t={}){let e=t.clock??ce,n=t.log===void 0?m=>console.info(m):t.log,r=t.baseUrl??void 0;if(r!=null){let m=ls(r);if(m!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${m}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let i=typeof window>"u"?void 0:window.location?.search,o=Nd(i),s=bc(i),a=mu(i),l=Aa();l.mark("sdk created");let d=()=>Yr(se.gameVersion,t.clientVersion?.gameVersion),u=new bn({client:()=>kt,clock:e,gameId:()=>se.identity?.gameId??null,playerId:()=>se.identity?.playerId??null,awaitPlayerId:async()=>(await dr(Li)).playerId,declarations:async()=>(await sr.load())?.analytics_events,environment:()=>{let m=d();return {sdk_version:Gs(),...m===null?{}:{game_version:m}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),c=lu(()=>{l.mark("engaged"),u.release(),D.reportEngaged();},typeof window>"u"?{}:window),g=m=>{if(m===false)return null;let E=m?.attempts??kw,F=m?.budgetMs??Rw;return !(E>0)||!(F>0)?null:{attempts:E,budgetMs:F,maxDelayMs:m?.maxDelayMs??Aw}},p=m=>{m.on("created",()=>{l.mark("room created");}),m.on("joined",()=>{l.mark("room joined");}),m.on("matchAllocationStarted",()=>{l.mark("allocation started");}),m.on("matchReady",()=>{l.mark("match ready");}),m.on("matchFailed",()=>{l.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 Vn;let f=t.allowedEmbedders;if(f!=null&&!Array.isArray(f))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 h=Array.from(f??[]),R=h.filter(m=>typeof m!="string"||!xt(m));if(R.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${R.length===1?"an entry":"entries"} that ${R.length===1?"is":"are"} not an origin: ${R.map(m=>typeof m=="string"?JSON.stringify(m):String(m)).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 v=Object.freeze([...new Set([...bw,...h])]),k=zn(e),y=new Set,_=zn(e),I=false,T=zn(e),H=Yd(n),q={},W=zn(e),C=t.manageAudio===false?null:xu();t.selectableText!==true&&Pu(),t.onScreenshot===void 0&&fu(window);let L=null,$=null,U=null,x=null,G=false,re=()=>{L===null||L===$||D.reportMuted(L)&&($=L);},pe,Q,tt=-1/0,we=null,Ae=()=>{if(pe===void 0||we!==null||pe===Q)return;let m=tt+1e3-e.now();if(m>0){we=e.setTimeout(()=>{we=null,Ae();},m);return}D.showPortraitBorders(pe)&&(Q=pe,tt=e.now());},xe=null,te=null,X=()=>{if(xe===null)return false;let m=JSON.stringify(ss(xe.visible,xe.only));return m===te?D.parentSupports("walletDisplay"):D.setWalletVisible(xe.visible,xe)?(te=m,true):false},ne=null,Ie=null,Ue=()=>{if(ne===null)return false;let m=JSON.stringify(Mi(ne.items));return m===Ie?D.parentSupports("gameMenu"):D.setMenu(ne.items)?(Ie=m,true):false},Ce=null,Jt=null,We=null,_t=null,He,zt=null,nt=Jm({frame:()=>D,clock:e,log:t.log}),b=Xd(()=>D),M=()=>Ce===null?false:Ce===Jt?D.parentSupports("gemCorner"):D.setGemCorner(Ce)?(Jt=Ce,true):false,B=()=>We===null?false:We===_t?D.parentSupports("rewardPresentation"):D.setRewardPresentation(We)?(_t=We,true):false,Z=()=>{if(He===void 0)return false;let m=JSON.stringify(He);return m===zt?D.parentSupports("menuStyle"):D.setMenuStyle(He)?(zt=m,true):false},ye=Eu({report:m=>D.reportFrameStats(m)}),rt=false,Fe=Lu(()=>Is,()=>rt),wt=m=>{let E=rt&&!m,F=rt!==m;if(rt=m,E&&Fe.close(),!!F)try{t.onDevToolsPermissionChange?.(m);}catch(ee){n?.(`[gem] onDevToolsPermissionChange threw: ${ee instanceof Error?ee.message:String(ee)}`),queueMicrotask(()=>{throw ee});}},Xn=r??vw,Rp=r!==void 0,Di,Fi=m=>(n?.(`[gem] token refused: ${m}`),t.onError?.("internal",m),false),kp=(m,E)=>{if(m===void 0)return E!==void 0?Fi("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=up(m);return F!==null?Fi(`the embedder named an API root that cannot be used: ${F}. Its value is withheld here rather than written to logs.`):Di!==void 0&&Di!==m?Fi("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."):(Di=m,Rp||(Xn=m),true)},St=window.location?.origin,$i=null,cs=-1/0,Ap=2e3,Yn=new Set,xp=m=>$i!==false?Promise.resolve(true):new Promise(E=>{let F=e.setTimeout(()=>{Yn.delete(ee),E(false);},m),ee=()=>{e.clearTimeout(F),Yn.delete(ee),E(true);};Yn.add(ee);}),qi=()=>{},Ni=null,Qn=()=>{},Zn=xm(e),ji=km(e),us=pu({bridge:{settled:m=>D.settled(m),parentSupports:m=>D.parentSupports(m)},clock:e,forced:a,log:n}),D=new Kn({allowedEmbedders:v,...typeof St=="string"&&St!==""?{selfOrigin:St}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","ticketEvents","clusterTarget","graphicsRoutes","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","rewardPresentation","portraitBorders","earnAllowance","inventoryChanged","share","shareResult","shareRemap","avatarPicker","vibration","frameStats","walletDisplay","gameMenu","gemCorner","menuStyle","gameSettings","engagement","reservedAreas","p2pRelayDrain","viewport","purchases","purchaseSettled","avatar3dPurchases","deviceSettings","ads","moments","signIn","friendChallenges","appLinks","openGame","store","storeOfferSheet","playInvites",...t.onFeedbackContext!==void 0?["feedbackContext"]:[],...t.onAudioChannels!==void 0?["audioChannels"]:[],...t.onTextScale!==void 0?["textScale"]:[]],onRefused:m=>{Ni=m,t.onRefused?.(m);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:m=>{se.onBridgeState(m),m!=="connected"&&Zn.abandon(),m!=="connected"&&ji.abandon(),m!=="connected"&&ye.setRequested(false),$=null,te=null,Ie=null,Jt=null,_t=null,zt=null,nt.forgetSent(),b.forgetSent(),Q=void 0,m==="refused"&&(console.error("[gem] this game refused the page that framed it"+(Ni===null?"":` (${Ni})`)+", 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."),qi()),m==="connected"&&(l.mark("bridge connected"),Pp(),re(),Ae(),X(),Ue(),M(),B(),Z(),nt.flush(),b.flush(),D.unbiddenLaunch&&!c.engaged&&u.hold(),u.startSession(),c.engaged&&D.reportEngaged()),t.onStateChange?.(m);},onPlayer:m=>{k.set(m);for(let E of [...y])E(m);t.onPlayer?.(m);},onPrefs:m=>{let E={reducedMotion:m.reducedMotion,muted:m.muted,locale:m.locale,showFrameStats:m.showFrameStats===true,music:m.music!==false,sounds:m.sounds!==false,recommended:m.recommended===void 0?null:Object.freeze({volume:m.recommended.volume,batterySaver:m.recommended.batterySaver,keyboardLayout:m.recommended.keyboardLayout,gamepadConfirm:m.recommended.gamepadConfirm,vibration:m.recommended.vibration,lookSensitivity:m.recommended.lookSensitivity??100,gamepadLookSensitivity:m.recommended.gamepadLookSensitivity??100,invertLookY:m.recommended.invertLookY??false,touchMovement:m.recommended.touchMovement==="fixed"?"fixed":"floating",graphicsQuality:zm(m.recommended.graphicsQuality,m.recommended.batterySaver),graphicsQualityAuto:m.recommended.graphicsQualityAuto??true,colorHelp:typeof m.recommended.colorHelp=="boolean"?m.recommended.colorHelp:null,textScale:Tw(m.recommended.textScale)})};_.set(E),$=E.muted,C?.setMuted(E.muted),ye.setRequested(E.showFrameStats&&D.parentSupports("frameStats")),t.onPrefs?.(E),t.onAudioChannels!==void 0&&(U===null||U.music!==E.music||U.sounds!==E.sounds)&&(U=Object.freeze({music:E.music,sounds:E.sounds}),t.onAudioChannels(U));let F=E.recommended?.textScale??null;t.onTextScale!==void 0&&(!G||F!==x)&&(G=true,x=F,t.onTextScale(F));},onCohorts:m=>{let E=Object.freeze(m.cohorts.map(F=>Object.freeze({experimentId:F.experimentId,variantKey:F.variantKey})));T.set(E),t.onCohorts?.(E);},onEarnAllowanceChanged:()=>H.emit(),onInventoryChanged:()=>q.drop?.(),onViewport:m=>{let E=Object.freeze({insets:Object.freeze({top:m.insets.top,right:m.insets.right,bottom:m.insets.bottom,left:m.insets.left}),reserved:Object.freeze((m.reserved??[]).map(({x:ee,y:Cs,width:Os,height:Ms,control:Qt})=>Object.freeze(Qt?{x:ee,y:Cs,width:Os,height:Ms,control:Object.freeze({x:Qt.x,y:Qt.y,width:Qt.width,height:Qt.height})}:{x:ee,y:Cs,width:Os,height:Ms})))});W.set(E);let F=Iu();Cu(F,E.insets),Mu(F,E.reserved,Ou()),t.onViewport?.(E);},onPause:m=>{m.paused||Qn(),I=m.paused,C?.setPaused?.(m.paused),u.setPaused(m.paused),ye.setPaused(m.paused),t.onPause?.(m.paused);},onSettingChange:m=>nt.onSettingChange(m),onMenuSelect:m=>{ne===null||m.entry!=="item"||!(Mi(ne.items).items??[]).some(F=>F.id===m.id)||ne.items?.find(F=>F.id===m.id)?.onSelect?.();},onWillTerminate:m=>{u.endSession(m.reason),t.onWillTerminate?.({reason:m.reason,graceMs:m.graceMs});},onToken:m=>{let E=m.garden;if(wt(m.allowDevTools===true),!kp(m.apiBaseUrl,E))return;let F=m;se.onToken(F);let ee=se.identity;ee&&(Bi.set(ee),ps||(ps=true,ge.reconcileSeats().catch(()=>{}))),gs.push({token:F.token,expiresAt:F.expiresAt});},onTokenDenied:m=>{wt(false),se.onDenied(m);},onScreenshot:(m,E,F)=>{Su(m,E,F,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{Ru(D,t.onFeedbackContext);},onDevtools:m=>{m==="close"?Fe.close():m==="open"?Fe.openFrom("platform").catch(()=>{}):Fe.isOpen?Fe.close():Fe.openFrom("platform").catch(()=>{});},onRoomEvent:m=>ge.handleRoomEvent({event:m.event,roomId:m.roomId,...m.matchId===void 0?{}:{matchId:m.matchId},...m.version===void 0?{}:{version:m.version},...m.reason===void 0?{}:{reason:m.reason},...m.platform===void 0?{}:{platform:m.platform}}),onSeatedEvent:m=>ge.handleSeated(m.roomId),onAutoStartFailedEvent:m=>ge.handleAutoStartFailed(m.roomId,m.code),onTicketEvent:m=>ge.handleTicketEvent({event:m.event,ticketId:m.ticketId,...m.partySize===void 0?{}:{partySize:m.partySize},...m.queuedAt===void 0?{}:{queuedAt:m.queuedAt},...m.expiresAt===void 0?{}:{expiresAt:m.expiresAt},...m.reason===void 0?{}:{reason:m.reason},...m.roomId===void 0?{}:{roomId:m.roomId}}),onSocketState:m=>{let E=$i;if($i=m.connected,m.connected)for(let ee of [...Yn])ee();if(!m.connected||E===true)return;let F=e.now();F-cs<Ap||(cs=F,ge.reconcile().catch(()=>{}));},onSignalEvent:m=>{let E=typeof m.data=="object"&&m.data!==null&&!Array.isArray(m.data)?m.data:{};ot.handleSignalEvent(m.matchId,m.event,E),m.event==="matchEnded"&&ge.reconcile({matchId:m.matchId,...typeof E.reason=="string"?{reason:E.reason}:{}}).catch(()=>{});},onRelayDraining:m=>{ot.handleSignalEvent(m.matchId,"relayDraining",{clusterTargetId:m.clusterTargetId,relayIps:m.relayIps,drainingSince:m.drainingSince,deadline:m.deadline});},onDedicatedEvent:m=>{m.event==="matchEnded"&&(Yt.handleMatchEnded(m.matchId,m.reason),ge.reconcile({matchId:m.matchId,...m.reason===void 0?{}:{reason:m.reason}}).catch(()=>{})),ms.handleEvent(m);},onClusterTarget:m=>nr.accept(m.clusterTargetId,m.clusterTargetIds),onGraphicsRoutes:m=>us.accept(m.entries),onLocalServer:m=>rr.accept(m),onLocalServerDenied:m=>rr.refuse(m),onPartyResult:m=>ys.settle(m.requestId,m.partyId),onPurchaseResult:m=>Xt.settle(m),onPurchaseSettled:m=>Xt.settled(m),onShareResult:m=>ji.settle(m),onDeviceSettings:m=>{tr.receive(m),t.onDeviceSettings?.(tr.api.current);},onDeviceSettingsResult:m=>tr.settle(m),onAdResult:m=>bs.settle(m),onMomentResult:m=>vs.settle(m),onSignInResult:m=>{m.outcome==="signed_in"&&Qn(),_s.settle(m);},onFriendChallengeResult:m=>Rs.settle(m),onArcadeAnswer:m=>{m.type==="gem.storePurchaseSettled"?Ss.settled(m):Tp(m);},onPlayInviteResult:m=>ks.settle(m)}),ms=new Nn({bridge:D}),Bi=zn(e);qi=()=>{Bi.release(),k.release(),T.release();},D.currentState==="refused"&&qi();let ps=false,Ui=new Set,er,gs={current:()=>er,subscribe:m=>(Ui.add(m),er!==void 0&&m(er),()=>Ui.delete(m)),push:m=>{er=m;for(let E of [...Ui])try{E(m);}catch(F){n?.(`[gem] a server-token listener threw: ${F instanceof Error?F.message:String(F)}`);}}},se=Fu({bridge:D,clock:e,onStateChange:(m,E)=>{if(m==="ready"){if(l.mark("token ready")){let F=l.marks.find(ee=>ee.name==="token ready")?.at;u.trackPlatform("gem_boot_ready",F===void 0?{}:{boot_ms:Math.max(0,Math.round(F))});}}else m==="lost"&&(l.mark("token lost"),u.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(m,E);}}),fs=()=>{let m=se.identity;return !m||se.source.currentState==="lost"?null:`${m.playerId}\0${m.gameId}\0${m.channel}`},Pp=()=>{l.mark("token requested"),se.source.get().catch(()=>{});},ys=fm({bridge:D,clock:e}),Rt={},Xt=ym({bridge:D,clock:e,onDropped:m=>t.onError?.("internal",m),confirm:async m=>Rt.confirm?.(m)??"unknown",confirmAvatar3d:async m=>Rt.confirmAvatar3d?.(m)??"unknown",onInventoryStale:()=>Rt.inventoryStale?.(),onListenerError:m=>t.onError?.("internal",`gem.purchases.onSettled listener threw: ${String(m)}`)}),tr=op({bridge:D,clock:e,onDropped:m=>t.onError?.("internal",m)}),hs={},bs=ep({bridge:D,clock:e,onDropped:m=>t.onError?.("internal",m),readAvailability:(m,E)=>hs.read?.(m,E)??Promise.reject(new Error("the gem-api client is not built yet")),log:t.log}),vs=rp({bridge:D,clock:e,onDropped:m=>t.onError?.("internal",m)}),_s=Rm({bridge:D,clock:e,onDropped:m=>t.onError?.("internal",m)}),ws={held:false},Ep=Pm({bridge:D,asker:Zn,acting:ws}),Ss=Tm({bridge:D,asker:Zn,acting:ws,onListenerError:m=>t.onError?.("internal",`gem.store.onSettled listener threw: ${String(m)}`),onPurchaseEnded:()=>Qn()}),Tp=m=>{Zn.settle(m)||t.onError?.("internal",`${m.type} (${m.outcome}) for an unknown requestId: `+JSON.stringify(m.requestId));},Rs=Hd({bridge:D,clock:e,onDropped:m=>t.onError?.("internal",m)}),ks=zd({bridge:D,clock:e,onDropped:m=>t.onError?.("internal",m)}),nr=oc({bridge:D,clock:e}),rr=Gu({bridge:D,clock:e}),Wi=yp(St),As=window.fetch,ir=Wi!==null&&typeof As=="function"?"unread":"read",or=null,Hi=false,Ip=m=>{if(ir==="read"||m.source!==window.parent)return false;let E=m.origin;return typeof E!="string"||v.some(F=>Pt(F,E))||vr(E,typeof St=="string"?St:void 0)?false:((or===null||!Hi)&&(or=m),ir==="unread"&&Wi!==null&&(ir="reading",fp({fetch:(F,ee)=>As.call(window,F,ee),selfOrigin:Wi,clock:e}).then(F=>{"refused"in F&&n?.(F.refused),F.origins.length>0&&dp(D,F.origins),ir="read";let ee=or;or=null,ee!==null&&D.currentState==="waiting"&&ar(ee);})),true)},ar=m=>{if(Ip(m))return false;let E=D.handleWindowMessage({data:m.data,origin:m.origin,source:m.source,ports:m.ports});return E&&window.removeEventListener("message",ar),E};window.addEventListener("message",ar),Hi=true;let it;try{it=du(window,ar);}finally{Hi=false;}let Cp=it?.capture,Vi=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];Vi?.domInteractive!==void 0&&Vi.domInteractive>0&&l.mark("document parsed",Vi.domInteractive),Cp?.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 Ki=t.handshakeWarningMs;Ki!==null&&n&&e.setTimeout(()=>{let m=it===null?"no capture script ran":`capture: ${it.delivered} offer(s) delivered, ${it.stale} stale, ${it.capture.dropped} evicted${it.capture.late?", installed late":""}`;if(D.currentState==="connected"){n(`[gem] handshake connected. boot: ${l.timeline()} \xB7 ${m}`);return}n(`[gem] no completed handshake after ${Ki??vp}ms (bridge state: ${D.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: ${l.timeline()} \xB7 `+m);},Ki??vp);let Op=Pr({get baseUrl(){return Xn},tokenSource:se.source,get defaultQuery(){let m=se.identity;return m?{game_id:m.gameId,channel:m.channel}:{}}}),kt=new Ve({transport:Op,clock:e}),he={client:kt,gameId:()=>se.identity?.gameId??""};Rt.confirm=m=>hm(he,m),Rt.confirmAvatar3d=m=>wm(he,m),hs.read=(m,E)=>Vl(he,"players","me",m,{signal:E});let Mp=()=>se.identity?.channel??"release",sr=new Fr(he,Mp),Gp=_m({player:()=>k.current,subscribe:m=>(y.add(m),()=>{y.delete(m);}),configFamilies:async()=>(await sr.load())?.avatar_3d_families,readOffers:()=>Sm(he),purchase:m=>Xt.requestAvatar3d(m),log:t.log}),xs=async m=>(await sr.load())?.currency(m)?.id??void 0,Ps=wd(he,po,{identity:fs,resolveCurrencyId:xs,watch:{clock:e,log:t.log},handOffRefusedPurchase:m=>Xt.handOffRefused(m)}),lr=Ps.scope;Rt.inventoryStale=()=>lr.inventory.refresh(),Qn=Ps.recheckPasses;let dr=async m=>{let E=await Bi.wait(m);if(E)return E;throw D.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).")},Ji=g(t.autoReconnect),ge=Dc(s===void 0?{}:{playWithTicket:s},{client:kt,clock:e,gameId:()=>se.identity?.gameId??null,playerId:()=>se.identity?.playerId??null,awaitGameId:async()=>(await dr(Li)).gameId,resolveParty:ys.resolve,resolveClusterTargets:nr.resolveList,refreshClusterTargets:nr.refresh,ensureLocalServer:rr.ensure,localHostAvailable:rr.available,...t.clientVersion===void 0?{}:{clientVersion:t.clientVersion},platformGameVersion:()=>se.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},...Ji===null?{}:{autoReconnect:{...Ji,redial:(m,E)=>zi.redialMatch(m,E),abandon:(m,E)=>zi.abandonMatch(m,E)}}});p(ge),iu({analytics:u,rooms:ge}),au({analytics:u});let ot=ru({client:kt,clock:e,rooms:ge,bridge:D,gameId:()=>se.identity?.gameId??"",baseUrl:()=>Xn,resolveClusterTargets:nr.resolveList,boot:l,...t.log===void 0?{}:{log:t.log}}),Es=ka(l,n),Yt=em({client:kt,clock:e,rooms:ge,signaling:()=>ms.channel(),signalingReady:xp,log:n??(()=>{})}),zi=pm({rooms:ge,p2p:{connect:m=>Es(ot.connect(m)),session:m=>ot.session(m)},dedicated:{connect:(m=>fi(l,"welcome",Yt.connect(m),n))},clock:e,identity:()=>se.identity,apiBaseUrl:()=>Xn,tokens:gs,room:()=>ge.currentRoom,autoReconnect:Ji!==null,...t.log===void 0?{}:{log:t.log}}),Lp=async()=>(await dr(Li)).playerId,Ts=new Mr(he,void 0,fs,xs);q.drop=()=>{lr.inventory.refresh(),Ts.refreshHeld();};let Is={client:kt,boot:l,get identity(){return se.identity},awaitIdentity:(m=Li)=>dr(m),awaitBridge:m=>D.settled(m),get player(){return k.current},awaitPlayer:(m=xw)=>k.wait(m),me:lr,characters:Ts,transfers:new Lr(he,po,lr.inventory),gameConfig:sr,purchases:Xt.api,deviceSettings:tr.api,graphics:us.api,moments:vs.api,ads:bs.api,account:_s.api,share:Am({frame:D,log:t.log,answers:ji}),arcade:Ep,store:Ss.api,branding:Dm({fetch:typeof window.fetch=="function"?(m,E)=>window.fetch.call(window,m,E):null,clock:e,devicePixelRatio:()=>window.devicePixelRatio??1,log:n}),vibration:Fm({frame:D,log:t.log}),get avatarPickerAvailable(){return D.currentState==="connected"&&D.parentSupports("avatarPicker")},openAvatarPicker:m=>D.requestAvatarPicker(m?.tab),avatars3d:Gp,settings:nt.api,controls:jm({recommended:()=>_.current?.recommended??null}),analytics:u,leaderboards:new un(he),challenges:new ln(he),showcase:new mn(he,Lp),friends:new pn(he,{challenge:Rs.challenge,inviteToPlay:ks.inviteToPlay,setInviteParams:b.set,...o===void 0?{}:{launchedChallengeId:o}}),platform:new fn(he,H,n),profiles:new yn(he),functions:new Xe((m,E)=>Ol(he,m,E)),get prefs(){return _.current},get paused(){return I},get textScale(){return _.current?.recommended?.textScale??null},get cohorts(){return T.current},get viewport(){return W.current},awaitCohorts:(m=Pw)=>T.wait(m),reportMuted:m=>{L=!!m,re();},showPortraitBorders:m=>{let E=Oi(m);E!==void 0&&(pe=E,Ae());},cueReward:m=>(Hr(m.cueId,"cueReward"),D.cueReward(m)),setWalletVisible:(m,E)=>{let F=Array.isArray(E?.only)?[...E.only]:void 0;return xe=F===void 0?{visible:m===true}:{visible:m===true,only:F},X()},setMenu:m=>(ne=Array.isArray(m?.items)?{items:m.items.map(E=>({...E}))}:{},Ue()),setGemCorner:m=>{if(!_w.includes(m)){let E=typeof m=="string"?JSON.stringify(m.slice(0,48)):`a value of type ${typeof m}`;return console.warn(`[gem] setGemCorner: ${E} is not a corner, so nothing was sent. Pass 'top-left', 'top-right', 'bottom-left' or 'bottom-right'.`),false}return Ce=m,M()},setRewardPresentation:m=>{if(!ww.includes(m)){let E=typeof m=="string"?JSON.stringify(m.slice(0,48)):`a value of type ${typeof m}`;return console.warn(`[gem] setRewardPresentation: ${E} is not a presentation, so nothing was sent. Pass 'game' or 'arcade'.`),false}return We=m,B()},setMenuStyle:m=>{let E=Sw(m);return E===void 0?false:(He=E,Z())},reportFrame:()=>ye.draw(),exit:m=>Ew(ge,D,m,u),frame:D,devtools:Fe,rooms:ge,dedicatedServer:{listClusterTargets:m=>Yt.listClusterTargets(m),connect:(m=>fi(l,"welcome",Yt.connect(m),n)),handleMatchEnded:(m,E)=>Yt.handleMatchEnded(m,E)},p2p:{handleSignalEvent:(m,E,F)=>ot.handleSignalEvent(m,E,F),session:m=>ot.session(m),connect:m=>Es(ot.connect(m))},match:zi};return Is}var _p="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 ds(t,e={}){let n=e.clock??ce,r=()=>{let a=t();if(a===null)throw new Error(_p);return a},i=null,o=()=>{if(i===null)throw new Error(_p);return i};return {server:{get identity(){return o().identity},get client(){return o().client},get api(){return o().api},get match(){return o().match},get analytics(){return o().analytics},get functions(){return o().functions},get challenges(){return o().challenges},get room(){return o().room},dispose(){i?.dispose();},get sizeClass(){return r().sizeClass},get roomArgs(){return r().roomArgs},get roster(){return r().roster},players(){return r().players()},profile(a){let d=r().profile?.(a);if(!d)return null;let u=d.displayName;return typeof u!="string"||u===""?null:{displayName:be(u,"profile.displayName"),...typeof d.displayTag=="string"&&d.displayTag!==""?{displayTag:be(d.displayTag,"profile.displayTag")}:{},...typeof d.discriminator=="string"?{discriminator:d.discriminator}:{}}},playerNumber(a){return r().playerNumber?.(a)},send(a,l,d){d===void 0?r().send(a,l):r().send(a,l,d);},broadcast(a,l){l===void 0?r().broadcast(a):r().broadcast(a,l);},kick(a,l){l===void 0?r().kick(a):r().kick(a,l);},log(a){r().log(a);},warn(a){r().warn(a);}},attach:()=>{i=Ht(r(),{...e,clock:n});}}}function wp(t,e={}){let{server:n,attach:r}=ds(()=>t,e);return r(),n}function Iw(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:Ye(e)}}}var Cw=1e4;function Ow(t){let e=false;return n=>{if(e)return;let r;try{r=t.match.reportPlayers([{playerId:n,state:"connected"}],AbortSignal.timeout(Cw));}catch{return}r.catch(i=>{i instanceof O&&i.status>=400&&i.status<500&&(e=i.status!==429);});}}function Sp(t,e={}){return ()=>{let n=null,{server:r,attach:i}=ds(()=>n,e),o=t(r),s={async init(l){n=l,i(),await o.init?.();},async shutdown(l){let d=Iw(l);try{await o.shutdown?.(d);}finally{r.dispose();}}},a=Ow(r);return s.join=(l,d)=>(a(l),o.join?.(l,d)),o.leave&&(s.leave=(l,d)=>o.leave?.(l,d)),o.message&&(s.message=(l,d,u,c)=>o.message?.(l,d,u,c)),s}}
3
- export{bw as ARCADE_EMBEDDERS,yw as AVATAR_RIGS,bn as AnalyticsApi,ie as AuthError,cr as CONDITIONAL_HEADERS,ln as ChallengesApi,os as DEVICE_SETTINGS_MAX_BYTES,A as DedicatedServerError,ct as FriendChallengeError,pn as FriendsApi,Xe as FunctionsApi,O as GemApiError,Ve as GemClient,fe as GemConfigError,Kn as GemFrame,hn as GemFunctionError,ae as GemSaveError,Vn as GemUnframedError,un as LeaderboardsApi,Td as MAX_PERIODS_BACK,Wf as PLATFORM_EVENTS,fn as PlatformApi,Ur as PlatformCurrenciesApi,Wr as PlatformEarnAllowanceApi,ve as PlayerText,yn as ProfilesApi,ze as PurchaseRefusal,xi as ShareRefusal,mn as ShowcaseApi,de as TransportRefusal,Sn as UNRELIABLE_CHANNEL_LABEL,be as asPlayerText,Aa as createBootTimeline,vC as createGem,Ht as createGemServer,rm as createHostTokenSource,wp as createMatchServer,Sp as defineServer,Kr as experimentSelection,Ew as leaveAndExit,Pe as mapIdentity,fi as markOnResolve,yo as platformIconUrl,_n as presentJoinCredential,Dt as readTemplateTransports,Rn as readTransportAdvert,ka as reportOnResolve,ce as systemClock,st as text,ur as toBase64,ni as webTransportAvailable};//# sourceMappingURL=gem-web-sdk.sdk.js.map
1
+ var fg=Object.defineProperty;var yg=(t,e)=>{for(var n in e)fg(t,n,{get:e[n],enumerable:true});};globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:24.0.0]";function Qs(){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)}var hg={initialDelayMs:2e3,maxDelayMs:6e4};function bg(t,e){return e!==void 0?!e:t==="chain_exhausted"}var Ot=class{constructor(e){this.options=e;}options;grant=null;state="pending";failure=null;generation=0;inFlight=null;rejected=false;retry=null;failures=0;notBefore=0;disposed=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.pastChainCeiling())throw new oe("chain_exhausted","the token chain reached its ceiling");if(this.inFlight===null&&this.options.clock.now()<this.notBefore)throw new oe(this.failure??"unavailable","the embedder asked for no new token yet; one is asked for when that wait is over");return this.refresh(this.nextReason())}pastChainCeiling(){return this.grant===null||this.seconds()<this.grant.chainEndsAt?false:(this.enter("lost","chain_exhausted"),true)}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);}dispose(){this.disposed=true,this.cancelRetry();}scheduleRetry(e){if(this.cancelRetry(),this.failures+=1,this.notBefore=e===void 0?0:this.options.clock.now()+e,this.disposed)return;let{initialDelayMs:n,maxDelayMs:r}=hg,o=Math.min(r,n*2**(this.failures-1)),i=Math.max(o/2,e??0)+Math.random()*(o/2);this.retry={handle:this.options.clock.setTimeout(()=>this.retryNow(),i)};}retryNow(){this.retry=null,this.notBefore=0,!(this.state==="lost"||this.pastChainCeiling())&&this.refresh(this.nextReason()).catch(()=>{});}cancelRetry(){this.retry!==null&&(this.options.clock.clearTimeout(this.retry.handle),this.retry=null);}refresh(e){if(this.inFlight)return this.inFlight;this.cancelRetry();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=vg(o),{retryable:s,retryAfterMs:a}=o??{};throw n===this.generation&&(bg(i,typeof s=="boolean"?s:void 0)?this.enter("lost",i):(this.scheduleRetry(typeof a=="number"&&Number.isFinite(a)&&a>0?a:void 0),this.enter("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){(e==="ready"||e==="lost")&&this.cancelRetry(),e==="ready"&&(this.failures=0,this.notBefore=0),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 vg(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 ue=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}},wr=["if-match","if-none-match"],Zs=4096;function _g(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let o=n.toLowerCase();if(!wr.includes(o)||r===void 0)continue;let i=typeof r=="string"?wg(r):r;if(typeof i!="string"||i.length>Zs||!Sg(i))throw new ue(`the ${o} header value cannot be sent \u2014 it is not a string, is longer than ${Zs} 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 wg(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 Sg(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 Rg(t){let{bytes:e}=t;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new ue("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 ue("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 el(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let o={...r},i=_g(o.headers),s=Rg(o),a=Object.freeze({...o,headers:i,...s===void 0?{}:{bytes:s}}),l=await e.tokenSource.get(),d=await t(a,l);if(d.status!==401||!n)return d;e.tokenSource.invalidate(l);let c=await e.tokenSource.get(),u=await t(a,c);if(u.status===401)throw e.tokenSource.close("unavailable"),new oe("unavailable","the server refused a freshly minted token");return u}}}function Sr(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(kg(e))}function Rr(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 gi(t){return new TextDecoder().decode(Rr(t))}function kg(t){let n="";for(let r=0;r<t.length;r+=32768)n+=String.fromCharCode(...t.subarray(r,r+32768));return n}var M=class extends Error{constructor(n,r,o,i,s){super(`${n} (${r}): ${o}`);this.reason=n;this.status=r;this.detail=o;this.retryAfterSeconds=i;this.code=s;this.name="GemApiError";}reason;status;detail;retryAfterSeconds;code;get retryable(){return this.reason==="unavailable"||this.reason==="rate_limited"}},rl=new WeakMap;function ol(t){return rl.get(t)??{}}var Ag=new Set([408,429,500,502,503,504]),xg=6e4,il=new WeakMap;function al(t,e){il.set(t,e);}function tl(t){return t!==null&&(t.reason==="rate_limited"||t.retryAfterSeconds!==void 0)}function Pg(t){if(t===void 0)return 2;if(!Number.isInteger(t)||t<0||t>10)throw new ue(`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 Ze=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,...un(o)},o.replaySafe===true,o.retryRateLimited!==false)}async post(e,n,r,o={}){return this.send({method:"POST",path:e,body:n,signal:r,...un(o)},o.replaySafe===true,o.retryRateLimited!==false)}async postBytes(e,n,r,o={}){let i=await this.sendRaw({method:"POST",path:e,bytes:n,responseType:"bytes",signal:r,...un(o)},o.replaySafe===true,o.retryRateLimited!==false);return {bytes:Eg(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,...un(o)},o.replaySafe===true,o.retryRateLimited!==false)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...un(r)},r.replaySafe===true,r.retryRateLimited!==false)}async send(e,n,r=true){return (await this.sendRaw(e,n,r)).body}async sendRaw(e,n,r=true){let o=n?Pg(this.options.maxRetries)+1:1,i=null;if(e.signal?.aborted)throw nl(e.signal);let s=e.signal===void 0?void 0:il.get(e.signal);for(let a=0;a<o;a++){if(a>0){let c=this.backoffMs(a,i);if(tl(i)&&s!==void 0&&c>=s())throw i;await this.backoff(c,e.signal);}if(e.signal?.aborted)throw tl(i)&&s!==void 0&&s()<=0?i:nl(e.signal);let l;try{l=await this.options.transport.request(e);}catch(c){if(oe.isAuthError(c)||ue.isRefusal(c)||e.signal?.aborted||Ig(c))throw c;i=new M("unavailable",0,String(c));continue}if(l.status>=200&&l.status<300||l.status===304)return l;let d=ll(l);if(!Ag.has(l.status)||l.status===429&&!r)throw d;i=d;}throw i??new M("unavailable",0,"no attempt was made")}backoffMs(e,n){let r=n?.retryAfterSeconds,o=r!==void 0?r*1e3:2**(e-1)*250,i=2**(e-1)*250;return Math.min(Math.max(o,i),xg)}backoff(e,n){return n?.aborted?Promise.resolve():new Promise(r=>{let o=this.options.clock,i=false,s=false,a,l=()=>{i||(i=true,s&&o.clearTimeout(a),n?.removeEventListener("abort",l),r());};n?.addEventListener("abort",l,{once:true}),a=o.setTimeout(l,e),s=true,i&&o.clearTimeout(a);})}};function Eg(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 un(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function nl(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function Ig(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function sl(t,e){return ll({status:t,body:e})}function ll(t){let e=Cg(t),n=Og(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&rl.set(e,r),e}var Tg=new Map([["insufficient_funds","insufficient_funds"]]);function Cg(t){let{status:e,body:n}=t,r=Mg(n),o=t.retryAfterSeconds??Lg(n),i=Gg(n),s=i===void 0?void 0:Tg.get(i);if(s!==void 0)return new M(s,e,r,void 0,i);switch(e){case 304:return new M("not_modified",e,r);case 400:case 422:return new M("invalid",e,r,void 0,i);case 403:return new M("forbidden",e,r,void 0,i);case 404:return new M("not_found",e,r,void 0,i);case 402:return new M("insufficient_funds",e,r,void 0,i);case 409:return new M("conflict",e,r,void 0,i);case 412:return new M("precondition_failed",e,r,void 0,i);case 413:return new M("too_large",e,r,void 0,i);case 429:return new M("rate_limited",e,r,o,i);default:return new M("unavailable",e,r,o,i)}}function Mg(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 Og(t){let n=t?.error?.details;return n===null?void 0:n}function Gg(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function Lg(t){let e=t?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function k(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 dl(t,e,n){let r=`/v1/inventory/transfers/${k(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function cl(t,e,n,r,o,i){let s=`/v1/inventory/${k(e)}/${k(n)}/progressions/${k(r)}/add`;return t.client.post(s,o,i?.signal)}async function ul(t,e,n){let r=`/v1/inventory/transfers/${k(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function ml(t,e,n){let r=`/v1/games/${k(t.gameId())}/matchmaking/tickets/${k(e)}`;return t.client.delete(r,n?.signal)}async function pl(t,e,n,r,o,i){let s=`/v1/inventory/${k(e)}/${k(n)}/progressions/${k(r)}/claim`;return t.client.post(s,o,i?.signal)}async function gl(t,e,n){return t.client.post("/v1/characters",e,n?.signal)}async function fl(t,e,n,r,o){let i=`/v1/inventory/${k(e)}/${k(n)}/orders/batch`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function yl(t,e,n,r,o){let i=`/v1/inventory/${k(e)}/${k(n)}/orders`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function hl(t,e,n){let r=`/v1/games/${k(t.gameId())}/matchmaking/tickets`;return t.client.post(r,e,n?.signal)}async function bl(t,e,n,r,o){let i=`/v1/settings/${k(e)}/${k(n)}/${k(r)}`;return t.client.delete(i,o?.signal)}async function vl(t,e,n,r,o){let i=`/v1/saves/${k(e)}/${k(n)}/${k(r)}`;return t.client.delete(i,o?.signal)}async function _l(t,e,n,r){let o=`/v1/showcase/players/${k(e)}/${k(n)}`;return t.client.delete(o,r?.signal)}async function wl(t,e,n,r,o){let i=`/v1/inventory/${k(e)}/${k(n)}/recipes/execute`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Sl(t,e,n,r,o,i){let s=`/v1/saves/${k(e)}/${k(n)}/${k(r)}/finalize`;return t.client.post(s,o,i?.signal)}async function Rl(t,e,n){let r=`/v1/games/${k(t.gameId())}/avatars-3d/${k(e)}/owned`;return t.client.get(r,n?.signal)}async function kl(t,e,n){let r=`/v1/games/${k(t.gameId())}/config/channels/${k(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Al(t,e,n){let r=`/v1/characters/${k(e)}`;return t.client.get(r,n?.signal)}async function xl(t,e,n){let r=`/v1/inventory/loot-tables/${k(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Pl(t,e,n,r,o){let i=`/v1/settings/${k(e)}/${k(n)}/${k(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function El(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(),s=`/v1/inventory/${k(e)}/${k(n)}`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function Il(t,e,n,r,o){let i=`/v1/inventory/${k(e)}/${k(n)}/items/${k(r)}`;return t.client.get(i,o?.signal)}async function Tl(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 s=i.toString(),a=`/v1/leaderboards/${k(e)}/${k(n)}/${k(r)}`+(s?`?${s}`:"");return t.client.get(a,o?.signal)}async function Cl(t,e,n,r,o){let i=`/v1/inventory/${k(e)}/${k(n)}/orders/${k(r)}`;return t.client.get(i,o?.signal)}async function Ml(t,e,n,r,o){let i=`/v1/inventory/${k(e)}/${k(n)}/progressions/${k(r)}`;return t.client.get(i,o?.signal)}async function Ol(t,e,n,r,o,i){let s=`/v1/inventory/${k(e)}/${k(n)}/catalogs/${k(r)}/recipes/${k(o)}/availability`;return t.client.get(s,i?.signal)}async function Gl(t,e,n,r){let o=new URLSearchParams;o.set("limit",String(r?.limit));let i=o.toString(),s=`/v1/inventory/${k(e)}/${k(n)}/recipe-usage`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function fi(t,e,n,r,o){let i=`/v1/saves/${k(e)}/${k(n)}/${k(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Ll(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/${k(e)}/friends`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function Dl(t,e,n){let r=`/v1/showcase/friends/${k(e)}`;return t.client.get(r,n?.signal)}async function Fl(t,e){let n=`/v1/games/${k(t.gameId())}/avatars-3d`;return t.client.get(n,e?.signal)}async function $l(t,e,n){let r=`/v1/inbox/friend-challenges/${k(e)}`;return t.client.get(r,n?.signal)}async function ql(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/${k(e)}`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function Nl(t,e){let n=`/v1/games/${k(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function jl(t,e){let n=`/v1/games/${k(t.gameId())}/players/me/passes`;return t.client.get(n,e?.signal)}async function kr(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function Bl(t,e,n){let r=`/v1/profiles/players/${k(e)}`;return t.client.get(r,n?.signal)}async function Ul(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 Wl(t,e,n){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${k(e)}`;return t.client.get(r,n?.signal)}async function Hl(t,e,n,r){let o=`/v1/showcase/players/${k(e)}/${k(n)}`;return t.client.get(o,r?.signal)}async function Vl(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function Kl(t,e,n){let r=`/v1/inventory/transfers/${k(e)}`;return t.client.get(r,n?.signal)}async function Jl(t,e,n){let r=`/v1/games/${k(t.gameId())}/matchmaking/tickets/${k(e)}/heartbeat`;return t.client.post(r,void 0,n?.signal)}async function zl(t,e,n){let r=`/v1/games/${k(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{...n?.keepalive===void 0?{}:{keepalive:n.keepalive},replaySafe:true,retryRateLimited:false})}async function Xl(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function Yl(t,e,n,r,o){let i=`/v1/inventory/${k(e)}/${k(n)}/platform-funded-game-inventory-purchases`;return t.client.post(i,r,o?.signal)}async function Ql(t,e,n){let r=new URLSearchParams;n?.cue_id!==void 0&&r.set("cue_id",String(n?.cue_id));let o=r.toString(),i="/v1/functions/invoke"+(o?`?${o}`:"");return t.client.postBytes(i,e,n?.signal)}async function Zl(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 ed(t,e){return t.client.get("/v1/characters",e?.signal)}async function td(t,e,n,r){let o=`/v1/settings/${k(e)}/${k(n)}`;return t.client.get(o,r?.signal)}async function nd(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(),s=`/v1/inventory/${k(e)}/${k(n)}/orders`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function rd(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(),s=`/v1/saves/${k(e)}/${k(n)}`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function od(t,e){let n=new URLSearchParams;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/inbox/friend-challenges"+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function id(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 ad(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 sd(t,e,n){let r=`/v1/inbox/friend-challenges/${k(e)}/answered`;return t.client.post(r,void 0,n?.signal)}async function ld(t,e,n,r){let o=`/v1/games/${k(t.gameId())}/matches/${k(e)}/end`;return t.client.post(o,n,r?.signal)}async function dd(t,e,n,r,o,i){let s=`/v1/inventory/${k(e)}/${k(n)}/progressions/${k(r)}/max`;return t.client.post(s,o,i?.signal)}async function cd(t,e,n,r,o,i){let s=`/v1/settings/${k(e)}/${k(n)}/${k(r)}`;return t.client.put(s,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ud(t,e,n,r,o){let i=`/v1/showcase/players/${k(e)}/${k(n)}`;return t.client.put(i,r,o?.signal)}async function md(t,e,n,r,o){let i=`/v1/inventory/${k(e)}/${k(n)}/rewarded-placements/${k(r)}/availability`;return t.client.get(i,o?.signal)}async function pd(t,e,n){let r=`/v1/inventory/transfers/${k(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function gd(t,e,n,r){let o=`/v1/characters/${k(e)}`;return t.client.patch(o,n,r?.signal)}async function fd(t,e,n,r,o,i){let s=`/v1/saves/${k(e)}/${k(n)}/${k(r)}/upload-url`;return t.client.post(s,o,i?.signal,{replaySafe:true})}async function yd(t,e,n,r,o,i){let s=`/v1/inventory/${k(e)}/${k(n)}/progressions/${k(r)}/reset`;return t.client.post(s,o,i?.signal)}async function hd(t,e,n){let r=`/v1/characters/${k(e)}`;return t.client.delete(r,n?.signal)}var B="gem-web-bridge",xr={min:1,max:1},Dg=65536,bd=8,Ar=5e3,vd=1024;var mn=Object.create(null),Pr="__malformed";var bi=Object.create(null),Fg=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.textScale.","textScale"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"],["gem.moments.","moments"],["gem.prefs.","audioChannels"],["gem.share.","shareRemap"]]);function Er(t){let e=bi[t];if(e!==void 0)return e;for(let[n,r]of Fg)if(t.startsWith(n))return r}function Gt(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 $g(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 qg(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function Ng(t){return /^[a-z_]+$/.test(t)}function jg(t){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)||/^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/.test(t)&&!t.includes("--")}function yi(t,e,n){if(e>bd)return `nesting deeper than ${bd}`;if(++n.nodes>Ar)return `more than ${Ar} values`;if(n.bytes>n.cap)return `over the ${n.cap} 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>vd)return `an array of ${t.length} entries, over the ${vd} limit`;n.bytes+=2;for(let a of t){let l=yi(a,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 s=t;for(let a in s){if(!Object.prototype.hasOwnProperty.call(s,a))continue;if(++n.nodes>Ar)return `more than ${Ar} values`;if(n.bytes+=a.length*3+4,n.bytes>n.cap)return `over the ${n.cap} byte limit`;let l=yi(s[a],e+1,n);if(l)return l}return null}function Bg(t,e=Dg){let n={nodes:0,bytes:0,seen:new Set,cap:e},r=yi(t,0,n);return r?`message contains ${r}`:n.bytes>e?`message is over the ${e} byte limit`:null}var Ug={origin:[Gt,"not a well-formed origin"],url:[$g,"not a safe absolute http(s) URL"],bcp47:[qg,"not a well-formed BCP 47 tag"],code:[Ng,"not a code of lower-case letters and underscores"],gameRef:[jg,"not a game id or web address"]};function _d(t,e,n){for(let r of e){let o=n===""?r[0]:`${n}.${r[0]}`,i=t[r[0]];if(i==null){if(r[1]<"a")continue;return `${o}: required`}let s=hi(i,r,o);if(s)return s}return null}function hi(t,e,n){let r=e[1].toLowerCase();switch(r){case "u":return typeof t=="boolean"?null:hi(t,typeof t=="string"?[e[0],"s",e[2]]:[e[0],"n",e[3],e[4]],n);case "s":{if(typeof t!="string")return `${n}: expected string`;if(t.length>e[2])return `${n}: exceeds ${e[2]} characters`;if(e[3]){let[o,i]=Ug[e[3]];if(!o(t))return `${n}: ${i}`}return null}case "n":case "i":return typeof t!="number"||!(r=="i"?Number.isInteger:Number.isFinite)(t)?`${n}: expected ${r=="i"?"integer":"number"}`:t<e[2]||t>e[3]?`${n}: out of range ${e[2]}..${e[3]}`:null;case "b":return typeof t=="boolean"?null:`${n}: expected boolean`;case "e":{let o=e[2];return o.includes(t)?null:`${n}: not one of ${o.join("|")}`}case "o":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected object`:_d(t,e[2],n);case "j":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected a plain object`:null;case "a":{if(!Array.isArray(t))return `${n}: expected array`;if(t.length>e[2])return `${n}: exceeds ${e[2]} items`;let o=e[3],i=`${n}[]`;for(let s of t){if(s==null){if(o[1]<"a")continue;return `${i}: required`}let a=hi(s,o,i);if(a)return a}return null}default:return `${n}: unknown kind ${String(r)}`}}var wd=Object.create(null);function I(t,e,n,r,o){return mn[t]=n,r&&(bi[t]=r),wd[t]=i=>{let s=Bg(i,o);if(s)return s;if(typeof i!="object"||i===null||Array.isArray(i))return "message: expected object";let a=i;return a.gem!==B?"gem: wrong protocol marker":a.type!==t?`type: expected ${t}`:_d(a,e,"")}}var pn=["","s",64],V=["requestId","s",64],gn=["currencySlug","s",32],fn=["matchId","s",64],He=["reason","S",64,"code"],et=["outcome","e",["ok","declined","unavailable"]];I("gem.handshake",[["versions","o",[["min","i",1,1e3],["max","i",1,1e3]]],["capabilities","A",64,pn],["embedder","s",2048,"origin"],["unbidden","B"]],30);I("gem.handshake.accept",[["v","i",1,1e3],["capabilities","A",64,pn]],5);I("gem.token",[["token","s",4096],["requestId","S",64],["generation","i",0,2147483647],["apiBaseUrl","S",512,"url"],["playerId","s",64],["gameId","s",64],["channel","e",["dev","test","release"]],["gameVersion","S",64],["expiresAt","i",0,4102444800],["chainEndsAt","i",0,4102444800],["allowDevTools","B"]],30);I("gem.token.denied",[V,["retryable","b"],["retryAfterMs","I",0,36e5],["reason","e",["chain_exhausted","unavailable"]],["correlationId","s",64]],30);I("gem.player",[["untrusted","o",[["displayName","s",64],["displayTag","S",80],["displayHandle","s",80]]],["playerId","S",64],["discriminator","S",8],["avatarIconUrl","S",2048,"url"],["avatarIconId","S",64],["avatar3dId","S",64],["avatar3dModelUrl","S",2048,"url"],["avatar3dIconUrl","S",2048,"url"],["avatars3d","A",8,["","o",[["family","s",32],["id","s",64],["modelUrl","s",256,"url"],["iconUrl","s",256,"url"]]]],["badges","A",2,["","o",[["itemId","s",64],["iconUrl","s",2048,"url"]]]],["displayTag","s",8],["avatarUrl","S",2048,"url"],["boost","O",[["multipliers","a",8,["","o",[["currencyId","s",64],gn,["multiplierBp","i",1e4,1e6]]]],["expiresInDays","I",1,7]]],["signInAvailable","B"]],12);I("gem.pause",[["paused","b"]],120);I("gem.prefs",[["reducedMotion","b"],["muted","b"],["showFrameStats","B"],["music","B"],["sounds","B"],["locale","s",35,"bcp47"],["recommended","O",[["volume","i",0,100],["batterySaver","b"],["keyboardLayout","e",["wasd","arrows"]],["gamepadConfirm","e",["south","east"]],["vibration","b"],["lookSensitivity","I",20,400],["gamepadLookSensitivity","I",20,400],["invertLookY","B"],["touchMovement","S",16,"code"],["graphicsQuality","S",16,"code"],["graphicsQualityAuto","B"],["colorHelp","B"],["textScale","I",100,200]]]],60);I("gem.cohorts",[["cohorts","a",8,["","o",[["experimentId","s",36],["variantKey","s",32]]]]],12,"cohorts");I("gem.earnAllowanceChanged",[],30,"earnAllowance");I("gem.inventoryChanged",[],30,"inventoryChanged");I("gem.viewport",[["insets","o",[["top","i",0,4096],["right","i",0,4096],["bottom","i",0,4096],["left","i",0,4096]]],["reserved","A",4,["","o",[["x","i",0,16384],["y","i",0,16384],["width","i",0,16384],["height","i",0,16384],["control","O",[["x","i",0,16384],["y","i",0,16384],["width","i",0,16384],["height","i",0,16384]]]]]]],60,"viewport");I("gem.deviceSettings",[["settings","J"]],12,"deviceSettings");I("gem.willTerminate",[["reason","e",["grant_expiring","session_ended","navigating","kill_switch"]],["graceMs","i",0,6e4]],10);I("gem.roomEvent",[["event","e",["updated","match_started","match_ready","match_failed","version_stale"]],["roomId","s",64],["matchId","S",64],["version","I",0,2147483647],["reason","S",64],["platform","E",["universal","mobile"]]],120,"rooms");I("gem.socketState",[["connected","b"],["reason","E",["connecting","dropped","watchdog","terminal"]]],12,"socketState");I("gem.seatedEvent",[["roomId","s",64]],60,"partySeating");I("gem.autoStartFailedEvent",[["roomId","s",64],["code","s",64]],30,"autoStartFailure");I("gem.ticketEvent",[["event","e",["queued","matched","expired","cancelled","failed"]],["ticketId","s",64],["partySize","I",1,64],["queuedAt","I",0,4102444800],["expiresAt","I",0,4102444800],["reason","S",64],["roomId","S",64]],60,"ticketEvents");I("gem.signalEvent",[["event","e",["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]],fn,["data","j"]],1800,"p2p");I("gem.relayDraining",[fn,["clusterTargetId","s",64],["relayIps","a",16,pn],["drainingSince","s",40],["deadline","s",40]],60,"p2pRelayDrain");I("gem.dedicatedEvent",[["event","e",["answer","error","matchEnded"]],fn,["sdp","S",10240],["sessionId","S",64],["code","S",64],["message","S",256],["reason","S",64]],120,"dedicated");I("gem.partyResult",[V,["partyId","S",64]],30,"parties");I("gem.clusterTarget",[["clusterTargetId","s",64],["clusterTargetIds","A",3,pn]],12,"clusterTarget");I("gem.graphicsRoutes",[["entries","a",32,["","o",[["gpu","s",32],["route","S",32],["host","S",32]]]]],12,"graphicsRoutes");I("gem.devtools",[["action","e",["open","close","toggle"]]],30,"devtools");I("gem.screenshot",[["maxWidth","i",1,7680],["maxHeight","i",1,4320]],6,"screenshot");I("gem.screenshot.denied",[["reason","e",["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]],["retryable","b"]],12,"screenshot");I("gem.requestContext",[],12,"feedbackContext");I("gem.gameContext",[["context","j"]],12,"feedbackContext");I("gem.signal",[["signal","e",["join","offer","answer","ice","migrationAck","hostUnreachable"]],fn,["data","j"]],1200,"p2p");I("gem.dedicatedOffer",[fn,["sdp","s",10240],["intent","e",["initial","ice_restart","full_reconnect"]]],60,"dedicated");I("gem.partyRequest",[V],12,"parties");I("gem.ready",[],5);I("gem.engaged",[],5,"engagement");I("gem.progress",[["loaded","i",0,1099511627776],["total","i",0,1099511627776]],600);I("gem.requestToken",[V,["reason","e",["initial","expiring","rejected"]]],12);I("gem.requestLocalServer",[V,["gameRoomId","s",64]],6,"localHost");I("gem.localServer",[V,["serverId","S",128]],30,"localHost");I("gem.localServer.denied",[V,["retryable","b"],["reason","e",["refused","unavailable"]]],30,"localHost");I("gem.exit",[["reason","S",64]],5);I("gem.openExternal",[["url","s",2048,"url"]],6);I("gem.requestFullscreen",[["enabled","b"]],30);I("gem.audioState",[["muted","b"]],120,"audioState");I("gem.rewardCue",[gn,["cueId","S",64],["expected","I",1,1e9],["origin","O",[["x","i",0,16384],["y","i",0,16384]]]],60,"rewardCue");I("gem.rewardPresentation",[["mode","e",["arcade","game"]]],12,"rewardPresentation");I("gem.walletDisplay",[["visible","b"],["currencies","A",8,pn],["score","B"]],60,"walletDisplay");I("gem.controlsDeclare",[["uses","o",[["lookSensitivity","S",16,"code"],["gamepadLookSensitivity","S",16,"code"],["invertLookY","S",16,"code"],["touchMovement","S",16,"code"]]]],60,"controls");I("gem.menu",[["settings","b"],["items","A",4,["","o",[["id","s",32],["label","s",40]]]]],60,"gameMenu");I("gem.menuSelect",[["entry","e",["settings","item"]],["id","S",32]],60,"gameMenu");I("gem.gemCorner",[["corner","e",["top-left","top-right","bottom-left","bottom-right"]]],12,"gemCorner");I("gem.menuStyle",[["ground","S",7],["accent","S",7]],12,"menuStyle");I("gem.settingsDeclare",[["settings","a",8,["","o",[["id","s",40],["label","s",40],["kind","e",["toggle","slider","choice"]],["value","u",40,-1e6,1e6],["quick","B"],["icon","S",16,"code"],["min","N",-1e6,1e6],["max","N",-1e6,1e6],["step","N",0,1e6],["options","A",4,["","o",[["id","s",40],["label","s",40]]]]]]]],120,"gameSettings");I("gem.settingChange",[["id","s",40],["value","u",40,-1e6,1e6]],120,"gameSettings");I("gem.requestShare",[["requestId","S",64],["params","a",16,["","o",[["key","s",64],["value","s",512]]]]],6,"share");I("gem.shareResult",[V,["outcome","e",["accepted","refused"]],He,["key","S",64]],30,"shareResult");I("gem.requestAvatarPicker",[["tab","E",["2d","3d"]]],6,"avatarPicker");I("gem.vibrate",[["pattern","a",99,["","i",0,1e4]]],600,"vibration");I("gem.frameStats",[["fps","i",0,1e3],["frameTimeP95Ms","i",0,1e5],["counts","E",["pageFrames","gameDraws"]]],120,"frameStats");I("gem.portraitBorders",[["name","S",40]],60,"portraitBorders");I("gem.error",[["code","e",["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]],["message","S",256]],60);I("gem.requestPurchase",[V,["purchaseKind","e",["item","recipe"]],["targetId","s",64],gn,["quantity","I",1,10],["catalogId","S",64],["origin","E",["sheet","direct_refused"]]],12,"purchases");I("gem.requestAvatar3dPurchase",[V,["itemId","s",64],gn],12,"avatar3dPurchases");I("gem.purchaseResult",[V,et,He,["purchaseId","S",64]],30,"purchases");I("gem.purchaseSettled",[["purchaseKind","e",["item","recipe"]],["targetId","s",64],["catalogId","S",64],["quantity","i",1,10],["purchaseId","S",64]],30,"purchaseSettled");I("gem.deviceSettings.put",[V,["settings","j"]],30,"deviceSettings");I("gem.deviceSettings.result",[V,["outcome","e",["stored","too_large","unavailable"]]],30,"deviceSettings");I("gem.requestAd",[V,["placement","s",32],["format","e",["interstitial","rewarded"]]],6,"ads");I("gem.adResult",[V,["outcome","e",["shown","no_ad","unavailable"]]],12,"ads");I("gem.signalMoment",[V,["kind","e",["level_end","run_end","match_end","menu_return","other_break"]],["placement","S",32],["wall","B"]],6,"moments");I("gem.momentResult",[V,["shown","b"]],12,"moments");I("gem.requestSignIn",[V],6,"signIn");I("gem.signInResult",[V,["outcome","e",["signed_in","declined","unavailable"]]],12,"signIn");I("gem.requestFriendChallenge",[V,["playerId","s",64],["template","s",64],["params","J"]],12,"friendChallenges");I("gem.friendChallengeResult",[V,["outcome","e",["accepted","cancelled","refused","unavailable","rate_limited","invalid"]],["code","S",64],["param","S",64],["channel","S",16],["configVersion","I",0,9007199254740991],["retryAfterMs","I",0,864e5],["detail","S",300]],30,"friendChallenges");I("gem.requestPlayInvite",[V,["params","A",16,["","o",[["key","s",64],["value","s",512]]]]],6,"playInvites");I("gem.playInviteResult",[V,["shown","b"]],12,"playInvites");I("gem.inviteParams",[["params","A",16,["","o",[["key","s",64],["value","s",512]]]]],30,"playInvites");I("gem.requestAppLinks",[V],12,"appLinks");I("gem.appLinksResult",[V,et,He,["arcade","O",[["store","e",["app_store","google_play"]]]],["game","O",[["store","e",["app_store","google_play"]]]]],30,"appLinks");I("gem.requestOpenApp",[V,["target","e",["arcade","game"]]],6,"appLinks");I("gem.openAppResult",[V,et,He],30,"appLinks");var Sd=I("gem.requestOpenGame",[V,["ref","s",40,"gameRef"]],6,"openGame");I("gem.openGameResult",[V,et,He],30,"openGame");I("gem.requestSimilarGames",[V,["limit","I",1,24]],12,"openGame");I("gem.similarGamesResult",[V,et,He,["games","a",24,["","o",[["gameId","s",36,"gameRef"],["slug","S",40,"gameRef"],["iconUrl","s",1024,"url"],["capsuleLandscapeUrl","s",1024,"url"],["capsulePortraitUrl","s",1024,"url"],["previewVideoUrl","S",1024,"url"],["previewPosterUrl","S",1024,"url"],["untrusted","o",[["name","s",64],["tagline","s",64],["shortDescription","s",320],["tags","a",10,["","s",32]]]]]]]],30,"openGame",524288);I("gem.requestStoreOffers",[V],12,"store");I("gem.storeOffersResult",[V,et,He,["offers","a",32,["","o",[["skuId","s",64],["kind","e",["gem_pack","boost","pass","bundle"]],["name","s",80],["description","s",400],["imageUrl","S",1024,"url"],["priceDisplay","s",32],["grant","O",[["currency","s",32],["amount","i",1,1e9]]],["pass","S",64],["earnMultipliers","A",8,["","o",[gn,["multiplierBp","i",1e4,1e6]]]]]]]],30,"store",262144);I("gem.requestStorePurchase",[V,["skuId","s",64]],12,"store");I("gem.storePurchaseResult",[V,et,He],30,"store");I("gem.storePurchaseSettled",[["skuId","s",64]],30,"store");I("gem.requestStoreOfferSheet",[V,["skuId","s",64]],12,"storeOfferSheet");I("gem.storeOfferSheetResult",[V,et,He],30,"storeOfferSheet");var Ir=Object.freeze(wd);mn.__malformed=60;Object.freeze(mn);Object.freeze(bi);var me={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},yn=class{constructor(e=me){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=mn[e];if(n===void 0)return false;let r=this.clock.now(),o=this.lastRefill.get(e)??r,i=this.tokens.get(e)??n,s=Math.max(0,r-o),a=Math.min(n,i+s*n/6e4);return a<1?(this.tokens.set(e,a),this.lastRefill.set(e,r),false):(this.tokens.set(e,a-1),this.lastRefill.set(e,r),true)}};function Lt(t,e){return t.toLowerCase()===e.toLowerCase()}function tt(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function Tr(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:tt(n.hostname)&&tt(r.hostname)}function Rd(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 Cr=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(a=>a.currencyId===e),s;return !i&&this.resolveCurrencyId&&(s=await this.resolveCurrencyId(e).catch(()=>{}),s!==void 0&&(i=o.find(a=>a.currencyId===s))),{currencyId:i?i.currencyId:s??e,total:i?i.total:null,...i?.buckets===void 0?{}:{buckets:i.buckets}}}};function _i(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 kd="inventory",Dt=t=>typeof t=="number"?t:0,hn=t=>typeof t=="string"?t:"";function vi(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 Ad(t){let e=t??{};return {itemDefinitionId:hn(e.item_definition_id),instanceId:hn(e.instance_id),quantity:Dt(e.quantity),acquiredAt:Dt(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function Wg(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:vi(e.currencies,r=>{let o=r??{},i=Array.isArray(o.buckets)?o.buckets.map(s=>{let a=s??{};return {bucket:hn(a.bucket),balance:Dt(a.balance)}}):void 0;return {currencyId:hn(o.currency_id),total:Dt(o.total),...i===void 0?{}:{buckets:i}}}),items:vi(e.items,Ad),progressions:vi(e.progressions,r=>{let o=r??{};return {progressionDefinitionId:hn(o.progression_definition_id),currentValue:Dt(o.current_value),completionCount:Dt(o.completion_count),isCompleted:o.is_completed===true,..._i(o)}}),...n===void 0?{}:{etag:n}}}var Mr=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${kd}#buckets`:kd;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(s=>s.itemDefinitionId===e);if(i.length>0)return i}let o=await Il(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(o)?o.map(Ad):[]}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 El(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 Wg(n)}};var Hg={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,already_owned:1,guest_upgrade_required:1,recipe_on_cooldown:1,recipe_max_uses_exceeded:1,item_max_stack_exceeded:1,recipe_costs_unmet:1,quantity_invalid:1,error:1},Vg=new Set(Object.keys(Hg));function xd(t){return typeof t=="string"&&Vg.has(t)?t:"error"}var nt=class extends RangeError{constructor(n,r){super(r);this.code=n;this.name="PurchaseRefusal";}code;retryable=false};var ie=t=>typeof t=="string"?t:"",Kg=t=>typeof t=="string"?t:ie(t&&typeof t=="object"?t.type:void 0),$e=t=>typeof t=="number"?t:0;function Jg(t){let e=t??{};return {prerequisiteType:ie(e.prerequisite_type),referenceId:ie(e.reference_id),required:$e(e.required),current:$e(e.current)}}function bn(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {orderId:ie(e.order_id),status:ie(e.status),...n===void 0?{}:{etag:n}}}function Or(){return crypto.randomUUID()}var zg="recipe-usage",Pd=100;function Gr(t){let e=t??{};switch(e.type){case "currency":return {kind:"currency",currencyId:ie(e.currency_id),bucket:ie(e.bucket),delta:$e(e.delta),balanceAfter:$e(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:ie(e.item_definition_id),instanceId:ie(e.instance_id),delta:$e(e.delta),quantityAfter:$e(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:ie(e.progression_definition_id),delta:$e(e.delta),valueAfter:$e(e.value_after),completed:e.completed===true};default:return {kind:"other",type:ie(e.type)}}}function Xg(t){let e=t??{},n=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:ie(e.entry_id),...n===void 0?{}:{rarityTier:n},rollNumber:$e(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(Gr):[]}}function Yg(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(Xg):void 0;return {orderId:ie(e.order_id),status:ie(e.status),...n===void 0?{}:{etag:n},granted:Array.isArray(e.granted)?e.granted.map(Gr):[],consumed:Array.isArray(e.consumed)?e.consumed.map(Gr):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(Gr):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function Qg(t){let e=t??{},n=e.price??{};return {payment:"platform_currency",orderId:ie(e.target_order_id)||ie(e.source_order_id),status:ie(e.status),purchaseId:ie(e.purchase_id),sourceOrderId:ie(e.source_order_id),price:{currencyId:ie(n.platform_currency_id),amount:$e(n.price)}}}function Zg(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:ie(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 Ed(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 Lr=class{constructor(e,n,r,o){this.api=e;this.entity=n;this.cache=r;this.handOffRefused=o;}api;entity;cache;handOffRefused;async create(e,n={}){let r=await this.write(()=>yl(this.api,this.entity.type,this.entity.id,{operations:e.map(Ed),source:n.source??"play",nonce:Or()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return bn(r)}async createMany(e,n={}){return this.write(()=>fl(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(Ed),nonce:Or()})),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 Ol(this.api,this.entity.type,this.entity.id,e,n,r===void 0?{}:{signal:r})??{},s=typeof i.uses_remaining=="number"?i.uses_remaining:void 0,a=typeof i.cooldown_expires_at=="string"?i.cooldown_expires_at:void 0,l=Array.isArray(i.lock_reasons)?i.lock_reasons.map(Jg):[];return {canExecute:i.can_execute===true,locked:i.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(i.reasons)?i.reasons.map(d=>Kg(d)):[],...s===void 0?{}:{usesRemaining:s},...a===void 0?{}:{cooldownExpiresAt:a}}}async recipeUsageAll(){return this.cache.read(zg,[],async()=>{let n=await Gl(this.api,this.entity.type,this.entity.id,{limit:Pd})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(Zg),truncated:r.length>=Pd}})}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(()=>wl(this.api,this.entity.type,this.entity.id,{catalog_id:u.catalogId,recipe_id:u.targetId,game_id:this.api.gameId(),nonce:Or()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...Yg(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([Ul(this.api,n.signal===void 0?{}:{signal:n.signal}),kr(this.api,n.signal===void 0?{}:{signal:n.signal})]),i=e.payment.currencySlug.toLowerCase(),s=o.currencies.find(u=>u.currency_id.toLowerCase()===i||u.slug.toLowerCase()===i);if(s===void 0){let u=o.currencies.map(p=>p.slug);throw new nt("unknown_currency",`platform currency ${JSON.stringify(e.payment.currencySlug)} is not an active platform currency. Active: ${u.length===0?"none":u.join(", ")}`)}let a=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(a===void 0)throw new nt("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=a.platform_prices.find(u=>u.platform_currency_id===s.currency_id);if(l===void 0){let u=g=>o.currencies.find(f=>f.currency_id===g)?.slug??g,p=a.platform_prices.map(g=>`${u(g.platform_currency_id)} ${g.price}`);throw new nt("no_price_in_currency",`purchase target ${JSON.stringify(e.targetId)} has no ${s.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 nt("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let c;try{c=await this.write(()=>Yl(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:s.currency_id,price:l.price*d},expected_config_version:r.config_version,nonce:Or(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));}catch(u){if(this.handOffRefused!==void 0&&u instanceof M&&u.status===403&&u.code==="guest_upgrade_required")try{this.handOffRefused({kind:e.kind,targetId:e.targetId,...e.kind==="recipe"?{catalogId:e.catalogId}:{},currencySlug:s.slug,quantity:d});}catch{}throw u}return Qg(c)}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(()=>cl(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return bn(o)}async maxProgression(e,n,r){let o=await this.write(()=>dd(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return bn(o)}async claimProgression(e,n){let r=await this.write(()=>pl(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return bn(r)}async resetProgression(e,n){let r=await this.write(()=>yd(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return bn(r)}async write(e){return this.cache.invalidate(),e()}};var wi=t=>typeof t=="string"?t:"",ef=t=>typeof t=="number"?t:0;function Id(t){let e=t??{};return {orderId:wi(e.order_id),status:wi(e.status),source:wi(e.source),createdAt:ef(e.created_at)}}var Dr=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await nd(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(Id):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await Cl(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Id(r)}};function tf(t,e){return Math.min(7,Math.max(1,Math.ceil((t-e)/864e5)))}function nf(t,e,n,r){if(!t)return 0;if(typeof e=="number"&&Number.isInteger(e))return Math.min(7,Math.max(1,e));if(n===null)return 7;let o=Date.parse(n);return Number.isFinite(o)?tf(o,r):7}function Fr(t,e){let n=t?.passes;if(!Array.isArray(n))return Object.freeze([]);let r=n.flatMap(o=>{let i=o??{};if(typeof i.pass!="string"||i.pass==="")return [];let s=i.held===true,a=s&&typeof i.ends_at=="string"?i.ends_at:null,l=nf(s,i.days_left,a,e);return [Object.freeze({pass:i.pass,held:s,daysLeft:l,endsAt:a})]});return Object.freeze(r)}var rf=["live"],Si=6e4,Td=864e5;function of(t){return Object.freeze({pass:t,held:false,daysLeft:0,endsAt:null})}var Cd=Object.freeze([]);function af(t){let n=t.flatMap(r=>r.endsAt===null?[]:[Date.parse(r.endsAt)]).filter(r=>Number.isFinite(r));return n.length===0?null:Math.min(...n)}function Md(t,e,n={}){let{watch:r,isGuest:o}=n,i=n.now??(r===void 0?()=>Date.now():()=>r.clock.now()),s=new Set,a=null,l=0,d=null,c=Si,u=()=>{d!==null&&r?.clock.clearTimeout(d.handle),d=null;},p=y=>{u(),!(r===void 0||s.size===0)&&(d={handle:r.clock.setTimeout(w,y)});},g=y=>{let v=af(y);if(v===null||r===void 0){u();return}let E=v-r.clock.now();p(E>0?Math.min(E,Td):Si);},f=y=>{r?.log?.(`[gem] a passes 'changed' listener threw: ${y instanceof Error?y.message:String(y)}`);},h=y=>{let v=a!==null&&JSON.stringify(a)!==JSON.stringify(y);if(a=y,c=Si,g(y),!!v)for(let E of [...s])try{let T=E(y);typeof T?.then=="function"&&T.then(void 0,f);}catch(T){f(T);}},R=()=>{if(o?.()===true)return h(Cd),Promise.resolve(Cd);let y=l;return e.read("passes",rf,()=>jl(t)).then(v=>{if(y!==l)return R();let E=Fr(v,i());return h(E),E})},b=()=>{R().catch(()=>{p(c),c=Math.min(c*2,Td);});};function w(){l+=1,e.invalidate(),u(),r!==void 0&&s.size>0&&b();}return {api:{list:R,async get(y){return (await R()).find(E=>E.pass===y)??of(y)},on(y,v){let E=s.size===0;return s.add(v),E&&r!==void 0&&(a===null?b():g(a)),()=>{s.delete(v),s.size===0&&u();}}},recheck:w}}var Od=t=>typeof t=="number"?t:0,sf=t=>typeof t=="string"?t:"";function lf(t){let e=t??{};return {progressionDefinitionId:sf(e.progression_definition_id),currentValue:Od(e.current_value),completionCount:Od(e.completion_count),isCompleted:e.is_completed===true,..._i(e)}}var $r=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 Ml(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return lf(i)}catch{return o??null}}};var vn=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,s=i?e:e+"\0"+n.join("\0"),a=this.slots.get(s);if(a){let u=a.filledAt;if(u!==void 0&&(o===void 0||this.clock.now()-u<=o))return Promise.resolve(a.value);if(a.inFlight)return a.inFlight}let l=a??{};this.slots.set(s,l);let d=this.generation,c=r().then(u=>(i&&this.generation===d&&(l.value=u,l.filledAt=this.clock.now()),u)).finally(()=>{l.inFlight===c&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(s)===l&&this.slots.delete(s));});return l.inFlight=c,c}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 df(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var cf=new Set(wr);function uf(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))cf.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function qr(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return el(async(n,r)=>{let o;try{o=new URL(t.baseUrl.replace(/\/+$/,""));}catch{throw new ue("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 ue(`${JSON.stringify(typeof n.path=="string"?df(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 ue(`${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,h=g?f?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new ue(`the ${h} 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 s=n.bytes,a=n.bytes===void 0?void 0:"application/octet-stream";try{n.body!==void 0&&(s=JSON.stringify(n.body),a="application/json");}catch(g){throw new ue(`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}`,...a===void 0?{}:{"content-type":a},...uf(n.headers)},body:s,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 c=l.headers.get("etag"),u=Ri(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...c===null?{}:{etag:c},...u===void 0?{}:{retryAfterSeconds:u},...p===null||p===""?{}:{invocationId:p}}},t)}function Ri(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}function ki(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 Nr(t){try{let e=ki(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var ae=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},mf=3e4,pf=5e3,Gd=6e4,gf=2**31-1,Ld="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",ff=/^[A-Za-z0-9_]{1,64}$/;function Ve(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(!ff.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function Dd(t,e){let n=new AbortController,r=Date.now()+e;al(n.signal,()=>r-Date.now());let o=AbortSignal.timeout(e),i=()=>n.abort(o.reason),s=()=>n.abort(t?.reason);return t?.aborted?n.abort(t.reason):(o.addEventListener("abort",i,{once:true}),t?.addEventListener("abort",s,{once:true})),{signal:n.signal,release:()=>{o.removeEventListener("abort",i),t?.removeEventListener("abort",s);}}}function Ai(t,e){return t.aborted&&e?.aborted!==true}var yf=new Set(["x-ms-blob-type"]),hf=/^[ -~]+$/;function bf(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new ae("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(!yf.has(i))throw new ae("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"||!hf.test(o))throw new ae("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 ae("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(i)} twice.`);n[i]=o;}return n}function xi(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 Pi(t){return t?.reason==="not_found"}function vf(t){return t?.code==="save_conflict"}function Fd(t){return t instanceof M&&t.reason==="rate_limited"}async function $d(t,e){let n=await Nr(e);return new M("rate_limited",429,`the save ${t} answered 429: too many save calls. ${n}`.trim(),Ri(e.headers.get("retry-after")))}function jr(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function _f(t,e,n,r,o){let i=false,s=()=>i?false:(i=true,a.detach?.(),true),a={signal:n.signal,budget:r,deadlineAt:Date.now()+r,teardown:n.teardown===true,overwrite:n.overwrite===true,identity:o,resolve:l=>{s()&&t(l);},reject:l=>{s()&&e(l);},detach:void 0};return a}function qd(t,e){return t!==null&&e!==null&&e!==t}function Nd(t){return new ae("save_conflict",`save ${JSON.stringify(t)} was not written: the signed-in player changed while it waited for the write before it, and it holds the last player's progress.`)}var Br=class{constructor(e,n,r={},o){this.api=e;this.entity=n;this.options=r;this.identity=o;}api;entity;options;identity;versions=new Map;seq=0;versionsOf=null;writes=new Map;holdUntil=0;async put(e,n,r={}){let o;try{o=JSON.stringify(n);}catch(i){throw new ae("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 ae("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={}){if(Ve(e),r.signal?.aborted)throw jr(r.signal);let o=this.budget(r.timeoutMs),i=this.slotWrites(e);return new Promise((s,a)=>{let l=i.queued;l?.release();let d=l?.waiters[l.waiters.length-1];d!==void 0&&this.holdOwn(i,d);let c=this.identity?.()??null;for(let u of l?.waiters.slice()??[])qd(u.identity,c)&&this.drop(i,u,Nd(e));i.queued=this.queue(i,n,r,_f(s,a,r,o,c),l?.waiters??[]),i.wake?.(),this.pump(e,i);})}holdOwn(e,n){let{signal:r}=n,o=n.deadlineAt-Date.now();if(r?.aborted)return this.drop(e,n,jr(r));if(o<=0)return this.drop(e,n,this.timeout("save",n.budget));let i=AbortSignal.timeout(o),s=()=>this.drop(e,n,this.timeout("save",n.budget)),a=()=>{r&&this.drop(e,n,jr(r));};i.addEventListener("abort",s,{once:true}),r?.addEventListener("abort",a,{once:true}),n.detach=()=>{i.removeEventListener("abort",s),r?.removeEventListener("abort",a);};}drop(e,n,r){let o=e.queued?.waiters,i=o?.indexOf(n)??-1;i>=0&&o?.splice(i,1),n.reject(r),e.wake?.();}queue(e,n,r,o,i){let{budget:s}=o,a=[...i,o],l=AbortSignal.timeout(s),d=g=>{if(e.queued===p){this.take(e,p);for(let f of a)f.reject(g);e.wake?.();}},c=()=>d(this.timeout("save",s)),u=()=>{r.signal&&d(jr(r.signal));};l.addEventListener("abort",c,{once:true}),r.signal?.addEventListener("abort",u,{once:true});let p={bytes:n,options:r,budget:s,deadlineAt:o.deadlineAt,identity:o.identity,waiters:a,release:()=>{l.removeEventListener("abort",c),r.signal?.removeEventListener("abort",u);}};return p}async pump(e,n){if(!n.running){n.running=true;try{for(let r=n.queued;r!==void 0;r=n.queued){let o=Date.now(),i=this.holdUntil-o;if(i>0){if(i>=r.deadlineAt-o){this.take(n,r);for(let l of r.waiters)l.reject(this.held(e,i));continue}for(let l of r.waiters.slice(0,-1))i>=l.deadlineAt-o&&this.drop(n,l,this.held(e,i));}let s=Math.max(i,this.spacing(n,r,o));if(s>0){await this.pause(n,s);continue}this.take(n,r);let a;try{a=this.precondition(e,r);}catch(l){for(let d of r.waiters)d.reject(l);continue}n.lastSentAt=o;try{let l=await this.send(e,r,a);for(let d of r.waiters)d.resolve(l);}catch(l){for(let d of r.waiters)d.reject(l);}}}finally{n.running=false;}}}spacing(e,n,r){if(e.lastSentAt===void 0||n.waiters.some(s=>s.teardown))return 0;let o=this.options.minWriteIntervalMs??pf,i=Math.min(...n.waiters.map(s=>s.deadlineAt-s.budget/2));return Math.min(e.lastSentAt+o,i)-r}pause(e,n){return new Promise(r=>{let o=()=>{clearTimeout(i),e.wake===o&&(e.wake=void 0),r();},i=setTimeout(o,Math.min(n,gf));e.wake=o;})}take(e,n){e.queued===n&&(e.queued=void 0),n.release();}slotWrites(e){let n=this.writes.get(e);return n===void 0&&(n={running:false,queued:void 0,lastSentAt:void 0,wake:void 0},this.writes.set(e,n)),n}noteRateLimit(e){if(!Fd(e))return;let n=e.retryAfterSeconds,r=n===void 0?Gd:Math.min(n*1e3,Gd);this.holdUntil=Math.max(this.holdUntil,Date.now()+r);}held(e,n){let r=Math.ceil(n/1e3);return new M("rate_limited",429,`save ${JSON.stringify(e)} was not sent: the platform refused a save call for the rate, and the wait it asked for ends in ${r}s, after this call's timeoutMs. Keep the state and write once the wait is over.`,r)}async send(e,n,r){let{bytes:o,options:i,budget:s}=n,a=i.contentType??"application/octet-stream",l=Dd(i.signal,Math.max(0,n.deadlineAt-Date.now()));try{let d=await fd(this.api,this.entity.type,this.entity.id,e,{size_bytes:o.byteLength,content_type:a,...r,...i.metadata===void 0?{}:{metadata:i.metadata}},{signal:l.signal});if(typeof d.upload_url!="string"||typeof d.session_id!="string")throw new ae("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let c=bf(d.upload_headers,e),u,p=this.options.fetch??globalThis.fetch.bind(globalThis);try{u=await p(d.upload_url,{method:"PUT",headers:{"content-type":a,...c},body:o,credentials:"omit",signal:l.signal});}catch(f){throw Ai(l.signal,i.signal)?this.timeout("upload",s):new ae("upload_failed",`${Ld} for PUT. Underlying error: ${f}`)}if(u.status===429)throw await $d("upload",u);if(!u.ok){let f=await Nr(u);throw new ae("upload_failed",u.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. "+f:`the save upload answered ${u.status}. `+(u.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. ":"")+f)}let g=xi(await Sl(this.api,this.entity.type,this.entity.id,e,{session_id:d.session_id},{signal:l.signal}));return this.remember(e,g.etag?{kind:"etag",etag:g.etag}:void 0),g}catch(d){throw vf(d)?new ae("save_conflict",`save ${JSON.stringify(e)} was not written: the stored save changed since this game last loaded or wrote it, so another device or tab saved in between. Load it again and decide what to write from what is stored, rather than resending this write.`):(this.noteRateLimit(d),this.rethrow(d,i.signal,l.signal,"save",s))}finally{l.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 ae("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={}){Ve(e);let r=this.budget(n.timeoutMs),o=Dd(n.signal,r),i=this.seq;try{let s;try{let c=await fi(this.api,this.entity.type,this.entity.id,e,{signal:o.signal});if(!c.modified)return this.remember(e,{kind:"empty"},i),null;s=c.body;}catch(c){if(Pi(c))return this.remember(e,{kind:"empty"},i),null;throw c}if(typeof s.download_url!="string")throw new ae("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),l;try{l=await a(s.download_url,{credentials:"omit",signal:o.signal});}catch(c){throw Ai(o.signal,n.signal)?this.timeout("download",r):new ae("download_failed",`${Ld} for GET. Underlying error: ${c}`)}if(l.status===429)throw await $d("download",l);if(!l.ok){let c=await Nr(l);throw new ae("download_failed",`the save download answered ${l.status}. `+(l.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+c)}let d=new Uint8Array(await l.arrayBuffer());return this.remember(e,s.etag?{kind:"etag",etag:s.etag}:void 0,i),d}catch(s){throw this.slots().get(e)===void 0&&this.remember(e,{kind:"failed"}),this.noteRateLimit(s),this.rethrow(s,n.signal,o.signal,"load",r)}finally{o.release();}}async describe(e,n={}){try{let r=await fi(this.api,this.entity.type,this.entity.id,Ve(e),{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?xi(r.body):null}catch(r){if(Pi(r))return null;throw r}}async list(e={}){let n=await rd(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(xi),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await vl(this.api,this.entity.type,this.entity.id,Ve(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!Pi(r))throw r}this.remember(e,{kind:"empty"});}precondition(e,n){if(qd(n.identity,this.identity?.()??null))throw Nd(e);if(n.waiters.some(o=>o.overwrite))return {};let r=this.slots().get(e);if(r===void 0)return {};if(r.kind==="etag")return {if_match:r.etag};if(r.kind==="empty")return {if_none_match:"*"};throw new ae("load_failed",`save ${JSON.stringify(e)} was not written: the last load of this slot failed, so what this write would replace is unknown, and it could be the player's real progress. Load it again before saving, or pass overwrite: true if replacing whatever is stored is what you mean.`)}remember(e,n,r){let o=this.slots(),i=o.get(e);r!==void 0&&i!==void 0&&i.kind!=="failed"&&i.seq>r||(this.seq+=1,n===void 0?o.delete(e):o.set(e,{...n,seq:this.seq}));}slots(){let e=this.identity?.()??null;return e!==null&&e!==this.versionsOf&&(this.versionsOf!==null&&this.versions.clear(),this.versionsOf=e),this.versions}budget(e){return e??this.options.timeoutMs??mf}timeout(e,n){return new ae("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,o,i){return e instanceof ae||Fd(e)?e:Ai(r,n)?this.timeout(o,i):e}};function wf(t){try{return gi(t)}catch{return t}}function Ei(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"?wf(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var Ur=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await td(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(o=>Ei(o)):[]}async get(e,n={}){try{let r=await Pl(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?Ei(r.body,r.etag):null}catch(r){if(jd(r))return null;throw r}}async put(e,n,r={}){let o=await cd(this.api,this.entity.type,this.entity.id,e,{value:Sr(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return Ei(o)}async delete(e,n){try{await bl(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});}catch(r){if(!jd(r))throw r}}};function jd(t){return t?.reason==="not_found"}function Ii(t,e,n={}){let r=new vn(me,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let o=new Mr(t,e,r);return {settings:new Ur(t,e),inventory:o,saves:new Br(t,e,n.saves??{},n.identity),currencies:new Cr(o,n.resolveCurrencyId),mutations:new Lr(t,e,r,n.handOffRefusedPurchase),orders:new Dr(t,e),progressions:new $r(t,e,o)}}function Bd(t,e,n={}){let r=new vn(me,n.identity),o=Md(t,r,n);return {scope:{...Ii(t,e,n),passes:o.api},recheckPasses:o.recheck}}var Ti={type:"players",id:"me"};var gt=t=>typeof t=="string"?t:"",Ft=t=>typeof t=="number"?t:0;function Wr(t,e){let n=e??{},r=gt(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:gt(n.player_id),gameId:gt(n.game_id),channel:gt(n.channel)||"release",name:gt(n.name),slotIndex:Ft(n.slot_index),isActive:n.is_active!==false,createdAt:gt(n.created_at),updatedAt:gt(n.updated_at)}}var Hr=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=Ii(this.api,{type:"characters",id:e},{saves:this.saves,identity:this.identity,resolveCurrencyId:this.resolveCurrencyId}),this.scopes.set(e,n)),n};refreshHeld(){for(let e of this.scopes.values())e.inventory.refresh();}async list(e){let r=(await ed(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(o=>Wr(this.scope,o)):[]}async get(e,n){let r=await Al(this.api,e,n===void 0?{}:{signal:n});return Wr(this.scope,r)}async create(e){let n=await gl(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return Wr(this.scope,n)}async update(e,n,r){let o=await gd(this.api,e,{name:n},r===void 0?{}:{signal:r});return Wr(this.scope,o)}async delete(e,n){await hd(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await Vl(this.api,e===void 0?{}:{signal:e})??{};return {totalSlots:Ft(r?.total_slots),availableSlots:Ft(r?.available_slots),activeCharacterCount:Ft(r?.active_character_count),defaultMaxSlots:Ft(r?.default_max_slots),purchasedExtraSlots:Ft(r?.purchased_extra_slots),canPurchaseMore:r?.can_purchase_more===true}}};var Hd="[gem: use gem.text.toPlain()]",Ud=new Set,Wd;function Sf(t){try{if(Ud.has(t))return;let e=globalThis.location;if(Wd??=!!e?.port&&tt(e.hostname??""),!Wd)return;Ud.add(t),console.warn(`[gem] ${t} is PlayerText, turned into a string: players see ${Hd}. Render text.toPlain(value) (text is in @indiegems/gem-web-sdk/sdk).
2
+ ${new Error().stack}`);}catch{}}var Se=class{#e;#n;constructor(e,n="player text"){this.#e=e,this.#n=n,Object.freeze(this);}toString(){return Sf(this.#n),Hd}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function we(t,e){return new Se(t,e)}var ft={toPlain(t){return Se.unwrap(t)},compare(t,e,n){let r=t instanceof Se?Se.unwrap(t):t,o=e instanceof Se?Se.unwrap(e):e;if(typeof Intl>"u"||typeof Intl.Collator!="function")return r<o?-1:r>o?1:0;let i;try{i=new Intl.Collator(n);}catch{i=new Intl.Collator;}return i.compare(r,o)},equals(t,e){let n=t instanceof Se?Se.unwrap(t):t,r=e instanceof Se?Se.unwrap(e):e;return n.normalize("NFC")===r.normalize("NFC")}};var $t=t=>typeof t=="string"?t:"";function Vr(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:$t(e.transfer_id),status:$t(e.status),sourceEntityId:$t(e.source_entity_id),targetEntityId:$t(e.target_entity_id),...n===void 0?{}:{message:we(n,"transfer.message")},createdAt:$t(e.created_at),expiresAt:$t(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function Rf(){return crypto.randomUUID()}var Kr=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 Xl(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:Rf()},e.signal===void 0?{}:{signal:e.signal});return Vr(n)}async list(e={}){let r=await ad(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(Vr):[],...o===void 0?{}:{nextCursor:o}}}async get(e,n){let r=await Kl(this.api,e,n===void 0?{}:{signal:n});return Vr(r)}async accept(e,n){return this.resolve(()=>dl(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>pd(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>ul(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),Vr(await e())}};var Me=class extends Error{constructor(n,r){super(r);this.code=n;this.name="PreviewError";}code};function Yd(t){return Number.isFinite(t)?Math.min(1e5,Math.max(1e4,Math.trunc(t))):1e4}function Vd(t,e){if(!Number.isSafeInteger(t)||t<=0)return Math.max(0,Math.trunc(t)||0);let n=BigInt(t)*BigInt(Yd(e));return Number(n/BigInt(1e4))}var de=t=>t!==null&&typeof t=="object"?t:{},Re=t=>Array.isArray(t)?t:[],be=t=>typeof t=="string"&&t!==""?t:void 0,Pe=t=>typeof t=="number"&&Number.isSafeInteger(t)?t:void 0;function Jr(t,e){return t.find(n=>n.id===e)??t.find(n=>n.slug===e)}function Kd(t){let e=de(t),n=e.type==="roll"?e:de(e.roll),r=be(n.loot_table_id)??be(n.loot_table);if(r!==void 0)return {kind:"roll",lootTableId:r,count:Pe(n.count)??1};if(e.type==="item_grant"){let o=be(e.item_definition_id);return o===void 0?null:{kind:"item",itemId:o,quantity:Pe(e.quantity)??1}}if(e.type==="currency_grant"){let o=be(e.currency_id),i=Pe(e.amount);return o===void 0||i===void 0?null:{kind:"currency",currencyId:o,amount:i}}return null}function kf(t,e){let n=Re(de(de(t).config).tracks);if(n.length===0)return e;let r=0;for(let o of n)for(let i of Re(de(o).levels)){let s=de(i),a=Pe(s.threshold),l=Pe(s.level);a!==void 0&&l!==void 0&&e>=a&&(r=Math.max(r,l));}return r}function Af(t,e,n){let r=o=>Pe(t.min)??Pe(t.min_quantity)??Pe(t.min_amount)??Pe(t.min_level)??o;switch(t.kind){case "holds_pass":{let o=be(t.pass);return o===void 0||e.passes===null?"unknown":e.passes.get(o)===true}case "owns_item":{let o=be(t.item_definition_id)??be(t.item);return o===void 0||e.items===null?"unknown":(e.items.get(o)??0)>=r(1)}case "has_currency":{let o=be(t.currency_id)??be(t.currency);return o===void 0||e.currencies===null?"unknown":(e.currencies.get(o)??0)>=r(1)}case "progression_complete":{let o=be(t.progression_definition_id)??be(t.progression);return o===void 0||e.progressions===null?"unknown":e.progressions.get(o)?.completed===true}case "progression_level":{let o=be(t.progression_definition_id)??be(t.progression);if(o===void 0||e.progressions===null)return "unknown";let i=e.progressions.get(o),s=i===void 0?null:n(o,i.value);return s!==null&&s>=r(1)}default:return "unknown"}}function Jd(t,e,n){let r=[],o=false;return t.forEach((i,s)=>{let a=de(i),l=Af(a,e,n);l===false?r.push({index:s,kind:String(a.kind)}):l==="unknown"&&(o=true);}),r.length>0?{eligible:false,unmet:r}:{eligible:o?"unknown":true,unmet:[]}}function zd(t,e){let n=de(t),r=Re(de(n.config).platform_grants),o=[];for(let i of r){let s=de(i),a=de(s.target),l=be(a.platform_currency_id),d=be(a.platform_currency_slug);if(l===void 0&&d===void 0)continue;let c={...l===void 0?{}:{currencyId:l},...d===void 0?{}:{currencySlug:d}};if(s.mode==="on_add"){if(e===void 0||e<=0)continue;let p=(Pe(s.per_unit)??1)*e;if(!Number.isSafeInteger(p)||p<=0)continue;o.push({...c,base:p,ifComplete:false});}else if(s.mode==="on_complete"){let u=Pe(s.amount);if(u===void 0||u<=0)continue;o.push({...c,base:u,ifComplete:true});}}return o}function zr(t,e){let n=1e4;for(let r of t)(e.currencyId!==void 0&&r.currencyId===e.currencyId||e.currencySlug!==void 0&&r.currencySlug===e.currencySlug)&&(n=Math.max(n,Yd(r.multiplierBp)));return n}function Qd(t){return t.earnMultipliers.map(e=>({currencySlug:e.currencySlug,multiplierBp:e.multiplierBp}))}function Xd(t){return {...t.currencySlug===void 0?{}:{currencySlug:t.currencySlug},...t.currencyId===void 0?{}:{currencyId:t.currencyId}}}function xf(t,e){if(t.currencyId!==void 0&&t.currencySlug!==void 0)return t;let n=e.find(r=>t.currencyId!==void 0&&r.currencyId===t.currencyId||t.currencySlug!==void 0&&r.currencySlug===t.currencySlug);return {...t,...t.currencyId===void 0&&n?.currencyId!==void 0?{currencyId:n.currencyId}:{},...t.currencySlug===void 0&&n?.currencySlug!==void 0?{currencySlug:n.currencySlug}:{}}}function Pf(t,e,n,r){if(e<=1e4||n.passes===null)return null;for(let o of r)if(!(o.pass===void 0||n.passes.get(o.pass)!==true)&&zr(Qd(o),t)===e)return o.pass;return null}var Ef=new Set(["owns_item","has_currency","progression_complete","progression_level"]);function Zd(t,e){if(!("recipe"in e))return false;let n=Re(t.catalogs).flatMap(o=>Re(de(o).recipes)),r=Jr(n.map(de),e.recipe);return Re(r?.bonuses).some(o=>Re(de(o).requires).some(i=>Ef.has(String(de(i).kind))))}function ec(t){let{config:e,target:n,boost:r,holdings:o,offers:i}=t,s=Re(e.catalogs).flatMap(b=>Re(de(b).recipes)),a=Re(e.progressions).map(de),l=(b,w)=>{let y=a.find(v=>v.id===b);return y===void 0?null:kf(y,w)},d=[],c=[],u=[];if("recipe"in n){if(typeof n.recipe!="string"||n.recipe==="")throw new Me("invalid_argument","preview: `recipe` must be a recipe id or slug");let b=Jr(s.map(de),n.recipe);if(b===void 0)throw new Me("not_found",`preview: no recipe ${JSON.stringify(n.recipe)}`);for(let y of Re(b.grants)){let v=Kd(y);v!==null&&d.push(v);let E=de(y);if(E.type==="progression_add"){let T=Jr(a,String(E.progression_definition_id));T!==void 0&&c.push(...zd(T,Pe(E.amount)));}}let w=be(b.loot_table_id);w!==void 0&&d.push({kind:"roll",lootTableId:w,count:1}),u=Re(b.bonuses);}else if("progression"in n){if(typeof n.progression!="string"||n.progression==="")throw new Me("invalid_argument","preview: `progression` must be a progression id or slug");if(n.add!==void 0&&(!Number.isSafeInteger(n.add)||n.add<=0))throw new Me("invalid_argument","preview: `add` must be a positive integer");let b=Jr(a,n.progression);if(b===void 0)throw new Me("not_found",`preview: no progression ${JSON.stringify(n.progression)}`);c=zd(b,n.add);}else throw new Me("invalid_argument","preview: pass `{ recipe }` or `{ progression }`");c=c.map(b=>xf(b,r));let p=c.map(b=>{let w=zr(r,b),y=Vd(b.base,w),v=y-b.base,E=Pf(b,w,o,i),T=v<=0?[]:[E===null?{source:"boost",amount:v}:{source:"pass",pass:E,amount:v}];return {...Xd(b),base:b.base,total:y,breakdown:T,...b.ifComplete?{ifComplete:true}:{}}}),g=u.map(de).map(b=>({id:String(b.id??""),requires:Re(b.requires),grants:Re(b.grants).map(Kd).filter(w=>w!==null)})),f=g.map(b=>({id:b.id,grants:b.grants,...Jd(b.requires,o,l)})),h=[],R=new Set;for(let b of i){let w=b.pass;if(w===void 0||R.has(w)||(R.add(w),o.passes===null||o.passes.get(w)===true))continue;let y={...o,passes:new Map([...o.passes,[w,true]])},v=Qd(b),E=c.flatMap(($,q)=>{let U=Math.max(zr(r,$),zr(v,$)),C=Vd($.base,U),O=C-p[q].total;return O>0?[{...Xd($),total:C,extra:O,...$.ifComplete?{ifComplete:true}:{}}]:[]}),T=g.filter(($,q)=>f[q].eligible!==true&&Jd($.requires,y,l).eligible===true).map($=>({id:$.id,grants:$.grants}));E.length===0&&T.length===0||h.push({pass:w,name:b.name,offer:b,platformGrants:E,bonuses:T});}return {grants:d,platformGrants:p,bonuses:f,upsells:h}}var If=t=>typeof t=="string"?t:"",Tf=t=>typeof t=="string"&&t?t:void 0,Cf=t=>typeof t=="number"?t:void 0;function tc(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 Mf(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new fe("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 fe("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=Cf(e.version);if(r===void 0)throw new fe("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let o=(l,d,c)=>{let u=If(l.id);if(!u)throw new fe("config_malformed",`${d}[${c}] has no \`id\`. Keys present: ${Object.keys(l).join(", ")||"(none)"}`);return u},i=n("items");i.forEach((l,d)=>o(l??{},"items",d));let s=n("currencies");s.forEach((l,d)=>o(l??{},"currencies",d));let a=t;return {...a,version:r,hash:typeof a.hash=="string"?a.hash:"",items:i,currencies:s,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 a.kv=="object"&&a.kv!==null&&!Array.isArray(a.kv)?a.kv:{},item:tc(i),currency:tc(s)}}var fe=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},nc=10*1024*1024,rc=15e3,oc=new Set(["dev","test","release"]);function Of(t){if(!oc.has(t))throw new fe("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...oc].join(", ")}. gem-api would reject the assignment read.`);return t}var Xr=t=>typeof t=="number"?t:0,Ci=t=>typeof t=="string"?t:"";function Gf(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:Ci(o.entry_id),weight:Xr(o.weight),dropRate:Xr(o.drop_rate),...i===void 0?{}:{rarityTier:i}}}):[];return {lootTableId:Ci(e.loot_table_id),name:Ci(e.name),rollCount:Xr(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:Xr(e.total_weight),entries:n}}var Yr=class{constructor(e,n,r={}){this.api=e;this.channel=n;this.options=r;}api;channel;options;loaded=void 0;inFlight=null;generation=0;dropRatesByConfig=new WeakMap;load(){if(this.loaded!==void 0)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=void 0,this.inFlight=null,this.generation+=1;}bindPreview(e){this.previewSources=e;}previewSources=null;async preview(e){let n=this.previewSources;if(n===null)throw new Me("unsupported","gem.gameConfig.preview runs in the browser only: a function or a server runs the recipe and reads the receipt (gem.earnings.fromReceipt)");let r=await this.load();if(r===null)throw new fe("config_channel_unknown","preview needs a loaded config, and this session's channel has none");let o=Zd(r,e),[i,s]=await Promise.all([n.holdings(o),n.offers()]);return ec({config:r,target:e,boost:n.boost(),holdings:i,offers:s})}async dropRates(e,n){let r=await this.load();if(r===null)throw new fe("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 s=(async()=>{let a=await xl(this.api,e,n===void 0?{}:{signal:n});return Gf(a)})().catch(a=>{throw o?.get(e)===s&&o.delete(e),a});return o.set(e,s),s}async fetchConfig(){let e=AbortSignal.timeout(this.options.timeoutMs??rc),n;try{let l=await kl(this.api,Of(this.channel()),{signal:e});if(!l.modified)throw new fe("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");n=l.body;}catch(l){if(l instanceof fe)throw l;if(l?.reason==="not_found")return null;throw l}let r=Tf(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 fe("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??rc}ms`):new fe("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=>ki(d)).catch(()=>"");throw new fe("config_unreachable",`the config document answered ${i.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let s=await i.text();if(s.length>nc)throw new fe("config_too_large",`the config document is ${s.length} bytes, over the ${nc} cap`);let a;try{a=JSON.parse(s);}catch(l){throw new fe("config_malformed",`config document is not JSON: ${String(l)}`)}return Mf(a)}};var Oi=t=>t!==null&&typeof t=="object"?t:{},Gi=t=>typeof t=="string"&&t!==""?t:void 0,Mi=t=>typeof t=="number"&&Number.isSafeInteger(t)?t:void 0;function Lf(t,e){let n=Oi(t);if(n.type!=="platform_grant")return null;let r=Gi(n.target_currency_id),o=Mi(n.granted);if(r===void 0||o===void 0)return null;let i=Mi(n.requested)??o,s=Math.max(0,Math.min(Mi(n.base_granted)??Math.min(i,o),o)),a=o-s,l=Oi(n.boost_source),d=Gi(l.pass),c=e(r);return {...c===void 0?{}:{currencySlug:c},currencyId:r,base:s,total:o,breakdown:a<=0?[]:[d===void 0?{source:"boost",amount:a}:{source:"pass",pass:d,amount:a}]}}function Qr(t){return {async fromReceipt(e){let n=Gi(Oi(e).target_currency_id),r=n===void 0?void 0:t.knownSlug(n);return n!==void 0&&r===void 0&&(r=await t.readSlugs().then(o=>o.get(n)||void 0,()=>{})),Lf(e,()=>r)}}}var ic=400,qe=t=>typeof t=="string"?t:"",Df=/(?:Z|[+-]\d{2}:?\d{2})$/i;function yt(t){let e=qe(t);if(!Df.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var Ff=/^[0-9a-f]{1,64}$/,$f=/^[0-9a-f]{16}$/,qf=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,Nf=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function Li(t){let e=qe(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])],s=new Date(Date.UTC(r,o-1,i));return s.getUTCFullYear()===r&&s.getUTCMonth()===o-1&&s.getUTCDate()===i?e:void 0}var jf=4096,Bf=new TextEncoder;function Uf(t){let e=qe(t.challenge_data),n=qe(t.challenge_data_hash);return e===""||!$f.test(n)?{}:Bf.encode(e).length>jf?{}:{data:e,dataHash:n}}function Wf(t){let e=t??{},n=yt(e.period_start_at),r=yt(e.period_ends_at);if(n===0||r===0)return;let o=qe(e.slug),i=qe(e.seed),s=Li(e.period_local_date),a=qe(e.boundary),l=qe(e.reset_time);return {id:qe(e.progression_definition_id),...o===""?{}:{slug:o},window:qe(e.window),periodStartAt:n,periodEndsAt:r,...s===void 0?{}:{periodLocalDate:s},boundary:qf.test(a)?a:"",resetTime:Nf.test(l)?l:"",seed:Ff.test(i)?i:"",...Uf(e)}}function qt(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 Zr(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(Wf).filter(n=>n!==void 0):[]}var _n=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;qt(n);let r=await Zl(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return Zr(r)}};function Ne(t){return typeof t=="string"&&t!==""?t:void 0}var ac=new Set(["localhost","127.0.0.1","[::1]"]);function ht(t){return Nt(t)}function Nt(t){let e=Ne(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:"&&ac.has(n.hostname)))return e}var Hf=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,Vf=/^[a-z][a-z0-9_]{0,31}$/;function Kf(t){if(!Array.isArray(t))return;let e=[],n=new Set;for(let r of t.slice(0,8)){let o=r??{},i=Ne(o.family),s=Ne(o.avatar_3d_id),a=ht(o.model_url),l=ht(o.icon_url);i===void 0||!Vf.test(i)||n.has(i)||s===void 0||!Hf.test(s)||a===void 0||l===void 0||(n.add(i),e.push({family:i,id:s,modelUrl:a,iconUrl:l}));}return e}function Jf(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},o=Ne(r.item_id),i=ht(r.icon_url);o!==void 0&&i!==void 0&&e.push({itemId:o,iconUrl:i});}return e}function Oe(t){let e=t??{},n=Ne(e.player_id),r=Ne(e.display_name),o=Ne(e.discriminator),i=Ne(e.display_tag),s=Ne(e.avatar_icon_id),a=ht(e.avatar_icon_url),l=Ne(e.avatar_3d_id),d=ht(e.avatar_3d_model_url),c=ht(e.avatar_3d_icon_url),u=Kf(e.avatars_3d);return {...n===void 0?{}:{playerId:n},...r===void 0?{}:{displayName:we(r,"displayName")},...o===void 0?{}:{discriminator:o},...i===void 0?{}:{displayTag:we(i,"displayTag")},...s===void 0?{}:{avatarIconId:s},...a===void 0?{}:{avatarIconUrl:a},...l===void 0?{}:{avatar3dId:l},...d===void 0?{}:{avatar3dModelUrl:d},...c===void 0?{}:{avatar3dIconUrl:c},...u===void 0?{}:{avatars3d:u},badges:Jf(e.badges)}}var zf=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function Di(t){if(t===void 0)return;let e=ht(t);if(e===void 0)return;let n=new URL(e);return ac.has(n.hostname)||zf.has(n.origin)?e:void 0}var sc=100,cc=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function Fi(t){let{periodsBack:e,period:n,playerId:r}=t;if(qt(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!cc.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 uc(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!cc.test(e))return;let n=Li(t.period_local_date),r=yt(t.period_start_at),o=yt(t.period_ends_at),i=r>0&&o>0;return {id:e,...n===void 0?{}:{localDate:n},...i?{startAt:r,endsAt:o}:{},opensAt:yt(t.opens_at),closesAt:yt(t.closes_at),final:t.final===true}}var wn=t=>typeof t=="string"?t:"",jt=t=>typeof t=="number"?t:0,Sn=t=>typeof t=="string"?t:void 0,Xf=t=>typeof t=="number"?t:void 0,mc={player:"players",character:"characters"};function Yf(t,e){let n=t??{},r=Sn(n.entity_id),o=typeof n.entity_type=="string"&&Object.hasOwn(mc,n.entity_type)?n.entity_type:void 0,i=pc(n.stats),s=n.properties!==null&&typeof n.properties=="object"?n.properties:void 0,a=e?n.is_viewer===true:void 0;return {...Oe(n),rank:jt(n.rank),occurredAt:jt(n.occurred_at),...a===void 0?{}:{isViewer:a},...r===void 0?{}:{entityId:r},...o===void 0?{}:{entityType:o},...i===void 0?{}:{stats:i},...s===void 0?{}:{properties:s}}}function lc(t,e){let n=t??{},r=Sn(n.bucket_1),o=Sn(n.bucket_2),i=Xf(n.update_frequency_seconds),s=uc(n);return {leaderboardType:wn(n.leaderboard_type),runType:wn(n.run_type),...r===void 0?{}:{bucket1:r},...o===void 0?{}:{bucket2:o},entries:Array.isArray(n.entries)?n.entries.map(a=>Yf(a,e)):[],generatedAt:jt(n.generated_at),...i===void 0?{}:{updateFrequencySeconds:i},...s===void 0?{}:{period:s}}}function dc(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=pc(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:jt(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function pc(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 Qf(t,e,n){let r=t??{},o=Sn(r.bucket_1),i=Sn(r.bucket_2),s=uc(r);return {leaderboardType:wn(r.leaderboard_type),runType:wn(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(dc).filter(a=>a!==void 0):[],personalBest:dc(r.personal_best)??null,totalRuns:jt(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:jt(r.generated_at),...s===void 0?{}:{period:s}}}var Rn=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=Fi(n),o=await ql(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 lc(o,false)}async friends(e,n={}){let r=Fi(n),o=await Ll(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 lc(o,true)}async mine(e,n={}){return this.#n(e,"player","me",n)}async character(e,n,r={}){return this.#n(e,"character",n,r)}async#n(e,n,r,o){if(o.limit!==void 0){let{limit:l}=o;if(!Number.isInteger(l)||l<1||l>sc)throw new TypeError(`limit must be an integer between 1 and ${sc}, got ${String(l)}`)}let i=Fi(o),s=await Tl(this.#e,e,mc[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}}),a=n==="player"&&r==="me"&&wn((s??{}).entity_id)||r;return Qf(s,n,a)}};var eo=t=>typeof t=="string"?t:"",$i=t=>typeof t=="number"?t:0;function gc(t){let e=t??{};return {playerId:eo(e.player_id),key:eo(e.key),value:e.value,updatedAt:$i(e.updated_at)}}function Zf(t){let e=t??{};return {...Oe(e),playerId:eo(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:$i(e.updated_at)}}function ey(t){return t?.reason==="not_found"}var kn=class{constructor(e,n){this.api=e;this.selfPlayerId=n;}api;selfPlayerId;async friends(e,n={}){let o=await Dl(this.api,Ve(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:eo(o.key),entries:Array.isArray(o.entries)?o.entries.map(Zf):[],generatedAt:$i(o.generated_at)}}async of(e,n,r={}){try{return gc(await Hl(this.api,e,Ve(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(o){if(ey(o))return null;throw o}}async set(e,n,r={}){if(Ve(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 gc(await ud(this.api,o,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await _l(this.api,r,Ve(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var ty="gemChallenge",fc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function yc(t){if(!(typeof t!="string"||t===""))try{return new URLSearchParams(t).get(ty)??void 0}catch{return}}var bt=class extends M{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});}},to=t=>typeof t=="string"?t:void 0;function hc(t){let e=t??{};return {...Oe(e),playerId:to(e.player_id)??""}}function bc(t){let e=t.has_more===true?to(t.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function ny(t){let e=t??{};return {friends:Array.isArray(e.data)?e.data.map(hc):[],...bc(e)}}var qi=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function ry(t){return typeof t!="object"||t===null||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(e=>typeof e[1]=="string"||typeof e[1]=="number"&&Number.isFinite(e[1])))}function vc(t){let e=t??{},n=qi(e.opened_at),r=qi(e.answered_at);return {id:to(e.item_id)??"",from:hc(e.sender),template:to(e.template)??"",params:ry(e.params),createdAt:qi(e.created_at)??0,...n===void 0?{}:{openedAt:n},...r===void 0?{}:{answeredAt:r}}}function oy(t){let e=t??{};return {challenges:Array.isArray(e.data)?e.data.map(vc):[],...bc(e)}}function iy(t){let e=t;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var An=class{#e;#n;#o;#s;#t;constructor(e,n={}){this.#e=e,this.#n=n.challenge,this.#o=n.inviteToPlay,this.#s=n.setInviteParams,this.#t=n.launchedChallengeId;}async list(e={}){let n=await id(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return ny(n)}challenge(e){return this.#n===void 0?Promise.resolve({outcome:"unavailable"}):this.#n(e)}inviteToPlay(e){return this.#o===void 0?Promise.resolve(false):this.#o(e)}setInviteParams(e){return this.#s===void 0?false:this.#s(e)}async inbox(e={}){let n=await od(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return oy(n)}async launchedChallenge(e={}){let n=this.#t;if(n===void 0||!fc.test(n))return null;try{return vc(await $l(this.#e,n,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(iy(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!fc.test(e))throw new M("invalid",400,"id must be a FriendChallenge.id, as gem.friends.launchedChallenge() or inbox() returned it",void 0,"bad_request");await sd(this.#e,e);}};var ay=0;function pe(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++ay)}-${String(Date.now())}-${t}`}}var sy=12e4,_c=8,ly=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,dy=/^[a-z0-9][a-z0-9_-]{0,63}$/;function xn(t,e,n={}){return new bt(new M("invalid",400,e,void 0,t),n)}function cy(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function uy(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!ly.test(e))return {error:xn("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!dy.test(n))return {error:xn("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(!cy(r))return {error:xn("param_invalid","params must be a plain object of strings and integers")};let o={},i=Object.keys(r);for(let s of i){let a=r[s];if(typeof a=="string"||typeof a=="number"&&Number.isSafeInteger(a)){Object.defineProperty(o,s,{value:a,enumerable:true,writable:true,configurable:true});continue}return {error:xn("param_invalid",`params.${s} must be a string or a safe integer`,{param:s})}}return i.length>_c?{error:xn("param_undeclared",`params has ${String(i.length)} keys; a template declares at most ${String(_c)}`)}:{playerId:e,template:n,params:o}}function my(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 bt(new M("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 bt(new M("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 py(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function wc(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=uy(n);if("error"in r)return Promise.reject(r.error);let o=`challenge-${pe()}`;return new Promise((i,s)=>{let a={},l=c=>{e.delete(o)&&(t.clock.clearTimeout(a.timer),"error"in c?s(c.error):i(c.outcome));};e.set(o,l),a.timer=t.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},t.timeoutMs??sy);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 (${py(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(my(n));}}}var gy=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","invite","_s","fbclid","ttclid","gclid","gbraid","wbraid","msclkid","gem_link","gem_test_ads","gem_cluster","moments","ads"]),fy=["utm_"];function Ni(t){return gy.has(t)||fy.some(e=>t.startsWith(e))}var yy=new Set(["_s","embedder"]),Sc="gemEsc_",Rc=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,ji=64,Bi=16,Ui=512,Wi=ji-Sc.length;function kc(t){return yy.has(t)?"reserved_key":(Ni(t)||t.startsWith(Sc))&&t.length>Wi?"round_trip":null}var hy=/[\p{Cc}\p{Cf}]/u,by=/\p{Cs}/u;function Bt(t,e){if(!vy(t))return {error:"params must be a plain object of string values"};let n=Object.entries(t);if(n.length>Bi)return {error:`at most ${Bi} params; got ${n.length}`};let r=[];for(let[o,i]of n){let s=JSON.stringify(o);if(!Rc.test(o))return {error:`param ${s}: a key is a letter followed by up to ${ji-1} letters, digits, _ or -`};let a=e?kc(o):Ni(o)?"reserved_key":null;if(a==="reserved_key")return {error:e?`param ${s} is reserved: the arcade never carries it in a share link`:`param ${s} is reserved: this arcade reads it itself and never forwards it`};if(a==="round_trip")return {error:`param ${s}: a reserved key is carried escaped, and this one is too long to stay a valid key \u2014 keep it to ${Wi} characters`};if(typeof i!="string")return {error:`param ${s}: values must be strings`};if(i.length>Ui)return {error:`param ${s}: a value is at most ${Ui} characters`};if(hy.test(i))return {error:`param ${s}: control and format characters are not allowed`};if(by.test(i))return {error:`param ${s}: a value must be well-formed text`};r.push({key:o,value:i});}return {pairs:r}}function vy(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var no="[gem] gem.friends",_y=3e4;function Ac(t){let e=null,n=new Map;return {inviteToPlay(r){if(!t.bridge.parentSupports("playInvites"))return Promise.resolve(false);let o;if(r!==void 0){if(typeof r!="object"||r===null)return console.warn(`${no}.inviteToPlay: pass { params }, or nothing. Nothing was asked.`),Promise.resolve(false);if(r.params!==void 0){let s=Bt(r.params,t.bridge.parentSupports("shareRemap"));if("error"in s)return console.warn(`${no}.inviteToPlay: ${s.error}. Nothing was asked.`),Promise.resolve(false);o=s.pairs;}}if(e!==null)return e;let i=`invite-${pe()}`;return e=new Promise(s=>{let a={},l=c=>{n.delete(i)&&(e=null,t.clock.clearTimeout(a.timer),s(c));};n.set(i,l),a.timer=t.clock.setTimeout(()=>{l(false);},t.timeoutMs??_y);let d=false;try{d=t.bridge.requestArcade({type:"gem.requestPlayInvite",requestId:i,...o===void 0?{}:{params:o}});}catch{}d||l(false);}),e},settle(r){let o=r.shown===true,i=n.get(r.requestId);if(i===void 0){t.onDropped?.(`gem.playInviteResult (shown: ${String(o)}) for an unknown requestId: `+JSON.stringify(r.requestId));return}i(o);}}}function xc(t){let e,n,r=()=>{if(e===void 0)return false;if(e===null&&n===void 0)return true;let o=t();if(o.currentState!=="connected"||!o.parentSupports("playInvites"))return false;let i;if(e!==null){let a=Bt(e,o.parentSupports("shareRemap"));if("error"in a)return console.warn(`${no}.setInviteParams: ${a.error}. Nothing was sent.`),false;i=a.pairs;}let s=i===void 0?"":JSON.stringify(i);return s===n?true:o.requestArcade({type:"gem.inviteParams",...i===void 0?{}:{params:i}})?(n=s,true):false};return {set(o){if(o!==null){let i=Bt(o,true);if("error"in i)return console.warn(`${no}.setInviteParams: ${i.error}. Nothing was sent; the last declaration stands.`),false;e=Object.fromEntries(i.pairs.map(({key:s,value:a})=>[s,a]));}else e=null;return r()},flush:r,forgetSent(){n=void 0;}}}var ro=t=>typeof t=="string"?t:void 0;function wy(t){let e=t??{},n=ro(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:ro(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var oo=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await kr(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let s=wy(i);s!==void 0&&o.push(s);}return o}},Hi=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function Sy(t){let e=t??{},n=ro(e.currency_id);if(n===void 0||n==="")return;let r=Hi(e.limit),o=Math.min(Hi(e.earned),r),i=Math.min(Hi(e.remaining),r-o),s=e.period_days,a=typeof s=="number"&&Number.isInteger(s)&&s>=1?s:1,l=e.resets_at,d=typeof l=="number"&&Number.isFinite(l)&&l>0?Math.round(l*1e3):void 0;return {currencySlug:ro(e.currency_slug)??"",currencyId:n,limit:r,earned:o,remaining:i,period:e.period==="day"?"day":"window",periodDays:a,...d===void 0?{}:{resetsAt:d}}}function Pc(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 io=class{#e;#n;#o;constructor(e,n,r){this.#e=e,this.#n=n,this.#o=r;}async get(e={}){let r=(await Nl(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let o=[];for(let i of r){let s=Sy(i);s!==void 0&&o.push(s);}return o}on(e,n){return e!=="changed"?(this.#o?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#n?.on(n)??(()=>{})}},Pn=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new oo(e),this.earnAllowance=new io(e,n,r);}};var Vi=t=>typeof t=="string"?t:"",Ec=t=>typeof t=="number"?t:0;function Ry(t){let e=t??{};return {key:Vi(e.key),visibility:Vi(e.visibility),value:e.value,updatedAt:Ec(e.updated_at)}}function ky(t){let e=t??{};return {...Oe(e),playerId:Vi(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(Ry):[],generatedAt:Ec(e.generated_at)}}function Ay(t){return t?.reason==="not_found"}var En=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return ky(await Bl(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(Ay(r))return null;throw r}}};function Ki(t){return typeof t=="string"&&/^[\w-]{1,64}$/.test(t)}function ao(t,e){if(t===void 0||Ki(t))return t;let n=typeof t=="string"?JSON.stringify(t.slice(0,72)):`a value of type ${typeof t}`;console.warn(`[gem] ${e}: cueId ${n} is not 1 to 64 letters, digits, _ or -, so it was left out. Use one crypto.randomUUID() per award.`);}var xy=new Map([["function_error",false],["function_failed",false],["function_timeout",false],["function_not_published",false],["function_input_too_large",false],["invalid_cue_id",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]]),In=class extends M{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:xy.get(this.code))??super.retryable}},rt=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=Py(e),o=ao(n.cueId,"functions.invoke"),i;try{i=await this.#e(r,{...n.signal===void 0?{}:{signal:n.signal},...o===void 0?{}:{cue_id:o}});}catch(s){throw s instanceof M?Iy(s):s}return Ey(i)}};function Py(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 ue(`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 ue(`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 Ey(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 Iy(t){let{details:e,invocationId:n}=ol(t),o=e?.untrusted?.message,i=e?.reason;return new In(t,{...n===void 0?{}:{invocationId:n},...t.code==="function_error"&&typeof o=="string"?{functionMessage:o}:{},...t.code==="function_failed"&&typeof i=="string"?{failure:i}:{}})}function so(t,e){let n=e?.retryAfterSeconds,r=typeof n=="number"&&Number.isFinite(n)&&n>0?n*1e3:0,o=1e4*2**Math.min(Math.max(0,t-1),16);return Math.min(Math.max(r,o),3e5)}var Ty=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost","gem_graphics_context_lost"],Ji="gem_";function zi(t){return t.startsWith(Ji)}function Cy(t){let e=2166136261;for(let n of new TextEncoder().encode(t))e^=n,e=Math.imul(e,16777619);return e>>>0}function My(t){let e=t;return e^=e>>>16,e=Math.imul(e,2246822507),e^=e>>>13,e=Math.imul(e,3266489909),e^=e>>>16,e>>>0}function lo(t,e,n){if(Xi(t,n),typeof e!="string"||e==="")throw new TypeError("[gem] experiment: playerId must be a non-empty string");let r=typeof n=="number"?n:n.length,o=My(Cy(`${t}:${e}`))%r;return typeof n=="number"?o:n[o]}function Xi(t,e){if(typeof t!="string"||t==="")throw new TypeError("[gem] experiment: key must be a non-empty string");if(typeof e=="number"){if(!Number.isInteger(e)||e<1||e>2048)throw new RangeError(`[gem] experiment '${t}': the count must be an integer from 1 to 2048; got ${String(e)}`);return}if(!Array.isArray(e))throw new TypeError(`[gem] experiment '${t}': pass a count or a list of strings; got ${typeof e}`);let n=e;if(n.length<1||n.length>2048)throw new RangeError(`[gem] experiment '${t}': the list must hold 1 to 2048 strings; got ${n.length}`);if(!n.every(r=>typeof r=="string"))throw new TypeError(`[gem] experiment '${t}': every option must be a string`)}var Ic=1e4,Tc=50,Oy=500,Gy=65536-4*1024,Ly=24*1024;function Cc(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 Dy=6e4;function Fy(t){let e=new Map;for(let n of t??[]){let r=new Set;for(let[o,i]of Object.entries(n.dimensions??{})){let s=i?.range;typeof s=="object"&&s!==null&&r.add(o);}r.size>0&&e.set(n.id,r);}return e}function $y(t,e){if(e===void 0)return t;let n=null,r={};for(let[o,i]of Object.entries(t.measures))e.has(o)?(n??={...t.dimensions})[o]=String(i):r[o]=i;return n===null?t:{dimensions:n,measures:r}}var Mc=t=>typeof t=="number"?t:0,qy=t=>typeof t=="string"?t:"";function co(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function Ny(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:Mc(i.index),code:qy(i.code)}}):[];return {accepted:Mc(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Yi(){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 jy(t){return t?.retryable===true}var Tn=class{#e;#n;#o;#s;#t=[];#b={};#a=0;#l=null;#v=false;#_=false;#p=0;#w=0;#S=0;#r=false;#R=null;#d=null;#u=false;#i=false;#g=false;#k=false;#A=false;#f=void 0;#x=false;#P=0;constructor(e){this.#e=e,this.#n=e.options?.enabled!==false,this.#o=Math.max(Ic,e.options?.flushIntervalMs??Ic),this.#s=Math.max(1,Math.floor(e.options?.maxQueue??Oy));}track(e,n={}){if(!this.#n||this.#r)return;if(zi(e)){this.#A||(this.#A=true,this.#h(`[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.#E(e,Cc({...this.#b,...n}));let r=this.#C();this.#f===void 0&&!this.#x&&r!==null&&r!==""&&(this.#x=true,this.#M());}setContext(e){this.#b={...this.#b,...e};}async experiment(e,n){Xi(e,n);let r=this.#e.awaitPlayerId===void 0?this.#e.playerId():await this.#e.awaitPlayerId();if(r===null)throw new Error(`[gem] experiment '${e}': no player to select for \u2014 this call was not made by a player.`);return typeof n=="number"?lo(e,r,n):lo(e,r,n)}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#i)return co();let n=this.#C();if(n===null||n==="")return this.#t.length>0&&!this.#k&&(this.#k=true,this.#h("[gem] analytics: events are being recorded but no play session has been established, so nothing is being sent. Outside the arcade this is expected.")),co();let r=e.keepalive===true;if(!r&&this.#e.declarations!==void 0&&this.#t.some(d=>!zi(d.name))&&await this.#M(),this.#T(),this.#t.length===0||this.#p>0&&!r)return co();this.#m();let o=this.#t.splice(0,this.#G(r)),i=this.#a;this.#a=0;let s=Math.round(this.#e.clock.now()),a={batch_id:Yi(),sent_at_ms:s,events:o.map(d=>Oc(d,s,this.#f?.get(d.name)))},l={client:this.#e.client(),gameId:()=>n};this.#p+=1;try{let d=await zl(l,a,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),c=Ny(d,i);return this.#w=0,this.#S=0,this.#L(c),c}catch(d){throw jy(d)?(this.#O(o,i),this.#w+=1,this.#S=this.#e.clock.now()+so(this.#w,d)):this.#h(`[gem] analytics: ${o.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#p-=1,this.#t.length>0&&this.#c();}}trackPlatform(e,n={}){this.#r||this.#i&&(e==="gem_pause"||e==="gem_resume")||this.#E(e,Cc(n));}hold(){this.#r||this.#d!==null||(this.#i=true,this.#m());}release(){if(!this.#i||this.#r)return;this.#i=false;let e=this.#e.clock.now(),n=this.#t.map(r=>({...r,atMs:e}));this.#t=n,this.#g&&(this.#g=false,this.#d=e,this.#u=false,this.#t.unshift({uid:Yi(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#t.length>=Tc?this.#y():this.#t.length>0&&this.#c();}get held(){return this.#i}startSession(){if(!(this.#r||this.#d!==null)){if(this.#i){this.#g=true;return}this.#d=this.#e.clock.now(),this.#u=false,this.trackPlatform("gem_session_start");}}endSession(e){if(this.#r||this.#u)return;if(this.#u=true,this.#i){this.#g=false,this.#t=[],this.#a=0;return}let n=this.#d;this.trackPlatform("gem_session_end",{reason:e,...n===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-n))}}),this.#y({keepalive:true});}setPaused(e){this.#r||e===this.#v||(this.#v=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#m():this.#t.length>0&&this.#c());}setHidden(e){this.#r||e===this.#_||(this.#_=e,e?this.#m():this.#t.length>0&&this.#c());}dispose(){this.#r=true,this.#m(),this.#t=[],this.#a=0;}get pending(){return this.#t.length}#E(e,n){let{dimensions:r,measures:o}=n;for(this.#T();this.#t.length>=this.#s;)this.#t.shift(),this.#a+=1;this.#t.push({uid:Yi(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:o}),this.#t.length>=Tc?this.#y():this.#c();}#y(e={}){if(e.keepalive!==true&&this.#I()>0){this.#c();return}this.flush(e).catch(()=>{});}#I(){return Math.max(0,this.#S-this.#e.clock.now())}#O(e,n){for(this.#t=[...e,...this.#t],this.#a+=n;this.#t.length>this.#s;)this.#t.shift(),this.#a+=1;}#G(e){let n=e?Ly:Gy,r=Math.min(this.#t.length,100),o=128;for(let i=0;i<r;i+=1){let s=this.#t[i];if(s===void 0)break;if(o+=JSON.stringify(Oc(s,0,this.#f?.get(s.name))).length+1,o>n)return Math.max(1,i)}return r}#c(){this.#l!==null||this.#v||this.#_||this.#i||this.#r||this.#p>0||(this.#l=this.#e.clock.setTimeout(()=>{this.#l=null,this.#y();},Math.max(this.#o,this.#I())));}#m(){this.#l!==null&&(this.#e.clock.clearTimeout(this.#l),this.#l=null);}#T(){let e=this.#D();e===null||e===""||(this.#R!==null&&this.#R!==e&&(this.#t=[],this.#a=0,this.#d=null,this.#u=false),this.#R=e);}#L(e){for(let n of e.rejected)this.#h(`[gem] analytics: an event was refused (${n.code}). `+By(n.code));}#h(e){let n=this.#e.log;n!==null&&(n===void 0?console.warn(e):n(e));}#C(){try{return this.#e.gameId()}catch{return null}}#D(){try{return this.#e.playerId()}catch{return null}}async#M(){let e=this.#e.declarations;if(e!==void 0&&!(this.#e.clock.now()<this.#P))try{this.#f=Fy(await e());}catch{this.#P=this.#e.clock.now()+Dy;}}};function Oc(t,e,n){let{dimensions:r,measures:o}=$y(t,n);return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:r,measures:o}}function By(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 xe(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e}function Ge(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=xe(n);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var Uy=2e3,Wy=5e3;function Lc(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 s,a=new Promise(l=>{let d=false,c=null;s=u=>{d||(d=true,r=null,t.clock.clearTimeout(c),l(u));},c=t.clock.setTimeout(()=>{n=true,s([]);},t.timeoutMs??Uy);});return r={promise:a,settle:s},a};return {resolveList:i,resolve(){return e.length>0||n||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e[0]):i().then(s=>s[0])},refresh(s){return !Gc(e,s)||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let l=null,d=c=>{o.delete(d)&&(t.clock.clearTimeout(l),a(c));};o.set(d,s),l=t.clock.setTimeout(()=>d(e),t.refreshTimeoutMs??Wy);})},accept(s,a){let l=Ge(a),d=xe(s),c=l.length>0?l:d===void 0?[]:[d];if(c.length!==0){e=c,r?.settle(c);for(let[u,p]of [...o])Gc(c,p)||u(c);}}}}function Gc(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Hy=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),A=class extends Error{constructor(n,r,o){super(`${n}: ${r}`,o);this.reason=n;this.name="DedicatedServerError",this.retryable=Hy.has(n),this.platformCode=o?.platformCode;}reason;retryable;platformCode};var Dc=["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"],Vy=new Set(Dc);function ot(t){return typeof t=="string"&&Vy.has(t)?t:"unknown"}var uo="webrtc_dedicated",ta=["universal","mobile","web"];var Ky="p2p_unavailable",Jy="capacity_unavailable",zy=2,Fc=3e4,$c=1e3,qc=2e4;async function na(t){let e=xe(t.clusterTargetId),n=t.nextClusterTarget,r=0,o=t.clock??me,i=t.retry??{},s=i.budgetMs??Fc,a=i.maxDelayMs??qc,l=i.initialDelayMs??$c,d=o.now(),c=d+s,u=0;for(;;){u++;try{let p=await aa(t.signal,"while allocating",()=>t.client.post(`${Bc(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!Xy(p)||s<=0)throw p;if(p.status===503&&p.code===Ky)throw new A("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===Jy?r+1:0,n!==void 0&&r>=zy){let b=n;n=void 0;let w=xe(await b());w!==void 0&&(e=w,r=0);}let g=Math.min(a,l*2**(u-1)),f=Math.min(a,(p.retryAfterSeconds??0)*1e3),R=Math.max(g/2,f)+Math.random()*(g/2);if(o.now()+R>c)throw Yy(t,p,u,o.now()-d,s);if(i.onWaiting?.({attempt:u,elapsedMs:o.now()-d,budgetMs:s,nextAttemptInMs:R,status:p.status,message:p.message}),await mo(o,R,t.signal),t.signal?.aborted)throw ea("while waiting to allocate")}}}function Xy(t){return t instanceof M?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function Yy(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 A("start_rate_limited",`the platform was still limiting match starts for room ${t.roomId} after ${i}: ${e.message}`,{cause:e}):new A("no_server_ready",`the platform had no server ready for room ${t.roomId} after ${i}: ${e.message}`,{cause:e})}var Qy=12e4,Zy=1e3;async function ra(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??Zy,o=t.timeoutMs??Qy,i=e.now()+o,s=Nc(t),a={seen:t.knownToExist===true};for(;;){let l=await jc(t,s,a);if(l.outcome!==null)return l.outcome;if(e.now()+r>i)throw new A("timeout",`match ${n} was still ${l.status} after ${o}ms`);await mo(e,r,t.signal);}}async function oa(t){return (await jc(t,Nc(t),{seen:t.knownToExist===true})).outcome}function Nc(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${Bc(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function jc(t,e,n){let{matchId:r}=t,o=t.clock.now(),i;try{i=await aa(t.signal,"while polling match status",()=>t.client.get(e,t.signal));}catch(s){if(s instanceof M&&s.reason==="not_found")return {status:"not_found",outcome:n.seen?{status:"ended",matchId:r,reason:"unknown"}:{status:"failed",matchId:r,reason:"not_found"}};throw s}if(n.seen=true,i.status==="ready")return {status:"ready",outcome:eh(r,i,o)};if(i.status==="failed"){let s=i.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:ot(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:i.failure_reason??"unknown"}}}return {status:i.status,outcome:null}}async function ia(t){let e=await aa(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 aa(t,e,n){if(t?.aborted)throw ea(e);try{return await n()}catch(r){throw t?.aborted?ea(e,r):r}}function ea(t,e){return new A("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function eh(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 Bc(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function mo(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 Uc(t){return typeof t=="string"&&t.trim()!==""}function po(t,e){return Uc(t)?t.trim():Uc(e)?e:null}var go="0.1.0-beta",Wc="0-beta",Ut="web",th=/^(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 nh(t){let e=th.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function Hc(t,e){let n=rh(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:go};let o=nh(r);if(o===null)throw new A("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 '${go}' for it.`);if(o!==Wc)throw new A("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${o}', and '${Wc}' 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 '${go}' for it.`);return {...t,platform:n,engineVersion:r}}function rh(t,e){if(t===void 0||t===Ut)return Ut;if(!ta.includes(t))throw new A("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${ta.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${Ut}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${Ut}' 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.`),Ut}function Cn(t){let e=t??{};if(typeof e.ticket_id!="string"||e.ticket_id.length===0)throw new Error("[gem] a matchmaking-ticket response carried no id");let n=e.heartbeat_interval_seconds;return {id:e.ticket_id,status:typeof e.status=="string"?e.status:"queued",...typeof e.reason=="string"?{reason:e.reason}:{},...typeof e.game_room_id=="string"?{roomId:e.game_room_id}:{},partySize:typeof e.party_size=="number"?e.party_size:1,queuedAt:Vc(e.queued_at),expiresAt:Vc(e.expires_at),heartbeatIntervalSeconds:typeof n=="number"&&n>0?n:0}}function Vc(t){if(typeof t!="string")return 0;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1e3):0}var oh=3,Kc=1e3,fo=class{constructor(e){this.options=e;this.snapshot=e.first;let n=new Promise((i,s)=>{this.resolve=i,this.reject=s;});n.catch(()=>{});let r=()=>this.snapshot,o=()=>this.status;this.ticket={get id(){return r().id},get status(){return o()},get partySize(){return r().partySize},get queuedAt(){return r().queuedAt},get expiresAt(){return r().expiresAt},outcome:n,cancel:()=>(this.requestCancel(),n)};}options;ticket;snapshot;status="queued";timer=null;busy=false;again=false;cancelRequested=false;soon=false;misses=0;settled=false;resolve;reject;start(){this.apply(this.snapshot);}poke(){this.settled||(this.soon=true,!this.busy&&(this.clearTimer(),this.tick()));}abandon(e=false){this.settled||(this.options.cancel(this.snapshot.id,e).catch(()=>{}),this.settle({status:"cancelled",reason:"requested"}));}requestCancel(){this.settled||(this.cancelRequested=true,this.trigger());}trigger(){if(this.busy){this.again=true;return}this.clearTimer(),this.tick();}schedule(e=false){if(this.settled)return;this.clearTimer();let n=e?Kc:Math.max(Kc,this.snapshot.heartbeatIntervalSeconds*1e3);this.timer=this.options.clock.setTimeout(()=>{this.timer=null,this.tick();},n);}clearTimer(){this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null);}async tick(){if(this.settled||this.busy)return;this.busy=true,this.again=false;let e=null,n=null;try{e=this.cancelRequested?await this.options.cancel(this.snapshot.id):await this.options.heartbeat(this.snapshot.id);}catch(r){n=r;}if(this.busy=false,!this.settled){if(e===null){this.missed(n);return}this.misses=0,await this.apply(e);}}missed(e){if(e instanceof M&&e.reason==="not_found"){this.settle({status:"lost"});return}if(this.misses+=1,this.misses<oh){this.next();return}this.options.cancel(this.snapshot.id).catch(()=>{});let n=e instanceof M&&e.code==="matchmaking_unavailable";this.settle({status:n?"unavailable":"lost"});}async apply(e){if(this.snapshot=e,e.status==="queued"){this.next();return}if(e.status==="matched"){await this.seat(e);return}e.status==="expired"?this.settle({status:"expired",reason:e.reason??"timed_out"}):e.status==="cancelled"?this.settle({status:"cancelled",reason:e.reason??"requested"}):this.settle({status:"failed",reason:e.reason??e.status});}next(){if(this.again){this.again=false,this.tick();return}let e=this.soon;this.soon=false,this.schedule(e);}async seat(e){if(e.roomId===void 0){this.fail(new Error("[gem] a matched matchmaking ticket named no game room"));return}this.busy=true;try{let n=await this.options.seat(e.roomId);this.busy=!1,this.settle({status:"matched",room:n});}catch(n){this.busy=false,this.fail(n);}}settle(e){this.settled||(this.finish(e.status),this.resolve(e));}fail(e){this.settled||(this.finish("matched"),this.reject(e));}finish(e){this.settled=true,this.status=e,this.clearTimer(),this.options.onSettled();}};var ih="gemPlayWith",ah=/^[A-Za-z0-9_-]{16,128}$/;function Jc(t){if(typeof t!="string"||t==="")return;let e;try{e=new URLSearchParams(t).get(ih);}catch{return}return e!==null&&ah.test(e)?e:void 0}function zc(t){let e=typeof t=="object"&&t!==null?t.play_with:void 0;return e==null?null:e==="joined"?"joined":"unavailable"}var sh="join",lh="welcome",dh="rejected",Xc=25e3,ch=1e3,sa=1;function la(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var uh={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 da(t){let e=typeof t=="string"?t:"unknown";return new A(uh[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function Mn(t){let{channel:e,clock:n}=t;return new Promise((r,o)=>{let i=false,s=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??Xc),a=n.setTimeout(()=>h(new A("timeout","the server runtime sent no welcome before the join credential expired. The channel was open, so this is the runtime not answering rather than a connection that never came up.")),Math.max(s,ch)),l=R=>{let b=R.data;if(typeof b!="string"){u(b);return}let w;try{w=JSON.parse(b);}catch{u(b);return}if(i){u(b);return}if(w.t===lh){let y=la(w.heartbeat_interval);f({...typeof w.player_id=="string"?{playerId:w.player_id}:{},...typeof w.match_id=="string"?{matchId:w.match_id}:{},...y===void 0?{}:{heartbeatIntervalMs:y}});return}if(w.t===dh){h(da(w.reason));return}u(b);},d=()=>{h(new A("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},c=()=>{h(new A("aborted","the caller aborted during the join exchange"));},u=R=>{i&&t.onMessage?.(R);},p=()=>{n.clearTimeout(a),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",c);},g=()=>{e.removeEventListener("message",l);},f=R=>{i=true,p(),t.onMessage===void 0&&g(),r({welcome:R,detach:g});},h=R=>{i||(i=true,p(),g(),o(R));};if(e.addEventListener("message",l),e.addEventListener("close",d),t.signal?.aborted){c();return}t.signal?.addEventListener("abort",c);try{e.send(JSON.stringify({t:sh,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:sa}:{}}));}catch(R){h(new A("connection_failed",`the join frame could not be sent on the open channel: ${String(R)}`,{cause:R}));}})}var vt=1,On=2,ca=4,pa=8,mh=2,ph=1e3,ga="heartbeat timeout",Gn="gem-uu",yo=2,Qc="gem_transports";function Wt(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!gh(r)||e.includes(r)||e.push(r);}return e}function gh(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function Ln(t,e){if(typeof t!="object"||t===null)return null;let n=t[Qc];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 ho(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var Zc=new TextEncoder,eu=new TextDecoder;function fa(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function ya(t){let e=0;return t?.reliable===false&&(e|=vt),t?.ordered===false&&(e|=On),e}function ha(t){return {reliable:(t&vt)===0,ordered:(t&On)===0}}var ba={reliable:true,ordered:true};function tu(t){return JSON.stringify({t:"join",credential:t,wire:yo,heartbeat:sa})}function nu(t){let e;try{e=JSON.parse(t);}catch{throw new A("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let n=la(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"?da(e.reason):new A("join_refused","the server answered the join out of protocol")}function bo(){return typeof globalThis.WebTransport=="function"&&va===null}function vo(){return va}var va=null;var Yc="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function fh(t){let e=Rr(t);if(e.byteLength!==32)throw new A("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var ua=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 A("connection_failed",`a control-stream record claims ${i} bytes`);if(this.buffered.byteLength<4+i)break;let s=this.buffered.slice(4,4+i);this.buffered=this.buffered.slice(4+i),r.push({flags:s[0]??0,payload:s.slice(1)});}return r}};function ma(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 Dn(t){let e=Math.min(t.timeoutMs??1e4,Math.max(t.credentialExpiresAt-t.clock.now(),1e3)),n=t.webTransport;if(n===void 0){let a=globalThis.WebTransport;if(a===void 0)throw new A("connection_failed","this environment has no WebTransport");n=t.certHashBase64===void 0?new a(t.url):new a(t.url,{serverCertificateHashes:[{algorithm:"sha-256",value:fh(t.certHashBase64)}]});}let r=n,o=a=>{try{r.close();}catch{}throw a},i=r.datagrams;(i?.readable===void 0||i.writable===void 0)&&(va=Yc,o(new A("connection_failed",`${Yc}; the rung is skipped for the rest of this page (a reload probes again)`)));let s=new Promise((a,l)=>{setTimeout(()=>l(new A("timeout","webtransport did not come up in time")),e);});try{await Promise.race([r.ready,s]);let a=r.incomingBidirectionalStreams.getReader(),l=await Promise.race([a.read(),s]);if(a.releaseLock(),l.done||l.value===void 0)return o(new A("connection_failed","the session ended before the control stream arrived"));let d=l.value,c=d.writable.getWriter();await c.write(ma(ca,Zc.encode(tu(t.credential))));let u=new ua,p=d.readable.getReader(),g;for(;g===void 0;){let f=await Promise.race([p.read(),s]);if(f.done||f.value===void 0)return o(new A("connection_failed","the control stream closed before the join was answered"));for(let h of u.push(f.value)){g=nu(eu.decode(h.payload));break}}return {link:yh(r,c,p,u,t.log??(f=>console.warn(f)),ou(g,t.clock)),welcome:g}}catch(a){return o(a)}}function yh(t,e,n,r,o,i){let s,a,l=false,d=f=>{if(!l){l=true,c.stop();try{t.close();}catch{}a?.(f);}},c=wa(i,()=>d(ga)),u=(f,h)=>{c.heard(),(f&pa)===0&&s!==void 0&&((f&ca)!==0?s(eu.decode(h),ba):s(h,ha(f)));};(async()=>{try{for(;;){let f=await n.read();if(f.done||f.value===void 0)break;for(let h of r.push(f.value))u(h.flags,h.payload);}}catch{}d("stream closed");})();let p,g;try{let f=t.datagrams;if(f?.readable!==void 0&&f.writable!==void 0){let h=f.readable.getReader();g=f.writable.getWriter(),p=f,(async()=>{try{for(;;){let R=await h.read();if(R.done||R.value===void 0)break;let b=R.value;b.byteLength!==0&&u((b[0]??0)|vt|On,b.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 (${ho(f)}); unreliable sends ride the stream`);}return t.closed.then(f=>d(ru(f?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(f,h){if(l)return;if(typeof f=="string"){e.write(ma(ca,Zc.encode(f))).catch(()=>d("write failed"));return}let R=ya(h);if((R&vt)!==0&&g!==void 0){let b=fa(R,f),w=p?.maxDatagramSize;if(w===void 0||b.byteLength<=w){g.write(b).catch(()=>{});return}}e.write(ma(R,f)).catch(()=>d("write failed"));},onMessage(f){s=f;},onClose(f){a=f;},close(){d("closed");}}}function _a(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 A("connection_failed","this environment has no WebSocket"));n=new o(t.url);}let r=n;return r.binaryType="arraybuffer",new Promise((o,i)=>{let s=false,a=setTimeout(()=>{s||(s=true,r.close(),i(new A("timeout","websocket did not come up in time")));},e),l=g=>{s||(s=true,clearTimeout(a),r.close(),i(g));},d=()=>{r.send(tu(t.credential));},c=g=>{if(s)return;if(typeof g.data!="string"){l(new A("join_refused","the server sent binary before answering the join"));return}let f;try{f=nu(g.data);}catch(h){l(h);return}s=true,clearTimeout(a),r.removeEventListener("open",d),r.removeEventListener("message",c),r.removeEventListener("close",u),r.removeEventListener("error",p),o({link:hh(r,ou(f,t.clock)),welcome:f});},u=()=>{l(new A("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new A("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",c),r.addEventListener("close",u),r.addEventListener("error",p),r.readyState===1&&d();})}function ru(t){return typeof t=="string"&&t.length>0?t:void 0}function ou(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function wa(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,ph)*mh,o=n.now(),i=null,s=()=>{i=null;let a=n.now()-o;if(a>=r){e();return}i=n.setTimeout(s,r-a);};return i=n.setTimeout(s,r),{heard:()=>{o=n.now();},stop:()=>{i!==null&&(n.clearTimeout(i),i=null);}}}function hh(t,e){let n,r,o=false,i=a=>{if(!o){o=true,s.stop();try{t.close();}catch{}r?.(a);}},s=wa(e,()=>i(ga));return t.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){n?.(a.data,ba);return}let l=new Uint8Array(a.data);if(l.byteLength===0)return;let d=l[0]??0;(d&pa)===0&&n?.(l.slice(1),ha(d));})),t.addEventListener("close",(a=>i(ru(a?.reason)??"socket closed"))),{transport:"websocket",send(a,l){if(!o){if(typeof a=="string"){t.send(a);return}t.send(fa(ya(l),a));}},onMessage(a){n=a;},onClose(a){r=a;},close(){i("closed");}}}function Sa(t,e,n,r){let o,i,s=false,a=n,l=u=>{if(!s){s=true,d.stop();try{t.close();}catch{}try{e.close();}catch{}i?.(u);}},d=wa(r,()=>l(ga)),c=(u,p)=>{if(d.heard(),typeof u=="string"){o?.(u,ba);return}let g=new Uint8Array(u);if(g.byteLength===0)return;let f=g[0]??0;(f&pa)===0&&o?.(g.slice(1),ha(f|p));};if(t.addEventListener("message",(u=>c(u.data,0))),t.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let u=e.connectionState;(u==="failed"||u==="closed")&&l(`connection ${u}`);})),a!==void 0){let u=a;u.addEventListener("message",(p=>c(p.data,vt|On))),u.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(u,p){if(s)return;if(typeof u=="string"){t.send(u);return}let g=ya(p),f=fa(g,u);if((g&vt)!==0&&a!==void 0&&a.readyState==="open"){a.send(f);return}t.send(f);},onMessage(u){o=u;},onClose(u){i=u;},close(){l("closed");}}}function iu(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let o=Ra(r);o!==void 0&&(e[n]=o);}return e}function au(t){if(Array.isArray(t))return t.map(bh).filter(e=>!!e)}function Ra(t){if(ka(t)||Array.isArray(t)&&t.every(ka))return t}function ka(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function bh(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=Ra(e.fixed),r=Ra(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},...Ht("description",vh(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(ka)?{allowed:e.allowed}:{},...Ht("min",Fn(e.min)),...Ht("max",Fn(e.max)),...Ht("minItems",Fn(e.min_items)),...Ht("maxItems",Fn(e.max_items)),...Ht("maxLength",Fn(e.max_length))}}function vh(t){return typeof t=="string"&&t.length>0?t:void 0}function Fn(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Ht(t,e){return e===void 0?{}:{[t]:e}}function Ke(t){let e=t??{},n=Q(e.id)??Q(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(_h):[];return {id:n,gameId:Q(e.game_id)??"",name:Q(e.name)??"",status:Q(e.status)??"open",hostPlayerId:Q(e.host_player_id)??"",maxPlayers:je(e.max_players)??0,memberCount:je(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...Ee("joinCode",Q(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...Ee("roomArgs",iu(e.room_args)),...Ee("roomArgsTemplate",au(e.room_args_template)),gameChannel:Q(e.game_channel)??"release",...Ee("region",Q(e.region)),...Ee("clusterTargetId",Q(e.cluster_target_id)),selfHosted:e.self_hosted===true,...Ee("matchId",Q(e.match_id)),version:je(e.version)??0,...Ee("templateId",Q(e.template_id)),...Ee("templateSlug",Q(e.template_slug)),roomType:Q(e.game_room_type)??"Standard",...Ee("transports",Wt(e.transports)??void 0),createdAt:je(e.created_at)??0,updatedAt:je(e.updated_at)??0,...Ee("startedAt",je(e.started_at))}}function _h(t){let e=t??{};return {...Oe(e),playerId:Q(e.player_id)??"",isReady:e.is_ready===true,role:Q(e.role)??"member",joinedAt:je(e.joined_at)??0,...Ee("groupId",Q(e.group_id)),...Ee("platform",Q(e.platform))}}function Aa(t){let e=t??{};return {id:Q(e.id)??Q(e.game_room_id)??"",gameId:Q(e.game_id)??"",name:Q(e.name)??"",status:Q(e.status)??"open",hostPlayerId:Q(e.host_player_id)??"",maxPlayers:je(e.max_players)??0,memberCount:je(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:Q(e.game_channel)??"release",roomType:Q(e.game_room_type)??"Standard",createdAt:je(e.created_at)??0}}function Q(t){return typeof t=="string"&&t.length>0?t:void 0}function je(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Ee(t,e){return e===void 0?{}:{[t]:e}}var _o=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(Aa),...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(Aa)}))}create(e,n,r){return Sh(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},...$n(n)},e.signal).then(Ke)}get(e,n){return this.options.client.get(this.roomV2(e),n).then(Ke)}join(e,n,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...n.partyId===void 0?{}:{party_id:n.partyId},...$n(r)},n.signal).then(Ke)}joinByCode(e,n,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...n.partyId===void 0?{}:{party_id:n.partyId},...$n(r)},n.signal).then(Ke)}quickJoin(e,n,r=[]){return xa(this.options,e,n,r).then(o=>o.room)}createTicket(e,n,r=[]){return hl(this.generated(),{templates:e.templateSlugs.map(o=>({template_slug:o})),...r.length===0?{}:{cluster_target_ids:[...r]},...e.partyId===void 0?{}:{party_id:e.partyId},...$n(n)},{...e.signal===void 0?{}:{signal:e.signal}}).then(Cn)}heartbeatTicket(e){return Jl(this.generated(),e).then(Cn)}cancelTicket(e,n=false){return n?this.options.client.delete(`/v1/games/${encodeURIComponent(this.options.gameId())}/matchmaking/tickets/${encodeURIComponent(e)}`,void 0,{keepalive:true}).then(Cn):ml(this.generated(),e).then(Cn)}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 lu(this.options,e)}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(Ke)}setReady(e,n,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:n},r).then(Ke)}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(Ke)}leaveMatch(e,n){return this.options.client.post(`/v1/games/${encodeURIComponent(this.options.gameId())}/matches/${encodeURIComponent(e)}/leave`,{},void 0,{keepalive:n}).then(()=>{})}generated(){return {client:this.options.client,gameId:this.options.gameId}}baseV2(){return su(this.options)}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 su(t){return `/v2/games/${encodeURIComponent(t.gameId())}/game-rooms`}function lu(t,e){return e===void 0&&t.selfHosted?.()===true}function xa(t,e,n,r=[],o){let i=lu(t,e.partyId);return t.client.post(`${su(t)}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...wh(e.templateSlugs,i),...e.region===void 0?{}:{region:e.region},...r.length===0?{}:{cluster_target_ids:[...r]},...e.name===void 0?{}:{name:e.name},...e.partyId===void 0?{}:{party_id:e.partyId},...i?{self_hosted:true}:{},...o===void 0?{}:{play_with_ticket:o},...$n(n)},e.signal).then(s=>({room:Ke(s),playWith:o===void 0?null:zc(s)}))}function wh(t,e){return t===void 0?{}:{templates:(e?t.slice(0,1):t).map(r=>({template_slug:r}))}}function $n(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function Sh(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 wo=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;}};var So=class{constructor(e){this.options=e;let n=e.first,r=new Promise(a=>{this.resolve=a;}),o=()=>this.status;this.ticket={id:n.ticketId,get status(){return o()},partySize:n.partySize??0,queuedAt:n.queuedAt??0,expiresAt:n.expiresAt??0,outcome:r};let i=n.queuedAt!==void 0&&n.expiresAt!==void 0?(n.expiresAt-n.queuedAt)*1e3:9e5,s=Math.min(Math.max(i,0),9e5)+5e3;this.timer=e.clock.setTimeout(()=>{this.timer=null,this.end({status:"lost"});},s);}options;ticket;status="queued";timer=null;resolve;get id(){return this.ticket.id}end(e){this.status==="queued"&&(this.status=e.status,this.timer!==null&&(this.options.clock.clearTimeout(this.timer),this.timer=null),this.options.onSettled(),this.resolve(e));}};function Rh(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var kh=1e3,Ah=3e3,xh=6e4,Ph=2,du=new Set(["game_room_closed","game_room_gone"]),Eh=12e4,Ih=5e3,Th=new Set(["invalid_cluster_target","capacity_unavailable"]),Ch=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function mu(t,e){return new Ea(e,t)}var Ea=class{constructor(e,n={}){this.options=e;this.internals=n;this.autoFollow=e.followMatch!==false,this.apiOptions={client:e.client,gameId:()=>this.requireGameId(),selfHosted:()=>e.localHostAvailable?.()===true},this.api=new _o(this.apiOptions),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;internals;emitter=new wo;api;apiOptions;playWithAnswer=null;room=null;ticketWatch=null;queueing=false;partyWatch=null;heldQueued=null;queuedFromRoomId=null;session={phase:"none"};seenMatches=new Set;refusedMatches=new Set;reconciling=null;reconcileAgain=false;pendingHint=null;settling=null;pollHandle=null;polling=false;pollIntervalMs=null;pinnedIntervalMs=null;lastPushAt=-1/0;inFlight=[];unloadListener=null;visibilityListener=null;seatPollHandle=null;reported=new Set;disposed=false;followAbort=null;followingMatchId=null;autoFollow;reconnect=null;startsInFlight=0;autoStartRetried=false;autoStartRetry=null;async create(e){this.assertNotInRoom("create"),this.assertNotQueued("create");let n=this.clusterTargets(),r=await this.attachParty(e),o=await this.run("create",async()=>{let i=await n,s=a=>this.api.create(r,this.version("create"),a);for(let a=0;;a++)try{return await s(i[a])}catch(l){if(!Pa(l))throw l;if(a+1<i.length)continue;let d=(await this.afterRefusedClusters(l,i)).find(c=>!i.includes(c));if(d===void 0)throw l;return s(d)}});return this.enter(o,"created"),this.askForLocalServer(o),o}async join(e,n={}){this.assertNotInRoom("join"),this.assertNotQueued("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"),this.assertNotQueued("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"),this.assertNotQueued("quickJoin"),Gh(e);let n=this.clusterTargets(),r=await this.attachParty(e),o=a=>this.postQuickJoin(r,a).catch(l=>this.retryPastStaleMembership(l,r,a)),i=await this.run("quickJoin",async()=>{let a=await n;return o(a).catch(async l=>{let d=await this.afterRefusedClusters(l,a);if(d.length===0||uu(d,a))throw l;return o(d)})}),{room:s}=i;return this.playWithAnswer=i.playWith,this.enter(s,"joined"),this.askForLocalServer(s),s}async queueForMatch(e){this.assertNotQueued("queueForMatch"),Oh(e?.templateSlugs),this.queueing=true;try{let n=this.clusterTargets(),r=await this.attachParty(e),o=await this.run("queueForMatch",async()=>{let s=await n;return this.api.createTicket(r,this.version("queueForMatch"),s).catch(async a=>{let l=await this.afterRefusedClusters(a,s);if(l.length===0||uu(l,s))throw a;return this.api.createTicket(r,this.version("queueForMatch"),l)})});this.heldQueued?.ticketId===o.id&&(this.heldQueued=null),this.partyWatch?.end({status:"lost"});let i=new fo({clock:this.options.clock,first:o,heartbeat:s=>this.track(this.api.heartbeatTicket(s)),cancel:(s,a)=>this.track(this.api.cancelTicket(s,a)),seat:s=>this.enterMatchedRoom(s),onSettled:()=>{this.ticketWatch===i&&(this.ticketWatch=null),this.retuneSeatWatch();}});return this.ticketWatch=i,this.retuneSeatWatch(),i.start(),i.ticket}finally{this.queueing=false;let n=this.heldQueued;this.heldQueued=null,n!==null&&this.showPartyTicket(n);}}async enterMatchedRoom(e){let n=await this.run("queueForMatch",()=>this.api.get(e));return this.disposed?n:(this.room!==null&&this.room.id!==n.id&&(this.queuedFromRoomId=this.room.id,this.exit()),this.room===null&&this.enter(n,"joined"),this.room?.id===n.id?this.room:n)}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 M&&o.reason==="not_found"){let i=this.heldMatchId;if(i!==null){let s=await this.askWhyEnded(i,e);this.endMatch(i,s??"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(()=>oa({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(s){return s instanceof M&&s.reason==="not_found"?o??null:(this.reportError("reconcile",s),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=ot(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 A("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=xe(n.clusterTargetId),i=o??(e.clusterTargetId===void 0?(await this.clusterTargets())[0]:void 0),s=i??e.clusterTargetId;await this.options.ensureLocalServer?.(e.id);let a=(c,u)=>na({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...c===void 0?{}:{clusterTargetId:c},...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=()=>a(i,[s]).catch(async c=>{if(o!==void 0||!Pa(c))throw c;let u=await this.nextCluster([s],true);if(u===void 0)throw c;return a(u,[s,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 A("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 ra({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 A("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!du.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new A("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(!_t()){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<kh){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(Rh(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!_t()){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(()=>oa({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,!du.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(s){this.reportError("reconcile",s),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 A("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 A("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 A("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 currentTicket(){return this.ticketWatch?.ticket??null}get partyTicket(){return this.partyWatch?.ticket??null}get currentMatch(){return this.emitter.retained}get matchConnectionState(){switch(this.session.phase){case "none":case "ended":return "disconnected";case "ready":case "connected":return "connected";case "suspended":return "suspended";default:return "connecting"}}get matchSession(){return this.session}holdsMatch(){return this.session.phase!=="none"&&this.session.phase!=="ended"}get heldMatchId(){return this.holdsMatch()?this.session.matchId??null:null}get isInRoom(){return this.room!==null}get isHost(){let e=this.playerId();return e!==null&&this.room?.hostPlayerId===e}get members(){return this.room?.members??[]}get playWith(){return this.playWithAnswer}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.ticketWatch!==null&&e.event!=="version_stale"&&e.roomId!==this.room?.id&&this.ticketWatch.poke(),this.room===null)return;if(e.event==="version_stale"){this.emitter.emit("versionUpdateAvailable",e.platform);return}if(e.roomId!==this.room.id||(this.lastPushAt=this.options.clock.now(),this.retune(),e.event==="updated"&&e.version!==void 0&&e.version<=this.room.version))return;let 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||!Th.has(e)?"leave":this.startsInFlight>0?"in_flight":this.autoStartRetried?"leave":"start"}abortAutoStartRetry(){this.autoStartRetry?.abort(),this.autoStartRetry=null;}handleSeated(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.watchingSeats&&this.room?.id!==e&&(this.reported.has(e)||this.track(this.reportSeat(e).catch(()=>{})));}}handleTicketEvent(e){if(!this.disposed){if(this.ticketWatch!==null){this.ticketWatch.poke();return}if(this.queueing){e.event==="queued"?this.heldQueued=e:this.heldQueued?.ticketId===e.ticketId&&(this.heldQueued=null);return}if(e.event==="queued"){this.showPartyTicket(e);return}if(e.event==="matched"){e.roomId!==void 0&&this.handleSeated(e.roomId),this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:"matched"});return}this.partyWatch?.id===e.ticketId&&this.partyWatch.end({status:e.event,reason:e.reason??e.event});}}showPartyTicket(e){if(this.disposed||this.partyWatch?.id===e.ticketId)return;this.partyWatch?.end({status:"lost"});let n=new So({clock:this.options.clock,first:e,onSettled:()=>{this.partyWatch===n&&(this.partyWatch=null);}});this.partyWatch=n,this.emitter.emit("partyQueued",n.ticket);}async reconcileSeats(){if(this.disposed||!this.watchingSeats||this.ticketWatch!==null)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.partyWatch?.end({status:"matched"}),this.emitter.emit("seated",r)));}retuneSeatWatch(){if(!(!this.disposed&&this.watchingSeats&&this.room===null&&this.ticketWatch===null&&this.seatPollMs>0&&_t())){this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null);return}if(this.seatPollHandle!==null)return;let 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(),!!_t())){if(this.room!==null){let r=this.reconnect?.parked??null;r!==null&&this.reconnect!==null?(this.reconnect.parked=null,this.track(r())):this.track(this.reconcile().catch(()=>{}));return}if(this.ticketWatch!==null){this.ticketWatch.poke();return}this.options.watchSeats!==false&&this.track(this.reconcileSeats().catch(()=>{}));}};for(let r of Ro)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.ticketWatch?.abandon(),this.heldQueued=null,this.partyWatch?.end({status:"lost"}),this.abortAutoStartRetry(),this.finishReconnect(),this.stopPolling(),this.emitter.clear(),this.unloadListener&&(globalThis.removeEventListener?.("pagehide",this.unloadListener),this.unloadListener=null),this.seatPollHandle!==null&&(this.options.clock.clearTimeout(this.seatPollHandle),this.seatPollHandle=null),this.visibilityListener){let e=globalThis;for(let r of Ro)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??Ih}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new A("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=po(this.options.platformGameVersion?.(),n?.gameVersion);if(r===null)throw new A("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 Hc({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return Ge(await this.options.resolveClusterTargets());let e=xe(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !Pa(e)||n.length===0?[]:Ge(await this.options.refreshClusterTargets?.(n)??[])}async nextCluster(e,n=false){let r=s=>s.find(a=>!e.includes(a)),o=await this.clusterTargets(),i=r(o);return i!==void 0||!n?i:r(Ge(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 M)||e.reason!=="conflict"||!Ch.has(e.code??""))throw e;if(this.options.recoverStaleMembership===false)throw new M(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 M(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 M(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.postQuickJoin(n,r)}postQuickJoin(e,n){return xa(this.apiOptions,e,this.version("quickJoin"),n,this.internals.playWithTicket)}assertNotInRoom(e){if(this.room!==null)throw new A("misconfigured",`${e} refused: already in room ${this.room.id}. Leave it first \u2014 this manager tracks one room, and a second would leave its state disagreeing with the server's about which one you are in.`)}assertNotQueued(e){if(!(this.ticketWatch===null&&!this.queueing))throw new A("misconfigured",`${e} refused: this player is waiting on a matchmaking ticket, which will seat them in a room of its own. Cancel it first \u2014 currentTicket.cancel() \u2014 or wait for its outcome.`)}requireRoom(e){if(this.room===null)throw new A("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 M?{operation:e,code:n.status,reason:n.reason,message:n.message,retryable:n.retryable}:{operation:e,code:0,reason:n instanceof A?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.queuedFromRoomId===e.id&&(this.queuedFromRoomId=null),this.abortFollow(),this.autoStartRetried=false,this.session={phase:"none"},this.seenMatches.clear(),this.refusedMatches.clear(),this.pendingHint=null,this.emitter.clearRetained(),this.emitter.emit(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(a=>[a.playerId,a])),o=new Map(e.members.map(a=>[a.playerId,a])),i=this.playerId();for(let a of o.keys())r.has(a)||this.emitter.emit("memberJoined",a);for(let a of r.keys())if(!o.has(a)){if(a===i){this.exit(),this.emitter.emit("kicked");return}this.emitter.emit("memberLeft",a);}for(let[a,l]of o){let d=r.get(a);d&&d.isReady!==l.isReady&&this.emitter.emit("readyChanged",a,l.isReady);}n.hostPlayerId!==e.hostPlayerId&&e.hostPlayerId.length>0&&this.emitter.emit("hostChanged",e.hostPlayerId);let s=Mh(n,e);this.room=e,this.adoptMatch(e),this.session.phase==="starting"&&this.followMatch(),s&&this.emitter.emit("updated",e);}adoptMatch(e){e.status!=="in_game"||e.matchId===void 0||this.session.matchId!==e.matchId&&(this.refusedMatches.has(e.matchId)||this.beginMatch(e.matchId));}beginMatch(e){let 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??Eh;return new Promise((o,i)=>{let s=u=>{a(),l(),this.options.clock.clearTimeout(c),e.signal?.removeEventListener("abort",d),u();},a=this.emitter.on("matchAllocationStarted",u=>s(()=>o(u))),l=this.emitter.on("matchFailed",(u,p)=>s(()=>i(new A("allocation_failed",`match ${u} did not come up: ${p}`)))),d=()=>s(()=>i(new A("aborted","the caller aborted while awaiting a match"))),c=this.options.clock.setTimeout(()=>s(()=>i(new A("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??Ah}pushedInterval(){return this.options.pushedPollIntervalMs??xh}pushed(){return this.options.clock.now()-this.lastPushAt<Ph*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=>{if(this.ticketWatch?.abandon(true),n?.persisted!==true&&(this.room!==null&&this.track(this.leave({keepalive:true}).catch(()=>{})),this.queuedFromRoomId!==null)){let r=this.queuedFromRoomId;this.queuedFromRoomId=null,this.track(this.api.leave(r,true,void 0,true).catch(()=>{}));}},e.addEventListener("pagehide",this.unloadListener));}};function _t(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var Ro=["visibilitychange","focus","pageshow","online"];function Mh(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||cu(t)!==cu(e)}function cu(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function Pa(t){return t instanceof M&&t.code==="invalid_cluster_target"}var ko=8;function Oh(t){if(!(Array.isArray(t)&&t.length>=1&&t.length<=ko&&t.every(n=>typeof n=="string"&&n.length>0)))throw new A("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${ko} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function Gh(t){let e=t?.templateSlugs;if(e===void 0)return;if(!(Array.isArray(e)&&e.length>=1&&e.length<=ko&&e.every(r=>typeof r=="string"&&r.length>0)))throw new A("misconfigured",`quickJoin's templateSlugs is an array naming one to ${ko} room templates by slug \u2014 quickJoin({ templateSlugs: ['duel', 'brawl'] }). A room that has to be created is made from the first.`);if(t?.templateSlug!==void 0||t?.templateId!==void 0)throw new A("misconfigured","quickJoin takes templateSlugs or a single templateSlug / templateId, not both. Put every template this player accepts in templateSlugs, with the one to create from first.")}function uu(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Lh=["p2p","dedicated","unknown"],Ia=["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 Vt=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let o=Dh(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 Dh(t,e,n){let r=Math.floor(n/1e3);return t.filter(o=>Ia.includes(o.type)).slice(0,100).map(o=>{let i=$h(o.transport??e);return {event_type:o.type,timestamp:r,...i===void 0?{}:{transport:i},data:{...Fh(o.labels),...o.value===void 0?{}:{value:o.value}}}})}function Fh(t){let e={};if(typeof t!="object"||t===null)return e;let n=0;for(let[r,o]of Object.entries(t)){if(n>=4)break;r==="value"||!pu(r)||!pu(o)||(e[r]=o,n+=1);}return e}function pu(t){return typeof t=="string"&&t.length>0&&t.length<=32}function $h(t){if(t!==void 0)return Lh.includes(t)?t:"unknown"}var qn=class{constructor(e){this.options=e;this.reporter=new Vt({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:Ao(o.credential)??"",hostFingerprint:Ao(o.host_fingerprint)??"",hostEpoch:xo(o.host_epoch)??0,expiresAt:(xo(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,c=(Array.isArray(d.urls)?d.urls:[]).filter(u=>typeof u=="string"&&u.length>0);c.length!==0&&i.push({urls:c,username:Ao(d.username)??"",credential:Ao(d.credential)??""});}let s=xo(o.expires_at),a=xo(o.ttl_seconds);return {iceServers:i,expiresAt:s!==void 0?s*1e3:Date.now()+(a??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)}`}},qh=new Set(["cluster_hidden","invalid_cluster_target"]);async function gu(t,e,n,r){let o=Ge(n);if(o.length===0)throw new Error("no cluster to lease TURN from");let i;for(let s of o)try{return {...await t.turnLease(e,s,r),clusterTargetId:s}}catch(a){if(!Nh(a))throw a;i=a;}throw i}function Nh(t){return t instanceof M&&qh.has(t.code??"")}function Ao(t){return typeof t=="string"&&t.length>0?t:void 0}function xo(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}var jh=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),j=class extends Error{constructor(n,r,o){super(`${n}: ${r}`,o);this.reason=n;this.name="P2pError",this.retryable=jh.has(n);}reason;retryable};var fu=10240,yu=2048,Bh=new TextEncoder;function hu(t){return Bh.encode(t).length}function Je(t,e){let n=o=>{throw new A("invalid_sdp",`the ${e} ${o}`)},r=hu(t);r>=fu&&n(`is ${r} bytes, over the ${fu} 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=hu(o);i>yu&&n(`has a ${i}-byte line, over the ${yu} limit`);}}function Po(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 Eo=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 Uh=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function Jt(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=Io(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function Io(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 Uh.test(r)?r:null}function Kt(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 Ta=5e3,Wh=12e4+Ta,Hh=1024,Vh=6e4,Kh=1e4,bu=64*1024;function Ca(t){let e=new Map,n=-1/0,r=null,o=(()=>{let a;try{a=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 a.username!==""||a.password!==""?{ok:false,reason:"the configured API base carries credentials in the URL, which `fetch` will not send. Its value is withheld here rather than written to logs. This is a configuration fault, not a server failure."}:{ok:true,url:a.href,shown:`${a.protocol}//${a.host}`}})(),i=()=>{let a=t.subtle??globalThis.crypto?.subtle;if(!a)throw new j("keys_unavailable","this environment has no WebCrypto, so a join credential cannot be verified. A page served over plain http on a non-loopback origin is the usual cause \u2014 crypto.subtle is only exposed in a secure context.");return a},s=async()=>{if(!o.ok)throw new j("keys_unavailable",o.reason);let a=t.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await a(o.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(Kh)});}catch{throw new j("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 j("keys_unavailable",`the JWKS endpoint answered ${o.shown} with an error`);let d;try{let p=await l.text();if(p.length>bu)throw new j("keys_unavailable",`the JWKS endpoint at ${o.shown} answered with more than ${bu} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof j?p:new j("keys_unavailable",`the JWKS endpoint at ${o.shown} did not answer with a readable key set.`)}let c=Array.isArray(d.keys)?d.keys:[],u=i();for(let p of c){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(a){let l=e.get(a);if(l)return l;if(!o.ok)throw new j("keys_unavailable",o.reason);if(r)return await r,e.get(a)??null;let d=t.now();if(!Number.isFinite(d))throw new j("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<Vh?null:(n=d,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var Nn=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>=Hh){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+Wh),true}};function _u(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 vu(t){try{let e=new TextDecoder().decode(_u(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function Ma(t,e,n,r,o){let i=H=>{throw new j("peer_unauthenticated",`the peer's join credential is not usable: ${H}`)},s=t.split(".");s.length!==3&&i("it is not a three-part JWT");let[a,l,d]=s,c=vu(a);c===null&&i("its header does not decode"),c.alg!=="RS256"&&i(`its alg is ${JSON.stringify(c.alg)}, not RS256`),c.typ!=="p2p+jwt"&&i(`its typ is ${JSON.stringify(c.typ)}, not p2p+jwt`);let u=c.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(`${a}.${l}`),h;try{h=_u(d);}catch{i("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,h,f)||i("its signature does not verify");let b=vu(l);b===null&&i("its payload does not decode");let w=b,y=H=>typeof w[H]=="string"?w[H]:"",v=H=>typeof w[H]=="number"&&Number.isFinite(w[H])?w[H]:NaN;y("iss")!==o.issuer&&i("it was issued by someone else"),y("aud")!==`${o.issuer}/p2p-match`&&i("its audience is not this platform"),y("match_id")!==e.matchId&&i("it is for another match"),y("game_id")!==e.gameId&&i("it is for another game");let E=v("exp")*1e3,T=v("nbf")*1e3;(!Number.isFinite(E)||e.now>E+Ta)&&i("it has expired"),Number.isFinite(T)&&e.now<T-Ta&&i("it is not valid yet");let $=y("role");$!=="host"&&$!=="client"&&i("it names no usable role");let q=v("host_epoch");q!==e.hostEpoch&&i("it names a different host epoch");let U=Io(y("fingerprint"));U===null&&i("its fingerprint claim is malformed"),Kt(U,e.peerFingerprint)||i("it was issued for a different certificate than this connection used");let C=Io(y("host_fingerprint"));C===null&&i("its host fingerprint claim is malformed"),Kt(C,e.hostFingerprint)||i("it was issued against a different host certificate");let O=y("jti");O.length===0&&i("it carries no jti, so replay cannot be detected"),r.admit(O,e.now)||i("it has already been used");let N=y("sub");return N.length===0&&i("it names no player"),{playerId:N.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:q,role:$,fingerprint:U,hostFingerprint:C,jti:O,expiresAt:E}}function Oa(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 Ga(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 La(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function Da(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 wu(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 Su(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var jn=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 Fa={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}},ze=["reliable","ordered","unreliable"];function $a(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 Bn(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var ku=1,Qh=3e4,Au=2e3,Zh=5e3,xu=6e4,eb=8,tb=12e4,nb=5e3,rb=8e3,Tu=18e5,ob=Tu+6e4,Na=class{constructor(e=eb){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;}},ib=new Na,ab=8,sb=new Set(["timeout","connection_failed","invalid_sdp","peer_unauthenticated","not_expected_player","keys_unavailable"]),Vn=class{constructor(e){this.options=e;this.keys=e.keys??Ca({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new Eo;links=new Map;replays=new Nn;keys;localPlayerId="";migration=null;lease=null;clusterTargetIds=[];leaseRenewal=null;leaseAskedAt=null;leaseRenewalWarned=false;credential=null;nextPeerId=ku+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;drainTimers=new Set;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??Qh;this.credentialDeadline=this.options.clock.now()+n;let r=new Promise((s,a)=>{this.ready={resolve:s,reject:a};});if(this.clusterTargetIds=Ge([this.options.clusterTargetId,...this.options.clusterTargetIds??[]]),this.clusterTargetIds.length>0)try{await this.takeLease(e),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: ${Wn(s)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let o=this.options.clock.setTimeout(()=>{this.fail(new j("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),i=()=>this.fail(new j("aborted","the caller aborted while connecting"));e?.aborted?i():e?.addEventListener("abort",i);try{await r;}finally{this.options.clock.clearTimeout(o),e?.removeEventListener("abort",i),this.ready=null;}}async kick(e){if(!this.isHost)throw new j("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.drainTimers)this.options.clock.clearTimeout(e);this.drainTimers.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);case "relayDraining":return this.onRelayDraining(n);default:return}}async onHello(e){let n=ce(e.playerId),r=ce(e.hostPlayerId),o=Un(e.hostEpoch);if(!(n===null||r===null||o===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new jn(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,ku),o=await r.connection.createOffer();await r.connection.setLocalDescription(o);let i=r.connection.localDescription?.sdp??o.sdp;if(!i)throw new j("invalid_sdp","the browser produced an offer with no SDP");Je(i,"offer"),this.refuseMedia(i,"offer"),this.options.signaling.offer(i,e),this.mark("offer sent"),this.fetchCredential().catch(s=>this.report_(s));}async fetchCredential(){let e=++this.credentialGeneration,r=this.links.get(this.hostPlayerId)?.connection.localDescription?.sdp,o=r===void 0?null:Jt(r);if(o===null)throw new j("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??ib,s=()=>this.closed||e!==this.credentialGeneration,a=Zh;for(;;){let l=i.delayUntilAllowed(this.options.clock.now());if(l>0&&!await this.waitForCredential(l,s))return;i.record(this.options.clock.now());try{let d=await this.options.api.joinCredential(this.options.matchId,o);if(s())return;this.credential=d,this.mark("credential ready"),this.maybeAuthenticate();return}catch(d){if(s())return;let c=d.status,u;if(c===409)u=Au;else if(c===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?u=p*1e3:(u=a,a=Math.min(a*2,xu)),u=Math.min(Math.max(u,Au),xu);}else throw d;if(!await this.waitForCredential(u,s))return}}}async waitForCredential(e,n){return this.options.clock.now()+e>this.credentialDeadline?false:(await this.sleep(e),!n())}async onOffer(e){let n=ce(e.fromPlayerId),r=ce(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=ab){let l=this.pendingOffers.keys().next().value;l!==void 0&&this.pendingOffers.delete(l);}this.pendingOffers.set(n,e);return}if(!this.isHost||this.migration.isKicked(n)===true)return;let o=ce(e.sessionId);if(o!==null&&this.answeredSessions.get(n)===o)return;Je(r,"offer"),this.refuseMedia(r,"offer");let i=Jt(r);if(i===null)throw new j("invalid_sdp",`the offer from ${n} carries no usable fingerprint`);if(this.mark("offer received"),o!==null&&this.answeredSessions.set(n,o),await this.refreshLease(false),this.closed||!this.isHost)return;let s=this.links.get(n);if(ce(e.intent)==="ice_restart"&&s?.admitted===true&&s.remoteFingerprint!==null&&Kt(s.remoteFingerprint,i)){await this.answer(s,r),this.mark("ice restart answered");return}s&&this.dropLink(s,"resignalled",false);let a=this.openLink(n,this.nextPeerId++);a.remoteFingerprint=i,await this.answer(a,r),this.mark("answer sent");}async answer(e,n){await e.connection.setRemoteDescription({type:"offer",sdp:n}),this.flushCandidates(e);let r=await e.connection.createAnswer();await e.connection.setLocalDescription(r);let o=e.connection.localDescription?.sdp??r.sdp;if(!o)throw new j("invalid_sdp","the browser produced an answer with no SDP");Je(o,"answer"),this.refuseMedia(o,"answer"),this.options.signaling.answer(e.playerId,o,e.assignedPeerId);}async onAnswer(e){if(this.isHost)return;let n=ce(e.fromPlayerId),r=ce(e.sdp);if(n===null||r===null)return;let o=this.links.get(this.hostPlayerId);if(!o||n!==this.hostPlayerId)return;Je(r,"answer"),this.refuseMedia(r,"answer");let i=Jt(r);if(i===null)throw new j("invalid_sdp","the host's answer carries no usable fingerprint");let s=Un(e.assignedPeerId);if(o.restart!==void 0&&s!==null&&s!==o.assignedPeerId){this.warn(`the host answered the ICE restart from a new connection (peer id ${s}, this link is ${o.assignedPeerId}); dropping the link to re-dial`),this.dropLink(o,"restart_mismatch",true);return}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:Kt(n.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new j("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),e.restart!==void 0&&(e.restart.answered=true,this.progressRestart(e));}async onIce(e){let n=ce(e.fromPlayerId),r=ce(e.candidate);if(n===null||r===null)return;let o=this.links.get(n);if(!o)return;let i=ce(e.sdpMid),s=Un(e.sdpMLineIndex)??Un(e.sdpMLineIndexAlt),a={candidate:r,...i===null?{}:{sdpMid:i},...s===null?{}:{sdpMLineIndex:s}};if(o.connection.remoteDescription===null){o.pendingCandidates.length<64&&o.pendingCandidates.push(a);return}await o.connection.addIceCandidate(a).catch(()=>{});}onPeerLeft(e){let n=ce(e.playerId);if(n===null)return;let r=ce(e.reason)??"left";if(n===this.localPlayerId){this.fail(new j("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=ce(e.hostPlayerId),r=Un(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let o=this.migration.apply({hostPlayerId:n,hostEpoch:r,...ce(e.reason)===null?{}:{reason:ce(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(s=>typeof s=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(o.kind==="duplicate")return;if(o.kind==="completed"){this.emitter.emit("hostChanged",n,r);return}if(o.kind==="refused"){this.report_(new j("migration_failed",o.why));return}for(let s of [...this.links.values()])this.dropLink(s,"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();let i=this.hostEpoch;await this.refreshLease(false),!(this.closed||this.hostEpoch!==i)&&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 j("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=ce(e.reason)??"ended";this.ended=n,this.emitter.emit("matchEnded",n),this.ready!==null&&this.fail(new j("match_ended",`the match ended: ${n}`)),this.close();}onSignalingError(e){let n=ce(e.code)??"unknown",r=ce(e.message)??"the platform refused a signaling message",o=this.isHost?void 0:this.links.get(this.hostPlayerId)?.restart;if(o!==void 0){this.warn(`the platform refused an ICE restart (${n}: ${r})`),o.settle(false);return}this.report_(new j("signaling_failed",`${n}: ${r}`));}async onRelayDraining(e){if(this.migration===null)return;let n=new Set((Array.isArray(e.relayIps)?e.relayIps:[]).filter(u=>typeof u=="string").map(u=>u.toLowerCase())),r=this.isHost?void 0:this.links.get(this.hostPlayerId),o,i=this.options.clock.now(),s=Date.parse(ce(e.deadline)??""),a=(Number.isFinite(s)?s:i+Tu)-i,l=this.options.clock.setTimeout(()=>{this.drainTimers.delete(l),this.onDrainDeadline(n,r,o).catch(u=>this.report_(u));},Math.max(0,Math.min(a,ob)));if(this.drainTimers.add(l),await this.refreshLease(true),this.closed||(this.withoutDrainingRelays(n),this.isHost))return;let d=this.links.get(this.hostPlayerId);if(d===void 0||!d.admitted)return this.reportRestart("skipped","announced");let c=await Pu(d.connection,n);if(!(this.closed||this.links.get(d.playerId)!==d)){if(c===false)return this.reportRestart("skipped","announced");await this.restartIceToHost(d,"announced")&&(o=d);}}async onDrainDeadline(e,n,r){if(this.closed||this.isHost)return;let o=this.links.get(this.hostPlayerId);if(o===void 0)return;let i=await Pu(o.connection,e);if(this.closed||this.links.get(o.playerId)!==o)return;(i===true||i===null&&o===n&&o!==r)&&this.dropLink(o,"relay_deadline",true);}withoutDrainingRelays(e){let n=this.lease;if(n===null||e.size===0)return;let r=false,o=[];for(let i of n.iceServers){let s=i.urls.filter(a=>{let l=lb(a),d=l===null||!e.has(l);return r||=!d,d});s.length>0&&o.push({...i,urls:s});}r&&(this.lease={iceServers:o,expiresAt:n.expiresAt},this.reconfigureLinks());}restartIceToHost(e,n){if(e.restart!==void 0)return e.restart.done;if(e.connection.restartIce===void 0)return this.reportRestart("skipped",n),Promise.resolve(false);let r=()=>{},o=new Promise(a=>{r=a;}),i=this.options.clock.setTimeout(()=>s.settle(false),rb),s={done:o,answered:false,settle:a=>{e.restart===s&&(e.restart=void 0,this.options.clock.clearTimeout(i),this.closed||this.reportRestart(a?"success":"failed",n),r(a));}};return e.restart=s,this.offerIceRestart(e).catch(a=>{this.warn(`could not restart ICE on the connection to the host: ${Wn(a)}`),s.settle(false);}),o}async offerIceRestart(e){let n=e.connection;n.restartIce?.();let r=await n.createOffer();await n.setLocalDescription(r);let o=n.localDescription?.sdp??r.sdp;if(!o)throw new j("invalid_sdp","the browser produced an offer with no SDP");Je(o,"offer"),this.refuseMedia(o,"offer"),!(e.restart===void 0||this.links.get(e.playerId)!==e)&&(this.options.signaling.offer(o,"ice_restart"),this.mark("ice restart offered"));}progressRestart(e){let n=e.restart;if(n===void 0)return;let r=e.connection.iceConnectionState;r==="failed"||r==="closed"?n.settle(false):n.answered&&qa(r)&&n.settle(true);}reportRestart(e,n){this.report([{type:"ice_restart_outcome_total",value:1,labels:{outcome:e,reason:n}}]);}async takeLease(e){this.leaseAskedAt=this.options.clock.now();let n=this.clusterTargetIds,r=await gu(this.options.api,this.options.matchId,n,e);this.lease={iceServers:r.iceServers,expiresAt:r.expiresAt},this.clusterTargetIds=n.slice(Math.max(0,n.indexOf(r.clusterTargetId)));}refreshLease(e){if(this.clusterTargetIds.length===0||this.closed)return Promise.resolve();if(this.leaseRenewal!==null)return this.leaseRenewal;let n=this.options.clock.now();if(this.leaseAskedAt!==null&&n-this.leaseAskedAt<nb)return Promise.resolve();let r=this.lease;if(!e&&r!==null&&r.expiresAt-n>=tb)return Promise.resolve();let o=this.takeLease().then(()=>{this.closed||(this.mark("turn re-leased"),this.reconfigureLinks());},i=>{this.leaseRenewalWarned||(this.leaseRenewalWarned=true,this.warn(`could not renew the TURN lease for this match, so connections keep the relays they were given: ${Wn(i)}`));}).finally(()=>{this.leaseRenewal=null;});return this.leaseRenewal=o,o}reconfigureLinks(){for(let e of this.links.values()){let n=e.connection;if(n.setConfiguration!==void 0)try{n.setConfiguration({...n.getConfiguration?.(),iceServers:this.iceServers()});}catch{}}}iceServers(){return (this.lease?.iceServers??[]).map(e=>({urls:[...e.urls],username:e.username,credential:e.credential}))}openLink(e,n){let o=(this.options.peerConnectionFactory??$a)({iceServers:this.iceServers(),...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),i={};for(let p of ze){let g=o.createDataChannel(p,Fa[p]);g.binaryType="arraybuffer",i[p]=g;}let s={playerId:e,assignedPeerId:n,connection:o,channels:i,remoteFingerprint:null,admitted:false,pendingCandidates:[],detachHandshake:()=>{},detachAll:()=>{}},a=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(s),d=()=>this.onConnectionState(s),c=p=>{this.onHandshakeMessage(s,p.data).catch(g=>this.report_(g));},u=()=>{this.onReliableOpen(s).catch(p=>this.report_(p));};return o.addEventListener("icecandidate",a),o.addEventListener("iceconnectionstatechange",l),o.addEventListener("connectionstatechange",d),i.reliable.addEventListener("open",u),i.reliable.addEventListener("message",c),s.detachHandshake=()=>{i.reliable.removeEventListener("open",u),i.reliable.removeEventListener("message",c);},s.detachAll=()=>{s.detachHandshake(),o.removeEventListener("icecandidate",a),o.removeEventListener("iceconnectionstatechange",l),o.removeEventListener("connectionstatechange",d);},this.links.set(e,s),s}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 j("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 j("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(Oa({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=Da(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 j(Su(r.reason),wu(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=Jt(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 Ma(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(s){let a=s instanceof j&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",Wn(s)),a&&this.fail(s);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(Ga({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(La(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){this.progressRestart(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(n==="disconnected"){if(e.recovering===true)return;if(e.admitted&&e.connection.restartIce!==void 0&&this.reportedUnreachableEpoch!==this.hostEpoch){this.recoverHostLink(e).catch(r=>this.report_(r));return}}this.voteHostUnreachable(n);}}async recoverHostLink(e){let n=this.hostEpoch,r=()=>!this.closed&&this.hostEpoch===n&&this.links.get(e.playerId)===e;e.recovering=true;try{if(await this.refreshLease(!0),!r())return;if(qa(e.connection.iceConnectionState))return this.reportRestart("skipped","disconnected");if(await this.restartIceToHost(e,"disconnected")||!r()||qa(e.connection.iceConnectionState))return;this.voteHostUnreachable(Eu(e.connection.iceConnectionState));}finally{e.recovering=false;}}voteHostUnreachable(e){if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,e);}catch(n){this.report_(n);}}}onConnectionState(e){let n=e.connection.connectionState;n!=="failed"&&n!=="closed"||(e.recovering===true&&this.voteHostUnreachable(Eu(e.connection.iceConnectionState)),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.restart?.settle(false),e.detachAll();for(let o of ze)Iu(e.channels[o]);Iu(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 j?e:new j("connection_failed",Wn(e),{cause:e}));}count(e){this.counted||!sb.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(Po(e))throw new j("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 ce(t){return typeof t=="string"&&t.length>0?t:null}function Un(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function Wn(t){return t instanceof Error?t.message:String(t)}async function Pu(t,e){if(t.getStats===void 0)return null;let n=new Map;try{(await t.getStats()).forEach((a,l)=>{typeof a=="object"&&a!==null&&n.set(l,a);});}catch{return null}let r=[...n.values()],o=r.find(a=>a.type==="transport")?.selectedCandidatePairId,i=(typeof o=="string"?n.get(o):void 0)??r.find(a=>a.type==="candidate-pair"&&a.selected===true)??r.find(a=>a.type==="candidate-pair"&&a.nominated===true&&a.state==="succeeded");if(i===void 0)return null;let s=[i.localCandidateId,i.remoteCandidateId].map(a=>typeof a=="string"?n.get(a):void 0);return s.every(a=>a===void 0)?null:s.some(a=>{let l=a?.address??a?.ip;return typeof l=="string"&&e.has(l.toLowerCase())})}function lb(t){let e=/^(?:turns?|stuns?):(?:\[([^\]]+)\]|([^:?/]+))/i.exec(t),n=e?.[1]??e?.[2];return n===void 0?null:n.toLowerCase()}function qa(t){return t==="connected"||t==="completed"}function Eu(t){return t==="failed"||t==="closed"?t:"disconnected"}function Iu(t){try{t.close();}catch{}}var db=100,cb=50,Kn=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??db)){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 j("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new j("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??cb));}};function K(t){return e=>typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function it(t,e){return n=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e?n:void 0}function zt(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function Cu(t){return typeof t=="boolean"?t:void 0}var ke=K(64),Jn=it(0,2147483647);function To(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=ke(n);typeof r=="string"&&e.push(r);}return e}function J(t,e,n){return {to:t,from:e,read:n,required:true}}function z(t,e,n){return {to:t,from:e,read:n,required:false}}var pb=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=zt("disconnected","failed","closed")(e.iceState),r=it(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:[J("sdp","sdp",K(10240)),J("signaling_intent","intent",zt("initial","ice_restart","full_reconnect")),z("sdp_hash","sdpHash",K(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[J("peer_id","peerId",ke),J("sdp","sdp",K(10240)),J("assigned_peer_id","assignedPeerId",it(0,4294967295)),z("sdp_hash","sdpHash",K(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[J("peer_id","peerId",ke),J("candidate","candidate",K(512)),z("sdp_mid","sdpMid",K(64)),z("sdp_mline_index","sdpMLineIndex",it(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[J("host_epoch","hostEpoch",Jn)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[J("host_epoch","hostEpoch",Jn),z("evidence","evidence",pb)]}}));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",p2p_relay_draining:"relayDraining"}));var gb=16,fb=t=>To(t)?.slice(0,gb);Object.freeze(Object.assign(Object.create(null),{hello:[J("playerId","player_id",ke),J("hostPlayerId","host_player_id",ke),J("hostEpoch","host_epoch",Jn),z("members","members",To)],offer:[J("fromPlayerId","from_player_id",ke),J("sdp","sdp",K(10240)),z("sessionId","signaling_session_id",K(128)),z("sdpHash","sdp_hash",K(128)),z("iceUfrag","ice_ufrag",K(64)),z("intent","signaling_intent",zt("initial","ice_restart","full_reconnect"))],answer:[J("fromPlayerId","from_player_id",ke),J("sdp","sdp",K(10240)),z("sessionId","signaling_session_id",K(128)),z("sdpHash","sdp_hash",K(128)),z("iceUfrag","ice_ufrag",K(64)),z("assignedPeerId","assigned_peer_id",it(0,4294967295))],ice:[J("fromPlayerId","from_player_id",ke),J("candidate","candidate",K(512)),z("sdpMid","sdp_mid",K(64)),z("sdpMLineIndex","sdp_m_line_index",it(0,255)),z("sdpMLineIndexAlt","sdp_mline_index",it(0,255))],peerJoined:[J("playerId","player_id",ke)],peerLeft:[J("playerId","player_id",ke),z("reason","reason",K(64))],migration:[J("hostPlayerId","new_host_player_id",ke),J("hostEpoch","host_epoch",Jn),z("reason","reason",K(64)),z("kickedPlayerIds","kicked_player_ids",To),z("migrationComplete","migration_complete",Cu)],matchEnded:[z("reason","reason",K(64))],error:[z("code","code",K(64)),z("message","message",K(256))],relayDraining:[J("clusterTargetId","cluster_target_id",ke),J("relayIps","relay_ips",fb),J("drainingSince","draining_since",K(40)),J("deadline","deadline",K(40))]}));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 St="webrtc_p2p";function Ou(t){let e=new qn({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 j("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=xe(r.clusterTargetId),i=o===void 0?await yb(t):[o];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 s=await t.rooms.awaitMatch({...r.timeoutMs===void 0?{}:{timeoutMs:r.timeoutMs},...r.signal===void 0?{}:{signal:r.signal}});if(s.protocol!==St)throw new j("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${St}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let a=new Kn({bridge:t.bridge,matchId:s.matchId,clock:t.clock}),l=new Vn({api:e,clock:t.clock,matchId:s.matchId,gameId:t.gameId(),baseUrl:typeof t.baseUrl=="function"?t.baseUrl():t.baseUrl,signaling:a,...i.length===0?{}:{clusterTargetIds:i},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await Bn(),...r.timeoutMs===void 0?{}:{connectTimeoutMs:r.timeoutMs},...t.boot===void 0?{}:{boot:t.boot},...t.log===void 0?{}:{log:t.log}});a.onDropped(d=>l.notifyCandidatesDropped(d)),n.set(s.matchId,l),l.on("matchEnded",()=>n.delete(s.matchId));try{await l.start(r.signal);}catch(d){throw n.delete(s.matchId),l.close(),d}return l}}}async function yb(t){if(t.resolveClusterTargets!==void 0)return Ge(await t.resolveClusterTargets());let e=xe(await t.resolveClusterTarget?.());return e===void 0?[]:[e]}function Gu(t){let{analytics:e,rooms:n}=t,r=t.target??globalThis,o=t.document??globalThis.document,i=[];if(typeof r.addEventListener=="function"){let a=d=>{d?.persisted!==true&&e.endSession("pagehide");};r.addEventListener("pagehide",a),i.push(()=>r.removeEventListener?.("pagehide",a));let l=()=>e.setHidden(!_t());for(let d of Ro)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(!_t());}let s=new Map;return i.push(n.on("matchReady",a=>{let l=a.protocol===St?"p2p":"dedicated";s.set(a.matchId,l),e.trackPlatform("gem_match_started",{transport:l});})),i.push(n.on("matchEnded",a=>{let l=s.get(a.matchId);l!==void 0&&(s.delete(a.matchId),e.trackPlatform("gem_match_ended",{transport:l}));})),()=>{for(let a of i.splice(0))try{a();}catch{}s.clear();}}var hb=[[/swiftshader|llvmpipe|softpipe|software|basic render driver/i,"software"],[/powervr d-series/i,"powervr_d_series"],[/powervr|imagination/i,"powervr_other"],[/adreno/i,"adreno"],[/mali|immortalis/i,"mali"],[/xclipse/i,"xclipse"],[/apple/i,"apple"],[/nvidia|geforce|quadro|tegra/i,"nvidia"],[/\bamd\b|radeon|\bati\b/i,"amd"],[/intel/i,"intel"]];function zn(t){if(t===null||t==="")return "unknown";for(let[e,n]of hb)if(e.test(t))return n;return "other"}function ja(t){return t===null||t===""?"unknown":/^ANGLE \(/.test(t)?/vulkan/i.test(t)?"angle_vulkan":/opengl es/i.test(t)?"angle_gles":/direct3d11|d3d11/i.test(t)?"angle_d3d11":/direct3d9|d3d9/i.test(t)?"angle_d3d9":/metal/i.test(t)?"angle_metal":/opengl/i.test(t)?"angle_opengl":"angle_other":"native_gl"}function Ba(t){return /Android/.test(t)&&/; wv\)/.test(t)?"android_webview":"other"}function Ua(t){try{let e=t.getParameter(t.RENDERER);if(typeof e=="string"&&e!==""&&!/^WebKit WebGL$/i.test(e))return e;let n=t.getExtension("WEBGL_debug_renderer_info");if(n){let r=t.getParameter(n.UNMASKED_RENDERER_WEBGL);if(typeof r=="string"&&r!=="")return r}return typeof e=="string"&&e!==""?e:null}catch{return null}}function bb(t){try{let{vendor:e,architecture:n,description:r}=t??{},o=[e,n,r].filter(i=>typeof i=="string"&&i!=="").join(" ").replace(/img-tec/gi,"PowerVR").replace(/qualcomm/gi,"Adreno").replace(/\barm\b/gi,"Mali").replace(/samsung/gi,"Xclipse");return zn(o)}catch{return "unknown"}}var vb=new Set(["webgl","webgl2","experimental-webgl"]),Lu=false;function Du(t){let e=t.win??globalThis.window,n=e?.HTMLCanvasElement?.prototype;if(Lu||!e||!n)return;Lu=true;let r=t.now??(()=>performance.now()),o=Ba(e.navigator?.userAgent??""),i=new WeakMap,s=null,a=0,l=(p,g,f)=>{try{if(a+=1,a>5)return;t.analytics.trackPlatform("gem_graphics_context_lost",{gpu:p,host:o,route:g,...f===void 0?{}:{context_ms:Math.max(0,Math.round(r()-f))},hidden:e.document?.visibilityState==="hidden"?1:0,nth_loss:a});}catch{}},d=p=>{let g=i.get(p),f=g?.renderer??s;l(zn(f),ja(f),g?.createdAt);},c=n.getContext;n.getContext=function(p,...g){let f=c.call(this,p,...g);try{if(f&&typeof p=="string"&&vb.has(p)&&!i.has(this)){let h=Ua(f);h!==null&&(s=h),i.set(this,{createdAt:r(),renderer:h}),this.addEventListener?.("webglcontextlost",()=>d(this));}}catch{}return f};let u=e.GPUAdapter?.prototype;if(u&&typeof u.requestDevice=="function"){let p=u.requestDevice;u.requestDevice=function(...g){let f=p.apply(this,g);try{let h=r(),R=bb(this.info),b=R==="unknown"?zn(s):R;Promise.resolve(f).then(w=>w?.lost).then(w=>{w&&w.reason!=="destroyed"&&l(b,"webgpu",h);},()=>{});}catch{}return f};}e.addEventListener?.("webglcontextlost",p=>{let g=p.target;g&&!i.has(g)&&d(g);},true);}var Fu=["pointerdown","keydown"];function $u(t,e=globalThis){let n=false,r=false,o=null,i=()=>{if(o!==null){try{e.cancelAnimationFrame?.(o);}catch{}o=null;}},s=()=>{if(!r){r=true,i();for(let g of Fu)e.removeEventListener?.(g,l,{capture:true});e.removeEventListener?.("gamepadconnected",p,{capture:true});}},a=()=>{if(!(n||r)){n=true,s();try{t();}catch{}}};function l(g){g?.isTrusted===true&&a();}let d=()=>{let g;try{g=e.navigator?.getGamepads?.()??[];}catch{return false}return g.some(f=>f?.buttons.some(h=>h.pressed)===true)},c=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},u=()=>{if(o=null,!(n||r)){if(d()){a();return}c()&&(o=e.requestAnimationFrame?.(u)??null);}};function p(){o===null&&!n&&!r&&u();}if(typeof e.addEventListener=="function"){for(let g of Fu)e.addEventListener(g,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",p,{capture:true,passive:true}),c()&&(o=e.requestAnimationFrame?.(u)??null);}return {get engaged(){return n},stop:s}}async function Co(t,e,n,r){let o=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),o}function Wa(t,e){let n=false;return async r=>{let o=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),o}}function Ha(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,s)=>i.at-s.at);return o.map((i,s)=>{let a=o[s-1],l=a===void 0?"":` (+${Math.round(i.at-a.at)}ms)`;return `${i.name}@${Math.round(i.at)}ms${l}`}).join(" \u2192 ")}}}var _b="GemWebSdkHandshake";var wb=()=>Date.now();function qu(t,e,n={}){let r=t[_b];if(r===void 0)return null;let o=n.ttlMs??9500,i=n.now??wb,s=r.events.splice(0),a=r.times?.splice(0),l=0,d=0,c=false,u=i()-o;for(let p=s.length-1;p>=0;p--){let g=a?.[p];if(g!==void 0&&g<u){d+=1;continue}if(l+=1,e(s[p])===true){c=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:c}}var Sb=["angle_gles","native_gl","angle_opengl","angle_other","angle_d3d11","angle_d3d9","angle_metal"],Rb=Object.freeze(Sb.map(t=>Object.freeze({gpu:"powervr_d_series",route:t}))),ju="gemGraphics",Nu=1e3,kb=5e3,Ab=32,xb=32,Pb=300;function Bu(t){if(typeof t!="string"||t==="")return null;try{let n=new URLSearchParams(t).get(ju)?.trim().toLowerCase();return n==="webgpu"||n==="webgl"||n==="safe"?n:null}catch{return null}}function Eb(t){if(!Array.isArray(t)||t.length>Ab)return null;let e=[];for(let n of t){if(n===null||typeof n!="object"||Array.isArray(n))return null;let{gpu:r,route:o,host:i}=n;if(!Va(r)||o!==void 0&&!Va(o)||i!==void 0&&!Va(i))return null;e.push(Object.freeze({gpu:r,...o===void 0?{}:{route:o},...i===void 0?{}:{host:i}}));}return Object.freeze(e)}function Va(t){return typeof t=="string"&&t!==""&&t.length<=xb}function Ib(t,e){return e.some(n=>n.gpu===t.gpu&&(n.route===void 0||n.route===t.route)&&(n.host===void 0||n.host===t.host))}function Tb(t){let e=t?.navigator?.gpu;return e&&typeof e.requestAdapter=="function"?e:null}function Cb(t){try{let e=t?.OffscreenCanvas;if(typeof e!="function")return null;let n=new e(1,1).getContext("webgl");if(!n)return null;let r=Ua(n);try{n.getExtension("WEBGL_lose_context")?.loseContext();}catch{}return r===null?null:{gpu:zn(r),route:ja(r),host:Ba(t?.navigator?.userAgent??"")}}catch{return null}}function Ka(t,e){return Object.freeze({route:t,listed:e})}var Mo=Ka("webgl",false);function Uu(t){let{bridge:e,clock:n,forced:r}=t,o=()=>t.win??globalThis.window,i=t.log??null,s=null,a=false,l=new Set,d,c=null,u=false,p=(b,w,y)=>new Promise(v=>{let E=n.setTimeout(()=>v(y),Math.max(0,w));b.then(T=>{n.clearTimeout(E),v(T);},()=>{n.clearTimeout(E),v(y);});}),g=(b,w)=>(c??=Promise.resolve().then(()=>b.requestAdapter()).then(y=>y!=null,()=>false),p(c,w,false)),f=async b=>{if(a||b<=0)return;let w=n.now(),y=await e.settled(b);if(a||y!=="connected"||!e.parentSupports("graphicsRoutes"))return;let v=b-(n.now()-w);v<=0||await new Promise(E=>{let T=()=>{l.delete(T),n.clearTimeout($),E();},$=n.setTimeout(T,v);l.add(T);});},h=async(b,w)=>Ka(b!==null&&await g(b,w)?"webgpu":"webgl",true),R=async b=>{let w=n.now()+b,y=()=>Math.max(0,w-n.now()),v=Tb(o());if(r!==null&&!u&&(u=true,i?.(`[gem] graphics route forced to ${r} by the ${ju} launch key`+(r==="webgpu"&&v===null?", but this browser has no WebGPU: webgl, listed":""))),r==="webgl")return Mo;if(r==="safe")return Ka("webgl",true);if(r==="webgpu")return h(v,y());await f(y()-(v===null?0:Math.min(Pb,b/2)));let E=s??Rb;return E.length===0||(d===void 0&&(d=Cb(o())),d===null||!Ib(d,E))?Mo:h(v,y())};return {api:{preferredRoute(b){let w=Number(b?.timeoutMs??Nu),y=Number.isFinite(w)?Math.min(Math.max(0,w),kb):Nu;return R(y).catch(()=>Mo)}},accept(b){let w=Eb(b);a=true,w!==null&&(s=w);for(let y of [...l])y();}}}var Ja=new WeakMap,Wu=new WeakSet,za=new Set,Oo=new Set,Go=[],Yt=null,Xa=false,Mb=1920;function Ya(t){return Ja.get(t)}function Qa(t){return !Xa||Wu.has(t)}function Za(t){return t.kind==="webgpu"?true:t.kind!=="webgl"&&t.kind!=="webgl2"&&t.kind!=="experimental-webgl"?false:t.context.getContextAttributes()?.preserveDrawingBuffer!==true}function Hu(t=globalThis.window){if(Xa||!t?.HTMLCanvasElement||typeof t.requestAnimationFrame!="function")return;Xa=true;for(let i of Array.from(t.document?.querySelectorAll("canvas")??[]))Wu.add(i);let e=t.HTMLCanvasElement.prototype,n=e.getContext;e.getContext=function(i,...s){let a=n.call(this,i,...s);if(a&&!Ja.has(this)){let l={kind:i,context:a};Ja.set(this,l),Za(l)&&za.add(this);}return a};let r=t.requestAnimationFrame,o=t.cancelAnimationFrame;t.requestAnimationFrame=i=>{let s=r.call(t,a=>{Oo.delete(s);try{i(a);}finally{Ob();}});return Oo.add(s),Ju(),s},t.cancelAnimationFrame=i=>{Oo.delete(i),o.call(t,i);};}function Vu(t,e){return new Promise(n=>{let r={canvas:t,done:i=>{clearTimeout(o),Go=Go.filter(s=>s!==r),n(i);}},o=setTimeout(()=>r.done(null),e);Go.push(r);})}function Ku(t){return Yt?.canvas===t?Yt.bitmap:null}function Ob(){for(let t of Go){let e;try{e=es(t.canvas);}catch(n){t.done(Promise.reject(n));continue}e&&t.done(createImageBitmap(t.canvas));}Oo.size===0&&Gb();}function Gb(){let t=null;for(let r of za)r.isConnected?(!t||r.width*r.height>t.width*t.height)&&(t=r):za.delete(r);if(!t||t.width===0||t.height===0)return;let e=Math.min(1,Mb/Math.max(t.width,t.height)),n=e<1?{resizeWidth:Math.max(1,Math.floor(t.width*e)),resizeHeight:Math.max(1,Math.floor(t.height*e)),resizeQuality:"medium"}:{};Ju(),Yt={canvas:t,bitmap:createImageBitmap(t,n).catch(()=>null)};}function Ju(){Yt&&(Yt.bitmap.then(t=>t?.close()),Yt=null);}function es(t){let e=Lb();if(!e)return true;e.clearRect(0,0,8,8),e.drawImage(t,0,0,8,8);let n=e.getImageData(0,0,8,8).data;for(let r=0;r<n.length;r+=4){if(n[r]|n[r+1]|n[r+2])return true;let o=n[r+3];if(o!==0&&o!==255)return true}return false}var Xn;function Lb(){if(Xn!==void 0)return Xn;if(typeof OffscreenCanvas=="function")Xn=new OffscreenCanvas(8,8).getContext("2d",{willReadFrequently:true});else {let t=globalThis.document?.createElement("canvas");t&&(t.width=t.height=8),Xn=t?.getContext("2d",{willReadFrequently:true})??null;}return Xn??null}var ts=false;async function Qu(t,e,n,r){if(ts){e.close(),n("busy",true);return}ts=true;let o=null;try{let i=await $b(t,r);if(typeof i=="string"){e.close(),n(i,Db(i));return}o=i;let a=await(r.encodeRef??(l=>Ub(l,r)))(o);if(o.close(),o=null,a===null){e.close(),n("failed",!0);return}if(a.size>Bb){e.close(),n("too_large",!1);return}e.postMessage(a);}catch(i){e.close(),n("failed",true),console.error("[gem] screenshot capture failed",i);}finally{ts=false,o?.close();}}function Db(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}}var Fb=600;async function $b(t,e){if(e.handler){let o=await e.handler(t);return o===null?"declined":zu(o,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=jb(n);if(!r)return "no_source";try{let o=await qb(r);return typeof o=="string"?o:zu(o,t)}catch(o){if(o instanceof DOMException&&o.name==="SecurityError")return "tainted";throw o}}async function qb(t){let e=Nb(t);if(typeof e=="string")return e;if(e.kind.includes("webgl")&&!e.context.getContextAttributes())return "unsupported";if(!Za(e))return createImageBitmap(t);let n=await Vu(t,Fb);if(n)return n;let r=await Ku(t);return r&&es(r)?createImageBitmap(r):e.kind==="webgpu"?"unreadable":"unsupported"}function Nb(t){let e=Ya(t);if(e)return e;if(!Qa(t))return "no_source";try{for(let n of ["webgl2","webgl","2d","webgpu"]){let r=t.getContext(n);if(r)return {kind:n,context:r}}}catch{return "unreadable"}return "unreadable"}function jb(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||!Ya(r)&&!Qa(r)||o>n&&(e=r,n=o);}return e}async function zu(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)),s=Math.max(1,Math.floor(t.height*o));try{let a=await createImageBitmap(t,{resizeWidth:i,resizeHeight:s,resizeQuality:"high"});return t.close(),a}catch{return t.close(),"too_large"}}var Bb=8*1024*1024,Xu="image/webp",Yu=.92;async function Ub(t,e){try{if(typeof OffscreenCanvas=="function"){let i=new OffscreenCanvas(t.width,t.height),s=i.getContext("2d");if(s){s.drawImage(t,0,0);let a=await i.convertToBlob({type:Xu,quality:Yu});if(a&&a.size>0)return a}}}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(s=>i(s),Xu,Yu);})}async function Zu(t,e){if(!e)return;let n;try{n=await Wb(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 Wb(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 em=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function nm(t=globalThis){let n=t[em];if(n!==void 0)return n;let r=false,o=()=>r,i=Kb(t),s=[],a=Hb(t,o,i.watch);a!==null&&s.push(a);let l=Vb(t,o,i.watch);l!==null&&s.push(l);let d={get muted(){return r},setMuted(c){let u=!!c;if(u!==r){r=u;for(let p of s)p();}},setPaused(c){i.setPaused(!!c);}};return Object.defineProperty(t,em,{value:d,configurable:true}),d}function Hb(t,e,n){let r=t.AudioNode?.prototype,o=t.AudioDestinationNode;if(r===void 0||o===void 0)return null;let i=t.OfflineAudioContext,s=r.connect,a=r.disconnect,l=new Map,d=u=>{let p=u.gain,g=u.context.currentTime;p.cancelScheduledValues(g),e()?p.setValueAtTime(0,g):p.setTargetAtTime(1,g,.01);},c=u=>{let p=u.context;if(i!==void 0&&p instanceof i)return null;let g=l.get(p);return g===void 0&&(g=p.createGain(),g.gain.value=e()?0:1,s.call(g,u),l.set(p,g),n.context(p)),g};return r.connect=function(...p){let[g,...f]=p;if(g instanceof o){let h;try{h=c(g);}catch{h=null;}if(h!==null)return s.call(this,h,...f),g}return s.apply(this,p)},r.disconnect=function(...p){let[g,...f]=p;if(g instanceof o){let h=l.get(g.context);if(h!==void 0&&h!==this)try{return a.call(this,h,...f)}catch{}}return a.apply(this,p)},()=>{for(let[u,p]of l){if(u.state==="closed"){l.delete(u);continue}try{d(p);}catch{}}}}function Vb(t,e,n){let r=t.HTMLMediaElement;if(r===void 0)return null;let o=r.prototype,i=Object.getOwnPropertyDescriptor(o,"muted"),s=i?.get,a=i?.set;if(s===void 0||a===void 0)return null;let l=o.play,d=new WeakMap,c=new WeakSet,u=new Set,p=g=>{d.has(g)||d.set(g,!!s.call(g)),c.has(g)||(c.add(g),u.add(new WeakRef(g)),n.element(g)),a.call(g,(d.get(g)??false)||e());};return Object.defineProperty(o,"muted",{configurable:true,enumerable:i?.enumerable??true,get(){let g=d.get(this);return g===void 0?!!s.call(this):g},set(g){d.set(this,!!g),p(this);}}),o.play=function(){try{p(this);}catch{}return l.call(this)},t.document?.addEventListener("play",g=>{let f=g.target;if(f instanceof r)try{p(f);}catch{}},true),()=>{for(let g of u){let f=g.deref();if(f===void 0){u.delete(g);continue}try{a.call(f,(d.get(f)??!1)||e());}catch{}}}}var tm=["pointerup","touchend","click","keydown"];function Kb(t){let e=t.document,n=new Set,r=new WeakSet,o=new WeakSet,i=new Set,s=new WeakSet,a=new Set,l=new Set,d=false,c=false,u=t.AudioContext?.prototype,p=u?.suspend,g=u?.resume,f=u!==void 0&&typeof p=="function"&&typeof g=="function";f&&(u.suspend=function(...D){try{o.add(this);}catch{}return p.apply(this,D)},u.resume=function(...D){try{o.delete(this);}catch{}return g.apply(this,D)});let h=t.HTMLMediaElement?.prototype,R=h?.pause;h!==void 0&&typeof R=="function"&&(h.pause=function(){l.delete(this),R.call(this);});let b=x=>x.state!=="running"&&x.state!=="closed"&&r.has(x)&&!o.has(x),w=x=>x.state==="running"&&i.has(x)&&!o.has(x),y=x=>x.paused&&!x.ended,v=()=>{for(let x of n)if(x.state==="closed")n.delete(x),i.delete(x);else if(b(x)||w(x))return true;for(let x of l){if(y(x))return true;l.delete(x);}return false},E=()=>{for(let x of a){let D=x.deref();if(D===void 0){a.delete(x);continue}try{!D.paused&&!D.ended&&l.add(D);}catch{}}},T=()=>{if(c){c=false,l.clear();for(let x of tm)e?.removeEventListener?.(x,q,true);}},$=()=>{try{c&&!v()&&T();}catch{}};function q(){if(!c||d)return;let x=[];try{for(let D of n){if(D.state==="closed"){n.delete(D),i.delete(D);continue}if(b(D)){i.delete(D);try{x.push(Promise.resolve(g?.call(D)));}catch{}}else if(w(D)){i.delete(D);try{x.push(Promise.resolve(p?.call(D))),s.add(D),x.push(Promise.resolve(g?.call(D)));}catch{}}}for(let D of l){if(!y(D)){l.delete(D);continue}try{x.push(Promise.resolve(D.play()).then(()=>l.delete(D),re=>{re?.name!=="NotAllowedError"&&l.delete(D);}));}catch{l.delete(D);}}}catch{}if(x.length===0){$();return}Promise.allSettled(x).then($);}let U=()=>{if(!(c||e===void 0)){c=true;for(let x of tm)e.addEventListener(x,q,true);}},C=()=>{E(),e?.visibilityState!=="hidden"&&U();},O=()=>{for(let x of n)x.state!=="closed"&&r.has(x)&&i.add(x);U();},N=()=>{i.clear(),E();};try{e?.addEventListener("visibilitychange",()=>{try{e.visibilityState==="hidden"?N():O();}catch{}},!0),t.addEventListener?.("pagehide",()=>{try{N();}catch{}}),t.addEventListener?.("pageshow",x=>{try{x.persisted&&O();}catch{}});}catch{}return {watch:{context(x){if(f)try{n.add(x),(x.state==="running"||x.currentTime>0)&&r.add(x),x.addEventListener("statechange",()=>{try{let D=x.state;D==="running"?(r.add(x),s.delete(x),i.has(x)&&U(),$()):D!=="closed"&&r.has(x)&&!o.has(x)&&!s.has(x)&&C();}catch{}});}catch{}},element(x){try{a.add(new WeakRef(x));}catch{}}},setPaused(x){d=x;}}}var Jb=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",zb=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',Xb=`${Jb}${zb}`,ns=new WeakSet;function rm(t=globalThis.document){if(t==null||ns.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(Xb),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],ns.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"),ns.add(t),"inline")}catch{return null}}function om(t){let e=t.windowMs??1e3,n=t.realm??globalThis,r=t.now??(()=>globalThis.performance?.now()??Date.now()),o=false,i=false,s=false,a=null,l=null,d=null,c=[],u=false,p=0,g=null,f=[],h=()=>o&&!i&&!s,R=()=>{l=null,d=null,c=[],p=0,g=null,f=[];},b=v=>{if(a=null,!h()){R();return}if(d!==null&&c.push(v-d),d=v,l===null)l=v;else {let E=v-l;if(E>=e&&c.length>0){if(u){let T=g===null?E:r()-g;t.report(Qb(p,f,E,T));}else t.report(Yb(c,E));l=v,c=[],p=0,f=[];}}w();},w=()=>{let v=n.requestAnimationFrame;typeof v=="function"&&(a=v.call(n,b));},y=()=>{if(h()){a===null&&(R(),w());return}a!==null&&(n.cancelAnimationFrame?.call(n,a),a=null),R();};return {setRequested(v){o=v,y();},setPaused(v){i=v,y();},draw(){if(!u){u=true,a!==null&&R();return}if(a===null||l===null)return;let v=r();g!==null&&f.length<1e3&&f.push(v-g),g=v,p+=1;},get running(){return a!==null},dispose(){s=true,y();}}}function Yb(t,e){return {fps:t.length*1e3/e,frameTimeP95Ms:im(t),counts:"pageFrames"}}function Qb(t,e,n,r){let o=r;return e.length>0&&(o=im(r>Math.max(...e)?[...e,r]:e)),{fps:t*1e3/n,frameTimeP95Ms:o,counts:"gameDraws"}}function im(t){let e=[...t].sort((r,o)=>r-o),n=Math.max(1,Math.ceil(e.length*.95));return e[n-1]}var Lo=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function am(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function sm(t,e){t!==null&&(t.style.setProperty(Lo.top,`${e.top}px`),t.style.setProperty(Lo.right,`${e.right}px`),t.style.setProperty(Lo.bottom,`${e.bottom}px`),t.style.setProperty(Lo.left,`${e.left}px`));}var Do=Object.freeze({tl:{width:"--gem-reserved-tl-width",height:"--gem-reserved-tl-height",centerY:"--gem-reserved-tl-center-y",controlHeight:"--gem-reserved-tl-control-height"},tr:{width:"--gem-reserved-tr-width",height:"--gem-reserved-tr-height",centerY:"--gem-reserved-tr-center-y",controlHeight:"--gem-reserved-tr-control-height"},bl:{width:"--gem-reserved-bl-width",height:"--gem-reserved-bl-height",centerY:"--gem-reserved-bl-center-y",controlHeight:"--gem-reserved-bl-control-height"},br:{width:"--gem-reserved-br-width",height:"--gem-reserved-br-height",centerY:"--gem-reserved-br-center-y",controlHeight:"--gem-reserved-br-control-height"}});function lm(){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 Zb(t,e){let n={tl:{width:0,height:0,control:null},tr:{width:0,height:0,control:null},bl:{width:0,height:0,control:null},br:{width:0,height:0,control:null}};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,s=o?r.x+r.width:e?e.width-r.x:r.width,a=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(s)),l.height=Math.max(l.height,Math.ceil(a));let d=r.control;if(d){let c=l.control;l.control=c?{top:Math.min(c.top,d.y),bottom:Math.max(c.bottom,d.y+d.height)}:{top:d.y,bottom:d.y+d.height};}}return n}function dm(t,e,n){if(t===null)return;let r=Zb(e,n);for(let o of ["tl","tr","bl","br"]){t.style.setProperty(Do[o].width,`${r[o].width}px`),t.style.setProperty(Do[o].height,`${r[o].height}px`);let i=r[o].control;t.style.setProperty(Do[o].centerY,i?`${(i.top+i.bottom)/2}px`:""),t.style.setProperty(Do[o].controlHeight,i?`${i.bottom-i.top}px`:"");}}var ev=3e4,Fo=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function cm(t){let e=t.clock??me,n=t.timeoutMs??ev,r=new Map,o=new Map,i=0,s=a=>{let l=r.get(a);return l?(r.delete(a),o.delete(l.room),e.clearTimeout(l.timer),l):null};return {available(){return t.bridge.parentSupports("localHost")},ensure(a){if(!t.bridge.parentSupports("localHost"))return Promise.resolve();let l=o.get(a);if(l)return l;let d=new Promise((c,u)=>{let p=`ls${++i}`,g=e.setTimeout(()=>{r.delete(p),o.delete(a),u(new Fo("timeout",true,`the embedder did not answer a local-server request for room ${a} within ${String(n)}ms`));},n);r.set(p,{room:a,resolve:c,reject:u,timer:g}),t.bridge.requestLocalServer(p,a)||(s(p),c());});return o.set(a,d),d.catch(()=>{}),d},accept(a){s(a.requestId)?.resolve();},refuse(a){let l=s(a.requestId);l&&l.reject(new Fo(a.reason,a.retryable,a.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 Yn={url:"https://downloads.indiegems.games/sdk/v24.0.0/gem-web-sdk.devtools.min.js",integrity:"sha384-zCuRCbPyGO57dxP8rwcnqF2TVDiJwQU5MZoYbKY5NrsX9UCxVng5SydD8nSxZqKp"};var Qt=null;function tv(){return Qt!==null||(Qt=new Promise((t,e)=>{let n=document.createElement("script");n.src=Yn.url,n.integrity=Yn.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){Qt=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${Yn.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{Qt=null,e(new Error(`gem devtools: could not load ${Yn.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);})),Qt}function um(t,e){let n=null,r=0;async function o(i){if(n!==null)return true;let s=++r;if(!e())return false;let a=await tv();return !e()||s!==r?false:(n!==null||(n=a.mount(t(),{openedBy:i,text:ft,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 nv=1e4,mm={reason:"unavailable",retryable:false};function pm(t){let e=new Map,n=null,r=null,o=0,i=(d,c)=>{c.timer=t.clock.setTimeout(()=>{e.delete(d),c.reject({reason:"timeout",retryable:true});},t.timeoutMs??nv);},s=(d,c)=>{let u=a(d);u&&c(u);},a=d=>{let c=e.get(d);return c?(e.delete(d),t.clock.clearTimeout(c.timer),c):null},l=new Ot({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((c,u)=>{let p=t.bridge.currentState;if(p==="refused"||p==="closed"){u(mm);return}let g=`t${++o}`,f={resolve:c,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 c={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)){s(d.requestId,u=>u.resolve(c));return}l.accept(c);},onDenied(d){s(d.requestId,c=>c.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[c,u]of e)u.held&&(u.held=false,t.clock.clearTimeout(u.timer),i(c,u),t.bridge.requestToken(c,u.reason));else if(d==="refused"||d==="closed")for(let c of [...e.keys()])s(c,u=>u.reject(mm));},get identity(){return n},get gameVersion(){return r}}}var rv=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),os="embedder_relay_unavailable",ov="embedder_no_relay",iv=new Set([os]),is=new Set([ov]),Qn=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new rs(this)}handleEvent(e){let n=this.pending.get(e.matchId);if(n!==void 0){if(e.event==="matchEnded"){n.refuse(new A("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 A("signaling_failed","the parent relayed an answer with no SDP in it"));return}n.settle({sdp:e.sdp});return}n.refuse(av(e.code,e.message));}}register(e,n){this.pending.get(e)?.refuse(new A("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 A("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 A("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 av(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new A(sv(t),r,{platformCode:t})}function sv(t){return t===void 0||iv.has(t)?"signaling_failed":is.has(t)?"offer_refused":rv.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var rs=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,n){if(this.closed)return Promise.reject(new A("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 A("aborted","the caller aborted before the offer was sent")):new Promise((o,i)=>{let s=()=>{a(),i(new A("aborted","the caller aborted the signaling exchange"));},a=()=>{n?.removeEventListener("abort",s),this.hub.release(e.matchId,l),this.teardown===a&&(this.teardown=null);},l={settle:d=>{a(),o(d);},refuse:d=>{a(),i(d);}};this.teardown=a,n?.addEventListener("abort",s),this.hub.register(e.matchId,l);try{r.dedicatedOffer(e.matchId,e.sdp,e.intent);}catch(d){l.refuse(d instanceof A?d:new A("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var gm="match_ended:",fm="server_shutdown:",ym="kicked:",lv=123;function dv(t){if(typeof t!="string"||t.length===0||t.length>lv)return {kind:"other"};if(t.startsWith(gm)){let e=ot(t.slice(gm.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(fm)?{kind:"server_shutdown",cause:t.slice(fm.length)}:t.startsWith(ym)?{kind:"kicked",detail:t.slice(ym.length)}:{kind:"other"}}function as(t,e,n){let r=dv(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 ss(){return {exchange(){return Promise.reject(new A("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 cv=3e3,uv=1e4,mv=15e3;async function $o(t){let e=t.peerConnection;try{bm(t,"before the handshake started"),ls(t);let n=e.createDataChannel(t.channelLabel??"gem",{ordered:!0});for(let s of t.extraChannels??[]){let a=e.createDataChannel(s.label,{...s.ordered===void 0?{}:{ordered:s.ordered},...s.maxRetransmits===void 0?{}:{maxRetransmits:s.maxRetransmits}});t.onExtraChannel?.(s.label,a);}let r=await e.createOffer();await e.setLocalDescription(r),await fv(e,t),ls(t);let o=e.localDescription?.sdp??r.sdp;if(!o)throw new A("invalid_sdp","the offer carried no SDP");Je(o,"offer"),hm(o,"offer");let i=await gv(t,o);if(ls(t),typeof i?.sdp!="string")throw new A("invalid_sdp","the signaling channel answered without an SDP");return Je(i.sdp,"answer"),hm(i.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:i.sdp}),await yv(n,t),bm(t,"before the channel opened"),n}catch(n){throw e.close(),pv(n)}}function pv(t){return t instanceof A?t:wm(t)?Rt():new A("connection_failed",Sm(t),{cause:t})}function hm(t,e){if(Po(t))throw new A("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 gv(t,e){let n=t.exchangeTimeoutMs??uv,r=_m(t,n),o=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(i=>{throw i instanceof A?i:wm(i)?Rt():new A("signaling_failed",Sm(i),{cause:i})});return hv(o,t,r,()=>r.exhausted?ds("while the offer was in flight"):new A("timeout",`no answer arrived within ${n}ms`))}function fv(t,e){if(t.iceGatheringState==="complete"||e.signal?.aborted)return Promise.resolve();let{clock:n}=e;return new Promise(r=>{let o=()=>{n.clearTimeout(s),t.removeEventListener("icegatheringstatechange",i),e.signal?.removeEventListener("abort",o),r();},i=()=>{t.iceGatheringState==="complete"&&o();},s=n.setTimeout(o,e.gatherTimeoutMs??cv);t.addEventListener("icegatheringstatechange",i),e.signal?.addEventListener("abort",o);})}function yv(t,e){if(e.signal?.aborted)return Promise.reject(Rt());if(t.readyState==="open")return Promise.resolve();if(t.readyState!=="connecting")return Promise.reject(new A("connection_failed",`the data channel was already '${t.readyState}' when the answer was applied`));let{clock:n}=e,r=e.openTimeoutMs??mv,o=_m(e,r);return new Promise((i,s)=>{let a=()=>{n.clearTimeout(p),t.removeEventListener("open",l),t.removeEventListener("close",d),t.removeEventListener("error",d),e.signal?.removeEventListener("abort",c);},l=()=>{a(),i();},d=g=>{a(),s(new A("connection_failed","the data channel failed before it opened",vm(g)===void 0?void 0:{cause:vm(g)}));},c=()=>{a(),s(Rt());},u=()=>{a(),s(o.exhausted?ds("while the channel was still opening"):new A("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",c);})}function _m(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 hv(t,e,n,r){let{clock:o,signal:i}=e;return i?.aborted?Promise.reject(Rt()):new Promise((s,a)=>{let l=u=>{o.clearTimeout(c),i?.removeEventListener("abort",d),u();},d=()=>l(()=>a(Rt())),c=o.setTimeout(()=>l(()=>a(r())),n.ms);i?.addEventListener("abort",d),t.then(u=>l(()=>s(u)),u=>l(()=>a(u)));})}function bm(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw ds(`already ${e}`)}function ds(t){return new A("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function ls(t){if(t.signal?.aborted)throw Rt()}function Rt(){return new A("aborted","the caller aborted the connection attempt")}function wm(t){return t?.name==="AbortError"}function vm(t){return t?.error}function Sm(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:[J("sdp","sdp",K(10240)),z("sessionId","session_id",K(64))],error:[z("code","code",K(64)),z("message","message",K(256))],matchEnded:[z("reason","reason",K(64))]}));function Tm(t){let{client:e,clock:n,rooms:r}=t,o=t.signaling??ss,i=t.log??(y=>console.warn(y)),s=new Vt({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,l=(y,v)=>{let E=a.get(y)??new Set;E.add(v),a.set(y,E);},d=(y,v)=>{let E=a.get(y);E!==void 0&&(E.delete(v),E.size===0&&a.delete(y));},c=async y=>{if(r.isHost&&!us(r)&&r.currentRoom?.matchId===void 0){let v=xe(y.clusterTargetId);await r.startMatch({...v===void 0?{}:{clusterTargetId:v},...y.retry===void 0?{}:{retry:y.retry},...y.signal===void 0?{}:{signal:y.signal}});}return Em(r.matchConnectionState==="suspended"?await r.reconnectToMatch(cs(y)):await r.awaitMatch(cs(y)))},u=async y=>Em(await r.pollMatchStatus(cs(y))),p=async(y,v)=>{let E=false;try{let T=await c(y),$=r.currentRoom?.transports;if($!==void 0&&!$.includes("webrtc"))throw new A("misconfigured",`the room template offers (${$.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 q=y.peerConnection??Im();E=!0;let U=await $o({peerConnection:q,signaling:v,clock:n,matchId:T.matchId,credentialExpiresAt:T.credentialExpiresAt,...qo(y,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),C=null;if(y.presentCredential!==!1)try{C=await Mn({channel:U,clock:n,credential:T.joinCredential,credentialExpiresAt:T.credentialExpiresAt,...qo(y,"onMessage","signal"),...y.welcomeTimeoutMs===void 0?{}:{ceilingMs:y.welcomeTimeoutMs}});}catch(O){throw Le(U),Le(q),O}return xv(r,T,U,q,v,y.reportDisconnect!==!1,y.reportConnected!==!1,C,{remember:l,forget:d},y.onMatchEnded)}catch(T){throw E&&Pm(s,T),Le(v),T}},g=async(y,v,E,T,$,q)=>{if(y==="webtransport"){let x=T?.webtransport;if(x===void 0)throw new A("misconfigured","webtransport is not advertised");let D={credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,clock:n};if(typeof x.named_url=="string"&&x.named_url!==""){let re=Math.max(Math.floor(q/2),1e3);try{return await Dn({url:x.named_url,timeoutMs:re,log:i,...D})}catch(ge){if(vo()!==null)throw ge;return i(`[gem] webtransport named dial failed (${ho(ge)}); retrying the pinned dial`),Dn({url:x.url,certHashBase64:x.cert_sha256_b64,timeoutMs:re,log:i,...D})}}return Dn({url:x.url,certHashBase64:x.cert_sha256_b64,timeoutMs:q,...D})}if(y==="websocket"){let x=T?.websocket;if(x===void 0)throw new A("misconfigured","websocket is not advertised");return _a({url:x.url,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,clock:n,timeoutMs:q})}let U=v.peerConnection??Im(),C,O=await $o({peerConnection:U,signaling:$,clock:n,matchId:E.matchId,credentialExpiresAt:E.credentialExpiresAt,extraChannels:[{label:Gn,ordered:false,maxRetransmits:0}],onExtraChannel:(x,D)=>{x===Gn&&(C=D);},...qo(v,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...v.exchangeTimeoutMs===void 0&&v.redial===true?{exchangeTimeoutMs:_v}:{}}),N;try{N=await Mn({channel:O,clock:n,credential:E.joinCredential,credentialExpiresAt:E.credentialExpiresAt,wire:yo,heartbeat:!0,...qo(v,"signal"),...v.welcomeTimeoutMs===void 0?{}:{ceilingMs:v.welcomeTimeoutMs}});}catch(x){throw Le(O),Le(U),x}let H=N.welcome.heartbeatIntervalMs;return {link:Sa(O,U,C,H===void 0?void 0:{clock:n,intervalMs:H}),welcome:N.welcome,channel:O,peerConnection:U}},f=(y,v,E,T,$)=>{let q=false,U;T.link.onClose(H=>{!q&&y.reportDisconnect!==false&&as(r,v.matchId,H),U?.(H);}),y.reportDisconnect!==false&&y.reportConnected!==false&&r.notifyMatchConnected(v.matchId);let C={transport:T.link.transport,send:(H,x)=>T.link.send(H,x),onMessage:H=>T.link.onMessage(H),onClose:H=>{U=H;},close:()=>T.link.close()},O=()=>{q||(q=true,Le(T.link),Le($));},N=H=>{if(!q){try{y.onMatchEnded?.(H);}catch{}O();}};return l(v.matchId,N),{matchId:v.matchId,transport:E,link:C,joinCredential:v.joinCredential,credentialExpiresAt:v.credentialExpiresAt,welcome:T.welcome,...T.channel===void 0?{}:{channel:T.channel},...T.peerConnection===void 0?{}:{peerConnection:T.peerConnection},close(){d(v.matchId,N),O();}}},h=async(y,v)=>{let E=r.currentRoom?.id,T=r.gameId,$=()=>({advert:Ln(r.currentRoom?.settings,y),template:r.currentRoom?.transports??null});if(E===void 0||T===null)return $();try{let q=await e.get(`/v2/games/${encodeURIComponent(T)}/game-rooms/${encodeURIComponent(E)}`,v);return {advert:Ln(q.settings,y),template:Wt(q.transports)??r.currentRoom?.transports??null}}catch{return $()}},R=(y,v)=>{let E=y??Rm;return v.length===0?E:E.filter(T=>v.includes(T))},b=async(y,v,E)=>{try{let T=await c(y),{advert:$,template:q}=await h(T.matchId,y.signal),U=R(q,v),C=U.filter(Z=>Rv(Z,$)),O=vo();if(O!==null&&U.includes("webtransport")&&$?.webtransport!==void 0&&i(`[gem] webtransport skipped: ${O} (learned on an earlier dial in this page)`),C.length===0){let Z=q===null?`the default order (${Rm.join(", ")})`:`the room template's transports (${q.join(", ")||"none"})`;throw new A("misconfigured",`none of ${Z}`+(v.length>0?`, narrowed to (${v.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let N=y.transportAttemptTimeoutMs??vv,H=()=>y.deadlineAt===void 0?1/0:y.deadlineAt-n.now(),x=Z=>t.signalingReady===void 0||Z<=0?Promise.resolve(!0):t.signalingReady(Z),D=[],re=[];for(let Z of C){if(H()<Am){i(`[gem] ${Z} rung not tried: the reconnect budget is spent`);break}re.length>0&&T.credentialExpiresAt-n.now()<xm&&(T=await u(y)),re.push(Z);let lt=!1,Ae=!1,Te={attempts:0,waitedMs:0};for(;;){if(Z==="webrtc"&&y.redial===!0){let te=Math.min(km,H());await x(te)||i(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(te)}ms; offering anyway`);}let Ce=Math.max(Math.min(N,H()),Am);try{return f(y,T,Z,await g(Z,y,T,$,E,Ce),E)}catch(te){let Y=te instanceof A?te:new A("connection_failed",te instanceof Error?te.message:String(te),{cause:te});if(Z==="webrtc"&&Pm(s,Y),(Y.reason==="credential_expired"||Y.reason==="credential_reused")&&!lt){lt=!0,T=await u(y);continue}if(Z==="webrtc"&&Y.reason==="signaling_failed"&&Y.platformCode===os&&!Ae){Ae=!0;let ne=Math.min(km,H());if(i(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(ne)}ms for the socket before offering again`),await x(ne))continue}if(Y.reason==="join_rate_limited"){let ne=Sv(Te,Math.random,H());if(ne!==null){if(Te.attempts+=1,Te.waitedMs+=ne,i(`[gem] ${Z} rung: the server is rate-limiting this player's joins; waiting ${Math.round(ne)}ms before presenting again (retry ${Te.attempts} of ${Mm.maxAttempts})`),await mo(n,ne,y.signal),y.signal?.aborted)throw new A("aborted","the caller aborted while waiting out a join rate limit");T.credentialExpiresAt-n.now()<xm&&(T=await u(y));continue}}if(wv.has(Y.reason)||Y.reason==="credential_expired"||Z==="webrtc"&&Cm(Y)){i(`[gem] ${Z} rung failed (${Y.reason}): ${ho(Y.cause??Y)} \u2014 `+(re.length<C.length?`falling through to ${C[re.length]}`:"no rungs left")),D.push(Y);break}throw i(`[gem] ${Z} rung refused the session (${Y.reason}): ${Y.message}`),Y}}}let ge=D[D.length-1];throw ge===void 0?new A("timeout",`the reconnect budget ran out before any transport (${C.join(", ")}) could be tried`):new A(ge.reason,`every transport tried (${re.join(", ")}) failed; the last said: ${ge.message}`,{cause:D,platformCode:ge.platformCode})}catch(T){throw Le(E),T}};return {listClusterTargets:async(y={})=>ia({client:e,...y}),handleMatchEnded(y,v){let E=a.get(y);if(E!==void 0){a.delete(y);for(let T of E)T(v);}},connect:(async(y={})=>{let v=y.signaling??o();return y.transports===void 0?p(y,v):b(y,y.transports,v)})}}var Rm=["webtransport","webrtc","websocket"],vv=1e4,_v=5e3,km=3e3,Am=1e3,xm=1e4,wv=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function Cm(t){return t.platformCode!==void 0&&is.has(t.platformCode)}var Mm={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function Sv(t,e=Math.random,n=1/0){let r=Mm;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 Rv(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&bo():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||kv(e.websocket.url)}function kv(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return tt(e)}function cs(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var Av=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function Pm(t,e){e instanceof A&&(!Av.has(e.reason)&&!Cm(e)||t.report([{type:"connection_failures_total",value:1}]));}function xv(t,e,n,r,o,i,s,a,l,d){let c=false,u=()=>{c||as(t,e.matchId,void 0);};i&&(n.addEventListener("close",u),s&&t.notifyMatchConnected(e.matchId));let p=()=>{c||(c=true,n.removeEventListener("close",u),a?.detach(),Le(n),Le(r),Le(o));},g=f=>{if(!c){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:a?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function us(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function Em(t){if(t.status==="failed")throw new A("allocation_failed",`match ${t.matchId} did not come up: ${t.reason}`);if(t.status==="ended")throw new A("match_ended",`match ${t.matchId} ended (${t.reason}) before this side connected.`);if(t.protocol!==uo)throw new A("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${uo}' 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 A("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 Im(){let t=globalThis.RTCPeerConnection;if(!t)throw new A("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 Le(t){try{t.close();}catch{}}function qo(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var Pv=1e4;function Om(t,e){return ms(t,e)}function ms(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=s=>({token:s.token,expiresAt:s.expiresAt,chainEndsAt:Number.POSITIVE_INFINITY}),r=null,o=new Ot({clock:e.clock,...e.onStateChange===void 0?{}:{onStateChange:e.onStateChange},request:()=>new Promise((s,a)=>{let l=e.clock.setTimeout(()=>{r=null,a({reason:"unavailable",retryable:true});},e.timeoutMs??Pv);r={resolve:d=>{e.clock.clearTimeout(l),s(d);},reject:a,timer:l};})}),i=t.onServerToken(s=>{let a=n(s),l=r;if(l){r=null,l.resolve(a);return}o.accept(a);});return {source:o,dispose(){i(),o.dispose(),r&&(e.clock.clearTimeout(r.timer),r.reject({reason:"unavailable",retryable:false}),r=null);}}}var gs={};yg(gs,{acceptTransfer:()=>Ev,addEntityProgression:()=>Iv,adminAction:()=>Tv,cancelInventoryTransfer:()=>Cv,claimEntityProgressionRewards:()=>Mv,closeGameRoom:()=>Ov,createEntityBatchOrder:()=>Gv,createEntityOrder:()=>Lv,createSession:()=>Dv,deleteEntityGameSetting:()=>Fv,deleteEntitySave:()=>$v,deleteSession:()=>qv,deleteShowcaseValue:()=>Nv,executeEntityRecipe:()=>jv,finalizeSaveUpload:()=>Bv,getChannelAssignment:()=>Uv,getDropRates:()=>Wv,getEntityCurrency:()=>Hv,getEntityGameSetting:()=>Vv,getEntityInventory:()=>Kv,getEntityInventoryItem:()=>Jv,getEntityLeaderboard:()=>zv,getEntityOrder:()=>Xv,getEntityProgression:()=>Yv,getEntityRecipeAvailability:()=>Qv,getEntityRecipeUsage:()=>Zv,getEntitySave:()=>e_,getEvent:()=>t_,getGameRoomV2:()=>n_,getLeaderboard:()=>r_,getPlayerGameProfile:()=>o_,getPurchaseCatalog:()=>i_,getResolvedTemplate:()=>a_,getRoomArgs:()=>s_,getShowcaseValue:()=>l_,getTransferDetails:()=>d_,ingestAnalyticsEvents:()=>ps,initiateInventoryTransfer:()=>c_,invokeFunction:()=>u_,kickPlayer:()=>m_,listChallenges:()=>p_,listEntityGameSettings:()=>g_,listEntityOrders:()=>f_,listEntityProgressions:()=>y_,listEntitySaves:()=>h_,listEvents:()=>b_,listGameRooms:()=>v_,listResolvedTemplates:()=>__,listTransfers:()=>w_,maxEntityProgression:()=>S_,putEntityGameSetting:()=>R_,putRoomArgs:()=>k_,putShowcaseValue:()=>A_,rejectTransfer:()=>x_,reportMatchPlayers:()=>P_,requestSaveUploadUrl:()=>E_,resetEntityProgression:()=>I_,setMatchBackfill:()=>T_,simulateEntityOrder:()=>C_,transferHostV2:()=>M_,updateGameRoomV2:()=>O_});function S(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 Ev(t,e,n){let r=`/v1/inventory/transfers/${S(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function Iv(t,e,n,r,o,i){let s=`/v1/inventory/${S(e)}/${S(n)}/progressions/${S(r)}/add`;return t.client.post(s,o,i?.signal)}async function Tv(t,e,n,r){let o=`/v1/voice/sessions/${S(e)}/admin`;return t.client.post(o,n,r?.signal)}async function Cv(t,e,n){let r=`/v1/inventory/transfers/${S(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Mv(t,e,n,r,o,i){let s=`/v1/inventory/${S(e)}/${S(n)}/progressions/${S(r)}/claim`;return t.client.post(s,o,i?.signal)}async function Ov(t,e,n){let r=`/v1/games/${S(t.gameId())}/game-rooms/${S(e)}`;return t.client.delete(r,n?.signal)}async function Gv(t,e,n,r,o){let i=`/v1/inventory/${S(e)}/${S(n)}/orders/batch`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Lv(t,e,n,r,o){let i=`/v1/inventory/${S(e)}/${S(n)}/orders`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Dv(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function Fv(t,e,n,r,o){let i=`/v1/settings/${S(e)}/${S(n)}/${S(r)}`;return t.client.delete(i,o?.signal)}async function $v(t,e,n,r,o){let i=`/v1/saves/${S(e)}/${S(n)}/${S(r)}`;return t.client.delete(i,o?.signal)}async function qv(t,e,n){let r=`/v1/voice/sessions/${S(e)}`;return t.client.delete(r,n?.signal)}async function Nv(t,e,n,r){let o=`/v1/showcase/players/${S(e)}/${S(n)}`;return t.client.delete(o,r?.signal)}async function jv(t,e,n,r,o){let i=`/v1/inventory/${S(e)}/${S(n)}/recipes/execute`;return t.client.post(i,r,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Bv(t,e,n,r,o,i){let s=`/v1/saves/${S(e)}/${S(n)}/${S(r)}/finalize`;return t.client.post(s,o,i?.signal)}async function Uv(t,e,n){let r=`/v1/games/${S(t.gameId())}/config/channels/${S(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Wv(t,e,n){let r=`/v1/inventory/loot-tables/${S(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Hv(t,e,n,r,o){let i=`/v1/inventory/${S(e)}/${S(n)}/currencies/${S(r)}`;return t.client.get(i,o?.signal)}async function Vv(t,e,n,r,o){let i=`/v1/settings/${S(e)}/${S(n)}/${S(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function Kv(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(),s=`/v1/inventory/${S(e)}/${S(n)}`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function Jv(t,e,n,r,o){let i=`/v1/inventory/${S(e)}/${S(n)}/items/${S(r)}`;return t.client.get(i,o?.signal)}async function zv(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 s=i.toString(),a=`/v1/leaderboards/${S(e)}/${S(n)}/${S(r)}`+(s?`?${s}`:"");return t.client.get(a,o?.signal)}async function Xv(t,e,n,r,o){let i=`/v1/inventory/${S(e)}/${S(n)}/orders/${S(r)}`;return t.client.get(i,o?.signal)}async function Yv(t,e,n,r,o){let i=`/v1/inventory/${S(e)}/${S(n)}/progressions/${S(r)}`;return t.client.get(i,o?.signal)}async function Qv(t,e,n,r,o,i){let s=`/v1/inventory/${S(e)}/${S(n)}/catalogs/${S(r)}/recipes/${S(o)}/availability`;return t.client.get(s,i?.signal)}async function Zv(t,e,n,r){let o=new URLSearchParams;r?.limit!==void 0&&o.set("limit",String(r?.limit));let i=o.toString(),s=`/v1/inventory/${S(e)}/${S(n)}/recipe-usage`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function e_(t,e,n,r,o){let i=`/v1/saves/${S(e)}/${S(n)}/${S(r)}`;return t.client.getWithEtag(i,{...o?.signal===void 0?{}:{signal:o.signal},...o?.ifNoneMatch===void 0?{}:{ifNoneMatch:o.ifNoneMatch}})}async function t_(t,e,n){let r=`/v1/events/${S(e)}`;return t.client.get(r,n?.signal)}async function n_(t,e,n){let r=`/v2/games/${S(t.gameId())}/game-rooms/${S(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function r_(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/${S(e)}`+(o?`?${o}`:"");return t.client.get(i,n?.signal)}async function o_(t,e,n){let r=`/v1/profiles/players/${S(e)}`;return t.client.get(r,n?.signal)}async function i_(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 a_(t,e,n){let r=`/v1/game-room-templates/${S(e)}`;return t.client.get(r,n?.signal)}async function s_(t,e,n){let r=`/v1/games/${S(t.gameId())}/game-rooms/${S(e)}/room-args`;return t.client.get(r,n?.signal)}async function l_(t,e,n,r){let o=`/v1/showcase/players/${S(e)}/${S(n)}`;return t.client.get(o,r?.signal)}async function d_(t,e,n){let r=`/v1/inventory/transfers/${S(e)}`;return t.client.get(r,n?.signal)}async function ps(t,e,n){let r=`/v1/games/${S(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true,retryRateLimited:false})}async function c_(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function u_(t,e,n){let r=new URLSearchParams;n?.cue_id!==void 0&&r.set("cue_id",String(n?.cue_id));let o=r.toString(),i="/v1/functions/invoke"+(o?`?${o}`:"");return t.client.postBytes(i,e,n?.signal)}async function m_(t,e,n,r){let o=`/v1/games/${S(t.gameId())}/game-rooms/${S(e)}/kick/${S(n)}`;return t.client.post(o,void 0,r?.signal)}async function p_(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 g_(t,e,n,r){let o=`/v1/settings/${S(e)}/${S(n)}`;return t.client.get(o,r?.signal)}async function f_(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(),s=`/v1/inventory/${S(e)}/${S(n)}/orders`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function y_(t,e,n,r){let o=`/v1/inventory/${S(e)}/${S(n)}/progressions`;return t.client.get(o,r?.signal)}async function h_(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(),s=`/v1/saves/${S(e)}/${S(n)}`+(i?`?${i}`:"");return t.client.get(s,r?.signal)}async function b_(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 v_(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/${S(t.gameId())}/game-rooms`+(r?`?${r}`:"");return t.client.get(o,e?.signal)}async function __(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function w_(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 S_(t,e,n,r,o,i){let s=`/v1/inventory/${S(e)}/${S(n)}/progressions/${S(r)}/max`;return t.client.post(s,o,i?.signal)}async function R_(t,e,n,r,o,i){let s=`/v1/settings/${S(e)}/${S(n)}/${S(r)}`;return t.client.put(s,o,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function k_(t,e,n,r){let o=`/v1/games/${S(t.gameId())}/game-rooms/${S(e)}/room-args`;return t.client.put(o,n,r?.signal)}async function A_(t,e,n,r,o){let i=`/v1/showcase/players/${S(e)}/${S(n)}`;return t.client.put(i,r,o?.signal)}async function x_(t,e,n){let r=`/v1/inventory/transfers/${S(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function P_(t,e,n,r){let o=`/v1/games/${S(t.gameId())}/matches/${S(e)}/players/report`;return t.client.post(o,n,r?.signal)}async function E_(t,e,n,r,o,i){let s=`/v1/saves/${S(e)}/${S(n)}/${S(r)}/upload-url`;return t.client.post(s,o,i?.signal,{replaySafe:true})}async function I_(t,e,n,r,o,i){let s=`/v1/inventory/${S(e)}/${S(n)}/progressions/${S(r)}/reset`;return t.client.post(s,o,i?.signal)}async function T_(t,e,n,r){let o=`/v1/games/${S(t.gameId())}/matches/${S(e)}/backfill`;return t.client.put(o,n,r?.signal)}async function C_(t,e,n,r,o){let i=`/v1/inventory/${S(e)}/${S(n)}/orders/simulate`;return t.client.post(i,r,o?.signal)}async function M_(t,e,n,r){let o=`/v2/games/${S(t.gameId())}/game-rooms/${S(e)}/transfer/${S(n)}`;return t.client.post(o,void 0,r?.signal)}async function O_(t,e,n,r){let o=`/v2/games/${S(t.gameId())}/game-rooms/${S(e)}`;return t.client.patch(o,n,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var G_=1e4,L_=50,D_=1e3,F_=65536-4*1024,Gm=t=>typeof t=="number"?t:0,$_=t=>typeof t=="string"?t:"";function Lm(){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 q_(t){return t?.retryable===true}function N_(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(o=>{let i=o??{};return {index:Gm(i.index),code:$_(i.code)}}):[];return {accepted:Gm(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Dm(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 Fm(t){let e=Math.max(1,Math.floor(t.maxQueue??D_)),n={client:t.client,gameId:()=>t.gameId},r=[],o=0,i=null,s=false,a=null,l=0,d=0,c=false,u=false,p=y=>{t.log?.(y);},g=()=>{i!==null&&(t.clock.clearTimeout(i),i=null);},f=()=>Math.max(0,d-t.clock.now()),h=()=>{i!==null||s||a!==null||(i=t.clock.setTimeout(()=>{i=null,b().catch(()=>{});},Math.max(G_,f())));},R=()=>{let y=Math.min(r.length,100),v=128;for(let E=0;E<y;E+=1){let T=r[E];if(T===void 0)break;if(v+=JSON.stringify(Dm(T,0)).length+1,v>F_)return Math.max(1,E)}return y};async function b(y){for(;a!==null;)await a.catch(()=>{});if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};let v=w(y);a=v;try{return await v}finally{a===v&&(a=null),r.length>0&&h();}}async function w(y){g();let v=r.splice(0,R()),E=o;o=0;let T=Math.round(t.clock.now()),$={batch_id:Lm(),sent_at_ms:T,events:v.map(q=>Dm(q,T))};try{let q=await ps(n,$,y===void 0?void 0:{signal:y}),U=N_(q,E);l=0,d=0;for(let C of U.rejected)p(`[gem] analytics: an event was refused (${C.code}). See the analytics_events section of your game config.`);return U}catch(q){if(q_(q)){for(r=[...v,...r],o+=E;r.length>e;)r.shift(),o+=1;l+=1,d=t.clock.now()+so(l,q);}else p(`[gem] analytics: ${v.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(q)}`);throw q}}return {track(y,v,E={}){if(s)return;if(typeof y!="string"||y===""){u||(u=true,p(`[gem] analytics: '${v}' 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(v.startsWith(Ji)){c||(c=true,p(`[gem] analytics: '${v}' 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 T={},$={};for(let[q,U]of Object.entries(E))typeof U=="string"?T[q]=U:typeof U=="number"&&Number.isFinite(U)&&($[q]=U);for(;r.length>=e;)r.shift(),o+=1;r.push({uid:Lm(),playerId:y,name:v,atMs:t.clock.now(),dimensions:T,measures:$}),r.length>=L_&&a===null&&f()===0?b().catch(()=>{}):h();},flush:y=>b(y),get pending(){return r.length},dispose(){s=true,g(),r=[],o=0;}}}function $m(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().");qt(r);let i=await t({player_id:n,...r===void 0?{}:{periods_back:r},...o===void 0?{}:{signal:o}});return Zr(i)}}}var j_=7;function B_(t){let e=t??{},r=(Array.isArray(e.boosts)?e.boosts:[]).flatMap(s=>{let a=s??{};return typeof a.currency_slug!="string"||a.currency_slug===""?[]:typeof a.multiplier_bp!="number"||!Number.isInteger(a.multiplier_bp)?[]:a.multiplier_bp<=0?[]:[Object.freeze({currencySlug:a.currency_slug,multiplier:a.multiplier_bp/1e4})]}),o=e.boosted===true,i=e.expires_in_days;return Object.freeze({active:o,multipliers:Object.freeze(r),...o&&typeof i=="number"&&Number.isInteger(i)?{expiresInDays:Math.min(j_,Math.max(1,i))}:{}})}function qm(t,e=()=>Date.now()){let n=t,r=n.passes,o=n.boost,i=typeof r=="function"?r:void 0,s=typeof o=="function"?o:void 0,a=async(l,d,c)=>{if(l===void 0)throw new Error(`this runtime cannot read a player's ${d}: the server image running this bundle predates host.${d}, or this is a listen host, and only the platform half of a dedicated server holds the allocation proof the read needs.`);if(typeof c!="string"||c==="")throw new TypeError(`gem.match.player${d==="passes"?"Passes":"Boost"}: playerId must be a non-empty string`);let u;try{u=await l.call(t,c);}catch(p){throw new M("unavailable",0,`the platform half could not be asked: ${String(p)}`)}if(u.status!==200)throw sl(u.status,u.body);return u.body};return {playerPasses:async l=>Fr(await a(i,"passes",l),e()),playerBoost:async l=>B_(await a(s,"boost",l))}}function U_(t){let e={};for(let[n,r]of Object.entries(gs))if(typeof r=="function"){let o=r;e[n]=(...i)=>o(t,...i);}return e}function Zt(t,e={}){let n=e.clock??me,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=ms(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),i=qr({baseUrl:r,tokenSource:o.source,defaultQuery:{game_id:t.gameId,channel:t.channel},...e.fetch===void 0?{}:{fetch:e.fetch}}),s=new Ze({transport:i,clock:n}),a={gameId:t.gameId,channel:t.channel,matchId:t.matchId,...t.gameRoomId===void 0?{}:{gameRoomId:t.gameRoomId}},l=U_({client:s,gameId:()=>a.gameId}),d=a.gameRoomId,c=t.endMatch,u=qm(t,()=>n.now()),p=t.log,g=Fm({client:s,clock:n,gameId:a.gameId,...typeof p=="function"?{log:h=>p.call(t,h)}:{}});return {identity:a,client:s,api:l,match:{end:async()=>{if(c===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 c.call(t);},setBackfill:async(h,R)=>{let b=await l.setMatchBackfill(a.matchId,{open:h.open,...h.seats===void 0?{}:{seats:h.seats}},R===void 0?{}:{signal:R});return {open:b.open,seats:b.seats??null}},reportPlayers:async(h,R)=>(await l.reportMatchPlayers(a.matchId,{players:h.map(w=>({player_id:w.playerId,state:w.state}))},R===void 0?{}:{signal:R})).players.map(w=>({playerId:w.player_id,outcome:w.outcome})),...u},analytics:g,earnings:Qr({knownSlug:()=>{},readSlugs:async()=>new Map}),functions:new rt(l.invokeFunction),challenges:$m(l.listChallenges),...d===void 0?{}:{room:{get:h=>l.getGameRoomV2(d,h),args:async h=>{let R=await l.getGameRoomV2(d,h?.signal===void 0?{}:{signal:h.signal}),b=R.modified?R.body:void 0;if(b?.room_args==null||b.room_args_template==null)throw new M("not_found",404,"this room's template declares no room args",void 0,"room_args_not_defined");return {room_args:b.room_args,room_args_template:b.room_args_template}}}},dispose:()=>{g.dispose(),o.dispose();}}}function kt(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function en(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function Zn(t){return typeof t=="string"?t:t.slice().buffer}function No(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 W_=5e3,Nm=3e4,jm=2e3,H_=1e4,V_=3,Bm=1;async function Um(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?_=>console.info(_):e.log,i=_=>o?.(`[gem host] ${_}`),s=typeof t=="function"?t():t,a=Promise.resolve(),l=true,d=false,c=(_,G)=>{l&&(a=a.then(async()=>{if(!d)try{await G();}catch(W){i(`the bundle's ${_} handler threw: ${At(W)}. Serving continues.`);}}));},u=true,p,g,f,h=_=>{if(!u)return;u=false,c("leave",()=>s.leave?.(r,{cause:_??"left"}));let G=g;G&&queueMicrotask(()=>G(_));},R={send(_,G){if(!u)return;let W=en(kt(G));c("message",()=>s.message?.(r,_,typeof _=="string",{reliable:W.reliable,ordered:W.ordered}));},onMessage(_){p=_;},onClose(_){g=_;},close(){h("closed");}},b=(_,G)=>{if(!u)return;let W=en(kt(G));queueMicrotask(()=>{u&&p?.(_,W);});},w=new Map,y=_=>{let G=[];for(let W of ze){let ee=_.channels[W];try{ee.binaryType="arraybuffer";}catch{}let ve=en(W),ct=Ue=>{let It=No(Ue?.data);It!==null&&c("message",()=>s.message?.(_.playerId,It.data,It.isText,{reliable:ve.reliable,ordered:ve.ordered}));};ee.addEventListener("message",ct),G.push(()=>ee.removeEventListener("message",ct));}w.get(_.playerId)?.forEach(W=>W()),w.set(_.playerId,G);},v=_=>{w.get(_)?.forEach(G=>G()),w.delete(_);},E=new Set,T=new Map,$=(_,G,W)=>({playerNumber:_.assignedPeerId,transport:"webrtc_p2p",...G?{rejoin:true}:{},...W?{superseded:true}:{}}),q=_=>{let G=w.has(_.playerId),W=E.has(_.playerId);E.add(_.playerId),y(_),G&&c("leave",()=>s.leave?.(_.playerId,{cause:"superseded"})),c("join",()=>s.join?.(_.playerId,$(_,W,G)));},U=new Set,C=(_,G,W)=>{if(_===r){b(G,W);return}let ee=n.peer(_);if(ee===null){let ve=T.get(_);if(ve!==void 0&&e.clock.now()-ve<jm)return;U.has(_)||(U.add(_),i(`send to '${_}' dropped: no such connected player`));return}ee.send(Zn(G),kt(W));},O={matchId:n.matchId,gameId:e.gameId,channel:e.channel,...e.gameRoomId===void 0?{}:{gameRoomId:e.gameRoomId},apiBaseUrl:e.apiBaseUrl,serverToken:()=>e.tokens.current(),onServerToken:_=>e.tokens.subscribe(_),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(_=>_.playerId)??[],players(){let _=u?[r]:[];for(let G of n.peers)_.push(G.playerId);return _},profile(_){let G=e.room()?.members.find(W=>W.playerId===_);if(!(!G||G.displayName===void 0))return {displayName:ft.toPlain(G.displayName),...G.displayTag===void 0?{}:{displayTag:ft.toPlain(G.displayTag)},...G.discriminator===void 0?{}:{discriminator:G.discriminator}}},playerNumber(_){return _===r?Bm:n.peer(_)?.assignedPeerId},send(_,G,W){C(_,G,W);},broadcast(_,G){let W=G?.except;u&&r!==W&&b(_,G);for(let ee of n.peers)ee.playerId!==W&&ee.send(Zn(_),kt(G));},async endMatch(){let _=await Ce();return _.answer!=="ok"&&i(_.cause),_.answer},kick(_,G){if(_===r){h(G??"kicked");return}n.kick(_).catch(W=>{i(`kick of '${_}' failed: ${At(W)}`);});},log(_){i(_);},warn(_){i(`\u26A0 ${_}`);}},N=()=>{},H=new Promise(_=>{N=_;}),x=[],D=null,re=async(_,G)=>{l=false;let W=a.then(async()=>{try{await s.shutdown(_);}catch(ee){i(`the bundle's shutdown threw: ${At(ee)}`);}});a=W,await W,Fe();for(let ee of x.splice(0))ee();for(let ee of [...w.keys()])v(ee);h(G);},ge=(_,G)=>D||(D=(async()=>{await re(G,_),n.close(),N();})(),D),Z=()=>D||(D=(async()=>{await re({reason:"signal"},"left"),await n.leave().catch(_=>i(`leaving the match failed: ${At(_)}`)),N();})(),D),lt=()=>D||(D=(async()=>{l=false;let _=await Ce();_.answer==="ok"?(await re({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(i(`${_.cause}; leaving instead`),await re({reason:"signal"},"left"),await n.leave().catch(G=>i(`leaving the match failed: ${At(G)}`))),N();})(),D),Ae=null,Te=()=>(Ae??=Zt(O,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),Ae),Ce=async()=>{try{return await ld({client:Te().client,gameId:()=>O.gameId},O.matchId,{},{signal:AbortSignal.timeout(W_)}),{answer:"ok"}}catch(_){return _ instanceof M&&(_.reason==="forbidden"||_.reason==="not_found")?{answer:_.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${_.reason})`}:{answer:"failed",cause:`ending the match failed: ${At(_)}`}}},te=null,Y=false,ne=0,De,Xe=null,Fe=()=>{Y=true,te!==null&&(e.clock.clearTimeout(te),te=null),Xe?.(),Xe=null;},nn=_=>{i(`heartbeats paused: ${_}; they resume when a fresh play token arrives`),Ye();let G=De,W=false,ee=e.tokens.subscribe(ve=>{W||Y||ve.token===G||Et(ve)||(W=true,Xe?.(),Xe=null,ne=0,De=void 0,Ye(),i("a fresh play token arrived; heartbeats resume"),te=e.clock.setTimeout(()=>{Qe();},0));});W?ee():Xe=ee;},Ye=()=>{let _=Ae;Ae=null,_?.dispose();},Et=_=>_.expiresAt*1e3<=e.clock.now(),Qe=async()=>{if(te=null,!Y){try{await Te().client.post(`/v1/games/${encodeURIComponent(O.gameId)}/matches/${encodeURIComponent(O.matchId)}/heartbeat`,void 0,AbortSignal.timeout(H_)),ne=0,De=void 0;}catch(_){if(_ instanceof M&&(_.reason==="forbidden"||_.reason==="not_found")){i(`the platform no longer holds this match under this host (${_.reason}); heartbeats stop`),Fe();return}if(K_(_)){if(Y)return;ne+=1;let G=e.tokens.current(),W=G===void 0?"this host holds no play token":Et(G)?"this host's play token has expired":G.token===De?"the platform refused this host's play token again":ne>=V_?`the platform refused this host's play token ${ne} times in a row`:null;if(De=G?.token,W!==null){nn(W);return}}else ne=0,De=void 0;i(`heartbeat failed: ${At(_)}`);}Y||(te=e.clock.setTimeout(()=>{Qe();},Nm));}},rn=()=>{Y||te!==null||(te=e.clock.setTimeout(()=>{Qe();},Nm));};{let _=N;N=()=>{Fe(),Ae?.dispose(),Ae=null,_();};}let dt=Promise.resolve().then(()=>s.init(O));a=dt.then(()=>{},()=>{}),c("join",()=>s.join?.(r,{playerNumber:Bm,transport:"loopback"})),x.push(n.on("peerJoined",q)),x.push(n.on("peerLeft",(_,G)=>{v(_);let W=e.clock.now();for(let[ee,ve]of T)W-ve>=jm&&T.delete(ee);T.set(_,W),U.delete(_),c("leave",()=>s.leave?.(_,{cause:G}));})),x.push(n.on("error",_=>{i(`\u26A0 session error: ${_.message}`);})),x.push(n.on("matchEnded",_=>{D||fs(f,_),ge("match ended",{reason:"match_ended",platform_reason:_});})),x.push(n.on("hostChanged",_=>{_!==r&&ge("host migrated",{reason:"host_migrated"});}));for(let _ of n.peers)q(_);try{await dt,rn();}catch(_){l=false,Fe(),d=true;for(let G of x.splice(0))G();for(let G of [...w.keys()])v(G);throw n.leave().catch(()=>{}),N(),_}return {matchId:n.matchId,localLink:R,onMatchEnded(_){f=_;},end:lt,leave:Z,stop:_=>ge(_,{reason:"stopped"}),done:H}}function fs(t,e){try{t?.(e);}catch{}}function K_(t){return t instanceof M&&t.status===401||oe.isAuthError(t)}function At(t){return t instanceof Error?t.message:String(t)}function ys(t,e){let n=async()=>{throw new A("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 Wm(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,o=new Map,i=async a=>{r.isHost&&!us(r)&&r.currentRoom?.matchId===void 0&&await r.startMatch({...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...a.signal===void 0?{}:{signal:a.signal}});let l={...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal}};return r.matchConnectionState==="suspended"?r.reconnectToMatch(l):r.awaitMatch(l)},s=a=>({...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0?{}:{clusterTargetId:a.clusterTargetId}});return {async serve(a,l={}){let d=await i(l);if(d.protocol!==St)return ys("dedicated",d.matchId);let c=t.p2p.session?.(d.matchId)??null;if(c===null&&!r.isHost||c!==null&&!c.isHost)return ys("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=c??await t.p2p.connect(s(l)),g=await Um(a,{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(a={}){let l=await i(a),d=a.onMatchEnded;if(l.protocol===St){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 f=await Bn(),h=async()=>t.p2p.connect({...s(a),certificate:f}),R=await h(),b=Z_(R,h,d,w=>{r.notifyMatchDisconnected(w).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(R.matchId,{redial:b.redial,abandon:b.abandon}),b.onClosed(()=>{e.get(R.matchId)?.abandon===b.abandon&&e.delete(R.matchId);})),b}let c=async(g=null)=>await t.dedicated.connect({...g===null?{}:{reportConnected:false,redial:true,...g.deadlineAt===void 0?{}:{deadlineAt:g.deadlineAt}},...a.timeoutMs===void 0?{}:{timeoutMs:a.timeoutMs},...a.signal===void 0?{}:{signal:a.signal},...a.clusterTargetId===void 0||a.clusterTargetId===null?{}:{clusterTargetId:a.clusterTargetId},...d===void 0?{}:{onMatchEnded:d},transports:a.transports??[]}),u=await c(),p=Q_(u,c,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(a,l){let d=e.get(a);return d===void 0?"closed":d.redial(l)},abandonMatch(a,l){e.get(a)?.abandon(l);}}}var Hm="link_closed",J_="host_unreachable",z_=new Set(["failed","closed","relay_deadline","restart_mismatch"]);function X_(t){return z_.has(t)?Hm:J_}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:(s,a)=>r.send(s,a),onMessage:s=>r.onMessage(s),onClose:s=>{i=s,r.onClose(a=>{o="closed",i?.(a);});},close:()=>r.close()}}function Q_(t,e,n,r){let o=t.matchId,i=t,s="connected",a,l,d=[],c=false,u=false,p=f=>{if(s!=="closed"){s="closed";for(let h of d.splice(0))h();l?.(f);}},g=f=>{f.link.onMessage((h,R)=>a?.(h,R)),f.link.onClose(h=>{if(f!==i||s==="closed")return;if(c||!r){p(h);return}let R=n.matchSession;if(R.phase==="suspended"&&R.matchId===o){s="suspended";return}p(h);});};return g(t),{matchId:o,protocol:"dedicated",get transport(){return i.transport},get state(){return s},send(f,h){s==="connected"&&i.link.send(f,h);},onMessage(f){a=f;},onClose(f){l=f;},close(){if(s!=="closed"){if(c=true,s==="suspended"){p("closed");return}i.close(),p("closed");}},async redial(f){if(s==="closed"||c)return "closed";if(u)return "connected";u=true;let h;try{h=await e(f===void 0?{}:{deadlineAt:f});}finally{u=false;}return c||s==="closed"?(h.close(),"closed"):(i=h,g(h),s="connected",n.notifyMatchConnected(o),"connected")},abandon(f){s!=="closed"&&(s==="connected"&&i.close(),p(f));},onClosed(f){s==="closed"?f():d.push(f);}}}function Z_(t,e,n,r,o,i=false){let s=t.matchId,a=t,l,d,c=[],u=[],p=[],g=false,f=false,h=false,R=false,b="connected",w=C=>{if(g)return;g=true,b="closed";for(let N of c.splice(0))N();for(let N of u.splice(0))N();for(let N of p.splice(0))N();let O=d;O&&queueMicrotask(()=>O(C));},y=C=>{for(let O of c.splice(0))O();for(let O of ze){let N=C.channels[O];try{N.binaryType="arraybuffer";}catch{}let H=en(O),x=D=>{let re=No(D?.data);re!==null&&l?.(re.data,H);};N.addEventListener("message",x),c.push(()=>N.removeEventListener("message",x));}},v=()=>a.peer(a.hostPlayerId),E=C=>{if(!(g||a.isHost)&&b!=="suspended"){if(r?.(C),i){b="suspended";return}w(C);}},T=C=>{for(let O of ze){let N=C.channels[O];if(typeof N.addEventListener!="function")continue;let H=()=>{v()===C&&E(Hm);};N.addEventListener("close",H),c.push(()=>N.removeEventListener?.("close",H));}},$=C=>{y(C),T(C),!g&&(b="connected",o?.());},q=C=>{for(let O of u.splice(0))O();u.push(C.on("migrating",()=>{R=true;})),u.push(C.on("hostChanged",O=>{if(R=false,O===C.playerId){w("host_migrated_here");return}let N=v();N!==null&&$(N);})),u.push(C.on("peerJoined",O=>{O.playerId===C.hostPlayerId&&$(O);})),u.push(C.on("matchEnded",O=>{g||fs(n,O),w(O);})),u.push(C.on("peerLeft",(O,N)=>{O===C.hostPlayerId&&E(X_(N));}));};q(a);let U=v();return U!==null&&$(U),{matchId:s,protocol:"p2p",get state(){return b},send(C,O){b==="connected"&&v()?.send(Zn(C),kt(O));},onMessage(C){l=C;},onClose(C){d=C;},close(){f=true,w("closed"),a.leave().catch(()=>{});},async redial(){if(b==="closed")return "closed";if(b==="connected"||h)return "connected";if(R)throw new j("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");h=true;let C;try{for(let N of c.splice(0))N();for(let N of u.splice(0))N();a.close(),C=await e();}finally{h=false;}if(g)return f?C.leave().catch(()=>{}):C.close(),"closed";a=C,q(a);let O=v();if(O===null)throw a.close(),new j("connection_failed","this peer rejoined the match but the host never answered with a link");return $(O),"connected"},abandon(C){w(C);},onClosed(C){g?C():p.push(C);}}}function Vm(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={},s=l=>{n.delete(r)&&(t.clock.clearTimeout(i.timer),o(l));};n.set(r,s),i.timer=t.clock.setTimeout(()=>s(void 0),t.timeoutMs??2e3);let a=false;try{a=t.bridge.requestParty(r);}catch{}a||s(void 0);})},settle(r,o){n.get(r)?.(o);}}}var ew=12e4;function xt(t,e){return {outcome:t,reason:e}}function Km(t){let e=false,n=new Map,r=new Set,o=l=>{for(let d of [...r])try{d(l);}catch(c){t.onListenerError?.(c);}},i=async l=>{try{return await t.confirm(l)}catch{return "unknown"}},s=(l,d,c,u)=>{if(!t.bridge.parentSupports(l))return Promise.resolve(xt("unavailable","error"));if(e)return Promise.resolve(xt("declined","busy"));let p=`purchase-${pe()}`;return new Promise(g=>{let f={},h=b=>{n.delete(p)&&(e=false,t.clock.clearTimeout(f.timer),g(b));};e=true,n.set(p,{finish:h,check:c,label:u}),f.timer=t.clock.setTimeout(()=>h(xt("unavailable","error")),t.timeoutMs??ew);let R=false;try{R=d(p);}catch{}R||h(xt("unavailable","error"));})},a=l=>l===void 0?null:t.confirm(l);return {api:{request(l){return s("purchases",d=>t.bridge.requestPurchase(d,l.kind,l.targetId,l.currencySlug,l.quantity,l.catalogId),a,d=>`purchase ${JSON.stringify(d)}`)},onSettled(l){return r.add(l),()=>{r.delete(l);}}},handOffRefused(l){s("purchases",d=>t.bridge.requestPurchase(d,l.kind,l.targetId,l.currencySlug,l.quantity,l.catalogId,"direct_refused"),a,d=>`purchase ${JSON.stringify(d)}`).then(d=>{d.outcome!=="ok"||d.purchaseId===void 0||(t.onInventoryStale?.(),o(Object.freeze({kind:l.kind,targetId:l.targetId,...l.catalogId===void 0?{}:{catalogId:l.catalogId},quantity:l.quantity,purchaseId:d.purchaseId})));});},settled(l){if(!t.bridge.parentSupports("purchaseSettled")){t.onDropped?.("gem.purchaseSettled from a parent that did not advertise purchaseSettled; ignored");return}let{purchaseId:d}=l;(async()=>{let c=d===void 0?"unknown":await i(d);if(c==="absent"){t.onDropped?.(`gem.purchaseSettled for purchase ${JSON.stringify(d)}, which the platform has no grant for; ignored`);return}t.onInventoryStale?.(),!(c!=="granted"||d===void 0)&&o(Object.freeze({kind:l.purchaseKind,targetId:l.targetId,...l.catalogId===void 0?{}:{catalogId:l.catalogId},quantity:l.quantity,purchaseId:d}));})();},requestAvatar3d(l){return s("avatar3dPurchases",d=>t.bridge.requestAvatar3dPurchase(d,l.itemId,l.currencySlug),()=>t.confirmAvatar3d(l.itemId),()=>`3D avatar ${JSON.stringify(l.itemId)}`)},settle(l){let d=l.outcome==="ok"||l.outcome==="declined"?l.outcome:"unavailable",c=n.get(l.requestId);if(c===void 0){t.onDropped?.(`gem.purchaseResult (${d}) for an unknown requestId: `+JSON.stringify(l.requestId));return}let{finish:u}=c;if(d!=="ok"){u(xt(d,xd(l.reason)));return}let p=l.purchaseId,g;try{g=c.check(p);}catch{g=Promise.resolve("unknown");}if(g===null){t.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),u(xt("unavailable","error"));return}(async()=>{let f;try{f=await g;}catch{f="unknown";}if(f==="granted"){u(p===void 0?{outcome:"ok"}:{outcome:"ok",purchaseId:p});return}f==="absent"&&t.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for "+c.label(p)),u(xt("unavailable","error"));})();}}}async function Jm(t,e){try{return (await Wl(t,e)).granted?"granted":"absent"}catch(n){return n instanceof M&&n.reason==="not_found"?"absent":"unknown"}}var tw="small_human",zm=/^[a-z][a-z0-9_]{0,31}$/,Xm=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,nw=8;function hs(t){if(t===null)return [];if(t.avatars3d!==void 0)return t.avatars3d;let{avatar3dId:e,avatar3dModelUrl:n,avatar3dIconUrl:r}=t;return e===void 0||n===void 0||r===void 0?[]:[{family:tw,id:e,modelUrl:n,iconUrl:r}]}function rw(t,e){return t.length===e.length&&t.every((n,r)=>{let o=e[r];return n.family===o.family&&n.id===o.id&&n.modelUrl===o.modelUrl})}function ow(t){let e=t??{},n=typeof e.item_id=="string"&&Xm.test(e.item_id)?e.item_id:void 0,r=typeof e.family=="string"&&zm.test(e.family)?e.family:void 0,o=typeof e.slug=="string"&&e.slug!==""?e.slug:void 0,i=typeof e.display_name=="string"&&e.display_name!==""?e.display_name:void 0,s=typeof e.description=="string"&&e.description!==""?e.description:void 0,a=Nt(e.icon_url),l=Nt(e.model_url),d=[];for(let c of Array.isArray(e.prices)?e.prices:[]){let u=c??{};typeof u.currency_slug=="string"&&u.currency_slug!==""&&typeof u.price=="number"&&Number.isSafeInteger(u.price)&&u.price>0&&d.push({currencySlug:u.currency_slug,price:u.price});}if(!(n===void 0||r===void 0||o===void 0||i===void 0||a===void 0||l===void 0||d.length===0))return {itemId:n,slug:o,family:r,displayName:i,...s===void 0?{}:{description:s},iconUrl:a,modelUrl:l,prices:d}}function iw(t){if(!Array.isArray(t))return [];let e=[];for(let n of t)if(typeof n=="string"&&zm.test(n)&&!e.includes(n)&&e.push(n),e.length===nw)break;return e}function Ym(t){let e=new Set,n=hs(t.player()),r=o=>{t.log?.(`[gem] an avatars3d onChange listener threw: ${o instanceof Error?o.message:String(o)}`);};return t.subscribe(o=>{let i=hs(o);if(!rw(n,i)){n=i;for(let s of [...e])try{s(i);}catch(a){r(a);}}}),{async families(){return iw(await t.configFamilies())},worn(o){let i=hs(t.player());if(o!==void 0)return i.find(l=>l.family===o);let a=t.player()?.avatar3dId;return (a===void 0?void 0:i.find(l=>l.id===a))??i[0]},async offers(){let o=await t.readOffers(),i=[];for(let s of Array.isArray(o?.offers)?o.offers:[]){let a=ow(s);a!==void 0&&i.push(a);}return i},purchase(o){let i=o?.itemId,s=o?.currencySlug;return typeof i!="string"||!Xm.test(i)?Promise.resolve({outcome:"declined",reason:"not_purchasable"}):typeof s!="string"||s===""?Promise.resolve({outcome:"declined",reason:"unknown_currency"}):t.purchase({itemId:i,currencySlug:s})},onChange(o){return e.add(o),()=>{e.delete(o);}}}}async function Qm(t,e){try{return (await Rl(t,e))?.owned===!0?"granted":"absent"}catch(n){return n instanceof M&&n.reason==="not_found"?"absent":"unknown"}}function Zm(t){return Fl(t)}var aw=6e5;function ep(t){let e=null,n=new Map,r=null,o=false,i=new Set,s=()=>{let a=t.bridge.parentSupports("signIn")&&r!==null&&r!==false;if(a!==o){o=a;for(let l of [...i])try{l(a);}catch(d){t.log?.(`[gem] an onSignInAvailableChange listener threw: ${String(d)}`);}}};return {notePlayer(a){r=a,s();},noteState(){r=null,s();},api:{get signInAvailable(){return o},onSignInAvailableChange(a){return i.add(a),()=>{i.delete(a);}},requestSignIn(){if(!t.bridge.parentSupports("signIn"))return Promise.resolve({outcome:"unavailable"});if(e!==null)return e;let a=`signin-${pe()}`;return e=new Promise(l=>{let d={},c=p=>{n.delete(a)&&(e=null,t.clock.clearTimeout(d.timer),l(p));};n.set(a,c),d.timer=t.clock.setTimeout(()=>{c({outcome:"unavailable"});},t.timeoutMs??aw);let u=false;try{u=t.bridge.requestSignIn(a);}catch{}u||c({outcome:"unavailable"});}),e}},settle(a){let l=a.outcome==="signed_in"||a.outcome==="declined"?a.outcome:"unavailable",d=n.get(a.requestId);if(d===void 0){t.onDropped?.(`gem.signInResult (${l}) for an unknown requestId: `+JSON.stringify(a.requestId));return}d({outcome:l});}}}var sw=1e4,jo="[gem] gem.share.request:",Bo=class extends Error{reason;constructor(e,n){super(`${jo} the arcade refused the share: ${e}`+(n===void 0?"":` (param ${JSON.stringify(n)})`)),this.name="ShareRefusal",this.reason=e,n!==void 0&&(this.key=n);}};function tp(t){let e=new Map;return {wait(n){let r=()=>{};return {answer:new Promise(i=>{let s={};r=a=>{e.delete(n)&&("timer"in s&&t.clearTimeout(s.timer),i(a));},e.set(n,r),s.timer=t.setTimeout(()=>r(null),sw);}),cancel:()=>r(null)}},settle(n){let r=e.get(n.requestId);return r===void 0?false:(r(n),true)},abandon(){for(let n of [...e.values()])n(null);}}}function np(t){let{frame:e,log:n,answers:r}=t,o=false,i=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,s=a=>{n!==null&&(n===void 0?console.warn(a):n(a));};return {get available(){return i()!==null},request(a){let l=i();if(l===null)throw new Error(`${jo} 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(`${jo} pass { params }, or nothing`);let d=Bt(a?.params===void 0?{}:a.params,l.parentSupports("shareRemap"));if("error"in d)throw new TypeError(`${jo} ${d.error}`);let{pairs:c}=d,u=l.parentSupports("shareResult")?`share-${pe()}`:void 0,p=u===void 0?null:r.wait(u);return l.requestShare(c,u)?p===null?Promise.resolve():p.answer.then(g=>{if(g?.outcome==="refused")throw new Bo(g.reason??"error",g.key)}):(p?.cancel(),o||(o=true,s("[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.")),Promise.resolve())}}}var er=3e4,bs=12e4;function tr(t,e,n){return t.held?Promise.resolve(n):(t.held=true,e().then(r=>(t.held=false,r)))}function se(t,e,n){return {outcome:t,reason:e,...n}}function at(t){let e=t.outcome==="ok"||t.outcome==="declined"?t.outcome:"unavailable";return typeof t.reason=="string"?{outcome:e,reason:t.reason}:{outcome:e}}function rp(t){let e=new Map;return {ask(n,r,o,i){let s=`arcade-${pe()}`;return new Promise(a=>{let l={},d=u=>{e.delete(s)&&("timer"in l&&t.clearTimeout(l.timer),a(o(u)));};e.set(s,{expect:n,finish:d}),i!==void 0&&(l.timer=t.setTimeout(()=>d(null),i));let c=false;try{c=r(s);}catch{}c||d(null);})},settle(n){let r=e.get(n.requestId);return r===void 0||r.expect!==n.type?false:(r.finish(n),true)},abandon(){for(let n of [...e.values()])n.finish(null);}}}var lw=12,dw=24,vs=Object.freeze({games:Object.freeze([])});function cw(t){let e=(n,r)=>we(n,`GameCard.${r}`);return Object.freeze({gameId:t.gameId,...t.slug===void 0?{}:{slug:t.slug},name:e(t.untrusted.name,"name"),tagline:e(t.untrusted.tagline,"tagline"),shortDescription:e(t.untrusted.shortDescription,"shortDescription"),tags:Object.freeze(t.untrusted.tags.map(n=>e(n,"tags"))),iconUrl:t.iconUrl,capsuleLandscapeUrl:t.capsuleLandscapeUrl,capsulePortraitUrl:t.capsulePortraitUrl,...t.previewVideoUrl===void 0?{}:{previewVideoUrl:t.previewVideoUrl},...t.previewPosterUrl===void 0?{}:{previewPosterUrl:t.previewPosterUrl}})}function Uo(t){return se("unavailable","error",t)}function op(t){let{bridge:e,asker:n,acting:r}=t,o=a=>e.currentState==="connected"&&e.parentSupports(a),i=new Map,s=(a,l)=>{let d=i.get(a);if(d!==void 0)return d;let c=l().then(u=>(i.delete(a),u));return i.set(a,c),c};return {get available(){return {appLinks:o("appLinks"),openGame:o("openGame")}},appLinks(){return e.parentSupports("appLinks")?s("appLinks",()=>n.ask("gem.appLinksResult",a=>e.requestArcade({type:"gem.requestAppLinks",requestId:a}),a=>{if(a===null)return Uo({});let l=a;return {...at(a),...l.arcade===void 0?{}:{arcade:{store:l.arcade.store}},...l.game===void 0?{}:{game:{store:l.game.store}}}},er)):Promise.resolve(se("unavailable","unsupported",{}))},openApp(a){return e.parentSupports("appLinks")?a!=="arcade"&&a!=="game"?Promise.resolve(se("unavailable","invalid_argument",{})):tr(r,()=>n.ask("gem.openAppResult",l=>e.requestArcade({type:"gem.requestOpenApp",requestId:l,target:a}),l=>l===null?Uo({}):at(l),bs),se("declined","busy",{})):Promise.resolve(se("unavailable","unsupported",{}))},openGame(a){if(!e.parentSupports("openGame"))return Promise.resolve(se("unavailable","unsupported",{}));let l=typeof a=="string"?a.toLowerCase():"";return Sd({gem:B,type:"gem.requestOpenGame",requestId:"-",ref:l})!==null?Promise.resolve(se("unavailable","invalid_argument",{})):tr(r,()=>n.ask("gem.openGameResult",c=>e.requestArcade({type:"gem.requestOpenGame",requestId:c,ref:l}),c=>c===null?Uo({}):at(c),bs),se("declined","busy",{}))},similarGames(a){if(!e.parentSupports("openGame"))return Promise.resolve(se("unavailable","unsupported",vs));let l=a?.limit;return l!==void 0&&(typeof l!="number"||!Number.isInteger(l)||l<1||l>dw)?Promise.resolve(se("unavailable","invalid_argument",vs)):s(`similar:${l??lw}`,()=>n.ask("gem.similarGamesResult",d=>e.requestArcade({type:"gem.requestSimilarGames",requestId:d,...l===void 0?{}:{limit:l}}),d=>{if(d===null)return Uo(vs);let c=at(d),u=d,p=c.outcome==="ok"?Object.freeze(u.games.map(cw)):[];return {...c,games:p}},er))}}}var uw=64,mw=[0,1e3,3e3,6e3],pw=64,ip=Object.freeze({offers:Object.freeze([])}),_s=Object.freeze({held:false});function gw(t){return t.kind==="gem_pack"&&t.grant!==void 0&&t.grant.currency!=="GEMS"?"coin_pack":t.kind}function fw(t){return Object.freeze({skuId:t.skuId,kind:gw(t),name:t.name,description:t.description,...t.imageUrl===void 0?{}:{imageUrl:t.imageUrl},priceDisplay:t.priceDisplay,...t.grant===void 0?{}:{grant:Object.freeze({currency:t.grant.currency,amount:t.grant.amount})},...t.pass===void 0||t.pass===""?{}:{pass:t.pass},earnMultipliers:Object.freeze((t.earnMultipliers??[]).map(e=>Object.freeze({currencySlug:e.currencySlug,multiplierBp:e.multiplierBp})))})}function ap(t){return t.reason===void 0?{outcome:t.outcome,held:false}:{outcome:t.outcome,reason:t.reason,held:false}}function sp(t){return typeof t=="string"&&t.length>0&&t.length<=pw}function lp(t){let{bridge:e,asker:n,acting:r}=t,o=new Set,i=null;function s(c,u,p,g){return e.parentSupports(c)?typeof g!="string"||g.length===0||g.length>uw?Promise.resolve(se("unavailable","invalid_argument",{})):tr(r,()=>n.ask(p,f=>e.requestArcade({type:u,requestId:f,skuId:g}),f=>f===null?se("unavailable","error",{}):at(f)).then(f=>((f.outcome==="ok"||f.reason==="error")&&t.onPurchaseEnded?.(),f)),se("declined","busy",{})):Promise.resolve(se("unavailable","unsupported",{}))}function a(){return e.parentSupports("store")?(i!==null||(i=n.ask("gem.storeOffersResult",c=>e.requestArcade({type:"gem.requestStoreOffers",requestId:c}),c=>{if(c===null)return se("unavailable","error",ip);let u=at(c),p=c,g=u.outcome==="ok"?Object.freeze(p.offers.map(fw)):[];return {...u,offers:g}},er).then(c=>(i=null,c))),i):Promise.resolve(se("unavailable","unsupported",ip))}function l(c){return s("storeOfferSheet","gem.requestStoreOfferSheet","gem.storeOfferSheetResult",c)}async function d(c){let{readPass:u,wait:p}=t;if(u===void 0)return false;let g=0;for(let f of mw){if(f>g){if(p===void 0)return false;await p(f-g),g=f;}try{if(await u(c))return !0}catch{}}return false}return {api:{get available(){return e.currentState==="connected"&&e.parentSupports("store")},get showOfferAvailable(){return e.currentState==="connected"&&e.parentSupports("storeOfferSheet")},offers:a,purchase(c){return s("store","gem.requestStorePurchase","gem.storePurchaseResult",c)},showOffer:l,async showPass(c){if(!sp(c))return se("unavailable","invalid_argument",_s);if(!e.parentSupports("storeOfferSheet"))return se("unavailable","unsupported",_s);let u=await a();if(u.outcome!=="ok")return ap(u);let p=u.offers.find(f=>f.pass===c);if(p===void 0)return se("unavailable","not_found",_s);let g=await l(p.skuId);return g.outcome!=="ok"||g.reason==="pending"?ap(g):await d(c)?{outcome:"ok",held:true}:{outcome:"ok",reason:"pending",held:false}},async passOnSale(c){if(!sp(c))return false;let u=await a();return u.outcome==="ok"&&u.offers.some(p=>p.pass===c)},onSettled(c){return o.add(c),()=>{o.delete(c);}}},settled(c){t.onPurchaseEnded?.();let u=Object.freeze({skuId:c.skuId});for(let p of [...o])try{p(u);}catch(g){t.onListenerError?.(g);}}}}var gp="https://gemarcade.com/branding/manifest.json",yw=1,dp=256*1024,hw=256,bw=64,vw=256,cp=8e3,_w=6e4,ww=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,up={GEMS:"gems-mark",ARCADE_TICKETS:"ticket-mark"},mp=Object.freeze({outcome:"unavailable"}),pp=Object.freeze({outcome:"not_found"});function Pt(t){return typeof t=="number"&&Number.isFinite(t)&&t>0}function Ho(t){return typeof t=="string"&&t!==""&&t.length<=vw}function Sw(t,e){if(!Ho(t))return;let n;try{n=new URL(t,e);}catch{return}let r=Nt(n.href);if(r!==void 0)return n.origin===new URL(e).origin?r:Di(r)}function Rw(t,e){let n=t??{},r=Sw(n.url,e);if(!(r===void 0||!Ho(n.type))&&!(typeof n.bytes!="number"||!(n.bytes>=0))&&!(n.theme!==void 0&&n.theme!=="light"&&n.theme!=="dark"))return Object.freeze({url:r,type:n.type,bytes:n.bytes,...Pt(n.width)?{width:n.width}:{},...Pt(n.height)?{height:n.height}:{},...Pt(n.size)?{size:n.size}:{},...Pt(n.density)?{density:n.density}:{},...n.vector===true?{vector:true}:{},...n.theme===void 0?{}:{theme:n.theme}})}function kw(t,e=gp){let n;try{n=JSON.parse(t);}catch{return null}let r=n??{};if(r.format!==yw||!Array.isArray(r.assets))return null;let o=[],i=new Set;for(let s of r.assets.slice(0,hw)){let a=s??{};if(!Ho(a.id)||!ww.test(a.id)||i.has(a.id)||!Ho(a.kind)||!Array.isArray(a.variants))continue;let l=[];for(let d of a.variants.slice(0,bw)){let c=Rw(d,e);c!==void 0&&l.push(c);}l.length!==0&&(i.add(a.id),o.push(Object.freeze({id:a.id,kind:a.kind,variants:Object.freeze(l)})));}return Object.freeze(o)}function Wo(t){let e;for(let n of t)(e===void 0||(n.width??0)>(e.width??0))&&(e=n);return e}function Aw(t,e,n){let r=t.find(l=>l.vector===true),o=t.filter(l=>l.size===void 0);if(e===void 0)return r??Wo(o)??Wo(t);let i=t.filter(l=>l.size===e);if(i.length>0){let l=c=>c.density??1,d=i.filter(c=>l(c)>=n);return d.length>0?d.reduce((c,u)=>l(u)<l(c)?u:c):i.reduce((c,u)=>l(u)>l(c)?u:c)}if(r!==void 0)return r;let s=o.filter(l=>(l.width??0)>=e*n);return (s.length>0?s.reduce((l,d)=>(d.width??0)<(l.width??0)?d:l):void 0)??Wo(o)??Wo(t)}function xw(t,e){let n=e.theme===void 0?[]:t.variants.filter(a=>a.theme===e.theme),r=t.variants.filter(a=>a.theme===void 0),o=[n,r].filter(a=>a.length>0);if(t.kind!=="image")return o[0]?.[0];let s=(e.size===void 0?void 0:o.find(a=>a.some(l=>l.size===e.size)))??o[0];return s&&Aw(s,e.size,e.density)}function Pw(t,e){if(e!==void 0){if(e===null||typeof e!="object")throw new TypeError(`[gem] branding.${t}: options must be an object`);if(e.size!==void 0&&!Pt(e.size))throw new RangeError(`[gem] branding.${t}: size must be a positive number of CSS px`);if(e.density!==void 0&&!Pt(e.density))throw new RangeError(`[gem] branding.${t}: density must be a positive number`);if(e.theme!==void 0&&e.theme!=="light"&&e.theme!=="dark")throw new TypeError(`[gem] branding.${t}: theme must be 'light' or 'dark'`)}}function fp(t){let e=t.manifestUrl??gp,n=null,r=null,o=-1/0,i=false,s=c=>(o=t.clock.now(),i||(i=true,t.log?.(`[gem] gem.branding could not read the platform's branding (${c}), so every lookup answers 'unavailable' and your bundled fallback shows. If your page sets a Content-Security-Policy, allow ${new URL(e).origin} in connect-src and img-src.`)),null),a=async()=>{if(t.fetch===null)return s("this page has no fetch");let c=t.fetch,u=typeof AbortController=="function"?new AbortController:null,p,g=new Promise(h=>{p=t.clock.setTimeout(()=>{u?.abort(),h(s(`no answer in ${cp} ms`));},cp);}),f=(async()=>{let h=await c(e,{credentials:"omit",redirect:"error",...u?{signal:u.signal}:{}});if(!h.ok)return s("the manifest answered an error");if(Number(h.headers.get("content-length"))>dp)return s("the manifest is too large");let R=await h.text();return R.length>dp?s("the manifest is too large"):kw(R,e)??s("the manifest is not format 1 JSON")})().catch(()=>s("the request failed"));try{return await Promise.race([f,g])}finally{t.clock.clearTimeout(p);}},l=()=>n!==null?Promise.resolve(n):r!==null?r:t.clock.now()-o<_w?Promise.resolve(null):(r=a().then(c=>(r=null,c!==null&&(n=c),c)),r),d=async(c,u,p,g)=>{Pw(c,g);let f=await l();if(f===null)return mp;let h=f.find(w=>w.id===u&&w.kind===p);if(h===void 0)return pp;let R=t.devicePixelRatio(),b=xw(h,{...g?.size===void 0?{}:{size:g.size},density:g?.density??(Pt(R)?R:1),...g?.theme===void 0?{}:{theme:g.theme}});return b===void 0?pp:Object.freeze({outcome:"ok",url:b.url,variant:b,asset:h})};return Object.freeze({get:async(c,u)=>{if(typeof c!="string"||c==="")throw new TypeError("[gem] branding.get: id must be a non-empty string");if(u===null||typeof u!="object"||typeof u.kind!="string")throw new TypeError("[gem] branding.get: options.kind must be a string, such as 'image'");return d("get",c,u.kind,u)},logo:c=>d("logo","gem-logo","image",c),wordmark:c=>d("wordmark","gem-wordmark","image",c),currencyMark:async(c,u)=>{let p=Object.prototype.hasOwnProperty.call(up,c)?up[c]:void 0;if(p===void 0)throw new TypeError("[gem] branding.currencyMark: currency must be 'GEMS' or 'ARCADE_TICKETS', not "+JSON.stringify(String(c).slice(0,40)));return d("currencyMark",p,"image",u)},trophy:c=>d("trophy","trophy-mark","image",c),list:async()=>{let c=await l();return c===null?mp:Object.freeze({outcome:"ok",assets:c})}})}var Cw="(any-pointer: coarse)";function Mw(t){let e=Array.isArray(t)?t:[t],n=[],r=1e4;for(let o of e){if(typeof o!="number"||!Number.isFinite(o)||o<0)return null;if(n.length===99||r===0)continue;let i=Math.min(Math.trunc(o),1e4,r);n.push(i),r-=i;}return n.length%2===0&&n.pop(),n.every(o=>o===0)?[]:n}function yp(t){let{frame:e,log:n}=t,r=t.environment??{navigator:typeof navigator>"u"?void 0:navigator,matchMedia:typeof matchMedia=="function"?c=>matchMedia(c):void 0},o=r.navigator,i,s=new Set,a=()=>typeof o?.vibrate!="function"||r.matchMedia===void 0?false:(i??=r.matchMedia(Cw),i.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(c,u)=>{s.has(c)||(s.add(c),n!==null&&(n===void 0?console.warn(u):n(u)));};return {get available(){return a()||l()},vibrate(c){let u=a();if(!u&&!l())return false;let p=Mw(c);if(p===null)return d("pattern","[gem] gem.vibration.vibrate did nothing: a pattern is a number of milliseconds, or an array of them, each finite and not negative."),false;if(o?.userActivation?.hasBeenActive!==true)return d("activation","[gem] gem.vibration.vibrate did nothing: the player has not tapped or pressed a key in your game yet, and browsers allow vibration only after that."),false;if(u)try{return o.vibrate(p)===!0}catch{return false}let g=e.requestVibrate(p);return g||d("rate","[gem] gem.vibration.vibrate was not sent: more than 600 vibrations in a minute. Vibrate on events, not every frame."),g}}}var tn=Math.PI/180,Be=Object.freeze({touch:Object.freeze({yaw:1*tn,pitch:.66*tn}),mouse:Object.freeze({yaw:.5*tn,pitch:.5*.77*tn}),stick:Object.freeze({yaw:240*tn,pitch:240*.77*tn}),stickDeadzone:.1,stickCurve:2,touchPitchMin:.25}),ws="[gem.controls]",Ss=Object.freeze({yaw:0,pitch:0}),Vo=t=>Number.isFinite(t)?t:0,hp=(t,e)=>({yaw:t+0,pitch:e+0});function bp(t){let e=Vo(t),n=(Math.abs(e)-Be.stickDeadzone)/(1-Be.stickDeadzone),r=Be.stickCurve,o=(Math.exp(r*n)-1)/(Math.exp(r)-1);return Math.sign(e)*Math.min(1,Math.max(0,o))+0}function Ow(t){let e=Math.min(1,2*Math.abs(t)/Math.PI);return (1-Math.pow(e,.75))*(1-Be.touchPitchMin)+Be.touchPitchMin}function vp(t,e){if(t===void 0)return {};if(typeof t!="object"||t===null)throw new TypeError(`${ws} ${e} takes an options object`);let n=t;for(let r of ["sensitivity","gamepadSensitivity"]){let o=n[r];if(o!==void 0&&!(typeof o=="number"&&Number.isFinite(o)&&o>0))throw new TypeError(`${ws} ${e}: ${r} must be a finite number above 0 (1 = the base speed); got ${String(o)}`)}if(n.invertY!==void 0&&typeof n.invertY!="boolean")throw new TypeError(`${ws} ${e}: invertY must be a boolean; got ${String(n.invertY)}`);return n}function Gw(t,e){let n=vp(e,"look()"),r=n.sensitivity,o=n.gamepadSensitivity,i=n.invertY,s=a=>i??a?.invertLookY??false;return {fromPointer(a,l,d,c){let u=Vo(a),p=Vo(l);if(u===0&&p===0)return Ss;let g=t(),f=r??(g===null?void 0:g.lookSensitivity/100)??1,h=d==="touch"||d==="pen",R=h?Be.touch:Be.mouse,b=u*R.yaw*f,w=-p*R.pitch*f;return s(g)&&(w=-w),h&&c!==void 0&&Number.isFinite(c)&&w*c>0&&(w*=Ow(c)),hp(b,w)},fromStick(a,l,d){let c=Vo(d);if(c<=0)return Ss;let u=bp(a),p=bp(l);if(u===0&&p===0)return Ss;let g=t(),f=o??(g===null?void 0:g.gamepadLookSensitivity/100)??1,h=u*Be.stick.yaw*c*f,R=-p*Be.stick.pitch*c*f;return s(g)&&(R=-R),hp(h,R)},set(a){let l=vp(a,"set()");"sensitivity"in l&&(r=l.sensitivity),"gamepadSensitivity"in l&&(o=l.gamepadSensitivity),"invertY"in l&&(i=l.invertY);}}}function _p(t){return {look:e=>Gw(t.recommended,e),LOOK_BASE:Be}}var wp=Object.freeze(["music","sfx","voice","eye","text","hint","speed","bright","controls","star"]),Sp=/^[A-Za-z0-9_-]{1,40}$/;function Rs(t){return typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=1e6}function Rp(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e.slice(0,40)}function kp(t,e,n,r){let o=a=>Number.parseFloat(a.toPrecision(12)),i=Math.min(n,Math.max(e,t)),s=o(e+Math.round((i-e)/r)*r);return s>n&&(s=o(s-r)),Math.min(n,Math.max(e,s))}function Ap(t,e){switch(t.kind){case "toggle":return typeof e=="boolean"?e:void 0;case "slider":{if(typeof e!="number"||!Number.isFinite(e))return;let n=t.min??0,r=t.max??100;return kp(e,n,r,t.step??1)}case "choice":return typeof e=="string"&&(t.options??[]).some(n=>n.id===e)?e:void 0;default:return}}function xp(t,e=()=>{}){if(!Array.isArray(t))return null;let n=[],r=0;for(let o=0;o<t.length;o+=1){let i=t[o],s=`settings[${o}]`;if(n.length===8){e(`${s} and later were left out: at most 8 settings are shown.`);break}if(typeof i!="object"||i===null){e(`${s} was dropped: a setting is an object.`);continue}let a=i,l=a.id;if(typeof l!="string"||!Sp.test(l)){e(`${s} was dropped: its id must be 1 to 40 of A-Z a-z 0-9 _ -.`);continue}let d=`${s} (${JSON.stringify(l)})`;if(n.some(p=>p.id===l)){e(`${d} was dropped: an earlier setting has the same id.`);continue}let c=Rp(a.label);if(c===void 0){e(`${d} was dropped: its label is empty.`);continue}let u;switch(a.kind){case "toggle":{if(typeof a.value!="boolean"){e(`${d} was dropped: a toggle's value is true or false.`);continue}u={id:l,label:c,kind:"toggle",value:a.value},a.quick===true&&(r<2?(u.quick=true,r+=1):e(`${d} is not in the quick row: at most 2 toggles are, the first that ask.`));break}case "slider":{let p=a.min??0,g=a.max??100,f=a.step??1;if(!Rs(p)||!Rs(g)||!Rs(f)||p>=g||f<=0){e(`${d} was dropped: a slider needs finite numbers within \xB11000000 with min below max and a step above 0.`);continue}if(typeof a.value!="number"||!Number.isFinite(a.value)){e(`${d} was dropped: a slider's value is a number.`);continue}u={id:l,label:c,kind:"slider",value:kp(a.value,p,g,f),min:p,max:g,step:f};break}case "choice":{let p=[];for(let g of Array.isArray(a.options)?a.options:[]){if(p.length===4)break;if(typeof g!="object"||g===null)continue;let f=g,h=Rp(f.label);typeof f.id!="string"||!Sp.test(f.id)||h===void 0||p.some(R=>R.id===f.id)||p.push({id:f.id,label:h});}if(p.length<2){e(`${d} was dropped: a choice needs 2 to 4 options, each with an id of 1 to 40 of A-Z a-z 0-9 _ - and a label.`);continue}if(typeof a.value!="string"||!p.some(g=>g.id===a.value)){e(`${d} was dropped: a choice's value is the id of one of its options.`);continue}u={id:l,label:c,kind:"choice",value:a.value,options:p};break}default:e(`${d} was dropped: its kind must be 'toggle', 'slider' or 'choice'.`);continue}a.icon!==void 0&&(wp.includes(a.icon)?u.icon=a.icon:e(`${d} keeps the Arcade's generic icon: ${JSON.stringify(a.icon)} is not one of ${wp.join(", ")}.`)),n.push(u);}return n}var Lw=500;function Pp(t){let{clock:e}=t,n=null,r=null,o=-1/0,i=null,s=new Set,a=new Set,l=u=>{a.has(u)||(a.add(u),t.log!==null&&(t.log===void 0?console.warn(u):t.log(u)));},d=()=>{let u=t.frame();return u.currentState==="connected"&&u.parentSupports("gameSettings")},c=()=>{if(n===null||i!==null)return;let u=JSON.stringify(n);if(u===r)return;let p=o+Lw-e.now();if(p>0){i=e.setTimeout(()=>{i=null,c();},p);return}t.frame().declareSettings(n)&&(r=u,o=e.now());};return {api:{declare(u){let p=xp(u,g=>l(`[gem] gem.settings.declare: ${g}`));return p===null?(l("[gem] gem.settings.declare did nothing: pass an array of settings, or [] for none."),false):(n=p,c(),d())},onChange(u){if(typeof u!="function")return ()=>{};let p=g=>u(g);return s.add(p),()=>{s.delete(p);}}},forgetSent(){r=null,o=-1/0;},flush:c,onSettingChange(u){let p=n?.findIndex(b=>b.id===u.id)??-1,g=n?.[p];if(n===null||g===void 0)return;let f=Ap(g,u.value);if(f===void 0)return;let h=JSON.stringify(n);n=n.map((b,w)=>w===p?{...b,value:f}:b),r===h&&(r=JSON.stringify(n));let R={id:g.id,value:f};for(let b of [...s])try{b(R);}catch(w){console.error("[gem] a gem.settings.onChange handler threw:",w);}}}}function Ep(t,e){return t==null?e?"low":"medium":t==="low"||t==="high"?t:"medium"}var Dw=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Ip(t){if(typeof t!="string"||!Dw.test(t))return;let e=Date.parse(t);return Number.isFinite(e)&&e>0?e:void 0}function nr(){return {declared:false,grantable:false,adGrantable:false,heldLimitReached:false}}var Fw=new Set(["coins","gems"]);function $w(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(typeof n!="object"||n===null)continue;let r=n,{kind:o,currency_id:i,price:s}=r;!Fw.has(o)||e.some(a=>a.kind===o)||typeof i!="string"||i.trim()===""||typeof s!="number"||!Number.isSafeInteger(s)||s<=0||e.push({kind:o,currencyId:i,price:s});}return e.length>0?e:void 0}function Tp(t,e){let n=typeof t=="object"&&t!==null?t:{},r=Ip(n.resets_at),o=r===void 0?{}:{resetsAt:r};if(n.declared!==true)return {...nr(),...o};let i=n.remaining_today,s=typeof i=="number"&&Number.isFinite(i)&&i>=0?Math.floor(i):void 0,a=n.next_eligible_at,l=Ip(a),d=n.held_limit_reached===true,c=a!=null,u=i!=null&&s===void 0,p=$w(n.options),f=(n.ad_grantable!==void 0&&n.ad_grantable!==null?n.ad_grantable===true:n.grantable===true&&(n.options===void 0||n.options===null))&&n.grantable===true&&e&&s!==0&&!u&&!c&&!d,h=p!==void 0&&n.grantable===true&&e;return {declared:true,grantable:f||h,adGrantable:f,...p===void 0?{}:{options:p},...s===void 0?{}:{remainingToday:s},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...o}}var qw=18e4,ks=32,Nw=/^[a-z0-9_-]+$/,jw="rewarded_requires_user_gesture";function Bw(){let t=globalThis.navigator?.userActivation?.isActive;return typeof t=="boolean"?t:void 0}var Uw=1e3;function Ww(){let t=globalThis,e=t.navigator?.getGamepads,n=t.performance?.now;if(typeof e!="function"||typeof n!="function")return;let r=n.call(t.performance),o=e.call(t.navigator);for(let i=0;i<o.length;i+=1){let s=o[i]?.timestamp;if(typeof s=="number"&&r-s>=0&&r-s<=Uw)return true}return false}var Cp=1e4;function Hw(t){return t==="interstitial"||t==="rewarded"}function Mp(t){return typeof t=="string"&&t!==""&&t.length<=ks&&Nw.test(t)}function Vw(t){let e=typeof t=="object"&&t!==null?t:{};return [e.name,e.reason,e.status].join()}function Ko(t){return typeof t=="string"?JSON.stringify(t):typeof t}function Op(t){let e=false,n=new Map,r=new Map,o=new Set,i=d=>{try{t.onDropped?.(d);}catch{}},s=false,a=d=>{if(s)return;s=true;let c=t.log;if(c!==null)try{c===void 0?console.warn(`[gem] ${d}`):c(`[gem] ${d}`);}catch{}},l=d=>{let c=t.readAvailability;if(c===void 0)return Promise.resolve(nr());let u=r.get(d);if(u!==void 0)return u;let p=new Promise(g=>{let f={},h=y=>f.done===true?false:(f.done=true,t.clock.clearTimeout(f.timer),g(y),true),R=(y,v)=>{!h(nr())||o.has(y)||(o.add(y),i(`gem.ads.rewardedStatus("${d}") answered not grantable: ${v}. Said once.`));},b=y=>{R(Vw(y),`the read failed (${y instanceof Error?y.message:Ko(y)})`);},w;try{w=Promise.resolve(c(d,AbortSignal.timeout(Cp)));}catch(y){w=Promise.reject(y);}f.timer=t.clock.setTimeout(()=>{R("timeout","no answer within 10 s");},Cp),w.then(y=>{try{h(Tp(y,t.bridge.parentSupports("ads")));}catch(v){b(v);}},b);});return r.set(d,p),p.then(()=>{r.get(d)===p&&r.delete(d);}),p};return {api:{rewardedStatus(d){return Mp(d)?l(d):(i(`gem.ads.rewardedStatus(${Ko(d)}) answered not grantable: a placement is 1..${String(ks)} characters of a-z, 0-9, '-' and '_'.`),Promise.resolve(nr()))},requestAd(d){if(!t.bridge.parentSupports("ads"))return Promise.resolve({outcome:"no_ad"});if(e)return Promise.resolve({outcome:"no_ad"});let c=d?.placement,u=d?.format;if(!Mp(c)||!Hw(u))return i(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${Ko(c)}, format ${Ko(u)}. A placement is 1..${String(ks)} 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"});if(u==="rewarded"){let g;try{g=(t.userActivation??Bw)();}catch{g=void 0;}if(g===false)try{(t.recentGamepadInput??Ww)()===!0&&(g=!0);}catch{}if(g===false){let f=`${jw}: gem.ads.requestAd("${c}", 'rewarded') answered no_ad without asking: the frame has no user activation and no controller input in the last second. Ask from the button's click, pointerup, touchend or keydown handler, or straight from a controller press, before any await or timer that can outlast the press. On a touchscreen, pointerdown and touchstart run before the tap counts.`;return i(f),a(f),Promise.resolve({outcome:"no_ad"})}}let p=`ad-${pe()}`;return new Promise(g=>{let f={},h=b=>{n.delete(p)&&(e=false,t.clock.clearTimeout(f.timer),g(b));};e=true,n.set(p,h),f.timer=t.clock.setTimeout(()=>{h({outcome:"unavailable"});},t.timeoutMs??qw);let R=false;try{R=t.bridge.requestAd(p,c,u);}catch{}R||h({outcome:"no_ad"});})}},settle(d){let c=d.outcome==="shown"||d.outcome==="no_ad"?d.outcome:"unavailable",u=n.get(d.requestId);if(u===void 0){t.onDropped?.(`gem.adResult (${c}) for an unknown requestId: `+JSON.stringify(d.requestId));return}u({outcome:c});}}}var Gp=Object.freeze(["level_end","run_end","match_end","menu_return","other_break"]),Lp=18e4,Kw=1e4,Jw=/^[a-z0-9_-]{1,32}$/;function As(t){return typeof t=="string"?JSON.stringify(t):typeof t}var rr=Object.freeze({shown:false});function Dp(t){let e=new Map,n,r=false,o=i=>{try{t.onDropped?.(i);}catch{}return rr};return {api:{signal(i){try{if(!t.bridge.parentSupports("moments"))return r?Promise.resolve(rr):(r=!0,Promise.resolve(o("moments_unsupported: gem.moments.signal answered shown: false without asking: this arcade does not do platform moments. Keep the call; it costs nothing. Said once.")));let s=i?.kind,a=i?.placement,l=i?.wall;if(!Gp.includes(s)||a!==void 0&&(typeof a!="string"||!Jw.test(a))||l!==void 0&&typeof l!="boolean")return Promise.resolve(o(`moments_invalid_argument: gem.moments.signal was called with arguments the SDK will not send: kind ${As(s)}, placement ${As(a)}, wall ${As(l)}. A kind is one of ${Gp.join(", ")}; a placement, when given, is 1..32 characters of a-z, 0-9, '-' and '_'; a wall, when given, is true or false. Answering shown: false.`));if(!t.bridge.readyCalled())return Promise.resolve(o(`moments_before_ready: gem.moments.signal({ kind: '${s}' }) before gem.frame.ready(): a moment is a break in play, and play has not started. Signal from the press that leaves a break, never on boot. Answering shown: false.`));if(e.size>0)return Promise.resolve(o(`moments_in_flight: gem.moments.signal({ kind: '${s}' }) while another moment is still waiting for its answer. Signal once per break, and await the answer before play resumes. Answering shown: false.`));let d=t.clock.now();if(n!==void 0&&d-n<Kw)return Promise.resolve(o(`moments_called_repeatedly: gem.moments.signal({ kind: '${s}' }) within 10 s of the last moment's answer (${String(d-n)} ms). One break, one signal, from the press that leaves it; never on a timer. Answering shown: false.`));let c=`moment-${pe()}`;return new Promise(u=>{let p={},g=(h,R)=>{e.delete(c)&&(t.clock.clearTimeout(p.timer),R&&(n=t.clock.now()),u(h));};e.set(c,h=>g(h,!0)),p.timer=t.clock.setTimeout(()=>{e.has(c)&&(g(rr,!0),o(`moments_timeout: gem.moments.signal({ kind: '${s}' }) had no answer within ${String((t.timeoutMs??Lp)/1e3)} s. Answering shown: false.`));},t.timeoutMs??Lp);let f=!1;try{f=t.bridge.signalMoment(c,s,a,l===!0?!0:void 0);}catch{}f||g(rr,!1);})}catch{return Promise.resolve(rr)}}},settle(i){let s=e.get(i.requestId);if(s===void 0){o(`gem.momentResult (shown: ${String(i.shown)}) for an unknown requestId: `+JSON.stringify(i.requestId));return}s({shown:i.shown===true});}}}var xs=16384;function Fp(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:zw(e)}function zw(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 Xw=1e4,Yw=5e3;function $p(t){let e=null,n=false,r=[],o=new Map,i=()=>{for(let s of r.splice(0))s();};return {api:{get current(){return e},wait(s=Yw){return n?Promise.resolve(e):new Promise(a=>{let l=()=>{let u=r.indexOf(d);u>=0&&r.splice(u,1);},d=()=>{t.clock.clearTimeout(c),l(),a(e);},c=t.clock.setTimeout(()=>{l(),a(e);},s);r.push(d);})},put(s){if(!t.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let a=Fp(s);if(a===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(a>16384)return Promise.resolve("too_large");let l=JSON.parse(JSON.stringify(s)),d=`device-settings-${pe()}`;return new Promise(c=>{let u={},p=f=>{o.delete(d)&&(t.clock.clearTimeout(u.timer),f==="stored"&&(e=l,n=true,i()),c(f));};o.set(d,p),u.timer=t.clock.setTimeout(()=>p("unavailable"),t.timeoutMs??Xw);let g=false;try{g=t.bridge.putDeviceSettings(d,l);}catch{}g||p("unavailable");})}},receive(s){let a=s.settings;e=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:null,n=true,i();},settle(s){let a=s.outcome==="stored"||s.outcome==="too_large"?s.outcome:"unavailable",l=o.get(s.requestId);if(l===void 0){t.onDropped?.(`gem.deviceSettings.result (${a}) for an unknown requestId: `+JSON.stringify(s.requestId));return}l(a);}}}var or=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";}};var Qw=/^[a-z0-9][a-z0-9_-]{0,39}$/;function Zw(t){return typeof t=="string"&&Qw.test(t)}function Jo(t){if(t===null||Zw(t))return t;let e=typeof t=="string"?JSON.stringify(t.length>48?`${t.slice(0,48)}\u2026`:t):`a value of type ${typeof t}`;console.warn(`[gem] showPortraitBorders: ${e} is not a border name, so nothing was sent. A name is 1 to 40 of a-z, 0-9, _ and -, starting with a letter or digit, exactly as your store page declares it under media.portrait_borders. Pass null for no art.`);}function qp(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Es(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 zo(t){let e=[];for(let n of Array.isArray(t)?t:[]){if(e.length===4)break;if(typeof n!="object"||n===null)continue;let{id:r,label:o}=n;typeof r!="string"||r.length===0||r.length>32||typeof o!="string"||o.trim().length===0||e.some(i=>i.id===r)||e.push({id:r,label:o.trim().slice(0,40)});}return e.length===0?{settings:false}:{settings:false,items:e}}function Np(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function eS(t){let e=t.untrusted,n=we(e.displayName,"gem.player.displayName"),r=e.displayTag||e.displayHandle,o=r?we(r,"gem.player.displayTag"):void 0,i=t.discriminator||t.displayTag,s=i&&/^[0-9]{1,8}$/.test(i)?i:void 0,a=t.avatarIconUrl||t.avatarUrl,l=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,d=t.avatarIconId,c=t.avatar3dId,u={displayName:n,displayHandle:o??n,badges:(t.badges??[]).map(h=>({itemId:h.itemId,iconUrl:h.iconUrl}))};t.playerId&&(u.playerId=t.playerId),s&&(u.discriminator=s),o&&(u.displayTag=o),a&&(u.avatarIconUrl=u.avatarUrl=a),d&&l.test(d)&&(u.avatarIconId=d),c&&l.test(c)&&(u.avatar3dId=c),t.avatar3dModelUrl&&(u.avatar3dModelUrl=t.avatar3dModelUrl),t.avatar3dIconUrl&&(u.avatar3dIconUrl=t.avatar3dIconUrl),t.avatars3d&&(u.avatars3d=t.avatars3d.filter(h=>l.test(h.id)&&/^[a-z][a-z0-9_]*$/.test(h.family)).filter((h,R,b)=>b.findIndex(w=>w.family==h.family)==R).map(({family:h,id:R,modelUrl:b,iconUrl:w})=>({family:h,id:R,modelUrl:b,iconUrl:w})));let p=t.boost,g=(p?.multipliers??[]).map(h=>({currencyId:h.currencyId,currencySlug:h.currencySlug,multiplier:h.multiplierBp/1e4})),f=g.some(h=>h.multiplier>1);return u.boost=f&&p?.expiresInDays?{active:f,multipliers:g,expiresInDays:p.expiresInDays}:{active:f,multipliers:g},u}var tS=1e4,nS=["appLinks","openGame","store","storeOfferSheet"],rS=["token","pause","menuSelect","settingChange","prefs","cohorts","viewport","willTerminate","localServer","roomEvent","seatedEvent","autoStartFailedEvent","ticketEvent","socketState","signalEvent","relayDraining","dedicatedEvent","clusterTarget","graphicsRoutes","partyResult","purchaseResult","purchaseSettled","inventoryChanged","shareResult","deviceSettings","adResult","momentResult","signInResult","friendChallengeResult","playInviteResult"],Ps=new WeakMap;function Bp(t,e){if(Ps.has(t))throw new Error("admitBuildEmbedders: already admitted");Ps.set(t,Object.freeze([...e]));}var ir=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??me,this.inbound=new yn(this.clock),this.outbound=new yn(this.clock);}options;state="waiting";port=null;version=null;peerCapabilities=[];unbidden=false;engagedSent=false;readyPending=false;readySent=false;settleWaiters=[];clock;inbound;outbound;expectedSource;get currentState(){return this.state}get parentCapabilities(){return this.peerCapabilities}parentSupports(e){return this.peerCapabilities.includes(e)}get protocolVersion(){return this.version}get unbiddenLaunch(){return this.unbidden}handleWindowMessage(e){if(e.source!==this.expectedSource)return this.refuse(e,"handshake did not come from the expected embedder window"),false;if(!(this.options.allowedEmbedders.some(a=>Lt(a,e.origin))||Tr(e.origin,this.options.selfOrigin)||(Ps.get(this)??[]).some(a=>Lt(a,e.origin))))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=Ir["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let o=e.data;if(!Lt(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 s=Rd(xr,o.versions);return s===null?(i.onmessage=null,i.postMessage({gem:B,type:"gem.error",code:"version_mismatch",message:`frame supports v${xr.min}..v${xr.max}`}),i.close(),this.transition("refused"),this.options.onError?.("version_mismatch"),false):(this.port=i,this.version=s,i.onmessage=a=>this.receive(a.data,a.ports??[]),i.start?.(),this.peerCapabilities=o.capabilities??[],this.unbidden=o.unbidden===true,i.postMessage({gem:B,type:"gem.handshake.accept",v:s,...this.options.capabilities===void 0?{}:{capabilities:[...this.options.capabilities]}}),this.transition("connected"),this.readyPending&&(this.readyPending=false,this.ready()),true)}ready(){if(this.state!=="connected"||!this.port){this.readyPending=true;return}if(this.readySent){this.options.onDropped?.("internal","gem.ready was already sent; duplicate suppressed");return}this.readySent=true,this.send({gem:B,type:"gem.ready"});}settled(e=tS){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:B,type:"gem.progress",loaded:e,total:n});}requestToken(e,n){this.send({gem:B,type:"gem.requestToken",requestId:e,reason:n});}requestLocalServer(e,n){return this.parentSupports("localHost")?(this.send({gem:B,type:"gem.requestLocalServer",requestId:e,gameRoomId:n}),true):false}exit(e){this.send(e===void 0?{gem:B,type:"gem.exit"}:{gem:B,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:B,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:B,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.gated("audioState")?(this.send({gem:B,type:"gem.audioState",muted:e}),true):false}reportEngaged(){return this.engagedSent||!this.gated("engagement")||!this.send({gem:B,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(!this.gated("rewardCue"))return false;let n={gem:B,type:"gem.rewardCue",currencySlug:String(e.currencySlug).slice(0,32)};return Ki(e.cueId)&&(n.cueId=e.cueId),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:qp(e.origin.x),y:qp(e.origin.y)}),this.send(n),true}showPortraitBorders(e){let n=Jo(e);return n===void 0||!this.gated("portraitBorders")?false:this.send(n===null?{gem:B,type:"gem.portraitBorders"}:{gem:B,type:"gem.portraitBorders",name:n})}setWalletVisible(e,n){return this.gated("walletDisplay")?this.send({gem:B,type:"gem.walletDisplay",...Es(e,n?.only)}):false}setMenu(e){return this.gated("gameMenu")?this.send({gem:B,type:"gem.menu",...zo(e)}):false}declareSettings(e){return this.gated("gameSettings")?this.send({gem:B,type:"gem.settingsDeclare",settings:e}):false}setGemCorner(e){return this.gated("gemCorner")?this.send({gem:B,type:"gem.gemCorner",corner:e}):false}setRewardPresentation(e){return this.gated("rewardPresentation")?this.send({gem:B,type:"gem.rewardPresentation",mode:e}):false}setMenuStyle(e){return this.gated("menuStyle")?this.send(e===null?{gem:B,type:"gem.menuStyle"}:{gem:B,type:"gem.menuStyle",ground:e.ground,accent:e.accent}):false}requestShare(e,n){return this.gated("share")?this.send({gem:B,type:"gem.requestShare",...n===void 0?{}:{requestId:n},params:e.map(({key:r,value:o})=>({key:r,value:o}))}):false}requestAvatarPicker(e){return this.gated("avatarPicker")?this.send({gem:B,type:"gem.requestAvatarPicker",...e==="2d"||e==="3d"?{tab:e}:{}}):false}requestVibrate(e){return this.gated("vibration")?this.send({gem:B,type:"gem.vibrate",pattern:[...e]}):false}reportFrameStats(e){return this.gated("frameStats")?(this.send({gem:B,type:"gem.frameStats",fps:Np(e.fps,1e3),frameTimeP95Ms:Np(e.frameTimeP95Ms,1e5),counts:e.counts==="gameDraws"?"gameDraws":"pageFrames"}),true):false}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:B,type:"gem.gameContext",context:e}),true)}signal(e,n,r){this.send({gem:B,type:"gem.signal",signal:e,matchId:n,data:r});}dedicatedOffer(e,n,r){this.send({gem:B,type:"gem.dedicatedOffer",matchId:e,sdp:n,intent:r});}requestParty(e){return this.send({gem:B,type:"gem.partyRequest",requestId:e})}requestPurchase(e,n,r,o,i,s,a){return this.send({gem:B,type:"gem.requestPurchase",requestId:e,purchaseKind:n,targetId:r,currencySlug:o,...i===void 0?{}:{quantity:i},...s===void 0?{}:{catalogId:s},...a===void 0?{}:{origin:a}})}requestAvatar3dPurchase(e,n,r){return this.parentSupports("avatar3dPurchases")?this.send({gem:B,type:"gem.requestAvatar3dPurchase",requestId:e,itemId:n,currencySlug:r}):false}putDeviceSettings(e,n){return this.send({gem:B,type:"gem.deviceSettings.put",requestId:e,settings:n})}requestAd(e,n,r){return this.send({gem:B,type:"gem.requestAd",requestId:e,placement:n,format:r})}signalMoment(e,n,r,o){return this.send({gem:B,type:"gem.signalMoment",requestId:e,kind:n,...r===void 0?{}:{placement:r},...o===true?{wall:true}:{}})}readyCalled(){return this.readySent||this.readyPending}requestSignIn(e){return this.send({gem:B,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,n,r,o){return this.send({gem:B,type:"gem.requestFriendChallenge",requestId:e,playerId:n,template:r,...o===void 0?{}:{params:o}})}requestArcade(e){return this.gated(Er(e.type))&&this.send({gem:B,...e})}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(Pr)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(Pr)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(Pr)&&this.options.onRefused?.(n);}fail(e,n){this.options.onError?.(e,n),this.state==="connected"&&this.port&&this.send({gem:B,type:"gem.error",code:e,...n===void 0?{}:{message:n}});}gated(e){return this.state==="connected"&&this.parentSupports(e)}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=Ir[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||jp(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=Ir[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=Er(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 s=o(e);if(s)return this.fail("invalid_message",`${r}: ${s}`),false;let a=e;if(a.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.devtools":this.options.onDevtools?.(a.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:a.maxWidth,maxHeight:a.maxHeight};if(!this.options.onScreenshot){l.close(),this.screenshotDenied("not_wired",false);break}return jp(n.slice(1)),this.options.onScreenshot(d,l,(c,u)=>this.screenshotDenied(c,u)),true}case "gem.token.denied":this.options.onTokenDenied?.(a);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(a);break;case "gem.player":{let l=a;this.options.onPlayer?.(eS(l),l.signInAvailable);break}case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(a);break;case "gem.error":this.options.onError?.(a.code,a.message);break;default:if(rS.includes(r.slice(4))){this.options[`on${r[4].toUpperCase()}${r.slice(5)}`]?.(a);break}if(nS.includes(Er(r))){this.options.onArcadeAnswer?.(a);break}this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,n){this.send({gem:B,type:"gem.screenshot.denied",reason:e,retryable:n});}};function jp(t){for(let e of t)try{e?.close?.();}catch{}}var Up="https://api.gemarcade.com";function Is(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 oS=new Set(["localhost","127.0.0.1","[::1]"]);function Wp(t){let e=Is(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!oS.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 Kp="/gem-embedders.json",Xo=4096,Hp=16,Vp=5e3,ar=Object.freeze({origins:Object.freeze([])});function st(t){return {origins:[],refused:`[gem] ${Kp} was ignored: ${t}`}}function iS(t){if(t.trim()==="")return ar;let e;try{e=JSON.parse(t);}catch{return st("it is not JSON.")}if(e===null||typeof e!="object"||Array.isArray(e))return st('it must be an object, { "embedders": [...] }.');let n=e.embedders;if(n===void 0)return ar;if(!Array.isArray(n))return st('"embedders" must be an array of origins.');if(n.length>Hp)return st(`"embedders" has more than ${Hp} entries.`);let r=n.filter(o=>typeof o!="string"||!Gt(o)||!o.toLowerCase().startsWith("https://")||tt(new URL(o).hostname));if(r.length>0){let o=r.slice(0,3).map(i=>typeof i=="string"?JSON.stringify(i.slice(0,100)):String(i)).join(", ");return st(`${r.length===1?"an entry is":"entries are"} not an https origin off this machine (${o}${r.length>3?", \u2026":""}).`)}return {origins:Object.freeze([...new Set(n)])}}async function Jp(t){let e=typeof AbortController=="function"?new AbortController:null,n,r=new Promise(i=>{n=t.clock.setTimeout(()=>{e?.abort(),i(st(`it took more than ${Vp} ms to read.`));},Vp);}),o=(async()=>{let i=await t.fetch(t.selfOrigin+Kp,{credentials:"omit",redirect:"error",...e?{signal:e.signal}:{}});if(!i.ok||(i.headers.get("content-type")??"").toLowerCase().includes("text/html"))return ar;if(Number(i.headers.get("content-length"))>Xo)return st(`it is larger than ${Xo} bytes.`);let a=await i.text();return a.length>Xo?st(`it is larger than ${Xo} bytes.`):iS(a)})().catch(()=>ar);try{return await Promise.race([o,r])}finally{t.clock.clearTimeout(n);}}function zp(t){if(typeof t!="string"||!Gt(t))return null;let e=t.slice(0,t.indexOf(":")).toLowerCase();return e==="https"||e==="http"?t:null}function Xp(t){return Object.freeze(t.map(([e,n])=>Object.freeze({node:e,parent:n})))}function aS(){let t=[["root",null],["hips","root"],["spine","hips"],["chest","spine"],["upper_chest","chest"],["neck","upper_chest"],["head","neck"],["head_socket","head"]];for(let e of ["l","r"]){let n=r=>`${r}_${e}`;t.push([n("shoulder"),"upper_chest"],[n("upper_arm"),n("shoulder")],[n("lower_arm"),n("upper_arm")],[n("hand"),n("lower_arm")],[n("hand_socket"),n("hand")]);for(let r of ["thumb","index","middle","ring","little"])for(let o=1;o<=3;o++)t.push([n(`${r}_${o}`),n(o===1?"hand":`${r}_${o-1}`)]);}for(let e of ["l","r"]){let n=r=>`${r}_${e}`;t.push([n("upper_leg"),"hips"],[n("lower_leg"),n("upper_leg")],[n("foot"),n("lower_leg")],[n("toes"),n("foot")]);}return t}var sS=Object.freeze({small_human:Xp([["root",null],["body","root"],["head","body"],["arm_l","body"],["arm_r","body"],["hand_socket","arm_r"],["leg_l","body"],["leg_r","body"]]),adult_human:Xp(aS())});var dS=Object.freeze(["https://gemarcade.com","https://developer.gemarcade.com","http://gemarcade.localhost","gemarcade://localhost","https://app.gemarcade.com"]),cS=Up,uS=["top-left","top-right","bottom-left","bottom-right"],mS=["arcade","game"];function Yp(t){let e=[1,3,5].map(n=>{let r=parseInt(t.slice(n,n+2),16)/255;return r<=.03928?r/12.92:((r+.055)/1.055)**2.4});return .2126*e[0]+.7152*e[1]+.0722*e[2]}function pS(t){if(t===null)return null;let{ground:e,accent:n}=Object(t);for(let[s,a]of [["ground",e],["accent",n]]){if(typeof a=="string"&&/^#[0-9a-fA-F]{6}$/.test(a))continue;let l=typeof a=="string"?JSON.stringify(a.slice(0,48)):`a value of type ${typeof a}`;console.warn(`[gem] setMenuStyle: ${s} is ${l}, which is not #rrggbb, so nothing was sent.`);return}let r={ground:e.toLowerCase(),accent:n.toLowerCase()},o=[Yp(r.ground),Yp(r.accent)],i=(Math.max(...o)+.05)/(Math.min(...o)+.05);if(i>=3)return r;console.warn(`[gem] setMenuStyle: accent ${r.accent} reaches ${Math.floor(i*100)/100}:1 against ground ${r.ground}, under the 3:1 it needs, so nothing was sent.`);}var Qp=8e3,Yo=15e3,gS=9e4,fS=1/0,yS=8e3,hS=5e3,bS=5e3;async function vS(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 sr(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 s=()=>{let d=r.indexOf(a);d>=0&&r.splice(d,1);},a=d=>{t.clearTimeout(l),s(),i(d);},l=t.setTimeout(()=>{s(),i(e);},o);r.push(a);})}}}function _S(t){return typeof t=="number"&&Number.isInteger(t)&&t>=100&&t<=200?t:null}function wM(t={}){let e=t.clock??me,n=t.log===void 0?m=>console.info(m):t.log,r=t.baseUrl??void 0;if(r!=null){let m=Is(r);if(m!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${m}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let o=typeof window>"u"?void 0:window.location?.search,i=yc(o),s=Jc(o),a=Bu(o),l=Ha();l.mark("sdk created");let d=()=>po(le.gameVersion,t.clientVersion?.gameVersion),c=new Tn({client:()=>Mt,clock:e,gameId:()=>le.identity?.gameId??null,playerId:()=>le.identity?.playerId??null,awaitPlayerId:async()=>(await _r(Yo)).playerId,declarations:async()=>(await an.load())?.analytics_events,environment:()=>{let m=d();return {sdk_version:Qs(),...m===null?{}:{game_version:m}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),u=$u(()=>{l.mark("engaged"),c.release(),F.reportEngaged();},typeof window>"u"?{}:window),p=m=>{if(m===false)return null;let P=m?.attempts??fS,L=m?.budgetMs??gS;return !(P>0)||!(L>0)?null:{attempts:P,budgetMs:L,maxDelayMs:m?.maxDelayMs??yS}},g=m=>{m.on("created",()=>{l.mark("room created");}),m.on("joined",()=>{l.mark("room joined");}),m.on("matchAllocationStarted",()=>{l.mark("allocation started");}),m.on("matchReady",()=>{l.mark("match ready");}),m.on("matchFailed",()=>{l.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 or;let f=t.allowedEmbedders;if(f!=null&&!Array.isArray(f))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 h=Array.from(f??[]),R=h.filter(m=>typeof m!="string"||!Gt(m));if(R.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${R.length===1?"an entry":"entries"} that ${R.length===1?"is":"are"} not an origin: ${R.map(m=>typeof m=="string"?JSON.stringify(m):String(m)).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 b=Object.freeze([...new Set([...dS,...h])]),w=sr(e),y=new Set,v=sr(e),E=false,T=sr(e),$=Pc(n),q={},U=sr(e),C=t.manageAudio===false?null:nm();t.selectableText!==true&&rm(),t.onScreenshot===void 0&&Hu(window);let O=null,N=null,H=null,x=null,D=false,re=()=>{O===null||O===N||F.reportMuted(O)&&(N=O);},ge,Z,lt=-1/0,Ae=null,Te=()=>{if(ge===void 0||Ae!==null||ge===Z)return;let m=lt+1e3-e.now();if(m>0){Ae=e.setTimeout(()=>{Ae=null,Te();},m);return}F.showPortraitBorders(ge)&&(Z=ge,lt=e.now());},Ce=null,te=null,Y=()=>{if(Ce===null)return false;let m=JSON.stringify(Es(Ce.visible,Ce.only));return m===te?F.parentSupports("walletDisplay"):F.setWalletVisible(Ce.visible,Ce)?(te=m,true):false},ne=null,De=null,Xe=()=>{if(ne===null)return false;let m=JSON.stringify(zo(ne.items));return m===De?F.parentSupports("gameMenu"):F.setMenu(ne.items)?(De=m,true):false},Fe=null,nn=null,Ye=null,Et=null,Qe,rn=null,dt=Pp({frame:()=>F,clock:e,log:t.log}),_=xc(()=>F),G=()=>Fe===null?false:Fe===nn?F.parentSupports("gemCorner"):F.setGemCorner(Fe)?(nn=Fe,true):false,W=()=>Ye===null?false:Ye===Et?F.parentSupports("rewardPresentation"):F.setRewardPresentation(Ye)?(Et=Ye,true):false,ee=()=>{if(Qe===void 0)return false;let m=JSON.stringify(Qe);return m===rn?F.parentSupports("menuStyle"):F.setMenuStyle(Qe)?(rn=m,true):false},ve=om({report:m=>F.reportFrameStats(m)}),ct=false,Ue=um(()=>Xs,()=>ct),It=m=>{let P=ct&&!m,L=ct!==m;if(ct=m,P&&Ue.close(),!!L)try{t.onDevToolsPermissionChange?.(m);}catch(X){n?.(`[gem] onDevToolsPermissionChange threw: ${X instanceof Error?X.message:String(X)}`),queueMicrotask(()=>{throw X});}},lr=r??cS,ng=r!==void 0,Qo,Zo=m=>(n?.(`[gem] token refused: ${m}`),t.onError?.("internal",m),false),rg=(m,P)=>{if(m===void 0)return P!==void 0?Zo("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 L=Wp(m);return L!==null?Zo(`the embedder named an API root that cannot be used: ${L}. Its value is withheld here rather than written to logs.`):Qo!==void 0&&Qo!==m?Zo("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."):(Qo=m,ng||(lr=m),true)},Tt=window.location?.origin,ei=null,Cs=-1/0,og=2e3,dr=new Set,ig=m=>ei!==false?Promise.resolve(true):new Promise(P=>{let L=e.setTimeout(()=>{dr.delete(X),P(false);},m),X=()=>{e.clearTimeout(L),dr.delete(X),P(true);};dr.add(X);}),ti=()=>{},ni=null,cr=()=>{},ri=false,ur=rp(e),oi=tp(e),Ms=Uu({bridge:{settled:m=>F.settled(m),parentSupports:m=>F.parentSupports(m)},clock:e,forced:a,log:n}),mr=ep({bridge:{parentSupports:m=>F.parentSupports(m),requestSignIn:m=>F.requestSignIn(m)},clock:e,onDropped:m=>t.onError?.("internal",m),log:n}),F=new ir({allowedEmbedders:b,...typeof Tt=="string"&&Tt!==""?{selfOrigin:Tt}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","ticketEvents","clusterTarget","graphicsRoutes","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","rewardPresentation","portraitBorders","earnAllowance","inventoryChanged","share","shareResult","shareRemap","avatarPicker","vibration","frameStats","walletDisplay","gameMenu","gemCorner","menuStyle","gameSettings","engagement","reservedAreas","p2pRelayDrain","viewport","purchases","purchaseSettled","avatar3dPurchases","deviceSettings","ads","moments","signIn","friendChallenges","appLinks","openGame","store","storeOfferSheet","playInvites",...t.onFeedbackContext!==void 0?["feedbackContext"]:[],...t.onAudioChannels!==void 0?["audioChannels"]:[],...t.onTextScale!==void 0?["textScale"]:[]],onRefused:m=>{ni=m,t.onRefused?.(m);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:m=>{le.onBridgeState(m),mr.noteState(),ri=false,m!=="connected"&&ur.abandon(),m!=="connected"&&oi.abandon(),m!=="connected"&&ve.setRequested(false),N=null,te=null,De=null,nn=null,Et=null,rn=null,dt.forgetSent(),_.forgetSent(),Z=void 0,m==="refused"&&(console.error("[gem] this game refused the page that framed it"+(ni===null?"":` (${ni})`)+", 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."),ti()),m==="connected"&&(l.mark("bridge connected"),ag(),re(),Te(),Y(),Xe(),G(),W(),ee(),dt.flush(),_.flush(),F.unbiddenLaunch&&!u.engaged&&c.hold(),c.startSession(),u.engaged&&F.reportEngaged()),t.onStateChange?.(m);},onPlayer:(m,P)=>{let L={...m,isGuest:P===true};w.set(L),mr.notePlayer(P),ri=P===true;for(let X of [...y])X(L);t.onPlayer?.(L);},onPrefs:m=>{let P={reducedMotion:m.reducedMotion,muted:m.muted,locale:m.locale,showFrameStats:m.showFrameStats===true,music:m.music!==false,sounds:m.sounds!==false,recommended:m.recommended===void 0?null:Object.freeze({volume:m.recommended.volume,batterySaver:m.recommended.batterySaver,keyboardLayout:m.recommended.keyboardLayout,gamepadConfirm:m.recommended.gamepadConfirm,vibration:m.recommended.vibration,lookSensitivity:m.recommended.lookSensitivity??100,gamepadLookSensitivity:m.recommended.gamepadLookSensitivity??100,invertLookY:m.recommended.invertLookY??false,touchMovement:m.recommended.touchMovement==="fixed"?"fixed":"floating",graphicsQuality:Ep(m.recommended.graphicsQuality,m.recommended.batterySaver),graphicsQualityAuto:m.recommended.graphicsQualityAuto??true,colorHelp:typeof m.recommended.colorHelp=="boolean"?m.recommended.colorHelp:null,textScale:_S(m.recommended.textScale)})};v.set(P),N=P.muted,C?.setMuted(P.muted),ve.setRequested(P.showFrameStats&&F.parentSupports("frameStats")),t.onPrefs?.(P),t.onAudioChannels!==void 0&&(H===null||H.music!==P.music||H.sounds!==P.sounds)&&(H=Object.freeze({music:P.music,sounds:P.sounds}),t.onAudioChannels(H));let L=P.recommended?.textScale??null;t.onTextScale!==void 0&&(!D||L!==x)&&(D=true,x=L,t.onTextScale(L));},onCohorts:m=>{let P=Object.freeze(m.cohorts.map(L=>Object.freeze({experimentId:L.experimentId,variantKey:L.variantKey})));T.set(P),t.onCohorts?.(P);},onEarnAllowanceChanged:()=>$.emit(),onInventoryChanged:()=>q.drop?.(),onViewport:m=>{let P=Object.freeze({insets:Object.freeze({top:m.insets.top,right:m.insets.right,bottom:m.insets.bottom,left:m.insets.left}),reserved:Object.freeze((m.reserved??[]).map(({x:X,y:ln,width:dn,height:cn,control:We})=>Object.freeze(We?{x:X,y:ln,width:dn,height:cn,control:Object.freeze({x:We.x,y:We.y,width:We.width,height:We.height})}:{x:X,y:ln,width:dn,height:cn})))});U.set(P);let L=am();sm(L,P.insets),dm(L,P.reserved,lm()),t.onViewport?.(P);},onPause:m=>{m.paused||cr(),E=m.paused,C?.setPaused?.(m.paused),c.setPaused(m.paused),ve.setPaused(m.paused),t.onPause?.(m.paused);},onSettingChange:m=>dt.onSettingChange(m),onMenuSelect:m=>{ne===null||m.entry!=="item"||!(zo(ne.items).items??[]).some(L=>L.id===m.id)||ne.items?.find(L=>L.id===m.id)?.onSelect?.();},onWillTerminate:m=>{c.endSession(m.reason),t.onWillTerminate?.({reason:m.reason,graceMs:m.graceMs});},onToken:m=>{let P=m.garden;if(It(m.allowDevTools===true),!rg(m.apiBaseUrl,P))return;let L=m;le.onToken(L);let X=le.identity;X&&(ii.set(X),Gs||(Gs=true,ye.reconcileSeats().catch(()=>{}))),Ls.push({token:L.token,expiresAt:L.expiresAt});},onTokenDenied:m=>{It(false),le.onDenied(m);},onScreenshot:(m,P,L)=>{Qu(m,P,L,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{Zu(F,t.onFeedbackContext);},onDevtools:m=>{m==="close"?Ue.close():m==="open"?Ue.openFrom("platform").catch(()=>{}):Ue.isOpen?Ue.close():Ue.openFrom("platform").catch(()=>{});},onRoomEvent:m=>ye.handleRoomEvent({event:m.event,roomId:m.roomId,...m.matchId===void 0?{}:{matchId:m.matchId},...m.version===void 0?{}:{version:m.version},...m.reason===void 0?{}:{reason:m.reason},...m.platform===void 0?{}:{platform:m.platform}}),onSeatedEvent:m=>ye.handleSeated(m.roomId),onAutoStartFailedEvent:m=>ye.handleAutoStartFailed(m.roomId,m.code),onTicketEvent:m=>ye.handleTicketEvent({event:m.event,ticketId:m.ticketId,...m.partySize===void 0?{}:{partySize:m.partySize},...m.queuedAt===void 0?{}:{queuedAt:m.queuedAt},...m.expiresAt===void 0?{}:{expiresAt:m.expiresAt},...m.reason===void 0?{}:{reason:m.reason},...m.roomId===void 0?{}:{roomId:m.roomId}}),onSocketState:m=>{let P=ei;if(ei=m.connected,m.connected)for(let X of [...dr])X();if(!m.connected||P===true)return;let L=e.now();L-Cs<og||(Cs=L,ye.reconcile().catch(()=>{}));},onSignalEvent:m=>{let P=typeof m.data=="object"&&m.data!==null&&!Array.isArray(m.data)?m.data:{};pt.handleSignalEvent(m.matchId,m.event,P),m.event==="matchEnded"&&ye.reconcile({matchId:m.matchId,...typeof P.reason=="string"?{reason:P.reason}:{}}).catch(()=>{});},onRelayDraining:m=>{pt.handleSignalEvent(m.matchId,"relayDraining",{clusterTargetId:m.clusterTargetId,relayIps:m.relayIps,drainingSince:m.drainingSince,deadline:m.deadline});},onDedicatedEvent:m=>{m.event==="matchEnded"&&(sn.handleMatchEnded(m.matchId,m.reason),ye.reconcile({matchId:m.matchId,...m.reason===void 0?{}:{reason:m.reason}}).catch(()=>{})),Os.handleEvent(m);},onClusterTarget:m=>fr.accept(m.clusterTargetId,m.clusterTargetIds),onGraphicsRoutes:m=>Ms.accept(m.entries),onLocalServer:m=>yr.accept(m),onLocalServerDenied:m=>yr.refuse(m),onPartyResult:m=>Fs.settle(m.requestId,m.partyId),onPurchaseResult:m=>on.settle(m),onPurchaseSettled:m=>on.settled(m),onShareResult:m=>oi.settle(m),onDeviceSettings:m=>{gr.receive(m),t.onDeviceSettings?.(gr.api.current);},onDeviceSettingsResult:m=>gr.settle(m),onAdResult:m=>qs.settle(m),onMomentResult:m=>Ns.settle(m),onSignInResult:m=>{m.outcome==="signed_in"&&cr(),mr.settle(m);},onFriendChallengeResult:m=>Bs.settle(m),onArcadeAnswer:m=>{m.type==="gem.storePurchaseSettled"?si.settled(m):lg(m);},onPlayInviteResult:m=>Us.settle(m)}),Os=new Qn({bridge:F}),ii=sr(e);ti=()=>{ii.release(),w.release(),T.release();},F.currentState==="refused"&&ti();let Gs=false,ai=new Set,pr,Ls={current:()=>pr,subscribe:m=>(ai.add(m),pr!==void 0&&m(pr),()=>ai.delete(m)),push:m=>{pr=m;for(let P of [...ai])try{P(m);}catch(L){n?.(`[gem] a server-token listener threw: ${L instanceof Error?L.message:String(L)}`);}}},le=pm({bridge:F,clock:e,onStateChange:(m,P)=>{if(m==="ready"){if(l.mark("token ready")){let L=l.marks.find(X=>X.name==="token ready")?.at;c.trackPlatform("gem_boot_ready",L===void 0?{}:{boot_ms:Math.max(0,Math.round(L))});}}else m==="lost"&&(l.mark("token lost"),c.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(m,P);}}),Ds=()=>{let m=le.identity;return !m||le.source.currentState==="lost"?null:`${m.playerId}\0${m.gameId}\0${m.channel}`},ag=()=>{l.mark("token requested"),le.source.get().catch(()=>{});},Fs=Vm({bridge:F,clock:e}),Ct={},on=Km({bridge:F,clock:e,onDropped:m=>t.onError?.("internal",m),confirm:async m=>Ct.confirm?.(m)??"unknown",confirmAvatar3d:async m=>Ct.confirmAvatar3d?.(m)??"unknown",onInventoryStale:()=>Ct.inventoryStale?.(),onListenerError:m=>t.onError?.("internal",`gem.purchases.onSettled listener threw: ${String(m)}`)}),gr=$p({bridge:F,clock:e,onDropped:m=>t.onError?.("internal",m)}),$s={},qs=Op({bridge:F,clock:e,onDropped:m=>t.onError?.("internal",m),readAvailability:(m,P)=>$s.read?.(m,P)??Promise.reject(new Error("the gem-api client is not built yet")),log:t.log}),Ns=Dp({bridge:F,clock:e,onDropped:m=>t.onError?.("internal",m)}),js={held:false},sg=op({bridge:F,asker:ur,acting:js}),si=lp({bridge:F,asker:ur,acting:js,onListenerError:m=>t.onError?.("internal",`gem.store.onSettled listener threw: ${String(m)}`),onPurchaseEnded:()=>cr(),readPass:async m=>(await mt.passes.get(m)).held,wait:m=>new Promise(P=>{e.setTimeout(P,m);})}),lg=m=>{ur.settle(m)||t.onError?.("internal",`${m.type} (${m.outcome}) for an unknown requestId: `+JSON.stringify(m.requestId));},Bs=wc({bridge:F,clock:e,onDropped:m=>t.onError?.("internal",m)}),Us=Ac({bridge:F,clock:e,onDropped:m=>t.onError?.("internal",m)}),fr=Lc({bridge:F,clock:e}),yr=cm({bridge:F,clock:e}),li=zp(Tt),Ws=window.fetch,hr=li!==null&&typeof Ws=="function"?"unread":"read",br=null,di=false,dg=m=>{if(hr==="read"||m.source!==window.parent)return false;let P=m.origin;return typeof P!="string"||b.some(L=>Lt(L,P))||Tr(P,typeof Tt=="string"?Tt:void 0)?false:((br===null||!di)&&(br=m),hr==="unread"&&li!==null&&(hr="reading",Jp({fetch:(L,X)=>Ws.call(window,L,X),selfOrigin:li,clock:e}).then(L=>{"refused"in L&&n?.(L.refused),L.origins.length>0&&Bp(F,L.origins),hr="read";let X=br;br=null,X!==null&&F.currentState==="waiting"&&vr(X);})),true)},vr=m=>{if(dg(m))return false;let P=F.handleWindowMessage({data:m.data,origin:m.origin,source:m.source,ports:m.ports});return P&&window.removeEventListener("message",vr),P};window.addEventListener("message",vr),di=true;let ut;try{ut=qu(window,vr);}finally{di=false;}let cg=ut?.capture,ci=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];ci?.domInteractive!==void 0&&ci.domInteractive>0&&l.mark("document parsed",ci.domInteractive),cg?.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 ui=t.handshakeWarningMs;ui!==null&&n&&e.setTimeout(()=>{let m=ut===null?"no capture script ran":`capture: ${ut.delivered} offer(s) delivered, ${ut.stale} stale, ${ut.capture.dropped} evicted${ut.capture.late?", installed late":""}`;if(F.currentState==="connected"){n(`[gem] handshake connected. boot: ${l.timeline()} \xB7 ${m}`);return}n(`[gem] no completed handshake after ${ui??Qp}ms (bridge state: ${F.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: ${l.timeline()} \xB7 `+m);},ui??Qp);let ug=qr({get baseUrl(){return lr},tokenSource:le.source,get defaultQuery(){let m=le.identity;return m?{game_id:m.gameId,channel:m.channel}:{}}}),Mt=new Ze({transport:ug,clock:e}),_e={client:Mt,gameId:()=>le.identity?.gameId??""};Ct.confirm=m=>Jm(_e,m),Ct.confirmAvatar3d=m=>Qm(_e,m),$s.read=(m,P)=>md(_e,"players","me",m,{signal:P});let mg=()=>le.identity?.channel??"release",an=new Yr(_e,mg),pg=Ym({player:()=>w.current,subscribe:m=>(y.add(m),()=>{y.delete(m);}),configFamilies:async()=>(await an.load())?.avatar_3d_families,readOffers:()=>Zm(_e),purchase:m=>on.requestAvatar3d(m),log:t.log}),Hs=async m=>(await an.load())?.currency(m)?.id??void 0,Vs=Bd(_e,Ti,{identity:Ds,resolveCurrencyId:Hs,watch:{clock:e,log:t.log},handOffRefusedPurchase:m=>on.handOffRefused(m),isGuest:()=>ri}),mt=Vs.scope;Ct.inventoryStale=()=>mt.inventory.refresh(),cr=Vs.recheckPasses;let Ks=new Pn(_e,$,n);an.bindPreview({boost:()=>(w.current?.boost.multipliers??[]).map(m=>({currencyId:m.currencyId,currencySlug:m.currencySlug,multiplierBp:Math.round(m.multiplier*1e4)})),holdings:async m=>{let P=mt.passes.list().then(he=>new Map(he.map(Ys=>[Ys.pass,Ys.held])),()=>null);if(!m)return {items:null,currencies:null,progressions:null,passes:await P};let L=await mt.inventory.snapshot().catch(()=>null),X=he=>he===void 0||he.nextCursor!==void 0?null:he.data,ln=X(L?.items),dn=X(L?.currencies),cn=X(L?.progressions),We=new Map;for(let he of ln??[])We.set(he.itemDefinitionId,(We.get(he.itemDefinitionId)??0)+he.quantity);return {items:ln===null?null:We,currencies:dn===null?null:new Map(dn.map(he=>[he.currencyId,he.total])),progressions:cn===null?null:new Map(cn.map(he=>[he.progressionDefinitionId,{value:he.currentValue,completed:he.isCompleted}])),passes:await P}},offers:async()=>{let m=await si.api.offers();return m.outcome==="ok"?m.offers:[]}});let _r=async m=>{let P=await ii.wait(m);if(P)return P;throw F.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).")},mi=p(t.autoReconnect),ye=mu(s===void 0?{}:{playWithTicket:s},{client:Mt,clock:e,gameId:()=>le.identity?.gameId??null,playerId:()=>le.identity?.playerId??null,awaitGameId:async()=>(await _r(Yo)).gameId,resolveParty:Fs.resolve,resolveClusterTargets:fr.resolveList,refreshClusterTargets:fr.refresh,ensureLocalServer:yr.ensure,localHostAvailable:yr.available,...t.clientVersion===void 0?{}:{clientVersion:t.clientVersion},platformGameVersion:()=>le.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},...mi===null?{}:{autoReconnect:{...mi,redial:(m,P)=>pi.redialMatch(m,P),abandon:(m,P)=>pi.abandonMatch(m,P)}}});g(ye),Gu({analytics:c,rooms:ye}),Du({analytics:c});let pt=Ou({client:Mt,clock:e,rooms:ye,bridge:F,gameId:()=>le.identity?.gameId??"",baseUrl:()=>lr,resolveClusterTargets:fr.resolveList,boot:l,...t.log===void 0?{}:{log:t.log}}),Js=Wa(l,n),sn=Tm({client:Mt,clock:e,rooms:ye,signaling:()=>Os.channel(),signalingReady:ig,log:n??(()=>{})}),pi=Wm({rooms:ye,p2p:{connect:m=>Js(pt.connect(m)),session:m=>pt.session(m)},dedicated:{connect:(m=>Co(l,"welcome",sn.connect(m),n))},clock:e,identity:()=>le.identity,apiBaseUrl:()=>lr,tokens:Ls,room:()=>ye.currentRoom,autoReconnect:mi!==null,...t.log===void 0?{}:{log:t.log}}),gg=async()=>(await _r(Yo)).playerId,zs=new Hr(_e,void 0,Ds,Hs);q.drop=()=>{mt.inventory.refresh(),zs.refreshHeld();};let Xs={client:Mt,boot:l,get identity(){return le.identity},awaitIdentity:(m=Yo)=>_r(m),awaitBridge:m=>F.settled(m),get player(){return w.current},awaitPlayer:(m=hS)=>w.wait(m),me:mt,characters:zs,transfers:new Kr(_e,Ti,mt.inventory),gameConfig:an,purchases:on.api,deviceSettings:gr.api,graphics:Ms.api,moments:Ns.api,ads:qs.api,account:mr.api,share:np({frame:F,log:t.log,answers:oi}),arcade:sg,store:si.api,branding:fp({fetch:typeof window.fetch=="function"?(m,P)=>window.fetch.call(window,m,P):null,clock:e,devicePixelRatio:()=>window.devicePixelRatio??1,log:n}),vibration:yp({frame:F,log:t.log}),get avatarPickerAvailable(){return F.currentState==="connected"&&F.parentSupports("avatarPicker")},openAvatarPicker:m=>F.requestAvatarPicker(m?.tab),avatars3d:pg,settings:dt.api,controls:_p({recommended:()=>v.current?.recommended??null}),analytics:c,leaderboards:new Rn(_e),challenges:new _n(_e),showcase:new kn(_e,gg),friends:new An(_e,{challenge:Bs.challenge,inviteToPlay:Us.inviteToPlay,setInviteParams:_.set,...i===void 0?{}:{launchedChallengeId:i}}),platform:Ks,earnings:Qr({knownSlug:m=>w.current?.boost.multipliers.find(P=>P.currencyId===m)?.currencySlug,readSlugs:async()=>new Map((await Ks.currencies.get()).map(m=>[m.currencyId,m.slug]))}),profiles:new En(_e),functions:new rt((m,P)=>Ql(_e,m,P)),get prefs(){return v.current},get paused(){return E},get textScale(){return v.current?.recommended?.textScale??null},get cohorts(){return T.current},get viewport(){return U.current},awaitCohorts:(m=bS)=>T.wait(m),reportMuted:m=>{O=!!m,re();},showPortraitBorders:m=>{let P=Jo(m);P!==void 0&&(ge=P,Te());},cueReward:m=>(ao(m.cueId,"cueReward"),F.cueReward(m)),setWalletVisible:(m,P)=>{let L=Array.isArray(P?.only)?[...P.only]:void 0;return Ce=L===void 0?{visible:m===true}:{visible:m===true,only:L},Y()},setMenu:m=>(ne=Array.isArray(m?.items)?{items:m.items.map(P=>({...P}))}:{},Xe()),setGemCorner:m=>{if(!uS.includes(m)){let P=typeof m=="string"?JSON.stringify(m.slice(0,48)):`a value of type ${typeof m}`;return console.warn(`[gem] setGemCorner: ${P} is not a corner, so nothing was sent. Pass 'top-left', 'top-right', 'bottom-left' or 'bottom-right'.`),false}return Fe=m,G()},setRewardPresentation:m=>{if(!mS.includes(m)){let P=typeof m=="string"?JSON.stringify(m.slice(0,48)):`a value of type ${typeof m}`;return console.warn(`[gem] setRewardPresentation: ${P} is not a presentation, so nothing was sent. Pass 'game' or 'arcade'.`),false}return Ye=m,W()},setMenuStyle:m=>{let P=pS(m);return P===void 0?false:(Qe=P,ee())},reportFrame:()=>ve.draw(),exit:m=>vS(ye,F,m,c),frame:F,devtools:Ue,rooms:ye,dedicatedServer:{listClusterTargets:m=>sn.listClusterTargets(m),connect:(m=>Co(l,"welcome",sn.connect(m),n)),handleMatchEnded:(m,P)=>sn.handleMatchEnded(m,P)},p2p:{handleSignalEvent:(m,P,L)=>pt.handleSignalEvent(m,P,L),session:m=>pt.session(m),connect:m=>Js(pt.connect(m))},match:pi};return Xs}var Zp="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 Ts(t,e={}){let n=e.clock??me,r=()=>{let a=t();if(a===null)throw new Error(Zp);return a},o=null,i=()=>{if(o===null)throw new Error(Zp);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 earnings(){return i().earnings},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(a){let d=r().profile?.(a);if(!d)return null;let c=d.displayName;return typeof c!="string"||c===""?null:{displayName:we(c,"profile.displayName"),...typeof d.displayTag=="string"&&d.displayTag!==""?{displayTag:we(d.displayTag,"profile.displayTag")}:{},...typeof d.discriminator=="string"?{discriminator:d.discriminator}:{}}},playerNumber(a){return r().playerNumber?.(a)},send(a,l,d){d===void 0?r().send(a,l):r().send(a,l,d);},broadcast(a,l){l===void 0?r().broadcast(a):r().broadcast(a,l);},kick(a,l){l===void 0?r().kick(a):r().kick(a,l);},log(a){r().log(a);},warn(a){r().warn(a);}},attach:()=>{o=Zt(r(),{...e,clock:n});}}}function eg(t,e={}){let{server:n,attach:r}=Ts(()=>t,e);return r(),n}function wS(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:ot(e)}}}var SS=1e4;function RS(t){let e=false;return n=>{if(e)return;let r;try{r=t.match.reportPlayers([{playerId:n,state:"connected"}],AbortSignal.timeout(SS));}catch{return}r.catch(o=>{o instanceof M&&o.status>=400&&o.status<500&&(e=o.status!==429);});}}function tg(t,e={}){return ()=>{let n=null,{server:r,attach:o}=Ts(()=>n,e),i=t(r),s={async init(l){n=l,o(),await i.init?.();},async shutdown(l){let d=wS(l);try{await i.shutdown?.(d);}finally{r.dispose();}}},a=RS(r);return s.join=(l,d)=>(a(l),i.join?.(l,d)),i.leave&&(s.leave=(l,d)=>i.leave?.(l,d)),i.message&&(s.message=(l,d,c,u)=>i.message?.(l,d,c,u)),s}}
3
+ export{dS as ARCADE_EMBEDDERS,sS as AVATAR_RIGS,Tn as AnalyticsApi,oe as AuthError,wr as CONDITIONAL_HEADERS,_n as ChallengesApi,xs as DEVICE_SETTINGS_MAX_BYTES,A as DedicatedServerError,bt as FriendChallengeError,An as FriendsApi,rt as FunctionsApi,M as GemApiError,Ze as GemClient,fe as GemConfigError,ir as GemFrame,In as GemFunctionError,ae as GemSaveError,or as GemUnframedError,Rn as LeaderboardsApi,ic as MAX_PERIODS_BACK,Ty as PLATFORM_EVENTS,Pn as PlatformApi,oo as PlatformCurrenciesApi,io as PlatformEarnAllowanceApi,Se as PlayerText,Me as PreviewError,En as ProfilesApi,nt as PurchaseRefusal,Bo as ShareRefusal,kn as ShowcaseApi,ue as TransportRefusal,Gn as UNRELIABLE_CHANNEL_LABEL,we as asPlayerText,Ha as createBootTimeline,wM as createGem,Zt as createGemServer,Om as createHostTokenSource,eg as createMatchServer,tg as defineServer,lo as experimentSelection,vS as leaveAndExit,Oe as mapIdentity,Co as markOnResolve,Di as platformIconUrl,Mn as presentJoinCredential,Wt as readTemplateTransports,Ln as readTransportAdvert,Wa as reportOnResolve,me as systemClock,ft as text,Sr as toBase64,bo as webTransportAvailable};//# sourceMappingURL=gem-web-sdk.sdk.js.map
4
4
  //# sourceMappingURL=gem-web-sdk.sdk.js.map