@indiegems/gem-web-sdk 15.0.0 → 15.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- var xu=Object.defineProperty;var Au=(t,e)=>{for(var n in e)xu(t,n,{get:e[n],enumerable:true});};globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:15.0.0]";function ba(){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 Pu={initialDelayMs:2e3,maxDelayMs:6e4};function Tu(t,e){return e!==void 0?!e:t==="chain_exhausted"}var mt=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 re(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 re("chain_exhausted","the token chain reached its ceiling");if(this.inFlight===null&&this.options.clock.now()<this.notBefore)throw new re(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}=Pu,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 re("internal","token arrived for a superseded generation");return this.grant=i,this.rejected=false,this.enter("ready"),i.token}).catch(i=>{let o=Eu(i),{retryable:s,retryAfterMs:a}=i??{};throw n===this.generation&&(Tu(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 re?i:new re(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)}},re=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 Eu(t){if(t instanceof re)return t.reason;let e=t?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var se=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}},ii=["if-match","if-none-match"],va=4096;function Cu(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let i=n.toLowerCase();if(!ii.includes(i)||r===void 0)continue;let o=typeof r=="string"?Iu(r):r;if(typeof o!="string"||o.length>va||!Mu(o))throw new se(`the ${i} header value cannot be sent \u2014 it is not a string, is longer than ${va} 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 Iu(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 Mu(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 Ou(t){let{bytes:e}=t;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new se("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 se("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 _a(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let i={...r},o=Cu(i.headers),s=Ou(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 m=await e.tokenSource.get(),c=await t(a,m);if(c.status===401)throw e.tokenSource.close("unavailable"),new re("unavailable","the server refused a freshly minted token");return c}}}function oi(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(Gu(e))}function Mn(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 ai(t){return new TextDecoder().decode(Mn(t))}function Gu(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"}},ka=new WeakMap;function Sa(t){return ka.get(t)??{}}var Lu=new Set([408,429,500,502,503,504]),Du=6e4;function Fu(t){if(t===void 0)return 2;if(!Number.isInteger(t)||t<0||t>10)throw new se(`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,...Ft(i)},i.replaySafe===true,i.retryRateLimited!==false)}async post(e,n,r,i={}){return this.send({method:"POST",path:e,body:n,signal:r,...Ft(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,...Ft(i)},i.replaySafe===true,i.retryRateLimited!==false);return {bytes:$u(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,...Ft(i)},i.replaySafe===true,i.retryRateLimited!==false)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...Ft(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?Fu(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw wa(e.signal);for(let s=0;s<i;s++){if(s>0&&await this.backoff(s,o,e.signal),e.signal?.aborted)throw wa(e.signal);let a;try{a=await this.options.transport.request(e);}catch(d){if(re.isAuthError(d)||se.isRefusal(d)||e.signal?.aborted||qu(d))throw d;o=new O("unavailable",0,String(d));continue}if(a.status>=200&&a.status<300||a.status===304)return a;let l=Nu(a);if(!Lu.has(a.status)||a.status===429&&!r)throw l;o=l;}throw o??new O("unavailable",0,"no attempt was made")}backoff(e,n,r){if(r?.aborted)return Promise.resolve();let i=n?.retryAfterSeconds,o=i!==void 0?i*1e3:2**(e-1)*250,s=2**(e-1)*250,a=Math.min(Math.max(o,s),Du);return new Promise(l=>{let d=this.options.clock,m=false,c=false,p,g=()=>{m||(m=true,c&&d.clearTimeout(p),r?.removeEventListener("abort",g),l());};r?.addEventListener("abort",g,{once:true}),p=d.setTimeout(g,a),c=true,m&&d.clearTimeout(p);})}};function $u(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 Ft(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function wa(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function qu(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function Nu(t){let e=Uu(t),n=Wu(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&ka.set(e,r),e}var ju=new Map([["insufficient_funds","insufficient_funds"]]);function Uu(t){let{status:e,body:n}=t,r=Bu(n),i=t.retryAfterSeconds??Vu(n),o=Hu(n),s=o===void 0?void 0:ju.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 Bu(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 Wu(t){let n=t?.error?.details;return n===null?void 0:n}function Hu(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function Vu(t){let e=t?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function _(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 Ra(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function xa(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/add`;return t.client.post(s,i,o?.signal)}async function Aa(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Pa(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets/${_(e)}`;return t.client.delete(r,n?.signal)}async function Ta(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/claim`;return t.client.post(s,i,o?.signal)}async function Ea(t,e,n){return t.client.post("/v1/characters",e,n?.signal)}async function Ca(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/orders/batch`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Ia(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/orders`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Ma(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets`;return t.client.post(r,e,n?.signal)}async function Oa(t,e,n,r,i){let o=`/v1/settings/${_(e)}/${_(n)}/${_(r)}`;return t.client.delete(o,i?.signal)}async function Ga(t,e,n,r,i){let o=`/v1/saves/${_(e)}/${_(n)}/${_(r)}`;return t.client.delete(o,i?.signal)}async function La(t,e,n,r){let i=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.delete(i,r?.signal)}async function Da(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/recipes/execute`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Fa(t,e,n,r,i,o){let s=`/v1/saves/${_(e)}/${_(n)}/${_(r)}/finalize`;return t.client.post(s,i,o?.signal)}async function $a(t,e,n){let r=`/v1/games/${_(t.gameId())}/avatars-3d/${_(e)}/owned`;return t.client.get(r,n?.signal)}async function qa(t,e,n){let r=`/v1/games/${_(t.gameId())}/config/channels/${_(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Na(t,e,n){let r=`/v1/characters/${_(e)}`;return t.client.get(r,n?.signal)}async function ja(t,e,n){let r=`/v1/inventory/loot-tables/${_(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Ua(t,e,n,r,i){let o=`/v1/settings/${_(e)}/${_(n)}/${_(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function Ba(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/${_(e)}/${_(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Wa(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/items/${_(r)}`;return t.client.get(o,i?.signal)}async function Ha(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/${_(e)}/${_(n)}/${_(r)}`+(s?`?${s}`:"");return t.client.get(a,i?.signal)}async function Va(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/orders/${_(r)}`;return t.client.get(o,i?.signal)}async function Ka(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}`;return t.client.get(o,i?.signal)}async function Ja(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/catalogs/${_(r)}/recipes/${_(i)}/availability`;return t.client.get(s,o?.signal)}async function za(t,e,n,r){let i=new URLSearchParams;i.set("limit",String(r?.limit));let o=i.toString(),s=`/v1/inventory/${_(e)}/${_(n)}/recipe-usage`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function si(t,e,n,r,i){let o=`/v1/saves/${_(e)}/${_(n)}/${_(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function Ya(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/${_(e)}/friends`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function Xa(t,e,n){let r=`/v1/showcase/friends/${_(e)}`;return t.client.get(r,n?.signal)}async function Qa(t,e){let n=`/v1/games/${_(t.gameId())}/avatars-3d`;return t.client.get(n,e?.signal)}async function Za(t,e,n){let r=`/v1/inbox/friend-challenges/${_(e)}`;return t.client.get(r,n?.signal)}async function es(t,e,n){let r=new URLSearchParams;n?.bucket_1!==void 0&&r.set("bucket_1",String(n?.bucket_1)),n?.bucket_2!==void 0&&r.set("bucket_2",String(n?.bucket_2)),n?.periods_back!==void 0&&r.set("periods_back",String(n?.periods_back)),n?.period!==void 0&&r.set("period",String(n?.period)),n?.player_id!==void 0&&r.set("player_id",String(n?.player_id));let i=r.toString(),o=`/v1/leaderboards/${_(e)}`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function ts(t,e){let n=`/v1/games/${_(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function On(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function ns(t,e,n){let r=`/v1/profiles/players/${_(e)}`;return t.client.get(r,n?.signal)}async function rs(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 is(t,e,n){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${_(e)}`;return t.client.get(r,n?.signal)}async function os(t,e,n,r){let i=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.get(i,r?.signal)}async function as(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function ss(t,e,n){let r=`/v1/inventory/transfers/${_(e)}`;return t.client.get(r,n?.signal)}async function ls(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets/${_(e)}/heartbeat`;return t.client.post(r,void 0,n?.signal)}async function ds(t,e,n){let r=`/v1/games/${_(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 cs(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function us(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/platform-funded-game-inventory-purchases`;return t.client.post(o,r,i?.signal)}async function ms(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function ps(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 gs(t,e){return t.client.get("/v1/characters",e?.signal)}async function ys(t,e,n,r){let i=`/v1/settings/${_(e)}/${_(n)}`;return t.client.get(i,r?.signal)}async function fs(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/${_(e)}/${_(n)}/orders`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function hs(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/${_(e)}/${_(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function bs(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 vs(t,e){let n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e?.limit)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor));let r=n.toString(),i="/v1/friends"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function _s(t,e){let n=new URLSearchParams;e.entity_type!==void 0&&n.set("entity_type",String(e.entity_type)),e.entity_id!==void 0&&n.set("entity_id",String(e.entity_id)),e?.direction!==void 0&&n.set("direction",String(e?.direction)),e?.status!==void 0&&n.set("status",String(e?.status)),e?.cursor!==void 0&&n.set("cursor",String(e?.cursor)),e?.limit!==void 0&&n.set("limit",String(e?.limit));let r=n.toString(),i="/v1/inventory/transfers"+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function ws(t,e,n){let r=`/v1/inbox/friend-challenges/${_(e)}/answered`;return t.client.post(r,void 0,n?.signal)}async function ks(t,e,n,r){let i=`/v1/games/${_(t.gameId())}/matches/${_(e)}/end`;return t.client.post(i,n,r?.signal)}async function Ss(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/max`;return t.client.post(s,i,o?.signal)}async function Rs(t,e,n,r,i,o){let s=`/v1/settings/${_(e)}/${_(n)}/${_(r)}`;return t.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function xs(t,e,n,r,i){let o=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.put(o,r,i?.signal)}async function As(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/rewarded-placements/${_(r)}/availability`;return t.client.get(o,i?.signal)}async function Ps(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function Ts(t,e,n,r){let i=`/v1/characters/${_(e)}`;return t.client.patch(i,n,r?.signal)}async function Es(t,e,n,r,i,o){let s=`/v1/saves/${_(e)}/${_(n)}/${_(r)}/upload-url`;return t.client.post(s,i,o?.signal,{replaySafe:true})}async function Cs(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/reset`;return t.client.post(s,i,o?.signal)}async function Is(t,e,n){let r=`/v1/characters/${_(e)}`;return t.client.delete(r,n?.signal)}var U="gem-web-bridge",Ln={min:1,max:1},pt=65536,Ms=8,Gn=5e3,Os=1024;var $t=Object.create(null),Dn="__malformed";var ci=Object.create(null),Ku=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"],["gem.moments.","moments"],["gem.prefs.","audioChannels"]]);function Gs(t){let e=ci[t];if(e!==void 0)return e;for(let[n,r]of Ku)if(t.startsWith(n))return r}function ui(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 Ju(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 zu(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function Yu(t){return /^[a-z_]+$/.test(t)}function li(t,e,n){if(e>Ms)return `nesting deeper than ${Ms}`;if(++n.nodes>Gn)return `more than ${Gn} values`;if(n.bytes>pt)return `over the ${pt} 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>Os)return `an array of ${t.length} entries, over the ${Os} limit`;n.bytes+=2;for(let a of t){let l=li(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>Gn)return `more than ${Gn} values`;if(n.bytes+=a.length*3+4,n.bytes>pt)return `over the ${pt} byte limit`;let l=li(s[a],e+1,n);if(l)return l}return null}function Xu(t){let e={nodes:0,bytes:0,seen:new Set},n=li(t,0,e);return n?`message contains ${n}`:e.bytes>pt?`message is over the ${pt} byte limit`:null}var Qu={origin:[ui,"not a well-formed origin"],url:[Ju,"not a safe absolute http(s) URL"],bcp47:[zu,"not a well-formed BCP 47 tag"],code:[Yu,"not a code of lower-case letters and underscores"]};function Ls(t,e,n){for(let r of e){let i=n===""?r.n:`${n}.${r.n}`,o=t[r.n];if(o==null){if(r.o)continue;return `${i}: required`}let s=di(o,r,i);if(s)return s}return null}function di(t,e,n){switch(e.k){case "u":return typeof t=="boolean"?null:di(t,{...e,k:typeof t=="string"?"s":"n"},n);case "s":{if(typeof t!="string")return `${n}: expected string`;if(t.length>e.max)return `${n}: exceeds ${e.max} characters`;if(e.f){let[r,i]=Qu[e.f];if(!r(t))return `${n}: ${i}`}return null}case "n":case "i":return typeof t!="number"||!(e.k=="i"?Number.isInteger:Number.isFinite)(t)?`${n}: expected ${e.k=="i"?"integer":"number"}`:t<e.lo||t>e.hi?`${n}: out of range ${e.lo}..${e.hi}`:null;case "b":return typeof t=="boolean"?null:`${n}: expected boolean`;case "e":{let r=e.v;return r.includes(t)?null:`${n}: not one of ${r.join("|")}`}case "o":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected object`:Ls(t,e.fs,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.max)return `${n}: exceeds ${e.max} items`;let r=e.it,i=`${n}[]`;for(let o of t){if(o==null){if(r.o)continue;return `${i}: required`}let s=di(o,r,i);if(s)return s}return null}default:{let r=e.k;return `${n}: unknown kind ${String(r)}`}}}var Ds=Object.create(null);function A(t,e,n,r){return $t[t]=n,r&&(ci[t]=r),Ds[t]=i=>{let o=Xu(i);if(o)return o;if(typeof i!="object"||i===null||Array.isArray(i))return "message: expected object";let s=i;return s.gem!==U?"gem: wrong protocol marker":s.type!==t?`type: expected ${t}`:Ls(s,e,"")}}var ie={n:"requestId",k:"s",max:64};A("gem.handshake",[{n:"versions",k:"o",fs:[{n:"min",k:"i",lo:1,hi:1e3},{n:"max",k:"i",lo:1,hi:1e3}]},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}},{n:"embedder",k:"s",max:2048,f:"origin"},{n:"unbidden",k:"b",o:1}],30);A("gem.handshake.accept",[{n:"v",k:"i",lo:1,hi:1e3},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}}],5);A("gem.token",[{n:"token",k:"s",max:4096},{n:"requestId",k:"s",o:1,max:64},{n:"generation",k:"i",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"s",o:1,max:512,f:"url"},{n:"playerId",k:"s",max:64},{n:"gameId",k:"s",max:64},{n:"channel",k:"e",v:["dev","test","release"]},{n:"gameVersion",k:"s",o:1,max:64},{n:"expiresAt",k:"i",lo:0,hi:4102444800},{n:"chainEndsAt",k:"i",lo:0,hi:4102444800},{n:"allowDevTools",k:"b",o:1}],30);A("gem.token.denied",[ie,{n:"retryable",k:"b"},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:36e5},{n:"reason",k:"e",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"s",max:64}],30);A("gem.player",[{n:"untrusted",k:"o",fs:[{n:"displayName",k:"s",max:64},{n:"displayTag",k:"s",o:1,max:80},{n:"displayHandle",k:"s",max:80}]},{n:"playerId",k:"s",o:1,max:64},{n:"discriminator",k:"s",o:1,max:8},{n:"avatarIconUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatarIconId",k:"s",o:1,max:64},{n:"avatar3dId",k:"s",o:1,max:64},{n:"avatar3dModelUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatar3dIconUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatars3d",k:"a",o:1,max:8,it:{n:"",k:"o",fs:[{n:"family",k:"s",max:32},{n:"id",k:"s",max:64},{n:"modelUrl",k:"s",max:256,f:"url"},{n:"iconUrl",k:"s",max:256,f:"url"}]}},{n:"badges",k:"a",o:1,max:2,it:{n:"",k:"o",fs:[{n:"itemId",k:"s",max:64},{n:"iconUrl",k:"s",max:2048,f:"url"}]}},{n:"displayTag",k:"s",max:8},{n:"avatarUrl",k:"s",o:1,max:2048,f:"url"},{n:"boost",k:"o",o:1,fs:[{n:"multipliers",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"currencyId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"multiplierBp",k:"i",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"i",o:1,lo:1,hi:7}]}],12);A("gem.pause",[{n:"paused",k:"b"}],120);A("gem.prefs",[{n:"reducedMotion",k:"b"},{n:"muted",k:"b"},{n:"showFrameStats",k:"b",o:1},{n:"music",k:"b",o:1},{n:"sounds",k:"b",o:1},{n:"locale",k:"s",max:35,f:"bcp47"},{n:"recommended",k:"o",o:1,fs:[{n:"volume",k:"i",lo:0,hi:100},{n:"batterySaver",k:"b"},{n:"keyboardLayout",k:"e",v:["wasd","arrows"]},{n:"gamepadConfirm",k:"e",v:["south","east"]},{n:"vibration",k:"b"},{n:"lookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"gamepadLookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"invertLookY",k:"b",o:1},{n:"touchMovement",k:"s",o:1,max:16,f:"code"},{n:"graphicsQuality",k:"s",o:1,max:16,f:"code"},{n:"graphicsQualityAuto",k:"b",o:1}]}],60);A("gem.cohorts",[{n:"cohorts",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"experimentId",k:"s",max:36},{n:"variantKey",k:"s",max:32}]}}],12,"cohorts");A("gem.earnAllowanceChanged",[],30,"earnAllowance");A("gem.viewport",[{n:"insets",k:"o",fs:[{n:"top",k:"i",lo:0,hi:4096},{n:"right",k:"i",lo:0,hi:4096},{n:"bottom",k:"i",lo:0,hi:4096},{n:"left",k:"i",lo:0,hi:4096}]},{n:"reserved",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384},{n:"width",k:"i",lo:0,hi:16384},{n:"height",k:"i",lo:0,hi:16384},{n:"control",k:"o",o:1,fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384},{n:"width",k:"i",lo:0,hi:16384},{n:"height",k:"i",lo:0,hi:16384}]}]}}],60,"viewport");A("gem.deviceSettings",[{n:"settings",k:"j",o:1}],12,"deviceSettings");A("gem.willTerminate",[{n:"reason",k:"e",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"i",lo:0,hi:6e4}],10);A("gem.roomEvent",[{n:"event",k:"e",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"s",max:64},{n:"matchId",k:"s",o:1,max:64},{n:"version",k:"i",o:1,lo:0,hi:2147483647},{n:"reason",k:"s",o:1,max:64},{n:"platform",k:"e",o:1,v:["universal","mobile"]}],120,"rooms");A("gem.socketState",[{n:"connected",k:"b"},{n:"reason",k:"e",o:1,v:["connecting","dropped","watchdog","terminal"]}],12,"socketState");A("gem.seatedEvent",[{n:"roomId",k:"s",max:64}],60,"partySeating");A("gem.autoStartFailedEvent",[{n:"roomId",k:"s",max:64},{n:"code",k:"s",max:64}],30,"autoStartFailure");A("gem.ticketEvent",[{n:"event",k:"e",v:["queued","matched","expired","cancelled","failed"]},{n:"ticketId",k:"s",max:64},{n:"partySize",k:"i",o:1,lo:1,hi:64},{n:"queuedAt",k:"i",o:1,lo:0,hi:4102444800},{n:"expiresAt",k:"i",o:1,lo:0,hi:4102444800},{n:"reason",k:"s",o:1,max:64},{n:"roomId",k:"s",o:1,max:64}],60,"ticketEvents");A("gem.signalEvent",[{n:"event",k:"e",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}],1800,"p2p");A("gem.dedicatedEvent",[{n:"event",k:"e",v:["answer","error","matchEnded"]},{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",o:1,max:10240},{n:"sessionId",k:"s",o:1,max:64},{n:"code",k:"s",o:1,max:64},{n:"message",k:"s",o:1,max:256},{n:"reason",k:"s",o:1,max:64}],120,"dedicated");A("gem.partyResult",[ie,{n:"partyId",k:"s",o:1,max:64}],30,"parties");A("gem.clusterTarget",[{n:"clusterTargetId",k:"s",max:64},{n:"clusterTargetIds",k:"a",o:1,max:3,it:{n:"",k:"s",max:64}}],12,"clusterTarget");A("gem.devtools",[{n:"action",k:"e",v:["open","close","toggle"]}],30,"devtools");A("gem.screenshot",[{n:"maxWidth",k:"i",lo:1,hi:7680},{n:"maxHeight",k:"i",lo:1,hi:4320}],6,"screenshot");A("gem.screenshot.denied",[{n:"reason",k:"e",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"b"}],12,"screenshot");A("gem.requestContext",[],12,"feedbackContext");A("gem.gameContext",[{n:"context",k:"j"}],12,"feedbackContext");A("gem.signal",[{n:"signal",k:"e",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}],1200,"p2p");A("gem.dedicatedOffer",[{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",max:10240},{n:"intent",k:"e",v:["initial","ice_restart","full_reconnect"]}],60,"dedicated");A("gem.partyRequest",[ie],12,"parties");A("gem.ready",[],5);A("gem.engaged",[],5,"engagement");A("gem.progress",[{n:"loaded",k:"i",lo:0,hi:1099511627776},{n:"total",k:"i",lo:0,hi:1099511627776}],600);A("gem.requestToken",[ie,{n:"reason",k:"e",v:["initial","expiring","rejected"]}],12);A("gem.requestLocalServer",[ie,{n:"gameRoomId",k:"s",max:64}],6,"localHost");A("gem.localServer",[ie,{n:"serverId",k:"s",o:1,max:128}],30,"localHost");A("gem.localServer.denied",[ie,{n:"retryable",k:"b"},{n:"reason",k:"e",v:["refused","unavailable"]}],30,"localHost");A("gem.exit",[{n:"reason",k:"s",o:1,max:64}],5);A("gem.openExternal",[{n:"url",k:"s",max:2048,f:"url"}],6);A("gem.requestFullscreen",[{n:"enabled",k:"b"}],30);A("gem.audioState",[{n:"muted",k:"b"}],120,"audioState");A("gem.rewardCue",[{n:"currencySlug",k:"s",max:32},{n:"expected",k:"i",o:1,lo:1,hi:1e9},{n:"origin",k:"o",o:1,fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384}]}],60,"rewardCue");A("gem.walletDisplay",[{n:"visible",k:"b"},{n:"currencies",k:"a",o:1,max:8,it:{n:"",k:"s",max:64}},{n:"score",k:"b",o:1}],60,"walletDisplay");A("gem.controlsDeclare",[{n:"uses",k:"o",fs:[{n:"lookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"gamepadLookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"invertLookY",k:"s",o:1,max:16,f:"code"},{n:"touchMovement",k:"s",o:1,max:16,f:"code"}]}],60,"controls");A("gem.menu",[{n:"settings",k:"b"},{n:"items",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"id",k:"s",max:32},{n:"label",k:"s",max:40}]}}],60,"gameMenu");A("gem.menuSelect",[{n:"entry",k:"e",v:["settings","item"]},{n:"id",k:"s",o:1,max:32}],60,"gameMenu");A("gem.gemCorner",[{n:"corner",k:"e",v:["top-left","top-right","bottom-left","bottom-right"]}],12,"gemCorner");A("gem.settingsDeclare",[{n:"settings",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"id",k:"s",max:40},{n:"label",k:"s",max:40},{n:"kind",k:"e",v:["toggle","slider","choice"]},{n:"value",k:"u",max:40,lo:-1e6,hi:1e6},{n:"quick",k:"b",o:1},{n:"icon",k:"s",o:1,max:16,f:"code"},{n:"min",k:"n",o:1,lo:-1e6,hi:1e6},{n:"max",k:"n",o:1,lo:-1e6,hi:1e6},{n:"step",k:"n",o:1,lo:0,hi:1e6},{n:"options",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"id",k:"s",max:40},{n:"label",k:"s",max:40}]}}]}}],120,"gameSettings");A("gem.settingChange",[{n:"id",k:"s",max:40},{n:"value",k:"u",max:40,lo:-1e6,hi:1e6}],120,"gameSettings");A("gem.requestShare",[{n:"params",k:"a",max:16,it:{n:"",k:"o",fs:[{n:"key",k:"s",max:64},{n:"value",k:"s",max:512}]}}],6,"share");A("gem.requestAvatarPicker",[{n:"tab",k:"e",o:1,v:["2d","3d"]}],6,"avatarPicker");A("gem.vibrate",[{n:"pattern",k:"a",max:99,it:{n:"",k:"i",lo:0,hi:1e4}}],600,"vibration");A("gem.frameStats",[{n:"fps",k:"i",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"i",lo:0,hi:1e5},{n:"counts",k:"e",o:1,v:["pageFrames","gameDraws"]}],120,"frameStats");A("gem.portraitBorders",[{n:"name",k:"s",o:1,max:40}],60,"portraitBorders");A("gem.error",[{n:"code",k:"e",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"s",o:1,max:256}],60);A("gem.requestPurchase",[ie,{n:"purchaseKind",k:"e",v:["item","recipe"]},{n:"targetId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"quantity",k:"i",o:1,lo:1,hi:10},{n:"catalogId",k:"s",o:1,max:64}],12,"purchases");A("gem.requestAvatar3dPurchase",[ie,{n:"itemId",k:"s",max:64},{n:"currencySlug",k:"s",max:32}],12,"avatar3dPurchases");A("gem.purchaseResult",[ie,{n:"outcome",k:"e",v:["ok","declined","unavailable"]},{n:"reason",k:"s",o:1,max:64,f:"code"},{n:"purchaseId",k:"s",o:1,max:64}],30,"purchases");A("gem.deviceSettings.put",[ie,{n:"settings",k:"j"}],30,"deviceSettings");A("gem.deviceSettings.result",[ie,{n:"outcome",k:"e",v:["stored","too_large","unavailable"]}],30,"deviceSettings");A("gem.requestAd",[ie,{n:"placement",k:"s",max:32},{n:"format",k:"e",v:["interstitial","rewarded"]}],6,"ads");A("gem.adResult",[ie,{n:"outcome",k:"e",v:["shown","no_ad","unavailable"]}],12,"ads");A("gem.signalMoment",[ie,{n:"kind",k:"e",v:["level_end","run_end","match_end","menu_return","other_break"]},{n:"placement",k:"s",o:1,max:32}],6,"moments");A("gem.momentResult",[ie,{n:"shown",k:"b"}],12,"moments");A("gem.requestSignIn",[ie],6,"signIn");A("gem.signInResult",[ie,{n:"outcome",k:"e",v:["signed_in","declined","unavailable"]}],12,"signIn");A("gem.requestFriendChallenge",[ie,{n:"playerId",k:"s",max:64},{n:"template",k:"s",max:64},{n:"params",k:"j",o:1}],12,"friendChallenges");A("gem.friendChallengeResult",[ie,{n:"outcome",k:"e",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"s",o:1,max:64},{n:"param",k:"s",o:1,max:64},{n:"channel",k:"s",o:1,max:16},{n:"configVersion",k:"i",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:864e5},{n:"detail",k:"s",o:1,max:300}],30,"friendChallenges");var Fn=Object.freeze(Ds);$t.__malformed=60;Object.freeze($t);Object.freeze(ci);var he={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},qt=class{constructor(e=he){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=$t[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 mi(t,e){return t.toLowerCase()===e.toLowerCase()}function gt(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function Fs(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:gt(n.hostname)&&gt(r.hostname)}function $s(t,e){if(e.min>e.max)return null;let n=Math.min(t.max,e.max),r=Math.max(t.min,e.min);return n>=r?n:null}var $n=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 gi(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 qs="inventory",yt=t=>typeof t=="number"?t:0,Nt=t=>typeof t=="string"?t:"";function pi(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 Ns(t){let e=t??{};return {itemDefinitionId:Nt(e.item_definition_id),instanceId:Nt(e.instance_id),quantity:yt(e.quantity),acquiredAt:yt(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function Zu(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:pi(e.currencies,r=>{let i=r??{},o=Array.isArray(i.buckets)?i.buckets.map(s=>{let a=s??{};return {bucket:Nt(a.bucket),balance:yt(a.balance)}}):void 0;return {currencyId:Nt(i.currency_id),total:yt(i.total),...o===void 0?{}:{buckets:o}}}),items:pi(e.items,Ns),progressions:pi(e.progressions,r=>{let i=r??{};return {progressionDefinitionId:Nt(i.progression_definition_id),currentValue:yt(i.current_value),completionCount:yt(i.completion_count),isCompleted:i.is_completed===true,...gi(i)}}),...n===void 0?{}:{etag:n}}}var qn=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${qs}#buckets`:qs;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 Wa(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(i)?i.map(Ns):[]}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 Ba(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 Zu(n)}};var em={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,recipe_on_cooldown:1,recipe_max_uses_exceeded:1,item_max_stack_exceeded:1,recipe_costs_unmet:1,quantity_invalid:1,error:1},tm=new Set(Object.keys(em));function js(t){return typeof t=="string"&&tm.has(t)?t:"error"}var Be=class extends RangeError{constructor(n,r){super(r);this.code=n;this.name="PurchaseRefusal";}code;retryable=false};var ee=t=>typeof t=="string"?t:"",nm=t=>typeof t=="string"?t:ee(t&&typeof t=="object"?t.type:void 0),Te=t=>typeof t=="number"?t:0;function rm(t){let e=t??{};return {prerequisiteType:ee(e.prerequisite_type),referenceId:ee(e.reference_id),required:Te(e.required),current:Te(e.current)}}function jt(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {orderId:ee(e.order_id),status:ee(e.status),...n===void 0?{}:{etag:n}}}function Nn(){return crypto.randomUUID()}var im="recipe-usage",Us=100;function jn(t){let e=t??{};switch(e.type){case "currency":return {kind:"currency",currencyId:ee(e.currency_id),bucket:ee(e.bucket),delta:Te(e.delta),balanceAfter:Te(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:ee(e.item_definition_id),instanceId:ee(e.instance_id),delta:Te(e.delta),quantityAfter:Te(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:ee(e.progression_definition_id),delta:Te(e.delta),valueAfter:Te(e.value_after),completed:e.completed===true};default:return {kind:"other",type:ee(e.type)}}}function om(t){let e=t??{},n=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:ee(e.entry_id),...n===void 0?{}:{rarityTier:n},rollNumber:Te(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(jn):[]}}function am(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(om):void 0;return {orderId:ee(e.order_id),status:ee(e.status),...n===void 0?{}:{etag:n},granted:Array.isArray(e.granted)?e.granted.map(jn):[],consumed:Array.isArray(e.consumed)?e.consumed.map(jn):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(jn):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function sm(t){let e=t??{},n=e.price??{};return {payment:"platform_currency",orderId:ee(e.target_order_id)||ee(e.source_order_id),status:ee(e.status),purchaseId:ee(e.purchase_id),sourceOrderId:ee(e.source_order_id),price:{currencyId:ee(n.platform_currency_id),amount:Te(n.price)}}}function lm(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:ee(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 Bs(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 Un=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;async create(e,n={}){let r=await this.write(()=>Ia(this.api,this.entity.type,this.entity.id,{operations:e.map(Bs),source:n.source??"play",nonce:Nn()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return jt(r)}async createMany(e,n={}){return this.write(()=>Ca(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(Bs),nonce:Nn()})),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 Ja(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(rm):[];return {canExecute:o.can_execute===true,locked:o.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(o.reasons)?o.reasons.map(d=>nm(d)):[],...s===void 0?{}:{usesRemaining:s},...a===void 0?{}:{cooldownExpiresAt:a}}}async recipeUsageAll(){return this.cache.read(im,[],async()=>{let n=await za(this.api,this.entity.type,this.entity.id,{limit:Us})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(lm),truncated:r.length>=Us}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,n={}){if(e.payment.kind==="configured"){let c=e,p=await this.write(()=>Da(this.api,this.entity.type,this.entity.id,{catalog_id:c.catalogId,recipe_id:c.targetId,game_id:this.api.gameId(),nonce:Nn()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...am(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,i]=await Promise.all([rs(this.api,n.signal===void 0?{}:{signal:n.signal}),On(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(p=>p.slug);throw new Be("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 Be("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=g=>i.currencies.find(y=>y.currency_id===g)?.slug??g,p=a.platform_prices.map(g=>`${c(g.platform_currency_id)} ${g.price}`);throw new Be("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 Be("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let m=await this.write(()=>us(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:Nn(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));return sm(m)}async executeRecipe(e,n,r={}){return await this.purchase({kind:"recipe",catalogId:e,targetId:n,payment:{kind:"configured"}},r)}async addProgression(e,n,r){let i=await this.write(()=>xa(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return jt(i)}async maxProgression(e,n,r){let i=await this.write(()=>Ss(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return jt(i)}async claimProgression(e,n){let r=await this.write(()=>Ta(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return jt(r)}async resetProgression(e,n){let r=await this.write(()=>Cs(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return jt(r)}async write(e){return this.cache.invalidate(),e()}};var yi=t=>typeof t=="string"?t:"",dm=t=>typeof t=="number"?t:0;function Ws(t){let e=t??{};return {orderId:yi(e.order_id),status:yi(e.status),source:yi(e.source),createdAt:dm(e.created_at)}}var Bn=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await fs(this.api,this.entity.type,this.entity.id,{...e.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(Ws):[],...i===void 0?{}:{nextCursor:i}}}async get(e,n){let r=await Va(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Ws(r)}};var Hs=t=>typeof t=="number"?t:0,cm=t=>typeof t=="string"?t:"";function um(t){let e=t??{};return {progressionDefinitionId:cm(e.progression_definition_id),currentValue:Hs(e.current_value),completionCount:Hs(e.completion_count),isCompleted:e.is_completed===true,...gi(e)}}var Wn=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 Ka(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return um(o)}catch{return i??null}}};var Hn=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,m=r().then(c=>(o&&this.generation===d&&(l.value=c,l.filledAt=this.clock.now()),c)).finally(()=>{l.inFlight===m&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(s)===l&&this.slots.delete(s));});return l.inFlight=m,m}invalidate(){this.slots.clear(),this.generation+=1;for(let e of [...this.listeners])e();}onInvalidate(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}rebind(){if(!this.identity)return;let e=this.identity();e!==this.boundTo&&(this.boundTo=e,this.invalidate());}};function fi(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 hi(t){try{let e=fi(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var le=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},mm=3e4,Vs="the save payload could not reach storage. From a browser this is almost always the storage account's CORS rule, which the platform owns and your game cannot change. If every save fails this way, report it rather than working around it",pm=/^[A-Za-z0-9_]{1,64}$/;function Ee(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(!pm.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function Ks(t,e){let n=new AbortController,r=AbortSignal.timeout(e),i=()=>n.abort(r.reason),o=()=>n.abort(t?.reason);return t?.aborted?n.abort(t.reason):(r.addEventListener("abort",i,{once:true}),t?.addEventListener("abort",o,{once:true})),{signal:n.signal,release:()=>{r.removeEventListener("abort",i),t?.removeEventListener("abort",o);}}}function bi(t,e){return t.aborted&&e?.aborted!==true}var gm=new Set(["x-ms-blob-type"]),ym=/^[ -~]+$/;function fm(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new le("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(!gm.has(o))throw new le("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"||!ym.test(i))throw new le("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 le("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(o)} twice.`);n[o]=i;}return n}function vi(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 _i(t){return t?.reason==="not_found"}var Vn=class{constructor(e,n,r={}){this.api=e;this.entity=n;this.options=r;}api;entity;options;async put(e,n,r={}){let i;try{i=JSON.stringify(n);}catch(o){throw new le("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 le("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={}){let i=r.contentType??"application/octet-stream",o=this.budget(r.timeoutMs),s=Ks(r.signal,o);try{let a=await Es(this.api,this.entity.type,this.entity.id,Ee(e),{size_bytes:n.byteLength,content_type:i,...r.metadata===void 0?{}:{metadata:r.metadata}},{signal:s.signal});if(typeof a.upload_url!="string"||typeof a.session_id!="string")throw new le("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let l=fm(a.upload_headers,e),d,m=this.options.fetch??globalThis.fetch.bind(globalThis);try{d=await m(a.upload_url,{method:"PUT",headers:{"content-type":i,...l},body:n,credentials:"omit",signal:s.signal});}catch(c){throw bi(s.signal,r.signal)?this.timeout("upload",o):new le("upload_failed",`${Vs} for PUT. Underlying error: ${c}`)}if(!d.ok){let c=await hi(d);throw new le("upload_failed",d.status===400?"the save upload answered 400. The platform and the service holding the bytes disagree about what this upload must carry, which is not something your game can fix and not worth retrying \u2014 report it. "+c:`the save upload answered ${d.status}. `+(d.status===403?"An upload URL is short-lived, so this is most likely an expired one \u2014 start the save again rather than retrying the upload. ":"")+c)}return vi(await Fa(this.api,this.entity.type,this.entity.id,Ee(e),{session_id:a.session_id},{signal:s.signal}))}catch(a){throw this.rethrow(a,r.signal,s.signal,"save",o)}finally{s.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 le("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={}){let r=this.budget(n.timeoutMs),i=Ks(n.signal,r);try{let o;try{let l=await si(this.api,this.entity.type,this.entity.id,Ee(e),{signal:i.signal});if(!l.modified)return null;o=l.body;}catch(l){if(_i(l))return null;throw l}if(typeof o.download_url!="string")throw new le("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let s=this.options.fetch??globalThis.fetch.bind(globalThis),a;try{a=await s(o.download_url,{credentials:"omit",signal:i.signal});}catch(l){throw bi(i.signal,n.signal)?this.timeout("download",r):new le("download_failed",`${Vs} for GET. Underlying error: ${l}`)}if(!a.ok){let l=await hi(a);throw new le("download_failed",`the save download answered ${a.status}. `+(a.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+l)}return new Uint8Array(await a.arrayBuffer())}catch(o){throw this.rethrow(o,n.signal,i.signal,"load",r)}finally{i.release();}}async describe(e,n={}){try{let r=await si(this.api,this.entity.type,this.entity.id,Ee(e),{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?vi(r.body):null}catch(r){if(_i(r))return null;throw r}}async list(e={}){let n=await hs(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}}),r=n.next_cursor;return {saves:(n.data??[]).map(vi),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await Ga(this.api,this.entity.type,this.entity.id,Ee(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!_i(r))throw r}}budget(e){return e??this.options.timeoutMs??mm}timeout(e,n){return new le("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,i,o){return e instanceof le?e:bi(r,n)?this.timeout(i,o):e}};function hm(t){try{return ai(t)}catch{return t}}function wi(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"?hm(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var Kn=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await ys(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(i=>wi(i)):[]}async get(e,n={}){try{let r=await Ua(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?wi(r.body,r.etag):null}catch(r){if(Js(r))return null;throw r}}async put(e,n,r={}){let i=await Rs(this.api,this.entity.type,this.entity.id,e,{value:oi(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return wi(i)}async delete(e,n){try{await Oa(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});}catch(r){if(!Js(r))throw r}}};function Js(t){return t?.reason==="not_found"}function Jn(t,e,n={}){let r=new Hn(he,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let i=new qn(t,e,r);return {settings:new Kn(t,e),inventory:i,saves:new Vn(t,e,n.saves??{}),currencies:new $n(i,n.resolveCurrencyId),mutations:new Un(t,e,r),orders:new Bn(t,e),progressions:new Wn(t,e,i)}}var ki={type:"players",id:"me"};var Ke=t=>typeof t=="string"?t:"",ft=t=>typeof t=="number"?t:0;function zn(t,e){let n=e??{},r=Ke(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:Ke(n.player_id),gameId:Ke(n.game_id),channel:Ke(n.channel)||"release",name:Ke(n.name),slotIndex:ft(n.slot_index),isActive:n.is_active!==false,createdAt:Ke(n.created_at),updatedAt:Ke(n.updated_at)}}var Yn=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=Jn(this.api,{type:"characters",id:e},{saves:this.saves,identity:this.identity,resolveCurrencyId:this.resolveCurrencyId}),this.scopes.set(e,n)),n};async list(e){let r=(await gs(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(i=>zn(this.scope,i)):[]}async get(e,n){let r=await Na(this.api,e,n===void 0?{}:{signal:n});return zn(this.scope,r)}async create(e){let n=await Ea(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return zn(this.scope,n)}async update(e,n,r){let i=await Ts(this.api,e,{name:n},r===void 0?{}:{signal:r});return zn(this.scope,i)}async delete(e,n){await Is(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await as(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 Xs="[gem: use gem.text.toPlain()]",zs=new Set,Ys;function bm(t){try{if(zs.has(t))return;let e=globalThis.location;if(Ys??=!!e?.port&&gt(e.hostname??""),!Ys)return;zs.add(t),console.warn(`[gem] ${t} is PlayerText, turned into a string: players see ${Xs}. Render text.toPlain(value) (text is in @indiegems/gem-web-sdk/sdk).
2
- ${new Error().stack}`);}catch{}}var be=class{#e;#n;constructor(e,n="player text"){this.#e=e,this.#n=n,Object.freeze(this);}toString(){return bm(this.#n),Xs}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function De(t,e){return new be(t,e)}var ht={toPlain(t){return be.unwrap(t)},compare(t,e,n){let r=t instanceof be?be.unwrap(t):t,i=e instanceof be?be.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 be?be.unwrap(t):t,r=e instanceof be?be.unwrap(e):e;return n.normalize("NFC")===r.normalize("NFC")}};var bt=t=>typeof t=="string"?t:"";function Xn(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:bt(e.transfer_id),status:bt(e.status),sourceEntityId:bt(e.source_entity_id),targetEntityId:bt(e.target_entity_id),...n===void 0?{}:{message:De(n,"transfer.message")},createdAt:bt(e.created_at),expiresAt:bt(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function vm(){return crypto.randomUUID()}var Qn=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 cs(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:vm()},e.signal===void 0?{}:{signal:e.signal});return Xn(n)}async list(e={}){let r=await _s(this.api,{entity_type:this.self.type,entity_id:this.self.id,...e.direction===void 0?{}:{direction:e.direction},...e.status===void 0?{}:{status:e.status},...e.cursor===void 0?{}:{cursor:e.cursor},...e.limit===void 0?{}:{limit:e.limit},...e.signal===void 0?{}:{signal:e.signal}})??{},i=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {transfers:Array.isArray(r.transfers)?r.transfers.map(Xn):[],...i===void 0?{}:{nextCursor:i}}}async get(e,n){let r=await ss(this.api,e,n===void 0?{}:{signal:n});return Xn(r)}async accept(e,n){return this.resolve(()=>Ra(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>Ps(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>Aa(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),Xn(await e())}};var _m=t=>typeof t=="string"?t:"",wm=t=>typeof t=="string"&&t?t:void 0,km=t=>typeof t=="number"?t:void 0;function Qs(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 Sm(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new ue("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 ue("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=km(e.version);if(r===void 0)throw new ue("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let i=(l,d,m)=>{let c=_m(l.id);if(!c)throw new ue("config_malformed",`${d}[${m}] 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:Qs(o),currency:Qs(s)}}var ue=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},Zs=10*1024*1024,el=15e3,tl=new Set(["dev","test","release"]);function Rm(t){if(!tl.has(t))throw new ue("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...tl].join(", ")}. gem-api would reject the assignment read.`);return t}var Zn=t=>typeof t=="number"?t:0,Si=t=>typeof t=="string"?t:"";function xm(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:Si(i.entry_id),weight:Zn(i.weight),dropRate:Zn(i.drop_rate),...o===void 0?{}:{rarityTier:o}}}):[];return {lootTableId:Si(e.loot_table_id),name:Si(e.name),rollCount:Zn(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:Zn(e.total_weight),entries:n}}var er=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 ue("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 ja(this.api,e,n===void 0?{}:{signal:n});return xm(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??el),n;try{let l=await qa(this.api,Rm(this.channel()),{signal:e});if(!l.modified)throw new ue("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");n=l.body;}catch(l){if(l instanceof ue)throw l;if(l?.reason==="not_found")return null;throw l}let r=wm(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 ue("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??el}ms`):new ue("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=>fi(d)).catch(()=>"");throw new ue("config_unreachable",`the config document answered ${o.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let s=await o.text();if(s.length>Zs)throw new ue("config_too_large",`the config document is ${s.length} bytes, over the ${Zs} cap`);let a;try{a=JSON.parse(s);}catch(l){throw new ue("config_malformed",`config document is not JSON: ${String(l)}`)}return Sm(a)}};var nl=400,Ce=t=>typeof t=="string"?t:"",Am=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Je(t){let e=Ce(t);if(!Am.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var Pm=/^[0-9a-f]{1,64}$/,Tm=/^[0-9a-f]{16}$/,Em=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,Cm=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function Ri(t){let e=Ce(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 Im=4096,Mm=new TextEncoder;function Om(t){let e=Ce(t.challenge_data),n=Ce(t.challenge_data_hash);return e===""||!Tm.test(n)?{}:Mm.encode(e).length>Im?{}:{data:e,dataHash:n}}function Gm(t){let e=t??{},n=Je(e.period_start_at),r=Je(e.period_ends_at);if(n===0||r===0)return;let i=Ce(e.slug),o=Ce(e.seed),s=Ri(e.period_local_date),a=Ce(e.boundary),l=Ce(e.reset_time);return {id:Ce(e.progression_definition_id),...i===""?{}:{slug:i},window:Ce(e.window),periodStartAt:n,periodEndsAt:r,...s===void 0?{}:{periodLocalDate:s},boundary:Em.test(a)?a:"",resetTime:Cm.test(l)?l:"",seed:Pm.test(o)?o:"",...Om(e)}}function vt(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 tr(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(Gm).filter(n=>n!==void 0):[]}var Ut=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;vt(n);let r=await ps(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return tr(r)}};function Ie(t){return typeof t=="string"&&t!==""?t:void 0}var rl=new Set(["localhost","127.0.0.1","[::1]"]);function ze(t){return nr(t)}function nr(t){let e=Ie(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:"&&rl.has(n.hostname)))return e}var Lm=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,Dm=/^[a-z][a-z0-9_]{0,31}$/;function Fm(t){if(!Array.isArray(t))return;let e=[],n=new Set;for(let r of t.slice(0,8)){let i=r??{},o=Ie(i.family),s=Ie(i.avatar_3d_id),a=ze(i.model_url),l=ze(i.icon_url);o===void 0||!Dm.test(o)||n.has(o)||s===void 0||!Lm.test(s)||a===void 0||l===void 0||(n.add(o),e.push({family:o,id:s,modelUrl:a,iconUrl:l}));}return e}function $m(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},i=Ie(r.item_id),o=ze(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function xe(t){let e=t??{},n=Ie(e.player_id),r=Ie(e.display_name),i=Ie(e.discriminator),o=Ie(e.display_tag),s=Ie(e.avatar_icon_id),a=ze(e.avatar_icon_url),l=Ie(e.avatar_3d_id),d=ze(e.avatar_3d_model_url),m=ze(e.avatar_3d_icon_url),c=Fm(e.avatars_3d);return {...n===void 0?{}:{playerId:n},...r===void 0?{}:{displayName:De(r,"displayName")},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:De(o,"displayTag")},...s===void 0?{}:{avatarIconId:s},...a===void 0?{}:{avatarIconUrl:a},...l===void 0?{}:{avatar3dId:l},...d===void 0?{}:{avatar3dModelUrl:d},...m===void 0?{}:{avatar3dIconUrl:m},...c===void 0?{}:{avatars3d:c},badges:$m(e.badges)}}var qm=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function Nm(t){if(t===void 0)return;let e=ze(t);if(e===void 0)return;let n=new URL(e);return rl.has(n.hostname)||qm.has(n.origin)?e:void 0}var il=100,sl=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function xi(t){let{periodsBack:e,period:n,playerId:r}=t;if(vt(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!sl.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 ll(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!sl.test(e))return;let n=Ri(t.period_local_date),r=Je(t.period_start_at),i=Je(t.period_ends_at),o=r>0&&i>0;return {id:e,...n===void 0?{}:{localDate:n},...o?{startAt:r,endsAt:i}:{},opensAt:Je(t.opens_at),closesAt:Je(t.closes_at),final:t.final===true}}var Bt=t=>typeof t=="string"?t:"",_t=t=>typeof t=="number"?t:0,Wt=t=>typeof t=="string"?t:void 0,jm=t=>typeof t=="number"?t:void 0,dl={player:"players",character:"characters"};function Um(t,e){let n=t??{},r=Wt(n.entity_id),i=typeof n.entity_type=="string"&&Object.hasOwn(dl,n.entity_type)?n.entity_type:void 0,o=cl(n.stats),s=n.properties!==null&&typeof n.properties=="object"?n.properties:void 0,a=e?n.is_viewer===true:void 0;return {...xe(n),rank:_t(n.rank),occurredAt:_t(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 ol(t,e){let n=t??{},r=Wt(n.bucket_1),i=Wt(n.bucket_2),o=jm(n.update_frequency_seconds),s=ll(n);return {leaderboardType:Bt(n.leaderboard_type),runType:Bt(n.run_type),...r===void 0?{}:{bucket1:r},...i===void 0?{}:{bucket2:i},entries:Array.isArray(n.entries)?n.entries.map(a=>Um(a,e)):[],generatedAt:_t(n.generated_at),...o===void 0?{}:{updateFrequencySeconds:o},...s===void 0?{}:{period:s}}}function al(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=cl(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:_t(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function cl(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 Bm(t,e,n){let r=t??{},i=Wt(r.bucket_1),o=Wt(r.bucket_2),s=ll(r);return {leaderboardType:Bt(r.leaderboard_type),runType:Bt(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(al).filter(a=>a!==void 0):[],personalBest:al(r.personal_best)??null,totalRuns:_t(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:_t(r.generated_at),...s===void 0?{}:{period:s}}}var Ht=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=xi(n),i=await es(this.#e,e,{...r,...n.bucket1===void 0?{}:{bucket_1:n.bucket1},...n.bucket2===void 0?{}:{bucket_2:n.bucket2},...n.signal===void 0?{}:{signal:n.signal}});return ol(i,false)}async friends(e,n={}){let r=xi(n),i=await Ya(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 ol(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>il)throw new TypeError(`limit must be an integer between 1 and ${il}, got ${String(l)}`)}let o=xi(i),s=await Ha(this.#e,e,dl[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"&&Bt((s??{}).entity_id)||r;return Bm(s,n,a)}};var rr=t=>typeof t=="string"?t:"",Ai=t=>typeof t=="number"?t:0;function ul(t){let e=t??{};return {playerId:rr(e.player_id),key:rr(e.key),value:e.value,updatedAt:Ai(e.updated_at)}}function Wm(t){let e=t??{};return {...xe(e),playerId:rr(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:Ai(e.updated_at)}}function Hm(t){return t?.reason==="not_found"}var Vt=class{constructor(e,n){this.api=e;this.selfPlayerId=n;}api;selfPlayerId;async friends(e,n={}){let i=await Xa(this.api,Ee(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:rr(i.key),entries:Array.isArray(i.entries)?i.entries.map(Wm):[],generatedAt:Ai(i.generated_at)}}async of(e,n,r={}){try{return ul(await os(this.api,e,Ee(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(i){if(Hm(i))return null;throw i}}async set(e,n,r={}){if(Ee(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 ul(await xs(this.api,i,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await La(this.api,r,Ee(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var Vm="gemChallenge",ml=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function pl(t){if(!(typeof t!="string"||t===""))try{return new URLSearchParams(t).get(Vm)??void 0}catch{return}}var Ye=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});}},ir=t=>typeof t=="string"?t:void 0;function gl(t){let e=t??{};return {...xe(e),playerId:ir(e.player_id)??""}}function yl(t){let e=t.has_more===true?ir(t.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function Km(t){let e=t??{};return {friends:Array.isArray(e.data)?e.data.map(gl):[],...yl(e)}}var Pi=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function Jm(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 fl(t){let e=t??{},n=Pi(e.opened_at),r=Pi(e.answered_at);return {id:ir(e.item_id)??"",from:gl(e.sender),template:ir(e.template)??"",params:Jm(e.params),createdAt:Pi(e.created_at)??0,...n===void 0?{}:{openedAt:n},...r===void 0?{}:{answeredAt:r}}}function zm(t){let e=t??{};return {challenges:Array.isArray(e.data)?e.data.map(fl):[],...yl(e)}}function Ym(t){let e=t;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var Kt=class{#e;#n;#o;constructor(e,n={}){this.#e=e,this.#n=n.challenge,this.#o=n.launchedChallengeId;}async list(e={}){let n=await vs(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Km(n)}challenge(e){return this.#n===void 0?Promise.resolve({outcome:"unavailable"}):this.#n(e)}async inbox(e={}){let n=await bs(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return zm(n)}async launchedChallenge(e={}){let n=this.#o;if(n===void 0||!ml.test(n))return null;try{return fl(await Za(this.#e,n,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(Ym(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!ml.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 ws(this.#e,e);}};var Xm=0;function we(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++Xm)}-${String(Date.now())}-${t}`}}var Qm=12e4,hl=8,Zm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,ep=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Jt(t,e,n={}){return new Ye(new O("invalid",400,e,void 0,t),n)}function tp(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function np(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!Zm.test(e))return {error:Jt("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!ep.test(n))return {error:Jt("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(!tp(r))return {error:Jt("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:Jt("param_invalid",`params.${s} must be a string or a safe integer`,{param:s})}}return o.length>hl?{error:Jt("param_undeclared",`params has ${String(o.length)} keys; a template declares at most ${String(hl)}`)}:{playerId:e,template:n,params:i}}function rp(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 Ye(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 Ye(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 ip(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function bl(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=np(n);if("error"in r)return Promise.reject(r.error);let i=`challenge-${we()}`;return new Promise((o,s)=>{let a={},l=m=>{e.delete(i)&&(t.clock.clearTimeout(a.timer),"error"in m?s(m.error):o(m.outcome));};e.set(i,l),a.timer=t.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},t.timeoutMs??Qm);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 (${ip(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(rp(n));}}}var or=t=>typeof t=="string"?t:void 0;function op(t){let e=t??{},n=or(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:or(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var ar=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await On(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=op(o);s!==void 0&&i.push(s);}return i}},Ti=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function ap(t){let e=t??{},n=or(e.currency_id);if(n===void 0||n==="")return;let r=Ti(e.limit),i=Math.min(Ti(e.earned),r),o=Math.min(Ti(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:or(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 vl(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 sr=class{#e;#n;#o;constructor(e,n,r){this.#e=e,this.#n=n,this.#o=r;}async get(e={}){let r=(await ts(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=ap(o);s!==void 0&&i.push(s);}return i}on(e,n){return e!=="changed"?(this.#o?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#n?.on(n)??(()=>{})}},zt=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new ar(e),this.earnAllowance=new sr(e,n,r);}};var Ei=t=>typeof t=="string"?t:"",_l=t=>typeof t=="number"?t:0;function sp(t){let e=t??{};return {key:Ei(e.key),visibility:Ei(e.visibility),value:e.value,updatedAt:_l(e.updated_at)}}function lp(t){let e=t??{};return {...xe(e),playerId:Ei(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(sp):[],generatedAt:_l(e.generated_at)}}function dp(t){return t?.reason==="not_found"}var Yt=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return lp(await ns(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(dp(r))return null;throw r}}};var cp=new Map([["function_error",false],["function_failed",false],["function_timeout",false],["function_not_published",false],["function_input_too_large",false],["functions_not_configured",false],["forbidden",false],["function_capacity_unavailable",true],["function_host_unreachable",true],["function_host_error",true],["rate_limited",true],["service_unavailable",true]]),lr=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:cp.get(this.code))??super.retryable}},Xe=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=up(e),i;try{i=await this.#e(r,n.signal===void 0?{}:{signal:n.signal});}catch(o){throw o instanceof O?pp(o):o}return mp(i)}};function up(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 se(`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 se(`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 mp(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 pp(t){let{details:e,invocationId:n}=Sa(t),i=e?.untrusted?.message,o=e?.reason;return new lr(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 dr(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 gp=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],Ci="gem_";function wl(t){return t.startsWith(Ci)}var kl=1e4,Sl=50,yp=500,fp=65536-4*1024,hp=24*1024;function Rl(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 xl=t=>typeof t=="number"?t:0,bp=t=>typeof t=="string"?t:"";function cr(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function vp(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(i=>{let o=i??{};return {index:xl(o.index),code:bp(o.code)}}):[];return {accepted:xl(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Ii(){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 _p(t){return t?.retryable===true}var Xt=class{#e;#n;#o;#f;#t=[];#h={};#a=0;#s=null;#b=false;#v=false;#m=0;#_=0;#w=0;#r=false;#k=null;#l=null;#c=false;#i=false;#p=false;#S=false;#R=false;constructor(e){this.#e=e,this.#n=e.options?.enabled!==false,this.#o=Math.max(kl,e.options?.flushIntervalMs??kl),this.#f=Math.max(1,Math.floor(e.options?.maxQueue??yp));}track(e,n={}){if(!(!this.#n||this.#r)){if(wl(e)){this.#R||(this.#R=true,this.#y(`[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.#x(e,Rl({...this.#h,...n}));}}setContext(e){this.#h={...this.#h,...e};}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#i)return cr();let n=this.#I();if(n===null||n==="")return this.#t.length>0&&!this.#S&&(this.#S=true,this.#y("[gem] analytics: events are being recorded but no play session has been established, so nothing is being sent. Outside the arcade this is expected.")),cr();if(this.#P(),this.#t.length===0)return cr();let r=e.keepalive===true;if(this.#m>0&&!r)return cr();this.#u();let i=this.#t.splice(0,this.#E(r)),o=this.#a;this.#a=0;let s=Math.round(this.#e.clock.now()),a={batch_id:Ii(),sent_at_ms:s,events:i.map(d=>Al(d,s))},l={client:this.#e.client(),gameId:()=>n};this.#m+=1;try{let d=await ds(l,a,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=vp(d,o);return this.#_=0,this.#w=0,this.#C(m),m}catch(d){throw _p(d)?(this.#T(i,o),this.#_+=1,this.#w=this.#e.clock.now()+dr(this.#_,d)):this.#y(`[gem] analytics: ${i.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#m-=1,this.#t.length>0&&this.#d();}}trackPlatform(e,n={}){this.#r||this.#i&&(e==="gem_pause"||e==="gem_resume")||this.#x(e,Rl(n));}hold(){this.#r||this.#l!==null||(this.#i=true,this.#u());}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.#p&&(this.#p=false,this.#l=e,this.#c=false,this.#t.unshift({uid:Ii(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#t.length>=Sl?this.#g():this.#t.length>0&&this.#d();}get held(){return this.#i}startSession(){if(!(this.#r||this.#l!==null)){if(this.#i){this.#p=true;return}this.#l=this.#e.clock.now(),this.#c=false,this.trackPlatform("gem_session_start");}}endSession(e){if(this.#r||this.#c)return;if(this.#c=true,this.#i){this.#p=false,this.#t=[],this.#a=0;return}let n=this.#l;this.trackPlatform("gem_session_end",{reason:e,...n===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-n))}}),this.#g({keepalive:true});}setPaused(e){this.#r||e===this.#b||(this.#b=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#u():this.#t.length>0&&this.#d());}setHidden(e){this.#r||e===this.#v||(this.#v=e,e?this.#u():this.#t.length>0&&this.#d());}dispose(){this.#r=true,this.#u(),this.#t=[],this.#a=0;}get pending(){return this.#t.length}#x(e,n){let{dimensions:r,measures:i}=n;for(this.#P();this.#t.length>=this.#f;)this.#t.shift(),this.#a+=1;this.#t.push({uid:Ii(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:i}),this.#t.length>=Sl?this.#g():this.#d();}#g(e={}){if(e.keepalive!==true&&this.#A()>0){this.#d();return}this.flush(e).catch(()=>{});}#A(){return Math.max(0,this.#w-this.#e.clock.now())}#T(e,n){for(this.#t=[...e,...this.#t],this.#a+=n;this.#t.length>this.#f;)this.#t.shift(),this.#a+=1;}#E(e){let n=e?hp:fp,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(Al(s,0)).length+1,i>n)return Math.max(1,o)}return r}#d(){this.#s!==null||this.#b||this.#v||this.#i||this.#r||this.#m>0||(this.#s=this.#e.clock.setTimeout(()=>{this.#s=null,this.#g();},Math.max(this.#o,this.#A())));}#u(){this.#s!==null&&(this.#e.clock.clearTimeout(this.#s),this.#s=null);}#P(){let e=this.#M();e===null||e===""||(this.#k!==null&&this.#k!==e&&(this.#t=[],this.#a=0,this.#l=null,this.#c=false),this.#k=e);}#C(e){for(let n of e.rejected)this.#y(`[gem] analytics: an event was refused (${n.code}). `+wp(n.code));}#y(e){let n=this.#e.log;n!==null&&(n===void 0?console.warn(e):n(e));}#I(){try{return this.#e.gameId()}catch{return null}}#M(){try{return this.#e.playerId()}catch{return null}}};function Al(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:t.dimensions,measures:t.measures}}function wp(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 ye(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e}function Qt(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=ye(n);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var kp=2e3,Sp=5e3;function Tl(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,m=null;s=c=>{d||(d=true,r=null,t.clock.clearTimeout(m),l(c));},m=t.clock.setTimeout(()=>{n=true,s([]);},t.timeoutMs??kp);});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 !Pl(e,s)||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let l=null,d=m=>{i.delete(d)&&(t.clock.clearTimeout(l),a(m));};i.set(d,s),l=t.clock.setTimeout(()=>d(e),t.refreshTimeoutMs??Sp);})},accept(s,a){let l=Qt(a),d=ye(s),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[c,p]of [...i])Pl(m,p)||c(m);}}}}function Pl(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Rp=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),w=class extends Error{constructor(n,r,i){super(`${n}: ${r}`,i);this.reason=n;this.name="DedicatedServerError",this.retryable=Rp.has(n),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var El=["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"],xp=new Set(El);function wt(t){return typeof t=="string"&&xp.has(t)?t:"unknown"}var ur="webrtc_dedicated",Li=["universal","mobile","web"];var Ap="p2p_unavailable",Pp="capacity_unavailable",Tp=2,Cl=3e4,Il=1e3,Ml=2e4;async function Di(t){let e=ye(t.clusterTargetId),n=t.nextClusterTarget,r=0,i=t.clock??he,o=t.retry??{},s=o.budgetMs??Cl,a=o.maxDelayMs??Ml,l=o.initialDelayMs??Il,d=i.now(),m=d+s,c=0;for(;;){c++;try{let p=await Ni(t.signal,"while allocating",()=>t.client.post(`${Ll(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!Ep(p)||s<=0)throw p;if(p.status===503&&p.code===Ap)throw new w("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===Pp?r+1:0,n!==void 0&&r>=Tp){let R=n;n=void 0;let P=ye(await R());P!==void 0&&(e=P,r=0);}let g=Math.min(a,l*2**(c-1)),y=Math.min(a,(p.retryAfterSeconds??0)*1e3),S=Math.max(g/2,y)+Math.random()*(g/2);if(i.now()+S>m)throw Cp(t,p,c,i.now()-d,s);if(o.onWaiting?.({attempt:c,elapsedMs:i.now()-d,budgetMs:s,nextAttemptInMs:S,status:p.status,message:p.message}),await mr(i,S,t.signal),t.signal?.aborted)throw Gi("while waiting to allocate")}}}function Ep(t){return t instanceof O?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function Cp(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 w("start_rate_limited",`the platform was still limiting match starts for room ${t.roomId} after ${o}: ${e.message}`,{cause:e}):new w("no_server_ready",`the platform had no server ready for room ${t.roomId} after ${o}: ${e.message}`,{cause:e})}var Ip=12e4,Mp=1e3;async function Fi(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??Mp,i=t.timeoutMs??Ip,o=e.now()+i,s=Ol(t),a={seen:t.knownToExist===true};for(;;){let l=await Gl(t,s,a);if(l.outcome!==null)return l.outcome;if(e.now()+r>o)throw new w("timeout",`match ${n} was still ${l.status} after ${i}ms`);await mr(e,r,t.signal);}}async function $i(t){return (await Gl(t,Ol(t),{seen:t.knownToExist===true})).outcome}function Ol(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${Ll(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function Gl(t,e,n){let{matchId:r}=t,i=t.clock.now(),o;try{o=await Ni(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:Op(r,o,i)};if(o.status==="failed"){let s=o.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:wt(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function qi(t){let e=await Ni(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 Ni(t,e,n){if(t?.aborted)throw Gi(e);try{return await n()}catch(r){throw t?.aborted?Gi(e,r):r}}function Gi(t,e){return new w("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function Op(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 Ll(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function mr(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 Dl(t){return typeof t=="string"&&t.trim()!==""}function pr(t,e){return Dl(t)?t.trim():Dl(e)?e:null}var gr="0.1.0-beta",Fl="0-beta",kt="web",Gp=/^(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 Lp(t){let e=Gp.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function $l(t,e){let n=Dp(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:gr};let i=Lp(r);if(i===null)throw new w("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 '${gr}' for it.`);if(i!==Fl)throw new w("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${Fl}' 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 '${gr}' for it.`);return {...t,platform:n,engineVersion:r}}function Dp(t,e){if(t===void 0||t===kt)return kt;if(!Li.includes(t))throw new w("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${Li.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${kt}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${kt}' 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.`),kt}function Zt(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:ql(e.queued_at),expiresAt:ql(e.expires_at),heartbeatIntervalSeconds:typeof n=="number"&&n>0?n:0}}function ql(t){if(typeof t!="string")return 0;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1e3):0}var Fp=3,Nl=1e3,yr=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?Nl:Math.max(Nl,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<Fp){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 $p="gemPlayWith",qp=/^[A-Za-z0-9_-]{16,128}$/;function jl(t){if(typeof t!="string"||t==="")return;let e;try{e=new URLSearchParams(t).get($p);}catch{return}return e!==null&&qp.test(e)?e:void 0}function Ul(t){let e=typeof t=="object"&&t!==null?t.play_with:void 0;return e==null?null:e==="joined"?"joined":"unavailable"}var Np="join",jp="welcome",Up="rejected",Bl=25e3,Bp=1e3,ji=1;function Ui(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var Wp={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 Bi(t){let e=typeof t=="string"?t:"unknown";return new w(Wp[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function en(t){let{channel:e,clock:n}=t;return new Promise((r,i)=>{let o=false,s=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??Bl),a=n.setTimeout(()=>v(new w("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,Bp)),l=S=>{let R=S.data;if(typeof R!="string"){c(R);return}let P;try{P=JSON.parse(R);}catch{c(R);return}if(o){c(R);return}if(P.t===jp){let h=Ui(P.heartbeat_interval);y({...typeof P.player_id=="string"?{playerId:P.player_id}:{},...typeof P.match_id=="string"?{matchId:P.match_id}:{},...h===void 0?{}:{heartbeatIntervalMs:h}});return}if(P.t===Up){v(Bi(P.reason));return}c(R);},d=()=>{v(new w("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{v(new w("aborted","the caller aborted during the join exchange"));},c=S=>{o&&t.onMessage?.(S);},p=()=>{n.clearTimeout(a),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},y=S=>{o=true,p(),t.onMessage===void 0&&g(),r({welcome:S,detach:g});},v=S=>{o||(o=true,p(),g(),i(S));};if(e.addEventListener("message",l),e.addEventListener("close",d),t.signal?.aborted){m();return}t.signal?.addEventListener("abort",m);try{e.send(JSON.stringify({t:Np,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:ji}:{}}));}catch(S){v(new w("connection_failed",`the join frame could not be sent on the open channel: ${String(S)}`,{cause:S}));}})}var Qe=1,tn=2,Wi=4,Ki=8,Hp=2,Vp=1e3,Ji="heartbeat timeout",nn="gem-uu",fr=2,Hl="gem_transports";function St(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!Kp(r)||e.includes(r)||e.push(r);}return e}function Kp(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function rn(t,e){if(typeof t!="object"||t===null)return null;let n=t[Hl];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 hr(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var Vl=new TextEncoder,Kl=new TextDecoder;function zi(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function Yi(t){let e=0;return t?.reliable===false&&(e|=Qe),t?.ordered===false&&(e|=tn),e}function Xi(t){return {reliable:(t&Qe)===0,ordered:(t&tn)===0}}var Qi={reliable:true,ordered:true};function Jl(t){return JSON.stringify({t:"join",credential:t,wire:fr,heartbeat:ji})}function zl(t){let e;try{e=JSON.parse(t);}catch{throw new w("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let n=Ui(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"?Bi(e.reason):new w("join_refused","the server answered the join out of protocol")}function br(){return typeof globalThis.WebTransport=="function"&&Zi===null}function vr(){return Zi}var Zi=null;var Wl="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Jp(t){let e=Mn(t);if(e.byteLength!==32)throw new w("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var Hi=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 w("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 Vi(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 on(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 w("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:Jp(t.certHashBase64)}]});}let r=n,i=a=>{try{r.close();}catch{}throw a},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(Zi=Wl,i(new w("connection_failed",`${Wl}; the rung is skipped for the rest of this page (a reload probes again)`)));let s=new Promise((a,l)=>{setTimeout(()=>l(new w("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 w("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(Vi(Wi,Vl.encode(Jl(t.credential))));let c=new Hi,p=d.readable.getReader(),g;for(;g===void 0;){let y=await Promise.race([p.read(),s]);if(y.done||y.value===void 0)return i(new w("connection_failed","the control stream closed before the join was answered"));for(let v of c.push(y.value)){g=zl(Kl.decode(v.payload));break}}return {link:zp(r,m,p,c,t.log??(y=>console.warn(y)),Xl(g,t.clock)),welcome:g}}catch(a){return i(a)}}function zp(t,e,n,r,i,o){let s,a,l=false,d=y=>{if(!l){l=true,m.stop();try{t.close();}catch{}a?.(y);}},m=to(o,()=>d(Ji)),c=(y,v)=>{m.heard(),(y&Ki)===0&&s!==void 0&&((y&Wi)!==0?s(Kl.decode(v),Qi):s(v,Xi(y)));};(async()=>{try{for(;;){let y=await n.read();if(y.done||y.value===void 0)break;for(let v of r.push(y.value))c(v.flags,v.payload);}}catch{}d("stream closed");})();let p,g;try{let y=t.datagrams;if(y?.readable!==void 0&&y.writable!==void 0){let v=y.readable.getReader();g=y.writable.getWriter(),p=y,(async()=>{try{for(;;){let S=await v.read();if(S.done||S.value===void 0)break;let R=S.value;R.byteLength!==0&&c((R[0]??0)|Qe|tn,R.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(y){p=void 0,g=void 0,i(`[gem] webtransport datagram lane unusable (${hr(y)}); unreliable sends ride the stream`);}return t.closed.then(y=>d(Yl(y?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(y,v){if(l)return;if(typeof y=="string"){e.write(Vi(Wi,Vl.encode(y))).catch(()=>d("write failed"));return}let S=Yi(v);if((S&Qe)!==0&&g!==void 0){let R=zi(S,y),P=p?.maxDatagramSize;if(P===void 0||R.byteLength<=P){g.write(R).catch(()=>{});return}}e.write(Vi(S,y)).catch(()=>d("write failed"));},onMessage(y){s=y;},onClose(y){a=y;},close(){d("closed");}}}function eo(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 w("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 w("timeout","websocket did not come up in time")));},e),l=g=>{s||(s=true,clearTimeout(a),r.close(),o(g));},d=()=>{r.send(Jl(t.credential));},m=g=>{if(s)return;if(typeof g.data!="string"){l(new w("join_refused","the server sent binary before answering the join"));return}let y;try{y=zl(g.data);}catch(v){l(v);return}s=true,clearTimeout(a),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",c),r.removeEventListener("error",p),i({link:Yp(r,Xl(y,t.clock)),welcome:y});},c=()=>{l(new w("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new w("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",m),r.addEventListener("close",c),r.addEventListener("error",p),r.readyState===1&&d();})}function Yl(t){return typeof t=="string"&&t.length>0?t:void 0}function Xl(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function to(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,Vp)*Hp,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 Yp(t,e){let n,r,i=false,o=a=>{if(!i){i=true,s.stop();try{t.close();}catch{}r?.(a);}},s=to(e,()=>o(Ji));return t.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){n?.(a.data,Qi);return}let l=new Uint8Array(a.data);if(l.byteLength===0)return;let d=l[0]??0;(d&Ki)===0&&n?.(l.slice(1),Xi(d));})),t.addEventListener("close",(a=>o(Yl(a?.reason)??"socket closed"))),{transport:"websocket",send(a,l){if(!i){if(typeof a=="string"){t.send(a);return}t.send(zi(Yi(l),a));}},onMessage(a){n=a;},onClose(a){r=a;},close(){o("closed");}}}function no(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=to(r,()=>l(Ji)),m=(c,p)=>{if(d.heard(),typeof c=="string"){i?.(c,Qi);return}let g=new Uint8Array(c);if(g.byteLength===0)return;let y=g[0]??0;(y&Ki)===0&&i?.(g.slice(1),Xi(y|p));};if(t.addEventListener("message",(c=>m(c.data,0))),t.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let c=e.connectionState;(c==="failed"||c==="closed")&&l(`connection ${c}`);})),a!==void 0){let c=a;c.addEventListener("message",(p=>m(p.data,Qe|tn))),c.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(c,p){if(s)return;if(typeof c=="string"){t.send(c);return}let g=Yi(p),y=zi(g,c);if((g&Qe)!==0&&a!==void 0&&a.readyState==="open"){a.send(y);return}t.send(y);},onMessage(c){i=c;},onClose(c){o=c;},close(){l("closed");}}}function Ql(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let i=ro(r);i!==void 0&&(e[n]=i);}return e}function Zl(t){if(Array.isArray(t))return t.map(Xp).filter(e=>!!e)}function ro(t){if(io(t)||Array.isArray(t)&&t.every(io))return t}function io(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function Xp(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=ro(e.fixed),r=ro(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},...Rt("description",Qp(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(io)?{allowed:e.allowed}:{},...Rt("min",an(e.min)),...Rt("max",an(e.max)),...Rt("minItems",an(e.min_items)),...Rt("maxItems",an(e.max_items)),...Rt("maxLength",an(e.max_length))}}function Qp(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 Rt(t,e){return e===void 0?{}:{[t]:e}}function Fe(t){let e=t??{},n=X(e.id)??X(e.game_room_id);if(n===void 0)throw new Error("[gem] a game-room response carried no id");let r=Array.isArray(e.members)?e.members.map(Zp):[];return {id:n,gameId:X(e.game_id)??"",name:X(e.name)??"",status:X(e.status)??"open",hostPlayerId:X(e.host_player_id)??"",maxPlayers:Me(e.max_players)??0,memberCount:Me(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...ke("joinCode",X(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...ke("roomArgs",Ql(e.room_args)),...ke("roomArgsTemplate",Zl(e.room_args_template)),gameChannel:X(e.game_channel)??"release",...ke("region",X(e.region)),...ke("clusterTargetId",X(e.cluster_target_id)),selfHosted:e.self_hosted===true,...ke("matchId",X(e.match_id)),version:Me(e.version)??0,...ke("templateId",X(e.template_id)),...ke("templateSlug",X(e.template_slug)),roomType:X(e.game_room_type)??"Standard",...ke("transports",St(e.transports)??void 0),createdAt:Me(e.created_at)??0,updatedAt:Me(e.updated_at)??0,...ke("startedAt",Me(e.started_at))}}function Zp(t){let e=t??{};return {...xe(e),playerId:X(e.player_id)??"",isReady:e.is_ready===true,role:X(e.role)??"member",joinedAt:Me(e.joined_at)??0,...ke("groupId",X(e.group_id)),...ke("platform",X(e.platform))}}function oo(t){let e=t??{};return {id:X(e.id)??X(e.game_room_id)??"",gameId:X(e.game_id)??"",name:X(e.name)??"",status:X(e.status)??"open",hostPlayerId:X(e.host_player_id)??"",maxPlayers:Me(e.max_players)??0,memberCount:Me(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:X(e.game_channel)??"release",roomType:X(e.game_room_type)??"Standard",createdAt:Me(e.created_at)??0}}function X(t){return typeof t=="string"&&t.length>0?t:void 0}function Me(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function ke(t,e){return e===void 0?{}:{[t]:e}}var _r=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(oo),...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(oo)}))}create(e,n,r){return tg(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},...sn(n)},e.signal).then(Fe)}get(e,n){return this.options.client.get(this.roomV2(e),n).then(Fe)}join(e,n,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...n.partyId===void 0?{}:{party_id:n.partyId},...sn(r)},n.signal).then(Fe)}joinByCode(e,n,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...n.partyId===void 0?{}:{party_id:n.partyId},...sn(r)},n.signal).then(Fe)}quickJoin(e,n,r=[]){return ao(this.options,e,n,r).then(i=>i.room)}createTicket(e,n,r=[]){return Ma(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},...sn(n)},{...e.signal===void 0?{}:{signal:e.signal}}).then(Zt)}heartbeatTicket(e){return ls(this.generated(),e).then(Zt)}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(Zt):Pa(this.generated(),e).then(Zt)}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 td(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(Fe)}setReady(e,n,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:n},r).then(Fe)}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(Fe)}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 ed(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 ed(t){return `/v2/games/${encodeURIComponent(t.gameId())}/game-rooms`}function td(t,e){return e===void 0&&t.selfHosted?.()===true}function ao(t,e,n,r=[],i){let o=td(t,e.partyId);return t.client.post(`${ed(t)}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...eg(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},...sn(n)},e.signal).then(s=>({room:Fe(s),playWith:i===void 0?null:Ul(s)}))}function eg(t,e){return t===void 0?{}:{templates:(e?t.slice(0,1):t).map(r=>({template_slug:r}))}}function sn(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function tg(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 wr=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 kr=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 ng(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var rg=1e3,ig=3e3,og=6e4,ag=2,nd=new Set(["game_room_closed","game_room_gone"]),sg=12e4,lg=5e3,dg=new Set(["invalid_cluster_target","capacity_unavailable"]),cg=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function ad(t,e){return new so(e,t)}var so=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 _r(this.apiOptions),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;internals;emitter=new wr;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;return this.api.create(r,this.version("create"),o[0]).catch(async s=>{let a=await this.afterRefusedClusters(s,o);if(a[0]===void 0||a[0]===o[0])throw s;return this.api.create(r,this.version("create"),a[0])})});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,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"),pg(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||od(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"),mg(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||od(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 yr({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(()=>$i({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=wt(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 w("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=ye(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=(m,c)=>Di({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...i===void 0?{nextClusterTarget:()=>this.nextCluster(c)}:{},retry:{...n.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),n.retry?.onWaiting?.(p);}},...n.signal===void 0?{}:{signal:n.signal}}),l=()=>a(o,[s]).catch(async m=>{if(i!==void 0||!id(m))throw m;let c=await this.nextCluster([s],true);if(c===void 0)throw m;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 w("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 Fi({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 w("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!nd.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new w("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(!Ze()){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<rg){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(ng(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!Ze()){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(()=>$i({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,!nd.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 w("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 w("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 w("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||!dg.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 kr({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&&Ze())){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(),!!Ze())){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 Sr)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 Sr)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??lg}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new w("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=pr(this.options.platformGameVersion?.(),n?.gameVersion);if(r===null)throw new w("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 $l({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return Qt(await this.options.resolveClusterTargets());let e=ye(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !id(e)||n.length===0?[]:Qt(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(Qt(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"||!cg.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 ao(this.apiOptions,e,this.version("quickJoin"),n,this.internals.playWithTicket)}assertNotInRoom(e){if(this.room!==null)throw new w("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 w("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 w("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 w?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=ug(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??sg;return new Promise((i,o)=>{let s=c=>{a(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),c();},a=this.emitter.on("matchAllocationStarted",c=>s(()=>i(c))),l=this.emitter.on("matchFailed",(c,p)=>s(()=>o(new w("allocation_failed",`match ${c} did not come up: ${p}`)))),d=()=>s(()=>o(new w("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>s(()=>o(new w("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??ig}pushedInterval(){return this.options.pushedPollIntervalMs??og}pushed(){return this.options.clock.now()-this.lastPushAt<ag*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 Ze(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var Sr=["visibilitychange","focus","pageshow","online"];function ug(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||rd(t)!==rd(e)}function rd(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function id(t){return t instanceof O&&t.code==="invalid_cluster_target"}var Rr=8;function mg(t){if(!(Array.isArray(t)&&t.length>=1&&t.length<=Rr&&t.every(n=>typeof n=="string"&&n.length>0)))throw new w("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${Rr} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function pg(t){let e=t?.templateSlugs;if(e===void 0)return;if(!(Array.isArray(e)&&e.length>=1&&e.length<=Rr&&e.every(r=>typeof r=="string"&&r.length>0)))throw new w("misconfigured",`quickJoin's templateSlugs is an array naming one to ${Rr} 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 w("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 od(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var gg=["p2p","dedicated","unknown"],lo=["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 xt=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let i=yg(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 yg(t,e,n){let r=Math.floor(n/1e3);return t.filter(i=>lo.includes(i.type)).slice(0,100).map(i=>{let o=fg(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:i.value===void 0?{}:{value:i.value}}})}function fg(t){if(t!==void 0)return gg.includes(t)?t:"unknown"}var ln=class{constructor(e){this.options=e;this.reporter=new xt({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:xr(i.credential)??"",hostFingerprint:xr(i.host_fingerprint)??"",hostEpoch:Ar(i.host_epoch)??0,expiresAt:(Ar(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,m=(Array.isArray(d.urls)?d.urls:[]).filter(c=>typeof c=="string"&&c.length>0);m.length!==0&&o.push({urls:m,username:xr(d.username)??"",credential:xr(d.credential)??""});}let s=Ar(i.expires_at),a=Ar(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)}`}};function xr(t){return typeof t=="string"&&t.length>0?t:void 0}function Ar(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}var hg=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),G=class extends Error{constructor(n,r,i){super(`${n}: ${r}`,i);this.reason=n;this.name="P2pError",this.retryable=hg.has(n);}reason;retryable};var sd=10240,ld=2048,bg=new TextEncoder;function dd(t){return bg.encode(t).length}function We(t,e){let n=i=>{throw new w("invalid_sdp",`the ${e} ${i}`)},r=dd(t);r>=sd&&n(`is ${r} bytes, over the ${sd} 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=dd(i);o>ld&&n(`has a ${o}-byte line, over the ${ld} limit`);}}function Pr(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 Tr=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 vg=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function At(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=Er(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function Er(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 vg.test(r)?r:null}function dn(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 co=5e3,_g=12e4+co,wg=1024,kg=6e4,Sg=1e4,cd=64*1024,ud=5;function uo(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 G("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 G("keys_unavailable",i.reason);let a=t.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await a(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(Sg)});}catch{throw new G("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 G("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let d;try{let p=await l.text();if(p.length>cd)throw new G("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${cd} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof G?p:new G("keys_unavailable",`the JWKS endpoint at ${i.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>ud)throw new G("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${ud} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=o();for(let p of m){let g=p;if(g.kty==="RSA"&&!(g.alg!==void 0&&g.alg!=="RS256")&&!(g.use!==void 0&&g.use!=="sig")&&!(typeof g.kid!="string"||g.kid.length===0))try{let y=await c.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(g.kid,y);}catch{}}};return {async key(a){let l=e.get(a);if(l)return l;if(!i.ok)throw new G("keys_unavailable",i.reason);if(r)return await r,e.get(a)??null;let d=t.now();if(!Number.isFinite(d))throw new G("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<kg?null:(n=d,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var cn=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>=wg){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+_g),true}};function pd(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 md(t){try{let e=new TextDecoder().decode(pd(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function mo(t,e,n,r,i){let o=$=>{throw new G("peer_unauthenticated",`the peer's join credential is not usable: ${$}`)},s=t.split(".");s.length!==3&&o("it is not a three-part JWT");let[a,l,d]=s,m=md(a);m===null&&o("its header does not decode"),m.alg!=="RS256"&&o(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let c=m.kid;(typeof c!="string"||c.length===0)&&o("it names no key");let p=await n.key(c);p===null&&o("it was signed by a key this build cannot resolve");let g=i.subtle??globalThis.crypto?.subtle;g||o("this environment has no WebCrypto");let y=new TextEncoder().encode(`${a}.${l}`),v;try{v=pd(d);}catch{o("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,v,y)||o("its signature does not verify");let R=md(l);R===null&&o("its payload does not decode");let P=R,h=$=>typeof P[$]=="string"?P[$]:"",k=$=>typeof P[$]=="number"&&Number.isFinite(P[$])?P[$]:NaN;h("iss")!==i.issuer&&o("it was issued by someone else"),h("aud")!==`${i.issuer}/p2p-match`&&o("its audience is not this platform"),h("match_id")!==e.matchId&&o("it is for another match"),h("game_id")!==e.gameId&&o("it is for another game");let C=k("exp")*1e3,T=k("nbf")*1e3;(!Number.isFinite(C)||e.now>C+co)&&o("it has expired"),Number.isFinite(T)&&e.now<T-co&&o("it is not valid yet");let W=h("role");W!=="host"&&W!=="client"&&o("it names no usable role");let F=k("host_epoch");F!==e.hostEpoch&&o("it names a different host epoch");let N=Er(h("fingerprint"));N===null&&o("its fingerprint claim is malformed"),dn(N,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let E=Er(h("host_fingerprint"));E===null&&o("its host fingerprint claim is malformed"),dn(E,e.hostFingerprint)||o("it was issued against a different host certificate");let M=h("jti");M.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit(M,e.now)||o("it has already been used");let L=h("sub");return L.length===0&&o("it names no player"),{playerId:L.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:F,role:W,fingerprint:N,hostFingerprint:E,jti:M,expiresAt:C}}function po(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 go(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 yo(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function fo(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 gd(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 yd(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var un=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 ho={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}},$e=["reliable","ordered","unreliable"];function bo(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 mn(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var hd=1,Tg=3e4,bd=2e3,Eg=5e3,vd=6e4,Cg=8,_o=class{constructor(e=Cg){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;}},Ig=new _o,Mg=8,Og=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??uo({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new Tr;links=new Map;replays=new cn;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=hd+1;ended=null;closed=false;ready=null;helloSeen=false;reportedUnreachableEpoch=-1;reportedStallEpoch=-1;counted=false;pendingOffers=new Map;answeredSessions=new Map;credentialGeneration=0;credentialDeadline=0;get matchId(){return this.options.matchId}get playerId(){return this.localPlayerId}get isHost(){return this.migration?.isLocalHost??false}get hostPlayerId(){return this.migration?.currentHostPlayerId??""}get hostEpoch(){return this.migration?.currentEpoch??0}get peers(){let e=[];for(let n of this.links.values())n.admitted&&e.push(this.expose(n));return e}peer(e){let n=this.links.get(e);return n&&n.admitted?this.expose(n):null}on(e,n){return this.emitter.on(e,n)}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}async start(e){let n=this.options.connectTimeoutMs??Tg;this.credentialDeadline=this.options.clock.now()+n;let r=new Promise((a,l)=>{this.ready={resolve:a,reject:l};}),i=ye(this.options.clusterTargetId);if(i!==void 0)try{let a=await this.options.api.turnLease(this.options.matchId,i,e);this.iceServers=a.iceServers,this.mark("turn leased");}catch(a){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${vo(a)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let o=this.options.clock.setTimeout(()=>{this.fail(new G("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),s=()=>this.fail(new G("aborted","the caller aborted while connecting"));e?.aborted?s():e?.addEventListener("abort",s);try{await r;}finally{this.options.clock.clearTimeout(o),e?.removeEventListener("abort",s),this.ready=null;}}async kick(e){if(!this.isHost)throw new G("misconfigured","only the current host of this match can kick a peer");await this.options.api.kick(this.options.matchId,e);}async leave(){try{await this.options.api.leave(this.options.matchId);}catch{}this.close();}close(){if(!this.closed){this.closed=true,this.pendingOffers.clear();for(let e of [...this.links.values()])this.dropLink(e,"closed",false);this.options.signaling.close(),this.emitter.clear();}}report(e){this.options.api.telemetry(e).catch(()=>{});}notifyCandidatesDropped(e){this.emitter.emit("candidatesDropped",e);}handleSignal(e,n){this.closed||this.route(e,n).catch(r=>this.report_(r));}async route(e,n){switch(e){case "hello":return this.onHello(n);case "offer":return this.onOffer(n);case "answer":return this.onAnswer(n);case "ice":return this.onIce(n);case "peerLeft":return this.onPeerLeft(n);case "migration":return this.onMigration(n);case "matchEnded":return this.onMatchEnded(n);case "error":return this.onSignalingError(n);default:return}}async onHello(e){let n=de(e.playerId),r=de(e.hostPlayerId),i=Cr(e.hostEpoch);if(!(n===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new un(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,hd),i=await r.connection.createOffer();await r.connection.setLocalDescription(i);let o=r.connection.localDescription?.sdp??i.sdp;if(!o)throw new G("invalid_sdp","the browser produced an offer with no SDP");We(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:At(r);if(i===null)throw new G("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??Ig,s=()=>this.closed||e!==this.credentialGeneration,a=Eg;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 m=d.status,c;if(m===409)c=bd;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?c=p*1e3:(c=a,a=Math.min(a*2,vd)),c=Math.min(Math.max(c,bd),vd);}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=de(e.fromPlayerId),r=de(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=Mg){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(n,e);return}if(!this.isHost||this.migration.isKicked(n)===true)return;let i=de(e.sessionId);if(i!==null&&this.answeredSessions.get(n)===i)return;We(r,"offer"),this.refuseMedia(r,"offer");let o=At(r);if(o===null)throw new G("invalid_sdp",`the offer from ${n} carries no usable fingerprint`);this.mark("offer received"),i!==null&&this.answeredSessions.set(n,i);let s=this.links.get(n);s&&this.dropLink(s,"resignalled",false);let a=this.openLink(n,this.nextPeerId++);a.remoteFingerprint=o,await a.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(a);let l=await a.connection.createAnswer();await a.connection.setLocalDescription(l);let d=a.connection.localDescription?.sdp??l.sdp;if(!d)throw new G("invalid_sdp","the browser produced an answer with no SDP");We(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(n,d,a.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let n=de(e.fromPlayerId),r=de(e.sdp);if(n===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||n!==this.hostPlayerId)return;We(r,"answer"),this.refuseMedia(r,"answer");let o=At(r);if(o===null)throw new G("invalid_sdp","the host's answer carries no usable fingerprint");this.mark("answer received"),i.remoteFingerprint=o,i.pendingAnswer=r,this.hostVerified(i)&&await this.applyAnswer(i,r);}hostVerified(e){let n=this.credential;return n===null||e.remoteFingerprint===null?false:dn(n.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new G("peer_unauthenticated","the host's DTLS certificate is not the one the platform attested for this match. Refusing before the handshake, so no credential is presented.")),this.dropLink(e,"host_fingerprint_mismatch",false),false)}maybeAuthenticate(){if(this.isHost)return;let e=this.links.get(this.hostPlayerId);if(!e||e.remoteFingerprint===null||e.connection.remoteDescription!==null)return;let n=e.pendingAnswer;n!==void 0&&this.hostVerified(e)&&this.applyAnswer(e,n).catch(r=>this.report_(r));}async applyAnswer(e,n){this.mark("host verified"),e.pendingAnswer=void 0,await e.connection.setRemoteDescription({type:"answer",sdp:n}),this.flushCandidates(e);}async onIce(e){let n=de(e.fromPlayerId),r=de(e.candidate);if(n===null||r===null)return;let i=this.links.get(n);if(!i)return;let o=de(e.sdpMid),s=Cr(e.sdpMLineIndex)??Cr(e.sdpMLineIndexAlt),a={candidate:r,...o===null?{}:{sdpMid:o},...s===null?{}:{sdpMLineIndex:s}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(a);return}await i.connection.addIceCandidate(a);}onPeerLeft(e){let n=de(e.playerId);if(n===null)return;let r=de(e.reason)??"left";if(n===this.localPlayerId){this.fail(new G("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=de(e.hostPlayerId),r=Cr(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:n,hostEpoch:r,...de(e.reason)===null?{}:{reason:de(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(o=>typeof o=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(i.kind!=="duplicate"){if(i.kind==="completed"){this.emitter.emit("hostChanged",n,r);return}if(i.kind==="refused"){this.report_(new G("migration_failed",i.why));return}for(let o of [...this.links.values()])this.dropLink(o,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",n,r),i.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration(),await this.offerToHost("full_reconnect");}}watchMigration(){let e=this.hostEpoch;this.options.clock.setTimeout(()=>{this.closed||this.migration===null||this.migration.currentEpoch===e&&this.migration.stalled(this.options.clock.now())&&this.reportedStallEpoch!==e&&(this.reportedStallEpoch=e,this.report_(new G("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=de(e.reason)??"ended";this.ended=n,this.emitter.emit("matchEnded",n),this.ready!==null&&this.fail(new G("match_ended",`the match ended: ${n}`)),this.close();}onSignalingError(e){let n=de(e.code)??"unknown",r=de(e.message)??"the platform refused a signaling message";this.report_(new G("signaling_failed",`${n}: ${r}`));}openLink(e,n){let i=(this.options.peerConnectionFactory??bo)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let p of $e){let g=i.createDataChannel(p,ho[p]);g.binaryType="arraybuffer",o[p]=g;}let s={playerId:e,assignedPeerId:n,connection:i,channels:o,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),m=p=>{this.onHandshakeMessage(s,p.data).catch(g=>this.report_(g));},c=()=>{this.onReliableOpen(s).catch(p=>this.report_(p));};return i.addEventListener("icecandidate",a),i.addEventListener("iceconnectionstatechange",l),i.addEventListener("connectionstatechange",d),o.reliable.addEventListener("open",c),o.reliable.addEventListener("message",m),s.detachHandshake=()=>{o.reliable.removeEventListener("open",c),o.reliable.removeEventListener("message",m);},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 G("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 G("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(po({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=fo(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 G(yd(r.reason),gd(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=At(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 mo(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 G&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",vo(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(go({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(yo(n));}catch{}this.dropLink(e,r,false);}finishAdmission(e){this.mark(this.isHost?"peer admitted":"admitted"),e.admitted=true,e.detachHandshake(),e.detachHandshake=()=>{},this.emitter.emit("peerJoined",this.expose(e)),this.settle();}onIceState(e){let n=e.connection.iceConnectionState;if(!(n!=="failed"&&n!=="disconnected"&&n!=="closed")){if(this.isHost){(n==="failed"||n==="closed")&&this.dropLink(e,n,true);return}if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,n);}catch(r){this.report_(r);}}}}onConnectionState(e){let n=e.connection.connectionState;n!=="failed"&&n!=="closed"||this.dropLink(e,n,true);}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(n,r="reliable")=>e.channels[r].send(n)}}dropLink(e,n,r){this.links.delete(e.playerId),e.detachAll();for(let i of $e)_d(e.channels[i]);_d(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 G?e:new G("connection_failed",vo(e),{cause:e}));}count(e){this.counted||!Og.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(Pr(e))throw new G("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 de(t){return typeof t=="string"&&t.length>0?t:null}function Cr(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function vo(t){return t instanceof Error?t.message:String(t)}function _d(t){try{t.close();}catch{}}var Gg=100,Lg=50,yn=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??Gg)){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 G("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new G("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??Lg));}};function H(t){return e=>typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function He(t,e){return n=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e?n:void 0}function Pt(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function wd(t){return typeof t=="boolean"?t:void 0}var ve=H(64),fn=He(0,2147483647);function wo(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=ve(n);typeof r=="string"&&e.push(r);}return e}function Y(t,e,n){return {to:t,from:e,read:n,required:true}}function V(t,e,n){return {to:t,from:e,read:n,required:false}}var $g=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=Pt("disconnected","failed","closed")(e.iceState),r=He(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:[Y("sdp","sdp",H(10240)),Y("signaling_intent","intent",Pt("initial","ice_restart","full_reconnect")),V("sdp_hash","sdpHash",H(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[Y("peer_id","peerId",ve),Y("sdp","sdp",H(10240)),Y("assigned_peer_id","assignedPeerId",He(0,4294967295)),V("sdp_hash","sdpHash",H(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[Y("peer_id","peerId",ve),Y("candidate","candidate",H(512)),V("sdp_mid","sdpMid",H(64)),V("sdp_mline_index","sdpMLineIndex",He(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[Y("host_epoch","hostEpoch",fn)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[Y("host_epoch","hostEpoch",fn),V("evidence","evidence",$g)]}}));Object.freeze(Object.assign(Object.create(null),{p2p_hello:"hello",p2p_sdp_offer:"offer",p2p_sdp_answer:"answer",p2p_ice_candidate:"ice",p2p_peer_joined:"peerJoined",p2p_peer_left:"peerLeft",p2p_host_migration:"migration",p2p_match_ended:"matchEnded",p2p_error:"error"}));Object.freeze(Object.assign(Object.create(null),{hello:[Y("playerId","player_id",ve),Y("hostPlayerId","host_player_id",ve),Y("hostEpoch","host_epoch",fn),V("members","members",wo)],offer:[Y("fromPlayerId","from_player_id",ve),Y("sdp","sdp",H(10240)),V("sessionId","signaling_session_id",H(128)),V("sdpHash","sdp_hash",H(128)),V("iceUfrag","ice_ufrag",H(64)),V("intent","signaling_intent",Pt("initial","ice_restart","full_reconnect"))],answer:[Y("fromPlayerId","from_player_id",ve),Y("sdp","sdp",H(10240)),V("sessionId","signaling_session_id",H(128)),V("sdpHash","sdp_hash",H(128)),V("iceUfrag","ice_ufrag",H(64)),V("assignedPeerId","assigned_peer_id",He(0,4294967295))],ice:[Y("fromPlayerId","from_player_id",ve),Y("candidate","candidate",H(512)),V("sdpMid","sdp_mid",H(64)),V("sdpMLineIndex","sdp_m_line_index",He(0,255)),V("sdpMLineIndexAlt","sdp_mline_index",He(0,255))],peerJoined:[Y("playerId","player_id",ve)],peerLeft:[Y("playerId","player_id",ve),V("reason","reason",H(64))],migration:[Y("hostPlayerId","new_host_player_id",ve),Y("hostEpoch","host_epoch",fn),V("reason","reason",H(64)),V("kickedPlayerIds","kicked_player_ids",wo),V("migrationComplete","migration_complete",wd)],matchEnded:[V("reason","reason",H(64))],error:[V("code","code",H(64)),V("message","message",H(256))]}));Object.freeze(Object.assign(Object.create(null),{party_invite_received:"inviteReceived",party_member_joined:"memberJoined",party_member_left:"memberLeft",party_member_kicked:"memberKicked",party_leader_transferred:"leaderTransferred",party_updated:"updated",party_disbanded:"disbanded",party_game_room_joined:"gameRoomJoined",party_game_room_left:"gameRoomLeft"}));var tt="webrtc_p2p";function Sd(t){let e=new ln({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 G("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=ye(r.clusterTargetId),o=i??ye(await t.resolveClusterTarget?.());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!==tt)throw new G("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${tt}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let a=new yn({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===void 0?{}:{clusterTargetId:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await mn(),...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}}}function Rd(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(!Ze());for(let d of Sr)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(!Ze());}let s=new Map;return o.push(n.on("matchReady",a=>{let l=a.protocol===tt?"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 xd=["pointerdown","keydown"];function Ad(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 g of xd)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(y=>y?.buttons.some(v=>v.pressed)===true)},m=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},c=()=>{if(i=null,!(n||r)){if(d()){a();return}m()&&(i=e.requestAnimationFrame?.(c)??null);}};function p(){i===null&&!n&&!r&&c();}if(typeof e.addEventListener=="function"){for(let g of xd)e.addEventListener(g,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",p,{capture:true,passive:true}),m()&&(i=e.requestAnimationFrame?.(c)??null);}return {get engaged(){return n},stop:s}}async function Ir(t,e,n,r){let i=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),i}function ko(t,e){let n=false;return async r=>{let i=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),i}}function So(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 qg="GemWebSdkHandshake";var Ng=()=>Date.now();function Pd(t,e,n={}){let r=t[qg];if(r===void 0)return null;let i=n.ttlMs??9500,o=n.now??Ng,s=r.events.splice(0),a=r.times?.splice(0),l=0,d=0,m=false,c=o()-i;for(let p=s.length-1;p>=0;p--){let g=a?.[p];if(g!==void 0&&g<c){d+=1;continue}if(l+=1,e(s[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}var Ro=new WeakMap,Td=new WeakSet,xo=new Set,Mr=new Set,Or=[],Et=null,Ao=false,jg=1920;function Po(t){return Ro.get(t)}function To(t){return !Ao||Td.has(t)}function Eo(t){return t.kind==="webgpu"?true:t.kind!=="webgl"&&t.kind!=="webgl2"&&t.kind!=="experimental-webgl"?false:t.context.getContextAttributes()?.preserveDrawingBuffer!==true}function Ed(t=globalThis.window){if(Ao||!t?.HTMLCanvasElement||typeof t.requestAnimationFrame!="function")return;Ao=true;for(let o of Array.from(t.document?.querySelectorAll("canvas")??[]))Td.add(o);let e=t.HTMLCanvasElement.prototype,n=e.getContext;e.getContext=function(o,...s){let a=n.call(this,o,...s);if(a&&!Ro.has(this)){let l={kind:o,context:a};Ro.set(this,l),Eo(l)&&xo.add(this);}return a};let r=t.requestAnimationFrame,i=t.cancelAnimationFrame;t.requestAnimationFrame=o=>{let s=r.call(t,a=>{Mr.delete(s);try{o(a);}finally{Ug();}});return Mr.add(s),Md(),s},t.cancelAnimationFrame=o=>{Mr.delete(o),i.call(t,o);};}function Cd(t,e){return new Promise(n=>{let r={canvas:t,done:o=>{clearTimeout(i),Or=Or.filter(s=>s!==r),n(o);}},i=setTimeout(()=>r.done(null),e);Or.push(r);})}function Id(t){return Et?.canvas===t?Et.bitmap:null}function Ug(){for(let t of Or){let e;try{e=Co(t.canvas);}catch(n){t.done(Promise.reject(n));continue}e&&t.done(createImageBitmap(t.canvas));}Mr.size===0&&Bg();}function Bg(){let t=null;for(let r of xo)r.isConnected?(!t||r.width*r.height>t.width*t.height)&&(t=r):xo.delete(r);if(!t||t.width===0||t.height===0)return;let e=Math.min(1,jg/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"}:{};Md(),Et={canvas:t,bitmap:createImageBitmap(t,n).catch(()=>null)};}function Md(){Et&&(Et.bitmap.then(t=>t?.close()),Et=null);}function Co(t){let e=Wg();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 hn;function Wg(){if(hn!==void 0)return hn;if(typeof OffscreenCanvas=="function")hn=new OffscreenCanvas(8,8).getContext("2d",{willReadFrequently:true});else {let t=globalThis.document?.createElement("canvas");t&&(t.width=t.height=8),hn=t?.getContext("2d",{willReadFrequently:true})??null;}return hn??null}var Io=false;async function Dd(t,e,n,r){if(Io){e.close(),n("busy",true);return}Io=true;let i=null;try{let o=await Kg(t,r);if(typeof o=="string"){e.close(),n(o,Hg(o));return}i=o;let a=await(r.encodeRef??(l=>Qg(l,r)))(i);if(i.close(),i=null,a===null){e.close(),n("failed",!0);return}if(a.size>Xg){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{Io=false,i?.close();}}function Hg(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 Vg=600;async function Kg(t,e){if(e.handler){let i=await e.handler(t);return i===null?"declined":Od(i,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=Yg(n);if(!r)return "no_source";try{let i=await Jg(r);return typeof i=="string"?i:Od(i,t)}catch(i){if(i instanceof DOMException&&i.name==="SecurityError")return "tainted";throw i}}async function Jg(t){let e=zg(t);if(typeof e=="string")return e;if(e.kind.includes("webgl")&&!e.context.getContextAttributes())return "unsupported";if(!Eo(e))return createImageBitmap(t);let n=await Cd(t,Vg);if(n)return n;let r=await Id(t);return r&&Co(r)?createImageBitmap(r):e.kind==="webgpu"?"unreadable":"unsupported"}function zg(t){let e=Po(t);if(e)return e;if(!To(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 Yg(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||!Po(r)&&!To(r)||i>n&&(e=r,n=i);}return e}async function Od(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 Xg=8*1024*1024,Gd="image/webp",Ld=.92;async function Qg(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:Gd,quality:Ld});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),Gd,Ld);})}async function Fd(t,e){if(!e)return;let n;try{n=await Zg(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 Zg(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 $d=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function qd(t=globalThis){let n=t[$d];if(n!==void 0)return n;let r=false,i=()=>r,o=[],s=ey(t,i);s!==null&&o.push(s);let a=ty(t,i);a!==null&&o.push(a);let l={get muted(){return r},setMuted(d){let m=!!d;if(m!==r){r=m;for(let c of o)c();}}};return Object.defineProperty(t,$d,{value:l,configurable:true}),l}function ey(t,e){let n=t.AudioNode?.prototype,r=t.AudioDestinationNode;if(n===void 0||r===void 0)return null;let i=t.OfflineAudioContext,o=n.connect,s=n.disconnect,a=new Map,l=m=>{let c=m.gain,p=m.context.currentTime;c.cancelScheduledValues(p),e()?c.setValueAtTime(0,p):c.setTargetAtTime(1,p,.01);},d=m=>{let c=m.context;if(i!==void 0&&c instanceof i)return null;let p=a.get(c);return p===void 0&&(p=c.createGain(),p.gain.value=e()?0:1,o.call(p,m),a.set(c,p)),p};return n.connect=function(...c){let[p,...g]=c;if(p instanceof r){let y;try{y=d(p);}catch{y=null;}if(y!==null)return o.call(this,y,...g),p}return o.apply(this,c)},n.disconnect=function(...c){let[p,...g]=c;if(p instanceof r){let y=a.get(p.context);if(y!==void 0&&y!==this)try{return s.call(this,y,...g)}catch{}}return s.apply(this,c)},()=>{for(let[m,c]of a){if(m.state==="closed"){a.delete(m);continue}try{l(c);}catch{}}}}function ty(t,e){let n=t.HTMLMediaElement;if(n===void 0)return null;let r=n.prototype,i=Object.getOwnPropertyDescriptor(r,"muted"),o=i?.get,s=i?.set;if(o===void 0||s===void 0)return null;let a=r.play,l=new WeakMap,d=new WeakSet,m=new Set,c=p=>{l.has(p)||l.set(p,!!o.call(p)),d.has(p)||(d.add(p),m.add(new WeakRef(p))),s.call(p,(l.get(p)??false)||e());};return Object.defineProperty(r,"muted",{configurable:true,enumerable:i?.enumerable??true,get(){let p=l.get(this);return p===void 0?!!o.call(this):p},set(p){l.set(this,!!p),c(this);}}),r.play=function(){try{c(this);}catch{}return a.call(this)},t.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof n)try{c(g);}catch{}},true),()=>{for(let p of m){let g=p.deref();if(g===void 0){m.delete(p);continue}try{s.call(g,(l.get(g)??!1)||e());}catch{}}}}var ny=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",ry=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',iy=`${ny}${ry}`,Mo=new WeakSet;function Nd(t=globalThis.document){if(t==null||Mo.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(iy),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],Mo.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"),Mo.add(t),"inline")}catch{return null}}function jd(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,m=[],c=false,p=0,g=null,y=[],v=()=>i&&!o&&!s,S=()=>{l=null,d=null,m=[],p=0,g=null,y=[];},R=k=>{if(a=null,!v()){S();return}if(d!==null&&m.push(k-d),d=k,l===null)l=k;else {let C=k-l;if(C>=e&&m.length>0){if(c){let T=g===null?C:r()-g;t.report(ay(p,y,C,T));}else t.report(oy(m,C));l=k,m=[],p=0,y=[];}}P();},P=()=>{let k=n.requestAnimationFrame;typeof k=="function"&&(a=k.call(n,R));},h=()=>{if(v()){a===null&&(S(),P());return}a!==null&&(n.cancelAnimationFrame?.call(n,a),a=null),S();};return {setRequested(k){i=k,h();},setPaused(k){o=k,h();},draw(){if(!c){c=true,a!==null&&S();return}if(a===null||l===null)return;let k=r();g!==null&&y.length<1e3&&y.push(k-g),g=k,p+=1;},get running(){return a!==null},dispose(){s=true,h();}}}function oy(t,e){return {fps:t.length*1e3/e,frameTimeP95Ms:Ud(t),counts:"pageFrames"}}function ay(t,e,n,r){let i=r;return e.length>0&&(i=Ud(r>Math.max(...e)?[...e,r]:e)),{fps:t*1e3/n,frameTimeP95Ms:i,counts:"gameDraws"}}function Ud(t){let e=[...t].sort((r,i)=>r-i),n=Math.max(1,Math.ceil(e.length*.95));return e[n-1]}var Gr=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function Bd(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function Wd(t,e){t!==null&&(t.style.setProperty(Gr.top,`${e.top}px`),t.style.setProperty(Gr.right,`${e.right}px`),t.style.setProperty(Gr.bottom,`${e.bottom}px`),t.style.setProperty(Gr.left,`${e.left}px`));}var Lr=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 Hd(){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 sy(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 m=l.control;l.control=m?{top:Math.min(m.top,d.y),bottom:Math.max(m.bottom,d.y+d.height)}:{top:d.y,bottom:d.y+d.height};}}return n}function Vd(t,e,n){if(t===null)return;let r=sy(e,n);for(let i of ["tl","tr","bl","br"]){t.style.setProperty(Lr[i].width,`${r[i].width}px`),t.style.setProperty(Lr[i].height,`${r[i].height}px`);let o=r[i].control;t.style.setProperty(Lr[i].centerY,o?`${(o.top+o.bottom)/2}px`:""),t.style.setProperty(Lr[i].controlHeight,o?`${o.bottom-o.top}px`:"");}}var ly=3e4,Dr=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function Kd(t){let e=t.clock??he,n=t.timeoutMs??ly,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((m,c)=>{let p=`ls${++o}`,g=e.setTimeout(()=>{r.delete(p),i.delete(a),c(new Dr("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:m,reject:c,timer:g}),t.bridge.requestLocalServer(p,a)||(s(p),m());});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 Dr(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 bn={url:"https://downloads.indiegems.games/sdk/v15.0.0/gem-web-sdk.devtools.min.js",integrity:"sha384-FO4DE3pawELjLb2ZWvoN5n2J5+azKiRhkhbhIiF8VdxW4lZ+Wp31MgEOiFenXow1"};var Ct=null;function dy(){return Ct!==null||(Ct=new Promise((t,e)=>{let n=document.createElement("script");n.src=bn.url,n.integrity=bn.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){Ct=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${bn.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{Ct=null,e(new Error(`gem devtools: could not load ${bn.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);})),Ct}function Jd(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 dy();return !e()||s!==r?false:(n!==null||(n=a.mount(t(),{openedBy:o,text:ht,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 cy=1e4,zd={reason:"unavailable",retryable:false};function Yd(t){let e=new Map,n=null,r=null,i=0,o=(d,m)=>{m.timer=t.clock.setTimeout(()=>{e.delete(d),m.reject({reason:"timeout",retryable:true});},t.timeoutMs??cy);},s=(d,m)=>{let c=a(d);c&&m(c);},a=d=>{let m=e.get(d);return m?(e.delete(d),t.clock.clearTimeout(m.timer),m):null},l=new mt({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((m,c)=>{let p=t.bridge.currentState;if(p==="refused"||p==="closed"){c(zd);return}let g=`t${++i}`,y={resolve:m,reject:c,reason:d,timer:null,held:p!=="connected"};e.set(g,y),o(g,y),y.held||t.bridge.requestToken(g,d);})});return {source:l,onToken(d){let m={token:d.token,expiresAt:d.expiresAt,chainEndsAt:d.chainEndsAt};if(n={playerId:d.playerId,gameId:d.gameId,channel:d.channel},r=d.gameVersion??null,d.requestId!==void 0&&e.has(d.requestId)){s(d.requestId,c=>c.resolve(m));return}l.accept(m);},onDenied(d){s(d.requestId,m=>m.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[m,c]of e)c.held&&(c.held=false,t.clock.clearTimeout(c.timer),o(m,c),t.bridge.requestToken(m,c.reason));else if(d==="refused"||d==="closed")for(let m of [...e.keys()])s(m,c=>c.reject(zd));},get identity(){return n},get gameVersion(){return r}}}function uy(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var my=new Set(ii);function py(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))my.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function Fr(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return _a(async(n,r)=>{let i;try{i=new URL(t.baseUrl.replace(/\/+$/,""));}catch{throw new se("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 se(`${JSON.stringify(typeof n.path=="string"?uy(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 se(`${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 g=i.username!==""||i.password!=="",y=o.username!==i.username||o.password!==i.password,v=g?y?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new se(`the ${v} 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[g,y]of Object.entries(t.defaultQuery??{}))o.searchParams.has(g)||o.searchParams.set(g,y);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 se(`the body of ${n.method} ${JSON.stringify(o.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(o.toString(),{method:n.method,headers:{authorization:`Bearer ${r}`,...a===void 0?{}:{"content-type":a},...py(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 m=l.headers.get("etag"),c=gy(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...m===null?{}:{etag:m},...c===void 0?{}:{retryAfterSeconds:c},...p===null||p===""?{}:{invocationId:p}}},t)}function gy(t){if(t===null)return;let e=t.trim();if(!/^\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)?n:void 0}var yy=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),Go="embedder_relay_unavailable",fy="embedder_no_relay",hy=new Set([Go]),Lo=new Set([fy]),vn=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new Oo(this)}handleEvent(e){let n=this.pending.get(e.matchId);if(n!==void 0){if(e.event==="matchEnded"){n.refuse(new w("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 w("signaling_failed","the parent relayed an answer with no SDP in it"));return}n.settle({sdp:e.sdp});return}n.refuse(by(e.code,e.message));}}register(e,n){this.pending.get(e)?.refuse(new w("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 w("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 w("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 by(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new w(vy(t),r,{platformCode:t})}function vy(t){return t===void 0||hy.has(t)?"signaling_failed":Lo.has(t)?"offer_refused":yy.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var Oo=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,n){if(this.closed)return Promise.reject(new w("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 w("aborted","the caller aborted before the offer was sent")):new Promise((i,o)=>{let s=()=>{a(),o(new w("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 w?d:new w("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var Xd="match_ended:",Qd="server_shutdown:",Zd="kicked:",_y=123;function wy(t){if(typeof t!="string"||t.length===0||t.length>_y)return {kind:"other"};if(t.startsWith(Xd)){let e=wt(t.slice(Xd.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(Qd)?{kind:"server_shutdown",cause:t.slice(Qd.length)}:t.startsWith(Zd)?{kind:"kicked",detail:t.slice(Zd.length)}:{kind:"other"}}function Do(t,e,n){let r=wy(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 Fo(){return {exchange(){return Promise.reject(new w("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 ky=3e3,Sy=1e4,Ry=15e3;async function $r(t){let e=t.peerConnection;try{tc(t,"before the handshake started"),$o(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 Py(e,t),$o(t);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new w("invalid_sdp","the offer carried no SDP");We(i,"offer"),ec(i,"offer");let o=await Ay(t,i);if($o(t),typeof o?.sdp!="string")throw new w("invalid_sdp","the signaling channel answered without an SDP");return We(o.sdp,"answer"),ec(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await Ty(n,t),tc(t,"before the channel opened"),n}catch(n){throw e.close(),xy(n)}}function xy(t){return t instanceof w?t:ic(t)?nt():new w("connection_failed",oc(t),{cause:t})}function ec(t,e){if(Pr(t))throw new w("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 Ay(t,e){let n=t.exchangeTimeoutMs??Sy,r=rc(t,n),i=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(o=>{throw o instanceof w?o:ic(o)?nt():new w("signaling_failed",oc(o),{cause:o})});return Ey(i,t,r,()=>r.exhausted?qo("while the offer was in flight"):new w("timeout",`no answer arrived within ${n}ms`))}function Py(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??ky);t.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function Ty(t,e){if(e.signal?.aborted)return Promise.reject(nt());if(t.readyState==="open")return Promise.resolve();if(t.readyState!=="connecting")return Promise.reject(new w("connection_failed",`the data channel was already '${t.readyState}' when the answer was applied`));let{clock:n}=e,r=e.openTimeoutMs??Ry,i=rc(e,r);return new Promise((o,s)=>{let a=()=>{n.clearTimeout(p),t.removeEventListener("open",l),t.removeEventListener("close",d),t.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{a(),o();},d=g=>{a(),s(new w("connection_failed","the data channel failed before it opened",nc(g)===void 0?void 0:{cause:nc(g)}));},m=()=>{a(),s(nt());},c=()=>{a(),s(i.exhausted?qo("while the channel was still opening"):new w("timeout",`the data channel did not open within ${r}ms`));},p=n.setTimeout(c,i.ms);t.addEventListener("open",l),t.addEventListener("close",d),t.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function rc(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 Ey(t,e,n,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(nt()):new Promise((s,a)=>{let l=c=>{i.clearTimeout(m),o?.removeEventListener("abort",d),c();},d=()=>l(()=>a(nt())),m=i.setTimeout(()=>l(()=>a(r())),n.ms);o?.addEventListener("abort",d),t.then(c=>l(()=>s(c)),c=>l(()=>a(c)));})}function tc(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw qo(`already ${e}`)}function qo(t){return new w("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function $o(t){if(t.signal?.aborted)throw nt()}function nt(){return new w("aborted","the caller aborted the connection attempt")}function ic(t){return t?.name==="AbortError"}function nc(t){return t?.error}function oc(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:[Y("sdp","sdp",H(10240)),V("sessionId","session_id",H(64))],error:[V("code","code",H(64)),V("message","message",H(256))],matchEnded:[V("reason","reason",H(64))]}));function pc(t){let{client:e,clock:n,rooms:r}=t,i=t.signaling??Fo,o=t.log??(h=>console.warn(h)),s=new xt({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,l=(h,k)=>{let C=a.get(h)??new Set;C.add(k),a.set(h,C);},d=(h,k)=>{let C=a.get(h);C!==void 0&&(C.delete(k),C.size===0&&a.delete(h));},m=async h=>{if(r.isHost&&!jo(r)&&r.currentRoom?.matchId===void 0){let k=ye(h.clusterTargetId);await r.startMatch({...k===void 0?{}:{clusterTargetId:k},...h.retry===void 0?{}:{retry:h.retry},...h.signal===void 0?{}:{signal:h.signal}});}return uc(r.matchConnectionState==="suspended"?await r.reconnectToMatch(No(h)):await r.awaitMatch(No(h)))},c=async h=>uc(await r.pollMatchStatus(No(h))),p=async(h,k)=>{let C=false;try{let T=await m(h),W=r.currentRoom?.transports;if(W!==void 0&&!W.includes("webrtc"))throw new w("misconfigured",`the room template offers (${W.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 F=h.peerConnection??mc();C=!0;let N=await $r({peerConnection:F,signaling:k,clock:n,matchId:T.matchId,credentialExpiresAt:T.credentialExpiresAt,...qr(h,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),E=null;if(h.presentCredential!==!1)try{E=await en({channel:N,clock:n,credential:T.joinCredential,credentialExpiresAt:T.credentialExpiresAt,...qr(h,"onMessage","signal"),...h.welcomeTimeoutMs===void 0?{}:{ceilingMs:h.welcomeTimeoutMs}});}catch(M){throw Ae(N),Ae(F),M}return $y(r,T,N,F,k,h.reportDisconnect!==!1,h.reportConnected!==!1,E,{remember:l,forget:d},h.onMatchEnded)}catch(T){throw C&&cc(s,T),Ae(k),T}},g=async(h,k,C,T,W,F)=>{if(h==="webtransport"){let B=T?.webtransport;if(B===void 0)throw new w("misconfigured","webtransport is not advertised");let K={credential:C.joinCredential,credentialExpiresAt:C.credentialExpiresAt,clock:n};if(typeof B.named_url=="string"&&B.named_url!==""){let te=Math.max(Math.floor(F/2),1e3);try{return await on({url:B.named_url,timeoutMs:te,log:o,...K})}catch(me){if(vr()!==null)throw me;return o(`[gem] webtransport named dial failed (${hr(me)}); retrying the pinned dial`),on({url:B.url,certHashBase64:B.cert_sha256_b64,timeoutMs:te,log:o,...K})}}return on({url:B.url,certHashBase64:B.cert_sha256_b64,timeoutMs:F,...K})}if(h==="websocket"){let B=T?.websocket;if(B===void 0)throw new w("misconfigured","websocket is not advertised");return eo({url:B.url,credential:C.joinCredential,credentialExpiresAt:C.credentialExpiresAt,clock:n,timeoutMs:F})}let N=k.peerConnection??mc(),E,M=await $r({peerConnection:N,signaling:W,clock:n,matchId:C.matchId,credentialExpiresAt:C.credentialExpiresAt,extraChannels:[{label:nn,ordered:false,maxRetransmits:0}],onExtraChannel:(B,K)=>{B===nn&&(E=K);},...qr(k,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...k.exchangeTimeoutMs===void 0&&k.redial===true?{exchangeTimeoutMs:My}:{}}),L;try{L=await en({channel:M,clock:n,credential:C.joinCredential,credentialExpiresAt:C.credentialExpiresAt,wire:fr,heartbeat:!0,...qr(k,"signal"),...k.welcomeTimeoutMs===void 0?{}:{ceilingMs:k.welcomeTimeoutMs}});}catch(B){throw Ae(M),Ae(N),B}let $=L.welcome.heartbeatIntervalMs;return {link:no(M,N,E,$===void 0?void 0:{clock:n,intervalMs:$}),welcome:L.welcome,channel:M,peerConnection:N}},y=(h,k,C,T,W)=>{let F=false,N;T.link.onClose($=>{!F&&h.reportDisconnect!==false&&Do(r,k.matchId,$),N?.($);}),h.reportDisconnect!==false&&h.reportConnected!==false&&r.notifyMatchConnected(k.matchId);let E={transport:T.link.transport,send:($,B)=>T.link.send($,B),onMessage:$=>T.link.onMessage($),onClose:$=>{N=$;},close:()=>T.link.close()},M=()=>{F||(F=true,Ae(T.link),Ae(W));},L=$=>{if(!F){try{h.onMatchEnded?.($);}catch{}M();}};return l(k.matchId,L),{matchId:k.matchId,transport:C,link:E,joinCredential:k.joinCredential,credentialExpiresAt:k.credentialExpiresAt,welcome:T.welcome,...T.channel===void 0?{}:{channel:T.channel},...T.peerConnection===void 0?{}:{peerConnection:T.peerConnection},close(){d(k.matchId,L),M();}}},v=async(h,k)=>{let C=r.currentRoom?.id,T=r.gameId,W=()=>({advert:rn(r.currentRoom?.settings,h),template:r.currentRoom?.transports??null});if(C===void 0||T===null)return W();try{let F=await e.get(`/v2/games/${encodeURIComponent(T)}/game-rooms/${encodeURIComponent(C)}`,k);return {advert:rn(F.settings,h),template:St(F.transports)??r.currentRoom?.transports??null}}catch{return W()}},S=(h,k)=>{let C=h??ac;return k.length===0?C:C.filter(T=>k.includes(T))},R=async(h,k,C)=>{try{let T=await m(h),{advert:W,template:F}=await v(T.matchId,h.signal),N=S(F,k),E=N.filter(z=>Ly(z,W)),M=vr();if(M!==null&&N.includes("webtransport")&&W?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${M} (learned on an earlier dial in this page)`),E.length===0){let z=F===null?`the default order (${ac.join(", ")})`:`the room template's transports (${F.join(", ")||"none"})`;throw new w("misconfigured",`none of ${z}`+(k.length>0?`, narrowed to (${k.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let L=h.transportAttemptTimeoutMs??Iy,$=()=>h.deadlineAt===void 0?1/0:h.deadlineAt-n.now(),B=z=>t.signalingReady===void 0||z<=0?Promise.resolve(!0):t.signalingReady(z),K=[],te=[];for(let z of E){if($()<lc){o(`[gem] ${z} rung not tried: the reconnect budget is spent`);break}te.length>0&&T.credentialExpiresAt-n.now()<dc&&(T=await c(h)),te.push(z);let qe=!1,_e=!1,pe={attempts:0,waitedMs:0};for(;;){if(z==="webrtc"&&h.redial===!0){let Z=Math.min(sc,$());await B(Z)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(Z)}ms; offering anyway`);}let Ne=Math.max(Math.min(L,$()),lc);try{return y(h,T,z,await g(z,h,T,W,C,Ne),C)}catch(Z){let J=Z instanceof w?Z:new w("connection_failed",Z instanceof Error?Z.message:String(Z),{cause:Z});if(z==="webrtc"&&cc(s,J),(J.reason==="credential_expired"||J.reason==="credential_reused")&&!qe){qe=!0,T=await c(h);continue}if(z==="webrtc"&&J.reason==="signaling_failed"&&J.platformCode===Go&&!_e){_e=!0;let oe=Math.min(sc,$());if(o(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(oe)}ms for the socket before offering again`),await B(oe))continue}if(J.reason==="join_rate_limited"){let oe=Gy(pe,Math.random,$());if(oe!==null){if(pe.attempts+=1,pe.waitedMs+=oe,o(`[gem] ${z} rung: the server is rate-limiting this player's joins; waiting ${Math.round(oe)}ms before presenting again (retry ${pe.attempts} of ${yc.maxAttempts})`),await mr(n,oe,h.signal),h.signal?.aborted)throw new w("aborted","the caller aborted while waiting out a join rate limit");T.credentialExpiresAt-n.now()<dc&&(T=await c(h));continue}}if(Oy.has(J.reason)||J.reason==="credential_expired"||z==="webrtc"&&gc(J)){o(`[gem] ${z} rung failed (${J.reason}): ${hr(J.cause??J)} \u2014 `+(te.length<E.length?`falling through to ${E[te.length]}`:"no rungs left")),K.push(J);break}throw o(`[gem] ${z} rung refused the session (${J.reason}): ${J.message}`),J}}}let me=K[K.length-1];throw me===void 0?new w("timeout",`the reconnect budget ran out before any transport (${E.join(", ")}) could be tried`):new w(me.reason,`every transport tried (${te.join(", ")}) failed; the last said: ${me.message}`,{cause:K,platformCode:me.platformCode})}catch(T){throw Ae(C),T}};return {listClusterTargets:async(h={})=>qi({client:e,...h}),handleMatchEnded(h,k){let C=a.get(h);if(C!==void 0){a.delete(h);for(let T of C)T(k);}},connect:(async(h={})=>{let k=h.signaling??i();return h.transports===void 0?p(h,k):R(h,h.transports,k)})}}var ac=["webtransport","webrtc","websocket"],Iy=1e4,My=5e3,sc=3e3,lc=1e3,dc=1e4,Oy=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function gc(t){return t.platformCode!==void 0&&Lo.has(t.platformCode)}var yc={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function Gy(t,e=Math.random,n=1/0){let r=yc;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 Ly(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&br():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||Dy(e.websocket.url)}function Dy(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return gt(e)}function No(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var Fy=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function cc(t,e){e instanceof w&&(!Fy.has(e.reason)&&!gc(e)||t.report([{type:"connection_failures_total",value:1}]));}function $y(t,e,n,r,i,o,s,a,l,d){let m=false,c=()=>{m||Do(t,e.matchId,void 0);};o&&(n.addEventListener("close",c),s&&t.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,n.removeEventListener("close",c),a?.detach(),Ae(n),Ae(r),Ae(i));},g=y=>{if(!m){try{d?.(y);}catch{}p();}};return l.remember(e.matchId,g),{matchId:e.matchId,channel:n,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:a?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function jo(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function uc(t){if(t.status==="failed")throw new w("allocation_failed",`match ${t.matchId} did not come up: ${t.reason}`);if(t.status==="ended")throw new w("match_ended",`match ${t.matchId} ended (${t.reason}) before this side connected.`);if(t.protocol!==ur)throw new w("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${ur}' 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 w("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 mc(){let t=globalThis.RTCPeerConnection;if(!t)throw new w("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 Ae(t){try{t.close();}catch{}}function qr(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var qy=1e4;function fc(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 mt({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??qy);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 Bo={};Au(Bo,{acceptTransfer:()=>Ny,addEntityProgression:()=>jy,adminAction:()=>Uy,cancelInventoryTransfer:()=>By,claimEntityProgressionRewards:()=>Wy,closeGameRoom:()=>Hy,createEntityBatchOrder:()=>Vy,createEntityOrder:()=>Ky,createSession:()=>Jy,deleteEntityGameSetting:()=>zy,deleteEntitySave:()=>Yy,deleteSession:()=>Xy,deleteShowcaseValue:()=>Qy,executeEntityRecipe:()=>Zy,finalizeSaveUpload:()=>ef,getChannelAssignment:()=>tf,getDropRates:()=>nf,getEntityCurrency:()=>rf,getEntityGameSetting:()=>of,getEntityInventory:()=>af,getEntityInventoryItem:()=>sf,getEntityLeaderboard:()=>lf,getEntityOrder:()=>df,getEntityProgression:()=>cf,getEntityRecipeAvailability:()=>uf,getEntityRecipeUsage:()=>mf,getEntitySave:()=>pf,getEvent:()=>gf,getGameRoomV2:()=>yf,getLeaderboard:()=>ff,getPlayerGameProfile:()=>hf,getPurchaseCatalog:()=>bf,getResolvedTemplate:()=>vf,getRoomArgs:()=>_f,getShowcaseValue:()=>wf,getTransferDetails:()=>kf,ingestAnalyticsEvents:()=>Uo,initiateInventoryTransfer:()=>Sf,invokeFunction:()=>Rf,kickPlayer:()=>xf,listChallenges:()=>Af,listEntityGameSettings:()=>Pf,listEntityOrders:()=>Tf,listEntityProgressions:()=>Ef,listEntitySaves:()=>Cf,listEvents:()=>If,listGameRooms:()=>Mf,listResolvedTemplates:()=>Of,listTransfers:()=>Gf,maxEntityProgression:()=>Lf,putEntityGameSetting:()=>Df,putRoomArgs:()=>Ff,putShowcaseValue:()=>$f,rejectTransfer:()=>qf,reportMatchPlayers:()=>Nf,requestSaveUploadUrl:()=>jf,resetEntityProgression:()=>Uf,setMatchBackfill:()=>Bf,simulateEntityOrder:()=>Wf,transferHostV2:()=>Hf,updateGameRoomV2:()=>Vf});function b(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 Ny(t,e,n){let r=`/v1/inventory/transfers/${b(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function jy(t,e,n,r,i,o){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/add`;return t.client.post(s,i,o?.signal)}async function Uy(t,e,n,r){let i=`/v1/voice/sessions/${b(e)}/admin`;return t.client.post(i,n,r?.signal)}async function By(t,e,n){let r=`/v1/inventory/transfers/${b(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Wy(t,e,n,r,i,o){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/claim`;return t.client.post(s,i,o?.signal)}async function Hy(t,e,n){let r=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}`;return t.client.delete(r,n?.signal)}async function Vy(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/orders/batch`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Ky(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/orders`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Jy(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function zy(t,e,n,r,i){let o=`/v1/settings/${b(e)}/${b(n)}/${b(r)}`;return t.client.delete(o,i?.signal)}async function Yy(t,e,n,r,i){let o=`/v1/saves/${b(e)}/${b(n)}/${b(r)}`;return t.client.delete(o,i?.signal)}async function Xy(t,e,n){let r=`/v1/voice/sessions/${b(e)}`;return t.client.delete(r,n?.signal)}async function Qy(t,e,n,r){let i=`/v1/showcase/players/${b(e)}/${b(n)}`;return t.client.delete(i,r?.signal)}async function Zy(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/recipes/execute`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function ef(t,e,n,r,i,o){let s=`/v1/saves/${b(e)}/${b(n)}/${b(r)}/finalize`;return t.client.post(s,i,o?.signal)}async function tf(t,e,n){let r=`/v1/games/${b(t.gameId())}/config/channels/${b(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function nf(t,e,n){let r=`/v1/inventory/loot-tables/${b(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function rf(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/currencies/${b(r)}`;return t.client.get(o,i?.signal)}async function of(t,e,n,r,i){let o=`/v1/settings/${b(e)}/${b(n)}/${b(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function af(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/${b(e)}/${b(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function sf(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/items/${b(r)}`;return t.client.get(o,i?.signal)}async function lf(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/${b(e)}/${b(n)}/${b(r)}`+(s?`?${s}`:"");return t.client.get(a,i?.signal)}async function df(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/orders/${b(r)}`;return t.client.get(o,i?.signal)}async function cf(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}`;return t.client.get(o,i?.signal)}async function uf(t,e,n,r,i,o){let s=`/v1/inventory/${b(e)}/${b(n)}/catalogs/${b(r)}/recipes/${b(i)}/availability`;return t.client.get(s,o?.signal)}async function mf(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/${b(e)}/${b(n)}/recipe-usage`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function pf(t,e,n,r,i){let o=`/v1/saves/${b(e)}/${b(n)}/${b(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function gf(t,e,n){let r=`/v1/events/${b(e)}`;return t.client.get(r,n?.signal)}async function yf(t,e,n){let r=`/v2/games/${b(t.gameId())}/game-rooms/${b(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function ff(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/${b(e)}`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function hf(t,e,n){let r=`/v1/profiles/players/${b(e)}`;return t.client.get(r,n?.signal)}async function bf(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 vf(t,e,n){let r=`/v1/game-room-templates/${b(e)}`;return t.client.get(r,n?.signal)}async function _f(t,e,n){let r=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}/room-args`;return t.client.get(r,n?.signal)}async function wf(t,e,n,r){let i=`/v1/showcase/players/${b(e)}/${b(n)}`;return t.client.get(i,r?.signal)}async function kf(t,e,n){let r=`/v1/inventory/transfers/${b(e)}`;return t.client.get(r,n?.signal)}async function Uo(t,e,n){let r=`/v1/games/${b(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true,retryRateLimited:false})}async function Sf(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function Rf(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function xf(t,e,n,r){let i=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}/kick/${b(n)}`;return t.client.post(i,void 0,r?.signal)}async function Af(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 Pf(t,e,n,r){let i=`/v1/settings/${b(e)}/${b(n)}`;return t.client.get(i,r?.signal)}async function Tf(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/${b(e)}/${b(n)}/orders`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Ef(t,e,n,r){let i=`/v1/inventory/${b(e)}/${b(n)}/progressions`;return t.client.get(i,r?.signal)}async function Cf(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/${b(e)}/${b(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function If(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 Mf(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/${b(t.gameId())}/game-rooms`+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function Of(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function Gf(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 Lf(t,e,n,r,i,o){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/max`;return t.client.post(s,i,o?.signal)}async function Df(t,e,n,r,i,o){let s=`/v1/settings/${b(e)}/${b(n)}/${b(r)}`;return t.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Ff(t,e,n,r){let i=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}/room-args`;return t.client.put(i,n,r?.signal)}async function $f(t,e,n,r,i){let o=`/v1/showcase/players/${b(e)}/${b(n)}`;return t.client.put(o,r,i?.signal)}async function qf(t,e,n){let r=`/v1/inventory/transfers/${b(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function Nf(t,e,n,r){let i=`/v1/games/${b(t.gameId())}/matches/${b(e)}/players/report`;return t.client.post(i,n,r?.signal)}async function jf(t,e,n,r,i,o){let s=`/v1/saves/${b(e)}/${b(n)}/${b(r)}/upload-url`;return t.client.post(s,i,o?.signal,{replaySafe:true})}async function Uf(t,e,n,r,i,o){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/reset`;return t.client.post(s,i,o?.signal)}async function Bf(t,e,n,r){let i=`/v1/games/${b(t.gameId())}/matches/${b(e)}/backfill`;return t.client.put(i,n,r?.signal)}async function Wf(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/orders/simulate`;return t.client.post(o,r,i?.signal)}async function Hf(t,e,n,r){let i=`/v2/games/${b(t.gameId())}/game-rooms/${b(e)}/transfer/${b(n)}`;return t.client.post(i,void 0,r?.signal)}async function Vf(t,e,n,r){let i=`/v2/games/${b(t.gameId())}/game-rooms/${b(e)}`;return t.client.patch(i,n,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var Kf=1e4,Jf=50,zf=1e3,Yf=65536-4*1024,hc=t=>typeof t=="number"?t:0,Xf=t=>typeof t=="string"?t:"";function bc(){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 Qf(t){return t?.retryable===true}function Zf(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(i=>{let o=i??{};return {index:hc(o.index),code:Xf(o.code)}}):[];return {accepted:hc(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function vc(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 _c(t){let e=Math.max(1,Math.floor(t.maxQueue??zf)),n={client:t.client,gameId:()=>t.gameId},r=[],i=0,o=null,s=false,a=null,l=0,d=0,m=false,c=false,p=h=>{t.log?.(h);},g=()=>{o!==null&&(t.clock.clearTimeout(o),o=null);},y=()=>Math.max(0,d-t.clock.now()),v=()=>{o!==null||s||a!==null||(o=t.clock.setTimeout(()=>{o=null,R().catch(()=>{});},Math.max(Kf,y())));},S=()=>{let h=Math.min(r.length,100),k=128;for(let C=0;C<h;C+=1){let T=r[C];if(T===void 0)break;if(k+=JSON.stringify(vc(T,0)).length+1,k>Yf)return Math.max(1,C)}return h};async function R(h){for(;a!==null;)await a.catch(()=>{});if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};let k=P(h);a=k;try{return await k}finally{a===k&&(a=null),r.length>0&&v();}}async function P(h){g();let k=r.splice(0,S()),C=i;i=0;let T=Math.round(t.clock.now()),W={batch_id:bc(),sent_at_ms:T,events:k.map(F=>vc(F,T))};try{let F=await Uo(n,W,h===void 0?void 0:{signal:h}),N=Zf(F,C);l=0,d=0;for(let E of N.rejected)p(`[gem] analytics: an event was refused (${E.code}). See the analytics_events section of your game config.`);return N}catch(F){if(Qf(F)){for(r=[...k,...r],i+=C;r.length>e;)r.shift(),i+=1;l+=1,d=t.clock.now()+dr(l,F);}else p(`[gem] analytics: ${k.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(F)}`);throw F}}return {track(h,k,C={}){if(s)return;if(typeof h!="string"||h===""){c||(c=true,p(`[gem] analytics: '${k}' 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(k.startsWith(Ci)){m||(m=true,p(`[gem] analytics: '${k}' 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={},W={};for(let[F,N]of Object.entries(C))typeof N=="string"?T[F]=N:typeof N=="number"&&Number.isFinite(N)&&(W[F]=N);for(;r.length>=e;)r.shift(),i+=1;r.push({uid:bc(),playerId:h,name:k,atMs:t.clock.now(),dimensions:T,measures:W}),r.length>=Jf&&a===null&&y()===0?R().catch(()=>{}):v();},flush:h=>R(h),get pending(){return r.length},dispose(){s=true,g(),r=[],i=0;}}}function wc(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().");vt(r);let o=await t({player_id:n,...r===void 0?{}:{periods_back:r},...i===void 0?{}:{signal:i}});return tr(o)}}}function eh(t){let e={};for(let[n,r]of Object.entries(Bo))if(typeof r=="function"){let i=r;e[n]=(...o)=>i(t,...o);}return e}function kc(t,e={}){let n=e.clock??he,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=fc(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),o=Fr({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=eh({client:s,gameId:()=>a.gameId}),d=a.gameRoomId,m=t.endMatch,c=t.log,p=_c({client:s,clock:n,gameId:a.gameId,...typeof c=="function"?{log:y=>c.call(t,y)}:{}});return {identity:a,client:s,api:l,match:{end:async()=>{if(m===void 0)throw new Error("this runtime cannot end the match: the server image running this bundle predates host.endMatch, and only the platform half holds the allocation proof an end needs.");await m.call(t);},setBackfill:async(y,v)=>{let S=await l.setMatchBackfill(a.matchId,{open:y.open,...y.seats===void 0?{}:{seats:y.seats}},v===void 0?{}:{signal:v});return {open:S.open,seats:S.seats??null}},reportPlayers:async(y,v)=>(await l.reportMatchPlayers(a.matchId,{players:y.map(R=>({player_id:R.playerId,state:R.state}))},v===void 0?{}:{signal:v})).players.map(R=>({playerId:R.player_id,outcome:R.outcome}))},analytics:p,functions:new Xe(l.invokeFunction),challenges:wc(l.listChallenges),...d===void 0?{}:{room:{get:y=>l.getGameRoomV2(d,y),args:async y=>{let v=await l.getGameRoomV2(d,y?.signal===void 0?{}:{signal:y.signal}),S=v.modified?v.body:void 0;if(S?.room_args==null||S.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:S.room_args,room_args_template:S.room_args_template}}}},dispose:()=>{p.dispose(),i.dispose();}}}function rt(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function It(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function _n(t){return typeof t=="string"?t:t.slice().buffer}function Nr(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 th=5e3,Sc=3e4,Rc=2e3,nh=1e4,rh=3,xc=1;async function Ac(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?f=>console.info(f):e.log,o=f=>i?.(`[gem host] ${f}`),s=typeof t=="function"?t():t,a=Promise.resolve(),l=true,d=false,m=(f,I)=>{l&&(a=a.then(async()=>{if(!d)try{await I();}catch(D){o(`the bundle's ${f} handler threw: ${it(D)}. Serving continues.`);}}));},c=true,p,g,y,v=f=>{if(!c)return;c=false,m("leave",()=>s.leave?.(r,{cause:f??"left"}));let I=g;I&&queueMicrotask(()=>I(f));},S={send(f,I){if(!c)return;let D=It(rt(I));m("message",()=>s.message?.(r,f,typeof f=="string",{reliable:D.reliable,ordered:D.ordered}));},onMessage(f){p=f;},onClose(f){g=f;},close(){v("closed");}},R=(f,I)=>{if(!c)return;let D=It(rt(I));queueMicrotask(()=>{c&&p?.(f,D);});},P=new Map,h=f=>{let I=[];for(let D of $e){let Q=f.channels[D];try{Q.binaryType="arraybuffer";}catch{}let fe=It(D),An=lt=>{let Gt=Nr(lt?.data);Gt!==null&&m("message",()=>s.message?.(f.playerId,Gt.data,Gt.isText,{reliable:fe.reliable,ordered:fe.ordered}));};Q.addEventListener("message",An),I.push(()=>Q.removeEventListener("message",An));}P.get(f.playerId)?.forEach(D=>D()),P.set(f.playerId,I);},k=f=>{P.get(f)?.forEach(I=>I()),P.delete(f);},C=new Set,T=new Map,W=(f,I,D)=>({playerNumber:f.assignedPeerId,transport:"webrtc_p2p",...I?{rejoin:true}:{},...D?{superseded:true}:{}}),F=f=>{let I=P.has(f.playerId),D=C.has(f.playerId);C.add(f.playerId),h(f),I&&m("leave",()=>s.leave?.(f.playerId,{cause:"superseded"})),m("join",()=>s.join?.(f.playerId,W(f,D,I)));},N=new Set,E=(f,I,D)=>{if(f===r){R(I,D);return}let Q=n.peer(f);if(Q===null){let fe=T.get(f);if(fe!==void 0&&e.clock.now()-fe<Rc)return;N.has(f)||(N.add(f),o(`send to '${f}' dropped: no such connected player`));return}Q.send(_n(I),rt(D));},M={matchId:n.matchId,gameId:e.gameId,channel:e.channel,...e.gameRoomId===void 0?{}:{gameRoomId:e.gameRoomId},apiBaseUrl:e.apiBaseUrl,serverToken:()=>e.tokens.current(),onServerToken:f=>e.tokens.subscribe(f),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(f=>f.playerId)??[],players(){let f=c?[r]:[];for(let I of n.peers)f.push(I.playerId);return f},profile(f){let I=e.room()?.members.find(D=>D.playerId===f);if(!(!I||I.displayName===void 0))return {displayName:ht.toPlain(I.displayName),...I.displayTag===void 0?{}:{displayTag:ht.toPlain(I.displayTag)},...I.discriminator===void 0?{}:{discriminator:I.discriminator}}},playerNumber(f){return f===r?xc:n.peer(f)?.assignedPeerId},send(f,I,D){E(f,I,D);},broadcast(f,I){let D=I?.except;c&&r!==D&&R(f,I);for(let Q of n.peers)Q.playerId!==D&&Q.send(_n(f),rt(I));},async endMatch(){let f=await Ne();return f.answer!=="ok"&&o(f.cause),f.answer},kick(f,I){if(f===r){v(I??"kicked");return}n.kick(f).catch(D=>{o(`kick of '${f}' failed: ${it(D)}`);});},log(f){o(f);},warn(f){o(`\u26A0 ${f}`);}},L=()=>{},$=new Promise(f=>{L=f;}),B=[],K=null,te=async(f,I)=>{l=false;let D=a.then(async()=>{try{await s.shutdown(f);}catch(Q){o(`the bundle's shutdown threw: ${it(Q)}`);}});a=D,await D,Le();for(let Q of B.splice(0))Q();for(let Q of [...P.keys()])k(Q);v(I);},me=(f,I)=>K||(K=(async()=>{await te(I,f),n.close(),L();})(),K),z=()=>K||(K=(async()=>{await te({reason:"signal"},"left"),await n.leave().catch(f=>o(`leaving the match failed: ${it(f)}`)),L();})(),K),qe=()=>K||(K=(async()=>{l=false;let f=await Ne();f.answer==="ok"?(await te({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(o(`${f.cause}; leaving instead`),await te({reason:"signal"},"left"),await n.leave().catch(I=>o(`leaving the match failed: ${it(I)}`))),L();})(),K),_e=null,pe=()=>(_e??=kc(M,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),_e),Ne=async()=>{try{return await ks({client:pe().client,gameId:()=>M.gameId},M.matchId,{},{signal:AbortSignal.timeout(th)}),{answer:"ok"}}catch(f){return f instanceof O&&(f.reason==="forbidden"||f.reason==="not_found")?{answer:f.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${f.reason})`}:{answer:"failed",cause:`ending the match failed: ${it(f)}`}}},Z=null,J=false,oe=0,Re,je=null,Le=()=>{J=true,Z!==null&&(e.clock.clearTimeout(Z),Z=null),je?.(),je=null;},at=f=>{o(`heartbeats paused: ${f}; they resume when a fresh play token arrives`),Pe();let I=Re,D=false,Q=e.tokens.subscribe(fe=>{D||J||fe.token===I||Ot(fe)||(D=true,je?.(),je=null,oe=0,Re=void 0,Pe(),o("a fresh play token arrived; heartbeats resume"),Z=e.clock.setTimeout(()=>{Ue();},0));});D?Q():je=Q;},Pe=()=>{let f=_e;_e=null,f?.dispose();},Ot=f=>f.expiresAt*1e3<=e.clock.now(),Ue=async()=>{if(Z=null,!J){try{await pe().client.post(`/v1/games/${encodeURIComponent(M.gameId)}/matches/${encodeURIComponent(M.matchId)}/heartbeat`,void 0,AbortSignal.timeout(nh)),oe=0,Re=void 0;}catch(f){if(f instanceof O&&(f.reason==="forbidden"||f.reason==="not_found")){o(`the platform no longer holds this match under this host (${f.reason}); heartbeats stop`),Le();return}if(ih(f)){if(J)return;oe+=1;let I=e.tokens.current(),D=I===void 0?"this host holds no play token":Ot(I)?"this host's play token has expired":I.token===Re?"the platform refused this host's play token again":oe>=rh?`the platform refused this host's play token ${oe} times in a row`:null;if(Re=I?.token,D!==null){at(D);return}}else oe=0,Re=void 0;o(`heartbeat failed: ${it(f)}`);}J||(Z=e.clock.setTimeout(()=>{Ue();},Sc));}},Hr=()=>{J||Z!==null||(Z=e.clock.setTimeout(()=>{Ue();},Sc));};{let f=L;L=()=>{Le(),_e?.dispose(),_e=null,f();};}let st=Promise.resolve().then(()=>s.init(M));a=st.then(()=>{},()=>{}),m("join",()=>s.join?.(r,{playerNumber:xc,transport:"loopback"})),B.push(n.on("peerJoined",F)),B.push(n.on("peerLeft",(f,I)=>{k(f);let D=e.clock.now();for(let[Q,fe]of T)D-fe>=Rc&&T.delete(Q);T.set(f,D),N.delete(f),m("leave",()=>s.leave?.(f,{cause:I}));})),B.push(n.on("error",f=>{o(`\u26A0 session error: ${f.message}`);})),B.push(n.on("matchEnded",f=>{K||Wo(y,f),me("match ended",{reason:"match_ended",platform_reason:f});})),B.push(n.on("hostChanged",f=>{f!==r&&me("host migrated",{reason:"host_migrated"});}));for(let f of n.peers)F(f);try{await st,Hr();}catch(f){l=false,Le(),d=true;for(let I of B.splice(0))I();for(let I of [...P.keys()])k(I);throw n.leave().catch(()=>{}),L(),f}return {matchId:n.matchId,localLink:S,onMatchEnded(f){y=f;},end:qe,leave:z,stop:f=>me(f,{reason:"stopped"}),done:$}}function Wo(t,e){try{t?.(e);}catch{}}function ih(t){return t instanceof O&&t.status===401||re.isAuthError(t)}function it(t){return t instanceof Error?t.message:String(t)}function Ho(t,e){let n=async()=>{throw new w("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 Pc(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,i=new Map,o=async a=>{r.isHost&&!jo(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!==tt)return Ho("dedicated",d.matchId);let m=t.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return Ho("peer",d.matchId);let c=t.identity();if(c===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let p=m??await t.p2p.connect(s(l)),g=await Ac(a,{session:p,clock:t.clock,gameId:c.gameId,channel:c.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:t.apiBaseUrl(),tokens:t.tokens,room:t.room,localPlayerId:p.playerId!==""?p.playerId:c.playerId,...t.log===void 0?{}:{log:t.log},...t.fetch===void 0?{}:{fetch:t.fetch}});return i.set(d.matchId,g),g.done.then(()=>{i.get(d.matchId)===g&&i.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>g.end(),leave:()=>g.leave(),stop:()=>g.stop()}},async connect(a={}){let l=await o(a),d=a.onMatchEnded;if(l.protocol===tt){let g=i.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),lh(l.matchId,g,d);if(r.isHost)throw new Error("[gem] this player hosts the P2P match, so there is no one to connect TO yet. Call gem.match.serve(yourServer) first; connect() then resolves the loopback to your own bundle.");let y=await mn(),v=async()=>t.p2p.connect({...s(a),certificate:y}),S=await v(),R=ch(S,v,d,P=>{r.notifyMatchDisconnected(P).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(S.matchId,{redial:R.redial,abandon:R.abandon}),R.onClosed(()=>{e.get(S.matchId)?.abandon===R.abandon&&e.delete(S.matchId);})),R}let m=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??[]}),c=await m(),p=dh(c,m,r,n);return n&&(e.set(c.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(c.matchId)?.abandon===p.abandon&&e.delete(c.matchId);})),p},async redialMatch(a,l){let d=e.get(a);return d===void 0?"closed":d.redial(l)},abandonMatch(a,l){e.get(a)?.abandon(l);}}}var Tc="link_closed",oh="host_unreachable",ah=new Set(["failed","closed"]);function sh(t){return ah.has(t)?Tc:oh}function lh(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 dh(t,e,n,r){let i=t.matchId,o=t,s="connected",a,l,d=[],m=false,c=false,p=y=>{if(s!=="closed"){s="closed";for(let v of d.splice(0))v();l?.(y);}},g=y=>{y.link.onMessage((v,S)=>a?.(v,S)),y.link.onClose(v=>{if(y!==o||s==="closed")return;if(m||!r){p(v);return}let S=n.matchSession;if(S.phase==="suspended"&&S.matchId===i){s="suspended";return}p(v);});};return g(t),{matchId:i,protocol:"dedicated",get transport(){return o.transport},get state(){return s},send(y,v){s==="connected"&&o.link.send(y,v);},onMessage(y){a=y;},onClose(y){l=y;},close(){if(s!=="closed"){if(m=true,s==="suspended"){p("closed");return}o.close(),p("closed");}},async redial(y){if(s==="closed"||m)return "closed";if(c)return "connected";c=true;let v;try{v=await e(y===void 0?{}:{deadlineAt:y});}finally{c=false;}return m||s==="closed"?(v.close(),"closed"):(o=v,g(v),s="connected",n.notifyMatchConnected(i),"connected")},abandon(y){s!=="closed"&&(s==="connected"&&o.close(),p(y));},onClosed(y){s==="closed"?y():d.push(y);}}}function ch(t,e,n,r,i,o=false){let s=t.matchId,a=t,l,d,m=[],c=[],p=[],g=false,y=false,v=false,S=false,R="connected",P=E=>{if(g)return;g=true,R="closed";for(let L of m.splice(0))L();for(let L of c.splice(0))L();for(let L of p.splice(0))L();let M=d;M&&queueMicrotask(()=>M(E));},h=E=>{for(let M of m.splice(0))M();for(let M of $e){let L=E.channels[M];try{L.binaryType="arraybuffer";}catch{}let $=It(M),B=K=>{let te=Nr(K?.data);te!==null&&l?.(te.data,$);};L.addEventListener("message",B),m.push(()=>L.removeEventListener("message",B));}},k=()=>a.peer(a.hostPlayerId),C=E=>{if(!(g||a.isHost)&&R!=="suspended"){if(r?.(E),o){R="suspended";return}P(E);}},T=E=>{for(let M of $e){let L=E.channels[M];if(typeof L.addEventListener!="function")continue;let $=()=>{k()===E&&C(Tc);};L.addEventListener("close",$),m.push(()=>L.removeEventListener?.("close",$));}},W=E=>{h(E),T(E),!g&&(R="connected",i?.());},F=E=>{for(let M of c.splice(0))M();c.push(E.on("migrating",()=>{S=true;})),c.push(E.on("hostChanged",M=>{if(S=false,M===E.playerId){P("host_migrated_here");return}let L=k();L!==null&&W(L);})),c.push(E.on("peerJoined",M=>{M.playerId===E.hostPlayerId&&W(M);})),c.push(E.on("matchEnded",M=>{g||Wo(n,M),P(M);})),c.push(E.on("peerLeft",(M,L)=>{M===E.hostPlayerId&&C(sh(L));}));};F(a);let N=k();return N!==null&&W(N),{matchId:s,protocol:"p2p",get state(){return R},send(E,M){R==="connected"&&k()?.send(_n(E),rt(M));},onMessage(E){l=E;},onClose(E){d=E;},close(){y=true,P("closed"),a.leave().catch(()=>{});},async redial(){if(R==="closed")return "closed";if(R==="connected"||v)return "connected";if(S)throw new G("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");v=true;let E;try{for(let L of m.splice(0))L();for(let L of c.splice(0))L();a.close(),E=await e();}finally{v=false;}if(g)return y?E.leave().catch(()=>{}):E.close(),"closed";a=E,F(a);let M=k();if(M===null)throw a.close(),new G("connection_failed","this peer rejoined the match but the host never answered with a link");return W(M),"connected"},abandon(E){P(E);},onClosed(E){g?E():p.push(E);}}}function Ec(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 uh=12e4;function ot(t,e){return {outcome:t,reason:e}}function Cc(t){let e=false,n=new Map,r=(i,o,s,a)=>{if(!t.bridge.parentSupports(i))return Promise.resolve(ot("unavailable","error"));if(e)return Promise.resolve(ot("declined","busy"));let l=`purchase-${we()}`;return new Promise(d=>{let m={},c=g=>{n.delete(l)&&(e=false,t.clock.clearTimeout(m.timer),d(g));};e=true,n.set(l,{finish:c,check:s,label:a}),m.timer=t.clock.setTimeout(()=>c(ot("unavailable","error")),t.timeoutMs??uh);let p=false;try{p=o(l);}catch{}p||c(ot("unavailable","error"));})};return {api:{request(i){return r("purchases",o=>t.bridge.requestPurchase(o,i.kind,i.targetId,i.currencySlug,i.quantity,i.catalogId),o=>o===void 0?null:t.confirm(o),o=>`purchase ${JSON.stringify(o)}`)}},requestAvatar3d(i){return r("avatar3dPurchases",o=>t.bridge.requestAvatar3dPurchase(o,i.itemId,i.currencySlug),()=>t.confirmAvatar3d(i.itemId),()=>`3D avatar ${JSON.stringify(i.itemId)}`)},settle(i){let o=i.outcome==="ok"||i.outcome==="declined"?i.outcome:"unavailable",s=n.get(i.requestId);if(s===void 0){t.onDropped?.(`gem.purchaseResult (${o}) for an unknown requestId: `+JSON.stringify(i.requestId));return}let{finish:a}=s;if(o!=="ok"){a(ot(o,js(i.reason)));return}let l=i.purchaseId,d;try{d=s.check(l);}catch{d=Promise.resolve("unknown");}if(d===null){t.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),a(ot("unavailable","error"));return}(async()=>{let m;try{m=await d;}catch{m="unknown";}if(m==="granted"){a(l===void 0?{outcome:"ok"}:{outcome:"ok",purchaseId:l});return}m==="absent"&&t.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for "+s.label(l)),a(ot("unavailable","error"));})();}}}async function Ic(t,e){try{return (await is(t,e)).granted?"granted":"absent"}catch(n){return n instanceof O&&n.reason==="not_found"?"absent":"unknown"}}var mh="small_human",Mc=/^[a-z][a-z0-9_]{0,31}$/,Oc=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,ph=8;function Vo(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:mh,id:e,modelUrl:n,iconUrl:r}]}function gh(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 yh(t){let e=t??{},n=typeof e.item_id=="string"&&Oc.test(e.item_id)?e.item_id:void 0,r=typeof e.family=="string"&&Mc.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=nr(e.icon_url),l=nr(e.model_url),d=[];for(let m of Array.isArray(e.prices)?e.prices:[]){let c=m??{};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 fh(t){if(!Array.isArray(t))return [];let e=[];for(let n of t)if(typeof n=="string"&&Mc.test(n)&&!e.includes(n)&&e.push(n),e.length===ph)break;return e}function Gc(t){let e=new Set,n=Vo(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=Vo(i);if(!gh(n,o)){n=o;for(let s of [...e])try{s(o);}catch(a){r(a);}}}),{async families(){return fh(await t.configFamilies())},worn(i){let o=Vo(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=yh(s);a!==void 0&&o.push(a);}return o},purchase(i){let o=i?.itemId,s=i?.currencySlug;return typeof o!="string"||!Oc.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 Lc(t,e){try{return (await $a(t,e))?.owned===!0?"granted":"absent"}catch(n){return n instanceof O&&n.reason==="not_found"?"absent":"unknown"}}function Dc(t){return Qa(t)}var hh=6e5;function Fc(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-${we()}`;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??hh);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 bh=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid","gem_test_ads"]),vh=["utm_"];function $c(t){return bh.has(t)||vh.some(e=>t.startsWith(e))}var qc=16,Nc=512,_h=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,wh=/[\p{Cc}\p{Cf}]/u,kh=/\p{Cs}/u,Oe="[gem] gem.share.request:";function jc(t){let{frame:e,log:n}=t,r=false,i=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,o=s=>{n!==null&&(n===void 0?console.warn(s):n(s));};return {get available(){return i()!==null},request(s){let a=i();if(a===null)throw new Error(`${Oe} the arcade does not handle share here \u2014 check gem.share.available first`);if(s!==void 0&&(typeof s!="object"||s===null))throw new TypeError(`${Oe} pass { params }, or nothing`);let l=s?.params===void 0?{}:s.params;if(!Sh(l))throw new TypeError(`${Oe} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>qc)throw new TypeError(`${Oe} at most ${qc} params; got ${d.length}`);let m=[];for(let[c,p]of d){let g=JSON.stringify(c);if(!_h.test(c))throw new TypeError(`${Oe} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if($c(c))throw new TypeError(`${Oe} param ${g} is reserved: the arcade reads it itself and never forwards it`);if(typeof p!="string")throw new TypeError(`${Oe} param ${g}: values must be strings`);if(p.length>Nc)throw new TypeError(`${Oe} param ${g}: a value is at most ${Nc} characters`);if(wh.test(p))throw new TypeError(`${Oe} param ${g}: control and format characters are not allowed`);if(kh.test(p))throw new TypeError(`${Oe} param ${g}: a value must be well-formed text`);m.push({key:c,value:p});}!a.requestShare(m)&&!r&&(r=true,o("[gem] gem.share.request was not sent: more than 6 share requests in a minute. Call it from your Share button's click, not a loop."));}}}function Sh(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var Ph="(any-pointer: coarse)";function Th(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 Uc(t){let{frame:e,log:n}=t,r=t.environment??{navigator:typeof navigator>"u"?void 0:navigator,matchMedia:typeof matchMedia=="function"?m=>matchMedia(m):void 0},i=r.navigator,o,s=new Set,a=()=>typeof i?.vibrate!="function"||r.matchMedia===void 0?false:(o??=r.matchMedia(Ph),o.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(m,c)=>{s.has(m)||(s.add(m),n!==null&&(n===void 0?console.warn(c):n(c)));};return {get available(){return a()||l()},vibrate(m){let c=a();if(!c&&!l())return false;let p=Th(m);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(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(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 Mt=Math.PI/180,Ge=Object.freeze({touch:Object.freeze({yaw:1*Mt,pitch:.66*Mt}),mouse:Object.freeze({yaw:.5*Mt,pitch:.5*.77*Mt}),stick:Object.freeze({yaw:240*Mt,pitch:240*.77*Mt}),stickDeadzone:.1,stickCurve:2,touchPitchMin:.25}),Ko="[gem.controls]",Jo=Object.freeze({yaw:0,pitch:0}),jr=t=>Number.isFinite(t)?t:0,Bc=(t,e)=>({yaw:t+0,pitch:e+0});function Wc(t){let e=jr(t),n=(Math.abs(e)-Ge.stickDeadzone)/(1-Ge.stickDeadzone),r=Ge.stickCurve,i=(Math.exp(r*n)-1)/(Math.exp(r)-1);return Math.sign(e)*Math.min(1,Math.max(0,i))+0}function Eh(t){let e=Math.min(1,2*Math.abs(t)/Math.PI);return (1-Math.pow(e,.75))*(1-Ge.touchPitchMin)+Ge.touchPitchMin}function Hc(t,e){if(t===void 0)return {};if(typeof t!="object"||t===null)throw new TypeError(`${Ko} ${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(`${Ko} ${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(`${Ko} ${e}: invertY must be a boolean; got ${String(n.invertY)}`);return n}function Ch(t,e){let n=Hc(e,"look()"),r=n.sensitivity,i=n.gamepadSensitivity,o=n.invertY,s=a=>o??a?.invertLookY??false;return {fromPointer(a,l,d,m){let c=jr(a),p=jr(l);if(c===0&&p===0)return Jo;let g=t(),y=r??(g===null?void 0:g.lookSensitivity/100)??1,v=d==="touch"||d==="pen",S=v?Ge.touch:Ge.mouse,R=c*S.yaw*y,P=-p*S.pitch*y;return s(g)&&(P=-P),v&&m!==void 0&&Number.isFinite(m)&&P*m>0&&(P*=Eh(m)),Bc(R,P)},fromStick(a,l,d){let m=jr(d);if(m<=0)return Jo;let c=Wc(a),p=Wc(l);if(c===0&&p===0)return Jo;let g=t(),y=i??(g===null?void 0:g.gamepadLookSensitivity/100)??1,v=c*Ge.stick.yaw*m*y,S=-p*Ge.stick.pitch*m*y;return s(g)&&(S=-S),Bc(v,S)},set(a){let l=Hc(a,"set()");"sensitivity"in l&&(r=l.sensitivity),"gamepadSensitivity"in l&&(i=l.gamepadSensitivity),"invertY"in l&&(o=l.invertY);}}}function Vc(t){return {look:e=>Ch(t.recommended,e),LOOK_BASE:Ge}}var Kc=Object.freeze(["music","sfx","voice","eye","text","hint","speed","bright","controls","star"]),Jc=/^[A-Za-z0-9_-]{1,40}$/;function zo(t){return typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=1e6}function zc(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e.slice(0,40)}function Yc(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 Xc(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 Yc(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 Qc(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"||!Jc.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 m=zc(a.label);if(m===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:m,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 p=a.min??0,g=a.max??100,y=a.step??1;if(!zo(p)||!zo(g)||!zo(y)||p>=g||y<=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:m,kind:"slider",value:Yc(a.value,p,g,y),min:p,max:g,step:y};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 y=g,v=zc(y.label);typeof y.id!="string"||!Jc.test(y.id)||v===void 0||p.some(S=>S.id===y.id)||p.push({id:y.id,label:v});}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}c={id:l,label:m,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&&(Kc.includes(a.icon)?c.icon=a.icon:e(`${d} keeps the Arcade's generic icon: ${JSON.stringify(a.icon)} is not one of ${Kc.join(", ")}.`)),n.push(c);}return n}var Ih=500;function Zc(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")},m=()=>{if(n===null||o!==null)return;let c=JSON.stringify(n);if(c===r)return;let p=i+Ih-e.now();if(p>0){o=e.setTimeout(()=>{o=null,m();},p);return}t.frame().declareSettings(n)&&(r=c,i=e.now());};return {api:{declare(c){let p=Qc(c,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,m(),d())},onChange(c){if(typeof c!="function")return ()=>{};let p=g=>c(g);return s.add(p),()=>{s.delete(p);}}},forgetSent(){r=null,i=-1/0;},flush:m,onSettingChange(c){let p=n?.findIndex(R=>R.id===c.id)??-1,g=n?.[p];if(n===null||g===void 0)return;let y=Xc(g,c.value);if(y===void 0)return;let v=JSON.stringify(n);n=n.map((R,P)=>P===p?{...R,value:y}:R),r===v&&(r=JSON.stringify(n));let S={id:g.id,value:y};for(let R of [...s])try{R(S);}catch(P){console.error("[gem] a gem.settings.onChange handler threw:",P);}}}}function eu(t,e){return t==null?e?"low":"medium":t==="low"||t==="high"?t:"medium"}var Mh=/(?:Z|[+-]\d{2}:?\d{2})$/i;function tu(t){if(typeof t!="string"||!Mh.test(t))return;let e=Date.parse(t);return Number.isFinite(e)&&e>0?e:void 0}function wn(){return {declared:false,grantable:false,heldLimitReached:false}}function nu(t,e){let n=typeof t=="object"&&t!==null?t:{},r=tu(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=tu(a),d=n.held_limit_reached===true,m=a!=null,c=o!=null&&s===void 0;return {declared:true,grantable:n.grantable===true&&e&&s!==0&&!c&&!m&&!d,...s===void 0?{}:{remainingToday:s},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...i}}var Oh=18e4,Yo=32,Gh=/^[a-z0-9_-]+$/,Lh="rewarded_requires_user_gesture";function Dh(){let t=globalThis.navigator?.userActivation?.isActive;return typeof t=="boolean"?t:void 0}var Fh=1e3;function $h(){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<=Fh)return true}return false}var ru=1e4;function qh(t){return t==="interstitial"||t==="rewarded"}function iu(t){return typeof t=="string"&&t!==""&&t.length<=Yo&&Gh.test(t)}function Nh(t){let e=typeof t=="object"&&t!==null?t:{};return [e.name,e.reason,e.status].join()}function Ur(t){return typeof t=="string"?JSON.stringify(t):typeof t}function ou(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 m=t.log;if(m!==null)try{m===void 0?console.warn(`[gem] ${d}`):m(`[gem] ${d}`);}catch{}},l=d=>{let m=t.readAvailability;if(m===void 0)return Promise.resolve(wn());let c=r.get(d);if(c!==void 0)return c;let p=new Promise(g=>{let y={},v=h=>y.done===true?false:(y.done=true,t.clock.clearTimeout(y.timer),g(h),true),S=(h,k)=>{!v(wn())||i.has(h)||(i.add(h),o(`gem.ads.rewardedStatus("${d}") answered not grantable: ${k}. Said once.`));},R=h=>{S(Nh(h),`the read failed (${h instanceof Error?h.message:Ur(h)})`);},P;try{P=Promise.resolve(m(d,AbortSignal.timeout(ru)));}catch(h){P=Promise.reject(h);}y.timer=t.clock.setTimeout(()=>{S("timeout","no answer within 10 s");},ru),P.then(h=>{try{v(nu(h,t.bridge.parentSupports("ads")));}catch(k){R(k);}},R);});return r.set(d,p),p.then(()=>{r.get(d)===p&&r.delete(d);}),p};return {api:{rewardedStatus(d){return iu(d)?l(d):(o(`gem.ads.rewardedStatus(${Ur(d)}) answered not grantable: a placement is 1..${String(Yo)} 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 m=d?.placement,c=d?.format;if(!iu(m)||!qh(c))return o(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${Ur(m)}, format ${Ur(c)}. A placement is 1..${String(Yo)} 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 g;try{g=(t.userActivation??Dh)();}catch{g=void 0;}if(g===false)try{(t.recentGamepadInput??$h)()===!0&&(g=!0);}catch{}if(g===false){let y=`${Lh}: gem.ads.requestAd("${m}", '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(y),a(y),Promise.resolve({outcome:"no_ad"})}}let p=`ad-${we()}`;return new Promise(g=>{let y={},v=R=>{n.delete(p)&&(e=false,t.clock.clearTimeout(y.timer),g(R));};e=true,n.set(p,v),y.timer=t.clock.setTimeout(()=>{v({outcome:"unavailable"});},t.timeoutMs??Oh);let S=false;try{S=t.bridge.requestAd(p,m,c);}catch{}S||v({outcome:"no_ad"});})}},settle(d){let m=d.outcome==="shown"||d.outcome==="no_ad"?d.outcome:"unavailable",c=n.get(d.requestId);if(c===void 0){t.onDropped?.(`gem.adResult (${m}) for an unknown requestId: `+JSON.stringify(d.requestId));return}c({outcome:m});}}}var au=Object.freeze(["level_end","run_end","match_end","menu_return","other_break"]),su=18e4,jh=1e4,Uh=/^[a-z0-9_-]{1,32}$/;function lu(t){return typeof t=="string"?JSON.stringify(t):typeof t}var kn=Object.freeze({shown:false});function du(t){let e=new Map,n,r=false,i=o=>{try{t.onDropped?.(o);}catch{}return kn};return {api:{signal(o){try{if(!t.bridge.parentSupports("moments"))return r?Promise.resolve(kn):(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;if(!au.includes(s)||a!==void 0&&(typeof a!="string"||!Uh.test(a)))return Promise.resolve(i(`moments_invalid_argument: gem.moments.signal was called with arguments the SDK will not send: kind ${lu(s)}, placement ${lu(a)}. A kind is one of ${au.join(", ")}; a placement, when given, is 1..32 characters of a-z, 0-9, '-' and '_'. 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 l=t.clock.now();if(n!==void 0&&l-n<jh)return Promise.resolve(i(`moments_called_repeatedly: gem.moments.signal({ kind: '${s}' }) within 10 s of the last moment's answer (${String(l-n)} ms). One break, one signal, from the press that leaves it; never on a timer. Answering shown: false.`));let d=`moment-${we()}`;return new Promise(m=>{let c={},p=(y,v)=>{e.delete(d)&&(t.clock.clearTimeout(c.timer),v&&(n=t.clock.now()),m(y));};e.set(d,y=>p(y,!0)),c.timer=t.clock.setTimeout(()=>{e.has(d)&&(p(kn,!0),i(`moments_timeout: gem.moments.signal({ kind: '${s}' }) had no answer within ${String((t.timeoutMs??su)/1e3)} s. Answering shown: false.`));},t.timeoutMs??su);let g=!1;try{g=t.bridge.signalMoment(d,s,a);}catch{}g||p(kn,!1);})}catch{return Promise.resolve(kn)}}},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 Xo=16384;function cu(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:Bh(e)}function Bh(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 Wh=1e4,Hh=5e3;function uu(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=Hh){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(m),l(),a(e);},m=t.clock.setTimeout(()=>{l(),a(e);},s);r.push(d);})},put(s){if(!t.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let a=cu(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-${we()}`;return new Promise(m=>{let c={},p=y=>{i.delete(d)&&(t.clock.clearTimeout(c.timer),y==="stored"&&(e=l,n=true,o()),m(y));};i.set(d,p),c.timer=t.clock.setTimeout(()=>p("unavailable"),t.timeoutMs??Wh);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,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 Sn=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 Vh=/^[a-z0-9][a-z0-9_-]{0,39}$/;function Kh(t){return typeof t=="string"&&Vh.test(t)}function Br(t){if(t===null||Kh(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 mu(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Qo(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 Wr(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 pu(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Jh(t){let e=t.untrusted,n=De(e.displayName,"gem.player.displayName"),r=e.displayTag||e.displayHandle,i=r?De(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,m=t.avatar3dId,c={displayName:n,displayHandle:i??n,badges:(t.badges??[]).map(v=>({itemId:v.itemId,iconUrl:v.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),m&&l.test(m)&&(c.avatar3dId=m),t.avatar3dModelUrl&&(c.avatar3dModelUrl=t.avatar3dModelUrl),t.avatar3dIconUrl&&(c.avatar3dIconUrl=t.avatar3dIconUrl),t.avatars3d&&(c.avatars3d=t.avatars3d.filter(v=>l.test(v.id)&&/^[a-z][a-z0-9_]*$/.test(v.family)).filter((v,S,R)=>R.findIndex(P=>P.family==v.family)==S).map(({family:v,id:S,modelUrl:R,iconUrl:P})=>({family:v,id:S,modelUrl:R,iconUrl:P})));let p=t.boost,g=(p?.multipliers??[]).map(v=>({currencyId:v.currencyId,currencySlug:v.currencySlug,multiplier:v.multiplierBp/1e4})),y=g.some(v=>v.multiplier>1);return c.boost=y&&p?.expiresInDays?{active:y,multipliers:g,expiresInDays:p.expiresInDays}:{active:y,multipliers:g},c}var zh=1e4,Rn=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??he,this.inbound=new qt(this.clock),this.outbound=new qt(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=>mi(a,e.origin))||Fs(e.origin,this.options.selfOrigin)))return this.refuse(e,`embedder '${e.origin}' is not in allowedEmbedders`),this.state==="waiting"&&this.transition("refused"),false;if(this.state==="connected")return this.fail("handshake_duplicate","this document already has a port"),false;if(this.state!=="waiting")return false;let r=Fn["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!mi(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=$s(Ln,i.versions);return s===null?(o.onmessage=null,o.postMessage({gem:U,type:"gem.error",code:"version_mismatch",message:`frame supports v${Ln.min}..v${Ln.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:U,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:U,type:"gem.ready"});}settled(e=zh){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:U,type:"gem.progress",loaded:e,total:n});}requestToken(e,n){this.send({gem:U,type:"gem.requestToken",requestId:e,reason:n});}requestLocalServer(e,n){return this.parentSupports("localHost")?(this.send({gem:U,type:"gem.requestLocalServer",requestId:e,gameRoomId:n}),true):false}exit(e){this.send(e===void 0?{gem:U,type:"gem.exit"}:{gem:U,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:U,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:U,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.gated("audioState")?(this.send({gem:U,type:"gem.audioState",muted:e}),true):false}reportEngaged(){return this.engagedSent||!this.gated("engagement")||!this.send({gem:U,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(!this.gated("rewardCue"))return false;let n={gem:U,type:"gem.rewardCue",currencySlug:String(e.currencySlug).slice(0,32)};return e.expected!==void 0&&Number.isFinite(e.expected)&&e.expected>=1&&(n.expected=Math.min(1e9,Math.round(e.expected))),e.origin&&(n.origin={x:mu(e.origin.x),y:mu(e.origin.y)}),this.send(n),true}showPortraitBorders(e){let n=Br(e);return n===void 0||!this.gated("portraitBorders")?false:this.send(n===null?{gem:U,type:"gem.portraitBorders"}:{gem:U,type:"gem.portraitBorders",name:n})}setWalletVisible(e,n){return this.gated("walletDisplay")?this.send({gem:U,type:"gem.walletDisplay",...Qo(e,n?.only)}):false}setMenu(e){return this.gated("gameMenu")?this.send({gem:U,type:"gem.menu",...Wr(e)}):false}declareSettings(e){return this.gated("gameSettings")?this.send({gem:U,type:"gem.settingsDeclare",settings:e}):false}setGemCorner(e){return this.gated("gemCorner")?this.send({gem:U,type:"gem.gemCorner",corner:e}):false}requestShare(e){return this.gated("share")?this.send({gem:U,type:"gem.requestShare",params:e.map(({key:n,value:r})=>({key:n,value:r}))}):false}requestAvatarPicker(e){return this.gated("avatarPicker")?this.send({gem:U,type:"gem.requestAvatarPicker",...e==="2d"||e==="3d"?{tab:e}:{}}):false}requestVibrate(e){return this.gated("vibration")?this.send({gem:U,type:"gem.vibrate",pattern:[...e]}):false}reportFrameStats(e){return this.gated("frameStats")?(this.send({gem:U,type:"gem.frameStats",fps:pu(e.fps,1e3),frameTimeP95Ms:pu(e.frameTimeP95Ms,1e5),counts:e.counts==="gameDraws"?"gameDraws":"pageFrames"}),true):false}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:U,type:"gem.gameContext",context:e}),true)}signal(e,n,r){this.send({gem:U,type:"gem.signal",signal:e,matchId:n,data:r});}dedicatedOffer(e,n,r){this.send({gem:U,type:"gem.dedicatedOffer",matchId:e,sdp:n,intent:r});}requestParty(e){return this.send({gem:U,type:"gem.partyRequest",requestId:e})}requestPurchase(e,n,r,i,o,s){return this.send({gem:U,type:"gem.requestPurchase",requestId:e,purchaseKind:n,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...s===void 0?{}:{catalogId:s}})}requestAvatar3dPurchase(e,n,r){return this.parentSupports("avatar3dPurchases")?this.send({gem:U,type:"gem.requestAvatar3dPurchase",requestId:e,itemId:n,currencySlug:r}):false}putDeviceSettings(e,n){return this.send({gem:U,type:"gem.deviceSettings.put",requestId:e,settings:n})}requestAd(e,n,r){return this.send({gem:U,type:"gem.requestAd",requestId:e,placement:n,format:r})}signalMoment(e,n,r){return this.send({gem:U,type:"gem.signalMoment",requestId:e,kind:n,...r===void 0?{}:{placement:r}})}readyCalled(){return this.readySent||this.readyPending}requestSignIn(e){return this.send({gem:U,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,n,r,i){return this.send({gem:U,type:"gem.requestFriendChallenge",requestId:e,playerId:n,template:r,...i===void 0?{}:{params:i}})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let n of this.settleWaiters.splice(0))n(e);this.options.onStateChange?.(e);}}refuseMalformed(e,n){if(!this.inbound.allow(Dn)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow(Dn)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow(Dn)&&this.options.onRefused?.(n);}fail(e,n){this.options.onError?.(e,n),this.state==="connected"&&this.port&&this.send({gem:U,type:"gem.error",code:e,...n===void 0?{}:{message:n}});}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=Fn[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||gu(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=Fn[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=Gs(r);if(o!==void 0&&!this.options.capabilities?.includes(o))return this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this frame did not advertise`),false;let s=i(e);if(s)return this.fail("invalid_message",`${r}: ${s}`),false;let a=e;if(a.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(a);break;case "gem.pause":this.options.onPause?.(a);break;case "gem.menuSelect":this.options.onMenuSelect?.(a);break;case "gem.settingChange":this.options.onSettingChange?.(a);break;case "gem.prefs":this.options.onPrefs?.(a);break;case "gem.cohorts":this.options.onCohorts?.(a);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(a);break;case "gem.willTerminate":this.options.onWillTerminate?.(a);break;case "gem.devtools":this.options.onDevtools?.(a.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let 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 gu(n.slice(1)),this.options.onScreenshot(d,l,(m,c)=>this.screenshotDenied(m,c)),true}case "gem.token.denied":this.options.onTokenDenied?.(a);break;case "gem.localServer":this.options.onLocalServer?.(a);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(a);break;case "gem.player":{this.options.onPlayer?.(Jh(a));break}case "gem.roomEvent":this.options.onRoomEvent?.(a);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(a);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(a);break;case "gem.ticketEvent":this.options.onTicketEvent?.(a);break;case "gem.socketState":this.options.onSocketState?.(a);break;case "gem.signalEvent":this.options.onSignalEvent?.(a);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(a);break;case "gem.clusterTarget":this.options.onClusterTarget?.(a);break;case "gem.partyResult":this.options.onPartyResult?.(a);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(a);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(a);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(a);break;case "gem.adResult":this.options.onAdResult?.(a);break;case "gem.momentResult":this.options.onMomentResult?.(a);break;case "gem.signInResult":this.options.onSignInResult?.(a);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(a);break;case "gem.error":this.options.onError?.(a.code,a.message);break;default:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,n){this.send({gem:U,type:"gem.screenshot.denied",reason:e,retryable:n});}};function gu(t){for(let e of t)try{e?.close?.();}catch{}}var yu="https://api.gemarcade.com";function Zo(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 Yh=new Set(["localhost","127.0.0.1","[::1]"]);function fu(t){let e=Zo(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!Yh.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}function hu(t){return Object.freeze(t.map(([e,n])=>Object.freeze({node:e,parent:n})))}function Xh(){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 Qh=Object.freeze({small_human:hu([["root",null],["body","root"],["head","body"],["arm_l","body"],["arm_r","body"],["hand_socket","arm_r"],["leg_l","body"],["leg_r","body"]]),adult_human:hu(Xh())});var eb=Object.freeze(["https://gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),tb=yu,nb=["top-left","top-right","bottom-left","bottom-right"],bu=8e3,ea=15e3,rb=9e4,ib=1/0,ob=8e3,ab=5e3,sb=5e3;async function lb(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 xn(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 GA(t={}){let e=t.clock??he,n=t.log===void 0?u=>console.info(u):t.log,r=t.baseUrl??void 0;if(r!=null){let u=Zo(r);if(u!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${u}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let i=typeof window>"u"?void 0:window.location?.search,o=pl(i),s=jl(i),a=So();a.mark("sdk created");let l=()=>pr(ne.gameVersion,t.clientVersion?.gameVersion),d=new Xt({client:()=>ct,clock:e,gameId:()=>ne.identity?.gameId??null,playerId:()=>ne.identity?.playerId??null,environment:()=>{let u=l();return {sdk_version:ba(),...u===null?{}:{game_version:u}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),m=Ad(()=>{a.mark("engaged"),d.release(),q.reportEngaged();},typeof window>"u"?{}:window),c=u=>{if(u===false)return null;let x=u?.attempts??ib,j=u?.budgetMs??rb;return !(x>0)||!(j>0)?null:{attempts:x,budgetMs:j,maxDelayMs:u?.maxDelayMs??ob}},p=u=>{u.on("created",()=>{a.mark("room created");}),u.on("joined",()=>{a.mark("room joined");}),u.on("matchAllocationStarted",()=>{a.mark("allocation started");}),u.on("matchReady",()=>{a.mark("match ready");}),u.on("matchFailed",()=>{a.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 Sn;let g=t.allowedEmbedders;if(g!=null&&!Array.isArray(g))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 y=Array.from(g??[]),v=y.filter(u=>typeof u!="string"||!ui(u));if(v.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${v.length===1?"an entry":"entries"} that ${v.length===1?"is":"are"} not an origin: ${v.map(u=>typeof u=="string"?JSON.stringify(u):String(u)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let S=Object.freeze([...new Set([...eb,...y])]),R=xn(e),P=new Set,h=xn(e),k=false,C=xn(e),T=vl(n),W=xn(e),F=t.manageAudio===false?null:qd();t.selectableText!==true&&Nd(),t.onScreenshot===void 0&&Ed(window);let N=null,E=null,M=null,L=()=>{N===null||N===E||q.reportMuted(N)&&(E=N);},$,B,K=-1/0,te=null,me=()=>{if($===void 0||te!==null||$===B)return;let u=K+1e3-e.now();if(u>0){te=e.setTimeout(()=>{te=null,me();},u);return}q.showPortraitBorders($)&&(B=$,K=e.now());},z=null,qe=null,_e=()=>{if(z===null)return false;let u=JSON.stringify(Qo(z.visible,z.only));return u===qe?q.parentSupports("walletDisplay"):q.setWalletVisible(z.visible,z)?(qe=u,true):false},pe=null,Ne=null,Z=()=>{if(pe===null)return false;let u=JSON.stringify(Wr(pe.items));return u===Ne?q.parentSupports("gameMenu"):q.setMenu(pe.items)?(Ne=u,true):false},J=null,oe=null,Re=Zc({frame:()=>q,clock:e,log:t.log}),je=()=>J===null?false:J===oe?q.parentSupports("gemCorner"):q.setGemCorner(J)?(oe=J,true):false,Le=jd({report:u=>q.reportFrameStats(u)}),at=false,Pe=Jd(()=>ga,()=>at),Ot=u=>{let x=at&&!u,j=at!==u;if(at=u,x&&Pe.close(),!!j)try{t.onDevToolsPermissionChange?.(u);}catch(ae){n?.(`[gem] onDevToolsPermissionChange threw: ${ae instanceof Error?ae.message:String(ae)}`),queueMicrotask(()=>{throw ae});}},Ue=r??tb,Hr=r!==void 0,st,f=u=>(n?.(`[gem] token refused: ${u}`),t.onError?.("internal",u),false),I=(u,x)=>{if(u===void 0)return x!==void 0?f("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 j=fu(u);return j!==null?f(`the embedder named an API root that cannot be used: ${j}. Its value is withheld here rather than written to logs.`):st!==void 0&&st!==u?f("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."):(st=u,Hr||(Ue=u),true)},D=window.location?.origin,Q=null,fe=-1/0,An=2e3,lt=new Set,Gt=u=>Q!==false?Promise.resolve(true):new Promise(x=>{let j=e.setTimeout(()=>{lt.delete(ae),x(false);},u),ae=()=>{e.clearTimeout(j),lt.delete(ae),x(true);};lt.add(ae);}),Vr=()=>{},Kr=null,q=new Rn({allowedEmbedders:S,...typeof D=="string"&&D!==""?{selfOrigin:D}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","ticketEvents","clusterTarget","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","portraitBorders","earnAllowance","share","avatarPicker","vibration","frameStats","walletDisplay","gameMenu","gemCorner","gameSettings","engagement","reservedAreas","viewport","purchases","avatar3dPurchases","deviceSettings","ads","moments","signIn","friendChallenges",...t.onFeedbackContext!==void 0?["feedbackContext"]:[],...t.onAudioChannels!==void 0?["audioChannels"]:[]],onRefused:u=>{Kr=u,t.onRefused?.(u);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:u=>{ne.onBridgeState(u),u!=="connected"&&Le.setRequested(false),E=null,qe=null,Ne=null,oe=null,Re.forgetSent(),B=void 0,u==="refused"&&(console.error("[gem] this game refused the page that framed it"+(Kr===null?"":` (${Kr})`)+", 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."),Vr()),u==="connected"&&(a.mark("bridge connected"),vu(),L(),me(),_e(),Z(),je(),Re.flush(),q.unbiddenLaunch&&!m.engaged&&d.hold(),d.startSession(),m.engaged&&q.reportEngaged()),t.onStateChange?.(u);},onPlayer:u=>{R.set(u);for(let x of [...P])x(u);t.onPlayer?.(u);},onPrefs:u=>{let x={reducedMotion:u.reducedMotion,muted:u.muted,locale:u.locale,showFrameStats:u.showFrameStats===true,music:u.music!==false,sounds:u.sounds!==false,recommended:u.recommended===void 0?null:Object.freeze({volume:u.recommended.volume,batterySaver:u.recommended.batterySaver,keyboardLayout:u.recommended.keyboardLayout,gamepadConfirm:u.recommended.gamepadConfirm,vibration:u.recommended.vibration,lookSensitivity:u.recommended.lookSensitivity??100,gamepadLookSensitivity:u.recommended.gamepadLookSensitivity??100,invertLookY:u.recommended.invertLookY??false,touchMovement:u.recommended.touchMovement==="fixed"?"fixed":"floating",graphicsQuality:eu(u.recommended.graphicsQuality,u.recommended.batterySaver),graphicsQualityAuto:u.recommended.graphicsQualityAuto??true})};h.set(x),E=x.muted,F?.setMuted(x.muted),Le.setRequested(x.showFrameStats&&q.parentSupports("frameStats")),t.onPrefs?.(x),t.onAudioChannels!==void 0&&(M===null||M.music!==x.music||M.sounds!==x.sounds)&&(M=Object.freeze({music:x.music,sounds:x.sounds}),t.onAudioChannels(M));},onCohorts:u=>{let x=Object.freeze(u.cohorts.map(j=>Object.freeze({experimentId:j.experimentId,variantKey:j.variantKey})));C.set(x),t.onCohorts?.(x);},onEarnAllowanceChanged:()=>T.emit(),onViewport:u=>{let x=Object.freeze({insets:Object.freeze({top:u.insets.top,right:u.insets.right,bottom:u.insets.bottom,left:u.insets.left}),reserved:Object.freeze((u.reserved??[]).map(({x:ae,y:ya,width:fa,height:ha,control:Dt})=>Object.freeze(Dt?{x:ae,y:ya,width:fa,height:ha,control:Object.freeze({x:Dt.x,y:Dt.y,width:Dt.width,height:Dt.height})}:{x:ae,y:ya,width:fa,height:ha})))});W.set(x);let j=Bd();Wd(j,x.insets),Vd(j,x.reserved,Hd()),t.onViewport?.(x);},onPause:u=>{k=u.paused,d.setPaused(u.paused),Le.setPaused(u.paused),t.onPause?.(u.paused);},onSettingChange:u=>Re.onSettingChange(u),onMenuSelect:u=>{pe===null||u.entry!=="item"||!(Wr(pe.items).items??[]).some(j=>j.id===u.id)||pe.items?.find(j=>j.id===u.id)?.onSelect?.();},onWillTerminate:u=>{d.endSession(u.reason),t.onWillTerminate?.({reason:u.reason,graceMs:u.graceMs});},onToken:u=>{let x=u.garden;if(Ot(u.allowDevTools===true),!I(u.apiBaseUrl,x))return;let j=u;ne.onToken(j);let ae=ne.identity;ae&&(Jr.set(ae),na||(na=true,ce.reconcileSeats().catch(()=>{}))),ra.push({token:j.token,expiresAt:j.expiresAt});},onTokenDenied:u=>{Ot(false),ne.onDenied(u);},onScreenshot:(u,x,j)=>{Dd(u,x,j,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{Fd(q,t.onFeedbackContext);},onDevtools:u=>{u==="close"?Pe.close():u==="open"?Pe.openFrom("platform").catch(()=>{}):Pe.isOpen?Pe.close():Pe.openFrom("platform").catch(()=>{});},onRoomEvent:u=>ce.handleRoomEvent({event:u.event,roomId:u.roomId,...u.matchId===void 0?{}:{matchId:u.matchId},...u.version===void 0?{}:{version:u.version},...u.reason===void 0?{}:{reason:u.reason},...u.platform===void 0?{}:{platform:u.platform}}),onSeatedEvent:u=>ce.handleSeated(u.roomId),onAutoStartFailedEvent:u=>ce.handleAutoStartFailed(u.roomId,u.code),onTicketEvent:u=>ce.handleTicketEvent({event:u.event,ticketId:u.ticketId,...u.partySize===void 0?{}:{partySize:u.partySize},...u.queuedAt===void 0?{}:{queuedAt:u.queuedAt},...u.expiresAt===void 0?{}:{expiresAt:u.expiresAt},...u.reason===void 0?{}:{reason:u.reason},...u.roomId===void 0?{}:{roomId:u.roomId}}),onSocketState:u=>{let x=Q;if(Q=u.connected,u.connected)for(let ae of [...lt])ae();if(!u.connected||x===true)return;let j=e.now();j-fe<An||(fe=j,ce.reconcile().catch(()=>{}));},onSignalEvent:u=>{let x=typeof u.data=="object"&&u.data!==null&&!Array.isArray(u.data)?u.data:{};ut.handleSignalEvent(u.matchId,u.event,x),u.event==="matchEnded"&&ce.reconcile({matchId:u.matchId,...typeof x.reason=="string"?{reason:x.reason}:{}}).catch(()=>{});},onDedicatedEvent:u=>{u.event==="matchEnded"&&(Lt.handleMatchEnded(u.matchId,u.reason),ce.reconcile({matchId:u.matchId,...u.reason===void 0?{}:{reason:u.reason}}).catch(()=>{})),ta.handleEvent(u);},onClusterTarget:u=>Cn.accept(u.clusterTargetId,u.clusterTargetIds),onLocalServer:u=>In.accept(u),onLocalServerDenied:u=>In.refuse(u),onPartyResult:u=>oa.settle(u.requestId,u.partyId),onPurchaseResult:u=>Yr.settle(u),onDeviceSettings:u=>{En.receive(u),t.onDeviceSettings?.(En.api.current);},onDeviceSettingsResult:u=>En.settle(u),onAdResult:u=>sa.settle(u),onMomentResult:u=>la.settle(u),onSignInResult:u=>da.settle(u),onFriendChallengeResult:u=>ca.settle(u)}),ta=new vn({bridge:q}),Jr=xn(e);Vr=()=>{Jr.release(),R.release(),C.release();},q.currentState==="refused"&&Vr();let na=false,zr=new Set,Pn,ra={current:()=>Pn,subscribe:u=>(zr.add(u),Pn!==void 0&&u(Pn),()=>zr.delete(u)),push:u=>{Pn=u;for(let x of [...zr])try{x(u);}catch(j){n?.(`[gem] a server-token listener threw: ${j instanceof Error?j.message:String(j)}`);}}},ne=Yd({bridge:q,clock:e,onStateChange:(u,x)=>{if(u==="ready"){if(a.mark("token ready")){let j=a.marks.find(ae=>ae.name==="token ready")?.at;d.trackPlatform("gem_boot_ready",j===void 0?{}:{boot_ms:Math.max(0,Math.round(j))});}}else u==="lost"&&(a.mark("token lost"),d.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(u,x);}}),ia=()=>{let u=ne.identity;return !u||ne.source.currentState==="lost"?null:`${u.playerId}\0${u.gameId}\0${u.channel}`},vu=()=>{a.mark("token requested"),ne.source.get().catch(()=>{});},oa=Ec({bridge:q,clock:e}),Tn={},Yr=Cc({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u),confirm:async u=>Tn.confirm?.(u)??"unknown",confirmAvatar3d:async u=>Tn.confirmAvatar3d?.(u)??"unknown"}),En=uu({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u)}),aa={},sa=ou({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u),readAvailability:(u,x)=>aa.read?.(u,x)??Promise.reject(new Error("the gem-api client is not built yet")),log:t.log}),la=du({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u)}),da=Fc({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u)}),ca=bl({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u)}),Cn=Tl({bridge:q,clock:e}),In=Kd({bridge:q,clock:e}),Xr=u=>{let x=q.handleWindowMessage({data:u.data,origin:u.origin,source:u.source,ports:u.ports});return x&&window.removeEventListener("message",Xr),x};window.addEventListener("message",Xr);let dt=Pd(window,Xr),_u=dt?.capture,Qr=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];Qr?.domInteractive!==void 0&&Qr.domInteractive>0&&a.mark("document parsed",Qr.domInteractive),_u?.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 Zr=t.handshakeWarningMs;Zr!==null&&n&&e.setTimeout(()=>{let u=dt===null?"no capture script ran":`capture: ${dt.delivered} offer(s) delivered, ${dt.stale} stale, ${dt.capture.dropped} evicted${dt.capture.late?", installed late":""}`;if(q.currentState==="connected"){n(`[gem] handshake connected. boot: ${a.timeline()} \xB7 ${u}`);return}n(`[gem] no completed handshake after ${Zr??bu}ms (bridge state: ${q.currentState}). Either the embedder does not run the gem-web-sdk parent half, its origin is not in this build\u2019s allowedEmbedders, or its handshake fired before this frame\u2019s listener registered. boot: ${a.timeline()} \xB7 `+u);},Zr??bu);let wu=Fr({get baseUrl(){return Ue},tokenSource:ne.source,get defaultQuery(){let u=ne.identity;return u?{game_id:u.gameId,channel:u.channel}:{}}}),ct=new Ve({transport:wu,clock:e}),ge={client:ct,gameId:()=>ne.identity?.gameId??""};Tn.confirm=u=>Ic(ge,u),Tn.confirmAvatar3d=u=>Lc(ge,u),aa.read=(u,x)=>As(ge,"players","me",u,{signal:x});let ku=()=>ne.identity?.channel??"release",ei=new er(ge,ku),Su=Gc({player:()=>R.current,subscribe:u=>(P.add(u),()=>{P.delete(u);}),configFamilies:async()=>(await ei.load())?.avatar_3d_families,readOffers:()=>Dc(ge),purchase:u=>Yr.requestAvatar3d(u),log:t.log}),ua=async u=>(await ei.load())?.currency(u)?.id??void 0,ma=Jn(ge,ki,{identity:ia,resolveCurrencyId:ua}),ti=async u=>{let x=await Jr.wait(u);if(x)return x;throw q.currentState==="refused"?new re("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 re("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).")},ni=c(t.autoReconnect),ce=ad(s===void 0?{}:{playWithTicket:s},{client:ct,clock:e,gameId:()=>ne.identity?.gameId??null,playerId:()=>ne.identity?.playerId??null,awaitGameId:async()=>(await ti(ea)).gameId,resolveParty:oa.resolve,resolveClusterTargets:Cn.resolveList,refreshClusterTargets:Cn.refresh,ensureLocalServer:In.ensure,localHostAvailable:In.available,...t.clientVersion===void 0?{}:{clientVersion:t.clientVersion},platformGameVersion:()=>ne.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},...ni===null?{}:{autoReconnect:{...ni,redial:(u,x)=>ri.redialMatch(u,x),abandon:(u,x)=>ri.abandonMatch(u,x)}}});p(ce),Rd({analytics:d,rooms:ce});let ut=Sd({client:ct,clock:e,rooms:ce,bridge:q,gameId:()=>ne.identity?.gameId??"",baseUrl:()=>Ue,resolveClusterTarget:Cn.resolve,boot:a,...t.log===void 0?{}:{log:t.log}}),pa=ko(a,n),Lt=pc({client:ct,clock:e,rooms:ce,signaling:()=>ta.channel(),signalingReady:Gt,log:n??(()=>{})}),ri=Pc({rooms:ce,p2p:{connect:u=>pa(ut.connect(u)),session:u=>ut.session(u)},dedicated:{connect:(u=>Ir(a,"welcome",Lt.connect(u),n))},clock:e,identity:()=>ne.identity,apiBaseUrl:()=>Ue,tokens:ra,room:()=>ce.currentRoom,autoReconnect:ni!==null,...t.log===void 0?{}:{log:t.log}}),Ru=async()=>(await ti(ea)).playerId,ga={client:ct,boot:a,get identity(){return ne.identity},awaitIdentity:(u=ea)=>ti(u),awaitBridge:u=>q.settled(u),get player(){return R.current},awaitPlayer:(u=ab)=>R.wait(u),me:ma,characters:new Yn(ge,void 0,ia,ua),transfers:new Qn(ge,ki,ma.inventory),gameConfig:ei,purchases:Yr.api,deviceSettings:En.api,moments:la.api,ads:sa.api,account:da.api,share:jc({frame:q,log:t.log}),vibration:Uc({frame:q,log:t.log}),get avatarPickerAvailable(){return q.currentState==="connected"&&q.parentSupports("avatarPicker")},openAvatarPicker:u=>q.requestAvatarPicker(u?.tab),avatars3d:Su,settings:Re.api,controls:Vc({recommended:()=>h.current?.recommended??null}),analytics:d,leaderboards:new Ht(ge),challenges:new Ut(ge),showcase:new Vt(ge,Ru),friends:new Kt(ge,{challenge:ca.challenge,...o===void 0?{}:{launchedChallengeId:o}}),platform:new zt(ge,T,n),profiles:new Yt(ge),functions:new Xe((u,x)=>ms(ge,u,x)),get prefs(){return h.current},get paused(){return k},get cohorts(){return C.current},get viewport(){return W.current},awaitCohorts:(u=sb)=>C.wait(u),reportMuted:u=>{N=!!u,L();},showPortraitBorders:u=>{let x=Br(u);x!==void 0&&($=x,me());},cueReward:u=>q.cueReward(u),setWalletVisible:(u,x)=>{let j=Array.isArray(x?.only)?[...x.only]:void 0;return z=j===void 0?{visible:u===true}:{visible:u===true,only:j},_e()},setMenu:u=>(pe=Array.isArray(u?.items)?{items:u.items.map(x=>({...x}))}:{},Z()),setGemCorner:u=>{if(!nb.includes(u)){let x=typeof u=="string"?JSON.stringify(u.slice(0,48)):`a value of type ${typeof u}`;return console.warn(`[gem] setGemCorner: ${x} is not a corner, so nothing was sent. Pass 'top-left', 'top-right', 'bottom-left' or 'bottom-right'.`),false}return J=u,je()},reportFrame:()=>Le.draw(),exit:u=>lb(ce,q,u,d),frame:q,devtools:Pe,rooms:ce,dedicatedServer:{listClusterTargets:u=>Lt.listClusterTargets(u),connect:(u=>Ir(a,"welcome",Lt.connect(u),n)),handleMatchEnded:(u,x)=>Lt.handleMatchEnded(u,x)},p2p:{handleSignalEvent:(u,x,j)=>ut.handleSignalEvent(u,x,j),session:u=>ut.session(u),connect:u=>pa(ut.connect(u))},match:ri};return ga}
3
- export{eb as ARCADE_EMBEDDERS,Qh as AVATAR_RIGS,Xt as AnalyticsApi,re as AuthError,Ut as ChallengesApi,Xo as DEVICE_SETTINGS_MAX_BYTES,w as DedicatedServerError,Ye as FriendChallengeError,Kt as FriendsApi,Xe as FunctionsApi,O as GemApiError,Ve as GemClient,ue as GemConfigError,Rn as GemFrame,lr as GemFunctionError,le as GemSaveError,Sn as GemUnframedError,Ht as LeaderboardsApi,nl as MAX_PERIODS_BACK,gp as PLATFORM_EVENTS,zt as PlatformApi,ar as PlatformCurrenciesApi,sr as PlatformEarnAllowanceApi,be as PlayerText,Yt as ProfilesApi,Be as PurchaseRefusal,Vt as ShowcaseApi,se as TransportRefusal,nn as UNRELIABLE_CHANNEL_LABEL,De as asPlayerText,So as createBootTimeline,GA as createGem,lb as leaveAndExit,xe as mapIdentity,Ir as markOnResolve,Nm as platformIconUrl,en as presentJoinCredential,St as readTemplateTransports,rn as readTransportAdvert,ko as reportOnResolve,ht as text,br as webTransportAvailable};//# sourceMappingURL=gem-web-sdk.game.js.map
1
+ var Pu=Object.defineProperty;var Tu=(t,e)=>{for(var n in e)Pu(t,n,{get:e[n],enumerable:true});};globalThis.__gemWebSdkVersion="[gem-web-sdk:sdkVersion:15.1.1]";function _a(){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 Eu={initialDelayMs:2e3,maxDelayMs:6e4};function Cu(t,e){return e!==void 0?!e:t==="chain_exhausted"}var mt=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 re(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 re("chain_exhausted","the token chain reached its ceiling");if(this.inFlight===null&&this.options.clock.now()<this.notBefore)throw new re(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}=Eu,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 re("internal","token arrived for a superseded generation");return this.grant=i,this.rejected=false,this.enter("ready"),i.token}).catch(i=>{let o=Iu(i),{retryable:s,retryAfterMs:a}=i??{};throw n===this.generation&&(Cu(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 re?i:new re(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)}},re=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 Iu(t){if(t instanceof re)return t.reason;let e=t?.reason;return typeof e=="string"&&["chain_exhausted","unavailable","timeout","internal"].includes(e)?e:"internal"}var se=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}},ai=["if-match","if-none-match"],wa=4096;function Mu(t){if(!t)return;let e={};for(let[n,r]of Object.entries(t)){let i=n.toLowerCase();if(!ai.includes(i)||r===void 0)continue;let o=typeof r=="string"?Ou(r):r;if(typeof o!="string"||o.length>wa||!Gu(o))throw new se(`the ${i} header value cannot be sent \u2014 it is not a string, is longer than ${wa} 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 Ou(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 Gu(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 Lu(t){let{bytes:e}=t;if(e!==void 0){if(Object.prototype.toString.call(e)!=="[object Uint8Array]")throw new se("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 se("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 ka(t,e){let n=e.replayUnauthorizedOnce??true;return {async request(r){let i={...r},o=Mu(i.headers),s=Lu(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 m=await e.tokenSource.get(),c=await t(a,m);if(c.status===401)throw e.tokenSource.close("unavailable"),new re("unavailable","the server refused a freshly minted token");return c}}}function si(t){let e=typeof t=="string"?new TextEncoder().encode(t):t;return btoa(Du(e))}function On(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 li(t){return new TextDecoder().decode(On(t))}function Du(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"}},Ra=new WeakMap;function xa(t){return Ra.get(t)??{}}var $u=new Set([408,429,500,502,503,504]),Fu=6e4;function qu(t){if(t===void 0)return 2;if(!Number.isInteger(t)||t<0||t>10)throw new se(`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,...$t(i)},i.replaySafe===true,i.retryRateLimited!==false)}async post(e,n,r,i={}){return this.send({method:"POST",path:e,body:n,signal:r,...$t(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,...$t(i)},i.replaySafe===true,i.retryRateLimited!==false);return {bytes:Nu(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,...$t(i)},i.replaySafe===true,i.retryRateLimited!==false)}async delete(e,n,r={}){return this.send({method:"DELETE",path:e,signal:n,...$t(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?qu(this.options.maxRetries)+1:1,o=null;if(e.signal?.aborted)throw Sa(e.signal);for(let s=0;s<i;s++){if(s>0&&await this.backoff(s,o,e.signal),e.signal?.aborted)throw Sa(e.signal);let a;try{a=await this.options.transport.request(e);}catch(d){if(re.isAuthError(d)||se.isRefusal(d)||e.signal?.aborted||ju(d))throw d;o=new O("unavailable",0,String(d));continue}if(a.status>=200&&a.status<300||a.status===304)return a;let l=Uu(a);if(!$u.has(a.status)||a.status===429&&!r)throw l;o=l;}throw o??new O("unavailable",0,"no attempt was made")}backoff(e,n,r){if(r?.aborted)return Promise.resolve();let i=n?.retryAfterSeconds,o=i!==void 0?i*1e3:2**(e-1)*250,s=2**(e-1)*250,a=Math.min(Math.max(o,s),Fu);return new Promise(l=>{let d=this.options.clock,m=false,c=false,p,g=()=>{m||(m=true,c&&d.clearTimeout(p),r?.removeEventListener("abort",g),l());};r?.addEventListener("abort",g,{once:true}),p=d.setTimeout(g,a),c=true,m&&d.clearTimeout(p);})}};function Nu(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 $t(t){return {...t.keepalive===void 0?{}:{keepalive:t.keepalive},...t.ifMatch===void 0?{}:{headers:{"if-match":t.ifMatch}}}}function Sa(t){return t.reason!==void 0?t.reason:new DOMException("The operation was aborted.","AbortError")}function ju(t){let e=t?.name;return e==="AbortError"||e==="TimeoutError"}function Uu(t){let e=Wu(t),n=Vu(t.body),r={...n===void 0?{}:{details:n},...t.invocationId===void 0?{}:{invocationId:t.invocationId}};return Object.keys(r).length>0&&Ra.set(e,r),e}var Bu=new Map([["insufficient_funds","insufficient_funds"]]);function Wu(t){let{status:e,body:n}=t,r=Hu(n),i=t.retryAfterSeconds??Ju(n),o=Ku(n),s=o===void 0?void 0:Bu.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 Hu(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 Vu(t){let n=t?.error?.details;return n===null?void 0:n}function Ku(t){let n=t?.error?.code;return typeof n=="string"&&n.length>0?n:void 0}function Ju(t){let e=t?.retryAfterSeconds;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function _(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 Aa(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function Pa(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/add`;return t.client.post(s,i,o?.signal)}async function Ta(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Ea(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets/${_(e)}`;return t.client.delete(r,n?.signal)}async function Ca(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/claim`;return t.client.post(s,i,o?.signal)}async function Ia(t,e,n){return t.client.post("/v1/characters",e,n?.signal)}async function Ma(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/orders/batch`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Oa(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/orders`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Ga(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets`;return t.client.post(r,e,n?.signal)}async function La(t,e,n,r,i){let o=`/v1/settings/${_(e)}/${_(n)}/${_(r)}`;return t.client.delete(o,i?.signal)}async function Da(t,e,n,r,i){let o=`/v1/saves/${_(e)}/${_(n)}/${_(r)}`;return t.client.delete(o,i?.signal)}async function $a(t,e,n,r){let i=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.delete(i,r?.signal)}async function Fa(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/recipes/execute`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function qa(t,e,n,r,i,o){let s=`/v1/saves/${_(e)}/${_(n)}/${_(r)}/finalize`;return t.client.post(s,i,o?.signal)}async function Na(t,e,n){let r=`/v1/games/${_(t.gameId())}/avatars-3d/${_(e)}/owned`;return t.client.get(r,n?.signal)}async function ja(t,e,n){let r=`/v1/games/${_(t.gameId())}/config/channels/${_(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function Ua(t,e,n){let r=`/v1/characters/${_(e)}`;return t.client.get(r,n?.signal)}async function Ba(t,e,n){let r=`/v1/inventory/loot-tables/${_(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function Wa(t,e,n,r,i){let o=`/v1/settings/${_(e)}/${_(n)}/${_(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function Ha(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/${_(e)}/${_(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Va(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/items/${_(r)}`;return t.client.get(o,i?.signal)}async function Ka(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/${_(e)}/${_(n)}/${_(r)}`+(s?`?${s}`:"");return t.client.get(a,i?.signal)}async function Ja(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/orders/${_(r)}`;return t.client.get(o,i?.signal)}async function za(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}`;return t.client.get(o,i?.signal)}async function Ya(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/catalogs/${_(r)}/recipes/${_(i)}/availability`;return t.client.get(s,o?.signal)}async function Xa(t,e,n,r){let i=new URLSearchParams;i.set("limit",String(r?.limit));let o=i.toString(),s=`/v1/inventory/${_(e)}/${_(n)}/recipe-usage`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function di(t,e,n,r,i){let o=`/v1/saves/${_(e)}/${_(n)}/${_(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function Qa(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/${_(e)}/friends`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function Za(t,e,n){let r=`/v1/showcase/friends/${_(e)}`;return t.client.get(r,n?.signal)}async function es(t,e){let n=`/v1/games/${_(t.gameId())}/avatars-3d`;return t.client.get(n,e?.signal)}async function ts(t,e,n){let r=`/v1/inbox/friend-challenges/${_(e)}`;return t.client.get(r,n?.signal)}async function ns(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/${_(e)}`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function rs(t,e){let n=`/v1/games/${_(t.gameId())}/players/me/earn-allowance`;return t.client.get(n,e?.signal)}async function Gn(t,e){return t.client.get("/v1/inventory/players/me/platform-currencies",e?.signal)}async function is(t,e,n){let r=`/v1/profiles/players/${_(e)}`;return t.client.get(r,n?.signal)}async function os(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 as(t,e,n){let r=`/v1/inventory/players/me/platform-funded-game-inventory-purchases/${_(e)}`;return t.client.get(r,n?.signal)}async function ss(t,e,n,r){let i=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.get(i,r?.signal)}async function ls(t,e){return t.client.get("/v1/characters/slots",e?.signal)}async function ds(t,e,n){let r=`/v1/inventory/transfers/${_(e)}`;return t.client.get(r,n?.signal)}async function cs(t,e,n){let r=`/v1/games/${_(t.gameId())}/matchmaking/tickets/${_(e)}/heartbeat`;return t.client.post(r,void 0,n?.signal)}async function us(t,e,n){let r=`/v1/games/${_(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 ms(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function ps(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/platform-funded-game-inventory-purchases`;return t.client.post(o,r,i?.signal)}async function gs(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function ys(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 fs(t,e){return t.client.get("/v1/characters",e?.signal)}async function hs(t,e,n,r){let i=`/v1/settings/${_(e)}/${_(n)}`;return t.client.get(i,r?.signal)}async function bs(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/${_(e)}/${_(n)}/orders`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function vs(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/${_(e)}/${_(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function _s(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 ws(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 ks(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 Ss(t,e,n){let r=`/v1/inbox/friend-challenges/${_(e)}/answered`;return t.client.post(r,void 0,n?.signal)}async function Rs(t,e,n,r){let i=`/v1/games/${_(t.gameId())}/matches/${_(e)}/end`;return t.client.post(i,n,r?.signal)}async function xs(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/max`;return t.client.post(s,i,o?.signal)}async function As(t,e,n,r,i,o){let s=`/v1/settings/${_(e)}/${_(n)}/${_(r)}`;return t.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function Ps(t,e,n,r,i){let o=`/v1/showcase/players/${_(e)}/${_(n)}`;return t.client.put(o,r,i?.signal)}async function Ts(t,e,n,r,i){let o=`/v1/inventory/${_(e)}/${_(n)}/rewarded-placements/${_(r)}/availability`;return t.client.get(o,i?.signal)}async function Es(t,e,n){let r=`/v1/inventory/transfers/${_(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function Cs(t,e,n,r){let i=`/v1/characters/${_(e)}`;return t.client.patch(i,n,r?.signal)}async function Is(t,e,n,r,i,o){let s=`/v1/saves/${_(e)}/${_(n)}/${_(r)}/upload-url`;return t.client.post(s,i,o?.signal,{replaySafe:true})}async function Ms(t,e,n,r,i,o){let s=`/v1/inventory/${_(e)}/${_(n)}/progressions/${_(r)}/reset`;return t.client.post(s,i,o?.signal)}async function Os(t,e,n){let r=`/v1/characters/${_(e)}`;return t.client.delete(r,n?.signal)}var U="gem-web-bridge",Dn={min:1,max:1},pt=65536,Gs=8,Ln=5e3,Ls=1024;var Ft=Object.create(null),$n="__malformed";var mi=Object.create(null),zu=Object.freeze([["gem.asyncOpponents.","asyncOpponents"],["gem.vibration.","vibration"],["gem.viewport.","reservedAreas"],["gem.moments.","moments"],["gem.prefs.","audioChannels"]]);function Ds(t){let e=mi[t];if(e!==void 0)return e;for(let[n,r]of zu)if(t.startsWith(n))return r}function pi(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 Yu(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 Xu(t){return /^[a-z]{2,8}(-[a-z0-9]{1,8})*$/i.test(t)}function Qu(t){return /^[a-z_]+$/.test(t)}function ci(t,e,n){if(e>Gs)return `nesting deeper than ${Gs}`;if(++n.nodes>Ln)return `more than ${Ln} values`;if(n.bytes>pt)return `over the ${pt} 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>Ls)return `an array of ${t.length} entries, over the ${Ls} limit`;n.bytes+=2;for(let a of t){let l=ci(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>Ln)return `more than ${Ln} values`;if(n.bytes+=a.length*3+4,n.bytes>pt)return `over the ${pt} byte limit`;let l=ci(s[a],e+1,n);if(l)return l}return null}function Zu(t){let e={nodes:0,bytes:0,seen:new Set},n=ci(t,0,e);return n?`message contains ${n}`:e.bytes>pt?`message is over the ${pt} byte limit`:null}var em={origin:[pi,"not a well-formed origin"],url:[Yu,"not a safe absolute http(s) URL"],bcp47:[Xu,"not a well-formed BCP 47 tag"],code:[Qu,"not a code of lower-case letters and underscores"]};function $s(t,e,n){for(let r of e){let i=n===""?r.n:`${n}.${r.n}`,o=t[r.n];if(o==null){if(r.o)continue;return `${i}: required`}let s=ui(o,r,i);if(s)return s}return null}function ui(t,e,n){switch(e.k){case "u":return typeof t=="boolean"?null:ui(t,{...e,k:typeof t=="string"?"s":"n"},n);case "s":{if(typeof t!="string")return `${n}: expected string`;if(t.length>e.max)return `${n}: exceeds ${e.max} characters`;if(e.f){let[r,i]=em[e.f];if(!r(t))return `${n}: ${i}`}return null}case "n":case "i":return typeof t!="number"||!(e.k=="i"?Number.isInteger:Number.isFinite)(t)?`${n}: expected ${e.k=="i"?"integer":"number"}`:t<e.lo||t>e.hi?`${n}: out of range ${e.lo}..${e.hi}`:null;case "b":return typeof t=="boolean"?null:`${n}: expected boolean`;case "e":{let r=e.v;return r.includes(t)?null:`${n}: not one of ${r.join("|")}`}case "o":return typeof t!="object"||t===null||Array.isArray(t)?`${n}: expected object`:$s(t,e.fs,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.max)return `${n}: exceeds ${e.max} items`;let r=e.it,i=`${n}[]`;for(let o of t){if(o==null){if(r.o)continue;return `${i}: required`}let s=ui(o,r,i);if(s)return s}return null}default:{let r=e.k;return `${n}: unknown kind ${String(r)}`}}}var Fs=Object.create(null);function A(t,e,n,r){return Ft[t]=n,r&&(mi[t]=r),Fs[t]=i=>{let o=Zu(i);if(o)return o;if(typeof i!="object"||i===null||Array.isArray(i))return "message: expected object";let s=i;return s.gem!==U?"gem: wrong protocol marker":s.type!==t?`type: expected ${t}`:$s(s,e,"")}}var ie={n:"requestId",k:"s",max:64};A("gem.handshake",[{n:"versions",k:"o",fs:[{n:"min",k:"i",lo:1,hi:1e3},{n:"max",k:"i",lo:1,hi:1e3}]},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}},{n:"embedder",k:"s",max:2048,f:"origin"},{n:"unbidden",k:"b",o:1}],30);A("gem.handshake.accept",[{n:"v",k:"i",lo:1,hi:1e3},{n:"capabilities",k:"a",o:1,max:64,it:{n:"",k:"s",max:64}}],5);A("gem.token",[{n:"token",k:"s",max:4096},{n:"requestId",k:"s",o:1,max:64},{n:"generation",k:"i",lo:0,hi:2147483647},{n:"apiBaseUrl",k:"s",o:1,max:512,f:"url"},{n:"playerId",k:"s",max:64},{n:"gameId",k:"s",max:64},{n:"channel",k:"e",v:["dev","test","release"]},{n:"gameVersion",k:"s",o:1,max:64},{n:"expiresAt",k:"i",lo:0,hi:4102444800},{n:"chainEndsAt",k:"i",lo:0,hi:4102444800},{n:"allowDevTools",k:"b",o:1}],30);A("gem.token.denied",[ie,{n:"retryable",k:"b"},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:36e5},{n:"reason",k:"e",v:["chain_exhausted","unavailable"]},{n:"correlationId",k:"s",max:64}],30);A("gem.player",[{n:"untrusted",k:"o",fs:[{n:"displayName",k:"s",max:64},{n:"displayTag",k:"s",o:1,max:80},{n:"displayHandle",k:"s",max:80}]},{n:"playerId",k:"s",o:1,max:64},{n:"discriminator",k:"s",o:1,max:8},{n:"avatarIconUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatarIconId",k:"s",o:1,max:64},{n:"avatar3dId",k:"s",o:1,max:64},{n:"avatar3dModelUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatar3dIconUrl",k:"s",o:1,max:2048,f:"url"},{n:"avatars3d",k:"a",o:1,max:8,it:{n:"",k:"o",fs:[{n:"family",k:"s",max:32},{n:"id",k:"s",max:64},{n:"modelUrl",k:"s",max:256,f:"url"},{n:"iconUrl",k:"s",max:256,f:"url"}]}},{n:"badges",k:"a",o:1,max:2,it:{n:"",k:"o",fs:[{n:"itemId",k:"s",max:64},{n:"iconUrl",k:"s",max:2048,f:"url"}]}},{n:"displayTag",k:"s",max:8},{n:"avatarUrl",k:"s",o:1,max:2048,f:"url"},{n:"boost",k:"o",o:1,fs:[{n:"multipliers",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"currencyId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"multiplierBp",k:"i",lo:1e4,hi:1e6}]}},{n:"expiresInDays",k:"i",o:1,lo:1,hi:7}]}],12);A("gem.pause",[{n:"paused",k:"b"}],120);A("gem.prefs",[{n:"reducedMotion",k:"b"},{n:"muted",k:"b"},{n:"showFrameStats",k:"b",o:1},{n:"music",k:"b",o:1},{n:"sounds",k:"b",o:1},{n:"locale",k:"s",max:35,f:"bcp47"},{n:"recommended",k:"o",o:1,fs:[{n:"volume",k:"i",lo:0,hi:100},{n:"batterySaver",k:"b"},{n:"keyboardLayout",k:"e",v:["wasd","arrows"]},{n:"gamepadConfirm",k:"e",v:["south","east"]},{n:"vibration",k:"b"},{n:"lookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"gamepadLookSensitivity",k:"i",o:1,lo:20,hi:400},{n:"invertLookY",k:"b",o:1},{n:"touchMovement",k:"s",o:1,max:16,f:"code"},{n:"graphicsQuality",k:"s",o:1,max:16,f:"code"},{n:"graphicsQualityAuto",k:"b",o:1}]}],60);A("gem.cohorts",[{n:"cohorts",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"experimentId",k:"s",max:36},{n:"variantKey",k:"s",max:32}]}}],12,"cohorts");A("gem.earnAllowanceChanged",[],30,"earnAllowance");A("gem.viewport",[{n:"insets",k:"o",fs:[{n:"top",k:"i",lo:0,hi:4096},{n:"right",k:"i",lo:0,hi:4096},{n:"bottom",k:"i",lo:0,hi:4096},{n:"left",k:"i",lo:0,hi:4096}]},{n:"reserved",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384},{n:"width",k:"i",lo:0,hi:16384},{n:"height",k:"i",lo:0,hi:16384},{n:"control",k:"o",o:1,fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384},{n:"width",k:"i",lo:0,hi:16384},{n:"height",k:"i",lo:0,hi:16384}]}]}}],60,"viewport");A("gem.deviceSettings",[{n:"settings",k:"j",o:1}],12,"deviceSettings");A("gem.willTerminate",[{n:"reason",k:"e",v:["grant_expiring","session_ended","navigating","kill_switch"]},{n:"graceMs",k:"i",lo:0,hi:6e4}],10);A("gem.roomEvent",[{n:"event",k:"e",v:["updated","match_started","match_ready","match_failed","version_stale"]},{n:"roomId",k:"s",max:64},{n:"matchId",k:"s",o:1,max:64},{n:"version",k:"i",o:1,lo:0,hi:2147483647},{n:"reason",k:"s",o:1,max:64},{n:"platform",k:"e",o:1,v:["universal","mobile"]}],120,"rooms");A("gem.socketState",[{n:"connected",k:"b"},{n:"reason",k:"e",o:1,v:["connecting","dropped","watchdog","terminal"]}],12,"socketState");A("gem.seatedEvent",[{n:"roomId",k:"s",max:64}],60,"partySeating");A("gem.autoStartFailedEvent",[{n:"roomId",k:"s",max:64},{n:"code",k:"s",max:64}],30,"autoStartFailure");A("gem.ticketEvent",[{n:"event",k:"e",v:["queued","matched","expired","cancelled","failed"]},{n:"ticketId",k:"s",max:64},{n:"partySize",k:"i",o:1,lo:1,hi:64},{n:"queuedAt",k:"i",o:1,lo:0,hi:4102444800},{n:"expiresAt",k:"i",o:1,lo:0,hi:4102444800},{n:"reason",k:"s",o:1,max:64},{n:"roomId",k:"s",o:1,max:64}],60,"ticketEvents");A("gem.signalEvent",[{n:"event",k:"e",v:["hello","offer","answer","ice","peerJoined","peerLeft","migration","matchEnded","error"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}],1800,"p2p");A("gem.dedicatedEvent",[{n:"event",k:"e",v:["answer","error","matchEnded"]},{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",o:1,max:10240},{n:"sessionId",k:"s",o:1,max:64},{n:"code",k:"s",o:1,max:64},{n:"message",k:"s",o:1,max:256},{n:"reason",k:"s",o:1,max:64}],120,"dedicated");A("gem.partyResult",[ie,{n:"partyId",k:"s",o:1,max:64}],30,"parties");A("gem.clusterTarget",[{n:"clusterTargetId",k:"s",max:64},{n:"clusterTargetIds",k:"a",o:1,max:3,it:{n:"",k:"s",max:64}}],12,"clusterTarget");A("gem.devtools",[{n:"action",k:"e",v:["open","close","toggle"]}],30,"devtools");A("gem.screenshot",[{n:"maxWidth",k:"i",lo:1,hi:7680},{n:"maxHeight",k:"i",lo:1,hi:4320}],6,"screenshot");A("gem.screenshot.denied",[{n:"reason",k:"e",v:["not_wired","no_source","unsupported","unreadable","tainted","too_large","busy","declined","failed"]},{n:"retryable",k:"b"}],12,"screenshot");A("gem.requestContext",[],12,"feedbackContext");A("gem.gameContext",[{n:"context",k:"j"}],12,"feedbackContext");A("gem.signal",[{n:"signal",k:"e",v:["join","offer","answer","ice","migrationAck","hostUnreachable"]},{n:"matchId",k:"s",max:64},{n:"data",k:"j"}],1200,"p2p");A("gem.dedicatedOffer",[{n:"matchId",k:"s",max:64},{n:"sdp",k:"s",max:10240},{n:"intent",k:"e",v:["initial","ice_restart","full_reconnect"]}],60,"dedicated");A("gem.partyRequest",[ie],12,"parties");A("gem.ready",[],5);A("gem.engaged",[],5,"engagement");A("gem.progress",[{n:"loaded",k:"i",lo:0,hi:1099511627776},{n:"total",k:"i",lo:0,hi:1099511627776}],600);A("gem.requestToken",[ie,{n:"reason",k:"e",v:["initial","expiring","rejected"]}],12);A("gem.requestLocalServer",[ie,{n:"gameRoomId",k:"s",max:64}],6,"localHost");A("gem.localServer",[ie,{n:"serverId",k:"s",o:1,max:128}],30,"localHost");A("gem.localServer.denied",[ie,{n:"retryable",k:"b"},{n:"reason",k:"e",v:["refused","unavailable"]}],30,"localHost");A("gem.exit",[{n:"reason",k:"s",o:1,max:64}],5);A("gem.openExternal",[{n:"url",k:"s",max:2048,f:"url"}],6);A("gem.requestFullscreen",[{n:"enabled",k:"b"}],30);A("gem.audioState",[{n:"muted",k:"b"}],120,"audioState");A("gem.rewardCue",[{n:"currencySlug",k:"s",max:32},{n:"expected",k:"i",o:1,lo:1,hi:1e9},{n:"origin",k:"o",o:1,fs:[{n:"x",k:"i",lo:0,hi:16384},{n:"y",k:"i",lo:0,hi:16384}]}],60,"rewardCue");A("gem.walletDisplay",[{n:"visible",k:"b"},{n:"currencies",k:"a",o:1,max:8,it:{n:"",k:"s",max:64}},{n:"score",k:"b",o:1}],60,"walletDisplay");A("gem.controlsDeclare",[{n:"uses",k:"o",fs:[{n:"lookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"gamepadLookSensitivity",k:"s",o:1,max:16,f:"code"},{n:"invertLookY",k:"s",o:1,max:16,f:"code"},{n:"touchMovement",k:"s",o:1,max:16,f:"code"}]}],60,"controls");A("gem.menu",[{n:"settings",k:"b"},{n:"items",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"id",k:"s",max:32},{n:"label",k:"s",max:40}]}}],60,"gameMenu");A("gem.menuSelect",[{n:"entry",k:"e",v:["settings","item"]},{n:"id",k:"s",o:1,max:32}],60,"gameMenu");A("gem.gemCorner",[{n:"corner",k:"e",v:["top-left","top-right","bottom-left","bottom-right"]}],12,"gemCorner");A("gem.settingsDeclare",[{n:"settings",k:"a",max:8,it:{n:"",k:"o",fs:[{n:"id",k:"s",max:40},{n:"label",k:"s",max:40},{n:"kind",k:"e",v:["toggle","slider","choice"]},{n:"value",k:"u",max:40,lo:-1e6,hi:1e6},{n:"quick",k:"b",o:1},{n:"icon",k:"s",o:1,max:16,f:"code"},{n:"min",k:"n",o:1,lo:-1e6,hi:1e6},{n:"max",k:"n",o:1,lo:-1e6,hi:1e6},{n:"step",k:"n",o:1,lo:0,hi:1e6},{n:"options",k:"a",o:1,max:4,it:{n:"",k:"o",fs:[{n:"id",k:"s",max:40},{n:"label",k:"s",max:40}]}}]}}],120,"gameSettings");A("gem.settingChange",[{n:"id",k:"s",max:40},{n:"value",k:"u",max:40,lo:-1e6,hi:1e6}],120,"gameSettings");A("gem.requestShare",[{n:"params",k:"a",max:16,it:{n:"",k:"o",fs:[{n:"key",k:"s",max:64},{n:"value",k:"s",max:512}]}}],6,"share");A("gem.requestAvatarPicker",[{n:"tab",k:"e",o:1,v:["2d","3d"]}],6,"avatarPicker");A("gem.vibrate",[{n:"pattern",k:"a",max:99,it:{n:"",k:"i",lo:0,hi:1e4}}],600,"vibration");A("gem.frameStats",[{n:"fps",k:"i",lo:0,hi:1e3},{n:"frameTimeP95Ms",k:"i",lo:0,hi:1e5},{n:"counts",k:"e",o:1,v:["pageFrames","gameDraws"]}],120,"frameStats");A("gem.portraitBorders",[{n:"name",k:"s",o:1,max:40}],60,"portraitBorders");A("gem.error",[{n:"code",k:"e",v:["version_mismatch","handshake_timeout","handshake_duplicate","invalid_message","rate_limited","token_unavailable","unsupported","unsupported_capability","internal"]},{n:"message",k:"s",o:1,max:256}],60);A("gem.requestPurchase",[ie,{n:"purchaseKind",k:"e",v:["item","recipe"]},{n:"targetId",k:"s",max:64},{n:"currencySlug",k:"s",max:32},{n:"quantity",k:"i",o:1,lo:1,hi:10},{n:"catalogId",k:"s",o:1,max:64}],12,"purchases");A("gem.requestAvatar3dPurchase",[ie,{n:"itemId",k:"s",max:64},{n:"currencySlug",k:"s",max:32}],12,"avatar3dPurchases");A("gem.purchaseResult",[ie,{n:"outcome",k:"e",v:["ok","declined","unavailable"]},{n:"reason",k:"s",o:1,max:64,f:"code"},{n:"purchaseId",k:"s",o:1,max:64}],30,"purchases");A("gem.deviceSettings.put",[ie,{n:"settings",k:"j"}],30,"deviceSettings");A("gem.deviceSettings.result",[ie,{n:"outcome",k:"e",v:["stored","too_large","unavailable"]}],30,"deviceSettings");A("gem.requestAd",[ie,{n:"placement",k:"s",max:32},{n:"format",k:"e",v:["interstitial","rewarded"]}],6,"ads");A("gem.adResult",[ie,{n:"outcome",k:"e",v:["shown","no_ad","unavailable"]}],12,"ads");A("gem.signalMoment",[ie,{n:"kind",k:"e",v:["level_end","run_end","match_end","menu_return","other_break"]},{n:"placement",k:"s",o:1,max:32}],6,"moments");A("gem.momentResult",[ie,{n:"shown",k:"b"}],12,"moments");A("gem.requestSignIn",[ie],6,"signIn");A("gem.signInResult",[ie,{n:"outcome",k:"e",v:["signed_in","declined","unavailable"]}],12,"signIn");A("gem.requestFriendChallenge",[ie,{n:"playerId",k:"s",max:64},{n:"template",k:"s",max:64},{n:"params",k:"j",o:1}],12,"friendChallenges");A("gem.friendChallengeResult",[ie,{n:"outcome",k:"e",v:["accepted","cancelled","refused","unavailable","rate_limited","invalid"]},{n:"code",k:"s",o:1,max:64},{n:"param",k:"s",o:1,max:64},{n:"channel",k:"s",o:1,max:16},{n:"configVersion",k:"i",o:1,lo:0,hi:9007199254740991},{n:"retryAfterMs",k:"i",o:1,lo:0,hi:864e5},{n:"detail",k:"s",o:1,max:300}],30,"friendChallenges");var Fn=Object.freeze(Fs);Ft.__malformed=60;Object.freeze(Ft);Object.freeze(mi);var he={now:()=>Date.now(),setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},qt=class{constructor(e=he){this.clock=e;}clock;tokens=new Map;lastRefill=new Map;allow(e){let n=Ft[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 gi(t,e){return t.toLowerCase()===e.toLowerCase()}function gt(t){let e=t.toLowerCase();return e==="localhost"||e.endsWith(".localhost")||e==="[::1]"||e==="::1"?true:/^127(\.\d{1,3}){3}$/.test(e)}function qs(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:gt(n.hostname)&&gt(r.hostname)}function Ns(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 qn=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 fi(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 js="inventory",yt=t=>typeof t=="number"?t:0,Nt=t=>typeof t=="string"?t:"";function yi(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 Us(t){let e=t??{};return {itemDefinitionId:Nt(e.item_definition_id),instanceId:Nt(e.instance_id),quantity:yt(e.quantity),acquiredAt:yt(e.acquired_at),...e.properties===void 0?{}:{properties:e.properties},...e.custom_data===void 0?{}:{customData:e.custom_data}}}function tm(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {currencies:yi(e.currencies,r=>{let i=r??{},o=Array.isArray(i.buckets)?i.buckets.map(s=>{let a=s??{};return {bucket:Nt(a.bucket),balance:yt(a.balance)}}):void 0;return {currencyId:Nt(i.currency_id),total:yt(i.total),...o===void 0?{}:{buckets:o}}}),items:yi(e.items,Us),progressions:yi(e.progressions,r=>{let i=r??{};return {progressionDefinitionId:Nt(i.progression_definition_id),currentValue:yt(i.current_value),completionCount:yt(i.completion_count),isCompleted:i.is_completed===true,...fi(i)}}),...n===void 0?{}:{etag:n}}}var Nn=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;snapshot(e={}){let n=e.buckets?`${js}#buckets`:js;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 Va(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Array.isArray(i)?i.map(Us):[]}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 Ha(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 tm(n)}};var nm={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,recipe_on_cooldown:1,recipe_max_uses_exceeded:1,item_max_stack_exceeded:1,recipe_costs_unmet:1,quantity_invalid:1,error:1},rm=new Set(Object.keys(nm));function Bs(t){return typeof t=="string"&&rm.has(t)?t:"error"}var Be=class extends RangeError{constructor(n,r){super(r);this.code=n;this.name="PurchaseRefusal";}code;retryable=false};var ee=t=>typeof t=="string"?t:"",im=t=>typeof t=="string"?t:ee(t&&typeof t=="object"?t.type:void 0),Te=t=>typeof t=="number"?t:0;function om(t){let e=t??{};return {prerequisiteType:ee(e.prerequisite_type),referenceId:ee(e.reference_id),required:Te(e.required),current:Te(e.current)}}function jt(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0;return {orderId:ee(e.order_id),status:ee(e.status),...n===void 0?{}:{etag:n}}}function jn(){return crypto.randomUUID()}var am="recipe-usage",Ws=100;function Un(t){let e=t??{};switch(e.type){case "currency":return {kind:"currency",currencyId:ee(e.currency_id),bucket:ee(e.bucket),delta:Te(e.delta),balanceAfter:Te(e.balance_after)};case "item":return {kind:"item",itemDefinitionId:ee(e.item_definition_id),instanceId:ee(e.instance_id),delta:Te(e.delta),quantityAfter:Te(e.quantity_after)};case "progression":return {kind:"progression",progressionDefinitionId:ee(e.progression_definition_id),delta:Te(e.delta),valueAfter:Te(e.value_after),completed:e.completed===true};default:return {kind:"other",type:ee(e.type)}}}function sm(t){let e=t??{},n=typeof e.rarity_tier=="string"?e.rarity_tier:void 0;return {entryId:ee(e.entry_id),...n===void 0?{}:{rarityTier:n},rollNumber:Te(e.roll_number),wasReplacement:e.was_replacement===true,grants:Array.isArray(e.grants)?e.grants.map(Un):[]}}function lm(t){let e=t??{},n=typeof e.etag=="string"?e.etag:void 0,r=Array.isArray(e.loot_results)?e.loot_results.map(sm):void 0;return {orderId:ee(e.order_id),status:ee(e.status),...n===void 0?{}:{etag:n},granted:Array.isArray(e.granted)?e.granted.map(Un):[],consumed:Array.isArray(e.consumed)?e.consumed.map(Un):[],autoClaimedRewards:Array.isArray(e.auto_claimed_rewards)?e.auto_claimed_rewards.map(Un):[],...r===void 0||r.length===0?{}:{lootResults:r}}}function dm(t){let e=t??{},n=e.price??{};return {payment:"platform_currency",orderId:ee(e.target_order_id)||ee(e.source_order_id),status:ee(e.status),purchaseId:ee(e.purchase_id),sourceOrderId:ee(e.source_order_id),price:{currencyId:ee(n.platform_currency_id),amount:Te(n.price)}}}function cm(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:ee(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 Hs(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 Bn=class{constructor(e,n,r){this.api=e;this.entity=n;this.cache=r;}api;entity;cache;async create(e,n={}){let r=await this.write(()=>Oa(this.api,this.entity.type,this.entity.id,{operations:e.map(Hs),source:n.source??"play",nonce:jn()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return jt(r)}async createMany(e,n={}){return this.write(()=>Ma(this.api,this.entity.type,this.entity.id,{orders:e.map(r=>({operations:r.map(Hs),nonce:jn()})),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 Ya(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(om):[];return {canExecute:o.can_execute===true,locked:o.locked===true||l.length>0,lockReasons:l,reasons:Array.isArray(o.reasons)?o.reasons.map(d=>im(d)):[],...s===void 0?{}:{usesRemaining:s},...a===void 0?{}:{cooldownExpiresAt:a}}}async recipeUsageAll(){return this.cache.read(am,[],async()=>{let n=await Xa(this.api,this.entity.type,this.entity.id,{limit:Ws})??{},r=Array.isArray(n.usages)?n.usages:[];return {usages:r.map(cm),truncated:r.length>=Ws}})}async recipeUsage(e){return (await this.recipeUsageAll()).usages.find(r=>r.recipeId===e)??null}async purchase(e,n={}){if(e.payment.kind==="configured"){let c=e,p=await this.write(()=>Fa(this.api,this.entity.type,this.entity.id,{catalog_id:c.catalogId,recipe_id:c.targetId,game_id:this.api.gameId(),nonce:jn()},{...n.ifMatch===void 0?{}:{ifMatch:n.ifMatch},...n.signal===void 0?{}:{signal:n.signal}}));return {payment:"configured",...lm(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,i]=await Promise.all([os(this.api,n.signal===void 0?{}:{signal:n.signal}),Gn(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(p=>p.slug);throw new Be("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 Be("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=g=>i.currencies.find(y=>y.currency_id===g)?.slug??g,p=a.platform_prices.map(g=>`${c(g.platform_currency_id)} ${g.price}`);throw new Be("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 Be("quantity_invalid","item purchase quantity must be an integer from 1 through 10");let m=await this.write(()=>ps(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:jn(),confirmation:"none"},n.signal===void 0?{}:{signal:n.signal}));return dm(m)}async executeRecipe(e,n,r={}){return await this.purchase({kind:"recipe",catalogId:e,targetId:n,payment:{kind:"configured"}},r)}async addProgression(e,n,r){let i=await this.write(()=>Pa(this.api,this.entity.type,this.entity.id,e,{amount:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return jt(i)}async maxProgression(e,n,r){let i=await this.write(()=>xs(this.api,this.entity.type,this.entity.id,e,{value:n,game_id:this.api.gameId()},r===void 0?{}:{signal:r}));return jt(i)}async claimProgression(e,n){let r=await this.write(()=>Ca(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return jt(r)}async resetProgression(e,n){let r=await this.write(()=>Ms(this.api,this.entity.type,this.entity.id,e,{game_id:this.api.gameId()},n===void 0?{}:{signal:n}));return jt(r)}async write(e){return this.cache.invalidate(),e()}};var hi=t=>typeof t=="string"?t:"",um=t=>typeof t=="number"?t:0;function Vs(t){let e=t??{};return {orderId:hi(e.order_id),status:hi(e.status),source:hi(e.source),createdAt:um(e.created_at)}}var Wn=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e={}){let r=await bs(this.api,this.entity.type,this.entity.id,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}})??{},i=typeof r.next_cursor=="string"?r.next_cursor:void 0;return {data:Array.isArray(r.orders)?r.orders.map(Vs):[],...i===void 0?{}:{nextCursor:i}}}async get(e,n){let r=await Ja(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return Vs(r)}};var Ks=t=>typeof t=="number"?t:0,mm=t=>typeof t=="string"?t:"";function pm(t){let e=t??{};return {progressionDefinitionId:mm(e.progression_definition_id),currentValue:Ks(e.current_value),completionCount:Ks(e.completion_count),isCompleted:e.is_completed===true,...fi(e)}}var Hn=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 za(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});return pm(o)}catch{return i??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,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,m=r().then(c=>(o&&this.generation===d&&(l.value=c,l.filledAt=this.clock.now()),c)).finally(()=>{l.inFlight===m&&(l.inFlight=void 0,l.filledAt===void 0&&this.slots.get(s)===l&&this.slots.delete(s));});return l.inFlight=m,m}invalidate(){this.slots.clear(),this.generation+=1;for(let e of [...this.listeners])e();}onInvalidate(e){return this.listeners.add(e),()=>{this.listeners.delete(e);}}rebind(){if(!this.identity)return;let e=this.identity();e!==this.boundTo&&(this.boundTo=e,this.invalidate());}};function bi(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 vi(t){try{let e=bi(await t.text());return e?`Storage said: ${e}`:""}catch{return ""}}var le=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemSaveError";}reason},gm=3e4,Js="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",ym=/^[A-Za-z0-9_]{1,64}$/;function Ee(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(!ym.test(t)||t.startsWith("_"))throw new TypeError(`${JSON.stringify(t)} is not a usable save key: ${e}.`);return t}function zs(t,e){let n=new AbortController,r=AbortSignal.timeout(e),i=()=>n.abort(r.reason),o=()=>n.abort(t?.reason);return t?.aborted?n.abort(t.reason):(r.addEventListener("abort",i,{once:true}),t?.addEventListener("abort",o,{once:true})),{signal:n.signal,release:()=>{r.removeEventListener("abort",i),t?.removeEventListener("abort",o);}}}function _i(t,e){return t.aborted&&e?.aborted!==true}var fm=new Set(["x-ms-blob-type"]),hm=/^[ -~]+$/;function bm(t,e){if(t==null)return {};if(typeof t!="object"||Array.isArray(t))throw new le("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(!fm.has(o))throw new le("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"||!hm.test(i))throw new le("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 le("save_malformed",`the grant for save ${JSON.stringify(e)} named ${JSON.stringify(o)} twice.`);n[o]=i;}return n}function wi(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 ki(t){return t?.reason==="not_found"}var Kn=class{constructor(e,n,r={}){this.api=e;this.entity=n;this.options=r;}api;entity;options;async put(e,n,r={}){let i;try{i=JSON.stringify(n);}catch(o){throw new le("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 le("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={}){let i=r.contentType??"application/octet-stream",o=this.budget(r.timeoutMs),s=zs(r.signal,o);try{let a=await Is(this.api,this.entity.type,this.entity.id,Ee(e),{size_bytes:n.byteLength,content_type:i,...r.metadata===void 0?{}:{metadata:r.metadata}},{signal:s.signal});if(typeof a.upload_url!="string"||typeof a.session_id!="string")throw new le("save_malformed",`the grant for save ${JSON.stringify(e)} named nowhere to put the bytes.`);let l=bm(a.upload_headers,e),d,m=this.options.fetch??globalThis.fetch.bind(globalThis);try{d=await m(a.upload_url,{method:"PUT",headers:{"content-type":i,...l},body:n,credentials:"omit",signal:s.signal});}catch(c){throw _i(s.signal,r.signal)?this.timeout("upload",o):new le("upload_failed",`${Js} for PUT. Underlying error: ${c}`)}if(!d.ok){let c=await vi(d);throw new le("upload_failed",d.status===400?"the save upload answered 400. The platform and the service holding the bytes disagree about what this upload must carry, which is not something your game can fix and not worth retrying \u2014 report it. "+c:`the save upload answered ${d.status}. `+(d.status===403?"An upload URL is short-lived, so this is most likely an expired one \u2014 start the save again rather than retrying the upload. ":"")+c)}return wi(await qa(this.api,this.entity.type,this.entity.id,Ee(e),{session_id:a.session_id},{signal:s.signal}))}catch(a){throw this.rethrow(a,r.signal,s.signal,"save",o)}finally{s.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 le("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={}){let r=this.budget(n.timeoutMs),i=zs(n.signal,r);try{let o;try{let l=await di(this.api,this.entity.type,this.entity.id,Ee(e),{signal:i.signal});if(!l.modified)return null;o=l.body;}catch(l){if(ki(l))return null;throw l}if(typeof o.download_url!="string")throw new le("save_malformed",`the record for save ${JSON.stringify(e)} named no link to its stored bytes.`);let s=this.options.fetch??globalThis.fetch.bind(globalThis),a;try{a=await s(o.download_url,{credentials:"omit",signal:i.signal});}catch(l){throw _i(i.signal,n.signal)?this.timeout("download",r):new le("download_failed",`${Js} for GET. Underlying error: ${l}`)}if(!a.ok){let l=await vi(a);throw new le("download_failed",`the save download answered ${a.status}. `+(a.status===403?"A download link lasts 15 minutes, so this is most likely an expired one \u2014 call get() again for a fresh one. ":"")+l)}return new Uint8Array(await a.arrayBuffer())}catch(o){throw this.rethrow(o,n.signal,i.signal,"load",r)}finally{i.release();}}async describe(e,n={}){try{let r=await di(this.api,this.entity.type,this.entity.id,Ee(e),{...n.signal===void 0?{}:{signal:n.signal},...n.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}});return r.modified?wi(r.body):null}catch(r){if(ki(r))return null;throw r}}async list(e={}){let n=await vs(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(wi),...typeof r=="string"&&r.length>0?{nextCursor:r}:{}}}async delete(e,n){try{await Da(this.api,this.entity.type,this.entity.id,Ee(e),{...n===void 0?{}:{signal:n}});}catch(r){if(!ki(r))throw r}}budget(e){return e??this.options.timeoutMs??gm}timeout(e,n){return new le("save_timeout",`the save ${e} did not finish within ${n}ms`)}rethrow(e,n,r,i,o){return e instanceof le?e:_i(r,n)?this.timeout(i,o):e}};function vm(t){try{return li(t)}catch{return t}}function Si(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"?vm(n.value):"",...r===void 0?{}:{etag:r},updatedAt:typeof n.updated_at=="number"?n.updated_at:0}}var Jn=class{constructor(e,n){this.api=e;this.entity=n;}api;entity;async list(e){let r=(await hs(this.api,this.entity.type,this.entity.id,e===void 0?{}:{signal:e}))?.settings;return Array.isArray(r)?r.map(i=>Si(i)):[]}async get(e,n={}){try{let r=await Wa(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?Si(r.body,r.etag):null}catch(r){if(Ys(r))return null;throw r}}async put(e,n,r={}){let i=await As(this.api,this.entity.type,this.entity.id,e,{value:si(n)},{...r.signal===void 0?{}:{signal:r.signal},...r.ifMatch===void 0?{}:{ifMatch:r.ifMatch}});return Si(i)}async delete(e,n){try{await La(this.api,this.entity.type,this.entity.id,e,n===void 0?{}:{signal:n});}catch(r){if(!Ys(r))throw r}}};function Ys(t){return t?.reason==="not_found"}function zn(t,e,n={}){let r=new Vn(he,n.identity);n.onInventoryChanged&&r.onInvalidate(n.onInventoryChanged);let i=new Nn(t,e,r);return {settings:new Jn(t,e),inventory:i,saves:new Kn(t,e,n.saves??{}),currencies:new qn(i,n.resolveCurrencyId),mutations:new Bn(t,e,r),orders:new Wn(t,e),progressions:new Hn(t,e,i)}}var Ri={type:"players",id:"me"};var Ke=t=>typeof t=="string"?t:"",ft=t=>typeof t=="number"?t:0;function Yn(t,e){let n=e??{},r=Ke(n.character_id);if(r==="")throw new Error("[gem] a character response carried no character_id");return {...t(r),id:r,playerId:Ke(n.player_id),gameId:Ke(n.game_id),channel:Ke(n.channel)||"release",name:Ke(n.name),slotIndex:ft(n.slot_index),isActive:n.is_active!==false,createdAt:Ke(n.created_at),updatedAt:Ke(n.updated_at)}}var Xn=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=zn(this.api,{type:"characters",id:e},{saves:this.saves,identity:this.identity,resolveCurrencyId:this.resolveCurrencyId}),this.scopes.set(e,n)),n};async list(e){let r=(await fs(this.api,e===void 0?{}:{signal:e}))?.characters;return Array.isArray(r)?r.map(i=>Yn(this.scope,i)):[]}async get(e,n){let r=await Ua(this.api,e,n===void 0?{}:{signal:n});return Yn(this.scope,r)}async create(e){let n=await Ia(this.api,{name:e.name},e.signal===void 0?{}:{signal:e.signal});return Yn(this.scope,n)}async update(e,n,r){let i=await Cs(this.api,e,{name:n},r===void 0?{}:{signal:r});return Yn(this.scope,i)}async delete(e,n){await Os(this.api,e,n===void 0?{}:{signal:n});}async slots(e){let r=await ls(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 Zs="[gem: use gem.text.toPlain()]",Xs=new Set,Qs;function _m(t){try{if(Xs.has(t))return;let e=globalThis.location;if(Qs??=!!e?.port&&gt(e.hostname??""),!Qs)return;Xs.add(t),console.warn(`[gem] ${t} is PlayerText, turned into a string: players see ${Zs}. Render text.toPlain(value) (text is in @indiegems/gem-web-sdk/sdk).
2
+ ${new Error().stack}`);}catch{}}var be=class{#e;#n;constructor(e,n="player text"){this.#e=e,this.#n=n,Object.freeze(this);}toString(){return _m(this.#n),Zs}toJSON(){return this.toString()}get[Symbol.toStringTag](){return "PlayerText"}static unwrap(e){return e.#e}};function De(t,e){return new be(t,e)}var ht={toPlain(t){return be.unwrap(t)},compare(t,e,n){let r=t instanceof be?be.unwrap(t):t,i=e instanceof be?be.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 be?be.unwrap(t):t,r=e instanceof be?be.unwrap(e):e;return n.normalize("NFC")===r.normalize("NFC")}};var bt=t=>typeof t=="string"?t:"";function Qn(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:bt(e.transfer_id),status:bt(e.status),sourceEntityId:bt(e.source_entity_id),targetEntityId:bt(e.target_entity_id),...n===void 0?{}:{message:De(n,"transfer.message")},createdAt:bt(e.created_at),expiresAt:bt(e.expires_at),...r===void 0?{}:{resolvedAt:r}}}function wm(){return crypto.randomUUID()}var Zn=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 ms(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:wm()},e.signal===void 0?{}:{signal:e.signal});return Qn(n)}async list(e={}){let r=await ks(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(Qn):[],...i===void 0?{}:{nextCursor:i}}}async get(e,n){let r=await ds(this.api,e,n===void 0?{}:{signal:n});return Qn(r)}async accept(e,n){return this.resolve(()=>Aa(this.api,e,n===void 0?{}:{signal:n}))}async reject(e,n){return this.resolve(()=>Es(this.api,e,n===void 0?{}:{signal:n}))}async cancel(e,n){return this.resolve(()=>Ta(this.api,e,n===void 0?{}:{signal:n}))}async resolve(e){return this.inventory.invalidate(),Qn(await e())}};var km=t=>typeof t=="string"?t:"",Sm=t=>typeof t=="string"&&t?t:void 0,Rm=t=>typeof t=="number"?t:void 0;function el(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 xm(t){if(typeof t!="object"||t===null||Array.isArray(t))throw new ue("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 ue("config_malformed",`config \`${l}\` is ${typeof d}, expected an array`);return d},r=Rm(e.version);if(r===void 0)throw new ue("config_malformed","config document has no numeric `version` \u2014 this is not a game config snapshot");let i=(l,d,m)=>{let c=km(l.id);if(!c)throw new ue("config_malformed",`${d}[${m}] 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:el(o),currency:el(s)}}var ue=class extends Error{constructor(n,r){super(r);this.reason=n;this.name="GemConfigError";}reason},tl=10*1024*1024,nl=15e3,rl=new Set(["dev","test","release"]);function Am(t){if(!rl.has(t))throw new ue("config_channel_unknown",`the play token names channel "${t}", which is not one of ${[...rl].join(", ")}. gem-api would reject the assignment read.`);return t}var er=t=>typeof t=="number"?t:0,xi=t=>typeof t=="string"?t:"";function Pm(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:xi(i.entry_id),weight:er(i.weight),dropRate:er(i.drop_rate),...o===void 0?{}:{rarityTier:o}}}):[];return {lootTableId:xi(e.loot_table_id),name:xi(e.name),rollCount:er(e.roll_count),allowDuplicateRolls:e.allow_duplicate_rolls===true,totalWeight:er(e.total_weight),entries:n}}var tr=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 ue("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 Ba(this.api,e,n===void 0?{}:{signal:n});return Pm(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??nl),n;try{let l=await ja(this.api,Am(this.channel()),{signal:e});if(!l.modified)throw new ue("config_malformed","the assignment read answered 304 Not Modified, but no `If-None-Match` was sent");n=l.body;}catch(l){if(l instanceof ue)throw l;if(l?.reason==="not_found")return null;throw l}let r=Sm(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 ue("config_timeout",`the config document did not arrive within ${this.options.timeoutMs??nl}ms`):new ue("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=>bi(d)).catch(()=>"");throw new ue("config_unreachable",`the config document answered ${o.status}`+(l?`: ${l}`:". The response carried no readable detail."))}let s=await o.text();if(s.length>tl)throw new ue("config_too_large",`the config document is ${s.length} bytes, over the ${tl} cap`);let a;try{a=JSON.parse(s);}catch(l){throw new ue("config_malformed",`config document is not JSON: ${String(l)}`)}return xm(a)}};var il=400,Ce=t=>typeof t=="string"?t:"",Tm=/(?:Z|[+-]\d{2}:?\d{2})$/i;function Je(t){let e=Ce(t);if(!Tm.test(e))return 0;let n=Date.parse(e);return Number.isFinite(n)?Math.floor(n/1e3):0}var Em=/^[0-9a-f]{1,64}$/,Cm=/^[0-9a-f]{16}$/,Im=/^[A-Za-z][A-Za-z0-9_+\-/]{0,63}$/,Mm=/^(?:[01]\d|2[0-3]):[0-5]\d$/;function Ai(t){let e=Ce(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 Om=4096,Gm=new TextEncoder;function Lm(t){let e=Ce(t.challenge_data),n=Ce(t.challenge_data_hash);return e===""||!Cm.test(n)?{}:Gm.encode(e).length>Om?{}:{data:e,dataHash:n}}function Dm(t){let e=t??{},n=Je(e.period_start_at),r=Je(e.period_ends_at);if(n===0||r===0)return;let i=Ce(e.slug),o=Ce(e.seed),s=Ai(e.period_local_date),a=Ce(e.boundary),l=Ce(e.reset_time);return {id:Ce(e.progression_definition_id),...i===""?{}:{slug:i},window:Ce(e.window),periodStartAt:n,periodEndsAt:r,...s===void 0?{}:{periodLocalDate:s},boundary:Im.test(a)?a:"",resetTime:Mm.test(l)?l:"",seed:Em.test(o)?o:"",...Lm(e)}}function vt(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 nr(t){let e=t??{};return Array.isArray(e.challenges)?e.challenges.map(Dm).filter(n=>n!==void 0):[]}var Ut=class{#e;constructor(e){this.#e=e;}async list(e={}){let{periodsBack:n}=e;vt(n);let r=await ys(this.#e,{...n===void 0?{}:{periods_back:n},...e.signal===void 0?{}:{signal:e.signal}});return nr(r)}};function Ie(t){return typeof t=="string"&&t!==""?t:void 0}var ol=new Set(["localhost","127.0.0.1","[::1]"]);function ze(t){return rr(t)}function rr(t){let e=Ie(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:"&&ol.has(n.hostname)))return e}var $m=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,Fm=/^[a-z][a-z0-9_]{0,31}$/;function qm(t){if(!Array.isArray(t))return;let e=[],n=new Set;for(let r of t.slice(0,8)){let i=r??{},o=Ie(i.family),s=Ie(i.avatar_3d_id),a=ze(i.model_url),l=ze(i.icon_url);o===void 0||!Fm.test(o)||n.has(o)||s===void 0||!$m.test(s)||a===void 0||l===void 0||(n.add(o),e.push({family:o,id:s,modelUrl:a,iconUrl:l}));}return e}function Nm(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=n??{},i=Ie(r.item_id),o=ze(r.icon_url);i!==void 0&&o!==void 0&&e.push({itemId:i,iconUrl:o});}return e}function xe(t){let e=t??{},n=Ie(e.player_id),r=Ie(e.display_name),i=Ie(e.discriminator),o=Ie(e.display_tag),s=Ie(e.avatar_icon_id),a=ze(e.avatar_icon_url),l=Ie(e.avatar_3d_id),d=ze(e.avatar_3d_model_url),m=ze(e.avatar_3d_icon_url),c=qm(e.avatars_3d);return {...n===void 0?{}:{playerId:n},...r===void 0?{}:{displayName:De(r,"displayName")},...i===void 0?{}:{discriminator:i},...o===void 0?{}:{displayTag:De(o,"displayTag")},...s===void 0?{}:{avatarIconId:s},...a===void 0?{}:{avatarIconUrl:a},...l===void 0?{}:{avatar3dId:l},...d===void 0?{}:{avatar3dModelUrl:d},...m===void 0?{}:{avatar3dIconUrl:m},...c===void 0?{}:{avatars3d:c},badges:Nm(e.badges)}}var jm=new Set(["https://downloads.gemarcade.com","https://cdn.gemarcade.com"]);function Um(t){if(t===void 0)return;let e=ze(t);if(e===void 0)return;let n=new URL(e);return ol.has(n.hostname)||jm.has(n.origin)?e:void 0}var al=100,dl=/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z)?$/;function Pi(t){let{periodsBack:e,period:n,playerId:r}=t;if(vt(e),e!==void 0&&n!==void 0)throw new TypeError("pass periodsBack or period, not both");if(n!==void 0&&(typeof n!="string"||!dl.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 cl(t){let e=typeof t.period_id=="string"?t.period_id:"";if(!dl.test(e))return;let n=Ai(t.period_local_date),r=Je(t.period_start_at),i=Je(t.period_ends_at),o=r>0&&i>0;return {id:e,...n===void 0?{}:{localDate:n},...o?{startAt:r,endsAt:i}:{},opensAt:Je(t.opens_at),closesAt:Je(t.closes_at),final:t.final===true}}var Bt=t=>typeof t=="string"?t:"",_t=t=>typeof t=="number"?t:0,Wt=t=>typeof t=="string"?t:void 0,Bm=t=>typeof t=="number"?t:void 0,ul={player:"players",character:"characters"};function Wm(t,e){let n=t??{},r=Wt(n.entity_id),i=typeof n.entity_type=="string"&&Object.hasOwn(ul,n.entity_type)?n.entity_type:void 0,o=ml(n.stats),s=n.properties!==null&&typeof n.properties=="object"?n.properties:void 0,a=e?n.is_viewer===true:void 0;return {...xe(n),rank:_t(n.rank),occurredAt:_t(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 sl(t,e){let n=t??{},r=Wt(n.bucket_1),i=Wt(n.bucket_2),o=Bm(n.update_frequency_seconds),s=cl(n);return {leaderboardType:Bt(n.leaderboard_type),runType:Bt(n.run_type),...r===void 0?{}:{bucket1:r},...i===void 0?{}:{bucket2:i},entries:Array.isArray(n.entries)?n.entries.map(a=>Wm(a,e)):[],generatedAt:_t(n.generated_at),...o===void 0?{}:{updateFrequencySeconds:o},...s===void 0?{}:{period:s}}}function ll(t){if(t===null||typeof t!="object"||Array.isArray(t))return;let e=t;if(!Number.isFinite(e.rank))return;let n=ml(e.stats),r=e.properties!==null&&typeof e.properties=="object"?e.properties:void 0;return {rank:e.rank,occurredAt:_t(e.occurred_at),...n===void 0?{}:{stats:n},...r===void 0?{}:{properties:r}}}function ml(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 Hm(t,e,n){let r=t??{},i=Wt(r.bucket_1),o=Wt(r.bucket_2),s=cl(r);return {leaderboardType:Bt(r.leaderboard_type),runType:Bt(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(ll).filter(a=>a!==void 0):[],personalBest:ll(r.personal_best)??null,totalRuns:_t(r.total_runs),totalRunsExact:r.total_runs_exact!==false,generatedAt:_t(r.generated_at),...s===void 0?{}:{period:s}}}var Ht=class{#e;constructor(e){this.#e=e;}async get(e,n={}){let r=Pi(n),i=await ns(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 sl(i,false)}async friends(e,n={}){let r=Pi(n),i=await Qa(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 sl(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>al)throw new TypeError(`limit must be an integer between 1 and ${al}, got ${String(l)}`)}let o=Pi(i),s=await Ka(this.#e,e,ul[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"&&Bt((s??{}).entity_id)||r;return Hm(s,n,a)}};var ir=t=>typeof t=="string"?t:"",Ti=t=>typeof t=="number"?t:0;function pl(t){let e=t??{};return {playerId:ir(e.player_id),key:ir(e.key),value:e.value,updatedAt:Ti(e.updated_at)}}function Vm(t){let e=t??{};return {...xe(e),playerId:ir(e.player_id),value:e.value,isViewer:e.is_viewer===true,updatedAt:Ti(e.updated_at)}}function Km(t){return t?.reason==="not_found"}var Vt=class{constructor(e,n){this.api=e;this.selfPlayerId=n;}api;selfPlayerId;async friends(e,n={}){let i=await Za(this.api,Ee(e),{...n.signal===void 0?{}:{signal:n.signal}})??{};return {key:ir(i.key),entries:Array.isArray(i.entries)?i.entries.map(Vm):[],generatedAt:Ti(i.generated_at)}}async of(e,n,r={}){try{return pl(await ss(this.api,e,Ee(n),{...r.signal===void 0?{}:{signal:r.signal}}))}catch(i){if(Km(i))return null;throw i}}async set(e,n,r={}){if(Ee(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 pl(await Ps(this.api,i,e,{value:n},{...r.signal===void 0?{}:{signal:r.signal}}))}async clear(e,n={}){let r=await this.selfPlayerId();await $a(this.api,r,Ee(e),{...n.signal===void 0?{}:{signal:n.signal}});}};var Jm="gemChallenge",gl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function yl(t){if(!(typeof t!="string"||t===""))try{return new URLSearchParams(t).get(Jm)??void 0}catch{return}}var Ye=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});}},or=t=>typeof t=="string"?t:void 0;function fl(t){let e=t??{};return {...xe(e),playerId:or(e.player_id)??""}}function hl(t){let e=t.has_more===true?or(t.next_cursor):void 0;return e===void 0?{}:{nextCursor:e}}function zm(t){let e=t??{};return {friends:Array.isArray(e.data)?e.data.map(fl):[],...hl(e)}}var Ei=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function Ym(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 bl(t){let e=t??{},n=Ei(e.opened_at),r=Ei(e.answered_at);return {id:or(e.item_id)??"",from:fl(e.sender),template:or(e.template)??"",params:Ym(e.params),createdAt:Ei(e.created_at)??0,...n===void 0?{}:{openedAt:n},...r===void 0?{}:{answeredAt:r}}}function Xm(t){let e=t??{};return {challenges:Array.isArray(e.data)?e.data.map(bl):[],...hl(e)}}function Qm(t){let e=t;return e?.reason==="not_found"&&e.code==="inbox_item_not_found"}var Kt=class{#e;#n;#o;constructor(e,n={}){this.#e=e,this.#n=n.challenge,this.#o=n.launchedChallengeId;}async list(e={}){let n=await ws(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return zm(n)}challenge(e){return this.#n===void 0?Promise.resolve({outcome:"unavailable"}):this.#n(e)}async inbox(e={}){let n=await _s(this.#e,{...e.limit===void 0?{}:{limit:e.limit},...e.cursor===void 0?{}:{cursor:e.cursor},...e.signal===void 0?{}:{signal:e.signal}});return Xm(n)}async launchedChallenge(e={}){let n=this.#o;if(n===void 0||!gl.test(n))return null;try{return bl(await ts(this.#e,n,{...e.signal===void 0?{}:{signal:e.signal}}))}catch(r){if(Qm(r))return null;throw r}}async markAnswered(e){if(typeof e!="string"||!gl.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 Ss(this.#e,e);}};var Zm=0;function we(){try{return crypto.randomUUID()}catch{let t=Math.random().toString(36).slice(2,10);return `local-${String(++Zm)}-${String(Date.now())}-${t}`}}var ep=12e4,vl=8,tp=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,np=/^[a-z0-9][a-z0-9_-]{0,63}$/;function Jt(t,e,n={}){return new Ye(new O("invalid",400,e,void 0,t),n)}function rp(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function ip(t){let{playerId:e,template:n,params:r}=t??{};if(typeof e!="string"||!tp.test(e))return {error:Jt("recipient_invalid","playerId must be a friend's playerId, as gem.friends.list() returned it")};if(typeof n!="string"||!np.test(n))return {error:Jt("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(!rp(r))return {error:Jt("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:Jt("param_invalid",`params.${s} must be a string or a safe integer`,{param:s})}}return o.length>vl?{error:Jt("param_undeclared",`params has ${String(o.length)} keys; a template declares at most ${String(vl)}`)}:{playerId:e,template:n,params:i}}function op(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 Ye(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 Ye(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 ap(t){return ["accepted","cancelled","refused","unavailable","rate_limited","invalid"].includes(t.outcome)?t.outcome:"unknown"}function _l(t){let e=new Map;return {challenge(n){if(!t.bridge.parentSupports("friendChallenges"))return Promise.resolve({outcome:"unavailable"});let r=ip(n);if("error"in r)return Promise.reject(r.error);let i=`challenge-${we()}`;return new Promise((o,s)=>{let a={},l=m=>{e.delete(i)&&(t.clock.clearTimeout(a.timer),"error"in m?s(m.error):o(m.outcome));};e.set(i,l),a.timer=t.clock.setTimeout(()=>{l({outcome:{outcome:"unavailable"}});},t.timeoutMs??ep);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 (${ap(n)}) for an unknown requestId: `+JSON.stringify(n.requestId));return}r(op(n));}}}var ar=t=>typeof t=="string"?t:void 0;function sp(t){let e=t??{},n=ar(e.currency_id);if(n===void 0||n==="")return;let r=typeof e.balance=="number"&&Number.isFinite(e.balance)?e.balance:0;return {slug:ar(e.slug)??"",currencyId:n,balance:r,access:e.access==="spend"?"spend":"read"}}var sr=class{#e;constructor(e){this.#e=e;}async get(e={}){let r=(await Gn(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=sp(o);s!==void 0&&i.push(s);}return i}},Ci=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?Math.floor(t):0;function lp(t){let e=t??{},n=ar(e.currency_id);if(n===void 0||n==="")return;let r=Ci(e.limit),i=Math.min(Ci(e.earned),r),o=Math.min(Ci(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:ar(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 wl(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 lr=class{#e;#n;#o;constructor(e,n,r){this.#e=e,this.#n=n,this.#o=r;}async get(e={}){let r=(await rs(this.#e,e))?.currencies;if(!Array.isArray(r))return [];let i=[];for(let o of r){let s=lp(o);s!==void 0&&i.push(s);}return i}on(e,n){return e!=="changed"?(this.#o?.(`[gem] unknown earnAllowance event '${String(e)}'; the only event is 'changed'`),()=>{}):this.#n?.on(n)??(()=>{})}},zt=class{currencies;earnAllowance;constructor(e,n,r){this.currencies=new sr(e),this.earnAllowance=new lr(e,n,r);}};var Ii=t=>typeof t=="string"?t:"",kl=t=>typeof t=="number"?t:0;function dp(t){let e=t??{};return {key:Ii(e.key),visibility:Ii(e.visibility),value:e.value,updatedAt:kl(e.updated_at)}}function cp(t){let e=t??{};return {...xe(e),playerId:Ii(e.player_id),showcase:Array.isArray(e.showcase)?e.showcase.map(dp):[],generatedAt:kl(e.generated_at)}}function up(t){return t?.reason==="not_found"}var Yt=class{#e;constructor(e){this.#e=e;}async of(e,n={}){try{return cp(await is(this.#e,e,{...n.signal===void 0?{}:{signal:n.signal}}))}catch(r){if(up(r))return null;throw r}}};var mp=new Map([["function_error",false],["function_failed",false],["function_timeout",false],["function_not_published",false],["function_input_too_large",false],["functions_not_configured",false],["forbidden",false],["function_capacity_unavailable",true],["function_host_unreachable",true],["function_host_error",true],["rate_limited",true],["service_unavailable",true]]),dr=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:mp.get(this.code))??super.retryable}},Xe=class{#e;constructor(e){this.#e=e;}async invoke(e,n={}){let r=pp(e),i;try{i=await this.#e(r,n.signal===void 0?{}:{signal:n.signal});}catch(o){throw o instanceof O?yp(o):o}return gp(i)}};function pp(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 se(`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 se(`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 gp(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 yp(t){let{details:e,invocationId:n}=xa(t),i=e?.untrusted?.message,o=e?.reason;return new dr(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 cr(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 fp=["gem_session_start","gem_session_end","gem_pause","gem_resume","gem_boot_ready","gem_match_started","gem_match_ended","gem_auth_lost"],Mi="gem_";function Sl(t){return t.startsWith(Mi)}function hp(t){let e=2166136261;for(let n of new TextEncoder().encode(t))e^=n,e=Math.imul(e,16777619);return e>>>0}function bp(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 ur(t,e,n){if(Oi(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=bp(hp(`${t}:${e}`))%r;return typeof n=="number"?i:n[i]}function Oi(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 Rl=1e4,xl=50,vp=500,_p=65536-4*1024,wp=24*1024;function Al(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 Pl=t=>typeof t=="number"?t:0,kp=t=>typeof t=="string"?t:"";function mr(t=0){return {accepted:0,rejected:[],dropped:t,duplicate:false}}function Sp(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(i=>{let o=i??{};return {index:Pl(o.index),code:kp(o.code)}}):[];return {accepted:Pl(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function Gi(){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 Rp(t){return t?.retryable===true}var Xt=class{#e;#n;#o;#f;#t=[];#h={};#a=0;#s=null;#b=false;#v=false;#m=0;#_=0;#w=0;#r=false;#k=null;#l=null;#c=false;#i=false;#p=false;#S=false;#R=false;constructor(e){this.#e=e,this.#n=e.options?.enabled!==false,this.#o=Math.max(Rl,e.options?.flushIntervalMs??Rl),this.#f=Math.max(1,Math.floor(e.options?.maxQueue??vp));}track(e,n={}){if(!(!this.#n||this.#r)){if(Sl(e)){this.#R||(this.#R=true,this.#y(`[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.#x(e,Al({...this.#h,...n}));}}setContext(e){this.#h={...this.#h,...e};}async experiment(e,n){Oi(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"?ur(e,r,n):ur(e,r,n)}get environment(){let e=this.#e.environment;return {...typeof e=="function"?e():e??{}}}async flush(e={}){if(this.#i)return mr();let n=this.#I();if(n===null||n==="")return this.#t.length>0&&!this.#S&&(this.#S=true,this.#y("[gem] analytics: events are being recorded but no play session has been established, so nothing is being sent. Outside the arcade this is expected.")),mr();if(this.#P(),this.#t.length===0)return mr();let r=e.keepalive===true;if(this.#m>0&&!r)return mr();this.#u();let i=this.#t.splice(0,this.#E(r)),o=this.#a;this.#a=0;let s=Math.round(this.#e.clock.now()),a={batch_id:Gi(),sent_at_ms:s,events:i.map(d=>Tl(d,s))},l={client:this.#e.client(),gameId:()=>n};this.#m+=1;try{let d=await us(l,a,{...e.signal===void 0?{}:{signal:e.signal},...r?{keepalive:!0}:{}}),m=Sp(d,o);return this.#_=0,this.#w=0,this.#C(m),m}catch(d){throw Rp(d)?(this.#T(i,o),this.#_+=1,this.#w=this.#e.clock.now()+cr(this.#_,d)):this.#y(`[gem] analytics: ${i.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String(d)}`),d}finally{this.#m-=1,this.#t.length>0&&this.#d();}}trackPlatform(e,n={}){this.#r||this.#i&&(e==="gem_pause"||e==="gem_resume")||this.#x(e,Al(n));}hold(){this.#r||this.#l!==null||(this.#i=true,this.#u());}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.#p&&(this.#p=false,this.#l=e,this.#c=false,this.#t.unshift({uid:Gi(),name:"gem_session_start",atMs:e,dimensions:{},measures:{}})),this.#t.length>=xl?this.#g():this.#t.length>0&&this.#d();}get held(){return this.#i}startSession(){if(!(this.#r||this.#l!==null)){if(this.#i){this.#p=true;return}this.#l=this.#e.clock.now(),this.#c=false,this.trackPlatform("gem_session_start");}}endSession(e){if(this.#r||this.#c)return;if(this.#c=true,this.#i){this.#p=false,this.#t=[],this.#a=0;return}let n=this.#l;this.trackPlatform("gem_session_end",{reason:e,...n===null?{}:{duration_ms:Math.max(0,Math.round(this.#e.clock.now()-n))}}),this.#g({keepalive:true});}setPaused(e){this.#r||e===this.#b||(this.#b=e,this.trackPlatform(e?"gem_pause":"gem_resume"),e?this.#u():this.#t.length>0&&this.#d());}setHidden(e){this.#r||e===this.#v||(this.#v=e,e?this.#u():this.#t.length>0&&this.#d());}dispose(){this.#r=true,this.#u(),this.#t=[],this.#a=0;}get pending(){return this.#t.length}#x(e,n){let{dimensions:r,measures:i}=n;for(this.#P();this.#t.length>=this.#f;)this.#t.shift(),this.#a+=1;this.#t.push({uid:Gi(),name:e,atMs:this.#e.clock.now(),dimensions:r,measures:i}),this.#t.length>=xl?this.#g():this.#d();}#g(e={}){if(e.keepalive!==true&&this.#A()>0){this.#d();return}this.flush(e).catch(()=>{});}#A(){return Math.max(0,this.#w-this.#e.clock.now())}#T(e,n){for(this.#t=[...e,...this.#t],this.#a+=n;this.#t.length>this.#f;)this.#t.shift(),this.#a+=1;}#E(e){let n=e?wp:_p,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(Tl(s,0)).length+1,i>n)return Math.max(1,o)}return r}#d(){this.#s!==null||this.#b||this.#v||this.#i||this.#r||this.#m>0||(this.#s=this.#e.clock.setTimeout(()=>{this.#s=null,this.#g();},Math.max(this.#o,this.#A())));}#u(){this.#s!==null&&(this.#e.clock.clearTimeout(this.#s),this.#s=null);}#P(){let e=this.#M();e===null||e===""||(this.#k!==null&&this.#k!==e&&(this.#t=[],this.#a=0,this.#l=null,this.#c=false),this.#k=e);}#C(e){for(let n of e.rejected)this.#y(`[gem] analytics: an event was refused (${n.code}). `+xp(n.code));}#y(e){let n=this.#e.log;n!==null&&(n===void 0?console.warn(e):n(e));}#I(){try{return this.#e.gameId()}catch{return null}}#M(){try{return this.#e.playerId()}catch{return null}}};function Tl(t,e){return {event_uid:t.uid,name:t.name,offset_ms:Math.round(t.atMs)-e,dimensions:t.dimensions,measures:t.measures}}function xp(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 ye(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e}function Qt(t){if(!Array.isArray(t))return [];let e=[];for(let n of t){let r=ye(n);if(!(r===void 0||e.includes(r))&&(e.push(r),e.length===3))break}return e}var Ap=2e3,Pp=5e3;function Cl(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,m=null;s=c=>{d||(d=true,r=null,t.clock.clearTimeout(m),l(c));},m=t.clock.setTimeout(()=>{n=true,s([]);},t.timeoutMs??Ap);});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 !El(e,s)||!t.bridge.parentSupports("clusterTarget")?Promise.resolve(e):new Promise(a=>{let l=null,d=m=>{i.delete(d)&&(t.clock.clearTimeout(l),a(m));};i.set(d,s),l=t.clock.setTimeout(()=>d(e),t.refreshTimeoutMs??Pp);})},accept(s,a){let l=Qt(a),d=ye(s),m=l.length>0?l:d===void 0?[]:[d];if(m.length!==0){e=m,r?.settle(m);for(let[c,p]of [...i])El(m,p)||c(m);}}}}function El(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var Tp=new Set(["timeout","credential_expired","credential_reused","join_rate_limited","signaling_failed","connection_failed","no_server_ready","start_rate_limited"]),w=class extends Error{constructor(n,r,i){super(`${n}: ${r}`,i);this.reason=n;this.name="DedicatedServerError",this.retryable=Tp.has(n),this.platformCode=i?.platformCode;}reason;retryable;platformCode};var Il=["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"],Ep=new Set(Il);function wt(t){return typeof t=="string"&&Ep.has(t)?t:"unknown"}var pr="webrtc_dedicated",Fi=["universal","mobile","web"];var Cp="p2p_unavailable",Ip="capacity_unavailable",Mp=2,Ml=3e4,Ol=1e3,Gl=2e4;async function qi(t){let e=ye(t.clusterTargetId),n=t.nextClusterTarget,r=0,i=t.clock??he,o=t.retry??{},s=o.budgetMs??Ml,a=o.maxDelayMs??Gl,l=o.initialDelayMs??Ol,d=i.now(),m=d+s,c=0;for(;;){c++;try{let p=await Bi(t.signal,"while allocating",()=>t.client.post(`${$l(t)}/start_match`,e===void 0?{}:{cluster_target_id:e},t.signal));return {matchId:p.match_id,status:p.status}}catch(p){if(!Op(p)||s<=0)throw p;if(p.status===503&&p.code===Cp)throw new w("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===Ip?r+1:0,n!==void 0&&r>=Mp){let R=n;n=void 0;let P=ye(await R());P!==void 0&&(e=P,r=0);}let g=Math.min(a,l*2**(c-1)),y=Math.min(a,(p.retryAfterSeconds??0)*1e3),S=Math.max(g/2,y)+Math.random()*(g/2);if(i.now()+S>m)throw Gp(t,p,c,i.now()-d,s);if(o.onWaiting?.({attempt:c,elapsedMs:i.now()-d,budgetMs:s,nextAttemptInMs:S,status:p.status,message:p.message}),await gr(i,S,t.signal),t.signal?.aborted)throw $i("while waiting to allocate")}}}function Op(t){return t instanceof O?t.status===503?true:t.status===429&&t.code!=="too_many_concurrent_matches":false}function Gp(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 w("start_rate_limited",`the platform was still limiting match starts for room ${t.roomId} after ${o}: ${e.message}`,{cause:e}):new w("no_server_ready",`the platform had no server ready for room ${t.roomId} after ${o}: ${e.message}`,{cause:e})}var Lp=12e4,Dp=1e3;async function Ni(t){let{clock:e,matchId:n}=t,r=t.pollIntervalMs??Dp,i=t.timeoutMs??Lp,o=e.now()+i,s=Ll(t),a={seen:t.knownToExist===true};for(;;){let l=await Dl(t,s,a);if(l.outcome!==null)return l.outcome;if(e.now()+r>o)throw new w("timeout",`match ${n} was still ${l.status} after ${i}ms`);await gr(e,r,t.signal);}}async function ji(t){return (await Dl(t,Ll(t),{seen:t.knownToExist===true})).outcome}function Ll(t){let e=new URLSearchParams({platform:t.version.platform,game_version:t.version.gameVersion});return `${$l(t)}/matches/${encodeURIComponent(t.matchId)}/status?${e}`}async function Dl(t,e,n){let{matchId:r}=t,i=t.clock.now(),o;try{o=await Bi(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:$p(r,o,i)};if(o.status==="failed"){let s=o.ended_reason;return typeof s=="string"?{status:"failed",outcome:{status:"ended",matchId:r,reason:wt(s)}}:{status:"failed",outcome:{status:"failed",matchId:r,reason:o.failure_reason??"unknown"}}}return {status:o.status,outcome:null}}async function Ui(t){let e=await Bi(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 Bi(t,e,n){if(t?.aborted)throw $i(e);try{return await n()}catch(r){throw t?.aborted?$i(e,r):r}}function $i(t,e){return new w("aborted",`the caller aborted ${t}`,e===void 0?void 0:{cause:e})}function $p(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 $l(t){return `/v1/games/${encodeURIComponent(t.gameId)}/game-rooms/${encodeURIComponent(t.roomId)}`}function gr(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 Fl(t){return typeof t=="string"&&t.trim()!==""}function yr(t,e){return Fl(t)?t.trim():Fl(e)?e:null}var fr="0.1.0-beta",ql="0-beta",kt="web",Fp=/^(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 qp(t){let e=Fp.exec(t),n=e?.[1],r=e?.[4];return n===void 0?null:r===void 0?n:`${n}-${r}`}function Nl(t,e){let n=Np(t.platform,e),r=t.engineVersion;if(r===void 0)return {...t,platform:n,engineVersion:fr};let i=qp(r);if(i===null)throw new w("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 '${fr}' for it.`);if(i!==ql)throw new w("misconfigured",`${e} refused: engineVersion '${r}' derives to engine line '${i}', and '${ql}' 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 '${fr}' for it.`);return {...t,platform:n,engineVersion:r}}function Np(t,e){if(t===void 0||t===kt)return kt;if(!Fi.includes(t))throw new w("misconfigured",`${e} refused: platform '${String(t)}' is not a client platform gem-api recognises \u2014 it knows ${Fi.map(n=>`'${n}'`).join(", ")}. Remove the field: the SDK reports '${kt}', which is the only one true of a browser build.`);return console.warn(`[gem] ${e}: clientVersion.platform '${t}' was replaced with '${kt}' 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.`),kt}function Zt(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:jl(e.queued_at),expiresAt:jl(e.expires_at),heartbeatIntervalSeconds:typeof n=="number"&&n>0?n:0}}function jl(t){if(typeof t!="string")return 0;let e=Date.parse(t);return Number.isFinite(e)?Math.floor(e/1e3):0}var jp=3,Ul=1e3,hr=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?Ul:Math.max(Ul,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<jp){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 Up="gemPlayWith",Bp=/^[A-Za-z0-9_-]{16,128}$/;function Bl(t){if(typeof t!="string"||t==="")return;let e;try{e=new URLSearchParams(t).get(Up);}catch{return}return e!==null&&Bp.test(e)?e:void 0}function Wl(t){let e=typeof t=="object"&&t!==null?t.play_with:void 0;return e==null?null:e==="joined"?"joined":"unavailable"}var Wp="join",Hp="welcome",Vp="rejected",Hl=25e3,Kp=1e3,Wi=1;function Hi(t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:void 0}var Jp={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 Vi(t){let e=typeof t=="string"?t:"unknown";return new w(Jp[e]??"join_refused",`the server runtime rejected the join credential: ${e}`)}function en(t){let{channel:e,clock:n}=t;return new Promise((r,i)=>{let o=false,s=Math.min(t.credentialExpiresAt-n.now(),t.ceilingMs??Hl),a=n.setTimeout(()=>v(new w("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,Kp)),l=S=>{let R=S.data;if(typeof R!="string"){c(R);return}let P;try{P=JSON.parse(R);}catch{c(R);return}if(o){c(R);return}if(P.t===Hp){let h=Hi(P.heartbeat_interval);y({...typeof P.player_id=="string"?{playerId:P.player_id}:{},...typeof P.match_id=="string"?{matchId:P.match_id}:{},...h===void 0?{}:{heartbeatIntervalMs:h}});return}if(P.t===Vp){v(Vi(P.reason));return}c(R);},d=()=>{v(new w("connection_failed","the channel closed before the join/welcome exchange completed, so there is nothing left to present the credential on."));},m=()=>{v(new w("aborted","the caller aborted during the join exchange"));},c=S=>{o&&t.onMessage?.(S);},p=()=>{n.clearTimeout(a),e.removeEventListener("close",d),t.signal?.removeEventListener("abort",m);},g=()=>{e.removeEventListener("message",l);},y=S=>{o=true,p(),t.onMessage===void 0&&g(),r({welcome:S,detach:g});},v=S=>{o||(o=true,p(),g(),i(S));};if(e.addEventListener("message",l),e.addEventListener("close",d),t.signal?.aborted){m();return}t.signal?.addEventListener("abort",m);try{e.send(JSON.stringify({t:Wp,credential:t.credential,...t.wire===void 0?{}:{wire:t.wire},...t.heartbeat===!0?{heartbeat:Wi}:{}}));}catch(S){v(new w("connection_failed",`the join frame could not be sent on the open channel: ${String(S)}`,{cause:S}));}})}var Qe=1,tn=2,Ki=4,Yi=8,zp=2,Yp=1e3,Xi="heartbeat timeout",nn="gem-uu",br=2,Kl="gem_transports";function St(t){if(!Array.isArray(t))return null;let e=[];for(let n of t){if(typeof n!="string")continue;let r=n.toLowerCase();!Xp(r)||e.includes(r)||e.push(r);}return e}function Xp(t){return t==="webtransport"||t==="webrtc"||t==="websocket"}function rn(t,e){if(typeof t!="object"||t===null)return null;let n=t[Kl];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 vr(t){return t instanceof Error?t.message===""?t.name:`${t.name}: ${t.message}`:String(t)}var Jl=new TextEncoder,zl=new TextDecoder;function Qi(t,e){let n=new Uint8Array(e.byteLength+1);return n[0]=t,n.set(e,1),n}function Zi(t){let e=0;return t?.reliable===false&&(e|=Qe),t?.ordered===false&&(e|=tn),e}function eo(t){return {reliable:(t&Qe)===0,ordered:(t&tn)===0}}var to={reliable:true,ordered:true};function Yl(t){return JSON.stringify({t:"join",credential:t,wire:br,heartbeat:Wi})}function Xl(t){let e;try{e=JSON.parse(t);}catch{throw new w("join_refused","the server answered the join with something unreadable")}if(e.t==="welcome"){let n=Hi(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"?Vi(e.reason):new w("join_refused","the server answered the join out of protocol")}function _r(){return typeof globalThis.WebTransport=="function"&&no===null}function wr(){return no}var no=null;var Vl="webtransport has no datagram lane; refusing the rung \u2014 server-to-client unreliable traffic would be silently lost";function Qp(t){let e=On(t);if(e.byteLength!==32)throw new w("misconfigured",`the advertised certificate hash decodes to ${e.byteLength} bytes; a SHA-256 is 32`);return e}var Ji=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 w("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 zi(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 on(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 w("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:Qp(t.certHashBase64)}]});}let r=n,i=a=>{try{r.close();}catch{}throw a},o=r.datagrams;(o?.readable===void 0||o.writable===void 0)&&(no=Vl,i(new w("connection_failed",`${Vl}; the rung is skipped for the rest of this page (a reload probes again)`)));let s=new Promise((a,l)=>{setTimeout(()=>l(new w("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 w("connection_failed","the session ended before the control stream arrived"));let d=l.value,m=d.writable.getWriter();await m.write(zi(Ki,Jl.encode(Yl(t.credential))));let c=new Ji,p=d.readable.getReader(),g;for(;g===void 0;){let y=await Promise.race([p.read(),s]);if(y.done||y.value===void 0)return i(new w("connection_failed","the control stream closed before the join was answered"));for(let v of c.push(y.value)){g=Xl(zl.decode(v.payload));break}}return {link:Zp(r,m,p,c,t.log??(y=>console.warn(y)),Zl(g,t.clock)),welcome:g}}catch(a){return i(a)}}function Zp(t,e,n,r,i,o){let s,a,l=false,d=y=>{if(!l){l=true,m.stop();try{t.close();}catch{}a?.(y);}},m=io(o,()=>d(Xi)),c=(y,v)=>{m.heard(),(y&Yi)===0&&s!==void 0&&((y&Ki)!==0?s(zl.decode(v),to):s(v,eo(y)));};(async()=>{try{for(;;){let y=await n.read();if(y.done||y.value===void 0)break;for(let v of r.push(y.value))c(v.flags,v.payload);}}catch{}d("stream closed");})();let p,g;try{let y=t.datagrams;if(y?.readable!==void 0&&y.writable!==void 0){let v=y.readable.getReader();g=y.writable.getWriter(),p=y,(async()=>{try{for(;;){let S=await v.read();if(S.done||S.value===void 0)break;let R=S.value;R.byteLength!==0&&c((R[0]??0)|Qe|tn,R.slice(1));}}catch{}})();}else i("[gem] webtransport link has no datagram lane; unreliable sends ride the stream");}catch(y){p=void 0,g=void 0,i(`[gem] webtransport datagram lane unusable (${vr(y)}); unreliable sends ride the stream`);}return t.closed.then(y=>d(Ql(y?.reason)??"session closed"),()=>d("session failed")),{transport:"webtransport",send(y,v){if(l)return;if(typeof y=="string"){e.write(zi(Ki,Jl.encode(y))).catch(()=>d("write failed"));return}let S=Zi(v);if((S&Qe)!==0&&g!==void 0){let R=Qi(S,y),P=p?.maxDatagramSize;if(P===void 0||R.byteLength<=P){g.write(R).catch(()=>{});return}}e.write(zi(S,y)).catch(()=>d("write failed"));},onMessage(y){s=y;},onClose(y){a=y;},close(){d("closed");}}}function ro(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 w("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 w("timeout","websocket did not come up in time")));},e),l=g=>{s||(s=true,clearTimeout(a),r.close(),o(g));},d=()=>{r.send(Yl(t.credential));},m=g=>{if(s)return;if(typeof g.data!="string"){l(new w("join_refused","the server sent binary before answering the join"));return}let y;try{y=Xl(g.data);}catch(v){l(v);return}s=true,clearTimeout(a),r.removeEventListener("open",d),r.removeEventListener("message",m),r.removeEventListener("close",c),r.removeEventListener("error",p),i({link:eg(r,Zl(y,t.clock)),welcome:y});},c=()=>{l(new w("connection_failed","the websocket closed before the join was answered"));},p=()=>{l(new w("connection_failed","the websocket failed before the join was answered"));};r.addEventListener("open",d),r.addEventListener("message",m),r.addEventListener("close",c),r.addEventListener("error",p),r.readyState===1&&d();})}function Ql(t){return typeof t=="string"&&t.length>0?t:void 0}function Zl(t,e){return t.heartbeatIntervalMs===void 0?void 0:{clock:e,intervalMs:t.heartbeatIntervalMs}}function io(t,e){if(t===void 0)return {heard:()=>{},stop:()=>{}};let{clock:n}=t,r=Math.max(t.intervalMs,Yp)*zp,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 eg(t,e){let n,r,i=false,o=a=>{if(!i){i=true,s.stop();try{t.close();}catch{}r?.(a);}},s=io(e,()=>o(Xi));return t.addEventListener("message",(a=>{if(s.heard(),typeof a.data=="string"){n?.(a.data,to);return}let l=new Uint8Array(a.data);if(l.byteLength===0)return;let d=l[0]??0;(d&Yi)===0&&n?.(l.slice(1),eo(d));})),t.addEventListener("close",(a=>o(Ql(a?.reason)??"socket closed"))),{transport:"websocket",send(a,l){if(!i){if(typeof a=="string"){t.send(a);return}t.send(Qi(Zi(l),a));}},onMessage(a){n=a;},onClose(a){r=a;},close(){o("closed");}}}function oo(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=io(r,()=>l(Xi)),m=(c,p)=>{if(d.heard(),typeof c=="string"){i?.(c,to);return}let g=new Uint8Array(c);if(g.byteLength===0)return;let y=g[0]??0;(y&Yi)===0&&i?.(g.slice(1),eo(y|p));};if(t.addEventListener("message",(c=>m(c.data,0))),t.addEventListener("close",(()=>l("channel closed"))),e.addEventListener("connectionstatechange",(()=>{let c=e.connectionState;(c==="failed"||c==="closed")&&l(`connection ${c}`);})),a!==void 0){let c=a;c.addEventListener("message",(p=>m(p.data,Qe|tn))),c.addEventListener("close",(()=>{a=void 0;}));}return {transport:"webrtc",send(c,p){if(s)return;if(typeof c=="string"){t.send(c);return}let g=Zi(p),y=Qi(g,c);if((g&Qe)!==0&&a!==void 0&&a.readyState==="open"){a.send(y);return}t.send(y);},onMessage(c){i=c;},onClose(c){o=c;},close(){l("closed");}}}function ed(t){if(typeof t!="object"||t===null)return;let e={};for(let[n,r]of Object.entries(t)){let i=ao(r);i!==void 0&&(e[n]=i);}return e}function td(t){if(Array.isArray(t))return t.map(tg).filter(e=>!!e)}function ao(t){if(so(t)||Array.isArray(t)&&t.every(so))return t}function so(t){return typeof t=="string"||typeof t=="boolean"||typeof t=="number"&&Number.isFinite(t)}function tg(t){let e=t??{};if(typeof e.name!="string"||e.name.length===0)return null;let n=ao(e.fixed),r=ao(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},...Rt("description",ng(e.description)),...Array.isArray(e.allowed)&&e.allowed.every(so)?{allowed:e.allowed}:{},...Rt("min",an(e.min)),...Rt("max",an(e.max)),...Rt("minItems",an(e.min_items)),...Rt("maxItems",an(e.max_items)),...Rt("maxLength",an(e.max_length))}}function ng(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 Rt(t,e){return e===void 0?{}:{[t]:e}}function $e(t){let e=t??{},n=X(e.id)??X(e.game_room_id);if(n===void 0)throw new Error("[gem] a game-room response carried no id");let r=Array.isArray(e.members)?e.members.map(rg):[];return {id:n,gameId:X(e.game_id)??"",name:X(e.name)??"",status:X(e.status)??"open",hostPlayerId:X(e.host_player_id)??"",maxPlayers:Me(e.max_players)??0,memberCount:Me(e.member_count)??r.length,members:r,isPublic:e.is_public!==false,...ke("joinCode",X(e.join_code)),...e.settings===void 0?{}:{settings:e.settings},...ke("roomArgs",ed(e.room_args)),...ke("roomArgsTemplate",td(e.room_args_template)),gameChannel:X(e.game_channel)??"release",...ke("region",X(e.region)),...ke("clusterTargetId",X(e.cluster_target_id)),selfHosted:e.self_hosted===true,...ke("matchId",X(e.match_id)),version:Me(e.version)??0,...ke("templateId",X(e.template_id)),...ke("templateSlug",X(e.template_slug)),roomType:X(e.game_room_type)??"Standard",...ke("transports",St(e.transports)??void 0),createdAt:Me(e.created_at)??0,updatedAt:Me(e.updated_at)??0,...ke("startedAt",Me(e.started_at))}}function rg(t){let e=t??{};return {...xe(e),playerId:X(e.player_id)??"",isReady:e.is_ready===true,role:X(e.role)??"member",joinedAt:Me(e.joined_at)??0,...ke("groupId",X(e.group_id)),...ke("platform",X(e.platform))}}function lo(t){let e=t??{};return {id:X(e.id)??X(e.game_room_id)??"",gameId:X(e.game_id)??"",name:X(e.name)??"",status:X(e.status)??"open",hostPlayerId:X(e.host_player_id)??"",maxPlayers:Me(e.max_players)??0,memberCount:Me(e.member_count)??0,isPublic:e.is_public!==false,gameChannel:X(e.game_channel)??"release",roomType:X(e.game_room_type)??"Standard",createdAt:Me(e.created_at)??0}}function X(t){return typeof t=="string"&&t.length>0?t:void 0}function Me(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function ke(t,e){return e===void 0?{}:{[t]:e}}var kr=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(lo),...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(lo)}))}create(e,n,r){return og(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},...sn(n)},e.signal).then($e)}get(e,n){return this.options.client.get(this.roomV2(e),n).then($e)}join(e,n,r){return this.options.client.post(`${this.roomV2(e)}/join`,{...n.partyId===void 0?{}:{party_id:n.partyId},...sn(r)},n.signal).then($e)}joinByCode(e,n,r){return this.options.client.post(`${this.baseV2()}/join`,{join_code:e,...n.partyId===void 0?{}:{party_id:n.partyId},...sn(r)},n.signal).then($e)}quickJoin(e,n,r=[]){return co(this.options,e,n,r).then(i=>i.room)}createTicket(e,n,r=[]){return Ga(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},...sn(n)},{...e.signal===void 0?{}:{signal:e.signal}}).then(Zt)}heartbeatTicket(e){return cs(this.generated(),e).then(Zt)}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(Zt):Ea(this.generated(),e).then(Zt)}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 rd(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($e)}setReady(e,n,r){return this.options.client.post(`${this.roomV2(e)}/ready`,{is_ready:n},r).then($e)}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($e)}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 nd(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 nd(t){return `/v2/games/${encodeURIComponent(t.gameId())}/game-rooms`}function rd(t,e){return e===void 0&&t.selfHosted?.()===true}function co(t,e,n,r=[],i){let o=rd(t,e.partyId);return t.client.post(`${nd(t)}/quick-join`,{...e.templateId===void 0?{}:{template_id:e.templateId},...e.templateSlug===void 0?{}:{template_slug:e.templateSlug},...ig(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},...sn(n)},e.signal).then(s=>({room:$e(s),playWith:i===void 0?null:Wl(s)}))}function ig(t,e){return t===void 0?{}:{templates:(e?t.slice(0,1):t).map(r=>({template_slug:r}))}}function sn(t){return {platform:t.platform,game_version:t.gameVersion,engine_version:t.engineVersion}}function og(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 Sr=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 Rr=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 ag(t,e){return Math.min(e,500*2**Math.max(0,t-1))}var sg=1e3,lg=3e3,dg=6e4,cg=2,id=new Set(["game_room_closed","game_room_gone"]),ug=12e4,mg=5e3,pg=new Set(["invalid_cluster_target","capacity_unavailable"]),gg=new Set(["already_in_matching_room","game_room_limit_per_game","game_room_limit_global"]);function ld(t,e){return new uo(e,t)}var uo=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 kr(this.apiOptions),this.installUnloadNotifier(),this.installResumeWatch(),this.retuneSeatWatch();}options;internals;emitter=new Sr;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;return this.api.create(r,this.version("create"),o[0]).catch(async s=>{let a=await this.afterRefusedClusters(s,o);if(a[0]===void 0||a[0]===o[0])throw s;return this.api.create(r,this.version("create"),a[0])})});return this.enter(i,"created"),this.askForLocalServer(i),i}async join(e,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"),hg(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||sd(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"),fg(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||sd(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 hr({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(()=>ji({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=wt(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 w("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=ye(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=(m,c)=>qi({client:this.options.client,clock:this.options.clock,gameId:this.requireGameId(),roomId:e.id,...m===void 0?{}:{clusterTargetId:m},...i===void 0?{nextClusterTarget:()=>this.nextCluster(c)}:{},retry:{...n.retry,onWaiting:p=>{this.emitter.emit("matchStartWaiting",p),n.retry?.onWaiting?.(p);}},...n.signal===void 0?{}:{signal:n.signal}}),l=()=>a(o,[s]).catch(async m=>{if(i!==void 0||!ad(m))throw m;let c=await this.nextCluster([s],true);if(c===void 0)throw m;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 w("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 Ni({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 w("allocation_failed",`match ${e.matchId} did not come up: ${e.reason}`);if(e.status==="ended")throw this.endMatch(e.matchId,e.reason,!id.has(e.reason)),this.track(this.reconcile().catch(()=>{})),new w("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(!Ze()){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<sg){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(ag(e.attempt,n.maxDelayMs),r));}async reconnectAttempt(e){if(!this.reconnecting(e))return;if(!Ze()){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(()=>ji({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,!id.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 w("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 w("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 w("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||!pg.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 Rr({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&&Ze())){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(),!!Ze())){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 xr)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 xr)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??mg}requireGameId(){let e=this.gameId;if(e!==null)return e;throw new w("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 w("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 Nl({...n,gameVersion:r},e)}async clusterTargets(){try{if(this.options.resolveClusterTargets!==void 0)return Qt(await this.options.resolveClusterTargets());let e=ye(await this.options.resolveClusterTarget?.());return e===void 0?[]:[e]}catch{return []}}async afterRefusedClusters(e,n){return !ad(e)||n.length===0?[]:Qt(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(Qt(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"||!gg.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 co(this.apiOptions,e,this.version("quickJoin"),n,this.internals.playWithTicket)}assertNotInRoom(e){if(this.room!==null)throw new w("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 w("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 w("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 w?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=yg(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??ug;return new Promise((i,o)=>{let s=c=>{a(),l(),this.options.clock.clearTimeout(m),e.signal?.removeEventListener("abort",d),c();},a=this.emitter.on("matchAllocationStarted",c=>s(()=>i(c))),l=this.emitter.on("matchFailed",(c,p)=>s(()=>o(new w("allocation_failed",`match ${c} did not come up: ${p}`)))),d=()=>s(()=>o(new w("aborted","the caller aborted while awaiting a match"))),m=this.options.clock.setTimeout(()=>s(()=>o(new w("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??lg}pushedInterval(){return this.options.pushedPollIntervalMs??dg}pushed(){return this.options.clock.now()-this.lastPushAt<cg*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 Ze(){let t=globalThis.document;return t?.visibilityState===void 0||t.visibilityState==="visible"}var xr=["visibilitychange","focus","pageshow","online"];function yg(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||od(t)!==od(e)}function od(t){return t.members.map(e=>`${e.playerId}:${e.isReady?1:0}:${e.role}`).sort().join(",")}function ad(t){return t instanceof O&&t.code==="invalid_cluster_target"}var Ar=8;function fg(t){if(!(Array.isArray(t)&&t.length>=1&&t.length<=Ar&&t.every(n=>typeof n=="string"&&n.length>0)))throw new w("misconfigured",`queueForMatch needs templateSlugs: an array naming one to ${Ar} room templates by slug, each with matchmaking turned on in your game config \u2014 queueForMatch({ templateSlugs: ['duel'] }).`)}function hg(t){let e=t?.templateSlugs;if(e===void 0)return;if(!(Array.isArray(e)&&e.length>=1&&e.length<=Ar&&e.every(r=>typeof r=="string"&&r.length>0)))throw new w("misconfigured",`quickJoin's templateSlugs is an array naming one to ${Ar} 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 w("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 sd(t,e){return t.length===e.length&&t.every((n,r)=>n===e[r])}var bg=["p2p","dedicated","unknown"],mo=["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 xt=class{constructor(e){this.options=e;}options;async post(e,n){let r=this.options.gameId();if(r===null||r==="")return;let i=vg(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 vg(t,e,n){let r=Math.floor(n/1e3);return t.filter(i=>mo.includes(i.type)).slice(0,100).map(i=>{let o=_g(i.transport??e);return {event_type:i.type,timestamp:r,...o===void 0?{}:{transport:o},data:i.value===void 0?{}:{value:i.value}}})}function _g(t){if(t!==void 0)return bg.includes(t)?t:"unknown"}var ln=class{constructor(e){this.options=e;this.reporter=new xt({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:Pr(i.credential)??"",hostFingerprint:Pr(i.host_fingerprint)??"",hostEpoch:Tr(i.host_epoch)??0,expiresAt:(Tr(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,m=(Array.isArray(d.urls)?d.urls:[]).filter(c=>typeof c=="string"&&c.length>0);m.length!==0&&o.push({urls:m,username:Pr(d.username)??"",credential:Pr(d.credential)??""});}let s=Tr(i.expires_at),a=Tr(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)}`}};function Pr(t){return typeof t=="string"&&t.length>0?t:void 0}function Tr(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}var wg=new Set(["timeout","signaling_failed","connection_failed","keys_unavailable"]),G=class extends Error{constructor(n,r,i){super(`${n}: ${r}`,i);this.reason=n;this.name="P2pError",this.retryable=wg.has(n);}reason;retryable};var dd=10240,cd=2048,kg=new TextEncoder;function ud(t){return kg.encode(t).length}function We(t,e){let n=i=>{throw new w("invalid_sdp",`the ${e} ${i}`)},r=ud(t);r>=dd&&n(`is ${r} bytes, over the ${dd} 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=ud(i);o>cd&&n(`has a ${o}-byte line, over the ${cd} limit`);}}function Er(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 Cr=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 Sg=/^sha-256 ([0-9A-F]{2}:){31}[0-9A-F]{2}$/;function At(t){let e=null;for(let n of t.split(/\r\n|\n/)){if(!n.startsWith("a=fingerprint:"))continue;let r=Ir(n.slice(14).trim());if(r===null||e!==null&&e!==r)return null;e=r;}return e}function Ir(t){let[e,...n]=t.trim().split(/\s+/);if(e===void 0||n.length===0)return null;let r=`${e.toLowerCase()} ${n.join("").toUpperCase()}`;return Sg.test(r)?r:null}function dn(t,e){if(t.length!==e.length)return false;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}var po=5e3,Rg=12e4+po,xg=1024,Ag=6e4,Pg=1e4,md=64*1024,pd=5;function go(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 G("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 G("keys_unavailable",i.reason);let a=t.fetch??((p,g)=>globalThis.fetch(p,g)),l;try{l=await a(i.url,{redirect:"error",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",signal:AbortSignal.timeout(Pg)});}catch{throw new G("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 G("keys_unavailable",`the JWKS endpoint answered ${i.shown} with an error`);let d;try{let p=await l.text();if(p.length>md)throw new G("keys_unavailable",`the JWKS endpoint at ${i.shown} answered with more than ${md} characters, which is not a key set this platform publishes.`);d=JSON.parse(p);}catch(p){throw p instanceof G?p:new G("keys_unavailable",`the JWKS endpoint at ${i.shown} did not answer with a readable key set.`)}let m=Array.isArray(d.keys)?d.keys:[];if(m.length>pd)throw new G("keys_unavailable",`the JWKS endpoint published ${m.length} keys, over the ${pd} the platform declares. Refusing rather than verifying against a set of unknown size.`);let c=o();for(let p of m){let g=p;if(g.kty==="RSA"&&!(g.alg!==void 0&&g.alg!=="RS256")&&!(g.use!==void 0&&g.use!=="sig")&&!(typeof g.kid!="string"||g.kid.length===0))try{let y=await c.importKey("jwk",{...p,alg:"RS256",ext:!0},{name:"RSASSA-PKCS1-v1_5",hash:"SHA-256"},!1,["verify"]);e.set(g.kid,y);}catch{}}};return {async key(a){let l=e.get(a);if(l)return l;if(!i.ok)throw new G("keys_unavailable",i.reason);if(r)return await r,e.get(a)??null;let d=t.now();if(!Number.isFinite(d))throw new G("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<Ag?null:(n=d,r??=s().finally(()=>{r=null;}),await r,e.get(a)??null)}}}var cn=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>=xg){let r=this.seen.keys().next().value;r!==void 0&&this.seen.delete(r);}return this.seen.set(e,n+Rg),true}};function yd(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 gd(t){try{let e=new TextDecoder().decode(yd(t)),n=JSON.parse(e);return typeof n!="object"||n===null||Array.isArray(n)?null:n}catch{return null}}async function yo(t,e,n,r,i){let o=F=>{throw new G("peer_unauthenticated",`the peer's join credential is not usable: ${F}`)},s=t.split(".");s.length!==3&&o("it is not a three-part JWT");let[a,l,d]=s,m=gd(a);m===null&&o("its header does not decode"),m.alg!=="RS256"&&o(`its alg is ${JSON.stringify(m.alg)}, not RS256`),m.typ!=="p2p+jwt"&&o(`its typ is ${JSON.stringify(m.typ)}, not p2p+jwt`);let c=m.kid;(typeof c!="string"||c.length===0)&&o("it names no key");let p=await n.key(c);p===null&&o("it was signed by a key this build cannot resolve");let g=i.subtle??globalThis.crypto?.subtle;g||o("this environment has no WebCrypto");let y=new TextEncoder().encode(`${a}.${l}`),v;try{v=yd(d);}catch{o("its signature does not decode");}await g.verify({name:"RSASSA-PKCS1-v1_5"},p,v,y)||o("its signature does not verify");let R=gd(l);R===null&&o("its payload does not decode");let P=R,h=F=>typeof P[F]=="string"?P[F]:"",k=F=>typeof P[F]=="number"&&Number.isFinite(P[F])?P[F]:NaN;h("iss")!==i.issuer&&o("it was issued by someone else"),h("aud")!==`${i.issuer}/p2p-match`&&o("its audience is not this platform"),h("match_id")!==e.matchId&&o("it is for another match"),h("game_id")!==e.gameId&&o("it is for another game");let C=k("exp")*1e3,T=k("nbf")*1e3;(!Number.isFinite(C)||e.now>C+po)&&o("it has expired"),Number.isFinite(T)&&e.now<T-po&&o("it is not valid yet");let W=h("role");W!=="host"&&W!=="client"&&o("it names no usable role");let $=k("host_epoch");$!==e.hostEpoch&&o("it names a different host epoch");let N=Ir(h("fingerprint"));N===null&&o("its fingerprint claim is malformed"),dn(N,e.peerFingerprint)||o("it was issued for a different certificate than this connection used");let E=Ir(h("host_fingerprint"));E===null&&o("its host fingerprint claim is malformed"),dn(E,e.hostFingerprint)||o("it was issued against a different host certificate");let M=h("jti");M.length===0&&o("it carries no jti, so replay cannot be detected"),r.admit(M,e.now)||o("it has already been used");let L=h("sub");return L.length===0&&o("it names no player"),{playerId:L.toLowerCase(),matchId:e.matchId,gameId:e.gameId,hostEpoch:$,role:W,fingerprint:N,hostFingerprint:E,jti:M,expiresAt:C}}function fo(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 ho(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 bo(t){let e=new ArrayBuffer(2),n=new DataView(e);return n.setUint8(0,3),n.setUint8(1,t),e}function vo(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 fd(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 hd(t){switch(t){case 129:return "not_expected_player";case 130:return "kicked";case 131:return "keys_unavailable";default:return "peer_unauthenticated"}}var un=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 _o={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}},Fe=["reliable","ordered","unreliable"];function wo(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 mn(){let t=globalThis.RTCPeerConnection;return t?.generateCertificate?t.generateCertificate({name:"ECDSA",namedCurve:"P-256"}):null}var vd=1,Mg=3e4,_d=2e3,Og=5e3,wd=6e4,Gg=8,So=class{constructor(e=Gg){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;}},Lg=new So,Dg=8,$g=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??go({baseUrl:e.baseUrl,now:()=>e.clock.now()});}options;emitter=new Cr;links=new Map;replays=new cn;keys;localPlayerId="";migration=null;iceServers=[];credential=null;nextPeerId=vd+1;ended=null;closed=false;ready=null;helloSeen=false;reportedUnreachableEpoch=-1;reportedStallEpoch=-1;counted=false;pendingOffers=new Map;answeredSessions=new Map;credentialGeneration=0;credentialDeadline=0;get matchId(){return this.options.matchId}get playerId(){return this.localPlayerId}get isHost(){return this.migration?.isLocalHost??false}get hostPlayerId(){return this.migration?.currentHostPlayerId??""}get hostEpoch(){return this.migration?.currentEpoch??0}get peers(){let e=[];for(let n of this.links.values())n.admitted&&e.push(this.expose(n));return e}peer(e){let n=this.links.get(e);return n&&n.admitted?this.expose(n):null}on(e,n){return this.emitter.on(e,n)}off(e,n){this.emitter.off(e,n);}once(e,n){return this.emitter.once(e,n)}async start(e){let n=this.options.connectTimeoutMs??Mg;this.credentialDeadline=this.options.clock.now()+n;let r=new Promise((a,l)=>{this.ready={resolve:a,reject:l};}),i=ye(this.options.clusterTargetId);if(i!==void 0)try{let a=await this.options.api.turnLease(this.options.matchId,i,e);this.iceServers=a.iceServers,this.mark("turn leased");}catch(a){this.mark("turn lease failed"),this.warn(`no TURN relay could be leased for this match, so peers behind a symmetric NAT will fail to connect: ${ko(a)}`);}else this.mark("turn skipped"),this.warn("connecting without a TURN relay because no cluster target was resolved. Host candidates only reach peers on the same network, so peers behind a symmetric NAT will fail to connect. The Arcade page normally resolves one for this player; outside it, pass `clusterTargetId` to connect().");this.options.signaling.join(),this.mark("signaling joined");let o=this.options.clock.setTimeout(()=>{this.fail(new G("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),s=()=>this.fail(new G("aborted","the caller aborted while connecting"));e?.aborted?s():e?.addEventListener("abort",s);try{await r;}finally{this.options.clock.clearTimeout(o),e?.removeEventListener("abort",s),this.ready=null;}}async kick(e){if(!this.isHost)throw new G("misconfigured","only the current host of this match can kick a peer");await this.options.api.kick(this.options.matchId,e);}async leave(){try{await this.options.api.leave(this.options.matchId);}catch{}this.close();}close(){if(!this.closed){this.closed=true,this.pendingOffers.clear();for(let e of [...this.links.values()])this.dropLink(e,"closed",false);this.options.signaling.close(),this.emitter.clear();}}report(e){this.options.api.telemetry(e).catch(()=>{});}notifyCandidatesDropped(e){this.emitter.emit("candidatesDropped",e);}handleSignal(e,n){this.closed||this.route(e,n).catch(r=>this.report_(r));}async route(e,n){switch(e){case "hello":return this.onHello(n);case "offer":return this.onOffer(n);case "answer":return this.onAnswer(n);case "ice":return this.onIce(n);case "peerLeft":return this.onPeerLeft(n);case "migration":return this.onMigration(n);case "matchEnded":return this.onMatchEnded(n);case "error":return this.onSignalingError(n);default:return}}async onHello(e){let n=de(e.playerId),r=de(e.hostPlayerId),i=Mr(e.hostEpoch);if(!(n===null||r===null||i===null)&&(this.mark("signaling hello"),this.localPlayerId=n,this.migration===null&&(this.migration=new un(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,vd),i=await r.connection.createOffer();await r.connection.setLocalDescription(i);let o=r.connection.localDescription?.sdp??i.sdp;if(!o)throw new G("invalid_sdp","the browser produced an offer with no SDP");We(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:At(r);if(i===null)throw new G("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??Lg,s=()=>this.closed||e!==this.credentialGeneration,a=Og;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 m=d.status,c;if(m===409)c=_d;else if(m===429){let p=d.retryAfterSeconds;typeof p=="number"&&Number.isFinite(p)&&p>=0?c=p*1e3:(c=a,a=Math.min(a*2,wd)),c=Math.min(Math.max(c,_d),wd);}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=de(e.fromPlayerId),r=de(e.sdp);if(n===null||r===null)return;if(this.migration===null){if(this.pendingOffers.delete(n),this.pendingOffers.size>=Dg){let m=this.pendingOffers.keys().next().value;m!==void 0&&this.pendingOffers.delete(m);}this.pendingOffers.set(n,e);return}if(!this.isHost||this.migration.isKicked(n)===true)return;let i=de(e.sessionId);if(i!==null&&this.answeredSessions.get(n)===i)return;We(r,"offer"),this.refuseMedia(r,"offer");let o=At(r);if(o===null)throw new G("invalid_sdp",`the offer from ${n} carries no usable fingerprint`);this.mark("offer received"),i!==null&&this.answeredSessions.set(n,i);let s=this.links.get(n);s&&this.dropLink(s,"resignalled",false);let a=this.openLink(n,this.nextPeerId++);a.remoteFingerprint=o,await a.connection.setRemoteDescription({type:"offer",sdp:r}),this.flushCandidates(a);let l=await a.connection.createAnswer();await a.connection.setLocalDescription(l);let d=a.connection.localDescription?.sdp??l.sdp;if(!d)throw new G("invalid_sdp","the browser produced an answer with no SDP");We(d,"answer"),this.refuseMedia(d,"answer"),this.options.signaling.answer(n,d,a.assignedPeerId),this.mark("answer sent");}async onAnswer(e){if(this.isHost)return;let n=de(e.fromPlayerId),r=de(e.sdp);if(n===null||r===null)return;let i=this.links.get(this.hostPlayerId);if(!i||n!==this.hostPlayerId)return;We(r,"answer"),this.refuseMedia(r,"answer");let o=At(r);if(o===null)throw new G("invalid_sdp","the host's answer carries no usable fingerprint");this.mark("answer received"),i.remoteFingerprint=o,i.pendingAnswer=r,this.hostVerified(i)&&await this.applyAnswer(i,r);}hostVerified(e){let n=this.credential;return n===null||e.remoteFingerprint===null?false:dn(n.hostFingerprint,e.remoteFingerprint)?true:(this.fail(new G("peer_unauthenticated","the host's DTLS certificate is not the one the platform attested for this match. Refusing before the handshake, so no credential is presented.")),this.dropLink(e,"host_fingerprint_mismatch",false),false)}maybeAuthenticate(){if(this.isHost)return;let e=this.links.get(this.hostPlayerId);if(!e||e.remoteFingerprint===null||e.connection.remoteDescription!==null)return;let n=e.pendingAnswer;n!==void 0&&this.hostVerified(e)&&this.applyAnswer(e,n).catch(r=>this.report_(r));}async applyAnswer(e,n){this.mark("host verified"),e.pendingAnswer=void 0,await e.connection.setRemoteDescription({type:"answer",sdp:n}),this.flushCandidates(e);}async onIce(e){let n=de(e.fromPlayerId),r=de(e.candidate);if(n===null||r===null)return;let i=this.links.get(n);if(!i)return;let o=de(e.sdpMid),s=Mr(e.sdpMLineIndex)??Mr(e.sdpMLineIndexAlt),a={candidate:r,...o===null?{}:{sdpMid:o},...s===null?{}:{sdpMLineIndex:s}};if(i.connection.remoteDescription===null){i.pendingCandidates.length<64&&i.pendingCandidates.push(a);return}await i.connection.addIceCandidate(a);}onPeerLeft(e){let n=de(e.playerId);if(n===null)return;let r=de(e.reason)??"left";if(n===this.localPlayerId){this.fail(new G("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=de(e.hostPlayerId),r=Mr(e.hostEpoch);if(n===null||r===null||this.migration===null)return;let i=this.migration.apply({hostPlayerId:n,hostEpoch:r,...de(e.reason)===null?{}:{reason:de(e.reason)},...Array.isArray(e.kickedPlayerIds)?{kickedPlayerIds:e.kickedPlayerIds.filter(o=>typeof o=="string")}:{},...typeof e.migrationComplete=="boolean"?{migrationComplete:e.migrationComplete}:{}},this.options.clock.now());if(i.kind!=="duplicate"){if(i.kind==="completed"){this.emitter.emit("hostChanged",n,r);return}if(i.kind==="refused"){this.report_(new G("migration_failed",i.why));return}for(let o of [...this.links.values()])this.dropLink(o,"migrating",false);if(this.options.signaling.discardQueued(),this.credential=null,this.emitter.emit("migrating",n,r),i.state==="preparing"){this.options.signaling.migrationAck(r),this.watchMigration();return}this.watchMigration(),await this.offerToHost("full_reconnect");}}watchMigration(){let e=this.hostEpoch;this.options.clock.setTimeout(()=>{this.closed||this.migration===null||this.migration.currentEpoch===e&&this.migration.stalled(this.options.clock.now())&&this.reportedStallEpoch!==e&&(this.reportedStallEpoch=e,this.report_(new G("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=de(e.reason)??"ended";this.ended=n,this.emitter.emit("matchEnded",n),this.ready!==null&&this.fail(new G("match_ended",`the match ended: ${n}`)),this.close();}onSignalingError(e){let n=de(e.code)??"unknown",r=de(e.message)??"the platform refused a signaling message";this.report_(new G("signaling_failed",`${n}: ${r}`));}openLink(e,n){let i=(this.options.peerConnectionFactory??wo)({iceServers:this.iceServers,...this.options.certificate===void 0?{}:{certificates:[this.options.certificate]}}),o={};for(let p of Fe){let g=i.createDataChannel(p,_o[p]);g.binaryType="arraybuffer",o[p]=g;}let s={playerId:e,assignedPeerId:n,connection:i,channels:o,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),m=p=>{this.onHandshakeMessage(s,p.data).catch(g=>this.report_(g));},c=()=>{this.onReliableOpen(s).catch(p=>this.report_(p));};return i.addEventListener("icecandidate",a),i.addEventListener("iceconnectionstatechange",l),i.addEventListener("connectionstatechange",d),o.reliable.addEventListener("open",c),o.reliable.addEventListener("message",m),s.detachHandshake=()=>{o.reliable.removeEventListener("open",c),o.reliable.removeEventListener("message",m);},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 G("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 G("timeout","the join credential expired before the channel opened \u2014 reconnect for a fresh one");e.channels.reliable.send(fo({jwt:n.credential,protocolVersion:32769,assignedPeerId:e.assignedPeerId}));}async onHandshakeMessage(e,n){if(!(n instanceof ArrayBuffer))return;let r=vo(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 G(hd(r.reason),fd(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=At(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 yo(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 G&&s.reason==="keys_unavailable";this.refuseLink(e,a?131:1,a?"keys_unavailable":"credential_invalid",ko(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(ho({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(bo(n));}catch{}this.dropLink(e,r,false);}finishAdmission(e){this.mark(this.isHost?"peer admitted":"admitted"),e.admitted=true,e.detachHandshake(),e.detachHandshake=()=>{},this.emitter.emit("peerJoined",this.expose(e)),this.settle();}onIceState(e){let n=e.connection.iceConnectionState;if(!(n!=="failed"&&n!=="disconnected"&&n!=="closed")){if(this.isHost){(n==="failed"||n==="closed")&&this.dropLink(e,n,true);return}if(this.reportedUnreachableEpoch!==this.hostEpoch){this.reportedUnreachableEpoch=this.hostEpoch;try{this.options.signaling.reportHostUnreachable(this.hostEpoch,n);}catch(r){this.report_(r);}}}}onConnectionState(e){let n=e.connection.connectionState;n!=="failed"&&n!=="closed"||this.dropLink(e,n,true);}expose(e){return {playerId:e.playerId,assignedPeerId:e.assignedPeerId,connection:e.connection,channels:e.channels,send:(n,r="reliable")=>e.channels[r].send(n)}}dropLink(e,n,r){this.links.delete(e.playerId),e.detachAll();for(let i of Fe)kd(e.channels[i]);kd(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 G?e:new G("connection_failed",ko(e),{cause:e}));}count(e){this.counted||!$g.has(e)||(this.counted=true,this.report([{type:"connection_failures_total",value:1}]));}refuseMedia(e,n){if(Er(e))throw new G("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 de(t){return typeof t=="string"&&t.length>0?t:null}function Mr(t){return typeof t=="number"&&Number.isInteger(t)?t:null}function ko(t){return t instanceof Error?t.message:String(t)}function kd(t){try{t.close();}catch{}}var Fg=100,qg=50,yn=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??Fg)){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 G("signaling_unavailable","this signaling client has been closed");if(!this.options.bridge.parentSupports("p2p"))throw new G("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??qg));}};function H(t){return e=>typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function He(t,e){return n=>typeof n=="number"&&Number.isInteger(n)&&n>=t&&n<=e?n:void 0}function Pt(...t){return e=>typeof e=="string"&&t.includes(e)?e:void 0}function Sd(t){return typeof t=="boolean"?t:void 0}var ve=H(64),fn=He(0,2147483647);function Ro(t){if(!Array.isArray(t))return;let e=[];for(let n of t){if(e.length>=64)break;let r=ve(n);typeof r=="string"&&e.push(r);}return e}function Y(t,e,n){return {to:t,from:e,read:n,required:true}}function V(t,e,n){return {to:t,from:e,read:n,required:false}}var Ug=t=>{if(typeof t!="object"||t===null||Array.isArray(t))return;let e=t,n=Pt("disconnected","failed","closed")(e.iceState),r=He(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:[Y("sdp","sdp",H(10240)),Y("signaling_intent","intent",Pt("initial","ice_restart","full_reconnect")),V("sdp_hash","sdpHash",H(128))]},answer:{type:"p2p_answer",gameScoped:false,args:[Y("peer_id","peerId",ve),Y("sdp","sdp",H(10240)),Y("assigned_peer_id","assignedPeerId",He(0,4294967295)),V("sdp_hash","sdpHash",H(128))]},ice:{type:"p2p_ice_candidate",gameScoped:false,args:[Y("peer_id","peerId",ve),Y("candidate","candidate",H(512)),V("sdp_mid","sdpMid",H(64)),V("sdp_mline_index","sdpMLineIndex",He(0,255))]},migrationAck:{type:"p2p_migration_ack",gameScoped:false,args:[Y("host_epoch","hostEpoch",fn)]},hostUnreachable:{type:"p2p_report_host_unreachable",gameScoped:false,args:[Y("host_epoch","hostEpoch",fn),V("evidence","evidence",Ug)]}}));Object.freeze(Object.assign(Object.create(null),{p2p_hello:"hello",p2p_sdp_offer:"offer",p2p_sdp_answer:"answer",p2p_ice_candidate:"ice",p2p_peer_joined:"peerJoined",p2p_peer_left:"peerLeft",p2p_host_migration:"migration",p2p_match_ended:"matchEnded",p2p_error:"error"}));Object.freeze(Object.assign(Object.create(null),{hello:[Y("playerId","player_id",ve),Y("hostPlayerId","host_player_id",ve),Y("hostEpoch","host_epoch",fn),V("members","members",Ro)],offer:[Y("fromPlayerId","from_player_id",ve),Y("sdp","sdp",H(10240)),V("sessionId","signaling_session_id",H(128)),V("sdpHash","sdp_hash",H(128)),V("iceUfrag","ice_ufrag",H(64)),V("intent","signaling_intent",Pt("initial","ice_restart","full_reconnect"))],answer:[Y("fromPlayerId","from_player_id",ve),Y("sdp","sdp",H(10240)),V("sessionId","signaling_session_id",H(128)),V("sdpHash","sdp_hash",H(128)),V("iceUfrag","ice_ufrag",H(64)),V("assignedPeerId","assigned_peer_id",He(0,4294967295))],ice:[Y("fromPlayerId","from_player_id",ve),Y("candidate","candidate",H(512)),V("sdpMid","sdp_mid",H(64)),V("sdpMLineIndex","sdp_m_line_index",He(0,255)),V("sdpMLineIndexAlt","sdp_mline_index",He(0,255))],peerJoined:[Y("playerId","player_id",ve)],peerLeft:[Y("playerId","player_id",ve),V("reason","reason",H(64))],migration:[Y("hostPlayerId","new_host_player_id",ve),Y("hostEpoch","host_epoch",fn),V("reason","reason",H(64)),V("kickedPlayerIds","kicked_player_ids",Ro),V("migrationComplete","migration_complete",Sd)],matchEnded:[V("reason","reason",H(64))],error:[V("code","code",H(64)),V("message","message",H(256))]}));Object.freeze(Object.assign(Object.create(null),{party_invite_received:"inviteReceived",party_member_joined:"memberJoined",party_member_left:"memberLeft",party_member_kicked:"memberKicked",party_leader_transferred:"leaderTransferred",party_updated:"updated",party_disbanded:"disbanded",party_game_room_joined:"gameRoomJoined",party_game_room_left:"gameRoomLeft"}));var tt="webrtc_p2p";function xd(t){let e=new ln({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 G("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=ye(r.clusterTargetId),o=i??ye(await t.resolveClusterTarget?.());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!==tt)throw new G("unsupported_protocol",`match ${s.matchId} speaks '${s.protocol}', not '${tt}'. Use \`dedicatedServer.connect()\` for a dedicated match; the two flows share WebRTC and nothing else.`);let a=new yn({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===void 0?{}:{clusterTargetId:o},...r.peerConnectionFactory===void 0?{}:{peerConnectionFactory:r.peerConnectionFactory},certificate:r.certificate??await mn(),...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}}}function Ad(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(!Ze());for(let d of xr)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(!Ze());}let s=new Map;return o.push(n.on("matchReady",a=>{let l=a.protocol===tt?"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 Pd=["pointerdown","keydown"];function Td(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 g of Pd)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(y=>y?.buttons.some(v=>v.pressed)===true)},m=()=>{try{return (e.navigator?.getGamepads?.()??[]).some(g=>g!==null)}catch{return false}},c=()=>{if(i=null,!(n||r)){if(d()){a();return}m()&&(i=e.requestAnimationFrame?.(c)??null);}};function p(){i===null&&!n&&!r&&c();}if(typeof e.addEventListener=="function"){for(let g of Pd)e.addEventListener(g,l,{capture:true,passive:true});e.addEventListener("gamepadconnected",p,{capture:true,passive:true}),m()&&(i=e.requestAnimationFrame?.(c)??null);}return {get engaged(){return n},stop:s}}async function Or(t,e,n,r){let i=await n;return t.mark(e)&&r&&r(`[gem] boot: ${t.timeline()}`),i}function xo(t,e){let n=false;return async r=>{let i=await r;return !n&&e&&(n=true,e(`[gem] boot: ${t.timeline()}`)),i}}function Ao(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 Bg="GemWebSdkHandshake";var Wg=()=>Date.now();function Ed(t,e,n={}){let r=t[Bg];if(r===void 0)return null;let i=n.ttlMs??9500,o=n.now??Wg,s=r.events.splice(0),a=r.times?.splice(0),l=0,d=0,m=false,c=o()-i;for(let p=s.length-1;p>=0;p--){let g=a?.[p];if(g!==void 0&&g<c){d+=1;continue}if(l+=1,e(s[p])===true){m=true;break}}return r.uninstall(),{capture:r,delivered:l,stale:d,accepted:m}}var Po=new WeakMap,Cd=new WeakSet,To=new Set,Gr=new Set,Lr=[],Et=null,Eo=false,Hg=1920;function Co(t){return Po.get(t)}function Io(t){return !Eo||Cd.has(t)}function Mo(t){return t.kind==="webgpu"?true:t.kind!=="webgl"&&t.kind!=="webgl2"&&t.kind!=="experimental-webgl"?false:t.context.getContextAttributes()?.preserveDrawingBuffer!==true}function Id(t=globalThis.window){if(Eo||!t?.HTMLCanvasElement||typeof t.requestAnimationFrame!="function")return;Eo=true;for(let o of Array.from(t.document?.querySelectorAll("canvas")??[]))Cd.add(o);let e=t.HTMLCanvasElement.prototype,n=e.getContext;e.getContext=function(o,...s){let a=n.call(this,o,...s);if(a&&!Po.has(this)){let l={kind:o,context:a};Po.set(this,l),Mo(l)&&To.add(this);}return a};let r=t.requestAnimationFrame,i=t.cancelAnimationFrame;t.requestAnimationFrame=o=>{let s=r.call(t,a=>{Gr.delete(s);try{o(a);}finally{Vg();}});return Gr.add(s),Gd(),s},t.cancelAnimationFrame=o=>{Gr.delete(o),i.call(t,o);};}function Md(t,e){return new Promise(n=>{let r={canvas:t,done:o=>{clearTimeout(i),Lr=Lr.filter(s=>s!==r),n(o);}},i=setTimeout(()=>r.done(null),e);Lr.push(r);})}function Od(t){return Et?.canvas===t?Et.bitmap:null}function Vg(){for(let t of Lr){let e;try{e=Oo(t.canvas);}catch(n){t.done(Promise.reject(n));continue}e&&t.done(createImageBitmap(t.canvas));}Gr.size===0&&Kg();}function Kg(){let t=null;for(let r of To)r.isConnected?(!t||r.width*r.height>t.width*t.height)&&(t=r):To.delete(r);if(!t||t.width===0||t.height===0)return;let e=Math.min(1,Hg/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"}:{};Gd(),Et={canvas:t,bitmap:createImageBitmap(t,n).catch(()=>null)};}function Gd(){Et&&(Et.bitmap.then(t=>t?.close()),Et=null);}function Oo(t){let e=Jg();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 hn;function Jg(){if(hn!==void 0)return hn;if(typeof OffscreenCanvas=="function")hn=new OffscreenCanvas(8,8).getContext("2d",{willReadFrequently:true});else {let t=globalThis.document?.createElement("canvas");t&&(t.width=t.height=8),hn=t?.getContext("2d",{willReadFrequently:true})??null;}return hn??null}var Go=false;async function Fd(t,e,n,r){if(Go){e.close(),n("busy",true);return}Go=true;let i=null;try{let o=await Xg(t,r);if(typeof o=="string"){e.close(),n(o,zg(o));return}i=o;let a=await(r.encodeRef??(l=>ny(l,r)))(i);if(i.close(),i=null,a===null){e.close(),n("failed",!0);return}if(a.size>ty){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{Go=false,i?.close();}}function zg(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 Yg=600;async function Xg(t,e){if(e.handler){let i=await e.handler(t);return i===null?"declined":Ld(i,t)}if(!e.useDefaultStrategy)return "not_wired";let n=e.documentRef??globalThis.document;if(!n)return "no_source";let r=ey(n);if(!r)return "no_source";try{let i=await Qg(r);return typeof i=="string"?i:Ld(i,t)}catch(i){if(i instanceof DOMException&&i.name==="SecurityError")return "tainted";throw i}}async function Qg(t){let e=Zg(t);if(typeof e=="string")return e;if(e.kind.includes("webgl")&&!e.context.getContextAttributes())return "unsupported";if(!Mo(e))return createImageBitmap(t);let n=await Md(t,Yg);if(n)return n;let r=await Od(t);return r&&Oo(r)?createImageBitmap(r):e.kind==="webgpu"?"unreadable":"unsupported"}function Zg(t){let e=Co(t);if(e)return e;if(!Io(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 ey(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||!Co(r)&&!Io(r)||i>n&&(e=r,n=i);}return e}async function Ld(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 ty=8*1024*1024,Dd="image/webp",$d=.92;async function ny(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:Dd,quality:$d});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),Dd,$d);})}async function qd(t,e){if(!e)return;let n;try{n=await ry(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 ry(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 Nd=Symbol.for("@indiegems/gem-web-sdk:audio-guard");function jd(t=globalThis){let n=t[Nd];if(n!==void 0)return n;let r=false,i=()=>r,o=[],s=iy(t,i);s!==null&&o.push(s);let a=oy(t,i);a!==null&&o.push(a);let l={get muted(){return r},setMuted(d){let m=!!d;if(m!==r){r=m;for(let c of o)c();}}};return Object.defineProperty(t,Nd,{value:l,configurable:true}),l}function iy(t,e){let n=t.AudioNode?.prototype,r=t.AudioDestinationNode;if(n===void 0||r===void 0)return null;let i=t.OfflineAudioContext,o=n.connect,s=n.disconnect,a=new Map,l=m=>{let c=m.gain,p=m.context.currentTime;c.cancelScheduledValues(p),e()?c.setValueAtTime(0,p):c.setTargetAtTime(1,p,.01);},d=m=>{let c=m.context;if(i!==void 0&&c instanceof i)return null;let p=a.get(c);return p===void 0&&(p=c.createGain(),p.gain.value=e()?0:1,o.call(p,m),a.set(c,p)),p};return n.connect=function(...c){let[p,...g]=c;if(p instanceof r){let y;try{y=d(p);}catch{y=null;}if(y!==null)return o.call(this,y,...g),p}return o.apply(this,c)},n.disconnect=function(...c){let[p,...g]=c;if(p instanceof r){let y=a.get(p.context);if(y!==void 0&&y!==this)try{return s.call(this,y,...g)}catch{}}return s.apply(this,c)},()=>{for(let[m,c]of a){if(m.state==="closed"){a.delete(m);continue}try{l(c);}catch{}}}}function oy(t,e){let n=t.HTMLMediaElement;if(n===void 0)return null;let r=n.prototype,i=Object.getOwnPropertyDescriptor(r,"muted"),o=i?.get,s=i?.set;if(o===void 0||s===void 0)return null;let a=r.play,l=new WeakMap,d=new WeakSet,m=new Set,c=p=>{l.has(p)||l.set(p,!!o.call(p)),d.has(p)||(d.add(p),m.add(new WeakRef(p))),s.call(p,(l.get(p)??false)||e());};return Object.defineProperty(r,"muted",{configurable:true,enumerable:i?.enumerable??true,get(){let p=l.get(this);return p===void 0?!!o.call(this):p},set(p){l.set(this,!!p),c(this);}}),r.play=function(){try{c(this);}catch{}return a.call(this)},t.document?.addEventListener("play",p=>{let g=p.target;if(g instanceof n)try{c(g);}catch{}},true),()=>{for(let p of m){let g=p.deref();if(g===void 0){m.delete(p);continue}try{s.call(g,(l.get(g)??!1)||e());}catch{}}}}var ay=":where(html){-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;-webkit-tap-highlight-color:transparent}",sy=':where(input,textarea,select,[contenteditable]:not([contenteditable="false"])){-webkit-user-select:text;user-select:text;-webkit-touch-callout:default}',ly=`${ay}${sy}`,Lo=new WeakSet;function Ud(t=globalThis.document){if(t==null||Lo.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(ly),t.adoptedStyleSheets=[...t.adoptedStyleSheets,r],Lo.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"),Lo.add(t),"inline")}catch{return null}}function Bd(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,m=[],c=false,p=0,g=null,y=[],v=()=>i&&!o&&!s,S=()=>{l=null,d=null,m=[],p=0,g=null,y=[];},R=k=>{if(a=null,!v()){S();return}if(d!==null&&m.push(k-d),d=k,l===null)l=k;else {let C=k-l;if(C>=e&&m.length>0){if(c){let T=g===null?C:r()-g;t.report(cy(p,y,C,T));}else t.report(dy(m,C));l=k,m=[],p=0,y=[];}}P();},P=()=>{let k=n.requestAnimationFrame;typeof k=="function"&&(a=k.call(n,R));},h=()=>{if(v()){a===null&&(S(),P());return}a!==null&&(n.cancelAnimationFrame?.call(n,a),a=null),S();};return {setRequested(k){i=k,h();},setPaused(k){o=k,h();},draw(){if(!c){c=true,a!==null&&S();return}if(a===null||l===null)return;let k=r();g!==null&&y.length<1e3&&y.push(k-g),g=k,p+=1;},get running(){return a!==null},dispose(){s=true,h();}}}function dy(t,e){return {fps:t.length*1e3/e,frameTimeP95Ms:Wd(t),counts:"pageFrames"}}function cy(t,e,n,r){let i=r;return e.length>0&&(i=Wd(r>Math.max(...e)?[...e,r]:e)),{fps:t*1e3/n,frameTimeP95Ms:i,counts:"gameDraws"}}function Wd(t){let e=[...t].sort((r,i)=>r-i),n=Math.max(1,Math.ceil(e.length*.95));return e[n-1]}var Dr=Object.freeze({top:"--gem-safe-top",right:"--gem-safe-right",bottom:"--gem-safe-bottom",left:"--gem-safe-left"});function Hd(){let e=globalThis.document?.documentElement;return e&&typeof e.style?.setProperty=="function"?e:null}function Vd(t,e){t!==null&&(t.style.setProperty(Dr.top,`${e.top}px`),t.style.setProperty(Dr.right,`${e.right}px`),t.style.setProperty(Dr.bottom,`${e.bottom}px`),t.style.setProperty(Dr.left,`${e.left}px`));}var $r=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 Kd(){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 uy(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 m=l.control;l.control=m?{top:Math.min(m.top,d.y),bottom:Math.max(m.bottom,d.y+d.height)}:{top:d.y,bottom:d.y+d.height};}}return n}function Jd(t,e,n){if(t===null)return;let r=uy(e,n);for(let i of ["tl","tr","bl","br"]){t.style.setProperty($r[i].width,`${r[i].width}px`),t.style.setProperty($r[i].height,`${r[i].height}px`);let o=r[i].control;t.style.setProperty($r[i].centerY,o?`${(o.top+o.bottom)/2}px`:""),t.style.setProperty($r[i].controlHeight,o?`${o.bottom-o.top}px`:"");}}var my=3e4,Fr=class extends Error{retryable;reason;constructor(e,n,r){super(r),this.name="LocalServerError",this.reason=e,this.retryable=n;}};function zd(t){let e=t.clock??he,n=t.timeoutMs??my,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((m,c)=>{let p=`ls${++o}`,g=e.setTimeout(()=>{r.delete(p),i.delete(a),c(new Fr("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:m,reject:c,timer:g}),t.bridge.requestLocalServer(p,a)||(s(p),m());});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 Fr(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 bn={url:"https://downloads.indiegems.games/sdk/v15.1.1/gem-web-sdk.devtools.min.js",integrity:"sha384-+6WXkxYqk8+nRtfc6z1q8rGrpPJtnPmLLcOr7vM8ytfuHM0xI8zOznQLmlxI+WrN"};var Ct=null;function py(){return Ct!==null||(Ct=new Promise((t,e)=>{let n=document.createElement("script");n.src=bn.url,n.integrity=bn.integrity,n.crossOrigin="anonymous",n.onload=()=>{let r=window.GemWebSdkDevtools;if(r===void 0){Ct=null,e(new Error(`gem devtools: the panel loaded but attached nothing. The artifact at ${bn.url} is not a gem-web-sdk devtools build.`));return}t(r);},n.onerror=()=>{Ct=null,e(new Error(`gem devtools: could not load ${bn.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);})),Ct}function Yd(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 py();return !e()||s!==r?false:(n!==null||(n=a.mount(t(),{openedBy:o,text:ht,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 gy=1e4,Xd={reason:"unavailable",retryable:false};function Qd(t){let e=new Map,n=null,r=null,i=0,o=(d,m)=>{m.timer=t.clock.setTimeout(()=>{e.delete(d),m.reject({reason:"timeout",retryable:true});},t.timeoutMs??gy);},s=(d,m)=>{let c=a(d);c&&m(c);},a=d=>{let m=e.get(d);return m?(e.delete(d),t.clock.clearTimeout(m.timer),m):null},l=new mt({clock:t.clock,onStateChange:t.onStateChange,request:d=>new Promise((m,c)=>{let p=t.bridge.currentState;if(p==="refused"||p==="closed"){c(Xd);return}let g=`t${++i}`,y={resolve:m,reject:c,reason:d,timer:null,held:p!=="connected"};e.set(g,y),o(g,y),y.held||t.bridge.requestToken(g,d);})});return {source:l,onToken(d){let m={token:d.token,expiresAt:d.expiresAt,chainEndsAt:d.chainEndsAt};if(n={playerId:d.playerId,gameId:d.gameId,channel:d.channel},r=d.gameVersion??null,d.requestId!==void 0&&e.has(d.requestId)){s(d.requestId,c=>c.resolve(m));return}l.accept(m);},onDenied(d){s(d.requestId,m=>m.reject({reason:d.reason,retryable:d.retryable,retryAfterMs:d.retryAfterMs}));},onBridgeState(d){if(d==="connected")for(let[m,c]of e)c.held&&(c.held=false,t.clock.clearTimeout(c.timer),o(m,c),t.bridge.requestToken(m,c.reason));else if(d==="refused"||d==="closed")for(let m of [...e.keys()])s(m,c=>c.reject(Xd));},get identity(){return n},get gameVersion(){return r}}}function yy(t){let e=t.lastIndexOf("@");return (e===-1?t:`***@${t.slice(e+1)}`).slice(0,200)}var fy=new Set(ai);function hy(t){if(!t)return {};let e={};for(let[n,r]of Object.entries(t))fy.has(n.toLowerCase())&&(e[n.toLowerCase()]=r);return e}function qr(t){let e=t.fetch??globalThis.fetch.bind(globalThis);return ka(async(n,r)=>{let i;try{i=new URL(t.baseUrl.replace(/\/+$/,""));}catch{throw new se("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 se(`${JSON.stringify(typeof n.path=="string"?yy(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 se(`${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 g=i.username!==""||i.password!=="",y=o.username!==i.username||o.password!==i.password,v=g?y?"baseUrl (and possibly the request path)":"baseUrl":"request path";throw new se(`the ${v} 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[g,y]of Object.entries(t.defaultQuery??{}))o.searchParams.has(g)||o.searchParams.set(g,y);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 se(`the body of ${n.method} ${JSON.stringify(o.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(o.toString(),{method:n.method,headers:{authorization:`Bearer ${r}`,...a===void 0?{}:{"content-type":a},...hy(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 m=l.headers.get("etag"),c=by(l.headers.get("retry-after")),p=l.headers.get("x-gem-invocation-id");return {status:l.status,body:d,...m===null?{}:{etag:m},...c===void 0?{}:{retryAfterSeconds:c},...p===null||p===""?{}:{invocationId:p}}},t)}function by(t){if(t===null)return;let e=t.trim();if(!/^\d+$/.test(e))return;let n=Number(e);return Number.isFinite(n)?n:void 0}var vy=new Set(["invalid_sdp","age_restricted","match_not_found","not_match_member","account_banned"]),$o="embedder_relay_unavailable",_y="embedder_no_relay",wy=new Set([$o]),Fo=new Set([_y]),vn=class{constructor(e){this.options=e;}options;pending=new Map;channel(){return new Do(this)}handleEvent(e){let n=this.pending.get(e.matchId);if(n!==void 0){if(e.event==="matchEnded"){n.refuse(new w("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 w("signaling_failed","the parent relayed an answer with no SDP in it"));return}n.settle({sdp:e.sdp});return}n.refuse(ky(e.code,e.message));}}register(e,n){this.pending.get(e)?.refuse(new w("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 w("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 w("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 ky(t,e){let n=e??"the offer was refused",r=t===void 0?n:`${n} (${t})`;return new w(Sy(t),r,{platformCode:t})}function Sy(t){return t===void 0||wy.has(t)?"signaling_failed":Fo.has(t)?"offer_refused":vy.has(t)?t==="invalid_sdp"?"invalid_sdp":"offer_refused":"signaling_failed"}var Do=class{constructor(e){this.hub=e;}hub;closed=false;teardown=null;exchange(e,n){if(this.closed)return Promise.reject(new w("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 w("aborted","the caller aborted before the offer was sent")):new Promise((i,o)=>{let s=()=>{a(),o(new w("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 w?d:new w("signaling_failed",d instanceof Error?d.message:String(d),{cause:d}));}})}close(){this.closed=true,this.teardown?.(),this.teardown=null;}};var Zd="match_ended:",ec="server_shutdown:",tc="kicked:",Ry=123;function xy(t){if(typeof t!="string"||t.length===0||t.length>Ry)return {kind:"other"};if(t.startsWith(Zd)){let e=wt(t.slice(Zd.length));return e==="unknown"?{kind:"other"}:{kind:"match_ended",reason:e}}return t.startsWith(ec)?{kind:"server_shutdown",cause:t.slice(ec.length)}:t.startsWith(tc)?{kind:"kicked",detail:t.slice(tc.length)}:{kind:"other"}}function qo(t,e,n){let r=xy(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 No(){return {exchange(){return Promise.reject(new w("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 Ay=3e3,Py=1e4,Ty=15e3;async function Nr(t){let e=t.peerConnection;try{rc(t,"before the handshake started"),jo(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 Iy(e,t),jo(t);let i=e.localDescription?.sdp??r.sdp;if(!i)throw new w("invalid_sdp","the offer carried no SDP");We(i,"offer"),nc(i,"offer");let o=await Cy(t,i);if(jo(t),typeof o?.sdp!="string")throw new w("invalid_sdp","the signaling channel answered without an SDP");return We(o.sdp,"answer"),nc(o.sdp,"answer"),await e.setRemoteDescription({type:"answer",sdp:o.sdp}),await My(n,t),rc(t,"before the channel opened"),n}catch(n){throw e.close(),Ey(n)}}function Ey(t){return t instanceof w?t:ac(t)?nt():new w("connection_failed",sc(t),{cause:t})}function nc(t,e){if(Er(t))throw new w("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 Cy(t,e){let n=t.exchangeTimeoutMs??Py,r=oc(t,n),i=t.signaling.exchange({matchId:t.matchId,sdp:e,intent:t.intent??"initial"},t.signal).catch(o=>{throw o instanceof w?o:ac(o)?nt():new w("signaling_failed",sc(o),{cause:o})});return Oy(i,t,r,()=>r.exhausted?Uo("while the offer was in flight"):new w("timeout",`no answer arrived within ${n}ms`))}function Iy(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??Ay);t.addEventListener("icegatheringstatechange",o),e.signal?.addEventListener("abort",i);})}function My(t,e){if(e.signal?.aborted)return Promise.reject(nt());if(t.readyState==="open")return Promise.resolve();if(t.readyState!=="connecting")return Promise.reject(new w("connection_failed",`the data channel was already '${t.readyState}' when the answer was applied`));let{clock:n}=e,r=e.openTimeoutMs??Ty,i=oc(e,r);return new Promise((o,s)=>{let a=()=>{n.clearTimeout(p),t.removeEventListener("open",l),t.removeEventListener("close",d),t.removeEventListener("error",d),e.signal?.removeEventListener("abort",m);},l=()=>{a(),o();},d=g=>{a(),s(new w("connection_failed","the data channel failed before it opened",ic(g)===void 0?void 0:{cause:ic(g)}));},m=()=>{a(),s(nt());},c=()=>{a(),s(i.exhausted?Uo("while the channel was still opening"):new w("timeout",`the data channel did not open within ${r}ms`));},p=n.setTimeout(c,i.ms);t.addEventListener("open",l),t.addEventListener("close",d),t.addEventListener("error",d),e.signal?.addEventListener("abort",m);})}function oc(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 Oy(t,e,n,r){let{clock:i,signal:o}=e;return o?.aborted?Promise.reject(nt()):new Promise((s,a)=>{let l=c=>{i.clearTimeout(m),o?.removeEventListener("abort",d),c();},d=()=>l(()=>a(nt())),m=i.setTimeout(()=>l(()=>a(r())),n.ms);o?.addEventListener("abort",d),t.then(c=>l(()=>s(c)),c=>l(()=>a(c)));})}function rc(t,e){if(t.credentialExpiresAt!==void 0&&!(t.clock.now()<t.credentialExpiresAt))throw Uo(`already ${e}`)}function Uo(t){return new w("credential_expired",`the join credential ran out ${t} \u2014 poll match status again for a fresh one`)}function jo(t){if(t.signal?.aborted)throw nt()}function nt(){return new w("aborted","the caller aborted the connection attempt")}function ac(t){return t?.name==="AbortError"}function ic(t){return t?.error}function sc(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:[Y("sdp","sdp",H(10240)),V("sessionId","session_id",H(64))],error:[V("code","code",H(64)),V("message","message",H(256))],matchEnded:[V("reason","reason",H(64))]}));function yc(t){let{client:e,clock:n,rooms:r}=t,i=t.signaling??No,o=t.log??(h=>console.warn(h)),s=new xt({client:e,gameId:()=>r.gameId,transport:"dedicated"}),a=new Map,l=(h,k)=>{let C=a.get(h)??new Set;C.add(k),a.set(h,C);},d=(h,k)=>{let C=a.get(h);C!==void 0&&(C.delete(k),C.size===0&&a.delete(h));},m=async h=>{if(r.isHost&&!Wo(r)&&r.currentRoom?.matchId===void 0){let k=ye(h.clusterTargetId);await r.startMatch({...k===void 0?{}:{clusterTargetId:k},...h.retry===void 0?{}:{retry:h.retry},...h.signal===void 0?{}:{signal:h.signal}});}return pc(r.matchConnectionState==="suspended"?await r.reconnectToMatch(Bo(h)):await r.awaitMatch(Bo(h)))},c=async h=>pc(await r.pollMatchStatus(Bo(h))),p=async(h,k)=>{let C=false;try{let T=await m(h),W=r.currentRoom?.transports;if(W!==void 0&&!W.includes("webrtc"))throw new w("misconfigured",`the room template offers (${W.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 $=h.peerConnection??gc();C=!0;let N=await Nr({peerConnection:$,signaling:k,clock:n,matchId:T.matchId,credentialExpiresAt:T.credentialExpiresAt,...jr(h,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal")}),E=null;if(h.presentCredential!==!1)try{E=await en({channel:N,clock:n,credential:T.joinCredential,credentialExpiresAt:T.credentialExpiresAt,...jr(h,"onMessage","signal"),...h.welcomeTimeoutMs===void 0?{}:{ceilingMs:h.welcomeTimeoutMs}});}catch(M){throw Ae(N),Ae($),M}return Uy(r,T,N,$,k,h.reportDisconnect!==!1,h.reportConnected!==!1,E,{remember:l,forget:d},h.onMatchEnded)}catch(T){throw C&&mc(s,T),Ae(k),T}},g=async(h,k,C,T,W,$)=>{if(h==="webtransport"){let B=T?.webtransport;if(B===void 0)throw new w("misconfigured","webtransport is not advertised");let K={credential:C.joinCredential,credentialExpiresAt:C.credentialExpiresAt,clock:n};if(typeof B.named_url=="string"&&B.named_url!==""){let te=Math.max(Math.floor($/2),1e3);try{return await on({url:B.named_url,timeoutMs:te,log:o,...K})}catch(me){if(wr()!==null)throw me;return o(`[gem] webtransport named dial failed (${vr(me)}); retrying the pinned dial`),on({url:B.url,certHashBase64:B.cert_sha256_b64,timeoutMs:te,log:o,...K})}}return on({url:B.url,certHashBase64:B.cert_sha256_b64,timeoutMs:$,...K})}if(h==="websocket"){let B=T?.websocket;if(B===void 0)throw new w("misconfigured","websocket is not advertised");return ro({url:B.url,credential:C.joinCredential,credentialExpiresAt:C.credentialExpiresAt,clock:n,timeoutMs:$})}let N=k.peerConnection??gc(),E,M=await Nr({peerConnection:N,signaling:W,clock:n,matchId:C.matchId,credentialExpiresAt:C.credentialExpiresAt,extraChannels:[{label:nn,ordered:false,maxRetransmits:0}],onExtraChannel:(B,K)=>{B===nn&&(E=K);},...jr(k,"intent","channelLabel","gatherTimeoutMs","exchangeTimeoutMs","openTimeoutMs","signal"),...k.exchangeTimeoutMs===void 0&&k.redial===true?{exchangeTimeoutMs:Dy}:{}}),L;try{L=await en({channel:M,clock:n,credential:C.joinCredential,credentialExpiresAt:C.credentialExpiresAt,wire:br,heartbeat:!0,...jr(k,"signal"),...k.welcomeTimeoutMs===void 0?{}:{ceilingMs:k.welcomeTimeoutMs}});}catch(B){throw Ae(M),Ae(N),B}let F=L.welcome.heartbeatIntervalMs;return {link:oo(M,N,E,F===void 0?void 0:{clock:n,intervalMs:F}),welcome:L.welcome,channel:M,peerConnection:N}},y=(h,k,C,T,W)=>{let $=false,N;T.link.onClose(F=>{!$&&h.reportDisconnect!==false&&qo(r,k.matchId,F),N?.(F);}),h.reportDisconnect!==false&&h.reportConnected!==false&&r.notifyMatchConnected(k.matchId);let E={transport:T.link.transport,send:(F,B)=>T.link.send(F,B),onMessage:F=>T.link.onMessage(F),onClose:F=>{N=F;},close:()=>T.link.close()},M=()=>{$||($=true,Ae(T.link),Ae(W));},L=F=>{if(!$){try{h.onMatchEnded?.(F);}catch{}M();}};return l(k.matchId,L),{matchId:k.matchId,transport:C,link:E,joinCredential:k.joinCredential,credentialExpiresAt:k.credentialExpiresAt,welcome:T.welcome,...T.channel===void 0?{}:{channel:T.channel},...T.peerConnection===void 0?{}:{peerConnection:T.peerConnection},close(){d(k.matchId,L),M();}}},v=async(h,k)=>{let C=r.currentRoom?.id,T=r.gameId,W=()=>({advert:rn(r.currentRoom?.settings,h),template:r.currentRoom?.transports??null});if(C===void 0||T===null)return W();try{let $=await e.get(`/v2/games/${encodeURIComponent(T)}/game-rooms/${encodeURIComponent(C)}`,k);return {advert:rn($.settings,h),template:St($.transports)??r.currentRoom?.transports??null}}catch{return W()}},S=(h,k)=>{let C=h??lc;return k.length===0?C:C.filter(T=>k.includes(T))},R=async(h,k,C)=>{try{let T=await m(h),{advert:W,template:$}=await v(T.matchId,h.signal),N=S($,k),E=N.filter(z=>qy(z,W)),M=wr();if(M!==null&&N.includes("webtransport")&&W?.webtransport!==void 0&&o(`[gem] webtransport skipped: ${M} (learned on an earlier dial in this page)`),E.length===0){let z=$===null?`the default order (${lc.join(", ")})`:`the room template's transports (${$.join(", ")||"none"})`;throw new w("misconfigured",`none of ${z}`+(k.length>0?`, narrowed to (${k.join(", ")}),`:"")+" is available here: the server advertises none of them, and only webrtc qualifies without an advertisement.")}let L=h.transportAttemptTimeoutMs??Ly,F=()=>h.deadlineAt===void 0?1/0:h.deadlineAt-n.now(),B=z=>t.signalingReady===void 0||z<=0?Promise.resolve(!0):t.signalingReady(z),K=[],te=[];for(let z of E){if(F()<cc){o(`[gem] ${z} rung not tried: the reconnect budget is spent`);break}te.length>0&&T.credentialExpiresAt-n.now()<uc&&(T=await c(h)),te.push(z);let qe=!1,_e=!1,pe={attempts:0,waitedMs:0};for(;;){if(z==="webrtc"&&h.redial===!0){let Z=Math.min(dc,F());await B(Z)||o(`[gem] webrtc rung: the page has not reported its signaling socket up after ${Math.round(Z)}ms; offering anyway`);}let Ne=Math.max(Math.min(L,F()),cc);try{return y(h,T,z,await g(z,h,T,W,C,Ne),C)}catch(Z){let J=Z instanceof w?Z:new w("connection_failed",Z instanceof Error?Z.message:String(Z),{cause:Z});if(z==="webrtc"&&mc(s,J),(J.reason==="credential_expired"||J.reason==="credential_reused")&&!qe){qe=!0,T=await c(h);continue}if(z==="webrtc"&&J.reason==="signaling_failed"&&J.platformCode===$o&&!_e){_e=!0;let oe=Math.min(dc,F());if(o(`[gem] webrtc rung: the page could not put the offer on its socket; waiting up to ${Math.round(oe)}ms for the socket before offering again`),await B(oe))continue}if(J.reason==="join_rate_limited"){let oe=Fy(pe,Math.random,F());if(oe!==null){if(pe.attempts+=1,pe.waitedMs+=oe,o(`[gem] ${z} rung: the server is rate-limiting this player's joins; waiting ${Math.round(oe)}ms before presenting again (retry ${pe.attempts} of ${hc.maxAttempts})`),await gr(n,oe,h.signal),h.signal?.aborted)throw new w("aborted","the caller aborted while waiting out a join rate limit");T.credentialExpiresAt-n.now()<uc&&(T=await c(h));continue}}if($y.has(J.reason)||J.reason==="credential_expired"||z==="webrtc"&&fc(J)){o(`[gem] ${z} rung failed (${J.reason}): ${vr(J.cause??J)} \u2014 `+(te.length<E.length?`falling through to ${E[te.length]}`:"no rungs left")),K.push(J);break}throw o(`[gem] ${z} rung refused the session (${J.reason}): ${J.message}`),J}}}let me=K[K.length-1];throw me===void 0?new w("timeout",`the reconnect budget ran out before any transport (${E.join(", ")}) could be tried`):new w(me.reason,`every transport tried (${te.join(", ")}) failed; the last said: ${me.message}`,{cause:K,platformCode:me.platformCode})}catch(T){throw Ae(C),T}};return {listClusterTargets:async(h={})=>Ui({client:e,...h}),handleMatchEnded(h,k){let C=a.get(h);if(C!==void 0){a.delete(h);for(let T of C)T(k);}},connect:(async(h={})=>{let k=h.signaling??i();return h.transports===void 0?p(h,k):R(h,h.transports,k)})}}var lc=["webtransport","webrtc","websocket"],Ly=1e4,Dy=5e3,dc=3e3,cc=1e3,uc=1e4,$y=new Set(["timeout","connection_failed","signaling_unavailable","signaling_failed"]);function fc(t){return t.platformCode!==void 0&&Fo.has(t.platformCode)}var hc={initialDelayMs:2e3,factor:2,jitterMs:1e3,maxAttempts:3,budgetMs:15e3};function Fy(t,e=Math.random,n=1/0){let r=hc;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 qy(t,e){return t==="webrtc"?e===null||e.webrtc!==false:e===null?false:t==="webtransport"?e.webtransport!==void 0&&_r():e.websocket===void 0?false:e.websocket.tls===true||globalThis.isSecureContext!==true||Ny(e.websocket.url)}function Ny(t){if(typeof t!="string")return false;let e;try{e=new URL(t).hostname.toLowerCase();}catch{return false}return gt(e)}function Bo(t){return {...t.timeoutMs===void 0?{}:{timeoutMs:t.timeoutMs},...t.pollIntervalMs===void 0?{}:{pollIntervalMs:t.pollIntervalMs},...t.signal===void 0?{}:{signal:t.signal}}}var jy=new Set(["timeout","connection_failed","credential_expired","signaling_unavailable","signaling_failed","invalid_sdp","join_refused"]);function mc(t,e){e instanceof w&&(!jy.has(e.reason)&&!fc(e)||t.report([{type:"connection_failures_total",value:1}]));}function Uy(t,e,n,r,i,o,s,a,l,d){let m=false,c=()=>{m||qo(t,e.matchId,void 0);};o&&(n.addEventListener("close",c),s&&t.notifyMatchConnected(e.matchId));let p=()=>{m||(m=true,n.removeEventListener("close",c),a?.detach(),Ae(n),Ae(r),Ae(i));},g=y=>{if(!m){try{d?.(y);}catch{}p();}};return l.remember(e.matchId,g),{matchId:e.matchId,channel:n,peerConnection:r,joinCredential:e.joinCredential,credentialExpiresAt:e.credentialExpiresAt,welcome:a?.welcome??null,close(){l.forget(e.matchId,g),p();}}}function Wo(t){let e=t.matchSession.phase;return e!=="none"&&e!=="ended"}function pc(t){if(t.status==="failed")throw new w("allocation_failed",`match ${t.matchId} did not come up: ${t.reason}`);if(t.status==="ended")throw new w("match_ended",`match ${t.matchId} ended (${t.reason}) before this side connected.`);if(t.protocol!==pr)throw new w("unsupported_protocol",`match ${t.matchId} speaks '${t.protocol}', which a browser cannot connect. Only '${pr}' 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 w("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 gc(){let t=globalThis.RTCPeerConnection;if(!t)throw new w("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 Ae(t){try{t.close();}catch{}}function jr(t,...e){let n={};for(let r of e)t[r]!==void 0&&(n[r]=t[r]);return n}var By=1e4;function bc(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 mt({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??By);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 Vo={};Tu(Vo,{acceptTransfer:()=>Wy,addEntityProgression:()=>Hy,adminAction:()=>Vy,cancelInventoryTransfer:()=>Ky,claimEntityProgressionRewards:()=>Jy,closeGameRoom:()=>zy,createEntityBatchOrder:()=>Yy,createEntityOrder:()=>Xy,createSession:()=>Qy,deleteEntityGameSetting:()=>Zy,deleteEntitySave:()=>ef,deleteSession:()=>tf,deleteShowcaseValue:()=>nf,executeEntityRecipe:()=>rf,finalizeSaveUpload:()=>of,getChannelAssignment:()=>af,getDropRates:()=>sf,getEntityCurrency:()=>lf,getEntityGameSetting:()=>df,getEntityInventory:()=>cf,getEntityInventoryItem:()=>uf,getEntityLeaderboard:()=>mf,getEntityOrder:()=>pf,getEntityProgression:()=>gf,getEntityRecipeAvailability:()=>yf,getEntityRecipeUsage:()=>ff,getEntitySave:()=>hf,getEvent:()=>bf,getGameRoomV2:()=>vf,getLeaderboard:()=>_f,getPlayerGameProfile:()=>wf,getPurchaseCatalog:()=>kf,getResolvedTemplate:()=>Sf,getRoomArgs:()=>Rf,getShowcaseValue:()=>xf,getTransferDetails:()=>Af,ingestAnalyticsEvents:()=>Ho,initiateInventoryTransfer:()=>Pf,invokeFunction:()=>Tf,kickPlayer:()=>Ef,listChallenges:()=>Cf,listEntityGameSettings:()=>If,listEntityOrders:()=>Mf,listEntityProgressions:()=>Of,listEntitySaves:()=>Gf,listEvents:()=>Lf,listGameRooms:()=>Df,listResolvedTemplates:()=>$f,listTransfers:()=>Ff,maxEntityProgression:()=>qf,putEntityGameSetting:()=>Nf,putRoomArgs:()=>jf,putShowcaseValue:()=>Uf,rejectTransfer:()=>Bf,reportMatchPlayers:()=>Wf,requestSaveUploadUrl:()=>Hf,resetEntityProgression:()=>Vf,setMatchBackfill:()=>Kf,simulateEntityOrder:()=>Jf,transferHostV2:()=>zf,updateGameRoomV2:()=>Yf});function b(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 Wy(t,e,n){let r=`/v1/inventory/transfers/${b(e)}/accept`;return t.client.post(r,void 0,n?.signal)}async function Hy(t,e,n,r,i,o){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/add`;return t.client.post(s,i,o?.signal)}async function Vy(t,e,n,r){let i=`/v1/voice/sessions/${b(e)}/admin`;return t.client.post(i,n,r?.signal)}async function Ky(t,e,n){let r=`/v1/inventory/transfers/${b(e)}/cancel`;return t.client.post(r,void 0,n?.signal)}async function Jy(t,e,n,r,i,o){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/claim`;return t.client.post(s,i,o?.signal)}async function zy(t,e,n){let r=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}`;return t.client.delete(r,n?.signal)}async function Yy(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/orders/batch`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Xy(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/orders`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function Qy(t,e,n){return t.client.post("/v1/voice/sessions",e,n?.signal)}async function Zy(t,e,n,r,i){let o=`/v1/settings/${b(e)}/${b(n)}/${b(r)}`;return t.client.delete(o,i?.signal)}async function ef(t,e,n,r,i){let o=`/v1/saves/${b(e)}/${b(n)}/${b(r)}`;return t.client.delete(o,i?.signal)}async function tf(t,e,n){let r=`/v1/voice/sessions/${b(e)}`;return t.client.delete(r,n?.signal)}async function nf(t,e,n,r){let i=`/v1/showcase/players/${b(e)}/${b(n)}`;return t.client.delete(i,r?.signal)}async function rf(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/recipes/execute`;return t.client.post(o,r,i?.signal,{...i?.ifMatch===void 0?{}:{ifMatch:i.ifMatch}})}async function of(t,e,n,r,i,o){let s=`/v1/saves/${b(e)}/${b(n)}/${b(r)}/finalize`;return t.client.post(s,i,o?.signal)}async function af(t,e,n){let r=`/v1/games/${b(t.gameId())}/config/channels/${b(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function sf(t,e,n){let r=`/v1/inventory/loot-tables/${b(e)}/drop-rates`;return t.client.get(r,n?.signal)}async function lf(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/currencies/${b(r)}`;return t.client.get(o,i?.signal)}async function df(t,e,n,r,i){let o=`/v1/settings/${b(e)}/${b(n)}/${b(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function cf(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/${b(e)}/${b(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function uf(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/items/${b(r)}`;return t.client.get(o,i?.signal)}async function mf(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/${b(e)}/${b(n)}/${b(r)}`+(s?`?${s}`:"");return t.client.get(a,i?.signal)}async function pf(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/orders/${b(r)}`;return t.client.get(o,i?.signal)}async function gf(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}`;return t.client.get(o,i?.signal)}async function yf(t,e,n,r,i,o){let s=`/v1/inventory/${b(e)}/${b(n)}/catalogs/${b(r)}/recipes/${b(i)}/availability`;return t.client.get(s,o?.signal)}async function ff(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/${b(e)}/${b(n)}/recipe-usage`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function hf(t,e,n,r,i){let o=`/v1/saves/${b(e)}/${b(n)}/${b(r)}`;return t.client.getWithEtag(o,{...i?.signal===void 0?{}:{signal:i.signal},...i?.ifNoneMatch===void 0?{}:{ifNoneMatch:i.ifNoneMatch}})}async function bf(t,e,n){let r=`/v1/events/${b(e)}`;return t.client.get(r,n?.signal)}async function vf(t,e,n){let r=`/v2/games/${b(t.gameId())}/game-rooms/${b(e)}`;return t.client.getWithEtag(r,{...n?.signal===void 0?{}:{signal:n.signal},...n?.ifNoneMatch===void 0?{}:{ifNoneMatch:n.ifNoneMatch}})}async function _f(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/${b(e)}`+(i?`?${i}`:"");return t.client.get(o,n?.signal)}async function wf(t,e,n){let r=`/v1/profiles/players/${b(e)}`;return t.client.get(r,n?.signal)}async function kf(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 Sf(t,e,n){let r=`/v1/game-room-templates/${b(e)}`;return t.client.get(r,n?.signal)}async function Rf(t,e,n){let r=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}/room-args`;return t.client.get(r,n?.signal)}async function xf(t,e,n,r){let i=`/v1/showcase/players/${b(e)}/${b(n)}`;return t.client.get(i,r?.signal)}async function Af(t,e,n){let r=`/v1/inventory/transfers/${b(e)}`;return t.client.get(r,n?.signal)}async function Ho(t,e,n){let r=`/v1/games/${b(t.gameId())}/analytics/events`;return t.client.post(r,e,n?.signal,{replaySafe:true,retryRateLimited:false})}async function Pf(t,e,n){return t.client.post("/v1/inventory/transfers",e,n?.signal)}async function Tf(t,e,n){return t.client.postBytes("/v1/functions/invoke",e,n?.signal)}async function Ef(t,e,n,r){let i=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}/kick/${b(n)}`;return t.client.post(i,void 0,r?.signal)}async function Cf(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 If(t,e,n,r){let i=`/v1/settings/${b(e)}/${b(n)}`;return t.client.get(i,r?.signal)}async function Mf(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/${b(e)}/${b(n)}/orders`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Of(t,e,n,r){let i=`/v1/inventory/${b(e)}/${b(n)}/progressions`;return t.client.get(i,r?.signal)}async function Gf(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/${b(e)}/${b(n)}`+(o?`?${o}`:"");return t.client.get(s,r?.signal)}async function Lf(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 Df(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/${b(t.gameId())}/game-rooms`+(r?`?${r}`:"");return t.client.get(i,e?.signal)}async function $f(t,e){return t.client.get("/v1/game-room-templates",e?.signal)}async function Ff(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 qf(t,e,n,r,i,o){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/max`;return t.client.post(s,i,o?.signal)}async function Nf(t,e,n,r,i,o){let s=`/v1/settings/${b(e)}/${b(n)}/${b(r)}`;return t.client.put(s,i,o?.signal,{...o?.ifMatch===void 0?{}:{ifMatch:o.ifMatch}})}async function jf(t,e,n,r){let i=`/v1/games/${b(t.gameId())}/game-rooms/${b(e)}/room-args`;return t.client.put(i,n,r?.signal)}async function Uf(t,e,n,r,i){let o=`/v1/showcase/players/${b(e)}/${b(n)}`;return t.client.put(o,r,i?.signal)}async function Bf(t,e,n){let r=`/v1/inventory/transfers/${b(e)}/reject`;return t.client.post(r,void 0,n?.signal)}async function Wf(t,e,n,r){let i=`/v1/games/${b(t.gameId())}/matches/${b(e)}/players/report`;return t.client.post(i,n,r?.signal)}async function Hf(t,e,n,r,i,o){let s=`/v1/saves/${b(e)}/${b(n)}/${b(r)}/upload-url`;return t.client.post(s,i,o?.signal,{replaySafe:true})}async function Vf(t,e,n,r,i,o){let s=`/v1/inventory/${b(e)}/${b(n)}/progressions/${b(r)}/reset`;return t.client.post(s,i,o?.signal)}async function Kf(t,e,n,r){let i=`/v1/games/${b(t.gameId())}/matches/${b(e)}/backfill`;return t.client.put(i,n,r?.signal)}async function Jf(t,e,n,r,i){let o=`/v1/inventory/${b(e)}/${b(n)}/orders/simulate`;return t.client.post(o,r,i?.signal)}async function zf(t,e,n,r){let i=`/v2/games/${b(t.gameId())}/game-rooms/${b(e)}/transfer/${b(n)}`;return t.client.post(i,void 0,r?.signal)}async function Yf(t,e,n,r){let i=`/v2/games/${b(t.gameId())}/game-rooms/${b(e)}`;return t.client.patch(i,n,r?.signal,{...r?.ifMatch===void 0?{}:{ifMatch:r.ifMatch}})}var Xf=1e4,Qf=50,Zf=1e3,eh=65536-4*1024,vc=t=>typeof t=="number"?t:0,th=t=>typeof t=="string"?t:"";function _c(){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 nh(t){return t?.retryable===true}function rh(t,e){let n=t??{},r=Array.isArray(n.rejected)?n.rejected.map(i=>{let o=i??{};return {index:vc(o.index),code:th(o.code)}}):[];return {accepted:vc(n.accepted),rejected:r,dropped:e,duplicate:n.duplicate===true}}function wc(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 kc(t){let e=Math.max(1,Math.floor(t.maxQueue??Zf)),n={client:t.client,gameId:()=>t.gameId},r=[],i=0,o=null,s=false,a=null,l=0,d=0,m=false,c=false,p=h=>{t.log?.(h);},g=()=>{o!==null&&(t.clock.clearTimeout(o),o=null);},y=()=>Math.max(0,d-t.clock.now()),v=()=>{o!==null||s||a!==null||(o=t.clock.setTimeout(()=>{o=null,R().catch(()=>{});},Math.max(Xf,y())));},S=()=>{let h=Math.min(r.length,100),k=128;for(let C=0;C<h;C+=1){let T=r[C];if(T===void 0)break;if(k+=JSON.stringify(wc(T,0)).length+1,k>eh)return Math.max(1,C)}return h};async function R(h){for(;a!==null;)await a.catch(()=>{});if(r.length===0)return {accepted:0,rejected:[],dropped:0,duplicate:false};let k=P(h);a=k;try{return await k}finally{a===k&&(a=null),r.length>0&&v();}}async function P(h){g();let k=r.splice(0,S()),C=i;i=0;let T=Math.round(t.clock.now()),W={batch_id:_c(),sent_at_ms:T,events:k.map($=>wc($,T))};try{let $=await Ho(n,W,h===void 0?void 0:{signal:h}),N=rh($,C);l=0,d=0;for(let E of N.rejected)p(`[gem] analytics: an event was refused (${E.code}). See the analytics_events section of your game config.`);return N}catch($){if(nh($)){for(r=[...k,...r],i+=C;r.length>e;)r.shift(),i+=1;l+=1,d=t.clock.now()+cr(l,$);}else p(`[gem] analytics: ${k.length} event(s) were discarded \u2014 the platform refused the batch and will refuse it again: ${String($)}`);throw $}}return {track(h,k,C={}){if(s)return;if(typeof h!="string"||h===""){c||(c=true,p(`[gem] analytics: '${k}' 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(k.startsWith(Mi)){m||(m=true,p(`[gem] analytics: '${k}' 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={},W={};for(let[$,N]of Object.entries(C))typeof N=="string"?T[$]=N:typeof N=="number"&&Number.isFinite(N)&&(W[$]=N);for(;r.length>=e;)r.shift(),i+=1;r.push({uid:_c(),playerId:h,name:k,atMs:t.clock.now(),dimensions:T,measures:W}),r.length>=Qf&&a===null&&y()===0?R().catch(()=>{}):v();},flush:h=>R(h),get pending(){return r.length},dispose(){s=true,g(),r=[],i=0;}}}function Sc(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().");vt(r);let o=await t({player_id:n,...r===void 0?{}:{periods_back:r},...i===void 0?{}:{signal:i}});return nr(o)}}}function ih(t){let e={};for(let[n,r]of Object.entries(Vo))if(typeof r=="function"){let i=r;e[n]=(...o)=>i(t,...o);}return e}function Rc(t,e={}){let n=e.clock??he,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=bc(t,{clock:n,...e.onAuthStateChange===void 0?{}:{onStateChange:e.onAuthStateChange}}),o=qr({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=ih({client:s,gameId:()=>a.gameId}),d=a.gameRoomId,m=t.endMatch,c=t.log,p=kc({client:s,clock:n,gameId:a.gameId,...typeof c=="function"?{log:y=>c.call(t,y)}:{}});return {identity:a,client:s,api:l,match:{end:async()=>{if(m===void 0)throw new Error("this runtime cannot end the match: the server image running this bundle predates host.endMatch, and only the platform half holds the allocation proof an end needs.");await m.call(t);},setBackfill:async(y,v)=>{let S=await l.setMatchBackfill(a.matchId,{open:y.open,...y.seats===void 0?{}:{seats:y.seats}},v===void 0?{}:{signal:v});return {open:S.open,seats:S.seats??null}},reportPlayers:async(y,v)=>(await l.reportMatchPlayers(a.matchId,{players:y.map(R=>({player_id:R.playerId,state:R.state}))},v===void 0?{}:{signal:v})).players.map(R=>({playerId:R.player_id,outcome:R.outcome}))},analytics:p,functions:new Xe(l.invokeFunction),challenges:Sc(l.listChallenges),...d===void 0?{}:{room:{get:y=>l.getGameRoomV2(d,y),args:async y=>{let v=await l.getGameRoomV2(d,y?.signal===void 0?{}:{signal:y.signal}),S=v.modified?v.body:void 0;if(S?.room_args==null||S.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:S.room_args,room_args_template:S.room_args_template}}}},dispose:()=>{p.dispose(),i.dispose();}}}function rt(t){return t?.reliable!==false?"reliable":t?.ordered!==false?"ordered":"unreliable"}function It(t){return {reliable:t==="reliable",ordered:t!=="unreliable"}}function _n(t){return typeof t=="string"?t:t.slice().buffer}function Ur(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 oh=5e3,xc=3e4,Ac=2e3,ah=1e4,sh=3,Pc=1;async function Tc(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?f=>console.info(f):e.log,o=f=>i?.(`[gem host] ${f}`),s=typeof t=="function"?t():t,a=Promise.resolve(),l=true,d=false,m=(f,I)=>{l&&(a=a.then(async()=>{if(!d)try{await I();}catch(D){o(`the bundle's ${f} handler threw: ${it(D)}. Serving continues.`);}}));},c=true,p,g,y,v=f=>{if(!c)return;c=false,m("leave",()=>s.leave?.(r,{cause:f??"left"}));let I=g;I&&queueMicrotask(()=>I(f));},S={send(f,I){if(!c)return;let D=It(rt(I));m("message",()=>s.message?.(r,f,typeof f=="string",{reliable:D.reliable,ordered:D.ordered}));},onMessage(f){p=f;},onClose(f){g=f;},close(){v("closed");}},R=(f,I)=>{if(!c)return;let D=It(rt(I));queueMicrotask(()=>{c&&p?.(f,D);});},P=new Map,h=f=>{let I=[];for(let D of Fe){let Q=f.channels[D];try{Q.binaryType="arraybuffer";}catch{}let fe=It(D),An=lt=>{let Gt=Ur(lt?.data);Gt!==null&&m("message",()=>s.message?.(f.playerId,Gt.data,Gt.isText,{reliable:fe.reliable,ordered:fe.ordered}));};Q.addEventListener("message",An),I.push(()=>Q.removeEventListener("message",An));}P.get(f.playerId)?.forEach(D=>D()),P.set(f.playerId,I);},k=f=>{P.get(f)?.forEach(I=>I()),P.delete(f);},C=new Set,T=new Map,W=(f,I,D)=>({playerNumber:f.assignedPeerId,transport:"webrtc_p2p",...I?{rejoin:true}:{},...D?{superseded:true}:{}}),$=f=>{let I=P.has(f.playerId),D=C.has(f.playerId);C.add(f.playerId),h(f),I&&m("leave",()=>s.leave?.(f.playerId,{cause:"superseded"})),m("join",()=>s.join?.(f.playerId,W(f,D,I)));},N=new Set,E=(f,I,D)=>{if(f===r){R(I,D);return}let Q=n.peer(f);if(Q===null){let fe=T.get(f);if(fe!==void 0&&e.clock.now()-fe<Ac)return;N.has(f)||(N.add(f),o(`send to '${f}' dropped: no such connected player`));return}Q.send(_n(I),rt(D));},M={matchId:n.matchId,gameId:e.gameId,channel:e.channel,...e.gameRoomId===void 0?{}:{gameRoomId:e.gameRoomId},apiBaseUrl:e.apiBaseUrl,serverToken:()=>e.tokens.current(),onServerToken:f=>e.tokens.subscribe(f),sizeClass:"listen_host",get roomArgs(){return e.room()?.roomArgs},roster:e.room()?.members.map(f=>f.playerId)??[],players(){let f=c?[r]:[];for(let I of n.peers)f.push(I.playerId);return f},profile(f){let I=e.room()?.members.find(D=>D.playerId===f);if(!(!I||I.displayName===void 0))return {displayName:ht.toPlain(I.displayName),...I.displayTag===void 0?{}:{displayTag:ht.toPlain(I.displayTag)},...I.discriminator===void 0?{}:{discriminator:I.discriminator}}},playerNumber(f){return f===r?Pc:n.peer(f)?.assignedPeerId},send(f,I,D){E(f,I,D);},broadcast(f,I){let D=I?.except;c&&r!==D&&R(f,I);for(let Q of n.peers)Q.playerId!==D&&Q.send(_n(f),rt(I));},async endMatch(){let f=await Ne();return f.answer!=="ok"&&o(f.cause),f.answer},kick(f,I){if(f===r){v(I??"kicked");return}n.kick(f).catch(D=>{o(`kick of '${f}' failed: ${it(D)}`);});},log(f){o(f);},warn(f){o(`\u26A0 ${f}`);}},L=()=>{},F=new Promise(f=>{L=f;}),B=[],K=null,te=async(f,I)=>{l=false;let D=a.then(async()=>{try{await s.shutdown(f);}catch(Q){o(`the bundle's shutdown threw: ${it(Q)}`);}});a=D,await D,Le();for(let Q of B.splice(0))Q();for(let Q of [...P.keys()])k(Q);v(I);},me=(f,I)=>K||(K=(async()=>{await te(I,f),n.close(),L();})(),K),z=()=>K||(K=(async()=>{await te({reason:"signal"},"left"),await n.leave().catch(f=>o(`leaving the match failed: ${it(f)}`)),L();})(),K),qe=()=>K||(K=(async()=>{l=false;let f=await Ne();f.answer==="ok"?(await te({reason:"match_ended",platform_reason:"explicit"},"match ended"),n.close()):(o(`${f.cause}; leaving instead`),await te({reason:"signal"},"left"),await n.leave().catch(I=>o(`leaving the match failed: ${it(I)}`))),L();})(),K),_e=null,pe=()=>(_e??=Rc(M,{clock:e.clock,...e.fetch===void 0?{}:{fetch:e.fetch}}),_e),Ne=async()=>{try{return await Rs({client:pe().client,gameId:()=>M.gameId},M.matchId,{},{signal:AbortSignal.timeout(oh)}),{answer:"ok"}}catch(f){return f instanceof O&&(f.reason==="forbidden"||f.reason==="not_found")?{answer:f.reason==="not_found"?"already_ended":"refused",cause:`the platform did not take the end from this host (${f.reason})`}:{answer:"failed",cause:`ending the match failed: ${it(f)}`}}},Z=null,J=false,oe=0,Re,je=null,Le=()=>{J=true,Z!==null&&(e.clock.clearTimeout(Z),Z=null),je?.(),je=null;},at=f=>{o(`heartbeats paused: ${f}; they resume when a fresh play token arrives`),Pe();let I=Re,D=false,Q=e.tokens.subscribe(fe=>{D||J||fe.token===I||Ot(fe)||(D=true,je?.(),je=null,oe=0,Re=void 0,Pe(),o("a fresh play token arrived; heartbeats resume"),Z=e.clock.setTimeout(()=>{Ue();},0));});D?Q():je=Q;},Pe=()=>{let f=_e;_e=null,f?.dispose();},Ot=f=>f.expiresAt*1e3<=e.clock.now(),Ue=async()=>{if(Z=null,!J){try{await pe().client.post(`/v1/games/${encodeURIComponent(M.gameId)}/matches/${encodeURIComponent(M.matchId)}/heartbeat`,void 0,AbortSignal.timeout(ah)),oe=0,Re=void 0;}catch(f){if(f instanceof O&&(f.reason==="forbidden"||f.reason==="not_found")){o(`the platform no longer holds this match under this host (${f.reason}); heartbeats stop`),Le();return}if(lh(f)){if(J)return;oe+=1;let I=e.tokens.current(),D=I===void 0?"this host holds no play token":Ot(I)?"this host's play token has expired":I.token===Re?"the platform refused this host's play token again":oe>=sh?`the platform refused this host's play token ${oe} times in a row`:null;if(Re=I?.token,D!==null){at(D);return}}else oe=0,Re=void 0;o(`heartbeat failed: ${it(f)}`);}J||(Z=e.clock.setTimeout(()=>{Ue();},xc));}},Jr=()=>{J||Z!==null||(Z=e.clock.setTimeout(()=>{Ue();},xc));};{let f=L;L=()=>{Le(),_e?.dispose(),_e=null,f();};}let st=Promise.resolve().then(()=>s.init(M));a=st.then(()=>{},()=>{}),m("join",()=>s.join?.(r,{playerNumber:Pc,transport:"loopback"})),B.push(n.on("peerJoined",$)),B.push(n.on("peerLeft",(f,I)=>{k(f);let D=e.clock.now();for(let[Q,fe]of T)D-fe>=Ac&&T.delete(Q);T.set(f,D),N.delete(f),m("leave",()=>s.leave?.(f,{cause:I}));})),B.push(n.on("error",f=>{o(`\u26A0 session error: ${f.message}`);})),B.push(n.on("matchEnded",f=>{K||Ko(y,f),me("match ended",{reason:"match_ended",platform_reason:f});})),B.push(n.on("hostChanged",f=>{f!==r&&me("host migrated",{reason:"host_migrated"});}));for(let f of n.peers)$(f);try{await st,Jr();}catch(f){l=false,Le(),d=true;for(let I of B.splice(0))I();for(let I of [...P.keys()])k(I);throw n.leave().catch(()=>{}),L(),f}return {matchId:n.matchId,localLink:S,onMatchEnded(f){y=f;},end:qe,leave:z,stop:f=>me(f,{reason:"stopped"}),done:F}}function Ko(t,e){try{t?.(e);}catch{}}function lh(t){return t instanceof O&&t.status===401||re.isAuthError(t)}function it(t){return t instanceof Error?t.message:String(t)}function Jo(t,e){let n=async()=>{throw new w("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 Ec(t){let e=new Map,n=t.autoReconnect===true,{rooms:r}=t,i=new Map,o=async a=>{r.isHost&&!Wo(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!==tt)return Jo("dedicated",d.matchId);let m=t.p2p.session?.(d.matchId)??null;if(m===null&&!r.isHost||m!==null&&!m.isHost)return Jo("peer",d.matchId);let c=t.identity();if(c===null)throw new Error("[gem] serve() needs the signed-in identity and none has arrived. Await gem.awaitIdentity() first \u2014 the host runs your bundle under the play token, and there is no token yet.");let p=m??await t.p2p.connect(s(l)),g=await Tc(a,{session:p,clock:t.clock,gameId:c.gameId,channel:c.channel,...r.currentRoom?.id===void 0?{}:{gameRoomId:r.currentRoom.id},apiBaseUrl:t.apiBaseUrl(),tokens:t.tokens,room:t.room,localPlayerId:p.playerId!==""?p.playerId:c.playerId,...t.log===void 0?{}:{log:t.log},...t.fetch===void 0?{}:{fetch:t.fetch}});return i.set(d.matchId,g),g.done.then(()=>{i.get(d.matchId)===g&&i.delete(d.matchId);}),{mode:"listen",matchId:d.matchId,end:()=>g.end(),leave:()=>g.leave(),stop:()=>g.stop()}},async connect(a={}){let l=await o(a),d=a.onMatchEnded;if(l.protocol===tt){let g=i.get(l.matchId);if(g!==void 0)return r.notifyMatchConnected(l.matchId),mh(l.matchId,g,d);if(r.isHost)throw new Error("[gem] this player hosts the P2P match, so there is no one to connect TO yet. Call gem.match.serve(yourServer) first; connect() then resolves the loopback to your own bundle.");let y=await mn(),v=async()=>t.p2p.connect({...s(a),certificate:y}),S=await v(),R=gh(S,v,d,P=>{r.notifyMatchDisconnected(P).catch(()=>{});},()=>r.notifyMatchConnected(l.matchId),n);return n&&(e.set(S.matchId,{redial:R.redial,abandon:R.abandon}),R.onClosed(()=>{e.get(S.matchId)?.abandon===R.abandon&&e.delete(S.matchId);})),R}let m=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??[]}),c=await m(),p=ph(c,m,r,n);return n&&(e.set(c.matchId,{redial:p.redial,abandon:p.abandon}),p.onClosed(()=>{e.get(c.matchId)?.abandon===p.abandon&&e.delete(c.matchId);})),p},async redialMatch(a,l){let d=e.get(a);return d===void 0?"closed":d.redial(l)},abandonMatch(a,l){e.get(a)?.abandon(l);}}}var Cc="link_closed",dh="host_unreachable",ch=new Set(["failed","closed"]);function uh(t){return ch.has(t)?Cc:dh}function mh(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 ph(t,e,n,r){let i=t.matchId,o=t,s="connected",a,l,d=[],m=false,c=false,p=y=>{if(s!=="closed"){s="closed";for(let v of d.splice(0))v();l?.(y);}},g=y=>{y.link.onMessage((v,S)=>a?.(v,S)),y.link.onClose(v=>{if(y!==o||s==="closed")return;if(m||!r){p(v);return}let S=n.matchSession;if(S.phase==="suspended"&&S.matchId===i){s="suspended";return}p(v);});};return g(t),{matchId:i,protocol:"dedicated",get transport(){return o.transport},get state(){return s},send(y,v){s==="connected"&&o.link.send(y,v);},onMessage(y){a=y;},onClose(y){l=y;},close(){if(s!=="closed"){if(m=true,s==="suspended"){p("closed");return}o.close(),p("closed");}},async redial(y){if(s==="closed"||m)return "closed";if(c)return "connected";c=true;let v;try{v=await e(y===void 0?{}:{deadlineAt:y});}finally{c=false;}return m||s==="closed"?(v.close(),"closed"):(o=v,g(v),s="connected",n.notifyMatchConnected(i),"connected")},abandon(y){s!=="closed"&&(s==="connected"&&o.close(),p(y));},onClosed(y){s==="closed"?y():d.push(y);}}}function gh(t,e,n,r,i,o=false){let s=t.matchId,a=t,l,d,m=[],c=[],p=[],g=false,y=false,v=false,S=false,R="connected",P=E=>{if(g)return;g=true,R="closed";for(let L of m.splice(0))L();for(let L of c.splice(0))L();for(let L of p.splice(0))L();let M=d;M&&queueMicrotask(()=>M(E));},h=E=>{for(let M of m.splice(0))M();for(let M of Fe){let L=E.channels[M];try{L.binaryType="arraybuffer";}catch{}let F=It(M),B=K=>{let te=Ur(K?.data);te!==null&&l?.(te.data,F);};L.addEventListener("message",B),m.push(()=>L.removeEventListener("message",B));}},k=()=>a.peer(a.hostPlayerId),C=E=>{if(!(g||a.isHost)&&R!=="suspended"){if(r?.(E),o){R="suspended";return}P(E);}},T=E=>{for(let M of Fe){let L=E.channels[M];if(typeof L.addEventListener!="function")continue;let F=()=>{k()===E&&C(Cc);};L.addEventListener("close",F),m.push(()=>L.removeEventListener?.("close",F));}},W=E=>{h(E),T(E),!g&&(R="connected",i?.());},$=E=>{for(let M of c.splice(0))M();c.push(E.on("migrating",()=>{S=true;})),c.push(E.on("hostChanged",M=>{if(S=false,M===E.playerId){P("host_migrated_here");return}let L=k();L!==null&&W(L);})),c.push(E.on("peerJoined",M=>{M.playerId===E.hostPlayerId&&W(M);})),c.push(E.on("matchEnded",M=>{g||Ko(n,M),P(M);})),c.push(E.on("peerLeft",(M,L)=>{M===E.hostPlayerId&&C(uh(L));}));};$(a);let N=k();return N!==null&&W(N),{matchId:s,protocol:"p2p",get state(){return R},send(E,M){R==="connected"&&k()?.send(_n(E),rt(M));},onMessage(E){l=E;},onClose(E){d=E;},close(){y=true,P("closed"),a.leave().catch(()=>{});},async redial(){if(R==="closed")return "closed";if(R==="connected"||v)return "connected";if(S)throw new G("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");v=true;let E;try{for(let L of m.splice(0))L();for(let L of c.splice(0))L();a.close(),E=await e();}finally{v=false;}if(g)return y?E.leave().catch(()=>{}):E.close(),"closed";a=E,$(a);let M=k();if(M===null)throw a.close(),new G("connection_failed","this peer rejoined the match but the host never answered with a link");return W(M),"connected"},abandon(E){P(E);},onClosed(E){g?E():p.push(E);}}}function Ic(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 yh=12e4;function ot(t,e){return {outcome:t,reason:e}}function Mc(t){let e=false,n=new Map,r=(i,o,s,a)=>{if(!t.bridge.parentSupports(i))return Promise.resolve(ot("unavailable","error"));if(e)return Promise.resolve(ot("declined","busy"));let l=`purchase-${we()}`;return new Promise(d=>{let m={},c=g=>{n.delete(l)&&(e=false,t.clock.clearTimeout(m.timer),d(g));};e=true,n.set(l,{finish:c,check:s,label:a}),m.timer=t.clock.setTimeout(()=>c(ot("unavailable","error")),t.timeoutMs??yh);let p=false;try{p=o(l);}catch{}p||c(ot("unavailable","error"));})};return {api:{request(i){return r("purchases",o=>t.bridge.requestPurchase(o,i.kind,i.targetId,i.currencySlug,i.quantity,i.catalogId),o=>o===void 0?null:t.confirm(o),o=>`purchase ${JSON.stringify(o)}`)}},requestAvatar3d(i){return r("avatar3dPurchases",o=>t.bridge.requestAvatar3dPurchase(o,i.itemId,i.currencySlug),()=>t.confirmAvatar3d(i.itemId),()=>`3D avatar ${JSON.stringify(i.itemId)}`)},settle(i){let o=i.outcome==="ok"||i.outcome==="declined"?i.outcome:"unavailable",s=n.get(i.requestId);if(s===void 0){t.onDropped?.(`gem.purchaseResult (${o}) for an unknown requestId: `+JSON.stringify(i.requestId));return}let{finish:a}=s;if(o!=="ok"){a(ot(o,Bs(i.reason)));return}let l=i.purchaseId,d;try{d=s.check(l);}catch{d=Promise.resolve("unknown");}if(d===null){t.onDropped?.("gem.purchaseResult claimed ok with no purchaseId, so nothing could be confirmed with the platform; answering unavailable"),a(ot("unavailable","error"));return}(async()=>{let m;try{m=await d;}catch{m="unknown";}if(m==="granted"){a(l===void 0?{outcome:"ok"}:{outcome:"ok",purchaseId:l});return}m==="absent"&&t.onDropped?.("gem.purchaseResult claimed ok, but the platform did not confirm a grant for "+s.label(l)),a(ot("unavailable","error"));})();}}}async function Oc(t,e){try{return (await as(t,e)).granted?"granted":"absent"}catch(n){return n instanceof O&&n.reason==="not_found"?"absent":"unknown"}}var fh="small_human",Gc=/^[a-z][a-z0-9_]{0,31}$/,Lc=/^[\da-f]{8}(-[\da-f]{4}){3}-[\da-f]{12}$/i,hh=8;function zo(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:fh,id:e,modelUrl:n,iconUrl:r}]}function bh(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 vh(t){let e=t??{},n=typeof e.item_id=="string"&&Lc.test(e.item_id)?e.item_id:void 0,r=typeof e.family=="string"&&Gc.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=rr(e.icon_url),l=rr(e.model_url),d=[];for(let m of Array.isArray(e.prices)?e.prices:[]){let c=m??{};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"&&Gc.test(n)&&!e.includes(n)&&e.push(n),e.length===hh)break;return e}function Dc(t){let e=new Set,n=zo(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=zo(i);if(!bh(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=zo(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=vh(s);a!==void 0&&o.push(a);}return o},purchase(i){let o=i?.itemId,s=i?.currencySlug;return typeof o!="string"||!Lc.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 $c(t,e){try{return (await Na(t,e))?.owned===!0?"granted":"absent"}catch(n){return n instanceof O&&n.reason==="not_found"?"absent":"unknown"}}function Fc(t){return es(t)}var wh=6e5;function qc(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-${we()}`;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??wh);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 kh=new Set(["play","channel","purchase","build","devtools","devLocale","social","embedder","_s","fbclid","ttclid","gclid","msclkid","gem_test_ads"]),Sh=["utm_"];function Nc(t){return kh.has(t)||Sh.some(e=>t.startsWith(e))}var jc=16,Uc=512,Rh=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,xh=/[\p{Cc}\p{Cf}]/u,Ah=/\p{Cs}/u,Oe="[gem] gem.share.request:";function Bc(t){let{frame:e,log:n}=t,r=false,i=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("share")?e:null,o=s=>{n!==null&&(n===void 0?console.warn(s):n(s));};return {get available(){return i()!==null},request(s){let a=i();if(a===null)throw new Error(`${Oe} the arcade does not handle share here \u2014 check gem.share.available first`);if(s!==void 0&&(typeof s!="object"||s===null))throw new TypeError(`${Oe} pass { params }, or nothing`);let l=s?.params===void 0?{}:s.params;if(!Ph(l))throw new TypeError(`${Oe} params must be a plain object of string values`);let d=Object.entries(l);if(d.length>jc)throw new TypeError(`${Oe} at most ${jc} params; got ${d.length}`);let m=[];for(let[c,p]of d){let g=JSON.stringify(c);if(!Rh.test(c))throw new TypeError(`${Oe} param ${g}: a key is a letter followed by up to 63 letters, digits, _ or -`);if(Nc(c))throw new TypeError(`${Oe} param ${g} is reserved: the arcade reads it itself and never forwards it`);if(typeof p!="string")throw new TypeError(`${Oe} param ${g}: values must be strings`);if(p.length>Uc)throw new TypeError(`${Oe} param ${g}: a value is at most ${Uc} characters`);if(xh.test(p))throw new TypeError(`${Oe} param ${g}: control and format characters are not allowed`);if(Ah.test(p))throw new TypeError(`${Oe} param ${g}: a value must be well-formed text`);m.push({key:c,value:p});}!a.requestShare(m)&&!r&&(r=true,o("[gem] gem.share.request was not sent: more than 6 share requests in a minute. Call it from your Share button's click, not a loop."));}}}function Ph(t){if(typeof t!="object"||t===null||Array.isArray(t))return false;let e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}var Ih="(any-pointer: coarse)";function Mh(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 Wc(t){let{frame:e,log:n}=t,r=t.environment??{navigator:typeof navigator>"u"?void 0:navigator,matchMedia:typeof matchMedia=="function"?m=>matchMedia(m):void 0},i=r.navigator,o,s=new Set,a=()=>typeof i?.vibrate!="function"||r.matchMedia===void 0?false:(o??=r.matchMedia(Ih),o.matches),l=()=>e!==null&&e.currentState==="connected"&&e.parentSupports("vibration"),d=(m,c)=>{s.has(m)||(s.add(m),n!==null&&(n===void 0?console.warn(c):n(c)));};return {get available(){return a()||l()},vibrate(m){let c=a();if(!c&&!l())return false;let p=Mh(m);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(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(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 Mt=Math.PI/180,Ge=Object.freeze({touch:Object.freeze({yaw:1*Mt,pitch:.66*Mt}),mouse:Object.freeze({yaw:.5*Mt,pitch:.5*.77*Mt}),stick:Object.freeze({yaw:240*Mt,pitch:240*.77*Mt}),stickDeadzone:.1,stickCurve:2,touchPitchMin:.25}),Yo="[gem.controls]",Xo=Object.freeze({yaw:0,pitch:0}),Br=t=>Number.isFinite(t)?t:0,Hc=(t,e)=>({yaw:t+0,pitch:e+0});function Vc(t){let e=Br(t),n=(Math.abs(e)-Ge.stickDeadzone)/(1-Ge.stickDeadzone),r=Ge.stickCurve,i=(Math.exp(r*n)-1)/(Math.exp(r)-1);return Math.sign(e)*Math.min(1,Math.max(0,i))+0}function Oh(t){let e=Math.min(1,2*Math.abs(t)/Math.PI);return (1-Math.pow(e,.75))*(1-Ge.touchPitchMin)+Ge.touchPitchMin}function Kc(t,e){if(t===void 0)return {};if(typeof t!="object"||t===null)throw new TypeError(`${Yo} ${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(`${Yo} ${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(`${Yo} ${e}: invertY must be a boolean; got ${String(n.invertY)}`);return n}function Gh(t,e){let n=Kc(e,"look()"),r=n.sensitivity,i=n.gamepadSensitivity,o=n.invertY,s=a=>o??a?.invertLookY??false;return {fromPointer(a,l,d,m){let c=Br(a),p=Br(l);if(c===0&&p===0)return Xo;let g=t(),y=r??(g===null?void 0:g.lookSensitivity/100)??1,v=d==="touch"||d==="pen",S=v?Ge.touch:Ge.mouse,R=c*S.yaw*y,P=-p*S.pitch*y;return s(g)&&(P=-P),v&&m!==void 0&&Number.isFinite(m)&&P*m>0&&(P*=Oh(m)),Hc(R,P)},fromStick(a,l,d){let m=Br(d);if(m<=0)return Xo;let c=Vc(a),p=Vc(l);if(c===0&&p===0)return Xo;let g=t(),y=i??(g===null?void 0:g.gamepadLookSensitivity/100)??1,v=c*Ge.stick.yaw*m*y,S=-p*Ge.stick.pitch*m*y;return s(g)&&(S=-S),Hc(v,S)},set(a){let l=Kc(a,"set()");"sensitivity"in l&&(r=l.sensitivity),"gamepadSensitivity"in l&&(i=l.gamepadSensitivity),"invertY"in l&&(o=l.invertY);}}}function Jc(t){return {look:e=>Gh(t.recommended,e),LOOK_BASE:Ge}}var zc=Object.freeze(["music","sfx","voice","eye","text","hint","speed","bright","controls","star"]),Yc=/^[A-Za-z0-9_-]{1,40}$/;function Qo(t){return typeof t=="number"&&Number.isFinite(t)&&Math.abs(t)<=1e6}function Xc(t){if(typeof t!="string")return;let e=t.trim();return e.length===0?void 0:e.slice(0,40)}function Qc(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 Zc(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 Qc(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 eu(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"||!Yc.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 m=Xc(a.label);if(m===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:m,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 p=a.min??0,g=a.max??100,y=a.step??1;if(!Qo(p)||!Qo(g)||!Qo(y)||p>=g||y<=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:m,kind:"slider",value:Qc(a.value,p,g,y),min:p,max:g,step:y};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 y=g,v=Xc(y.label);typeof y.id!="string"||!Yc.test(y.id)||v===void 0||p.some(S=>S.id===y.id)||p.push({id:y.id,label:v});}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}c={id:l,label:m,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&&(zc.includes(a.icon)?c.icon=a.icon:e(`${d} keeps the Arcade's generic icon: ${JSON.stringify(a.icon)} is not one of ${zc.join(", ")}.`)),n.push(c);}return n}var Lh=500;function tu(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")},m=()=>{if(n===null||o!==null)return;let c=JSON.stringify(n);if(c===r)return;let p=i+Lh-e.now();if(p>0){o=e.setTimeout(()=>{o=null,m();},p);return}t.frame().declareSettings(n)&&(r=c,i=e.now());};return {api:{declare(c){let p=eu(c,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,m(),d())},onChange(c){if(typeof c!="function")return ()=>{};let p=g=>c(g);return s.add(p),()=>{s.delete(p);}}},forgetSent(){r=null,i=-1/0;},flush:m,onSettingChange(c){let p=n?.findIndex(R=>R.id===c.id)??-1,g=n?.[p];if(n===null||g===void 0)return;let y=Zc(g,c.value);if(y===void 0)return;let v=JSON.stringify(n);n=n.map((R,P)=>P===p?{...R,value:y}:R),r===v&&(r=JSON.stringify(n));let S={id:g.id,value:y};for(let R of [...s])try{R(S);}catch(P){console.error("[gem] a gem.settings.onChange handler threw:",P);}}}}function nu(t,e){return t==null?e?"low":"medium":t==="low"||t==="high"?t:"medium"}var Dh=/(?:Z|[+-]\d{2}:?\d{2})$/i;function ru(t){if(typeof t!="string"||!Dh.test(t))return;let e=Date.parse(t);return Number.isFinite(e)&&e>0?e:void 0}function wn(){return {declared:false,grantable:false,heldLimitReached:false}}function iu(t,e){let n=typeof t=="object"&&t!==null?t:{},r=ru(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=ru(a),d=n.held_limit_reached===true,m=a!=null,c=o!=null&&s===void 0;return {declared:true,grantable:n.grantable===true&&e&&s!==0&&!c&&!m&&!d,...s===void 0?{}:{remainingToday:s},...l===void 0?{}:{nextEligibleAt:l},heldLimitReached:d,...i}}var $h=18e4,Zo=32,Fh=/^[a-z0-9_-]+$/,qh="rewarded_requires_user_gesture";function Nh(){let t=globalThis.navigator?.userActivation?.isActive;return typeof t=="boolean"?t:void 0}var jh=1e3;function Uh(){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<=jh)return true}return false}var ou=1e4;function Bh(t){return t==="interstitial"||t==="rewarded"}function au(t){return typeof t=="string"&&t!==""&&t.length<=Zo&&Fh.test(t)}function Wh(t){let e=typeof t=="object"&&t!==null?t:{};return [e.name,e.reason,e.status].join()}function Wr(t){return typeof t=="string"?JSON.stringify(t):typeof t}function su(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 m=t.log;if(m!==null)try{m===void 0?console.warn(`[gem] ${d}`):m(`[gem] ${d}`);}catch{}},l=d=>{let m=t.readAvailability;if(m===void 0)return Promise.resolve(wn());let c=r.get(d);if(c!==void 0)return c;let p=new Promise(g=>{let y={},v=h=>y.done===true?false:(y.done=true,t.clock.clearTimeout(y.timer),g(h),true),S=(h,k)=>{!v(wn())||i.has(h)||(i.add(h),o(`gem.ads.rewardedStatus("${d}") answered not grantable: ${k}. Said once.`));},R=h=>{S(Wh(h),`the read failed (${h instanceof Error?h.message:Wr(h)})`);},P;try{P=Promise.resolve(m(d,AbortSignal.timeout(ou)));}catch(h){P=Promise.reject(h);}y.timer=t.clock.setTimeout(()=>{S("timeout","no answer within 10 s");},ou),P.then(h=>{try{v(iu(h,t.bridge.parentSupports("ads")));}catch(k){R(k);}},R);});return r.set(d,p),p.then(()=>{r.get(d)===p&&r.delete(d);}),p};return {api:{rewardedStatus(d){return au(d)?l(d):(o(`gem.ads.rewardedStatus(${Wr(d)}) answered not grantable: a placement is 1..${String(Zo)} 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 m=d?.placement,c=d?.format;if(!au(m)||!Bh(c))return o(`gem.ads.requestAd was called with arguments the SDK will not send: placement ${Wr(m)}, format ${Wr(c)}. A placement is 1..${String(Zo)} 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 g;try{g=(t.userActivation??Nh)();}catch{g=void 0;}if(g===false)try{(t.recentGamepadInput??Uh)()===!0&&(g=!0);}catch{}if(g===false){let y=`${qh}: gem.ads.requestAd("${m}", '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(y),a(y),Promise.resolve({outcome:"no_ad"})}}let p=`ad-${we()}`;return new Promise(g=>{let y={},v=R=>{n.delete(p)&&(e=false,t.clock.clearTimeout(y.timer),g(R));};e=true,n.set(p,v),y.timer=t.clock.setTimeout(()=>{v({outcome:"unavailable"});},t.timeoutMs??$h);let S=false;try{S=t.bridge.requestAd(p,m,c);}catch{}S||v({outcome:"no_ad"});})}},settle(d){let m=d.outcome==="shown"||d.outcome==="no_ad"?d.outcome:"unavailable",c=n.get(d.requestId);if(c===void 0){t.onDropped?.(`gem.adResult (${m}) for an unknown requestId: `+JSON.stringify(d.requestId));return}c({outcome:m});}}}var lu=Object.freeze(["level_end","run_end","match_end","menu_return","other_break"]),du=18e4,Hh=1e4,Vh=/^[a-z0-9_-]{1,32}$/;function cu(t){return typeof t=="string"?JSON.stringify(t):typeof t}var kn=Object.freeze({shown:false});function uu(t){let e=new Map,n,r=false,i=o=>{try{t.onDropped?.(o);}catch{}return kn};return {api:{signal(o){try{if(!t.bridge.parentSupports("moments"))return r?Promise.resolve(kn):(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;if(!lu.includes(s)||a!==void 0&&(typeof a!="string"||!Vh.test(a)))return Promise.resolve(i(`moments_invalid_argument: gem.moments.signal was called with arguments the SDK will not send: kind ${cu(s)}, placement ${cu(a)}. A kind is one of ${lu.join(", ")}; a placement, when given, is 1..32 characters of a-z, 0-9, '-' and '_'. 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 l=t.clock.now();if(n!==void 0&&l-n<Hh)return Promise.resolve(i(`moments_called_repeatedly: gem.moments.signal({ kind: '${s}' }) within 10 s of the last moment's answer (${String(l-n)} ms). One break, one signal, from the press that leaves it; never on a timer. Answering shown: false.`));let d=`moment-${we()}`;return new Promise(m=>{let c={},p=(y,v)=>{e.delete(d)&&(t.clock.clearTimeout(c.timer),v&&(n=t.clock.now()),m(y));};e.set(d,y=>p(y,!0)),c.timer=t.clock.setTimeout(()=>{e.has(d)&&(p(kn,!0),i(`moments_timeout: gem.moments.signal({ kind: '${s}' }) had no answer within ${String((t.timeoutMs??du)/1e3)} s. Answering shown: false.`));},t.timeoutMs??du);let g=!1;try{g=t.bridge.signalMoment(d,s,a);}catch{}g||p(kn,!1);})}catch{return Promise.resolve(kn)}}},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 ea=16384;function mu(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:Kh(e)}function Kh(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 Jh=1e4,zh=5e3;function pu(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=zh){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(m),l(),a(e);},m=t.clock.setTimeout(()=>{l(),a(e);},s);r.push(d);})},put(s){if(!t.bridge.parentSupports("deviceSettings"))return Promise.resolve("unavailable");let a=mu(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-${we()}`;return new Promise(m=>{let c={},p=y=>{i.delete(d)&&(t.clock.clearTimeout(c.timer),y==="stored"&&(e=l,n=true,o()),m(y));};i.set(d,p),c.timer=t.clock.setTimeout(()=>p("unavailable"),t.timeoutMs??Jh);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,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 Sn=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 Yh=/^[a-z0-9][a-z0-9_-]{0,39}$/;function Xh(t){return typeof t=="string"&&Yh.test(t)}function Hr(t){if(t===null||Xh(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 gu(t){return Math.min(16384,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function ta(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 Vr(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 yu(t,e){return Math.min(e,Math.max(0,Math.round(Number.isFinite(t)?t:0)))}function Qh(t){let e=t.untrusted,n=De(e.displayName,"gem.player.displayName"),r=e.displayTag||e.displayHandle,i=r?De(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,m=t.avatar3dId,c={displayName:n,displayHandle:i??n,badges:(t.badges??[]).map(v=>({itemId:v.itemId,iconUrl:v.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),m&&l.test(m)&&(c.avatar3dId=m),t.avatar3dModelUrl&&(c.avatar3dModelUrl=t.avatar3dModelUrl),t.avatar3dIconUrl&&(c.avatar3dIconUrl=t.avatar3dIconUrl),t.avatars3d&&(c.avatars3d=t.avatars3d.filter(v=>l.test(v.id)&&/^[a-z][a-z0-9_]*$/.test(v.family)).filter((v,S,R)=>R.findIndex(P=>P.family==v.family)==S).map(({family:v,id:S,modelUrl:R,iconUrl:P})=>({family:v,id:S,modelUrl:R,iconUrl:P})));let p=t.boost,g=(p?.multipliers??[]).map(v=>({currencyId:v.currencyId,currencySlug:v.currencySlug,multiplier:v.multiplierBp/1e4})),y=g.some(v=>v.multiplier>1);return c.boost=y&&p?.expiresInDays?{active:y,multipliers:g,expiresInDays:p.expiresInDays}:{active:y,multipliers:g},c}var Zh=1e4,Rn=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??he,this.inbound=new qt(this.clock),this.outbound=new qt(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=>gi(a,e.origin))||qs(e.origin,this.options.selfOrigin)))return this.refuse(e,`embedder '${e.origin}' is not in allowedEmbedders`),this.state==="waiting"&&this.transition("refused"),false;if(this.state==="connected")return this.fail("handshake_duplicate","this document already has a port"),false;if(this.state!=="waiting")return false;let r=Fn["gem.handshake"]?.(e.data);if(r)return this.refuse(e,`malformed handshake: ${r}`),false;let i=e.data;if(!gi(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=Ns(Dn,i.versions);return s===null?(o.onmessage=null,o.postMessage({gem:U,type:"gem.error",code:"version_mismatch",message:`frame supports v${Dn.min}..v${Dn.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:U,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:U,type:"gem.ready"});}settled(e=Zh){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:U,type:"gem.progress",loaded:e,total:n});}requestToken(e,n){this.send({gem:U,type:"gem.requestToken",requestId:e,reason:n});}requestLocalServer(e,n){return this.parentSupports("localHost")?(this.send({gem:U,type:"gem.requestLocalServer",requestId:e,gameRoomId:n}),true):false}exit(e){this.send(e===void 0?{gem:U,type:"gem.exit"}:{gem:U,type:"gem.exit",reason:e});}openExternal(e){this.send({gem:U,type:"gem.openExternal",url:e});}requestFullscreen(e){this.send({gem:U,type:"gem.requestFullscreen",enabled:e});}reportMuted(e){return this.gated("audioState")?(this.send({gem:U,type:"gem.audioState",muted:e}),true):false}reportEngaged(){return this.engagedSent||!this.gated("engagement")||!this.send({gem:U,type:"gem.engaged"})?false:(this.engagedSent=true,true)}cueReward(e){if(!this.gated("rewardCue"))return false;let n={gem:U,type:"gem.rewardCue",currencySlug:String(e.currencySlug).slice(0,32)};return e.expected!==void 0&&Number.isFinite(e.expected)&&e.expected>=1&&(n.expected=Math.min(1e9,Math.round(e.expected))),e.origin&&(n.origin={x:gu(e.origin.x),y:gu(e.origin.y)}),this.send(n),true}showPortraitBorders(e){let n=Hr(e);return n===void 0||!this.gated("portraitBorders")?false:this.send(n===null?{gem:U,type:"gem.portraitBorders"}:{gem:U,type:"gem.portraitBorders",name:n})}setWalletVisible(e,n){return this.gated("walletDisplay")?this.send({gem:U,type:"gem.walletDisplay",...ta(e,n?.only)}):false}setMenu(e){return this.gated("gameMenu")?this.send({gem:U,type:"gem.menu",...Vr(e)}):false}declareSettings(e){return this.gated("gameSettings")?this.send({gem:U,type:"gem.settingsDeclare",settings:e}):false}setGemCorner(e){return this.gated("gemCorner")?this.send({gem:U,type:"gem.gemCorner",corner:e}):false}requestShare(e){return this.gated("share")?this.send({gem:U,type:"gem.requestShare",params:e.map(({key:n,value:r})=>({key:n,value:r}))}):false}requestAvatarPicker(e){return this.gated("avatarPicker")?this.send({gem:U,type:"gem.requestAvatarPicker",...e==="2d"||e==="3d"?{tab:e}:{}}):false}requestVibrate(e){return this.gated("vibration")?this.send({gem:U,type:"gem.vibrate",pattern:[...e]}):false}reportFrameStats(e){return this.gated("frameStats")?(this.send({gem:U,type:"gem.frameStats",fps:yu(e.fps,1e3),frameTimeP95Ms:yu(e.frameTimeP95Ms,1e5),counts:e.counts==="gameDraws"?"gameDraws":"pageFrames"}),true):false}sendGameContext(e){return this.state!=="connected"?false:(this.send({gem:U,type:"gem.gameContext",context:e}),true)}signal(e,n,r){this.send({gem:U,type:"gem.signal",signal:e,matchId:n,data:r});}dedicatedOffer(e,n,r){this.send({gem:U,type:"gem.dedicatedOffer",matchId:e,sdp:n,intent:r});}requestParty(e){return this.send({gem:U,type:"gem.partyRequest",requestId:e})}requestPurchase(e,n,r,i,o,s){return this.send({gem:U,type:"gem.requestPurchase",requestId:e,purchaseKind:n,targetId:r,currencySlug:i,...o===void 0?{}:{quantity:o},...s===void 0?{}:{catalogId:s}})}requestAvatar3dPurchase(e,n,r){return this.parentSupports("avatar3dPurchases")?this.send({gem:U,type:"gem.requestAvatar3dPurchase",requestId:e,itemId:n,currencySlug:r}):false}putDeviceSettings(e,n){return this.send({gem:U,type:"gem.deviceSettings.put",requestId:e,settings:n})}requestAd(e,n,r){return this.send({gem:U,type:"gem.requestAd",requestId:e,placement:n,format:r})}signalMoment(e,n,r){return this.send({gem:U,type:"gem.signalMoment",requestId:e,kind:n,...r===void 0?{}:{placement:r}})}readyCalled(){return this.readySent||this.readyPending}requestSignIn(e){return this.send({gem:U,type:"gem.requestSignIn",requestId:e})}requestFriendChallenge(e,n,r,i){return this.send({gem:U,type:"gem.requestFriendChallenge",requestId:e,playerId:n,template:r,...i===void 0?{}:{params:i}})}close(){this.port&&(this.port.onmessage=null,this.port.close(),this.port=null),this.state!=="refused"&&this.transition("closed");}transition(e){if(this.state!==e){this.state=e;for(let n of this.settleWaiters.splice(0))n(e);this.options.onStateChange?.(e);}}refuseMalformed(e,n){if(!this.inbound.allow($n)){this.options.onDropped?.(e,n);return}this.fail(e,n);}dropUnknownType(e){this.inbound.allow($n)&&this.options.onDropped?.("unsupported",`ignored unknown message type '${e}'`);}refuse(e,n){e.ports?.[0]?.close?.(),this.inbound.allow($n)&&this.options.onRefused?.(n);}fail(e,n){this.options.onError?.(e,n),this.state==="connected"&&this.port&&this.send({gem:U,type:"gem.error",code:e,...n===void 0?{}:{message:n}});}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=Fn[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||fu(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=Fn[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=Ds(r);if(o!==void 0&&!this.options.capabilities?.includes(o))return this.fail("unsupported_capability",`${r} requires the '${o}' capability, which this frame did not advertise`),false;let s=i(e);if(s)return this.fail("invalid_message",`${r}: ${s}`),false;let a=e;if(a.v!==this.version)return this.fail("invalid_message",`${r}: expected v ${String(this.version)}`),false;switch(r){case "gem.token":this.options.onToken?.(a);break;case "gem.pause":this.options.onPause?.(a);break;case "gem.menuSelect":this.options.onMenuSelect?.(a);break;case "gem.settingChange":this.options.onSettingChange?.(a);break;case "gem.prefs":this.options.onPrefs?.(a);break;case "gem.cohorts":this.options.onCohorts?.(a);break;case "gem.earnAllowanceChanged":this.options.onEarnAllowanceChanged?.();break;case "gem.viewport":this.options.onViewport?.(a);break;case "gem.willTerminate":this.options.onWillTerminate?.(a);break;case "gem.devtools":this.options.onDevtools?.(a.action);break;case "gem.requestContext":this.options.onRequestContext?.();break;case "gem.screenshot":{let 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 fu(n.slice(1)),this.options.onScreenshot(d,l,(m,c)=>this.screenshotDenied(m,c)),true}case "gem.token.denied":this.options.onTokenDenied?.(a);break;case "gem.localServer":this.options.onLocalServer?.(a);break;case "gem.localServer.denied":this.options.onLocalServerDenied?.(a);break;case "gem.player":{this.options.onPlayer?.(Qh(a));break}case "gem.roomEvent":this.options.onRoomEvent?.(a);break;case "gem.seatedEvent":this.options.onSeatedEvent?.(a);break;case "gem.autoStartFailedEvent":this.options.onAutoStartFailedEvent?.(a);break;case "gem.ticketEvent":this.options.onTicketEvent?.(a);break;case "gem.socketState":this.options.onSocketState?.(a);break;case "gem.signalEvent":this.options.onSignalEvent?.(a);break;case "gem.dedicatedEvent":this.options.onDedicatedEvent?.(a);break;case "gem.clusterTarget":this.options.onClusterTarget?.(a);break;case "gem.partyResult":this.options.onPartyResult?.(a);break;case "gem.purchaseResult":this.options.onPurchaseResult?.(a);break;case "gem.deviceSettings":this.options.onDeviceSettings?.(a);break;case "gem.deviceSettings.result":this.options.onDeviceSettingsResult?.(a);break;case "gem.adResult":this.options.onAdResult?.(a);break;case "gem.momentResult":this.options.onMomentResult?.(a);break;case "gem.signInResult":this.options.onSignInResult?.(a);break;case "gem.friendChallengeResult":this.options.onFriendChallengeResult?.(a);break;case "gem.error":this.options.onError?.(a.code,a.message);break;default:this.fail("unsupported",`no frame handler for '${r}'`);}return false}screenshotDenied(e,n){this.send({gem:U,type:"gem.screenshot.denied",reason:e,retryable:n});}};function fu(t){for(let e of t)try{e?.close?.();}catch{}}var hu="https://api.gemarcade.com";function na(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 eb=new Set(["localhost","127.0.0.1","[::1]"]);function bu(t){let e=na(t);if(e!==null)return e;let n=new URL(t);return n.protocol==="http:"&&!eb.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}function vu(t){return Object.freeze(t.map(([e,n])=>Object.freeze({node:e,parent:n})))}function tb(){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 nb=Object.freeze({small_human:vu([["root",null],["body","root"],["head","body"],["arm_l","body"],["arm_r","body"],["hand_socket","arm_r"],["leg_l","body"],["leg_r","body"]]),adult_human:vu(tb())});var ib=Object.freeze(["https://gemarcade.com","http://gemarcade.localhost","gemarcade://localhost"]),ob=hu,ab=["top-left","top-right","bottom-left","bottom-right"],_u=8e3,Kr=15e3,sb=9e4,lb=1/0,db=8e3,cb=5e3,ub=5e3;async function mb(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 xn(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 NA(t={}){let e=t.clock??he,n=t.log===void 0?u=>console.info(u):t.log,r=t.baseUrl??void 0;if(r!=null){let u=na(r);if(u!==null)throw new Error(`[gem] the baseUrl passed to createGem cannot be used: ${u}. Its value is withheld here rather than written to logs. This is a configuration fault.`)}let i=typeof window>"u"?void 0:window.location?.search,o=yl(i),s=Bl(i),a=Ao();a.mark("sdk created");let l=()=>yr(ne.gameVersion,t.clientVersion?.gameVersion),d=new Xt({client:()=>ct,clock:e,gameId:()=>ne.identity?.gameId??null,playerId:()=>ne.identity?.playerId??null,awaitPlayerId:async()=>(await Mn(Kr)).playerId,environment:()=>{let u=l();return {sdk_version:_a(),...u===null?{}:{game_version:u}}},...t.analytics===void 0?{}:{options:t.analytics},log:n}),m=Td(()=>{a.mark("engaged"),d.release(),q.reportEngaged();},typeof window>"u"?{}:window),c=u=>{if(u===false)return null;let x=u?.attempts??lb,j=u?.budgetMs??sb;return !(x>0)||!(j>0)?null:{attempts:x,budgetMs:j,maxDelayMs:u?.maxDelayMs??db}},p=u=>{u.on("created",()=>{a.mark("room created");}),u.on("joined",()=>{a.mark("room joined");}),u.on("matchAllocationStarted",()=>{a.mark("allocation started");}),u.on("matchReady",()=>{a.mark("match ready");}),u.on("matchFailed",()=>{a.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 Sn;let g=t.allowedEmbedders;if(g!=null&&!Array.isArray(g))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 y=Array.from(g??[]),v=y.filter(u=>typeof u!="string"||!pi(u));if(v.length>0)throw new Error(`createGem: \`allowedEmbedders\` has ${v.length===1?"an entry":"entries"} that ${v.length===1?"is":"are"} not an origin: ${v.map(u=>typeof u=="string"?JSON.stringify(u):String(u)).join(", ")}. An origin is scheme, host and optional port with nothing after it \u2014 'https://my-own-site.example', not 'https://my-own-site.example/'. \`undefined\` usually means a build-time value that was not set. The Gem Arcade is allowed without any entry.`);let S=Object.freeze([...new Set([...ib,...y])]),R=xn(e),P=new Set,h=xn(e),k=false,C=xn(e),T=wl(n),W=xn(e),$=t.manageAudio===false?null:jd();t.selectableText!==true&&Ud(),t.onScreenshot===void 0&&Id(window);let N=null,E=null,M=null,L=()=>{N===null||N===E||q.reportMuted(N)&&(E=N);},F,B,K=-1/0,te=null,me=()=>{if(F===void 0||te!==null||F===B)return;let u=K+1e3-e.now();if(u>0){te=e.setTimeout(()=>{te=null,me();},u);return}q.showPortraitBorders(F)&&(B=F,K=e.now());},z=null,qe=null,_e=()=>{if(z===null)return false;let u=JSON.stringify(ta(z.visible,z.only));return u===qe?q.parentSupports("walletDisplay"):q.setWalletVisible(z.visible,z)?(qe=u,true):false},pe=null,Ne=null,Z=()=>{if(pe===null)return false;let u=JSON.stringify(Vr(pe.items));return u===Ne?q.parentSupports("gameMenu"):q.setMenu(pe.items)?(Ne=u,true):false},J=null,oe=null,Re=tu({frame:()=>q,clock:e,log:t.log}),je=()=>J===null?false:J===oe?q.parentSupports("gemCorner"):q.setGemCorner(J)?(oe=J,true):false,Le=Bd({report:u=>q.reportFrameStats(u)}),at=false,Pe=Yd(()=>fa,()=>at),Ot=u=>{let x=at&&!u,j=at!==u;if(at=u,x&&Pe.close(),!!j)try{t.onDevToolsPermissionChange?.(u);}catch(ae){n?.(`[gem] onDevToolsPermissionChange threw: ${ae instanceof Error?ae.message:String(ae)}`),queueMicrotask(()=>{throw ae});}},Ue=r??ob,Jr=r!==void 0,st,f=u=>(n?.(`[gem] token refused: ${u}`),t.onError?.("internal",u),false),I=(u,x)=>{if(u===void 0)return x!==void 0?f("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 j=bu(u);return j!==null?f(`the embedder named an API root that cannot be used: ${j}. Its value is withheld here rather than written to logs.`):st!==void 0&&st!==u?f("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."):(st=u,Jr||(Ue=u),true)},D=window.location?.origin,Q=null,fe=-1/0,An=2e3,lt=new Set,Gt=u=>Q!==false?Promise.resolve(true):new Promise(x=>{let j=e.setTimeout(()=>{lt.delete(ae),x(false);},u),ae=()=>{e.clearTimeout(j),lt.delete(ae),x(true);};lt.add(ae);}),zr=()=>{},Yr=null,q=new Rn({allowedEmbedders:S,...typeof D=="string"&&D!==""?{selfOrigin:D}:{},expectedSource:window.parent,clock:e,capabilities:["rooms","p2p","dedicated","parties","partySeating","autoStartFailure","ticketEvents","clusterTarget","devtools","localHost","cohorts","socketState","screenshot","audioState","rewardCue","portraitBorders","earnAllowance","share","avatarPicker","vibration","frameStats","walletDisplay","gameMenu","gemCorner","gameSettings","engagement","reservedAreas","viewport","purchases","avatar3dPurchases","deviceSettings","ads","moments","signIn","friendChallenges",...t.onFeedbackContext!==void 0?["feedbackContext"]:[],...t.onAudioChannels!==void 0?["audioChannels"]:[]],onRefused:u=>{Yr=u,t.onRefused?.(u);},...t.onError===void 0?{}:{onError:t.onError},onStateChange:u=>{ne.onBridgeState(u),u!=="connected"&&Le.setRequested(false),E=null,qe=null,Ne=null,oe=null,Re.forgetSent(),B=void 0,u==="refused"&&(console.error("[gem] this game refused the page that framed it"+(Yr===null?"":` (${Yr})`)+", 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."),zr()),u==="connected"&&(a.mark("bridge connected"),wu(),L(),me(),_e(),Z(),je(),Re.flush(),q.unbiddenLaunch&&!m.engaged&&d.hold(),d.startSession(),m.engaged&&q.reportEngaged()),t.onStateChange?.(u);},onPlayer:u=>{R.set(u);for(let x of [...P])x(u);t.onPlayer?.(u);},onPrefs:u=>{let x={reducedMotion:u.reducedMotion,muted:u.muted,locale:u.locale,showFrameStats:u.showFrameStats===true,music:u.music!==false,sounds:u.sounds!==false,recommended:u.recommended===void 0?null:Object.freeze({volume:u.recommended.volume,batterySaver:u.recommended.batterySaver,keyboardLayout:u.recommended.keyboardLayout,gamepadConfirm:u.recommended.gamepadConfirm,vibration:u.recommended.vibration,lookSensitivity:u.recommended.lookSensitivity??100,gamepadLookSensitivity:u.recommended.gamepadLookSensitivity??100,invertLookY:u.recommended.invertLookY??false,touchMovement:u.recommended.touchMovement==="fixed"?"fixed":"floating",graphicsQuality:nu(u.recommended.graphicsQuality,u.recommended.batterySaver),graphicsQualityAuto:u.recommended.graphicsQualityAuto??true})};h.set(x),E=x.muted,$?.setMuted(x.muted),Le.setRequested(x.showFrameStats&&q.parentSupports("frameStats")),t.onPrefs?.(x),t.onAudioChannels!==void 0&&(M===null||M.music!==x.music||M.sounds!==x.sounds)&&(M=Object.freeze({music:x.music,sounds:x.sounds}),t.onAudioChannels(M));},onCohorts:u=>{let x=Object.freeze(u.cohorts.map(j=>Object.freeze({experimentId:j.experimentId,variantKey:j.variantKey})));C.set(x),t.onCohorts?.(x);},onEarnAllowanceChanged:()=>T.emit(),onViewport:u=>{let x=Object.freeze({insets:Object.freeze({top:u.insets.top,right:u.insets.right,bottom:u.insets.bottom,left:u.insets.left}),reserved:Object.freeze((u.reserved??[]).map(({x:ae,y:ha,width:ba,height:va,control:Dt})=>Object.freeze(Dt?{x:ae,y:ha,width:ba,height:va,control:Object.freeze({x:Dt.x,y:Dt.y,width:Dt.width,height:Dt.height})}:{x:ae,y:ha,width:ba,height:va})))});W.set(x);let j=Hd();Vd(j,x.insets),Jd(j,x.reserved,Kd()),t.onViewport?.(x);},onPause:u=>{k=u.paused,d.setPaused(u.paused),Le.setPaused(u.paused),t.onPause?.(u.paused);},onSettingChange:u=>Re.onSettingChange(u),onMenuSelect:u=>{pe===null||u.entry!=="item"||!(Vr(pe.items).items??[]).some(j=>j.id===u.id)||pe.items?.find(j=>j.id===u.id)?.onSelect?.();},onWillTerminate:u=>{d.endSession(u.reason),t.onWillTerminate?.({reason:u.reason,graceMs:u.graceMs});},onToken:u=>{let x=u.garden;if(Ot(u.allowDevTools===true),!I(u.apiBaseUrl,x))return;let j=u;ne.onToken(j);let ae=ne.identity;ae&&(Xr.set(ae),ia||(ia=true,ce.reconcileSeats().catch(()=>{}))),oa.push({token:j.token,expiresAt:j.expiresAt});},onTokenDenied:u=>{Ot(false),ne.onDenied(u);},onScreenshot:(u,x,j)=>{Fd(u,x,j,{...t.onScreenshot===void 0?{}:{handler:t.onScreenshot},useDefaultStrategy:true});},onRequestContext:()=>{qd(q,t.onFeedbackContext);},onDevtools:u=>{u==="close"?Pe.close():u==="open"?Pe.openFrom("platform").catch(()=>{}):Pe.isOpen?Pe.close():Pe.openFrom("platform").catch(()=>{});},onRoomEvent:u=>ce.handleRoomEvent({event:u.event,roomId:u.roomId,...u.matchId===void 0?{}:{matchId:u.matchId},...u.version===void 0?{}:{version:u.version},...u.reason===void 0?{}:{reason:u.reason},...u.platform===void 0?{}:{platform:u.platform}}),onSeatedEvent:u=>ce.handleSeated(u.roomId),onAutoStartFailedEvent:u=>ce.handleAutoStartFailed(u.roomId,u.code),onTicketEvent:u=>ce.handleTicketEvent({event:u.event,ticketId:u.ticketId,...u.partySize===void 0?{}:{partySize:u.partySize},...u.queuedAt===void 0?{}:{queuedAt:u.queuedAt},...u.expiresAt===void 0?{}:{expiresAt:u.expiresAt},...u.reason===void 0?{}:{reason:u.reason},...u.roomId===void 0?{}:{roomId:u.roomId}}),onSocketState:u=>{let x=Q;if(Q=u.connected,u.connected)for(let ae of [...lt])ae();if(!u.connected||x===true)return;let j=e.now();j-fe<An||(fe=j,ce.reconcile().catch(()=>{}));},onSignalEvent:u=>{let x=typeof u.data=="object"&&u.data!==null&&!Array.isArray(u.data)?u.data:{};ut.handleSignalEvent(u.matchId,u.event,x),u.event==="matchEnded"&&ce.reconcile({matchId:u.matchId,...typeof x.reason=="string"?{reason:x.reason}:{}}).catch(()=>{});},onDedicatedEvent:u=>{u.event==="matchEnded"&&(Lt.handleMatchEnded(u.matchId,u.reason),ce.reconcile({matchId:u.matchId,...u.reason===void 0?{}:{reason:u.reason}}).catch(()=>{})),ra.handleEvent(u);},onClusterTarget:u=>Cn.accept(u.clusterTargetId,u.clusterTargetIds),onLocalServer:u=>In.accept(u),onLocalServerDenied:u=>In.refuse(u),onPartyResult:u=>sa.settle(u.requestId,u.partyId),onPurchaseResult:u=>Zr.settle(u),onDeviceSettings:u=>{En.receive(u),t.onDeviceSettings?.(En.api.current);},onDeviceSettingsResult:u=>En.settle(u),onAdResult:u=>da.settle(u),onMomentResult:u=>ca.settle(u),onSignInResult:u=>ua.settle(u),onFriendChallengeResult:u=>ma.settle(u)}),ra=new vn({bridge:q}),Xr=xn(e);zr=()=>{Xr.release(),R.release(),C.release();},q.currentState==="refused"&&zr();let ia=false,Qr=new Set,Pn,oa={current:()=>Pn,subscribe:u=>(Qr.add(u),Pn!==void 0&&u(Pn),()=>Qr.delete(u)),push:u=>{Pn=u;for(let x of [...Qr])try{x(u);}catch(j){n?.(`[gem] a server-token listener threw: ${j instanceof Error?j.message:String(j)}`);}}},ne=Qd({bridge:q,clock:e,onStateChange:(u,x)=>{if(u==="ready"){if(a.mark("token ready")){let j=a.marks.find(ae=>ae.name==="token ready")?.at;d.trackPlatform("gem_boot_ready",j===void 0?{}:{boot_ms:Math.max(0,Math.round(j))});}}else u==="lost"&&(a.mark("token lost"),d.trackPlatform("gem_auth_lost"));t.onAuthStateChange?.(u,x);}}),aa=()=>{let u=ne.identity;return !u||ne.source.currentState==="lost"?null:`${u.playerId}\0${u.gameId}\0${u.channel}`},wu=()=>{a.mark("token requested"),ne.source.get().catch(()=>{});},sa=Ic({bridge:q,clock:e}),Tn={},Zr=Mc({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u),confirm:async u=>Tn.confirm?.(u)??"unknown",confirmAvatar3d:async u=>Tn.confirmAvatar3d?.(u)??"unknown"}),En=pu({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u)}),la={},da=su({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u),readAvailability:(u,x)=>la.read?.(u,x)??Promise.reject(new Error("the gem-api client is not built yet")),log:t.log}),ca=uu({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u)}),ua=qc({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u)}),ma=_l({bridge:q,clock:e,onDropped:u=>t.onError?.("internal",u)}),Cn=Cl({bridge:q,clock:e}),In=zd({bridge:q,clock:e}),ei=u=>{let x=q.handleWindowMessage({data:u.data,origin:u.origin,source:u.source,ports:u.ports});return x&&window.removeEventListener("message",ei),x};window.addEventListener("message",ei);let dt=Ed(window,ei),ku=dt?.capture,ti=typeof performance>"u"?void 0:performance.getEntriesByType?.("navigation")?.[0];ti?.domInteractive!==void 0&&ti.domInteractive>0&&a.mark("document parsed",ti.domInteractive),ku?.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 ni=t.handshakeWarningMs;ni!==null&&n&&e.setTimeout(()=>{let u=dt===null?"no capture script ran":`capture: ${dt.delivered} offer(s) delivered, ${dt.stale} stale, ${dt.capture.dropped} evicted${dt.capture.late?", installed late":""}`;if(q.currentState==="connected"){n(`[gem] handshake connected. boot: ${a.timeline()} \xB7 ${u}`);return}n(`[gem] no completed handshake after ${ni??_u}ms (bridge state: ${q.currentState}). Either the embedder does not run the gem-web-sdk parent half, its origin is not in this build\u2019s allowedEmbedders, or its handshake fired before this frame\u2019s listener registered. boot: ${a.timeline()} \xB7 `+u);},ni??_u);let Su=qr({get baseUrl(){return Ue},tokenSource:ne.source,get defaultQuery(){let u=ne.identity;return u?{game_id:u.gameId,channel:u.channel}:{}}}),ct=new Ve({transport:Su,clock:e}),ge={client:ct,gameId:()=>ne.identity?.gameId??""};Tn.confirm=u=>Oc(ge,u),Tn.confirmAvatar3d=u=>$c(ge,u),la.read=(u,x)=>Ts(ge,"players","me",u,{signal:x});let Ru=()=>ne.identity?.channel??"release",ri=new tr(ge,Ru),xu=Dc({player:()=>R.current,subscribe:u=>(P.add(u),()=>{P.delete(u);}),configFamilies:async()=>(await ri.load())?.avatar_3d_families,readOffers:()=>Fc(ge),purchase:u=>Zr.requestAvatar3d(u),log:t.log}),pa=async u=>(await ri.load())?.currency(u)?.id??void 0,ga=zn(ge,Ri,{identity:aa,resolveCurrencyId:pa}),Mn=async u=>{let x=await Xr.wait(u);if(x)return x;throw q.currentState==="refused"?new re("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 re("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).")},ii=c(t.autoReconnect),ce=ld(s===void 0?{}:{playWithTicket:s},{client:ct,clock:e,gameId:()=>ne.identity?.gameId??null,playerId:()=>ne.identity?.playerId??null,awaitGameId:async()=>(await Mn(Kr)).gameId,resolveParty:sa.resolve,resolveClusterTargets:Cn.resolveList,refreshClusterTargets:Cn.refresh,ensureLocalServer:In.ensure,localHostAvailable:In.available,...t.clientVersion===void 0?{}:{clientVersion:t.clientVersion},platformGameVersion:()=>ne.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},...ii===null?{}:{autoReconnect:{...ii,redial:(u,x)=>oi.redialMatch(u,x),abandon:(u,x)=>oi.abandonMatch(u,x)}}});p(ce),Ad({analytics:d,rooms:ce});let ut=xd({client:ct,clock:e,rooms:ce,bridge:q,gameId:()=>ne.identity?.gameId??"",baseUrl:()=>Ue,resolveClusterTarget:Cn.resolve,boot:a,...t.log===void 0?{}:{log:t.log}}),ya=xo(a,n),Lt=yc({client:ct,clock:e,rooms:ce,signaling:()=>ra.channel(),signalingReady:Gt,log:n??(()=>{})}),oi=Ec({rooms:ce,p2p:{connect:u=>ya(ut.connect(u)),session:u=>ut.session(u)},dedicated:{connect:(u=>Or(a,"welcome",Lt.connect(u),n))},clock:e,identity:()=>ne.identity,apiBaseUrl:()=>Ue,tokens:oa,room:()=>ce.currentRoom,autoReconnect:ii!==null,...t.log===void 0?{}:{log:t.log}}),Au=async()=>(await Mn(Kr)).playerId,fa={client:ct,boot:a,get identity(){return ne.identity},awaitIdentity:(u=Kr)=>Mn(u),awaitBridge:u=>q.settled(u),get player(){return R.current},awaitPlayer:(u=cb)=>R.wait(u),me:ga,characters:new Xn(ge,void 0,aa,pa),transfers:new Zn(ge,Ri,ga.inventory),gameConfig:ri,purchases:Zr.api,deviceSettings:En.api,moments:ca.api,ads:da.api,account:ua.api,share:Bc({frame:q,log:t.log}),vibration:Wc({frame:q,log:t.log}),get avatarPickerAvailable(){return q.currentState==="connected"&&q.parentSupports("avatarPicker")},openAvatarPicker:u=>q.requestAvatarPicker(u?.tab),avatars3d:xu,settings:Re.api,controls:Jc({recommended:()=>h.current?.recommended??null}),analytics:d,leaderboards:new Ht(ge),challenges:new Ut(ge),showcase:new Vt(ge,Au),friends:new Kt(ge,{challenge:ma.challenge,...o===void 0?{}:{launchedChallengeId:o}}),platform:new zt(ge,T,n),profiles:new Yt(ge),functions:new Xe((u,x)=>gs(ge,u,x)),get prefs(){return h.current},get paused(){return k},get cohorts(){return C.current},get viewport(){return W.current},awaitCohorts:(u=ub)=>C.wait(u),reportMuted:u=>{N=!!u,L();},showPortraitBorders:u=>{let x=Hr(u);x!==void 0&&(F=x,me());},cueReward:u=>q.cueReward(u),setWalletVisible:(u,x)=>{let j=Array.isArray(x?.only)?[...x.only]:void 0;return z=j===void 0?{visible:u===true}:{visible:u===true,only:j},_e()},setMenu:u=>(pe=Array.isArray(u?.items)?{items:u.items.map(x=>({...x}))}:{},Z()),setGemCorner:u=>{if(!ab.includes(u)){let x=typeof u=="string"?JSON.stringify(u.slice(0,48)):`a value of type ${typeof u}`;return console.warn(`[gem] setGemCorner: ${x} is not a corner, so nothing was sent. Pass 'top-left', 'top-right', 'bottom-left' or 'bottom-right'.`),false}return J=u,je()},reportFrame:()=>Le.draw(),exit:u=>mb(ce,q,u,d),frame:q,devtools:Pe,rooms:ce,dedicatedServer:{listClusterTargets:u=>Lt.listClusterTargets(u),connect:(u=>Or(a,"welcome",Lt.connect(u),n)),handleMatchEnded:(u,x)=>Lt.handleMatchEnded(u,x)},p2p:{handleSignalEvent:(u,x,j)=>ut.handleSignalEvent(u,x,j),session:u=>ut.session(u),connect:u=>ya(ut.connect(u))},match:oi};return fa}
3
+ export{ib as ARCADE_EMBEDDERS,nb as AVATAR_RIGS,Xt as AnalyticsApi,re as AuthError,Ut as ChallengesApi,ea as DEVICE_SETTINGS_MAX_BYTES,w as DedicatedServerError,Ye as FriendChallengeError,Kt as FriendsApi,Xe as FunctionsApi,O as GemApiError,Ve as GemClient,ue as GemConfigError,Rn as GemFrame,dr as GemFunctionError,le as GemSaveError,Sn as GemUnframedError,Ht as LeaderboardsApi,il as MAX_PERIODS_BACK,fp as PLATFORM_EVENTS,zt as PlatformApi,sr as PlatformCurrenciesApi,lr as PlatformEarnAllowanceApi,be as PlayerText,Yt as ProfilesApi,Be as PurchaseRefusal,Vt as ShowcaseApi,se as TransportRefusal,nn as UNRELIABLE_CHANNEL_LABEL,De as asPlayerText,Ao as createBootTimeline,NA as createGem,ur as experimentSelection,mb as leaveAndExit,xe as mapIdentity,Or as markOnResolve,Um as platformIconUrl,en as presentJoinCredential,St as readTemplateTransports,rn as readTransportAdvert,xo as reportOnResolve,ht as text,_r as webTransportAvailable};//# sourceMappingURL=gem-web-sdk.game.js.map
4
4
  //# sourceMappingURL=gem-web-sdk.game.js.map